From 28ef524e26d117390944ae8696d79ce79c990e3f Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 15:50:47 +0000 Subject: [PATCH 001/183] fix(journeys): report unexercised local hooks accurately [skip ci] Signed-off-by: Jeremi Joslin --- products/platform/journeys/README.md | 4 ++++ products/platform/journeys/lib.sh | 11 +++++++++++ products/platform/journeys/rstack-dev.sh | 4 +++- products/platform/journeys/test_lib.sh | 18 ++++++++++++++++-- 4 files changed, 34 insertions(+), 3 deletions(-) diff --git a/products/platform/journeys/README.md b/products/platform/journeys/README.md index c5ec25dbc0..eb437b9a2d 100644 --- a/products/platform/journeys/README.md +++ b/products/platform/journeys/README.md @@ -149,6 +149,10 @@ Threshold outcomes are report-only in CI. The functional ratchet controls journey acceptance, and comparison code errors fail the harness. Promote uses its functional ratchet. +In `rstack-dev`, the run log and `cells.tsv` mark the hook step `unexercised` +when the journey has no hook delivery to check. The cell still runs its later +steps, including retention and cleanup. + ## Running the static check The check reads these files and a few source files. It starts no container and diff --git a/products/platform/journeys/lib.sh b/products/platform/journeys/lib.sh index d3a7d21a14..60a710b9f0 100644 --- a/products/platform/journeys/lib.sh +++ b/products/platform/journeys/lib.sh @@ -2295,6 +2295,17 @@ journey_unreached() { _jc_reason=$reason } +# journey_unexercised STEP: record an optional step and continue the cell. +journey_unexercised() { + local step=${1:-} + journey__require_step_start "$step" + [[ "$step" != "$_journey_last_step" ]] || + journey__script_error "the final step of $_jc_product cannot be marked unexercised" + journey__record_line "$step" unexercised - 0.000 + _jc_recorded+="$step"$'\n' + journey__say "$_jc_product $step: unexercised" +} + # journey_assist_enabled NAME: true when --assist lists NAME. journey_assist_enabled() { [[ ",$JOURNEY_ASSISTS," == *",${1:-},"* ]] diff --git a/products/platform/journeys/rstack-dev.sh b/products/platform/journeys/rstack-dev.sh index 215fafa518..14ecab1c43 100755 --- a/products/platform/journeys/rstack-dev.sh +++ b/products/platform/journeys/rstack-dev.sh @@ -605,8 +605,10 @@ walk_product() { sink=$(jq -er '.bregHookSink.receivedUrl' "$START_FILE") journey_poll 30 -- hook_received "$sink" "A retained contact" journey_http hook GET "$sink" || unexpected_answer hook + journey_pass hook + else + journey_unexercised hook fi - journey_pass hook if [[ "$uses_postgres" == true ]]; then if [[ "$product" != breg ]]; then diff --git a/products/platform/journeys/test_lib.sh b/products/platform/journeys/test_lib.sh index 7a16c5f522..baf1988438 100644 --- a/products/platform/journeys/test_lib.sh +++ b/products/platform/journeys/test_lib.sh @@ -398,8 +398,8 @@ driver_binaries() { # The cell of PRODUCT as CELL_ describes it: pass, fail:STEP:CODE, # needs:STEP:THING, poll:STEP (a journey_poll that runs out of time), -# unreached:STEP, blocker:STEP:CODE:ASSIST or harness:STEP. The default is the -# product's row in the synthetic table. +# unreached:STEP, unexercised:STEP, blocker:STEP:CODE:ASSIST or harness:STEP. +# The default is the product's row in the synthetic table. driver_cell() { local product=$1 plan_name plan kind stop code assist step plan_name="CELL_$product" @@ -421,6 +421,10 @@ driver_cell() { journey_unreached "$step" "runs beside its parent" break ;; + unexercised) + journey_unexercised "$step" + continue + ;; fail) if ! journey_step "$step" -- "$alpha" fail; then journey_fail "$step" "$code" @@ -1875,6 +1879,16 @@ case_modes() { drive 1 CELL_gamma=unreached:start -- "${run_args[@]}" --expected "$table" check_equal "unreached at another step is a mismatch" mismatch "$(json '.cells[] | select(.product == "gamma") | .verdict' "$out/summary.json")" + begin_case unexercised-step + drive 0 CELL_alpha=unexercised:call -- "${run_args[@]}" --product alpha --expected "$table" --strict + check "the skipped step is recorded" has $'alpha\tcall\tunexercised\t-' "$out/cells.tsv" + check "later steps still run" has $'alpha\tstop\tpass\t-' "$out/cells.tsv" + check "the log identifies the unexercised step" has "alpha call: unexercised" "$last_err" + + begin_case final-step-must-run + drive 3 CELL_alpha=unexercised:stop -- "${run_args[@]}" --product alpha + check "the required final step cannot be skipped" has "the final step of alpha cannot be marked unexercised" "$last_err" + begin_case ratchet-stale drive 0 CELL_beta=pass -- "${run_args[@]}" --expected "$table" check "a listed failure that passes is a warning" has "warning: a listed failure no longer fails" "$last_err" From 684619d157a7543098985fb45e8756ab6dbda6b7 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 09:26:32 +0000 Subject: [PATCH 002/183] test(render): qualify signed document delivery Signed-off-by: Jeremi Joslin --- .../content/docs/operate/registry-render.mdx | 36 ++ .../render/scripts/test_signed_delivery.py | 378 ++++++++++++++++++ 2 files changed, 414 insertions(+) create mode 100644 products/render/scripts/test_signed_delivery.py diff --git a/docs/site/src/content/docs/operate/registry-render.mdx b/docs/site/src/content/docs/operate/registry-render.mdx index 8d06e83260..65a9abbcaf 100644 --- a/docs/site/src/content/docs/operate/registry-render.mdx +++ b/docs/site/src/content/docs/operate/registry-render.mdx @@ -461,6 +461,42 @@ document type the route takes as `seal`, so a client can tell them apart first. [configuration reference](../../reference/render-configuration/#seal-documents) lists the keys, problems, and response shapes. +### Verify a delivered PDF + +Save the exact PDF bytes. For a JSON response, base64-decode `pdfBase64` to get those bytes. +Keep the delivery record for the same response. Use `X-Registry-Signed-File-Digest` or +`signedFileDigest` to identify the complete file. Use `X-Registry-Document-Digest` or +`documentDigest` to identify its first revision. + +Obtain the trust roots and expected seal identity from your institution's trusted configuration. +For a shared issuing CA, confirm the signature's leaf certificate against the expected +fingerprint. Render's `certificateDigest` is the SHA-256 of that certificate in DER form. +A digest supplied with the PDF can confirm the file matches the delivery record. +The signature and independently established trust establish who sealed it. + +Set `SIGNED_FILE_DIGEST` and `DOCUMENT_DIGEST` to the labelled digests from the delivery record. +Run these commands from a Registry Stack source checkout with the received `signed.pdf` and +your institution's `seal-root.pem`: + +```bash +printf '%s %s\n' "${SIGNED_FILE_DIGEST#sha256:}" signed.pdf | sha256sum --check --strict +uv run --script products/render/scripts/validate-seal.py \ + --pdf signed.pdf --trust-root seal-root.pem --document-digest "$DOCUMENT_DIGEST" +``` + +Accept the file only if both commands succeed and the verified seal matches your policy. +The validator reports `"ok": true` and the verified level. For B-T, include the approved timestamp +trust root with another `--trust-root` if needed and require the reported level `B-T`. +The validator checks full-file signature coverage and works offline with soft-fail revocation. +Use your institution's revocation policy when it calls for fresh revocation evidence. +If a digest or signature check fails, obtain the original signed file and its delivery record again. +If trust or identity fails, confirm the expected signer and trust roots with the issuing institution. + +{/* Evidence: crates/registry-render/src/server.rs, respond_sealed; + crates/registry-render/src/seal.rs, Seal::certificate_digest; + products/render/scripts/validate-seal.py, validate; + products/render/scripts/test_signed_delivery.py, verify_delivery. */} + ### Use a test seal in development Issue a test certificate from your own test authority and set `assuranceProfile: local` in the runtime file. diff --git a/products/render/scripts/test_signed_delivery.py b/products/render/scripts/test_signed_delivery.py new file mode 100644 index 0000000000..d77dcddc57 --- /dev/null +++ b/products/render/scripts/test_signed_delivery.py @@ -0,0 +1,378 @@ +#!/usr/bin/env python3 +# /// script +# requires-python = ">=3.11" +# dependencies = ["pyhanko==0.38.1"] +# /// +# SPDX-License-Identifier: Apache-2.0 +"""Exercise the published Render seal endpoint and verify the delivered PDF.""" + +import argparse +import base64 +import hashlib +import http.client +import json +import os +import socket +import subprocess +import sys +import tempfile +import threading +import time +from contextlib import contextmanager +from datetime import datetime, timedelta, timezone +from http.server import BaseHTTPRequestHandler, HTTPServer +from pathlib import Path + +from asn1crypto import keys, tsp +from asn1crypto import x509 as asn1_x509 +from cryptography import x509 +from cryptography.hazmat.primitives import hashes, serialization +from cryptography.hazmat.primitives.asymmetric import ec, rsa, utils +from cryptography.x509.oid import ExtendedKeyUsageOID, NameOID, ObjectIdentifier +from pyhanko.pdf_utils.reader import PdfFileReader +from pyhanko.sign.timestamps import DummyTimeStamper + +HERE = Path(__file__).resolve().parent +NOTICE = HERE.parents[2] / "crates/registry-render/tests/fixtures/sealed-notice" +ISSUER = "https://issuer.example.test" +AUDIENCE = "urn:render:qualification" +CLIENT = "records-service" +DOCUMENT_SIGNING = ObjectIdentifier("1.3.6.1.5.5.7.3.36") +REQUEST = json.dumps({ + "issuedAt": "2026-01-01T00:00:00Z", + "data": {"reference": "SYNTHETIC-01", "body": "Fictional qualification notice."}, +}) + + +def b64url(data): + return base64.urlsafe_b64encode(data).rstrip(b"=").decode() + + +def sign_token(key, scope): + now = int(time.time()) + header = {"alg": "ES256", "kid": "fixture", "typ": "at+jwt"} + claims = { + "iss": ISSUER, "sub": "qualification-caller", "aud": AUDIENCE, + "client_id": CLIENT, "iat": now, "exp": now + 300, "scope": scope, + } + data = ".".join(b64url(json.dumps(value).encode()) for value in (header, claims)) + r, s = utils.decode_dss_signature(key.sign(data.encode(), ec.ECDSA(hashes.SHA256()))) + return data + "." + b64url(r.to_bytes(32, "big") + s.to_bytes(32, "big")) + + +def issue_certificate(public_key, name, issuer, issuer_key, *, purpose=None): + now = datetime.now(timezone.utc) + subject = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, name)]) + is_root = issuer is None + builder = ( + x509.CertificateBuilder() + .subject_name(subject) + .issuer_name(subject if is_root else issuer.subject) + .public_key(public_key) + .serial_number(x509.random_serial_number()) + .not_valid_before(now - timedelta(minutes=5)) + .not_valid_after(now + timedelta(days=90)) + .add_extension(x509.BasicConstraints(ca=is_root, path_length=None), critical=True) + .add_extension(x509.KeyUsage( + digital_signature=not is_root, content_commitment=not is_root, + key_encipherment=False, data_encipherment=False, key_agreement=False, + key_cert_sign=is_root, crl_sign=is_root, encipher_only=False, decipher_only=False, + ), critical=True) + ) + if purpose is not None: + builder = builder.add_extension( + x509.ExtendedKeyUsage([purpose]), critical=purpose == ExtendedKeyUsageOID.TIME_STAMPING + ) + return builder.sign(issuer_key, hashes.SHA256()) + + +def write_fixture(binary, directory): + def run(*args): + subprocess.run([binary, *args], check=True, stdout=subprocess.DEVNULL, timeout=30) + + run("package", "--bundle", NOTICE, "--output", directory / "package") + secrets = directory / "secrets" + secrets.mkdir(mode=0o700) + csr_path = directory / "seal.csr" + run("keygen", "--key", secrets / "seal.jwk", "--csr", csr_path, + "--common-name", "Qualification test seal", "--country", "FR") + signer_key = x509.load_pem_x509_csr(csr_path.read_bytes()).public_key() + root_key = ec.generate_private_key(ec.SECP256R1()) + root = issue_certificate(root_key.public_key(), "Qualification root", None, root_key) + other_key = ec.generate_private_key(ec.SECP256R1()) + other = issue_certificate(other_key.public_key(), "Unrelated root", None, other_key) + leaf = issue_certificate( + signer_key, "Qualification test seal", root, root_key, purpose=DOCUMENT_SIGNING + ) + for name, certificates in ( + ("root.pem", [root]), ("other-root.pem", [other]), ("chain.pem", [leaf, root]) + ): + (directory / name).write_bytes(b"".join( + certificate.public_bytes(serialization.Encoding.PEM) for certificate in certificates + )) + + issuer_key = ec.generate_private_key(ec.SECP256R1()) + point = issuer_key.public_key().public_numbers() + jwks = {"keys": [{ + "kty": "EC", "crv": "P-256", "alg": "ES256", "kid": "fixture", + "x": b64url(point.x.to_bytes(32, "big")), "y": b64url(point.y.to_bytes(32, "big")), + }]} + (secrets / "jwks.json").write_text(json.dumps(jwks)) + return issuer_key, "sha256:" + leaf.fingerprint(hashes.SHA256()).hex() + + +@contextmanager +def timestamp_authority(directory): + root_key = ec.generate_private_key(ec.SECP256R1()) + root = issue_certificate(root_key.public_key(), "Qualification TSA root", None, root_key) + (directory / "tsa-root.pem").write_bytes(root.public_bytes(serialization.Encoding.PEM)) + tsa_key = rsa.generate_private_key(public_exponent=65537, key_size=2048) + leaf = issue_certificate( + tsa_key.public_key(), "Qualification TSA", root, root_key, + purpose=ExtendedKeyUsageOID.TIME_STAMPING, + ) + fixture = DummyTimeStamper( + asn1_x509.Certificate.load(leaf.public_bytes(serialization.Encoding.DER)), + keys.PrivateKeyInfo.load(tsa_key.private_bytes( + serialization.Encoding.DER, serialization.PrivateFormat.PKCS8, + serialization.NoEncryption(), + )), + ) + timestamp_digests = [] + + class TimestampHandler(BaseHTTPRequestHandler): + def do_POST(self): + self.connection.settimeout(3) + assert self.path == "/timestamp" + assert self.headers["Content-Type"] == "application/timestamp-query" + data = self.rfile.read(int(self.headers["Content-Length"])) + reply = fixture.request_tsa_response(tsp.TimeStampReq.load(data)) + timestamp_digests.append( + "sha256:" + hashlib.sha256(reply["time_stamp_token"].dump()).hexdigest() + ) + response = reply.dump() + self.send_response_only(200) + self.send_header("Content-Type", "application/timestamp-reply") + self.send_header("Content-Length", str(len(response))) + self.end_headers() + self.wfile.write(response) + + with HTTPServer(("127.0.0.1", 0), TimestampHandler) as server: + thread = threading.Thread(target=server.serve_forever) + thread.start() + try: + yield f"http://127.0.0.1:{server.server_port}/timestamp", timestamp_digests + finally: + server.shutdown() + thread.join() + + +def request(port, path, *, token=None): + connection = http.client.HTTPConnection("127.0.0.1", port, timeout=25) + try: + if token is None: + connection.request("GET", path) + else: + connection.request("POST", path, REQUEST, { + "Authorization": "Bearer " + token, + "Accept": "application/pdf", + "Content-Type": "application/json", + }) + response = connection.getresponse() + return response.status, response.headers, response.read() + finally: + connection.close() + + +def delivery(binary, directory, issuer_key, *, tsa_url=None): + with socket.socket() as reservation: + reservation.bind(("127.0.0.1", 0)) + port = reservation.getsockname()[1] + audit = directory / "audit.jsonl" + runtime = directory / "runtime.yaml" + if tsa_url is None: + timestamp_settings = "withoutTimestamp: seal-stops-validating-when-certificate-expires" + else: + timestamp_settings = f"timestampAuthority:\n url: {tsa_url}" + runtime.write_text(f"""\ +apiVersion: id.registrystack.org/formats/render/runtime/v1alpha1 +kind: RenderRuntimeConfig +listener: + bind: 127.0.0.1:{port} +package: + root: {json.dumps(str(directory / 'package'))} +secretProviders: + file: + root: {json.dumps(str(directory / 'secrets'))} +authentication: + oidc: + issuers: + fixture: + issuer: {ISSUER} + audience: {AUDIENCE} + allowedClients: [{CLIENT}] + jwksSource: + type: static + documentRef: secret:file/jwks.json +audit: + path: {json.dumps(str(audit))} +assuranceProfile: local +signing: + seals: + ministry: + signer: + type: local-jwk + privateKeyRef: secret:file/seal.jwk + certificateChainFile: {json.dumps(str(directory / 'chain.pem'))} + {timestamp_settings} + allowedClients: [{CLIENT}] +""") + checked = subprocess.run( + [binary, "check", "--bundle", directory / "package", "--runtime-config", runtime, + "--environment", "--posture", "development", "--format", "json"], + capture_output=True, timeout=30, + ) + report = json.loads(checked.stdout) + assert checked.returncode == 0 and report["ok"], report + assert [item["code"] for item in report["diagnostics"]] == [ + "render.posture.local-assurance" + ], report + log_path = directory / "serve.jsonl" + with log_path.open("w") as log, subprocess.Popen( + [binary, "serve", "--runtime-config", runtime, "--posture", "development"], + stdout=subprocess.DEVNULL, stderr=log, + ) as server: + try: + for _ in range(100): + if server.poll() is not None: + raise RuntimeError(f"Render exited before readiness ({server.returncode})") + try: + status, _, body = request(port, "/ready") + except ConnectionRefusedError: + time.sleep(0.1) + continue + if status == 200 and json.loads(body)["signing"]["ministry"]["status"] == "ready": + break + time.sleep(0.1) + else: + raise RuntimeError("Render seal did not become ready") + + path = "/v1/seal/notice" + status, headers, body = request(port, path, token=sign_token(issuer_key, "render:seal")) + assert status == 200, f"seal returned HTTP {status}" + assert headers.get_content_type() == "application/pdf" + assert headers["Registry-Posture"] == "development" + assert headers["X-Registry-Seal-Test-Only"] == "true" + assert headers["X-Registry-Seal-Id"] == "ministry" + assert headers["X-Registry-Seal-Level"] == ("B-B" if tsa_url is None else "B-T") + assert ("X-Registry-Timestamped-At" in headers) == (tsa_url is not None) + refused, _, problem = request(port, path, token=sign_token(issuer_key, "render:render")) + assert refused == 403, f"wrong scope returned HTTP {refused}" + refusal = json.loads(problem) + assert refusal["code"] == "render.forbidden" and refusal["failedCheck"] == "scope" + finally: + if server.poll() is None: + server.terminate() + try: + server.wait(timeout=10) + except subprocess.TimeoutExpired: + server.kill() + server.wait() + raise + assert server.returncode == 0, f"Render shutdown exited {server.returncode}" + warnings = [ + event["fields"].get("error_code") + for event in map(json.loads, log_path.read_text().splitlines()) + if event["level"] in ("WARN", "ERROR") + ] + assert warnings == ["render.posture.local-assurance"], warnings + entries = [json.loads(line) for line in audit.read_text().splitlines()] + sealed, = (entry for entry in entries if entry["record"].get("outcome") == "sealed") + matching = [entry["phase"] for entry in entries + if entry["correlation"] == sealed["correlation"]] + assert matching == ["request", "response"], matching + for name, header in ( + ("documentDigest", "X-Registry-Document-Digest"), + ("signedFileDigest", "X-Registry-Signed-File-Digest"), + ("certificateDigest", "X-Registry-Certificate-Digest"), + ): + assert sealed["record"][name] == headers[header], name + return headers, body, sealed["record"] + + +def verify_delivery(directory, headers, pdf, expected_certificate, *, tsa_root=None): + signed_digest = "sha256:" + hashlib.sha256(pdf).hexdigest() + assert headers["X-Registry-Signed-File-Digest"] == signed_digest + assert headers["X-Registry-Certificate-Digest"] == expected_certificate + signed = directory / "document.pdf" + signed.write_bytes(pdf) + with signed.open("rb") as stream: + signature, = PdfFileReader(stream).embedded_signatures + certificate_digest = "sha256:" + hashlib.sha256(signature.signer_cert.dump()).hexdigest() + assert certificate_digest == expected_certificate + + def verify(path, *trust_roots): + roots = [argument for root in trust_roots for argument in ("--trust-root", root)] + result = subprocess.run( + [sys.executable, HERE / "validate-seal.py", "--pdf", path, + *roots, "--document-digest", + headers["X-Registry-Document-Digest"]], + capture_output=True, timeout=30, + ) + return result.returncode, json.loads(result.stdout) + + root = directory / "root.pem" + roots = [root] + if tsa_root is not None: + roots.append(tsa_root) + code, report = verify(signed, root) + assert code == 1 and not report["ok"], report + assert any( + check["name"] == "signature-timestamp-valid" and not check["ok"] + for check in report["checks"] + ), report + code, report = verify(signed, *roots) + assert (code, report["ok"], report["level"]) == ( + 0, True, headers["X-Registry-Seal-Level"] + ), report + code, report = verify(signed, directory / "other-root.pem") + assert code == 1 and not report["ok"], report + assert any(check["name"] == "trusted" and not check["ok"] for check in report["checks"]) + + # Change a byte in the original revision without breaking PDF syntax. + tampered = directory / "tampered.pdf" + assert pdf.startswith(b"%PDF-") and pdf[7:8].isdigit() + replacement = b"6" if pdf[7:8] != b"6" else b"7" + tampered.write_bytes(pdf[:7] + replacement + pdf[8:]) + code, report = verify(tampered, *roots) + assert code == 1 and not report["ok"], report + assert any(check["name"] == "intact" and not check["ok"] for check in report["checks"]), report + assert "sha256:" + hashlib.sha256(tampered.read_bytes()).hexdigest() != signed_digest + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--render", type=Path, required=True, help="published Render executable") + parser.add_argument("--scratch", type=Path, required=True, help="parent for a private fixture") + args = parser.parse_args() + binary = args.render.resolve(strict=True) + os.umask(0o077) + with tempfile.TemporaryDirectory(prefix="render-delivery-", dir=args.scratch) as temporary: + directory = Path(temporary).resolve() + issuer_key, certificate = write_fixture(binary, directory) + headers, pdf, audit = delivery(binary, directory, issuer_key) + verify_delivery(directory, headers, pdf, certificate) + assert "timestampTokenDigest" not in audit + (directory / "timestamped").mkdir() + with timestamp_authority(directory) as (tsa_url, timestamp_digests): + # Each runtime needs its own audit file and a single fixture key set. + timestamped = directory / "timestamped" + issuer_key, certificate = write_fixture(binary, timestamped) + headers, pdf, audit = delivery(binary, timestamped, issuer_key, tsa_url=tsa_url) + verify_delivery(timestamped, headers, pdf, certificate, tsa_root=directory / "tsa-root.pem") + assert timestamp_digests == [audit["timestampTokenDigest"]] + print("B-B and B-T signed delivery passed: exact PDF, first revision, signer, audit, and refusals") + + +if __name__ == "__main__": + main() From 16462c50eab8172e7210ce47926eb9547c640b68 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 09:26:32 +0000 Subject: [PATCH 003/183] docs(scheduling): qualify Keycloak catalogue access Signed-off-by: Jeremi Joslin --- .../src/content/docs/operate/scheduling.mdx | 28 +++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/docs/site/src/content/docs/operate/scheduling.mdx b/docs/site/src/content/docs/operate/scheduling.mdx index 6ac31ea9d1..dde5ad4ca3 100644 --- a/docs/site/src/content/docs/operate/scheduling.mdx +++ b/docs/site/src/content/docs/operate/scheduling.mdx @@ -153,6 +153,34 @@ databaseAccess: false networkAccess: false ``` +### Use Keycloak for catalogue reads + +Follow the [Keycloak issuer recipe](../advanced/connect-an-oidc-issuer/#keycloak) +for the entry under `authentication.oidc.issuers`. Set `audience` to your +Scheduling API client ID in Keycloak. Give the calling client's service account +a role on that API client so Keycloak includes it in the access token's +audience. Attach `scheduling:read` as a default client scope to the calling +client, or use the scope you configured in `readsScope`. + +After Scheduling is ready, obtain a client-credentials access token and call +`GET /v1/locations`. Expect HTTP `200`. If you receive +`authentication.refused`, check the issuer URL, token type, audience and +`allowedClients`. If you receive `profile.not-authorized`, check that the +token contains the read scope in the configured `scopeClaim`. + +A hold or appointment requires a token carrying a [Scheduling task +grant](../../reference/scheduling-task-grants/). A catalogue token without the +grant receives HTTP `403` with `operation.not-authorized` on a hold request. +To book with Keycloak, provision and verify a grant flow that binds the token +to the exact Scheduling resource and action. The catalogue setup above issues +the identity used for the read. + +{/* Evidence: products/platform/journeys/own-provider.sh, write_keycloak_recipe, + keycloak_default_scope, step_token, call_request; + products/platform/journeys/keycloak/realm.json, scheduling-booking-agent; + crates/registry-scheduling/src/auth.rs; crates/registry-scheduling/src/http.rs, + create_hold; products/scheduling/generated/registry-scheduling.openapi.json. */} + ## Package the policy ```sh From f027d570d3ec1d100981a4eb6ab4848358331549 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 14:12:36 +0000 Subject: [PATCH 004/183] test(render): qualify Transit and HTTPS timestamp delivery Signed-off-by: Jeremi Joslin --- products/render/README.md | 10 + .../render/scripts/test_signed_delivery.py | 92 +++++-- .../render/scripts/test_transit_delivery.py | 256 ++++++++++++++++++ 3 files changed, 334 insertions(+), 24 deletions(-) create mode 100644 products/render/scripts/test_transit_delivery.py diff --git a/products/render/README.md b/products/render/README.md index 855511d07e..a97d8b917e 100644 --- a/products/render/README.md +++ b/products/render/README.md @@ -63,6 +63,16 @@ The scaffold compiles offline out of the box: the binary embeds a baseline Latin font set. Scripts beyond Latin (Arabic, Hebrew, …) need a bundle font (see `registry-render init`'s note) and `registry-render check` names the gap. +## Qualify signed delivery + +Check development B-B and B-T delivery from the repository root with +`uv run --script products/render/scripts/test_signed_delivery.py`. +Pass `--render ` and `--scratch `. +Use the same arguments with `products/render/scripts/test_transit_delivery.py` +to check production-posture B-T through OpenBao Transit and an HTTPS timestamp +authority. The Transit check needs a local Linux Docker engine and the +OpenBao image pinned in the script. + ## Where to read next - [Deploy Registry Render](https://docs.registrystack.org/operate/registry-render/): install, diff --git a/products/render/scripts/test_signed_delivery.py b/products/render/scripts/test_signed_delivery.py index d77dcddc57..b571ee3b54 100644 --- a/products/render/scripts/test_signed_delivery.py +++ b/products/render/scripts/test_signed_delivery.py @@ -60,7 +60,7 @@ def sign_token(key, scope): return data + "." + b64url(r.to_bytes(32, "big") + s.to_bytes(32, "big")) -def issue_certificate(public_key, name, issuer, issuer_key, *, purpose=None): +def issue_certificate(public_key, name, issuer, issuer_key, *, purpose=None, names=None): now = datetime.now(timezone.utc) subject = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, name)]) is_root = issuer is None @@ -83,10 +83,12 @@ def issue_certificate(public_key, name, issuer, issuer_key, *, purpose=None): builder = builder.add_extension( x509.ExtendedKeyUsage([purpose]), critical=purpose == ExtendedKeyUsageOID.TIME_STAMPING ) + if names is not None: + builder = builder.add_extension(x509.SubjectAlternativeName(names), critical=False) return builder.sign(issuer_key, hashes.SHA256()) -def write_fixture(binary, directory): +def write_fixture(binary, directory, *, transit_socket=None): def run(*args): subprocess.run([binary, *args], check=True, stdout=subprocess.DEVNULL, timeout=30) @@ -94,7 +96,13 @@ def run(*args): secrets = directory / "secrets" secrets.mkdir(mode=0o700) csr_path = directory / "seal.csr" - run("keygen", "--key", secrets / "seal.jwk", "--csr", csr_path, + key_settings = ["--key", secrets / "seal.jwk"] + if transit_socket is not None: + key_settings = [ + "--transit-unix-socket-path", transit_socket, "--transit-mount", "transit", + "--transit-key-name", "render-seal", "--transit-key-version", "1", + ] + run("keygen", *key_settings, "--csr", csr_path, "--common-name", "Qualification test seal", "--country", "FR") signer_key = x509.load_pem_x509_csr(csr_path.read_bytes()).public_key() root_key = ec.generate_private_key(ec.SECP256R1()) @@ -122,7 +130,7 @@ def run(*args): @contextmanager -def timestamp_authority(directory): +def timestamp_authority(directory, *, tls=None): root_key = ec.generate_private_key(ec.SECP256R1()) root = issue_certificate(root_key.public_key(), "Qualification TSA root", None, root_key) (directory / "tsa-root.pem").write_bytes(root.public_bytes(serialization.Encoding.PEM)) @@ -158,10 +166,14 @@ def do_POST(self): self.wfile.write(response) with HTTPServer(("127.0.0.1", 0), TimestampHandler) as server: + scheme = "http" + if tls is not None: + server.socket = tls.wrap_socket(server.socket, server_side=True) + scheme = "https" thread = threading.Thread(target=server.serve_forever) thread.start() try: - yield f"http://127.0.0.1:{server.server_port}/timestamp", timestamp_digests + yield f"{scheme}://127.0.0.1:{server.server_port}/timestamp", timestamp_digests finally: server.shutdown() thread.join() @@ -184,7 +196,10 @@ def request(port, path, *, token=None): connection.close() -def delivery(binary, directory, issuer_key, *, tsa_url=None): +def delivery( + binary, directory, issuer_key, *, tsa_url=None, transit_socket=None, + tsa_ca=False, expect_timestamp_failure=False, +): with socket.socket() as reservation: reservation.bind(("127.0.0.1", 0)) port = reservation.getsockname()[1] @@ -194,6 +209,20 @@ def delivery(binary, directory, issuer_key, *, tsa_url=None): timestamp_settings = "withoutTimestamp: seal-stops-validating-when-certificate-expires" else: timestamp_settings = f"timestampAuthority:\n url: {tsa_url}" + if tsa_ca: + timestamp_settings += "\n caBundleRef: secret:file/tsa-tls-root.pem" + posture = "development" + assurance = "local" + signer = "type: local-jwk\n privateKeyRef: secret:file/seal.jwk" + expected_warnings = ["render.posture.local-assurance"] + if transit_socket is not None: + posture = assurance = "production" + signer = ( + f"type: transit\n unixSocketPath: {json.dumps(str(transit_socket))}\n" + " mount: transit\n keyName: render-seal\n keyVersion: 1\n" + " attemptTimeoutMilliseconds: 2000" + ) + expected_warnings = [] runtime.write_text(f"""\ apiVersion: id.registrystack.org/formats/render/runtime/v1alpha1 kind: RenderRuntimeConfig @@ -216,30 +245,27 @@ def delivery(binary, directory, issuer_key, *, tsa_url=None): documentRef: secret:file/jwks.json audit: path: {json.dumps(str(audit))} -assuranceProfile: local +assuranceProfile: {assurance} signing: seals: ministry: signer: - type: local-jwk - privateKeyRef: secret:file/seal.jwk + {signer} certificateChainFile: {json.dumps(str(directory / 'chain.pem'))} {timestamp_settings} allowedClients: [{CLIENT}] """) checked = subprocess.run( [binary, "check", "--bundle", directory / "package", "--runtime-config", runtime, - "--environment", "--posture", "development", "--format", "json"], + "--environment", "--posture", posture, "--format", "json"], capture_output=True, timeout=30, ) report = json.loads(checked.stdout) assert checked.returncode == 0 and report["ok"], report - assert [item["code"] for item in report["diagnostics"]] == [ - "render.posture.local-assurance" - ], report + assert [item["code"] for item in report["diagnostics"]] == expected_warnings, report log_path = directory / "serve.jsonl" with log_path.open("w") as log, subprocess.Popen( - [binary, "serve", "--runtime-config", runtime, "--posture", "development"], + [binary, "serve", "--runtime-config", runtime, "--posture", posture], stdout=subprocess.DEVNULL, stderr=log, ) as server: try: @@ -259,17 +285,29 @@ def delivery(binary, directory, issuer_key, *, tsa_url=None): path = "/v1/seal/notice" status, headers, body = request(port, path, token=sign_token(issuer_key, "render:seal")) - assert status == 200, f"seal returned HTTP {status}" - assert headers.get_content_type() == "application/pdf" - assert headers["Registry-Posture"] == "development" - assert headers["X-Registry-Seal-Test-Only"] == "true" - assert headers["X-Registry-Seal-Id"] == "ministry" - assert headers["X-Registry-Seal-Level"] == ("B-B" if tsa_url is None else "B-T") - assert ("X-Registry-Timestamped-At" in headers) == (tsa_url is not None) + if expect_timestamp_failure: + assert status == 502 and headers.get_content_type() == "application/problem+json" + assert json.loads(body)["code"] == "render.timestamp-failed" + else: + assert status == 200, f"seal returned HTTP {status}" + assert headers.get_content_type() == "application/pdf" + assert headers["X-Registry-Seal-Id"] == "ministry" + assert headers["X-Registry-Seal-Level"] == ("B-B" if tsa_url is None else "B-T") + assert ("X-Registry-Timestamped-At" in headers) == (tsa_url is not None) + if posture == "development": + assert headers["Registry-Posture"] == "development" + assert headers["X-Registry-Seal-Test-Only"] == "true" + else: + assert "Registry-Posture" not in headers + assert "X-Registry-Seal-Test-Only" not in headers refused, _, problem = request(port, path, token=sign_token(issuer_key, "render:render")) assert refused == 403, f"wrong scope returned HTTP {refused}" refusal = json.loads(problem) - assert refusal["code"] == "render.forbidden" and refusal["failedCheck"] == "scope" + assert refusal["code"] == "render.forbidden" + if posture == "development": + assert refusal["failedCheck"] == "scope" + else: + assert "failedCheck" not in refusal finally: if server.poll() is None: server.terminate() @@ -281,12 +319,18 @@ def delivery(binary, directory, issuer_key, *, tsa_url=None): raise assert server.returncode == 0, f"Render shutdown exited {server.returncode}" warnings = [ - event["fields"].get("error_code") + event["fields"].get("error_code") or event["fields"].get("problem") for event in map(json.loads, log_path.read_text().splitlines()) if event["level"] in ("WARN", "ERROR") ] - assert warnings == ["render.posture.local-assurance"], warnings + if expect_timestamp_failure: + expected_warnings.append("timestamp-failed") + assert warnings == expected_warnings, warnings entries = [json.loads(line) for line in audit.read_text().splitlines()] + if expect_timestamp_failure: + assert not any(entry["record"].get("outcome") == "sealed" for entry in entries) + assert any(entry["record"].get("problem") == "timestamp-failed" for entry in entries) + return headers, body, None sealed, = (entry for entry in entries if entry["record"].get("outcome") == "sealed") matching = [entry["phase"] for entry in entries if entry["correlation"] == sealed["correlation"]] diff --git a/products/render/scripts/test_transit_delivery.py b/products/render/scripts/test_transit_delivery.py new file mode 100644 index 0000000000..68646662cc --- /dev/null +++ b/products/render/scripts/test_transit_delivery.py @@ -0,0 +1,256 @@ +#!/usr/bin/env python3 +# /// script +# requires-python = ">=3.11" +# dependencies = ["pyhanko==0.38.1"] +# /// +# SPDX-License-Identifier: Apache-2.0 +"""Qualify production-posture Render with disposable OpenBao and an HTTPS TSA.""" + +import argparse +import http.client +import ipaddress +import json +import os +import socket +import ssl +import subprocess +import tempfile +import time +from contextlib import contextmanager +from pathlib import Path + +from cryptography import x509 +from cryptography.hazmat.primitives import serialization +from cryptography.hazmat.primitives.asymmetric import ec +from cryptography.x509.oid import ExtendedKeyUsageOID + +from test_signed_delivery import ( + delivery, + issue_certificate, + timestamp_authority, + verify_delivery, + write_fixture, +) + +OPENBAO = "ghcr.io/openbao/openbao@sha256:09f1eaaee351c329d75a5a89654d6e1ad4792998650c3cbf0c3513a76d9d9b6e" +POLICY = """ +path "transit/keys/render-seal" { + capabilities = ["read"] +} + +path "transit/sign/render-seal/sha2-256" { + capabilities = ["update"] + required_parameters = ["input", "key_version", "marshaling_algorithm", "prehashed"] + allowed_parameters = { + "input" = [] + "key_version" = ["1"] + "marshaling_algorithm" = ["jws"] + "prehashed" = [true] + } +} +""" + + +@contextmanager +def bao_process(config, command): + directory = config.parent + identity = f"{os.getuid()}:{os.getgid()}" + container_id = subprocess.check_output( + ["docker", "run", "--pull", "never", "--rm", "--detach", + "--network", "host", "--user", identity, + "--mount", f"type=bind,source={directory},target={directory}", + "--entrypoint", "bao", OPENBAO, command, "-config", config], + text=True, timeout=30, + ).strip() + try: + yield + finally: + subprocess.run(["docker", "stop", "--time", "3", container_id], + check=True, stdout=subprocess.DEVNULL, timeout=15) + + +def bao_request(connection, method, path, *, token=None, data=None): + headers = {"X-Vault-Request": "true", "Content-Type": "application/json"} + if token is not None: + headers["X-Vault-Token"] = token + try: + connection.request(method, "/v1/" + path, json.dumps(data) if data is not None else None, + headers) + response = connection.getresponse() + payload = response.read() + return response.status, json.loads(payload) if payload else None + finally: + connection.close() + + +def wait_for(probe, expected): + for _ in range(50): + try: + status, result = probe() + except (ConnectionRefusedError, FileNotFoundError): + time.sleep(0.1) + continue + if status == expected: + return result + time.sleep(0.1) + raise RuntimeError(f"OpenBao did not return HTTP {expected} for the readiness probe") + + +class UnixHttpConnection(http.client.HTTPConnection): + def __init__(self, path): + super().__init__("localhost", timeout=3) + self.path = path + + def connect(self): + self.sock = socket.socket(socket.AF_UNIX) + self.sock.settimeout(self.timeout) + self.sock.connect(str(self.path)) + + +@contextmanager +def transit_proxy(directory): + with socket.socket() as reservation: + reservation.bind(("127.0.0.1", 0)) + port = reservation.getsockname()[1] + server = directory / "bao.hcl" + server.write_text(f""" +disable_mlock = true +api_addr = "http://127.0.0.1:{port}" +storage "inmem" {{}} +listener "tcp" {{ + address = "127.0.0.1:{port}" + tls_disable = true +}} +""") + root_token = None + + def request(method, path, expected, data=None): + status, response = bao_request( + http.client.HTTPConnection("127.0.0.1", port, timeout=3), + method, path, token=root_token, data=data, + ) + assert status == expected, f"OpenBao {method} {path}: HTTP {status}, expected {expected}" + return response + + with bao_process(server, "server"): + def health(): + return bao_request(http.client.HTTPConnection("127.0.0.1", port, timeout=3), + "GET", "sys/health") + + wait_for(health, 501) + init = request("PUT", "sys/init", 200, {"secret_shares": 1, "secret_threshold": 1}) + root_token = init["root_token"] + request("PUT", "sys/unseal", 200, {"key": init["keys_base64"][0]}) + request("POST", "sys/mounts/transit", 204, {"type": "transit"}) + request("POST", "transit/keys/render-seal", 200, { + "type": "ecdsa-p256", "derived": False, "exportable": False, + "allow_plaintext_backup": False, + }) + request("PUT", "sys/policies/acl/render-seal", 204, {"policy": POLICY}) + request("POST", "sys/auth/approle", 204, {"type": "approle"}) + request("POST", "auth/approle/role/render-seal", 204, { + "token_policies": ["render-seal"], "token_ttl": "10m", "token_max_ttl": "10m", + "secret_id_ttl": "10m", + }) + role = request("GET", "auth/approle/role/render-seal/role-id", 200) + secret = request("POST", "auth/approle/role/render-seal/secret-id", 200) + (directory / "role-id").write_text(role["data"]["role_id"]) + (directory / "secret-id").write_text(secret["data"]["secret_id"]) + unix_socket = directory / "bao.sock" + agent = directory / "agent.hcl" + agent.write_text(f""" +vault {{ + address = "http://127.0.0.1:{port}" + retry {{ num_retries = -1 }} +}} +auto_auth {{ + method "approle" {{ + config = {{ + role_id_file_path = {json.dumps(str(directory / 'role-id'))} + secret_id_file_path = {json.dumps(str(directory / 'secret-id'))} + }} + }} +}} +api_proxy {{ use_auto_auth_token = "force" }} +listener "unix" {{ + address = {json.dumps(str(unix_socket))} + tls_disable = true + socket_mode = "0660" + socket_user = "{os.getuid()}" + socket_group = "{os.getgid()}" + require_request_header = true +}} +""") + with bao_process(agent, "agent"): + metadata = wait_for(lambda: bao_request( + UnixHttpConnection(unix_socket), "GET", "transit/keys/render-seal" + ), 200)["data"] + assert metadata["type"] == "ecdsa-p256" and metadata["latest_version"] == 1 + for setting in ("derived", "exportable", "allow_plaintext_backup"): + assert metadata[setting] is False, setting + owner = unix_socket.stat() + mode = owner.st_mode & 0o777 + assert mode == 0o660, f"OpenBao Agent socket has mode {mode:#o}" + assert (owner.st_uid, owner.st_gid) == (os.getuid(), os.getgid()) + forced, _ = bao_request(UnixHttpConnection(unix_socket), "GET", "sys/mounts", + token=root_token) + assert forced == 403, f"proxy forwarded the caller token, HTTP {forced}" + yield unix_socket + + +def tsa_tls(directory): + root_key = ec.generate_private_key(ec.SECP256R1()) + root = issue_certificate(root_key.public_key(), "Qualification TLS root", None, root_key) + key = ec.generate_private_key(ec.SECP256R1()) + leaf = issue_certificate( + key.public_key(), "Qualification RFC 3161 server", root, root_key, + purpose=ExtendedKeyUsageOID.SERVER_AUTH, + names=[x509.IPAddress(ipaddress.IPv4Address("127.0.0.1"))], + ) + chain = directory / "tls-chain.pem" + chain.write_bytes(leaf.public_bytes(serialization.Encoding.PEM)) + private = directory / "tls-key.pem" + private.write_bytes(key.private_bytes( + serialization.Encoding.PEM, serialization.PrivateFormat.PKCS8, serialization.NoEncryption() + )) + context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) + context.load_cert_chain(chain, private) + return context, root.public_bytes(serialization.Encoding.PEM) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--render", type=Path, required=True, help="published Render executable") + parser.add_argument("--scratch", type=Path, required=True, help="parent for a private fixture") + args = parser.parse_args() + binary = args.render.resolve(strict=True) + os.umask(0o077) + with tempfile.TemporaryDirectory(prefix="transit-", dir=args.scratch) as temporary: + directory = Path(temporary).resolve() + tls, tls_root = tsa_tls(directory) + with transit_proxy(directory) as proxy, timestamp_authority(directory, tls=tls) as tsa: + url, digests = tsa + untrusted = directory / "untrusted" + untrusted.mkdir() + issuer, _ = write_fixture(binary, untrusted, transit_socket=proxy) + delivery(binary, untrusted, issuer, tsa_url=url, transit_socket=proxy, + expect_timestamp_failure=True) + assert digests == [], "a timestamp query crossed the untrusted TLS connection" + + trusted = directory / "trusted" + trusted.mkdir() + issuer, certificate = write_fixture(binary, trusted, transit_socket=proxy) + (trusted / "secrets/tsa-tls-root.pem").write_bytes(tls_root) + headers, pdf, audit = delivery( + binary, trusted, issuer, tsa_url=url, transit_socket=proxy, tsa_ca=True + ) + verify_delivery(trusted, headers, pdf, certificate, tsa_root=directory / "tsa-root.pem") + assert digests == [audit["timestampTokenDigest"]] + assert { + path.name for path in (trusted / "secrets").iterdir() + } == {"jwks.json", "tsa-tls-root.pem"} + print("Production-posture Render passed with OpenBao Transit and an independently trusted HTTPS TSA") + + +if __name__ == "__main__": + main() From 8376bf7b8583fd3251a3e0aa94b9136c405d9623 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 14:35:15 +0000 Subject: [PATCH 005/183] test(discovery): pin catalog transport behavior Signed-off-by: Jeremi Joslin --- .../scripts/test_catalog_transport.py | 181 ++++++++++++++++++ 1 file changed, 181 insertions(+) create mode 100644 products/discovery/scripts/test_catalog_transport.py diff --git a/products/discovery/scripts/test_catalog_transport.py b/products/discovery/scripts/test_catalog_transport.py new file mode 100644 index 0000000000..1f120aa96b --- /dev/null +++ b/products/discovery/scripts/test_catalog_transport.py @@ -0,0 +1,181 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: Apache-2.0 +"""Check Discovery catalog transport using a verified discoveryctl executable. + +Run with --discoveryctl --scratch . +The regression needs IPv4 and IPv6 loopback and performs no external fetches. +""" + +import argparse +import hashlib +import json +import os +import socket +import subprocess +import tempfile +import threading +from contextlib import contextmanager +from http.server import BaseHTTPRequestHandler, HTTPServer +from pathlib import Path + +PRODUCT = Path(__file__).resolve().parents[1] +PROFILE = "registry-discovery-v1alpha1" +MEDIA_TYPE = 'application/ld+json;profile="https://registrystack.org/discovery/profile/v1alpha1"' +CATALOG = PRODUCT / "fixtures/descriptions/evidence.jsonld" + + +@contextmanager +def catalog_server(host, url_host, family): + seen = [] + connections = [] + description = CATALOG.read_bytes() + + class CatalogHandler(BaseHTTPRequestHandler): + def do_GET(self): + seen.append((self.path, self.headers.get("Accept"), "Authorization" in self.headers)) + if self.path == "/redirect": + self.send_response_only(302) + self.send_header("Location", "/catalog.jsonld") + self.end_headers() + elif self.path == "/catalog.jsonld": + self.send_response_only(200) + self.send_header("Content-Type", MEDIA_TYPE) + self.send_header("Content-Length", str(len(description))) + self.end_headers() + self.wfile.write(description) + else: + self.send_response_only(404) + self.end_headers() + + class CatalogServer(HTTPServer): + address_family = family + + def get_request(self): + connection, address = super().get_request() + connection.settimeout(3) + connections.append(address) + return connection, address + + with CatalogServer((host, 0), CatalogHandler) as server: + thread = threading.Thread(target=server.serve_forever) + thread.start() + try: + yield f"{url_host}:{server.server_port}", seen, connections + finally: + server.shutdown() + thread.join() + + +def project_for(directory, url): + project = directory / "project" + project.mkdir(parents=True) + (project / "origins.yaml").write_text(f"""\ +apiVersion: id.registrystack.org/formats/discovery/origins/v1alpha1 +kind: DiscoveryOrigins +origins: + fixture: + catalogUrl: {json.dumps(url)} + profile: {PROFILE} +""") + (project / "mappings").mkdir() + mapping = PRODUCT / "examples/starter/mappings/adult-status.yaml" + (project / "mappings/adult-status.yaml").write_bytes(mapping.read_bytes()) + return project + + +def run_package(binary, directory, url, posture, *, proxy=None): + project = project_for(directory, url) + output = directory / "package" + env = os.environ.copy() + env.pop("REGISTRY_STACK_POSTURE", None) + if proxy is not None: + for key in ("HTTP_PROXY", "http_proxy", "ALL_PROXY", "all_proxy"): + env[key] = proxy + for key in ("NO_PROXY", "no_proxy"): + env.pop(key, None) + result = subprocess.run( + [binary, "package", "--project", project, "--output", output, "--posture", posture], + capture_output=True, text=True, timeout=30, env=env, + ) + return result, output + + +def require_refusal(result, output, diagnostic): + assert result.returncode == 1, (result.returncode, result.stdout, result.stderr) + assert diagnostic in result.stderr, result.stderr + assert not output.exists(), output + + +def loopback_cases(binary, directory, host, url_host, family): + with catalog_server(host, url_host, family) as (authority, seen, connections): + url = f"http://{authority}/catalog.jsonld" + request = ("/catalog.jsonld", MEDIA_TYPE, False) + result, output = run_package( + binary, directory / "development", url, "development", + proxy=f"http://{authority}", + ) + assert result.returncode == 0, (result.stdout, result.stderr) + assert seen == [request], seen + assert len(connections) == 1, connections + index_path = output / "discovery-index.json" + index_bytes = index_path.read_bytes() + index = json.loads(index_bytes) + assert len(index["services"]) == 1, index + assert index["origins"][0]["catalogUrl"] == url, index["origins"] + digest = hashlib.sha256(index_bytes).hexdigest() + checksums = (output / "SHA256SUMS").read_text().splitlines() + assert f"{digest} {index_path.name}" in checksums, checksums + + for scheme in ("http", "https"): + result, output = run_package( + binary, directory / f"production-{scheme}", + f"{scheme}://{authority}/catalog.jsonld", "production", + ) + require_refusal(result, output, "discovery.posture.loopback-catalog-url") + assert seen == [request], seen + assert len(connections) == 1, connections + + result, output = run_package( + binary, directory / "redirect", f"http://{authority}/redirect", "development", + ) + require_refusal(result, output, "an approved Discovery origin could not be fetched safely") + assert seen == [request, ("/redirect", MEDIA_TYPE, False)], seen + assert len(connections) == 2, connections + + +def spelling_cases(binary, directory): + for label, url, expected in ( + ("short-ipv4", "http://127.1:9/catalog.jsonld", "config.invalid-value"), + ("other-ipv4", "http://127.0.0.2:9/catalog.jsonld", + "discovery.origins.catalog-url-not-allowed"), + ("mapped-ipv6", "http://[::ffff:127.0.0.1]:9/catalog.jsonld", + "discovery.origins.catalog-url-not-allowed"), + ): + project = project_for(directory / label, url) + result = subprocess.run( + [binary, "check", "--project", project, "--posture", "development", "--format", "json"], + capture_output=True, text=True, timeout=10, + ) + assert result.returncode == 1, (result.returncode, result.stdout, result.stderr) + diagnostics = json.loads(result.stdout)["diagnostics"] + assert [(item["code"], item["path"]) for item in diagnostics] == [ + (expected, "/origins/fixture/catalogUrl") + ], diagnostics + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--discoveryctl", type=Path, required=True) + parser.add_argument("--scratch", type=Path, required=True) + args = parser.parse_args() + binary = args.discoveryctl.resolve(strict=True) + with tempfile.TemporaryDirectory(prefix="discovery-transport-", dir=args.scratch) as temporary: + directory = Path(temporary).resolve() + loopback_cases(binary, directory / "v4", "127.0.0.1", "127.0.0.1", socket.AF_INET) + loopback_cases(binary, directory / "v6", "::1", "[::1]", socket.AF_INET6) + spelling_cases(binary, directory) + print("Discovery catalog transport passed: two exact loopback fetches and nine refusal cases") + + +if __name__ == "__main__": + main() From 026eb4e43db9c3c20c846b1eecd1428bfc3128b4 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 09:20:19 +0000 Subject: [PATCH 006/183] fix(journeys): complete Render promotion with zero refusals Signed-off-by: Jeremi Joslin --- products/platform/journeys/README.md | 2 +- products/platform/journeys/expected-failures.yaml | 12 ++++-------- products/platform/journeys/promote.sh | 2 +- products/platform/journeys/test_journey_tables.py | 4 +++- 4 files changed, 9 insertions(+), 11 deletions(-) diff --git a/products/platform/journeys/README.md b/products/platform/journeys/README.md index eb437b9a2d..a4f7b26956 100644 --- a/products/platform/journeys/README.md +++ b/products/platform/journeys/README.md @@ -44,7 +44,7 @@ identity provider. | `rstack-dev.sh` | The `rstack dev` journey, with a recipe per product for the steps from `start` on. | | `own-provider.sh` | The own-provider journey: a stock Keycloak (`--issuer keycloak`) or pinned ThunderID (`--issuer thunderid`) plus a stock PostgreSQL started on loopback, then each product from its starter to authenticated calls and hooks. | | `lib-assists.sh` | The assists, sourced only when `--assist` names one: `sql` (provisioning statements through psql), `certificate` (a private CA and a TLS server certificate for the pg container), `token-type` (Keycloak's at+jwt header setting) and `mapper` (a hardcoded actor-kind claim mapper). The only journey file allowed to call psql, openssl or docker exec. Each use counts as a pass-rule violation. | -| `promote.sh` | The promote journey: `promote.sh --from RUN_DIR --bin-dir DIR`, paired with a kept Keycloak `own-provider.sh` run directory (`run.json` journey `own-provider` and `own-provider.json` issuer `keycloak`). Mismatched provider run directories (such as `--issuer thunderid`) are refused explicitly. It tries the files in place with no development declaration, compares startup and check diagnostics, and applies each remedy. Casework, Messaging, Scheduling, Documents, and Coordinator inputs that start successfully and pass the production check with zero diagnostics continue to a fresh production process and repeat the authenticated call. A product whose development cell did not finish stops at `input`. | +| `promote.sh` | The promote journey: `promote.sh --from RUN_DIR --bin-dir DIR`, paired with a kept Keycloak `own-provider.sh` run directory (`run.json` journey `own-provider` and `own-provider.json` issuer `keycloak`). Mismatched provider run directories (such as `--issuer thunderid`) are refused explicitly. It tries the files in place with no development declaration, compares startup and check diagnostics, and applies each remedy. Casework, Messaging, Scheduling, Documents, Coordinator, and Render inputs that start successfully and pass the production check with zero diagnostics continue to a fresh production process and repeat the authenticated call. A product whose development cell did not finish stops at `input`. | | `keycloak/realm.json` | The realm the Keycloak own-provider journey imports: per product, one caller client with a service account and one API client for the product's audience. Documents also has a service-account client that exercises the human staff profile's refusal. The realm holds no protocol mappers. | | `projects/` | The runtime files and pure-data fixture helpers the own-provider journey uses (Render, Coordinator, loopback hook and source receivers, and the composed BReg + Casework + Scheduling fixture writer). | diff --git a/products/platform/journeys/expected-failures.yaml b/products/platform/journeys/expected-failures.yaml index 9c1984e4ed..106d4336a9 100644 --- a/products/platform/journeys/expected-failures.yaml +++ b/products/platform/journeys/expected-failures.yaml @@ -100,14 +100,6 @@ expectedFailures: basis: observed observedOn: "origin/main cd83550e, journey run 20261127023442-18b4 against own-provider run 20261127021546-ddef" reason: "The development journey did not finish for this product, so there are no files to promote." - - journey: promote - product: render - step: refusals - code: journey.promote.nothing-refused - removedBy: rstack-dev-products - basis: observed - observedOn: "PR #2798, promote run 20261128133333-b78e on own-provider run 20261128133312-c739" - reason: "Render passes own-provider with a runtime file that carries no development-only setting (loopback listener, loopback HTTP issuer, explicit allowedClients, no database), so registry-render check and serve accept it under the default production posture and refuse nothing." - journey: promote product: discovery step: input @@ -253,6 +245,10 @@ unreached: # observedOn: "origin/main cd83550e, promote run 20261127025000-816f on own-provider run 20261127024425-265d (assisted: sql, certificate, token-type, mapper)" # reason: "The assisted Scheduling cell reached T1. Started with no development declaration, schedulingctl check (which has no --production flag) lists no refusal and the server starts and answers /readyz, so zero refusals are listed. No shared posture exists on main, so nothing can refuse. The count becomes meaningful once the posture change lands." passes: + - journey: promote + product: render + basis: observed + observedOn: "v0.49.0 binaries, promote run 20261201091716-e777" - journey: own-provider product: casework basis: observed diff --git a/products/platform/journeys/promote.sh b/products/platform/journeys/promote.sh index 41d0f250a5..2322b6cabd 100755 --- a/products/platform/journeys/promote.sh +++ b/products/platform/journeys/promote.sh @@ -319,7 +319,7 @@ production_outcome() { printf '%s\n' remediate elif [[ "$state" == started && "$status" == 0 && -z "$codes" ]]; then case "$product" in - casework | messaging | scheduling | documents | coordinator) printf '%s\n' compatible ;; + casework | messaging | scheduling | documents | coordinator | render) printf '%s\n' compatible ;; *) printf '%s\n' missing-refusal ;; esac else diff --git a/products/platform/journeys/test_journey_tables.py b/products/platform/journeys/test_journey_tables.py index 50d1a89fcb..7650fe2895 100644 --- a/products/platform/journeys/test_journey_tables.py +++ b/products/platform/journeys/test_journey_tables.py @@ -507,7 +507,9 @@ def test_zero_diagnostics_requires_a_successful_check_and_an_explicit_case(self) ("messaging", "started", 0, "", "compatible"), ("scheduling", "started", 0, "", "compatible"), ("coordinator", "started", 0, "", "compatible"), - ("render", "started", 0, "", "missing-refusal"), + ("render", "started", 0, "", "compatible"), + ("render", "refused", 1, "render.config.refused", "remediate"), + ("breg", "started", 0, "", "missing-refusal"), ("messaging", "started", 1, "", "invalid"), ("scheduling", "refused", 1, "", "invalid"), ("coordinator", "refused", 1, "config.dev-only", "remediate"), From c052066697cc2c00c6c4e9616fa1b56ed0f2f22f Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 14:36:05 +0000 Subject: [PATCH 007/183] fix(journeys): verify Adapter promotion and count production refusals Signed-off-by: Jeremi Joslin --- products/platform/journeys/README.md | 22 ++++- .../platform/journeys/expected-failures.yaml | 24 ++--- products/platform/journeys/lib.sh | 15 ++- products/platform/journeys/own-provider.sh | 95 +++++++------------ products/platform/journeys/promote.sh | 53 ++++++++--- .../platform/journeys/test_journey_tables.py | 3 + products/platform/journeys/test_lib.sh | 16 ++++ 7 files changed, 134 insertions(+), 94 deletions(-) diff --git a/products/platform/journeys/README.md b/products/platform/journeys/README.md index a4f7b26956..f2e5bfacfa 100644 --- a/products/platform/journeys/README.md +++ b/products/platform/journeys/README.md @@ -44,7 +44,7 @@ identity provider. | `rstack-dev.sh` | The `rstack dev` journey, with a recipe per product for the steps from `start` on. | | `own-provider.sh` | The own-provider journey: a stock Keycloak (`--issuer keycloak`) or pinned ThunderID (`--issuer thunderid`) plus a stock PostgreSQL started on loopback, then each product from its starter to authenticated calls and hooks. | | `lib-assists.sh` | The assists, sourced only when `--assist` names one: `sql` (provisioning statements through psql), `certificate` (a private CA and a TLS server certificate for the pg container), `token-type` (Keycloak's at+jwt header setting) and `mapper` (a hardcoded actor-kind claim mapper). The only journey file allowed to call psql, openssl or docker exec. Each use counts as a pass-rule violation. | -| `promote.sh` | The promote journey: `promote.sh --from RUN_DIR --bin-dir DIR`, paired with a kept Keycloak `own-provider.sh` run directory (`run.json` journey `own-provider` and `own-provider.json` issuer `keycloak`). Mismatched provider run directories (such as `--issuer thunderid`) are refused explicitly. It tries the files in place with no development declaration, compares startup and check diagnostics, and applies each remedy. Casework, Messaging, Scheduling, Documents, Coordinator, and Render inputs that start successfully and pass the production check with zero diagnostics continue to a fresh production process and repeat the authenticated call. A product whose development cell did not finish stops at `input`. | +| `promote.sh` | The promote journey: `promote.sh --from RUN_DIR --bin-dir DIR`, paired with a kept Keycloak `own-provider.sh` run directory (`run.json` journey `own-provider` and `own-provider.json` issuer `keycloak`). Mismatched provider run directories (such as `--issuer thunderid`) are refused explicitly. It tries the files in place with no development declaration, compares startup and check diagnostics, and applies each remedy. Adapter, Casework, Messaging, Scheduling, Documents, Coordinator, and Render inputs that start successfully and pass the production check with zero diagnostics continue to a fresh production process and repeat the authenticated call. A product whose development cell did not finish stops at `input`. | | `keycloak/realm.json` | The realm the Keycloak own-provider journey imports: per product, one caller client with a service account and one API client for the product's audience. Documents also has a service-account client that exercises the human staff profile's refusal. The realm holds no protocol mappers. | | `projects/` | The runtime files and pure-data fixture helpers the own-provider journey uses (Render, Coordinator, loopback hook and source receivers, and the composed BReg + Casework + Scheduling fixture writer). | @@ -108,6 +108,21 @@ and grant exchange, commit a hold and an appointment, and verify a signed appointment hook correlated to that appointment. A skipped hook cannot satisfy the ThunderID cell. +## Adapter promotion + +The Adapter facade uses loopback PostgreSQL and a disposable Basic Auth source. +The harness keeps file-backed references in the development run for promotion. +`adapterctl provision` creates the database and roles. The runtime applies its +schema at startup, and `/ready` checks it. The standalone `database.connect` +step and the hook step are marked `unexercised`. The authenticated +`POST /v1/records/person` proves a write and leaves the first authenticated +read measurement empty. + +The development run stops the source after saving the HTTP 201 response. The +production run presents the same request and idempotency key with the source +stopped. It checks HTTP 201 and matches the response body against the saved +development response. + ## Reading the ratchet table A cell fails at its first failing step with one code. The code has one of these @@ -147,7 +162,10 @@ zero is compared against the minimum. Threshold outcomes are report-only in CI. The functional ratchet controls journey acceptance, and comparison code errors fail the harness. Promote -uses its functional ratchet. +uses its functional ratchet. Its `productionRefusals` field counts distinct +codes matched by the initial production startup and check. It is `null` until +the comparison was measured, and `0` when the comparison found no refusals. +The existing `total.refusalsMet` counts refusals across the cell. In `rstack-dev`, the run log and `cells.tsv` mark the hook step `unexercised` when the journey has no hook delivery to check. The cell still runs its later diff --git a/products/platform/journeys/expected-failures.yaml b/products/platform/journeys/expected-failures.yaml index 106d4336a9..86960f7d46 100644 --- a/products/platform/journeys/expected-failures.yaml +++ b/products/platform/journeys/expected-failures.yaml @@ -59,14 +59,6 @@ expectedFailures: basis: observed observedOn: "journey run 20261128141250-8151" reason: "prepare, issuer, and database.provision pass (bregctl provision accepts loopback-plaintext on the reader's plain PostgreSQL server). database.connect runs bregctl test to produce the receipt bregctl package requires, and bregctl test refuses because the package.root directory in runtime.yaml does not exist yet before bregctl package creates it." - - journey: own-provider - product: adapter - step: database.provision - code: product.config.refused - removedBy: rstack-dev-products - basis: observed - observedOn: "PR #2798, journey run 20261128120405-7e2e" - reason: "prepare and issuer pass (adapterctl check of the facade-recovery example with the breg-records profile). adapterctl provision (added in PR #2798) resolves database.migrationUrlRef from the runtime file's secret provider; runtime.example.yaml references secret:env/ADAPTER_DB_MIGRATION while own-provider writes secret files and leaves that environment variable unset, so provision refuses with config.refused." - journey: own-provider product: evidence step: issuer @@ -92,14 +84,6 @@ expectedFailures: basis: observed observedOn: "origin/main cd83550e, journey run 20261127023442-18b4 against own-provider run 20261127021546-ddef" reason: "The development journey did not finish for this product, so there are no files to promote." - - journey: promote - product: adapter - step: input - code: journey.promote.no-input - removedBy: rstack-dev-products - basis: observed - observedOn: "origin/main cd83550e, journey run 20261127023442-18b4 against own-provider run 20261127021546-ddef" - reason: "The development journey did not finish for this product, so there are no files to promote." - journey: promote product: discovery step: input @@ -245,6 +229,14 @@ unreached: # observedOn: "origin/main cd83550e, promote run 20261127025000-816f on own-provider run 20261127024425-265d (assisted: sql, certificate, token-type, mapper)" # reason: "The assisted Scheduling cell reached T1. Started with no development declaration, schedulingctl check (which has no --production flag) lists no refusal and the server starts and answers /readyz, so zero refusals are listed. No shared posture exists on main, so nothing can refuse. The count becomes meaningful once the posture change lands." passes: + - journey: own-provider + product: adapter + basis: observed + observedOn: "v0.49.0 binaries, own-provider run 20261201143319-b2e1" + - journey: promote + product: adapter + basis: observed + observedOn: "v0.49.0 binaries, promote run 20261201143356-36b6" - journey: promote product: render basis: observed diff --git a/products/platform/journeys/lib.sh b/products/platform/journeys/lib.sh index 60a710b9f0..0cdf66ad8a 100644 --- a/products/platform/journeys/lib.sh +++ b/products/platform/journeys/lib.sh @@ -1552,6 +1552,7 @@ journey_cell_begin() { _jc_idp=0 _jc_certs=0 _jc_refusals=0 + _jc_production_refusals=null _jc_named=null _jc_assist_count=0 _jc_seconds=0.000 @@ -2353,7 +2354,9 @@ journey_blocker() { # journey_count COUNTER [N]: add N (default 1) to a counted quantity the # library cannot see: identity-provider-changes, certificates, -# documentation-words, refusals or errors-that-say-what-to-change. +# documentation-words, refusals or errors-that-say-what-to-change. The +# production-refusals counter records the initial comparison once and adds +# its measured count to the total refusals. journey_count() { local counter=${1:-} amount=${2:-1} journey__require_cell @@ -2363,6 +2366,12 @@ journey_count() { certificates) _jc_certs=$((_jc_certs + amount)) ;; documentation-words) _jc_doc_words=$((_jc_doc_words + amount)) ;; refusals) _jc_refusals=$((_jc_refusals + amount)) ;; + production-refusals) + [[ "$JOURNEY_NAME" == promote && "$_jc_production_refusals" == null ]] || + journey__script_error "production refusals are recorded once per promote cell" + _jc_production_refusals=$amount + _jc_refusals=$((_jc_refusals + amount)) + ;; errors-that-say-what-to-change) [[ "$_jc_named" != null ]] || _jc_named=0 _jc_named=$((_jc_named + amount)) @@ -2439,6 +2448,7 @@ journey_cell_end() { --arg product "$_jc_product" --arg outcome "$outcome" \ --arg step "${_jc_fail_step:-$_jc_unreached}" --arg code "$_jc_fail_code" --arg reason "$_jc_reason" \ --argjson blockers "$_jc_blockers_json" --argjson t1 "$_jc_t1_json" --argjson t2 "$_jc_t2_json" \ + --arg journey "$JOURNEY_NAME" --argjson productionRefusals "$_jc_production_refusals" \ --argjson total "$total" \ 'def opt: if . == "" then null else . end; { @@ -2455,7 +2465,8 @@ journey_cell_end() { "machine-time-to-t1": (if $t1 == null then null else ($t1.machineSeconds / 60) end), "errors-that-say-what-to-change": $total.errorsThatSayWhatToChange } - }' >"$JOURNEY_OUT/$_jc_product/cell.json" || journey_harness_failure "cannot write the cell of $_jc_product" + } + (if $journey == "promote" then {$productionRefusals} else {} end)' \ + >"$JOURNEY_OUT/$_jc_product/cell.json" || journey_harness_failure "cannot write the cell of $_jc_product" if journey__first_hour_column "$JOURNEY_NAME" >/dev/null; then public="$JOURNEY_OUT/public-cell-receipts/$_jc_product" receipt="$(journey__first_hour_receipt "$JOURNEY_NAME" "$JOURNEY_OUT/$_jc_product/cell.json")" || diff --git a/products/platform/journeys/own-provider.sh b/products/platform/journeys/own-provider.sh index 73d24db5bf..be38fb4ba0 100755 --- a/products/platform/journeys/own-provider.sh +++ b/products/platform/journeys/own-provider.sh @@ -885,12 +885,12 @@ recipe() { CALL_PATH=/v1/workflows/coordinator ;; adapter) + TOOL=adapterctl CLIENT=registry-adapter-example-client + CALL_METHOD=POST CALL_PATH=/v1/records/person if [[ "$ISSUER_KIND" == thunderid ]]; then - TOOL=adapterctl CLIENT=registry-adapter-example-client AUDIENCE=urn:example:adapter SCOPE=records:write - CALL_METHOD=POST CALL_PATH=/v1/records/person + AUDIENCE=urn:example:adapter SCOPE=records:write else - TOOL=adapterctl CLIENT=registry-adapter-example-client AUDIENCE=registry-adapter-example SCOPE=records.write - CALL_PATH=/v1/records/person + AUDIENCE=registry-adapter-example SCOPE=records.write fi ;; evidence) @@ -1121,12 +1121,17 @@ step_prepare() { copy_file "$PROJECT/runtime.example.yaml" "$RUNTIME_FILE" [[ $CELL_OVER -eq 0 ]] || return 0 edit "$RUNTIME_FILE" " bind: 127.0.0.1:8080" " bind: 127.0.0.1:$PORT" listener-bind + free_port ADAPTER_SOURCE_PORT + edit "$RUNTIME_FILE" " baseUrl: https://reference.example.invalid" " baseUrl: http://127.0.0.1:$ADAPTER_SOURCE_PORT" if [[ "$ISSUER_KIND" == thunderid ]]; then - free_port ADAPTER_SOURCE_PORT edit "$PROJECT/project.yaml" " scopes: [records.write]" " scopes: [records:write]" scopes - edit "$RUNTIME_FILE" " baseUrl: https://reference.example.invalid" " baseUrl: http://127.0.0.1:$ADAPTER_SOURCE_PORT" edit "$RUNTIME_FILE" " audience: registry-adapter-example" " audience: $AUDIENCE" audience fi + harness_edit "$RUNTIME_FILE" $'\nendpoints:\n' $'\nsecretProviders:\n file:\n root: '"$SECRETS"$'\nendpoints:\n' + harness_edit "$RUNTIME_FILE" secret:env/REFERENCE_USERNAME secret:file/reference-username + harness_edit "$RUNTIME_FILE" secret:env/REFERENCE_PASSWORD secret:file/reference-password + harness_edit "$RUNTIME_FILE" secret:env/ADAPTER_DB_RUNTIME secret:file/runtime-database-url + harness_edit "$RUNTIME_FILE" secret:env/ADAPTER_DB_MIGRATION secret:file/migration-database-url ;; evidence) PRODUCT_KEY_DIRS+=("$PROJECT/.generated/secrets") @@ -1396,10 +1401,6 @@ write_product_secrets() { fi journey_secret_new "$name" "$bytes" done < <(secret_references "$RUNTIME_FILE") - if [[ "$ISSUER_KIND" == thunderid && "$product" == adapter ]]; then - journey_secret_new adapter-reference-username 16 - journey_secret_new adapter-reference-password 24 - fi } # breg_schema_test_credentials: acquire real client tokens for BReg's schema @@ -1529,21 +1530,6 @@ step_database() { journey_pass database.connect return 0 fi - if [[ "$ISSUER_KIND" == thunderid && "$product" == adapter ]]; then - local mig_url run_url ref_user ref_pass - mig_url=$(<"$MIGRATION_URL_FILE") - run_url=$(<"$RUNTIME_URL_FILE") - read_secret adapter-reference-username ref_user - read_secret adapter-reference-password ref_pass - ADAPTER_DB_MIGRATION="$mig_url" ADAPTER_DB_RUNTIME="$run_url" \ - REFERENCE_USERNAME="$ref_user" REFERENCE_PASSWORD="$ref_pass" \ - database_step database.provision "$TOOL provision --runtime-config $RUNTIME_FILE --admin-url-file $ADMIN_URL_FILE" -- \ - "$TOOL_BIN" provision --runtime-config "$RUNTIME_FILE" --admin-url-file "$ADMIN_URL_FILE" - [[ $CELL_OVER -eq 0 ]] || return 0 - # Adapter applies its journal and idempotency schema at startup; it has no apply command. - journey_pass database.connect - return 0 - fi database_step database.provision "$TOOL provision --runtime-config $RUNTIME_FILE --admin-url-file $ADMIN_URL_FILE" -- \ "$TOOL_BIN" provision --runtime-config "$RUNTIME_FILE" --admin-url-file "$ADMIN_URL_FILE" [[ $CELL_OVER -eq 0 ]] || return 0 @@ -1610,7 +1596,8 @@ step_database() { "$TOOL_BIN" --format json apply --initial --runtime-config "$RUNTIME_FILE" --package "$build/package" ;; adapter) - journey_harness_failure "no database.connect recipe is written for adapter: it has no apply command, and its runtime reads the database URLs from secret:env references; extend step_database in own-provider.sh" + # Adapter applies its journal and idempotency schema at startup. + journey_unexercised database.connect ;; esac } @@ -1623,14 +1610,10 @@ serve_command() { casework | messaging | scheduling | documents) SERVE_COMMAND=("$SERVER_BIN" --runtime-config "$RUNTIME_FILE" serve) ;; render) SERVE_COMMAND=("$SERVER_BIN" serve --runtime-config "$RUNTIME_FILE") ;; adapter) - if [[ "$ISSUER_KIND" == thunderid ]]; then - SERVE_COMMAND=("$SERVER_BIN" serve --runtime-config "$RUNTIME_FILE" - --project "$PROJECT" - --profile "$JOURNEY_ROOT/products/adapter/profiles/breg-records/profile.yaml" - --pack "$PROJECT/pack.yaml") - else - journey_harness_failure "no start recipe is written for $product; add one to serve_command in own-provider.sh" - fi + SERVE_COMMAND=("$SERVER_BIN" serve --runtime-config "$RUNTIME_FILE" + --project "$PROJECT" + --profile "$JOURNEY_ROOT/products/adapter/profiles/breg-records/profile.yaml" + --pack "$PROJECT/pack.yaml") ;; evidence) if [[ "$ISSUER_KIND" == thunderid ]]; then @@ -1703,24 +1686,15 @@ step_start() { local product=$1 status=0 ready_url serve_command "$product" port_is_free "$PORT" || journey_harness_failure "port $PORT is in use; the journey cannot start $product on it" - if [[ "$ISSUER_KIND" == thunderid && "$product" == adapter ]]; then - local mig_url run_url ref_user ref_pass - mig_url=$(<"$MIGRATION_URL_FILE") - run_url=$(<"$RUNTIME_URL_FILE") - read_secret adapter-reference-username ref_user - read_secret adapter-reference-password ref_pass + if [[ "$product" == adapter ]]; then journey_start start adapter-source -- python3 "$PROJECTS_DIR/adapter-source.py" \ "$ADAPTER_SOURCE_PORT" "$SECRETS/adapter-reference-username" "$SECRETS/adapter-reference-password" || journey_harness_failure "the Adapter loopback source failed to start" journey_ready start adapter-source --timeout 30 -- \ curl --silent --show-error --fail --output /dev/null "http://127.0.0.1:$ADAPTER_SOURCE_PORT/ready" || journey_harness_failure "the Adapter loopback source did not answer /ready" - ADAPTER_DB_MIGRATION="$mig_url" ADAPTER_DB_RUNTIME="$run_url" \ - REFERENCE_USERNAME="$ref_user" REFERENCE_PASSWORD="$ref_pass" \ - journey_start start server --settle 3 -- "${SERVE_COMMAND[@]}" || status=$? - else - journey_start start server --settle 3 -- "${SERVE_COMMAND[@]}" || status=$? fi + journey_start start server --settle 3 -- "${SERVE_COMMAND[@]}" || status=$? SERVER_LOG_OUT=$JOURNEY_STEP_STDOUT SERVER_LOG_ERR=$JOURNEY_STEP_STDERR if [[ $status -ne 0 ]]; then @@ -1868,11 +1842,9 @@ call_request() { options+=(--header 'Content-Type: application/json' --data-file "$WORK/request.json") ;; adapter) - if [[ "$ISSUER_KIND" == thunderid ]]; then - options+=(--header 'Content-Type: application/json' - --header 'Idempotency-Key: journey-adapter-first-call' - --data-file "$WORK/adapter-call-body.json") - fi + options+=(--header 'Content-Type: application/json' + --header 'Idempotency-Key: journey-adapter-first-call' + --data-file "$WORK/adapter-call-body.json") ;; esac local status=0 @@ -1881,8 +1853,13 @@ call_request() { if [[ "$CELL" == scheduling && "$CALL_METHOD" == GET && "$CALL_PATH" == /v1/locations && "$JOURNEY_HTTP_STATUS" == 200 ]]; then scheduling_catalogue_ok=1 fi - if [[ "$ISSUER_KIND" == thunderid && "$CELL" == adapter && "$JOURNEY_HTTP_STATUS" != 201 ]]; then - journey_harness_failure "Adapter POST /v1/records/person returned HTTP $JOURNEY_HTTP_STATUS instead of 201" + if [[ "$CELL" == adapter ]]; then + [[ "$JOURNEY_HTTP_STATUS" == 201 ]] || + journey_harness_failure "Adapter POST /v1/records/person returned HTTP $JOURNEY_HTTP_STATUS instead of 201" + jq -e '.data == {name: "Example Person"} and .meta.recordTypeId == "person"' "$JOURNEY_STEP_STDOUT" >/dev/null || + journey_harness_failure "Adapter did not return the source fixture's person record" + cp -- "$JOURNEY_STEP_STDOUT" "$WORK/call.response" || + journey_harness_failure "cannot preserve the Adapter response for promotion" fi journey_request_contract "$CALL_METHOD" "$CALL_PATH" "${options[@]+"${options[@]}"}" >"$WORK/call.contract" journey_claim_names ACCESS_TOKEN >"$WORK/call.claims" @@ -1968,10 +1945,8 @@ step_call() { journey_harness_failure "cannot build the Render request body; see $JOURNEY_STEP_STDERR" ;; adapter) - if [[ "$ISSUER_KIND" == thunderid ]]; then - journey_write_file "$WORK/adapter-call-body.json" < <(printf '%s\n' \ - '{"data":{"recordId":"person-1","domainData":{"name":"Example Person"}}}') - fi + journey_write_file "$WORK/adapter-call-body.json" < <(printf '%s\n' \ + '{"data":{"recordId":"person-1","domainData":{"name":"Example Person"}}}') ;; esac call_request || status=$? @@ -1982,7 +1957,8 @@ step_call() { fi check_wrong_kind journey_pass call - journey_reached t1 + # Adapter's authenticated create is a write. It supplies no T1 read measurement. + [[ "$CELL" == adapter ]] || journey_reached t1 return 0 fi [[ "$JOURNEY_HTTP_STATUS" != 000 ]] || @@ -2021,7 +1997,7 @@ step_call() { status=0 call_request || status=$? if [[ $status -eq 0 ]]; then - journey_reached t1 + [[ "$CELL" == adapter ]] || journey_reached t1 return 0 fi # The refusal of this call is logged after the response is written, and @@ -2759,12 +2735,13 @@ step_hook() { documents_hook journey_pass hook ;; + adapter) journey_unexercised hook ;; *) journey_pass hook ;; esac } step_stop() { - if [[ "$ISSUER_KIND" == thunderid && "$CELL" == adapter ]] && journey_process_running adapter-source; then + if [[ "$CELL" == adapter ]] && journey_process_running adapter-source; then journey_stop stop adapter-source || journey_harness_failure "the Adapter loopback source ignored SIGTERM" fi if journey_stop stop server; then diff --git a/products/platform/journeys/promote.sh b/products/platform/journeys/promote.sh index 2322b6cabd..411e98aac1 100755 --- a/products/platform/journeys/promote.sh +++ b/products/platform/journeys/promote.sh @@ -21,8 +21,8 @@ # production check and the list from the start. The two # lists must be equal, or the run stops as a harness # failure. The explicit production-compatible cases can continue -# with zero diagnostics. The count goes to refusalsMet -# in summary.json. +# with zero diagnostics. The number of distinct matched +# codes goes to productionRefusals in summary.json. # fix each refusal is fixed by the function fix_. A # code with no function is a harness failure that names # it, so a new refusal is looked at and never recorded @@ -36,7 +36,8 @@ # http... # same-contract the request line, the headers other than the token # and the token's claim names equal the original authenticated -# call's recorded contract and claim names. +# call's recorded contract and claim names. Adapter also +# replays the original HTTP 201 response with the source stopped. # # The input. --from RUN_DIR is a run directory of own-provider.sh that ended # with --keep, under the same JOURNEY_CONTAINER_PREFIX. Without --from this run @@ -211,6 +212,12 @@ recipe() { case "$product" in breg | coordinator) SERVE_COMMAND=("$SERVER_BIN" --runtime-config "$RUNTIME_FILE") ;; casework | messaging | scheduling | documents) SERVE_COMMAND=("$SERVER_BIN" --runtime-config "$RUNTIME_FILE" serve) ;; + adapter) + SERVE_COMMAND=("$SERVER_BIN" serve --runtime-config "$RUNTIME_FILE" + --project "$PROJECT" + --profile "$JOURNEY_ROOT/products/adapter/profiles/breg-records/profile.yaml" + --pack "$PROJECT/pack.yaml") + ;; render) SERVE_COMMAND=("$SERVER_BIN" serve --runtime-config "$RUNTIME_FILE") ;; *) journey_harness_failure "no start recipe is written for $product; add one to recipe in promote.sh" ;; esac @@ -319,7 +326,7 @@ production_outcome() { printf '%s\n' remediate elif [[ "$state" == started && "$status" == 0 && -z "$codes" ]]; then case "$product" in - casework | messaging | scheduling | documents | coordinator | render) printf '%s\n' compatible ;; + casework | messaging | scheduling | documents | coordinator | render | adapter) printf '%s\n' compatible ;; *) printf '%s\n' missing-refusal ;; esac else @@ -379,6 +386,16 @@ call_recipe() { CLIENT="coordinator-producer" CALL_PATH=/v1/workflows/coordinator ;; + adapter) + CLIENT=registry-adapter-example-client + CALL_METHOD=POST + CALL_PATH=/v1/records/person + [[ -f "$FROM/work/adapter/adapter-call-body.json" ]] || + journey_harness_failure "the Adapter input holds no request body" + CALL_OPTIONS=(--header 'Content-Type: application/json' + --header 'Idempotency-Key: journey-adapter-first-call' + --data-file "$FROM/work/adapter/adapter-call-body.json") + ;; render) CLIENT="portal" CALL_METHOD=POST @@ -463,7 +480,7 @@ promote_call_failure() { } walk_product() { - local product=$1 tier outcome count code dev_claims dev_contract check_status production_case + local product=$1 tier outcome count=0 code dev_claims dev_contract check_status production_case journey_product_field "$product" tier tier CELL=$product journey_cell_begin "$product" @@ -515,20 +532,17 @@ walk_product() { invalid) journey_harness_failure "the production check of $product returned status $check_status for diagnostic codes [$CHECK_CODES]; see $JOURNEY_STEP_STDERR" ;; - missing-refusal) - journey_fail refusals journey.promote.nothing-refused - journey_cell_end - return 0 - ;; - compatible) - count=0 - printf 'promote: %s passed the production check with zero diagnostics; no remediation required\n' "$product" - ;; remediate) count=$(printf '%s\n' "$CHECK_CODES" | wc -l | tr -d ' ') ;; esac - journey_count refusals "$count" + journey_count production-refusals "$count" + printf 'promote: %s measured %s production refusal(s)\n' "$product" "$count" + if [[ "$production_case" == missing-refusal ]]; then + journey_fail refusals journey.promote.nothing-refused + journey_cell_end + return 0 + fi journey_pass refusals # fix: first the contract as the development files give it (the claim names @@ -545,6 +559,9 @@ walk_product() { elif [[ "$production_case" == compatible ]]; then journey_harness_failure "the production-compatible case for $product requires the original development request and claim names; rerun own-provider" fi + if [[ "$product" == adapter && ! -s "$recorded/call.response" ]]; then + journey_harness_failure "Adapter promotion requires the recorded development response; rerun own-provider" + fi if [[ "$production_case" == remediate ]]; then while IFS= read -r code; do apply_fix "$code" @@ -586,6 +603,12 @@ walk_product() { journey_harness_failure "the token claims of $product differ between the development files and the production start" fi [[ "$(journey_request_contract "$CALL_METHOD" "$CALL_PATH" "${CALL_OPTIONS[@]+"${CALL_OPTIONS[@]}"}")" == "$dev_contract" ]] || journey_harness_failure "the request of $product changed between the development files and the production start" + if [[ "$product" == adapter ]]; then + [[ "$JOURNEY_HTTP_STATUS" == 201 ]] || + journey_harness_failure "the promoted Adapter returned HTTP $JOURNEY_HTTP_STATUS instead of 201" + cmp -s -- "$recorded/call.response" "$JOURNEY_STEP_STDOUT" || + journey_harness_failure "the promoted Adapter response differs from the development response" + fi journey_stop same-contract server || journey_harness_failure "the server of $product ignored SIGTERM" journey_pass same-contract journey_cell_end diff --git a/products/platform/journeys/test_journey_tables.py b/products/platform/journeys/test_journey_tables.py index 7650fe2895..ded29c2924 100644 --- a/products/platform/journeys/test_journey_tables.py +++ b/products/platform/journeys/test_journey_tables.py @@ -508,6 +508,9 @@ def test_zero_diagnostics_requires_a_successful_check_and_an_explicit_case(self) ("scheduling", "started", 0, "", "compatible"), ("coordinator", "started", 0, "", "compatible"), ("render", "started", 0, "", "compatible"), + ("adapter", "started", 0, "", "compatible"), + ("adapter", "refused", 1, "config.refused", "remediate"), + ("adapter", "started", 1, "", "invalid"), ("render", "refused", 1, "render.config.refused", "remediate"), ("breg", "started", 0, "", "missing-refusal"), ("messaging", "started", 1, "", "invalid"), diff --git a/products/platform/journeys/test_lib.sh b/products/platform/journeys/test_lib.sh index baf1988438..fc94e323fa 100644 --- a/products/platform/journeys/test_lib.sh +++ b/products/platform/journeys/test_lib.sh @@ -806,6 +806,9 @@ driver_replay() { esac break fi + if [[ "$step" == refusals && -n "${REPLAY_PRODUCTION_REFUSALS:-}" ]]; then + journey_count production-refusals "$REPLAY_PRODUCTION_REFUSALS" + fi journey_pass "$step" done <<<"$steps" if [[ "$kind" == pass && ${REPLAY_COUNTERS:-0} != 0 ]]; then @@ -2037,6 +2040,19 @@ case_real_tables() { check_equal "every product has a cell" "$(value replayed)" "$(json '.cells | length' "$out/summary.json")" check_equal "every cell equals its row" 0 "$(json '[.cells[] | select(.verdict != "ok")] | length' "$out/summary.json")" + begin_case production-refusal-count + local count + for count in 0 2; do + drive 0 TEST_JOURNEY=promote SCENARIO=replay REPLAY_PRODUCTION_REFUSALS="$count" JOURNEY_TABLES_DIR= -- \ + --product render --product breg --expected "$lib_dir/expected-failures.yaml" --strict + check_equal "the blocked cell explicitly records an unmeasured comparison" true \ + "$(json '.cells[] | select(.product == "breg") | has("productionRefusals") and .productionRefusals == null' "$out/summary.json")" + check_equal "the completed comparison records its measured count" "$count" \ + "$(json '.cells[] | select(.product == "render") | .productionRefusals' "$out/summary.json")" + check_equal "the production refusals are also included in the aggregate" "$count" \ + "$(json '.cells[] | select(.product == "render") | .total.refusalsMet' "$out/summary.json")" + done + begin_case real-table-missing-first-hour-measurements drive 0 TEST_JOURNEY=rstack-dev SCENARIO=replay JOURNEY_TABLES_DIR= -- --expected "$lib_dir/expected-failures.yaml" --strict check_equal "every functional cell equals its row" 0 "$(json '[.cells[] | select(.verdict != "ok")] | length' "$out/summary.json")" From 26d7e2c77dabacdb7907ee5f7099a5126004ab34 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 15:57:32 +0000 Subject: [PATCH 008/183] fix(journeys): report verified first-hour endpoints Signed-off-by: Jeremi Joslin --- products/platform/journeys/README.md | 6 ++++++ products/platform/journeys/own-provider.sh | 5 ++--- products/platform/journeys/rstack-dev.sh | 15 +++++++++++++-- 3 files changed, 21 insertions(+), 5 deletions(-) diff --git a/products/platform/journeys/README.md b/products/platform/journeys/README.md index f2e5bfacfa..83d416787a 100644 --- a/products/platform/journeys/README.md +++ b/products/platform/journeys/README.md @@ -160,6 +160,12 @@ lists the outcome, verdict, and each counter's value, threshold, direction, and status. An unrecorded planted-error measurement is missing. A recorded zero is compared against the minimum. +T1 is captured at the first successful authenticated read. If the local +journey's first operation is a write, its authenticated readback can provide +T1. T2 is captured after the runner has verified the write across a restart +and checked delivery for paths that exercise a hook. The current local T2 +receipts cover BReg, Coordinator, and Messaging. + Threshold outcomes are report-only in CI. The functional ratchet controls journey acceptance, and comparison code errors fail the harness. Promote uses its functional ratchet. Its `productionRefusals` field counts distinct diff --git a/products/platform/journeys/own-provider.sh b/products/platform/journeys/own-provider.sh index be38fb4ba0..b0ce7dd8e5 100755 --- a/products/platform/journeys/own-provider.sh +++ b/products/platform/journeys/own-provider.sh @@ -1957,8 +1957,7 @@ step_call() { fi check_wrong_kind journey_pass call - # Adapter's authenticated create is a write. It supplies no T1 read measurement. - [[ "$CELL" == adapter ]] || journey_reached t1 + [[ "$CALL_METHOD" != GET ]] || journey_reached t1 return 0 fi [[ "$JOURNEY_HTTP_STATUS" != 000 ]] || @@ -1997,7 +1996,7 @@ step_call() { status=0 call_request || status=$? if [[ $status -eq 0 ]]; then - [[ "$CELL" == adapter ]] || journey_reached t1 + [[ "$CALL_METHOD" != GET ]] || journey_reached t1 return 0 fi # The refusal of this call is logged after the response is written, and diff --git a/products/platform/journeys/rstack-dev.sh b/products/platform/journeys/rstack-dev.sh index 14ecab1c43..1b23c5e3d2 100755 --- a/products/platform/journeys/rstack-dev.sh +++ b/products/platform/journeys/rstack-dev.sh @@ -479,6 +479,7 @@ unexpected_answer() { walk_product() { # shellcheck disable=SC2034 # token and token2 are set by name through issue_token local product=$1 work project tier plan_capable status=0 url message_id='' token='' token2='' workflow_revision='' uses_postgres + local first_read=0 journey_product_field "$product" tier tier journey_product_field "$product" rstackDevPlan plan_capable journey_product_field "$product" usesPostgres uses_postgres @@ -596,7 +597,10 @@ walk_product() { unexpected_answer call fi journey_pass call - journey_reached t1 + if [[ "$CALL_METHOD" == GET && -n "$PERSON" ]]; then + journey_reached t1 + first_read=1 + fi # hook: BReg's keep write also triggers its local sink. if [[ "$product" == breg ]]; then @@ -663,10 +667,17 @@ walk_product() { fi jq -e --arg expected "$KEEP_EXPECT" '[.. | strings] | index($expected) != null' "$JOURNEY_STEP_STDOUT" >/dev/null || journey_harness_failure "the retained $product response did not contain the written record" - journey_reached t2 + if [[ "$method" == GET && $first_read -eq 0 ]]; then + journey_reached t1 + fi if [[ -n "$audit" ]]; then journey_step keep -- audit_was_appended "$work/audit-before-restart.jsonl" "$audit" fi + # These paths have written and read back a record across a restart. + # BReg also delivered its observer hook before the restart. + case "$product" in + breg | coordinator | messaging) journey_reached t2 ;; + esac else printf '%s\n' "$product has no PostgreSQL state to retain." fi From 102c0e45e4d80551053ef5888adfb88d7526a8ec Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 16:00:57 +0000 Subject: [PATCH 009/183] test(journeys): gate hook reporting through the real local walk Signed-off-by: Jeremi Joslin --- .../platform/journeys/test_journey_tables.py | 130 ++++++++++++++++++ 1 file changed, 130 insertions(+) diff --git a/products/platform/journeys/test_journey_tables.py b/products/platform/journeys/test_journey_tables.py index ded29c2924..d2609ba479 100644 --- a/products/platform/journeys/test_journey_tables.py +++ b/products/platform/journeys/test_journey_tables.py @@ -834,6 +834,136 @@ def test_promote_refuses_thunderid_run_directory(self): self.assertIn("keycloak", result.stderr) +class LocalHookWalk(unittest.TestCase): + def walk(self, product, delivered): + script = (TABLES / "rstack-dev.sh").read_text(encoding="utf-8") + functions = [] + for name in ("walk_product", "recipe", "hook_received"): + match = re.search(rf"^{name}\(\) \{{\n.*?^\}}\n", script, re.M | re.S) + self.assertIsNotNone(match, name) + functions.append(match.group(0)) + driver = r""" +source "$1/lib.sh" +scratch=$2 product=$3 delivered=$4 +trace=$scratch/trace +LIVE_RUNS='' +printf '{"authentication":{"oidc":{"issuers":{"fixture":{}}}},"audit":{"path":"%s/audit.jsonl"}}\n' \ + "$scratch" >"$scratch/runtime.json" +: >"$scratch/audit.jsonl" +: >"$scratch/audit.schedulingctl.jsonl" +init_command() { INIT_COMMAND=(true); } +add_contact_hook() { :; } +start_run() { + local result=passed + [[ "$1" != keep ]] || result=skipped + RUN=$1-run + START_FILE=$scratch/$1.json + jq -n --arg product "$CELL" --arg runtime "$scratch/runtime.json" --arg result "$result" ' + {runtimeConfigs: {($product): $runtime}, scenarios: [{id: "starter", result: $result}], + bregHookSink: {receivedUrl: "http://127.0.0.1:49191/received"}}' >"$START_FILE" + LIVE_RUNS+="$RUN"$'\n' +} +run_url() { printf '%s\n' 'http://127.0.0.1:49192'; } +issue_token() { :; } +write_keep() { + KEEP_PERSON=$PERSON + KEEP_PATH=/retained + KEEP_EXPECT=retained-id + printf 'write %s\n' "$1" >>"$trace" +} +sink_response() { + if [[ "$delivered" == yes ]]; then + jq -nc '[{body: ({type: "contact-created", data: { + recordId: "retained-id", values: {name: "A retained contact"}}} | tojson)}]' + else + printf '%s\n' '[]' + fi +} +curl() { + [[ "${!#}" == http://127.0.0.1:49191/received ]] + printf '%s\n' 'poll sink' >>"$trace" + sink_response +} +journey_poll() { + # One deterministic poll attempt runs the real predicate and models a timeout on failure. + shift 2 + "$@" +} +journey_http() { + JOURNEY_STEP_STDOUT=$scratch/response.json + case "$1" in + call) printf '%s\n' '{}' >"$JOURNEY_STEP_STDOUT" ;; + hook) + [[ "${!#}" == http://127.0.0.1:49191/received ]] + printf '%s\n' 'read sink' >>"$trace" + sink_response >"$JOURNEY_STEP_STDOUT" + ;; + keep) + printf '%s\n' 'read retained record' >>"$trace" + printf '%s\n' '{"recordId":"retained-id"}' >"$JOURNEY_STEP_STDOUT" + ;; + *) return 1 ;; + esac +} +rstack_dev() { :; } +state_is_empty() { :; } +edit_for_restart() { :; } +audit_was_appended() { :; } +attach_database() { journey_pass attach; } +run_containers() { printf '%s\n' 'fake-container'; } +journey_check_absent() { :; } + +journey_init rstack-dev -- --product "$product" --out "$scratch/run" +if [[ "$delivered" == terminal-step ]]; then + journey_cell_begin "$product" + journey_unexercised stop +else + walk_product "$product" +fi +journey_finish +""" + with tempfile.TemporaryDirectory() as directory: + scratch = Path(directory) + result = subprocess.run( + ["bash", "-euo", "pipefail", "-c", "\n".join(functions) + driver, + "local-hook-walk", str(TABLES), directory, product, delivered], + env={**os.environ, "JOURNEY_TABLES_DIR": str(TABLES)}, + capture_output=True, text=True, timeout=15, + ) + cells = (scratch / "run" / "cells.tsv").read_text(encoding="utf-8") + outcomes = [tuple(row.split("\t")[1:3]) for row in cells.splitlines()[1:]] + trace_file = scratch / "trace" + trace = trace_file.read_text(encoding="utf-8").splitlines() if trace_file.exists() else [] + return result, outcomes, trace + + def test_scheduling_reports_unexercised_and_keeps_walking(self): + result, outcomes, trace = self.walk("scheduling", "no") + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertEqual([row for row in outcomes if row[0] == "hook"], [("hook", "unexercised")]) + self.assertIn("scheduling hook: unexercised", result.stderr) + self.assertEqual(outcomes[-3:], [("keep", "pass"), ("attach", "pass"), ("stop", "pass")]) + self.assertEqual(trace, ["write scheduling", "read retained record"]) + + def test_breg_passes_hook_after_payload_arrives(self): + result, outcomes, trace = self.walk("breg", "yes") + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertEqual([row for row in outcomes if row[0] == "hook"], [("hook", "pass")]) + self.assertEqual(outcomes[-3:], [("keep", "pass"), ("attach", "pass"), ("stop", "pass")]) + self.assertEqual(trace, ["write breg", "poll sink", "read sink", "read retained record"]) + + def test_breg_does_not_pass_hook_without_payload(self): + result, outcomes, trace = self.walk("breg", "no") + self.assertEqual(result.returncode, 3, result.stdout + result.stderr) + self.assertFalse(any(step in {"hook", "keep", "stop"} for step, _ in outcomes)) + self.assertEqual(trace, ["write breg", "poll sink"]) + + def test_final_step_cannot_be_unexercised(self): + result, outcomes, _ = self.walk("scheduling", "terminal-step") + self.assertEqual(result.returncode, 3, result.stdout + result.stderr) + self.assertIn("the final step of scheduling cannot be marked unexercised", result.stderr) + self.assertEqual(outcomes, []) + + class HookReceiverAndAdapterSource(unittest.TestCase): def test_hook_receiver_signature_verification(self): spec = importlib.util.spec_from_file_location( From a74753847407df382f18d7786645a10d5358c788 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 16:06:08 +0000 Subject: [PATCH 010/183] refactor(discovery): select numeric loopback catalog transport Signed-off-by: Jeremi Joslin --- crates/registry-discoveryctl/src/build.rs | 39 ++++++++++++++++------- 1 file changed, 27 insertions(+), 12 deletions(-) diff --git a/crates/registry-discoveryctl/src/build.rs b/crates/registry-discoveryctl/src/build.rs index a0c6320cc5..b528cb7361 100644 --- a/crates/registry-discoveryctl/src/build.rs +++ b/crates/registry-discoveryctl/src/build.rs @@ -14,10 +14,11 @@ use registry_platform_config::{ write_package, DeclaredPosture, PackageError, PackageLimits, Posture, PostureReport, VerifiedPackage, }; +use registry_platform_httputil::select::{select_destination, validate_selected_fetch}; use registry_platform_httputil::{ read_bounded, validate_response_headers, FetchUrlPolicy, PeerPolicy, ResponseHeaderError, }; -use reqwest::header::{ACCEPT, CONTENT_ENCODING, CONTENT_TYPE}; +use reqwest::header::{HeaderValue, ACCEPT, CONTENT_ENCODING, CONTENT_TYPE}; use sha2::{Digest as _, Sha256}; use thiserror::Error; use time::{format_description::well_known::Rfc3339, OffsetDateTime}; @@ -200,17 +201,31 @@ async fn fetch_origins( for approved in project.origins.iter().filter(|origin| origin.enabled) { let url = approved.catalog_url.to_url(); - let validated = policy - .validate_dns_pinned_for_immediate_fetch_with_timeout(&url, dns_timeout) - .await - .map_err(|_| BuildError::Fetch)?; - let response = validated - .immediate_get_with_timeout(fetch_timeout) - .map_err(|_| BuildError::Fetch)? - .header(ACCEPT, registry_discovery_profile::MEDIA_TYPE) - .send() - .await - .map_err(|_| BuildError::Fetch)?; + // Named hosts and HTTPS keep their existing DNS admission policy. + let response = if url.scheme() == "http" + && matches!(url.host_str(), Some("127.0.0.1" | "[::1]")) + { + let selected = select_destination(&url, None, &[]).map_err(|_| BuildError::Fetch)?; + validate_selected_fetch(&selected) + .map_err(|_| BuildError::Fetch)? + .get( + &HeaderValue::from_static(registry_discovery_profile::MEDIA_TYPE), + fetch_timeout, + ) + .await + .map_err(|_| BuildError::Fetch)? + } else { + policy + .validate_dns_pinned_for_immediate_fetch_with_timeout(&url, dns_timeout) + .await + .map_err(|_| BuildError::Fetch)? + .immediate_get_with_timeout(fetch_timeout) + .map_err(|_| BuildError::Fetch)? + .header(ACCEPT, registry_discovery_profile::MEDIA_TYPE) + .send() + .await + .map_err(|_| BuildError::Fetch)? + }; validate_response_headers(response.headers(), peer_policy).map_err( |error| match error { ResponseHeaderError::DevelopmentPeer => BuildError::DevelopmentPeer, From 6a6311f6465223b73ce4d5f3d44f0a36d722e229 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 16:06:08 +0000 Subject: [PATCH 011/183] docs(platform): document integrity checks for public trust files Signed-off-by: Jeremi Joslin --- .../docs/security/hardening-checklist.mdx | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/docs/site/src/content/docs/security/hardening-checklist.mdx b/docs/site/src/content/docs/security/hardening-checklist.mdx index 1463b3ffce..3e8a54adec 100644 --- a/docs/site/src/content/docs/security/hardening-checklist.mdx +++ b/docs/site/src/content/docs/security/hardening-checklist.mdx @@ -133,6 +133,26 @@ refusal holds in development. Production refuses all of them. deploy/helm/registry-stack/templates/evidence-deployment.yaml, stage-evidence-inputs; deploy/helm/registry-stack/README.md, Images and workload security. */} +## Public configuration files + +Protect who can replace public trust material. Replacing an issuer's static JWKS or a CA bundle +changes which keys or certificates your deployment trusts. + +- If an input such as `jwksSource.documentRef` or `database.caBundleRef` references + `secret:file/`, stage it with the same owner, mode and link rules as the other files under + `secretProviders.file.root`. +- If a runtime checks its configuration path with the shared trusted path rule, give it an absolute, + normalised path without symbolic links. In production, root or the runtime user must own the file + and its ancestors. Clear group and other write access. The rule permits a root-owned sticky + ancestor. +- In a container deployment, check the owner and mode as seen by the runtime user. Run the + product's production configuration check, then confirm readiness. To verify a CA or key set, + also exercise an operation that connects to the configured peer or verifies its token. + +{/* Evidence: crates/registry-platform-config/src/blocks.rs, JwksSource, DatabaseConfig; + crates/registry-platform-config/src/loader.rs, require_trusted_runtime_path; + crates/registry-platform-config/src/secrets.rs, SecretResolver, open_secret_file. */} + ## Check BReg and Casework authority 1. Use separate migration and runtime database roles with TLS. Run the product's doctor against From c6d3c5c9dbd9c780f8167a8918795185f4a5f5d3 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 16:03:12 +0000 Subject: [PATCH 012/183] fix(journeys): bind both standalone Casework issuer defaults Signed-off-by: Jeremi Joslin --- products/platform/journeys/own-provider.sh | 13 ++++++-- .../platform/journeys/test_journey_tables.py | 32 +++++++++++++++++++ 2 files changed, 43 insertions(+), 2 deletions(-) diff --git a/products/platform/journeys/own-provider.sh b/products/platform/journeys/own-provider.sh index b0ce7dd8e5..161be1114e 100755 --- a/products/platform/journeys/own-provider.sh +++ b/products/platform/journeys/own-provider.sh @@ -1003,6 +1003,16 @@ unrecognized_subcommand() { # --------------------------------------------------------------------------- # The steps +# Bind the standalone producer to the issuer and subject this run provisions. +bind_casework_producer() { + local path=$1 issuer=$2 subject=$3 starter_issuer=https://identity.casework.example.test + if ! grep -Fxq " issuer: $starter_issuer" "$path"; then + starter_issuer=http://127.0.0.1:8093 + fi + edit "$path" " issuer: $starter_issuer" " issuer: $issuer" issuer-url + edit "$path" " subject: b75315b2-5854-70f3-8867-511dd771a6da" " subject: $subject" +} + # prepare: the product's starter, its package and its runtime file, with the # paths and ports of this machine. step_prepare() { @@ -1031,8 +1041,7 @@ step_prepare() { casework) reader_command prepare --concepts project -- "$TOOL_BIN" init "$PROJECT" [[ $CELL_OVER -eq 0 ]] || return 0 - edit "$PROJECT/casework.yaml" " issuer: http://127.0.0.1:8093" " issuer: $ACTIVE_ISSUER" issuer-url - edit "$PROJECT/casework.yaml" " subject: b75315b2-5854-70f3-8867-511dd771a6da" " subject: $CASEWORK_SUBJECT" + bind_casework_producer "$PROJECT/casework.yaml" "$ACTIVE_ISSUER" "$CASEWORK_SUBJECT" reader_command prepare --concepts package -- "$TOOL_BIN" package --output "$PROJECT/.casework/package" "$PROJECT" [[ $CELL_OVER -eq 0 ]] || return 0 RUNTIME_FILE=$PROJECT/runtime.yaml diff --git a/products/platform/journeys/test_journey_tables.py b/products/platform/journeys/test_journey_tables.py index d2609ba479..5e7da418f8 100644 --- a/products/platform/journeys/test_journey_tables.py +++ b/products/platform/journeys/test_journey_tables.py @@ -834,6 +834,38 @@ def test_promote_refuses_thunderid_run_directory(self): self.assertIn("keycloak", result.stderr) +class CaseworkProducerFixture(unittest.TestCase): + def test_binds_either_standalone_starter_issuer(self): + script = (TABLES / "own-provider.sh").read_text(encoding="utf-8") + functions = [] + for name in ("harness_edit", "bind_casework_producer"): + match = re.search(rf"^{name}\(\) \{{\n.*?^\}}\n", script, re.M | re.S) + self.assertIsNotNone(match, name) + functions.append(match.group(0)) + driver = r""" +journey_harness_failure() { printf '%s\n' "$1" >&2; exit 3; } +edit() { harness_edit "$1" "$2" "$3"; } +bind_casework_producer "$1" http://127.0.0.1:19000/realms/registry fixture-subject +""" + for issuer in ("http://127.0.0.1:8093", "https://identity.casework.example.test"): + with self.subTest(issuer=issuer), tempfile.TemporaryDirectory() as directory: + path = Path(directory) / "casework.yaml" + path.write_text( + "trustedProducers:\n requester:\n profile: requester\n" + f" issuer: {issuer}\n subject: b75315b2-5854-70f3-8867-511dd771a6da\n" + " sourceNamespaces: [standalone]\n", encoding="utf-8", + ) + result = subprocess.run( + ["bash", "-eu", "-c", "\n".join(functions) + driver, "casework-producer", str(path)], + capture_output=True, text=True, timeout=10, + ) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(yaml.safe_load(path.read_text(encoding="utf-8"))["trustedProducers"]["requester"], { + "profile": "requester", "issuer": "http://127.0.0.1:19000/realms/registry", + "subject": "fixture-subject", "sourceNamespaces": ["standalone"], + }) + + class LocalHookWalk(unittest.TestCase): def walk(self, product, delivered): script = (TABLES / "rstack-dev.sh").read_text(encoding="utf-8") From 89239df3ee701fdcae72e19203f0632f6dddcc5d Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 16:05:10 +0000 Subject: [PATCH 013/183] fix(journeys): pair Evidence checks with the selected runtime Signed-off-by: Jeremi Joslin --- products/platform/journeys/own-provider.sh | 4 +++- products/platform/journeys/rstack-dev.sh | 2 ++ 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/products/platform/journeys/own-provider.sh b/products/platform/journeys/own-provider.sh index 161be1114e..5d733cdba4 100755 --- a/products/platform/journeys/own-provider.sh +++ b/products/platform/journeys/own-provider.sh @@ -1316,6 +1316,8 @@ step_issuer() { --pack "$PROJECT/pack.yaml" --runtime "$RUNTIME_FILE" ;; evidence) + # The check and package commands resolve their matching runtime as a child. + local -x EVIDENCE_BIN="$SERVER_BIN" if [[ "$ISSUER_KIND" == thunderid ]]; then edit "$RUNTIME_FILE" " uri: http://127.0.0.1:8081/oauth2/jwks" \ " uri: $TID_ISSUER/oauth2/jwks" jwks-uri @@ -1328,7 +1330,7 @@ step_issuer() { reader_command issuer -- "$TOOL_BIN" check "$PROJECT" --target "$RUNTIME_FILE" --posture development --format json [[ $CELL_OVER -eq 0 ]] || return 0 local candidate=$WORK/candidate installed=$WORK/installed-package - reader_command issuer -- env EVIDENCE_BIN="$SERVER_BIN" "$TOOL_BIN" package "$PROJECT" \ + reader_command issuer -- "$TOOL_BIN" package "$PROJECT" \ --target "$RUNTIME_FILE" --output "$candidate" --posture development --format json [[ $CELL_OVER -eq 0 ]] || return 0 SEALED_DIRS+=("$candidate") diff --git a/products/platform/journeys/rstack-dev.sh b/products/platform/journeys/rstack-dev.sh index 1b23c5e3d2..b163c45f89 100755 --- a/products/platform/journeys/rstack-dev.sh +++ b/products/platform/journeys/rstack-dev.sh @@ -50,6 +50,8 @@ for name in breg casework evidence messaging scheduling documents coordinator ad export "RSTACK_${upper}CTL_BIN=$JOURNEY_BIN_DIR/${name}ctl" done export RSTACK_RENDER_BIN=$JOURNEY_BIN_DIR/registry-render +# Evidence's authoring CLI invokes the runtime when checking the selected target. +export EVIDENCE_BIN=$JOURNEY_BIN_DIR/evidence # Runs this script started and has not yet stopped, one id per line. LIVE_RUNS='' From f7fbcbc0a884c8c788b4d91930903909ea2f305f Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 16:07:00 +0000 Subject: [PATCH 014/183] test(journeys): correlate the local BReg hook receipt Signed-off-by: Jeremi Joslin --- products/platform/journeys/rstack-dev.sh | 17 +++++++-- .../platform/journeys/test_journey_tables.py | 35 ++++++++++++------- 2 files changed, 38 insertions(+), 14 deletions(-) diff --git a/products/platform/journeys/rstack-dev.sh b/products/platform/journeys/rstack-dev.sh index b163c45f89..39dc3a52cd 100755 --- a/products/platform/journeys/rstack-dev.sh +++ b/products/platform/journeys/rstack-dev.sh @@ -609,8 +609,11 @@ walk_product() { local sink write_keep "$product" "$work" "$project" "$url" "$run" sink=$(jq -er '.bregHookSink.receivedUrl' "$START_FILE") - journey_poll 30 -- hook_received "$sink" "A retained contact" + journey_poll 30 -- hook_received "$sink" "$KEEP_EXPECT" || + journey_harness_failure "the BReg hook sink did not receive the retained contact's creation event" journey_http hook GET "$sink" || unexpected_answer hook + breg_hook_matches "$KEEP_EXPECT" "$JOURNEY_STEP_STDOUT" || + journey_harness_failure "the BReg hook receipt does not contain the retained contact's creation event" journey_pass hook else journey_unexercised hook @@ -752,8 +755,18 @@ assert all(json.loads(line)["eventId"] for line in after[len(before):].splitline PYAUDIT } +# breg_hook_matches RECORD_ID [FILE]: find the exact creation event in the +# sink's capture. Without FILE, read the current poll response from stdin. +breg_hook_matches() { + local record_id=$1 + shift + jq -e --arg record "$record_id" 'any(.[] | .body | fromjson?; + .type == "contact-created" and .data.recordId == $record and + .data.values.name == "A retained contact")' "$@" >/dev/null +} + hook_received() { - curl --silent --fail --max-time 3 "$1" | jq -e --arg name "$2" 'any(.[] | .body | fromjson? | .. | strings; . == $name)' >/dev/null + curl --silent --fail --max-time 3 "$1" | breg_hook_matches "$2" } # attach_database PROJECT: start PROJECT against a PostgreSQL server the reader diff --git a/products/platform/journeys/test_journey_tables.py b/products/platform/journeys/test_journey_tables.py index 5e7da418f8..933b233676 100644 --- a/products/platform/journeys/test_journey_tables.py +++ b/products/platform/journeys/test_journey_tables.py @@ -870,7 +870,7 @@ class LocalHookWalk(unittest.TestCase): def walk(self, product, delivered): script = (TABLES / "rstack-dev.sh").read_text(encoding="utf-8") functions = [] - for name in ("walk_product", "recipe", "hook_received"): + for name in ("walk_product", "recipe", "hook_received", "breg_hook_matches"): match = re.search(rf"^{name}\(\) \{{\n.*?^\}}\n", script, re.M | re.S) self.assertIsNotNone(match, name) functions.append(match.group(0)) @@ -904,12 +904,14 @@ def walk(self, product, delivered): printf 'write %s\n' "$1" >>"$trace" } sink_response() { - if [[ "$delivered" == yes ]]; then - jq -nc '[{body: ({type: "contact-created", data: { - recordId: "retained-id", values: {name: "A retained contact"}}} | tojson)}]' - else - printf '%s\n' '[]' - fi + local record + case "$delivered" in + yes | missing-on-read) record=retained-id ;; + wrong-record) record=other-id ;; + *) printf '%s\n' '[]'; return ;; + esac + jq -nc --arg record "$record" '[{body: ({type: "contact-created", data: { + recordId: $record, values: {name: "A retained contact"}}} | tojson)}]' } curl() { [[ "${!#}" == http://127.0.0.1:49191/received ]] @@ -928,7 +930,11 @@ def walk(self, product, delivered): hook) [[ "${!#}" == http://127.0.0.1:49191/received ]] printf '%s\n' 'read sink' >>"$trace" - sink_response >"$JOURNEY_STEP_STDOUT" + if [[ "$delivered" == missing-on-read ]]; then + printf '%s\n' '[]' >"$JOURNEY_STEP_STDOUT" + else + sink_response >"$JOURNEY_STEP_STDOUT" + fi ;; keep) printf '%s\n' 'read retained record' >>"$trace" @@ -984,10 +990,15 @@ def test_breg_passes_hook_after_payload_arrives(self): self.assertEqual(trace, ["write breg", "poll sink", "read sink", "read retained record"]) def test_breg_does_not_pass_hook_without_payload(self): - result, outcomes, trace = self.walk("breg", "no") - self.assertEqual(result.returncode, 3, result.stdout + result.stderr) - self.assertFalse(any(step in {"hook", "keep", "stop"} for step, _ in outcomes)) - self.assertEqual(trace, ["write breg", "poll sink"]) + for delivered in ("no", "wrong-record", "missing-on-read"): + with self.subTest(delivered=delivered): + result, outcomes, trace = self.walk("breg", delivered) + self.assertEqual(result.returncode, 3, result.stdout + result.stderr) + self.assertFalse(any(step in {"hook", "keep", "stop"} for step, _ in outcomes)) + expected = ["write breg", "poll sink"] + if delivered == "missing-on-read": + expected.append("read sink") + self.assertEqual(trace, expected) def test_final_step_cannot_be_unexercised(self): result, outcomes, _ = self.walk("scheduling", "terminal-step") From ef83a1fa3f88328d94251a9847c75f545e73d76c Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 16:12:56 +0000 Subject: [PATCH 015/183] docs(dev): explain when to use a function or a flow Signed-off-by: Jeremi Joslin --- .../configure/run-a-project-with-rstack-dev.mdx | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/docs/site/src/content/docs/configure/run-a-project-with-rstack-dev.mdx b/docs/site/src/content/docs/configure/run-a-project-with-rstack-dev.mdx index b9bd5b2f13..e01dc434ba 100644 --- a/docs/site/src/content/docs/configure/run-a-project-with-rstack-dev.mdx +++ b/docs/site/src/content/docs/configure/run-a-project-with-rstack-dev.mdx @@ -847,6 +847,20 @@ A later `start` creates a fresh application run. Product data on managed Postgre crates/registry-rstack-dev/src/lib.rs application-root; crates/registry-rstack-dev/src/products.rs PreparedApplication. */} +### Choose a function or a flow + +Use a server-side function for work that finishes within one request. Use a Coordinator flow when +work waits for a person or a date, or when each step needs review. Call function code from the +flow when the flow cannot express an individual step. + +A function owns no product authority. The product authorises every call the function makes. +When the whole procedure lives in function code, you lose the Coordinator diagram and its +record of each step. + +{/* Evidence: crates/registry-coordinator/src/operations.rs, operation_catalog; + products/coordinator/AGENTS.md, Registry Coordinator product; + docs/site/src/content/docs/configure/coordinator.mdx. */} + ### Browser issuer The browser issuer presents only the plan's synthetic test people. From 7123cd4d9c383e54698e55bfd1441e4b0b048468 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 16:18:01 +0000 Subject: [PATCH 016/183] feat(session): generate a checked standalone Envoy configuration Signed-off-by: Jeremi Joslin --- crates/registry-cli-docs/catalog.json | 121 ++++++++++- crates/registry-session/Cargo.toml | 2 +- crates/registry-session/README.md | 7 + crates/registry-session/src/gateway.rs | 2 +- crates/registry-session/src/gateway/verify.rs | 193 +++++++++++++++++- crates/registry-session/src/lib.rs | 48 ++++- crates/registry-session/src/main.rs | 11 + crates/registry-session/tests/binary.rs | 155 ++++++++++++++ .../src/content/docs/configure/session.mdx | 29 ++- 9 files changed, 554 insertions(+), 14 deletions(-) diff --git a/crates/registry-cli-docs/catalog.json b/crates/registry-cli-docs/catalog.json index abb867c811..1db71b3d5f 100644 --- a/crates/registry-cli-docs/catalog.json +++ b/crates/registry-cli-docs/catalog.json @@ -27519,9 +27519,9 @@ { "name": "envoy", "invocation": "registry-session gateway envoy", - "about": "Write or compare the Envoy configuration fragments", + "about": "Generate or verify the Envoy configuration", "long_about": null, - "usage": "registry-session gateway envoy [OPTIONS] <--out |--check |--verify-assembled >", + "usage": "registry-session gateway envoy [OPTIONS] <--out |--check |--verify-assembled |--standalone-out >", "arguments": [], "options": [ { @@ -27551,6 +27551,33 @@ "possible_values": [], "environment": null }, + { + "display": "--standalone-out ", + "description": "Write one complete Envoy JSON configuration using loopback listeners and upstreams", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--listen
", + "description": "Numeric loopback socket address for Envoy", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--upstream ", + "description": "Numeric loopback socket for one configured module or page cluster. Repeat for each cluster", + "always_required": false, + "repeatable": true, + "default_values": [], + "possible_values": [], + "environment": null + }, { "display": "--posture ", "description": "Declared posture: development or production. Unset means production.", @@ -27577,7 +27604,31 @@ "arguments": [ "--out ", "--check ", - "--verify-assembled " + "--verify-assembled ", + "--standalone-out " + ] + }, + { + "kind": "requires-all", + "when": "--standalone-out ", + "arguments": [ + "--listen
" + ] + }, + { + "kind": "requires-all", + "when": "--upstream ", + "arguments": [ + "--listen
", + "--standalone-out " + ] + }, + { + "kind": "mutually-exclusive", + "when": null, + "arguments": [ + "--check ", + "--listen
" ] }, { @@ -27593,6 +27644,38 @@ "when": null, "arguments": [ "--check ", + "--standalone-out " + ] + }, + { + "kind": "mutually-exclusive", + "when": null, + "arguments": [ + "--check ", + "--upstream " + ] + }, + { + "kind": "mutually-exclusive", + "when": null, + "arguments": [ + "--check ", + "--verify-assembled " + ] + }, + { + "kind": "mutually-exclusive", + "when": null, + "arguments": [ + "--listen
", + "--out " + ] + }, + { + "kind": "mutually-exclusive", + "when": null, + "arguments": [ + "--listen
", "--verify-assembled " ] }, @@ -27601,6 +27684,38 @@ "when": null, "arguments": [ "--out ", + "--standalone-out " + ] + }, + { + "kind": "mutually-exclusive", + "when": null, + "arguments": [ + "--out ", + "--upstream " + ] + }, + { + "kind": "mutually-exclusive", + "when": null, + "arguments": [ + "--out ", + "--verify-assembled " + ] + }, + { + "kind": "mutually-exclusive", + "when": null, + "arguments": [ + "--standalone-out ", + "--verify-assembled " + ] + }, + { + "kind": "mutually-exclusive", + "when": null, + "arguments": [ + "--upstream ", "--verify-assembled " ] } diff --git a/crates/registry-session/Cargo.toml b/crates/registry-session/Cargo.toml index dc1419efbd..cbc2295a76 100644 --- a/crates/registry-session/Cargo.toml +++ b/crates/registry-session/Cargo.toml @@ -43,6 +43,7 @@ schemars = { workspace = true, optional = true } serde.workspace = true serde_json.workspace = true sha2.workspace = true +tempfile.workspace = true thiserror.workspace = true tokio.workspace = true tracing.workspace = true @@ -54,7 +55,6 @@ zeroize.workspace = true jsonschema.workspace = true registry-platform-testing.workspace = true reqwest.workspace = true -tempfile.workspace = true tower = { workspace = true, features = ["util"] } [[example]] diff --git a/crates/registry-session/README.md b/crates/registry-session/README.md index 63f38ece6d..ae746385a3 100644 --- a/crates/registry-session/README.md +++ b/crates/registry-session/README.md @@ -55,6 +55,13 @@ them byte for byte. `--verify-assembled /absolute/path/envoy.yaml` checks the assembled static gateway configuration against the runtime file. Regenerate, splice and verify after every runtime change. +For a gateway and upstreams on one host, use `gateway envoy --standalone-out +/absolute/path/envoy.json --listen 127.0.0.1:8080 --upstream +registry=127.0.0.1:8100`. Set `gateway.service.host` to a numeric loopback +address. Supply one `--upstream` for every cluster named by a module or page, +then run `envoy --mode validate --config-path /absolute/path/envoy.json`. +Place an HTTPS-terminating reverse proxy on the same host for a public origin. + The session cookie is `__Host-registry-session` and holds an opaque 256-bit identifier. The temporary sign-in cookie is `__Host-registry-signin`. Both cookies carry `Secure`, `HttpOnly`, `SameSite=Lax` and `Path=/` in both diff --git a/crates/registry-session/src/gateway.rs b/crates/registry-session/src/gateway.rs index f56fa53fc1..f8278d29de 100644 --- a/crates/registry-session/src/gateway.rs +++ b/crates/registry-session/src/gateway.rs @@ -813,7 +813,7 @@ fn array<'a>(value: &'a Value, key: &str) -> &'a [Value] { } mod verify; -pub use verify::verify_assembled; +pub use verify::{verify_assembled, write_standalone}; #[cfg(test)] mod tests { diff --git a/crates/registry-session/src/gateway/verify.rs b/crates/registry-session/src/gateway/verify.rs index 096e7de25e..f40a953c46 100644 --- a/crates/registry-session/src/gateway/verify.rs +++ b/crates/registry-session/src/gateway/verify.rs @@ -10,10 +10,16 @@ //! refused with a finding that names the member and says why. It does not try //! to model the rest of Envoy. -use std::{fs, io::Read, path::Path}; +use std::{ + collections::{BTreeMap, BTreeSet}, + fs, + io::{Read, Write}, + net::{IpAddr, SocketAddr}, + path::Path, +}; use registry_platform_yaml::{Reader, Refusal, ScalarHook, ScalarSite, ScalarStyle}; -use serde_json::Value; +use serde_json::{json, Value}; use super::*; use crate::wire::SOURCE_PROFILE_HEADER; @@ -106,6 +112,8 @@ struct Expected { routes: Vec, /// The generated local reply mappers, which come first and in order. mappers: Vec, + /// The two Session clusters, in generation order. + clusters: Vec, /// The host's own filters the generated routes switch off. host_filters: Vec, /// The host filters some generated route keeps on. @@ -171,7 +179,7 @@ impl Expected { ); } } - fragment("clusters.yaml")?; + let clusters = items(fragment("clusters.yaml")?); Ok(Self { authority: config .gateway_authority() @@ -179,6 +187,7 @@ impl Expected { filters: items(fragment("http-filters.yaml")?), routes: items(fragment("routes.yaml")?), mappers, + clusters, host_filters: config .gateway .iter() @@ -196,6 +205,178 @@ impl Expected { } } +/// Write a static Envoy configuration for a loopback deployment. The same +/// checked routes, filters and reply mappers are used for fragment integration. +pub fn write_standalone<'a>( + runtime_config: &Path, + output: &Path, + listen: SocketAddr, + upstreams: impl IntoIterator, + posture: DeclaredPosture, +) -> Result { + let loaded = load_for_gateway(runtime_config, posture)?; + let mut expected = Expected::new(&loaded.config)?; + let gateway = loaded + .config + .gateway + .as_ref() + .ok_or(GatewayError::NoGatewayBlock)?; + if !expected.host_filters.is_empty() { + return Err(standalone_refusal( + "Remove gateway.hostFilters or integrate the generated fragments.", + )); + } + if !loopback_socket(listen) { + return Err(standalone_refusal( + "Set --listen to a numeric loopback address and nonzero port.", + )); + } + if !gateway + .service + .host + .as_str() + .parse::() + .is_ok_and(|ip| ip.is_loopback()) + { + return Err(standalone_refusal( + "Set gateway.service.host to a numeric loopback address.", + )); + } + let required = expected + .protected + .iter() + .map(String::as_str) + .filter(|name| !matches!(*name, PUBLIC_CLUSTER | CHECK_CLUSTER)) + .collect::>(); + let addresses = standalone_upstreams(&required, upstreams)?; + let mut definitions = String::new(); + for (name, address) in addresses { + cluster( + &mut definitions, + name, + &address.ip().to_string(), + u32::from(address.port()), + ); + } + if !definitions.is_empty() { + expected.clusters.extend( + parse_fragment(&GeneratedFile { + name: "standalone-clusters", + content: definitions, + })? + .as_array() + .cloned() + .ok_or_else(|| standalone_refusal("Could not assemble the upstream clusters."))?, + ); + } + + let strip_port = !expected + .authority + .rsplit_once(':') + .is_some_and(|(_, port)| port.parse::().is_ok()); + let mut filters = expected.filters.clone(); + filters.push(json!({ + "name": "envoy.filters.http.router", + "typed_config": {"@type": ROUTER_TYPE}, + })); + let document = json!({ + "static_resources": { + "listeners": [{ + "name": "registry-session", + "address": {"socket_address": { + "address": listen.ip().to_string(), "port_value": listen.port(), + }}, + "filter_chains": [{"filters": [{ + "name": "envoy.filters.network.http_connection_manager", + "typed_config": { + "@type": MANAGER_TYPE, + "stat_prefix": "registry_session", + "strip_trailing_host_dot": true, + "strip_matching_host_port": strip_port, + "route_config": { + "name": "registry-session", + "virtual_hosts": [{ + "name": "registry-session", + "domains": [&expected.authority], + "routes": &expected.routes, + }], + }, + "local_reply_config": {"mappers": &expected.mappers}, + "http_filters": filters, + }, + }]}], + }], + "clusters": &expected.clusters, + }, + }); + let bytes = serde_json::to_vec_pretty(&document) + .map_err(|_| standalone_refusal("Could not serialize the configuration."))?; + let document = scan_assembly(output, &bytes)?; + verify_document(&expected, &document)?; + + let parent = output + .parent() + .filter(|path| !path.as_os_str().is_empty()) + .unwrap_or_else(|| Path::new(".")); + let mut staged = + tempfile::NamedTempFile::new_in(parent).map_err(|error| io_error(output, &error))?; + staged + .write_all(&bytes) + .and_then(|()| staged.write_all(b"\n")) + .map_err(|error| io_error(output, &error))?; + staged + .persist(output) + .map_err(|error| io_error(output, &error.error))?; + Ok(loaded.posture) +} + +fn loopback_socket(address: SocketAddr) -> bool { + address.ip().is_loopback() && address.port() != 0 +} + +fn standalone_refusal(finding: impl Into) -> GatewayError { + GatewayError::Refused(vec![finding.into()]) +} + +fn standalone_upstreams<'a>( + required: &BTreeSet<&str>, + upstreams: impl IntoIterator, +) -> Result, GatewayError> { + let mut bindings = BTreeMap::new(); + for binding in upstreams { + let (name, socket) = binding + .split_once('=') + .ok_or_else(|| standalone_refusal("Pass each --upstream as CLUSTER=ADDRESS."))?; + if !required.contains(name) { + return Err(standalone_refusal( + "Name a configured module or page cluster in --upstream.", + )); + } + let address = socket + .parse() + .ok() + .filter(|address| loopback_socket(*address)) + .ok_or_else(|| { + standalone_refusal(format!( + "Set --upstream for {name} to a numeric loopback address and nonzero port." + )) + })?; + if bindings.insert(name, address).is_some() { + return Err(standalone_refusal(format!( + "Cluster {name} is supplied more than once." + ))); + } + } + for &name in required { + if !bindings.contains_key(name) { + return Err(standalone_refusal(format!( + "Pass --upstream for the required cluster {name}." + ))); + } + } + Ok(bindings) +} + /// Check an assembled Envoy configuration offline against what the runtime /// file generates now. /// @@ -238,6 +419,10 @@ fn read_assembly(assembled: &Path) -> Result { file.take(MAXIMUM_ASSEMBLED_BYTES + 1) .read_to_end(&mut bytes) .map_err(|error| io_error(assembled, &error))?; + scan_assembly(assembled, &bytes) +} + +fn scan_assembly(assembled: &Path, bytes: &[u8]) -> Result { if bytes.len() as u64 > MAXIMUM_ASSEMBLED_BYTES { return Err(GatewayError::Assembled(vec![ "the assembled configuration is larger than 16 MiB".to_owned(), @@ -246,7 +431,7 @@ fn read_assembly(assembled: &Path) -> Result { let mut reading = EnvoyReading; let document = Reader::new(assembled.display().to_string()) .with_hook(&mut reading) - .scan(&bytes) + .scan(bytes) .map_err(GatewayError::AssembledSyntax)? .ok_or_else(|| { GatewayError::Assembled(vec!["the assembled configuration is empty".to_owned()]) diff --git a/crates/registry-session/src/lib.rs b/crates/registry-session/src/lib.rs index 182ae27c8e..59cf14d7d3 100644 --- a/crates/registry-session/src/lib.rs +++ b/crates/registry-session/src/lib.rs @@ -25,7 +25,7 @@ mod signin; pub mod store; pub mod wire; -use std::path::PathBuf; +use std::{net::SocketAddr, path::PathBuf}; use clap::{value_parser, Arg, ArgAction, ArgGroup, Command}; use registry_platform_posture::POSTURE_FLAG; @@ -106,10 +106,10 @@ pub fn command() -> Command { .subcommand_required(true) .subcommand( Command::new("envoy") - .about("Write or compare the Envoy configuration fragments") + .about("Generate or verify the Envoy configuration") .group( ArgGroup::new("mode") - .args(["out", "check", "verify-assembled"]) + .args(["out", "check", "verify-assembled", "standalone-out"]) .required(true) .multiple(false), ) @@ -136,6 +136,32 @@ pub fn command() -> Command { runtime file generates", ) .value_parser(value_parser!(PathBuf)), + ) + .arg( + Arg::new("standalone-out") + .long("standalone-out") + .value_name("FILE") + .help("Write one complete Envoy JSON configuration using loopback listeners and upstreams") + .requires("listen") + .value_parser(value_parser!(PathBuf)), + ) + .arg( + Arg::new("listen") + .long("listen") + .value_name("ADDRESS") + .help("Numeric loopback socket address for Envoy") + .requires("standalone-out") + .conflicts_with_all(["out", "check", "verify-assembled"]) + .value_parser(value_parser!(SocketAddr)), + ) + .arg( + Arg::new("upstream") + .long("upstream") + .value_name("CLUSTER=ADDRESS") + .help("Numeric loopback socket for one configured module or page cluster. Repeat for each cluster") + .requires("standalone-out") + .conflicts_with_all(["out", "check", "verify-assembled"]) + .action(ArgAction::Append), ), ), ) @@ -157,12 +183,26 @@ mod tests { } #[test] - fn a_gateway_mode_is_exactly_one_of_out_check_and_verify_assembled() { + fn a_gateway_mode_is_exactly_one_of_the_four_outputs_or_checks() { let envoy = ["--runtime-config", "/r.yaml", "gateway", "envoy"]; let with = |extra: &[&str]| parses(&[&envoy[..], extra].concat()); assert!(with(&["--out", "/d"])); assert!(with(&["--check", "/d"])); assert!(with(&["--verify-assembled", "/e.yaml"])); + assert!(with(&[ + "--standalone-out", + "/e.json", + "--listen", + "127.0.0.1:8080" + ])); + assert!(!with(&["--standalone-out", "/e.json"])); + assert!(!with(&["--out", "/d", "--listen", "127.0.0.1:8080"])); + assert!(!with(&[ + "--check", + "/d", + "--upstream", + "api=127.0.0.1:8100" + ])); assert!(!with(&[])); assert!(!with(&["--out", "/d", "--check", "/d"])); assert!(!with(&["--out", "/d", "--verify-assembled", "/e.yaml"])); diff --git a/crates/registry-session/src/main.rs b/crates/registry-session/src/main.rs index eea80bdfe9..7fd0345682 100644 --- a/crates/registry-session/src/main.rs +++ b/crates/registry-session/src/main.rs @@ -1,5 +1,6 @@ // SPDX-License-Identifier: Apache-2.0 +use std::net::SocketAddr; use std::path::PathBuf; use std::process::ExitCode; @@ -96,6 +97,16 @@ async fn main() -> ExitCode { }; let result = if let Some(assembled) = arguments.get_one::("verify-assembled") { gateway::verify_assembled(path, assembled, posture) + } else if let Some(out) = arguments.get_one::("standalone-out") { + let listen = *arguments + .get_one::("listen") + .expect("standalone output requires --listen"); + let upstreams = arguments + .get_many::("upstream") + .into_iter() + .flatten() + .map(String::as_str); + gateway::write_standalone(path, out, listen, upstreams, posture) } else { let mode = match ( arguments.get_one::("out"), diff --git a/crates/registry-session/tests/binary.rs b/crates/registry-session/tests/binary.rs index 66a6436f59..4c82831ab5 100644 --- a/crates/registry-session/tests/binary.rs +++ b/crates/registry-session/tests/binary.rs @@ -233,6 +233,161 @@ async fn the_check_reports_a_refused_file_without_serving() { const GATEWAY_FIXTURE: &str = include_str!("gateway/runtime.yaml"); +#[test] +fn gateway_writes_a_deterministic_checked_standalone_configuration() { + let root = tempfile::tempdir().expect("directory"); + let runtime = root.path().join("runtime.yaml"); + std::fs::write(&runtime, standalone_runtime()).expect("runtime"); + let config = root.path().join("envoy.json"); + + generate_standalone(&runtime, &config); + let first = std::fs::read(&config).expect("read Envoy configuration"); + generate_standalone(&runtime, &config); + assert_eq!( + std::fs::read(&config).expect("read regenerated configuration"), + first + ); + + let verified = runtime_command(&runtime) + .args(["gateway", "envoy", "--verify-assembled"]) + .arg(&config) + .output() + .expect("check complete Envoy configuration"); + assert!( + verified.status.success(), + "{}", + String::from_utf8_lossy(&verified.stderr) + ); + + let document: serde_json::Value = serde_json::from_slice(&first).expect("JSON configuration"); + assert_eq!( + document.pointer("/static_resources/listeners/0/address/socket_address/address"), + Some(&serde_json::json!("127.0.0.1")) + ); + assert_eq!( + document + .pointer("/static_resources/clusters") + .and_then(serde_json::Value::as_array) + .map(Vec::len), + Some(4) + ); +} + +#[test] +#[ignore = "requires Docker and the pinned Envoy image"] +fn envoy_validates_the_generated_standalone_configuration() { + let root = tempfile::tempdir().expect("directory"); + let runtime = root.path().join("runtime.yaml"); + std::fs::write(&runtime, standalone_runtime()).expect("runtime"); + let config = root.path().join("envoy.json"); + generate_standalone(&runtime, &config); + + let image = "envoyproxy/envoy:v1.39.6@sha256:1fde8efee875e4e4f6a39a90fe49d9338e1caacce5762034ef9fb4bbb9ad6aed"; + let mount = format!( + "type=bind,source={},target=/envoy.json,readonly", + config.display() + ); + let output = Command::new("docker") + .args([ + "run", + "--rm", + "--pull=never", + "--network=none", + "--mount", + &mount, + "--entrypoint", + "/usr/local/bin/envoy", + image, + "--mode", + "validate", + "--config-path", + "/envoy.json", + ]) + .output() + .expect("run the pinned Envoy validator"); + assert!( + output.status.success(), + "{}{}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr) + ); +} + +fn generate_standalone(runtime: &std::path::Path, config: &std::path::Path) { + let output = runtime_command(runtime) + .args(["gateway", "envoy", "--standalone-out"]) + .arg(config) + .args([ + "--listen", + "127.0.0.1:8080", + "--upstream", + "registry=127.0.0.1:8100", + "--upstream", + "pages=[::1]:8200", + ]) + .output() + .expect("write complete Envoy configuration"); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); +} + +#[test] +fn standalone_generation_refuses_missing_or_undeclared_clusters_and_public_binds() { + let root = tempfile::tempdir().expect("directory"); + let runtime = root.path().join("runtime.yaml"); + std::fs::write(&runtime, standalone_runtime()).expect("runtime"); + let config = root.path().join("envoy.json"); + + for (listen, upstreams, expected) in [ + ("127.0.0.1:8080", vec!["registry=127.0.0.1:8100"], "pages"), + ( + "127.0.0.1:8080", + vec!["registry=127.0.0.1:8100", "bogus=127.0.0.1:8200"], + "configured module or page cluster", + ), + ("0.0.0.0:8080", vec![], "loopback"), + ( + "127.0.0.1:8080", + vec!["registry=127.0.0.1:8100", "registry=127.0.0.1:8101"], + "more than once", + ), + ] { + let mut command = runtime_command(&runtime); + command + .args(["gateway", "envoy", "--standalone-out"]) + .arg(&config) + .args(["--listen", listen]); + for upstream in upstreams { + command.args(["--upstream", upstream]); + } + let output = command.output().expect("run standalone generator"); + let stderr = String::from_utf8_lossy(&output.stderr); + assert_eq!(output.status.code(), Some(1), "{stderr}"); + assert!(stderr.contains(expected), "{stderr}"); + assert!(!config.exists()); + } +} + +fn standalone_runtime() -> String { + include_str!("../../../products/platform/examples/session/runtime.yaml") + .replace("10.0.0.5", "127.0.0.1") + .replace( + "modules:\n", + "gateway:\n service: {host: 127.0.0.1, publicPort: 8120, checkPort: 8121}\nmodules:\n", + ) + .replace( + " audience: person\n", + " audience: person\n upstream: {cluster: registry, prefixRewrite: /}\n", + ) + .replace( + " signIn: citizen\n", + " signIn: citizen\n upstream: {cluster: pages}\n", + ) +} + /// Run `gateway envoy` on `runtime_text`, with the sentinel secrets in the /// process environment and in the file provider's directory. Returns the exit /// code, everything the command printed, and the content of every file it diff --git a/docs/site/src/content/docs/configure/session.mdx b/docs/site/src/content/docs/configure/session.mdx index e006f55066..cf4a163a57 100644 --- a/docs/site/src/content/docs/configure/session.mdx +++ b/docs/site/src/content/docs/configure/session.mdx @@ -249,7 +249,34 @@ If a value uses an environment expression, add `--environment` with that variabl crates/registry-session/src/offline.rs run, receipt_diagnostics, receipt_findings; crates/registry-session/src/lib.rs command. */} -## 3. Generate and splice the gateway fragments +## 3. Generate the Envoy configuration + +### Standalone gateway on one host + +Use the standalone generator when Envoy, Session, and the module and page services share one +host. Set `gateway.service.host` to a numeric loopback address in the Session runtime file. +For a public HTTPS origin, terminate TLS in a reverse proxy on the same host and preserve the +public authority when forwarding to Envoy. Supply the socket for each distinct cluster named +by the configured modules and pages. + +```bash +registry-session --runtime-config /etc/registry-session/runtime.yaml gateway envoy \ + --standalone-out /etc/envoy/envoy.json --listen 127.0.0.1:8080 \ + --upstream registry=127.0.0.1:8100 --upstream pages=127.0.0.1:8200 +registry-session --runtime-config /etc/registry-session/runtime.yaml gateway envoy \ + --verify-assembled /etc/envoy/envoy.json +envoy --mode validate --config-path /etc/envoy/envoy.json +``` + +The generator verifies the complete configuration before replacing the output file. +The Envoy command validates the file against the installed Envoy binary. Registry Stack tests +it with Envoy 1.39.6. Use the fragment workflow when you need custom HTTP filters or upstreams +on other hosts. + +{/* Evidence: crates/registry-session/src/gateway/verify.rs, write_standalone; + crates/registry-session/tests/binary.rs, envoy_validates_the_generated_standalone_configuration. */} + +### Integrate with an existing gateway Generate into a directory you reserve for these files. The command writes or replaces the four fragments there: From 880e71aa74c580158d9491d6a154110cd9660ea6 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 16:24:11 +0000 Subject: [PATCH 017/183] fix(casework): align the standalone starter and development issuer Signed-off-by: Jeremi Joslin --- crates/registry-caseworkctl/src/project.rs | 31 ++++++++++-- .../docs/configure/casework-directory.mdx | 2 +- .../content/docs/tutorials/first-casework.mdx | 48 +++---------------- 3 files changed, 36 insertions(+), 45 deletions(-) diff --git a/crates/registry-caseworkctl/src/project.rs b/crates/registry-caseworkctl/src/project.rs index d6c7ab1fe8..8bbe66a7f2 100644 --- a/crates/registry-caseworkctl/src/project.rs +++ b/crates/registry-caseworkctl/src/project.rs @@ -145,7 +145,7 @@ reviewPolicies: trustedProducers: requester: profile: requester - issuer: http://127.0.0.1:8093 + issuer: https://identity.casework.example.test subject: b75315b2-5854-70f3-8867-511dd771a6da sourceNamespaces: [standalone] reviewPolicies: [decision] @@ -315,8 +315,7 @@ fn development_plan(project: &CaseworkProject) -> Result<(String, String, String .iter() .find(|profile| profile.acts_as == CaseworkActsAs::Staff) .context("the template needs a staff profile for the development journey")?; - // A logical HTTPS issuer for the run. The starter's producer pins may - // identify a different teaching issuer and stay in the authored policy. + // The logical HTTPS issuer matches the standalone requester binding. let issuer = "https://identity.casework.example.test"; let mut people = BTreeMap::new(); let mut roles = BTreeMap::new(); @@ -1240,6 +1239,32 @@ pub(super) fn doctor(path: &Path, declared: DeclaredPosture) -> Result { mod display_integrity_tests { use super::*; + #[test] + fn standalone_starter_pins_its_generated_development_requester() { + let root = crate::canonical_tempdir(); + let project_path = root.path().join("project"); + init(&project_path, "standalone-decision").unwrap(); + + let project = load_and_check_policy(&project_path).unwrap(); + let producer = project + .trusted_producers + .iter() + .find(|producer| producer.profile.as_str() == "requester") + .expect("the standalone requester has a producer binding"); + let plan_path = project_path.join("dev.yaml"); + let plan = registry_platform_yaml::Reader::new(plan_path.display().to_string()) + .scan(&fs::read(&plan_path).unwrap()) + .unwrap() + .unwrap() + .to_json_value(); + + assert_eq!(plan["issuer"].as_str(), Some(producer.issuer.as_str())); + assert_eq!( + plan["people"]["requester"]["subject"].as_str(), + Some(producer.subject.as_str()) + ); + } + fn assert_typed_authoring_refusal(error: anyhow::Error) { let (exit, diagnostic) = crate::classify_failure(crate::CommandKind::Authoring, &error); assert_eq!(exit, crate::DOMAIN_REFUSAL_EXIT); diff --git a/docs/site/src/content/docs/configure/casework-directory.mdx b/docs/site/src/content/docs/configure/casework-directory.mdx index 04cabd5cd0..3b393598df 100644 --- a/docs/site/src/content/docs/configure/casework-directory.mdx +++ b/docs/site/src/content/docs/configure/casework-directory.mdx @@ -42,7 +42,7 @@ bootstrap call a deployment uses, as the plan's `administrator` person: ```yaml title="dev-journeys.yaml" test-excerpt="tutorial-work/casework/dev-journeys.yaml" body: teamId: decisions-team - staff: [{issuer: https://identity.standalone.example.test, subject: staff}] + staff: [{issuer: https://identity.casework.example.test, subject: staff}] supervisors: [] queueId: decisions ``` diff --git a/docs/site/src/content/docs/tutorials/first-casework.mdx b/docs/site/src/content/docs/tutorials/first-casework.mdx index 105d9aac0f..4b118a1ad1 100644 --- a/docs/site/src/content/docs/tutorials/first-casework.mdx +++ b/docs/site/src/content/docs/tutorials/first-casework.mdx @@ -110,47 +110,13 @@ Casework keeps the snapshot the producer sends and refuses each listed case. ## Describe the local run -`rstack dev` runs the project on your machine from a plan file. First tell Casework which issuer -and subject the producer's tokens carry. The template trusts a fixed local address, and a run signs -its test tokens under an HTTPS issuer name of your choosing: - -```diff test-edit title="casework.yaml" - trustedProducers: - requester: - profile: requester -- issuer: http://127.0.0.1:8093 -- subject: b75315b2-5854-70f3-8867-511dd771a6da -+ issuer: https://identity.standalone.example.test -+ subject: requester -``` +`rstack dev` uses the generated `dev.yaml`. The plan issues test tokens under the requester's +issuer and subject in `casework.yaml`. -Replace the generated plan with the following plan. It lists the product, test people and the roles they hold. It names a journey file, which -runs when the run starts: - -```yaml title="dev.yaml" test-file -apiVersion: id.registrystack.org/formats/rstack/dev/v1alpha1 -kind: RStackDev -issuer: https://identity.standalone.example.test -products: - - {product: casework, project: ., audience: "urn:example:standalone-decision"} -people: - administrator: - subject: administrator - client: standalone-workbench - roles: [administrator] - staff: - subject: staff - client: standalone-workbench - roles: [staff] - requester: - subject: requester - client: standalone-requester - roles: [requester] -journeyFile: dev-journeys.yaml -``` +{/* Evidence: crates/registry-caseworkctl/src/project.rs, STANDALONE_YAML, development_plan. */} -A new Casework directory has no staff. The journey has the administrator seat one team on the -`decisions` queue and put the person `staff` in it: +A new Casework directory has no staff. Replace `dev-journeys.yaml` to have the administrator +seat one team on the `decisions` queue and put the person `staff` in it: ```yaml title="dev-journeys.yaml" test-file apiVersion: id.registrystack.org/formats/rstack/journeys/v1alpha1 @@ -166,7 +132,7 @@ journeys: headers: {If-Match: '"0"', Idempotency-Key: staff-the-queue} body: teamId: decisions-team - staff: [{issuer: https://identity.standalone.example.test, subject: staff}] + staff: [{issuer: https://identity.casework.example.test, subject: staff}] supervisors: [] queueId: decisions expect: {status: 200} @@ -293,7 +259,7 @@ claimed_revision="$(jq -r .revision claimed.json)" ```json test-excerpt { "revision": 2, - "state": {"held": {"holder": {"issuer": "https://identity.standalone.example.test", "subject": "staff"}}} + "state": {"held": {"holder": {"issuer": "https://identity.casework.example.test", "subject": "staff"}}} } ``` From 65f7410f6631e715c8d28e07ecda01f186c258aa Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 16:30:01 +0000 Subject: [PATCH 018/183] feat(dev): attach BReg hooks without replacing the managed issuer Signed-off-by: Jeremi Joslin --- crates/registry-rstack-dev/src/plan.rs | 31 +++- crates/registry-rstack/tests/dev_run.rs | 158 ++++++++++++++++++ .../run-a-project-with-rstack-dev.mdx | 16 +- 3 files changed, 201 insertions(+), 4 deletions(-) diff --git a/crates/registry-rstack-dev/src/plan.rs b/crates/registry-rstack-dev/src/plan.rs index 2508dd2f53..f3bb726607 100644 --- a/crates/registry-rstack-dev/src/plan.rs +++ b/crates/registry-rstack-dev/src/plan.rs @@ -1334,12 +1334,16 @@ impl Plan { "Set issuer to the exact numeric loopback HTTP origin for an external key endpoint, or use `run` or a fixed HTTPS issuer for runner-managed keys.", )?; if let Some(bindings) = &self.external_breg { + let hook_only = !bindings.hooks.is_empty() + && bindings.review_authority.is_none() + && bindings.task_grant.is_none() + && bindings.schema_test_headers.is_empty(); require( - self.jwks_uri().is_some() + (self.jwks_uri().is_some() || hook_only) && self.products.iter().any(|p| p.product == Product::Breg), "/externalBreg", - "External BReg connections require BReg and an external issuer.", - "Add BReg and externalJwksUri to this plan, or remove externalBreg.", + "External BReg connections require BReg. A binding other than a hook also requires an external issuer.", + "Add BReg to the plan, and add externalJwksUri for any bindings other than hooks.", )?; bindings.validate(root)?; } @@ -2325,6 +2329,27 @@ mod tests { } } + #[test] + fn a_fixed_external_hook_may_use_the_managed_development_issuer() { + let (root, mut plan) = plan(json!({"id": "read", "product": "breg", + "as": "operator", "method": "GET", "path": "/v1/records", "expect": {"status": 200}})); + fs::create_dir(root.path().join("fixture")).unwrap(); + crate::write_private(&root.path().join("fixture/key"), b"synthetic fixture").unwrap(); + let mut external = json!({"hooks": {"events": { + "origin": "http://127.0.0.1:41000", + "path": "/events", + "keyRef": "secret:file/key", + }}}); + plan.external_breg = Some(serde_json::from_value(external.clone()).unwrap()); + plan.validate(root.path()).expect("hook-only attachment"); + + external["schemaTestHeaders"] = json!({"operator": "secret:file/key"}); + plan.external_breg = Some(serde_json::from_value(external).unwrap()); + let error = plan.validate(root.path()).unwrap_err(); + assert_eq!(error.field, "/externalBreg"); + assert!(error.reason.contains("external issuer")); + } + #[test] fn external_breg_peers_require_numeric_loopback_http() { for pointer in [ diff --git a/crates/registry-rstack/tests/dev_run.rs b/crates/registry-rstack/tests/dev_run.rs index ad381c9433..bf26f3ce76 100644 --- a/crates/registry-rstack/tests/dev_run.rs +++ b/crates/registry-rstack/tests/dev_run.rs @@ -3481,6 +3481,164 @@ fn breg_alone_runs_end_to_end() { ); } +#[test] +#[cfg(target_os = "linux")] +#[ignore = "requires Docker, its pinned receiver image, and built BReg binaries"] +fn breg_attaches_to_an_independent_signed_hook_receiver() { + let scratch = tempfile::tempdir().unwrap(); + let state = scratch.path().join("state"); + let project = scratch.path().join("project"); + copy_tree(&example_project("breg/examples/minimal"), &project); + let fixture = project.join("fixture"); + fs::create_dir(&fixture).unwrap(); + let key = fixture.join("event-hmac"); + use std::io::Write; + fs::OpenOptions::new() + .write(true) + .create_new(true) + .mode(0o600) + .open(&key) + .unwrap() + .write_all(b"synthetic attach-test signing material") + .unwrap(); + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let port = listener.local_addr().unwrap().port(); + let plan = project.join("dev.yaml"); + let mut text = fs::read_to_string(&plan).unwrap(); + text.push_str(&format!( + "\nexternalBreg:\n hooks:\n contact-sink: {{origin: \"http://127.0.0.1:{port}\", path: /events, keyRef: \"secret:file/event-hmac\"}}\n" + )); + fs::write(plan, text).unwrap(); + let registry = project.join("registry.yaml"); + let text = fs::read_to_string(®istry).unwrap().replacen( + "\nactions:\n", + "\n hooks:\n - id: contact-created\n phase: after\n trigger: created\n projection: [name, jurisdiction]\n handler: {type: url, destinationId: contact-sink}\n\nactions:\n", + 1, + ); + fs::write(registry, text).unwrap(); + let command = |arguments: &[&str]| { + rstack_dev(&state, true) + .env("PATH", std::env::var_os("PATH").unwrap_or_default()) + .env("RSTACK_BREG_BIN", host("breg")) + .env_remove("REGISTRY_STACK_POSTURE") + .args(arguments) + .output() + .unwrap() + }; + let checked = command(&["check", utf8(&project)]); + assert!( + checked.status.success(), + "check refused the hook attachment: {}", + String::from_utf8_lossy(&checked.stdout) + ); + + let receiver = example_project("platform/journeys/projects/hook-receiver.py"); + let receiver_mount = format!( + "type=bind,source={},target=/receiver.py,readonly", + receiver.display() + ); + let fixture_mount = format!("type=bind,source={},target=/fixture", fixture.display()); + let name = format!( + "v051-hook-{}", + scratch.path().file_name().unwrap().to_string_lossy() + ); + let docker = |args: &[&str]| Command::new("docker").args(args).output().unwrap(); + let image = "mcr.microsoft.com/playwright:v1.60.0-noble@sha256:9bd26ad900bb5e0f4dee75839e957a89ae89c2b7ab1e76050e559790e946b948"; + drop(listener); + let started = docker(&[ + "run", + "--detach", + "--rm", + "--pull=never", + "--network=host", + "--name", + &name, + "--mount", + &receiver_mount, + "--mount", + &fixture_mount, + "--entrypoint", + "python3", + image, + "/receiver.py", + &port.to_string(), + "/events", + "contact-created", + "/fixture/event-hmac", + "/fixture/event.json", + ]); + assert!( + started.status.success(), + "{}", + String::from_utf8_lossy(&started.stderr) + ); + let origin = format!("http://127.0.0.1:{port}"); + let ready = Command::new("curl") + .args([ + "--fail", + "--silent", + "--noproxy", + "*", + "--retry", + "5", + "--retry-connrefused", + "--max-time", + "2", + ]) + .arg(format!("{origin}/ready")) + .output() + .unwrap(); + let run = ready + .status + .success() + .then(|| command(&["start", utf8(&project), "--ttl", "1m"])); + let receipt_path = fixture.join("event.json"); + let receipt = run + .as_ref() + .filter(|output| output.status.success()) + .and_then(|_| { + let deadline = Instant::now() + Duration::from_secs(15); + while Instant::now() < deadline { + if let Some(event) = fs::read(&receipt_path) + .ok() + .and_then(|bytes| serde_json::from_slice::(&bytes).ok()) + .filter(|event| event["data"]["values"]["name"] == "Example contact") + { + return Some(event); + } + thread::sleep(Duration::from_millis(100)); + } + None + }); + let report = run + .as_ref() + .and_then(|output| serde_json::from_slice::(&output.stdout).ok()); + let stopped = report + .as_ref() + .and_then(|report| report["run_id"].as_str()) + .map(|id| command(&["stop", id, "--clean"])); + let receiver_stopped = docker(&["stop", &name]); + + assert!(receiver_stopped.status.success(), "receiver did not stop"); + assert!( + ready.status.success(), + "the sibling receiver did not become ready" + ); + let started = run.expect("start was attempted"); + assert!( + started.status.success(), + "start refused the hook attachment: {}", + String::from_utf8_lossy(&started.stdout) + ); + let run = report.expect("valid start report"); + assert!(run["bregHookSink"].is_null()); + assert_eq!(run["scenarios"][0]["result"], "passed"); + assert!(stopped.expect("BReg stopped and cleaned").status.success()); + let event = receipt.expect("signed event received"); + assert_eq!(event["type"], "contact-created"); + assert_eq!(event["data"]["values"]["name"], "Example contact"); +} + #[test] #[ignore = "requires RSTACK_DEV_DATABASE_URL, RSTACK_DEV_DATABASE_CA and built caseworkctl and casework binaries"] fn casework_alone_runs_end_to_end() { diff --git a/docs/site/src/content/docs/configure/run-a-project-with-rstack-dev.mdx b/docs/site/src/content/docs/configure/run-a-project-with-rstack-dev.mdx index e01dc434ba..90bd1fa738 100644 --- a/docs/site/src/content/docs/configure/run-a-project-with-rstack-dev.mdx +++ b/docs/site/src/content/docs/configure/run-a-project-with-rstack-dev.mdx @@ -482,7 +482,6 @@ When a BReg project declares the corresponding connection, the plan can bind ext - `externalBreg.reviewAuthority` names the Casework producer, token endpoint and private-key JWT credentials. - `externalBreg.taskGrant` pairs the exact assertion issuer and client with the Casework status connection. -- `externalBreg.hooks` binds declared destination IDs to signed outbound requests to a loopback event proxy. For BReg schema rehearsals, `externalBreg.schemaTestHeaders` maps each selected person to an owner-only bearer header obtained from the external issuer. @@ -493,6 +492,21 @@ Use `secret:file/NAME` for fixture keys and headers. Put each file under the pro For a Messaging throughput rehearsal, set `RSTACK_DEV_MESSAGING_MOCK_LATENCY_MS` before starting the run. The local mock gateway delays its responses by this many milliseconds. +## Use a BReg hook receiver you run + +Set `externalBreg.hooks` when you run a separate BReg hook receiver. You can use the development +runner's issuer for a plan that attaches only hooks. Bind every declared destination ID to its +numeric loopback origin, exact event path, and `secret:file/NAME` under `fixture/`. Give the +receiver the matching HMAC key. For a sibling container, publish the receiver port on the host's +loopback interface. + +Run `rstack dev check` before starting the project. Make an authorised change that emits the event +and check that the receiver verifies its signature and records the expected event. + +{/* Evidence: crates/registry-rstack-dev/src/plan.rs, a_fixed_external_hook_may_use_the_managed_development_issuer; + crates/registry-rstack-dev/src/products.rs, prepare_breg_hooks; + crates/registry-rstack-dev/src/external_breg.rs, Hook, hook_key. */} + ## The managed PostgreSQL server The run starts PostgreSQL for BReg, Casework, Messaging, Scheduling, Documents, Coordinator and From fc5a255426b6d63a67f290814b850cd2f9eb76df Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 16:30:01 +0000 Subject: [PATCH 019/183] refactor(messaging): select HTTP provider transports centrally Signed-off-by: Jeremi Joslin --- .../src/http_provider/settings.rs | 49 +++++++++++++------ 1 file changed, 33 insertions(+), 16 deletions(-) diff --git a/crates/registry-messaging/src/http_provider/settings.rs b/crates/registry-messaging/src/http_provider/settings.rs index 6a5ddeb319..1b8acd421b 100644 --- a/crates/registry-messaging/src/http_provider/settings.rs +++ b/crates/registry-messaging/src/http_provider/settings.rs @@ -29,6 +29,9 @@ use registry_platform_httputil::destination::{ is_script_visible_response_header_name, is_script_writable_request_header_name, MAX_DESTINATION_OPERATION_TIMEOUT, MAX_DESTINATION_PRIVATE_CIDRS, }; +use registry_platform_httputil::select::{ + select_destination, DestinationSelectionError, TransportClass, +}; use registry_platform_yaml::{ ApiVersion, Decoded, EnvelopeRule, Expect, FormatSpec, Invalid, Reader, RemovedKey, Report, UniqueList, @@ -1287,23 +1290,16 @@ fn split_base_url( "must not carry credentials, a query, or a fragment", )); } - let development = match parsed.scheme() { - "https" => false, - "http" => { - let loopback = parsed - .host_str() - .and_then(registry_platform_httputil::loopback::loopback_host) - .is_some(); - if !loopback { - return Err(invalid( - field, - "http is allowed only to a loopback host; use https", - )); + let selected = select_destination(&parsed, None, &[]).map_err(|error| { + let message = match error { + DestinationSelectionError::PrivateNetworkNotDeclared => { + "http is allowed only to a loopback host; use https" } - true - } - _ => return Err(invalid(field, "must use https, or http to a loopback host")), - }; + _ => "must use https, or http to a loopback host", + }; + invalid(field, message) + })?; + let development = selected.transport() == TransportClass::LoopbackPlaintext; // The URL parser resolves dot segments and their escapes, so the // configured text is checked too: the path sent is the path written. let path = parsed.path().to_owned(); @@ -1414,6 +1410,27 @@ fn token_form_body( mod tests { use super::*; + #[test] + fn provider_and_token_paths_keep_the_configured_https_origin() { + let expected_origin = "https://provider.example.test:8443/".to_owned(); + let (origin, path, development) = + split_base_url("baseUrl", "https://provider.example.test:8443/v1/", true).unwrap(); + assert_eq!( + (origin, path, development), + (expected_origin.clone(), "/v1/".to_owned(), false) + ); + let (origin, path, development) = split_base_url( + "authentication.tokenEndpoint", + "https://provider.example.test:8443/issuer/token", + false, + ) + .unwrap(); + assert_eq!( + (origin, path, development), + (expected_origin, "/issuer/token".to_owned(), false) + ); + } + #[test] fn plain_http_is_allowed_only_to_a_loopback_host() { for base_url in [ From 4600170933c2a0613c1fdc157d7836e5fdb3a5b9 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 16:27:27 +0000 Subject: [PATCH 020/183] feat(coordinator): name in-flow Rhai computations transforms Signed-off-by: Jeremi Joslin (cherry picked from commit 0ce005b78b72f0ee74946ac338d9a98915224781) --- crates/registry-coordinator/src/authoring.rs | 114 ++++++------ crates/registry-coordinator/src/cli.rs | 22 +-- crates/registry-coordinator/src/compare.rs | 4 +- crates/registry-coordinator/src/completion.rs | 4 +- crates/registry-coordinator/src/contracts.rs | 10 +- crates/registry-coordinator/src/definition.rs | 76 ++++---- .../registry-coordinator/src/event_trigger.rs | 6 +- .../src/event_trigger_tests.rs | 6 +- .../registry-coordinator/src/external_http.rs | 12 +- crates/registry-coordinator/src/functions.rs | 100 +++++------ .../registry-coordinator/src/mapping_check.rs | 12 +- crates/registry-coordinator/src/problem.rs | 6 +- crates/registry-coordinator/src/protocol.rs | 2 +- .../registry-coordinator/src/read_in_force.rs | 2 +- crates/registry-coordinator/src/scenarios.rs | 24 +-- crates/registry-coordinator/src/worker.rs | 2 +- .../tests/authored_project.rs | 64 +++---- .../registry-coordinator/tests/authoring.rs | 77 +++++++-- .../tests/authoring_findings.rs | 40 ++--- .../tests/breg_action_native.rs | 8 +- .../tests/canonical_model.rs | 44 ++--- .../tests/cli_authoring.rs | 2 +- .../tests/external_command_project.rs | 6 +- .../fixtures/external-command/workflow.yaml | 6 +- .../tests/fixtures/review-wait/workflow.yaml | 6 +- .../tests/helper_functions.rs | 46 ++--- .../tests/instant_functions.rs | 12 +- .../tests/mapping_checks.rs | 10 +- .../tests/mapping_grammar.rs | 34 ++-- .../tests/nested_fields.rs | 16 +- .../tests/postgres_state.rs | 61 ++++--- .../tests/process_restart.rs | 6 +- .../tests/product_contract_imports.rs | 5 +- .../tests/recovery_audit.rs | 4 +- .../tests/review_wait_postgres.rs | 2 +- .../tests/runtime_config.rs | 4 +- .../tests/scheduling_event_native.rs | 4 +- .../tests/support/breg_service.rs | 4 +- .../tests/support/decision_evaluation.rs | 8 +- .../tests/support/leased_wait_deadline.rs | 10 +- .../tests/support/restore_pending.rs | 4 +- .../tests/support/snapshot_boundary.rs | 4 +- .../tests/wait_for_authoring.rs | 2 +- .../src/products/catalog_coordinator.rs | 55 +++--- .../tests/coordinator_navigation.rs | 20 +-- .../content/docs/configure/coordinator.mdx | 63 +++---- .../src/content/docs/operate/coordinator.mdx | 4 +- .../src/content/docs/reference/glossary.mdx | 5 +- .../src/content/docs/security/coordinator.mdx | 30 ++-- .../src/content/docs/start/coordinator.mdx | 6 +- .../kobotoolbox-job/workflow/workflow.yaml | 22 +-- products/coordinator/AGENTS.md | 4 +- products/coordinator/CHANGELOG.md | 2 + .../examples/decision-follow-up/README.md | 2 +- .../examples/decision-follow-up/workflow.yaml | 14 +- .../deferred-appointment/workflow.yaml | 18 +- .../examples/delayed-follow-up/workflow.yaml | 10 +- .../earlier-appointment-alerts/workflow.yaml | 66 +++---- .../examples/external-directory/workflow.yaml | 10 +- .../examples/external-job/README.md | 4 +- .../examples/external-job/workflow.yaml | 6 +- .../governed-action-follow-up/README.md | 2 +- .../governed-action-follow-up/workflow.yaml | 14 +- .../accept-invitation/workflow.yaml | 34 ++-- .../issue-invitation/workflow.yaml | 10 +- .../request-only/workflow.yaml | 22 +-- .../examples/reviewed-notice/workflow.yaml | 18 +- .../generated/fixture/fixture.schema.json | 6 +- .../generated/operations/catalog.json | 2 +- .../external.command.v1.output.schema.json | 2 +- .../generated/project/project.schema.json | 162 +++++++++--------- 71 files changed, 787 insertions(+), 717 deletions(-) diff --git a/crates/registry-coordinator/src/authoring.rs b/crates/registry-coordinator/src/authoring.rs index 16df88a480..339fbcc310 100644 --- a/crates/registry-coordinator/src/authoring.rs +++ b/crates/registry-coordinator/src/authoring.rs @@ -45,16 +45,19 @@ const FORMAT: FormatSpec<'static> = FormatSpec { RemovedKey { pointer: "/title", replacement: "Write project.label." }, RemovedKey { pointer: "/label", replacement: "Move label to project.label." }, RemovedKey { pointer: "/description", replacement: "Move description to project.description." }, - RemovedKey { pointer: "/functions/*/title", replacement: "Write label." }, + RemovedKey { pointer: "/functions", replacement: "Rename functions to transforms, then replace each type: function and function member with type: transform and transform." }, + RemovedKey { pointer: "/transforms/*/title", replacement: "Write label." }, + RemovedKey { pointer: "/workflow/steps/*/*/function", replacement: "Write type: transform and name the Transform in the transform member." }, + RemovedKey { pointer: "/workflow/eventTriggers/*/input/function", replacement: "Write type: transform and name the Transform in the transform member." }, RemovedKey { pointer: "/operations/*/title", replacement: "Write label." }, RemovedKey { pointer: "/workflow/steps/*/title", replacement: "Write label." }, RemovedKey { pointer: "/connections", replacement: "Declare logical connections on Operation aliases under operations, then bind them in runtime.yaml." }, - RemovedKey { pointer: "/functionsFile", replacement: "Declare named typed Functions under functions, each with its source asset." }, + RemovedKey { pointer: "/functionsFile", replacement: "Declare named typed Transforms under transforms, each with its source asset." }, RemovedKey { pointer: "/deadlineSeconds", replacement: "Move deadlineSeconds to workflow.deadlineSeconds." }, RemovedKey { pointer: "/start", replacement: "Move start to workflow.start." }, RemovedKey { pointer: "/steps", replacement: "Move steps to workflow.steps and use Operation aliases." }, RemovedKey { pointer: "/outcomes", replacement: "Move outcomes to workflow.outcomes." }, - RemovedKey { pointer: "/workflow/steps/*/*/arguments", replacement: "Use inputs with the Function signature's named references." }, + RemovedKey { pointer: "/workflow/steps/*/*/arguments", replacement: "Use inputs with the Transform signature's named references." }, ], }; @@ -74,7 +77,7 @@ pub struct CoordinatorProject { types: BTreeMap, /// Named typed bounded pure computations over one object of named inputs. #[serde(default)] - functions: BTreeMap, + transforms: BTreeMap, /// Local aliases for exact versioned host Operations and logical deployment connections. #[serde(default)] operations: BTreeMap, @@ -164,7 +167,7 @@ struct AuthoredOperation { /// or external command Operation. #[serde(default)] response_schema: Option, - /// The typed pure Function that interprets an external command's provider + /// The typed pure Transform that interprets an external command's provider /// response into an accepted result, a declared refusal or an uncertain /// outcome. Required on, and accepted only on, `external.command/v1`. #[serde(default)] @@ -194,7 +197,7 @@ struct AuthoredOperation { enum AuthoredCompletion { /// Repeats the accepted read under host-owned transport and credentials. BoundedPoll { - /// The typed pure Function that turns the saved command and response into an observation. + /// The typed pure Transform that turns the saved command and response into an observation. interpret: LocalId, /// Seconds between pending observations; the host may impose a stricter minimum. interval_seconds: BoundedU32<1, 86_400>, @@ -205,16 +208,16 @@ registry_platform_yaml::tagged_union!(AuthoredCompletion); #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] -struct AuthoredFunction { +struct AuthoredTransform { /// The pinned pure runtime; rhai has no clock, network, database or credential capability. - runtime: FunctionRuntime, + runtime: TransformRuntime, /// A local reviewed source asset inside the project directory. source: String, /// One public source function taking exactly one named-input object. entrypoint: String, /// Named input schemas or references; every declared input is required exactly once. inputs: BTreeMap, - /// The declared result schema or mapping; Functions and the host enforce it. + /// The declared result schema or mapping; Transforms and the host enforce it. output: Schema, /// Optional narrowing of the bounded pure profile; omitted limits retain the default ceiling. #[serde(default)] @@ -232,7 +235,7 @@ struct AuthoredFunction { #[derive(Debug, Deserialize)] #[serde(rename_all = "kebab-case")] #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] -enum FunctionRuntime { +enum TransformRuntime { Rhai, } @@ -424,7 +427,7 @@ enum Member { /// A literal JSON value; it remains subject to bounded value checks. value: ForeignValue, }, - /// Builds a nested object member by member, never with a Function. + /// Builds a nested object member by member, never with a Transform. Fields { /// Object members built from typed references, literals or nested fields. fields: Fields, @@ -442,10 +445,10 @@ registry_platform_yaml::tagged_union!(Member); #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] #[cfg_attr(feature = "schema", schemars(!remote, tag = "type"))] enum AuthoredMapping { - /// Computes a value with a declared typed pure Function. - Function { - /// A declared pure Function called with an object of named inputs. - function: LocalId, + /// Computes a value with a declared typed pure Transform. + Transform { + /// A declared pure Transform called with an object of named inputs. + transform: LocalId, /// Named input schemas or references; every declared input is required exactly once. inputs: BTreeMap, }, @@ -617,7 +620,7 @@ enum AuthoredStep { Finish { /// One declared terminal outcome name. outcome: LocalId, - /// The declared result schema or mapping; Functions and the host enforce it. + /// The declared result schema or mapping; Transforms and the host enforce it. #[serde(default)] output: Option, /// An optional human label; it changes neither stable identity nor behavior revision. @@ -799,9 +802,9 @@ impl From for crate::compare::Condition { impl From for Mapping { fn from(mapping: AuthoredMapping) -> Self { let reference = match mapping { - AuthoredMapping::Function { function, inputs } => { + AuthoredMapping::Transform { transform, inputs } => { return Self::Function { - function: function.into_string(), + function: transform.into_string(), inputs: inputs .into_iter() .map(|(id, reference)| (id.into_string(), reference.into())) @@ -855,7 +858,7 @@ pub(crate) fn asset_path(root: &Path, asset: &str) -> Result CoordinatorError::new("definition.read", "the project asset is unavailable") .with_exit(3) .suggest( - "Restore the named generated contract or Function source asset inside the project.", + "Restore the named generated contract or Transform source asset inside the project.", ) })?; if !candidate.starts_with(&root) || !candidate.is_file() { @@ -960,8 +963,8 @@ fn project_integrity_diagnostics( map_ids("/types", &project.types), ), ( - "coordinator.project.function-id-collision", - map_ids("/functions", &project.functions), + "coordinator.project.transform-id-collision", + map_ids("/transforms", &project.transforms), ), ( "coordinator.project.operation-id-collision", @@ -1002,13 +1005,13 @@ fn project_integrity_diagnostics( ), )); } - for (id, function) in &project.functions { + for (id, function) in &project.transforms { errors.extend(collisions( document, - "coordinator.project.function-input-id-collision", + "coordinator.project.transform-input-id-collision", &map_ids( &format!( - "/functions/{}/inputs", + "/transforms/{}/inputs", registry_platform_yaml::escape_pointer_segment(id.as_str()) ), &function.inputs, @@ -1054,15 +1057,15 @@ fn project_integrity_diagnostics( let groups = [ ( - "coordinator.project.duplicate-function-label", - "functions", + "coordinator.project.duplicate-transform-label", + "transforms", project - .functions + .transforms .iter() .filter_map(|(id, item)| { item.label.as_ref().map(|label| { let pointer = format!( - "/functions/{}/label", + "/transforms/{}/label", registry_platform_yaml::escape_pointer_segment(id.as_str()) ); (id.as_str().to_owned(), label.clone(), pointer) @@ -1292,13 +1295,13 @@ fn compile(project: CoordinatorProject, path: &Path) -> Result { (Operation::ExternalCommand, None) => { return Err(schema_error( format!("/operations/{id}/interpret"), - "external.command/v1 requires interpret: the Function that turns the provider response into an accepted result, a declared refusal or an uncertain outcome", + "external.command/v1 requires interpret: the Transform that turns the provider response into an accepted result, a declared refusal or an uncertain outcome", )); } (_, Some(_)) => { return Err(schema_error( format!("/operations/{id}/interpret"), - "only external.command/v1 accepts an interpretation Function", + "only external.command/v1 accepts an interpretation Transform", )); } (_, None) => {} @@ -1366,7 +1369,7 @@ fn compile(project: CoordinatorProject, path: &Path) -> Result { }, ); } - // Base operation schemas resolve before Function signatures. No completion + // Base operation schemas resolve before Transform signatures. No completion // output may take part in that graph, so a completion cannot define itself. let raw_operations = operations.clone(); let resolver = Schemas { @@ -1385,8 +1388,8 @@ fn compile(project: CoordinatorProject, path: &Path) -> Result { .transpose()?; } let base = operations.clone(); - // Interpretation Functions can see only resolved base Operation schemas - // and host-owned completions. Downstream Functions resolve after bounded + // Interpretation Transforms can see only resolved base Operation schemas + // and host-owned completions. Downstream Transforms resolve after bounded // completion bindings, so ordinary mappings can consume their typed output. let resolver = Schemas { types: &raw_types, @@ -1407,7 +1410,7 @@ fn compile(project: CoordinatorProject, path: &Path) -> Result { .collect::>(); let mut functions = BTreeMap::new(); let mut downstream = Vec::new(); - for (id, function) in project.functions { + for (id, function) in project.transforms { if interpreters.contains(id.as_str()) { functions.insert( id.as_str().to_owned(), @@ -1425,16 +1428,19 @@ fn compile(project: CoordinatorProject, path: &Path) -> Result { .expect("the base alias exists"); let field = format!("/operations/{operation_id}/interpret"); let function = functions.get(interpret.as_str()).ok_or_else(|| { - schema_error(field.clone(), "the interpretation Function is not declared") + schema_error( + field.clone(), + "the interpretation Transform is not declared", + ) })?; if function.inputs.len() != 2 || function.inputs.get("command") != Some(&operation.input) || function.inputs.get("response") != Some(&operation.output) { - return Err(schema_error(field, "the interpretation Function must take command and response with the command's exact input and response schemas")); + return Err(schema_error(field, "the interpretation Transform must take command and response with the command's exact input and response schemas")); } let (output, refusal) = - command_interpretation(&function.output, &format!("/functions/{interpret}/output"))?; + command_interpretation(&function.output, &format!("/transforms/{interpret}/output"))?; operation.response = Some(std::mem::replace(&mut operation.output, output)); operation.refusal = refusal; operation.interpret = Some(interpret.into_string()); @@ -1464,17 +1470,17 @@ fn compile(project: CoordinatorProject, path: &Path) -> Result { let function = functions.get(interpret.as_str()).ok_or_else(|| { schema_error( format!("/operations/{operation_id}/completions/{name}/interpret"), - "the interpretation Function is not declared", + "the interpretation Transform is not declared", ) })?; if function.inputs.len() != 2 || function.inputs.get("command") != Some(&operation.input) || function.inputs.get("response") != Some(&operation.output) { - return Err(schema_error(format!("/operations/{operation_id}/completions/{name}/interpret"), "the interpretation Function must take command and response with the owning Operation's exact schemas")); + return Err(schema_error(format!("/operations/{operation_id}/completions/{name}/interpret"), "the interpretation Transform must take command and response with the owning Operation's exact schemas")); } let output = - terminal_schema(&function.output, &format!("/functions/{interpret}/output"))?; + terminal_schema(&function.output, &format!("/transforms/{interpret}/output"))?; operation.completions.insert( name, CompletionDefinition { @@ -1755,7 +1761,7 @@ fn compile(project: CoordinatorProject, path: &Path) -> Result { fn resolve_function( id: &str, - function: AuthoredFunction, + function: AuthoredTransform, resolver: &Schemas<'_>, ) -> Result { let _runtime = function.runtime; @@ -1767,14 +1773,14 @@ fn resolve_function( resolver .resolve( &schema.0.into_value(), - &format!("/functions/{id}/inputs/{name}"), + &format!("/transforms/{id}/inputs/{name}"), ) .map(|schema| (name, schema)) }) .collect::>>()?; let output = resolver.resolve( &function.output.0.into_value(), - &format!("/functions/{id}/output"), + &format!("/transforms/{id}/output"), )?; Ok(FunctionDefinition { runtime: "rhai".into(), @@ -1816,8 +1822,8 @@ fn reference_sites(document: &Document) -> BTreeMap { - Some(format!("/functions/{id}")) + ("transform" | "interpret", Some(id)) if !schema => { + Some(format!("/transforms/{id}")) } ( "next" | "onTimeout" | "onCancel" | "onDeclaredRefusal" | "step", @@ -1851,7 +1857,7 @@ fn reference_sites(document: &Document) -> BTreeMap { Some(format!("asset:{asset}")) @@ -1936,8 +1942,8 @@ fn reference_sites(document: &Document) -> BTreeMap Result<()> { } /// The step output and declared refusal an external command's interpretation -/// establishes. The Function returns one closed object per state: `accepted` +/// establishes. The Transform returns one closed object per state: `accepted` /// with a required `result`, and optionally `refused` with a required closed /// enum `code` and `uncertain`. The step output is the accepted result, still /// bound to the interpretation's own local definitions; the refusal admits only @@ -2385,10 +2391,10 @@ pub(crate) fn positioned(document: &Document, error: CoordinatorError) -> Coordi } // A function's own definition is placed in functions.rhai; a function // that fails while a step evaluates it is placed at that step. - if error.code.starts_with("function.") + if error.code.starts_with("transform.") && !matches!( error.code.as_str(), - "function.value-limit" | "function.json" + "transform.value-limit" | "transform.json" ) && error.file.as_deref().map(std::path::PathBuf::as_path) != Some(Path::new("workflow.yaml")) @@ -2490,7 +2496,7 @@ pub fn project_schema() -> std::result::Result { maps(&mut schema); for (pointer, minimum, maximum) in [ ("/properties/operations", 0, 64), - ("/properties/functions", 0, 128), + ("/properties/transforms", 0, 128), ("/properties/types", 0, 128), ("/$defs/AuthoredWorkflow/properties/eventTriggers", 0, 16), ("/$defs/AuthoredWorkflow/properties/calendarTriggers", 0, 1), @@ -2510,13 +2516,13 @@ pub fn project_schema() -> std::result::Result { if variant .pointer("/properties/type/const") .and_then(Value::as_str) - == Some("function") + == Some("transform") { variant["properties"]["inputs"]["maxProperties"] = json!(16); } } } - if let Some(inputs) = schema.pointer_mut("/$defs/AuthoredFunction/properties/inputs") { + if let Some(inputs) = schema.pointer_mut("/$defs/AuthoredTransform/properties/inputs") { inputs["maxProperties"] = json!(16); } let mut text = serde_json::to_string_pretty(&schema)?; diff --git a/crates/registry-coordinator/src/cli.rs b/crates/registry-coordinator/src/cli.rs index af486e8715..accdfc4ccb 100644 --- a/crates/registry-coordinator/src/cli.rs +++ b/crates/registry-coordinator/src/cli.rs @@ -106,8 +106,8 @@ impl ListTurn { /// What `explain` describes without a project. #[derive(Subcommand)] enum ExplainTopic { - /// List the helpers a pure Function may call, with the interpreter ABI and limits. - Functions, + /// List the helpers a pure Transform may call, with the interpreter ABI and limits. + Transforms, } mod identity_facts; @@ -155,7 +155,7 @@ enum Command { #[command(subcommand)] topic: GenerateTopic, }, - /// Validate the workflow, functions and root YAML companions offline. + /// Validate the workflow, Transforms and root YAML companions offline. Check { #[arg(long)] /// Directory containing workflow.yaml and its declared code and contract assets. @@ -174,7 +174,7 @@ enum Command { /// Check under the production posture. production: bool, }, - /// Explain a checked graph, mappings and execution bounds offline, or the helpers Functions may call. + /// Explain a checked graph, mappings and execution bounds offline, or the helpers Transforms may call. #[command(args_conflicts_with_subcommands = true, subcommand_negates_reqs = true)] Explain { #[arg(long, required = true)] @@ -971,7 +971,7 @@ async fn execute( Ok(json!({"status":"generated","output":output})) } Command::Check { project, explain, deny_warnings, environment, .. } => check(project.as_deref(), runtime_config(cli)?.as_deref(), *explain, *deny_warnings, *environment, declared, explicit_settings), - Command::Explain { topic: Some(ExplainTopic::Functions), .. } => Ok(crate::functions::explain()), + Command::Explain { topic: Some(ExplainTopic::Transforms), .. } => Ok(crate::functions::explain()), Command::Explain { project, .. } => check(project.as_deref(), runtime_config(cli)?.as_deref(), true, false, false, declared, explicit_settings), Command::Test { project, fixtures } => test(project, fixtures.as_deref()), Command::Package { project, output } => { @@ -1623,9 +1623,9 @@ fn render_human(cli: &Cli, value: &Value) -> String { render_explain(value) } Command::Explain { - topic: Some(ExplainTopic::Functions), + topic: Some(ExplainTopic::Transforms), .. - } => render_functions(value), + } => render_transforms(value), Command::Check { .. } => { let mut out = String::new(); if let Some(workflow) = value["workflow"].as_str() { @@ -1780,15 +1780,15 @@ fn render_explain(value: &Value) -> String { .map(|(limit, bound)| format!("{limit} {bound}")) .collect::>() .join(", "); - out.push_str(&format!("Function limits: {limits}\n")); + out.push_str(&format!("Transform limits: {limits}\n")); out.push_str(&format!("Recovery: {}\n", text(&value["recovery"]))); out } /// The profile, then its helper names in lines a terminal can show. -fn render_functions(value: &Value) -> String { +fn render_transforms(value: &Value) -> String { let mut out = format!( - "Pure function helpers, profile {}\nInterpreter ABI: {}\nFunction limits: {}\nHelpers:\n", + "Transform helpers, profile {}\nInterpreter ABI: {}\nFunction limits: {}\nHelpers:\n", text(&value["profile"]), text(&value["interpreterAbi"]), value["limits"] @@ -1822,7 +1822,7 @@ fn render_functions(value: &Value) -> String { /// A step mapping as one phrase: `f(input, step a /b)`, `{m: input /n}` or /// one reference. fn mapping(value: &Value) -> String { - if let Some(function) = value["function"].as_str() { + if let Some(function) = value["transform"].as_str() { let arguments = value["arguments"] .as_array() .into_iter() diff --git a/crates/registry-coordinator/src/compare.rs b/crates/registry-coordinator/src/compare.rs index 217cfb2985..8aaa762fa6 100644 --- a/crates/registry-coordinator/src/compare.rs +++ b/crates/registry-coordinator/src/compare.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: Apache-2.0 //! The compare decision of a choose step: an ordered list of tests over typed -//! values that routes to `matched` or `unmatched`. A compare holds no Function, +//! values that routes to `matched` or `unmatched`. A compare holds no Transform, //! no nesting and no clock, so the same input and step outputs always take the //! same route. //! @@ -358,7 +358,7 @@ mod tests { fn only_a_compare_that_cannot_test_its_value_is_a_failed_choice() { let choice = CoordinatorError::new("mapping.choice", "the value is missing"); assert_eq!(failure_code(&choice), "choice-invalid"); - for code in ["mapping.path", "mapping.branch", "function.failed"] { + for code in ["mapping.path", "mapping.branch", "transform.failed"] { let error = CoordinatorError::new(code, "refused"); assert_eq!(failure_code(&error), "mapping-invalid", "{code}"); } diff --git a/crates/registry-coordinator/src/completion.rs b/crates/registry-coordinator/src/completion.rs index a6013d1308..6771c5a16e 100644 --- a/crates/registry-coordinator/src/completion.rs +++ b/crates/registry-coordinator/src/completion.rs @@ -23,7 +23,7 @@ use registry_platform_crypto::delivery_signature::{ use registry_review_protocol::ReviewCompletion; use uuid::Uuid; -/// Interpret one bounded external observation using the pinned pure Function. +/// Interpret one bounded external observation using the pinned pure Transform. /// The original saved command is the only correlation input; mappings are not /// evaluated again while waiting. Invalid evidence remains a recovery hold. pub(crate) fn interpret_poll( @@ -65,7 +65,7 @@ pub(crate) fn interpret_poll( }; match value.get("state").and_then(serde_json::Value::as_str) { Some("pending") => CompletionObservation::Pending { retry_after: None }, - // The Function's complete interpretation envelope has been checked. + // The Transform's complete interpretation envelope has been checked. // The worker or scenario checks the cached terminal contract once. Some("complete" | "refused") => CompletionObservation::Settled(value), _ => hold(), diff --git a/crates/registry-coordinator/src/contracts.rs b/crates/registry-coordinator/src/contracts.rs index f95bfb593f..efa16f2389 100644 --- a/crates/registry-coordinator/src/contracts.rs +++ b/crates/registry-coordinator/src/contracts.rs @@ -28,7 +28,7 @@ pub struct OperationContract { output_validator: JSONSchema, refusal_validator: Option, /// The complete provider response an `external.command/v1` interpretation - /// Function reads, before it becomes an accepted result or a refusal. + /// Transform reads, before it becomes an accepted result or a refusal. response_validator: Option, } @@ -172,7 +172,7 @@ impl OperationContract { Ok(self) } - /// Checks a provider response before an interpretation Function reads it. + /// Checks a provider response before an interpretation Transform reads it. /// An operation without a declared response accepts none. pub fn check_response(&self, value: &Value) -> Result<(), Violation> { match &self.response_validator { @@ -1255,13 +1255,13 @@ mod derived { (input::(), output::()) } - /// The command body is a JSON object a pinned pure Function builds; the + /// The command body is a JSON object a pinned pure Transform builds; the /// output is the bounded provider response the pinned interpretation - /// Function receives, never the step result itself. + /// Transform receives, never the step result itself. pub(super) fn external_command() -> (Value, Value) { let mut response = output::(); response["description"] = json!( - "The bounded provider response. The operation's interpret Function \ + "The bounded provider response. The operation's interpret Transform \ receives it with the command and returns the step result, a declared \ refusal, or an uncertain outcome." ); diff --git a/crates/registry-coordinator/src/definition.rs b/crates/registry-coordinator/src/definition.rs index 813d9326ee..2b3d45be7c 100644 --- a/crates/registry-coordinator/src/definition.rs +++ b/crates/registry-coordinator/src/definition.rs @@ -17,7 +17,7 @@ use serde_json::Value; use crate::{ functions::{ - check_value, Functions, INTERPRETER_ABI, MAXIMUM_FUNCTION_ARRAY_ITEMS, + check_value, Transforms, INTERPRETER_ABI, MAXIMUM_FUNCTION_ARRAY_ITEMS, MAXIMUM_FUNCTION_CALL_LEVELS, MAXIMUM_FUNCTION_EXPRESSION_DEPTH, MAXIMUM_FUNCTION_MAP_ENTRIES, MAXIMUM_FUNCTION_OPERATIONS, MAXIMUM_FUNCTION_SOURCE_BYTES, MAXIMUM_FUNCTION_STRING_BYTES, @@ -53,7 +53,7 @@ pub struct Definition { pub workflow: Workflow, pub digest: String, frozen: Snapshot, - functions: Functions, + functions: Transforms, input_schema: Arc, outcome_schemas: BTreeMap>, operation_contracts: BTreeMap>, @@ -94,12 +94,14 @@ pub struct ServiceDeadline { pub next: String, } -/// How a step computes its value: a pure function over references, an +/// How a step computes its value: a pure Transform over references, an /// object built member by member from references and nested objects, or one /// reference. #[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)] #[serde(untagged, deny_unknown_fields)] pub enum Mapping { + // Frozen v1alpha1 snapshots and semantic revisions keep this member. + // Authoring and operator explanations use the Transform vocabulary. Function { function: String, inputs: BTreeMap, @@ -114,7 +116,7 @@ pub enum Mapping { } /// One member of a fields mapping: a reference, or a nested object built -/// the same way. A member never calls a Function. +/// the same way. A member never calls a Transform. #[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)] #[serde(untagged)] pub enum Member { @@ -188,6 +190,15 @@ pub(crate) fn valid_field_name(name: &str) -> bool { } impl Mapping { + fn explain(&self) -> Value { + match self { + Self::Function { function, inputs } => { + serde_json::json!({"transform":function,"inputs":inputs}) + } + mapping => serde_json::json!(mapping), + } + } + /// Each reference with its member path below the mapping. pub(crate) fn references(&self) -> Vec<(String, &Reference)> { match self { @@ -370,13 +381,13 @@ pub struct ResolvedOperation { pub refusal: Option, pub completions: BTreeMap, pub revision: String, - /// The pinned pure Function that turns an external command's saved + /// The pinned pure Transform that turns an external command's saved /// command and bounded provider response into an accepted result, a /// declared refusal or an uncertain outcome. Present only on /// `external.command/v1`. #[serde(default, skip_serializing_if = "Option::is_none")] pub interpret: Option, - /// The bounded provider response the interpretation Function reads. + /// The bounded provider response the interpretation Transform reads. /// Present only on `external.command/v1`, whose `output` is the /// interpreted accepted result. #[serde(default, skip_serializing_if = "Option::is_none")] @@ -680,14 +691,14 @@ impl Definition { .map_err(|error| { crate::authoring::positioned( &document, - error.at(&path, format!("/functions/{name}/source")), + error.at(&path, format!("/transforms/{name}/source")), ) })?; let source = read_text(&source_path, MAXIMUM_FUNCTION_SOURCE_BYTES as usize) .map_err(|error| { crate::authoring::positioned( &document, - error.at(&path, format!("/functions/{name}/source")), + error.at(&path, format!("/transforms/{name}/source")), ) })?; sources.insert(function.source.clone(), source); @@ -813,7 +824,7 @@ impl Definition { Err(error) => findings.push(error), _ => {} } - let functions = Functions::compile(&frozen.sources, &frozen.workflow.functions) + let functions = Transforms::compile(&frozen.sources, &frozen.workflow.functions) .map_err(|refused| findings.extend(refused)) .ok(); let input_schema = compile_schema(&frozen.workflow.input) @@ -967,10 +978,7 @@ impl Definition { }; let mut item = serde_json::json!({"id":id,"kind":kind,"next":step.targets()}); if let Some(mapping) = step.mapping() { - item["mapping"] = serde_json::json!(mapping); - if let Mapping::Function { inputs, .. } = mapping { - item["mapping"]["inputs"] = serde_json::json!(inputs); - } + item["mapping"] = mapping.explain(); } match step { Step::Call { @@ -1026,9 +1034,13 @@ impl Definition { item }) .collect::>(); + let mut event_triggers = serde_json::json!(self.workflow.event_triggers); + for (id, trigger) in &self.workflow.event_triggers { + event_triggers[id]["input"] = trigger.input.explain(); + } let mut report = serde_json::json!({"workflow":self.workflow.id,"version":self.workflow.version,"workflowRevision":self.digest, "start":self.workflow.start,"deadlineSeconds":parse_duration(&self.workflow.deadline)?.num_seconds(), - "contracts":contracts,"operations":self.workflow.operations,"operationContracts":operation_contracts,"calendarTriggers":self.workflow.calendar_triggers,"eventTriggers":self.workflow.event_triggers,"functions":self.workflow.functions,"types":self.workflow.types,"references":self.workflow.references,"presentation":self.workflow.presentation,"connections":self.workflow.connections,"outcomes":self.workflow.outcomes.keys().collect::>(),"steps":steps, + "contracts":contracts,"operations":self.workflow.operations,"operationContracts":operation_contracts,"calendarTriggers":self.workflow.calendar_triggers,"eventTriggers":event_triggers,"transforms":self.workflow.functions,"types":self.workflow.types,"references":self.workflow.references,"presentation":self.workflow.presentation,"connections":self.workflow.connections,"outcomes":self.workflow.outcomes.keys().collect::>(),"steps":steps, "limits":crate::functions::limits(),"valueLimits":crate::functions::value_limits(),"interpreterAbi":self.frozen.interpreter_abi,"schemaAbi":self.frozen.schema_abi,"adapterAbi":self.frozen.adapter_abi, "recovery":"A run restores this exact snapshot. retry-same preserves a frozen command and cannot adopt edited mappings or repeat an uncertain hold-after-dispatch evaluation."}); @@ -1355,7 +1367,7 @@ fn seal_revisions(workflow: &mut Workflow, sources: &BTreeMap) - for function in workflow.functions.values_mut() { let source = sources .get(&function.source) - .ok_or_else(|| fail("function.definition"))?; + .ok_or_else(|| fail("transform.definition"))?; function.revision = crate::functions::revision(function, source)?; } for operation in workflow.operations.values_mut() { @@ -1395,9 +1407,9 @@ fn seal_revisions(workflow: &mut Workflow, sources: &BTreeMap) - Ok(()) } -/// An external command pins one interpretation Function over its exact +/// An external command pins one interpretation Transform over its exact /// command and response schemas, and its output and refusal are exactly what -/// that Function declares. No other operation carries an interpretation. +/// that Transform declares. No other operation carries an interpretation. fn command_interpretation_valid(flow: &Workflow, operation: &ResolvedOperation) -> bool { if operation.uses != Operation::ExternalCommand { return operation.interpret.is_none() && operation.response.is_none(); @@ -1579,7 +1591,7 @@ fn build_fields( /// What computed a mapping's value, as a refusal names it. fn producer(mapping: &Mapping) -> String { match mapping { - Mapping::Function { function, .. } => format!("function {function}"), + Mapping::Function { function, .. } => format!("Transform {function}"), Mapping::Fields { .. } => "the fields mapping".into(), Mapping::Compare { .. } => "the compare".into(), Mapping::Reference(_) => "the reference".into(), @@ -1679,7 +1691,7 @@ fn workflow_findings(flow: &Workflow) -> Vec { ("connections", flow.connections.len(), 0, 16), ("outcomes", flow.outcomes.len(), 1, 64), ("operations", flow.operations.len(), 0, 64), - ("functions", flow.functions.len(), 0, 128), + ("transforms", flow.functions.len(), 0, 128), ("types", flow.types.len(), 0, 128), ("contracts", flow.contracts.len(), 0, 16), ] { @@ -1878,11 +1890,11 @@ fn workflow_findings(flow: &Workflow) -> Vec { } if let Some(Mapping::Function { function, inputs }) = step.mapping() { match flow.functions.get(function) { - None => findings.push(authored("mapping.function", &format!("steps.{name}.{}.function", step.role()), - &format!("Function {function} is not declared; available Functions are {}", listed(flow.functions.keys().map(String::as_str))), - "Name one of the declared Functions, or add its typed signature and reviewed source asset.")), - Some(signature) if inputs.keys().ne(signature.inputs.keys()) => findings.push(authored("mapping.function", &format!("steps.{name}.{}.inputs",step.role()), - "the named Function inputs must match its declared signature exactly", "Supply every declared input name once and remove undeclared names.")), + None => findings.push(authored("mapping.transform", &format!("steps.{name}.{}.transform", step.role()), + &format!("Transform {function} is not declared; available Transforms are {}", listed(flow.functions.keys().map(String::as_str))), + "Name one of the declared Transforms, or add its typed signature and reviewed source asset.")), + Some(signature) if inputs.keys().ne(signature.inputs.keys()) => findings.push(authored("mapping.transform", &format!("steps.{name}.{}.inputs",step.role()), + "the named Transform inputs must match its declared signature exactly", "Supply every declared input name once and remove undeclared names.")), _ => {}, } } @@ -2332,12 +2344,12 @@ pub(crate) fn validate_mapping( return Err(authored( "mapping.reference", &base, - "waitUntil and choose take a function or a single reference, not fields", - "Select the instant or label with one reference, or compute it in a function.", + "waitUntil and choose take a Transform or a single reference, not fields", + "Select the instant or label with one reference, or compute it in a Transform.", )) } (_, Mapping::Function { function, .. }) if !valid_name(function) => { - return Err(fail("mapping.function").at("workflow.yaml", format!("steps.{name}"))) + return Err(fail("mapping.transform").at("workflow.yaml", format!("steps.{name}"))) } (_, Mapping::Fields { fields }) => fields_bounds(fields, &base, 1, &mut 0)?, (_, Mapping::Compare { compare }) => compare.check(step, name)?, @@ -2354,7 +2366,7 @@ pub(crate) fn validate_mapping( "mapping.literal", &format!("{field}.value"), "the literal exceeds the structured value bounds", - "Shorten the literal or build the value in a function; literals hold at most 32 levels, 4096 nodes, 16384-byte strings, 131072 canonical bytes, and integers within 2^53 - 1.", + "Shorten the literal or build the value in a Transform; literals hold at most 32 levels, 4096 nodes, 16384-byte strings, 131072 canonical bytes, and integers within 2^53 - 1.", ) })?; continue; @@ -2539,16 +2551,16 @@ fn fail(code: &'static str) -> CoordinatorError { "definition.cycle" => "the graph contains a cycle", "definition.unreachable" => "a step is not reachable from start", "definition.deadline" => "deadline must be a positive s, m, h or d duration no longer than 365 days", - "mapping.branch" => "the function did not return a declared branch label", + "mapping.branch" => "the Transform did not return a declared branch label", "mapping.timestamp" => "waitUntil did not return an RFC 3339 instant", "mapping.missing-output" => "a declared prior call output is absent", "mapping.path" => "the reference path names no member of the value it reads", - "mapping.call-shape" => "the call input function did not return an object", + "mapping.call-shape" => "the call input Transform did not return an object", "definition.input" => "the start input does not satisfy its authored schema", "definition.outcome" => "the final output does not satisfy the declared outcome schema", "definition.schema" => "the schema is invalid or uses an unsupported format or external reference", _ => "the workflow definition or mapping was refused", - }).suggest("Inspect the authored field and function, correct the definition, then rerun check. Admitted runs keep their original snapshot.") + }).suggest("Inspect the authored field and Transform, correct the definition, then rerun check. Admitted runs keep their original snapshot.") } /// A run cancels only work it opened, so a cancel's input is a fields @@ -2559,7 +2571,7 @@ fn fail(code: &'static str) -> CoordinatorError { /// - a review cancel's `request` is the whole accepted request, with no path, /// a `casework.submit-review-request/v1` step returned. /// -/// Any other source, such as the run input, a literal, a Function, a nested +/// Any other source, such as the run input, a literal, a Transform, a nested /// object or another step, is refused with the code, message and suggestion /// returned here. Ordinary step reference checks then hold that the step ran /// on every route here. diff --git a/crates/registry-coordinator/src/event_trigger.rs b/crates/registry-coordinator/src/event_trigger.rs index 0361df8242..6dd75c724c 100644 --- a/crates/registry-coordinator/src/event_trigger.rs +++ b/crates/registry-coordinator/src/event_trigger.rs @@ -204,7 +204,7 @@ pub(crate) fn check_key_references( } /// Resolved governed trigger. The package revision covers every member, the -/// event schema and all referenced Function implementation bytes. +/// event schema and all referenced Transform implementation bytes. #[derive(Clone, Debug, Deserialize, Serialize, PartialEq)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct EventTrigger { @@ -217,7 +217,7 @@ pub struct EventTrigger { impl EventTrigger { /// Evaluate only after durable duplicate lookup. Exact replay must not be - /// reinterpreted by an edited active mapping or Function. + /// reinterpreted by an edited active mapping or Transform. pub(crate) fn map(&self, definition: &Definition, event: &Value) -> Result { crate::functions::check_value(event)?; let schema = crate::definition::compile_schema(&self.event)?; @@ -463,7 +463,7 @@ pub fn verify_delivery( let event_source = envelope.source.as_str(); let value = serde_json::to_value(&envelope).map_err(|_| invalid_event())?; crate::functions::check_value(&value).map_err(|error| { - if error.code == "function.value-limit" { + if error.code == "transform.value-limit" { event_too_large() } else { invalid_event() diff --git a/crates/registry-coordinator/src/event_trigger_tests.rs b/crates/registry-coordinator/src/event_trigger_tests.rs index cfb13e052f..253cdf0ae4 100644 --- a/crates/registry-coordinator/src/event_trigger_tests.rs +++ b/crates/registry-coordinator/src/event_trigger_tests.rs @@ -666,7 +666,7 @@ fn a_function_used_only_by_an_event_trigger_is_hash_covered() { let workflow = project_text() .replace( "workflow:\n input:", - r#"functions: + r#"transforms: event-input: runtime: rhai source: functions.rhai @@ -687,8 +687,8 @@ workflow: fields: recordId: {type: input, path: /data/recordId}"#, r#" input: - type: function - function: event-input + type: transform + transform: event-input inputs: event: {type: input}"#, ); diff --git a/crates/registry-coordinator/src/external_http.rs b/crates/registry-coordinator/src/external_http.rs index 0bc397e345..c6fa2cb42a 100644 --- a/crates/registry-coordinator/src/external_http.rs +++ b/crates/registry-coordinator/src/external_http.rs @@ -275,7 +275,7 @@ impl ExternalHttpConnection { /// so the same command can still be retried. A `Retry-After` either /// answer carries that the command cannot use is ignored. Only a status /// `command_status` classifies as interpreted reaches the operation's - /// pinned interpretation Function, which receives the response. + /// pinned interpretation Transform, which receives the response. pub async fn command( &self, input: &Value, @@ -478,12 +478,12 @@ impl ExternalHttpConnection { /// What an `external.command/v1` attempt does with the provider's HTTP status /// before any body is read. Only [`CommandStatus::Interpreted`] reaches the -/// operation's interpretation Function; scenario checks use the same -/// classification, so a synthetic response reply cannot show the Function +/// operation's interpretation Transform; scenario checks use the same +/// classification, so a synthetic response reply cannot show the Transform /// reading a status the worker never hands it. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(crate) enum CommandStatus { - /// The bounded response goes to the interpretation Function. + /// The bounded response goes to the interpretation Transform. Interpreted, /// A redirect is never followed. It may answer an accepted command, so /// the command is uncertain. @@ -512,8 +512,8 @@ pub(crate) fn command_status(status: reqwest::StatusCode) -> CommandStatus { } /// Interpret one provider response to an `external.command/v1` call with the -/// project's pinned pure Function. The response is held to its declared -/// schema before the Function reads it. Anything the Function cannot turn into +/// project's pinned pure Transform. The response is held to its declared +/// schema before the Transform reads it. Anything the Transform cannot turn into /// an accepted result or a declared refusal leaves the command uncertain, /// never failed: the provider may already have applied it. No code carries a /// response or command value. diff --git a/crates/registry-coordinator/src/functions.rs b/crates/registry-coordinator/src/functions.rs index c0e567043d..dc068f2a06 100644 --- a/crates/registry-coordinator/src/functions.rs +++ b/crates/registry-coordinator/src/functions.rs @@ -1,5 +1,5 @@ // SPDX-License-Identifier: Apache-2.0 -//! Pure functions under one pinned, bounded interpreter profile. +//! Pure Transforms under one pinned, bounded interpreter profile. use crate::definition::{compile_schema, FunctionDefinition}; use chrono::{DateTime, Datelike, SecondsFormat, TimeDelta, Utc}; @@ -55,7 +55,7 @@ const PROFILE: RhaiProfile = RhaiProfile { }; #[derive(Clone)] -pub(crate) struct Functions { +pub(crate) struct Transforms { entries: BTreeMap, } @@ -83,7 +83,7 @@ fn profile(function: &FunctionDefinition) -> RhaiProfile { } } -impl Functions { +impl Transforms { pub(crate) fn compile( sources: &BTreeMap, definitions: &BTreeMap, @@ -96,7 +96,7 @@ impl Functions { let result = (|| { let source = sources .get(&function.source) - .ok_or_else(|| failure("function.definition"))?; + .ok_or_else(|| failure("transform.definition"))?; let limits = &function.limits; let ceiling = crate::definition::FunctionLimits::default(); if function.runtime != "rhai" @@ -119,20 +119,20 @@ impl Functions { || limits.source_bytes > ceiling.source_bytes || function.inputs.len() > 16 { - return Err(failure("function.limits") - .at("workflow.yaml", format!("/functions/{name}/limits"))); + return Err(failure("transform.limits") + .at("workflow.yaml", format!("/transforms/{name}/limits"))); } let ast = platform::compile_entrypoint(&profile(function), source, &function.entrypoint, &[1]) .map_err(|error| match error { - platform::RhaiCompileError::SourceBound => failure("function.source-limit").at(&function.source, "/"), - platform::RhaiCompileError::Parse(position) if refused_only_for_curry(source) => CoordinatorError::new("function.definition", "function source uses `curry`, which Coordinator Functions do not offer") + platform::RhaiCompileError::SourceBound => failure("transform.source-limit").at(&function.source, "/"), + platform::RhaiCompileError::Parse(position) if refused_only_for_curry(source) => CoordinatorError::new("transform.definition", "Transform source uses `curry`, which Coordinator Transforms do not offer") .at(&function.source, format!("line {} column {}", position.line().unwrap_or(0), position.position().unwrap_or(0))) .suggest("Pass the value as an argument where the function is called, for example add(1, x) instead of Fn(\"add\").curry(1).call(x)."), - platform::RhaiCompileError::Parse(position) => CoordinatorError::new("function.definition", syntax_refusal(source)) + platform::RhaiCompileError::Parse(position) => CoordinatorError::new("transform.definition", syntax_refusal(source)) .at(&function.source, format!("line {} column {}", position.line().unwrap_or(0), position.position().unwrap_or(0))) - .suggest("Correct the named Function source syntax and rerun check."), - platform::RhaiCompileError::Entrypoint => CoordinatorError::new("function.definition", "the Function entrypoint must name one public Rhai function taking one named-input object") - .at("workflow.yaml", format!("/functions/{name}/entrypoint")) + .suggest("Correct the named Transform source syntax and rerun check."), + platform::RhaiCompileError::Entrypoint => CoordinatorError::new("transform.definition", "the Transform entrypoint must name one public Rhai function taking one named-input object") + .at("workflow.yaml", format!("/transforms/{name}/entrypoint")) .suggest("Declare one public function with exactly one parameter for its named input object."), })?; let mut names = std::collections::BTreeSet::new(); @@ -141,7 +141,7 @@ impl Functions { .any(|function| !names.insert(function.name.to_owned())) || names.len() > 128 { - return Err(failure("function.definition").at(&function.source, "/")); + return Err(failure("transform.definition").at(&function.source, "/")); } let properties = function .inputs @@ -160,8 +160,8 @@ impl Functions { let output = std::sync::Arc::new(compile_schema(&function.output)?); let revision = revision(function, source)?; if function.revision != revision { - return Err(failure("function.revision") - .at("workflow.yaml", format!("/functions/{name}"))); + return Err(failure("transform.revision") + .at("workflow.yaml", format!("/transforms/{name}"))); } Ok(CompiledFunction { definition: function.clone(), @@ -172,7 +172,7 @@ impl Functions { })(); match result { Ok(compiled) => { - // Functions share one source, so each walk finds the same + // Transforms share one source, so each walk finds the same // calls; a call is reported once, at its position. let unknown = unknown_calls(&compiled); if unknown.is_empty() { @@ -203,46 +203,46 @@ impl Functions { let function = self .entries .get(name) - .ok_or_else(|| failure("function.definition"))?; + .ok_or_else(|| failure("transform.definition"))?; check_value(inputs)?; if !function.input.is_valid(inputs) { return Err(contract_failure( name, - "function.input", + "transform.input", &function.input, inputs, synthetic, )); } let arguments = - vec![rhai::serde::to_dynamic(inputs).map_err(|_| failure("function.input"))?]; + vec![rhai::serde::to_dynamic(inputs).map_err(|_| failure("transform.input"))?]; let engine = platform::build_engine(&profile(&function.definition), None, register_pure_packages); let value = platform::call_with_fresh_scope(&engine, &function.ast, &function.definition.entrypoint, arguments) .map_err(|error| { let refusal = failure(match platform::classify_failure(&error) { - platform::RhaiFailureCategory::ResourceExhausted => "function.resource-limit", - platform::RhaiFailureCategory::Other => "function.execution", + platform::RhaiFailureCategory::ResourceExhausted => "transform.resource-limit", + platform::RhaiFailureCategory::Other => "transform.execution", }); - if synthetic { CoordinatorError { message: format!("function {name} failed: {}", located(&function.definition.entrypoint, &error)), ..refusal } - .suggest(format!("Correct Function {name} in {} at the named position, or correct its synthetic inputs.", function.definition.source)) } + if synthetic { CoordinatorError { message: format!("Transform {name} failed: {}", located(&function.definition.entrypoint, &error)), ..refusal } + .suggest(format!("Correct Transform {name} in {} at the named position, or correct its synthetic inputs.", function.definition.source)) } else { refusal } })?; if holds_non_finite(&value, 0) { - let refusal = failure("function.execution"); + let refusal = failure("transform.execution"); return Err(if synthetic { - CoordinatorError { message: format!("function {name} returned NaN or an infinite number, which has no JSON form"), ..refusal } - .suggest(format!("Correct Function {name} so it never divides by zero or takes the square root of a negative number; test with is_finite first.")) + CoordinatorError { message: format!("Transform {name} returned NaN or an infinite number, which has no JSON form"), ..refusal } + .suggest(format!("Correct Transform {name} so it never divides by zero or takes the square root of a negative number; test with is_finite first.")) } else { refusal }); } - let value = rhai::serde::from_dynamic(&value).map_err(|_| failure("function.output"))?; + let value = rhai::serde::from_dynamic(&value).map_err(|_| failure("transform.output"))?; check_value(&value)?; if !function.output.is_valid(&value) { return Err(contract_failure( name, - "function.output", + "transform.output", &function.output, &value, synthetic, @@ -263,21 +263,21 @@ fn contract_failure( if !synthetic { return refusal; } - let role = if code == "function.input" { + let role = if code == "transform.input" { "named inputs" } else { "output" }; let rule = crate::definition::schema_refusal(schema, value).unwrap_or_default(); - CoordinatorError {message:format!("function {name} returned a value of class {}; its declared {role} schema refuses it{rule}",crate::definition::class(value)),..refusal} - .suggest(format!("Correct Function {name} or its synthetic input mappings to satisfy the named signature rule.")) + CoordinatorError {message:format!("Transform {name} returned a value of class {}; its declared {role} schema refuses it{rule}",crate::definition::class(value)),..refusal} + .suggest(format!("Correct Transform {name} or its synthetic input mappings to satisfy the named signature rule.")) } pub(crate) fn revision(function: &FunctionDefinition, source: &str) -> Result { let semantic = serde_json::json!({"runtime":function.runtime,"profile":function.profile,"capabilities":function.capabilities,"abi":function.abi,"entrypoint":function.entrypoint, "inputs":function.inputs.iter().map(|(name,schema)| (name,crate::definition::semantic_schema(schema))).collect::>(),"output":crate::definition::semantic_schema(&function.output),"limits":function.limits,"valueLimits":value_limits(),"sourceDigest":registry_platform_config::sha256_uri(source.as_bytes())}); let bytes = registry_platform_canonical_json::canonicalize_json(&semantic) - .map_err(|_| failure("function.definition"))?; + .map_err(|_| failure("transform.definition"))?; Ok(registry_platform_config::sha256_uri(&bytes)) } @@ -349,7 +349,7 @@ fn syntax_refusal(source: &str) -> String { .err() .map(|error| format!(": {}", error.err_type())) .unwrap_or_default(); - format!("function source has invalid or disabled syntax{reason}") + format!("Transform source has invalid or disabled syntax{reason}") } /// Bound structured values before conversion and after execution as well as @@ -376,23 +376,23 @@ pub(crate) fn check_value(value: &Value) -> Result<()> { } } if !walk(value, 0, &mut 0) { - return Err(failure("function.value-limit")); + return Err(failure("transform.value-limit")); } let bytes = registry_platform_canonical_json::canonicalize_json(value) - .map_err(|_| failure("function.json"))?; + .map_err(|_| failure("transform.json"))?; if bytes.len() > MAXIMUM_VALUE_BYTES { - return Err(failure("function.value-limit")); + return Err(failure("transform.value-limit")); } Ok(()) } fn failure(code: &'static str) -> CoordinatorError { CoordinatorError::new(code, match code { - "function.resource-limit" => "the function exceeded its operation, call-depth or value-size budget", - "function.value-limit" => "the structured value exceeded its size or depth budget", - "function.execution" => "the function could not evaluate its supplied values", - "function.source-limit" => "functions.rhai exceeds the 65536-byte source budget", - _ => "the pure function boundary refused the definition or value", + "transform.resource-limit" => "the Transform exceeded its operation, call-depth or value-size budget", + "transform.value-limit" => "the structured value exceeded its size or depth budget", + "transform.execution" => "the Transform could not evaluate its supplied values", + "transform.source-limit" => "functions.rhai exceeds the 65536-byte source budget", + _ => "the pure Transform boundary refused the definition or value", }).suggest("Inspect the named mapping and reduce bounded work or correct its declared arguments; values are omitted.") } @@ -424,7 +424,7 @@ fn register_pure_packages(engine: &mut Engine) { /// every host: IEEE 754 arithmetic (`sqrt` is correctly rounded), rounding, /// parsing and conversion. The package's libm functions (`sin`, `exp`, `ln`, /// `hypot` and the like) are left out because their last digits depend on the -/// host's math library, and Function results are recomputed when waits replay. +/// host's math library, and Transform results are recomputed when waits replay. fn register_deterministic_math(engine: &mut Engine) { engine .register_fn("PI", || std::f64::consts::PI) @@ -643,7 +643,7 @@ const INTERPRETER_CALLS: [&str; 6] = [ "type_of", ]; -/// The names a Function may call: every callable the pure profile registers, +/// The names a Transform may call: every callable the pure profile registers, /// listed once from a real engine so the list cannot drift from what runs. /// Operators, property accessors and the symbols the profile disables are not /// calls an author writes by name. @@ -668,7 +668,7 @@ pub(crate) fn helpers() -> &'static BTreeSet { } /// Array methods that take a function by value or by name. A string literal -/// given to one of them names a Function to call. `index_of` and `contains` +/// given to one of them names a Transform to call. `index_of` and `contains` /// are left out: they search for the string. const CALLBACK_METHODS: [&str; 16] = [ "for_each", @@ -694,7 +694,7 @@ const NAMING_CALLS: [&str; 2] = ["Fn", "is_def_fn"]; /// One finding for each call, in `name`'s source, to a name that is neither a /// profile helper nor a function the source defines. Calls are matched by -/// name alone, so a wrong argument count still fails when the Function runs. +/// name alone, so a wrong argument count still fails when the Transform runs. /// A string literal given to `Fn`, `is_def_fn` or an array method such as /// `map` is read as a function name. A method call is skipped when the source /// also uses its name as a map key or property, since it may call a function @@ -761,14 +761,14 @@ fn unknown_calls(function: &CompiledFunction) -> Vec { _ => "/".to_owned(), }; CoordinatorError::new( - "function.unknown-call", + "transform.unknown-call", format!( "`{callee}` is not available: it is neither a helper of {PURE_PROFILE} nor a function defined in {}", function.definition.source ), ) .at(&function.definition.source, location) - .suggest("Call a listed helper, such as trim, split and starts_with for strings or parse_int and abs for numbers, or define the function in the same source; `coordinatorctl explain functions` lists every helper.") + .suggest("Call a listed helper, such as trim, split and starts_with for strings or parse_int and abs for numbers, or define the function in the same source; `coordinatorctl explain transforms` lists every helper.") }) .collect() } @@ -831,8 +831,8 @@ const HELPER_NOTES: [&str; 2] = [ "A top-level const is not visible inside a function: read it as global::NAME, or pass it as an input.", ]; -/// What `coordinatorctl explain functions` reports: the profile, its -/// interpreter ABI and limits, and every helper a Function may call. +/// What `coordinatorctl explain transforms` reports: the profile, its +/// interpreter ABI and limits, and every helper a Transform may call. pub(crate) fn explain() -> Value { json!({ "profile": PURE_PROFILE, @@ -874,7 +874,7 @@ fn instant_refused() -> Box { } /// Structured JSON custody limits, shared by every host Operation boundary. -/// These are distinct from a pure Function's narrowed interpreter limits. +/// These are distinct from a pure Transform's narrowed interpreter limits. pub(crate) fn value_limits() -> Value { serde_json::json!({ "maximumBytes": MAXIMUM_VALUE_BYTES, diff --git a/crates/registry-coordinator/src/mapping_check.rs b/crates/registry-coordinator/src/mapping_check.rs index 942f4aa864..85cc38615d 100644 --- a/crates/registry-coordinator/src/mapping_check.rs +++ b/crates/registry-coordinator/src/mapping_check.rs @@ -70,17 +70,17 @@ fn check_step( if let Mapping::Function { function, inputs } = mapping { let signature = workflow.functions.get(function).ok_or_else(|| { authored( - "mapping.function", + "mapping.transform", &format!("{base}.function"), - "the named Function is not declared", - "Name one of the project's declared Functions.", + "the named Transform is not declared", + "Name one of the project's declared Transforms.", ) })?; if inputs.keys().ne(signature.inputs.keys()) { return Err(authored( - "mapping.function", + "mapping.transform", &format!("{base}.inputs"), - "the named Function inputs must match its declared signature exactly", + "the named Transform inputs must match its declared signature exactly", "Supply every declared input name once and remove undeclared names.", )); } @@ -192,7 +192,7 @@ fn schema_fits(target: &Value, read: &Read<'_>, field: &str) -> Result<()> { wanted.describe(), offered.describe() ), - "Select a value of the target type, or convert it with a typed Function.", + "Select a value of the target type, or convert it with a typed Transform.", )); } Ok(()) diff --git a/crates/registry-coordinator/src/problem.rs b/crates/registry-coordinator/src/problem.rs index f3ef8d6722..d94ab9f297 100644 --- a/crates/registry-coordinator/src/problem.rs +++ b/crates/registry-coordinator/src/problem.rs @@ -372,7 +372,7 @@ impl ProblemCode { } Self::CheckNotWaiting => "That step is not waiting.", Self::DefinitionRefused => { - "The workflow's workflow definition, one of its mappings or one of its functions refused the request." + "The workflow's workflow definition, one of its mappings or one of its Transforms refused the request." } Self::DeploymentActivationChanged => { "An apply changed the active packages after this service started. Restart it with the runtime file that apply used." @@ -529,7 +529,7 @@ pub(crate) fn for_error(code: &str) -> Option { } code if code.starts_with("definition.") || code.starts_with("mapping.") - || code.starts_with("function.") => + || code.starts_with("transform.") => { ProblemCode::DefinitionRefused } @@ -715,7 +715,7 @@ mod tests { ("deployment.refused", ProblemCode::DeploymentRefused), ("state-key-custody", ProblemCode::DeploymentRefused), ("mapping.branch", ProblemCode::DefinitionRefused), - ("function.arity", ProblemCode::DefinitionRefused), + ("transform.arity", ProblemCode::DefinitionRefused), ("mutation-uncertain", ProblemCode::MutationUncertain), ] { assert_eq!(for_error(internal), Some(public), "{internal}"); diff --git a/crates/registry-coordinator/src/protocol.rs b/crates/registry-coordinator/src/protocol.rs index 8ef9776dd0..49e2f14030 100644 --- a/crates/registry-coordinator/src/protocol.rs +++ b/crates/registry-coordinator/src/protocol.rs @@ -432,7 +432,7 @@ pub trait AdapterSet: Send + Sync { /// Observe a named completion of the exact accepted call. Both arguments /// are protected durable values. The host interprets bounded external - /// reads using the immutable Workflow Function, never an adapter script. + /// reads using the immutable Workflow Transform, never an adapter script. async fn observe_completion( &self, _request: &CallRequest, diff --git a/crates/registry-coordinator/src/read_in_force.rs b/crates/registry-coordinator/src/read_in_force.rs index eca262a4bb..0a19ca69a3 100644 --- a/crates/registry-coordinator/src/read_in_force.rs +++ b/crates/registry-coordinator/src/read_in_force.rs @@ -173,7 +173,7 @@ pub(crate) async fn read_in_force( } /// The subject fields a call names, when the mapping spells them out as a -/// literal or as nested fields. A subject built by a Function or read whole +/// literal or as nested fields. A subject built by a Transform or read whole /// from input is not known until the run. fn literal_subject_fields(input: &Mapping) -> Option> { let subject = match input { diff --git a/crates/registry-coordinator/src/scenarios.rs b/crates/registry-coordinator/src/scenarios.rs index 22261885f4..28b6c9405d 100644 --- a/crates/registry-coordinator/src/scenarios.rs +++ b/crates/registry-coordinator/src/scenarios.rs @@ -119,7 +119,7 @@ enum AuthoredReply { /// The product returned a package-declared, no-effect business refusal. /// A supported call takes its `onDeclaredRefusal` edge when it has one; /// otherwise the run stops as refused. An `external.command/v1` step - /// takes a `response` reply instead, which its interpretation Function + /// takes a `response` reply instead, which its interpretation Transform /// may turn into a declared refusal. DeclaredRefusal { /// The validated refusal code the package declares. @@ -132,9 +132,9 @@ enum AuthoredReply { code: LocalId, }, /// The provider answered an `external.command/v1` call with `value`. The - /// operation's pinned interpretation Function turns it into an accepted + /// operation's pinned interpretation Transform turns it into an accepted /// result, a declared refusal or an uncertain outcome, as it would at run - /// time. The status must be one the worker hands to that Function: a + /// time. The status must be one the worker hands to that Transform: a /// redirect, a 429 or a 5xx never reaches it, so a fixture models those /// with an `uncertain` or `retryable` reply. Response { @@ -210,7 +210,7 @@ enum AuthoredWait { value: ForeignValue, }, /// The host repeats the accepted external read and interprets these - /// synthetic typed responses under the completion's named Function. + /// synthetic typed responses under the completion's named Transform. Observations { /// One to 128 bounded response objects in observation order. #[cfg_attr(feature = "schema", schemars(length(min = 1, max = 128)))] @@ -939,7 +939,7 @@ fn execute(definition: &Definition, scenario: &Scenario) -> Result Result Result Result { terminal = Some(value); break; }, crate::protocol::CompletionObservation::Pending { .. } => { now += chrono::Duration::seconds(i64::from(*interval_seconds)); }, - _ => return Err(error("scenario.wait-observation", format!("/waits/{step}/responses/{index}"), "the pinned polling interpretation did not establish a valid observation", "Correct the interpretation Function and response correlation under the named completion contract.")), + _ => return Err(error("scenario.wait-observation", format!("/waits/{step}/responses/{index}"), "the pinned polling interpretation did not establish a valid observation", "Correct the interpretation Transform and response correlation under the named completion contract.")), } } if let Some(value) = terminal { @@ -1867,7 +1867,7 @@ fn disbursement_acceptance(value: &Value) -> Option String { } /// The status of a synthetic command response the worker would never hand to -/// the interpretation Function, with the reply that models what the worker +/// the interpretation Transform, with the reply that models what the worker /// does instead. The worker reads the status before any body, so a scenario -/// cannot show the Function reading a redirect, a 429 or a server failure. +/// cannot show the Transform reading a redirect, a 429 or a server failure. fn uninterpreted_status(response: &Value) -> Option<(String, &'static str)> { use crate::external_http::{command_status, CommandStatus}; let Some(status) = response diff --git a/crates/registry-coordinator/src/worker.rs b/crates/registry-coordinator/src/worker.rs index 4675f79121..e55e8f1fda 100644 --- a/crates/registry-coordinator/src/worker.rs +++ b/crates/registry-coordinator/src/worker.rs @@ -733,7 +733,7 @@ impl Worker { }, }; // A command's provider response becomes its step result only - // through the project's pinned interpretation Function. + // through the project's pinned interpretation Transform. let result = match result { CallOutcome::Success(response) if request.operation == crate::protocol::Operation::ExternalCommand => diff --git a/crates/registry-coordinator/tests/authored_project.rs b/crates/registry-coordinator/tests/authored_project.rs index 44e9355c97..ed49346dff 100644 --- a/crates/registry-coordinator/tests/authored_project.rs +++ b/crates/registry-coordinator/tests/authored_project.rs @@ -28,8 +28,8 @@ fn project() -> Value { "type": "finish", "outcome": "accepted", "output": { - "type": "function", - "function": "identity", + "type": "transform", + "transform": "identity", "inputs": { "arg0": { "type": "input" @@ -70,8 +70,8 @@ fn declared_refusal_project() -> Value { "type": "call", "operation": "invoke-breg-action", "input": { - "type": "function", - "function": "command", + "type": "transform", + "transform": "command", "inputs": { "arg0": { "type": "input" @@ -174,10 +174,10 @@ fn authored_project_converts_to_the_versioned_snapshot_abi() { fn project_check_keeps_a_positioned_duplicate_function_title_warning() { let root = tempfile::tempdir().unwrap(); let mut authored = declare_test_functions(&project()); - authored["functions"]["identity"]["label"] = json!("Identity function"); - let mut copy = authored["functions"]["identity"].clone(); + authored["transforms"]["identity"]["label"] = json!("Identity function"); + let mut copy = authored["transforms"]["identity"].clone(); copy["label"] = json!("identity function"); - authored["functions"]["identity-copy"] = copy; + authored["transforms"]["identity-copy"] = copy; let bytes = serde_json::to_vec(&authored).unwrap(); fs::write( root.path().join("functions.rhai"), @@ -191,10 +191,10 @@ fn project_check_keeps_a_positioned_duplicate_function_title_warning() { let finding = warnings .diagnostics() .iter() - .find(|diagnostic| diagnostic.code == "coordinator.project.duplicate-function-label") + .find(|diagnostic| diagnostic.code == "coordinator.project.duplicate-transform-label") .expect("the duplicate title warning survives project compilation"); - assert_eq!(finding.path, "/functions/identity-copy/label"); - assert_eq!(finding.related[0].path, "/functions/identity/label"); + assert_eq!(finding.path, "/transforms/identity-copy/label"); + assert_eq!(finding.related[0].path, "/transforms/identity/label"); assert!(finding.message.contains("`identity`")); assert!(finding.message.contains("`identity-copy`")); assert!(!finding.message.contains("Identity function")); @@ -204,10 +204,10 @@ fn project_check_keeps_a_positioned_duplicate_function_title_warning() { fn project_check_keeps_duplicate_title_warnings_beside_compile_errors() { let root = tempfile::tempdir().unwrap(); let mut authored = declare_test_functions(&project()); - authored["functions"]["identity"]["label"] = json!("Identity function"); - let mut copy = authored["functions"]["identity"].clone(); + authored["transforms"]["identity"]["label"] = json!("Identity function"); + let mut copy = authored["transforms"]["identity"].clone(); copy["label"] = json!("identity function"); - authored["functions"]["identity-copy"] = copy; + authored["transforms"]["identity-copy"] = copy; authored["workflow"]["steps"]["done"] = json!({ "type": "call", "operation": "missing-operation", @@ -220,7 +220,7 @@ fn project_check_keeps_duplicate_title_warnings_beside_compile_errors() { let error = authoring::parse_project(&path, fs::read(&path).unwrap()) .expect_err("the missing operation refuses compilation"); for code in [ - "coordinator.project.duplicate-function-label", + "coordinator.project.duplicate-transform-label", "coordinator.definition.operation", ] { assert!( @@ -237,7 +237,7 @@ fn project_check_keeps_duplicate_title_warnings_beside_compile_errors() { fn project_check_refuses_separator_lookalikes_in_the_function_namespace() { let root = tempfile::tempdir().unwrap(); let mut authored = project(); - authored["functions"] = json!({ + authored["transforms"] = json!({ "identity-fn": { "runtime": "rhai", "source": "functions.rhai", @@ -259,10 +259,10 @@ fn project_check_refuses_separator_lookalikes_in_the_function_namespace() { let finding = error .diagnostics .iter() - .find(|diagnostic| diagnostic.code == "coordinator.project.function-id-collision") + .find(|diagnostic| diagnostic.code == "coordinator.project.transform-id-collision") .expect("the function collision has its own finding"); - assert_eq!(finding.path, "/functions/identity_fn"); - assert_eq!(finding.related[0].path, "/functions/identity-fn"); + assert_eq!(finding.path, "/transforms/identity_fn"); + assert_eq!(finding.related[0].path, "/transforms/identity-fn"); assert!(finding.message.contains("`identity-fn`")); assert!(finding.message.contains("`identity_fn`")); } @@ -433,7 +433,7 @@ fn declared_refusal_is_available_only_on_its_edge_and_not_after_a_mixed_join() { .remove("refused"); joined["workflow"]["steps"]["joined"] = json!({ "type":"finish", "outcome":"joined", "output":{ - "type":"function", "function":"identity", "inputs": {"arg0": {"type":"step", "step":"act"}} + "type":"transform", "transform":"identity", "inputs": {"arg0": {"type":"step", "step":"act"}} } }); joined["workflow"]["outcomes"] = json!({"joined":{}}); @@ -569,7 +569,7 @@ fn reads_and_evaluations_accept_on_failure_but_mutations_refuse_it() { "apiVersion":"id.registrystack.org/formats/coordinator/project/v1alpha1", "kind":"CoordinatorProject", "project":{"id":"evaluation-failure-route","version":"1"}, - "functions":{"command":{ + "transforms":{"command":{ "runtime":"rhai","source":"functions.rhai","entrypoint":"command", "inputs":{"arg0":{"type":"object"}}, "output":{"operationInput":"evaluate"} @@ -579,7 +579,7 @@ fn reads_and_evaluations_accept_on_failure_but_mutations_refuse_it() { "input":{"type":"object"},"deadlineSeconds":60,"start":"act", "steps":{ "act":{"type":"call","operation":"evaluate", - "input":{"type":"function","function":"command","inputs":{"arg0":{"type":"input"}}}, + "input":{"type":"transform","transform":"command","inputs":{"arg0":{"type":"input"}}}, "next":"accepted","onFailure":"refused"}, "accepted":{"type":"finish","outcome":"accepted"}, "refused":{"type":"finish","outcome":"refused"} @@ -636,7 +636,7 @@ fn a_failure_route_has_no_call_output_and_names_a_declared_step() { project["workflow"]["steps"]["refused"] = json!({ "type":"finish", "outcome":"refused", - "output":{"type":"function","function":"identity","inputs":{"arg0":{"type":"step","step":"act"}}} + "output":{"type":"transform","transform":"identity","inputs":{"arg0":{"type":"step","step":"act"}}} }); project["workflow"]["outcomes"]["refused"] = json!({}); write_project(root.path(), &project, source); @@ -706,7 +706,7 @@ fn function_compile_diagnostics_keep_the_function_file_and_position() { .err() .expect("must refuse syntax"); let finding = &error.diagnostics[0]; - assert_eq!(finding.code, "coordinator.function.definition"); + assert_eq!(finding.code, "coordinator.transform.definition"); assert_eq!(finding.path, ""); let source = finding.source.as_ref().unwrap(); assert!(source.file.ends_with("functions.rhai")); @@ -746,7 +746,7 @@ fn linked_function_source_refusal_points_to_the_authored_reference() { .err() .expect("a linked source must refuse"); let finding = error.diagnostics.first().expect("a positioned finding"); - assert_eq!(finding.path, "/functions/identity/source"); + assert_eq!(finding.path, "/transforms/identity/source"); assert!(finding .source .as_ref() @@ -770,7 +770,7 @@ fn missing_function_source_keeps_the_operational_exit_and_authored_position() { .err() .expect("missing source must refuse"); assert_eq!(error.exit_code, 3); - assert_eq!(error.diagnostics[0].path, "/functions/identity/source"); + assert_eq!(error.diagnostics[0].path, "/transforms/identity/source"); assert!(error.diagnostics[0] .source .as_ref() @@ -786,7 +786,7 @@ fn execution_member_diagnostics_preserve_authored_step_names() { let mut project = project(); project["workflow"]["start"] = json!(name); project["workflow"]["steps"] = json!({name: { - "type":"wait-until", "waitUntil":{"type":"function", "function":"identity", "inputs": {"arg0": {"type":"input"}}}, + "type":"wait-until", "waitUntil":{"type":"transform", "transform":"identity", "inputs": {"arg0": {"type":"input"}}}, "next":"missing" }}); write_project( @@ -883,7 +883,7 @@ fn project_schema_matches_local_keys_bounds_and_foreign_schema_members() { assert!(schema["properties"].get("functionsFile").is_none()); for (pointer, minimum, maximum) in [ ("/properties/operations", 0, 64), - ("/properties/functions", 0, 128), + ("/properties/transforms", 0, 128), ("/properties/types", 0, 128), ("/$defs/AuthoredWorkflow/properties/steps", 1, 64), ("/$defs/AuthoredWorkflow/properties/outcomes", 1, 64), @@ -904,11 +904,11 @@ fn project_schema_matches_local_keys_bounds_and_foreign_schema_members() { .collect::>(); assert_eq!( tags, - ["function", "fields", "compare", "input", "step", "literal"] + ["transform", "fields", "compare", "input", "step", "literal"] ); let function = variants .iter() - .find(|variant| variant["properties"]["type"]["const"] == "function") + .find(|variant| variant["properties"]["type"]["const"] == "transform") .unwrap(); assert_eq!(function["properties"]["inputs"]["maxProperties"], 16); assert_eq!(schema["$defs"]["Fields"]["maxProperties"], 64); @@ -1111,9 +1111,9 @@ fn authoring_schemas_describe_every_member_and_form() { fn declare_test_functions(project: &Value) -> Value { fn mapping(value: &Value, functions: &mut serde_json::Map) { if let Some(object) = value.as_object() { - if object.get("type") == Some(&json!("function")) { + if object.get("type") == Some(&json!("transform")) { if let (Some(name), Some(inputs)) = ( - object.get("function").and_then(Value::as_str), + object.get("transform").and_then(Value::as_str), object.get("inputs").and_then(Value::as_object), ) { let signature = inputs @@ -1135,6 +1135,6 @@ fn declare_test_functions(project: &Value) -> Value { let mut project = project.clone(); let mut functions = serde_json::Map::new(); mapping(&project["workflow"]["steps"], &mut functions); - project["functions"] = Value::Object(functions); + project["transforms"] = Value::Object(functions); project } diff --git a/crates/registry-coordinator/tests/authoring.rs b/crates/registry-coordinator/tests/authoring.rs index 5dd36350b5..1244874aff 100644 --- a/crates/registry-coordinator/tests/authoring.rs +++ b/crates/registry-coordinator/tests/authoring.rs @@ -34,14 +34,14 @@ fn authored_value(source: &str) -> Value { } fn computed_workflow() -> String { let mut workflow = authored_value(WORKFLOW); - workflow["functions"]["send-after"] = json!({"runtime":"rhai","source":"functions.rhai","entrypoint":"send_after", + workflow["transforms"]["send-after"] = json!({"runtime":"rhai","source":"functions.rhai","entrypoint":"send_after", "inputs":{"input":{"typeRef":"workflow-input"}},"output":{"type":"string","format":"date-time"}}); - workflow["functions"]["read-request"] = json!({"runtime":"rhai","source":"functions.rhai","entrypoint":"read_request", + workflow["transforms"]["read-request"] = json!({"runtime":"rhai","source":"functions.rhai","entrypoint":"read_request", "inputs":{"input":{"typeRef":"workflow-input"}},"output":{"operationInput":"applications-read-record"}}); workflow["workflow"]["steps"]["due"]["waitUntil"] = - json!({"type":"function","function":"send-after","inputs":{"input":{"type":"input"}}}); + json!({"type":"transform","transform":"send-after","inputs":{"input":{"type":"input"}}}); workflow["workflow"]["steps"]["read-application"]["input"] = - json!({"type":"function","function":"read-request","inputs":{"input":{"type":"input"}}}); + json!({"type":"transform","transform":"read-request","inputs":{"input":{"type":"input"}}}); workflow.to_string() } fn computed_source() -> String { @@ -69,6 +69,44 @@ fn refused(result: registry_coordinator::Result) -> CoordinatorError } } +#[test] +fn authored_transforms_use_their_own_vocabulary_but_keep_the_frozen_snapshot_format() { + let authored = authored_value(WORKFLOW); + assert!(authored["transforms"]["notice-route"].is_object()); + assert!(authored.get("functions").is_none()); + let definition = fixture(); + let report = definition.explain().unwrap(); + assert!(report["transforms"]["notice-route"].is_object()); + assert!(report.get("functions").is_none()); + let permission = report["steps"] + .as_array() + .unwrap() + .iter() + .find(|step| step["id"] == "permission") + .unwrap(); + assert_eq!(permission["mapping"]["transform"], "notice-route"); + assert!(permission["mapping"].get("function").is_none()); + let snapshot = definition.snapshot().unwrap(); + let frozen: Value = serde_json::from_str(&snapshot).unwrap(); + assert!(frozen["workflow"]["functions"]["notice-route"].is_object()); + assert_eq!( + frozen["workflow"]["steps"]["permission"]["choose"]["function"], + "notice-route" + ); + let restored = Definition::from_snapshot(&snapshot).unwrap(); + assert_eq!(restored.snapshot().unwrap(), snapshot); + assert_eq!(restored.digest, definition.digest); +} + +#[test] +fn retired_function_declaration_points_to_transforms() { + let legacy = WORKFLOW.replace("\ntransforms:", "\nfunctions:"); + let error = refused(load(&legacy, SOURCE)); + assert!(error.diagnostics.iter().any(|diagnostic| { + diagnostic.path == "/functions" && diagnostic.suggested_action.contains("transforms") + })); +} + #[test] fn synthetic_fixture_maps_current_permission_and_receipt() { let definition = fixture(); @@ -121,14 +159,14 @@ fn synthetic_fixture_maps_current_permission_and_receipt() { fn shared_mapping_is_validated_only_for_the_executing_branch() { let workflow = json!({ "apiVersion":"id.registrystack.org/formats/coordinator/project/v1alpha1","kind":"CoordinatorProject","project":{"id":"shared-mapping","version":"1"}, - "functions":{ + "transforms":{ "branch":{"runtime":"rhai","source":"functions.rhai","entrypoint":"branch","inputs":{"input":{"type":"object"}},"output":{"type":"string","enum":["number","text"]}}, "value":{"runtime":"rhai","source":"functions.rhai","entrypoint":"value","inputs":{"input":{"type":"object"}},"output":{}} },"workflow":{"input":{"type":"object","required":["choice","value"],"properties":{"choice":{"enum":["number","text"]},"value":{}},"additionalProperties":false},"deadlineSeconds":3600,"start":"select", "steps":{ - "select":{"type":"choose","choose":{"type":"function","function":"branch","inputs":{"input":{"type":"input"}}},"cases":{"number":"finish-number","text":"finish-text"}}, - "finish-number":{"type":"finish","outcome":"number","output":{"type":"function","function":"value","inputs":{"input":{"type":"input"}}}}, - "finish-text":{"type":"finish","outcome":"text","output":{"type":"function","function":"value","inputs":{"input":{"type":"input"}}}} + "select":{"type":"choose","choose":{"type":"transform","transform":"branch","inputs":{"input":{"type":"input"}}},"cases":{"number":"finish-number","text":"finish-text"}}, + "finish-number":{"type":"finish","outcome":"number","output":{"type":"transform","transform":"value","inputs":{"input":{"type":"input"}}}}, + "finish-text":{"type":"finish","outcome":"text","output":{"type":"transform","transform":"value","inputs":{"input":{"type":"input"}}}} },"outcomes":{"number":{"type":"integer"},"text":{"type":"string"}}} }); let definition = load( @@ -283,7 +321,10 @@ fn bad_graphs_and_whole_value_references_refuse() { json!("arbitrary-http"), ), ("/workflow/deadlineSeconds", json!("é")), - ("/functions/notice-route/source", json!("../functions.rhai")), + ( + "/transforms/notice-route/source", + json!("../functions.rhai"), + ), ("/workflow/deadlineSeconds", json!("${DEADLINE}")), ] { let mut workflow = base.clone(); @@ -345,7 +386,7 @@ fn branch_timestamp_schema_and_missing_values_refuse_without_values() { let error = definition .evaluate("permission", &input(), &outputs) .unwrap_err(); - assert_eq!(error.code, "function.output"); + assert_eq!(error.code, "transform.output"); assert!(!error.to_string().contains(CANARY)); let definition = fixture(); assert_eq!( @@ -375,7 +416,7 @@ fn branch_timestamp_schema_and_missing_values_refuse_without_values() { .initial_due(&input(), instant("2026-10-09T09:00:00Z")) .unwrap_err() .code, - "function.output" + "transform.output" ); } @@ -390,7 +431,7 @@ fn pure_profile_has_no_clock_sleep_or_io_and_limits_computation() { &source.replace("input.sendAfter", expression), )); assert_eq!( - error.code, "coordinator.function.unknown-call", + error.code, "coordinator.transform.unknown-call", "{expression}" ); } @@ -405,7 +446,7 @@ fn pure_profile_has_no_clock_sleep_or_io_and_limits_computation() { .evaluate("due", &input(), &BTreeMap::new()) .unwrap_err() .code, - "function.resource-limit" + "transform.resource-limit" ); } let definition = load( @@ -636,14 +677,14 @@ fn resource_limits_include_recursion_input_values_and_non_object_commands() { .evaluate("due", &input(), &BTreeMap::new()) .unwrap_err() .code, - "function.resource-limit" + "transform.resource-limit" ); let definition = fixture(); let mut excessive = input(); excessive["sendAfter"] = json!("x".repeat(16385)); assert_eq!( definition.validate_input(&excessive).unwrap_err().code, - "function.value-limit" + "transform.value-limit" ); let definition = load( &workflow, @@ -658,7 +699,7 @@ fn resource_limits_include_recursion_input_values_and_non_object_commands() { .evaluate("read-application", &input(), &BTreeMap::new()) .unwrap_err() .code, - "function.output" + "transform.output" ); } @@ -721,10 +762,10 @@ fn authoring_diagnostics_locate_graph_reference_and_functions_without_runtime_va &source.replace("fn send_after(input)", "fn send_after(input, extra)"), )); // The step that calls the function is where the mismatch is placed. - assert_eq!(error.code, "coordinator.function.definition"); + assert_eq!(error.code, "coordinator.transform.definition"); assert_eq!( error.field.as_deref(), - Some("/functions/send-after/entrypoint") + Some("/transforms/send-after/entrypoint") ); assert!(error.diagnostics[0] .source diff --git a/crates/registry-coordinator/tests/authoring_findings.rs b/crates/registry-coordinator/tests/authoring_findings.rs index 61298639b1..84213d3742 100644 --- a/crates/registry-coordinator/tests/authoring_findings.rs +++ b/crates/registry-coordinator/tests/authoring_findings.rs @@ -172,7 +172,7 @@ fn a_function_returning_an_undeclared_label_is_reported_at_its_step_by_check_and let findings = check["diagnostics"].as_array().unwrap(); assert_eq!(findings.len(), 1, "{check}"); let finding = &findings[0]; - assert_eq!(finding["code"], "coordinator.function.output"); + assert_eq!(finding["code"], "coordinator.transform.output"); assert_eq!(finding["path"], "/workflow/steps/permission/choose"); assert!(finding["source"]["file"] .as_str() @@ -181,7 +181,7 @@ fn a_function_returning_an_undeclared_label_is_reported_at_its_step_by_check_and assert_eq!(finding["source"]["line"], workflow_line("choose:") + 1); let message = finding["message"].as_str().unwrap(); for expected in [ - "function notice-route returned a value of class string", + "Transform notice-route returned a value of class string", "declared output schema refuses it", ] .into_iter() @@ -215,14 +215,14 @@ fn a_rhai_failure_names_its_kind_and_position_offline() { let (check, test) = refused(&root); assert_eq!(check["diagnostics"], test["diagnostics"], "{check}\n{test}"); let finding = &check["diagnostics"][0]; - assert_eq!(finding["code"], "coordinator.function.execution"); + assert_eq!(finding["code"], "coordinator.transform.execution"); assert_eq!(finding["path"], "/workflow/steps/permission/choose"); assert_eq!(finding["source"]["line"], workflow_line("choose:") + 1); let message = finding["message"].as_str().unwrap(); // The kind of failure and its position in functions.rhai, never the // engine's own words, which may repeat the values it was given. assert!( - message.contains("function notice-route failed: a property is missing in function notice_route at line 6, column "), + message.contains("Transform notice-route failed: a property is missing in function notice_route at line 6, column "), "{message}" ); assert!(!message.contains("member"), "{message}"); @@ -245,10 +245,10 @@ fn a_thrown_rhai_error_names_its_kind_and_position_but_no_value() { let (check, test) = refused(&root); assert_eq!(check["diagnostics"], test["diagnostics"], "{check}\n{test}"); let finding = &check["diagnostics"][0]; - assert_eq!(finding["code"], "coordinator.function.execution"); + assert_eq!(finding["code"], "coordinator.transform.execution"); let message = finding["message"].as_str().unwrap(); assert!( - message.contains("function notice-route failed: an error was thrown in function notice_route at line 6, column "), + message.contains("Transform notice-route failed: an error was thrown in function notice_route at line 6, column "), "{message}" ); assert_unrepeated(&root, &[MARKER, RECORD_ID]); @@ -273,7 +273,7 @@ fn a_failure_in_a_called_function_is_placed_in_that_function() { let message = check["diagnostics"][0]["message"].as_str().unwrap(); assert!( message.contains( - "function notice-route failed: an error was thrown in function helper at line 10, column 5" + "Transform notice-route failed: an error was thrown in function helper at line 10, column 5" ), "{message}" ); @@ -548,18 +548,18 @@ fn a_refused_step_value_is_named_by_its_class_and_rule_never_by_value() { let mut functions = FUNCTIONS.to_owned(); let expected = match kind { "wait" => { - workflow["functions"]["send-after"] = json!({"runtime":"rhai","source":"functions.rhai","entrypoint":"send_after","inputs":{"input":{"typeRef":"workflow-input"}},"output":{"type":"string"}}); - workflow["workflow"]["steps"]["due"]["waitUntil"] = json!({"type":"function","function":"send-after","inputs":{"input":{"type":"input"}}}); + workflow["transforms"]["send-after"] = json!({"runtime":"rhai","source":"functions.rhai","entrypoint":"send_after","inputs":{"input":{"typeRef":"workflow-input"}},"output":{"type":"string"}}); + workflow["workflow"]["steps"]["due"]["waitUntil"] = json!({"type":"transform","transform":"send-after","inputs":{"input":{"type":"input"}}}); functions.push_str(&format!( "\nfn send_after(args) {{ \"{MARKER}\" + args.input.applicationId }}" )); - "function send-after returned a value of class string; expected an RFC 3339 instant with an offset" + "Transform send-after returned a value of class string; expected an RFC 3339 instant with an offset" } "finish" => { - workflow["functions"]["accepted-output"] = json!({"runtime":"rhai","source":"functions.rhai","entrypoint":"accepted_output","inputs":{"input":{"typeRef":"workflow-input"}},"output":{"type":"object"}}); - workflow["workflow"]["steps"]["accepted"]["output"] = json!({"type":"function","function":"accepted-output","inputs":{"input":{"type":"input"}}}); + workflow["transforms"]["accepted-output"] = json!({"runtime":"rhai","source":"functions.rhai","entrypoint":"accepted_output","inputs":{"input":{"typeRef":"workflow-input"}},"output":{"type":"object"}}); + workflow["workflow"]["steps"]["accepted"]["output"] = json!({"type":"transform","transform":"accepted-output","inputs":{"input":{"type":"input"}}}); functions.push_str(&format!("\nfn accepted_output(args) {{ #{{messageId: \"{MARKER}\" + args.input.applicationId}} }}")); - "function accepted-output returned a value of class object; the message-accepted outcome schema refuses it at /messageId by its rule /properties/messageId/format" + "Transform accepted-output returned a value of class object; the message-accepted outcome schema refuses it at /messageId by its rule /properties/messageId/format" } _ => { fs::write( @@ -747,13 +747,13 @@ fn a_connection_name_is_bound_at_deployment_and_changes_the_semantic_revision() #[test] fn an_unknown_function_is_reported_at_its_step_with_the_declared_functions() { let mut workflow = authored_value(); - workflow["workflow"]["steps"]["notify"]["input"]["function"] = json!("notice-reqest"); + workflow["workflow"]["steps"]["notify"]["input"]["transform"] = json!("notice-reqest"); let findings = checked_value(workflow); assert_eq!(findings.len(), 1); finding( &findings, - "/workflow/steps/notify/input/function", - "coordinator.mapping.function", + "/workflow/steps/notify/input/transform", + "coordinator.mapping.transform", &["notice-reqest", "notice-request", "notice-route"], ); } @@ -770,8 +770,8 @@ fn a_function_called_with_the_wrong_inputs_is_reported_at_its_step() { finding( &findings, "/workflow/steps/notify/input/inputs", - "coordinator.mapping.function", - &["named Function inputs", "signature"], + "coordinator.mapping.transform", + &["named Transform inputs", "signature"], ); } @@ -855,7 +855,7 @@ fn authored_semantic_errors_and_warnings_share_one_file_budget() { fn check_reports_every_independent_error_in_one_run() { let mut workflow = authored_value(); workflow["workflow"]["start"] = json!("begin"); - workflow["workflow"]["steps"]["permission"]["choose"]["function"] = json!("notice-rout"); + workflow["workflow"]["steps"]["permission"]["choose"]["transform"] = json!("notice-rout"); workflow["workflow"]["steps"]["skipped"]["outcome"] = json!("no-permission"); let findings = checked_value(workflow); let mut paths = findings @@ -868,7 +868,7 @@ fn check_reports_every_independent_error_in_one_run() { [ "/workflow/outcomes/no-current-permission", "/workflow/start", - "/workflow/steps/permission/choose/function", + "/workflow/steps/permission/choose/transform", "/workflow/steps/skipped/outcome" ], "{findings:#?}" diff --git a/crates/registry-coordinator/tests/breg_action_native.rs b/crates/registry-coordinator/tests/breg_action_native.rs index d0c6dc75cd..cf80d52ccb 100644 --- a/crates/registry-coordinator/tests/breg_action_native.rs +++ b/crates/registry-coordinator/tests/breg_action_native.rs @@ -390,7 +390,7 @@ types: operations: act: {uses: breg.invoke-action/v1, connection: applications, action: {contract: source, id: update-item}} notify: {uses: messaging.submit-message/v1, connection: notices} -functions: +transforms: action_request: runtime: rhai source: functions.rhai @@ -417,17 +417,17 @@ workflow: act: type: call operation: act - input: {type: function, function: action_request, inputs: {input: {type: input}}} + input: {type: transform, transform: action_request, inputs: {input: {type: input}}} next: notify notify: type: call operation: notify - input: {type: function, function: notice_request, inputs: {action: {type: step, step: act}}} + input: {type: transform, transform: notice_request, inputs: {action: {type: step, step: act}}} next: done done: type: finish outcome: accepted - output: {type: function, function: result, inputs: {action: {type: step, step: act}, notice: {type: step, step: notify}}} + output: {type: transform, transform: result, inputs: {action: {type: step, step: act}, notice: {type: step, step: notify}}} outcomes: accepted: {typeRef: accepted-output} "#).unwrap(); diff --git a/crates/registry-coordinator/tests/canonical_model.rs b/crates/registry-coordinator/tests/canonical_model.rs index 69c54e5720..34ccf333af 100644 --- a/crates/registry-coordinator/tests/canonical_model.rs +++ b/crates/registry-coordinator/tests/canonical_model.rs @@ -10,10 +10,10 @@ fn project() -> Value { "project": {"id":"typed-workflow","version":"1"}, "types": {"request": {"type":"object","additionalProperties":false,"required":["text"], "properties":{"text":{"type":"string"}}}}, - "functions": {"render": {"runtime":"rhai","source":"functions.rhai","entrypoint":"render", + "transforms": {"render": {"runtime":"rhai","source":"functions.rhai","entrypoint":"render", "inputs":{"request":{"typeRef":"request"}},"output":{"type":"string"}}}, "workflow": {"input":{"typeRef":"request"},"deadlineSeconds":3600,"start":"done", - "steps":{"done":{"type":"finish","outcome":"rendered","output":{"type":"function","function":"render","inputs":{"request":{"type":"input"}}}}}, + "steps":{"done":{"type":"finish","outcome":"rendered","output":{"type":"transform","transform":"render","inputs":{"request":{"type":"input"}}}}}, "outcomes":{"rendered":{"type":"string"}}} }) } @@ -57,7 +57,7 @@ fn named_function_inputs_are_typed_and_the_snapshot_restores_without_sources() { let error = definition .evaluate("done", &json!({"text":42}), &BTreeMap::new()) .unwrap_err(); - assert_eq!(error.code, "function.input"); + assert_eq!(error.code, "transform.input"); assert!(!error.message.contains("42")); } @@ -69,10 +69,10 @@ fn presentation_version_and_unreferenced_definitions_do_not_change_workflow_revi edited["project"]["description"] = json!("Shows a text."); edited["project"]["version"] = json!("next"); edited["workflow"]["steps"]["done"]["label"] = json!("Show the text"); - edited["functions"]["render"]["label"] = json!("Render a notice"); + edited["transforms"]["render"]["label"] = json!("Render a notice"); edited["types"]["request"]["properties"]["text"]["description"] = json!("Public text"); edited["types"]["unrelated"] = json!({"type":"integer"}); - edited["functions"]["unrelated"] = json!({"runtime":"rhai","source":"functions.rhai","entrypoint":"render", + edited["transforms"]["unrelated"] = json!({"runtime":"rhai","source":"functions.rhai","entrypoint":"render", "inputs":{"ignored":{"type":"integer"}},"output":{"type":"string"}}); let edited = load(&edited, SOURCE).unwrap(); assert_eq!(initial.digest, edited.digest); @@ -150,14 +150,14 @@ fn an_event_trigger_label_and_description_do_not_change_workflow_revision() { fn a_title_is_refused_with_label_as_its_replacement() { for (pointer, set) in [ ("/title", "project"), - ("/functions/render/title", "function"), + ("/transforms/render/title", "transform"), ("/workflow/steps/done/title", "step"), ("/operations/read-job/title", "operation"), ] { let mut edited = project(); match set { "project" => edited["title"] = json!("Readable workflow"), - "function" => edited["functions"]["render"]["title"] = json!("Render a notice"), + "transform" => edited["transforms"]["render"]["title"] = json!("Render a notice"), "operation" => { edited["operations"] = json!({"read-job":{"title":"Read the job","uses":"external.get/v1","connection":"jobs"}}); } @@ -185,11 +185,11 @@ fn changed_function_code_or_limits_changes_workflow_revision() { .digest ); let mut edited = project(); - edited["functions"]["render"]["limits"] = json!({"operations":500}); + edited["transforms"]["render"]["limits"] = json!({"operations":500}); let edited = load(&edited, SOURCE).unwrap(); assert_ne!(initial.digest, edited.digest); assert_eq!( - edited.explain().unwrap()["functions"]["render"]["limits"]["operations"], + edited.explain().unwrap()["transforms"]["render"]["limits"]["operations"], 500 ); } @@ -207,7 +207,7 @@ fn signature_names_and_closed_output_are_enforced_without_rendering_values() { let error = definition .evaluate("done", &json!({"text":"private-canary"}), &BTreeMap::new()) .unwrap_err(); - assert_eq!(error.code, "function.output"); + assert_eq!(error.code, "transform.output"); assert!(!error.message.contains("private-canary")); } @@ -225,8 +225,8 @@ fn schema_references_resolve_nested_properties_and_preserve_reference_sites() { ); assert!(references["/workflow/input/typeRef"]["source"]["line"].is_number()); assert_eq!( - references["/workflow/steps/done/output/function"]["target"], - "/functions/render" + references["/workflow/steps/done/output/transform"]["target"], + "/transforms/render" ); } @@ -255,13 +255,13 @@ fn schema_cycles_mixtures_and_undeclared_references_point_to_authored_fields() { #[test] fn the_default_profile_has_no_clock_and_narrowing_cannot_widen_it() { let error = refused(&project(), "fn render(inputs) { timestamp().to_string() }"); - assert_eq!(error.code, "coordinator.function.unknown-call"); + assert_eq!(error.code, "coordinator.transform.unknown-call"); let mut edited = project(); - edited["functions"]["render"]["limits"] = json!({"operations":100001}); + edited["transforms"]["render"]["limits"] = json!({"operations":100001}); let error = refused(&edited, SOURCE); assert_eq!( error.diagnostics[0].path, - "/functions/render/limits/operations" + "/transforms/render/limits/operations" ); assert_eq!(error.diagnostics[0].code, "config.out-of-range"); } @@ -287,7 +287,7 @@ fn poll_completion_uses_base_schemas_then_resolves_typed_terminal_output() { let mut edited = project(); edited["operations"] = json!({"read-job":{"uses":"external.get/v1","connection":"jobs","responseSchema":{"type":"object","required":["status","body"],"additionalProperties":false,"properties":{"status":{"type":"integer"},"body":{"type":"object"}}}, "completions":{"terminal":{"type":"bounded-poll","interpret":"observe","intervalSeconds":30}}}}); - edited["functions"] = json!({"observe":{"runtime":"rhai","source":"functions.rhai","entrypoint":"observe", + edited["transforms"] = json!({"observe":{"runtime":"rhai","source":"functions.rhai","entrypoint":"observe", "inputs":{"command":{"operationInput":"read-job"},"response":{"operationOutput":"read-job"}},"output":{"oneOf":[ {"type":"object","additionalProperties":false,"required":["state"],"properties":{"state":{"type":"string","const":"pending"}}}, {"type":"object","additionalProperties":false,"required":["state","result"],"properties":{"state":{"type":"string","const":"complete"},"result":{"type":"string"}}}, @@ -341,7 +341,7 @@ fn poll_completion_uses_base_schemas_then_resolves_typed_terminal_output() { assert!(definition .validate_outcome("terminal", &json!({"state":"pending"})) .is_err()); - edited["functions"]["observe"]["output"]["oneOf"][1]["title"] = + edited["transforms"]["observe"]["output"]["oneOf"][1]["title"] = json!("A successful job observation"); let retitled = load(&edited, "fn observe(inputs) { #{state: \"pending\"} }").unwrap(); assert_eq!(definition.digest, retitled.digest); @@ -350,7 +350,7 @@ fn poll_completion_uses_base_schemas_then_resolves_typed_terminal_output() { "type":"object","required":["id"],"additionalProperties":false, "properties":{"id":{"$ref":"#/$defs/identifier"}} }); - edited["functions"]["observe"]["output"]["oneOf"][1]["properties"]["result"] = + edited["transforms"]["observe"]["output"]["oneOf"][1]["properties"]["result"] = json!({"typeRef":"job-result"}); let referenced = load(&edited, "fn observe(inputs) { #{state: \"pending\"} }").unwrap(); referenced @@ -371,10 +371,10 @@ fn poll_completion_uses_base_schemas_then_resolves_typed_terminal_output() { restored .validate_outcome("terminal", &json!({"state":"refused","code":"job-failed"})) .unwrap(); - edited["functions"]["observe"]["output"] = + edited["transforms"]["observe"]["output"] = json!({"completionOutput":{"operation":"read-job","name":"terminal"}}); let error = refused(&edited, "fn observe(inputs) { #{state: \"pending\"} }"); - assert_eq!(error.diagnostics[0].path, "/functions/observe/output"); + assert_eq!(error.diagnostics[0].path, "/transforms/observe/output"); } #[cfg(feature = "schema")] @@ -397,7 +397,7 @@ fn whole_schema_references_rebase_local_definitions_when_embedded() { "$defs":{"text":{"type":"string","minLength":2}}, "properties":{"value":{"$ref":"#/$defs/text"}}}); edited["types"]["request"]["properties"]["text"] = json!({"typeRef":"message"}); - edited["functions"]["render"]["output"] = json!({"typeRef":"message"}); + edited["transforms"]["render"]["output"] = json!({"typeRef":"message"}); edited["workflow"]["outcomes"]["rendered"] = json!({"typeRef":"message"}); let definition = load(&edited, SOURCE).unwrap(); assert!(definition @@ -416,7 +416,7 @@ fn whole_schema_references_rebase_local_definitions_when_embedded() { #[test] fn function_source_assets_cannot_escape_the_project() { let mut edited = project(); - edited["functions"]["render"]["source"] = json!("../outside.rhai"); + edited["transforms"]["render"]["source"] = json!("../outside.rhai"); let error = refused(&edited, SOURCE); assert!(error.message.contains("relative path")); } diff --git a/crates/registry-coordinator/tests/cli_authoring.rs b/crates/registry-coordinator/tests/cli_authoring.rs index 81df08b754..fc36973895 100644 --- a/crates/registry-coordinator/tests/cli_authoring.rs +++ b/crates/registry-coordinator/tests/cli_authoring.rs @@ -201,7 +201,7 @@ fn init_check_and_explain_work_without_database_or_signing_keys() { ]); assert!(explained.status.success()); let result: Value = serde_json::from_slice(&explained.stdout).unwrap(); - assert!(result["functions"] + assert!(result["transforms"] .as_object() .unwrap() .values() diff --git a/crates/registry-coordinator/tests/external_command_project.rs b/crates/registry-coordinator/tests/external_command_project.rs index a2dd79412d..16b5ef7a7b 100644 --- a/crates/registry-coordinator/tests/external_command_project.rs +++ b/crates/registry-coordinator/tests/external_command_project.rs @@ -249,17 +249,17 @@ fn the_interpretation_takes_the_command_and_its_bounded_response() { #[test] fn the_interpretation_declares_accepted_and_only_known_states() { let findings = refused(&[("const: accepted", "const: complete")]); - finding(&findings, "/functions/bill-outcome/output", &["accepted"]); + finding(&findings, "/transforms/bill-outcome/output", &["accepted"]); let findings = refused(&[("enum: [account-closed]", "minLength: 1")]); finding( &findings, - "/functions/bill-outcome/output", + "/transforms/bill-outcome/output", &["closed enum"], ); let findings = refused(&[("const: uncertain", "const: pending")]); - finding(&findings, "/functions/bill-outcome/output", &["uncertain"]); + finding(&findings, "/transforms/bill-outcome/output", &["uncertain"]); } #[test] diff --git a/crates/registry-coordinator/tests/fixtures/external-command/workflow.yaml b/crates/registry-coordinator/tests/fixtures/external-command/workflow.yaml index a2207e13fe..93f1742130 100644 --- a/crates/registry-coordinator/tests/fixtures/external-command/workflow.yaml +++ b/crates/registry-coordinator/tests/fixtures/external-command/workflow.yaml @@ -50,7 +50,7 @@ types: properties: state: {type: string, const: uncertain} -functions: +transforms: bill-request: runtime: rhai source: functions.rhai @@ -84,8 +84,8 @@ workflow: type: call operation: create-bill input: - type: function - function: bill-request + type: transform + transform: bill-request inputs: request: {type: input} next: billed diff --git a/crates/registry-coordinator/tests/fixtures/review-wait/workflow.yaml b/crates/registry-coordinator/tests/fixtures/review-wait/workflow.yaml index 6285eec536..3acfdfe8f6 100644 --- a/crates/registry-coordinator/tests/fixtures/review-wait/workflow.yaml +++ b/crates/registry-coordinator/tests/fixtures/review-wait/workflow.yaml @@ -14,7 +14,7 @@ types: applicationVersion: {type: string, minLength: 1, maxLength: 64} applicationDigest: {type: string, pattern: "^sha256:[0-9a-f]{64}$"} email: {type: string, format: email} -functions: +transforms: review-request: runtime: rhai source: functions.rhai @@ -41,7 +41,7 @@ workflow: submit-review: type: call operation: submit-review-request - input: {type: function, function: review-request, inputs: {input: {type: input}}} + input: {type: transform, transform: review-request, inputs: {input: {type: input}}} next: await-review await-review: type: wait-for @@ -62,7 +62,7 @@ workflow: notify: type: call operation: submit-message - input: {type: function, function: notice-request, inputs: {input: {type: input}, result: {type: step, step: await-review}}} + input: {type: transform, transform: notice-request, inputs: {input: {type: input}, result: {type: step, step: await-review}}} next: notice-sent notice-sent: type: finish diff --git a/crates/registry-coordinator/tests/helper_functions.rs b/crates/registry-coordinator/tests/helper_functions.rs index a6f3ad9342..2b85025ef4 100644 --- a/crates/registry-coordinator/tests/helper_functions.rs +++ b/crates/registry-coordinator/tests/helper_functions.rs @@ -10,12 +10,12 @@ fn write_project(root: &Path, source: &str) { let workflow = json!({ "apiVersion": authoring::API_VERSION, "kind": authoring::KIND, "project": {"id": "helpers", "version": "1"}, - "functions": { + "transforms": { "probe": {"runtime":"rhai","source":"functions.rhai","entrypoint":"probe","inputs":{"request":{"type":"object"}},"output":{}} }, "workflow": {"input": {"type": "object"}, "deadlineSeconds": 86400, "start": "done", "steps": { - "done": {"type": "finish", "outcome": "measured", "output": {"type": "function", "function": "probe", "inputs": {"request":{"type": "input"}}}} + "done": {"type": "finish", "outcome": "measured", "output": {"type": "transform", "transform": "probe", "inputs": {"request":{"type": "input"}}}} }, "outcomes": {"measured": {}} } }); @@ -131,7 +131,7 @@ fn helpers_that_make_longer_strings_stay_inside_the_string_budget() { ] { let source = body.replace("aaaaaaaa", &"a".repeat(1024)); let error = run(&source, json!({})).unwrap_err(); - assert_eq!(error.code, "function.resource-limit", "{body}"); + assert_eq!(error.code, "transform.resource-limit", "{body}"); } } @@ -147,7 +147,7 @@ fn an_oversized_replace_reaches_a_loaded_project_as_a_resource_limit_refusal() { json!({"big": big}), ) .unwrap_err(); - assert_eq!(error.code, "function.resource-limit"); + assert_eq!(error.code, "transform.resource-limit"); } #[test] @@ -155,7 +155,7 @@ fn a_call_to_a_name_the_profile_lacks_is_refused_at_load_with_its_position_and_a let error = load("parse_decimal(inputs.request.digits)") .err() .expect("unknown helper is refused"); - assert_eq!(error.code, "coordinator.function.unknown-call"); + assert_eq!(error.code, "coordinator.transform.unknown-call"); assert!( error.message.contains("`parse_decimal`"), "{}", @@ -166,7 +166,7 @@ fn a_call_to_a_name_the_profile_lacks_is_refused_at_load_with_its_position_and_a .suggested_action .as_deref() .unwrap() - .contains("coordinatorctl explain functions"), + .contains("coordinatorctl explain transforms"), "{error:?}" ); let source = error.diagnostics[0] @@ -197,7 +197,7 @@ fn every_unknown_call_is_reported_and_known_calls_and_local_functions_pass() { .as_array() .unwrap() .iter() - .filter(|d| d["code"] == "coordinator.function.unknown-call") + .filter(|d| d["code"] == "coordinator.transform.unknown-call") .map(|d| d["message"].as_str().unwrap().to_owned()) .collect::>(); assert_eq!(findings.len(), 3, "{report}"); @@ -214,7 +214,7 @@ fn every_unknown_call_is_reported_and_known_calls_and_local_functions_pass() { #[test] fn explain_functions_lists_the_helpers_of_the_profile() { - let output = cli(&["--format", "json", "explain", "functions"]); + let output = cli(&["--format", "json", "explain", "transforms"]); assert!( output.status.success(), "{}", @@ -267,10 +267,10 @@ fn explain_functions_lists_the_helpers_of_the_profile() { assert!(report["interpreterAbi"].as_str().unwrap().contains("/v3;")); assert_eq!(report["limits"]["stringBytes"], 16384); - let human = cli(&["explain", "functions"]); + let human = cli(&["explain", "transforms"]); assert!(human.status.success()); let text = String::from_utf8(human.stdout).unwrap(); - assert!(text.starts_with("Pure function helpers"), "{text}"); + assert!(text.starts_with("Transform helpers"), "{text}"); assert!(text.contains("parse_int"), "{text}"); assert!(text.contains("Notes:"), "{text}"); assert!(text.contains("global::NAME"), "{text}"); @@ -291,7 +291,7 @@ fn explain_without_a_project_names_the_argument_and_its_help_lists_the_topic() { let help = cli(&["explain", "--help"]); assert!(help.status.success()); let text = String::from_utf8(help.stdout).unwrap(); - assert!(text.contains("functions"), "{text}"); + assert!(text.contains("transforms"), "{text}"); assert!(text.contains("--project"), "{text}"); } @@ -307,7 +307,7 @@ fn pad_with_an_empty_padding_string_is_refused_instead_of_looping() { ), ] { let error = within(10, move || run(body, request)).unwrap_err(); - assert_eq!(error.code, "function.execution", "{body}"); + assert_eq!(error.code, "transform.execution", "{body}"); } } @@ -332,7 +332,7 @@ fn pad_with_a_string_fills_to_the_length_and_stops_at_the_budget() { r#"let s = ""; s.pad(9223372036854775807, "ab"); s"#, ] { let error = within(10, move || run(body, json!({}))).unwrap_err(); - assert_eq!(error.code, "function.resource-limit", "{body}"); + assert_eq!(error.code, "transform.resource-limit", "{body}"); } } @@ -413,9 +413,9 @@ fn package_string_helpers_end_on_empty_zero_and_extreme_arguments() { if let Err(error) = outcome { assert!( [ - "function.execution", - "function.resource-limit", - "function.output" + "transform.execution", + "transform.resource-limit", + "transform.output" ] .contains(&error.code.as_ref()), "{call}: {error:?}" @@ -451,7 +451,7 @@ fn only_math_whose_result_is_the_same_on_every_host_is_available() { let error = load(name) .err() .unwrap_or_else(|| panic!("{name} is available")); - assert_eq!(error.code, "coordinator.function.unknown-call", "{name}"); + assert_eq!(error.code, "coordinator.transform.unknown-call", "{name}"); } let value = run( r#" @@ -492,7 +492,7 @@ fn a_result_holding_nan_or_infinity_is_refused_not_turned_into_null() { "parse_float(\"NaN\")", ] { let error = run(body, json!({})).unwrap_err(); - assert_eq!(error.code, "function.execution", "{body}"); + assert_eq!(error.code, "transform.execution", "{body}"); } // Finite numbers, and a NaN that is only tested, still pass. assert_eq!( @@ -511,7 +511,7 @@ fn a_function_that_curries_is_refused_at_check_with_a_way_forward() { let Err(error) = Definition::load(root.path()) else { panic!("a Function that curries was accepted"); }; - assert_eq!(error.code, "coordinator.function.definition"); + assert_eq!(error.code, "coordinator.transform.definition"); assert!(error.message.contains("curry"), "{}", error.message); let hint = error.suggested_action.as_deref().unwrap_or_default(); assert!(hint.contains("curry"), "{hint}"); @@ -527,8 +527,8 @@ fn a_refusal_in_a_shared_source_is_reported_once() { ); let path = root.path().join("workflow.yaml"); let mut workflow: Value = serde_json::from_str(&fs::read_to_string(&path).unwrap()).unwrap(); - workflow["functions"]["other"] = workflow["functions"]["probe"].clone(); - workflow["functions"]["other"]["entrypoint"] = json!("other"); + workflow["transforms"]["other"] = workflow["transforms"]["probe"].clone(); + workflow["transforms"]["other"]["entrypoint"] = json!("other"); fs::write(&path, workflow.to_string()).unwrap(); let output = cli(&[ "--format", @@ -542,7 +542,7 @@ fn a_refusal_in_a_shared_source_is_reported_once() { .as_array() .unwrap() .iter() - .filter(|d| d["code"] == "coordinator.function.definition") + .filter(|d| d["code"] == "coordinator.transform.definition") .count(); assert_eq!(refusals, 1, "{report}"); } @@ -563,7 +563,7 @@ fn unknown_call_names(source: &str) -> Vec { .map(Vec::as_slice) .unwrap_or_default() .iter() - .filter(|d| d["code"] == "coordinator.function.unknown-call") + .filter(|d| d["code"] == "coordinator.transform.unknown-call") .map(|d| { let message = d["message"].as_str().unwrap(); message.split('`').nth(1).unwrap().to_owned() diff --git a/crates/registry-coordinator/tests/instant_functions.rs b/crates/registry-coordinator/tests/instant_functions.rs index 401441fae4..57b6bde8cf 100644 --- a/crates/registry-coordinator/tests/instant_functions.rs +++ b/crates/registry-coordinator/tests/instant_functions.rs @@ -15,14 +15,14 @@ fn project(functions: &str) -> tempfile::TempDir { let workflow = json!({ "apiVersion": authoring::API_VERSION, "kind": authoring::KIND, "project": {"id": "instants", "version": "1"}, - "functions": { + "transforms": { "due": {"runtime":"rhai","source":"functions.rhai","entrypoint":"due","inputs":{"request":{"type":"object"}},"output":{"type":"string","format":"date-time"}}, "elapsed": {"runtime":"rhai","source":"functions.rhai","entrypoint":"elapsed","inputs":{"request":{"type":"object"}},"output":{"type":"integer"}} }, "workflow": {"input": {"type": "object"}, "deadlineSeconds": 86400, "start": "due", "steps": { - "due": {"type": "wait-until", "waitUntil": {"type": "function", "function": "due", "inputs": {"request":{"type": "input"}}}, "next": "done"}, - "done": {"type": "finish", "outcome": "measured", "output": {"type": "function", "function": "elapsed", "inputs": {"request":{"type": "input"}}}} + "due": {"type": "wait-until", "waitUntil": {"type": "transform", "transform": "due", "inputs": {"request":{"type": "input"}}}, "next": "done"}, + "done": {"type": "finish", "outcome": "measured", "output": {"type": "transform", "transform": "elapsed", "inputs": {"request":{"type": "input"}}}} }, "outcomes": {"measured": {"type": "integer"}} } }); @@ -52,7 +52,7 @@ fn between(at: &str, other: &str) -> registry_coordinator::Result { definition().evaluate("done", &json!({"at": at, "other": other}), &BTreeMap::new()) } -const REFUSED: &str = "the function could not evaluate its supplied values"; +const REFUSED: &str = "the Transform could not evaluate its supplied values"; #[test] fn add_seconds_moves_an_instant_and_writes_it_in_utc() { @@ -107,7 +107,7 @@ fn an_instant_or_result_outside_rfc_3339_is_a_function_failure_that_omits_the_va ]; for refusal in refusals { let error = refusal.err().unwrap(); - assert_eq!(error.code, "function.execution"); + assert_eq!(error.code, "transform.execution"); assert_eq!(error.message, REFUSED); let rendered = serde_json::to_string(&json!({ "message": error.message, "field": error.field, @@ -136,5 +136,5 @@ fn the_function_profile_reads_no_clock() { let error = Definition::load(project(&functions).path()) .err() .expect("a call to the clock is refused"); - assert_eq!(error.code, "coordinator.function.unknown-call"); + assert_eq!(error.code, "coordinator.transform.unknown-call"); } diff --git a/crates/registry-coordinator/tests/mapping_checks.rs b/crates/registry-coordinator/tests/mapping_checks.rs index cd9e038297..f8c555749c 100644 --- a/crates/registry-coordinator/tests/mapping_checks.rs +++ b/crates/registry-coordinator/tests/mapping_checks.rs @@ -289,7 +289,7 @@ fn a_mapping_that_fits_every_schema_loads() { #[test] fn open_members_accept_any_path_beneath_them() { let mut project = project(); - project["workflow"]["steps"]["done"]["output"] = json!({"type": "function", "function": "combine", "inputs": {"arg0": {"type": "input", "path": "/labels/lname"}, "arg1": {"type": "input", "path": "/labels/other"}, "arg2": {"type": "input", "path": "/tree/child/child/child/name"}, "arg3": {"type": "input", "path": "/slots/3"}, "arg4": {"type": "input", "path": "/extra/any/depth"}, "arg5": {"type": "step", "step": "read", "path": "/data/domainData/any/0/depth"}, "arg6": {"type": "step", "step": "read", "path": "/data/extension"}, "arg7": {"type": "step", "step": "read", "path": "/links/self"}, "arg8": {"type": "step", "step": "lookup", "path": "/body/0/a~1b"}}}); + project["workflow"]["steps"]["done"]["output"] = json!({"type": "transform", "transform": "combine", "inputs": {"arg0": {"type": "input", "path": "/labels/lname"}, "arg1": {"type": "input", "path": "/labels/other"}, "arg2": {"type": "input", "path": "/tree/child/child/child/name"}, "arg3": {"type": "input", "path": "/slots/3"}, "arg4": {"type": "input", "path": "/extra/any/depth"}, "arg5": {"type": "step", "step": "read", "path": "/data/domainData/any/0/depth"}, "arg6": {"type": "step", "step": "read", "path": "/data/extension"}, "arg7": {"type": "step", "step": "read", "path": "/links/self"}, "arg8": {"type": "step", "step": "lookup", "path": "/body/0/a~1b"}}}); load(&project, "fn combine(__named) { let a = __named.arg0; let b = __named.arg1; let c = __named.arg2; let d = __named.arg3; let e = __named.arg4; let f = __named.arg5; let g = __named.arg6; let h = __named.arg7; let i = __named.arg8; () }").unwrap(); } @@ -335,7 +335,7 @@ fn a_path_the_operation_output_does_not_declare_is_refused() { #[test] fn function_arguments_have_their_paths_checked_and_nothing_else() { let mut project = project(); - project["workflow"]["steps"]["done"]["output"] = json!({"type": "function", "function": "combine", "inputs": {"arg0": {"type": "input", "path": "/count"}, "arg1": {"type": "input", "path": "/tree/child/nmae"}}}); + project["workflow"]["steps"]["done"]["output"] = json!({"type": "transform", "transform": "combine", "inputs": {"arg0": {"type": "input", "path": "/count"}, "arg1": {"type": "input", "path": "/tree/child/nmae"}}}); assert_finding( &refused(&project), "coordinator.mapping.path", @@ -642,9 +642,9 @@ fn an_admitted_snapshot_is_not_held_to_the_static_checks() { fn declare_test_functions(project: &Value) -> Value { fn mapping(value: &Value, functions: &mut serde_json::Map) { if let Some(object) = value.as_object() { - if object.get("type") == Some(&json!("function")) { + if object.get("type") == Some(&json!("transform")) { if let (Some(name), Some(inputs)) = ( - object.get("function").and_then(Value::as_str), + object.get("transform").and_then(Value::as_str), object.get("inputs").and_then(Value::as_object), ) { let signature = inputs @@ -666,6 +666,6 @@ fn declare_test_functions(project: &Value) -> Value { let mut project = project.clone(); let mut functions = serde_json::Map::new(); mapping(&project["workflow"]["steps"], &mut functions); - project["functions"] = Value::Object(functions); + project["transforms"] = Value::Object(functions); project } diff --git a/crates/registry-coordinator/tests/mapping_grammar.rs b/crates/registry-coordinator/tests/mapping_grammar.rs index 1218d1b570..bcb4464fdb 100644 --- a/crates/registry-coordinator/tests/mapping_grammar.rs +++ b/crates/registry-coordinator/tests/mapping_grammar.rs @@ -214,7 +214,7 @@ fn references_and_fields_carry_plumbing_without_a_function() { #[test] fn function_arguments_accept_paths_and_literals() { let mut project = project(); - project["workflow"]["steps"]["done"]["output"] = json!({"type": "function", "function": "combine", "inputs": {"arg0": {"type": "input", "path": "/applicationId"}, "arg1": {"type": "literal", "value": {"nested": [1, true, null]}}, "arg2": {"type": "step", "step": "read", "path": "/data"}, "arg3": {"type": "step", "step": "read"}}}); + project["workflow"]["steps"]["done"]["output"] = json!({"type": "transform", "transform": "combine", "inputs": {"arg0": {"type": "input", "path": "/applicationId"}, "arg1": {"type": "literal", "value": {"nested": [1, true, null]}}, "arg2": {"type": "step", "step": "read", "path": "/data"}, "arg3": {"type": "step", "step": "read"}}}); let definition = load( &project, "fn combine(__named) { let id = __named.arg0; let literal = __named.arg1; let data = __named.arg2; let whole = __named.arg3; let count = if literal.nested.len() == 3 && literal.nested[1] { \"3\" } else { \"?\" }; #{ record: data.recordId + \":\" + id + \":\" + count + \":\" + whole.meta.datasetId, note: () } }", @@ -319,21 +319,21 @@ fn a_malformed_pointer_is_refused_at_its_member() { fn an_input_names_its_form_function_or_fields() { for (value, path, code, message, action) in [ ( - json!({"function": "f", "inputs": {}}), + json!({"transform": "f", "inputs": {}}), "/workflow/steps/read/input", "config.missing-key", "the member `type` is missing; it names which form this mapping takes", - "Add `type` with one of `function`, `fields`, `compare`, `input`, `step`, `literal`.", + "Add `type` with one of `transform`, `fields`, `compare`, `input`, `step`, `literal`.", ), ( json!({"type": "unknown"}), "/workflow/steps/read/input/type", "config.unknown-variant", - "expected one of `function`, `fields`, `compare`, `input`, `step`, `literal`", - "Use one of `function`, `fields`, `compare`, `input`, `step`, `literal`.", + "expected one of `transform`, `fields`, `compare`, `input`, `step`, `literal`", + "Use one of `transform`, `fields`, `compare`, `input`, `step`, `literal`.", ), ( - json!({"type": "function", "function": "f"}), + json!({"type": "transform", "transform": "f"}), "/workflow/steps/read/input", "config.missing-key", "the required member `inputs` is missing", @@ -347,11 +347,11 @@ fn an_input_names_its_form_function_or_fields() { "Add `fields`.", ), ( - json!({"type": "function", "function": "f", "inputs": {}, "fields": {}}), + json!({"type": "transform", "transform": "f", "inputs": {}, "fields": {}}), "/workflow/steps/read/input/fields", "config.unknown-key", "`fields` is not a member of this mapping", - "Remove `fields`; the accepted keys are `type`, `function`, `inputs`.", + "Remove `fields`; the accepted keys are `type`, `transform`, `inputs`.", ), ] { let mut project = project(); @@ -368,18 +368,18 @@ fn an_input_names_its_form_function_or_fields() { fn a_selector_names_its_form_function_or_one_reference() { for (value, path, code, message, action) in [ ( - json!({"function": "f", "inputs": {}}), + json!({"transform": "f", "inputs": {}}), "/workflow/steps/route/choose", "config.missing-key", "the member `type` is missing; it names which form this mapping takes", - "Add `type` with one of `function`, `fields`, `compare`, `input`, `step`, `literal`.", + "Add `type` with one of `transform`, `fields`, `compare`, `input`, `step`, `literal`.", ), ( json!({"type": "unknown"}), "/workflow/steps/route/choose/type", "config.unknown-variant", - "expected one of `function`, `fields`, `compare`, `input`, `step`, `literal`", - "Use one of `function`, `fields`, `compare`, `input`, `step`, `literal`.", + "expected one of `transform`, `fields`, `compare`, `input`, `step`, `literal`", + "Use one of `transform`, `fields`, `compare`, `input`, `step`, `literal`.", ), ( json!({"type": "step"}), @@ -410,11 +410,11 @@ fn a_selector_names_its_form_function_or_one_reference() { "Remove `path`; the accepted keys are `type`, `value`.", ), ( - json!({"type": "function", "function": "f", "inputs": {}, "path": "/x"}), + json!({"type": "transform", "transform": "f", "inputs": {}, "path": "/x"}), "/workflow/steps/route/choose/path", "config.unknown-key", "`path` is not a member of this mapping", - "Remove `path`; the accepted keys are `type`, `function`, `inputs`.", + "Remove `path`; the accepted keys are `type`, `transform`, `inputs`.", ), ] { let mut project = project(); @@ -554,9 +554,9 @@ fn reference_selectors_keep_their_result_contracts() { fn declare_test_functions(project: &Value) -> Value { fn mapping(value: &Value, functions: &mut serde_json::Map) { if let Some(object) = value.as_object() { - if object.get("type") == Some(&json!("function")) { + if object.get("type") == Some(&json!("transform")) { if let (Some(name), Some(inputs)) = ( - object.get("function").and_then(Value::as_str), + object.get("transform").and_then(Value::as_str), object.get("inputs").and_then(Value::as_object), ) { let signature = inputs @@ -578,6 +578,6 @@ fn declare_test_functions(project: &Value) -> Value { let mut project = project.clone(); let mut functions = serde_json::Map::new(); mapping(&project["workflow"]["steps"], &mut functions); - project["functions"] = Value::Object(functions); + project["transforms"] = Value::Object(functions); project } diff --git a/crates/registry-coordinator/tests/nested_fields.rs b/crates/registry-coordinator/tests/nested_fields.rs index be3265a61f..e5d3b9085c 100644 --- a/crates/registry-coordinator/tests/nested_fields.rs +++ b/crates/registry-coordinator/tests/nested_fields.rs @@ -137,9 +137,9 @@ fn only(error: &CoordinatorError) -> &Diagnostic { fn declare_test_functions(project: &Value) -> Value { fn mapping(value: &Value, functions: &mut serde_json::Map) { if let Some(object) = value.as_object() { - if object.get("type") == Some(&json!("function")) { + if object.get("type") == Some(&json!("transform")) { if let (Some(name), Some(inputs)) = ( - object.get("function").and_then(Value::as_str), + object.get("transform").and_then(Value::as_str), object.get("inputs").and_then(Value::as_object), ) { let signature = inputs @@ -157,7 +157,7 @@ fn declare_test_functions(project: &Value) -> Value { let mut project = project.clone(); let mut functions = serde_json::Map::new(); mapping(&project["workflow"]["steps"], &mut functions); - project["functions"] = Value::Object(functions); + project["transforms"] = Value::Object(functions); project } @@ -342,7 +342,7 @@ fn a_nested_member_reads_only_outputs_available_on_every_route() { fn a_nested_member_never_holds_a_function() { let mut project = project(); project["workflow"]["steps"]["lookup"]["input"]["fields"]["query"]["fields"]["page"] = - json!({"type": "function", "function": "page", "inputs": {}}); + json!({"type": "transform", "transform": "page", "inputs": {}}); let error = parse_refused(&project); let finding = &error.diagnostics[0]; assert_eq!(finding.code, "config.unknown-variant"); @@ -357,7 +357,7 @@ fn a_nested_member_never_holds_a_function() { // Function inputs stay plain references. let mut project = self::project(); - project["workflow"]["steps"]["lookup"]["input"] = json!({"type": "function", "function": "build", "inputs": { + project["workflow"]["steps"]["lookup"]["input"] = json!({"type": "transform", "transform": "build", "inputs": { "page": {"type": "fields", "fields": {}} }}); let error = parse_refused(&project); @@ -377,11 +377,11 @@ fn a_nested_member_never_holds_a_function() { fn a_nested_mapping_freezes_the_input_a_function_would_build() { let declarative = load(&project(), "").unwrap(); let mut computed = project(); - computed["workflow"]["steps"]["lookup"]["input"] = json!({"type": "function", "function": "build_query", "inputs": { + computed["workflow"]["steps"]["lookup"]["input"] = json!({"type": "transform", "transform": "build_query", "inputs": { "page": {"type": "input", "path": "/page"}, "record": {"type": "step", "step": "read", "path": "/data/recordId"} }}); - computed["workflow"]["steps"]["done"]["output"] = json!({"type": "function", "function": "build_outcome", "inputs": { + computed["workflow"]["steps"]["done"]["output"] = json!({"type": "transform", "transform": "build_outcome", "inputs": { "id": {"type": "input", "path": "/applicationId"}, "record": {"type": "step", "step": "read", "path": "/data/recordId"} }}); @@ -485,7 +485,7 @@ fn a_snapshot_refuses_unknown_members_of_a_nested_mapping() { reference_with_fields["fields"]["page"]["fields"] = json!({}); let mut function_shaped = query.clone(); function_shaped["fields"]["page"] = - json!({"type": "function", "function": "page", "inputs": {}}); + json!({"type": "transform", "transform": "page", "inputs": {}}); let mut wrong_case = query.clone(); wrong_case["type"] = json!("Fields"); for (case, query) in [ diff --git a/crates/registry-coordinator/tests/postgres_state.rs b/crates/registry-coordinator/tests/postgres_state.rs index 1c628b45b0..49c065fcba 100644 --- a/crates/registry-coordinator/tests/postgres_state.rs +++ b/crates/registry-coordinator/tests/postgres_state.rs @@ -49,7 +49,7 @@ kind: CoordinatorProject project: {id: synthetic-declared-refusal, version: v1} contracts: applications: {type: breg, source: applications.json} -functions: +transforms: action: runtime: rhai source: functions.rhai @@ -75,14 +75,14 @@ workflow: action: type: call operation: invoke-breg-action - input: {type: function, function: action, inputs: {input: {type: input}}} + input: {type: transform, transform: action, inputs: {input: {type: input}}} next: applied onDeclaredRefusal: refused applied: {type: finish, outcome: applied} refused: type: finish outcome: refused - output: {type: function, function: keep, inputs: {value: {type: step, step: action}}} + output: {type: transform, transform: keep, inputs: {value: {type: step, step: action}}} outcomes: applied: {type: 'null'} refused: {operationRefusal: invoke-breg-action} @@ -99,7 +99,7 @@ kind: CoordinatorProject project: {id: synthetic-declared-refusal-deadline, version: v1} contracts: applications: {type: breg, source: applications.json} -functions: +transforms: action: runtime: rhai source: functions.rhai @@ -125,13 +125,13 @@ workflow: action: type: call operation: invoke-breg-action - input: {type: function, function: action, inputs: {input: {type: input}}} + input: {type: transform, transform: action, inputs: {input: {type: input}}} next: applied onDeclaredRefusal: later later: type: call operation: invoke-breg-action - input: {type: function, function: action, inputs: {input: {type: input}}} + input: {type: transform, transform: action, inputs: {input: {type: input}}} next: applied applied: {type: finish, outcome: applied} outcomes: @@ -143,7 +143,7 @@ kind: CoordinatorProject project: id: synthetic-reminder version: v1 -functions: +transforms: timer: runtime: rhai source: functions.rhai @@ -214,8 +214,8 @@ workflow: wait: type: wait-until waitUntil: - type: function - function: timer + type: transform + transform: timer inputs: input: type: input @@ -224,8 +224,8 @@ workflow: type: call operation: read-record input: - type: function - function: record + type: transform + transform: record inputs: input: type: input @@ -233,8 +233,8 @@ workflow: choose: type: choose choose: - type: function - function: permission + type: transform + transform: permission inputs: record: type: step @@ -246,8 +246,8 @@ workflow: type: call operation: submit-message input: - type: function - function: message + type: transform + transform: message inputs: record: type: step @@ -257,8 +257,8 @@ workflow: type: finish outcome: sent output: - type: function - function: receipt + type: transform + transform: receipt inputs: message: type: step @@ -311,7 +311,7 @@ async fn harness() -> Harness { .unwrap(); std::fs::write(project.path().join("applications.json"), include_str!("../../../products/coordinator/examples/governed-action-follow-up/generated/applications.contract.json")).unwrap(); std::fs::write(project.path().join("workflow.yaml"), WORKFLOW).expect("workflow"); - std::fs::write(project.path().join("functions.rhai"), FUNCTIONS).expect("functions"); + std::fs::write(project.path().join("functions.rhai"), FUNCTIONS).expect("transforms"); let definition = Definition::load(project.path()).expect("valid synthetic definition"); Harness { url, @@ -1865,7 +1865,7 @@ async fn a_call_input_outside_the_operation_input_is_refused_before_dispatch_wit // A permissive Function result still cannot bypass the host's exact // Operation contract or freeze an invalid command. let mut workflow = authored_workflow_value(WORKFLOW); - workflow["functions"]["message"]["output"] = json!({"type":"object"}); + workflow["transforms"]["message"]["output"] = json!({"type":"object"}); std::fs::write(h.project.path().join("workflow.yaml"), workflow.to_string()).unwrap(); let definition = Definition::load(h.project.path()).unwrap(); let run = h @@ -1925,7 +1925,7 @@ async fn invalid_dictionary_values_never_disclose_member_names_or_dispatch() { apiVersion: id.registrystack.org/formats/coordinator/project/v1alpha1 kind: CoordinatorProject project: {id: synthetic-dictionary-privacy, version: '1'} -functions: +transforms: request: runtime: rhai source: functions.rhai @@ -1949,7 +1949,7 @@ workflow: read: type: call operation: read-job - input: {type: function, function: request, inputs: {request: {type: input}}} + input: {type: transform, transform: request, inputs: {request: {type: input}}} next: done done: {type: finish, outcome: done} outcomes: {done: {type: 'null'}} @@ -3946,36 +3946,36 @@ async fn invalid_following_wait(prior: &str, body: &str) -> Harness { let mut workflow = authored_workflow_value(WORKFLOW); let mut steps = serde_json::Map::new(); let input_mapping = - json!({"type":"function","function":"record","inputs":{"input":{"type":"input"}}}); + json!({"type":"transform","transform":"record","inputs":{"input":{"type":"input"}}}); let start = match prior { "read" => { steps.insert("read".into(),json!({"type":"call","operation":"read-record","input":input_mapping,"next":"later"})); "read" } "choose" => { - steps.insert("choose".into(),json!({"type":"choose","choose":{"type":"function","function":"choose-input","inputs":{"input":{"type":"input"}}},"cases":{"yes":"later"}})); + steps.insert("choose".into(),json!({"type":"choose","choose":{"type":"transform","transform":"choose-input","inputs":{"input":{"type":"input"}}},"cases":{"yes":"later"}})); "choose" } "wait" => { - steps.insert("wait".into(),json!({"type":"wait-until","waitUntil":{"type":"function","function":"timer","inputs":{"input":{"type":"input"}}},"next":"later"})); + steps.insert("wait".into(),json!({"type":"wait-until","waitUntil":{"type":"transform","transform":"timer","inputs":{"input":{"type":"input"}}},"next":"later"})); "wait" } "message" => { steps.insert("read".into(),json!({"type":"call","operation":"read-record","input":input_mapping,"next":"message"})); - steps.insert("message".into(),json!({"type":"call","operation":"submit-message","input":{"type":"function","function":"message","inputs":{"record":{"type":"step","step":"read"}}},"next":"later"})); + steps.insert("message".into(),json!({"type":"call","operation":"submit-message","input":{"type":"transform","transform":"message","inputs":{"record":{"type":"step","step":"read"}}},"next":"later"})); "read" } _ => panic!("unknown test prior step"), }; - steps.insert("later".into(),json!({"type":"wait-until","waitUntil":{"type":"function","function":"broken-wait","inputs":{"input":{"type":"input"}}},"next":"future-read"})); + steps.insert("later".into(),json!({"type":"wait-until","waitUntil":{"type":"transform","transform":"broken-wait","inputs":{"input":{"type":"input"}}},"next":"future-read"})); steps.insert( "future-read".into(), json!({"type":"call","operation":"read-record","input":input_mapping,"next":"done"}), ); steps.insert("done".into(), json!({"type":"finish","outcome":"done"})); workflow["workflow"] = json!({"input":{"type":"object"},"deadlineSeconds":3600,"start":start,"steps":steps,"outcomes":{"done":{"type":"null"}}}); - workflow["functions"]["choose-input"] = json!({"runtime":"rhai","source":"functions.rhai","entrypoint":"choose_input","inputs":{"input":{"type":"object"}},"output":{"type":"string","enum":["yes"]}}); - workflow["functions"]["broken-wait"] = json!({"runtime":"rhai","source":"functions.rhai","entrypoint":"broken_wait","inputs":{"input":{"type":"object"}},"output":{}}); + workflow["transforms"]["choose-input"] = json!({"runtime":"rhai","source":"functions.rhai","entrypoint":"choose_input","inputs":{"input":{"type":"object"}},"output":{"type":"string","enum":["yes"]}}); + workflow["transforms"]["broken-wait"] = json!({"runtime":"rhai","source":"functions.rhai","entrypoint":"broken_wait","inputs":{"input":{"type":"object"}},"output":{}}); std::fs::write(h.project.path().join("workflow.yaml"), workflow.to_string()).unwrap(); std::fs::write(h.project.path().join("functions.rhai"),format!("{FUNCTIONS}\nfn choose_input(args) {{ \"yes\" }}\nfn broken_wait(args) {{let input=args.input; {body}}}")).unwrap(); h.definition = Definition::load(h.project.path()).unwrap(); @@ -4681,9 +4681,8 @@ async fn interrupted_mutation(kind: &str, prepared: bool) -> (Harness, Uuid, Arc .as_object_mut() .unwrap() .remove("read"); - document["workflow"]["steps"]["message"]["input"] = - json!({"type":"function","function":"pre-io-command","inputs":{"input":{"type":"input"}}}); - document["functions"]["pre-io-command"] = json!({"runtime":"rhai","source":"functions.rhai","entrypoint":"pre_io_command","inputs":{"input":{"type":"object"}},"output":{"operationInput":"submit-message"}}); + document["workflow"]["steps"]["message"]["input"] = json!({"type":"transform","transform":"pre-io-command","inputs":{"input":{"type":"input"}}}); + document["transforms"]["pre-io-command"] = json!({"runtime":"rhai","source":"functions.rhai","entrypoint":"pre_io_command","inputs":{"input":{"type":"object"}},"output":{"operationInput":"submit-message"}}); if kind == "appointment" { document["operations"]["submit-message"]["uses"] = json!("scheduling.create-appointment/v1"); diff --git a/crates/registry-coordinator/tests/process_restart.rs b/crates/registry-coordinator/tests/process_restart.rs index 6c16e8afd6..a2fd1c955a 100644 --- a/crates/registry-coordinator/tests/process_restart.rs +++ b/crates/registry-coordinator/tests/process_restart.rs @@ -346,7 +346,7 @@ async fn exited_decision_workers_hold_unknown_results_and_reuse_completed_result apiVersion: id.registrystack.org/formats/coordinator/project/v1alpha1 kind: CoordinatorProject project: {id: process-decision, version: '1'} -functions: +transforms: decision-request: runtime: rhai source: functions.rhai @@ -371,11 +371,11 @@ workflow: evaluate: type: call operation: evaluate - input: {type: function, function: decision-request, inputs: {input: {type: input}}} + input: {type: transform, transform: decision-request, inputs: {input: {type: input}}} next: wait wait: type: wait-until - waitUntil: {type: function, function: timer, inputs: {input: {type: input}}} + waitUntil: {type: transform, transform: timer, inputs: {input: {type: input}}} next: done done: type: finish diff --git a/crates/registry-coordinator/tests/product_contract_imports.rs b/crates/registry-coordinator/tests/product_contract_imports.rs index e716c5faf4..88f563997d 100644 --- a/crates/registry-coordinator/tests/product_contract_imports.rs +++ b/crates/registry-coordinator/tests/product_contract_imports.rs @@ -299,10 +299,9 @@ fn template_import_checks_computed_data_and_keeps_local_schema_references() { project["contracts"] = json!({"notices": {"type": "messaging", "source": "contract.json"}}); project["operations"]["request"]["template"] = json!({"contract": "notices", "id": "licence-issued", "version": "1"}); - project["functions"] = json!({"message": {"runtime": "rhai", "source": "functions.rhai", "entrypoint": "message", + project["transforms"] = json!({"message": {"runtime": "rhai", "source": "functions.rhai", "entrypoint": "message", "inputs": {"input": {"type": "object"}}, "output": {"type": "object"}}}); - project["workflow"]["steps"]["call"]["input"] = - json!({"type": "function", "function": "message", "inputs": {"input": {"type": "input"}}}); + project["workflow"]["steps"]["call"]["input"] = json!({"type": "transform", "transform": "message", "inputs": {"input": {"type": "input"}}}); fs::write( root.path().join("functions.rhai"), "fn message(args) { args.input }", diff --git a/crates/registry-coordinator/tests/recovery_audit.rs b/crates/registry-coordinator/tests/recovery_audit.rs index 7069cccdd7..dbd1bdcb03 100644 --- a/crates/registry-coordinator/tests/recovery_audit.rs +++ b/crates/registry-coordinator/tests/recovery_audit.rs @@ -132,7 +132,7 @@ async fn harness() -> Harness { r#"apiVersion: id.registrystack.org/formats/coordinator/project/v1alpha1 kind: CoordinatorProject project: {id: recovery-audit, version: v1} -functions: +transforms: timer: runtime: rhai source: functions.rhai @@ -146,7 +146,7 @@ workflow: steps: wait: type: wait-until - waitUntil: {type: function, function: timer, inputs: {input: {type: input}}} + waitUntil: {type: transform, transform: timer, inputs: {input: {type: input}}} next: done done: {type: finish, outcome: done} outcomes: {done: {type: 'null'}} diff --git a/crates/registry-coordinator/tests/review_wait_postgres.rs b/crates/registry-coordinator/tests/review_wait_postgres.rs index 60e91ceb2a..b7f369d83d 100644 --- a/crates/registry-coordinator/tests/review_wait_postgres.rs +++ b/crates/registry-coordinator/tests/review_wait_postgres.rs @@ -290,7 +290,7 @@ async fn harness_with_options(on_timeout: bool, on_cancel: bool, cleanup_wait: b workflow_with_cancel(on_timeout, on_cancel, cleanup_wait), ) .expect("workflow"); - std::fs::write(project.path().join("functions.rhai"), FUNCTIONS).expect("functions"); + std::fs::write(project.path().join("functions.rhai"), FUNCTIONS).expect("transforms"); let definition = Definition::load(project.path()).expect("valid synthetic definition"); Harness { url, diff --git a/crates/registry-coordinator/tests/runtime_config.rs b/crates/registry-coordinator/tests/runtime_config.rs index 8a499cc6d5..4762697ffe 100644 --- a/crates/registry-coordinator/tests/runtime_config.rs +++ b/crates/registry-coordinator/tests/runtime_config.rs @@ -806,7 +806,7 @@ fn init_writes_eight_entries_for_an_offline_checkable_project_and_never_overwrit let explanation = definition.explain().unwrap(); assert_eq!(explanation["workflowRevision"], definition.digest); assert!(explanation["operations"].is_object()); - assert!(explanation["functions"].is_object()); + assert!(explanation["transforms"].is_object()); assert_eq!(explanation["steps"].as_array().unwrap().len(), 6); assert_eq!(explanation["limits"]["operations"], 100000); fs::write(path.join("functions.rhai"), CANARY).unwrap(); @@ -926,7 +926,7 @@ fn appointment_workflow_refuses_ordinary_authority_before_admission_or_activatio ) .unwrap(); read_only["workflow"]["start"] = json!("metadata"); - read_only.as_object_mut().unwrap().remove("functions"); + read_only.as_object_mut().unwrap().remove("transforms"); read_only["operations"] .as_object_mut() .unwrap() diff --git a/crates/registry-coordinator/tests/scheduling_event_native.rs b/crates/registry-coordinator/tests/scheduling_event_native.rs index 00d18ca87b..56daa20b4f 100644 --- a/crates/registry-coordinator/tests/scheduling_event_native.rs +++ b/crates/registry-coordinator/tests/scheduling_event_native.rs @@ -286,7 +286,7 @@ fn write_project(root: &Path) { "appointmentId":{"type":"string","format":"uuid"}, "state":{"type":"string","enum":["confirmed","cancelled"]} }}}, - "functions":{"notice-request":{"runtime":"rhai","source":"functions.rhai","entrypoint":"notice_request", + "transforms":{"notice-request":{"runtime":"rhai","source":"functions.rhai","entrypoint":"notice_request", "inputs":{"input":{"typeRef":"lifecycle-input"}},"output":{"operationInput":"send-message"}}}, "operations":{"send-message":{"uses":"messaging.submit-message/v1","connection":"notices"}}, "workflow":{ @@ -313,7 +313,7 @@ fn write_project(root: &Path) { "deadlineSeconds":300, "start":"notify", "steps":{ - "notify":{"type":"call","operation":"send-message","input":{"type":"function","function":"notice-request","inputs":{"input":{"type":"input"}}},"next":"accepted"}, + "notify":{"type":"call","operation":"send-message","input":{"type":"transform","transform":"notice-request","inputs":{"input":{"type":"input"}}},"next":"accepted"}, "accepted":{"type":"finish","outcome":"message-accepted","output":{"type":"fields","fields":{"messageId":{"type":"step","step":"notify","path":"/id"}}}} }, "outcomes":{"message-accepted":{"type":"object","additionalProperties":false,"required":["messageId"],"properties":{"messageId":{"type":"string","format":"uuid"}}}} diff --git a/crates/registry-coordinator/tests/support/breg_service.rs b/crates/registry-coordinator/tests/support/breg_service.rs index 8f4bded57e..960b9f5294 100644 --- a/crates/registry-coordinator/tests/support/breg_service.rs +++ b/crates/registry-coordinator/tests/support/breg_service.rs @@ -176,11 +176,11 @@ impl Breg { "fields":[{"id":"owner", "type":"string", "required":true, "maximumLength":80, "classification":"internal"}, {"id":"label", "type":"string", "required":true, "minimumLength":1, "maximumLength":80, "classification":"internal"}]}}, "datasets":{"synthetic-items": {}}, - "functions":{"update-item-plan": {"runtime":"rhai","source":"scripts/update-item.rhai","entrypoint":"plan","abi":"registry.action-plan/v1"}}, + "transforms":{"update-item-plan": {"runtime":"rhai","source":"scripts/update-item.rhai","entrypoint":"plan","abi":"registry.action-plan/v1"}}, "actions":{"update-item": { "execution":{"mode":"immediate"}, "inputs":[ {"id":"target", "apiName":"targetId", "type":"reference", "target":"item", "required":true, "classification":"internal"}, {"id":"label", "type":"string", "required":true, "minimumLength":1, "maximumLength":80, "classification":"internal"}], - "plan":{"type":"function", "function":"update-item-plan", "inputs":["target","label"], + "plan":{"type":"transform", "transform":"update-item-plan", "inputs":["target","label"], "refusals":[{"code":"label-not-eligible", "label":"The label is not eligible."}], "writes":[{"id":"item", "target":{"fromInput":"target"}, "operation":"patch", "fields":["label"]}]}}}, "accessProfiles":{ diff --git a/crates/registry-coordinator/tests/support/decision_evaluation.rs b/crates/registry-coordinator/tests/support/decision_evaluation.rs index 0c8cbb1a55..5c32c9b7d2 100644 --- a/crates/registry-coordinator/tests/support/decision_evaluation.rs +++ b/crates/registry-coordinator/tests/support/decision_evaluation.rs @@ -7,7 +7,7 @@ const DECISION_WORKFLOW: &str = r#" apiVersion: id.registrystack.org/formats/coordinator/project/v1alpha1 kind: CoordinatorProject project: {id: synthetic-decision, version: '1'} -functions: +transforms: decision-request: runtime: rhai source: functions.rhai @@ -26,7 +26,7 @@ workflow: evaluate: type: call operation: evaluate - input: {type: function, function: decision-request, inputs: {input: {type: input}}} + input: {type: transform, transform: decision-request, inputs: {input: {type: input}}} next: done done: type: finish @@ -250,9 +250,9 @@ async fn completed_decision_is_reused_after_restart_and_downstream_mapping_failu let mut h = decision_harness().await; if broken_wait { let mut document = authored_workflow_value(DECISION_WORKFLOW); - document["functions"]["broken-wait"] = json!({"runtime":"rhai","source":"functions.rhai","entrypoint":"broken_wait","inputs":{"input":{"type":"object"}},"output":{}}); + document["transforms"]["broken-wait"] = json!({"runtime":"rhai","source":"functions.rhai","entrypoint":"broken_wait","inputs":{"input":{"type":"object"}},"output":{}}); document["workflow"]["steps"]["evaluate"]["next"] = json!("later"); - document["workflow"]["steps"]["later"] = json!({"type":"wait-until","waitUntil":{"type":"function","function":"broken-wait","inputs":{"input":{"type":"input"}}},"next":"done"}); + document["workflow"]["steps"]["later"] = json!({"type":"wait-until","waitUntil":{"type":"transform","transform":"broken-wait","inputs":{"input":{"type":"input"}}},"next":"done"}); std::fs::write(h.project.path().join("workflow.yaml"), document.to_string()).unwrap(); std::fs::write( h.project.path().join("functions.rhai"), diff --git a/crates/registry-coordinator/tests/support/leased_wait_deadline.rs b/crates/registry-coordinator/tests/support/leased_wait_deadline.rs index 641d71e2b6..4d0b089bb9 100644 --- a/crates/registry-coordinator/tests/support/leased_wait_deadline.rs +++ b/crates/registry-coordinator/tests/support/leased_wait_deadline.rs @@ -15,7 +15,7 @@ kind: CoordinatorProject project: id: leased-timer version: v1 -functions: +transforms: timer: runtime: rhai source: functions.rhai @@ -35,11 +35,11 @@ workflow: steps: wait: type: wait-until - waitUntil: {type: function, function: timer, inputs: {input: {type: input}}} + waitUntil: {type: transform, transform: timer, inputs: {input: {type: input}}} next: choose choose: type: choose - choose: {type: function, function: choice, inputs: {input: {type: input}}} + choose: {type: transform, transform: choice, inputs: {input: {type: input}}} cases: {done: done} done: {type: finish, outcome: done} outcomes: @@ -175,7 +175,7 @@ async fn leased_finish_preserves_outcome_under_restore_review_and_after_retentio apiVersion: id.registrystack.org/formats/coordinator/project/v1alpha1 kind: CoordinatorProject project: {id: leased-finish, version: v1} -functions: +transforms: keep: runtime: rhai source: functions.rhai @@ -190,7 +190,7 @@ workflow: done: type: finish outcome: done - output: {type: function, function: keep, inputs: {input: {type: input}}} + output: {type: transform, transform: keep, inputs: {input: {type: input}}} outcomes: done: {type: object} "#, diff --git a/crates/registry-coordinator/tests/support/restore_pending.rs b/crates/registry-coordinator/tests/support/restore_pending.rs index a4423a1f36..61680764a0 100644 --- a/crates/registry-coordinator/tests/support/restore_pending.rs +++ b/crates/registry-coordinator/tests/support/restore_pending.rs @@ -32,12 +32,12 @@ async fn pending_work(kind: &str, at: chrono::DateTime) -> (Harness, Uuid, .remove("read"); let operation = "submit-message"; document["workflow"]["steps"]["message"]["operation"] = json!(operation); - document["workflow"]["steps"]["message"]["input"] = json!({"type":"function","function":"pending-command","inputs":{"input":{"type":"input"}}}); + document["workflow"]["steps"]["message"]["input"] = json!({"type":"transform","transform":"pending-command","inputs":{"input":{"type":"input"}}}); if kind == "appointment" { document["operations"][operation] = json!({"uses":"scheduling.create-appointment/v1","connection":"messages"}); } - document["functions"]["pending-command"] = json!({"runtime":"rhai","source":"functions.rhai","entrypoint":"pending_command","inputs":{"input":{"type":"object"}},"output":{"operationInput":operation}}); + document["transforms"]["pending-command"] = json!({"runtime":"rhai","source":"functions.rhai","entrypoint":"pending_command","inputs":{"input":{"type":"object"}},"output":{"operationInput":operation}}); let functions = h.project.path().join("functions.rhai"); let source = std::fs::read_to_string(&functions).unwrap(); std::fs::write( diff --git a/crates/registry-coordinator/tests/support/snapshot_boundary.rs b/crates/registry-coordinator/tests/support/snapshot_boundary.rs index 740cfa8786..f936001652 100644 --- a/crates/registry-coordinator/tests/support/snapshot_boundary.rs +++ b/crates/registry-coordinator/tests/support/snapshot_boundary.rs @@ -15,11 +15,11 @@ pub fn project_at_snapshot_size(path: &Path, size: usize) { let mut workflow = json!({ "apiVersion": "id.registrystack.org/formats/coordinator/project/v1alpha1", "kind": "CoordinatorProject", "project": {"id": "snapshot-boundary", "version": "1"}, - "functions":{"branch":{"runtime":"rhai","source":"functions.rhai","entrypoint":"branch","inputs":{"input":{"type":"null"}},"output":{"enum":["one","two","three"]}}}, + "transforms":{"branch":{"runtime":"rhai","source":"functions.rhai","entrypoint":"branch","inputs":{"input":{"type":"null"}},"output":{"enum":["one","two","three"]}}}, "workflow":{ "input": schema, "deadlineSeconds": 3600, "start": "select", "steps": { - "select": {"type": "choose", "choose": {"type": "function", "function": "branch", "inputs": {"input":{"type":"input"}}}, + "select": {"type": "choose", "choose": {"type": "transform", "transform": "branch", "inputs": {"input":{"type":"input"}}}, "cases": {"one": "first", "two": "second", "three": "third"}}, "first": {"type": "finish", "outcome": "one"}, "second": {"type": "finish", "outcome": "two"}, "third": {"type": "finish", "outcome": "three"} diff --git a/crates/registry-coordinator/tests/wait_for_authoring.rs b/crates/registry-coordinator/tests/wait_for_authoring.rs index 785a4c5164..67928a7ea1 100644 --- a/crates/registry-coordinator/tests/wait_for_authoring.rs +++ b/crates/registry-coordinator/tests/wait_for_authoring.rs @@ -325,7 +325,7 @@ fn a_review_cancel_built_by_a_function_is_refused() { ), ( " input:\n type: fields\n fields:\n request: {type: step, step: submit-review}\n reason: {type: literal, value: \"No decision within fourteen days.\"}\n", - " input: {type: function, function: withdrawal, inputs: {request: {type: step, step: submit-review}}}\n", + " input: {type: transform, transform: withdrawal, inputs: {request: {type: step, step: submit-review}}}\n", ), ], ); diff --git a/crates/registry-language-server/src/products/catalog_coordinator.rs b/crates/registry-language-server/src/products/catalog_coordinator.rs index 72e07ea93f..44ab88af5a 100644 --- a/crates/registry-language-server/src/products/catalog_coordinator.rs +++ b/crates/registry-language-server/src/products/catalog_coordinator.rs @@ -6,7 +6,7 @@ use super::spec::{DocumentRules, FileRule, NameRule as N}; const DECLARATIONS: &[N] = &[ N::global("project/id", "Coordinator workflow"), N::global("types/$key", "Coordinator type"), - N::global("functions/$key", "Coordinator Function"), + N::global("transforms/$key", "Coordinator Transform"), N::global("contracts/$key", "Coordinator contract import"), N::global("operations/$key", "Coordinator Operation"), N::global("workflow/steps/$key", "Coordinator Step"), @@ -31,13 +31,13 @@ const REFERENCES: &[N] = &[ ), N::global( "operations/*/completions/*/interpret", - "Coordinator Function", + "Coordinator Transform", ), - N::global("operations/*/interpret", "Coordinator Function"), + N::global("operations/*/interpret", "Coordinator Transform"), // Mapping inputs and fields hold References, so literal JSON payloads are never walked. N { - only_when: Some(("type", "function")), - ..N::global("workflow/steps/*/input/function", "Coordinator Function") + only_when: Some(("type", "transform")), + ..N::global("workflow/steps/*/input/transform", "Coordinator Transform") }, N { only_when: Some(("type", "step")), @@ -52,8 +52,8 @@ const REFERENCES: &[N] = &[ ..N::global("workflow/steps/*/input/fields/*/step", "Coordinator Step") }, N { - only_when: Some(("type", "function")), - ..N::global("workflow/steps/*/choose/function", "Coordinator Function") + only_when: Some(("type", "transform")), + ..N::global("workflow/steps/*/choose/transform", "Coordinator Transform") }, N { only_when: Some(("type", "step")), @@ -68,10 +68,10 @@ const REFERENCES: &[N] = &[ ..N::global("workflow/steps/*/choose/fields/*/step", "Coordinator Step") }, N { - only_when: Some(("type", "function")), + only_when: Some(("type", "transform")), ..N::global( - "workflow/steps/*/waitUntil/function", - "Coordinator Function", + "workflow/steps/*/waitUntil/transform", + "Coordinator Transform", ) }, N { @@ -93,8 +93,8 @@ const REFERENCES: &[N] = &[ ) }, N { - only_when: Some(("type", "function")), - ..N::global("workflow/steps/*/output/function", "Coordinator Function") + only_when: Some(("type", "transform")), + ..N::global("workflow/steps/*/output/transform", "Coordinator Transform") }, N { only_when: Some(("type", "step")), @@ -109,10 +109,10 @@ const REFERENCES: &[N] = &[ ..N::global("workflow/steps/*/output/fields/*/step", "Coordinator Step") }, N { - only_when: Some(("type", "function")), + only_when: Some(("type", "transform")), ..N::global( - "workflow/eventTriggers/*/input/function", - "Coordinator Function", + "workflow/eventTriggers/*/input/transform", + "Coordinator Transform", ) }, N { @@ -142,35 +142,38 @@ const REFERENCES: &[N] = &[ "types/*/completionOutput/operation", "Coordinator Operation", ), - N::global("functions/*/inputs/*/typeRef", "Coordinator type"), + N::global("transforms/*/inputs/*/typeRef", "Coordinator type"), N::global( - "functions/*/inputs/*/operationInput", + "transforms/*/inputs/*/operationInput", "Coordinator Operation", ), N::global( - "functions/*/inputs/*/operationOutput", + "transforms/*/inputs/*/operationOutput", "Coordinator Operation", ), N::global( - "functions/*/inputs/*/operationRefusal", + "transforms/*/inputs/*/operationRefusal", "Coordinator Operation", ), N::global( - "functions/*/inputs/*/completionOutput/operation", + "transforms/*/inputs/*/completionOutput/operation", "Coordinator Operation", ), - N::global("functions/*/output/typeRef", "Coordinator type"), - N::global("functions/*/output/operationInput", "Coordinator Operation"), + N::global("transforms/*/output/typeRef", "Coordinator type"), N::global( - "functions/*/output/operationOutput", + "transforms/*/output/operationInput", "Coordinator Operation", ), N::global( - "functions/*/output/operationRefusal", + "transforms/*/output/operationOutput", "Coordinator Operation", ), N::global( - "functions/*/output/completionOutput/operation", + "transforms/*/output/operationRefusal", + "Coordinator Operation", + ), + N::global( + "transforms/*/output/completionOutput/operation", "Coordinator Operation", ), N::global("operations/*/responseSchema/typeRef", "Coordinator type"), @@ -252,7 +255,7 @@ pub(super) const DOCUMENTS: &[DocumentRules] = &[ references: REFERENCES, // Assets remain navigation targets; no Rhai or generated contract bytes are indexed. files: &[ - FileRule::root("functions/*/source", false), + FileRule::root("transforms/*/source", false), FileRule::root("contracts/*/source", false), ], }, diff --git a/crates/registry-language-server/tests/coordinator_navigation.rs b/crates/registry-language-server/tests/coordinator_navigation.rs index c4d256e462..1562a85e0e 100644 --- a/crates/registry-language-server/tests/coordinator_navigation.rs +++ b/crates/registry-language-server/tests/coordinator_navigation.rs @@ -19,8 +19,8 @@ types: <|type|>request: {type: object} contracts: <|contract|>registry: {type: breg, source: <|contract-file|>generated/registry.json} -functions: - <|function|>make-request: +transforms: + <|transform|>make-request: runtime: rhai source: <|function-file|>functions.rhai entrypoint: make_request @@ -41,8 +41,8 @@ workflow: dataSchema: urn:example:remote-event:v1 event: {typeRef: <|event-type-use|>request} input: - type: function - function: <|event-function-use|>make-request + type: transform + transform: <|event-function-use|>make-request inputs: {request: {type: input}} review: outcomes: @@ -53,8 +53,8 @@ workflow: type: call operation: <|operation-use|>read-record input: - type: function - function: <|function-use|>make-request + type: transform + transform: <|function-use|>make-request inputs: {request: {type: input}} next: <|next-use|>complete <|finish|>complete: @@ -66,7 +66,7 @@ workflow: record: {type: step, step: <|step-use|>read} literal: type: literal - value: {type: function, function: not-a-local-function, step: not-a-local-step, typeRef: not-a-local-type} + value: {type: transform, transform: not-a-local-function, step: not-a-local-step, typeRef: not-a-local-type} outcomes: <|outcome|>handled: {operationOutput: <|output-operation-use|>read-record} "#; @@ -100,8 +100,8 @@ fn coordinator_native_review_and_event_edges_resolve_without_claiming_external_n ("operation-use", "operation", "read-record"), ("output-operation-use", "operation", "read-record"), ("contract-use", "contract", "registry"), - ("function-use", "function", "make-request"), - ("event-function-use", "function", "make-request"), + ("function-use", "transform", "make-request"), + ("event-function-use", "transform", "make-request"), ("start-use", "step", "read"), ("next-use", "finish", "complete"), ("step-use", "step", "read"), @@ -262,7 +262,7 @@ async fn coordinator_discovery_unsaved_diagnostics_and_watched_assets_use_the_re ); let changed = source - .replace("function: make-request", "function: unknown-function") + .replace("transform: make-request", "transform: unknown-function") .replace("operation: read-record", "operation: unknown-operation") .replace("start: read", "start: unknown-step") .replace("typeRef: request", "typeRef: unknown-type") diff --git a/docs/site/src/content/docs/configure/coordinator.mdx b/docs/site/src/content/docs/configure/coordinator.mdx index e6d4593921..d3772511bd 100644 --- a/docs/site/src/content/docs/configure/coordinator.mdx +++ b/docs/site/src/content/docs/configure/coordinator.mdx @@ -136,17 +136,18 @@ read-application: `type: input` reads the run's input, `type: step` an earlier call's output, and `type: literal` a fixed value. A `path` is a JSON Pointer into it. `type: fields` builds an object of up to 64 -members, and `type: function` computes the value with a Function, as `permission` and `notify` do. +members, and `type: transform` computes the value with a Transform, as `permission` and `notify` do. {/* Evidence: crates/registry-coordinator/src/cli.rs, render_explain; crates/registry-coordinator/src/authoring.rs, AuthoredStep, Mapping; crates/registry-coordinator/src/operations.rs, CATALOG. */} -## Functions +## Transforms -`notice-route` and `notice-request` are Rhai entrypoints in `functions.rhai`. `workflow.yaml` -declares each one's inputs and output by schema, here the read operation's output and the -Messaging operation's input: +Declare `notice-route` and `notice-request` under `transforms` in `workflow.yaml`. +Each [Transform](../../reference/glossary/#transform) names a Rhai entrypoint in `functions.rhai` +and declares its input and output schemas. +This Transform reads the BReg operation's output and produces the Messaging operation's input. ```yaml title="follow-up/workflow.yaml" test-excerpt="follow-up/workflow.yaml" notice-request: @@ -162,13 +163,17 @@ notice-request: operationInput: notices-submit-message ``` -A Function is pure: it has no clock, network, database, file, or credential. The host checks its +A Transform is pure: it has no clock, network, database, file, or credential. The host checks its inputs and output against those schemas and stops it at the limits `check --explain` prints. -`add_seconds` and `seconds_between` compute over instants a Function is given. +`add_seconds` and `seconds_between` compute over instants a Transform is given. {/* Evidence: crates/registry-coordinator/src/functions.rs; crates/registry-coordinator/src/definition.rs, FunctionLimits. */} +If you are upgrading an authored workflow, rename its `functions` section to `transforms`. +In each mapping, change `type: function` to `type: transform` and rename its `function` member +to `transform`. Then run `coordinatorctl check --project ./follow-up`. + ## Check a change `check` fits every mapping to the schemas it reads and feeds. Misspell the input member the read @@ -216,7 +221,7 @@ Valid runtime configuration ``` The `Definition:` digest is the workflow revision. It hashes what execution depends on: input, -steps, outcomes, and the operation and Function revisions used. Labels, descriptions (including `project.label` and `project.description`), and +steps, outcomes, and the operation and Transform revisions used. Labels, descriptions (including `project.label` and `project.description`), and `project.version` do not change it. Every run records the revision it was admitted under. {/* Evidence: crates/registry-coordinator/src/mapping_check.rs; @@ -250,7 +255,7 @@ The schema execution profile is pinned in every snapshot; unknown formats and re ### Build nested objects A `fields` mapping builds an object member by member. -Each member is a reference (`input`, `step`, or `literal`) or another `fields` mapping, so a workflow builds a structured operation input without a Function: +Each member is a reference (`input`, `step`, or `literal`) or another `fields` mapping, so a workflow builds a structured operation input without a Transform: ```yaml start: @@ -278,8 +283,8 @@ start: Nesting reaches a depth of 4, counting the outermost mapping as 1, and the whole mapping holds at most 64 members across all levels. A nested object counts as one member, and so does each of its own members. -A nested member holds only references and further `fields` mappings, never a Function: compute such a value in an earlier step and reference it. -`wait-until`, `choose`, and Function `inputs` still take references only. +A nested member holds only references and further `fields` mappings, never a Transform: compute such a value in an earlier step and reference it. +`wait-until`, `choose`, and Transform `inputs` still take references only. Compilation refuses a fifth level with `mapping.fields-depth` and a 65th member with `mapping.fields-count`, each at the member's path. The compiler checks every member against the operation input schema at that member's path, and the built object is validated again before preparation. @@ -311,7 +316,7 @@ size: Conditions run in order and stop at the first decisive one, so `present: true` before a numeric test guards an optional value. A missing or wrongly typed value in any other test fails the run with `choice-invalid`; it never routes silently to `unmatched`. -A compare holds no Function and no clock. +A compare holds no Transform and no clock. A compare treats the numbers `4` and `4.0` as equal, as JSON Schema does. Casework routing uses the same `equals` and `oneOf` names but compares JSON values exactly, so `4` and `4.0` differ there. @@ -377,12 +382,12 @@ Give the deadline route its own steps, such as a notice and a finish, disjoint f {/* Evidence: crates/registry-coordinator/src/authoring.rs service_deadline_seconds, on_deadline. */} -### Function helpers +### Transform helpers Each Rhai entrypoint takes one object of its declared named inputs and returns one typed value. -A Function declares `runtime`, `source`, `entrypoint`, `inputs`, and `output`. +A Transform declares `runtime`, `source`, `entrypoint`, `inputs`, and `output`. Explicit limits can only narrow the host's ceilings on operations, calls, expressions, strings, arrays, maps, and source size. -A Function cannot obtain credentials, read a clock, or reach a filesystem, network, or database, and it cannot construct workflow steps. +A Transform cannot obtain credentials, read a clock, or reach a filesystem, network, or database, and it cannot construct workflow steps. The profile's callable names are the interpreter's own calls, the arithmetic, logic, string, array, map, and iterator packages, and these helpers: @@ -396,14 +401,14 @@ The trigonometric, hyperbolic, exponential, and logarithmic functions are not av A result that holds NaN or an infinite number is refused with `function.execution`. A top-level `const` is not visible inside a function: read it as `global::NAME` or pass it as an input. -`check` reports a call to any other name as `coordinator.function.unknown-call` at its position in the Function source, unless the source defines that name. -Calls are matched by name only, so a wrong argument count still fails when the Function runs. -The check is an authoring aid, not a security boundary: the engine refuses any name it lacks when the Function runs. +`check` reports a call to any other name as `coordinator.transform.unknown-call` at its position in the Transform source, unless the source defines that name. +Calls are matched by name only, so a wrong argument count still fails when the Transform runs. +The check is an authoring aid, not a security boundary: the engine refuses any name it lacks when the Transform runs. It also reads a string literal given to `Fn`, `is_def_fn`, or an array method such as `map` as a function name, and skips a method call whose name the source also uses as a map key or property. -`coordinatorctl explain functions` prints the names, the interpreter ABI, and the limits. +`coordinatorctl explain transforms` prints the names, the interpreter ABI, and the limits. The ABI names the helper set, so a definition frozen under an earlier ABI is refused with `definition.abi` and the project is re-authored. -{/* Evidence: crates/registry-coordinator/tests/helper_functions.rs coordinator.function.unknown-call; +{/* Evidence: crates/registry-coordinator/tests/helper_functions.rs coordinator.transform.unknown-call; crates/registry-coordinator/src/functions.rs; crates/registry-coordinator/src/definition.rs definition.abi. */} @@ -522,8 +527,8 @@ await-review: `timeoutSeconds` is required and shorter than the run deadline. Casework submission exposes `result`, and the BReg Proposal operations expose `proposal`. The payment collection operations expose `collection` and the disbursement operations expose `disbursement`, as [Collect and disburse payments](#collect-and-disburse-payments) describes. -An external GET operation can declare a named `bounded-poll` completion with a typed pure `interpret` Function and `intervalSeconds`. -The Function receives the saved command and the latest validated response and returns `pending`, `complete` with a typed result, or a declared `refused` code. +An external GET operation can declare a named `bounded-poll` completion with a typed pure `interpret` Transform and `intervalSeconds`. +The Transform receives the saved command and the latest validated response and returns `pending`, `complete` with a typed result, or a declared `refused` code. The host owns transport, credentials, permitted destinations, scheduling, correlation, and the durable read budget, and the workflow graph stays acyclic. External polling is independent of Casework and BReg, and neither external operation offers an arbitrary HTTP method or a dynamic destination. @@ -863,7 +868,7 @@ An `external.get/v1` alias can specialise its validated response and declare a b `external.command/v1` sends one POST to a provider the operator configured. Workflow data supplies only the JSON body; the runtime connection fixes the origin, the exact relative `commandPath`, and the credential, and redirects are never followed. A connection without `commandPath` stays read-only, and `check` refuses a command alias bound to it or to a connection of another type. -The alias names a required `interpret` Function and can specialise the provider's `{status, body}` response: +The alias names a required `interpret` Transform and can specialise the provider's `{status, body}` response: ```yaml types: @@ -887,7 +892,7 @@ types: properties: state: {type: string, const: uncertain} -functions: +transforms: bill-outcome: runtime: rhai source: functions.rhai @@ -905,14 +910,14 @@ operations: interpret: bill-outcome ``` -The Function reads the frozen command and the validated response, held to the alias's `responseSchema`, and returns `accepted` with a result, `refused` with a declared code, or `uncertain`. +The Transform reads the frozen command and the validated response, held to the alias's `responseSchema`, and returns `accepted` with a result, `refused` with a declared code, or `uncertain`. The step output is the accepted `result`, typed by the `bill` schema in this example. A declared code takes `onDeclaredRefusal` as `{refusalCode}`, and an interpreter that never returns `refused` has no refusal route. -Return `uncertain` for any answer the Function does not recognise, so the run holds instead of guessing. +Return `uncertain` for any answer the Transform does not recognise, so the run holds instead of guessing. An accepted result is the provider's answer as the project interprets it; Coordinator does not independently verify the provider's effect. -Only a response whose status Coordinator neither holds nor retries reaches the Function: a redirect, a 429, and any 5xx never do. -Fixtures reply to the step with `type: response` and a `{status, body}` value, which the same Function interprets, and the status must be one the Function sees at run time. +Only a response whose status Coordinator neither holds nor retries reaches the Transform: a redirect, a 429, and any 5xx never do. +Fixtures reply to the step with `type: response` and a `{status, body}` value, which the same Transform interprets, and the status must be one the Transform sees at run time. A `success` or `declared-refusal` reply to the step is refused. `coordinatorctl test` refuses a `response` reply with a redirect, 429, or 5xx status at `scenario.reply`, naming the `uncertain` or `retryable` reply that models it. @@ -1069,7 +1074,7 @@ same for Python. Regenerate after any change that moves the revision. Give the operator the package directory, its package digest, and a `runtime.yaml` template with secret references and no secret values. For each connection, list the product, the access profile -or review policy it needs, and for Messaging the template and sender profile the Functions name. +or review policy it needs, and for Messaging the template and sender profile the Transforms name. The operator pins the package in `deployment.packages` by `root` and `expectedDigest`. One deployment serves up to sixteen workflows; each is applied, upgraded, and rolled back on its own, and a run keeps the definition it started with. diff --git a/docs/site/src/content/docs/operate/coordinator.mdx b/docs/site/src/content/docs/operate/coordinator.mdx index f95a9c5639..489c3612e1 100644 --- a/docs/site/src/content/docs/operate/coordinator.mdx +++ b/docs/site/src/content/docs/operate/coordinator.mdx @@ -150,7 +150,7 @@ Retain the keys needed to read those snapshots and the custody metadata needed f Pin the package digest for exact bytes; use `workflowRevision` for execution semantics. -- The computed workflow revision hashes the input, graph, outcomes, used Operation and Function revisions, and host execution contracts. +- The computed workflow revision hashes the input, graph, outcomes, used Operation and Transform revisions, and host execution contracts. Presentation labels and descriptions do not change it. `check` prints it on its `Definition:` line, and start, status, list, and inspect report it as `workflowRevision`. Existing runs keep their admitted revision. @@ -1067,7 +1067,7 @@ An `external.command/v1` call has no read-only receipt, so `reconcile` reports ` The run holds at once with the effect unknown, and `retry-same` resends the same command while the deadline is still in the future. A 429 the deadline ends still ends the run `expired`. - A command ignores a `Retry-After` it cannot use, such as a date, a duplicate field, a malformed value, or a wait over 86,400 seconds, and retries on the ordinary backoff instead. -- Any other server error, a redirect, a timeout, a lost acknowledgement, or a response the interpretation Function cannot settle holds the run as uncertain. +- Any other server error, a redirect, a timeout, a lost acknowledgement, or a response the interpretation Transform cannot settle holds the run as uncertain. - After an uncertain attempt, including a retried 503, a declared refusal or 429 keeps the run held. Check the provider's record and cancel the run if no further step is wanted. diff --git a/docs/site/src/content/docs/reference/glossary.mdx b/docs/site/src/content/docs/reference/glossary.mdx index eecbeea412..d0cf3c90f0 100644 --- a/docs/site/src/content/docs/reference/glossary.mdx +++ b/docs/site/src/content/docs/reference/glossary.mdx @@ -111,7 +111,7 @@ Product names are always in English, including on future translated pages.
An `evidence.yaml` file and the scripts it names, kept in version control, declaring assertion definitions, sources, lookups, and Functions. `evidencectl` checks, tests, and packages it with a target into a deployment candidate.
Function
-
A project-local typed implementation asset. In BReg, an Action's Plan uses one to compute effects within the Action's declared write ceiling; it cannot grant authority or invent a review decision. In an Evidence project, a Rhai script with the `assertion-derive/v1` interface that turns a source route's validated facts into declared outputs, under fixed operation and size limits. Provider response normalisation belongs to the reviewed Adapter pack. In a Registry Coordinator workflow, a Rhai script that routes a `choose` step or computes a value a call's input maps with `type: function`, with no clock, file, network, database, or credentials.
+
A project-local typed implementation asset. In BReg, an Action's Plan uses one to compute effects within the Action's declared write ceiling; it cannot grant authority or invent a review decision. In an Evidence project, a Rhai script with the `assertion-derive/v1` interface that turns a source route's validated facts into declared outputs, under fixed operation and size limits. Provider response normalisation belongs to the reviewed Adapter pack.
grant ceiling
The widest authority a Registry Evidence assertion definition lets any grant give for it: the authorities, actor kinds, value origins, and audiences a grant may name. A target authority's grant may only narrow it; Registry Evidence refuses to activate one that widens it.
@@ -296,6 +296,9 @@ Product names are always in English, including on future translated pages.
team
A named Casework group that serves queues and declares the profiles its members and supervisors must hold; its membership lives in the directory.
+
Transform
+
A bounded Rhai computation in a Registry Coordinator workflow. A `type: transform` mapping calls it with named, typed inputs. It can select a branch or compute an operation value using only the supplied data.
+
trust domain
The institutional boundary whose operators, runtime identities, policy, keys, and approval govern one deployment. A Registry Evidence process serves one trust domain, named by the URI in `service.trustDomain`, with one signer and one audit boundary.
diff --git a/docs/site/src/content/docs/security/coordinator.mdx b/docs/site/src/content/docs/security/coordinator.mdx index d7a61e323a..150a5b50fa 100644 --- a/docs/site/src/content/docs/security/coordinator.mdx +++ b/docs/site/src/content/docs/security/coordinator.mdx @@ -25,7 +25,7 @@ Deployment steps are in [Deploy Registry Coordinator](../../operate/coordinator/ Adapter payment connection. Operator configuration is trusted; workflow data is not. - A workflow author writes a project that Coordinator freezes into a definition. - The author supplies bodies, mappings and pure Functions. + The author supplies bodies, mappings and pure Transforms. The author does not choose destinations, headers, credentials or recovery behaviour; the closed operation catalogue does. - Providers decide every effect a run requests: Registry Casework, Registry Scheduling, BReg, the @@ -232,12 +232,12 @@ Enforcement: Once the request may have left, a lost or broken exchange, a timeout, a redirect, any other 5xx, and an oversize, malformed or schema-invalid response are uncertain and hold the run. - Coordinator checks the response against the alias's `responseSchema`, then runs the project's - pinned pure Function. + pinned pure Transform. Only `accepted` with a result matching the step's declared output, or `refused` with a declared - code, leaves the hold; everything else, including a Function error, is uncertain. - The worker and offline scenarios use the same Function, and scenario validation + code, leaves the hold; everything else, including a Transform error, is uncertain. + The worker and offline scenarios use the same Transform, and scenario validation (`scenario.reply`) refuses a `success` or `declared-refusal` reply to the step, so no scenario - reaches a result or refusal route the Function would not produce. + reaches a result or refusal route the Transform would not produce. Transport and scenario validation share one status classification, so a `response` reply with a status the worker holds or retries before interpretation (a redirect, a 429 or any 5xx) is refused too. @@ -489,9 +489,9 @@ Refused: a metadata answer beyond 8 MiB; any business answer beyond 64 KiB. derived_response_limits_retain_credentials_and_leave_the_original_bound_unchanged. These HTTP fixtures do not establish database transaction or deployed service behavior. */} -### COORDINATOR-INV-09: the pure Function profile is bounded and deterministic +### COORDINATOR-INV-09: the pure Transform profile is bounded and deterministic -Threat: a pure Function runs author-supplied code inside the worker. +Threat: a pure Transform runs author-supplied code inside the worker. An argument-controlled loop or allocation could hold a worker thread or exhaust memory. A host-dependent result could differ when a wait replays or a job attempt recomputes, and a changed engine could reinterpret a frozen definition. @@ -535,18 +535,18 @@ Enforcement: functions take results from the platform math library and may differ in the last digits between operating systems, CPU architectures or library versions. Results are recomputed, not only read back: a held wait is recomputed when waits replay, the next - WaitUntil is evaluated again, and each job attempt runs the Function again. + WaitUntil is evaluated again, and each job attempt runs the Transform again. A deadline computed with such a function could therefore land a second apart on two hosts. Coordinator registers only deterministic functions: `sqrt`, `floor`, `ceiling`, `round`, `int`, `fraction`, `is_nan`, `is_finite`, `is_infinite`, `to_degrees`, `to_radians`, `PI`, `E`, `parse_int`, `parse_float`, `to_int` and `to_float`, next to the arithmetic package's `abs`, `sign`, `min` and `max`. -- A Function result holding NaN or an infinite float (`0.0 / 0.0`, `sqrt(-1.0)`) is refused with +- A Transform result holding NaN or an infinite float (`0.0 / 0.0`, `sqrt(-1.0)`) is refused with `function.execution` where results turn into JSON, instead of becoming `null`. - The unknown-call check walks the syntax tree and function table, which Rhai exposes only under its `internals` feature, enabled in the build. It is an authoring aid, not a security boundary: the engine refuses any name it lacks when the - Function runs. + Transform runs. Refused: empty-padding `pad`; `pad` or `replace` results over the string budget; NaN and infinity results; a definition frozen under another interpreter identity; any function outside the @@ -616,7 +616,7 @@ admission. Startup refuses a profile without `subjects`. Threat: every workflow in a deployment calls Casework under the same review producer identity, so Casework cannot tell which run submitted a review request. -A cancel whose `request` is built from input, a literal, a Function or another step could withdraw +A cancel whose `request` is built from input, a literal, a Transform or another step could withdraw a review that another run submitted. Enforcement: check refuses a `casework.cancel-review-request/v1` step unless its input is a fields @@ -891,7 +891,7 @@ The residuals refer to them by number. A live run whose retained definition a version does not restore, under another interpreter identity or a restore rule it breaks, is held with `definition-refused`, and only a release that accepts its definition can end it (COORDINATOR-INV-12). -9. Treat a project's Function as reviewed code: a Function that maps an ambiguous provider answer +9. Treat a project's Transform as reviewed code: a Transform that maps an ambiguous provider answer to `accepted` is an authoring defect that scenarios and review must catch. 10. List in each access profile's `subjects` only the identities it is meant to admit: a producer client's own service-account subject, or the named operators. @@ -987,10 +987,10 @@ Each residual names the condition under which it applies, its consequence, and t - Consequence: `reconcile` cannot settle an uncertain command. - Mitigation: check the provider's records, then retry or cancel the held run. -### COORDINATOR-RES-08: an accepted result is the Function's reading +### COORDINATOR-RES-08: an accepted result is the Transform's reading - Condition: Coordinator does not independently verify the provider's effect. -- Consequence: a Function that maps an ambiguous answer to `accepted` records an effect that may +- Consequence: a Transform that maps an ambiguous answer to `accepted` records an effect that may not have happened. - Mitigation: cover ambiguous answers in scenarios and review. @@ -1106,7 +1106,7 @@ Each residual names the condition under which it applies, its consequence, and t ### COORDINATOR-RES-19: float `**` is not on the deterministic math list -- Condition: a Function uses float `**` (`powf`, in the arithmetic package). +- Condition: a Transform uses float `**` (`powf`, in the arithmetic package). - Consequence: its result is not covered by the deterministic-math rule, so last digits could differ across hosts. - Mitigation: do not derive a deadline or a comparison threshold from float `**`. diff --git a/docs/site/src/content/docs/start/coordinator.mdx b/docs/site/src/content/docs/start/coordinator.mdx index fa5ad46650..0f5cf575a2 100644 --- a/docs/site/src/content/docs/start/coordinator.mdx +++ b/docs/site/src/content/docs/start/coordinator.mdx @@ -39,9 +39,9 @@ cannot restore that definition holds the run. A workflow is built from five step types: - `call` runs one product operation. -- `choose` routes on one typed value, on a pure [Function](../../reference/glossary/#function) +- `choose` routes on one typed value, on a pure [Transform](../../reference/glossary/#function) written in bounded [Rhai](../../reference/glossary/#rhai), or on a `compare` of typed values that - needs no Function. In a `compare`, a value that is missing or of the wrong type fails the run + needs no Transform. In a `compare`, a value that is missing or of the wrong type fails the run instead of routing to `unmatched`. The `present` test is the exception, because it reads absence. - `wait-until` waits for an instant. - `wait-for` waits for a named result, such as a Casework review decision. @@ -49,7 +49,7 @@ A workflow is built from five step types: `coordinatorctl check` compiles the project offline. It proves that each step a mapping reads has run on every route that reaches it, and it checks each path against the declared schemas. Values a -schema leaves open, and values a Function computes, are left to scenarios and the runtime. +schema leaves open, and values a Transform computes, are left to scenarios and the runtime. `coordinatorctl package` freezes the project into an immutable [package](../../reference/glossary/#package) whose digest the deployment pins. diff --git a/products/adapter/examples/kobotoolbox-job/workflow/workflow.yaml b/products/adapter/examples/kobotoolbox-job/workflow/workflow.yaml index e449f06d23..dd9a02a1e2 100644 --- a/products/adapter/examples/kobotoolbox-job/workflow/workflow.yaml +++ b/products/adapter/examples/kobotoolbox-job/workflow/workflow.yaml @@ -40,7 +40,7 @@ contracts: households: type: breg source: generated/households.contract.json -functions: +transforms: proposal-request: runtime: rhai source: functions.rhai @@ -132,8 +132,8 @@ workflow: type: call operation: submit-household input: - type: function - function: proposal-request + type: transform + transform: proposal-request inputs: event: {type: input, path: /event} next: await-proposal @@ -155,8 +155,8 @@ workflow: type: call operation: lookup-household input: - type: function - function: lookup-request + type: transform + transform: lookup-request inputs: event: {type: input, path: /event} next: review-resolved @@ -165,8 +165,8 @@ workflow: type: call operation: submit-review input: - type: function - function: resolved-review-request + type: transform + transform: resolved-review-request inputs: event: {type: input, path: /event} lookup: {type: step, step: lookup-revised} @@ -181,8 +181,8 @@ workflow: type: call operation: submit-review input: - type: function - function: unresolved-review-request + type: transform + transform: unresolved-review-request inputs: event: {type: input, path: /event} next: await-unresolved-review @@ -196,8 +196,8 @@ workflow: type: call operation: submit-review input: - type: function - function: returned-review-request + type: transform + transform: returned-review-request inputs: event: {type: input, path: /event} next: await-returned-review diff --git a/products/coordinator/AGENTS.md b/products/coordinator/AGENTS.md index 8ca991b8c2..548afa576e 100644 --- a/products/coordinator/AGENTS.md +++ b/products/coordinator/AGENTS.md @@ -36,8 +36,8 @@ receives the call, which decides it under its own authorization. that contract. Wake-ups only advance an eligible authoritative read and start no run. Keep the durable observation floor, budget, correlation, and original deadline intact across recovery. -- Keep the canonical authoring separation: contracts, types, named pure Functions, - local exact Operation aliases, and one Workflow graph. Functions take one typed +- Keep the canonical authoring separation: contracts, types, named pure Transforms, + local exact Operation aliases, and one Workflow graph. Transforms take one typed object of named inputs and gain no I/O capability. Runtime uses one tagged connections map. Each exact verified client identity resolves one access profile, which scopes run actions through workflows. Start requires the expected workflowRevision. diff --git a/products/coordinator/CHANGELOG.md b/products/coordinator/CHANGELOG.md index b0d0a6f445..6f74ab51fe 100644 --- a/products/coordinator/CHANGELOG.md +++ b/products/coordinator/CHANGELOG.md @@ -2,6 +2,8 @@ ## Unreleased +- BREAKING: Name the bounded Rhai computations in a Coordinator workflow Transforms. Rename `functions` to `transforms` and use `type: transform` with a `transform` member in mappings. Use `coordinatorctl explain transforms` for the interpreter helpers and update diagnostic consumers from `coordinator.function.*` to `coordinator.transform.*`. Retained definition snapshots keep their reader and revision format. + ## 0.49.0 - 2026-12-01 - BREAKING: BReg record operation outputs use `revisionId` and the updated Registry Record metadata names. Migration: update workflow mappings and fixture replies, then recompile against the regenerated operation contracts. diff --git a/products/coordinator/examples/decision-follow-up/README.md b/products/coordinator/examples/decision-follow-up/README.md index 02d0359e5a..fc1f38383e 100644 --- a/products/coordinator/examples/decision-follow-up/README.md +++ b/products/coordinator/examples/decision-follow-up/README.md @@ -77,5 +77,5 @@ cp /tmp/applications-actions/generated/action-contracts.json \ ``` Review a changed contract before packaging a new workflow version. -Functions declare named input schemas and take one object of those inputs; they do not select +Transforms declare named input schemas and take one object of those inputs; they do not select transport credentials or replace the imported Action contract. diff --git a/products/coordinator/examples/decision-follow-up/workflow.yaml b/products/coordinator/examples/decision-follow-up/workflow.yaml index 7a06a1f976..68aa6f1002 100644 --- a/products/coordinator/examples/decision-follow-up/workflow.yaml +++ b/products/coordinator/examples/decision-follow-up/workflow.yaml @@ -23,7 +23,7 @@ contracts: applications: type: breg source: generated/applications.contract.json -functions: +transforms: assessment-request: runtime: rhai source: functions.rhai @@ -75,8 +75,8 @@ workflow: type: call operation: assessor-evaluate-decision input: - type: function - function: assessment-request + type: transform + transform: assessment-request inputs: input: type: input @@ -84,8 +84,8 @@ workflow: route: type: choose choose: - type: function - function: assessment-route + type: transform + transform: assessment-route inputs: reply: type: step @@ -98,8 +98,8 @@ workflow: type: call operation: applications-invoke-breg-action input: - type: function - function: action-request + type: transform + transform: action-request inputs: input: type: input diff --git a/products/coordinator/examples/deferred-appointment/workflow.yaml b/products/coordinator/examples/deferred-appointment/workflow.yaml index 13e5058a63..6e9c0b16fe 100644 --- a/products/coordinator/examples/deferred-appointment/workflow.yaml +++ b/products/coordinator/examples/deferred-appointment/workflow.yaml @@ -40,7 +40,7 @@ types: expiresAt: type: integer minimum: 1 -functions: +transforms: appointment-route: runtime: rhai source: functions.rhai @@ -129,8 +129,8 @@ workflow: eligibility: type: choose choose: - type: function - function: appointment-route + type: transform + transform: appointment-route inputs: record: type: step @@ -173,8 +173,8 @@ workflow: capacity: type: choose choose: - type: function - function: capacity-route + type: transform + transform: capacity-route inputs: availability: type: step @@ -186,8 +186,8 @@ workflow: type: call operation: bookings-create-appointment input: - type: function - function: booking-request + type: transform + transform: booking-request inputs: input: type: input @@ -202,8 +202,8 @@ workflow: type: call operation: notices-submit-message input: - type: function - function: notice-request + type: transform + transform: notice-request inputs: input: type: input diff --git a/products/coordinator/examples/delayed-follow-up/workflow.yaml b/products/coordinator/examples/delayed-follow-up/workflow.yaml index d7aaa06e93..163c28a75c 100644 --- a/products/coordinator/examples/delayed-follow-up/workflow.yaml +++ b/products/coordinator/examples/delayed-follow-up/workflow.yaml @@ -18,7 +18,7 @@ types: sendAfter: type: string format: date-time -functions: +transforms: notice-route: runtime: rhai source: functions.rhai @@ -77,8 +77,8 @@ workflow: permission: type: choose choose: - type: function - function: notice-route + type: transform + transform: notice-route inputs: record: type: step @@ -90,8 +90,8 @@ workflow: type: call operation: notices-submit-message input: - type: function - function: notice-request + type: transform + transform: notice-request inputs: input: type: input diff --git a/products/coordinator/examples/earlier-appointment-alerts/workflow.yaml b/products/coordinator/examples/earlier-appointment-alerts/workflow.yaml index 282c245a2b..9b18615820 100644 --- a/products/coordinator/examples/earlier-appointment-alerts/workflow.yaml +++ b/products/coordinator/examples/earlier-appointment-alerts/workflow.yaml @@ -28,7 +28,7 @@ contracts: notice-templates: type: messaging source: generated/notices.contract.json -functions: +transforms: source-route: runtime: rhai source: functions.rhai @@ -155,8 +155,8 @@ workflow: source-state: type: choose choose: - type: function - function: source-route + type: transform + transform: source-route inputs: {subscription: {type: step, step: read-subscription}} cases: inspect: read-appointment @@ -167,8 +167,8 @@ workflow: type: call operation: scheduling-read-appointment input: - type: function - function: appointment-request + type: transform + transform: appointment-request inputs: input: {type: input} subscription: {type: step, step: read-subscription} @@ -176,8 +176,8 @@ workflow: appointment-state: type: choose choose: - type: function - function: appointment-route + type: transform + transform: appointment-route inputs: subscription: {type: step, step: read-subscription} appointment: {type: step, step: read-appointment} @@ -186,30 +186,30 @@ workflow: type: call operation: scheduling-preview-availability input: - type: function - function: preview-request + type: transform + transform: preview-request inputs: {subscription: {type: step, step: read-subscription}} next: capacity capacity: type: choose choose: - type: function - function: capacity-route + type: transform + transform: capacity-route inputs: {preview: {type: step, step: preview}} cases: {available: claim-state, unavailable: no-capacity} claim-state: type: choose choose: - type: function - function: claim-route + type: transform + transform: claim-route inputs: {subscription: {type: step, step: read-subscription}} cases: {claim: claim, resume: read-current-subscription} claim: type: call operation: alerts-claim input: - type: function - function: claim-request + type: transform + transform: claim-request inputs: {subscription: {type: step, step: read-subscription}} next: read-current-subscription read-current-subscription: @@ -225,8 +225,8 @@ workflow: type: call operation: scheduling-read-appointment input: - type: function - function: appointment-request + type: transform + transform: appointment-request inputs: input: {type: input} subscription: {type: step, step: read-current-subscription} @@ -234,8 +234,8 @@ workflow: final-state: type: choose choose: - type: function - function: final-route + type: transform + transform: final-route inputs: subscription: {type: step, step: read-current-subscription} appointment: {type: step, step: read-current-appointment} @@ -244,23 +244,23 @@ workflow: type: call operation: scheduling-preview-availability input: - type: function - function: preview-request + type: transform + transform: preview-request inputs: {subscription: {type: step, step: read-current-subscription}} next: final-capacity final-capacity: type: choose choose: - type: function - function: capacity-route + type: transform + transform: capacity-route inputs: {preview: {type: step, step: final-preview}} cases: {available: authorize-dispatch, unavailable: capacity-changed} authorize-dispatch: type: call operation: alerts-authorize-dispatch input: - type: function - function: authorize-request + type: transform + transform: authorize-request inputs: {subscription: {type: step, step: read-current-subscription}} next: read-dispatching-subscription read-dispatching-subscription: @@ -276,8 +276,8 @@ workflow: type: call operation: scheduling-read-appointment input: - type: function - function: appointment-request + type: transform + transform: appointment-request inputs: input: {type: input} subscription: {type: step, step: read-dispatching-subscription} @@ -285,8 +285,8 @@ workflow: dispatch-state: type: choose choose: - type: function - function: dispatch-route + type: transform + transform: dispatch-route inputs: subscription: {type: step, step: read-dispatching-subscription} appointment: {type: step, step: read-dispatching-appointment} @@ -295,16 +295,16 @@ workflow: type: call operation: notices-submit-message input: - type: function - function: notice-request + type: transform + transform: notice-request inputs: {subscription: {type: step, step: read-dispatching-subscription}} next: record-submission record-submission: type: call operation: alerts-record-submission input: - type: function - function: completion-request + type: transform + transform: completion-request inputs: subscription: {type: step, step: read-dispatching-subscription} message: {type: step, step: notify} diff --git a/products/coordinator/examples/external-directory/workflow.yaml b/products/coordinator/examples/external-directory/workflow.yaml index 62c5800893..91d8c55c8f 100644 --- a/products/coordinator/examples/external-directory/workflow.yaml +++ b/products/coordinator/examples/external-directory/workflow.yaml @@ -17,7 +17,7 @@ types: type: string minLength: 1 maxLength: 128 -functions: +transforms: lookup-request: runtime: rhai source: functions.rhai @@ -54,8 +54,8 @@ workflow: type: call operation: directory-external-get input: - type: function - function: lookup-request + type: transform + transform: lookup-request inputs: input: type: input @@ -63,8 +63,8 @@ workflow: result: type: choose choose: - type: function - function: office-route + type: transform + transform: office-route inputs: reply: type: step diff --git a/products/coordinator/examples/external-job/README.md b/products/coordinator/examples/external-job/README.md index 1e34f05720..f0c768ba36 100644 --- a/products/coordinator/examples/external-job/README.md +++ b/products/coordinator/examples/external-job/README.md @@ -11,11 +11,11 @@ coordinatorctl test --project products/coordinator/examples/external-job ``` The `read-job` Operation alias uses `external.get/v1`, specializes its response schema, and exposes -a named `terminal` completion. Its `bounded-poll` declaration names pure Function `job-observation` +a named `terminal` completion. Its `bounded-poll` declaration names pure Transform `job-observation` and a 30-second interval. The workflow reads once, then waits on `completion: {step: read, name: terminal}` for up to 600 seconds within a 900-second run deadline. -The request Function takes one named-input object and selects only the configured `jobs/status` +The request Transform takes one named-input object and selects only the configured `jobs/status` path and `id` query parameter. The interpreter receives the saved original `command` and latest validated `response`. It checks the job ID, returns `pending` for queued/running, `complete` with a typed job result for succeeded, or a declared `external-job-failed` refusal for failed. diff --git a/products/coordinator/examples/external-job/workflow.yaml b/products/coordinator/examples/external-job/workflow.yaml index a98c40d9ad..eec46cfdbb 100644 --- a/products/coordinator/examples/external-job/workflow.yaml +++ b/products/coordinator/examples/external-job/workflow.yaml @@ -50,7 +50,7 @@ types: state: {type: string, const: refused} code: {type: string, enum: [external-job-failed]} -functions: +transforms: job-request: runtime: rhai source: functions.rhai @@ -88,8 +88,8 @@ workflow: type: call operation: read-job input: - type: function - function: job-request + type: transform + transform: job-request inputs: request: {type: input} next: await-terminal diff --git a/products/coordinator/examples/governed-action-follow-up/README.md b/products/coordinator/examples/governed-action-follow-up/README.md index 6d0b753375..be48b94a67 100644 --- a/products/coordinator/examples/governed-action-follow-up/README.md +++ b/products/coordinator/examples/governed-action-follow-up/README.md @@ -96,5 +96,5 @@ cp /tmp/applications-actions/generated/action-contracts.json \ ``` Review a changed contract before packaging a new workflow version. -Functions declare named input schemas and take one object of those inputs; they do not select +Transforms declare named input schemas and take one object of those inputs; they do not select transport credentials or replace the imported Action contract. diff --git a/products/coordinator/examples/governed-action-follow-up/workflow.yaml b/products/coordinator/examples/governed-action-follow-up/workflow.yaml index 2417e1d8ef..68a5167ab0 100644 --- a/products/coordinator/examples/governed-action-follow-up/workflow.yaml +++ b/products/coordinator/examples/governed-action-follow-up/workflow.yaml @@ -18,7 +18,7 @@ contracts: applications: type: breg source: generated/applications.contract.json -functions: +transforms: information-route: runtime: rhai source: functions.rhai @@ -88,8 +88,8 @@ workflow: needs-information: type: choose choose: - type: function - function: information-route + type: transform + transform: information-route inputs: record: type: step @@ -101,8 +101,8 @@ workflow: type: call operation: applications-invoke-breg-action input: - type: function - function: action-request + type: transform + transform: action-request inputs: input: type: input @@ -115,8 +115,8 @@ workflow: type: call operation: notices-submit-message input: - type: function - function: notice-request + type: transform + transform: notice-request inputs: record: type: step diff --git a/products/coordinator/examples/invitation-booking/accept-invitation/workflow.yaml b/products/coordinator/examples/invitation-booking/accept-invitation/workflow.yaml index abbfcf22a9..87f43a7694 100644 --- a/products/coordinator/examples/invitation-booking/accept-invitation/workflow.yaml +++ b/products/coordinator/examples/invitation-booking/accept-invitation/workflow.yaml @@ -22,7 +22,7 @@ contracts: invitations: type: breg source: generated/invitations.contract.json -functions: +transforms: invitation-route: runtime: rhai source: functions.rhai @@ -131,8 +131,8 @@ workflow: current-state: type: choose choose: - type: function - function: invitation-route + type: transform + transform: invitation-route inputs: invitation: {type: step, step: read-invitation} cases: @@ -147,8 +147,8 @@ workflow: type: call operation: invitations-claim input: - type: function - function: claim-request + type: transform + transform: claim-request inputs: input: {type: input} next: read-claimed-invitation @@ -170,16 +170,16 @@ workflow: type: call operation: catalogue-read-availability input: - type: function - function: availability-request + type: transform + transform: availability-request inputs: invitation: {type: step, step: read-claimed-invitation} next: capacity capacity: type: choose choose: - type: function - function: capacity-route + type: transform + transform: capacity-route inputs: availability: {type: step, step: availability} cases: @@ -189,8 +189,8 @@ workflow: type: call operation: invitations-record-no-capacity input: - type: function - function: record-no-capacity-request + type: transform + transform: record-no-capacity-request inputs: invitation: {type: step, step: read-claimed-invitation} next: no-capacity @@ -198,8 +198,8 @@ workflow: type: call operation: book-appointment input: - type: function - function: booking-request + type: transform + transform: booking-request inputs: input: {type: input} invitation: {type: step, step: read-claimed-invitation} @@ -210,8 +210,8 @@ workflow: type: call operation: invitations-record-booking-result input: - type: function - function: record-result-request + type: transform + transform: record-result-request inputs: invitation: {type: step, step: read-claimed-invitation} appointment: {type: step, step: book} @@ -220,8 +220,8 @@ workflow: type: call operation: notices-submit-message input: - type: function - function: notice-request + type: transform + transform: notice-request inputs: invitation: {type: step, step: read-claimed-invitation} appointment: {type: step, step: book} diff --git a/products/coordinator/examples/invitation-booking/issue-invitation/workflow.yaml b/products/coordinator/examples/invitation-booking/issue-invitation/workflow.yaml index 9a0a8ebfd0..8fa14404da 100644 --- a/products/coordinator/examples/invitation-booking/issue-invitation/workflow.yaml +++ b/products/coordinator/examples/invitation-booking/issue-invitation/workflow.yaml @@ -27,7 +27,7 @@ contracts: invitations: type: breg source: generated/invitations.contract.json -functions: +transforms: issue-request: runtime: rhai source: functions.rhai @@ -62,8 +62,8 @@ workflow: type: call operation: invitations-issue input: - type: function - function: issue-request + type: transform + transform: issue-request inputs: input: {type: input} next: read-invitation @@ -80,8 +80,8 @@ workflow: type: call operation: notices-submit-message input: - type: function - function: notice-request + type: transform + transform: notice-request inputs: invitation: {type: step, step: read-invitation} next: accepted diff --git a/products/coordinator/examples/reservation-review/request-only/workflow.yaml b/products/coordinator/examples/reservation-review/request-only/workflow.yaml index bd31b3aeb1..19bbd4c272 100644 --- a/products/coordinator/examples/reservation-review/request-only/workflow.yaml +++ b/products/coordinator/examples/reservation-review/request-only/workflow.yaml @@ -23,7 +23,7 @@ types: expiresAt: {type: integer, minimum: 1} contracts: reservations: {type: breg, source: generated/reservations.contract.json} -functions: +transforms: review-request: runtime: rhai source: functions.rhai @@ -133,7 +133,7 @@ workflow: submit-review: type: call operation: review-submit - input: {type: function, function: review-request, inputs: {input: {type: input}, reservation: {type: step, step: read-source}}} + input: {type: transform, transform: review-request, inputs: {input: {type: input}, reservation: {type: step, step: read-source}}} next: await-review await-review: type: wait-for @@ -149,12 +149,12 @@ workflow: record-rejected: type: call operation: source-review-rejected - input: {type: function, function: source-rejection-request, inputs: {input: {type: input}, result: {type: step, step: await-review}}} + input: {type: transform, transform: source-rejection-request, inputs: {input: {type: input}, result: {type: step, step: await-review}}} next: rejected record-approved: type: call operation: source-review-approved - input: {type: function, function: source-decision-request, inputs: {input: {type: input}, result: {type: step, step: await-review}}} + input: {type: transform, transform: source-decision-request, inputs: {input: {type: input}, result: {type: step, step: await-review}}} next: await-agreement-fixture await-agreement-fixture: type: wait-until @@ -167,12 +167,12 @@ workflow: record-agreement-failed: type: call operation: source-agreement-failed - input: {type: function, function: agreement-failed-request, inputs: {input: {type: input}}} + input: {type: transform, transform: agreement-failed-request, inputs: {input: {type: input}}} next: agreement-failed record-agreement-completed: type: call operation: source-agreement-completed - input: {type: function, function: agreement-completed-request, inputs: {input: {type: input}}} + input: {type: transform, transform: agreement-completed-request, inputs: {input: {type: input}}} next: read-after-agreement read-after-agreement: type: call @@ -187,17 +187,17 @@ workflow: book: type: call operation: scheduling-book - input: {type: function, function: booking-request, inputs: {input: {type: input}, reservation: {type: step, step: read-after-agreement}, metadata: {type: step, step: metadata}}} + input: {type: transform, transform: booking-request, inputs: {input: {type: input}, reservation: {type: step, step: read-after-agreement}, metadata: {type: step, step: metadata}}} next: record-confirmed record-confirmed: type: call operation: source-record-confirmed - input: {type: function, function: record-confirmation-request, inputs: {input: {type: input}, appointment: {type: step, step: book}}} + input: {type: transform, transform: record-confirmation-request, inputs: {input: {type: input}, appointment: {type: step, step: book}}} next: notify notify: type: call operation: notices-submit - input: {type: function, function: notice-request, inputs: {input: {type: input}, reservation: {type: step, step: read-after-agreement}, appointment: {type: step, step: book}}} + input: {type: transform, transform: notice-request, inputs: {input: {type: input}, reservation: {type: step, step: read-after-agreement}, appointment: {type: step, step: book}}} next: confirmed cancel-review-timeout: type: call @@ -212,12 +212,12 @@ workflow: record-withdrawal-after-timeout: type: call operation: source-withdraw - input: {type: function, function: withdrawal-request, inputs: {input: {type: input}}} + input: {type: transform, transform: withdrawal-request, inputs: {input: {type: input}}} next: review-withdrawn record-withdrawal-after-cancel: type: call operation: source-withdraw - input: {type: function, function: withdrawal-request, inputs: {input: {type: input}}} + input: {type: transform, transform: withdrawal-request, inputs: {input: {type: input}}} next: review-withdrawn confirmed: type: finish diff --git a/products/coordinator/examples/reviewed-notice/workflow.yaml b/products/coordinator/examples/reviewed-notice/workflow.yaml index cba135d3fc..df320a1737 100644 --- a/products/coordinator/examples/reviewed-notice/workflow.yaml +++ b/products/coordinator/examples/reviewed-notice/workflow.yaml @@ -23,7 +23,7 @@ types: applicationDigest: type: string pattern: ^sha256:[0-9a-f]{64}$ -functions: +transforms: review-subject-route: runtime: rhai source: functions.rhai @@ -114,8 +114,8 @@ workflow: verify-review-subject: type: choose choose: - type: function - function: review-subject-route + type: transform + transform: review-subject-route inputs: input: type: input @@ -129,8 +129,8 @@ workflow: type: call operation: review-submit-review-request input: - type: function - function: review-request + type: transform + transform: review-request inputs: input: type: input @@ -176,8 +176,8 @@ workflow: verify-notice: type: choose choose: - type: function - function: notice-route + type: transform + transform: notice-route inputs: input: type: input @@ -192,8 +192,8 @@ workflow: type: call operation: notices-submit-message input: - type: function - function: notice-request + type: transform + transform: notice-request inputs: input: type: input diff --git a/products/coordinator/generated/fixture/fixture.schema.json b/products/coordinator/generated/fixture/fixture.schema.json index 3d92772d5c..511d1dc962 100644 --- a/products/coordinator/generated/fixture/fixture.schema.json +++ b/products/coordinator/generated/fixture/fixture.schema.json @@ -102,7 +102,7 @@ }, { "additionalProperties": false, - "description": "The product returned a package-declared, no-effect business refusal.\nA supported call takes its `onDeclaredRefusal` edge when it has one;\notherwise the run stops as refused. An `external.command/v1` step\ntakes a `response` reply instead, which its interpretation Function\nmay turn into a declared refusal.", + "description": "The product returned a package-declared, no-effect business refusal.\nA supported call takes its `onDeclaredRefusal` edge when it has one;\notherwise the run stops as refused. An `external.command/v1` step\ntakes a `response` reply instead, which its interpretation Transform\nmay turn into a declared refusal.", "properties": { "refusalCode": { "$ref": "#/$defs/DeclaredRefusalCode", @@ -140,7 +140,7 @@ }, { "additionalProperties": false, - "description": "The provider answered an `external.command/v1` call with `value`. The\noperation's pinned interpretation Function turns it into an accepted\nresult, a declared refusal or an uncertain outcome, as it would at run\ntime. The status must be one the worker hands to that Function: a\nredirect, a 429 or a 5xx never reaches it, so a fixture models those\nwith an `uncertain` or `retryable` reply.", + "description": "The provider answered an `external.command/v1` call with `value`. The\noperation's pinned interpretation Transform turns it into an accepted\nresult, a declared refusal or an uncertain outcome, as it would at run\ntime. The status must be one the worker hands to that Transform: a\nredirect, a 429 or a 5xx never reaches it, so a fixture models those\nwith an `uncertain` or `retryable` reply.", "properties": { "type": { "const": "response", @@ -196,7 +196,7 @@ }, { "additionalProperties": false, - "description": "The host repeats the accepted external read and interprets these\nsynthetic typed responses under the completion's named Function.", + "description": "The host repeats the accepted external read and interprets these\nsynthetic typed responses under the completion's named Transform.", "properties": { "responses": { "description": "One to 128 bounded response objects in observation order.", diff --git a/products/coordinator/generated/operations/catalog.json b/products/coordinator/generated/operations/catalog.json index bf1abe8a5a..d152b1b43c 100644 --- a/products/coordinator/generated/operations/catalog.json +++ b/products/coordinator/generated/operations/catalog.json @@ -2258,7 +2258,7 @@ }, "output": { "$schema": "https://json-schema.org/draft/2020-12/schema", - "description": "The bounded provider response. The operation's interpret Function receives it with the command and returns the step result, a declared refusal, or an uncertain outcome.", + "description": "The bounded provider response. The operation's interpret Transform receives it with the command and returns the step result, a declared refusal, or an uncertain outcome.", "properties": { "body": { "description": "The parsed JSON response body, or null for an empty body." diff --git a/products/coordinator/generated/operations/external.command.v1.output.schema.json b/products/coordinator/generated/operations/external.command.v1.output.schema.json index 5ebe3566fd..ac42a0be8b 100644 --- a/products/coordinator/generated/operations/external.command.v1.output.schema.json +++ b/products/coordinator/generated/operations/external.command.v1.output.schema.json @@ -1,6 +1,6 @@ { "$schema": "https://json-schema.org/draft/2020-12/schema", - "description": "The bounded provider response. The operation's interpret Function receives it with the command and returns the step result, a declared refusal, or an uncertain outcome.", + "description": "The bounded provider response. The operation's interpret Transform receives it with the command and returns the step result, a declared refusal, or an uncertain outcome.", "properties": { "body": { "description": "The parsed JSON response body, or null for an empty body." diff --git a/products/coordinator/generated/project/project.schema.json b/products/coordinator/generated/project/project.schema.json index 64304d2df8..533b3328f0 100644 --- a/products/coordinator/generated/project/project.schema.json +++ b/products/coordinator/generated/project/project.schema.json @@ -52,7 +52,7 @@ "properties": { "interpret": { "$ref": "#/$defs/LocalId", - "description": "The typed pure Function that turns the saved command and response into an observation." + "description": "The typed pure Transform that turns the saved command and response into an observation." }, "intervalSeconds": { "description": "Seconds between pending observations; the host may impose a stricter minimum.", @@ -174,68 +174,12 @@ ], "type": "object" }, - "AuthoredFunction": { - "additionalProperties": false, - "properties": { - "description": { - "$ref": "#/$defs/DisplayText", - "description": "An optional explanation for readers; it has no execution or authorization effect." - }, - "entrypoint": { - "description": "One public source function taking exactly one named-input object.", - "type": "string" - }, - "inputs": { - "additionalProperties": { - "$ref": "#/$defs/Schema" - }, - "description": "Named input schemas or references; every declared input is required exactly once.", - "maxProperties": 16, - "propertyNames": { - "$ref": "#/$defs/LocalId" - }, - "type": "object" - }, - "label": { - "$ref": "#/$defs/DisplayText", - "description": "An optional human label; it changes neither stable identity nor behavior revision." - }, - "limits": { - "$ref": "#/$defs/NarrowedLimits", - "description": "Optional narrowing of the bounded pure profile; omitted limits retain the default ceiling." - }, - "output": { - "$ref": "#/$defs/Schema", - "description": "The declared result schema or mapping; Functions and the host enforce it." - }, - "runtime": { - "$ref": "#/$defs/FunctionRuntime", - "description": "The pinned pure runtime; rhai has no clock, network, database or credential capability." - }, - "source": { - "description": "A local reviewed source asset inside the project directory.", - "type": "string" - } - }, - "required": [ - "runtime", - "source", - "entrypoint", - "inputs", - "output" - ], - "type": "object" - }, "AuthoredMapping": { "oneOf": [ { "additionalProperties": false, - "description": "Computes a value with a declared typed pure Function.", + "description": "Computes a value with a declared typed pure Transform.", "properties": { - "function": { - "$ref": "#/$defs/LocalId", - "description": "A declared pure Function called with an object of named inputs." - }, "inputs": { "additionalProperties": { "$ref": "#/$defs/Reference" @@ -247,14 +191,18 @@ }, "type": "object" }, + "transform": { + "$ref": "#/$defs/LocalId", + "description": "A declared pure Transform called with an object of named inputs." + }, "type": { - "const": "function", + "const": "transform", "type": "string" } }, "required": [ "type", - "function", + "transform", "inputs" ], "type": "object" @@ -399,7 +347,7 @@ }, "interpret": { "$ref": "#/$defs/LocalId", - "description": "The typed pure Function that interprets an external command's provider\nresponse into an accepted result, a declared refusal or an uncertain\noutcome. Required on, and accepted only on, `external.command/v1`." + "description": "The typed pure Transform that interprets an external command's provider\nresponse into an accepted result, a declared refusal or an uncertain\noutcome. Required on, and accepted only on, `external.command/v1`." }, "label": { "$ref": "#/$defs/DisplayText", @@ -615,7 +563,7 @@ }, "output": { "$ref": "#/$defs/AuthoredMapping", - "description": "The declared result schema or mapping; Functions and the host enforce it." + "description": "The declared result schema or mapping; Transforms and the host enforce it." }, "type": { "const": "finish", @@ -630,6 +578,58 @@ } ] }, + "AuthoredTransform": { + "additionalProperties": false, + "properties": { + "description": { + "$ref": "#/$defs/DisplayText", + "description": "An optional explanation for readers; it has no execution or authorization effect." + }, + "entrypoint": { + "description": "One public source function taking exactly one named-input object.", + "type": "string" + }, + "inputs": { + "additionalProperties": { + "$ref": "#/$defs/Schema" + }, + "description": "Named input schemas or references; every declared input is required exactly once.", + "maxProperties": 16, + "propertyNames": { + "$ref": "#/$defs/LocalId" + }, + "type": "object" + }, + "label": { + "$ref": "#/$defs/DisplayText", + "description": "An optional human label; it changes neither stable identity nor behavior revision." + }, + "limits": { + "$ref": "#/$defs/NarrowedLimits", + "description": "Optional narrowing of the bounded pure profile; omitted limits retain the default ceiling." + }, + "output": { + "$ref": "#/$defs/Schema", + "description": "The declared result schema or mapping; Transforms and the host enforce it." + }, + "runtime": { + "$ref": "#/$defs/TransformRuntime", + "description": "The pinned pure runtime; rhai has no clock, network, database or credential capability." + }, + "source": { + "description": "A local reviewed source asset inside the project directory.", + "type": "string" + } + }, + "required": [ + "runtime", + "source", + "entrypoint", + "inputs", + "output" + ], + "type": "object" + }, "AuthoredWorkflow": { "additionalProperties": false, "properties": { @@ -761,12 +761,6 @@ }, "type": "object" }, - "FunctionRuntime": { - "enum": [ - "rhai" - ], - "type": "string" - }, "ImportedContract": { "additionalProperties": false, "properties": { @@ -860,7 +854,7 @@ }, { "additionalProperties": false, - "description": "Builds a nested object member by member, never with a Function.", + "description": "Builds a nested object member by member, never with a Transform.", "properties": { "fields": { "$ref": "#/$defs/Fields", @@ -1101,6 +1095,12 @@ "version" ], "type": "object" + }, + "TransformRuntime": { + "enum": [ + "rhai" + ], + "type": "string" } }, "$id": "https://id.registrystack.org/schemas/coordinator/project/project.v1alpha1.schema.json", @@ -1123,18 +1123,6 @@ }, "type": "object" }, - "functions": { - "additionalProperties": { - "$ref": "#/$defs/AuthoredFunction" - }, - "description": "Named typed bounded pure computations over one object of named inputs.", - "maxProperties": 128, - "minProperties": 0, - "propertyNames": { - "$ref": "#/$defs/LocalId" - }, - "type": "object" - }, "kind": { "const": "CoordinatorProject", "description": "The kind of document this is.", @@ -1173,6 +1161,18 @@ "description": "The shared Project identity; its version is a human release label, not the computed Workflow revision.", "unevaluatedProperties": false }, + "transforms": { + "additionalProperties": { + "$ref": "#/$defs/AuthoredTransform" + }, + "description": "Named typed bounded pure computations over one object of named inputs.", + "maxProperties": 128, + "minProperties": 0, + "propertyNames": { + "$ref": "#/$defs/LocalId" + }, + "type": "object" + }, "types": { "additionalProperties": { "$ref": "#/$defs/Schema" From 7de192b82d3cc047f87977b3a4c50e430f214f43 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 16:08:59 +0000 Subject: [PATCH 021/183] fix(coordinator): align generated path parameter names Signed-off-by: Jeremi Joslin (cherry picked from commit a6fb970cff0279d89e2fdda8b62bdb8319473e9c) --- .../typescript/tests/live/products.live.ts | 6 +- clients/typescript/tests/media.test.ts | 12 +-- clients/typescript/tests/page.test.ts | 2 +- crates/registry-coordinator/src/http.rs | 73 ++++++++++++++++--- .../src/http/admission_contracts.rs | 4 +- .../content/docs/configure/adapter-jobs.mdx | 2 +- .../content/docs/configure/coordinator.mdx | 2 +- .../src/content/docs/operate/coordinator.mdx | 2 +- .../content/docs/reference/api-stability.mdx | 8 +- .../reference/apis/registry-coordinator.mdx | 10 +-- .../src/content/docs/start/coordinator.mdx | 2 +- 11 files changed, 87 insertions(+), 36 deletions(-) diff --git a/clients/typescript/tests/live/products.live.ts b/clients/typescript/tests/live/products.live.ts index 2a8f564d44..85488bea88 100644 --- a/clients/typescript/tests/live/products.live.ts +++ b/clients/typescript/tests/live/products.live.ts @@ -157,7 +157,7 @@ export function registerServerLiveMatrix( token: () => manifest.tokens.coordinatorCaller, })) const workflow = await client.call('workflowContract', { - path: { workflow: manifest.metadata.coordinatorWorkflow }, + path: { workflowId: manifest.metadata.coordinatorWorkflow }, }) assert.equal(workflow.status, 200) assert.equal(workflow.developmentPeer, true) @@ -180,12 +180,12 @@ export function registerServerLiveMatrix( }) assert.equal(replayed.data.runId, started.data.runId) - const status = await client.call('runStatus', { path: { run: started.data.runId } }) + const status = await client.call('runStatus', { path: { runId: started.data.runId } }) assert.equal(status.data.runId, started.data.runId) const anon = new CoordinatorClient(new Transport({ baseUrl: manifest.products.coordinator, token: () => undefined })) await expectUnauthorized(anon.call('workflowContract', { - path: { workflow: manifest.metadata.coordinatorWorkflow }, + path: { workflowId: manifest.metadata.coordinatorWorkflow }, })) }) diff --git a/clients/typescript/tests/media.test.ts b/clients/typescript/tests/media.test.ts index 84d7160587..b6895891cc 100644 --- a/clients/typescript/tests/media.test.ts +++ b/clients/typescript/tests/media.test.ts @@ -177,20 +177,22 @@ test('Scheduling receipt lookup needs the original key and sends exactly it as a test('a signed Coordinator event sends the signed bytes unchanged and no bearer credential', async () => { const signed = new TextEncoder().encode('{ "id" : "evt-1",\n "type": "fixture" }\n') let asked = 0 - let seen: { body: unknown; authorization: string | null; credentials: unknown } | undefined + let seen: { path: string; body: unknown; authorization: string | null; credentials: unknown } | undefined const coordinator = make(Coordinator, { baseUrl: 'https://registry.example', token: () => { asked++; return 'bearer' }, - fetch: async (_url, init) => { - seen = { body: init?.body, authorization: new Headers(init?.headers).get('authorization'), credentials: init?.credentials } + fetch: async (url, init) => { + seen = { path: new URL(String(url)).pathname, body: init?.body, + authorization: new Headers(init?.headers).get('authorization'), credentials: init?.credentials } return new Response(null, { status: 204 }) } }) const headers = { 'webhook-id': '00000000-0000-4000-8000-000000000001', 'webhook-timestamp': '1614265330', 'webhook-signature': 'v1,fixture' } - const answer = await coordinator.call('admitEvent', { path: { workflow: 'w', trigger: 't' }, headers, body: signed }) + const answer = await coordinator.call('admitEvent', { path: { workflowId: 'w', triggerId: 't' }, headers, body: signed }) assert.equal(answer.status, 204) assert.ok(seen?.body instanceof Uint8Array) + assert.equal(seen.path, '/v1/events/w/t') assert.deepEqual(seen.body, signed) assert.equal(seen.authorization, null) assert.equal(seen.credentials, 'omit') assert.equal(asked, 0) - await assert.rejects(coordinator.call('admitEvent', { path: { workflow: 'w', trigger: 't' }, headers, + await assert.rejects(coordinator.call('admitEvent', { path: { workflowId: 'w', triggerId: 't' }, headers, body: { id: 'evt-1' } as never }), { name: 'TypeError', message: 'Signed request body must be the signed bytes' }) }) diff --git a/clients/typescript/tests/page.test.ts b/clients/typescript/tests/page.test.ts index 5ba0bc7139..7c2f649dce 100644 --- a/clients/typescript/tests/page.test.ts +++ b/clients/typescript/tests/page.test.ts @@ -310,7 +310,7 @@ test('a signed operation omits cookies and keeps a 401 as a signature refusal in const { seen, fetch } = recording(() => new Response(null, { status: 401 })) const coordinator = make(Coordinator, { baseUrl, fetch }) const headers = { 'webhook-id': '00000000-0000-4000-8000-000000000001', 'webhook-timestamp': '1', 'webhook-signature': 'v1,x' } - await assert.rejects(coordinator.call('admitEvent', { path: { workflow: 'w', trigger: 't' }, headers, body: Uint8Array.of(123, 125) }), + await assert.rejects(coordinator.call('admitEvent', { path: { workflowId: 'w', triggerId: 't' }, headers, body: Uint8Array.of(123, 125) }), { reason: 'status', status: 401 }) assert.deepEqual(seen, [{ authorization: null, credentials: 'omit', page: 'page' }]) }) diff --git a/crates/registry-coordinator/src/http.rs b/crates/registry-coordinator/src/http.rs index 46776e612e..85ced4d8f8 100644 --- a/crates/registry-coordinator/src/http.rs +++ b/crates/registry-coordinator/src/http.rs @@ -1280,6 +1280,55 @@ mod problem_tests { } } + #[test] + fn openapi_uses_explicit_path_identifier_names() { + let document = openapi(); + let operations: [(&str, &str, &str, &[&str]); 8] = [ + ( + "/v1/workflows/{workflowId}", + "get", + "workflowContract", + &["workflowId"], + ), + ("/v1/runs/{runId}", "get", "runStatus", &["runId"]), + ("/v1/runs/{runId}/inspect", "get", "inspectRun", &["runId"]), + ("/v1/runs/{runId}/check", "post", "checkNow", &["runId"]), + ( + "/v1/runs/{runId}/retry-same", + "post", + "retrySame", + &["runId"], + ), + ("/v1/runs/{runId}/cancel", "post", "cancelRun", &["runId"]), + ( + "/v1/runs/{runId}/reconcile", + "post", + "reconcileRun", + &["runId"], + ), + ( + "/v1/events/{workflowId}/{triggerId}", + "post", + "admitEvent", + &["workflowId", "triggerId"], + ), + ]; + for (path, method, id, expected_names) in operations { + let operation = &document["paths"][path][method]; + assert_eq!(operation["operationId"], id, "{method} {path}"); + let parameters = operation["parameters"].as_array().unwrap(); + let names: Vec<_> = parameters + .iter() + .filter(|parameter| parameter["in"] == "path") + .map(|parameter| { + assert_eq!(parameter["required"], true, "{method} {path}"); + parameter["name"].as_str().unwrap() + }) + .collect(); + assert_eq!(names.as_slice(), expected_names, "{method} {path}"); + } + } + #[test] fn openapi_summarizes_every_operation_once() { let document = openapi(); @@ -1963,7 +2012,7 @@ const BODY_PROBLEMS: [ProblemCode; 3] = [ ProblemCode::RequestBodyTooLarge, ProblemCode::RequestUnsupportedMediaType, ]; -/// Every problem resolving the `{run}` path segment can answer. +/// Every problem resolving the `{runId}` path segment can answer. const RUN_PROBLEMS: [ProblemCode; 2] = [ProblemCode::RequestInvalid, ProblemCode::RunNotVisible]; /// Every problem a review completion sender can be answered with. const REVIEW_COMPLETION_PROBLEMS: [ProblemCode; 6] = [ @@ -2052,11 +2101,11 @@ fn summary(operation_id: &str) -> &'static str { pub fn openapi() -> Value { use ProblemCode as P; let run_state = json!({"type":"string","enum":["running","finished","failed","cancelled","cancelled-after-effect","expired","attention","cancel-requested"]}); - let run_param = json!({"name":"run","in":"path","required":true,"schema":{"type":"string","format":"uuid"}}); + let run_param = json!({"name":"runId","in":"path","required":true,"schema":{"type":"string","format":"uuid"}}); let mut paths = serde_json::Map::new(); let operations: [DocumentedOperation; 15] = [ ( - "/v1/workflows/{workflow}", + "/v1/workflows/{workflowId}", "get", "workflowContract", None, @@ -2102,7 +2151,7 @@ pub fn openapi() -> Value { .concat(), ), ( - "/v1/runs/{run}", + "/v1/runs/{runId}", "get", "runStatus", None, @@ -2110,7 +2159,7 @@ pub fn openapi() -> Value { RUN_PROBLEMS.to_vec(), ), ( - "/v1/runs/{run}/inspect", + "/v1/runs/{runId}/inspect", "get", "inspectRun", None, @@ -2126,7 +2175,7 @@ pub fn openapi() -> Value { .concat(), ), ( - "/v1/runs/{run}/check", + "/v1/runs/{runId}/check", "post", "checkNow", Some("CheckNow"), @@ -2134,7 +2183,7 @@ pub fn openapi() -> Value { [&BODY_PROBLEMS[..], &RUN_PROBLEMS[..], &[P::CheckNotWaiting]].concat(), ), ( - "/v1/runs/{run}/retry-same", + "/v1/runs/{runId}/retry-same", "post", "retrySame", Some("Reason"), @@ -2157,7 +2206,7 @@ pub fn openapi() -> Value { .concat(), ), ( - "/v1/runs/{run}/cancel", + "/v1/runs/{runId}/cancel", "post", "cancelRun", Some("Reason"), @@ -2170,7 +2219,7 @@ pub fn openapi() -> Value { .concat(), ), ( - "/v1/runs/{run}/reconcile", + "/v1/runs/{runId}/reconcile", "post", "reconcileRun", Some("Reason"), @@ -2257,11 +2306,11 @@ pub fn openapi() -> Value { json!({"description":"Authorized result","content":{"application/json":{"schema":{"$ref":format!("#/components/schemas/{response}")}}}}), ); let mut op = json!({"operationId":id,"summary":summary(id),"security":[{"bearer":[]}],"responses":responses}); - if path.contains("{run}") { + if path.contains("{runId}") { op["parameters"] = json!([run_param.clone()]); } - if path.contains("{workflow}") { - op["parameters"] = json!([{"name":"workflow","in":"path","required":true,"schema":{"type":"string","minLength":1,"maxLength":64}}]); + if path.contains("{workflowId}") { + op["parameters"] = json!([{"name":"workflowId","in":"path","required":true,"schema":{"type":"string","minLength":1,"maxLength":64}}]); } if id == "listRuns" { op["parameters"] = json!([ diff --git a/crates/registry-coordinator/src/http/admission_contracts.rs b/crates/registry-coordinator/src/http/admission_contracts.rs index bf951c8edc..6e640710dd 100644 --- a/crates/registry-coordinator/src/http/admission_contracts.rs +++ b/crates/registry-coordinator/src/http/admission_contracts.rs @@ -76,11 +76,11 @@ fn event_path(paths: &mut Map) { "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"}}} })); - let mut parameters = ["workflow", "trigger"].into_iter().map(|name| { + let mut parameters = ["workflowId", "triggerId"].into_iter().map(|name| { json!({"name":name,"in":"path","required":true,"schema":{"type":"string","minLength":1,"maxLength":64}}) }).collect::>(); parameters.extend(webhook_parameters()); - paths.insert("/v1/events/{workflow}/{trigger}".into(), json!({"post":{ + paths.insert("/v1/events/{workflowId}/{triggerId}".into(), json!({"post":{ "operationId":"admitEvent","summary":"Start a workflow from an authenticated product event", "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, diff --git a/docs/site/src/content/docs/configure/adapter-jobs.mdx b/docs/site/src/content/docs/configure/adapter-jobs.mdx index 3b756ef826..2f32611da7 100644 --- a/docs/site/src/content/docs/configure/adapter-jobs.mdx +++ b/docs/site/src/content/docs/configure/adapter-jobs.mdx @@ -373,7 +373,7 @@ A metadata mismatch or operation refusal never selects another operation or dest {/* 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 job sends one event per item as a canonical JSON `HookEnvelope` in a Standard Webhooks POST to `/v1/events/{workflowId}/{triggerId}`. 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. diff --git a/docs/site/src/content/docs/configure/coordinator.mdx b/docs/site/src/content/docs/configure/coordinator.mdx index d3772511bd..976f784ddf 100644 --- a/docs/site/src/content/docs/configure/coordinator.mdx +++ b/docs/site/src/content/docs/configure/coordinator.mdx @@ -484,7 +484,7 @@ A trigger accepts a logical source, an exact event type and data-schema identity The event source owns event meaning and disclosure, and product event names and payload meanings stay in the authored project. 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}`. +The receiver is `POST /v1/events/{workflowId}/{triggerId}`. 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. diff --git a/docs/site/src/content/docs/operate/coordinator.mdx b/docs/site/src/content/docs/operate/coordinator.mdx index 489c3612e1..1f49c16706 100644 --- a/docs/site/src/content/docs/operate/coordinator.mdx +++ b/docs/site/src/content/docs/operate/coordinator.mdx @@ -902,7 +902,7 @@ The client resends an admission whose outcome is unknown only under its original An operator policy lists every owner's runs in those workflows. `limit` takes 1 to 100 and defaults to 20. Pass `nextCursor` as `cursor` with the same filters to continue; each page rechecks current caller and workflow permissions. -Keep the run ID a start returns for direct lookup with `GET /v1/runs/{run}`. +Keep the run ID a start returns for direct lookup with `GET /v1/runs/{runId}`. Filters, which combine: diff --git a/docs/site/src/content/docs/reference/api-stability.mdx b/docs/site/src/content/docs/reference/api-stability.mdx index d504c33734..fcaa81795a 100644 --- a/docs/site/src/content/docs/reference/api-stability.mdx +++ b/docs/site/src/content/docs/reference/api-stability.mdx @@ -69,10 +69,10 @@ Registry Evidence's versioned routes are `POST /v1/evidence`, `POST /v1/evidence [experimental surfaces](#experimental-surfaces). Registry Coordinator's promise covers its workflow model of five step types, its run API, and -the `coordinator` SDK namespace. Its versioned routes are `GET /v1/workflows/{workflow}`, -`POST /v1/runs`, `GET /v1/runs`, `GET /v1/runs/{run}`, `GET /v1/runs/{run}/inspect`, -`POST /v1/runs/{run}/retry-same`, `POST /v1/runs/{run}/cancel`, `POST /v1/runs/{run}/reconcile`, -`POST /v1/runs/{run}/check`, `POST /v1/events/{workflow}/{trigger}`, and +the `coordinator` SDK namespace. Its versioned routes are `GET /v1/workflows/{workflowId}`, +`POST /v1/runs`, `GET /v1/runs`, `GET /v1/runs/{runId}`, `GET /v1/runs/{runId}/inspect`, +`POST /v1/runs/{runId}/retry-same`, `POST /v1/runs/{runId}/cancel`, `POST /v1/runs/{runId}/reconcile`, +`POST /v1/runs/{runId}/check`, `POST /v1/events/{workflowId}/{triggerId}`, and `POST /v1/review-completions`. Its deployment-wide operator routes are `GET /v1/doctor`, `POST /v1/restore-hold`, `POST /v1/release-restore-hold`, `POST /v1/release-admission-hold`, `POST /v1/complete-execution-recovery`, and `POST /v1/retention`. Its operational routes are diff --git a/docs/site/src/content/docs/reference/apis/registry-coordinator.mdx b/docs/site/src/content/docs/reference/apis/registry-coordinator.mdx index c54ff48477..7b4357bcb9 100644 --- a/docs/site/src/content/docs/reference/apis/registry-coordinator.mdx +++ b/docs/site/src/content/docs/reference/apis/registry-coordinator.mdx @@ -17,7 +17,7 @@ import ApiReferenceTable from '../../../../components/ApiReferenceTable.astro'; Registry Coordinator serves one HTTP surface for starting a run of a served workflow, following and recovering that run, operating the deployment, and taking Casework completion wake-ups. Every route except `/health`, `/ready`, `/v1/review-completions`, and -`/v1/events/{workflow}/{trigger}` takes a caller access token, and the access profile that token +`/v1/events/{workflowId}/{triggerId}` takes a caller access token, and the access profile that token resolves to decides what the caller may do. A Casework completion authenticates with its Standard Webhooks signature, as does a product event. [API stability](../../api-stability/) states the versioning contract. @@ -66,7 +66,7 @@ configured for that connection, and the receiving product decides it. ## Discover a workflow -`GET /v1/workflows/{workflow}` returns the active permitted contract, including `workflowRevision`, +`GET /v1/workflows/{workflowId}` returns the active permitted contract, including `workflowRevision`, input, and declared outcomes. It requires the caller's `start` action for that Workflow. Use that revision for fresh starts or a generated revision-pinned TypeScript/Python wrapper. Generated wrappers provide typed `start`, `get`, and `cancel` over the maintained public generic @@ -106,7 +106,7 @@ A start is refused before admission when: ## Start a run from a product event -`POST /v1/events/{workflow}/{trigger}` admits a run from a signed product event, when the workflow +`POST /v1/events/{workflowId}/{triggerId}` admits a run from a signed product event, when the workflow declares that trigger and the runtime file lists its source under `eventSources`. The body is the platform hook envelope, at most 1,048,576 canonical JSON bytes, above which it answers `413 request.body-too-large`; the admitted event value must then fit the 131,072-byte value @@ -130,7 +130,7 @@ The event grants no authority for the calls the run then makes. ## Read and inspect runs -`GET /v1/runs/{run}` answers the run's `RunStatus`: its `workflow`, computed `workflowRevision`, +`GET /v1/runs/{runId}` answers the run's `RunStatus`: its `workflow`, computed `workflowRevision`, `bindingDigest`, its current step and state, when it was admitted and when its deadline falls, whether an effect is `uncertain`, and whether it needs restore review. `stepLabel` is the label the workflow author gave the current step, as packaged in the workflow @@ -160,7 +160,7 @@ includes `nextCursor`, pass it as `cursor` with the same filters to continue. Ev current caller and workflow permissions. An invalid cursor or one from a different caller or filter answers `400 request.invalid`. Keep the run ID a start returns for direct status lookup. -`GET /v1/runs/{run}/inspect` answers the run, one entry per step with its state, attempt count, +`GET /v1/runs/{runId}/inspect` answers the run, one entry per step with its state, attempt count, whether its command is prepared, whether its effect is uncertain, and whether its receipt expired, and a `recovery` block. `recovery.retryAllowed` and `recovery.reason` describe whether the run can be scheduled again. For a compatible current call, `recovery.operation` names the pinned operation's diff --git a/docs/site/src/content/docs/start/coordinator.mdx b/docs/site/src/content/docs/start/coordinator.mdx index 0f5cf575a2..22ce72f66b 100644 --- a/docs/site/src/content/docs/start/coordinator.mdx +++ b/docs/site/src/content/docs/start/coordinator.mdx @@ -63,7 +63,7 @@ schema leaves open, and values a Transform computes, are left to scenarios and t An authorised caller starts a run with `POST /v1/runs`, giving the expected workflow revision, its input, and an idempotency key. An authored event trigger can also start one from a signed product -event at `POST /v1/events/{workflow}/{trigger}`, and an authored calendar trigger starts one on a +event at `POST /v1/events/{workflowId}/{triggerId}`, and an authored calendar trigger starts one on a schedule with no caller. The same key with the same revision and input returns the same run, and the [API reference](../../reference/apis/registry-coordinator/) states what a conflicting reuse gets. From e44ce00b5432d0b366245450a1a485c52d8c3238 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 16:03:55 +0000 Subject: [PATCH 022/183] fix(coordinator-client): name the Idempotency-Key header in refusals Signed-off-by: Jeremi Joslin (cherry picked from commit eda8527801989cad0022abda0962707b6610cb05) --- crates/registry-coordinator-client/src/client.rs | 4 +++- crates/registry-coordinator-client/tests/http.rs | 5 ++++- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/crates/registry-coordinator-client/src/client.rs b/crates/registry-coordinator-client/src/client.rs index 2a17003fcc..7ac0020be3 100644 --- a/crates/registry-coordinator-client/src/client.rs +++ b/crates/registry-coordinator-client/src/client.rs @@ -121,7 +121,9 @@ impl CoordinatorClient { return Err(Error::invalid_request("the workflow identifier is invalid")); } if key.is_empty() || key.len() > 256 || !key.bytes().all(|b| (0x20..=0x7e).contains(&b)) { - return Err(Error::invalid_request("the admission key is invalid")); + return Err(Error::invalid_request( + "Idempotency-Key must contain 1 to 256 printable ASCII characters", + )); } if !valid_revision(&request.workflow_revision) { return Err(Error::invalid_request("the workflow revision is invalid")); diff --git a/crates/registry-coordinator-client/tests/http.rs b/crates/registry-coordinator-client/tests/http.rs index 679e8c136c..717ed310c9 100644 --- a/crates/registry-coordinator-client/tests/http.rs +++ b/crates/registry-coordinator-client/tests/http.rs @@ -1423,11 +1423,14 @@ async fn invalid_admission_and_recovery_fail_before_io() { "", "contains\tcontrol", "injected\r\nheader", + "mañana", &"a".repeat(257), ] { assert!(matches!( client.start(&token(), key, &request()).await, - Err(CoordinatorClientError::InvalidRequest { .. }) + Err(CoordinatorClientError::InvalidRequest { + reason: "Idempotency-Key must contain 1 to 256 printable ASCII characters", + }) )); } let mut input = request(); From b577bec9babae677a275bc57a39cf0e3a9f8c391 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 16:32:25 +0000 Subject: [PATCH 023/183] chore(coordinator): regenerate explicit path parameter contracts Signed-off-by: Jeremi Joslin (cherry picked from commit 0a8db954f5131de825a4536f270796a1652f60c1) --- .../openapi/coordinator.openapi.json | 34 +++++++++---------- 1 file changed, 17 insertions(+), 17 deletions(-) diff --git a/products/coordinator/generated/openapi/coordinator.openapi.json b/products/coordinator/generated/openapi/coordinator.openapi.json index 787e91fdaf..2d32d9e97c 100644 --- a/products/coordinator/generated/openapi/coordinator.openapi.json +++ b/products/coordinator/generated/openapi/coordinator.openapi.json @@ -1768,14 +1768,14 @@ "summary": "Report deployment readiness and run state" } }, - "/v1/events/{workflow}/{trigger}": { + "/v1/events/{workflowId}/{triggerId}": { "post": { "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.", "operationId": "admitEvent", "parameters": [ { "in": "path", - "name": "workflow", + "name": "workflowId", "required": true, "schema": { "maxLength": 64, @@ -1785,7 +1785,7 @@ }, { "in": "path", - "name": "trigger", + "name": "triggerId", "required": true, "schema": { "maxLength": 64, @@ -3824,13 +3824,13 @@ "summary": "Start a run of a served workflow" } }, - "/v1/runs/{run}": { + "/v1/runs/{runId}": { "get": { "operationId": "runStatus", "parameters": [ { "in": "path", - "name": "run", + "name": "runId", "required": true, "schema": { "format": "uuid", @@ -4038,14 +4038,14 @@ "summary": "Read one run's status" } }, - "/v1/runs/{run}/cancel": { + "/v1/runs/{runId}/cancel": { "post": { "description": "An authorized cancellation of a parked review wait with onCancel records durable intent and takes that authored path. A leased result read settles or expires before cleanup advances. Repeating cancellation preserves cleanup, reported by authoredCancelRequested. Other cancellation stops future calls where possible; it never reverses an accepted product effect.", "operationId": "cancelRun", "parameters": [ { "in": "path", - "name": "run", + "name": "runId", "required": true, "schema": { "format": "uuid", @@ -4333,13 +4333,13 @@ "summary": "Cancel a run" } }, - "/v1/runs/{run}/check": { + "/v1/runs/{runId}/check": { "post": { "operationId": "checkNow", "parameters": [ { "in": "path", - "name": "run", + "name": "runId", "required": true, "schema": { "format": "uuid", @@ -4626,13 +4626,13 @@ "summary": "Read a waiting step's product now" } }, - "/v1/runs/{run}/inspect": { + "/v1/runs/{runId}/inspect": { "get": { "operationId": "inspectRun", "parameters": [ { "in": "path", - "name": "run", + "name": "runId", "required": true, "schema": { "format": "uuid", @@ -4865,13 +4865,13 @@ "summary": "Inspect a run's steps and recovery options" } }, - "/v1/runs/{run}/reconcile": { + "/v1/runs/{runId}/reconcile": { "post": { "operationId": "reconcileRun", "parameters": [ { "in": "path", - "name": "run", + "name": "runId", "required": true, "schema": { "format": "uuid", @@ -5165,13 +5165,13 @@ "summary": "Reconcile an uncertain step against its receipt" } }, - "/v1/runs/{run}/retry-same": { + "/v1/runs/{runId}/retry-same": { "post": { "operationId": "retrySame", "parameters": [ { "in": "path", - "name": "run", + "name": "runId", "required": true, "schema": { "format": "uuid", @@ -5466,13 +5466,13 @@ "summary": "Retry a held step with the same command" } }, - "/v1/workflows/{workflow}": { + "/v1/workflows/{workflowId}": { "get": { "operationId": "workflowContract", "parameters": [ { "in": "path", - "name": "workflow", + "name": "workflowId", "required": true, "schema": { "maxLength": 64, From 6ccf78fba82527db5ff09686222c1957c0fa43f9 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 16:45:03 +0000 Subject: [PATCH 024/183] docs(dev): describe the available external flow call Signed-off-by: Jeremi Joslin --- .../docs/configure/run-a-project-with-rstack-dev.mdx | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/docs/site/src/content/docs/configure/run-a-project-with-rstack-dev.mdx b/docs/site/src/content/docs/configure/run-a-project-with-rstack-dev.mdx index 90bd1fa738..bc1935738f 100644 --- a/docs/site/src/content/docs/configure/run-a-project-with-rstack-dev.mdx +++ b/docs/site/src/content/docs/configure/run-a-project-with-rstack-dev.mdx @@ -864,8 +864,10 @@ A later `start` creates a fresh application run. Product data on managed Postgre ### Choose a function or a flow Use a server-side function for work that finishes within one request. Use a Coordinator flow when -work waits for a person or a date, or when each step needs review. Call function code from the -flow when the flow cannot express an individual step. +work waits for a person or a date, or when each step needs review. When a step needs code the +flow cannot express, the existing +[`external.command/v1` operation](../coordinator/#call-an-external-provider) can call an external +provider. The operator binds the destination and credential in the Coordinator runtime file. A function owns no product authority. The product authorises every call the function makes. When the whole procedure lives in function code, you lose the Coordinator diagram and its From a6a6868f03923ccae461d74f7fbe8d28ea876c3b Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 17:03:54 +0000 Subject: [PATCH 025/183] chore(release): wire the held Session binary into the native roster Signed-off-by: Jeremi Joslin --- release/scripts/release_roster.py | 9 +++++---- release/scripts/test_release_candidate.py | 14 ++++++++++++++ release/scripts/test_release_roster.py | 11 ++++++++--- 3 files changed, 27 insertions(+), 7 deletions(-) diff --git a/release/scripts/release_roster.py b/release/scripts/release_roster.py index 609b851abf..e5b7b98d5d 100644 --- a/release/scripts/release_roster.py +++ b/release/scripts/release_roster.py @@ -68,10 +68,9 @@ script builds, stages, or publishes them yet, so the product stays held until it is releasable. -``SESSION_FIRST_RELEASE`` is the single place that decides which release -first ships the ``registry-session`` binary and any image or security evidence -of its own. No release script builds, stages, or publishes it yet, so the -service stays held until it is releasable. +``SESSION_FIRST_RELEASE`` decides which numbered release first includes the +``registry-session`` binary in the native platform builds. The service stays +held while the release gate is unset. ``PYTHON_311_ABI_FIRST_RELEASE`` is the single place that decides which release first builds the Python client wheels against the Python 3.11 stable @@ -137,6 +136,7 @@ ("registry-manifest-cli", "registry-manifest"), ("registry-coordinator", "coordinator"), ("registry-coordinator", "coordinatorctl"), + ("registry-session", "registry-session"), ("registry-adapter", "adapter"), ("registry-adapterctl", "adapterctl"), ) @@ -164,6 +164,7 @@ def additional_platform_builds(version: tuple[int, int, int]): "registry-discoveryctl": discoveryctl_in_release(version), "registry-render": render_in_release(version), "registry-coordinator": coordinator_binaries_in_release(version), + "registry-session": session_in_release(version), "registry-adapter": adapter_in_release(version), "registry-adapterctl": adapter_in_release(version), } diff --git a/release/scripts/test_release_candidate.py b/release/scripts/test_release_candidate.py index 54b1b109cf..d0f20c4b4a 100644 --- a/release/scripts/test_release_candidate.py +++ b/release/scripts/test_release_candidate.py @@ -1567,6 +1567,20 @@ def test_breg_services_join_only_the_rosters_from_their_first_release( self.assertNotIn(f"{service}-v0.38.0-install.sh", inventory) self.assertNotIn(f"{service}-v0.38.0-macos-arm64", inventory) + @roster_patch("release_roster.SESSION_FIRST_RELEASE", (0, 51, 0)) + def test_session_first_release_closes_native_platform_assets(self) -> None: + old = self.module._release_payload_inventory("0.50.0") + self.assertFalse(any(name.startswith("registry-session-") for name in old)) + current = self.module._release_payload_inventory("0.51.0") + self.assertEqual( + { + "registry-session-v0.51.0-linux-amd64": "binary", + "registry-session-v0.51.0-linux-arm64": "binary", + "registry-session-v0.51.0-macos-arm64.tar.gz": "binary", + }, + {name: kind for name, kind in current.items() if name.startswith("registry-session-")}, + ) + @roster_patch("release_roster.COORDINATOR_FIRST_RELEASE", (0, 42, 0)) def test_no_version_ships_the_breg_services_until_the_roster_names_one( self, diff --git a/release/scripts/test_release_roster.py b/release/scripts/test_release_roster.py index ae0e22c92f..417d9e9cb8 100644 --- a/release/scripts/test_release_roster.py +++ b/release/scripts/test_release_roster.py @@ -123,9 +123,14 @@ def test_session_service_is_held_out_of_every_release(self) -> None: ("registry-session", "registry-session"), release_roster.additional_platform_builds(version), ) - with mock.patch.object(release_roster, "SESSION_FIRST_RELEASE", (0, 49, 0)): - self.assertFalse(release_roster.session_in_release((0, 48, 99))) - self.assertTrue(release_roster.session_in_release((0, 49, 0))) + + def test_session_first_release_adds_its_native_binary_to_the_roster(self) -> None: + binary = ("registry-session", "registry-session") + with mock.patch.object(release_roster, "SESSION_FIRST_RELEASE", (0, 51, 0)): + self.assertFalse(release_roster.session_in_release((0, 50, 0))) + self.assertNotIn(binary, release_roster.additional_platform_builds((0, 50, 0))) + self.assertTrue(release_roster.session_in_release((0, 51, 0))) + self.assertIn(binary, release_roster.additional_platform_builds((0, 51, 0))) def test_coordinator_binary_release_does_not_release_its_image(self): self.assertFalse(release_roster.coordinator_binaries_in_release((0, 43, 99))) From cced2b473011a3b04819fe94062b6bf6a5a6a54b Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 17:10:31 +0000 Subject: [PATCH 026/183] feat(dev): admit explicitly selected private PostgreSQL transport Signed-off-by: Jeremi Joslin --- crates/registry-platform-postgres/src/lib.rs | 16 ++- crates/registry-rstack-dev/src/database.rs | 101 +++++++++++++----- crates/registry-rstack-dev/src/products.rs | 13 ++- .../run-a-project-with-rstack-dev.mdx | 7 ++ 4 files changed, 104 insertions(+), 33 deletions(-) diff --git a/crates/registry-platform-postgres/src/lib.rs b/crates/registry-platform-postgres/src/lib.rs index 367f003c59..0a13457e51 100644 --- a/crates/registry-platform-postgres/src/lib.rs +++ b/crates/registry-platform-postgres/src/lib.rs @@ -52,11 +52,17 @@ pub fn loopback_postgres_connection( postgres: Config, resolve: &HostResolver, ) -> Result { - let permitted = check_database_hosts( - DatabaseTransport::LoopbackPlaintext, - &database_hosts(&postgres), - resolve, - )?; + connection_for_transport(postgres, DatabaseTransport::LoopbackPlaintext, resolve) +} + +/// Pin a parsed PostgreSQL configuration after the caller has admitted an +/// explicit transport. The caller still sets the matching driver TLS mode. +pub fn connection_for_transport( + postgres: Config, + transport: DatabaseTransport, + resolve: &HostResolver, +) -> Result { + let permitted = check_database_hosts(transport, &database_hosts(&postgres), resolve)?; pinned(&permitted, postgres) } diff --git a/crates/registry-rstack-dev/src/database.rs b/crates/registry-rstack-dev/src/database.rs index 81a60bb38a..7895dfab80 100644 --- a/crates/registry-rstack-dev/src/database.rs +++ b/crates/registry-rstack-dev/src/database.rs @@ -7,7 +7,7 @@ use std::{ time::{Duration, Instant}, }; -use anyhow::{anyhow, bail, Context, Result}; +use anyhow::{anyhow, bail, ensure, Context, Result}; use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _}; use registry_platform_config::{DatabaseTransport, HostResolver}; use registry_platform_provision::{ @@ -262,7 +262,7 @@ type AdminConnectionTask = tokio::task::JoinHandle { + Self::Plaintext => { let (client, connection) = bounded_connection(config.connect(tokio_postgres::NoTls), timeout).await?; Ok((client, tokio::spawn(connection))) @@ -387,12 +387,9 @@ impl Endpoint { DatabaseTransport::VerifiedTls => { url.query_pairs_mut().append_pair("sslmode", "require"); } - DatabaseTransport::LoopbackPlaintext => { + DatabaseTransport::LoopbackPlaintext | DatabaseTransport::PrivateNetworkPlaintext => { url.query_pairs_mut().append_pair("sslmode", "disable"); } - DatabaseTransport::PrivateNetworkPlaintext => { - bail!("private-network-plaintext is not supported by rstack dev"); - } } Ok(url.into()) } @@ -423,24 +420,26 @@ impl Database { apply_session_options(&mut admin_config); let transport = match endpoint.transport { DatabaseTransport::VerifiedTls => AdminTransport::Tls(tls_connector(ca_pem)?), - DatabaseTransport::LoopbackPlaintext => { + DatabaseTransport::LoopbackPlaintext | DatabaseTransport::PrivateNetworkPlaintext => { if ca_pem.is_some() { bail!( "RSTACK_DEV_DATABASE_CA cannot be set when the PostgreSQL administrator \ - URL uses sslmode=disable" + URL selects plaintext" ); } - AdminTransport::LoopbackPlaintext - } - DatabaseTransport::PrivateNetworkPlaintext => { - bail!("private-network-plaintext is not supported by rstack dev"); + AdminTransport::Plaintext } }; let session_context = match endpoint.transport { DatabaseTransport::LoopbackPlaintext => { "cannot establish the PostgreSQL administrator session over loopback plaintext" } - _ => "cannot establish the PostgreSQL administrator session over verified TLS", + DatabaseTransport::PrivateNetworkPlaintext => { + "cannot establish the PostgreSQL administrator session over private network plaintext" + } + DatabaseTransport::VerifiedTls => { + "cannot establish the PostgreSQL administrator session over verified TLS" + } }; let runtime = Builder::new_current_thread() .enable_all() @@ -449,7 +448,7 @@ impl Database { let ownership_lock = ownership_lock_statement(run_id)?; let session_deadline = Instant::now() + CLEANUP_ATTEMPT_TIMEOUT; let (admin_config, endpoint, client, connection_task, recovery_identity) = - if matches!(transport, AdminTransport::LoopbackPlaintext) + if matches!(transport, AdminTransport::Plaintext) && admin_config.get_hostaddrs().len() > 1 { let mut last_error = None; @@ -485,7 +484,7 @@ impl Database { Some(found) => found, None => { return Err(last_error.unwrap_or_else(|| { - anyhow!("no checked loopback PostgreSQL address answered") + anyhow!("no checked plaintext PostgreSQL address answered") })) .context(session_context) .map_err(super::operational); @@ -1336,6 +1335,7 @@ fn admin_config_with_resolver( ); } let mut requested_transport: Option = None; + let mut private_plaintext = false; for (key, value) in parsed.query_pairs() { match key.as_ref() { "sslmode" => { @@ -1356,18 +1356,31 @@ fn admin_config_with_resolver( "the PostgreSQL admin URL must not set sslrootcert; set RSTACK_DEV_DATABASE_CA \ to a CA PEM file instead" ), + "transport" => { + if private_plaintext || value != "private-network-plaintext" { + bail!("the PostgreSQL admin URL transport may specify private-network-plaintext once"); + } + private_plaintext = true; + } "connect_timeout" | "application_name" => {} other => bail!("the PostgreSQL admin URL query parameter {other} is not supported"), } } - let transport = requested_transport.unwrap_or(DatabaseTransport::VerifiedTls); + let transport = + if private_plaintext { + ensure!(requested_transport != Some(DatabaseTransport::VerifiedTls), + "the PostgreSQL admin URL must not combine private-network-plaintext with TLS sslmode"); + DatabaseTransport::PrivateNetworkPlaintext + } else { + requested_transport.unwrap_or(DatabaseTransport::VerifiedTls) + }; // tokio-postgres does not parse verify-ca or verify-full, and the runner // 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") + .filter(|(key, _)| key != "sslmode" && key != "transport") .map(|(key, value)| (key.into_owned(), value.into_owned())) .collect(); if kept.is_empty() { @@ -1403,20 +1416,20 @@ fn admin_config_with_resolver( config.ssl_mode(SslMode::Disable); } DatabaseTransport::PrivateNetworkPlaintext => { - bail!("private-network-plaintext is not supported by rstack dev"); + config = registry_platform_postgres::connection_for_transport(config, transport, resolve) + .map_err(|_| anyhow!("the PostgreSQL admin URL with private-network-plaintext must resolve only to permitted private or loopback addresses"))?; + config.ssl_mode(SslMode::Disable); } } let host = match transport { - DatabaseTransport::LoopbackPlaintext => { + DatabaseTransport::LoopbackPlaintext | DatabaseTransport::PrivateNetworkPlaintext => { let pinned = *config.get_hostaddrs().first().ok_or_else(|| { - anyhow!("the PostgreSQL loopback host did not resolve to an address") + anyhow!("the PostgreSQL plaintext host did not resolve to an address") })?; ip_to_url_host(pinned) } - DatabaseTransport::VerifiedTls | DatabaseTransport::PrivateNetworkPlaintext => { - parsed.host().expect("the host was checked").to_owned() - } + DatabaseTransport::VerifiedTls => parsed.host().expect("the host was checked").to_owned(), }; Ok(( config, @@ -2029,6 +2042,46 @@ mod tests { assert!(!ca_conflict.contains(password)); } + #[test] + fn explicitly_selected_private_plaintext_pins_every_checked_address() { + let url = "postgresql://admin:synthetic-url-value@postgres.compose:5432/postgres?transport=private-network-plaintext"; + let private = std::net::IpAddr::from([172, 20, 0, 7]); + let (config, endpoint) = + admin_config_with_resolver(url, &move |_| Ok(vec![private])).unwrap(); + assert_eq!(config.get_ssl_mode(), SslMode::Disable); + assert!(config.get_hosts().is_empty()); + assert_eq!(config.get_hostaddrs(), &[private]); + assert_eq!( + endpoint.transport, + DatabaseTransport::PrivateNetworkPlaintext + ); + assert_eq!( + endpoint.product_url("owned", "runtime", "pw").unwrap(), + "postgresql://runtime:pw@172.20.0.7:5432/owned?sslmode=disable" + ); + for addresses in [ + vec![private, std::net::IpAddr::from([203, 0, 113, 1])], + vec![std::net::IpAddr::from([169, 254, 169, 254])], + ] { + let error = admin_config_with_resolver(url, &move |_| Ok(addresses.clone())) + .err() + .expect("public or mixed answers must be refused") + .to_string(); + assert!(error.contains("private-network-plaintext"), "{error}"); + assert!(!error.contains("synthetic-url-value")); + } + for suffix in ["&sslmode=require", "&transport=private-network-plaintext"] { + assert!(admin_config_with_resolver(&format!("{url}{suffix}"), &|_| { + panic!("contradictory inputs must be refused before lookup"); + }) + .is_err()); + } + assert!(admin_config( + "postgresql://admin:synthetic-url-value@172.20.0.7/postgres?sslmode=disable" + ) + .is_err()); + } + #[test] fn spatial_runs_are_refused_without_a_supported_postgis() { assert!(require_postgis(Some("3.5.2")).is_ok()); diff --git a/crates/registry-rstack-dev/src/products.rs b/crates/registry-rstack-dev/src/products.rs index 667e2caeef..0a2b3ed443 100644 --- a/crates/registry-rstack-dev/src/products.rs +++ b/crates/registry-rstack-dev/src/products.rs @@ -2359,10 +2359,15 @@ fn shared_config( "runtimeUrlRef": secret_ref(&format!("{name}-runtime-url")), "migrationUrlRef": secret_ref(&format!("{name}-migration-url")) }); - if database_transport == DatabaseTransport::LoopbackPlaintext { - database["transport"] = json!("loopback-plaintext"); - } else if root.join("postgres-ca").is_file() { - database["caBundleRef"] = json!(secret_ref("postgres-ca")); + match database_transport { + DatabaseTransport::LoopbackPlaintext => database["transport"] = json!("loopback-plaintext"), + DatabaseTransport::PrivateNetworkPlaintext => { + database["transport"] = json!("private-network-plaintext"); + } + DatabaseTransport::VerifiedTls if root.join("postgres-ca").is_file() => { + database["caBundleRef"] = json!(secret_ref("postgres-ca")); + } + DatabaseTransport::VerifiedTls => {} } let audit = json!({ "hashKeyRef": secret_ref(&format!("{name}-audit-key")), diff --git a/docs/site/src/content/docs/configure/run-a-project-with-rstack-dev.mdx b/docs/site/src/content/docs/configure/run-a-project-with-rstack-dev.mdx index bc1935738f..4509de3a1b 100644 --- a/docs/site/src/content/docs/configure/run-a-project-with-rstack-dev.mdx +++ b/docs/site/src/content/docs/configure/run-a-project-with-rstack-dev.mdx @@ -542,6 +542,11 @@ By default it must serve TLS, and the runner verifies the server certificate and For a local server on a loopback host (`127.0.0.1`, `::1`, or `localhost` resolving only to loopback addresses), you can use plaintext by passing `?sslmode=disable` in the administrator URL and leaving `RSTACK_DEV_DATABASE_CA` unset. Generated product runtime configurations then use `database.transport: loopback-plaintext`. +If the runner and PostgreSQL share a private development network, such as a Docker Compose network, you can select `?transport=private-network-plaintext` explicitly. +The runner checks that every resolved address is eligible for private network plaintext and connects to one of those addresses directly. +Generated product runtime configurations use `database.transport: private-network-plaintext` and the same address. +Leave `RSTACK_DEV_DATABASE_CA` unset for either plaintext transport. + The administrator role named in the URL needs `LOGIN CREATEROLE CREATEDB`. Superuser is not needed for a non-spatial run. The runner sets `createrole_self_grant` on its own sessions, so you do not configure it. @@ -557,6 +562,8 @@ The URL accepts these query parameters and refuses all others: - `sslmode`: `require`, `verify-ca`, or `verify-full` for verified TLS (the default when omitted, verifying the certificate and host name whichever you choose), or `disable` for plaintext on a loopback host only. Setting `RSTACK_DEV_DATABASE_CA` with `sslmode=disable` is refused. +- `transport=private-network-plaintext` explicitly selects a private development network. + Leave `sslmode` unset for this transport and pass the same URL for recovery. - `connect_timeout` and `application_name`. - `sslrootcert` is refused. Set `RSTACK_DEV_DATABASE_CA` instead. From 6cbef5ee627cc5101f9c64aa5f869ea9786b6dca Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 16:34:23 +0000 Subject: [PATCH 027/183] fix(coordinator): align conformance inputs with transforms Signed-off-by: Jeremi Joslin (cherry picked from commit c3f5e84685f3fcc6a1a5e5cf7623da5e75f1fdbb) --- products/platform/config-formats.yaml | 2 +- products/platform/conformance/yaml/formats.yaml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/products/platform/config-formats.yaml b/products/platform/config-formats.yaml index c507fc67da..1609f84bc2 100644 --- a/products/platform/config-formats.yaml +++ b/products/platform/config-formats.yaml @@ -3933,7 +3933,7 @@ formats: integer: /workflow/deadlineSeconds boolean: none reference: /workflow/start - relativePath: /functions/notice-route/source + relativePath: /transforms/notice-route/source securityMembers: [] restrictingMembers: [] - id: coordinator/runtime diff --git a/products/platform/conformance/yaml/formats.yaml b/products/platform/conformance/yaml/formats.yaml index 0ea961ba7e..d125edaaa3 100644 --- a/products/platform/conformance/yaml/formats.yaml +++ b/products/platform/conformance/yaml/formats.yaml @@ -135,7 +135,7 @@ formats: # Isolate the path role: other functions keep their shared source file # when the corpus moves or symlinks this one outside the project. set: - /functions/notice-route/source: notice-route.rhai + /transforms/notice-route/source: notice-route.rhai write: notice-route.rhai: | fn notice_route(args) { From 31c4efc147e7487a6bc6999445157a31584e6251 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 17:13:26 +0000 Subject: [PATCH 028/183] fix(journeys): qualify BReg against stock Keycloak Signed-off-by: Jeremi Joslin (cherry picked from commit 18fde180c61313327d806120c52a21b4b6b3d4aa) --- .../platform/journeys/expected-failures.yaml | 16 +- .../platform/journeys/keycloak/realm.json | 5 + products/platform/journeys/own-provider.sh | 299 +++++++++++------- products/platform/journeys/promote.sh | 12 +- .../platform/journeys/test_journey_tables.py | 66 ++++ 5 files changed, 275 insertions(+), 123 deletions(-) diff --git a/products/platform/journeys/expected-failures.yaml b/products/platform/journeys/expected-failures.yaml index 86960f7d46..628a4210f6 100644 --- a/products/platform/journeys/expected-failures.yaml +++ b/products/platform/journeys/expected-failures.yaml @@ -51,14 +51,6 @@ authenticationStages: [header, algorithm, token-type, key, signature, issuer, au changes: [posture, postgres-tls-requirement, rstack-dev-products, caller-contract] expectedFailures: - - journey: own-provider - product: breg - step: database.connect - code: product.breg.runtime.package-root-unavailable - removedBy: rstack-dev-products - basis: observed - observedOn: "journey run 20261128141250-8151" - reason: "prepare, issuer, and database.provision pass (bregctl provision accepts loopback-plaintext on the reader's plain PostgreSQL server). database.connect runs bregctl test to produce the receipt bregctl package requires, and bregctl test refuses because the package.root directory in runtime.yaml does not exist yet before bregctl package creates it." - journey: own-provider product: evidence step: issuer @@ -74,8 +66,8 @@ expectedFailures: code: journey.promote.no-input removedBy: rstack-dev-products basis: observed - observedOn: "origin/main cd83550e, journey run 20261127023442-18b4 against own-provider run 20261127021546-ddef" - reason: "The development journey did not finish for this product, so there are no files to promote." + observedOn: "v0.49.0 binaries, retained database run 43837b0a62714a74a2564085615cf432" + reason: "The Keycloak proof uses a disposable static-claim fixture. Its input is scoped to own-provider verification. A separate retained development database was refused by the production runtime with platform.activation.posture-mismatch." - journey: promote product: evidence step: input @@ -229,6 +221,10 @@ unreached: # observedOn: "origin/main cd83550e, promote run 20261127025000-816f on own-provider run 20261127024425-265d (assisted: sql, certificate, token-type, mapper)" # reason: "The assisted Scheduling cell reached T1. Started with no development declaration, schedulingctl check (which has no --production flag) lists no refusal and the server starts and answers /readyz, so zero refusals are listed. No shared posture exists on main, so nothing can refuse. The count becomes meaningful once the posture change lands." passes: + - journey: own-provider + product: breg + basis: observed + observedOn: "v0.49.0 binaries, own-provider run 20261201170814-cac9" - journey: own-provider product: adapter basis: observed diff --git a/products/platform/journeys/keycloak/realm.json b/products/platform/journeys/keycloak/realm.json index 32ea513be3..8e516a6e67 100644 --- a/products/platform/journeys/keycloak/realm.json +++ b/products/platform/journeys/keycloak/realm.json @@ -23,6 +23,9 @@ {"clientId": "directory-client", "name": "BReg caller", "enabled": true, "protocol": "openid-connect", "publicClient": false, "secret": "${JOURNEY_CLIENT_SECRET_BREG}", "standardFlowEnabled": false, "implicitFlowEnabled": false, "directAccessGrantsEnabled": false, "serviceAccountsEnabled": true}, + {"clientId": "foreign-directory-client", "name": "BReg outside-jurisdiction caller", "enabled": true, "protocol": "openid-connect", "publicClient": false, + "secret": "${JOURNEY_CLIENT_SECRET_BREG_FOREIGN}", "standardFlowEnabled": false, "implicitFlowEnabled": false, + "directAccessGrantsEnabled": false, "serviceAccountsEnabled": true}, {"clientId": "urn:example:casework", "name": "Casework API", "enabled": true, "protocol": "openid-connect", "publicClient": false, "standardFlowEnabled": false, "implicitFlowEnabled": false, "directAccessGrantsEnabled": false, "serviceAccountsEnabled": false}, @@ -78,6 +81,8 @@ "users": [ {"username": "service-account-directory-client", "enabled": true, "serviceAccountClientId": "directory-client", "clientRoles": {"urn:breg:local-directory": ["access"]}}, + {"username": "service-account-foreign-directory-client", "enabled": true, "serviceAccountClientId": "foreign-directory-client", + "clientRoles": {"urn:breg:local-directory": ["access"]}}, {"username": "service-account-casework-client", "enabled": true, "serviceAccountClientId": "casework-client", "clientRoles": {"urn:example:casework": ["access"]}}, {"username": "service-account-case-system", "enabled": true, "serviceAccountClientId": "case-system", diff --git a/products/platform/journeys/own-provider.sh b/products/platform/journeys/own-provider.sh index 5d733cdba4..e9126eba97 100755 --- a/products/platform/journeys/own-provider.sh +++ b/products/platform/journeys/own-provider.sh @@ -28,6 +28,9 @@ # through the admin API at setup and made a default scope of its caller. Each # product counts three identity-provider changes: its caller client, its # audience and its scope. +# BReg's disposable fixture binds exact scopes to two callers and sets its +# authored principal, purpose and jurisdiction with built-in static mappers. +# A token issued before the mappers are installed must still be refused. # # What the harness does that the reader does not type, and so is not counted: # - the secret folder of every product is the run's secrets/ folder, so each @@ -434,6 +437,9 @@ CASEWORK_SUBJECT='' DOCUMENTS_SUBJECT='' COORDINATOR_SUBJECT='' BREG_HOOK_PORT='' +BREG_SCOPE_UNLINKS=0 +# shellcheck disable=SC2034 # Read by name through the token and HTTP helpers. +BREG_CONTROL_TOKEN='' ADAPTER_SOURCE_PORT='' REACHED_AUTH_PRODUCTS=() THUNDERID_SESSION_IDS=() @@ -506,6 +512,47 @@ keycloak_default_scope() { journey_harness_failure "Keycloak refused to add scope $scope to client $client (HTTP $KC_STATUS)" } +# Keep the built-in scopes that do not appear in the access token's scope +# claim. The BReg schema test compares the caller's entire issued scope set. +breg_keycloak_exact_scope() { + local client=$1 uuid defaults scopes scope_id + keycloak_client_uuid "$client" uuid + keycloak_admin GET "/clients/$uuid/default-client-scopes" + [[ "$KC_STATUS" == 200 ]] || journey_harness_failure "Keycloak cannot list the default scopes of $client" + defaults=$KC_BODY + # Keycloak omits attributes from the per-client scope listing. + keycloak_admin GET /client-scopes + [[ "$KC_STATUS" == 200 ]] || journey_harness_failure "Keycloak cannot read scope attributes" + scopes=$(jq -r --argjson defaults "$defaults" --arg scope "$SCOPE" ' + .[] | .id as $id | select(any($defaults[]; .id == $id)) + | select(.name != $scope and .attributes["include.in.token.scope"] != "false") | .id' <<<"$KC_BODY") || + journey_harness_failure "Keycloak returned an invalid default scope inventory" + while IFS= read -r scope_id; do + [[ -n "$scope_id" ]] || continue + keycloak_admin DELETE "/clients/$uuid/default-client-scopes/$scope_id" + [[ "$KC_STATUS" == 204 ]] || journey_harness_failure "Keycloak refused to unlink a default scope from $client" + BREG_SCOPE_UNLINKS=$((BREG_SCOPE_UNLINKS + 1)) + done <<<"$scopes" +} + +breg_keycloak_mappers() { + jq -cn --arg principal "$1" --arg jurisdiction "$2" ' + {registry_principal: $principal, registry_purpose: "directory-administration", jurisdiction: $jurisdiction} + | to_entries | map({name: .key, protocol: "openid-connect", protocolMapper: "oidc-hardcoded-claim-mapper", + config: {"claim.name": .key, "claim.value": .value, "jsonType.label": "String", "access.token.claim": "true", + "id.token.claim": "false", "userinfo.token.claim": "false", "introspection.token.claim": "false"}})' +} + +breg_keycloak_add_mappers() { + local uuid mappers mapper + keycloak_client_uuid "$1" uuid + mappers=$(breg_keycloak_mappers "$2" "$3" | jq -c '.[]') || journey_harness_failure "cannot assemble BReg's static mappers" + while IFS= read -r mapper; do + keycloak_admin POST "/clients/$uuid/protocol-mappers/models" "$mapper" + [[ "$KC_STATUS" == 201 ]] || journey_harness_failure "Keycloak refused a static BReg mapper (HTTP $KC_STATUS)" + done <<<"$mappers" +} + # keycloak_service_account_subject CLIENT_ID VAR: the `sub` of the client's # service account, which a Coordinator policy names. keycloak_service_account_subject() { @@ -529,6 +576,8 @@ start_keycloak() { done journey_secret_new client-documents-wrong-kind 24 secret_envs+=(--secret-env JOURNEY_CLIENT_SECRET_DOCUMENTS_WRONG_KIND=client-documents-wrong-kind) + journey_secret_new client-breg-foreign 24 + secret_envs+=(--secret-env JOURNEY_CLIENT_SECRET_BREG_FOREIGN=client-breg-foreign) journey_container_run kc --port 8080 \ --env=KC_BOOTSTRAP_ADMIN_USERNAME=admin \ --secret-env KC_BOOTSTRAP_ADMIN_PASSWORD=keycloak-admin "${secret_envs[@]}" \ @@ -1029,14 +1078,12 @@ step_prepare() { edit "$RUNTIME_FILE" " root: /var/lib/breg/secrets" " root: $SECRETS" secret-file edit "$RUNTIME_FILE" " root: /var/lib/breg/package" " root: $WORK/build/package" package edit "$RUNTIME_FILE" " path: /var/log/breg/audit.jsonl" " path: $WORK/audit.jsonl" - if [[ "$ISSUER_KIND" == thunderid ]]; then - free_port BREG_HOOK_PORT - local hook_decl hook_dest - hook_decl=$(printf ' hooks:\n - id: contact-created\n phase: after\n trigger: created\n projection: [name, email, jurisdiction]\n handler: {type: url, destinationId: contact-sink}') - edit "$PROJECT/registry.yaml" $'\nactions:\n' $'\n'"$hook_decl"$'\n\nactions:\n' - hook_dest=$(printf 'destinations:\n hooks:\n contact-sink:\n origin: http://127.0.0.1:%s\n path: /events\n networkProfile: loopback-http\n dnsFamily: dual-stack-strict\n allowedPrivateCidrs: []\n hmacSha256KeyRef: secret:file/contact-sink-hmac\n classificationCeiling: internal\n deliveryCeilings:\n attemptTimeoutMilliseconds: 2000\n maximumAttempts: 5\n' "$BREG_HOOK_PORT") - printf '\n%s' "$hook_dest" >>"$RUNTIME_FILE" - fi + free_port BREG_HOOK_PORT + local hook_decl hook_dest + hook_decl=$(printf ' hooks:\n - id: contact-created\n phase: after\n trigger: created\n projection: [name, email, jurisdiction]\n handler: {type: url, destinationId: contact-sink}') + edit "$PROJECT/registry.yaml" $'\nactions:\n' $'\n'"$hook_decl"$'\n\nactions:\n' + hook_dest=$(printf 'destinations:\n hooks:\n contact-sink:\n origin: http://127.0.0.1:%s\n path: /events\n networkProfile: loopback-http\n dnsFamily: dual-stack-strict\n allowedPrivateCidrs: []\n hmacSha256KeyRef: secret:file/contact-sink-hmac\n classificationCeiling: internal\n deliveryCeilings:\n attemptTimeoutMilliseconds: 2000\n maximumAttempts: 5\n' "$BREG_HOOK_PORT") + printf '\n%s' "$hook_dest" >>"$RUNTIME_FILE" ;; casework) reader_command prepare --concepts project -- "$TOOL_BIN" init "$PROJECT" @@ -1295,9 +1342,10 @@ step_issuer() { case "$product" in breg) edit "$RUNTIME_FILE" " allowedAlgorithm: EdDSA" " allowedAlgorithm: RS256" - if [[ "$ISSUER_KIND" == thunderid ]]; then - edit "$RUNTIME_FILE" " allowedClients: [directory-client]" \ - " allowedClients: [directory-client, foreign-directory-client]" + edit "$RUNTIME_FILE" " allowedClients: [directory-client]" \ + " allowedClients: [directory-client, foreign-directory-client]" + if [[ "$ISSUER_KIND" == keycloak ]]; then + journey_count identity-provider-changes "$((2 + BREG_SCOPE_UNLINKS))" fi reader_command issuer -- "$TOOL_BIN" --format json check "$PROJECT" --runtime-config "$RUNTIME_FILE" ;; @@ -1414,82 +1462,94 @@ write_product_secrets() { done < <(secret_references "$RUNTIME_FILE") } -# breg_schema_test_credentials: acquire real client tokens for BReg's schema -# rehearsal and write a schema-test credential binding document covering every -# step of tests/journeys.yaml. +# Get a client-credentials token into the caller's variable. Keep the token +# response and the client secret out of the step output. +breg_keycloak_token() { + local client=$1 ref=$2 variable=$3 secret_file response issued + journey_secret_path "$ref" secret_file + response=$(curl --silent --show-error --fail --max-time 30 \ + --data grant_type=client_credentials --data "client_id=$client" \ + --data-urlencode "client_secret@$secret_file" "$KC_ISSUER/protocol/openid-connect/token") || + journey_harness_failure "Keycloak refused the BReg client credentials of $client" + issued=$(jq -er '.access_token | strings | select(length > 0)' <<<"$response") || + journey_harness_failure "Keycloak returned no BReg access token for $client" + printf -v "$variable" '%s' "$issued" + local label=${variable,,} + journey_secret_register "$ref-token-${label//_/-}" "$variable" +} + +# Check issuer-provided identity and the exact scope before BReg sees a token. +# An empty principal represents the control issued before mapper installation. +breg_keycloak_token_matches() { + local variable=$1 client=$2 subject=$3 principal=$4 jurisdiction=$5 + printf '%s' "${!variable}" | perl -MMIME::Base64 -e ' + local $/; my $token = ; + my $payload = (split /\./, $token)[1] // ""; + $payload =~ tr{-_}{+/}; + $payload .= "=" x ((4 - length($payload) % 4) % 4); + print decode_base64($payload);' | + jq -e --arg issuer "$KC_ISSUER" --arg client "$client" --arg subject "$subject" \ + --arg audience "$AUDIENCE" --arg scope "$SCOPE" --arg principal "$principal" --arg zone "$jurisdiction" ' + {issuer: (.iss == $issuer), client: (.azp == $client), subject: (.sub == $subject), + audience: (([.aud] | flatten | index($audience)) != null), scope: (.scope == $scope), + profile: (if $principal == "" then + (has("registry_principal") or has("registry_purpose") or has("jurisdiction") | not) + else + .registry_principal == $principal and .registry_purpose == "directory-administration" and .jurisdiction == $zone + end)} as $checks + | ($checks | to_entries | map(select(.value | not) | .key)) as $mismatches + | if ($mismatches | length) == 0 then true else + "Unexpected Keycloak token fields: \($mismatches | join(", ")); issued scope: \(.scope // "")\n" | halt_error(1) + end' >/dev/null +} + +# Acquire exact credentials for every step in the unmodified BReg fixture suite. breg_schema_test_credentials() { - local credentials_file=$1 secret_file response token + local credentials_file=$1 primary_subject foreign_subject + # shellcheck disable=SC2034 # Read by name through token fetch and secret helpers. + local breg_schema_token='' breg_foreign_schema_token='' if [[ "$ISSUER_KIND" == thunderid ]]; then - # shellcheck disable=SC2034 # read by name in write_own_secret and thunderid_fetch_token - local breg_schema_token='' breg_foreign_schema_token='' thunderid_fetch_token "$TID_ROOT" "$TID_REGISTRATION" "$CLIENT" breg_schema_token "$AUDIENCE" thunderid_fetch_token "$TID_ROOT" "$TID_REGISTRATION" foreign-directory-client breg_foreign_schema_token "$AUDIENCE" - write_own_secret breg-schema-token breg_schema_token - write_own_secret breg-foreign-schema-token breg_foreign_schema_token - journey_write_file "$credentials_file" --concepts client,grant,scopes,secret-file < <( - perl -MJSON::PP -e ' - my ($path) = @ARGV; - open my $fh, "<", $path or die "cannot read $path: $!\n"; - my ($journey, $step, @bindings); - while (my $line = <$fh>) { - if ($line =~ /^ - id: (\S+)/) { - $journey = $1; - $step = undef; - } elsif (defined $journey && $line =~ /^ - id: (\S+)/) { - $step = $1; - push @bindings, { - journeyId => $journey, - stepId => $step, - credential => { - type => "bearer", - tokenRef => "secret:file/breg-schema-token", - }, - }; - } elsif (@bindings && $line =~ /jurisdiction:\s*zone-b/) { - $bindings[-1]{credential}{tokenRef} = "secret:file/breg-foreign-schema-token"; - } - } - die "no journey steps found in $path\n" unless @bindings; - print JSON::PP->new->utf8->canonical->pretty->encode({ - apiVersion => "id.registrystack.org/formats/breg/schema-test-credentials/v1", - kind => "BRegSchemaTestCredentials", - bindings => \@bindings, - });' "$PROJECT/tests/journeys.yaml" - ) - return 0 + else + keycloak_service_account_subject "$CLIENT" primary_subject + keycloak_service_account_subject foreign-directory-client foreign_subject + breg_keycloak_token "$CLIENT" client-breg BREG_CONTROL_TOKEN + breg_keycloak_token_matches BREG_CONTROL_TOKEN "$CLIENT" "$primary_subject" '' '' || + journey_harness_failure "Keycloak no-mapper control did not issue the exact stock BReg scope and caller" + breg_keycloak_add_mappers "$CLIENT" synthetic-directory-editor zone-a + breg_keycloak_add_mappers foreign-directory-client synthetic-foreign-editor zone-b + journey_count identity-provider-changes 6 + breg_keycloak_token "$CLIENT" client-breg breg_schema_token + breg_keycloak_token foreign-directory-client client-breg-foreign breg_foreign_schema_token + breg_keycloak_token_matches breg_schema_token "$CLIENT" "$primary_subject" synthetic-directory-editor zone-a || + journey_harness_failure "Keycloak did not issue the exact BReg editor claims and scope" + breg_keycloak_token_matches breg_foreign_schema_token foreign-directory-client "$foreign_subject" synthetic-foreign-editor zone-b || + journey_harness_failure "Keycloak did not issue the exact BReg foreign editor claims and scope" fi - journey_secret_path "client-breg" secret_file - response=$(curl --silent --show-error --max-time 30 \ - --data grant_type=client_credentials \ - --data "client_id=$CLIENT" \ - --data-urlencode "client_secret@$secret_file" \ - "$KC_ISSUER/protocol/openid-connect/token") || - journey_harness_failure "Keycloak did not answer for $CLIENT while preparing bregctl test" - token=$(printf '%s' "$response" | jq -r '.access_token // empty') || - journey_harness_failure "Keycloak answered non-JSON for $CLIENT while preparing bregctl test" - [[ -n "$token" ]] || - journey_harness_failure "Keycloak refused client credentials for $CLIENT while preparing bregctl test" - # shellcheck disable=SC2034 # read by name in write_own_secret and journey_secret_register - BREG_SCHEMA_TOKEN=$token - journey_secret_register breg-schema-token BREG_SCHEMA_TOKEN - write_own_secret breg-schema-token BREG_SCHEMA_TOKEN + write_own_secret breg-schema-token breg_schema_token + write_own_secret breg-foreign-schema-token breg_foreign_schema_token journey_write_file "$credentials_file" --concepts client,grant,scopes,secret-file < <( perl -MJSON::PP -e ' my ($path) = @ARGV; open my $fh, "<", $path or die "cannot read $path: $!\n"; - my ($journey, @bindings); + my ($journey, $step, @bindings); while (my $line = <$fh>) { if ($line =~ /^ - id: (\S+)/) { $journey = $1; + $step = undef; } elsif (defined $journey && $line =~ /^ - id: (\S+)/) { + $step = $1; push @bindings, { journeyId => $journey, - stepId => $1, + stepId => $step, credential => { type => "bearer", tokenRef => "secret:file/breg-schema-token", }, }; + } elsif (@bindings && $line =~ /jurisdiction:\s*zone-b/) { + $bindings[-1]{credential}{tokenRef} = "secret:file/breg-foreign-schema-token"; } } die "no journey steps found in $path\n" unless @bindings; @@ -1563,42 +1623,35 @@ step_database() { breg) local credentials=$WORK/schema-test-credentials.json receipt=$WORK/schema-test-receipt.json build=$WORK/build breg_schema_test_credentials "$credentials" - if [[ "$ISSUER_KIND" == thunderid ]]; then - # bregctl test records an initial activation in its target database, so - # run schema rehearsal against a separate breg_test database while keeping - # the serving breg database empty for bregctl apply --initial. - local test_rt=$WORK/test-runtime.yaml test_pkg=$WORK/test-package - # shellcheck disable=SC2034 # read by name in write_own_secret - local mig_pw run_pw test_url - journey_secret_new breg-test-mig-pw 24 - journey_secret_new breg-test-run-pw 24 - read_secret breg-test-mig-pw mig_pw - read_secret breg-test-run-pw run_pw - test_url="postgresql://breg_test_migration:$mig_pw@127.0.0.1:$PG_PORT/breg_test" - write_own_secret breg-test-migration-database-url test_url - # shellcheck disable=SC2034 # read by name in write_own_secret - test_url="postgresql://breg_test_runtime:$run_pw@127.0.0.1:$PG_PORT/breg_test" - write_own_secret breg-test-runtime-database-url test_url - mkdir -p -- "$test_pkg" - copy_file "$RUNTIME_FILE" "$test_rt" - harness_edit "$test_rt" " databaseId: local-directory-db" " databaseId: local-directory-test-db" - harness_edit "$test_rt" " runtimeUrlRef: secret:file/breg-runtime-database-url" " runtimeUrlRef: secret:file/breg-test-runtime-database-url" - harness_edit "$test_rt" " migrationUrlRef: secret:file/breg-migration-database-url" " migrationUrlRef: secret:file/breg-test-migration-database-url" - harness_edit "$test_rt" " migration: breg_migration" " migration: breg_test_migration" - harness_edit "$test_rt" " runtime: breg_runtime" " runtime: breg_test_runtime" - harness_edit "$test_rt" " root: $build/package" " root: $test_pkg" - reader_command database.connect -- "$TOOL_BIN" provision --runtime-config "$test_rt" --admin-url-file "$ADMIN_URL_FILE" - [[ $CELL_OVER -eq 0 ]] || return 0 - reader_command database.connect \ - --typed "$TOOL test $PROJECT --runtime-config $test_rt --credentials $credentials --output $receipt" -- \ - "$TOOL_BIN" --format json test "$PROJECT" --runtime-config "$test_rt" --credentials "$credentials" --output "$receipt" - [[ $CELL_OVER -eq 0 ]] || return 0 - else - reader_command database.connect \ - --typed "$TOOL test $PROJECT --runtime-config $RUNTIME_FILE --credentials $credentials --output $receipt" -- \ - "$TOOL_BIN" --format json test "$PROJECT" --runtime-config "$RUNTIME_FILE" --credentials "$credentials" --output "$receipt" - [[ $CELL_OVER -eq 0 ]] || return 0 - fi + # bregctl test records an initial activation in its target database, so + # run schema rehearsal against a separate breg_test database while keeping + # the serving breg database empty for bregctl apply --initial. + local test_rt=$WORK/test-runtime.yaml test_pkg=$WORK/test-package + # shellcheck disable=SC2034 # read by name in write_own_secret + local mig_pw run_pw test_url + journey_secret_new breg-test-mig-pw 24 + journey_secret_new breg-test-run-pw 24 + read_secret breg-test-mig-pw mig_pw + read_secret breg-test-run-pw run_pw + test_url="postgresql://breg_test_migration:$mig_pw@127.0.0.1:$PG_PORT/breg_test" + write_own_secret breg-test-migration-database-url test_url + # shellcheck disable=SC2034 # read by name in write_own_secret + test_url="postgresql://breg_test_runtime:$run_pw@127.0.0.1:$PG_PORT/breg_test" + write_own_secret breg-test-runtime-database-url test_url + mkdir -p -- "$test_pkg" + copy_file "$RUNTIME_FILE" "$test_rt" + harness_edit "$test_rt" " databaseId: local-directory-db" " databaseId: local-directory-test-db" + harness_edit "$test_rt" " runtimeUrlRef: secret:file/breg-runtime-database-url" " runtimeUrlRef: secret:file/breg-test-runtime-database-url" + harness_edit "$test_rt" " migrationUrlRef: secret:file/breg-migration-database-url" " migrationUrlRef: secret:file/breg-test-migration-database-url" + harness_edit "$test_rt" " migration: breg_migration" " migration: breg_test_migration" + harness_edit "$test_rt" " runtime: breg_runtime" " runtime: breg_test_runtime" + harness_edit "$test_rt" " root: $build/package" " root: $test_pkg" + reader_command database.connect -- "$TOOL_BIN" provision --runtime-config "$test_rt" --admin-url-file "$ADMIN_URL_FILE" + [[ $CELL_OVER -eq 0 ]] || return 0 + reader_command database.connect \ + --typed "$TOOL test $PROJECT --runtime-config $test_rt --credentials $credentials --output $receipt" -- \ + "$TOOL_BIN" --format json test "$PROJECT" --runtime-config "$test_rt" --credentials "$credentials" --output "$receipt" + [[ $CELL_OVER -eq 0 ]] || return 0 reader_command database.connect --concepts package \ --typed "$TOOL package $PROJECT --test-receipt $receipt --output $build" -- \ "$TOOL_BIN" --format json package "$PROJECT" --test-receipt "$receipt" --output "$build" @@ -1967,6 +2020,14 @@ step_call() { REACHED_AUTH_PRODUCTS+=("$CELL") fi check_wrong_kind + if [[ "$CELL" == breg && "$ISSUER_KIND" == keycloak ]]; then + journey_http call --expect-status 401 --bearer BREG_CONTROL_TOKEN GET "http://127.0.0.1:$PORT$CALL_PATH" && + [[ "$JOURNEY_HTTP_PROBLEM_CODE" == authentication.refused ]] || + journey_harness_failure "BReg's no-mapper control returned HTTP $JOURNEY_HTTP_STATUS ($JOURNEY_HTTP_PROBLEM_CODE)" + refresh_server_log + grep -Eq 'failed_check"?[:=][[:space:]]*"token-claims"' "$SERVER_LOG_OUT" "$SERVER_LOG_ERR" || + journey_harness_failure "BReg did not refuse the no-mapper control at the authored claims check" + fi journey_pass call [[ "$CALL_METHOD" != GET ]] || journey_reached t1 return 0 @@ -2204,6 +2265,19 @@ breg_hook() { journey_stop hook breg-hook-receiver || journey_harness_failure "the BReg hook receiver ignored SIGTERM" journey_step hook -- assert_signed_hook_acceptance "$receiver_out" /events contact-created || journey_harness_failure "the BReg signed hook acceptance record did not confirm HMAC receiver authority without inbound credential headers" + if [[ "$ISSUER_KIND" == keycloak ]]; then + # shellcheck disable=SC2034 # Read by name through the secret and HTTP helpers. + local foreign_token='' + read_secret breg-foreign-schema-token foreign_token + journey_http hook --expect-status 200 --bearer ACCESS_TOKEN GET "$origin/v1/records/contacts/$record_id" || + journey_harness_failure "the BReg editor could not read the contact named by the signed hook" + # shellcheck disable=SC2016 # jq binds its own variables. + journey_step hook -- jq -e --arg record "$record_id" '.data.recordId == $record' "$JOURNEY_STEP_STDOUT" || + journey_harness_failure "the BReg editor did not receive the exact contact" + journey_http hook --expect-status 404 --bearer foreign_token GET "$origin/v1/records/contacts/$record_id" && + [[ "$JOURNEY_HTTP_PROBLEM_CODE" == resource.not-found ]] || + journey_harness_failure "the BReg foreign caller was not concealed from the exact contact" + fi } # composed_scheduling_hook: exercise a real BReg + Casework + Scheduling @@ -2722,13 +2796,8 @@ JSON step_hook() { case "$CELL" in breg) - if [[ "$ISSUER_KIND" == thunderid ]]; then - breg_hook - journey_pass hook - else - journey_unreached hook "The product delivers hooks, and this journey does not start a hook receiver yet." - CELL_OVER=1 - fi + breg_hook + journey_pass hook ;; scheduling) [[ $scheduling_catalogue_ok -eq 1 ]] || @@ -2894,6 +2963,11 @@ if [[ ${#PRIMARY[@]} -gt 0 ]]; then recipe "$product" keycloak_default_scope "$CLIENT" "$SCOPE" case "$product" in + breg) + keycloak_default_scope foreign-directory-client "$SCOPE" + breg_keycloak_exact_scope "$CLIENT" + breg_keycloak_exact_scope foreign-directory-client + ;; casework) keycloak_default_scope "$CLIENT" casework:staff keycloak_service_account_subject "$CLIENT" CASEWORK_SUBJECT @@ -2908,12 +2982,13 @@ if [[ ${#PRIMARY[@]} -gt 0 ]]; then fi jq -n --arg issuer "$ISSUER_KIND" --arg image "$KEYCLOAK_IMAGE" --arg realm "$REALM" \ --arg issuerUrl "$KC_ISSUER" --arg postgres "$POSTGRES_IMAGE" --arg pgPort "$PG_PORT" \ - --arg port "$PORT" --arg metricsPort "$METRICS_PORT" \ + --arg port "$PORT" --arg metricsPort "$METRICS_PORT" --args \ 'def opt: if . == "" then null else . end; {schema: "registry.journey-own-provider/v1", issuer: $issuer, issuerImage: $image, realm: $realm, issuerUrl: ($issuerUrl | opt), postgresImage: $postgres, postgresPort: ($pgPort | opt | if . == null then null else tonumber end), productPort: ($port | tonumber), productMetricsPort: ($metricsPort | tonumber), - containers: {issuer: "kc", postgres: "pg"}}' >"$JOURNEY_OUT/own-provider.json" || + fixtureOnlyProducts: [$ARGS.positional[] | select(. == "breg")], + containers: {issuer: "kc", postgres: "pg"}}' "${PRIMARY[@]}" >"$JOURNEY_OUT/own-provider.json" || journey_harness_failure "cannot write $JOURNEY_OUT/own-provider.json" else jq -n --arg issuer "$ISSUER_KIND" --arg image "$THUNDERID_IMAGE" \ diff --git a/products/platform/journeys/promote.sh b/products/platform/journeys/promote.sh index 411e98aac1..9be251e4ee 100755 --- a/products/platform/journeys/promote.sh +++ b/products/platform/journeys/promote.sh @@ -152,6 +152,12 @@ field() { # promote starts from the files the assists left. input_outcome() { local value + # Fixture-only inputs carry authorization setup specific to the rehearsal. + if [[ -f "$FROM/own-provider.json" ]] && jq -e --arg product "$1" \ + '(.fixtureOnlyProducts // []) | index($product) != null' "$FROM/own-provider.json" >/dev/null; then + printf -v "$2" '%s' fixture-only + return + fi value=$(jq -r --arg product "$1" '[.cells[] | select(.product == $product)] | if length != 1 then "missing" elif .[0].outcome == "pass" or (.[0].outcome == "unreached" and .[0].toT1 != null) then "finished" else .[0].outcome end' "$FROM/summary.json") || @@ -493,7 +499,11 @@ walk_product() { # input input_outcome "$product" outcome if [[ "$outcome" != finished ]]; then - printf 'promote: the %s journey did not finish for %s (cell outcome %s); nothing to promote\n' "$INPUT_JOURNEY" "$product" "$outcome" >&2 + if [[ "$outcome" == fixture-only ]]; then + printf 'promote: the %s input for %s is scoped to its own-provider fixture\n' "$INPUT_JOURNEY" "$product" >&2 + else + printf 'promote: the %s journey did not finish for %s (cell outcome %s); nothing to promote\n' "$INPUT_JOURNEY" "$product" "$outcome" >&2 + fi journey_fail input journey.promote.no-input journey_cell_end return 0 diff --git a/products/platform/journeys/test_journey_tables.py b/products/platform/journeys/test_journey_tables.py index 933b233676..f6813f3bdd 100644 --- a/products/platform/journeys/test_journey_tables.py +++ b/products/platform/journeys/test_journey_tables.py @@ -352,6 +352,27 @@ def test_realm_import_has_no_protocol_mappers(self): class KeycloakRecipe(unittest.TestCase): + def test_breg_mappers_are_static_and_only_set_authored_claims(self): + script = (TABLES / "own-provider.sh").read_text(encoding="utf-8") + match = re.search(r"^breg_keycloak_mappers\(\) \{\n.*?^\}\n", script, re.S | re.M) + self.assertIsNotNone(match) + for principal, zone in (("synthetic-directory-editor", "zone-a"), + ("synthetic-foreign-editor", "zone-b")): + result = subprocess.run( + ["bash", "-euo", "pipefail", "-c", match.group(0) + '\nbreg_keycloak_mappers "$1" "$2"', + "breg-keycloak-mappers", principal, zone], capture_output=True, text=True, timeout=5, + ) + self.assertEqual(result.returncode, 0, result.stderr) + mappings = json.loads(result.stdout) + self.assertEqual({m["config"]["claim.name"]: m["config"]["claim.value"] for m in mappings}, + {"registry_principal": principal, "registry_purpose": "directory-administration", + "jurisdiction": zone}) + self.assertEqual(len(mappings), 3) + for mapper in mappings: + self.assertEqual(mapper["protocolMapper"], "oidc-hardcoded-claim-mapper") + self.assertEqual(mapper["config"]["access.token.claim"], "true") + self.assertEqual(mapper["config"]["jsonType.label"], "String") + def test_documents_realm_provisions_custodian_and_wrong_kind_service_clients(self): realm = json.loads((TABLES / "keycloak" / "realm.json").read_text(encoding="utf-8")) clients = {client["clientId"]: client for client in realm["clients"]} @@ -497,6 +518,25 @@ def test_change_in_request_bytes_changes_contract_without_exposing_body(self): class ProductionOutcome(unittest.TestCase): + def test_scoped_fixture_input_cannot_be_promoted(self): + script = (TABLES / "promote.sh").read_text(encoding="utf-8") + function = re.search(r"^input_outcome\(\) \{\n.*?^\}\n", script, re.S | re.M) + self.assertIsNotNone(function) + with tempfile.TemporaryDirectory() as directory: + path = Path(directory) + (path / "summary.json").write_text(json.dumps({"cells": [ + {"product": product, "outcome": "pass"} for product in ("breg", "adapter") + ]}), encoding="utf-8") + provider = path / "own-provider.json" + for fixture_only, expected_breg in ((["breg"], "fixture-only"), ([], "finished")): + provider.write_text(json.dumps({"fixtureOnlyProducts": fixture_only}), encoding="utf-8") + result = subprocess.check_output( + ["bash", "-euo", "pipefail", "-c", function.group(0) + '\nFROM=$1\n' + 'input_outcome breg breg; input_outcome adapter adapter; printf "%s\\n" "$breg" "$adapter"', + "promote-input", str(path)], text=True, timeout=5, + ) + self.assertEqual(result.splitlines(), [expected_breg, "finished"]) + def test_zero_diagnostics_requires_a_successful_check_and_an_explicit_case(self): script = (TABLES / "promote.sh").read_text(encoding="utf-8") function = re.search(r"^production_outcome\(\) \{\n.*?^\}\n", script, re.S | re.M) @@ -1189,6 +1229,32 @@ def test_token_has_audience_and_scope_handles_keycloak_array_and_string_shapes(s ) self.assertEqual(result.returncode == 0, should_pass, f"{label}: {result.stderr}") + def test_breg_keycloak_checks_exact_scope_and_distinguishes_the_unmapped_control(self): + fn = self._extract_functions("breg_keycloak_token_matches") + claims = {"iss": "https://keycloak.example.test", "aud": "urn:example:api", + "azp": "directory-client", "sub": "keycloak-service-account", + "scope": "registry:directory:write"} + mapped = dict(claims, registry_principal="synthetic-directory-editor", + registry_purpose="directory-administration", jurisdiction="zone-a") + for label, payload, control, accepted in ( + ("exact", mapped, False, True), + ("extra scope", {**mapped, "scope": "registry:directory:write profile"}, False, False), + ("wrong zone", {**mapped, "jurisdiction": "zone-b"}, False, False), + ("wrong client", {**mapped, "azp": "foreign-directory-client"}, False, False), + ("unmapped control", claims, True, True), + ("mapped control", mapped, True, False), + ): + with self.subTest(case=label): + result = subprocess.run( + ["bash", "-euo", "pipefail", "-c", fn + '\n' + + 'TOKEN=$1 KC_ISSUER=https://keycloak.example.test SCOPE=registry:directory:write AUDIENCE=urn:example:api\n' + 'breg_keycloak_token_matches TOKEN directory-client keycloak-service-account "$2" "$3"', + "bash", self._encode_payload_for_parser_test(payload), + "" if control else "synthetic-directory-editor", "" if control else "zone-a"], + capture_output=True, text=True, timeout=5, + ) + self.assertEqual(result.returncode == 0, accepted, result.stderr) + def test_assert_wrong_agent_grant_refused_distinguishes_setup_and_credential_errors(self): fn = self._extract_functions("assert_wrong_agent_grant_refused") exact = "Casework refused the grant; check its approval, client, expiry and revocation" From 09edacefad8f07451ad3f51ceaf3bcf73d7f9c26 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 17:20:49 +0000 Subject: [PATCH 029/183] fix(journeys): clean up explicitly kept fixture inputs Signed-off-by: Jeremi Joslin (cherry picked from commit 8695c6a0e68a64d12a0f31562ceb86833c45c565) --- products/platform/journeys/promote.sh | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/products/platform/journeys/promote.sh b/products/platform/journeys/promote.sh index 9be251e4ee..2079de2fa5 100755 --- a/products/platform/journeys/promote.sh +++ b/products/platform/journeys/promote.sh @@ -500,6 +500,10 @@ walk_product() { input_outcome "$product" outcome if [[ "$outcome" != finished ]]; then if [[ "$outcome" == fixture-only ]]; then + # An explicitly kept fixture still needs cleanup when no cell can use it. + if [[ -f "$FROM/kept" ]]; then + take_over_input + fi printf 'promote: the %s input for %s is scoped to its own-provider fixture\n' "$INPUT_JOURNEY" "$product" >&2 else printf 'promote: the %s journey did not finish for %s (cell outcome %s); nothing to promote\n' "$INPUT_JOURNEY" "$product" "$outcome" >&2 From 364b8fadd47b9382aa46b461e06c3578ed5fc416 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 17:24:56 +0000 Subject: [PATCH 030/183] feat(dev): capture signed Documents and Scheduling observer hooks Signed-off-by: Jeremi Joslin --- Cargo.lock | 1 + crates/registry-rstack-dev/Cargo.toml | 1 + crates/registry-rstack-dev/src/lib.rs | 4 + crates/registry-rstack-dev/src/products.rs | 140 +++++++++++++++++- crates/registry-rstack-dev/src/sinks.rs | 123 ++++++++++++++- .../run-a-project-with-rstack-dev.mdx | 11 ++ 6 files changed, 274 insertions(+), 6 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 276ad7859e..c08f26801e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -8401,6 +8401,7 @@ dependencies = [ "registry-platform-buildinfo", "registry-platform-config", "registry-platform-crypto", + "registry-platform-hooks", "registry-platform-httputil", "registry-platform-postgres", "registry-platform-provision", diff --git a/crates/registry-rstack-dev/Cargo.toml b/crates/registry-rstack-dev/Cargo.toml index 24f678cc21..a710db5c2e 100644 --- a/crates/registry-rstack-dev/Cargo.toml +++ b/crates/registry-rstack-dev/Cargo.toml @@ -41,6 +41,7 @@ registry-cli-report.workspace = true registry-platform-buildinfo.workspace = true registry-platform-config.workspace = true registry-platform-crypto.workspace = true +registry-platform-hooks = { workspace = true, features = ["receiver"] } registry-platform-httputil.workspace = true registry-platform-postgres.workspace = true registry-platform-provision.workspace = true diff --git a/crates/registry-rstack-dev/src/lib.rs b/crates/registry-rstack-dev/src/lib.rs index aeedf1dc89..f50cf119c5 100644 --- a/crates/registry-rstack-dev/src/lib.rs +++ b/crates/registry-rstack-dev/src/lib.rs @@ -1734,6 +1734,10 @@ fn worker(root: &Path, output: &mut dyn Write) -> Result<()> { if let Some(hook_sink) = products.breg_hook_report() { report["bregHookSink"] = hook_sink; } + let hook_sinks = products.signed_hook_reports(); + if !hook_sinks.is_empty() { + report["hookSinks"] = json!(hook_sinks); + } let created_keys = products.created_kept_keys(); if !created_keys.is_empty() { report["createdKeptKeys"] = json!(created_keys.as_slice()); diff --git a/crates/registry-rstack-dev/src/products.rs b/crates/registry-rstack-dev/src/products.rs index 0a2b3ed443..f828e66af4 100644 --- a/crates/registry-rstack-dev/src/products.rs +++ b/crates/registry-rstack-dev/src/products.rs @@ -350,6 +350,7 @@ pub(super) struct ProductRunner<'a> { /// run. gateway: Option, hook_sink: Option, + signed_hook_sinks: BTreeMap, /// Where each Messaging provider's sent messages can be read, by provider /// ID. sinks: BTreeMap, @@ -389,6 +390,7 @@ impl<'a> ProductRunner<'a> { coordinator_issuer: None, gateway: None, hook_sink: None, + signed_hook_sinks: BTreeMap::new(), sinks: BTreeMap::new(), messaging_providers: None, runtime_configs: BTreeMap::new(), @@ -1298,6 +1300,88 @@ impl<'a> ProductRunner<'a> { }) } + pub(super) fn signed_hook_reports(&self) -> serde_json::Map { + self.signed_hook_sinks + .iter() + .map(|(product, sink)| { + ( + product.name().to_owned(), + json!({"receivedUrl": format!("{}/received", sink.origin)}), + ) + }) + .collect() + } + + fn bind_signed_hooks( + &mut self, + product: Product, + project: &Path, + runtime: &mut Value, + ) -> Result<()> { + use registry_platform_crypto::delivery_signature::{DeliveryKey, DeliveryKeys}; + use registry_platform_yaml::LocalId; + + let project_file = match product { + Product::Documents => "documents.yaml", + Product::Scheduling => "scheduling.yaml", + _ => return Ok(()), + }; + // The product has already validated and packaged the authored policy. + // Read only the URL destination names the development runtime must bind. + let document = authored_document(&project.join(project_file))?; + let hooks = match &document["hooks"] { + Value::Null => Vec::new(), + Value::Array(hooks) if product == Product::Documents => hooks.iter().collect(), + Value::Object(hooks) if product == Product::Scheduling => hooks.values().collect(), + _ => anyhow::bail!("unexpected observer hook inventory in the checked project"), + }; + let destinations = hooks + .into_iter() + .filter(|hook| hook["handler"]["type"] == "url") + .map(|hook| { + let id = hook["handler"]["destinationId"] + .as_str() + .context("the URL observer must name a destination")?; + LocalId::new(id).context("invalid URL observer destination identifier")?; + Ok::<_, anyhow::Error>(id) + }) + .collect::>>()?; + if destinations.is_empty() { + return Ok(()); + } + + let mut keys = BTreeMap::new(); + let mut references = BTreeMap::new(); + for id in destinations { + let key = random_key_bytes()?; + let reference = + self.secret(&format!("{}-hook-{id}", product.name()), key.as_slice())?; + references.insert(id, reference); + keys.insert( + id.to_owned(), + DeliveryKeys::new(DeliveryKey::new(key.as_slice())?, None)?, + ); + } + let sink = GatewayServer::start_signed_hooks(keys)?; + let configs: serde_json::Map = references + .into_iter() + .map(|(id, reference)| { + ( + id.to_owned(), + json!({ + "url": format!("{}/events/{id}", sink.origin), + "hmacSha256KeyRef": reference, + "attemptTimeoutMilliseconds": 2000, + "maximumAttempts": 5, + }), + ) + }) + .collect(); + runtime["destinations"]["hooks"] = json!(configs); + self.signed_hook_sinks.insert(product, sink); + Ok(()) + } + fn activate_casework( &self, database: &mut Database, @@ -1363,7 +1447,7 @@ impl<'a> ProductRunner<'a> { } fn activate_additional( - &self, + &mut self, product: Product, database: Option<&mut Database>, project: &Path, @@ -1397,8 +1481,9 @@ impl<'a> ProductRunner<'a> { } else { None }; - let configuration = + let mut configuration = self.additional_config(product, project, bind, &package, database_urls.as_ref())?; + self.bind_signed_hooks(product, project, &mut configuration)?; let path = self.root.join(format!("{name}-runtime.yaml")); write_private(&path, &serde_json::to_vec(&configuration)?)?; @@ -1971,6 +2056,7 @@ impl<'a> ProductRunner<'a> { drop(self.coordinator_issuer.take()); drop(self.gateway.take()); drop(self.hook_sink.take()); + self.signed_hook_sinks.clear(); Ok(()) } @@ -5558,6 +5644,56 @@ INVENTORY } } + #[test] + fn signed_observer_hooks_connect_only_declared_destinations_to_the_run_sink() { + let root = tempfile::tempdir().unwrap(); + let terminate = AtomicBool::new(false); + let mut runner = + ProductRunner::new(Arc::new(breg_input(false)), root.path(), &terminate).unwrap(); + for (product, name) in [ + (Product::Documents, "documents.yaml"), + (Product::Scheduling, "scheduling.yaml"), + ] { + let policy = root.path().join(name); + let (empty, declared) = match product { + Product::Documents => ( + "hooks: []\n", + "hooks:\n - handler: {type: url, destinationId: events}\n - handler: {type: url, destinationId: events}\n", + ), + Product::Scheduling => ( + "hooks: {}\n", + "hooks:\n booking: {handler: {type: url, destinationId: events}}\n cancellation: {handler: {type: url, destinationId: events}}\n", + ), + _ => unreachable!(), + }; + fs::write(&policy, empty).unwrap(); + let mut config = json!({}); + runner + .bind_signed_hooks(product, root.path(), &mut config) + .unwrap(); + assert_eq!(config, json!({})); + assert!(!runner.signed_hook_reports().contains_key(product.name())); + + fs::write(&policy, declared).unwrap(); + runner + .bind_signed_hooks(product, root.path(), &mut config) + .unwrap(); + let hooks = config["destinations"]["hooks"].as_object().unwrap(); + assert_eq!(hooks.len(), 1); + let report = runner.signed_hook_reports(); + let received = report[product.name()]["receivedUrl"].as_str().unwrap(); + let origin = received.strip_suffix("/received").unwrap(); + assert!(origin.starts_with("http://127.0.0.1:")); + assert_eq!(hooks["events"]["url"], format!("{origin}/events/events")); + let file = format!("{}-hook-events", product.name()); + assert_eq!( + hooks["events"]["hmacSha256KeyRef"], + format!("secret:file/{file}") + ); + assert_eq!(fs::metadata(runner.root.join(file)).unwrap().len(), 32); + } + } + #[test] fn external_hook_ids_must_match_the_inventory_exactly() { use std::os::unix::fs::PermissionsExt; diff --git a/crates/registry-rstack-dev/src/sinks.rs b/crates/registry-rstack-dev/src/sinks.rs index 9a3765c8cd..cdebee7091 100644 --- a/crates/registry-rstack-dev/src/sinks.rs +++ b/crates/registry-rstack-dev/src/sinks.rs @@ -20,14 +20,18 @@ use axum::{ routing::{get, post}, Json, Router, }; -use registry_platform_crypto::mac::{constant_time_eq, hmac_sha256}; +use registry_platform_crypto::{ + delivery_signature::DeliveryKeys, + mac::{constant_time_eq, hmac_sha256}, +}; +use registry_platform_hooks::receiver::{verify_hook_delivery, DeliveryFreshness, HookDelivery}; use serde_json::{json, Value}; use std::{ - collections::{BTreeSet, HashMap, VecDeque}, + collections::{BTreeMap, BTreeSet, HashMap, VecDeque}, net::{Ipv4Addr, TcpListener}, sync::{mpsc, Arc, Mutex}, thread, - time::Duration, + time::{Duration, SystemTime}, }; use zeroize::Zeroizing; @@ -117,6 +121,18 @@ impl GatewayServer { Self::start_router(router, "rstack-dev-hook-sink") } + pub(super) fn start_signed_hooks(keys: BTreeMap) -> Result { + let router = Router::new() + .route("/events/{destination}", post(receive_signed_hook)) + .route("/received", get(list_signed_hooks)) + .layer(DefaultBodyLimit::max(HOOK_BODY_LIMIT)) + .with_state(Arc::new(SignedHooks { + keys, + deliveries: Mutex::new(VecDeque::new()), + })); + Self::start_router(router, "rstack-dev-signed-hook-sink") + } + fn start_router(router: Router, name: &str) -> Result { let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)) .context("cannot reserve a loopback port for the HTTP sink")?; @@ -195,11 +211,63 @@ impl GatewayServer { type HookDeliveries = Arc>>; +struct SignedHooks { + keys: BTreeMap, + deliveries: Mutex>, +} + +async fn receive_signed_hook( + State(sink): State>, + Path(destination): Path, + headers: HeaderMap, + body: Bytes, +) -> StatusCode { + let Some(keys) = sink.keys.get(&destination) else { + return StatusCode::NOT_FOUND; + }; + if [ + "authorization", + "registry-source-authorization", + "proxy-authorization", + "cookie", + ] + .iter() + .any(|name| headers.contains_key(*name)) + || verify_hook_delivery( + HookDelivery { + headers: headers + .iter() + .map(|(name, value)| (name.as_str(), value.as_bytes())), + body: &body, + keys, + }, + DeliveryFreshness::default_at(SystemTime::now()), + ) + .is_err() + { + return StatusCode::FORBIDDEN; + } + record_hook(&sink.deliveries, headers, body); + StatusCode::NO_CONTENT +} + +async fn list_signed_hooks(State(sink): State>) -> Json { + Json(json!(*sink + .deliveries + .lock() + .expect("signed hook sink lock"))) +} + async fn receive_hook( State(deliveries): State, headers: HeaderMap, body: Bytes, ) -> StatusCode { + record_hook(&deliveries, headers, body); + StatusCode::NO_CONTENT +} + +fn record_hook(deliveries: &Mutex>, headers: HeaderMap, body: Bytes) { use base64::{engine::general_purpose::STANDARD, Engine as _}; let headers: Vec<_> = headers @@ -223,7 +291,6 @@ async fn receive_hook( |text| json!(text), ), })); - StatusCode::NO_CONTENT } async fn list_hooks(State(deliveries): State) -> Json { @@ -524,6 +591,54 @@ mod tests { .contains(&json!({"name": "x-delivery-number", "value": "1000"}))); } + #[test] + fn signed_hook_capture_checks_destination_signature_and_headers() { + use registry_platform_crypto::delivery_signature::{sign, DeliveryKey, DeliveryKeys}; + use std::{collections::BTreeMap, time::SystemTime}; + + const ID: &str = "00000000-0000-4000-8000-000000000001"; + const BODY: &str = r#"{"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"}"#; + let keys = |byte| DeliveryKeys::new(DeliveryKey::new(&[byte; 32]).unwrap(), None).unwrap(); + let sink = GatewayServer::start_signed_hooks(BTreeMap::from([ + ("expected".to_owned(), keys(31)), + ("other".to_owned(), keys(32)), + ])) + .unwrap(); + let timestamp = SystemTime::now() + .duration_since(SystemTime::UNIX_EPOCH) + .unwrap() + .as_secs(); + let signature = sign(&keys(31), ID, timestamp, BODY.as_bytes()).unwrap(); + + for (destination, credential, expected) in [ + ("other", false, 403), + ("expected", true, 403), + ("missing", false, 404), + ("expected", false, 204), + ] { + let (status, _) = call(|client| { + let request = client + .post(format!("{}/events/{destination}", sink.origin)) + .header("content-type", "application/json") + .header("webhook-id", ID) + .header("webhook-timestamp", timestamp.to_string()) + .header("webhook-signature", &signature) + .body(BODY); + if credential { + request.bearer_auth("synthetic-canary") + } else { + request + } + }); + assert_eq!(status, expected, "{destination}"); + } + let (status, received) = call(|client| client.get(format!("{}/received", sink.origin))); + assert_eq!(status, 200); + assert_eq!(received.as_array().unwrap().len(), 1); + assert_eq!(received[0]["body"], BODY); + assert!(!received.to_string().contains("synthetic-canary")); + } + #[test] fn dropping_the_gateway_stops_its_listener() { let gateway = gateway("http://127.0.0.1:9"); diff --git a/docs/site/src/content/docs/configure/run-a-project-with-rstack-dev.mdx b/docs/site/src/content/docs/configure/run-a-project-with-rstack-dev.mdx index 4509de3a1b..c9334df37f 100644 --- a/docs/site/src/content/docs/configure/run-a-project-with-rstack-dev.mdx +++ b/docs/site/src/content/docs/configure/run-a-project-with-rstack-dev.mdx @@ -746,6 +746,17 @@ A journey can call the Messaging API as a test person and poll for the delivery crates/registry-rstack-dev/src/docker.rs org.registrystack.rstack.dev-run; products/messaging/examples/starter/dev.yaml. */} +### Document Store and Scheduling hook captures + +When a Document Store or Scheduling project declares URL observers, the run binds their destinations +to a loopback receiver. The receiver verifies the webhook signature with a separate key for each +destination. Read the captured synthetic events at `hookSinks..receivedUrl` in the start +report. Trigger the observer through the product's authorised operation, then match the event type +and identifier in the capture. + +{/* Evidence: crates/registry-rstack-dev/src/products.rs, bind_signed_hooks, signed_hook_reports; + crates/registry-rstack-dev/src/sinks.rs, start_signed_hooks, receive_signed_hook. */} + ### Authored journey file `dev.yaml` must set `journeyFile`, for example `journeyFile: dev-journeys.yaml`. From 88b09be7e582afe7e067ecd23570478108eca986 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 17:23:14 +0000 Subject: [PATCH 031/183] test(journeys): verify retained Documents version-ready delivery Signed-off-by: Jeremi Joslin (cherry picked from commit cace9cd94d67c978ad06c205b7bd54f7f7300976) --- products/platform/journeys/rstack-dev.sh | 126 +++++++++++++++--- .../platform/journeys/test_journey_tables.py | 88 +++++++++++- 2 files changed, 196 insertions(+), 18 deletions(-) diff --git a/products/platform/journeys/rstack-dev.sh b/products/platform/journeys/rstack-dev.sh index 39dc3a52cd..f24b30b5b1 100755 --- a/products/platform/journeys/rstack-dev.sh +++ b/products/platform/journeys/rstack-dev.sh @@ -286,6 +286,18 @@ path.write_text(source.replace(marker, hook + marker)) PYHOOK } +# Use the maintained Documents observer policies with the development starter's +# people, journey, and custody policies. +add_documents_hooks() { + local target=$1/documents.yaml + local starter=$JOURNEY_ROOT/products/documents/examples/starter/documents.yaml + if ! grep -Fxq 'hooks:' "$target"; then + grep -Fxq 'hooks:' "$starter" || journey_harness_failure "the Documents starter has no observer policies" + printf '\n' >>"$target" + sed -n '/^hooks:$/,$p' "$starter" >>"$target" + fi +} + # The Adapter starter writes two effects to an authored reference endpoint. # Speak the documented fixture's two replies over a disposable local socket. start_adapter_source() { @@ -401,11 +413,6 @@ write_keep() { KEEP_EXPECT=retained-counter return ;; - documents) - path=/v1/documents - body='{"policyId":"institutional-custody","expectedDigest":"sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855","length":1,"mediaType":"application/pdf","label":"Retained document","custodian":{"subject":"starter-citizen"}}' - field='.document.id' - ;; coordinator) path=/v1/runs send_after=$(python3 -c 'from datetime import datetime, timedelta, timezone; print((datetime.now(timezone.utc) + timedelta(days=1)).isoformat(timespec="seconds"))') @@ -426,7 +433,7 @@ write_keep() { [[ "$product" != casework ]] || write_path="$path?accessProfile=requester" journey_http "$step" "${options[@]}" --data-file "$work/keep-body.json" --capture "$field" saved_id "$method" "$url$write_path" || unexpected_answer "$step" case "$product" in - breg | documents | coordinator) KEEP_PATH=$path/$saved_id ;; + breg | coordinator) KEEP_PATH=$path/$saved_id ;; casework) KEEP_PATH=$path/$saved_id ;; adapter) KEEP_PATH=$path ;; esac @@ -481,7 +488,7 @@ unexpected_answer() { walk_product() { # shellcheck disable=SC2034 # token and token2 are set by name through issue_token local product=$1 work project tier plan_capable status=0 url message_id='' token='' token2='' workflow_revision='' uses_postgres - local first_read=0 + local first_read=0 documents_receipt='' journey_product_field "$product" tier tier journey_product_field "$product" rstackDevPlan plan_capable journey_product_field "$product" usesPostgres uses_postgres @@ -526,6 +533,7 @@ walk_product() { # start: one command, after supplying the optional fixture endpoints. case "$product" in breg) add_contact_hook "$project" ;; + documents) add_documents_hooks "$project" ;; casework) # Use the generated test person's issuer for the starter's # trusted producer on this disposable project. @@ -604,8 +612,9 @@ walk_product() { first_read=1 fi - # hook: BReg's keep write also triggers its local sink. - if [[ "$product" == breg ]]; then + # The BReg and Documents writes also test retention after restart. + case "$product" in + breg) local sink write_keep "$product" "$work" "$project" "$url" "$run" sink=$(jq -er '.bregHookSink.receivedUrl' "$START_FILE") @@ -615,12 +624,16 @@ walk_product() { breg_hook_matches "$KEEP_EXPECT" "$JOURNEY_STEP_STDOUT" || journey_harness_failure "the BReg hook receipt does not contain the retained contact's creation event" journey_pass hook - else - journey_unexercised hook - fi + ;; + documents) + documents_ready_hook "$work" "$url" token documents_receipt + journey_pass hook + ;; + *) journey_unexercised hook ;; + esac if [[ "$uses_postgres" == true ]]; then - if [[ "$product" != breg ]]; then + if [[ "$product" != breg && "$product" != documents ]]; then write_keep "$product" "$work" "$project" "$url" "$run" fi local audit='' first_start_file=$START_FILE @@ -672,6 +685,10 @@ walk_product() { fi jq -e --arg expected "$KEEP_EXPECT" '[.. | strings] | index($expected) != null' "$JOURNEY_STEP_STDOUT" >/dev/null || journey_harness_failure "the retained $product response did not contain the written record" + if [[ "$product" == documents ]]; then + documents_ready_matches "$documents_receipt" "$JOURNEY_STEP_STDOUT" || + journey_harness_failure "the retained document no longer identifies the ready version" + fi if [[ "$method" == GET && $first_read -eq 0 ]]; then journey_reached t1 fi @@ -679,9 +696,9 @@ walk_product() { journey_step keep -- audit_was_appended "$work/audit-before-restart.jsonl" "$audit" fi # These paths have written and read back a record across a restart. - # BReg also delivered its observer hook before the restart. + # BReg and Documents also delivered an observer hook before the restart. case "$product" in - breg | coordinator | messaging) journey_reached t2 ;; + breg | coordinator | documents | messaging) journey_reached t2 ;; esac else printf '%s\n' "$product has no PostgreSQL state to retain." @@ -769,6 +786,85 @@ hook_received() { curl --silent --fail --max-time 3 "$1" | breg_hook_matches "$2" } +# The managed sink authenticates the delivery. Correlate its captured envelope +# and signing headers to the operation, without accepting forwarded credentials. +signed_hook_matches() { + local expected=$1 + shift + jq -e --argjson expected "$expected" 'any(.[]; + . as $capture | (.body | fromjson?) as $event | + $event.type == $expected.type and $event.data == $expected.data and + ($expected.source == null or $event.source == $expected.source) and + ($event.id | type == "string" and length > 0) and + any($capture.headers[]; .name == "webhook-id" and .value == $event.id) and + any($capture.headers[]; .name == "webhook-timestamp" and (.value | test("^[0-9]+$"))) and + any($capture.headers[]; .name == "webhook-signature" and (.value | startswith("v1,"))) and + all($capture.headers[]; .name != "authorization" and .name != "cookie" and + .name != "registry-source-authorization" and .name != "proxy-authorization"))' "$@" >/dev/null +} + +signed_hook_received() { + curl --silent --fail --max-time 3 "$1" | signed_hook_matches "$2" +} + +managed_hook_url() { + local product=$1 value + value=$(jq -er --arg product "$product" '.hookSinks[$product].receivedUrl | strings | select(length > 0)' "$START_FILE") || + journey_harness_failure "the local $product run did not report its hook sink" + printf -v "$2" '%s' "$value" +} + +check_managed_hook() { + local product=$1 sink=$2 expected=$3 + journey_poll 45 -- signed_hook_received "$sink" "$expected" || + journey_harness_failure "the local $product hook sink did not receive the expected event" + journey_http hook GET "$sink" || unexpected_answer hook + signed_hook_matches "$expected" "$JOURNEY_STEP_STDOUT" || + journey_harness_failure "the local $product hook receipt did not contain the expected event" +} + +documents_ready_matches() { + jq -e --argjson event "$1" ' + .id == $event.data.documentId and .version.id == $event.data.versionId and + .version.expectedDigest == $event.data.versionDigest and .version.status == "ready"' "$2" >/dev/null +} + +# Reserve and upload the synthetic PDF, then read the same ready version. +# Leave its path and ID for the retained read rather than reserving a second document. +documents_ready_hook() { + local work=$1 origin=$2 bearer=$3 result=$4 + local pdf=$work/retained.pdf reserve=$work/document-reserve.json + local digest document='' version='' upload='' ready_event sink + managed_hook_url documents sink + journey_write_file "$pdf" < <(printf '%%PDF-1.7\n%%%%EOF\n') + digest=$(perl -MDigest::SHA -e 'print "sha256:", Digest::SHA->new(256)->addfile($ARGV[0], "b")->hexdigest' "$pdf") || + journey_harness_failure "cannot digest the synthetic document" + journey_write_file "$reserve" < <( + jq -cn --arg digest "$digest" --argjson length "$(wc -c <"$pdf")" \ + '{policyId:"institutional-custody", custodian:{subject:"starter-citizen"}, + expectedDigest:$digest, length:$length, mediaType:"application/pdf"}' + ) + journey_http hook --expect-status 201 --bearer "$bearer" --header 'Content-Type: application/json' \ + --header 'Idempotency-Key: journey-document-reservation' --data-file "$reserve" \ + --capture .uploadPath upload --capture .document.id document --capture .document.version.id version \ + POST "$origin/v1/documents" || unexpected_answer hook + [[ "$upload" =~ ^/v1/uploads/[0-9a-f-]+/content$ ]] || + journey_harness_failure "the document reservation returned an invalid upload path" + journey_http hook --expect-status 200 --bearer "$bearer" --header 'Content-Type: application/pdf' \ + --data-file "$pdf" PUT "$origin$upload" || unexpected_answer hook + ready_event=$(jq -cn --arg document "$document" --arg version "$version" --arg digest "$digest" \ + '{source:"urn:registrystack:documents:civil-registry-documents", type:"document-version-ready", + data:{documentId:$document, versionId:$version, versionDigest:$digest, policyId:"institutional-custody", policyVersion:"1"}}') + check_managed_hook documents "$sink" "$ready_event" + KEEP_PERSON=$PERSON + KEEP_PATH=/v1/documents/$document + KEEP_EXPECT=$document + journey_http hook --expect-status 200 --bearer "$bearer" GET "$origin$KEEP_PATH" || unexpected_answer hook + documents_ready_matches "$ready_event" "$JOURNEY_STEP_STDOUT" || + journey_harness_failure "the document read did not return the exact ready version from the hook" + printf -v "$result" '%s' "$ready_event" +} + # attach_database PROJECT: start PROJECT against a PostgreSQL server the reader # runs: a stock container with no certificate, using explicit loopback plaintext # (?sslmode=disable). The password reaches the child process through the diff --git a/products/platform/journeys/test_journey_tables.py b/products/platform/journeys/test_journey_tables.py index f6813f3bdd..9b70fa6297 100644 --- a/products/platform/journeys/test_journey_tables.py +++ b/products/platform/journeys/test_journey_tables.py @@ -910,7 +910,11 @@ class LocalHookWalk(unittest.TestCase): def walk(self, product, delivered): script = (TABLES / "rstack-dev.sh").read_text(encoding="utf-8") functions = [] - for name in ("walk_product", "recipe", "hook_received", "breg_hook_matches"): + for name in ( + "walk_product", "recipe", "hook_received", "breg_hook_matches", + "managed_hook_url", "check_managed_hook", "signed_hook_received", "signed_hook_matches", + "documents_ready_hook", "documents_ready_matches", + ): match = re.search(rf"^{name}\(\) \{{\n.*?^\}}\n", script, re.M | re.S) self.assertIsNotNone(match, name) functions.append(match.group(0)) @@ -925,14 +929,19 @@ def walk(self, product, delivered): : >"$scratch/audit.schedulingctl.jsonl" init_command() { INIT_COMMAND=(true); } add_contact_hook() { :; } +add_documents_hooks() { :; } start_run() { local result=passed [[ "$1" != keep ]] || result=skipped RUN=$1-run START_FILE=$scratch/$1.json - jq -n --arg product "$CELL" --arg runtime "$scratch/runtime.json" --arg result "$result" ' + jq -n --arg product "$CELL" --arg runtime "$scratch/runtime.json" --arg result "$result" \ + --arg delivered "$delivered" ' {runtimeConfigs: {($product): $runtime}, scenarios: [{id: "starter", result: $result}], - bregHookSink: {receivedUrl: "http://127.0.0.1:49191/received"}}' >"$START_FILE" + bregHookSink: {receivedUrl: "http://127.0.0.1:49191/received"}} + + if $delivered == "no-sink" then {} else + {hookSinks: {documents: {receivedUrl: "http://127.0.0.1:49191/received"}}} + end' >"$START_FILE" LIVE_RUNS+="$RUN"$'\n' } run_url() { printf '%s\n' 'http://127.0.0.1:49192'; } @@ -945,6 +954,19 @@ def walk(self, product, delivered): } sink_response() { local record + if [[ "$CELL" == documents ]]; then + jq -nc --arg digest "$(<"$scratch/digest")" --arg mode "$delivered" ' + {id: "evt-1", source: "urn:registrystack:documents:civil-registry-documents", + type: "document-version-ready", data: {documentId: "retained-id", + versionId: (if $mode == "other-version" then "other" else "version-id" end), + versionDigest: $digest, policyId: "institutional-custody", policyVersion: "1"}} as $event | + [{body: ($event | tojson), headers: [ + {name: "webhook-id", value: "evt-1"}, + {name: "webhook-timestamp", value: "1"}, + {name: "webhook-signature", value: "v1,fixture"} + ] + (if $mode == "forwarded-auth" then [{name: "authorization", value: "fixture"}] else [] end)}]' + return + fi case "$delivered" in yes | missing-on-read) record=retained-id ;; wrong-record) record=other-id ;; @@ -963,8 +985,46 @@ def walk(self, product, delivered): shift 2 "$@" } +document_view() { + jq -nc --arg digest "$(<"$scratch/digest")" --arg version "$1" \ + '{id:"retained-id", version:{id:$version, status:"ready", expectedDigest:$digest}}' +} +documents_http() { + local request=${@: -2:1} url=${!#} + case "$request $url" in + 'POST http://127.0.0.1:49192/v1/documents') + local expected actual + expected=$(jq -er '.expectedDigest' "$work/document-reserve.json") + actual=$(perl -MDigest::SHA -e 'print "sha256:", Digest::SHA->new(256)->addfile($ARGV[0], "b")->hexdigest' "$work/retained.pdf") + [[ "$expected" == "$actual" ]] + printf '%s' "$expected" >"$scratch/digest" + document=retained-id version=version-id upload=/v1/uploads/abcd/content + printf '%s\n' 'reserve document' >>"$trace" + ;; + 'PUT http://127.0.0.1:49192/v1/uploads/abcd/content') + printf '%s\n' 'upload document' >>"$trace" + ;; + 'GET http://127.0.0.1:49192/v1/documents/retained-id') + printf '%s\n' 'read ready document' >>"$trace" + if [[ "$1" == keep && "$delivered" == changed-after-restart ]]; then + document_view other-version >"$JOURNEY_STEP_STDOUT" + else + document_view version-id >"$JOURNEY_STEP_STDOUT" + fi + ;; + *) return 1 ;; + esac +} journey_http() { JOURNEY_STEP_STDOUT=$scratch/response.json + if [[ "$CELL" == documents ]]; then + case "${!#}" in + http://127.0.0.1:49192/v1/documents* | http://127.0.0.1:49192/v1/uploads/*) + documents_http "$@" + return + ;; + esac + fi case "$1" in call) printf '%s\n' '{}' >"$JOURNEY_STEP_STDOUT" ;; hook) @@ -1046,6 +1106,28 @@ def test_final_step_cannot_be_unexercised(self): self.assertIn("the final step of scheduling cannot be marked unexercised", result.stderr) self.assertEqual(outcomes, []) + def test_documents_keeps_the_same_ready_version_after_one_upload(self): + result, outcomes, trace = self.walk("documents", "yes") + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertEqual(outcomes[-4:], [("hook", "pass"), ("keep", "pass"), ("attach", "pass"), ("stop", "pass")]) + self.assertEqual(trace, ["reserve document", "upload document", "poll sink", "read sink", + "read ready document", "read ready document"]) + + def test_documents_refuses_unmatched_capture_or_readback(self): + for delivered, diagnostic in ( + ("no-sink", "did not report its hook sink"), + ("other-version", "did not receive the expected event"), + ("forwarded-auth", "did not receive the expected event"), + ("changed-after-restart", "no longer identifies the ready version"), + ): + with self.subTest(delivered=delivered): + result, outcomes, trace = self.walk("documents", delivered) + self.assertEqual(result.returncode, 3, result.stdout + result.stderr) + self.assertIn(diagnostic, result.stderr) + self.assertNotIn(("keep", "pass"), outcomes) + if delivered == "no-sink": + self.assertEqual(trace, []) + class HookReceiverAndAdapterSource(unittest.TestCase): def test_hook_receiver_signature_verification(self): From 527c45829184b1db95588a863e8b929e10561d90 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 17:32:14 +0000 Subject: [PATCH 032/183] feat(dev): check saved Casework reports offline Signed-off-by: Jeremi Joslin --- Cargo.lock | 1 + crates/registry-rstack-dev/Cargo.toml | 5 +- crates/registry-rstack-dev/src/lib.rs | 32 +- .../registry-rstack-dev/src/owner_report.rs | 453 ++++++++++++++++++ .../src/owner_report_tests.rs | 182 +++++++ crates/registry-rstack/src/cli.rs | 106 +++- products/platform/CONFIG-CONVENTIONS.md | 19 +- products/platform/config-formats.yaml | 9 +- .../scripts/check-config-conventions.py | 34 +- .../scripts/test_check_config_conventions.py | 33 ++ 10 files changed, 835 insertions(+), 39 deletions(-) create mode 100644 crates/registry-rstack-dev/src/owner_report.rs create mode 100644 crates/registry-rstack-dev/src/owner_report_tests.rs diff --git a/Cargo.lock b/Cargo.lock index c08f26801e..70191da9f4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -8399,6 +8399,7 @@ dependencies = [ "rcgen", "registry-cli-report", "registry-platform-buildinfo", + "registry-platform-canonical-json", "registry-platform-config", "registry-platform-crypto", "registry-platform-hooks", diff --git a/crates/registry-rstack-dev/Cargo.toml b/crates/registry-rstack-dev/Cargo.toml index a710db5c2e..abeddad28b 100644 --- a/crates/registry-rstack-dev/Cargo.toml +++ b/crates/registry-rstack-dev/Cargo.toml @@ -35,10 +35,12 @@ axum.workspace = true base64.workspace = true clap.workspace = true getrandom.workspace = true +jsonschema.workspace = true postgres-protocol.workspace = true rcgen.workspace = true registry-cli-report.workspace = true registry-platform-buildinfo.workspace = true +registry-platform-canonical-json.workspace = true registry-platform-config.workspace = true registry-platform-crypto.workspace = true registry-platform-hooks = { workspace = true, features = ["receiver"] } @@ -64,6 +66,3 @@ tokio-postgres-rustls.workspace = true url.workspace = true uuid = { workspace = true, features = ["serde"] } zeroize.workspace = true - -[dev-dependencies] -jsonschema.workspace = true diff --git a/crates/registry-rstack-dev/src/lib.rs b/crates/registry-rstack-dev/src/lib.rs index f50cf119c5..667bf3b685 100644 --- a/crates/registry-rstack-dev/src/lib.rs +++ b/crates/registry-rstack-dev/src/lib.rs @@ -22,6 +22,7 @@ mod external_breg; pub(crate) mod guard; mod issuer; mod journey; +mod owner_report; pub(crate) mod plan; mod preview; mod products; @@ -120,10 +121,13 @@ pub struct Args { enum Entry { Check { /// Refuse unaccepted warnings. Development posture listings do not count. - #[arg(long)] + #[arg(long, conflicts_with = "owner_report_format")] deny_warnings: bool, #[arg(long)] json: bool, + #[arg(long, value_enum)] + owner_report_format: Option, + /// Plan directory, or the saved JSON file when an owner report format is selected. project: PathBuf, }, Start { @@ -609,11 +613,18 @@ pub fn run(args: Args, stdout: &mut dyn Write, stderr: &mut dyn Write) -> ExitCo project, deny_warnings, json, + owner_report_format, } => { + if let Some(format) = owner_report_format { + let (report, exit) = owner_report::check_file(&project, format); + return ExitCode::from(write_check_report( + report, exit, json, stdout, stderr, true, + )); + } if let Err((code, message, action)) = require_development(declared(None)) { let report = Report::new(vec![Diagnostic::error(code, "", message, action)]); return ExitCode::from(write_check_report( - report, USAGE_EXIT, json, stdout, stderr, + report, USAGE_EXIT, json, stdout, stderr, false, )); } return ExitCode::from(check(&project, deny_warnings, json, stdout, stderr)); @@ -934,6 +945,7 @@ fn check( machine, stdout, stderr, + false, ); } let (code, action, exit) = if error.is::() { @@ -956,7 +968,7 @@ fn check( } }, }; - write_check_report(report, exit, machine, stdout, stderr) + write_check_report(report, exit, machine, stdout, stderr, false) } fn write_check_report( @@ -965,20 +977,28 @@ fn write_check_report( machine: bool, stdout: &mut dyn Write, stderr: &mut dyn Write, + structure_only: bool, ) -> u8 { let result = if machine { - let payload = json!({ + let mut payload = json!({ "ok": exit == 0, "command": "dev-check", "status": registry_cli_report::Status::from_exit(exit).as_str(), "diagnostics": report.to_json_value(), }); + if structure_only { + payload["assessment"] = json!("owner-report-structure"); + } write_check_json(stdout, payload) .map_err(io::Error::other) .and_then(|()| writeln!(stdout)) } else if exit == 0 { - writeln!(stdout, "Development plan is valid") - .and_then(|()| write!(stdout, "{}", report.render_human())) + let message = if structure_only { + "Owner report structure is valid" + } else { + "Development plan is valid" + }; + writeln!(stdout, "{message}").and_then(|()| write!(stdout, "{}", report.render_human())) } else { write!(stderr, "{}", report.render_human()) }; diff --git a/crates/registry-rstack-dev/src/owner_report.rs b/crates/registry-rstack-dev/src/owner_report.rs new file mode 100644 index 0000000000..4cd409be95 --- /dev/null +++ b/crates/registry-rstack-dev/src/owner_report.rs @@ -0,0 +1,453 @@ +// SPDX-License-Identifier: Apache-2.0 + +//! Structural read-back of bounded saved JSON reports. + +use jsonschema::{ + error::ErrorIterator, + paths::{JSONPointer, JsonPointerNode, PathChunk}, + Draft, JSONSchema, Keyword, ValidationError, +}; +use registry_platform_yaml::{ + ApiVersion, Diagnostic, EnvelopeRule, Expect, FormatSpec, Reader, Report, Source, + MAXIMUM_DOCUMENT_BYTES, +}; +use serde_json::{json, Value}; +use std::{ + collections::BTreeMap, + fs::OpenOptions, + io::{self, Read}, + os::unix::fs::OpenOptionsExt, + path::Path, + sync::OnceLock, +}; + +const CASEWORK: &str = include_str!("../../../products/casework/contracts/cli/report.schema.json"); +const CASEWORK_FORMAT: FormatSpec<'static> = FormatSpec { + kind: "CaseworkReport", + envelope: EnvelopeRule::ApiVersionKind { + api_versions: &[ApiVersion::current( + "id.registrystack.org/formats/casework/report/v1alpha2", + )], + retired_api_versions: &[], + }, + removed_keys: &[], +}; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, clap::ValueEnum)] +pub(crate) enum Format { + CaseworkReport, +} + +#[derive(Debug)] +pub(crate) struct Invalid { + path: String, + message: &'static str, + position: Option<(usize, usize)>, + schema_unavailable: bool, +} + +impl Invalid { + fn at(path: impl Into, message: &'static str) -> Self { + Self { + path: path.into(), + message, + position: None, + schema_unavailable: false, + } + } +} + +fn parse(bytes: &[u8]) -> Result { + if bytes.len() > MAXIMUM_DOCUMENT_BYTES { + return Err(Invalid::at("", "Owner report exceeds the 1 MiB limit")); + } + registry_platform_canonical_json::parse_json_preserving_integers(bytes).map_err(|error| { + Invalid { + path: String::new(), + message: "Expected one valid JSON document with unique member names", + position: (error.line() > 0).then_some((error.line(), error.column())), + schema_unavailable: false, + } + }) +} + +fn decode(bytes: &[u8], format: Format) -> Result { + let report = parse(bytes)?; + let expected = match format { + Format::CaseworkReport => &CASEWORK_FORMAT, + }; + // The JSON parser enforces the declared syntax. The shared reader checks + // the envelope and document limits. Its diagnostics can name user input, + // so only positions and known envelope fields reach this command's report. + Reader::new("owner report") + .read(bytes, &Expect::one(expected)) + .map_err(|report| { + let mut invalid = Invalid::at( + "", + "Expected a valid CaseworkReport v1alpha2 envelope and document", + ); + if let Some(first) = report.diagnostics().first() { + if matches!(first.path.as_str(), "/kind" | "/apiVersion") { + invalid.path.clone_from(&first.path); + } + invalid.position = first + .source + .as_ref() + .and_then(|source| source.line.zip(source.column)); + } + invalid + })?; + validate(&report, format)?; + Ok(report) +} + +fn validate(report: &Value, format: Format) -> Result<(), Invalid> { + match format { + Format::CaseworkReport => validate_casework(report), + } +} + +struct CaseworkSchemas { + family: Schema, + branches: BTreeMap, +} + +fn validate_casework(report: &Value) -> Result<(), Invalid> { + static SCHEMAS: OnceLock> = OnceLock::new(); + let schemas = SCHEMAS.get_or_init(|| { + let mut schema: Value = serde_json::from_str(CASEWORK).ok()?; + let mut branches = BTreeMap::new(); + for branch in schema["oneOf"].as_array()? { + // The generated family consists of closed branches with distinct command constants. + if branch["additionalProperties"] != false { + return None; + } + let command = branch.pointer("/properties/command/const")?.as_str()?; + let mut branch = branch.clone(); + branch["$defs"] = schema["$defs"].clone(); + if branches + .insert(command.to_owned(), compile(branch)?) + .is_some() + { + return None; + } + } + // Every selected command branch already rejects undeclared fields. + // jsonschema 0.18 misattributes evaluated properties across the root + // applicators, so compile the family without the redundant closure. + if schema.as_object_mut()?.remove("unevaluatedProperties") != Some(json!(false)) { + return None; + } + Some(CaseworkSchemas { + family: compile(schema)?, + branches, + }) + }); + let schemas = schemas.as_ref().ok_or_else(schema_unavailable)?; + let branch = report["command"] + .as_str() + .and_then(|command| schemas.branches.get(command)) + .ok_or_else(|| { + Invalid::at( + "/command", + "Expected a command from the Casework report contract", + ) + })?; + // Validate the selected branch first to retain its field-level diagnostics. + // The family also imposes shared completion and refusal rules at the root. + branch.validate(report, "")?; + schemas.family.validate(report, "") +} + +fn schema_unavailable() -> Invalid { + Invalid { + schema_unavailable: true, + ..Invalid::at("", "The embedded owner report schema could not be loaded") + } +} + +const MAX_DIAGNOSTIC_NODES: usize = 256; +const MAX_DIAGNOSTIC_TEXT_BYTES: usize = 16 * 1024; + +struct Schema { + validator: JSONSchema, + document: Value, +} + +impl Schema { + fn validate(&self, value: &Value, prefix: &str) -> Result<(), Invalid> { + if self.validator.is_valid(value) { + return Ok(()); + } + let fallback = || Invalid::at(prefix, "Owner report violates the selected schema"); + // The detailed validator eagerly collects child errors for array items. + // Bound the tree and text it can inspect before requesting even one error. + let mut nodes = MAX_DIAGNOSTIC_NODES; + let mut text_bytes = MAX_DIAGNOSTIC_TEXT_BYTES; + if !fits_diagnostic_budget(value, &mut nodes, &mut text_bytes) { + return Err(fallback()); + } + let Some(error) = self + .validator + .validate(value) + .err() + .and_then(|mut errors| errors.next()) + else { + return Err(fallback()); + }; + let message = match error.kind { + jsonschema::error::ValidationErrorKind::Custom { .. } => { + "Expected a native JSON integer within the field's bounds" + } + _ => "Owner report violates the selected schema at this location", + }; + Err(Invalid::at( + self.diagnostic_path(prefix, &error.instance_path), + message, + )) + } + + fn diagnostic_path(&self, prefix: &str, instance_path: &JSONPointer) -> String { + let mut path = prefix.to_owned(); + let mut schema = &self.document; + for part in instance_path { + let Some(resolved) = self.resolve_path_schema(schema) else { + break; + }; + // Only literal properties and array items establish a safe path. + // Dynamic map members and ambiguous schema positions end the path. + match part { + PathChunk::Property(name) => { + let Some(child) = resolved["properties"].get(name.as_ref()) else { + break; + }; + schema = child; + path.push('/'); + path.push_str(&name.replace('~', "~0").replace('/', "~1")); + } + PathChunk::Index(index) => { + let Some(child) = resolved["prefixItems"] + .get(*index) + .or_else(|| resolved.get("items")) + else { + break; + }; + schema = child; + path.push('/'); + path.push_str(&index.to_string()); + } + PathChunk::Keyword(_) => break, + } + } + path + } + + fn resolve_path_schema<'a>(&'a self, mut schema: &'a Value) -> Option<&'a Value> { + for _ in 0..16 { + let Some(reference) = schema.get("$ref") else { + return Some(schema); + }; + let pointer = reference.as_str()?.strip_prefix('#')?; + schema = self.document.pointer(pointer)?; + } + None + } +} + +fn fits_diagnostic_budget(value: &Value, nodes: &mut usize, text_bytes: &mut usize) -> bool { + let Some(remaining) = nodes.checked_sub(1) else { + return false; + }; + *nodes = remaining; + match value { + Value::Array(items) => items + .iter() + .all(|item| fits_diagnostic_budget(item, nodes, text_bytes)), + Value::Object(fields) => fields.iter().all(|(key, value)| { + spend_text_budget(key, text_bytes) && fits_diagnostic_budget(value, nodes, text_bytes) + }), + Value::String(text) => spend_text_budget(text, text_bytes), + _ => true, + } +} + +fn spend_text_budget(text: &str, budget: &mut usize) -> bool { + let Some(remaining) = budget.checked_sub(text.len()) else { + return false; + }; + *budget = remaining; + true +} + +const EXACT_INTEGER: &str = "x-rstack-report-integer"; + +fn compile(mut document: Value) -> Option { + annotate(&mut document); + let validator = JSONSchema::options() + .with_draft(Draft::Draft202012) + .with_keyword(EXACT_INTEGER, exact_integer) + .compile(&document) + .ok()?; + Some(Schema { + validator, + document, + }) +} + +// Add integer-token checks to compiler input only. The standard validator still +// applies the generated schema and resolves references and union arms normally. +fn annotate(schema: &mut Value) { + if schema["type"] == "integer" + || schema["type"] + .as_array() + .is_some_and(|types| types.iter().any(|ty| ty == "integer")) + { + schema[EXACT_INTEGER] = json!(true); + } + for key in [ + "properties", + "$defs", + "patternProperties", + "dependentSchemas", + ] { + if let Some(children) = schema.get_mut(key).and_then(Value::as_object_mut) { + for child in children.values_mut() { + annotate(child); + } + } + } + for key in ["oneOf", "anyOf", "allOf", "prefixItems"] { + if let Some(children) = schema.get_mut(key).and_then(Value::as_array_mut) { + for child in children { + annotate(child); + } + } + } + for key in [ + "items", + "additionalProperties", + "if", + "then", + "else", + "not", + "contains", + ] { + if let Some(child) = schema.get_mut(key) { + annotate(child); + } + } +} + +fn integer(value: &Value) -> Option { + value + .as_u64() + .map(i128::from) + .or_else(|| value.as_i64().map(i128::from)) +} + +struct ExactInteger { + path: JSONPointer, + minimum: i128, + maximum: i128, + nullable: bool, +} + +fn exact_integer<'a>( + parent: &'a serde_json::Map, + _: &'a Value, + path: JSONPointer, +) -> Result, ValidationError<'a>> { + let minimum = parent + .get("minimum") + .and_then(integer) + .unwrap_or(i128::from(i64::MIN)); + let mut maximum = parent + .get("maximum") + .and_then(integer) + .unwrap_or(i128::from(u64::MAX)); + if parent.get("format").and_then(Value::as_str) == Some("uint") { + maximum = maximum.min(usize::MAX as i128); + } + let nullable = parent + .get("type") + .and_then(Value::as_array) + .is_some_and(|types| types.iter().any(|ty| ty == "null")); + Ok(Box::new(ExactInteger { + path, + minimum, + maximum, + nullable, + })) +} + +impl Keyword for ExactInteger { + fn is_valid(&self, value: &Value) -> bool { + (self.nullable && value.is_null()) + || integer(value).is_some_and(|n| (self.minimum..=self.maximum).contains(&n)) + } + + fn validate<'a>(&self, value: &'a Value, path: &JsonPointerNode) -> ErrorIterator<'a> { + if self.is_valid(value) { + Box::new(std::iter::empty()) + } else { + Box::new(std::iter::once(ValidationError::custom( + self.path.clone(), + path.clone().into(), + value, + "Expected a bounded native integer", + ))) + } + } +} + +pub(crate) fn check_file(path: &Path, format: Format) -> (Report, u8) { + let file = OpenOptions::new() + .read(true) + .custom_flags(rustix::fs::OFlags::NONBLOCK.bits() as i32) + .open(path); + let bytes = file.and_then(|file| { + if !file.metadata()?.is_file() { + return Err(io::Error::other("expected a regular file")); + } + let mut bytes = Vec::new(); + file.take(MAXIMUM_DOCUMENT_BYTES as u64 + 1) + .read_to_end(&mut bytes)?; + Ok(bytes) + }); + let (invalid, exit, code, remedy) = match bytes { + Ok(bytes) => match decode(&bytes, format) { + Ok(_) => return (Report::new(Vec::new()), 0), + Err(error) if error.schema_unavailable => ( + error, + crate::OPERATIONAL_FAILURE_EXIT, + "rstack.dev.owner-report-schema-unavailable", + "Use an rstack development host with a valid embedded owner report schema.", + ), + Err(error) => ( + error, + crate::DOMAIN_REFUSAL_EXIT, + "rstack.dev.owner-report-invalid", + "Select the matching owner report format and capture a fresh report as JSON.", + ), + }, + Err(_) => ( + Invalid::at("", "Cannot read the owner report as a regular file"), + crate::OPERATIONAL_FAILURE_EXIT, + "rstack.dev.owner-report-unreadable", + "Pass a readable regular JSON file to --owner-report.", + ), + }; + let mut diagnostic = Diagnostic::error(code, invalid.path, invalid.message, remedy); + diagnostic.source = Some(Source { + file: path.display().to_string(), + line: invalid.position.map(|(line, _)| line), + column: invalid + .position + .and_then(|(_, column)| (column > 0).then_some(column)), + }); + (Report::new(vec![diagnostic]), exit) +} + +#[cfg(test)] +#[path = "owner_report_tests.rs"] +mod tests; diff --git a/crates/registry-rstack-dev/src/owner_report_tests.rs b/crates/registry-rstack-dev/src/owner_report_tests.rs new file mode 100644 index 0000000000..cedb7ad82a --- /dev/null +++ b/crates/registry-rstack-dev/src/owner_report_tests.rs @@ -0,0 +1,182 @@ +// SPDX-License-Identifier: Apache-2.0 + +use super::*; + +const CASEWORK: &str = + include_str!("../../../products/casework/examples/formats/reports/check-report.json"); + +#[test] +fn casework_checks_resolved_branch_and_exact_numeric_tokens() { + let report = |count: &str| { + let value: Value = serde_json::from_str(CASEWORK).unwrap(); + let marker = "replace-count"; + let mut value = value; + value["filesChecked"] = json!(marker); + serde_json::to_string(&value) + .unwrap() + .replace(&format!("\"{marker}\""), count) + }; + for count in ["0", &usize::MAX.to_string()] { + assert!(decode(report(count).as_bytes(), Format::CaseworkReport).is_ok()); + } + for count in ["-1", "1.0", "1e0"] { + let error = decode(report(count).as_bytes(), Format::CaseworkReport).unwrap_err(); + assert_eq!(error.path, "/filesChecked"); + } + assert!(decode( + report("18446744073709551616").as_bytes(), + Format::CaseworkReport + ) + .is_err()); + let mut check: Value = serde_json::from_str(CASEWORK).unwrap(); + check["status"] = json!("domain-refusal"); + assert!(decode(&serde_json::to_vec(&check).unwrap(), Format::CaseworkReport).is_err()); + check["status"] = json!("complete"); + check["unexpected"] = json!(true); + assert!(decode(&serde_json::to_vec(&check).unwrap(), Format::CaseworkReport).is_err()); + check.as_object_mut().unwrap().remove("unexpected"); + check["command"] = json!("package"); + assert!(decode(&serde_json::to_vec(&check).unwrap(), Format::CaseworkReport).is_err()); +} + +#[test] +fn casework_native_u32_counts_use_the_selected_command_branch() { + let mut report = json!({ + "ok": true, "command": "generate-identity-facts", "status": "complete", + "apiVersion": "id.registrystack.org/formats/casework/report/v1alpha2", + "kind": "CaseworkReport", "version": "synthetic", "diagnostics": [], + "output": "synthetic.json", "product": "casework", + "claims": u32::MAX, "accessProfiles": 0, "assertionIssuers": 0, + }); + let decode = + |report: &Value| decode(&serde_json::to_vec(report).unwrap(), Format::CaseworkReport); + assert!(decode(&report).is_ok()); + report["claims"] = json!(u64::from(u32::MAX) + 1); + assert_eq!(decode(&report).unwrap_err().path, "/claims"); +} + +#[test] +fn plain_reader_refuses_duplicate_trailing_and_oversized_json() { + assert!(parse(br#"{"a":{"b":1,"b":2}}"#).is_err()); + assert!(parse(br#"{} {}"#).is_err()); + assert!(parse(&vec![b' '; MAXIMUM_DOCUMENT_BYTES + 1]).is_err()); +} + +#[test] +fn integer_constraints_follow_refs_and_selected_union_arms() { + let schema = compile(json!({ + "$defs": {"bound": {"type": ["integer", "null"], "minimum": 0, "maximum": 65535}}, + "oneOf": [ + {"type": "object", "required": ["type", "count"], + "properties": {"type": {"const": "count"}, "count": {"$ref": "#/$defs/bound"}}}, + {"type": "object", "required": ["type", "count"], + "properties": {"type": {"const": "number"}, "count": {"type": "number"}}} + ] + })) + .unwrap(); + for (raw, valid) in [ + (br#"{"type":"count","count":65535}"#.as_slice(), true), + (br#"{"type":"count","count":null}"#, true), + (br#"{"type":"count","count":65536}"#, false), + (br#"{"type":"count","count":1e0}"#, false), + (br#"{"type":"number","count":1e0}"#, true), + ] { + assert_eq!(schema.validator.is_valid(&parse(raw).unwrap()), valid); + } + let signed = + compile(json!({"type": "integer", "minimum": i64::MIN, "maximum": i64::MAX})).unwrap(); + assert!(signed.validator.is_valid(&json!(i64::MIN))); + assert!(signed.validator.is_valid(&json!(i64::MAX))); + assert!(!signed.validator.is_valid(&json!(i64::MAX as u64 + 1))); + assert!(!signed + .validator + .is_valid(&parse(b"-9223372036854775809").unwrap())); + let unsigned = compile(json!({"type": "integer", "minimum":0, "maximum": u64::MAX})).unwrap(); + for n in [(1u64 << 53) - 1, (1u64 << 53) + 1, u64::MAX - 1, u64::MAX] { + assert!(unsigned.validator.is_valid(&json!(n))); + } +} + +#[test] +fn hosted_file_check_reports_structure_and_redacts_parser_errors() { + let file = tempfile::NamedTempFile::new().unwrap(); + let run = |bytes: &[u8]| { + std::fs::write(file.path(), bytes).unwrap(); + let mut out = Vec::new(); + let mut err = Vec::new(); + let status = crate::run( + crate::Args { + entry: crate::Entry::Check { + project: file.path().to_owned(), + deny_warnings: false, + json: true, + owner_report_format: Some(Format::CaseworkReport), + }, + }, + &mut out, + &mut err, + ); + assert!(err.is_empty()); + (status, String::from_utf8(out).unwrap()) + }; + let (status, output) = run(CASEWORK.as_bytes()); + assert_eq!(status, std::process::ExitCode::SUCCESS); + let report: Value = serde_json::from_str(&output).unwrap(); + assert_eq!(report["assessment"], "owner-report-structure"); + let (status, output) = + run(b"{\n\"synthetic-private-member\": 1, \"synthetic-private-member\": 2}"); + assert_eq!(status, std::process::ExitCode::from(1)); + assert!(!output.contains("synthetic-private-member")); + let report: Value = serde_json::from_str(&output).unwrap(); + assert_eq!(report["diagnostics"][0]["source"]["line"], 2); + assert_eq!( + report["diagnostics"][0]["code"], + "rstack.dev.owner-report-invalid" + ); +} + +#[test] +fn near_limit_invalid_diagnostics_use_the_generic_fallback() { + let mut report: Value = serde_json::from_str(CASEWORK).unwrap(); + let cell = json!("x".repeat(64)); + let cell_bytes = serde_json::to_vec(&cell).unwrap().len() + 1; + let cap = MAXIMUM_DOCUMENT_BYTES; + let overhead = serde_json::to_vec(&report).unwrap().len(); + report["diagnostics"] = json!(vec![cell; (cap - overhead) / cell_bytes]); + let bytes = serde_json::to_vec(&report).unwrap(); + assert!((cap - cell_bytes..=cap).contains(&bytes.len())); + let error = decode(&bytes, Format::CaseworkReport).unwrap_err(); + assert_eq!(error.path, ""); + assert_eq!(error.message, "Owner report violates the selected schema"); +} + +#[test] +fn ordinary_diagnostics_retain_exact_field_locations() { + let mut report: Value = serde_json::from_str(CASEWORK).unwrap(); + report["policyBindings"][0]["digest"] = json!(false); + let error = validate(&report, Format::CaseworkReport).unwrap_err(); + assert_eq!(error.path, "/policyBindings/0/digest"); + assert_eq!( + error.message, + "Owner report violates the selected schema at this location" + ); +} + +#[test] +fn dynamic_map_members_are_redacted_even_when_they_match_schema_names() { + let document: Value = serde_json::from_str(super::CASEWORK).unwrap(); + let schema = compile(json!({ + "$defs": document["$defs"], + "properties": { + "condition": {"$ref": "#/$defs/RoutingCondition"}, + "stage": {"type": "string"} + } + })) + .unwrap(); + for key in ["stage", "synthetic-private-map-key"] { + let value = json!({"condition": {"fields": {(key): false}}}); + let error = schema.validate(&value, "").unwrap_err(); + assert_eq!(error.path, "/condition/fields"); + assert!(!format!("{error:?}").contains(key)); + } +} diff --git a/crates/registry-rstack/src/cli.rs b/crates/registry-rstack/src/cli.rs index da79b8d4f5..31bc49f7a4 100644 --- a/crates/registry-rstack/src/cli.rs +++ b/crates/registry-rstack/src/cli.rs @@ -260,12 +260,20 @@ struct ClientGenerate { #[derive(Subcommand)] enum DevCommand { - /// Validate a development plan without starting services. - #[command(after_help = "Example:\n rstack dev check ./my-registry-project")] + /// Validate a development plan or the structure of a saved owner report without starting services. + #[command( + after_help = "Examples:\n rstack dev check ./my-registry-project\n rstack dev check --owner-report ./report.json --owner-report-format casework-report" + )] Check { /// Project directory containing dev.yaml and, when it declares audiences, service.yaml. - #[arg(value_name = "PROJECT")] - project: PathBuf, + #[arg(value_name = "PROJECT", required_unless_present = "owner_report")] + project: Option, + /// Saved JSON report to check structurally. + #[arg(long, value_name = "FILE", conflicts_with_all = ["project", "deny_warnings"], requires = "owner_report_format")] + owner_report: Option, + /// Exact saved document format. + #[arg(long, requires = "owner_report", conflicts_with_all = ["project", "deny_warnings"], value_parser = ["casework-report"])] + owner_report_format: Option, /// Refuse an unaccepted warning. /// Development posture listings do not count. #[arg(long)] @@ -2079,7 +2087,11 @@ fn dev_help(format: ReportFormat) -> Result<(), CliFailure> { fn admit_dev(action: &DevCommand, format: ReportFormat) -> Result<(), CliFailure> { if !matches!( action, - DevCommand::Check { .. } | DevCommand::Start { .. } | DevCommand::Issuer { .. } + DevCommand::Check { + owner_report: None, + .. + } | DevCommand::Start { .. } + | DevCommand::Issuer { .. } ) { return Ok(()); } @@ -2146,17 +2158,34 @@ fn dispatch_dev(cli: &Cli, action: &DevCommand, format: ReportFormat) -> Result< let (name, mut options, target, database_url, needs) = match action { DevCommand::Check { project, + owner_report, + owner_report_format, deny_warnings, - } => ( - "check", - deny_warnings - .then(|| OsString::from("--deny-warnings")) - .into_iter() - .collect::>(), - project.as_os_str(), - None, - DevNeeds::check(project), - ), + } => { + if let (Some(file), Some(format)) = (owner_report, owner_report_format) { + ( + "check", + vec![option("owner-report-format", format.as_ref())], + file.as_os_str(), + None, + DevNeeds::any_host(), + ) + } else { + let project = project + .as_ref() + .expect("clap requires a project or owner report"); + ( + "check", + deny_warnings + .then(|| OsString::from("--deny-warnings")) + .into_iter() + .collect(), + project.as_os_str(), + None, + DevNeeds::check(project), + ) + } + } DevCommand::Start { project, application_root, @@ -2554,6 +2583,53 @@ fn set_selected_generation_environment( mod tests { use super::*; + #[test] + fn dev_check_owner_report_requires_an_explicit_exclusive_format() { + let parse = |args: &[&str]| { + Cli::try_parse_from( + ["rstack", "dev", "check"] + .into_iter() + .chain(args.iter().copied()), + ) + }; + assert!(parse(&["./project", "--deny-warnings"]).is_ok()); + assert!(parse(&[ + "--owner-report", + "./report.json", + "--owner-report-format", + "casework-report" + ]) + .is_ok()); + for args in [ + &[][..], + &["--owner-report", "./report.json"], + &["--owner-report-format", "casework-report"], + &["./project", "--owner-report-format", "casework-report"], + &[ + "--owner-report", + "./report.json", + "--owner-report-format", + "guess", + ], + &[ + "./project", + "--owner-report", + "./report.json", + "--owner-report-format", + "casework-report", + ], + &[ + "--deny-warnings", + "--owner-report", + "./report.json", + "--owner-report-format", + "casework-report", + ], + ] { + assert!(parse(args).is_err(), "{args:?}"); + } + } + #[test] fn selected_generation_projects_optional_service_binaries() { let generation = tempfile::tempdir().unwrap(); diff --git a/products/platform/CONFIG-CONVENTIONS.md b/products/platform/CONFIG-CONVENTIONS.md index 58049ac7e0..240194e1d5 100644 --- a/products/platform/CONFIG-CONVENTIONS.md +++ b/products/platform/CONFIG-CONVENTIONS.md @@ -42,7 +42,9 @@ In scope: CFG-SCHEMA-6. A product output that a maintained tool reads is a registered contract: it is a read-back format, registered with its schema and a `reader` entry naming that tool's reading function, whatever command prints it. Explain output a - maintained tool reads belongs here, not under `reader: none`. + maintained tool reads belongs in the read-back category. A saved writer + report may register `passiveReport: true` when a maintained offline check + validates it on read-back and its integers only observe completed work. A **build artifact** is a read-back format that its own product's build writes and reads again and that no one edits (the compiled package model in BReg's `package.json`). It is registered with `audience: generated` and @@ -580,12 +582,15 @@ value outside them with `config.out-of-range`, naming the bounds. An implicit a maximum below the unsigned format's own ceiling, as the bounded types emit it, does. -An output format registered with `reader: none` may state its writer's native -integer range. The schema must declare both bounds explicitly from the actual -serialized type, rather than rely on `format` alone. An observed count or -sequence does not configure resource use, so it needs no invented operational -cap. This distinction changes no input limit, output closedness, or other -schema requirement. +An output format registered with `reader: none` or a generated JSON report +registered with `passiveReport: true` may state its writer's native integer +range. Declare `minimum` and `maximum` explicitly from the serialized type. +A passive report's registered reader validates those bounds against the owner +schema. Use the marker only for a saved writer report with an offline file +check and no security or restricting members. Its integers record completed +work. The marker leaves the payload contract, reader limits and all other +checks in force. Files that configure work or convey authority follow the +ordinary reader rules. *Enforced by:* the convention lint (every `integer` property declares `minimum` and `maximum`); the conformance corpus boundary sweep (each integer in each format's example whose registered schema states both bounds, set one diff --git a/products/platform/config-formats.yaml b/products/platform/config-formats.yaml index 1609f84bc2..56ef0beea9 100644 --- a/products/platform/config-formats.yaml +++ b/products/platform/config-formats.yaml @@ -1709,6 +1709,7 @@ formats: files: [] syntax: json audience: generated + passiveReport: true stability: unpromised current: apiVersion: id.registrystack.org/formats/casework/report/v1alpha2 @@ -1725,11 +1726,15 @@ formats: origin: generated generator: cargo run -p registry-caseworkctl --features schema --example report-schemas -- --output products/casework/contracts/cli driftCheck: crates/registry-caseworkctl/src/schema.rs - reader: none + reader: + crate: registry-rstack-dev + file: crates/registry-rstack-dev/src/owner_report.rs + function: check_file + type: untyped emittedBy: file: crates/registry-caseworkctl/src/report.rs symbol: write - check: none + check: rstack dev check --owner-report {file} --owner-report-format casework-report example: products/casework/examples/formats/reports/check-report.json conformance: none securityMembers: [] diff --git a/products/platform/scripts/check-config-conventions.py b/products/platform/scripts/check-config-conventions.py index 19624d66a8..f6e72ae124 100644 --- a/products/platform/scripts/check-config-conventions.py +++ b/products/platform/scripts/check-config-conventions.py @@ -113,7 +113,7 @@ "target", "schema", "reader", "check", "example", "conformance", "securityMembers", "restrictingMembers", ) -OPTIONAL_FORMAT_FIELDS = ("emittedBy", "exceptionClass", "topLevel", "buildArtifact", "notes") +OPTIONAL_FORMAT_FIELDS = ("emittedBy", "exceptionClass", "topLevel", "buildArtifact", "passiveReport", "notes") ENUMS = { "syntax": ("yaml", "json", "jsonl", "text"), "audience": ("authored", "operator", "generated"), @@ -1177,6 +1177,7 @@ def __init__(self, root: Path, report: Report) -> None: self.canonical: dict = {} self.convention: Convention | None = None self.formats: list[dict] = [] + self.passive_reports: set[str] = set() self.by_id: dict[str, dict] = {} self.quantities: list[tuple[str, str, str, str, str]] = [] @@ -1570,11 +1571,31 @@ def check_registry(self, registry: dict) -> None: self.check_target(fid, entry, kinds) self.check_schema_entry(fid, entry) self.check_reader(fid, entry) + writer = None if "emittedBy" in entry: - self.check_symbol(fid, "emittedBy", entry["emittedBy"]) + writer = self.check_symbol(fid, "emittedBy", entry["emittedBy"]) document = self.check_example(fid, entry) entry["_example"] = document schema = self.format_schema(entry) + if "passiveReport" in entry: + if ( + entry["passiveReport"] is True + and entry["audience"] == "generated" + and entry["syntax"] == "json" + and "buildArtifact" not in entry + and writer is not None + and isinstance(schema, dict) + and isinstance(entry["reader"], dict) + and isinstance(entry["check"], str) + and "{file}" in entry["check"] + and entry["securityMembers"] == entry["restrictingMembers"] == [] + ): + self.passive_reports.add(fid) + else: + self.error( + f"{fid}: passiveReport requires true on a generated JSON writer report with a schema, " + "a reader and file check, and no build, security, or restricting members" + ) self.check_conformance(fid, entry, document, schema) self.check_members(fid, entry, schema) for kind, ids in kinds.items(): @@ -1914,14 +1935,15 @@ def find(rule: str, visit: Visit, message: str, fix: str, suffix: tuple[str, ... # do not bound configured work. Reports may state the writer's # native range, but still need both bounds explicitly in schema. output = entry is not None and entry.get("reader") == "none" - implicit = not output and str(node.get("format", "")).startswith("uint") and node.get("minimum") == 0 \ + passive = fid in self.passive_reports + implicit = not (output or passive) and str(node.get("format", "")).startswith("uint") and node.get("minimum") == 0 \ and node.get("maximum", UNSIGNED_CEILING.get(node.get("format"))) == UNSIGNED_CEILING.get(node.get("format")) - has_minimum = ("minimum" in node and not implicit) or "exclusiveMinimum" in node - has_maximum = "maximum" in node or "exclusiveMaximum" in node + has_minimum = ("minimum" in node and not implicit) or (not passive and "exclusiveMinimum" in node) + has_maximum = "maximum" in node or (not passive and "exclusiveMaximum" in node) if not (has_minimum and has_maximum): missing = [bound for bound, present in (("minimum", has_minimum), ("maximum", has_maximum)) if not present] detail = " (minimum 0 is the unsigned type's implicit bound)" if implicit else "" - fix = "State both bounds from the writer's serialized integer type" if output else \ + fix = "State both bounds from the writer's serialized integer type" if output or passive else \ "Read it with BoundedU32/BoundedU64 and state both bounds" find("CFG-QTY-4", visit, f"an integer without a stated {' and '.join(missing)}{detail}", fix) closing = None if visit.conditional else self.closing_problem(document, visit) diff --git a/products/platform/scripts/test_check_config_conventions.py b/products/platform/scripts/test_check_config_conventions.py index 9ad7790787..c99ca00b03 100644 --- a/products/platform/scripts/test_check_config_conventions.py +++ b/products/platform/scripts/test_check_config_conventions.py @@ -1198,6 +1198,39 @@ def test_cfg_qty_4_read_back_format_still_requires_semantic_bounds(self) -> None } self.assertFinding(self.repo.run(), "CFG-QTY-4", P, at(PROJECT_SCHEMA, "/$defs/Queue/properties/retryCount")) + def passive_report(self) -> dict: + entry = self.repo.fmt(R) + entry.update( + passiveReport=True, + reader={"crate": "registry-casework-core", "file": CONFIG_RS, "function": "load", "type": "untyped"}, + check="rstack dev check --owner-report {file} --owner-report-format casework-report", + ) + self.repo.report["properties"]["filesChecked"] = { + "type": "integer", "format": "uint64", "minimum": 0, "maximum": 2**64 - 1, + } + return entry + + def test_cfg_qty_4_accepts_explicit_native_passive_report_bounds(self) -> None: + self.passive_report() + report = self.repo.run() + self.assertEqual(report.errors, []) + self.assertNoFinding(report, "CFG-QTY-4") + + def test_cfg_qty_4_passive_report_flag_cannot_exempt_authored_config(self) -> None: + self.passive_report()["audience"] = "authored" + report = self.repo.run() + self.assertTrue(any("passiveReport requires" in error for error in report.errors)) + self.assertFinding(report, "CFG-QTY-4", R, at(REPORT_SCHEMA, "/properties/filesChecked")) + + def test_cfg_qty_4_passive_report_still_requires_both_bounds(self) -> None: + self.passive_report() + fields = self.repo.report["properties"]["filesChecked"] + for bound in ("minimum", "maximum"): + with self.subTest(bound=bound): + value = fields.pop(bound) + self.assertFinding(self.repo.run(), "CFG-QTY-4", R, at(REPORT_SCHEMA, "/properties/filesChecked")) + fields[bound] = value + def test_cfg_qty_4_accepts_a_bounded_type_whose_stated_minimum_is_zero(self) -> None: self.queue()["leewayMilliseconds"] = {"type": "integer", "format": "uint64", "minimum": 0, "maximum": 300000} self.assertNoFinding(self.repo.run(), "CFG-QTY-4") From c4284081552c6a91c39de09d4926f5949981a0df Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 17:35:35 +0000 Subject: [PATCH 033/183] docs(dev): describe private PostgreSQL startup and cleanup Signed-off-by: Jeremi Joslin --- .../configure/run-a-project-with-rstack-dev.mdx | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/docs/site/src/content/docs/configure/run-a-project-with-rstack-dev.mdx b/docs/site/src/content/docs/configure/run-a-project-with-rstack-dev.mdx index c9334df37f..facc3555e7 100644 --- a/docs/site/src/content/docs/configure/run-a-project-with-rstack-dev.mdx +++ b/docs/site/src/content/docs/configure/run-a-project-with-rstack-dev.mdx @@ -547,6 +547,11 @@ The runner checks that every resolved address is eligible for private network pl Generated product runtime configurations use `database.transport: private-network-plaintext` and the same address. Leave `RSTACK_DEV_DATABASE_CA` unset for either plaintext transport. +With Compose, give PostgreSQL a health check and wait for it to pass before running `rstack dev start`. +For example, run `docker compose up -d --wait postgres` when the service is named `postgres`. +Keep PostgreSQL reachable until `rstack dev stop` finishes dropping the run's databases and roles. +Then bring down the Compose project. + The administrator role named in the URL needs `LOGIN CREATEROLE CREATEDB`. Superuser is not needed for a non-spatial run. The runner sets `createrole_self_grant` on its own sessions, so you do not configure it. @@ -560,10 +565,11 @@ The URL must be a `postgres://` or `postgresql://` URL with one TCP host, a user Percent-encode special characters in the password. The URL accepts these query parameters and refuses all others: -- `sslmode`: `require`, `verify-ca`, or `verify-full` for verified TLS (the default when omitted, verifying the certificate and host name whichever you choose), or `disable` for plaintext on a loopback host only. - Setting `RSTACK_DEV_DATABASE_CA` with `sslmode=disable` is refused. -- `transport=private-network-plaintext` explicitly selects a private development network. - Leave `sslmode` unset for this transport and pass the same URL for recovery. +- `sslmode` accepts `require`, `verify-ca`, and `verify-full`. Each verifies the certificate and host name, as does the default TLS mode. + `sslmode=disable` on its own selects loopback plaintext. +- `transport=private-network-plaintext` explicitly selects plaintext on a private development network. + Use this selector alone or with `sslmode=disable`. A TLS `sslmode` conflicts with it. + Leave `RSTACK_DEV_DATABASE_CA` unset for plaintext and pass the same URL for recovery. - `connect_timeout` and `application_name`. - `sslrootcert` is refused. Set `RSTACK_DEV_DATABASE_CA` instead. From 851e0e7f1c9910ba0434c876c93d486c75b6f5a7 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 17:36:32 +0000 Subject: [PATCH 034/183] fix(journeys): tighten BReg fixture proof and promotion input Signed-off-by: Jeremi Joslin (cherry picked from commit eeb305259154c2d33241a059af1825d43954aa07) --- products/platform/journeys/README.md | 14 +++ .../platform/journeys/expected-failures.yaml | 4 +- products/platform/journeys/own-provider.sh | 106 +++++++++++++----- products/platform/journeys/promote.sh | 37 ++++-- .../platform/journeys/test_journey_tables.py | 32 +++++- 5 files changed, 148 insertions(+), 45 deletions(-) diff --git a/products/platform/journeys/README.md b/products/platform/journeys/README.md index 83d416787a..e576405035 100644 --- a/products/platform/journeys/README.md +++ b/products/platform/journeys/README.md @@ -173,6 +173,20 @@ codes matched by the initial production startup and check. It is `null` until the comparison was measured, and `0` when the comparison found no refusals. The existing `total.refusalsMet` counts refusals across the cell. +The stock Keycloak BReg editor requests an optional client scope for the +fixture's static claims. Keycloak keeps the issued `scope` claim unchanged. +The no-mapper control obtains a fresh token for that same service account +without the optional scope and checks the refusal against the response's +trace ID. The foreign caller also gets a fresh token for its exact-record +assertion. + +The BReg setup records `fixtureOnlyProducts: ["breg"]` in +`own-provider.json`. Promotion reports `journey.promote.no-input` for this +fixture. A passing BReg input directory that predates the marker is refused as +`legacy-unmarked`. A present marker with any other value is refused as +`invalid-fixture-marker`. These refusals happen before production startup. +An explicitly kept input is still taken over and cleaned up. + In `rstack-dev`, the run log and `cells.tsv` mark the hook step `unexercised` when the journey has no hook delivery to check. The cell still runs its later steps, including retention and cleanup. diff --git a/products/platform/journeys/expected-failures.yaml b/products/platform/journeys/expected-failures.yaml index 628a4210f6..a742620b08 100644 --- a/products/platform/journeys/expected-failures.yaml +++ b/products/platform/journeys/expected-failures.yaml @@ -66,8 +66,8 @@ expectedFailures: code: journey.promote.no-input removedBy: rstack-dev-products basis: observed - observedOn: "v0.49.0 binaries, retained database run 43837b0a62714a74a2564085615cf432" - reason: "The Keycloak proof uses a disposable static-claim fixture. Its input is scoped to own-provider verification. A separate retained development database was refused by the production runtime with platform.activation.posture-mismatch." + observedOn: "v0.49.0 binaries, strict promote run 20261201173525-487a from own-provider run 20261201173442-23a5" + reason: "The stock Keycloak input is marked as a fixture for own-provider verification. Promotion refuses it at input before attempting to start production." - journey: promote product: evidence step: input diff --git a/products/platform/journeys/own-provider.sh b/products/platform/journeys/own-provider.sh index e9126eba97..e2c06721cc 100755 --- a/products/platform/journeys/own-provider.sh +++ b/products/platform/journeys/own-provider.sh @@ -30,7 +30,7 @@ # audience and its scope. # BReg's disposable fixture binds exact scopes to two callers and sets its # authored principal, purpose and jurisdiction with built-in static mappers. -# A token issued before the mappers are installed must still be refused. +# An editor token issued without the optional mapper scope must be refused. # # What the harness does that the reader does not type, and so is not counted: # - the secret folder of every product is the run's secrets/ folder, so each @@ -438,8 +438,9 @@ DOCUMENTS_SUBJECT='' COORDINATOR_SUBJECT='' BREG_HOOK_PORT='' BREG_SCOPE_UNLINKS=0 -# shellcheck disable=SC2034 # Read by name through the token and HTTP helpers. -BREG_CONTROL_TOKEN='' +BREG_KEYCLOAK_CLAIM_SCOPE='breg-fixture-claims' +BREG_EDITOR_SUBJECT='' +BREG_FOREIGN_SUBJECT='' ADAPTER_SOURCE_PORT='' REACHED_AUTH_PRODUCTS=() THUNDERID_SESSION_IDS=() @@ -553,6 +554,24 @@ breg_keycloak_add_mappers() { done <<<"$mappers" } +# Keep the editor's static mappers on its own optional client scope. Keycloak +# can then issue a fresh unmapped token to the same client and service account. +breg_keycloak_editor_scope() { + local uuid scope_id body + body=$(breg_keycloak_mappers synthetic-directory-editor zone-a | jq -c --arg name "$BREG_KEYCLOAK_CLAIM_SCOPE" ' + {name: $name, protocol: "openid-connect", attributes: {"include.in.token.scope": "false"}, protocolMappers: .}') || + journey_harness_failure "cannot assemble the BReg editor's optional claim scope" + keycloak_admin POST /client-scopes "$body" + [[ "$KC_STATUS" == 201 ]] || journey_harness_failure "Keycloak refused the BReg editor's claim scope (HTTP $KC_STATUS)" + keycloak_admin GET /client-scopes + [[ "$KC_STATUS" == 200 ]] || journey_harness_failure "Keycloak cannot list its client scopes" + scope_id=$(jq -er --arg name "$BREG_KEYCLOAK_CLAIM_SCOPE" '.[] | select(.name == $name) | .id' <<<"$KC_BODY") || + journey_harness_failure "Keycloak did not list the BReg editor's claim scope" + keycloak_client_uuid "$CLIENT" uuid + keycloak_admin PUT "/clients/$uuid/optional-client-scopes/$scope_id" + [[ "$KC_STATUS" == 204 ]] || journey_harness_failure "Keycloak refused to bind the editor's optional scope (HTTP $KC_STATUS)" +} + # keycloak_service_account_subject CLIENT_ID VAR: the `sub` of the client's # service account, which a Coordinator policy names. keycloak_service_account_subject() { @@ -1345,7 +1364,7 @@ step_issuer() { edit "$RUNTIME_FILE" " allowedClients: [directory-client]" \ " allowedClients: [directory-client, foreign-directory-client]" if [[ "$ISSUER_KIND" == keycloak ]]; then - journey_count identity-provider-changes "$((2 + BREG_SCOPE_UNLINKS))" + journey_count identity-provider-changes "$((10 + BREG_SCOPE_UNLINKS))" fi reader_command issuer -- "$TOOL_BIN" --format json check "$PROJECT" --runtime-config "$RUNTIME_FILE" ;; @@ -1465,11 +1484,13 @@ write_product_secrets() { # Get a client-credentials token into the caller's variable. Keep the token # response and the client secret out of the step output. breg_keycloak_token() { - local client=$1 ref=$2 variable=$3 secret_file response issued + local client=$1 ref=$2 variable=$3 claims_scope=${4:-} secret_file response issued + local -a options=() + [[ -z "$claims_scope" ]] || options=(--data-urlencode "scope=$claims_scope") journey_secret_path "$ref" secret_file response=$(curl --silent --show-error --fail --max-time 30 \ --data grant_type=client_credentials --data "client_id=$client" \ - --data-urlencode "client_secret@$secret_file" "$KC_ISSUER/protocol/openid-connect/token") || + --data-urlencode "client_secret@$secret_file" "${options[@]}" "$KC_ISSUER/protocol/openid-connect/token") || journey_harness_failure "Keycloak refused the BReg client credentials of $client" issued=$(jq -er '.access_token | strings | select(length > 0)' <<<"$response") || journey_harness_failure "Keycloak returned no BReg access token for $client" @@ -1479,7 +1500,7 @@ breg_keycloak_token() { } # Check issuer-provided identity and the exact scope before BReg sees a token. -# An empty principal represents the control issued before mapper installation. +# An empty principal represents an editor token issued without the mapper scope. breg_keycloak_token_matches() { local variable=$1 client=$2 subject=$3 principal=$4 jurisdiction=$5 printf '%s' "${!variable}" | perl -MMIME::Base64 -e ' @@ -1505,26 +1526,18 @@ breg_keycloak_token_matches() { # Acquire exact credentials for every step in the unmodified BReg fixture suite. breg_schema_test_credentials() { - local credentials_file=$1 primary_subject foreign_subject + local credentials_file=$1 # shellcheck disable=SC2034 # Read by name through token fetch and secret helpers. local breg_schema_token='' breg_foreign_schema_token='' if [[ "$ISSUER_KIND" == thunderid ]]; then thunderid_fetch_token "$TID_ROOT" "$TID_REGISTRATION" "$CLIENT" breg_schema_token "$AUDIENCE" thunderid_fetch_token "$TID_ROOT" "$TID_REGISTRATION" foreign-directory-client breg_foreign_schema_token "$AUDIENCE" else - keycloak_service_account_subject "$CLIENT" primary_subject - keycloak_service_account_subject foreign-directory-client foreign_subject - breg_keycloak_token "$CLIENT" client-breg BREG_CONTROL_TOKEN - breg_keycloak_token_matches BREG_CONTROL_TOKEN "$CLIENT" "$primary_subject" '' '' || - journey_harness_failure "Keycloak no-mapper control did not issue the exact stock BReg scope and caller" - breg_keycloak_add_mappers "$CLIENT" synthetic-directory-editor zone-a - breg_keycloak_add_mappers foreign-directory-client synthetic-foreign-editor zone-b - journey_count identity-provider-changes 6 - breg_keycloak_token "$CLIENT" client-breg breg_schema_token + breg_keycloak_token "$CLIENT" client-breg breg_schema_token "$BREG_KEYCLOAK_CLAIM_SCOPE" breg_keycloak_token foreign-directory-client client-breg-foreign breg_foreign_schema_token - breg_keycloak_token_matches breg_schema_token "$CLIENT" "$primary_subject" synthetic-directory-editor zone-a || + breg_keycloak_token_matches breg_schema_token "$CLIENT" "$BREG_EDITOR_SUBJECT" synthetic-directory-editor zone-a || journey_harness_failure "Keycloak did not issue the exact BReg editor claims and scope" - breg_keycloak_token_matches breg_foreign_schema_token foreign-directory-client "$foreign_subject" synthetic-foreign-editor zone-b || + breg_keycloak_token_matches breg_foreign_schema_token foreign-directory-client "$BREG_FOREIGN_SUBJECT" synthetic-foreign-editor zone-b || journey_harness_failure "Keycloak did not issue the exact BReg foreign editor claims and scope" fi write_own_secret breg-schema-token breg_schema_token @@ -1805,10 +1818,15 @@ step_token() { journey_pass token return 0 fi - local token_url=$KC_ISSUER/protocol/openid-connect/token status=0 + local token_url=$KC_ISSUER/protocol/openid-connect/token status=0 typed_scope='' + local -a scope_option=() + if [[ "$CELL" == breg ]]; then + scope_option=(--form "scope=$BREG_KEYCLOAK_CLAIM_SCOPE") + typed_scope=" -d scope=$BREG_KEYCLOAK_CLAIM_SCOPE" + fi journey_http token --concepts client,grant,scopes \ - --typed "curl -X POST $token_url -d grant_type=client_credentials -d client_id=$CLIENT -d client_secret=\$SECRET" \ - --form grant_type=client_credentials --form "client_id=$CLIENT" --form-secret "client_secret=client-$CELL" \ + --typed "curl -X POST $token_url -d grant_type=client_credentials -d client_id=$CLIENT -d client_secret=\$SECRET$typed_scope" \ + --form grant_type=client_credentials --form "client_id=$CLIENT" --form-secret "client_secret=client-$CELL" "${scope_option[@]}" \ --capture-secret .access_token ACCESS_TOKEN POST "$token_url" || status=$? if [[ $status -ne 0 ]]; then journey_harness_failure "Keycloak refused the client credentials of $CLIENT (HTTP $JOURNEY_HTTP_STATUS); the realm is the journey's own setup, see $JOURNEY_STEP_STDOUT" @@ -1993,6 +2011,30 @@ check_thunderid_negative_auth() { journey_harness_failure "$CELL did not refuse a wrong-audience ThunderID token with HTTP 401 (got HTTP $JOURNEY_HTTP_STATUS)" } +# Match the claims check to the trace from the control's HTTP response. +breg_claims_refused_at_trace() { + local trace=$1 + shift + jq -Rne --arg trace "$trace" 'any(inputs | fromjson?; + .fields.trace_id == $trace and .fields.decision == "refused" and .fields.failed_check == "token-claims")' "$@" >/dev/null +} + +breg_no_mapper_control() { + # shellcheck disable=SC2034 # Read by name through the token and HTTP helpers. + local control_token='' trace + breg_keycloak_token "$CLIENT" client-breg control_token + breg_keycloak_token_matches control_token "$CLIENT" "$BREG_EDITOR_SUBJECT" '' '' || + journey_harness_failure "Keycloak did not issue the exact stock BReg scope and caller for the no-mapper control" + journey_http call --expect-status 401 --bearer control_token GET "http://127.0.0.1:$PORT$CALL_PATH" && + [[ "$JOURNEY_HTTP_PROBLEM_CODE" == authentication.refused ]] || + journey_harness_failure "BReg's no-mapper control returned HTTP $JOURNEY_HTTP_STATUS ($JOURNEY_HTTP_PROBLEM_CODE)" + trace=$(jq -er '.traceId | strings | select(test("^[0-9a-f]{32}$"))' "$JOURNEY_STEP_STDOUT") || + journey_harness_failure "BReg's no-mapper response did not include a valid trace ID" + refresh_server_log + breg_claims_refused_at_trace "$trace" "$SERVER_LOG_OUT" "$SERVER_LOG_ERR" || + journey_harness_failure "BReg's no-mapper trace $trace has no refusal at the authored claims check" +} + # call: the first authenticated request. A refusal is named by the HTTP status # and the stage the product logged, by the problem code it answered when its # log names no stage. Optional assists may retry the request. @@ -2021,12 +2063,7 @@ step_call() { fi check_wrong_kind if [[ "$CELL" == breg && "$ISSUER_KIND" == keycloak ]]; then - journey_http call --expect-status 401 --bearer BREG_CONTROL_TOKEN GET "http://127.0.0.1:$PORT$CALL_PATH" && - [[ "$JOURNEY_HTTP_PROBLEM_CODE" == authentication.refused ]] || - journey_harness_failure "BReg's no-mapper control returned HTTP $JOURNEY_HTTP_STATUS ($JOURNEY_HTTP_PROBLEM_CODE)" - refresh_server_log - grep -Eq 'failed_check"?[:=][[:space:]]*"token-claims"' "$SERVER_LOG_OUT" "$SERVER_LOG_ERR" || - journey_harness_failure "BReg did not refuse the no-mapper control at the authored claims check" + breg_no_mapper_control fi journey_pass call [[ "$CALL_METHOD" != GET ]] || journey_reached t1 @@ -2266,14 +2303,17 @@ breg_hook() { journey_step hook -- assert_signed_hook_acceptance "$receiver_out" /events contact-created || journey_harness_failure "the BReg signed hook acceptance record did not confirm HMAC receiver authority without inbound credential headers" if [[ "$ISSUER_KIND" == keycloak ]]; then - # shellcheck disable=SC2034 # Read by name through the secret and HTTP helpers. - local foreign_token='' - read_secret breg-foreign-schema-token foreign_token journey_http hook --expect-status 200 --bearer ACCESS_TOKEN GET "$origin/v1/records/contacts/$record_id" || journey_harness_failure "the BReg editor could not read the contact named by the signed hook" # shellcheck disable=SC2016 # jq binds its own variables. journey_step hook -- jq -e --arg record "$record_id" '.data.recordId == $record' "$JOURNEY_STEP_STDOUT" || journey_harness_failure "the BReg editor did not receive the exact contact" + local foreign_token='' + breg_keycloak_token foreign-directory-client client-breg-foreign foreign_token + breg_keycloak_token_matches foreign_token foreign-directory-client "$BREG_FOREIGN_SUBJECT" synthetic-foreign-editor zone-b || + journey_harness_failure "Keycloak did not issue the exact BReg foreign caller for the hook assertion" + [[ "$foreign_token" != "$(<"$SECRETS/breg-foreign-schema-token")" ]] || + journey_harness_failure "Keycloak reused the BReg schema test token for the hook assertion" journey_http hook --expect-status 404 --bearer foreign_token GET "$origin/v1/records/contacts/$record_id" && [[ "$JOURNEY_HTTP_PROBLEM_CODE" == resource.not-found ]] || journey_harness_failure "the BReg foreign caller was not concealed from the exact contact" @@ -2967,6 +3007,10 @@ if [[ ${#PRIMARY[@]} -gt 0 ]]; then keycloak_default_scope foreign-directory-client "$SCOPE" breg_keycloak_exact_scope "$CLIENT" breg_keycloak_exact_scope foreign-directory-client + keycloak_service_account_subject "$CLIENT" BREG_EDITOR_SUBJECT + keycloak_service_account_subject foreign-directory-client BREG_FOREIGN_SUBJECT + breg_keycloak_editor_scope + breg_keycloak_add_mappers foreign-directory-client synthetic-foreign-editor zone-b ;; casework) keycloak_default_scope "$CLIENT" casework:staff diff --git a/products/platform/journeys/promote.sh b/products/platform/journeys/promote.sh index 2079de2fa5..87aa6d1f17 100755 --- a/products/platform/journeys/promote.sh +++ b/products/platform/journeys/promote.sh @@ -152,16 +152,25 @@ field() { # promote starts from the files the assists left. input_outcome() { local value - # Fixture-only inputs carry authorization setup specific to the rehearsal. - if [[ -f "$FROM/own-provider.json" ]] && jq -e --arg product "$1" \ - '(.fixtureOnlyProducts // []) | index($product) != null' "$FROM/own-provider.json" >/dev/null; then - printf -v "$2" '%s' fixture-only - return - fi value=$(jq -r --arg product "$1" '[.cells[] | select(.product == $product)] | if length != 1 then "missing" elif .[0].outcome == "pass" or (.[0].outcome == "unreached" and .[0].toT1 != null) then "finished" else .[0].outcome end' "$FROM/summary.json") || journey_harness_failure "cannot read the cell of $1 in $FROM/summary.json" + if [[ "$value" == finished && "$1" == breg ]]; then + # A passing BReg summary alone cannot authorize reuse of the fixture. + if [[ ! -e "$FROM/own-provider.json" ]]; then + value=legacy-unmarked + else + value=$(jq -er ' + if type != "object" then "invalid-fixture-marker" + elif has("fixtureOnlyProducts") | not then "legacy-unmarked" + elif .fixtureOnlyProducts == ["breg"] then "fixture-only" + else "invalid-fixture-marker" end' "$FROM/own-provider.json" 2>/dev/null) || value=invalid-fixture-marker + fi + elif [[ "$value" == finished && -f "$FROM/own-provider.json" ]] && jq -e --arg product "$1" ' + .fixtureOnlyProducts | type == "array" and index($product) != null' "$FROM/own-provider.json" >/dev/null; then + value=fixture-only + fi printf -v "$2" '%s' "$value" } @@ -499,15 +508,23 @@ walk_product() { # input input_outcome "$product" outcome if [[ "$outcome" != finished ]]; then - if [[ "$outcome" == fixture-only ]]; then + case "$outcome" in + fixture-only | legacy-unmarked | invalid-fixture-marker) # An explicitly kept fixture still needs cleanup when no cell can use it. if [[ -f "$FROM/kept" ]]; then take_over_input fi - printf 'promote: the %s input for %s is scoped to its own-provider fixture\n' "$INPUT_JOURNEY" "$product" >&2 - else + if [[ "$outcome" == fixture-only ]]; then + printf 'promote: %s %s input refused (fixture-only). This fixture is scoped to own-provider verification\n' "$INPUT_JOURNEY" "$product" >&2 + else + printf 'promote: %s %s input refused (%s). Use the current own-provider runner to record the BReg fixture marker\n' \ + "$INPUT_JOURNEY" "$product" "$outcome" >&2 + fi + ;; + *) printf 'promote: the %s journey did not finish for %s (cell outcome %s); nothing to promote\n' "$INPUT_JOURNEY" "$product" "$outcome" >&2 - fi + ;; + esac journey_fail input journey.promote.no-input journey_cell_end return 0 diff --git a/products/platform/journeys/test_journey_tables.py b/products/platform/journeys/test_journey_tables.py index 9b70fa6297..cb107b64bd 100644 --- a/products/platform/journeys/test_journey_tables.py +++ b/products/platform/journeys/test_journey_tables.py @@ -352,6 +352,24 @@ def test_realm_import_has_no_protocol_mappers(self): class KeycloakRecipe(unittest.TestCase): + def test_breg_refusal_requires_the_control_trace(self): + script = (TABLES / "own-provider.sh").read_text(encoding="utf-8") + function = re.search(r"^breg_claims_refused_at_trace\(\) \{\n.*?^\}\n", script, re.S | re.M) + self.assertIsNotNone(function) + trace = "01a2329737512fef4af31980675d47a2" + other = "01a23294626136512634d9f00f1cf6ee" + with tempfile.TemporaryDirectory() as directory: + log = Path(directory) / "server.log" + for second_check, accepted in (("token-time", False), ("token-claims", True)): + records = [{"fields": {"trace_id": id_, "decision": "refused", "failed_check": check}} + for id_, check in ((other, "token-claims"), (trace, second_check))] + log.write_text("non-JSON output\n" + "\n".join(map(json.dumps, records)) + "\n", encoding="utf-8") + result = subprocess.run( + ["bash", "-euo", "pipefail", "-c", function.group(0) + '\nbreg_claims_refused_at_trace "$@"', + "breg-control-trace", trace, str(log)], capture_output=True, text=True, timeout=5, + ) + self.assertEqual(result.returncode == 0, accepted, result.stderr) + def test_breg_mappers_are_static_and_only_set_authored_claims(self): script = (TABLES / "own-provider.sh").read_text(encoding="utf-8") match = re.search(r"^breg_keycloak_mappers\(\) \{\n.*?^\}\n", script, re.S | re.M) @@ -528,8 +546,18 @@ def test_scoped_fixture_input_cannot_be_promoted(self): {"product": product, "outcome": "pass"} for product in ("breg", "adapter") ]}), encoding="utf-8") provider = path / "own-provider.json" - for fixture_only, expected_breg in ((["breg"], "fixture-only"), ([], "finished")): - provider.write_text(json.dumps({"fixtureOnlyProducts": fixture_only}), encoding="utf-8") + cases = ( + (None, "legacy-unmarked"), + ({}, "legacy-unmarked"), + ({"fixtureOnlyProducts": ["breg"]}, "fixture-only"), + ({"fixtureOnlyProducts": []}, "invalid-fixture-marker"), + ({"fixtureOnlyProducts": "breg"}, "invalid-fixture-marker"), + ({"fixtureOnlyProducts": ["breg", 1]}, "invalid-fixture-marker"), + ({"fixtureOnlyProducts": None}, "invalid-fixture-marker"), + ) + for metadata, expected_breg in cases: + if metadata is not None: + provider.write_text(json.dumps(metadata), encoding="utf-8") result = subprocess.check_output( ["bash", "-euo", "pipefail", "-c", function.group(0) + '\nFROM=$1\n' 'input_outcome breg breg; input_outcome adapter adapter; printf "%s\\n" "$breg" "$adapter"', From 8d0ece8aad4beb30348b33c60a2122a08a39eec9 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 17:40:30 +0000 Subject: [PATCH 035/183] fix(release): keep Session numbered assembly and nightlies aligned Signed-off-by: Jeremi Joslin --- release/VERIFY.md | 6 ++- .../build-additional-platform-binaries.sh | 6 ++- release/scripts/build-nightly-linux-arm64.sh | 2 +- release/scripts/build-release-binaries.sh | 14 ++++++ .../scripts/build-release-native-platform.sh | 6 ++- .../scripts/merge-release-binary-shards.py | 2 + .../merge-release-native-platform-shards.py | 2 +- release/scripts/nightly_release.py | 2 +- release/scripts/registry-release | 2 + release/scripts/release_candidate.py | 4 +- release/scripts/release_roster.py | 14 ++++-- .../test_merge_release_binary_shards.py | 12 +++++ release/scripts/test_nightly_release.py | 14 ++++++ release/scripts/test_registry_release.py | 9 ++++ .../scripts/test_release_native_platform.py | 47 ++++++++++++++++--- release/scripts/test_release_roster.py | 9 ++++ 16 files changed, 130 insertions(+), 21 deletions(-) diff --git a/release/VERIFY.md b/release/VERIFY.md index 305ef1785a..afce0e149b 100644 --- a/release/VERIFY.md +++ b/release/VERIFY.md @@ -284,8 +284,10 @@ Registry Adapter binaries join in `v0.46.0`, as set by `ADAPTER_IMAGE_FIRST_RELEASE` is unset. The Registry Document Store is held out of every release while `DOCUMENTS_FIRST_RELEASE` is `None`, and no release roster names it. -The session service is held out while `SESSION_FIRST_RELEASE` is `None`. -No release script builds, stages or publishes `registry-session` yet. +`SESSION_FIRST_RELEASE` controls the `registry-session` binary for numbered +Linux amd64, Linux arm64 and macOS arm64 payloads. It remains unset pending +native release qualification. Session has no image or installer in this +roster, and the frozen nightly profiles keep their existing inventory. `BREG_SERVICES_FIRST_RELEASE`, `MESSAGING_FIRST_RELEASE`, `RENDER_FIRST_RELEASE`, `EVIDENCE_OID4VCI_IMAGE_FIRST_RELEASE`, and the three Coordinator release constants in `release/scripts/release_roster.py` diff --git a/release/scripts/build-additional-platform-binaries.sh b/release/scripts/build-additional-platform-binaries.sh index b369c3007e..bdc507225f 100644 --- a/release/scripts/build-additional-platform-binaries.sh +++ b/release/scripts/build-additional-platform-binaries.sh @@ -18,7 +18,11 @@ if [[ "$#" == 6 ]]; then exclude_discovery=1 fi repo_root="$(git rev-parse --show-toplevel)" -builds="$(python3 "${repo_root}/release/scripts/release_roster.py" additional-platform-builds "${version}")" +roster_flags=() +if [[ "${tag}" == "v${version}-nightly."* ]]; then + roster_flags+=(--nightly) +fi +builds="$(python3 "${repo_root}/release/scripts/release_roster.py" additional-platform-builds "${version}" "${roster_flags[@]}")" cargo_bin="${CARGO:-cargo}" if [[ -z "${builds}" ]]; then exit 0 diff --git a/release/scripts/build-nightly-linux-arm64.sh b/release/scripts/build-nightly-linux-arm64.sh index d8d24c50f9..d9638ecb2f 100644 --- a/release/scripts/build-nightly-linux-arm64.sh +++ b/release/scripts/build-nightly-linux-arm64.sh @@ -65,7 +65,7 @@ from pathlib import Path sys.path.insert(0, str(Path('release/scripts').resolve())) from release_candidate import _release_payload_inventory version, tag, target = sys.argv[1:] -for asset, kind in _release_payload_inventory(version).items(): +for asset, kind in _release_payload_inventory(version, nightly=True).items(): if kind != 'binary' or not asset.endswith('-linux-arm64'): continue binary = asset.split(f'-v{version}-', 1)[0] diff --git a/release/scripts/build-release-binaries.sh b/release/scripts/build-release-binaries.sh index 38c0a931ed..778eed9208 100755 --- a/release/scripts/build-release-binaries.sh +++ b/release/scripts/build-release-binaries.sh @@ -165,6 +165,10 @@ include_coordinator_image=0 if [[ "$(python3 "${script_dir}/release_roster.py" coordinator-in-release "${version}")" == true ]]; then include_coordinator_image=1 fi +include_session=0 +if [[ -z "${nightly_tag}" && "$(python3 "${script_dir}/release_roster.py" session-in-release "${version}")" == true ]]; then + include_session=1 +fi # Adapter binaries have an independent boundary from image publication. include_adapter=0 adapter_in_release="$(python3 "${script_dir}/release_roster.py" \ @@ -358,6 +362,13 @@ build_payload() { fi fi + if [[ "${include_session}" -eq 1 ]]; then + cargo build --release --locked -p registry-session --bin registry-session + cp target/release/registry-session "dist/bin/registry-session-${RELEASE_TAG}-linux-amd64" + check_version "dist/bin/registry-session-${RELEASE_TAG}-linux-amd64" \ + "registry-session ${RELEASE_TAG#v}" + fi + # One invocation per binary keeps each product's feature boundary. if [[ "${include_adapter}" -eq 1 ]]; then cargo build --release --locked \ @@ -729,6 +740,9 @@ if [[ "${group}" == all || "${group}" == core ]]; then image_bin_binaries+=(coordinator coordinatorctl) fi fi + if [[ "${include_session}" -eq 1 ]]; then + bin_assets+=("registry-session-${tag}-linux-amd64") + fi if [[ "${include_adapter}" -eq 1 ]]; then bin_assets+=( "adapter-${tag}-linux-amd64" diff --git a/release/scripts/build-release-native-platform.sh b/release/scripts/build-release-native-platform.sh index 6d029cb95f..fac430bf27 100755 --- a/release/scripts/build-release-native-platform.sh +++ b/release/scripts/build-release-native-platform.sh @@ -343,7 +343,11 @@ build_scheduling() { check_version "schedulingctl ${display_version}" } -additional_platform_builds="$(python3 "${repo_root}/release/scripts/release_roster.py" additional-platform-builds "${version}")" +roster_flags=() +if [[ -n "${nightly_tag}" ]]; then + roster_flags+=(--nightly) +fi +additional_platform_builds="$(python3 "${repo_root}/release/scripts/release_roster.py" additional-platform-builds "${version}" "${roster_flags[@]}")" if [[ "${exclude_discovery}" -eq 1 ]]; then filtered_platform_builds="" while read -r package binary; do diff --git a/release/scripts/merge-release-binary-shards.py b/release/scripts/merge-release-binary-shards.py index f0bd56741d..5607bf7686 100755 --- a/release/scripts/merge-release-binary-shards.py +++ b/release/scripts/merge-release-binary-shards.py @@ -141,6 +141,8 @@ def rosters( f"coordinatorctl-{tag}-linux-amd64", ] ) + if nightly_tag is None and release_roster.session_in_release(parsed): + common.append(f"registry-session-{tag}-linux-amd64") if release_roster.adapter_in_release(parsed): common.extend( [ diff --git a/release/scripts/merge-release-native-platform-shards.py b/release/scripts/merge-release-native-platform-shards.py index 7d240445ec..9927c627c5 100755 --- a/release/scripts/merge-release-native-platform-shards.py +++ b/release/scripts/merge-release-native-platform-shards.py @@ -82,7 +82,7 @@ def rosters( core.insert(0, f"relayctl-{tag}-{ASSET}") if parsed >= MINT_RETIREMENT_VERSION: core.remove(f"mint-{tag}-{ASSET}") - additional = release_roster.additional_platform_builds(parsed) + additional = release_roster.additional_platform_builds(parsed, nightly=nightly_tag is not None) additional_core = [ f"{binary}-{tag}-{ASSET}" for _, binary in additional diff --git a/release/scripts/nightly_release.py b/release/scripts/nightly_release.py index 5544fa6f49..98a9ee6c56 100644 --- a/release/scripts/nightly_release.py +++ b/release/scripts/nightly_release.py @@ -641,7 +641,7 @@ def assemble( expected_roster = current_roster(base, record["tag"]) if record.get("schema_version") != SCHEMA_V2 or record.get("roster") != expected_roster: raise NightlyError("build plan source roster mismatch") - release_assets = release_candidate._release_payload_inventory(base) + release_assets = release_candidate._release_payload_inventory(base, nightly=True) for name, kind in release_assets.items(): if kind == "notice": notice = ROOT / name diff --git a/release/scripts/registry-release b/release/scripts/registry-release index 0dcfd38f41..4565d23fcd 100755 --- a/release/scripts/registry-release +++ b/release/scripts/registry-release @@ -295,6 +295,8 @@ def artifact_inventory_errors(version: str, artifacts: dict[Any, Any]) -> list[s expected_inventory.add("registry-render") if release_roster.coordinator_binaries_in_release(parsed_version): expected_inventory.update({"coordinator", "coordinatorctl"}) + if release_roster.session_in_release(parsed_version): + expected_inventory.add("registry-session") if release_roster.adapter_in_release(parsed_version): expected_inventory.update({"adapter", "adapterctl"}) if release_roster.rstack_in_release(parsed_version): diff --git a/release/scripts/release_candidate.py b/release/scripts/release_candidate.py index 71b4639d2d..47af0ecffc 100644 --- a/release/scripts/release_candidate.py +++ b/release/scripts/release_candidate.py @@ -374,7 +374,7 @@ def _version_uses_release_docs(version: tuple[int, int, int]) -> bool: return version >= DOCS_RELEASE_RESUMPTION_VERSION -def _release_payload_inventory(version: str) -> dict[str, str]: +def _release_payload_inventory(version: str, *, nightly: bool = False) -> dict[str, str]: tag = f"v{version}" version_tuple = tuple(int(part) for part in version.split(".")) inventory = { @@ -538,7 +538,7 @@ def _release_payload_inventory(version: str) -> dict[str, str]: inventory[f"registry-language-server-{tag}-macos-arm64"] = "binary" if version_tuple >= THIRD_PARTY_NOTICES_MINIMUM_VERSION: inventory["THIRD_PARTY_NOTICES"] = "notice" - for _, binary in release_roster.additional_platform_builds(version_tuple): + for _, binary in release_roster.additional_platform_builds(version_tuple, nightly=nightly): for platform in ("linux-amd64", "linux-arm64", "macos-arm64"): inventory[f"{binary}-{tag}-{platform}"] = "binary" for installer in release_roster.additional_installers(version_tuple): diff --git a/release/scripts/release_roster.py b/release/scripts/release_roster.py index e5b7b98d5d..f3ec613e85 100644 --- a/release/scripts/release_roster.py +++ b/release/scripts/release_roster.py @@ -69,8 +69,8 @@ it is releasable. ``SESSION_FIRST_RELEASE`` decides which numbered release first includes the -``registry-session`` binary in the native platform builds. The service stays -held while the release gate is unset. +``registry-session`` binary in the native platform builds. Its image and +the frozen nightly inventories are independent of this gate. ``PYTHON_311_ABI_FIRST_RELEASE`` is the single place that decides which release first builds the Python client wheels against the Python 3.11 stable @@ -153,7 +153,7 @@ } -def additional_platform_builds(version: tuple[int, int, int]): +def additional_platform_builds(version: tuple[int, int, int], *, nightly: bool = False): """Return the additional native binaries without changing historical releases.""" if tuple(version) < ALL_PLATFORMS_FIRST_RELEASE: return () @@ -164,7 +164,7 @@ def additional_platform_builds(version: tuple[int, int, int]): "registry-discoveryctl": discoveryctl_in_release(version), "registry-render": render_in_release(version), "registry-coordinator": coordinator_binaries_in_release(version), - "registry-session": session_in_release(version), + "registry-session": not nightly and session_in_release(version), "registry-adapter": adapter_in_release(version), "registry-adapterctl": adapter_in_release(version), } @@ -373,6 +373,10 @@ def main(argv: list[str] | None = None) -> int: commands = parser.add_subparsers(dest="command", required=True) platforms = commands.add_parser("additional-platform-builds") platforms.add_argument("version", type=version_argument) + platforms.add_argument("--nightly", action="store_true") + session = commands.add_parser("session-in-release") + session.add_argument("version", type=version_argument) + session.set_defaults(in_release=session_in_release) coordinator_binaries = commands.add_parser("coordinator-binaries-in-release") coordinator_binaries.add_argument("version", type=version_argument) coordinator_binaries.set_defaults(in_release=coordinator_binaries_in_release) @@ -482,7 +486,7 @@ def main(argv: list[str] | None = None) -> int: relay.set_defaults(in_release=relay_in_release) args = parser.parse_args(argv) if args.command == "additional-platform-builds": - for crate, binary in additional_platform_builds(args.version): + for crate, binary in additional_platform_builds(args.version, nightly=args.nightly): print(crate, binary) return 0 print("true" if args.in_release(args.version) else "false") diff --git a/release/scripts/test_merge_release_binary_shards.py b/release/scripts/test_merge_release_binary_shards.py index 3b4afb7b3c..010b140f90 100644 --- a/release/scripts/test_merge_release_binary_shards.py +++ b/release/scripts/test_merge_release_binary_shards.py @@ -75,6 +75,18 @@ def digest(data: bytes) -> str: class MergeReleaseBinaryShardsTest(unittest.TestCase): + def test_session_is_a_numbered_core_binary_and_has_no_image(self) -> None: + version = "0.51.0" + nightly_tag = f"v{version}-nightly.20261201.{SOURCE_SHA}" + with mock.patch.object(MODULE.release_roster, "SESSION_FIRST_RELEASE", (0, 51, 0)): + past, _ = MODULE.rosters("0.50.0") + numbered, images = MODULE.rosters(version) + nightly, _ = MODULE.rosters(version, nightly_tag) + self.assertNotIn("registry-session-v0.50.0-linux-amd64", past["core"]) + self.assertIn("registry-session-v0.51.0-linux-amd64", numbered["core"]) + self.assertNotIn(f"registry-session-{nightly_tag}-linux-amd64", nightly["core"]) + self.assertNotIn("registry-session", dict(images)) + def setUp(self) -> None: self.temporary = tempfile.TemporaryDirectory() self.addCleanup(self.temporary.cleanup) diff --git a/release/scripts/test_nightly_release.py b/release/scripts/test_nightly_release.py index d2232057fa..f1c958abca 100644 --- a/release/scripts/test_nightly_release.py +++ b/release/scripts/test_nightly_release.py @@ -48,6 +48,20 @@ class NightlyTest(unittest.TestCase): + def test_numbered_session_does_not_change_frozen_nightly_inventory(self): + version = "0.51.0" + tag = f"v{version}-nightly.20261201.{SHA}" + before = nightly.current_roster(version, tag) + with patch.object(nightly.release_roster, "SESSION_FIRST_RELEASE", (0, 51, 0)): + self.assertEqual(before, nightly.current_roster(version, tag)) + inventory = release_candidate._release_payload_inventory(version, nightly=True) + expected = sorted( + name.replace(f"v{version}", tag) + for name, kind in inventory.items() + if kind in {"binary", "notice"} + ) + self.assertEqual(before["payloads"], expected) + def test_current_platform_roster_preserves_historical_manifest_meaning(self): tag = f"v0.44.0-nightly.20261023.{SHA}" roster = nightly.current_roster("0.44.0", tag) diff --git a/release/scripts/test_registry_release.py b/release/scripts/test_registry_release.py index 3bb133b3b7..a6065eb0fa 100755 --- a/release/scripts/test_registry_release.py +++ b/release/scripts/test_registry_release.py @@ -4117,6 +4117,15 @@ def released(version: str) -> dict[str, str]: [], module.artifact_inventory_errors("0.42.0", incomplete) ) + before_session = released("0.50.0") + at_session = released("0.51.0") + session = "registry-session" + with mock.patch.object(module.release_roster, "SESSION_FIRST_RELEASE", (0, 51, 0)): + self.assertEqual([], module.artifact_inventory_errors("0.50.0", before_session)) + self.assertTrue(module.artifact_inventory_errors("0.50.0", before_session | {session: "0.50.0"})) + self.assertTrue(module.artifact_inventory_errors("0.51.0", at_session)) + self.assertEqual([], module.artifact_inventory_errors("0.51.0", at_session | {session: "0.51.0"})) + # Holding the image does not hold the independently released binaries. with mock.patch.object( module.release_roster, "COORDINATOR_FIRST_RELEASE", None diff --git a/release/scripts/test_release_native_platform.py b/release/scripts/test_release_native_platform.py index a8a640255d..5ee6bd57c1 100755 --- a/release/scripts/test_release_native_platform.py +++ b/release/scripts/test_release_native_platform.py @@ -281,10 +281,9 @@ def setUp(self) -> None: self.fake_codesign.chmod(0o755) def roster_shim( - self, stem: str, first_release: tuple[int, int, int] + self, stem: str, first_releases: dict[str, tuple[int, int, int]] ) -> Path: - """Return a directory whose python3 answers the roster as if it named - ``first_release``, and runs every other command unchanged.""" + """Run the real roster with fixture gates and pass through other commands.""" shim_dir = self.root / f"{stem}-roster-shim" shim_dir.mkdir() shim = shim_dir / "python3" @@ -298,12 +297,12 @@ def roster_shim( if ( len(args) >= 2 and args[0].endswith("/release_roster.py") - and args[1] == "breg-services-in-release" ): spec = importlib.util.spec_from_file_location("release_roster", args[0]) roster = importlib.util.module_from_spec(spec) spec.loader.exec_module(roster) - roster.BREG_SERVICES_FIRST_RELEASE = {first_release!r} + for constant, first_release in {first_releases!r}.items(): + setattr(roster, constant, first_release) sys.exit(roster.main(args[1:])) os.execv({sys.executable!r}, [{sys.executable!r}, *args]) """, @@ -326,6 +325,7 @@ def build( missing_fips_binary: str | None = None, nightly_tag: str | None = None, breg_services_first_release: tuple[int, int, int] | None = None, + session_first_release: tuple[int, int, int] | None = None, exclude_discovery: bool = False, ) -> tuple[subprocess.CompletedProcess[str], Path, list[list[str]]]: stem = name or group @@ -348,8 +348,14 @@ def build( environment["FAKE_CARGO_FAIL_CALL"] = str(fail_call) if binary_version is not None: environment["FAKE_BINARY_VERSION"] = binary_version - if breg_services_first_release is not None: - shim_dir = self.roster_shim(stem, breg_services_first_release) + first_releases = { + name: value for name, value in ( + ("BREG_SERVICES_FIRST_RELEASE", breg_services_first_release), + ("SESSION_FIRST_RELEASE", session_first_release), + ) if value is not None + } + if first_releases: + shim_dir = self.roster_shim(stem, first_releases) environment["PATH"] = f"{shim_dir}{os.pathsep}{environment['PATH']}" parsed = tuple(int(part) for part in version.split(".")) if fips_shared or parsed >= (0, 33, 0): @@ -371,6 +377,7 @@ def build( "registry-render", "coordinator", "coordinatorctl", + "registry-session", "adapter", "adapterctl", ] @@ -525,6 +532,32 @@ def test_nightly_language_server_keeps_its_cargo_version(self): ).is_file() ) + def test_session_numbered_archive_is_built_and_nightly_archive_is_omitted(self): + version = "0.51.0" + first_release = (0, 51, 0) + numbered_tag = f"v{version}" + nightly_tag = f"{numbered_tag}-nightly.20261201.{SOURCE_SHA}" + asset = f"registry-session-{numbered_tag}-macos-arm64.tar.gz" + with mock.patch.object(MODULE.release_roster, "SESSION_FIRST_RELEASE", first_release): + result, output, _ = self.build( + "core", name="session-numbered", version=version, session_first_release=first_release, + ) + self.assertEqual(0, result.returncode, result.stderr) + self.assertIn(asset, MODULE.rosters(version)["core"]) + with tarfile.open(output / "platform" / asset, "r:gz") as package: + self.assertEqual( + [asset.removesuffix(".tar.gz"), "libaws_lc_fips_0_14_2_crypto.dylib", "THIRD_PARTY_NOTICES"], + package.getnames(), + ) + result, output, calls = self.build( + "core", name="session-nightly", version=version, nightly_tag=nightly_tag, + session_first_release=first_release, + ) + self.assertEqual(0, result.returncode, result.stderr) + self.assertFalse(any("registry-session" in call for call in calls)) + paths = [path.name for path in (output / "platform").iterdir()] + self.assertCountEqual(paths, MODULE.rosters(version, nightly_tag)["core"]) + def test_v0_44_core_bundles_and_launches_every_additional_native_binary(self): result, output, calls = self.build("core", version="0.44.0") self.assertEqual(0, result.returncode, result.stderr) diff --git a/release/scripts/test_release_roster.py b/release/scripts/test_release_roster.py index 417d9e9cb8..ef760bad06 100644 --- a/release/scripts/test_release_roster.py +++ b/release/scripts/test_release_roster.py @@ -131,6 +131,15 @@ def test_session_first_release_adds_its_native_binary_to_the_roster(self) -> Non self.assertNotIn(binary, release_roster.additional_platform_builds((0, 50, 0))) self.assertTrue(release_roster.session_in_release((0, 51, 0))) self.assertIn(binary, release_roster.additional_platform_builds((0, 51, 0))) + self.assertNotIn(binary, release_roster.additional_platform_builds((0, 51, 0), nightly=True)) + for arguments, expected in ( + (["session-in-release", "0.50.0"], "false\n"), + (["session-in-release", "0.51.0"], "true\n"), + ): + stdout = io.StringIO() + with redirect_stdout(stdout): + self.assertEqual(0, release_roster.main(arguments)) + self.assertEqual(expected, stdout.getvalue()) def test_coordinator_binary_release_does_not_release_its_image(self): self.assertFalse(release_roster.coordinator_binaries_in_release((0, 43, 99))) From 0ff51eda092a5083d0156cda876732ab88158875 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 17:16:26 +0000 Subject: [PATCH 036/183] fix(scheduling): date fresh starters from initialization Keep the starter calendars and their fixtures usable after the checked example dates while preserving finite opening and admission policy. Derive the guide holiday from its fixture clock. Signed-off-by: Jeremi Joslin (cherry picked from commit c17dca44e6683dceecc3bea8ce0df39471258495) --- crates/registry-schedulingctl/Cargo.toml | 2 +- crates/registry-schedulingctl/src/project.rs | 95 ++++++++++++-- .../registry-schedulingctl/src/templates.rs | 117 +++++++++++++++++- .../src/content/docs/configure/scheduling.mdx | 69 +++++++---- products/scheduling/AGENTS.md | 13 +- products/scheduling/README.md | 12 +- .../scheduling/scripts/check-checkpoint.sh | 27 +++- 7 files changed, 283 insertions(+), 52 deletions(-) diff --git a/crates/registry-schedulingctl/Cargo.toml b/crates/registry-schedulingctl/Cargo.toml index bf39cf0de9..68618b181b 100644 --- a/crates/registry-schedulingctl/Cargo.toml +++ b/crates/registry-schedulingctl/Cargo.toml @@ -22,6 +22,7 @@ workspace = true registry-rstack-dev.workspace = true registry-cli-report.workspace = true anyhow.workspace = true +chrono.workspace = true clap.workspace = true registry-cli-api.workspace = true registry-platform-audit.workspace = true @@ -45,7 +46,6 @@ zeroize.workspace = true # already demand. Asking for it here instead would turn it on for every build # 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 diff --git a/crates/registry-schedulingctl/src/project.rs b/crates/registry-schedulingctl/src/project.rs index 694cea0228..dbae9da77c 100644 --- a/crates/registry-schedulingctl/src/project.rs +++ b/crates/registry-schedulingctl/src/project.rs @@ -2,11 +2,10 @@ //! Project loading and the offline init, check, test, and explain reports. //! -//! Everything here runs without a network, a database, or a clock: the -//! authored policy, its records, and its fixtures are read from the project -//! directory through the shared reader, checked and replayed through the -//! pure core, and rendered as one JSON report per command. A refused project -//! is the reader's own report, every diagnostic at its position. +//! Init dates a new starter from today's UTC date. The other offline commands +//! read the policy, records, and fixtures through the shared reader and pure +//! core without reading the clock. A refused project is the reader's own +//! report, every diagnostic at its position. use registry_platform_config::DeclaredPosture; use std::collections::BTreeMap; @@ -14,6 +13,7 @@ use std::fs; use std::path::{Path, PathBuf}; use anyhow::{Context, Result}; +use chrono::{NaiveDate, Utc}; use registry_platform_config::package::{plan_package, write_package}; use registry_platform_config::{sha256_uri, UNAVAILABLE_CODE}; use registry_platform_yaml::{Decoded, Diagnostic, Report, Source}; @@ -37,6 +37,10 @@ const FIXTURES_DIRECTORY: &str = "fixtures"; const NO_FIXTURES_CODE: &str = "scheduling.fixture.none"; pub(super) fn init(project: &Path, template: &str) -> Result { + init_on(project, template, Utc::now().date_naive()) +} + +fn init_on(project: &Path, template: &str, today: NaiveDate) -> Result { let Some(files) = templates::template_files(template) else { anyhow::bail!( "unknown template {template:?}; available templates: standalone-exact-time, standalone-arrival-window, resource-reservations" @@ -58,7 +62,8 @@ pub(super) fn init(project: &Path, template: &str) -> Result { fs::create_dir(staging.path().join(FIXTURES_DIRECTORY))?; let mut created = Vec::new(); for (relative, contents) in &files { - fs::write(staging.path().join(relative), contents)?; + let contents = templates::date_file(template, relative, contents, today); + fs::write(staging.path().join(relative), contents.as_bytes())?; created.push((*relative).to_owned()); } let staging_path = staging.keep(); @@ -856,13 +861,89 @@ fn absolute_lexical(path: &Path) -> std::io::Result { mod tests { use super::*; use registry_scheduling::config::RuntimeConfig; + use registry_scheduling_core::location_open_intervals; + + #[test] + fn fresh_starters_publish_supply_after_the_original_example_dates() { + let root = tempfile::tempdir().unwrap(); + let posture = registry_scheduling::config::DEFAULT_POSTURE; + for day in ["2027-01-01", "2028-02-29", "2037-11-02"] { + let today = day.parse::().unwrap(); + let now = today.and_hms_opt(0, 0, 0).unwrap().and_utc(); + for (template, expected_cases) in [ + ("standalone-exact-time", 8), + ("standalone-arrival-window", 6), + ("resource-reservations", 11), + ] { + let project = root.path().join(day).join(template); + init_on(&project, template, today).unwrap(); + let context = format!("{day} {template}"); + let checked = check(&project, false, posture).unwrap(); + assert_eq!(checked["diagnostics"], json!([]), "{context}"); + let replay = test(&project, posture).unwrap(); + let mut case_count = 0; + for fixture in replay["fixtures"].as_array().unwrap() { + assert_eq!(fixture["status"], "passed", "{context}: {fixture}"); + for case in fixture["cases"].as_array().unwrap() { + assert_eq!(case["status"], "pass", "{context}: {case}"); + case_count += 1; + } + } + assert_eq!(case_count, expected_cases, "{context}"); + + let authored = read_project(&project, true, posture).unwrap(); + let policy = authored.policy.unwrap().value; + let facts = authored.facts.unwrap(); + for offering in &policy.offerings { + let location = facts.location(&offering.location).unwrap(); + let intervals = + location_open_intervals(&policy, &location.id, &location.timezone, &[]) + .unwrap(); + assert!( + intervals.iter().any(|open| open.end > now), + "{context}: {}", + offering.id + ); + if let Some(arrival) = &offering.arrival { + let window = offering.served_windows(&facts.windows).next().unwrap(); + assert!(window.start > now + chrono::TimeDelta::days(1), "{context}"); + assert!( + window.start + < now + chrono::TimeDelta::days(i64::from(arrival.horizon_days)), + "{context}" + ); + } + } + } + } + } + + #[test] + fn init_reproduces_the_committed_examples_on_their_reference_date() { + let root = tempfile::tempdir().unwrap(); + for template in [ + "standalone-exact-time", + "standalone-arrival-window", + "resource-reservations", + ] { + let project = root.path().join(template); + init_on(&project, template, templates::EXAMPLE_DATE).unwrap(); + for (relative, bytes) in templates::template_files(template).unwrap() { + assert_eq!( + fs::read(project.join(relative)).unwrap(), + bytes.as_bytes(), + "{template}/{relative}" + ); + } + } + } /// A tempdir holding one freshly initialized template project, plus the /// paths the tempdir keeps alive. fn initialized(template: &str) -> (tempfile::TempDir, PathBuf) { let root = tempfile::tempdir().unwrap(); let project = root.path().join("project"); - init(&project, template).unwrap(); + init_on(&project, template, templates::EXAMPLE_DATE).unwrap(); (root, project) } diff --git a/crates/registry-schedulingctl/src/templates.rs b/crates/registry-schedulingctl/src/templates.rs index 39c43313f1..ad86c0547f 100644 --- a/crates/registry-schedulingctl/src/templates.rs +++ b/crates/registry-schedulingctl/src/templates.rs @@ -5,8 +5,121 @@ //! Each template is a working project: its policy passes the check with zero //! findings and its fixtures replay all-Pass offline, which the tests prove //! end to end. The files are the committed examples under -//! `products/scheduling/examples`, so the two cannot drift, and every file -//! carries its schema modeline on its first line. +//! `products/scheduling/examples`, dated as of a common reference day. +//! Init moves their date groups together so the live supply is usable and +//! each fixture still proves the same scenario. Every file carries its +//! schema modeline on its first line. + +use std::borrow::Cow; + +use chrono::{Datelike, Days, NaiveDate, Weekday}; + +#[cfg(test)] +pub(super) const EXAMPLE_DATE: NaiveDate = example_date(10, 1); +const EXAMPLE_COUNTER: NaiveDate = example_date(10, 5); +const EXAMPLE_ARRIVAL: NaiveDate = example_date(10, 10); +const EXAMPLE_FOLD: NaiveDate = example_date(11, 1); + +const fn example_date(month: u32, day: u32) -> NaiveDate { + NaiveDate::from_ymd_opt(2026, month, day).expect("valid starter reference date") +} + +pub(super) fn date_file<'a>( + template: &str, + relative: &str, + contents: &'a str, + today: NaiveDate, +) -> Cow<'a, str> { + let counter_shift = || { + // The example opens on the Thursday before the Monday fixture. Shift + // by whole weeks and choose a Monday whose opening has begun today. + let monday = on_or_after(today - Days::new(2), Weekday::Mon); + monday - EXAMPLE_COUNTER + }; + let fold_shift = || next_new_york_fold(today) - EXAMPLE_FOLD; + match (template, relative) { + ("standalone-exact-time", "scheduling.yaml") => { + let counter = counter_shift(); + let fold = fold_shift(); + shift_dates(contents, |date| { + date + if date == EXAMPLE_FOLD { fold } else { counter } + }) + } + ("standalone-exact-time", "fixtures/counter-stations.yaml") => { + let shift = counter_shift(); + shift_dates(contents, |date| date + shift) + } + ("standalone-exact-time", "records.yaml" | "fixtures/fold-day-rebooking.yaml") + | ("resource-reservations", "records.yaml" | "fixtures/named-intervals.yaml") => { + let shift = fold_shift(); + shift_dates(contents, |date| date + shift) + } + ( + "standalone-arrival-window", + "scheduling.yaml" + | "records.yaml" + | "fixtures/household-morning.yaml" + | "fixtures/household-afternoon.yaml", + ) => { + // Both named blocks need to be on the same Saturday, far enough + // ahead for their lead time and the example cancellation cutoff. + let saturday = on_or_after(today + Days::new(7), Weekday::Sat); + let shift = saturday - EXAMPLE_ARRIVAL; + shift_dates(contents, |date| date + shift) + } + ("resource-reservations", "scheduling.yaml") => { + let year = next_new_york_fold(today).year(); + // Cover the fixture's November fold and the live dates leading up + // to it, including when the fold will land in the next year. + shift_dates(contents, |date| { + let shifted = date.with_year(year).expect("valid opening date"); + if date == example_date(1, 1) { + shifted.min(today) + } else { + shifted + } + }) + } + _ => Cow::Borrowed(contents), + } +} + +fn on_or_after(date: NaiveDate, weekday: Weekday) -> NaiveDate { + date + Days::new(u64::from(weekday.days_since(date.weekday()))) +} + +fn next_new_york_fold(today: NaiveDate) -> NaiveDate { + // America/New_York returns to standard time on the first Sunday in November. + let fold = |year| { + let november = NaiveDate::from_ymd_opt(year, 11, 1).expect("valid November date"); + on_or_after(november, Weekday::Sun) + }; + let this_year = fold(today.year()); + if this_year > today { + this_year + } else { + fold(today.year() + 1) + } +} + +/// Move ISO date prefixes in the built-in YAML, including the dates in UTC +/// timestamps. Keep the emitted file formatting and all clock times intact. +fn shift_dates(contents: &str, shift: impl Fn(NaiveDate) -> NaiveDate) -> Cow<'_, str> { + let date_char = |c: char| c.is_ascii_digit() || c == '-'; + let mut output = String::with_capacity(contents.len()); + for token in contents.split_inclusive(|c| !date_char(c)) { + let date = token.trim_end_matches(|c| !date_char(c)); + if date.len() == 10 { + if let Ok(parsed) = NaiveDate::parse_from_str(date, "%Y-%m-%d") { + output.push_str(&shift(parsed).format("%Y-%m-%d").to_string()); + output.push_str(&token[date.len()..]); + continue; + } + } + output.push_str(token); + } + Cow::Owned(output) +} /// The example directory one template's files are read from. macro_rules! example { diff --git a/docs/site/src/content/docs/configure/scheduling.mdx b/docs/site/src/content/docs/configure/scheduling.mdx index cb4e5ae2ca..8b078a1c6e 100644 --- a/docs/site/src/content/docs/configure/scheduling.mdx +++ b/docs/site/src/content/docs/configure/scheduling.mdx @@ -36,36 +36,50 @@ openings: weekdays: [mon, tue, wed, thu, fri] startTime: "09:00" endTime: "12:30" - effectiveFrom: "2026-10-01" - effectiveUntil: "2026-12-31" + effectiveFrom: "" + effectiveUntil: "" ``` -Times are wall-clock times at the location, read in the time zone its location record names, so -the counter opens at 09:00 Bangkok time on weekdays. The opening ends on `effectiveUntil`; from -2027 this offering publishes no starts until you extend that date and deploy the change. +Times are local to the time zone in the location record. The counter opens at 09:00 Bangkok time +on weekdays. Read `effectiveFrom` and `effectiveUntil` +in your file for the dates `init` generated when you created the project. Both dates are +inclusive. To publish starts after `effectiveUntil`, set a new approved range and deploy the +change. A single opening can span at most 3,650 days between its first and last dates. + +{/* Evidence: crates/registry-schedulingctl/src/templates.rs, date_file(); + crates/registry-scheduling-core/src/policy.rs, PatternSpanTooLarge. */} ## Close a public holiday Every opening names a [holiday set](../../reference/glossary/#holiday-set), and a date in that set -closes the opening for the whole day. The starter's set closes nothing yet. Close Tuesday 13 -October 2026: - -```diff test-edit title="scheduling/scheduling.yaml" - office-holidays: - revision: 1 -+ dates: -+ - "2026-10-13" - label: Public holidays observed by the registry offices. -``` +closes the opening for the whole day. Use Python 3 to add the Tuesday after the counter fixture's +Monday `now` to `office-holidays.dates`. Add a booking case for 09:00 Bangkok time that day. +This keeps the holiday inside the fixture's booking horizon and leaves its Monday cases intact. -Prove it with a case at the end of the counter fixture. A booking at 09:00 that day must be -refused: - -```yaml title="scheduling/fixtures/counter-stations.yaml" test-append +```sh +python3 - <<'PY' +from datetime import datetime, timedelta +from pathlib import Path + +project = Path("scheduling") +fixture = project / "fixtures/counter-stations.yaml" +fixture_text = fixture.read_text(encoding="utf-8") +fixture_now = next(line.split(": ", 1)[1] for line in fixture_text.splitlines() + if line.startswith("now: ")) +holiday = datetime.strptime(fixture_now, "%Y-%m-%dT%H:%M:%SZ").date() + timedelta(days=1) + +policy = project / "scheduling.yaml" +policy_text = policy.read_text(encoding="utf-8") +holiday_set = " office-holidays:\n revision: 1\n" +before, after = policy_text.split(holiday_set, 1) +if after.startswith(" dates:") or "the-holiday-is-not-served" in fixture_text: + raise SystemExit("The starter already has holiday dates or has recorded the holiday case.") +policy.write_text(f'{before}{holiday_set} dates:\n - "{holiday}"\n{after}', encoding="utf-8") +fixture.write_text(fixture_text + f"""\ - name: the-holiday-is-not-served request: offering: registry-update-30 - start: 2026-10-13T02:00:00Z + start: {holiday}T02:00:00Z party: recipients: 1 attendees: 1 @@ -74,6 +88,8 @@ refused: expect: type: refused code: schedule.unpublished +""", encoding="utf-8") +PY ``` ```sh @@ -96,15 +112,16 @@ does not establish source reachability or deployment readiness. `schedule.unpublished` is the answer for any start the policy does not publish, whether the day is a holiday, a weekend, or outside the opening hours. -A closure that affects one location for part of a day is not policy. It is an exception record in -`records.yaml`, which the operator applies to a running deployment without a new package: +A closure that affects one location for part of a day is an exception record in `records.yaml`. +The operator applies it to a running deployment without a new package. Read the `hall-prep` +exception in your starter for the date of the New York clock change the fixture exercises. ```yaml title="scheduling/records.yaml" test-excerpt="scheduling/records.yaml" exceptions: - id: hall-prep location: new-york-hall kind: closure - date: "2026-11-01" + date: "" startTime: "00:15" endTime: "00:45" ``` @@ -256,8 +273,10 @@ schedulingctl explain ./arrival --format json } ``` -The window itself is a record in `./arrival/records.yaml`, with its start, end, and `units`. A -`subquotas` entry caps how many of those units one channel, `public` or `assisted`, may take. A +The window itself is a record in `./arrival/records.yaml`, with its start, end, and `units`. +The starter dates both windows on the same upcoming Saturday. After those windows pass, publish +new dated records for future bookings. +A `subquotas` entry caps how many of those units one channel, `public` or `assisted`, may take. A subquota is a ceiling, not a reservation: the other channel may still use units the first leaves free. A channel the policy declares but gives no subquota draws from the window's total alone, and a request naming an undeclared channel is refused. diff --git a/products/scheduling/AGENTS.md b/products/scheduling/AGENTS.md index 3d3e965425..dff3278c03 100644 --- a/products/scheduling/AGENTS.md +++ b/products/scheduling/AGENTS.md @@ -33,13 +33,12 @@ product. Document Store, Evidence, or Messaging crate, and none of those products reach a scheduling crate. Run `scripts/check_dependency_direction.py` after dependency changes. -- Each directory under `examples/` is exactly what `schedulingctl init` writes - for the template with the same name (the `resource-reservations` example also - keeps a README the template does not write), and the checkpoint fails if any - of the three pairs drifts apart. When `schedulingctl init` starts emitting or - changing a file, copy that output into every applicable committed example - (`standalone-exact-time`, `standalone-arrival-window`, and - `resource-reservations`) in the same commit. +- The three starter directories under `examples/` are the checked snapshots + for `schedulingctl init` on 2026-10-01. The `resource-reservations` example + also keeps a README the template does not write. The CLI test checks the + exact snapshot bytes and the checkpoint verifies both fresh and committed + projects. When `init` changes a file, keep each applicable snapshot in + sync and date its fixture cases relative to the fixture clock. - Keep authored examples and the checkpoint demo small. Do not add a later-wave surface to close a documentation obligation; record the exclusion instead. diff --git a/products/scheduling/README.md b/products/scheduling/README.md index 7081d86d31..f68d9557aa 100644 --- a/products/scheduling/README.md +++ b/products/scheduling/README.md @@ -73,8 +73,10 @@ serves the runtime on loopback. See `products/scheduling/demo/README.md`. - `contracts/`: the security invariant matrix, its test traceability, and recorded decisions. - `examples/`: `standalone-exact-time`, `standalone-arrival-window`, and `resource-reservations` - are what `schedulingctl init --template ` writes, and `formats/` holds a sample - `schedulingctl` report. The `resource-reservations` example also keeps a README. + are snapshots of `schedulingctl init --template ` as of 2026-10-01. Their five fixtures + replay against their declared clocks. Run `init` for live supply dated from the day you create + a project. `formats/` holds a sample `schedulingctl` report, and `resource-reservations` also + keeps a README. - `generated/`: the OpenAPI description and the JSON Schemas derived from the Rust types. Do not edit them by hand. - `demo/`: the acceptance demo. @@ -99,9 +101,9 @@ cargo build --locked -p registry-schedulingctl products/scheduling/scripts/check-checkpoint.sh ``` -`examples/standalone-exact-time/` is exactly what -`schedulingctl init --template standalone-exact-time` writes, and the checkpoint fails if the two -drift apart. +The checkpoint checks and replays all three committed examples and freshly initialized projects. +The CLI unit test verifies that initialization on the reference date reproduces the example files +byte for byte. For PostgreSQL execution, the destructive test suites require a separate disposable database and the `postgres-test` feature: diff --git a/products/scheduling/scripts/check-checkpoint.sh b/products/scheduling/scripts/check-checkpoint.sh index 80373a5067..5a1a1e371a 100755 --- a/products/scheduling/scripts/check-checkpoint.sh +++ b/products/scheduling/scripts/check-checkpoint.sh @@ -41,7 +41,7 @@ cleanup() { } trap cleanup EXIT HUP INT TERM -for template in standalone-exact-time standalone-arrival-window; do +for template in standalone-exact-time standalone-arrival-window resource-reservations; do "$schedulingctl_bin" init "$work/$template" --template "$template" >/dev/null "$schedulingctl_bin" check "$work/$template" >/dev/null "$schedulingctl_bin" test "$work/$template" >/dev/null @@ -153,14 +153,31 @@ if [ "$written" != "$sums_digest" ]; then exit 1 fi -# The committed examples are the starter templates' output, so neither can -# drift from what an adopter initializes, including its live records document. +# The committed examples match what an adopter initializes, with the live +# and fixture dates shifted from the snapshot to the day of init. The CLI +# unit test compares the exact bytes with init pinned to the snapshot date. # The resource-reservations example also carries a README, which the template # does not write, so the comparison excludes that one file. for template in standalone-exact-time standalone-arrival-window resource-reservations; do example="$repo_root/products/scheduling/examples/$template" - "$schedulingctl_bin" init "$work/example-$template" --template "$template" >/dev/null - diff -r -x README.md "$work/example-$template" "$example" >/dev/null + python3 - "$work/$template" "$example" <<'PY' +import re +import sys +from pathlib import Path + +date = re.compile(rb"(?", path.read_bytes()) + for path in root.rglob("*") if path.is_file() and path.name != "README.md" + } + +fresh, snapshot = (files(Path(root)) for root in sys.argv[1:]) +for path in sorted(fresh.keys() | snapshot.keys()): + if fresh.get(path) != snapshot.get(path): + sys.exit(f"{sys.argv[2]}/{path}: starter differs from snapshot after masking dates") +PY "$schedulingctl_bin" check "$example" >/dev/null "$schedulingctl_bin" test "$example" >/dev/null done From 41e6c86b1efe5e1c1bbc2e9710bf26fc34dd3f71 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 17:55:58 +0000 Subject: [PATCH 037/183] fix(dev): narrow and verify private PostgreSQL attachment Signed-off-by: Jeremi Joslin --- crates/registry-platform-postgres/README.md | 3 +- crates/registry-platform-postgres/src/lib.rs | 21 +- crates/registry-rstack-dev/src/database.rs | 214 +++++++++++++----- crates/registry-rstack-dev/src/products.rs | 15 ++ .../run-a-project-with-rstack-dev.mdx | 4 + products/platform/CHANGELOG.md | 6 + 6 files changed, 207 insertions(+), 56 deletions(-) diff --git a/crates/registry-platform-postgres/README.md b/crates/registry-platform-postgres/README.md index adcd9380b2..0d3f150df9 100644 --- a/crates/registry-platform-postgres/README.md +++ b/crates/registry-platform-postgres/README.md @@ -4,5 +4,6 @@ - `postgres_connection` checks every host and `hostaddr` of a parsed connection string under the runtime's `database.transport`. Under a plaintext transport it returns a configuration that dials only the numeric addresses each host was checked as, so the driver never resolves a name again. Under `verified-tls` the configuration is returned unchanged. - `loopback_postgres_connection` does the same under `loopback-plaintext`, for a constructor that holds no runtime database block. -- Both take the host resolver as an argument. A runtime passes `registry_platform_config::resolve_database_host`; tests pass a fixed answer. +- `private_development_postgres_connection` pins only private and loopback addresses for the development runner's explicitly selected administrator transport. Product runtimes use `postgres_connection` with the loaded database block and its posture witness. +- Each entry point takes a host resolver. A runtime passes `registry_platform_config::resolve_database_host`. Tests pass a fixed answer. - A keyword host written as an IP address in brackets, such as `host=[::1]`, is dropped from the list, as the driver itself fails that entry. When no other host is left, the connection is refused with `platform.database.bracketed-host`. diff --git a/crates/registry-platform-postgres/src/lib.rs b/crates/registry-platform-postgres/src/lib.rs index 0a13457e51..8ed2cc157f 100644 --- a/crates/registry-platform-postgres/src/lib.rs +++ b/crates/registry-platform-postgres/src/lib.rs @@ -55,12 +55,25 @@ pub fn loopback_postgres_connection( connection_for_transport(postgres, DatabaseTransport::LoopbackPlaintext, resolve) } -/// Pin a parsed PostgreSQL configuration after the caller has admitted an -/// explicit transport. The caller still sets the matching driver TLS mode. -pub fn connection_for_transport( +/// Pin a PostgreSQL administrator configuration for an explicitly selected +/// private development attachment. Only the development runner uses this +/// entry point. Product runtimes use [`postgres_connection`] with a loaded +/// database block and its posture witness. +pub fn private_development_postgres_connection( + postgres: Config, + resolve: &dyn Fn(&str) -> std::io::Result>, +) -> Result { + connection_for_transport( + postgres, + DatabaseTransport::PrivateNetworkPlaintext, + resolve, + ) +} + +fn connection_for_transport( postgres: Config, transport: DatabaseTransport, - resolve: &HostResolver, + resolve: &dyn Fn(&str) -> std::io::Result>, ) -> Result { let permitted = check_database_hosts(transport, &database_hosts(&postgres), resolve)?; pinned(&permitted, postgres) diff --git a/crates/registry-rstack-dev/src/database.rs b/crates/registry-rstack-dev/src/database.rs index 7895dfab80..440b2b18f7 100644 --- a/crates/registry-rstack-dev/src/database.rs +++ b/crates/registry-rstack-dev/src/database.rs @@ -1,7 +1,9 @@ // SPDX-License-Identifier: Apache-2.0 use std::{ + cell::Cell, future::Future, + net::IpAddr, str::FromStr, thread, time::{Duration, Instant}, @@ -324,6 +326,24 @@ fn open_admin_session( Ok((client, connection_task, identity)) } +fn open_plaintext_candidates( + admin_url: &str, + addresses: &[IpAddr], + mut open: impl FnMut(&Config) -> Result, +) -> Result<(Config, Endpoint, T)> { + let mut last_error = None; + for &address in addresses { + let (mut candidate, endpoint) = + admin_config_with_resolver(admin_url, &move |_| Ok(vec![address]))?; + apply_session_options(&mut candidate); + match open(&candidate) { + Ok(session) => return Ok((candidate, endpoint, session)), + Err(error) => last_error = Some(error), + } + } + Err(last_error.unwrap_or_else(|| anyhow!("no checked plaintext PostgreSQL address answered"))) +} + #[derive(Clone)] pub(super) struct DatabaseUrls { pub runtime: String, @@ -451,45 +471,23 @@ impl Database { if matches!(transport, AdminTransport::Plaintext) && admin_config.get_hostaddrs().len() > 1 { - let mut last_error = None; - let mut connected = None; - for &address in admin_config.get_hostaddrs() { - let (mut candidate_config, candidate_endpoint) = - admin_config_with_resolver(admin_url, &move |_| Ok(vec![address]))?; - apply_session_options(&mut candidate_config); - match open_admin_session( - &runtime, - &candidate_config, - &transport, - &ownership_lock, - expected_identity, - session_deadline, - ) { - Ok((client, connection_task, recovery_identity)) => { - connected = Some(( - candidate_config, - candidate_endpoint, - client, - connection_task, - recovery_identity, - )); - break; - } - Err(error) => { - last_error = Some(error); - } - } - } - match connected { - Some(found) => found, - None => { - return Err(last_error.unwrap_or_else(|| { - anyhow!("no checked plaintext PostgreSQL address answered") - })) - .context(session_context) - .map_err(super::operational); - } - } + let (config, endpoint, (client, task, identity)) = open_plaintext_candidates( + admin_url, + admin_config.get_hostaddrs(), + |candidate| { + open_admin_session( + &runtime, + candidate, + &transport, + &ownership_lock, + expected_identity, + session_deadline, + ) + }, + ) + .context(session_context) + .map_err(super::operational)?; + (config, endpoint, client, task, identity) } else { let (client, connection_task, recovery_identity) = open_admin_session( &runtime, @@ -1358,7 +1356,9 @@ fn admin_config_with_resolver( ), "transport" => { if private_plaintext || value != "private-network-plaintext" { - bail!("the PostgreSQL admin URL transport may specify private-network-plaintext once"); + bail!( + "the PostgreSQL admin URL transport may specify private-network-plaintext once" + ); } private_plaintext = true; } @@ -1366,14 +1366,15 @@ fn admin_config_with_resolver( other => bail!("the PostgreSQL admin URL query parameter {other} is not supported"), } } - let transport = - if private_plaintext { - ensure!(requested_transport != Some(DatabaseTransport::VerifiedTls), - "the PostgreSQL admin URL must not combine private-network-plaintext with TLS sslmode"); - DatabaseTransport::PrivateNetworkPlaintext - } else { - requested_transport.unwrap_or(DatabaseTransport::VerifiedTls) - }; + let transport = if private_plaintext { + ensure!( + requested_transport != Some(DatabaseTransport::VerifiedTls), + "the PostgreSQL admin URL must not combine private-network-plaintext with TLS sslmode" + ); + DatabaseTransport::PrivateNetworkPlaintext + } else { + requested_transport.unwrap_or(DatabaseTransport::VerifiedTls) + }; // tokio-postgres does not parse verify-ca or verify-full, and the runner // sets its own TLS mode, so the checked sslmode is not passed on. @@ -1416,8 +1417,23 @@ fn admin_config_with_resolver( config.ssl_mode(SslMode::Disable); } DatabaseTransport::PrivateNetworkPlaintext => { - config = registry_platform_postgres::connection_for_transport(config, transport, resolve) - .map_err(|_| anyhow!("the PostgreSQL admin URL with private-network-plaintext must resolve only to permitted private or loopback addresses"))?; + let lookup_failed = Cell::new(false); + let checked_resolver = |host: &str| { + let result = resolve(host); + lookup_failed.set(result.as_ref().map_or(true, Vec::is_empty)); + result + }; + config = registry_platform_postgres::private_development_postgres_connection( + config, + &checked_resolver, + ) + .map_err(|_| { + if lookup_failed.get() { + anyhow!("could not resolve the PostgreSQL admin host for private-network-plaintext") + } else { + anyhow!("the PostgreSQL admin URL with private-network-plaintext must resolve only to permitted private or loopback addresses") + } + })?; config.ssl_mode(SslMode::Disable); } } @@ -2059,6 +2075,17 @@ mod tests { endpoint.product_url("owned", "runtime", "pw").unwrap(), "postgresql://runtime:pw@172.20.0.7:5432/owned?sslmode=disable" ); + let (explicit, selected) = + admin_config_with_resolver(&format!("{url}&sslmode=disable"), &move |_| { + Ok(vec![private]) + }) + .unwrap(); + assert_eq!(explicit.get_ssl_mode(), SslMode::Disable); + assert_eq!(explicit.get_hostaddrs(), &[private]); + assert_eq!( + selected.transport, + DatabaseTransport::PrivateNetworkPlaintext + ); for addresses in [ vec![private, std::net::IpAddr::from([203, 0, 113, 1])], vec![std::net::IpAddr::from([169, 254, 169, 254])], @@ -2082,6 +2109,61 @@ mod tests { .is_err()); } + #[test] + fn private_admin_url_distinguishes_lookup_failure_from_refused_addresses() { + let base = + "postgresql://admin:synthetic-url-value@postgres.compose:5432/postgres?transport="; + for value in ["", "loopback-plaintext", "verified-tls"] { + assert!(admin_config_with_resolver(&format!("{base}{value}"), &|_| { + panic!("an invalid selector must be refused before lookup"); + }) + .is_err()); + } + let url = format!("{base}private-network-plaintext"); + let failure = admin_config_with_resolver(&url, &|_| { + Err(std::io::Error::other("synthetic-private-dns-error")) + }) + .err() + .unwrap() + .to_string(); + assert!(failure.contains("could not resolve"), "{failure}"); + assert!(!failure.contains("synthetic"), "{failure}"); + let refusal = + admin_config_with_resolver(&url, &|_| Ok(vec!["203.0.113.1".parse().unwrap()])) + .err() + .unwrap(); + assert!(refusal + .to_string() + .contains("permitted private or loopback addresses")); + } + + #[test] + fn private_plaintext_tries_checked_candidates_in_order_and_pins_the_winner() { + let url = "postgresql://admin:synthetic-url-value@postgres.compose:5432/postgres?transport=private-network-plaintext"; + let addresses = ["172.20.0.7", "172.20.0.9", "172.20.0.11"].map(|ip| ip.parse().unwrap()); + let (checked, _) = + admin_config_with_resolver(url, &move |_| Ok(addresses.to_vec())).unwrap(); + let mut attempted = Vec::new(); + let (config, endpoint, ()) = + open_plaintext_candidates(url, checked.get_hostaddrs(), |config| { + let [address] = config.get_hostaddrs() else { + panic!("expected one checked candidate") + }; + attempted.push(*address); + if *address == addresses[0] { + bail!("first address refused") + } + Ok(()) + }) + .unwrap(); + assert_eq!(attempted, &addresses[..2]); + assert_eq!(config.get_hostaddrs(), &addresses[1..2]); + assert_eq!( + endpoint.product_url("owned", "runtime", "pw").unwrap(), + "postgresql://runtime:pw@172.20.0.9:5432/owned?sslmode=disable" + ); + } + #[test] fn spatial_runs_are_refused_without_a_supported_postgis() { assert!(require_postgis(Some("3.5.2")).is_ok()); @@ -2975,7 +3057,7 @@ mod postgres_tests { } } -/// Loopback plaintext attach against a real server without TLS. +/// Explicit plaintext attach against a real server without TLS. /// `RSTACK_DEV_TEST_PLAINTEXT_DATABASE_URL` names a disposable loopback /// PostgreSQL administrator URL with `?sslmode=disable`. Without the variable /// the test fails on the spot: a skipped database test is not database @@ -3032,5 +3114,35 @@ mod plaintext_postgres_tests { .cleanup() .expect("cleanup drops every provisioned database and role"); assert!(database.pending_names().is_empty()); + drop(database); + + // The workflow selects this test by its existing name. Exercise the + // private selector against the same disposable server on loopback. + let mut private_url = Url::parse(&admin_url).unwrap(); + private_url + .query_pairs_mut() + .append_pair("transport", "private-network-plaintext"); + let mut database = Database::connect(private_url.as_str(), None, &run_id) + .expect("attach over the explicitly selected private transport"); + let urls = database.provision("documents", false, false).unwrap(); + assert_eq!(urls.transport, DatabaseTransport::PrivateNetworkPlaintext); + let recorded_identity = database.recovery_identity().clone(); + let mut different_cluster = recorded_identity.clone(); + different_cluster.system_identifier ^= 1; + let names = database.pending_names(); + assert!(!names.is_empty()); + drop(database); + let refusal = + Database::connect_for_recovery(private_url.as_str(), None, &run_id, &different_cluster) + .err() + .expect("a different cluster cannot take over the run"); + assert!(format!("{refusal:#}").contains("different PostgreSQL cluster")); + let mut recovery = + Database::connect_for_recovery(private_url.as_str(), None, &run_id, &recorded_identity) + .expect("recover the private attachment from the recorded cluster"); + recovery.adopt("documents", false).unwrap(); + assert_eq!(recovery.pending_names(), names); + recovery.cleanup().unwrap(); + assert!(recovery.pending_names().is_empty()); } } diff --git a/crates/registry-rstack-dev/src/products.rs b/crates/registry-rstack-dev/src/products.rs index f828e66af4..bf6411e885 100644 --- a/crates/registry-rstack-dev/src/products.rs +++ b/crates/registry-rstack-dev/src/products.rs @@ -4688,6 +4688,21 @@ mod tests { ); assert_eq!(plaintext["database"]["transport"], "loopback-plaintext"); assert!(plaintext["database"].get("caBundleRef").is_none()); + + let private = casework_config( + &runner.input.plan, + "casework", + &root, + &package, + &identity, + "127.0.0.1:0", + DatabaseTransport::PrivateNetworkPlaintext, + ); + assert_eq!( + private["database"]["transport"], + "private-network-plaintext" + ); + assert!(private["database"].get("caBundleRef").is_none()); } #[test] diff --git a/docs/site/src/content/docs/configure/run-a-project-with-rstack-dev.mdx b/docs/site/src/content/docs/configure/run-a-project-with-rstack-dev.mdx index facc3555e7..41a1b4d7ac 100644 --- a/docs/site/src/content/docs/configure/run-a-project-with-rstack-dev.mdx +++ b/docs/site/src/content/docs/configure/run-a-project-with-rstack-dev.mdx @@ -543,9 +543,13 @@ For a local server on a loopback host (`127.0.0.1`, `::1`, or `localhost` resolv Generated product runtime configurations then use `database.transport: loopback-plaintext`. If the runner and PostgreSQL share a private development network, such as a Docker Compose network, you can select `?transport=private-network-plaintext` explicitly. +The connection is unencrypted and the PostgreSQL server is unauthenticated. +Use this transport for disposable, synthetic data on an operator-isolated development network. +Use verified TLS for shared, hosted or routed CI networks. The runner checks that every resolved address is eligible for private network plaintext and connects to one of those addresses directly. Generated product runtime configurations use `database.transport: private-network-plaintext` and the same address. Leave `RSTACK_DEV_DATABASE_CA` unset for either plaintext transport. +On recovery, PostgreSQL reports its own cluster identifier. The check catches a wrong-cluster setup during recovery. With Compose, give PostgreSQL a health check and wait for it to pass before running `rstack dev start`. For example, run `docker compose up -d --wait postgres` when the service is named `postgres`. diff --git a/products/platform/CHANGELOG.md b/products/platform/CHANGELOG.md index c8768fa0a8..6cba08e2f4 100644 --- a/products/platform/CHANGELOG.md +++ b/products/platform/CHANGELOG.md @@ -2,6 +2,12 @@ ## Unreleased +- `rstack dev` can attach to PostgreSQL on an isolated development network + when the administrator URL selects `transport=private-network-plaintext`. + The runner pins the checked numeric address in the generated product URLs. + Verified TLS remains the default. Production and `provision` keep their + existing transport rules. + ## 0.50.0 - 2026-12-01 - BREAKING: Projects with authored development people must replace their grants with roles defined in `service.yaml` and assigned under `people..roles` in `dev.yaml`. See the [Stack migration notes](../../release/notes/v0.50.0.md#service-roles). From dba70df69e4aaf26cc0df6e134340fbd10edb4a7 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 17:57:30 +0000 Subject: [PATCH 038/183] fix(dev): exercise saved report refusals in strict conformance Signed-off-by: Jeremi Joslin --- crates/registry-rstack-dev/src/lib.rs | 10 +- .../registry-rstack-dev/src/owner_report.rs | 359 ++++++++++++------ .../src/owner_report_tests.rs | 69 +++- crates/registry-rstack/src/cli.rs | 31 +- .../reports/identity-facts-report.json | 18 + products/platform/CONFIG-CONVENTIONS.md | 3 + products/platform/config-formats.yaml | 2 +- .../scripts/check-config-conventions.py | 9 +- .../scripts/run-config-conformance.py | 35 +- .../scripts/test_check_config_conventions.py | 6 + .../scripts/test_run_config_conformance.py | 39 ++ 11 files changed, 446 insertions(+), 135 deletions(-) create mode 100644 products/casework/examples/formats/reports/identity-facts-report.json diff --git a/crates/registry-rstack-dev/src/lib.rs b/crates/registry-rstack-dev/src/lib.rs index 667bf3b685..8ddc19f915 100644 --- a/crates/registry-rstack-dev/src/lib.rs +++ b/crates/registry-rstack-dev/src/lib.rs @@ -121,7 +121,7 @@ pub struct Args { enum Entry { Check { /// Refuse unaccepted warnings. Development posture listings do not count. - #[arg(long, conflicts_with = "owner_report_format")] + #[arg(long)] deny_warnings: bool, #[arg(long)] json: bool, @@ -616,7 +616,13 @@ pub fn run(args: Args, stdout: &mut dyn Write, stderr: &mut dyn Write) -> ExitCo owner_report_format, } => { if let Some(format) = owner_report_format { - let (report, exit) = owner_report::check_file(&project, format); + let (report, mut exit) = owner_report::check_file(&project, format); + if exit == 0 + && deny_warnings + && registry_platform_config::has_denied_warnings(report.diagnostics()) + { + exit = DOMAIN_REFUSAL_EXIT; + } return ExitCode::from(write_check_report( report, exit, json, stdout, stderr, true, )); diff --git a/crates/registry-rstack-dev/src/owner_report.rs b/crates/registry-rstack-dev/src/owner_report.rs index 4cd409be95..e825a2b4b2 100644 --- a/crates/registry-rstack-dev/src/owner_report.rs +++ b/crates/registry-rstack-dev/src/owner_report.rs @@ -3,17 +3,18 @@ //! Structural read-back of bounded saved JSON reports. use jsonschema::{ - error::ErrorIterator, + error::{ErrorIterator, ValidationErrorKind}, paths::{JSONPointer, JsonPointerNode, PathChunk}, Draft, JSONSchema, Keyword, ValidationError, }; use registry_platform_yaml::{ - ApiVersion, Diagnostic, EnvelopeRule, Expect, FormatSpec, Reader, Report, Source, - MAXIMUM_DOCUMENT_BYTES, + escape_pointer_segment, ApiVersion, Diagnostic, Document, EnvelopeRule, Expect, FormatSpec, + Reader, Report, Severity, Source, MAXIMUM_DOCUMENT_BYTES, }; use serde_json::{json, Value}; use std::{ - collections::BTreeMap, + borrow::Cow, + collections::{BTreeMap, BTreeSet}, fs::OpenOptions, io::{self, Read}, os::unix::fs::OpenOptionsExt, @@ -41,7 +42,8 @@ pub(crate) enum Format { #[derive(Debug)] pub(crate) struct Invalid { path: String, - message: &'static str, + code: &'static str, + message: Cow<'static, str>, position: Option<(usize, usize)>, schema_unavailable: bool, } @@ -50,11 +52,36 @@ impl Invalid { fn at(path: impl Into, message: &'static str) -> Self { Self { path: path.into(), - message, + code: "rstack.dev.owner-report-invalid", + message: Cow::Borrowed(message), position: None, schema_unavailable: false, } } + + fn into_report(self, file: &str) -> (Report, u8) { + let (exit, code, remedy) = if self.schema_unavailable { + ( + crate::OPERATIONAL_FAILURE_EXIT, + "rstack.dev.owner-report-schema-unavailable", + "Use an rstack development host with a valid embedded owner report schema.", + ) + } else { + (crate::DOMAIN_REFUSAL_EXIT, self.code, FORMAT_REMEDY) + }; + let mut diagnostic = Diagnostic::error(code, self.path, self.message, remedy); + diagnostic.artifact = Some(CASEWORK_FORMAT.kind.to_owned()); + diagnostic.source = Some(Source { + file: file.to_owned(), + line: self.position.map(|(line, _)| line), + column: self + .position + .and_then(|(_, column)| (column > 0).then_some(column)), + }); + let mut report = Report::new(vec![diagnostic]); + report.set_files_checked(1); + (report, exit) + } } fn parse(bytes: &[u8]) -> Result { @@ -63,47 +90,99 @@ fn parse(bytes: &[u8]) -> Result { } registry_platform_canonical_json::parse_json_preserving_integers(bytes).map_err(|error| { Invalid { - path: String::new(), - message: "Expected one valid JSON document with unique member names", - position: (error.line() > 0).then_some((error.line(), error.column())), - schema_unavailable: false, + position: parse_position(bytes, error.line(), error.column()), + ..Invalid::at( + "", + "Expected one valid JSON document with unique member names", + ) } }) } -fn decode(bytes: &[u8], format: Format) -> Result { - let report = parse(bytes)?; +fn parse_position(bytes: &[u8], line: usize, byte_column: usize) -> Option<(usize, usize)> { + let line_bytes = bytes + .split(|byte| *byte == b'\n') + .nth(line.checked_sub(1)?)?; + let prefix = &line_bytes[..byte_column.saturating_sub(1).min(line_bytes.len())]; + Some((line, String::from_utf8_lossy(prefix).chars().count() + 1)) +} + +fn check_bytes(file: &str, bytes: &[u8], format: Format) -> (Report, u8) { + let report = match parse(bytes) { + Ok(report) => report, + Err(error) => return error.into_report(file), + }; let expected = match format { Format::CaseworkReport => &CASEWORK_FORMAT, }; // The JSON parser enforces the declared syntax. The shared reader checks - // the envelope and document limits. Its diagnostics can name user input, - // so only positions and known envelope fields reach this command's report. - Reader::new("owner report") - .read(bytes, &Expect::one(expected)) - .map_err(|report| { - let mut invalid = Invalid::at( - "", - "Expected a valid CaseworkReport v1alpha2 envelope and document", - ); - if let Some(first) = report.diagnostics().first() { - if matches!(first.path.as_str(), "/kind" | "/apiVersion") { - invalid.path.clone_from(&first.path); - } - invalid.position = first - .source - .as_ref() - .and_then(|source| source.line.zip(source.column)); - } - invalid - })?; - validate(&report, format)?; - Ok(report) + // the envelope and retains positions for every schema diagnostic. + let document = match Reader::new(file).read(bytes, &Expect::one(expected)) { + Ok(document) => document, + Err(mut report) => { + redact_structure(&mut report); + return (report, crate::DOMAIN_REFUSAL_EXIT); + } + }; + let issues = match validate(&report, format, Some(&document)) { + Ok(issues) => issues, + Err(error) => return error.into_report(file), + }; + let mut report = document.report_with(issues.into_iter().map(|issue| { + let mut diagnostic = document.diagnostic_at_value( + Severity::Error, + issue.code, + &issue.path, + &issue.message, + FORMAT_REMEDY, + ); + if let (Some((line, column)), Some(source)) = (issue.position, &mut diagnostic.source) { + source.line = Some(line); + source.column = Some(column); + } + diagnostic + })); + redact_warnings(&mut report); + let exit = u8::from(report.has_errors()); + (report, exit) +} + +const FORMAT_REMEDY: &str = + "Select the matching owner report format and capture a fresh report as JSON."; + +fn redact_structure(report: &mut Report) { + for diagnostic in report.diagnostics_mut() { + if diagnostic.code == "config.too-many-problems" { + continue; + } + if !matches!(diagnostic.path.as_str(), "/kind" | "/apiVersion") { + diagnostic.path.clear(); + } + diagnostic.message = + "Expected a valid CaseworkReport v1alpha2 envelope and document".to_owned(); + diagnostic.suggested_action = FORMAT_REMEDY.to_owned(); + diagnostic.related.clear(); + } } -fn validate(report: &Value, format: Format) -> Result<(), Invalid> { +fn redact_warnings(report: &mut Report) { + for diagnostic in report.diagnostics_mut() { + if diagnostic.severity == Severity::Warning { + diagnostic.path.clear(); + diagnostic.message = "Owner report uses a deprecated document form".to_owned(); + diagnostic.suggested_action = FORMAT_REMEDY.to_owned(); + diagnostic.related.clear(); + } + } +} + +fn validate( + report: &Value, + format: Format, + document: Option<&Document>, +) -> Result, Invalid> { match format { - Format::CaseworkReport => validate_casework(report), + Format::CaseworkReport => validate_casework(report, document), } } @@ -112,7 +191,7 @@ struct CaseworkSchemas { branches: BTreeMap, } -fn validate_casework(report: &Value) -> Result<(), Invalid> { +fn validate_casework(report: &Value, document: Option<&Document>) -> Result, Invalid> { static SCHEMAS: OnceLock> = OnceLock::new(); let schemas = SCHEMAS.get_or_init(|| { let mut schema: Value = serde_json::from_str(CASEWORK).ok()?; @@ -146,17 +225,25 @@ fn validate_casework(report: &Value) -> Result<(), Invalid> { let schemas = schemas.as_ref().ok_or_else(schema_unavailable)?; let branch = report["command"] .as_str() - .and_then(|command| schemas.branches.get(command)) - .ok_or_else(|| { - Invalid::at( - "/command", - "Expected a command from the Casework report contract", - ) - })?; + .and_then(|command| schemas.branches.get(command)); + let Some(branch) = branch else { + return Ok(vec![Invalid::at( + if report.get("command").is_some() { + "/command" + } else { + "" + }, + "Expected a command from the Casework report contract", + )]); + }; // Validate the selected branch first to retain its field-level diagnostics. // The family also imposes shared completion and refusal rules at the root. - branch.validate(report, "")?; - schemas.family.validate(report, "") + let issues = branch.issues(report, "", document); + if issues.is_empty() { + Ok(schemas.family.issues(report, "", document)) + } else { + Ok(issues) + } } fn schema_unavailable() -> Invalid { @@ -175,36 +262,96 @@ struct Schema { } impl Schema { - fn validate(&self, value: &Value, prefix: &str) -> Result<(), Invalid> { + fn issues(&self, value: &Value, prefix: &str, document: Option<&Document>) -> Vec { if self.validator.is_valid(value) { - return Ok(()); + return Vec::new(); } let fallback = || Invalid::at(prefix, "Owner report violates the selected schema"); - // The detailed validator eagerly collects child errors for array items. - // Bound the tree and text it can inspect before requesting even one error. + // Detailed validation eagerly collects child errors for array items. let mut nodes = MAX_DIAGNOSTIC_NODES; let mut text_bytes = MAX_DIAGNOSTIC_TEXT_BYTES; if !fits_diagnostic_budget(value, &mut nodes, &mut text_bytes) { - return Err(fallback()); + return vec![fallback()]; } - let Some(error) = self - .validator - .validate(value) - .err() - .and_then(|mut errors| errors.next()) - else { - return Err(fallback()); + let Err(errors) = self.validator.validate(value) else { + return vec![fallback()]; }; - let message = match error.kind { - jsonschema::error::ValidationErrorKind::Custom { .. } => { - "Expected a native JSON integer within the field's bounds" + let mut issues = Vec::new(); + let mut seen = BTreeSet::new(); + for error in errors { + let path = self.diagnostic_path(prefix, &error.instance_path); + let raw_parent = error.instance_path.to_string(); + if let ValidationErrorKind::AdditionalProperties { unexpected } = &error.kind { + for key in unexpected { + // Use the unknown key to locate it, then report only the safe parent. + let raw = format!("{raw_parent}/{}", escape_pointer_segment(key)); + let position = document + .and_then(|doc| doc.key_span_of(&raw)) + .map(|span| (span.start.line, span.start.column)); + let issue = Invalid { + code: "config.unknown-key", + position, + ..Invalid::at( + path.clone(), + "Owner report contains a member outside the selected schema", + ) + }; + issues.push(issue); + } + continue; } - _ => "Owner report violates the selected schema at this location", - }; - Err(Invalid::at( - self.diagnostic_path(prefix, &error.instance_path), - message, - )) + let mut issue = Invalid::at( + path, + "Owner report violates the selected schema at this location", + ); + issue.position = document + .and_then(|doc| doc.span_of(&raw_parent)) + .map(|span| (span.start.line, span.start.column)); + match &error.kind { + ValidationErrorKind::Minimum { .. } + | ValidationErrorKind::Maximum { .. } + | ValidationErrorKind::Custom { .. } => { + if let Some((minimum, maximum)) = self.error_integer_bounds(&error) { + issue.code = if integer(&error.instance).is_some() { + "config.out-of-range" + } else { + "config.wrong-type" + }; + issue.message = + format!("Expected a JSON integer from {minimum} to {maximum}").into(); + } + } + ValidationErrorKind::Required { property } => { + issue.code = "config.missing-key"; + if let Some(key) = property.as_str() { + issue.message = format!("Owner report requires the {key} member").into(); + } + issue.position = document + .and_then(|doc| doc.key_span_of(&raw_parent)) + .map(|span| (span.start.line, span.start.column)) + .or(issue.position); + } + _ => {} + } + if seen.insert(( + issue.path.clone(), + issue.position, + issue.code, + issue.message.clone(), + )) { + issues.push(issue); + } + } + issues + } + + fn error_integer_bounds(&self, error: &ValidationError<'_>) -> Option<(i128, i128)> { + let schema_path = error.schema_path.to_string(); + let (parent, _) = schema_path.rsplit_once('/')?; + let schema = self.document.pointer(parent)?.as_object()?; + schema + .contains_key(EXACT_INTEGER) + .then(|| exact_integer_bounds(schema)) } fn diagnostic_path(&self, prefix: &str, instance_path: &JSONPointer) -> String { @@ -223,7 +370,7 @@ impl Schema { }; schema = child; path.push('/'); - path.push_str(&name.replace('~', "~0").replace('/', "~1")); + path.push_str(&escape_pointer_segment(name)); } PathChunk::Index(index) => { let Some(child) = resolved["prefixItems"] @@ -357,6 +504,20 @@ fn exact_integer<'a>( _: &'a Value, path: JSONPointer, ) -> Result, ValidationError<'a>> { + let (minimum, maximum) = exact_integer_bounds(parent); + let nullable = parent + .get("type") + .and_then(Value::as_array) + .is_some_and(|types| types.iter().any(|ty| ty == "null")); + Ok(Box::new(ExactInteger { + path, + minimum, + maximum, + nullable, + })) +} + +fn exact_integer_bounds(parent: &serde_json::Map) -> (i128, i128) { let minimum = parent .get("minimum") .and_then(integer) @@ -368,16 +529,7 @@ fn exact_integer<'a>( if parent.get("format").and_then(Value::as_str) == Some("uint") { maximum = maximum.min(usize::MAX as i128); } - let nullable = parent - .get("type") - .and_then(Value::as_array) - .is_some_and(|types| types.iter().any(|ty| ty == "null")); - Ok(Box::new(ExactInteger { - path, - minimum, - maximum, - nullable, - })) + (minimum, maximum) } impl Keyword for ExactInteger { @@ -414,38 +566,27 @@ pub(crate) fn check_file(path: &Path, format: Format) -> (Report, u8) { .read_to_end(&mut bytes)?; Ok(bytes) }); - let (invalid, exit, code, remedy) = match bytes { - Ok(bytes) => match decode(&bytes, format) { - Ok(_) => return (Report::new(Vec::new()), 0), - Err(error) if error.schema_unavailable => ( - error, + let file = path.to_string_lossy(); + match bytes { + Ok(bytes) => check_bytes(&file, &bytes, format), + Err(_) => { + let mut diagnostic = Diagnostic::error( + "rstack.dev.owner-report-unreadable", + "", + "Cannot read the owner report as a regular file", + "Pass a readable regular JSON file to --owner-report.", + ); + diagnostic.source = Some(Source { + file: file.into_owned(), + line: None, + column: None, + }); + ( + Report::new(vec![diagnostic]), crate::OPERATIONAL_FAILURE_EXIT, - "rstack.dev.owner-report-schema-unavailable", - "Use an rstack development host with a valid embedded owner report schema.", - ), - Err(error) => ( - error, - crate::DOMAIN_REFUSAL_EXIT, - "rstack.dev.owner-report-invalid", - "Select the matching owner report format and capture a fresh report as JSON.", - ), - }, - Err(_) => ( - Invalid::at("", "Cannot read the owner report as a regular file"), - crate::OPERATIONAL_FAILURE_EXIT, - "rstack.dev.owner-report-unreadable", - "Pass a readable regular JSON file to --owner-report.", - ), - }; - let mut diagnostic = Diagnostic::error(code, invalid.path, invalid.message, remedy); - diagnostic.source = Some(Source { - file: path.display().to_string(), - line: invalid.position.map(|(line, _)| line), - column: invalid - .position - .and_then(|(_, column)| (column > 0).then_some(column)), - }); - (Report::new(vec![diagnostic]), exit) + ) + } + } } #[cfg(test)] diff --git a/crates/registry-rstack-dev/src/owner_report_tests.rs b/crates/registry-rstack-dev/src/owner_report_tests.rs index cedb7ad82a..b49ae3a350 100644 --- a/crates/registry-rstack-dev/src/owner_report_tests.rs +++ b/crates/registry-rstack-dev/src/owner_report_tests.rs @@ -5,6 +5,15 @@ use super::*; const CASEWORK: &str = include_str!("../../../products/casework/examples/formats/reports/check-report.json"); +fn decode(bytes: &[u8], format: Format) -> Result<(), Diagnostic> { + let (report, exit) = check_bytes("synthetic.json", bytes, format); + if exit == 0 { + Ok(()) + } else { + Err(report.into_diagnostics().into_iter().next().unwrap()) + } +} + #[test] fn casework_checks_resolved_branch_and_exact_numeric_tokens() { let report = |count: &str| { @@ -135,6 +144,60 @@ fn hosted_file_check_reports_structure_and_redacts_parser_errors() { ); } +#[test] +fn saved_report_retains_positions_and_numeric_bounds_without_echoing_input() { + let file = tempfile::NamedTempFile::new().unwrap(); + let source = CASEWORK + .replace("\"filesChecked\": 1", "\"filesChecked\": -918204") + .replace( + "\"networkAccess\": false", + "\"networkAccess\": \"synthetic-private-value\"", + ); + std::fs::write(file.path(), source).unwrap(); + let (report, exit) = check_file(file.path(), Format::CaseworkReport); + assert_eq!(exit, 1); + assert_eq!(report.error_count(), 2); + let diagnostics = report.diagnostics(); + assert_eq!(diagnostics[0].code, "config.out-of-range"); + assert_eq!(diagnostics[0].path, "/filesChecked"); + assert!(diagnostics[0].message.contains(&usize::MAX.to_string())); + let position = diagnostics[0].source.as_ref().unwrap(); + assert_eq!((position.line, position.column), (Some(9), Some(19))); + assert_eq!(diagnostics[1].path, "/networkAccess"); + assert_eq!(diagnostics[1].source.as_ref().unwrap().line, Some(10)); + let output = report.render_human(); + assert!(!output.contains("-918204")); + assert!(!output.contains("synthetic-private-value")); +} + +#[test] +fn saved_report_retains_unknown_key_locations_and_all_envelope_refusals() { + let source = CASEWORK.replace( + "\"version\": \"0.49.0-dev\"", + "\"version\": \"0.49.0-dev\",\n \"private-canary-one\": true,\n \"private-canary-two\": false", + ); + let (report, exit) = check_bytes("synthetic.json", source.as_bytes(), Format::CaseworkReport); + assert_eq!(exit, 1); + assert_eq!(report.error_count(), 2); + for (diagnostic, line) in report.diagnostics().iter().zip([8, 9]) { + let position = diagnostic.source.as_ref().unwrap(); + assert_eq!((position.line, position.column), (Some(line), Some(3))); + assert_eq!(diagnostic.code, "config.unknown-key"); + } + assert!(!report.render_human().contains("private-canary")); + + let source = CASEWORK.replace("CaseworkReport", "private-kind").replace( + "\"id.registrystack.org/formats/casework/report/v1alpha2\"", + "[\"private-version\"]", + ); + let (report, exit) = check_bytes("synthetic.json", source.as_bytes(), Format::CaseworkReport); + assert_eq!(exit, 1); + assert_eq!(report.error_count(), 2); + assert_eq!(report.diagnostics()[0].path, "/apiVersion"); + assert_eq!(report.diagnostics()[1].path, "/kind"); + assert!(!report.render_human().contains("private-")); +} + #[test] fn near_limit_invalid_diagnostics_use_the_generic_fallback() { let mut report: Value = serde_json::from_str(CASEWORK).unwrap(); @@ -154,7 +217,9 @@ fn near_limit_invalid_diagnostics_use_the_generic_fallback() { fn ordinary_diagnostics_retain_exact_field_locations() { let mut report: Value = serde_json::from_str(CASEWORK).unwrap(); report["policyBindings"][0]["digest"] = json!(false); - let error = validate(&report, Format::CaseworkReport).unwrap_err(); + let error = validate(&report, Format::CaseworkReport, None) + .unwrap() + .remove(0); assert_eq!(error.path, "/policyBindings/0/digest"); assert_eq!( error.message, @@ -175,7 +240,7 @@ fn dynamic_map_members_are_redacted_even_when_they_match_schema_names() { .unwrap(); for key in ["stage", "synthetic-private-map-key"] { let value = json!({"condition": {"fields": {(key): false}}}); - let error = schema.validate(&value, "").unwrap_err(); + let error = schema.issues(&value, "", None).remove(0); assert_eq!(error.path, "/condition/fields"); assert!(!format!("{error:?}").contains(key)); } diff --git a/crates/registry-rstack/src/cli.rs b/crates/registry-rstack/src/cli.rs index 31bc49f7a4..543b749c55 100644 --- a/crates/registry-rstack/src/cli.rs +++ b/crates/registry-rstack/src/cli.rs @@ -269,10 +269,15 @@ enum DevCommand { #[arg(value_name = "PROJECT", required_unless_present = "owner_report")] project: Option, /// Saved JSON report to check structurally. - #[arg(long, value_name = "FILE", conflicts_with_all = ["project", "deny_warnings"], requires = "owner_report_format")] + #[arg( + long, + value_name = "FILE", + conflicts_with = "project", + requires = "owner_report_format" + )] owner_report: Option, /// Exact saved document format. - #[arg(long, requires = "owner_report", conflicts_with_all = ["project", "deny_warnings"], value_parser = ["casework-report"])] + #[arg(long, requires = "owner_report", conflicts_with = "project", value_parser = ["casework-report"])] owner_report_format: Option, /// Refuse an unaccepted warning. /// Development posture listings do not count. @@ -2162,10 +2167,15 @@ fn dispatch_dev(cli: &Cli, action: &DevCommand, format: ReportFormat) -> Result< owner_report_format, deny_warnings, } => { + let mut options = deny_warnings + .then(|| OsString::from("--deny-warnings")) + .into_iter() + .collect::>(); if let (Some(file), Some(format)) = (owner_report, owner_report_format) { + options.push(option("owner-report-format", format.as_ref())); ( "check", - vec![option("owner-report-format", format.as_ref())], + options, file.as_os_str(), None, DevNeeds::any_host(), @@ -2176,10 +2186,7 @@ fn dispatch_dev(cli: &Cli, action: &DevCommand, format: ReportFormat) -> Result< .expect("clap requires a project or owner report"); ( "check", - deny_warnings - .then(|| OsString::from("--deny-warnings")) - .into_iter() - .collect(), + options, project.as_os_str(), None, DevNeeds::check(project), @@ -2597,7 +2604,8 @@ mod tests { "--owner-report", "./report.json", "--owner-report-format", - "casework-report" + "casework-report", + "--deny-warnings", ]) .is_ok()); for args in [ @@ -2618,13 +2626,6 @@ mod tests { "--owner-report-format", "casework-report", ], - &[ - "--deny-warnings", - "--owner-report", - "./report.json", - "--owner-report-format", - "casework-report", - ], ] { assert!(parse(args).is_err(), "{args:?}"); } diff --git a/products/casework/examples/formats/reports/identity-facts-report.json b/products/casework/examples/formats/reports/identity-facts-report.json new file mode 100644 index 0000000000..cdd4c57374 --- /dev/null +++ b/products/casework/examples/formats/reports/identity-facts-report.json @@ -0,0 +1,18 @@ +{ + "ok": true, + "command": "generate-identity-facts", + "status": "complete", + "apiVersion": "id.registrystack.org/formats/casework/report/v1alpha2", + "kind": "CaseworkReport", + "version": "0.49.0-dev", + "accessProfiles": 4, + "assertionIssuers": 0, + "claims": 1, + "output": "casework.identity-facts.yaml", + "product": "casework", + "posture": { + "value": "production", + "source": "default" + }, + "diagnostics": [] +} diff --git a/products/platform/CONFIG-CONVENTIONS.md b/products/platform/CONFIG-CONVENTIONS.md index 240194e1d5..c2b8f02f4d 100644 --- a/products/platform/CONFIG-CONVENTIONS.md +++ b/products/platform/CONFIG-CONVENTIONS.md @@ -45,6 +45,9 @@ In scope: maintained tool reads belongs in the read-back category. A saved writer report may register `passiveReport: true` when a maintained offline check validates it on read-back and its integers only observe completed work. + Register the `rstack dev check --owner-report` command and a saved writer + example with bounded integers. The corpus runs its baseline and both sides + of the integer boundary sweep with `--deny-warnings`. These cells must pass. A **build artifact** is a read-back format that its own product's build writes and reads again and that no one edits (the compiled package model in BReg's `package.json`). It is registered with `audience: generated` and diff --git a/products/platform/config-formats.yaml b/products/platform/config-formats.yaml index 56ef0beea9..30a46a43d1 100644 --- a/products/platform/config-formats.yaml +++ b/products/platform/config-formats.yaml @@ -1735,7 +1735,7 @@ formats: file: crates/registry-caseworkctl/src/report.rs symbol: write check: rstack dev check --owner-report {file} --owner-report-format casework-report - example: products/casework/examples/formats/reports/check-report.json + example: products/casework/examples/formats/reports/identity-facts-report.json conformance: none securityMembers: [] restrictingMembers: [] diff --git a/products/platform/scripts/check-config-conventions.py b/products/platform/scripts/check-config-conventions.py index f6e72ae124..2cfd646502 100644 --- a/products/platform/scripts/check-config-conventions.py +++ b/products/platform/scripts/check-config-conventions.py @@ -1587,14 +1587,19 @@ def check_registry(self, registry: dict) -> None: and isinstance(schema, dict) and isinstance(entry["reader"], dict) and isinstance(entry["check"], str) - and "{file}" in entry["check"] + and re.fullmatch( + r"rstack dev check --owner-report \{file\} --owner-report-format [a-z][a-z0-9-]*", + entry["check"], + ) + and isinstance(document, dict) and entry["securityMembers"] == entry["restrictingMembers"] == [] ): self.passive_reports.add(fid) else: self.error( f"{fid}: passiveReport requires true on a generated JSON writer report with a schema, " - "a reader and file check, and no build, security, or restricting members" + "a reader and offline rstack owner-report check, a saved example, " + "and no build, security, or restricting members" ) self.check_conformance(fid, entry, document, schema) self.check_members(fid, entry, schema) diff --git a/products/platform/scripts/run-config-conformance.py b/products/platform/scripts/run-config-conformance.py index 7a78f743fe..3dd3867e73 100644 --- a/products/platform/scripts/run-config-conformance.py +++ b/products/platform/scripts/run-config-conformance.py @@ -195,6 +195,8 @@ VARIABLE = "REGISTRY_CONFORMANCE_VALUE" UNSET_VARIABLE = "REGISTRY_CONFORMANCE_UNSET" BASELINE = "baseline" +INTEGER_BOUNDARY_SWEEP = "integer-boundary-sweep" +PASSIVE_REPORT_CASES = frozenset((BASELINE, INTEGER_BOUNDARY_SWEEP)) TIMEOUT_SECONDS = 120 CODE = re.compile(r"^[a-z0-9]+(-[a-z0-9]+)*(\.[a-z0-9]+(-[a-z0-9]+)*)+$") @@ -376,6 +378,7 @@ class Format: harness: dict[str, Any] schema: str | None = None schema_id: str | None = None + passive_report: bool = False def with_harness(self, harness: dict[str, Any]) -> "Format": return dataclasses.replace(self, harness=dict(harness)) @@ -1319,7 +1322,7 @@ def resolve_expected( # Reports -def parse_report(stdout: str) -> tuple[list[Any] | None, list[str]]: +def parse_report(stdout: str, *, passive: bool = False) -> tuple[list[Any] | None, list[str]]: text = stdout.strip() if not text: return None, [NO_REPORT] @@ -1329,6 +1332,8 @@ def parse_report(stdout: str) -> tuple[list[Any] | None, list[str]]: return None, [NOT_ONE_DOCUMENT] if not isinstance(value, dict): return None, [NOT_AN_OBJECT] + if passive and value.get("assessment") != "owner-report-structure": + return None, ["the JSON report has no owner-report-structure assessment"] diagnostics = value.get("diagnostics") if not isinstance(diagnostics, list): return None, [NO_DIAGNOSTICS] @@ -1576,6 +1581,8 @@ def sanitize(text: str, work: str) -> str: def not_applicable(case: Case, fmt: Format) -> str | None: """Why a case does not apply to a format, or None when it does.""" + if fmt.passive_report and case.id not in PASSIVE_REPORT_CASES: + return "a passive JSON report runs the baseline and integer boundary sweep" audiences = case.applies_to.get("audiences") if audiences and fmt.audience not in audiences: return f"the case applies to {' and '.join(audiences)} files" @@ -1596,7 +1603,7 @@ def partition_formats(formats: list[Format]) -> tuple[list[Format], dict[str, st skipped[fmt.id] = "no check command" elif not fmt.example: skipped[fmt.id] = "no example" - elif fmt.syntax != "yaml": + elif fmt.syntax != "yaml" and not (fmt.syntax == "json" and fmt.passive_report): skipped[fmt.id] = f"syntax {fmt.syntax}; the corpus mutates YAML text" else: reached.append(fmt) @@ -1803,6 +1810,7 @@ def load_registry(path: Path) -> list[Format]: harness={}, schema=str(root / schema["path"]) if isinstance(schema.get("path"), str) else None, schema_id=schema["id"] if isinstance(schema.get("id"), str) else None, + passive_report=entry.get("passiveReport") is True, ) ) return formats @@ -2067,7 +2075,7 @@ def check_variant( problems += marker_problems(stdout, stderr) posture_warnings = 0 if case.expect.get("report", True): - diagnostics, report = parse_report(stdout.decode("utf-8", "replace")) + diagnostics, report = parse_report(stdout.decode("utf-8", "replace"), passive=fmt.passive_report) problems += report if diagnostics is not None: compared = diagnostics @@ -2267,7 +2275,16 @@ def plan(root: Path, formats: list[Format], cases: list[Case], harness: dict[str swept: dict[str, dict[str, Case]] = {case.id: {} for case in cases} for fmt in reached: text = prepare_example((root / str(fmt.example)).read_text(encoding="utf-8"), fmt, {}) + if fmt.passive_report: + try: + json.loads(text) + except ValueError: + raise HarnessError(f"{fmt.id}: the passive report example is not JSON") from None for case in cases: + if fmt.passive_report and case.id in PASSIVE_REPORT_CASES: + case = dataclasses.replace( + case, args=[*case.args, "--deny-warnings"], human=case.id == INTEGER_BOUNDARY_SWEEP, + ) why = not_applicable(case, fmt) variants = [] if why is None and case.run is None: @@ -2276,6 +2293,8 @@ def plan(root: Path, formats: list[Format], cases: list[Case], harness: dict[str except NotApplicable as error: why = str(error) if why is not None: + if fmt.passive_report and case.id in PASSIVE_REPORT_CASES: + raise HarnessError(f"{fmt.id}: passive report must exercise {case.id}: {why}") inapplicable[(fmt.id, case.id)] = why elif case.operation == SWEEP: for variant in variants: @@ -2311,6 +2330,9 @@ def validate_ids( """ format_ids = {fmt.id for fmt in formats} case_ids = {case.id for case in cases} + passive = {fmt.id for fmt in formats if fmt.passive_report} + if passive and not PASSIVE_REPORT_CASES <= case_ids: + raise HarnessError("the corpus needs the baseline and integer boundary sweep for passive reports") for format_id in harness: if only_formats is not None and format_id not in only_formats: continue @@ -2321,6 +2343,8 @@ def validate_ids( continue if format_id not in format_ids: raise HarnessError(f"expected-failures.yaml names format {format_id}, which the registry does not") + if format_id in passive: + raise HarnessError(f"passive report {format_id} cannot have an expected-failure waiver") if not names_case(case_id, cases): raise HarnessError(f"expected-failures.yaml names case {case_id}, which the corpus does not") for format_id in expected.unreached: @@ -2328,6 +2352,8 @@ def validate_ids( continue if format_id not in format_ids: raise HarnessError(f"expected-failures.yaml names format {format_id}, which the registry does not") + if format_id in passive: + raise HarnessError(f"passive report {format_id} cannot have an unreached waiver") for case_id in expected.inapplicable: if case_id not in case_ids: raise HarnessError(f"expected-failures.yaml names case {case_id}, which the corpus does not") @@ -2426,8 +2452,9 @@ def report( if args.write_expected_failures: failures, refused = {}, [] + passive = {fmt.id for fmt in work.reached if fmt.passive_report} for cell, problems in results.items(): - if any(unmaskable(problem) for problem in problems): + if problems and (cell[0] in passive or any(unmaskable(problem) for problem in problems)): refused.append(cell) elif problems: failures[cell] = Listed(reason(problems), digest(problems)) diff --git a/products/platform/scripts/test_check_config_conventions.py b/products/platform/scripts/test_check_config_conventions.py index c99ca00b03..d4d0b95a46 100644 --- a/products/platform/scripts/test_check_config_conventions.py +++ b/products/platform/scripts/test_check_config_conventions.py @@ -1222,6 +1222,12 @@ def test_cfg_qty_4_passive_report_flag_cannot_exempt_authored_config(self) -> No self.assertTrue(any("passiveReport requires" in error for error in report.errors)) self.assertFinding(report, "CFG-QTY-4", R, at(REPORT_SCHEMA, "/properties/filesChecked")) + def test_cfg_qty_4_passive_report_requires_a_maintained_corpus_check(self) -> None: + self.passive_report()["check"] = "true {file}" + report = self.repo.run() + self.assertTrue(any("passiveReport requires" in error for error in report.errors)) + self.assertFinding(report, "CFG-QTY-4", R, at(REPORT_SCHEMA, "/properties/filesChecked")) + def test_cfg_qty_4_passive_report_still_requires_both_bounds(self) -> None: self.passive_report() fields = self.repo.report["properties"]["filesChecked"] diff --git a/products/platform/scripts/test_run_config_conformance.py b/products/platform/scripts/test_run_config_conformance.py index 10237499aa..51c376a8c8 100644 --- a/products/platform/scripts/test_run_config_conformance.py +++ b/products/platform/scripts/test_run_config_conformance.py @@ -2208,6 +2208,45 @@ def setUp(self) -> None: self.cases = runner.load_cases(self.corpus / "cases") self.registry = runner.load_registry(ROOT / runner.REGISTRY) + def test_passive_casework_report_has_a_positive_and_both_integer_controls(self) -> None: + fmt = next(fmt for fmt in self.registry if fmt.id == "casework/report") + plan = runner.plan(ROOT, [fmt], self.cases, runner.load_harness(self.corpus / "formats.yaml")) + self.assertEqual([fmt.id], [item.id for item in plan.reached]) + self.assertNotIn(fmt.id, plan.skipped) + cells = {case.id: case for _, case in plan.cells} + self.assertEqual(set(cells), {"baseline", "integer-boundary-sweep"}) + source = (ROOT / fmt.example).read_text(encoding="utf-8") + bounds = cells["integer-boundary-sweep"] + mutations = runner.mutate(source, bounds.mutation, fmt) + self.assertIn("--deny-warnings", bounds.args) + observed = {(mutation.sites[0].values["pointer"], json.loads(mutation.text)["claims"]) + for mutation in mutations if mutation.sites[0].values["pointer"] == "/claims"} + self.assertEqual(observed, {("/claims", -1), ("/claims", 4294967296)}) + + def test_passive_report_cannot_have_a_corpus_waiver(self) -> None: + fmt = next(fmt for fmt in self.registry if fmt.id == "casework/report") + for expected in ( + runner.ExpectedFailures({(fmt.id, "baseline"): runner.Listed("fixture", "test")}, {}, {}), + runner.ExpectedFailures({}, {fmt.id: "fixture"}, {}), + ): + with self.assertRaisesRegex(runner.HarnessError, "passive report.*cannot"): + runner.validate_ids(expected, self.registry, self.cases, {}) + + def test_passive_report_check_that_always_accepts_fails_the_executable_corpus(self) -> None: + with tempfile.TemporaryDirectory() as directory: + binary = Path(directory) / "rstack" + binary.write_text( + f"#!{sys.executable}\nprint('{{\"assessment\":\"owner-report-structure\",\"diagnostics\":[]}}')\n", + encoding="utf-8", + ) + binary.chmod(0o755) + stdout = io.StringIO() + with redirect_stdout(stdout): + exit_code = runner.main(["--bin-dir", directory, "--only-format", "casework/report", "--matrix"]) + self.assertEqual(exit_code, 1, stdout.getvalue()) + self.assertIn("casework/report\tbaseline\tpass", stdout.getvalue()) + self.assertIn("casework/report\tinteger-boundary-sweep\tfail", stdout.getvalue()) + def test_cfg_check_3_every_case_cites_known_rules(self) -> None: convention = (ROOT / "products/platform/CONFIG-CONVENTIONS.md").read_text(encoding="utf-8") known = set(re.findall(r"^\*\*(CFG-[A-Z]+-[0-9]+) \(", convention, re.MULTILINE)) From 47b5adaaf36cdee7cd219e65877ca3ff95e33516 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 18:03:25 +0000 Subject: [PATCH 039/183] fix(dev): classify private PostgreSQL lookup failures as operational Signed-off-by: Jeremi Joslin --- crates/registry-rstack-dev/src/database.rs | 29 ++++++++++++++++------ 1 file changed, 21 insertions(+), 8 deletions(-) diff --git a/crates/registry-rstack-dev/src/database.rs b/crates/registry-rstack-dev/src/database.rs index 440b2b18f7..318de38fd4 100644 --- a/crates/registry-rstack-dev/src/database.rs +++ b/crates/registry-rstack-dev/src/database.rs @@ -1429,7 +1429,9 @@ fn admin_config_with_resolver( ) .map_err(|_| { if lookup_failed.get() { - anyhow!("could not resolve the PostgreSQL admin host for private-network-plaintext") + super::operational(anyhow!( + "could not resolve the PostgreSQL admin host for private-network-plaintext" + )) } else { anyhow!("the PostgreSQL admin URL with private-network-plaintext must resolve only to permitted private or loopback addresses") } @@ -2124,17 +2126,28 @@ mod tests { Err(std::io::Error::other("synthetic-private-dns-error")) }) .err() - .unwrap() - .to_string(); - assert!(failure.contains("could not resolve"), "{failure}"); - assert!(!failure.contains("synthetic"), "{failure}"); + .unwrap(); let refusal = admin_config_with_resolver(&url, &|_| Ok(vec!["203.0.113.1".parse().unwrap()])) .err() .unwrap(); - assert!(refusal - .to_string() - .contains("permitted private or loopback addresses")); + for (error, code, class, message) in [ + (failure, 3, "operational", "could not resolve the PostgreSQL admin host for private-network-plaintext"), + (refusal, 1, "domain", "the PostgreSQL admin URL with private-network-plaintext must resolve only to permitted private or loopback addresses"), + ] { + let mut wire = Vec::new(); + crate::reply(&mut wire, &crate::WorkerReply::failed(&error)).unwrap(); + let crate::WorkerReply::Failed { error, operational } = serde_json::from_slice(&wire).unwrap() else { + panic!("a refused lookup must produce a worker failure"); + }; + let (report, exit_code) = crate::error_report(&crate::restore_failure(error, operational)); + assert_eq!(exit_code, code); + assert_eq!(report, serde_json::json!({ + "schema_version": "registry.rstack.error.v1", + "status": "refused", + "error": {"class": class, "message": message}, + })); + } } #[test] From 3c130b28b18a600a4f5125a2a403e256fae3e68e Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 18:01:36 +0000 Subject: [PATCH 040/183] fix(scheduling): verify starter freshness and fold dates Bracket fresh initialization with UTC dates so the checkpoint detects stale supply across midnight. Confirm the fixture fold against the shared timezone data before publishing either New York starter. Signed-off-by: Jeremi Joslin (cherry picked from commit 164b72adceba30031e92f55ac86328b2f1785998) --- Cargo.lock | 1 + crates/registry-schedulingctl/Cargo.toml | 1 + crates/registry-schedulingctl/src/project.rs | 26 ++++++++++- .../registry-schedulingctl/src/templates.rs | 39 ++++++++++++----- .../scheduling/scripts/check-checkpoint.sh | 43 +++++++++++++++++++ 5 files changed, 98 insertions(+), 12 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 70191da9f4..908cca90db 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -8560,6 +8560,7 @@ version = "0.50.0" dependencies = [ "anyhow", "chrono", + "chrono-tz", "clap", "registry-cli-api", "registry-cli-report", diff --git a/crates/registry-schedulingctl/Cargo.toml b/crates/registry-schedulingctl/Cargo.toml index 68618b181b..670ef6edbd 100644 --- a/crates/registry-schedulingctl/Cargo.toml +++ b/crates/registry-schedulingctl/Cargo.toml @@ -23,6 +23,7 @@ registry-rstack-dev.workspace = true registry-cli-report.workspace = true anyhow.workspace = true chrono.workspace = true +chrono-tz.workspace = true clap.workspace = true registry-cli-api.workspace = true registry-platform-audit.workspace = true diff --git a/crates/registry-schedulingctl/src/project.rs b/crates/registry-schedulingctl/src/project.rs index dbae9da77c..51aeb41a56 100644 --- a/crates/registry-schedulingctl/src/project.rs +++ b/crates/registry-schedulingctl/src/project.rs @@ -62,7 +62,7 @@ fn init_on(project: &Path, template: &str, today: NaiveDate) -> Result { fs::create_dir(staging.path().join(FIXTURES_DIRECTORY))?; let mut created = Vec::new(); for (relative, contents) in &files { - let contents = templates::date_file(template, relative, contents, today); + let contents = templates::date_file(template, relative, contents, today)?; fs::write(staging.path().join(relative), contents.as_bytes())?; created.push((*relative).to_owned()); } @@ -938,6 +938,30 @@ mod tests { } } + #[test] + fn init_does_not_publish_a_starter_for_a_fold_missing_from_the_timezone_data() { + let root = tempfile::tempdir().unwrap(); + let before_fold = "2026-10-31".parse().unwrap(); + // In 2006 the fold had already happened in October. This also tests + // the refusal without depending on where the installed data ends. + let before_regular_sunday = "2006-10-31".parse().unwrap(); + for template in ["standalone-exact-time", "resource-reservations"] { + let supported = root.path().join("supported").join(template); + init_on(&supported, template, before_fold).unwrap(); + + let refused = root.path().join("refused").join(template); + let error = init_on(&refused, template, before_regular_sunday).unwrap_err(); + assert!(error + .to_string() + .contains("America/New_York fold on 2006-11-05")); + assert!(!refused.exists()); + } + + let arrival = root.path().join("standalone-arrival-window"); + init_on(&arrival, "standalone-arrival-window", before_regular_sunday).unwrap(); + assert!(arrival.is_dir()); + } + /// A tempdir holding one freshly initialized template project, plus the /// paths the tempdir keeps alive. fn initialized(template: &str) -> (tempfile::TempDir, PathBuf) { diff --git a/crates/registry-schedulingctl/src/templates.rs b/crates/registry-schedulingctl/src/templates.rs index ad86c0547f..7be5529380 100644 --- a/crates/registry-schedulingctl/src/templates.rs +++ b/crates/registry-schedulingctl/src/templates.rs @@ -12,7 +12,9 @@ use std::borrow::Cow; -use chrono::{Datelike, Days, NaiveDate, Weekday}; +use anyhow::{ensure, Result}; +use chrono::{Datelike, Days, NaiveDate, Offset, TimeDelta, TimeZone, Weekday}; +use chrono_tz::America::New_York; #[cfg(test)] pub(super) const EXAMPLE_DATE: NaiveDate = example_date(10, 1); @@ -29,18 +31,18 @@ pub(super) fn date_file<'a>( relative: &str, contents: &'a str, today: NaiveDate, -) -> Cow<'a, str> { +) -> Result> { let counter_shift = || { // The example opens on the Thursday before the Monday fixture. Shift // by whole weeks and choose a Monday whose opening has begun today. let monday = on_or_after(today - Days::new(2), Weekday::Mon); monday - EXAMPLE_COUNTER }; - let fold_shift = || next_new_york_fold(today) - EXAMPLE_FOLD; - match (template, relative) { + let fold_shift = || next_new_york_fold(today).map(|fold| fold - EXAMPLE_FOLD); + Ok(match (template, relative) { ("standalone-exact-time", "scheduling.yaml") => { let counter = counter_shift(); - let fold = fold_shift(); + let fold = fold_shift()?; shift_dates(contents, |date| { date + if date == EXAMPLE_FOLD { fold } else { counter } }) @@ -51,7 +53,7 @@ pub(super) fn date_file<'a>( } ("standalone-exact-time", "records.yaml" | "fixtures/fold-day-rebooking.yaml") | ("resource-reservations", "records.yaml" | "fixtures/named-intervals.yaml") => { - let shift = fold_shift(); + let shift = fold_shift()?; shift_dates(contents, |date| date + shift) } ( @@ -68,7 +70,7 @@ pub(super) fn date_file<'a>( shift_dates(contents, |date| date + shift) } ("resource-reservations", "scheduling.yaml") => { - let year = next_new_york_fold(today).year(); + let year = next_new_york_fold(today)?.year(); // Cover the fixture's November fold and the live dates leading up // to it, including when the fold will land in the next year. shift_dates(contents, |date| { @@ -81,25 +83,40 @@ pub(super) fn date_file<'a>( }) } _ => Cow::Borrowed(contents), - } + }) } fn on_or_after(date: NaiveDate, weekday: Weekday) -> NaiveDate { date + Days::new(u64::from(weekday.days_since(date.weekday()))) } -fn next_new_york_fold(today: NaiveDate) -> NaiveDate { +fn next_new_york_fold(today: NaiveDate) -> Result { // America/New_York returns to standard time on the first Sunday in November. let fold = |year| { let november = NaiveDate::from_ymd_opt(year, 11, 1).expect("valid November date"); on_or_after(november, Weekday::Sun) }; let this_year = fold(today.year()); - if this_year > today { + let fold = if this_year > today { this_year } else { fold(today.year() + 1) - } + }; + // Both fixtures keep their original UTC clock times. Verify the offset + // change at precisely 06:00 UTC with the same timezone data as replay. + let transition = fold.and_hms_opt(6, 0, 0).expect("valid UTC time"); + let offset_seconds = |instant| { + New_York + .offset_from_utc_datetime(&instant) + .fix() + .local_minus_utc() + }; + ensure!( + offset_seconds(transition - TimeDelta::seconds(1)) == -4 * 3600 + && offset_seconds(transition) == -5 * 3600, + "America/New_York fold on {fold} does not match the starter's 06:00 UTC transition in the installed timezone data" + ); + Ok(fold) } /// Move ISO date prefixes in the built-in YAML, including the dates in UTC diff --git a/products/scheduling/scripts/check-checkpoint.sh b/products/scheduling/scripts/check-checkpoint.sh index 5a1a1e371a..dc4da027f8 100755 --- a/products/scheduling/scripts/check-checkpoint.sh +++ b/products/scheduling/scripts/check-checkpoint.sh @@ -42,7 +42,50 @@ cleanup() { trap cleanup EXIT HUP INT TERM for template in standalone-exact-time standalone-arrival-window resource-reservations; do + init_before=$(date -u +%Y-%m-%d) "$schedulingctl_bin" init "$work/$template" --template "$template" >/dev/null + init_after=$(date -u +%Y-%m-%d) + # Accept either UTC day if init crosses midnight. Replay uses fixture + # clocks and the later snapshot comparison deliberately ignores dates. + python3 - "$work/$template" "$init_before" "$init_after" <<'PY' +import sys +from datetime import date, timedelta +from pathlib import Path + +import yaml + +project = Path(sys.argv[1]) +first_day, last_day = sorted(date.fromisoformat(day) for day in sys.argv[2:]) +records = yaml.safe_load((project / "records.yaml").read_text(encoding="utf-8")) + +def require(condition, detail): + if not condition: + sys.exit(f"{project.name}: {detail} for UTC init dates {first_day} to {last_day}") + +if project.name == "standalone-arrival-window": + starts = {window["start"].date() for window in records["windows"]} + require(len(starts) == 1, "arrival windows must share one date") + start = starts.pop() + earliest = first_day + timedelta(days=7) + latest = last_day + timedelta(days=13) + require(start.weekday() == 5 and earliest <= start <= latest, + "arrival windows are outside the starter date range") +else: + openings = yaml.safe_load((project / "scheduling.yaml").read_text(encoding="utf-8"))["openings"] + if project.name == "standalone-exact-time": + opening = openings["bangkok-counter-hours"] + future_day = openings["new-york-hall-hours"]["effectiveFrom"] + label = "New York fold opening" + else: + opening = openings["hall-hours"] + maintenance = next(item for item in records["exceptions"] if item["id"] == "maintenance-day") + future_day = maintenance["date"] + label = "New York maintenance closure" + first_covered = max(first_day, date.fromisoformat(opening["effectiveFrom"])) + last_covered = min(last_day, date.fromisoformat(opening["effectiveUntil"])) + require(first_covered <= last_covered, "regular opening does not cover initialization") + require(date.fromisoformat(future_day) > first_covered, f"{label} is stale") +PY "$schedulingctl_bin" check "$work/$template" >/dev/null "$schedulingctl_bin" test "$work/$template" >/dev/null "$schedulingctl_bin" explain "$work/$template" >/dev/null From 4b48be0c68158033235096660632184f05141076 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 18:27:55 +0000 Subject: [PATCH 041/183] feat(session): export routes from checked standalone HTTPS Signed-off-by: Jeremi Joslin --- crates/registry-rstack/src/cli.rs | 10 +- crates/registry-session/src/gateway.rs | 17 +- crates/registry-session/src/gateway/verify.rs | 369 ++++++++++++++++-- crates/registry-session/src/lib.rs | 31 ++ crates/registry-session/src/main.rs | 19 +- crates/registry-session/tests/binary.rs | 133 +++++++ .../src/content/docs/configure/session.mdx | 28 ++ .../src/content/docs/security/session.mdx | 3 + 8 files changed, 581 insertions(+), 29 deletions(-) diff --git a/crates/registry-rstack/src/cli.rs b/crates/registry-rstack/src/cli.rs index 543b749c55..e3f52b7fe9 100644 --- a/crates/registry-rstack/src/cli.rs +++ b/crates/registry-rstack/src/cli.rs @@ -296,7 +296,9 @@ enum DevCommand { /// Root of an already-built local application when dev.yaml declares one. #[arg(long, value_name = "DIRECTORY")] application_root: Option, - /// PostgreSQL administrator URL (verified TLS, or loopback with sslmode=disable). + /// PostgreSQL administrator URL. Defaults to verified TLS. For development, select + /// loopback plaintext with sslmode=disable or private network plaintext with + /// transport=private-network-plaintext. /// Defaults to RSTACK_DEV_DATABASE_URL; without either, the run starts its own /// PostgreSQL server in Docker. #[arg(long, value_name = "URL")] @@ -353,9 +355,9 @@ enum DevCommand { /// Remove the project's managed PostgreSQL volume and state after stopping. #[arg(long, conflicts_with = "recover")] clean: bool, - /// PostgreSQL administrator URL for --recover (verified TLS, or loopback with - /// sslmode=disable). Defaults to RSTACK_DEV_DATABASE_URL; a run that started its own - /// server needs none. + /// The same PostgreSQL administrator URL used at start, including its transport + /// choice. Defaults to RSTACK_DEV_DATABASE_URL; a run that started its own server + /// needs none. #[arg(long, value_name = "URL", requires = "recover")] database_url: Option, }, diff --git a/crates/registry-session/src/gateway.rs b/crates/registry-session/src/gateway.rs index f8278d29de..2566d393ce 100644 --- a/crates/registry-session/src/gateway.rs +++ b/crates/registry-session/src/gateway.rs @@ -192,6 +192,14 @@ pub fn generate(config: &RuntimeConfig) -> Result, GatewayErr fn load_for_gateway( runtime_config: &Path, posture: DeclaredPosture, +) -> Result, GatewayError> { + load_gateway_config(runtime_config, posture, false) +} + +fn load_gateway_config( + runtime_config: &Path, + posture: DeclaredPosture, + checked_routes: bool, ) -> Result, GatewayError> { let (mut file, check) = read_runtime_file(runtime_config, false, posture); let Some(loaded) = file.loaded.take() else { @@ -214,6 +222,11 @@ fn load_for_gateway( }; require("/publicOrigin", file.defers("/publicOrigin")); require("/gateway", file.defers_within("/gateway")); + if checked_routes { + for pointer in ["/listener", "/checkListener", "/issuer", "/signIns"] { + require(pointer, file.defers_within(pointer)); + } + } for (list, count) in [ ("modules", loaded.config.modules.len()), ("pages", loaded.config.pages.len()), @@ -813,7 +826,9 @@ fn array<'a>(value: &'a Value, key: &str) -> &'a [Value] { } mod verify; -pub use verify::{verify_assembled, write_standalone}; +pub use verify::{ + verify_assembled, write_standalone, write_verified_route_inventory, StandaloneTls, +}; #[cfg(test)] mod tests { diff --git a/crates/registry-session/src/gateway/verify.rs b/crates/registry-session/src/gateway/verify.rs index f40a953c46..97757c879b 100644 --- a/crates/registry-session/src/gateway/verify.rs +++ b/crates/registry-session/src/gateway/verify.rs @@ -14,14 +14,17 @@ use std::{ collections::{BTreeMap, BTreeSet}, fs, io::{Read, Write}, - net::{IpAddr, SocketAddr}, + net::{IpAddr, Ipv4Addr, SocketAddr}, path::Path, }; +use registry_platform_config::{ListenerNetworkExposure, TlsTermination}; use registry_platform_yaml::{Reader, Refusal, ScalarHook, ScalarSite, ScalarStyle}; use serde_json::{json, Value}; +use sha2::{Digest, Sha256}; use super::*; +use crate::config::ModuleProduct; use crate::wire::SOURCE_PROFILE_HEADER; /// The most bytes of an assembled configuration `--verify-assembled` reads. @@ -212,9 +215,15 @@ pub fn write_standalone<'a>( output: &Path, listen: SocketAddr, upstreams: impl IntoIterator, + tls: Option>, posture: DeclaredPosture, ) -> Result { - let loaded = load_for_gateway(runtime_config, posture)?; + refuse_input_output_alias(output, runtime_config)?; + if let Some(tls) = &tls { + refuse_input_output_alias(output, tls.certificate)?; + refuse_input_output_alias(output, tls.key)?; + } + let loaded = load_gateway_config(runtime_config, posture, tls.is_some())?; let mut expected = Expected::new(&loaded.config)?; let gateway = loaded .config @@ -242,13 +251,46 @@ pub fn write_standalone<'a>( "Set gateway.service.host to a numeric loopback address.", )); } - let required = expected + let addresses = standalone_upstreams(&standalone_clusters(&expected), upstreams)?; + if tls.is_some() { + let ingress = validate_checked_transport(&loaded.config, addresses.values().copied())?; + if ingress != listen { + return Err(standalone_refusal( + "Make --listen match the numeric HTTPS publicOrigin.", + )); + } + } + let document = standalone_document(&mut expected, listen, addresses, tls.as_ref())?; + let bytes = serde_json::to_vec_pretty(&document) + .map_err(|_| standalone_refusal("Could not serialize the configuration."))?; + let document = scan_assembly(output, &bytes)?; + verify_document(&expected, &document)?; + + write_output(output, &bytes)?; + Ok(loaded.posture) +} + +/// File paths as Envoy will see them. The generator reads neither file. +pub struct StandaloneTls<'a> { + pub certificate: &'a Path, + pub key: &'a Path, +} + +fn standalone_clusters(expected: &Expected) -> BTreeSet<&str> { + expected .protected .iter() .map(String::as_str) .filter(|name| !matches!(*name, PUBLIC_CLUSTER | CHECK_CLUSTER)) - .collect::>(); - let addresses = standalone_upstreams(&required, upstreams)?; + .collect() +} + +fn standalone_document( + expected: &mut Expected, + listen: SocketAddr, + addresses: BTreeMap<&str, SocketAddr>, + tls: Option<&StandaloneTls<'_>>, +) -> Result { let mut definitions = String::new(); for (name, address) in addresses { cluster( @@ -259,15 +301,19 @@ pub fn write_standalone<'a>( ); } if !definitions.is_empty() { - expected.clusters.extend( - parse_fragment(&GeneratedFile { - name: "standalone-clusters", - content: definitions, - })? - .as_array() - .cloned() - .ok_or_else(|| standalone_refusal("Could not assemble the upstream clusters."))?, - ); + let mut custom = parse_fragment(&GeneratedFile { + name: "standalone-clusters", + content: definitions, + })? + .as_array() + .cloned() + .ok_or_else(|| standalone_refusal("Could not assemble the upstream clusters."))?; + if tls.is_some() { + for cluster in &mut custom { + cluster["type"] = json!("STATIC"); + } + } + expected.clusters.extend(custom); } let strip_port = !expected @@ -279,7 +325,7 @@ pub fn write_standalone<'a>( "name": "envoy.filters.http.router", "typed_config": {"@type": ROUTER_TYPE}, })); - let document = json!({ + let mut document = json!({ "static_resources": { "listeners": [{ "name": "registry-session", @@ -309,11 +355,178 @@ pub fn write_standalone<'a>( "clusters": &expected.clusters, }, }); - let bytes = serde_json::to_vec_pretty(&document) - .map_err(|_| standalone_refusal("Could not serialize the configuration."))?; - let document = scan_assembly(output, &bytes)?; - verify_document(&expected, &document)?; + if let Some(tls) = tls { + let certificate = checked_tls_path(tls.certificate)?; + let key = checked_tls_path(tls.key)?; + document["static_resources"]["listeners"][0]["filter_chains"][0]["transport_socket"] = json!({ + "name": "envoy.transport_sockets.tls", + "typed_config": { + "@type": "type.googleapis.com/envoy.extensions.transport_sockets.tls.v3.DownstreamTlsContext", + "common_tls_context": { + "alpn_protocols": ["h2", "http/1.1"], + "tls_certificates": [{ + "certificate_chain": {"filename": certificate}, + "private_key": {"filename": key}, + }], + }, + }, + }); + } + Ok(document) +} + +fn checked_tls_path(path: &Path) -> Result<&str, GatewayError> { + path.to_str() + .filter(|value| path.is_absolute() && !value.chars().any(char::is_control)) + .ok_or_else(|| standalone_refusal("Use absolute UTF-8 filenames for gateway TLS material.")) +} + +fn refuse_input_output_alias(output: &Path, input: &Path) -> Result<(), GatewayError> { + let canonical = |path: &Path| { + path.canonicalize().ok().or_else(|| { + let parent = path + .parent() + .filter(|parent| !parent.as_os_str().is_empty()); + let directory = parent + .unwrap_or_else(|| Path::new(".")) + .canonicalize() + .ok()?; + Some(directory.join(path.file_name()?)) + }) + }; + if output == input || canonical(output).is_some_and(|output| canonical(input) == Some(output)) { + return Err(standalone_refusal( + "Write the gateway output to a file distinct from its input files.", + )); + } + Ok(()) +} + +fn validate_checked_transport( + config: &RuntimeConfig, + upstreams: impl IntoIterator, +) -> Result { + let gateway = config + .gateway + .as_ref() + .ok_or(GatewayError::NoGatewayBlock)?; + let origin = config.public_origin.to_url(); + let ingress = origin + .host_str() + .and_then(|host| host.parse::().ok()) + .zip(origin.port_or_known_default()) + .map(|(host, port)| SocketAddr::from((host, port))) + .filter(|socket| origin.scheme() == "https" && loopback_socket(*socket)) + .ok_or_else(|| { + standalone_refusal("Checked routes require a numeric IPv4 loopback HTTPS publicOrigin.") + })?; + let origin_authority = origin + .port() + .map_or_else(|| ingress.ip().to_string(), |_| ingress.to_string()); + if config.gateway_authority().as_deref() != Some(origin_authority.as_str()) + || config.listener.network_exposure != ListenerNetworkExposure::PrivateAddress + || !matches!( + config.listener.tls_termination, + TlsTermination::LoopbackPlaintext | TlsTermination::OperatorControlledUpstream + ) + || config + .issuer + .endpoints() + .iter() + .any(|(_, endpoint)| endpoint.to_url().scheme() != "https") + { + return Err(standalone_refusal("Checked routes require the public authority, private Session listeners and HTTPS issuer endpoints.")); + } + let host = gateway + .service + .host + .as_str() + .parse::() + .ok() + .filter(Ipv4Addr::is_loopback) + .ok_or_else(|| { + standalone_refusal("Checked routes require numeric IPv4 loopback Session listeners.") + })?; + let public = SocketAddr::from((host, gateway.service.public_port.get() as u16)); + let check = SocketAddr::from((host, gateway.service.check_port.get() as u16)); + if public != config.listener.bind.0 || check != config.check_listener.0 { + return Err(standalone_refusal( + "Match the gateway's Session sockets to the runtime listeners.", + )); + } + let mut sockets = BTreeSet::new(); + for socket in [ingress, public, check].into_iter().chain(upstreams) { + if !socket.is_ipv4() || !loopback_socket(socket) || !sockets.insert(socket) { + return Err(standalone_refusal("Use a distinct numeric IPv4 loopback socket for each gateway listener and upstream.")); + } + } + let routes = config + .modules + .iter() + .map(|module| module.upstream.as_ref()) + .chain(config.pages.iter().map(|page| page.upstream.as_ref())); + let mut clusters = BTreeSet::from([PUBLIC_CLUSTER, CHECK_CLUSTER]); + if !gateway.host_filters.is_empty() + || routes.into_iter().any(|upstream| { + upstream.is_none_or(|upstream| { + !upstream.keep_host_filters.is_empty() + || !clusters.insert(upstream.cluster.as_str()) + }) + }) + { + return Err(standalone_refusal( + "Checked routes require one exclusive cluster per route and no host filters.", + )); + } + Ok(ingress) +} +fn verify_checked_transport<'a>( + config: &RuntimeConfig, + document: &'a Value, +) -> Result, GatewayError> { + let refusal = || { + standalone_refusal( + "Use the complete dedicated loopback HTTPS Envoy assembly for checked route export.", + ) + }; + let mut expected = Expected::new(config)?; + let resources = &document["static_resources"]; + let chain = &resources["listeners"][0]["filter_chains"][0]; + let certificates = + &chain["transport_socket"]["typed_config"]["common_tls_context"]["tls_certificates"][0]; + let certificate = certificates["certificate_chain"]["filename"] + .as_str() + .ok_or_else(refusal)?; + let key = certificates["private_key"]["filename"] + .as_str() + .ok_or_else(refusal)?; + let tls = StandaloneTls { + certificate: Path::new(certificate), + key: Path::new(key), + }; + let clusters = resources["clusters"].as_array().ok_or_else(refusal)?; + let addresses: BTreeMap<_, _> = standalone_clusters(&expected).into_iter().map(|name| { + let endpoint = clusters.iter().find(|cluster| cluster["name"] == name) + .and_then(|cluster| cluster.pointer("/load_assignment/endpoints/0/lb_endpoints/0/endpoint/address/socket_address")) + .ok_or_else(refusal)?; + let ip = endpoint["address"].as_str().and_then(|value| value.parse::().ok()).ok_or_else(refusal)?; + let port = endpoint["port_value"].as_u64().and_then(|port| u16::try_from(port).ok()).ok_or_else(refusal)?; + Ok((name.to_owned(), SocketAddr::from((ip, port)))) + }).collect::>()?; + let ingress = validate_checked_transport(config, addresses.values().copied())?; + let by_name = addresses + .iter() + .map(|(name, socket)| (name.as_str(), *socket)) + .collect(); + let wanted = standalone_document(&mut expected, ingress, by_name, Some(&tls))?; + if document != &wanted { + return Err(refusal()); + } + Ok(tls) +} + +fn write_output(output: &Path, bytes: &[u8]) -> Result<(), GatewayError> { let parent = output .parent() .filter(|path| !path.as_os_str().is_empty()) @@ -321,13 +534,13 @@ pub fn write_standalone<'a>( let mut staged = tempfile::NamedTempFile::new_in(parent).map_err(|error| io_error(output, &error))?; staged - .write_all(&bytes) + .write_all(bytes) .and_then(|()| staged.write_all(b"\n")) .map_err(|error| io_error(output, &error))?; staged .persist(output) .map_err(|error| io_error(output, &error.error))?; - Ok(loaded.posture) + Ok(()) } fn loopback_socket(address: SocketAddr) -> bool { @@ -399,6 +612,114 @@ pub fn verify_assembled( Ok(loaded.posture) } +/// Project the browser-facing routes only after verifying the same runtime and +/// assembly as the gateway checks. Upstream addresses and credentials are +/// absent. The operation catalogue and products still decide what a route can +/// call and who can call it. +pub fn write_verified_route_inventory( + runtime_config: &Path, + assembled: &Path, + output: &Path, + selection: &str, + posture: DeclaredPosture, +) -> Result { + let loaded = load_gateway_config(runtime_config, posture, true).map_err(|_| { + standalone_refusal("Supply a valid and literal Session runtime for checked route export.") + })?; + let config = &loaded.config; + let assembly_bytes = read_assembly_bytes(assembled).map_err(|_| { + standalone_refusal("Supply a readable, valid Envoy assembly for checked route export.") + })?; + let json_refusal = + || standalone_refusal("Supply the generated standalone Envoy configuration as JSON."); + let document = scan_assembly(assembled, &assembly_bytes).map_err(|_| json_refusal())?; + if serde_json::from_slice::(&assembly_bytes).map_err(|_| json_refusal())? != document { + return Err(json_refusal()); + } + let tls = verify_checked_transport(config, &document)?; + refuse_input_output_alias(output, runtime_config)?; + refuse_input_output_alias(output, assembled)?; + refuse_input_output_alias(output, tls.certificate)?; + refuse_input_output_alias(output, tls.key)?; + + let module = config + .modules + .iter() + .find(|module| module.id.as_str() == selection) + .filter(|module| module.product == Some(ModuleProduct::Breg)) + .ok_or_else(|| standalone_refusal("Select one declared BReg product module."))?; + let rewrite = module + .upstream + .as_ref() + .and_then(|upstream| upstream.prefix_rewrite.as_ref()) + .map(|prefix| prefix.as_str()); + let overlap = + |other: &str| lies_under(&module.prefix, other) || lies_under(other, &module.prefix); + if rewrite != Some("/") + || module.prefix.len() > 256 + || !module.prefix.ends_with('/') + || !module + .prefix + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || b"/._:-".contains(&byte)) + || config + .modules + .iter() + .any(|other| other.id != module.id && overlap(&other.prefix)) + || config.pages.iter().any(|page| overlap(&page.prefix)) + { + return Err(standalone_refusal( + "Select a disjoint BReg module prefix that rewrites to the product root.", + )); + } + if config.pages.iter().any(|page| { + config.modules.iter().any(|module| { + lies_under(&page.prefix, &module.prefix) || lies_under(&module.prefix, &page.prefix) + }) + }) { + return Err(standalone_refusal( + "Use page prefixes disjoint from all module prefixes in a checked inventory.", + )); + } + let sign_ins = config + .sign_ins + .iter() + .map(|entry| entry.id.as_str()) + .filter(|id| module.admits(id)) + .collect::>(); + if sign_ins.is_empty() || sign_ins.len() > 64 || config.pages.len() > 64 { + return Err(standalone_refusal( + "Checked routes require one to 64 admitted sign-in kinds and at most 64 pages.", + )); + } + let modules = [ + json!({"id": module.id.as_str(), "product": "breg", "prefix": module.prefix, "prefixRewrite": rewrite, "signIns": sign_ins}), + ]; + let pages: Vec<_> = config + .pages + .iter() + .map(|page| json!({"prefix": page.prefix, "signIn": page.sign_in.as_str()})) + .collect(); + let assembly_bytes = serde_json::to_vec(&document) + .map_err(|_| standalone_refusal("Could not serialize the verified assembly."))?; + let gateway_sha256: String = Sha256::digest(assembly_bytes) + .iter() + .map(|byte| format!("{byte:02x}")) + .collect(); + let inventory = json!({ + "apiVersion": "id.registrystack.org/formats/platform/session-route-inventory/v1alpha1", + "kind": "PlatformSessionRouteInventory", + "publicOrigin": config.public_origin.as_str().trim_end_matches('/'), + "gatewaySha256": gateway_sha256, + "modules": modules, + "pages": pages, + }); + let bytes = serde_json::to_vec_pretty(&inventory) + .map_err(|_| standalone_refusal("Could not serialize the verified route inventory."))?; + write_output(output, &bytes)?; + Ok(loaded.posture) +} + fn verify_loaded(config: &RuntimeConfig, assembled: &Path) -> Result<(), GatewayError> { let expected = Expected::new(config)?; let document = read_assembly(assembled)?; @@ -406,6 +727,10 @@ fn verify_loaded(config: &RuntimeConfig, assembled: &Path) -> Result<(), Gateway } fn read_assembly(assembled: &Path) -> Result { + scan_assembly(assembled, &read_assembly_bytes(assembled)?) +} + +fn read_assembly_bytes(assembled: &Path) -> Result, GatewayError> { let file = fs::File::open(assembled).map_err(|error| io_error(assembled, &error))?; let metadata = file .metadata() @@ -419,7 +744,7 @@ fn read_assembly(assembled: &Path) -> Result { file.take(MAXIMUM_ASSEMBLED_BYTES + 1) .read_to_end(&mut bytes) .map_err(|error| io_error(assembled, &error))?; - scan_assembly(assembled, &bytes) + Ok(bytes) } fn scan_assembly(assembled: &Path, bytes: &[u8]) -> Result { diff --git a/crates/registry-session/src/lib.rs b/crates/registry-session/src/lib.rs index 59cf14d7d3..a60a0d15f5 100644 --- a/crates/registry-session/src/lib.rs +++ b/crates/registry-session/src/lib.rs @@ -137,6 +137,21 @@ pub fn command() -> Command { ) .value_parser(value_parser!(PathBuf)), ) + .arg( + Arg::new("route-inventory-out") + .long("route-inventory-out") + .value_name("FILE") + .help("Write browser paths for the selected BReg route from a verified loopback HTTPS assembly") + .requires_all(["verify-assembled", "checked-route"]) + .value_parser(value_parser!(PathBuf)), + ) + .arg( + Arg::new("checked-route") + .long("checked-route") + .value_name("ID") + .help("Select the BReg product module for the browser route inventory") + .requires("route-inventory-out"), + ) .arg( Arg::new("standalone-out") .long("standalone-out") @@ -162,6 +177,22 @@ pub fn command() -> Command { .requires("standalone-out") .conflicts_with_all(["out", "check", "verify-assembled"]) .action(ArgAction::Append), + ) + .arg( + Arg::new("tls-certificate") + .long("tls-certificate") + .value_name("FILE") + .help("Absolute filename of the certificate chain for dedicated loopback HTTPS") + .requires_all(["standalone-out", "tls-key"]) + .value_parser(value_parser!(PathBuf)), + ) + .arg( + Arg::new("tls-key") + .long("tls-key") + .value_name("FILE") + .help("Absolute filename of the Envoy TLS private key") + .requires("tls-certificate") + .value_parser(value_parser!(PathBuf)), ), ), ) diff --git a/crates/registry-session/src/main.rs b/crates/registry-session/src/main.rs index 7fd0345682..abc8633e46 100644 --- a/crates/registry-session/src/main.rs +++ b/crates/registry-session/src/main.rs @@ -96,7 +96,18 @@ async fn main() -> ExitCode { return ExitCode::from(2); }; let result = if let Some(assembled) = arguments.get_one::("verify-assembled") { - gateway::verify_assembled(path, assembled, posture) + match arguments.get_one::("route-inventory-out") { + Some(out) => gateway::write_verified_route_inventory( + path, + assembled, + out, + arguments + .get_one::("checked-route") + .expect("inventory requires a module"), + posture, + ), + None => gateway::verify_assembled(path, assembled, posture), + } } else if let Some(out) = arguments.get_one::("standalone-out") { let listen = *arguments .get_one::("listen") @@ -106,7 +117,11 @@ async fn main() -> ExitCode { .into_iter() .flatten() .map(String::as_str); - gateway::write_standalone(path, out, listen, upstreams, posture) + let tls = arguments + .get_one::("tls-certificate") + .zip(arguments.get_one::("tls-key")) + .map(|(certificate, key)| gateway::StandaloneTls { certificate, key }); + gateway::write_standalone(path, out, listen, upstreams, tls, posture) } else { let mode = match ( arguments.get_one::("out"), diff --git a/crates/registry-session/tests/binary.rs b/crates/registry-session/tests/binary.rs index 4c82831ab5..d584f56418 100644 --- a/crates/registry-session/tests/binary.rs +++ b/crates/registry-session/tests/binary.rs @@ -273,6 +273,139 @@ fn gateway_writes_a_deterministic_checked_standalone_configuration() { ); } +#[test] +fn gateway_inventory_requires_the_exact_verified_assembly() { + let root = tempfile::tempdir().expect("directory"); + let runtime = root.path().join("runtime.yaml"); + std::fs::write( + &runtime, + standalone_runtime().replace("https://app.example", "https://127.0.0.1:8080"), + ) + .expect("runtime"); + let assembly = root.path().join("envoy.json"); + let routes = root.path().join("routes.json"); + let certificate = root.path().join("cert.pem"); + let key = root.path().join("key.pem"); + std::fs::write(&key, "synthetic key placeholder").expect("key placeholder"); + let export = |output: &std::path::Path| { + run_command( + runtime_command(&runtime) + .args(["gateway", "envoy", "--verify-assembled"]) + .arg(&assembly) + .arg("--route-inventory-out") + .arg(output) + .args(["--checked-route", "breg"]), + ) + }; + let verify = || export(&routes); + generate_standalone(&runtime, &assembly); + assert_eq!(verify().0, 1, "ordinary plaintext assembly must not export"); + assert!(!routes.exists()); + + let (exit, _, stderr) = run_command( + runtime_command(&runtime) + .args(["gateway", "envoy", "--standalone-out"]) + .arg(&assembly) + .args([ + "--listen", + "127.0.0.1:8080", + "--upstream", + "registry=127.0.0.1:8100", + "--upstream", + "pages=127.0.0.1:8200", + ]) + .arg("--tls-certificate") + .arg(&certificate) + .arg("--tls-key") + .arg(&key), + ); + assert_eq!(exit, 0, "{stderr}"); + let (exit, _, stderr) = verify(); + assert_eq!(exit, 0, "{stderr}"); + let first = std::fs::read(&routes).expect("route inventory"); + let inventory: serde_json::Value = serde_json::from_slice(&first).expect("JSON inventory"); + assert_eq!(inventory["kind"], "PlatformSessionRouteInventory"); + assert_eq!(inventory["publicOrigin"], "https://127.0.0.1:8080"); + assert_eq!( + inventory["modules"], + json!([{ + "id": "breg", + "product": "breg", + "prefix": "/api/registry/", + "prefixRewrite": "/", + "signIns": ["citizen"] + }]) + ); + assert_eq!( + inventory["pages"], + json!([{"prefix": "/apply/", "signIn": "citizen"}]) + ); + let output = String::from_utf8_lossy(&first); + for private in [ + ":8100", + ":8121", + "secret:", + "https://id.example", + "clientId", + "key.pem", + ] { + assert!(!output.contains(private), "{output}"); + } + + let (exit, _, stderr) = verify(); + assert_eq!(exit, 0, "{stderr}"); + assert_eq!(std::fs::read(&routes).expect("regenerated routes"), first); + + assert_eq!(export(&key).0, 1, "refuse to overwrite the gateway TLS key"); + assert_eq!( + std::fs::read_to_string(&key).expect("original key placeholder"), + "synthetic key placeholder" + ); + assert_eq!( + export(&certificate).0, + 1, + "refuse to create output at the declared certificate filename" + ); + let child = root.path().join("child"); + std::fs::create_dir(&child).expect("nested directory"); + assert_eq!( + export(&child.join("../cert.pem")).0, + 1, + "refuse an alternate spelling of the declared certificate filename" + ); + assert!(!certificate.exists()); + + let contents = std::fs::read_to_string(&assembly).expect("Envoy configuration"); + std::fs::write( + &assembly, + contents.replacen("\"static_resources\"", "static_resources", 1), + ) + .expect("convert assembly to flow YAML"); + assert_eq!(verify().0, 1, "the checked exporter requires JSON"); + assert_eq!(std::fs::read(&routes).expect("retained inventory"), first); + + assert!(contents.contains("/api/registry/")); + std::fs::write(&assembly, contents.replace("/api/registry/", "/api/other/")) + .expect("mutate assembled route"); + let (exit, _, _) = verify(); + assert_eq!(exit, 1); + assert_eq!(std::fs::read(&routes).expect("retained inventory"), first); + + let mut remote: serde_json::Value = serde_json::from_str(&contents).expect("assembly JSON"); + let clusters = remote["static_resources"]["clusters"] + .as_array_mut() + .expect("clusters"); + let registry = clusters + .iter_mut() + .find(|cluster| cluster["name"] == "registry") + .expect("BReg cluster"); + registry["load_assignment"]["endpoints"][0]["lb_endpoints"][0]["endpoint"]["address"] + ["socket_address"]["address"] = json!("192.0.2.1"); + std::fs::write(&assembly, remote.to_string()).expect("mutate upstream address"); + assert_eq!(verify().0, 1); + assert_eq!(std::fs::read(&routes).expect("retained inventory"), first); +} + #[test] #[ignore = "requires Docker and the pinned Envoy image"] fn envoy_validates_the_generated_standalone_configuration() { diff --git a/docs/site/src/content/docs/configure/session.mdx b/docs/site/src/content/docs/configure/session.mdx index cf4a163a57..7f09e99219 100644 --- a/docs/site/src/content/docs/configure/session.mdx +++ b/docs/site/src/content/docs/configure/session.mdx @@ -276,6 +276,34 @@ on other hosts. {/* Evidence: crates/registry-session/src/gateway/verify.rs, write_standalone; crates/registry-session/tests/binary.rs, envoy_validates_the_generated_standalone_configuration. */} +### Export the checked BReg browser route + +Use the dedicated loopback HTTPS assembly for checked route export. Set `publicOrigin` to +`https://127.0.0.1:8443` and give each configured upstream a distinct numeric IPv4 loopback +socket. Session's public and check binds must match the two sockets declared in `gateway.service`. +Keep the issuer endpoints on HTTPS. Configure the BReg route to rewrite its disjoint prefix to `/`. + +Provide absolute certificate and key filenames as Envoy will see them. The generator records +the paths. The browser verifies the live TLS certificate for the numeric origin. + +```bash +registry-session --runtime-config /etc/registry-session/runtime.yaml gateway envoy \ + --standalone-out /etc/envoy/envoy.json --listen 127.0.0.1:8443 \ + --upstream registry=127.0.0.1:8100 --upstream pages=127.0.0.1:8200 \ + --tls-certificate /run/tls/app.crt --tls-key /run/tls/app.key +registry-session --runtime-config /etc/registry-session/runtime.yaml gateway envoy \ + --verify-assembled /etc/envoy/envoy.json --route-inventory-out /tmp/session-routes.json \ + --checked-route breg +``` + +The export checks the standalone Envoy JSON and records the selected BReg product route, +its admitted sign-in kinds and the page bindings. Use it with the assembly that produced it. +Envoy and Session check live requests, and the product authorizes the operation. + +{/* Evidence: crates/registry-session/src/gateway/verify.rs, validate_checked_transport, + verify_checked_transport, write_verified_route_inventory; + crates/registry-session/tests/binary.rs, gateway_inventory_requires_the_exact_verified_assembly. */} + ### Integrate with an existing gateway Generate into a directory you reserve for these files. diff --git a/docs/site/src/content/docs/security/session.mdx b/docs/site/src/content/docs/security/session.mdx index 996388e1cb..20ebaae20f 100644 --- a/docs/site/src/content/docs/security/session.mdx +++ b/docs/site/src/content/docs/security/session.mdx @@ -81,6 +81,9 @@ A module's `signIns` list routes kinds of sessions, but grants no product permis 5. Terminate TLS in front of the public listener. The service accepts `development-loopback` only in development posture. Use it for local HTTP in a browser that supports `Secure` cookies on loopback. + For checked browser route export, use the dedicated loopback HTTPS Envoy assembly and deploy + the verified configuration. The browser verifies the ingress certificate. The operator + controls the gateway namespace, private Session sockets and upstream endpoints. 6. Name every host HTTP filter in `gateway.hostFilters`. Retain a filter on a module or page only through `upstream.keepHostFilters`. A retained filter must preserve the path, route cache and authorisation header. From 541aac5611a8496324d299e035c5812d9212dfa3 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 18:29:18 +0000 Subject: [PATCH 042/183] docs: explain when to choose a service function or flow Signed-off-by: Jeremi Joslin --- .../run-a-project-with-rstack-dev.mdx | 41 ++++++++++++------- docs/site/src/content/docs/start/adopt.mdx | 39 ++++++++++-------- 2 files changed, 49 insertions(+), 31 deletions(-) diff --git a/docs/site/src/content/docs/configure/run-a-project-with-rstack-dev.mdx b/docs/site/src/content/docs/configure/run-a-project-with-rstack-dev.mdx index 41a1b4d7ac..b7389d5f30 100644 --- a/docs/site/src/content/docs/configure/run-a-project-with-rstack-dev.mdx +++ b/docs/site/src/content/docs/configure/run-a-project-with-rstack-dev.mdx @@ -889,21 +889,32 @@ A later `start` creates a fresh application run. Product data on managed Postgre crates/registry-rstack-dev/src/lib.rs application-root; crates/registry-rstack-dev/src/products.rs PreparedApplication. */} -### Choose a function or a flow - -Use a server-side function for work that finishes within one request. Use a Coordinator flow when -work waits for a person or a date, or when each step needs review. When a step needs code the -flow cannot express, the existing -[`external.command/v1` operation](../coordinator/#call-an-external-provider) can call an external -provider. The operator binds the destination and credential in the Coordinator runtime file. - -A function owns no product authority. The product authorises every call the function makes. -When the whole procedure lives in function code, you lose the Coordinator diagram and its -record of each step. - -{/* Evidence: crates/registry-coordinator/src/operations.rs, operation_catalog; - products/coordinator/AGENTS.md, Registry Coordinator product; - docs/site/src/content/docs/configure/coordinator.mdx. */} +### Choose a service function or a Coordinator flow + +Use a service function for work that finishes within one request. A service function is +server-side code that your application calls. In business registration, it can check the +submitted details and call the BReg Action that creates the Record. In medical licence renewal, +it can prepare a new expiry and call the BReg renewal Action with the condition the holder +reviewed. In each case, the write completes within the request. + +Use a Coordinator flow when work waits for a person or a date, or when reviewers need to +inspect the steps of a procedure. For example, a flow can request an officer's review, wait +for the decision, and then call the product that carries out the next step. Call a service +function for an individual step the flow cannot express. To call your code through the +current [external provider operation](../coordinator/#call-an-external-provider), implement +the external command contract and have your operator configure the provider. + +A service function holds no authority of its own. Send Record changes through the owning +product under the caller's authority. BReg checks that authority before it carries out the +Action. You can draw a Coordinator flow from its declared steps and inspect the record of +each run's steps. If you write the whole procedure as function code, you give up that drawing +and per-step record. + +{/* Evidence: crates/registry-coordinator/src/definition.rs, Step::WaitUntil, Step::WaitFor; + crates/registry-coordinator/src/cli.rs, render_explain; + crates/registry-coordinator/src/store.rs, RunInspection; + crates/registry-coordinator/src/operations.rs, external.command/v1; + crates/registry-breg/src/api/actions.rs, authorize_action_mode. */} ### Browser issuer diff --git a/docs/site/src/content/docs/start/adopt.mdx b/docs/site/src/content/docs/start/adopt.mdx index 33f506d416..e432783e7b 100644 --- a/docs/site/src/content/docs/start/adopt.mdx +++ b/docs/site/src/content/docs/start/adopt.mdx @@ -140,28 +140,35 @@ Your team owns four things: That answer means that the first request completed. Read its result, such as the Record or the Proposal, and do not send the request again. -Each product still checks every call itself and stores its own results. - -Some sequences of steps run for days or weeks. -For example: ask a reviewer, wait for the decision, then send the applicant a notice. -Add [Registry Coordinator](../../reference/glossary/#registry-coordinator) only when such a -sequence must continue without a person or a running script keeping track of it. -Coordinator runs the sequence as a reviewed workflow. -It keeps the workflow going across long waits, outages, and restarts. -Read the [Coordinator overview](../coordinator/) for more. - -Review alone does not need Coordinator. -Your application can prepare a Proposal, get a Casework review, and have BReg apply it. -A Proposal is a change that BReg holds before it applies it. -BReg freezes exactly what will change when the Proposal is submitted. -Where the Action requires a review, BReg applies the change only after approval. - Add [Registry Messaging](../../reference/glossary/#registry-messaging) only when the application must send messages from templates that were reviewed in advance. Messaging sends one message to one destination over one channel, such as SMS or email. It sends through a messaging provider that is configured for your deployment. It then reports what it knows about delivery. +### Choose a service function or a Coordinator flow + +Use a service function when the work finishes within one request, such as preparing the input +for a licence renewal. The function holds no authority of its own. It asks the owning product +to make the change, and the product checks the caller's authority and stores the result. + +Use a [Registry Coordinator](../coordinator/) flow when the work must wait or someone needs to +review the procedure's steps. For example, the flow can ask for a review, wait for the +decision, and then send the applicant a notice. Call a service function for a step the flow +cannot express. If you write the whole procedure as function code, you give up the drawing +and the record of each step. See [how to choose a service function or a flow](../../configure/run-a-project-with-rstack-dev/#choose-a-service-function-or-a-coordinator-flow). + +If the work is a single review of a BReg change, your application can submit a Proposal to +BReg and let BReg and Casework handle the review. BReg freezes what will change when the +Proposal is submitted. Where the Action requires review, BReg applies the change only after +approval. + +{/* Evidence: crates/registry-coordinator/src/definition.rs, Step::WaitUntil, Step::WaitFor; + crates/registry-coordinator/src/cli.rs, render_explain; + crates/registry-coordinator/src/store.rs, RunInspection; + crates/registry-breg/src/api/actions.rs, authorize_action_mode; + products/breg/contracts/security-invariant-matrix.yaml. */} + ## Run your own module On this page, a module is a service or worker that you write, deploy, and run yourself. From afabc126ea05ad8d8cbe9644e2a30d6bbd96046e Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 18:27:12 +0000 Subject: [PATCH 043/183] docs(breg): reach a business preview from BReg Start Use the existing business registration example and a matching npm release to take an adopter from the first product page to a browser registration. Signed-off-by: Jeremi Joslin (cherry picked from commit dc0645fd39f83dcc6d79a18e3c23a937936db27e) --- docs/site/astro.config.mjs | 1 + .../scripts/information-architecture.test.mjs | 16 +++ .../content/docs/start/breg-quickstart.mdx | 2 + .../docs/tutorials/preview-a-breg-service.mdx | 113 ++++++++++++++++++ 4 files changed, 132 insertions(+) create mode 100644 docs/site/src/content/docs/tutorials/preview-a-breg-service.mdx diff --git a/docs/site/astro.config.mjs b/docs/site/astro.config.mjs index c877023df3..18e04bb609 100644 --- a/docs/site/astro.config.mjs +++ b/docs/site/astro.config.mjs @@ -802,6 +802,7 @@ export default defineConfig({ items: [ { label: 'Overview', slug: 'start/breg-quickstart' }, { label: 'Your first registry', slug: 'tutorials/first-breg' }, + { label: 'Preview a browser service', slug: 'tutorials/preview-a-breg-service' }, { label: 'How a registry works', slug: 'explanation/configuration-defined-registry' }, { label: 'Tutorials', diff --git a/docs/site/scripts/information-architecture.test.mjs b/docs/site/scripts/information-architecture.test.mjs index 1fd830d676..300164ab73 100644 --- a/docs/site/scripts/information-architecture.test.mjs +++ b/docs/site/scripts/information-architecture.test.mjs @@ -13,6 +13,7 @@ import { RETIRED_RELAY_ROUTES, } from '../src/lib/relay-retirement-redirects.mjs'; import { flattenSidebarGroups } from '../src/lib/sidebar.mjs'; +import { readJourney } from './tutorial-runner/page.mjs'; import { docsetPublishesBregOpenApi, docsetPublishesEvidenceOid4vciOpenApi, @@ -890,6 +891,7 @@ test('keeps the BReg guide and references in one adoption path', () => { assert.deepEqual(slugs, [ 'start/breg-quickstart', 'tutorials/first-breg', + 'tutorials/preview-a-breg-service', 'explanation/configuration-defined-registry', 'tutorials/change-a-registry-with-an-action', 'tutorials/extend-a-registry-with-a-module', @@ -943,6 +945,7 @@ test('keeps the BReg guide and references in one adoption path', () => { breg, [ "slug: 'tutorials/first-breg'", + "slug: 'tutorials/preview-a-breg-service'", "label: 'Tutorials'", "label: 'Author a registry'", "label: 'Deploy and operate'", @@ -952,6 +955,8 @@ test('keeps the BReg guide and references in one adoption path', () => { ], 'Base Registry Engine', ); + const overview = readFileSync(resolve(siteRoot, 'src/content/docs/start/breg-quickstart.mdx'), 'utf8'); + assert.match(overview, /\]\(\.\.\/\.\.\/tutorials\/preview-a-breg-service\/\)/u); // The homepage names the doors into the path, not every room: the overview, // the first tutorial, the deployment page, and the tutorial @@ -972,6 +977,17 @@ test('keeps the BReg guide and references in one adoption path', () => { } }); +test('reads the first BReg tutorial development files from the scaffold', () => { + const firstBreg = readFileSync(resolve(siteRoot, 'src/content/docs/tutorials/first-breg.mdx'), 'utf8'); + const { steps, errors } = readJourney(firstBreg); + assert.deepEqual(errors, []); + const devFiles = steps.filter(({ path }) => path === 'dev.yaml' || path === 'dev-journeys.yaml'); + assert.deepEqual(devFiles.map(({ kind, path }) => [kind, path]), [ + ['excerpt', 'dev.yaml'], + ['excerpt', 'dev-journeys.yaml'], + ]); +}); + // Both runtime products ask an adopter for infrastructure before they serve // anything: PostgreSQL, a token issuer, and a signing process for Base Registry // Engine; a Transit proxy, an identity provider, and durable audit storage for diff --git a/docs/site/src/content/docs/start/breg-quickstart.mdx b/docs/site/src/content/docs/start/breg-quickstart.mdx index 95e9457ef1..989cf0e4bd 100644 --- a/docs/site/src/content/docs/start/breg-quickstart.mdx +++ b/docs/site/src/content/docs/start/breg-quickstart.mdx @@ -58,6 +58,8 @@ journal stay on, so the local registry checks each request the way a deployed on ## Then follow your role - **You build applications on a registry.** Keep the + [preview a business registration service](../../tutorials/preview-a-breg-service/) to submit a + test registration from your browser. Keep the [client reference](../../reference/breg-client-capabilities/) open, then [send registry events to a webhook](../../tutorials/send-registry-events-to-a-webhook/) to connect the registry to the systems around it. diff --git a/docs/site/src/content/docs/tutorials/preview-a-breg-service.mdx b/docs/site/src/content/docs/tutorials/preview-a-breg-service.mdx new file mode 100644 index 0000000000..932fa53978 --- /dev/null +++ b/docs/site/src/content/docs/tutorials/preview-a-breg-service.mdx @@ -0,0 +1,113 @@ +--- +title: Preview a business registration service +description: Run the business registration starter, submit a test registration in your browser, and read the resulting Record from Base Registry Engine. +status: draft +owner: registry-docs +source_repos: + - registry-stack +last_reviewed: unreviewed +doc_type: tutorial +persona: + - data publisher + - operator +locale: en +standards_referenced: [] +tutorial_test: + toolset: breg + skip: The browser preview uses the matching release checkout, npm package, Node.js 24 and Docker. Replay it with the service preview acceptance tools. +--- + +import QuickstartMeta from '../../../components/QuickstartMeta.astro'; + +If you are building a service on Base Registry Engine (BReg), try the business registration +starter. You will run it on your machine, register a test business from a browser form, and see +the Record that BReg returns. + + + +## Scaffold the preview + +Start in an empty working directory. Use the Registry Stack release selected in the docs +version picker and install the BReg component from that release. Replace `` with the +release number, without the leading `v`. Copy the business registration starter from its source tag. + +```sh +version='' +rstack breg --version +git clone --depth 1 --branch "v${version}" https://github.com/registrystack/registry-stack.git registry-stack-preview-source +cp -R registry-stack-preview-source/products/platform/examples/service-previews/business-registration ./business-registration +``` + +Check that the reported tool version matches ``. +You now have a `business-registration` directory with a registry project, a browser page, and a +registration function. If Git cannot find the tag, check the release number in the verified +installer's filename. If the starter is missing, choose a release that includes the preview. + +## Install the client + +Install the published client for the release you selected. npm saves that exact version in your +copy of the starter. Run the remaining commands from the preview directory. + +```sh +cd business-registration +npm install --save-exact "@registrystack/client@${version}" +``` + +If npm cannot find the version, check the package version against the Registry Stack release you +installed. Use the same version for both. + +{/* Evidence: crates/registry-rstack/src/cli.rs, generate_client(); clients/typescript/package.json. */} + +## Start the preview + +Use synthetic data and trusted code on a trusted machine. The preview runs as a test registrar. +Other processes and users on the same host can reach the loopback URL. + +Check the development plan and start a local run. + +```sh +rstack dev check . +rstack dev start . --ttl 30m +``` + +If the check fails, use the file and field named in its diagnostic. The first start may download +the PostgreSQL image. If start fails, check that Docker is running and read the diagnostic. +Keep the run ID and open the URL marked `Application` in the start report. + +{/* Evidence: crates/registry-rstack/src/cli.rs, dispatch_dev; crates/registry-rstack-dev/src/lib.rs, start(). */} + +## Register a test business + +In the browser, enter `Example Supply Cooperative` for **Business name** and +`BR-TUTORIAL-001` for **Registration number**. Select **Register business**. + +The **Business registered** confirmation shows the name, registration number and Record ID +read back from BReg. Reload the page and use a fresh number to repeat the exercise in the same run. + +{/* TODO[evidence]: Bind the business-registration page and its native browser acceptance source when the preview release baseline lands. */} + +## Stop the preview + +Replace `` with the ID from the start report. The `--clean` flag deletes the managed +development data for this preview. + +```sh +RUN='' +rstack dev stop "$RUN" --clean +``` + +The stop report confirms the run stopped. + +## Next + +[Generate clients for your own projects](../../reference/typescript-clients/) From 6ef9140a923b1288750c856baa6d2c790e4e3c0d Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 16:54:03 +0000 Subject: [PATCH 044/183] test(breg): verify the native role facts writer against compiled grants Signed-off-by: Jeremi Joslin (cherry picked from commit dbd13263bfa3a6853adc14216cd454ede4b9840c) --- .../registry-bregctl/tests/identity_facts.rs | 171 ++++++++++++++++++ 1 file changed, 171 insertions(+) diff --git a/crates/registry-bregctl/tests/identity_facts.rs b/crates/registry-bregctl/tests/identity_facts.rs index 945e5ece46..b4f47b19fd 100644 --- a/crates/registry-bregctl/tests/identity_facts.rs +++ b/crates/registry-bregctl/tests/identity_facts.rs @@ -151,6 +151,177 @@ fn an_existing_output_is_refused_and_left_unchanged() { assert_eq!(std::fs::read_to_string(&output).unwrap(), "keep"); } +#[test] +fn native_inventory_report_matches_the_independently_compiled_external_views_project() { + use std::collections::{BTreeMap, BTreeSet}; + use std::fmt::Write as _; + use std::process::Command; + + use registry_breg::compiler::{compile_project, CompileProfile}; + use registry_breg::contract::parse_project_yaml; + use registry_thunderid_tooling::identity_facts::ClaimType; + use serde_json::{json, Value}; + use sha2::{Digest, Sha256}; + + // The archived witness used a copy of this project. Check the maintained + // source directly so the publisher and witness exercise the same input. + let project = Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../products/breg/examples/external-views") + .canonicalize() + .unwrap(); + let authored = parse_project_yaml(&std::fs::read(project.join("registry.yaml")).unwrap()) + .expect("the donor is readable"); + let compiled = compile_project(&authored, &[], CompileProfile::Authoring) + .expect("the separate compiler produces the donor inventory"); + let scratch = tempfile::tempdir().unwrap(); + let runtime = runtime(scratch.path()); + edit_runtime( + &runtime, + "allowedClients: [generic-registry-client]", + "allowedClients: [officer, restricted, licensing-refresh, staff-app]", + ); + let first = scratch.path().join("first-facts.yaml"); + let second = scratch.path().join("second-facts.yaml"); + let native = |output: &Path| { + Command::new(env!("CARGO_BIN_EXE_bregctl")) + .args(["--format", "json", "generate", "identity-facts"]) + .arg(&project) + .arg("--runtime-config") + .arg(&runtime) + .arg("--output") + .arg(output) + .env_remove("REGISTRY_STACK_POSTURE") + .output() + .expect("native bregctl starts") + }; + let report = |output: &Path| { + let result = native(output); + assert!(result.status.success(), "native writer refused the fixture"); + assert!(result.stderr.is_empty(), "unexpected native writer stderr"); + let mut report: Value = registry_platform_canonical_json::parse_json_strict(&result.stdout) + .expect("the completed report is unique-member JSON"); + assert_eq!(report["kind"], "BRegCtlReport"); + assert_eq!( + report["apiVersion"], + registry_bregctl::CTL_REPORT_API_VERSION + ); + assert_eq!(report["command"], "generate"); + assert_eq!(report["status"], "complete"); + assert_eq!(report["ok"], true); + assert_eq!(report["revision"], compiled.revision()); + let bytes = std::fs::read(output).unwrap(); + let mut digest = String::new(); + for byte in Sha256::digest(&bytes) { + write!(digest, "{byte:02x}").unwrap(); + } + let artifact = &mut report["artifacts"][0]; + assert_eq!( + *artifact, + json!({ + "path": output, + "byteLength": bytes.len(), + "mediaType": "application/yaml", + "sha256": digest, + }) + ); + artifact["path"] = json!("identity-facts.yaml"); + (bytes, report) + }; + let (facts_bytes, first_report) = report(&first); + assert_eq!((facts_bytes.clone(), first_report.clone()), report(&second)); + let facts = read_facts(&first); + assert_eq!( + first_report["explanation"]["identityFacts"], + json!({"accessProfiles": facts.access_profiles.len(), "claims": facts.claims.len()}) + ); + + let mut expected = BTreeMap::new(); + for entity in compiled.entities().values() { + for profile in entity.access_profiles.values() { + let entry = expected.entry(profile.id.as_str()).or_insert_with(|| { + ( + profile.required_scopes.as_set(), + profile.required_purposes.as_set(), + profile.requester_clients.as_set(), + BTreeSet::new(), + ) + }); + entry.3.insert(profile.principal_claim.as_str()); + entry.3.extend( + profile + .row_boundaries + .iter() + .map(|boundary| boundary.claim.as_str()), + ); + } + } + assert_eq!(facts.access_profiles.len(), expected.len()); + for profile in &facts.access_profiles { + let (scopes, purposes, clients, required_claims) = &expected[profile.id.as_str()]; + assert_eq!( + profile.scopes.iter().cloned().collect::>(), + **scopes + ); + assert_eq!( + profile.purposes.iter().cloned().collect::>(), + **purposes + ); + assert_eq!( + profile + .requester_clients + .iter() + .flatten() + .cloned() + .collect::>(), + **clients, + ); + assert_eq!( + profile + .required_claims + .iter() + .map(String::as_str) + .collect::>(), + *required_claims, + ); + } + let authority = registry_breg::authority::authority_inventory(&compiled).unwrap(); + for (name, claim) in authority.direct_claims { + let kind = if claim.multi_value { + ClaimType::StringArray + } else { + ClaimType::String + }; + assert_eq!(facts.claims[&name], kind); + } + + let schema = serde_json::from_str(include_str!( + "../../../products/platform/schemas/identity-facts.schema.json" + )) + .unwrap(); + let validator = jsonschema::JSONSchema::options() + .with_draft(jsonschema::Draft::Draft202012) + .compile(&schema) + .unwrap(); + let facts_value = serde_json::to_value(facts).unwrap(); + assert!(validator.is_valid(&facts_value)); + let mut malformed = facts_value; + malformed["unrecognized"] = json!("synthetic-refusal"); + assert!(!validator.is_valid(&malformed)); + assert!(registry_thunderid_tooling::identity_facts::read( + "malformed", + &serde_json::to_vec(&malformed).unwrap(), + ) + .is_err()); + let refusal = native(&first); + assert_eq!(refusal.status.code(), Some(1)); + let refusal = registry_platform_canonical_json::parse_json_strict(&refusal.stdout).unwrap(); + assert_eq!( + refusal["diagnostics"][0]["code"], + "identity-facts.output-exists" + ); + assert_eq!(std::fs::read(first).unwrap(), facts_bytes); +} + #[test] fn an_unrestricted_runtime_states_unrestricted_admission() { let scratch = tempfile::tempdir().unwrap(); From 3b8f27573d202e56c9705774c833dbdf19b188a0 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 18:33:35 +0000 Subject: [PATCH 045/183] feat(bregctl): publish completed identity facts report schema Signed-off-by: Jeremi Joslin --- crates/registry-bregctl/src/check.rs | 1 + crates/registry-bregctl/src/identity_facts.rs | 8 +- crates/registry-bregctl/src/lib.rs | 6 +- crates/registry-bregctl/src/tool_schema.rs | 134 +++++++- .../registry-bregctl/tests/identity_facts.rs | 14 + crates/registry-bregctl/tests/tool_schema.rs | 65 +++- .../formats/identity-facts-report.json | 44 +++ .../tools/ctl-report.v1alpha1.schema.json | 319 ++++++++++++++++++ products/platform/config-formats.yaml | 11 +- 9 files changed, 581 insertions(+), 21 deletions(-) create mode 100644 products/breg/examples/formats/identity-facts-report.json create mode 100644 products/breg/generated/tools/ctl-report.v1alpha1.schema.json diff --git a/crates/registry-bregctl/src/check.rs b/crates/registry-bregctl/src/check.rs index a0386cd661..b7802f0f00 100644 --- a/crates/registry-bregctl/src/check.rs +++ b/crates/registry-bregctl/src/check.rs @@ -100,6 +100,7 @@ pub(super) struct RankedDiagnostic<'a> { } #[derive(Clone, Copy, Serialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] #[serde(rename_all = "kebab-case")] pub(super) enum FindingRank { WidensAccess, diff --git a/crates/registry-bregctl/src/identity_facts.rs b/crates/registry-bregctl/src/identity_facts.rs index e53df5460b..d359a0f2ad 100644 --- a/crates/registry-bregctl/src/identity_facts.rs +++ b/crates/registry-bregctl/src/identity_facts.rs @@ -565,13 +565,15 @@ fn refuse_unissuable_claim( ))) } -/// Write `facts` to a new file. An existing file is never replaced. -pub(crate) fn write(facts: &IdentityFacts, output: &Path) -> Result<(), FactsError> { +/// Write `facts` to a new file and return the exact YAML written. +/// An existing file is never replaced. +pub(crate) fn write(facts: &IdentityFacts, output: &Path) -> Result { let yaml = facts.to_yaml().map_err(|_| FactsError::Encode)?; let mut file = OpenOptions::new() .write(true) .create_new(true) .open(output) .map_err(FactsError::Write)?; - file.write_all(yaml.as_bytes()).map_err(FactsError::Write) + file.write_all(yaml.as_bytes()).map_err(FactsError::Write)?; + Ok(yaml) } diff --git a/crates/registry-bregctl/src/lib.rs b/crates/registry-bregctl/src/lib.rs index 05cb3335ea..064bcde286 100644 --- a/crates/registry-bregctl/src/lib.rs +++ b/crates/registry-bregctl/src/lib.rs @@ -1965,6 +1965,7 @@ enum ExplainSubject { } #[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Serialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] #[serde(rename_all = "snake_case")] enum ProfileArg { #[default] @@ -2224,6 +2225,7 @@ where } #[derive(Serialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] struct RankedProjectFinding<'a> { #[serde(flatten)] diagnostic: &'a registry_platform_yaml::Diagnostic, @@ -10035,7 +10037,7 @@ fn generate_identity_facts( ) })?; let facts = stated.facts; - identity_facts::write(&facts, &args.output).map_err(|error| { + let yaml = identity_facts::write(&facts, &args.output).map_err(|error| { fail( error.code(), &error.to_string(), @@ -10057,7 +10059,7 @@ fn generate_identity_facts( artifacts: vec![artifact_report( &args.output.display().to_string(), "application/yaml", - facts.to_yaml().unwrap_or_default().as_bytes(), + yaml.as_bytes(), )], explanation: Some(json!({ "identityFacts": { diff --git a/crates/registry-bregctl/src/tool_schema.rs b/crates/registry-bregctl/src/tool_schema.rs index 46c675b886..32a22191e6 100644 --- a/crates/registry-bregctl/src/tool_schema.rs +++ b/crates/registry-bregctl/src/tool_schema.rs @@ -1,22 +1,34 @@ // SPDX-License-Identifier: Apache-2.0 -//! Generated JSON Schemas for the tool files `bregctl` reads. +//! Generated JSON Schemas for BReg tooling contracts. //! -//! Each schema is derived from the types its reader decodes and published -//! with the header the reader checks before decoding them. The committed -//! copies under `products/breg/generated/tools` come from the `tool-schema` -//! example; `products/breg/scripts/check-tool-schemas.sh` fails when they -//! differ from what the reader types generate. +//! Each schema publishes the version and kind a reader checks along with the +//! members it accepts. The committed copies under `products/breg/generated/tools` +//! come from the `tool-schema` example and are checked by +//! `products/breg/scripts/check-tool-schemas.sh`. use std::collections::BTreeMap; use registry_breg::{fixtures, migration_plan}; -use registry_platform_yaml::{EnvelopeRule, FormatSpec, VersionStatus}; +use registry_platform_config::identity_facts::{MAXIMUM_CLAIMS, MAXIMUM_PROFILES}; +use registry_platform_yaml::{ApiVersion, EnvelopeRule, FormatSpec, VersionStatus}; +use schemars::generate::SchemaSettings; use serde_json::{json, Map, Value}; -use crate::{examples, init_from_model, test_lifecycle}; +use crate::{ + examples, init_from_model, test_lifecycle, ProfileArg, RankedProjectFinding, + CTL_REPORT_API_VERSION, CTL_REPORT_KIND, +}; const SCHEMA_DIALECT: &str = "https://json-schema.org/draft/2020-12/schema"; const SCHEMA_ID_BASE: &str = "https://id.registrystack.org/schemas/"; +const CTL_REPORT_FORMAT: FormatSpec<'static> = FormatSpec { + kind: CTL_REPORT_KIND, + envelope: EnvelopeRule::ApiVersionKind { + api_versions: &[ApiVersion::current(CTL_REPORT_API_VERSION)], + retired_api_versions: &[], + }, + removed_keys: &[], +}; /// One published tool schema. struct Tool { @@ -28,7 +40,7 @@ struct Tool { members: fn() -> schemars::Schema, } -fn tools() -> [Tool; 6] { +fn tools() -> [Tool; 7] { [ Tool { namespace: "breg", @@ -72,9 +84,108 @@ fn tools() -> [Tool; 6] { spec: migration_plan::MIGRATION_DESCRIPTOR_FORMAT, members: migration_plan::migration_descriptor_schema, }, + Tool { + namespace: "breg", + format: "ctl-report", + title: "Completed BReg identity facts command report", + spec: CTL_REPORT_FORMAT, + members: completed_identity_facts_report_schema, + }, ] } +fn completed_identity_facts_report_schema() -> schemars::Schema { + let mut generator = SchemaSettings::draft2020_12() + .for_serialize() + .into_generator(); + let profile = generator.subschema_for::(); + let diagnostic = generator.subschema_for::>(); + let definitions = generator.take_definitions(true); + let mut schema = json!({ + "type": "object", + "additionalProperties": false, + "description": "The completed report from bregctl generate identity-facts. Validation describes the report structure; its artifact metadata does not establish the path or contents of a file.", + "required": ["ok", "command", "status", "version", "profile", "revision", "posture", "diagnostics", "artifacts", "explanation"], + "properties": { + "ok": {"type": "boolean", "const": true}, + "command": {"type": "string", "const": "generate"}, + "status": {"type": "string", "const": registry_cli_report::Status::Complete.as_str()}, + "version": {"type": "string", "minLength": 1}, + "profile": profile, + "revision": {"type": "string", "pattern": "^sha256:[0-9a-f]{64}$", "minLength": 71, "maxLength": 71}, + "posture": { + "type": "object", "additionalProperties": false, + "required": ["value", "source"], + "properties": { + "value": {"type": "string", "enum": ["production", "development"]}, + "source": {"type": "string", "enum": ["default", "environment", "flag"]} + } + }, + "diagnostics": {"type": "array", "items": diagnostic}, + "artifacts": { + "type": "array", "minItems": 1, "maxItems": 1, + "items": { + "type": "object", "additionalProperties": false, + "required": ["path", "mediaType", "byteLength", "sha256"], + "properties": { + "path": {"type": "string", "minLength": 1}, + "mediaType": {"type": "string", "const": "application/yaml"}, + "byteLength": {"type": "integer", "minimum": 1, "maximum": registry_platform_yaml::MAXIMUM_DOCUMENT_BYTES}, + "sha256": {"type": "string", "pattern": "^[0-9a-f]{64}$", "minLength": 64, "maxLength": 64} + } + } + }, + "explanation": { + "type": "object", "additionalProperties": false, + "required": ["identityFacts"], + "properties": { + "identityFacts": { + "type": "object", "additionalProperties": false, + "required": ["accessProfiles", "claims"], + "properties": { + "accessProfiles": {"type": "integer", "minimum": 0, "maximum": MAXIMUM_PROFILES}, + "claims": {"type": "integer", "minimum": 0, "maximum": MAXIMUM_CLAIMS} + } + } + } + }, + "nextSteps": {"type": "array", "minItems": 1, "items": {"type": "string"}} + }, + "$defs": definitions + }); + close_diagnostic_objects(&mut schema["$defs"]); + // Positioned findings point into a bounded source or runtime document. + // Coordinates start at one and may point just past its last character. + let maximum_coordinate = registry_platform_yaml::MAXIMUM_DOCUMENT_BYTES + 1; + for definition in ["Source", "Related"] { + let properties = &mut schema["$defs"][definition]["properties"]; + for name in ["line", "column"] { + let coordinate = properties + .get_mut(name) + .expect("diagnostic source defines this coordinate"); + coordinate["minimum"] = json!(1); + coordinate["maximum"] = json!(maximum_coordinate); + } + } + schemars::Schema::try_from(schema).expect("the report schema is an object") +} + +/// Saved reports require exact members even for the shared diagnostic types. +fn close_diagnostic_objects(schema: &mut Value) { + match schema { + Value::Object(object) => { + if object.contains_key("properties") { + object.insert("additionalProperties".to_owned(), Value::Bool(false)); + } + for value in object.values_mut() { + close_diagnostic_objects(value); + } + } + Value::Array(values) => values.iter_mut().for_each(close_diagnostic_objects), + _ => {} + } +} + /// Every tool schema under its committed file name, /// `..schema.json`. pub fn documents() -> Result, serde_json::Error> { @@ -112,9 +223,8 @@ fn current_api_version(spec: &FormatSpec<'static>) -> &'static str { } } -/// The reader checks `apiVersion` and `kind` and removes them before it -/// decodes the members, so the derived schema lacks them; the published one -/// requires both, each with the one value this release reads. +/// Require the envelope in the published schema. The member definition covers +/// the body that remains after the reader checks the version and kind. fn with_header(mut derived: Value, api_version: &str, kind: &str) -> Value { let Value::Object(object) = &mut derived else { unreachable!("a reader type derives an object schema") diff --git a/crates/registry-bregctl/tests/identity_facts.rs b/crates/registry-bregctl/tests/identity_facts.rs index b4f47b19fd..05ec8c6f38 100644 --- a/crates/registry-bregctl/tests/identity_facts.rs +++ b/crates/registry-bregctl/tests/identity_facts.rs @@ -209,6 +209,20 @@ fn native_inventory_report_matches_the_independently_compiled_external_views_pro assert_eq!(report["status"], "complete"); assert_eq!(report["ok"], true); assert_eq!(report["revision"], compiled.revision()); + #[cfg(feature = "schema")] + { + let schemas = registry_bregctl::tool_schema::documents().unwrap(); + let schema = serde_json::from_str(&schemas["ctl-report.v1alpha1.schema.json"]) + .expect("generated report schema is JSON"); + let validator = jsonschema::JSONSchema::options() + .with_draft(jsonschema::Draft::Draft202012) + .compile(&schema) + .expect("generated report schema compiles"); + assert!( + validator.is_valid(&report), + "native report violates its schema" + ); + } let bytes = std::fs::read(output).unwrap(); let mut digest = String::new(); for byte in Sha256::digest(&bytes) { diff --git a/crates/registry-bregctl/tests/tool_schema.rs b/crates/registry-bregctl/tests/tool_schema.rs index 365c9b3737..d4f6bbc454 100644 --- a/crates/registry-bregctl/tests/tool_schema.rs +++ b/crates/registry-bregctl/tests/tool_schema.rs @@ -36,6 +36,10 @@ const EXAMPLES: &[(&str, &str)] = &[ "products/breg/examples/formats/retire-legacy-field-binding.json", ), ("migration-descriptor.v1alpha1.schema.json", DESCRIPTOR), + ( + "ctl-report.v1alpha1.schema.json", + "products/breg/examples/formats/identity-facts-report.json", + ), ]; const DESCRIPTOR: &str = "products/breg/examples/formats/reviewed-migrations/modules/asset-site-placement-core/migrations/read-maintenance-note/descriptor.json"; @@ -79,6 +83,64 @@ fn every_committed_example_satisfies_its_generated_schema() { } } +#[test] +fn identity_facts_report_schema_refuses_other_reports_and_undeclared_members() { + let documents = documents().expect("the tool schemas generate"); + let schema = compile(&documents["ctl-report.v1alpha1.schema.json"]); + let valid = example("products/breg/examples/formats/identity-facts-report.json"); + for (path, refused) in [ + ("/kind", json!("PlatformIdentityFacts")), + ("/command", json!("check")), + ("/status", json!("domain-refusal")), + ("/ok", json!(false)), + ("/artifacts", json!([])), + ("/artifacts/0/byteLength", json!(-1)), + ("/artifacts/0/sha256", json!("unexpected")), + ("/explanation/identityFacts/accessProfiles", json!("3")), + ("/explanation/identityFacts/accessProfiles", json!(65)), + ( + "/diagnostics/0/source", + json!({"file": "registry.yaml", "extra": true}), + ), + ] { + let mut changed = valid.clone(); + *changed + .pointer_mut(path) + .expect("member is present in fixture") = refused; + assert!(!schema.is_valid(&changed), "accepted a change at {path}"); + } + let mut extra = valid.clone(); + extra["explanation"]["identityFacts"]["unrecognised"] = json!(true); + assert!(!schema.is_valid(&extra)); + let mut missing = valid; + missing.as_object_mut().unwrap().remove("explanation"); + assert!(!schema.is_valid(&missing)); +} + +#[test] +fn identity_facts_report_schema_bounds_document_coordinates() { + let documents = documents().expect("the tool schemas generate"); + let schema = compile(&documents["ctl-report.v1alpha1.schema.json"]); + let mut report = example("products/breg/examples/formats/identity-facts-report.json"); + report["diagnostics"][0]["related"] = json!([{ + "file": "registry.yaml", "path": "", "message": "Check the project", "line": 1, "column": 1 + }]); + let maximum = registry_platform_yaml::MAXIMUM_DOCUMENT_BYTES + 1; + for path in [ + "/diagnostics/0/source/line", + "/diagnostics/0/source/column", + "/diagnostics/0/related/0/line", + "/diagnostics/0/related/0/column", + ] { + for (coordinate, admitted) in [(0, false), (1, true), (maximum, true), (maximum + 1, false)] + { + let mut changed = report.clone(); + *changed.pointer_mut(path).expect("coordinate exists") = json!(coordinate); + assert_eq!(schema.is_valid(&changed), admitted, "{path}: {coordinate}"); + } + } +} + #[test] fn example_scenario_schema_uses_bounded_display_text() { let documents = documents().expect("the tool schemas generate"); @@ -382,8 +444,9 @@ fn a_wrong_header_a_missing_header_and_an_explicit_null_are_refused() { } /// The identifiers the catalog records, in file-name order. -const IDENTIFIERS: [&str; 6] = [ +const IDENTIFIERS: [&str; 7] = [ "https://id.registrystack.org/schemas/breg/backup-binding/backup-binding.v1alpha1.schema.json", + "https://id.registrystack.org/schemas/breg/ctl-report/ctl-report.v1alpha1.schema.json", "https://id.registrystack.org/schemas/breg/example-scenarios/example-scenarios.v1alpha1.schema.json", "https://id.registrystack.org/schemas/breg/journeys/journeys.v1.schema.json", "https://id.registrystack.org/schemas/breg/migration-descriptor/migration-descriptor.v1alpha1.schema.json", diff --git a/products/breg/examples/formats/identity-facts-report.json b/products/breg/examples/formats/identity-facts-report.json new file mode 100644 index 0000000000..d9dd14156c --- /dev/null +++ b/products/breg/examples/formats/identity-facts-report.json @@ -0,0 +1,44 @@ +{ + "ok": true, + "command": "generate", + "status": "complete", + "apiVersion": "id.registrystack.org/formats/breg/ctl-report/v1alpha1", + "kind": "BRegCtlReport", + "version": "0.49.0", + "artifacts": [ + { + "byteLength": 802, + "mediaType": "application/yaml", + "path": "identity-facts.yaml", + "sha256": "d6061ec53e023e24401cbff448cfea3f900c78747956ec97265b6b3da64a4f62" + } + ], + "explanation": { + "identityFacts": { + "accessProfiles": 3, + "claims": 4 + } + }, + "profile": "authoring", + "revision": "sha256:a850cc821c54ce783ab57c4d271edb7e8f8d2fc16fc8dca172bc6320f137a385", + "posture": { + "value": "production", + "source": "default" + }, + "diagnostics": [ + { + "artifact": "BRegModule", + "code": "breg.record-type.stored-field-unfillable", + "message": "this optional stored field has no writable access grant, fixed Action set, function-plan write, or import that can supply a value; add the field to one of those writers, or remove the field", + "path": "/extendRecordTypes/record/fields/0", + "rank": "hygiene", + "severity": "warning", + "source": { + "column": 9, + "file": "modules/record-notes/module.yaml", + "line": 19 + }, + "suggestedAction": "Add the field to a grant's writableFields, a fixed Action set, a function plan write, or an import permission, or remove the field." + } + ] +} diff --git a/products/breg/generated/tools/ctl-report.v1alpha1.schema.json b/products/breg/generated/tools/ctl-report.v1alpha1.schema.json new file mode 100644 index 0000000000..5642d5ce12 --- /dev/null +++ b/products/breg/generated/tools/ctl-report.v1alpha1.schema.json @@ -0,0 +1,319 @@ +{ + "$defs": { + "CheckScope": { + "additionalProperties": false, + "description": "A source file relative to the project and the resource path a check reports.", + "properties": { + "file": { + "minLength": 1, + "type": "string" + }, + "path": { + "description": "A pointer whose list positions use existing unique identifiers when available.", + "type": "string" + } + }, + "required": [ + "file", + "path" + ], + "type": "object" + }, + "FindingRank": { + "enum": [ + "widens-access", + "performance", + "hygiene" + ], + "type": "string" + }, + "ProfileArg": { + "enum": [ + "authoring", + "production" + ], + "type": "string" + }, + "RankedProjectFinding": { + "additionalProperties": false, + "description": "One problem, in the shape every checking command reports (CFG-DIAG-1).\n\nMessages name keys, paths, accepted values, bounds, and the expected\nenvelope without repeating rejected scalar values (CFG-SEC-3). Warning\nacceptance metadata separately identifies the resource and carries the\nproject's deliberately authored reason.", + "properties": { + "acceptedReason": { + "description": "The project's reason for accepting this advisory warning.", + "type": "string" + }, + "artifact": { + "description": "The document's `kind`, or the expected kind when the document's own is\nabsent or wrong and the reader expected exactly one.", + "type": "string" + }, + "code": { + "type": "string" + }, + "message": { + "type": "string" + }, + "path": { + "description": "RFC 6901 JSON pointer into the document as written; `\"\"` is the root.", + "type": "string" + }, + "rank": { + "$ref": "#/$defs/FindingRank" + }, + "related": { + "items": { + "$ref": "#/$defs/Related" + }, + "type": "array" + }, + "scope": { + "$ref": "#/$defs/CheckScope", + "description": "Project-relative identity copied into a check acceptance." + }, + "severity": { + "$ref": "#/$defs/Severity" + }, + "source": { + "$ref": "#/$defs/Source" + }, + "suggestedAction": { + "type": "string" + } + }, + "required": [ + "severity", + "code", + "path", + "message", + "suggestedAction", + "rank" + ], + "type": "object" + }, + "Related": { + "additionalProperties": false, + "description": "A second place that explains a diagnostic, such as the first occurrence\nof a duplicate. Human output prints it as a `note:` line.", + "properties": { + "column": { + "format": "uint", + "maximum": 1048577, + "minimum": 1, + "type": "integer" + }, + "file": { + "type": "string" + }, + "line": { + "format": "uint", + "maximum": 1048577, + "minimum": 1, + "type": "integer" + }, + "message": { + "type": "string" + }, + "path": { + "type": "string" + } + }, + "required": [ + "file", + "path", + "message" + ], + "type": "object" + }, + "Severity": { + "description": "Whether a diagnostic refuses the input.", + "enum": [ + "error", + "warning" + ], + "type": "string" + }, + "Source": { + "additionalProperties": false, + "description": "Where a diagnostic points. `file` is the path exactly as the caller gave\nit; `line` and `column` are 1-based and absent when the problem concerns\nthe file as a whole.", + "properties": { + "column": { + "format": "uint", + "maximum": 1048577, + "minimum": 1, + "type": "integer" + }, + "file": { + "type": "string" + }, + "line": { + "format": "uint", + "maximum": 1048577, + "minimum": 1, + "type": "integer" + } + }, + "required": [ + "file" + ], + "type": "object" + } + }, + "$id": "https://id.registrystack.org/schemas/breg/ctl-report/ctl-report.v1alpha1.schema.json", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "description": "The completed report from bregctl generate identity-facts. Validation describes the report structure; its artifact metadata does not establish the path or contents of a file.", + "properties": { + "apiVersion": { + "const": "id.registrystack.org/formats/breg/ctl-report/v1alpha1", + "description": "The format and version this file is written in.", + "type": "string" + }, + "artifacts": { + "items": { + "additionalProperties": false, + "properties": { + "byteLength": { + "maximum": 1048576, + "minimum": 1, + "type": "integer" + }, + "mediaType": { + "const": "application/yaml", + "type": "string" + }, + "path": { + "minLength": 1, + "type": "string" + }, + "sha256": { + "maxLength": 64, + "minLength": 64, + "pattern": "^[0-9a-f]{64}$", + "type": "string" + } + }, + "required": [ + "path", + "mediaType", + "byteLength", + "sha256" + ], + "type": "object" + }, + "maxItems": 1, + "minItems": 1, + "type": "array" + }, + "command": { + "const": "generate", + "type": "string" + }, + "diagnostics": { + "items": { + "$ref": "#/$defs/RankedProjectFinding" + }, + "type": "array" + }, + "explanation": { + "additionalProperties": false, + "properties": { + "identityFacts": { + "additionalProperties": false, + "properties": { + "accessProfiles": { + "maximum": 64, + "minimum": 0, + "type": "integer" + }, + "claims": { + "maximum": 64, + "minimum": 0, + "type": "integer" + } + }, + "required": [ + "accessProfiles", + "claims" + ], + "type": "object" + } + }, + "required": [ + "identityFacts" + ], + "type": "object" + }, + "kind": { + "const": "BRegCtlReport", + "description": "The kind of document this file is.", + "type": "string" + }, + "nextSteps": { + "items": { + "type": "string" + }, + "minItems": 1, + "type": "array" + }, + "ok": { + "const": true, + "type": "boolean" + }, + "posture": { + "additionalProperties": false, + "properties": { + "source": { + "enum": [ + "default", + "environment", + "flag" + ], + "type": "string" + }, + "value": { + "enum": [ + "production", + "development" + ], + "type": "string" + } + }, + "required": [ + "value", + "source" + ], + "type": "object" + }, + "profile": { + "$ref": "#/$defs/ProfileArg" + }, + "revision": { + "maxLength": 71, + "minLength": 71, + "pattern": "^sha256:[0-9a-f]{64}$", + "type": "string" + }, + "status": { + "const": "complete", + "type": "string" + }, + "version": { + "minLength": 1, + "type": "string" + } + }, + "required": [ + "apiVersion", + "kind", + "ok", + "command", + "status", + "version", + "profile", + "revision", + "posture", + "diagnostics", + "artifacts", + "explanation" + ], + "title": "Completed BReg identity facts command report", + "type": "object" +} diff --git a/products/platform/config-formats.yaml b/products/platform/config-formats.yaml index 30a46a43d1..e8b8283d9c 100644 --- a/products/platform/config-formats.yaml +++ b/products/platform/config-formats.yaml @@ -1400,7 +1400,7 @@ formats: restrictingMembers: [] - id: breg/ctl-report product: breg - title: bregctl --format json report + title: Completed bregctl generate identity-facts JSON report files: [] syntax: json audience: generated @@ -1414,13 +1414,18 @@ formats: target: apiVersion: id.registrystack.org/formats/breg/ctl-report/v1alpha1 kind: BRegCtlReport - schema: none + schema: + path: products/breg/generated/tools/ctl-report.v1alpha1.schema.json + id: https://id.registrystack.org/schemas/breg/ctl-report/ctl-report.v1alpha1.schema.json + origin: generated + generator: cargo run -p registry-bregctl --features schema --example tool-schema -- --output products/breg/generated/tools + driftCheck: products/breg/scripts/check-tool-schemas.sh reader: none emittedBy: file: crates/registry-bregctl/src/lib.rs symbol: write_ctl_report check: none - example: products/breg/examples/formats/ctl-report.json + example: products/breg/examples/formats/identity-facts-report.json conformance: none securityMembers: [] restrictingMembers: [] From 39c9c8fa68c476fe38d38bd6e09c309b672cac39 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 18:25:11 +0000 Subject: [PATCH 046/183] feat(deploy): add business registration reference host Signed-off-by: Jeremi Joslin (cherry picked from commit 523189e2f71da53b9328229d7c9017630d281f7a) --- .../business-registration/.dockerignore | 5 + .../examples/business-registration/Dockerfile | 7 + .../examples/business-registration/README.md | 177 +++++++++++++ .../business-registration/breg-runtime.yaml | 43 ++++ .../business-registration/check-gateway.sh | 10 + .../business-registration/compose.yaml | 235 ++++++++++++++++++ .../examples/business-registration/edge.yaml | 128 ++++++++++ .../examples/business-registration/host.mjs | 132 ++++++++++ .../identity-deployment.yaml | 28 +++ .../business-registration/init-postgres.sh | 25 ++ .../business-registration/issuer-ready.mjs | 34 +++ .../business-registration/package-lock.json | 28 +++ .../business-registration/package.json | 7 + .../business-registration/pg_hba.conf | 3 + .../business-registration/session.yaml | 54 ++++ .../business-registration/tests/host.test.mjs | 69 +++++ .../business-registration/tests/smoke.sh | 33 +++ .../tests/test_compose.py | 80 ++++++ .../business-registration/thunderid.sh | 41 +++ .../business-registration/thunderid.yaml | 57 +++++ .../business-registration/upstreams.yaml | 63 +++++ 21 files changed, 1259 insertions(+) create mode 100644 deploy/examples/business-registration/.dockerignore create mode 100644 deploy/examples/business-registration/Dockerfile create mode 100644 deploy/examples/business-registration/README.md create mode 100644 deploy/examples/business-registration/breg-runtime.yaml create mode 100644 deploy/examples/business-registration/check-gateway.sh create mode 100644 deploy/examples/business-registration/compose.yaml create mode 100644 deploy/examples/business-registration/edge.yaml create mode 100644 deploy/examples/business-registration/host.mjs create mode 100644 deploy/examples/business-registration/identity-deployment.yaml create mode 100755 deploy/examples/business-registration/init-postgres.sh create mode 100644 deploy/examples/business-registration/issuer-ready.mjs create mode 100644 deploy/examples/business-registration/package-lock.json create mode 100644 deploy/examples/business-registration/package.json create mode 100644 deploy/examples/business-registration/pg_hba.conf create mode 100644 deploy/examples/business-registration/session.yaml create mode 100644 deploy/examples/business-registration/tests/host.test.mjs create mode 100755 deploy/examples/business-registration/tests/smoke.sh create mode 100644 deploy/examples/business-registration/tests/test_compose.py create mode 100644 deploy/examples/business-registration/thunderid.sh create mode 100644 deploy/examples/business-registration/thunderid.yaml create mode 100644 deploy/examples/business-registration/upstreams.yaml diff --git a/deploy/examples/business-registration/.dockerignore b/deploy/examples/business-registration/.dockerignore new file mode 100644 index 0000000000..dc6492ac2c --- /dev/null +++ b/deploy/examples/business-registration/.dockerignore @@ -0,0 +1,5 @@ +* +!Dockerfile +!package.json +!package-lock.json +!host.mjs diff --git a/deploy/examples/business-registration/Dockerfile b/deploy/examples/business-registration/Dockerfile new file mode 100644 index 0000000000..a38bf67221 --- /dev/null +++ b/deploy/examples/business-registration/Dockerfile @@ -0,0 +1,7 @@ +FROM node:24.22.3@sha256:dc26ae92c9fb15cf6b1d63e20f0944b2efe0f115b20e00be48fb23fceb061c54 +WORKDIR /app +COPY package.json package-lock.json ./ +RUN npm ci --omit=dev --ignore-scripts --no-audit --no-fund +COPY host.mjs ./ +USER node +ENTRYPOINT ["node", "/app/host.mjs"] diff --git a/deploy/examples/business-registration/README.md b/deploy/examples/business-registration/README.md new file mode 100644 index 0000000000..865be5000b --- /dev/null +++ b/deploy/examples/business-registration/README.md @@ -0,0 +1,177 @@ +# Business registration on the Compose reference host + +Run the business-registration preview's compiled function and static page with +Registry Session, Envoy, ThunderID, BReg and PostgreSQL. The application opens +at `https://127.0.0.1:8443/apply/`. Use a disposable project and synthetic +registrar. The example uses production posture and verified TLS with loopback +host bindings. + +The browser receives an opaque Session cookie. Envoy checks it and supplies +the registrar's access token on the private function and registry routes. +The function uses that token for the existing BReg Action. BReg applies its +own access profile, issuer, scope and row rules. The Node host has read-only +bundle files and no database or issuer credentials. + +## Prepare the deployment inputs + +Use Docker Compose v2 on Linux amd64. Set `RECIPE` to the absolute path of this +directory and prepare a fresh private directory for `REFERENCE_CONFIG`. Stage +`breg`, `bregctl` and `registry-session` in `REFERENCE_ARTIFACTS`. Verify the +matching BReg release binaries against their manifest. Use a matching native +Session binary verified against the local candidate's artifact receipt until +Session is available in a numbered release. + +Set these inputs in your shell and in a Compose environment file. Use absolute +paths. Set `REFERENCE_UID` and `REFERENCE_GID` if the nonroot owner of these +inputs differs from 1000. Both Envoy relays use this same UID. Each Compose +project needs its own input, audit, checked-config and socket directories. + +| Variable | Value | +| --- | --- | +| `REFERENCE_CONFIG` | Private directory with the layout below | +| `REFERENCE_ARTIFACTS` | Directory with the verified executables | +| `BUSINESS_BUNDLE` | Build output of the business-registration preview | +| `BUSINESS_BUNDLE_SHA256` | Runtime file digest of the reviewed preview build | + +Generate the preview bundle with the matching preview builder. The recipe uses +its `manifest.json`, `functions/register-business.mjs`, and the three files in +the manifest's `staticOutput` directory, `index.html`, `app.js` and +`service.css`. Use a build whose page references its assets by relative URL so +the same page can run under `/apply/`. The digest covers each of these five +files and its relative path. Derive it once from the reviewed build, then +include that value in the instance's input file. + +```bash +bundle_host=$(docker build --quiet "$RECIPE") +docker run --rm --network none \ + --mount "type=bind,source=$BUSINESS_BUNDLE,target=/run/bundle,readonly" \ + "$bundle_host" --digest /run/bundle +``` + +Name the sealed BReg package from that preview project in both BReg inputs. +Follow the [BReg test and package steps](../../../docs/site/src/content/docs/operate/breg.mdx) +with a separate schema-test database. Use the same package and recorded digest +for activation and serving. Set `BREG_PACKAGE_DIGEST` in your shell from the +package receipt. + +| Path under `REFERENCE_CONFIG` | Contents | +| --- | --- | +| `app-tls/app.crt`, `app-tls/app.key` | TLS pair with an IP SAN of `127.0.0.1` | +| `issuer-tls/issuer.crt`, `issuer-tls/issuer.key` | TLS pair for `identity.reference.test` | +| `trust/https-ca.pem`, `trust/postgres-ca.pem` | Trust roots for the HTTPS and PostgreSQL certificates | +| `postgres/server.crt`, `postgres/server.key`, `postgres/bootstrap-password`, `postgres/thunderid-password` | TLS pair for DNS name `postgres`, database admin password and ThunderID database password | +| `postgres/schema/` | Four schema files from the pinned ThunderID image, staged below | +| `session/secrets/` | Owner-only `registrar-client` and `audit-key` | +| `breg/runtime/` | [Runtime configuration](breg-runtime.yaml) as `runtime.yaml`, sealed `package/`, and owner-only `secrets/` with the serving database URL, database CA, cursor key and audit key | +| `breg/admin/` | Same runtime file and package, separately staged for the explicit BReg admin commands. Also provide `admin-database-url` and the migration database URL in `secrets/`. | +| `thunderid/bootstrap.yaml` | A copy of [thunderid.yaml](thunderid.yaml), used once with writable backing stores | +| `thunderid/deployment.yaml` | The same ThunderID base plus the generated store settings, used by the issuer after setup | +| `thunderid/bootstrap-secrets/` | `DB_CONFIG_PASSWORD` and `ADMIN_PASSWORD` for the one-shot setup | +| `thunderid/secrets/` | `DB_CONFIG_PASSWORD`, `REGISTRAR_CLIENT_SECRET`, and `REGISTRAR_PASSWORD` for serving | +| `thunderid/resources/`, `thunderid/front-gateway/`, `thunderid/identity-receipt.json` | Output of identity generation | +| `gateway/envoy.yaml` | Reviewed complete Envoy configuration from the matching Session CLI | +| `gateway-checked/`, `relay/`, `breg/audit/`, `session/audit/` | Empty private directories owned by the instance UID | + +The Session client secret equals `REGISTRAR_CLIENT_SECRET`. Both ThunderID +`DB_CONFIG_PASSWORD` files carry the value in `postgres/thunderid-password`. +The PostgreSQL files must be readable by the image's UID 999 and the +ThunderID secrets by UID 10001. Give private keys and secret files mode 0600. +Use distinct random values for admin, registrar, database and audit credentials. +BReg URLs target `postgres:5432`; runtime and migration use different roles and +passwords and point at the same registry database. BReg's CA file carries +`postgres-ca.pem`. Configure the local browser to resolve +`identity.reference.test` to `127.0.0.1` and trust the HTTPS CA. + +Generate the issuer inputs with the matching `rstack identity generate thunderid` +command and [identity-deployment.yaml](identity-deployment.yaml). Use the +preview's BReg project and a host-side copy of the BReg runtime file whose +package and secret-provider roots exist and are readable. The private resource +files carry references to the secret names above. Stage the generated +`resources/`, `front-gateway/` and `identity-receipt.json` at the paths in the +table. Merge the generated ThunderID store settings into the serving deployment +file, retaining the supplied `server`, `jwt`, `crypto` and `database` blocks. +The generated issuer, application registration, subject claims and registrar +scope must agree with the BReg and Session files. + +For checked browser route export, use the matching Lane 2 Session CLI with the +checked-route flags. Generate the complete Envoy file over [session.yaml](session.yaml). +The gateway itself terminates app TLS at `127.0.0.1:8443`. Use +`/run/tls/app.crt` and `/run/tls/app.key` as its TLS paths and these three +distinct private first hops. + +| Session route | Upstream | Rewrite | +| --- | --- | --- | +| `/registry/businesses/` | `registry=127.0.0.1:8100` | `/` | +| `/api/functions/` | `functions=127.0.0.1:8300` | `/functions/` | +| `/apply/` | `pages=127.0.0.1:8200` | `/` | + +```bash +session=("$REFERENCE_ARTIFACTS/registry-session" --runtime-config "$RECIPE/session.yaml") +"${session[@]}" gateway envoy --posture production \ + --standalone-out "$REFERENCE_CONFIG/gateway/envoy.yaml" --listen 127.0.0.1:8443 \ + --upstream registry=127.0.0.1:8100 --upstream pages=127.0.0.1:8200 \ + --upstream functions=127.0.0.1:8300 \ + --tls-certificate /run/tls/app.crt --tls-key /run/tls/app.key +"${session[@]}" gateway envoy --posture production \ + --verify-assembled "$REFERENCE_CONFIG/gateway/envoy.yaml" \ + --route-inventory-out "$REFERENCE_CONFIG/gateway/route-inventory.json" --checked-route businesses +``` + +Only the `businesses` module supplies the browser's product-client route +inventory. The Compose startup verifies the supplied Envoy file against Session +and installs exactly the verified bytes before Envoy starts. The application +and BReg share the upstream namespace. Session's check listener is in the +separate gateway namespace. The two Envoy relays connect these namespaces over +three private owner-only Unix sockets. The host app port passes TLS through to +the Session-checked gateway. + +## Start with empty state + +Set `REFERENCE_ENV` to the absolute path of the Compose environment file. +Choose a unique project name. Extract the database scripts before starting +PostgreSQL. The initialization script creates only ThunderID's four databases +and applies the matching schemas as the ThunderID role. + +```bash +compose=(docker compose --project-name business-reference \ + --env-file "$REFERENCE_ENV" --file "$RECIPE/compose.yaml") + +mkdir -p "$REFERENCE_CONFIG/postgres/schema" +for schema in config:configdb entity:entitydb runtime_transient:runtime_transient runtime_persistent:runtime_persistent; do + "${compose[@]}" run -T --rm --no-deps --entrypoint cat thunderid-setup \ + "dbscripts/${schema#*:}/postgres.sql" > "$REFERENCE_CONFIG/postgres/schema/${schema%%:*}.sql" +done + +"${compose[@]}" up --detach --wait postgres +"${compose[@]}" run -T --rm thunderid-setup + +"${compose[@]}" run -T --rm breg-admin provision --posture production \ + --runtime-config /run/breg/runtime.yaml --admin-url-file /run/breg/secrets/admin-database-url +"${compose[@]}" run -T --rm breg-admin apply --posture production --initial \ + --runtime-config /run/breg/runtime.yaml --package /run/breg/package \ + --expected-digest "$BREG_PACKAGE_DIGEST" + +"${compose[@]}" up --wait --wait-timeout 60 --build +"${compose[@]}" ps +``` + +The ThunderID setup job creates the built-in password flow first. The serving +issuer then loads the registrar app and user from the generated resources. +Before BReg starts, a one-shot checks the issuer's HTTPS discovery document and +signing keys from BReg's network namespace. +The setup containers are for fresh state. PostgreSQL data and ThunderID signing +and encryption material live in project-owned volumes. `docker compose stop` +preserves those volumes. Session state is in memory and a Session restart +requires signing in again. + +## Check the routes + +Run `bash "$RECIPE/tests/smoke.sh" "$REFERENCE_CONFIG/trust/https-ca.pem"`. +The probe checks TLS, the issuer discovery document and administrative route +refusals, the sign-in redirect, and Session and origin refusals. Then open +`https://127.0.0.1:8443/apply/`, sign in as the disposable registrar and +register a synthetic business. The page should show its Record ID from BReg. +Verify the Record through the same BReg route and registrar session. + +Release-candidate smoke wiring, published Session and Coordinator images, +and the `rstack dev` route-parity gate are v0.52 work. diff --git a/deploy/examples/business-registration/breg-runtime.yaml b/deploy/examples/business-registration/breg-runtime.yaml new file mode 100644 index 0000000000..8717e1b804 --- /dev/null +++ b/deploy/examples/business-registration/breg-runtime.yaml @@ -0,0 +1,43 @@ +apiVersion: id.registrystack.org/formats/breg/runtime/v1alpha1 +kind: BRegRuntimeConfig +listener: + bind: 127.0.0.1:8100 + publicOrigin: https://127.0.0.1:8443/registry/businesses +identity: + environment: reference + instanceId: business-registration + databaseId: business-registration +secretProviders: + file: + root: /run/breg/secrets +database: + transport: verified-tls + runtimeUrlRef: secret:file/runtime-database-url + migrationUrlRef: secret:file/migration-database-url + caBundleRef: secret:file/database-ca + pool: + maximumConnections: 4 + roles: + runtime: breg_runtime + migration: breg_migration +package: + root: /run/breg/package +authentication: + oidc: + issuers: + thunderid: + issuer: https://identity.reference.test:9443 + audience: urn:example:business-register + allowedAlgorithm: RS256 + scopeClaim: scope + scopeSeparator: " " + allowedClients: [business-registrar] + maximumTokenLifetimeSeconds: 3600 + leewayMilliseconds: 30000 + authorityClaims: + principal: sub +audit: + hashKeyRef: secret:file/audit-key + path: /var/lib/breg/audit.jsonl +cursor: + secretRef: secret:file/cursor-key diff --git a/deploy/examples/business-registration/check-gateway.sh b/deploy/examples/business-registration/check-gateway.sh new file mode 100644 index 0000000000..23bd2b921f --- /dev/null +++ b/deploy/examples/business-registration/check-gateway.sh @@ -0,0 +1,10 @@ +#!/usr/bin/env bash +set -euo pipefail + +session=(/opt/native/registry-session --runtime-config /run/reference/session.yaml) +"${session[@]}" check --posture production --deny-warnings --identity-receipt /run/reference/identity-receipt.json +candidate=$(mktemp /run/gateway/envoy.XXXXXX) +trap 'rm -f -- "$candidate"' EXIT +cp -- /run/gateway-input/envoy.yaml "$candidate" +"${session[@]}" gateway envoy --posture production --verify-assembled "$candidate" +mv -f -- "$candidate" /run/gateway/envoy.yaml diff --git a/deploy/examples/business-registration/compose.yaml b/deploy/examples/business-registration/compose.yaml new file mode 100644 index 0000000000..5a193cdf35 --- /dev/null +++ b/deploy/examples/business-registration/compose.yaml @@ -0,0 +1,235 @@ +x-native: &native + image: ubuntu:24.04@sha256:73b999393d07f2bf65a40373778a44dc9a6d54ad7718d29247d8ff9413c4d6a8 + user: "${REFERENCE_UID:-1000}:${REFERENCE_GID:-1000}" + read_only: true + cap_drop: [ALL] + security_opt: [no-new-privileges:true] + +x-envoy: &envoy + image: envoyproxy/envoy:v1.39.6@sha256:1fde8efee875e4e4f6a39a90fe49d9338e1caacce5762034ef9fb4bbb9ad6aed + user: "${REFERENCE_UID:-1000}:${REFERENCE_GID:-1000}" + entrypoint: [envoy, --disable-hot-restart] + read_only: true + cap_drop: [ALL] + security_opt: [no-new-privileges:true] + +x-thunderid: &thunderid + image: ghcr.io/thunder-id/thunderid:1.0.1@sha256:d3c0613ff447a551fd440768a15bdfb6668948e80809cbb50f82d6752f22ab3e + entrypoint: [bash, /run/reference/thunderid.sh] + read_only: true + cap_drop: [ALL] + security_opt: [no-new-privileges:true] + tmpfs: [/tmp] + environment: + PGSSLROOTCERT: /run/trust/postgres-ca.pem + depends_on: + postgres: + condition: service_healthy + +services: + edge: + <<: *envoy + command: [-c, /run/reference/edge.yaml] + ports: + - "127.0.0.1:8443:8080" + - "127.0.0.1:9443:9443" + volumes: + - ./edge.yaml:/run/reference/edge.yaml:ro + - ${REFERENCE_CONFIG:?Set REFERENCE_CONFIG}/issuer-tls:/run/tls:ro + - ${REFERENCE_CONFIG}/relay:/run/relay:ro + networks: + ingress: + issuer: + aliases: [identity.reference.test] + issuer-front: + + upstreams: + <<: *envoy + command: [-c, /run/reference/upstreams.yaml] + volumes: + - ./upstreams.yaml:/run/reference/upstreams.yaml:ro + - ${REFERENCE_CONFIG}/relay:/run/relay + networks: [issuer, database] + + gateway-check: + <<: *native + network_mode: none + entrypoint: [bash, /run/reference/check-gateway.sh] + volumes: + - ./check-gateway.sh:/run/reference/check-gateway.sh:ro + - ./session.yaml:/run/reference/session.yaml:ro + - ${REFERENCE_ARTIFACTS:?Set REFERENCE_ARTIFACTS}/registry-session:/opt/native/registry-session:ro + - ${REFERENCE_CONFIG}/gateway:/run/gateway-input:ro + - ${REFERENCE_CONFIG}/gateway-checked:/run/gateway + - ${REFERENCE_CONFIG}/thunderid/identity-receipt.json:/run/reference/identity-receipt.json:ro + + gateway: + <<: *envoy + network_mode: service:edge + command: [-c, /run/gateway/envoy.yaml] + volumes: + - ${REFERENCE_CONFIG}/gateway-checked:/run/gateway:ro + - ${REFERENCE_CONFIG}/app-tls:/run/tls:ro + depends_on: + gateway-check: + condition: service_completed_successfully + + session: + <<: *native + network_mode: service:edge + entrypoint: [/opt/native/registry-session] + command: [--runtime-config, /run/reference/session.yaml, --posture, production] + environment: + SSL_CERT_FILE: /run/trust/https-ca.pem + volumes: + - ./session.yaml:/run/reference/session.yaml:ro + - ${REFERENCE_ARTIFACTS}/registry-session:/opt/native/registry-session:ro + - ${REFERENCE_CONFIG}/session/secrets:/run/session-secrets:ro + - ${REFERENCE_CONFIG}/session/audit:/var/lib/session + - ${REFERENCE_CONFIG}/trust:/run/trust:ro + + application: + build: . + user: "${REFERENCE_UID:-1000}:${REFERENCE_GID:-1000}" + network_mode: service:upstreams + read_only: true + init: true + cap_drop: [ALL] + security_opt: [no-new-privileges:true] + environment: + BUSINESS_BUNDLE: /run/bundle + BUSINESS_BUNDLE_SHA256: ${BUSINESS_BUNDLE_SHA256:?Set BUSINESS_BUNDLE_SHA256} + volumes: + - ${BUSINESS_BUNDLE:?Set BUSINESS_BUNDLE}:/run/bundle:ro + + issuer-ready: + image: node:24.22.3@sha256:dc26ae92c9fb15cf6b1d63e20f0944b2efe0f115b20e00be48fb23fceb061c54 + user: "${REFERENCE_UID:-1000}:${REFERENCE_GID:-1000}" + network_mode: service:upstreams + read_only: true + cap_drop: [ALL] + security_opt: [no-new-privileges:true] + command: [node, /run/reference/issuer-ready.mjs] + environment: + NODE_EXTRA_CA_CERTS: /run/trust/https-ca.pem + volumes: + - ./issuer-ready.mjs:/run/reference/issuer-ready.mjs:ro + - ${REFERENCE_CONFIG}/trust:/run/trust:ro + depends_on: + edge: + condition: service_started + identity-gateway: + condition: service_started + thunderid: + condition: service_started + + breg: + <<: *native + network_mode: service:upstreams + entrypoint: [/opt/native/breg] + command: [--runtime-config, /run/breg/runtime.yaml, --posture, production] + environment: + SSL_CERT_FILE: /run/trust/https-ca.pem + volumes: + - ${REFERENCE_ARTIFACTS}/breg:/opt/native/breg:ro + - ${REFERENCE_CONFIG}/breg/runtime:/run/breg:ro + - ${REFERENCE_CONFIG}/breg/audit:/var/lib/breg + - ${REFERENCE_CONFIG}/trust:/run/trust:ro + depends_on: + postgres: + condition: service_healthy + issuer-ready: + condition: service_completed_successfully + + breg-admin: + <<: *native + profiles: [setup] + networks: [database] + entrypoint: [/opt/native/bregctl] + environment: + SSL_CERT_FILE: /run/trust/https-ca.pem + volumes: + - ${REFERENCE_ARTIFACTS}/bregctl:/opt/native/bregctl:ro + - ${REFERENCE_CONFIG}/breg/admin:/run/breg:ro + - ${REFERENCE_CONFIG}/breg/audit:/var/lib/breg + - ${REFERENCE_CONFIG}/trust:/run/trust:ro + depends_on: + postgres: + condition: service_healthy + + identity-gateway: + <<: *envoy + command: [-c, /run/identity/envoy.yaml] + volumes: + - ${REFERENCE_CONFIG}/thunderid/front-gateway:/run/identity:ro + networks: [issuer-front, identity-backend] + + thunderid: + <<: *thunderid + command: [serve] + networks: [identity-backend, identity-database] + volumes: + - &issuer-launch ./thunderid.sh:/run/reference/thunderid.sh:ro + - ${REFERENCE_CONFIG}/thunderid/deployment.yaml:/opt/thunderid/deployment.yaml:ro + - ${REFERENCE_CONFIG}/thunderid/resources:/opt/thunderid/config/resources:ro + - ${REFERENCE_CONFIG}/thunderid/secrets:/run/identity-secrets:ro + - &issuer-trust ${REFERENCE_CONFIG}/trust:/run/trust:ro + - &issuer-certs issuer-certs:/opt/thunderid/config/certs + - &issuer-secrets issuer-secrets:/opt/thunderid/config/secrets + + thunderid-setup: + <<: *thunderid + command: [setup] + profiles: [setup] + networks: [identity-database] + volumes: + - *issuer-launch + - ${REFERENCE_CONFIG}/thunderid/bootstrap.yaml:/opt/thunderid/deployment.yaml:ro + - ${REFERENCE_CONFIG}/thunderid/bootstrap-secrets:/run/identity-secrets:ro + - *issuer-trust + - *issuer-certs + - *issuer-secrets + + postgres: + image: postgres:17.11@sha256:ff87138949ad9a46f32ff23bd6852b52ce024a13dffe9b4087be98292cdd3b4f + environment: + POSTGRES_PASSWORD_FILE: /run/postgres/bootstrap-password + command: + - postgres + - -c + - ssl=on + - -c + - ssl_cert_file=/run/postgres/server.crt + - -c + - ssl_key_file=/run/postgres/server.key + - -c + - hba_file=/run/reference/pg_hba.conf + volumes: + - postgres-data:/var/lib/postgresql/data + - ${REFERENCE_CONFIG}/postgres:/run/postgres:ro + - ./pg_hba.conf:/run/reference/pg_hba.conf:ro + - ./init-postgres.sh:/docker-entrypoint-initdb.d/10-identity.sh:ro + healthcheck: + test: [CMD, pg_isready, -h, 127.0.0.1, -U, postgres] + interval: 2s + timeout: 2s + retries: 30 + networks: [database, identity-database] + +networks: + ingress: + issuer: + internal: true + issuer-front: + internal: true + identity-backend: + internal: true + database: + internal: true + identity-database: + internal: true + +volumes: + postgres-data: + issuer-certs: + issuer-secrets: diff --git a/deploy/examples/business-registration/edge.yaml b/deploy/examples/business-registration/edge.yaml new file mode 100644 index 0000000000..9e29da5cb1 --- /dev/null +++ b/deploy/examples/business-registration/edge.yaml @@ -0,0 +1,128 @@ +static_resources: + listeners: + - name: app_tcp + address: + socket_address: {address: 0.0.0.0, port_value: 8080} + filter_chains: + - filters: + - name: envoy.filters.network.tcp_proxy + typed_config: + "@type": type.googleapis.com/envoy.extensions.filters.network.tcp_proxy.v3.TcpProxy + stat_prefix: app_tcp + cluster: app_tls + - name: issuer_https + address: + socket_address: {address: 0.0.0.0, port_value: 9443} + filter_chains: + - transport_socket: + name: envoy.transport_sockets.tls + typed_config: + "@type": type.googleapis.com/envoy.extensions.transport_sockets.tls.v3.DownstreamTlsContext + common_tls_context: + tls_params: {tls_minimum_protocol_version: TLSv1_2} + tls_certificates: + - certificate_chain: {filename: /run/tls/issuer.crt} + private_key: {filename: /run/tls/issuer.key} + filters: + - name: envoy.filters.network.http_connection_manager + typed_config: + "@type": type.googleapis.com/envoy.extensions.filters.network.http_connection_manager.v3.HttpConnectionManager + stat_prefix: issuer_https + use_remote_address: true + normalize_path: true + merge_slashes: true + path_with_escaped_slashes_action: REJECT_REQUEST + route_config: + name: issuer + virtual_hosts: + - name: issuer + domains: ["identity.reference.test:9443"] + routes: + - match: {prefix: /} + route: {cluster: issuer_front} + http_filters: + - name: envoy.filters.http.router + typed_config: + "@type": type.googleapis.com/envoy.extensions.filters.http.router.v3.Router + # Checked Envoy reaches these three private, distinct first hops. + - name: to_registry + address: + socket_address: {address: 127.0.0.1, port_value: 8100} + filter_chains: + - filters: + - name: envoy.filters.network.tcp_proxy + typed_config: + "@type": type.googleapis.com/envoy.extensions.filters.network.tcp_proxy.v3.TcpProxy + stat_prefix: to_registry + cluster: registry_socket + - name: to_pages + address: + socket_address: {address: 127.0.0.1, port_value: 8200} + filter_chains: + - filters: + - name: envoy.filters.network.tcp_proxy + typed_config: + "@type": type.googleapis.com/envoy.extensions.filters.network.tcp_proxy.v3.TcpProxy + stat_prefix: to_pages + cluster: pages_socket + - name: to_functions + address: + socket_address: {address: 127.0.0.1, port_value: 8300} + filter_chains: + - filters: + - name: envoy.filters.network.tcp_proxy + typed_config: + "@type": type.googleapis.com/envoy.extensions.filters.network.tcp_proxy.v3.TcpProxy + stat_prefix: to_functions + cluster: functions_socket + clusters: + - name: app_tls + type: STATIC + connect_timeout: 2s + load_assignment: + cluster_name: app_tls + endpoints: + - lb_endpoints: + - endpoint: + address: + socket_address: {address: 127.0.0.1, port_value: 8443} + - name: issuer_front + type: STRICT_DNS + connect_timeout: 2s + load_assignment: + cluster_name: issuer_front + endpoints: + - lb_endpoints: + - endpoint: + address: + socket_address: {address: identity-gateway, port_value: 8080} + - name: registry_socket + type: STATIC + connect_timeout: 2s + load_assignment: + cluster_name: registry_socket + endpoints: + - lb_endpoints: + - endpoint: + address: + pipe: {path: /run/relay/registry.sock} + - name: pages_socket + type: STATIC + connect_timeout: 2s + load_assignment: + cluster_name: pages_socket + endpoints: + - lb_endpoints: + - endpoint: + address: + pipe: {path: /run/relay/pages.sock} + - name: functions_socket + type: STATIC + connect_timeout: 2s + load_assignment: + cluster_name: functions_socket + endpoints: + - lb_endpoints: + - endpoint: + address: + pipe: {path: /run/relay/functions.sock} diff --git a/deploy/examples/business-registration/host.mjs b/deploy/examples/business-registration/host.mjs new file mode 100644 index 0000000000..9349b467d1 --- /dev/null +++ b/deploy/examples/business-registration/host.mjs @@ -0,0 +1,132 @@ +import { createHash } from 'node:crypto' +import { readFile, realpath } from 'node:fs/promises' +import { isAbsolute, join, relative, sep } from 'node:path' +import { pathToFileURL } from 'node:url' +import { serve } from 'srvx/node' + +const functionName = 'register-business' +const functionPath = '/functions/' + functionName +const pages = new Map([ + ['/index.html', 'text/html; charset=utf-8'], + ['/app.js', 'text/javascript; charset=utf-8'], + ['/service.css', 'text/css; charset=utf-8'], +]) + +async function readBundleFile(root, path) { + const resolved = await realpath(join(root, path)) + const location = relative(root, resolved) + if (location === '..' || location.startsWith('..' + sep) || isAbsolute(location)) { + throw new Error('A runtime file leaves the bundle.') + } + return readFile(resolved) +} + +async function readBundle(directory) { + if (!isAbsolute(directory ?? '')) throw new Error('Use an absolute preview bundle directory.') + const root = await realpath(directory) + const manifestBytes = await readBundleFile(root, 'manifest.json') + const manifest = JSON.parse(manifestBytes) + if (manifest.product?.id !== 'businesses' || manifest.product.profile !== 'business-registrar' + || !Array.isArray(manifest.functions) || manifest.functions.length !== 1 || manifest.functions[0] !== functionName + || typeof manifest.staticOutput !== 'string' || !manifest.staticOutput || isAbsolute(manifest.staticOutput)) { + throw new Error('Use the business-registration preview bundle.') + } + const modulePath = 'functions/' + functionName + '.mjs' + const files = new Map([['manifest.json', manifestBytes]]) + for (const path of [modulePath, ...Array.from(pages.keys(), name => join(manifest.staticOutput, name))]) { + files.set(path, await readBundleFile(root, path)) + } + const hashes = Array.from(files, ([path, bytes]) => [path, createHash('sha256').update(bytes).digest('hex')]) + const digest = createHash('sha256').update(JSON.stringify(hashes)).digest('hex') + return { + digest, + module: files.get(modulePath), + assets: new Map(Array.from(pages.keys(), path => [path, files.get(join(manifest.staticOutput, path))])), + } +} + +export async function bundleDigest(directory) { + return (await readBundle(directory)).digest +} + +async function requestFunction(request, handle) { + const url = new URL(request.url) + if (url.pathname !== functionPath || url.search) return new Response(null, { status: 404 }) + if (request.method !== 'POST') return new Response(null, { status: 405, headers: { allow: 'POST' } }) + // The checked Envoy route supplies the caller's bearer over private loopback. + if (!/^Bearer [A-Za-z0-9._-]+$/u.test(request.headers.get('authorization') ?? '')) { + return new Response(null, { status: 401, headers: { 'cache-control': 'no-store' } }) + } + // Read through srvx's limit before the function can catch a body read error. + const body = await request.arrayBuffer() + return handle(new Request(request.url, { method: request.method, headers: request.headers, body })) +} + +function requestPage(request, assets) { + const pathname = new URL(request.url).pathname + const path = pathname === '/' ? '/index.html' : pathname + const bytes = assets.get(path) + if (!bytes) return new Response(null, { status: 404 }) + if (request.method !== 'GET' && request.method !== 'HEAD') { + return new Response(null, { status: 405, headers: { allow: 'GET, HEAD' } }) + } + return new Response(request.method === 'GET' ? bytes : null, { + headers: { 'content-type': pages.get(path), 'x-content-type-options': 'nosniff' }, + }) +} + +export async function startHost(directory, expectedDigest, { functionsPort = 8300, pagesPort = 8200 } = {}) { + const bundle = await readBundle(directory) + if (bundle.digest !== expectedDigest) throw new Error('The preview bundle digest differs from the deployment pin.') + // Import the bytes that were checked. The compiler emits a self-contained ESM module. + const { default: createHandler } = await import('data:text/javascript;base64,' + bundle.module.toString('base64')) + const handle = await createHandler({ products: { businesses: { baseUrl: 'http://127.0.0.1:8100' } } }) + if (typeof handle !== 'function') throw new TypeError('The compiled registration module must create a handler.') + + const options = { hostname: '127.0.0.1', silent: true, gracefulShutdown: false } + const functions = serve({ + ...options, + port: functionsPort, + maxRequestBodySize: 32_768, + fetch: request => requestFunction(request, handle), + error(error) { + if (error?.code === 'ERR_BODY_TOO_LARGE') return new Response(null, { status: 413 }) + console.error('The registration function could not complete its request.') + return new Response(null, { status: 500 }) + }, + }) + const staticPages = serve({ ...options, port: pagesPort, fetch: request => requestPage(request, bundle.assets) }) + try { + await Promise.all([functions.ready(), staticPages.ready()]) + } catch (error) { + await Promise.allSettled([functions.close(true), staticPages.close(true)]) + throw error + } + return { + functionsOrigin: new URL(functions.url).origin, + pagesOrigin: new URL(staticPages.url).origin, + close: () => Promise.all([functions.close(true), staticPages.close(true)]), + } +} + +if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { + if (process.argv[2] === '--digest') { + console.log(await bundleDigest(process.argv[3])) + } else { + try { + const host = await startHost(process.env.BUSINESS_BUNDLE, process.env.BUSINESS_BUNDLE_SHA256) + const stop = () => host.close().catch(() => { + console.error('The reference host could not close its listeners.') + process.exitCode = 1 + }) + process.once('SIGINT', stop) + process.once('SIGTERM', stop) + } catch (error) { + const message = error.message === 'The preview bundle digest differs from the deployment pin.' + ? error.message + : 'The reference host could not load its checked bundle or start its private listeners.' + console.error(message) + process.exitCode = 1 + } + } +} diff --git a/deploy/examples/business-registration/identity-deployment.yaml b/deploy/examples/business-registration/identity-deployment.yaml new file mode 100644 index 0000000000..43a47ebd08 --- /dev/null +++ b/deploy/examples/business-registration/identity-deployment.yaml @@ -0,0 +1,28 @@ +apiVersion: id.registrystack.org/formats/platform/identity-deployment/v1 +kind: PlatformIdentityDeployment +organizationUnit: + handle: business-registration + name: Business registration +personAudience: urn:example:business-register +sessionApps: + - id: business-registrar + clientSecretRef: secret:env/REGISTRAR_CLIENT_SECRET + origin: https://127.0.0.1:8443 + redirectUris: [https://127.0.0.1:8443/session/callback] + postLogoutRedirectUris: [https://127.0.0.1:8443/session/signed-out] + products: [breg] + tokenAttributes: [registry_actor_kind, registry_office] + grants: + - product: breg + accessProfiles: [business-registrar] +users: + - id: reference-registrar + username: reference-registrar + email: reference-registrar@example.invalid + passwordRef: secret:env/REGISTRAR_PASSWORD + claims: + registry_actor_kind: human + registry_office: central + grants: + - product: breg + accessProfiles: [business-registrar] diff --git a/deploy/examples/business-registration/init-postgres.sh b/deploy/examples/business-registration/init-postgres.sh new file mode 100755 index 0000000000..97420da574 --- /dev/null +++ b/deploy/examples/business-registration/init-postgres.sh @@ -0,0 +1,25 @@ +#!/usr/bin/env bash +set -euo pipefail + +THUNDERID_DB_PASSWORD=$(&2 + exit 1 +fi +export THUNDERID_DB_PASSWORD +psql --username postgres --dbname postgres --set ON_ERROR_STOP=1 <<'SQL' +SET log_min_error_statement = panic; +\getenv thunderid_password THUNDERID_DB_PASSWORD +CREATE ROLE thunderid LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE PASSWORD :'thunderid_password'; +CREATE DATABASE thunderid_config OWNER thunderid; +CREATE DATABASE thunderid_runtime_transient OWNER thunderid; +CREATE DATABASE thunderid_entity OWNER thunderid; +CREATE DATABASE thunderid_runtime_persistent OWNER thunderid; +REVOKE CONNECT ON DATABASE thunderid_config, thunderid_runtime_transient, thunderid_entity, thunderid_runtime_persistent FROM PUBLIC; +SQL +unset THUNDERID_DB_PASSWORD + +for database in config entity runtime_transient runtime_persistent; do + psql --username postgres --dbname "thunderid_$database" --set ON_ERROR_STOP=1 \ + --command 'SET ROLE thunderid' --file "/run/postgres/schema/$database.sql" +done diff --git a/deploy/examples/business-registration/issuer-ready.mjs b/deploy/examples/business-registration/issuer-ready.mjs new file mode 100644 index 0000000000..46c931385b --- /dev/null +++ b/deploy/examples/business-registration/issuer-ready.mjs @@ -0,0 +1,34 @@ +import { setTimeout as pause } from 'node:timers/promises' + +const issuer = 'https://identity.reference.test:9443' +const jwksUrl = issuer + '/oauth2/jwks' + +async function get(url) { + const response = await fetch(url, { signal: AbortSignal.timeout(1500), redirect: 'error' }) + if (!response.ok) throw new Error('HTTP ' + response.status) + return response.json() +} + +async function waitForIssuer() { + const deadline = Date.now() + 30_000 + let failure + do { + try { + const discovery = await get(issuer + '/.well-known/openid-configuration') + if (discovery.issuer === issuer && discovery.jwks_uri === jwksUrl) { + const { keys } = await get(jwksUrl) + if (Array.isArray(keys) && keys.length > 0) return true + failure = 'signing keys missing' + } else { + failure = 'unexpected discovery metadata' + } + } catch (error) { + failure = error.cause?.code ?? error.name + } + await pause(500) + } while (Date.now() < deadline) + console.error('The reference issuer did not become ready: ' + failure) + return false +} + +if (!(await waitForIssuer())) process.exitCode = 1 diff --git a/deploy/examples/business-registration/package-lock.json b/deploy/examples/business-registration/package-lock.json new file mode 100644 index 0000000000..d2a97cca06 --- /dev/null +++ b/deploy/examples/business-registration/package-lock.json @@ -0,0 +1,28 @@ +{ + "name": "registry-business-registration-reference", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "registry-business-registration-reference", + "dependencies": { + "srvx": "1.0.8" + }, + "engines": { + "node": ">=24 <25" + } + }, + "node_modules/srvx": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/srvx/-/srvx-1.0.8.tgz", + "integrity": "sha512-ngFS/J6St4PJfHRHGjr78xkPPtbyXtdMOLNE4x/XZunEK3OhV7aGUWMHf9WTUEy6wm1U0W4okkd82ZFFWRVQTw==", + "license": "MIT", + "bin": { + "srvx": "bin/srvx.mjs" + }, + "engines": { + "node": ">=20.16.0" + } + } + } +} diff --git a/deploy/examples/business-registration/package.json b/deploy/examples/business-registration/package.json new file mode 100644 index 0000000000..5816515a72 --- /dev/null +++ b/deploy/examples/business-registration/package.json @@ -0,0 +1,7 @@ +{ + "name": "registry-business-registration-reference", + "private": true, + "engines": { "node": ">=24 <25" }, + "dependencies": { "srvx": "1.0.8" }, + "scripts": { "test": "node --test tests/host.test.mjs" } +} diff --git a/deploy/examples/business-registration/pg_hba.conf b/deploy/examples/business-registration/pg_hba.conf new file mode 100644 index 0000000000..1a2304cecb --- /dev/null +++ b/deploy/examples/business-registration/pg_hba.conf @@ -0,0 +1,3 @@ +local all all peer +hostssl all all 0.0.0.0/0 scram-sha-256 +hostssl all all ::/0 scram-sha-256 diff --git a/deploy/examples/business-registration/session.yaml b/deploy/examples/business-registration/session.yaml new file mode 100644 index 0000000000..8e9d433af8 --- /dev/null +++ b/deploy/examples/business-registration/session.yaml @@ -0,0 +1,54 @@ +apiVersion: id.registrystack.org/formats/platform/session-runtime/v1alpha1 +kind: PlatformSessionRuntimeConfig +listener: + bind: 127.0.0.1:8120 + tlsTermination: operator-controlled-upstream +checkListener: 127.0.0.1:8121 +publicOrigin: https://127.0.0.1:8443 +secretProviders: + file: + root: /run/session-secrets +issuer: + id: https://identity.reference.test:9443 + authorization: https://identity.reference.test:9443/oauth2/authorize + endSession: https://identity.reference.test:9443/oauth2/logout + token: https://identity.reference.test:9443/oauth2/token + revocation: https://identity.reference.test:9443/oauth2/revoke + jwks: https://identity.reference.test:9443/oauth2/jwks +personAudience: urn:example:business-register +gateway: + service: + host: 127.0.0.1 + publicPort: 8120 + checkPort: 8121 +modules: + - id: businesses + product: breg + prefix: /registry/businesses/ + audience: person + signIns: [registrar] + upstream: + cluster: registry + prefixRewrite: / + - id: functions + product: breg + prefix: /api/functions/ + audience: person + signIns: [registrar] + upstream: + cluster: functions + prefixRewrite: /functions/ +pages: + - prefix: /apply/ + signIn: registrar + upstream: + cluster: pages + prefixRewrite: / +signIns: + registrar: + clientId: business-registrar + clientSecretRef: secret:file/registrar-client + scopes: [registry:business:register] +audit: + hashKeyRef: secret:file/audit-key + path: /var/lib/session/audit.jsonl diff --git a/deploy/examples/business-registration/tests/host.test.mjs b/deploy/examples/business-registration/tests/host.test.mjs new file mode 100644 index 0000000000..d9a79d5529 --- /dev/null +++ b/deploy/examples/business-registration/tests/host.test.mjs @@ -0,0 +1,69 @@ +import assert from 'node:assert/strict' +import { mkdtemp, mkdir, writeFile, rm, symlink } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { test } from 'node:test' +import { bundleDigest, startHost } from '../host.mjs' + +async function fixture(t) { + const root = await mkdtemp(join(tmpdir(), 'reference-host-test-')) + t.after(() => rm(root, { recursive: true })) + await mkdir(join(root, 'functions')) + await mkdir(join(root, 'project/web/dist'), { recursive: true }) + const manifest = { + product: { id: 'businesses', profile: 'business-registrar' }, + functions: ['register-business'], + staticOutput: 'project/web/dist', + } + await writeFile(join(root, 'manifest.json'), JSON.stringify(manifest)) + await writeFile(join(root, 'functions/register-business.mjs'), ` + export default ({ products }) => request => { + if (products.businesses.baseUrl !== 'http://127.0.0.1:8100') throw new Error('Wrong upstream') + return Response.json({ caller: request.headers.get('authorization') === 'Bearer synthetic.caller.token' }) + } + `) + for (const name of ['index.html', 'app.js', 'service.css']) { + await writeFile(join(root, 'project/web/dist', name), name) + } + return root +} + +test('loads the checked bundle and serves only the declared function and page assets', async t => { + const root = await fixture(t) + const host = await startHost(root, await bundleDigest(root), { functionsPort: 0, pagesPort: 0 }) + t.after(host.close) + const route = host.functionsOrigin + '/functions/register-business' + const headers = { authorization: 'Bearer synthetic.caller.token' } + + assert.equal((await fetch(route, { method: 'POST' })).status, 401) + assert.equal((await fetch(route, { method: 'POST', headers: { authorization: 'Bearer a, Bearer b' } })).status, 401) + assert.equal((await fetch(route, { headers })).status, 405) + assert.equal((await fetch(route + '?unexpected=true', { method: 'POST', headers })).status, 404) + assert.deepEqual(await (await fetch(route, { method: 'POST', headers })).json(), { caller: true }) + assert.equal((await fetch(route, { method: 'POST', headers, body: 'x'.repeat(32_769) })).status, 413) + + const page = await fetch(host.pagesOrigin) + assert.equal((await page.text()), 'index.html') + assert.equal(page.headers.get('content-type'), 'text/html; charset=utf-8') + assert.equal(page.headers.get('x-content-type-options'), 'nosniff') + assert.equal((await fetch(host.pagesOrigin + '/app.js', { method: 'HEAD' })).status, 200) + assert.equal((await fetch(host.pagesOrigin + '/app.js', { method: 'POST' })).status, 405) + for (const path of ['/manifest.json', '/functions/register-business.mjs', '/project/web/dist/index.html']) { + assert.equal((await fetch(host.pagesOrigin + path)).status, 404) + } +}) + +test('refuses changed bundles before importing function code', async t => { + const root = await fixture(t) + const expected = await bundleDigest(root) + await writeFile(join(root, 'functions/register-business.mjs'), 'throw new Error("never import this")') + await assert.rejects(startHost(root, expected), /bundle digest differs/) +}) + +test('refuses files that resolve outside the bundle', async t => { + const root = await fixture(t) + const file = join(root, 'project/web/dist/app.js') + await rm(file) + await symlink('/etc/hosts', file) + await assert.rejects(bundleDigest(root), /leaves the bundle/) +}) diff --git a/deploy/examples/business-registration/tests/smoke.sh b/deploy/examples/business-registration/tests/smoke.sh new file mode 100755 index 0000000000..e23a23bc9c --- /dev/null +++ b/deploy/examples/business-registration/tests/smoke.sh @@ -0,0 +1,33 @@ +#!/usr/bin/env bash +set -euo pipefail + +ca=${1:?Pass the HTTPS CA file for the disposable reference stack.} +app=https://127.0.0.1:8443 +issuer=https://identity.reference.test:9443 +http=(curl --silent --show-error --noproxy '*' --cacert "$ca" --max-time 10) +identity=("${http[@]}" --resolve identity.reference.test:9443:127.0.0.1) + +expect_status() { + local expected=$1 status + shift + status=$("$@" --output /dev/null --write-out '%{http_code}') + if [[ "$status" != "$expected" ]]; then + printf 'Expected HTTP %s, received %s.\n' "$expected" "$status" >&2 + exit 1 + fi +} + +"${identity[@]}" --fail "$issuer/.well-known/openid-configuration" | + jq -e --arg issuer "$issuer" '.issuer == $issuer' >/dev/null +expect_status 404 "${identity[@]}" "$issuer/applications" +expect_status 403 "${identity[@]}" -H 'X-HTTP-Method-Override: GET' "$issuer/.well-known/openid-configuration" +expect_status 302 "${http[@]}" "$app/apply/" +expect_status 401 "${http[@]}" -H 'Registry-Client: page' "$app/registry/businesses/v1/records/businesses" +function_call=("${http[@]}" -X POST -H 'Registry-Client: page' -H "Origin: $app" + -H 'Authorization: Bearer synthetic.browser.value' "$app/api/functions/register-business") +expect_status 401 "${function_call[@]}" +"${function_call[@]}" | jq -e '.code == "session.expired"' >/dev/null +expect_status 403 "${http[@]}" -X POST -H 'Registry-Client: page' -H "Origin: $issuer" \ + "$app/api/functions/register-business" +expect_status 404 "${http[@]}" "$app/check/businesses" +printf 'HTTPS issuer, private routes, signed-in page redirect and session refusals passed.\n' diff --git a/deploy/examples/business-registration/tests/test_compose.py b/deploy/examples/business-registration/tests/test_compose.py new file mode 100644 index 0000000000..b6a38096f8 --- /dev/null +++ b/deploy/examples/business-registration/tests/test_compose.py @@ -0,0 +1,80 @@ +"""Check the reference's published listeners and private service boundaries.""" + +import json +import os +from pathlib import Path +import shutil +import subprocess +import unittest + + +EXAMPLE = Path(__file__).resolve().parents[1] +DOCKER = shutil.which("docker") + + +@unittest.skipUnless(DOCKER, "Docker Compose is needed to render the reference") +class ComposeReference(unittest.TestCase): + @classmethod + def setUpClass(cls): + if subprocess.run([DOCKER, "compose", "version"], capture_output=True).returncode: + raise unittest.SkipTest("The Docker Compose plugin is unavailable") + env = dict(os.environ, REFERENCE_CONFIG="/reference/config", REFERENCE_ARTIFACTS="/reference/bin", + BUSINESS_BUNDLE="/reference/bundle", BUSINESS_BUNDLE_SHA256="0" * 64) + rendered = subprocess.run( + [DOCKER, "compose", "-f", str(EXAMPLE / "compose.yaml"), "--profile", "setup", + "config", "--format", "json"], env=env, check=True, capture_output=True, text=True, + ) + cls.compose = json.loads(rendered.stdout) + cls.services = cls.compose["services"] + + def test_only_the_loopback_edge_publishes_ports(self): + bindings = {name: service["ports"] for name, service in self.services.items() if service.get("ports")} + self.assertEqual(list(bindings), ["edge"]) + self.assertEqual( + {(row["host_ip"], row["published"], row["target"]) for row in bindings["edge"]}, + {("127.0.0.1", "8443", 8080), ("127.0.0.1", "9443", 9443)}, + ) + + def test_credential_endpoints_and_plaintext_hops_are_separate(self): + self.assertEqual(self.services["gateway"]["network_mode"], "service:edge") + self.assertEqual(self.services["session"]["network_mode"], "service:edge") + self.assertEqual(self.services["application"]["network_mode"], "service:upstreams") + self.assertEqual(self.services["breg"]["network_mode"], "service:upstreams") + backend = set(self.services["thunderid"]["networks"]) + self.assertTrue(backend.isdisjoint(self.services["upstreams"]["networks"])) + self.assertTrue(backend.isdisjoint(self.services["edge"]["networks"])) + self.assertTrue(set(self.services["identity-gateway"]["networks"]).isdisjoint( + self.services["upstreams"]["networks"] + )) + self.assertEqual(set(self.services["postgres"]["networks"]), {"database", "identity-database"}) + self.assertEqual(set(self.compose["volumes"]), {"issuer-certs", "issuer-secrets", "postgres-data"}) + + def test_checked_snapshot_and_bundle_are_read_only_in_consumers(self): + gateway = self.services["gateway"] + self.assertEqual(gateway["depends_on"]["gateway-check"]["condition"], "service_completed_successfully") + self.assertEqual(self.services["gateway-check"]["network_mode"], "none") + checked = next(mount for mount in gateway["volumes"] if mount["target"] == "/run/gateway") + self.assertEqual(checked["source"], "/reference/config/gateway-checked") + self.assertTrue(checked["read_only"]) + app = self.services["application"] + self.assertEqual([mount["target"] for mount in app["volumes"]], ["/run/bundle"]) + self.assertTrue(app["volumes"][0]["read_only"]) + self.assertEqual(app["environment"]["BUSINESS_BUNDLE_SHA256"], "0" * 64) + + def test_one_shots_keep_bootstrap_authority_out_of_serving_mounts(self): + for name in ("breg-admin", "thunderid-setup"): + self.assertEqual(self.services[name]["profiles"], ["setup"]) + boot = self.services["thunderid-setup"]["volumes"] + serve = self.services["thunderid"]["volumes"] + self.assertTrue(any("bootstrap-secrets" in mount["source"] for mount in boot)) + self.assertFalse(any("bootstrap-secrets" in mount["source"] for mount in serve)) + self.assertFalse(any("/config/resources" in mount["target"] for mount in boot)) + self.assertFalse(any("/breg/admin" in mount["source"] for mount in self.services["breg"]["volumes"])) + + def test_breg_waits_for_the_issuer_from_its_own_namespace(self): + readiness = self.services["issuer-ready"] + self.assertEqual(readiness["network_mode"], self.services["breg"]["network_mode"]) + self.assertEqual( + self.services["breg"]["depends_on"]["issuer-ready"]["condition"], "service_completed_successfully" + ) + self.assertTrue(all(mount["read_only"] for mount in readiness["volumes"])) diff --git a/deploy/examples/business-registration/thunderid.sh b/deploy/examples/business-registration/thunderid.sh new file mode 100644 index 0000000000..2116e5d375 --- /dev/null +++ b/deploy/examples/business-registration/thunderid.sh @@ -0,0 +1,41 @@ +#!/usr/bin/env bash +set -euo pipefail + +read_secret() { + local name=$1 value + value=$(<"/run/identity-secrets/$name") + if [[ -z "$value" ]]; then + printf 'Missing ThunderID input %s.\n' "$name" >&2 + exit 1 + fi + printf -v "$name" '%s' "$value" + export "${name?}" +} + +read_secret DB_CONFIG_PASSWORD +export DB_RUNTIME_TRANSIENT_PASSWORD="$DB_CONFIG_PASSWORD" +export DB_ENTITY_PASSWORD="$DB_CONFIG_PASSWORD" +export DB_RUNTIME_PERSISTENT_PASSWORD="$DB_CONFIG_PASSWORD" + +case "${1:-}" in + serve) + read_secret REGISTRAR_CLIENT_SECRET + read_secret REGISTRAR_PASSWORD + exec ./start.sh + ;; + setup) + read_secret ADMIN_PASSWORD + # Suppress the upstream bootstrap's credential notices. + if ./setup.sh >/dev/null 2>&1; then + printf 'ThunderID bootstrap completed.\n' + else + status=$? + printf 'ThunderID bootstrap failed with status %s. Check the reviewed bootstrap inputs.\n' "$status" >&2 + exit "$status" + fi + ;; + *) + printf 'Choose ThunderID setup or serve.\n' >&2 + exit 2 + ;; +esac diff --git a/deploy/examples/business-registration/thunderid.yaml b/deploy/examples/business-registration/thunderid.yaml new file mode 100644 index 0000000000..f7edabe8ed --- /dev/null +++ b/deploy/examples/business-registration/thunderid.yaml @@ -0,0 +1,57 @@ +server: + hostname: 0.0.0.0 + port: 8090 + http_only: true + public_url: https://identity.reference.test:9443 + security: + direct_auth_secret: file://config/secrets/direct_auth_secret +jwt: + issuer: https://identity.reference.test:9443 + preferred_key_id: default-key +crypto: + encryption: + key: file://config/certs/crypto.key + keys: + - id: default-key + cert_file: config/certs/signing.cert + key_file: config/certs/signing.key + - id: ecdsa-key + cert_file: config/certs/ecdsa-signing.cert + key_file: config/certs/ecdsa-signing.key +database: + config: + type: postgres + postgres: + hostname: postgres + port: 5432 + name: thunderid_config + username: thunderid + password: "{{.DB_CONFIG_PASSWORD}}" + sslmode: verify-full + runtime_transient: + type: postgres + postgres: + hostname: postgres + port: 5432 + name: thunderid_runtime_transient + username: thunderid + password: "{{.DB_RUNTIME_TRANSIENT_PASSWORD}}" + sslmode: verify-full + entity: + type: postgres + postgres: + hostname: postgres + port: 5432 + name: thunderid_entity + username: thunderid + password: "{{.DB_ENTITY_PASSWORD}}" + sslmode: verify-full + runtime_persistent: + type: postgres + postgres: + hostname: postgres + port: 5432 + name: thunderid_runtime_persistent + username: thunderid + password: "{{.DB_RUNTIME_PERSISTENT_PASSWORD}}" + sslmode: verify-full diff --git a/deploy/examples/business-registration/upstreams.yaml b/deploy/examples/business-registration/upstreams.yaml new file mode 100644 index 0000000000..551b767931 --- /dev/null +++ b/deploy/examples/business-registration/upstreams.yaml @@ -0,0 +1,63 @@ +static_resources: + listeners: + - name: from_registry + address: + pipe: {path: /run/relay/registry.sock, mode: 384} + filter_chains: + - filters: + - name: envoy.filters.network.tcp_proxy + typed_config: + "@type": type.googleapis.com/envoy.extensions.filters.network.tcp_proxy.v3.TcpProxy + stat_prefix: from_registry + cluster: registry + - name: from_pages + address: + pipe: {path: /run/relay/pages.sock, mode: 384} + filter_chains: + - filters: + - name: envoy.filters.network.tcp_proxy + typed_config: + "@type": type.googleapis.com/envoy.extensions.filters.network.tcp_proxy.v3.TcpProxy + stat_prefix: from_pages + cluster: pages + - name: from_functions + address: + pipe: {path: /run/relay/functions.sock, mode: 384} + filter_chains: + - filters: + - name: envoy.filters.network.tcp_proxy + typed_config: + "@type": type.googleapis.com/envoy.extensions.filters.network.tcp_proxy.v3.TcpProxy + stat_prefix: from_functions + cluster: functions + clusters: + - name: registry + type: STATIC + connect_timeout: 2s + load_assignment: + cluster_name: registry + endpoints: + - lb_endpoints: + - endpoint: + address: + socket_address: {address: 127.0.0.1, port_value: 8100} + - name: pages + type: STATIC + connect_timeout: 2s + load_assignment: + cluster_name: pages + endpoints: + - lb_endpoints: + - endpoint: + address: + socket_address: {address: 127.0.0.1, port_value: 8200} + - name: functions + type: STATIC + connect_timeout: 2s + load_assignment: + cluster_name: functions + endpoints: + - lb_endpoints: + - endpoint: + address: + socket_address: {address: 127.0.0.1, port_value: 8300} From 2e98555f3edcc2b691b4affb57d0c400e5fb88aa Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 18:30:00 +0000 Subject: [PATCH 047/183] fix(deploy): require checked route export before starting Envoy Signed-off-by: Jeremi Joslin (cherry picked from commit 8a307b96ff39ddfe2750c7de49f3d17c511827b5) --- .../examples/business-registration/README.md | 17 ++-- .../business-registration/check-gateway.sh | 26 ++++-- .../business-registration/compose.yaml | 3 +- .../tests/test_compose.py | 4 + .../tests/test_gateway_check.py | 81 +++++++++++++++++++ 5 files changed, 115 insertions(+), 16 deletions(-) create mode 100644 deploy/examples/business-registration/tests/test_gateway_check.py diff --git a/deploy/examples/business-registration/README.md b/deploy/examples/business-registration/README.md index 865be5000b..f770c98329 100644 --- a/deploy/examples/business-registration/README.md +++ b/deploy/examples/business-registration/README.md @@ -69,7 +69,7 @@ package receipt. | `thunderid/bootstrap-secrets/` | `DB_CONFIG_PASSWORD` and `ADMIN_PASSWORD` for the one-shot setup | | `thunderid/secrets/` | `DB_CONFIG_PASSWORD`, `REGISTRAR_CLIENT_SECRET`, and `REGISTRAR_PASSWORD` for serving | | `thunderid/resources/`, `thunderid/front-gateway/`, `thunderid/identity-receipt.json` | Output of identity generation | -| `gateway/envoy.yaml` | Reviewed complete Envoy configuration from the matching Session CLI | +| `gateway/envoy.json` | Reviewed complete Envoy configuration from the matching Session CLI | | `gateway-checked/`, `relay/`, `breg/audit/`, `session/audit/` | Empty private directories owned by the instance UID | The Session client secret equals `REGISTRAR_CLIENT_SECRET`. Both ThunderID @@ -93,8 +93,8 @@ file, retaining the supplied `server`, `jwt`, `crypto` and `database` blocks. The generated issuer, application registration, subject claims and registrar scope must agree with the BReg and Session files. -For checked browser route export, use the matching Lane 2 Session CLI with the -checked-route flags. Generate the complete Envoy file over [session.yaml](session.yaml). +Use a matching Session CLI that supports standalone TLS assembly and checked +route export. Generate the complete Envoy file from [session.yaml](session.yaml). The gateway itself terminates app TLS at `127.0.0.1:8443`. Use `/run/tls/app.crt` and `/run/tls/app.key` as its TLS paths and these three distinct private first hops. @@ -108,19 +108,20 @@ distinct private first hops. ```bash session=("$REFERENCE_ARTIFACTS/registry-session" --runtime-config "$RECIPE/session.yaml") "${session[@]}" gateway envoy --posture production \ - --standalone-out "$REFERENCE_CONFIG/gateway/envoy.yaml" --listen 127.0.0.1:8443 \ + --standalone-out "$REFERENCE_CONFIG/gateway/envoy.json" --listen 127.0.0.1:8443 \ --upstream registry=127.0.0.1:8100 --upstream pages=127.0.0.1:8200 \ --upstream functions=127.0.0.1:8300 \ --tls-certificate /run/tls/app.crt --tls-key /run/tls/app.key "${session[@]}" gateway envoy --posture production \ - --verify-assembled "$REFERENCE_CONFIG/gateway/envoy.yaml" \ + --verify-assembled "$REFERENCE_CONFIG/gateway/envoy.json" \ --route-inventory-out "$REFERENCE_CONFIG/gateway/route-inventory.json" --checked-route businesses ``` Only the `businesses` module supplies the browser's product-client route -inventory. The Compose startup verifies the supplied Envoy file against Session -and installs exactly the verified bytes before Envoy starts. The application -and BReg share the upstream namespace. Session's check listener is in the +inventory. At startup, Compose runs the strict export for `businesses` against +a staged copy of the supplied Envoy file. It installs those exact bytes after +the export succeeds. The startup inventory is temporary. The application and +BReg share the upstream namespace. Session's check listener is in the separate gateway namespace. The two Envoy relays connect these namespaces over three private owner-only Unix sockets. The host app port passes TLS through to the Session-checked gateway. diff --git a/deploy/examples/business-registration/check-gateway.sh b/deploy/examples/business-registration/check-gateway.sh index 23bd2b921f..acd8742040 100644 --- a/deploy/examples/business-registration/check-gateway.sh +++ b/deploy/examples/business-registration/check-gateway.sh @@ -1,10 +1,22 @@ #!/usr/bin/env bash set -euo pipefail +umask 077 -session=(/opt/native/registry-session --runtime-config /run/reference/session.yaml) -"${session[@]}" check --posture production --deny-warnings --identity-receipt /run/reference/identity-receipt.json -candidate=$(mktemp /run/gateway/envoy.XXXXXX) -trap 'rm -f -- "$candidate"' EXIT -cp -- /run/gateway-input/envoy.yaml "$candidate" -"${session[@]}" gateway envoy --posture production --verify-assembled "$candidate" -mv -f -- "$candidate" /run/gateway/envoy.yaml +reference=$2 +input=$3 +output=$4 +session=("$1" --runtime-config "$reference/session.yaml") +"${session[@]}" check --posture production --deny-warnings --identity-receipt "$reference/identity-receipt.json" + +staging=$(mktemp -d "$output/.check.XXXXXX") +candidate="$staging/envoy.json" +inventory="$staging/route-inventory.json" +trap 'rm -f -- "$candidate" "$inventory"; rmdir -- "$staging"' EXIT +cp -- "$input" "$candidate" +"${session[@]}" gateway envoy --posture production --verify-assembled "$candidate" \ + --route-inventory-out "$inventory" --checked-route businesses +if [[ ! -s "$inventory" ]]; then + printf 'Session did not produce the checked route inventory.\n' >&2 + exit 1 +fi +mv -fT -- "$candidate" "$output/envoy.json" diff --git a/deploy/examples/business-registration/compose.yaml b/deploy/examples/business-registration/compose.yaml index 5a193cdf35..5b9d164bb9 100644 --- a/deploy/examples/business-registration/compose.yaml +++ b/deploy/examples/business-registration/compose.yaml @@ -55,6 +55,7 @@ services: <<: *native network_mode: none entrypoint: [bash, /run/reference/check-gateway.sh] + command: [/opt/native/registry-session, /run/reference, /run/gateway-input/envoy.json, /run/gateway] volumes: - ./check-gateway.sh:/run/reference/check-gateway.sh:ro - ./session.yaml:/run/reference/session.yaml:ro @@ -66,7 +67,7 @@ services: gateway: <<: *envoy network_mode: service:edge - command: [-c, /run/gateway/envoy.yaml] + command: [-c, /run/gateway/envoy.json] volumes: - ${REFERENCE_CONFIG}/gateway-checked:/run/gateway:ro - ${REFERENCE_CONFIG}/app-tls:/run/tls:ro diff --git a/deploy/examples/business-registration/tests/test_compose.py b/deploy/examples/business-registration/tests/test_compose.py index b6a38096f8..cdf540f87c 100644 --- a/deploy/examples/business-registration/tests/test_compose.py +++ b/deploy/examples/business-registration/tests/test_compose.py @@ -52,6 +52,10 @@ def test_credential_endpoints_and_plaintext_hops_are_separate(self): def test_checked_snapshot_and_bundle_are_read_only_in_consumers(self): gateway = self.services["gateway"] self.assertEqual(gateway["depends_on"]["gateway-check"]["condition"], "service_completed_successfully") + self.assertEqual(gateway["command"], ["-c", "/run/gateway/envoy.json"]) + self.assertEqual(self.services["gateway-check"]["command"][-2:], [ + "/run/gateway-input/envoy.json", "/run/gateway", + ]) self.assertEqual(self.services["gateway-check"]["network_mode"], "none") checked = next(mount for mount in gateway["volumes"] if mount["target"] == "/run/gateway") self.assertEqual(checked["source"], "/reference/config/gateway-checked") diff --git a/deploy/examples/business-registration/tests/test_gateway_check.py b/deploy/examples/business-registration/tests/test_gateway_check.py new file mode 100644 index 0000000000..5744eb134e --- /dev/null +++ b/deploy/examples/business-registration/tests/test_gateway_check.py @@ -0,0 +1,81 @@ +"""Exercise the gateway one-shot with a stand-in for the Session CLI.""" + +import os +from pathlib import Path +import subprocess +from tempfile import TemporaryDirectory +import unittest + + +EXAMPLE = Path(__file__).resolve().parents[1] + + +class GatewayCheck(unittest.TestCase): + def setUp(self): + self.root = Path(self.enterContext(TemporaryDirectory())) + self.input = self.root / "envoy.json" + self.input.write_bytes(b'{"candidate":true}\n') + self.output = self.root / "checked" + self.output.mkdir() + self.installed = self.output / "envoy.json" + self.installed.write_bytes(b'{"previous":true}\n') + self.session = self.root / "registry-session" + self.session.write_text("""#!/usr/bin/env python3 +import os +from pathlib import Path +import sys + +root = Path(__file__).parent +runtime = root / "session.yaml" +identity = root / "identity-receipt.json" +assert sys.argv[1:3] == ["--runtime-config", str(runtime)] +args = sys.argv[3:] +if args[0] == "check": + assert args == [ + "check", "--posture", "production", "--deny-warnings", "--identity-receipt", str(identity), + ] + sys.exit(0) + +assert args[:5] == ["gateway", "envoy", "--posture", "production", "--verify-assembled"] +assert args[6] == "--route-inventory-out" +assert args[8:] == ["--checked-route", "businesses"] +staged, inventory = Path(args[5]), Path(args[7]) +source = root / "envoy.json" +assert staged != source and staged.read_bytes() == source.read_bytes() +assert staged.parent == inventory.parent and not inventory.exists() +outcome = os.environ["EXPORT_OUTCOME"] +if outcome == "refused": + sys.exit(1) +if outcome == "accepted": + inventory.write_text("{}") + source.write_text("changed after staging") +""") + self.session.chmod(0o700) + + def run_check(self, outcome): + return subprocess.run( + ["bash", str(EXAMPLE / "check-gateway.sh"), str(self.session), + str(self.root), str(self.input), str(self.output)], + capture_output=True, text=True, env=dict(os.environ, EXPORT_OUTCOME=outcome), + ) + + def test_installs_exact_bytes_checked_by_strict_export(self): + original = self.input.read_bytes() + result = self.run_check("accepted") + self.assertEqual(result.returncode, 0, result.stderr) + self.assertNotEqual(self.input.read_bytes(), original) + self.assertEqual(self.installed.read_bytes(), original) + self.assertEqual(list(self.output.iterdir()), [self.installed]) + + def test_retains_installed_bytes_when_strict_export_refuses(self): + result = self.run_check("refused") + self.assertEqual(result.returncode, 1, result.stderr) + self.assertEqual(self.installed.read_bytes(), b'{"previous":true}\n') + self.assertEqual(list(self.output.iterdir()), [self.installed]) + + def test_requires_export_output_before_installing(self): + result = self.run_check("no-inventory") + self.assertEqual(result.returncode, 1, result.stderr) + self.assertIn("route inventory", result.stderr) + self.assertEqual(self.installed.read_bytes(), b'{"previous":true}\n') + self.assertEqual(list(self.output.iterdir()), [self.installed]) From 50edbea367bd468eea774589906d948cfaec65d6 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 18:37:18 +0000 Subject: [PATCH 048/183] docs(coordinator): align route labels with OpenAPI Signed-off-by: Jeremi Joslin (cherry picked from commit 58457730a84b5204856ea554d680b3704b66f90b) --- docs/site/src/data/coordinator-api.yaml | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/docs/site/src/data/coordinator-api.yaml b/docs/site/src/data/coordinator-api.yaml index cab253d937..8927909ca0 100644 --- a/docs/site/src/data/coordinator-api.yaml +++ b/docs/site/src/data/coordinator-api.yaml @@ -53,15 +53,15 @@ rows: - ['`GET`', '`/health`', 'None', '`200` with `{"live":true}` while the process answers.'] - ['`GET`', '`/ready`', 'None', '`200` with `{"ready":true}`, or `503` with `{"ready":false}` while the service cannot accept work.'] - - ['`GET`', '`/v1/workflows/{workflow}`', 'Bearer, `start` on the named workflow', 'Discover the active revision, input schema, and declared outcomes.'] + - ['`GET`', '`/v1/workflows/{workflowId}`', 'Bearer, `start` on the named workflow', 'Discover the active revision, input schema, and declared outcomes.'] - ['`POST`', '`/v1/runs`', 'Bearer, `start` on the named workflow', 'Start one run with the expected `workflowRevision` and an `Idempotency-Key`.'] - ['`GET`', '`/v1/runs`', 'Bearer, `status`', 'List at most 100 of the most recently admitted runs the caller may see, newest first.'] - - ['`GET`', '`/v1/runs/{run}`', 'Bearer, `status`', 'Read one run''s progress and its reviewed terminal output.'] - - ['`GET`', '`/v1/runs/{run}/inspect`', 'Bearer, `inspect`', 'Read bounded steps, accepted or unknown effects, durable wait budgets, and available recovery actions.'] - - ['`POST`', '`/v1/runs/{run}/cancel`', 'Bearer, `cancel`', 'Stop future dispatch where possible, without rolling back an accepted effect.'] - - ['`POST`', '`/v1/runs/{run}/check`', 'Bearer, `inspect`', 'Read a waiting step''s product now, no sooner than the read floor after its last read, counting against the wait''s read budget. Body `{"step":"..."}`.'] - - ['`POST`', '`/v1/runs/{run}/reconcile`', 'Bearer, `reconcile`', 'Settle an uncertain call from the receiving product''s original-key receipt.'] - - ['`POST`', '`/v1/runs/{run}/retry-same`', 'Bearer, `retry-same`', 'Schedule held work again with its original command, key, binding, and authority.'] + - ['`GET`', '`/v1/runs/{runId}`', 'Bearer, `status`', 'Read one run''s progress and its reviewed terminal output.'] + - ['`GET`', '`/v1/runs/{runId}/inspect`', 'Bearer, `inspect`', 'Read bounded steps, accepted or unknown effects, durable wait budgets, and available recovery actions.'] + - ['`POST`', '`/v1/runs/{runId}/cancel`', 'Bearer, `cancel`', 'Stop future dispatch where possible, without rolling back an accepted effect.'] + - ['`POST`', '`/v1/runs/{runId}/check`', 'Bearer, `inspect`', 'Read a waiting step''s product now, no sooner than the read floor after its last read, counting against the wait''s read budget. Body `{"step":"..."}`.'] + - ['`POST`', '`/v1/runs/{runId}/reconcile`', 'Bearer, `reconcile`', 'Settle an uncertain call from the receiving product''s original-key receipt.'] + - ['`POST`', '`/v1/runs/{runId}/retry-same`', 'Bearer, `retry-same`', 'Schedule held work again with its original command, key, binding, and authority.'] - ['`GET`', '`/v1/doctor`', 'Bearer, operator', 'Report activation, audit readiness, holds, and run counts.'] - ['`POST`', '`/v1/restore-hold`', 'Bearer, operator', 'Place the restore hold, which stops dispatch and admissions.'] - ['`POST`', '`/v1/release-restore-hold`', 'Bearer, operator', 'Release the restore hold once no held work is unresolved.'] @@ -69,4 +69,4 @@ - ['`POST`', '`/v1/complete-execution-recovery`', 'Bearer, operator', 'Attest complete execution history and prior fencing while the restore hold remains.'] - ['`POST`', '`/v1/retention`', 'Bearer, operator', 'Erase eligible terminal payloads that ended before a cutoff.'] - ['`POST`', '`/v1/review-completions`', 'Standard Webhooks signature using the key selected by the recipient binding', 'Bring forward the next result read of a run waiting on that review request.'] - - ['`POST`', '`/v1/events/{workflow}/{trigger}`', 'Standard Webhooks signature using the key for the trigger URL', 'Admit one run per exact authenticated event and trigger; exact redelivery returns the same run.'] + - ['`POST`', '`/v1/events/{workflowId}/{triggerId}`', 'Standard Webhooks signature using the key for the trigger URL', 'Admit one run per exact authenticated event and trigger; exact redelivery returns the same run.'] From de9531581c075bb5f57052ac404a5eb187611bb3 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 18:47:06 +0000 Subject: [PATCH 049/183] test(coordinator): check transform fields in the configuration reference Signed-off-by: Jeremi Joslin --- docs/site/scripts/generate-coordinator-configuration.test.mjs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/site/scripts/generate-coordinator-configuration.test.mjs b/docs/site/scripts/generate-coordinator-configuration.test.mjs index f60c6147a1..2ba4c6d542 100644 --- a/docs/site/scripts/generate-coordinator-configuration.test.mjs +++ b/docs/site/scripts/generate-coordinator-configuration.test.mjs @@ -31,9 +31,10 @@ test('Coordinator project and runtime references carry the keys authors and oper const keys = (id) => new Set(document.contracts.find((contract) => contract.id === id) .fields.map((field) => field.key_path)); const project = keys('project'); - for (const path of ['workflow.steps', 'workflow.start', 'operations.*.uses', 'functions.*.entrypoint']) { + for (const path of ['workflow.steps', 'workflow.start', 'operations.*.uses', 'transforms.*.entrypoint']) { assert.ok(project.has(path), path); } + assert.ok(!project.has('functions.*.entrypoint')); const runtime = keys('runtime'); for (const path of [ 'connections', From 18119615e5d4f338e489125981780624b7b7bc31 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 18:47:06 +0000 Subject: [PATCH 050/183] test(journeys): record native Keycloak BReg qualification Signed-off-by: Jeremi Joslin --- products/platform/journeys/README.md | 6 ++++++ products/platform/journeys/expected-failures.yaml | 2 +- 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/products/platform/journeys/README.md b/products/platform/journeys/README.md index e576405035..de96d0d80f 100644 --- a/products/platform/journeys/README.md +++ b/products/platform/journeys/README.md @@ -180,6 +180,12 @@ without the optional scope and checks the refusal against the response's trace ID. The foreign caller also gets a fresh token for its exact-record assertion. +The managed BReg launcher creates a separate rehearsal package root before `bregctl test`. +The own-provider runner uses the separate rehearsal package and database for both issuers. +Strict Keycloak run `20261201182016-4bf3` passed all ten steps with same-source binaries. +It verified the no-mapper claim refusal, signed delivery, exact editor read and foreign read +refusal. The paired strict promotion run `20261201182055-d29b` verified clean teardown. + The BReg setup records `fixtureOnlyProducts: ["breg"]` in `own-provider.json`. Promotion reports `journey.promote.no-input` for this fixture. A passing BReg input directory that predates the marker is refused as diff --git a/products/platform/journeys/expected-failures.yaml b/products/platform/journeys/expected-failures.yaml index a742620b08..753099fc0b 100644 --- a/products/platform/journeys/expected-failures.yaml +++ b/products/platform/journeys/expected-failures.yaml @@ -224,7 +224,7 @@ passes: - journey: own-provider product: breg basis: observed - observedOn: "v0.49.0 binaries, own-provider run 20261201170814-cac9" + observedOn: "same-source binaries, strict Keycloak own-provider run 20261201182016-4bf3" - journey: own-provider product: adapter basis: observed From 77f58ec8aeb10cfae89d217c192141c3eec23aa9 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 18:47:06 +0000 Subject: [PATCH 051/183] feat(dev): check saved BReg identity-facts reports offline Signed-off-by: Jeremi Joslin --- .../registry-rstack-dev/src/owner_report.rs | 101 +++++++++++++----- .../src/owner_report_tests.rs | 49 +++++++++ crates/registry-rstack/src/cli.rs | 12 ++- .../scripts/generate-breg-configuration.mjs | 10 +- .../generate-breg-configuration.test.mjs | 7 +- .../generate-identity-configuration.mdx | 16 +++ products/platform/config-formats.yaml | 9 +- 7 files changed, 171 insertions(+), 33 deletions(-) diff --git a/crates/registry-rstack-dev/src/owner_report.rs b/crates/registry-rstack-dev/src/owner_report.rs index e825a2b4b2..13c3b88bf8 100644 --- a/crates/registry-rstack-dev/src/owner_report.rs +++ b/crates/registry-rstack-dev/src/owner_report.rs @@ -23,6 +23,8 @@ use std::{ }; const CASEWORK: &str = include_str!("../../../products/casework/contracts/cli/report.schema.json"); +const BREG_IDENTITY_FACTS: &str = + include_str!("../../../products/breg/generated/tools/ctl-report.v1alpha1.schema.json"); const CASEWORK_FORMAT: FormatSpec<'static> = FormatSpec { kind: "CaseworkReport", envelope: EnvelopeRule::ApiVersionKind { @@ -33,10 +35,30 @@ const CASEWORK_FORMAT: FormatSpec<'static> = FormatSpec { }, removed_keys: &[], }; +const BREG_REPORT_FORMAT: FormatSpec<'static> = FormatSpec { + kind: "BRegCtlReport", + envelope: EnvelopeRule::ApiVersionKind { + api_versions: &[ApiVersion::current( + "id.registrystack.org/formats/breg/ctl-report/v1alpha1", + )], + retired_api_versions: &[], + }, + removed_keys: &[], +}; #[derive(Clone, Copy, Debug, PartialEq, Eq, clap::ValueEnum)] pub(crate) enum Format { CaseworkReport, + BregIdentityFactsReport, +} + +impl Format { + fn spec(self) -> &'static FormatSpec<'static> { + match self { + Self::CaseworkReport => &CASEWORK_FORMAT, + Self::BregIdentityFactsReport => &BREG_REPORT_FORMAT, + } + } } #[derive(Debug)] @@ -59,7 +81,7 @@ impl Invalid { } } - fn into_report(self, file: &str) -> (Report, u8) { + fn into_report(self, file: &str, format: Format) -> (Report, u8) { let (exit, code, remedy) = if self.schema_unavailable { ( crate::OPERATIONAL_FAILURE_EXIT, @@ -70,7 +92,7 @@ impl Invalid { (crate::DOMAIN_REFUSAL_EXIT, self.code, FORMAT_REMEDY) }; let mut diagnostic = Diagnostic::error(code, self.path, self.message, remedy); - diagnostic.artifact = Some(CASEWORK_FORMAT.kind.to_owned()); + diagnostic.artifact = Some(format.spec().kind.to_owned()); diagnostic.source = Some(Source { file: file.to_owned(), line: self.position.map(|(line, _)| line), @@ -110,23 +132,20 @@ fn parse_position(bytes: &[u8], line: usize, byte_column: usize) -> Option<(usiz fn check_bytes(file: &str, bytes: &[u8], format: Format) -> (Report, u8) { let report = match parse(bytes) { Ok(report) => report, - Err(error) => return error.into_report(file), - }; - let expected = match format { - Format::CaseworkReport => &CASEWORK_FORMAT, + Err(error) => return error.into_report(file, format), }; // The JSON parser enforces the declared syntax. The shared reader checks // the envelope and retains positions for every schema diagnostic. - let document = match Reader::new(file).read(bytes, &Expect::one(expected)) { + let document = match Reader::new(file).read(bytes, &Expect::one(format.spec())) { Ok(document) => document, Err(mut report) => { - redact_structure(&mut report); + redact_structure(&mut report, format); return (report, crate::DOMAIN_REFUSAL_EXIT); } }; let issues = match validate(&report, format, Some(&document)) { Ok(issues) => issues, - Err(error) => return error.into_report(file), + Err(error) => return error.into_report(file, format), }; let mut report = document.report_with(issues.into_iter().map(|issue| { let mut diagnostic = document.diagnostic_at_value( @@ -150,7 +169,13 @@ fn check_bytes(file: &str, bytes: &[u8], format: Format) -> (Report, u8) { const FORMAT_REMEDY: &str = "Select the matching owner report format and capture a fresh report as JSON."; -fn redact_structure(report: &mut Report) { +fn redact_structure(report: &mut Report, format: Format) { + let message = match format { + Format::CaseworkReport => "Expected a valid CaseworkReport v1alpha2 envelope and document", + Format::BregIdentityFactsReport => { + "Expected a valid BRegCtlReport v1alpha1 envelope and document" + } + }; for diagnostic in report.diagnostics_mut() { if diagnostic.code == "config.too-many-problems" { continue; @@ -158,8 +183,7 @@ fn redact_structure(report: &mut Report) { if !matches!(diagnostic.path.as_str(), "/kind" | "/apiVersion") { diagnostic.path.clear(); } - diagnostic.message = - "Expected a valid CaseworkReport v1alpha2 envelope and document".to_owned(); + diagnostic.message = message.to_owned(); diagnostic.suggested_action = FORMAT_REMEDY.to_owned(); diagnostic.related.clear(); } @@ -183,6 +207,14 @@ fn validate( ) -> Result, Invalid> { match format { Format::CaseworkReport => validate_casework(report, document), + Format::BregIdentityFactsReport => { + static SCHEMA: OnceLock> = OnceLock::new(); + let schema = SCHEMA + .get_or_init(|| compile(serde_json::from_str(BREG_IDENTITY_FACTS).ok()?)) + .as_ref() + .ok_or_else(schema_unavailable)?; + Ok(schema.issues(report, "", document)) + } } } @@ -279,7 +311,7 @@ impl Schema { let mut issues = Vec::new(); let mut seen = BTreeSet::new(); for error in errors { - let path = self.diagnostic_path(prefix, &error.instance_path); + let (path, instance_schema) = self.diagnostic_path(prefix, &error.instance_path); let raw_parent = error.instance_path.to_string(); if let ValidationErrorKind::AdditionalProperties { unexpected } = &error.kind { for key in unexpected { @@ -311,7 +343,9 @@ impl Schema { ValidationErrorKind::Minimum { .. } | ValidationErrorKind::Maximum { .. } | ValidationErrorKind::Custom { .. } => { - if let Some((minimum, maximum)) = self.error_integer_bounds(&error) { + if let Some((minimum, maximum)) = + self.error_integer_bounds(&error, instance_schema) + { issue.code = if integer(&error.instance).is_some() { "config.out-of-range" } else { @@ -345,28 +379,43 @@ impl Schema { issues } - fn error_integer_bounds(&self, error: &ValidationError<'_>) -> Option<(i128, i128)> { + fn error_integer_bounds( + &self, + error: &ValidationError<'_>, + instance_schema: Option<&Value>, + ) -> Option<(i128, i128)> { let schema_path = error.schema_path.to_string(); - let (parent, _) = schema_path.rsplit_once('/')?; - let schema = self.document.pointer(parent)?.as_object()?; - schema - .contains_key(EXACT_INTEGER) - .then(|| exact_integer_bounds(schema)) + // A validator can report the path through a reference rather than the + // definition that holds the bounds. Use the instance schema when the + // path resolves entirely through declared properties and array items. + let reported = schema_path + .rsplit_once('/') + .and_then(|(parent, _)| self.document.pointer(parent)); + [reported, instance_schema] + .into_iter() + .flatten() + .filter_map(Value::as_object) + .find(|schema| schema.contains_key(EXACT_INTEGER)) + .map(exact_integer_bounds) } - fn diagnostic_path(&self, prefix: &str, instance_path: &JSONPointer) -> String { + fn diagnostic_path( + &self, + prefix: &str, + instance_path: &JSONPointer, + ) -> (String, Option<&Value>) { let mut path = prefix.to_owned(); let mut schema = &self.document; for part in instance_path { let Some(resolved) = self.resolve_path_schema(schema) else { - break; + return (path, None); }; // Only literal properties and array items establish a safe path. // Dynamic map members and ambiguous schema positions end the path. match part { PathChunk::Property(name) => { let Some(child) = resolved["properties"].get(name.as_ref()) else { - break; + return (path, None); }; schema = child; path.push('/'); @@ -377,16 +426,16 @@ impl Schema { .get(*index) .or_else(|| resolved.get("items")) else { - break; + return (path, None); }; schema = child; path.push('/'); path.push_str(&index.to_string()); } - PathChunk::Keyword(_) => break, + PathChunk::Keyword(_) => return (path, None), } } - path + (path, self.resolve_path_schema(schema)) } fn resolve_path_schema<'a>(&'a self, mut schema: &'a Value) -> Option<&'a Value> { diff --git a/crates/registry-rstack-dev/src/owner_report_tests.rs b/crates/registry-rstack-dev/src/owner_report_tests.rs index b49ae3a350..4a650da70b 100644 --- a/crates/registry-rstack-dev/src/owner_report_tests.rs +++ b/crates/registry-rstack-dev/src/owner_report_tests.rs @@ -4,6 +4,8 @@ use super::*; const CASEWORK: &str = include_str!("../../../products/casework/examples/formats/reports/check-report.json"); +const BREG_IDENTITY_FACTS: &str = + include_str!("../../../products/breg/examples/formats/identity-facts-report.json"); fn decode(bytes: &[u8], format: Format) -> Result<(), Diagnostic> { let (report, exit) = check_bytes("synthetic.json", bytes, format); @@ -64,6 +66,53 @@ fn casework_native_u32_counts_use_the_selected_command_branch() { assert_eq!(decode(&report).unwrap_err().path, "/claims"); } +#[test] +fn breg_reads_only_completed_identity_facts_report_structure() { + let format = Format::BregIdentityFactsReport; + let mut report: Value = serde_json::from_str(BREG_IDENTITY_FACTS).unwrap(); + report["artifacts"][0]["path"] = json!("never-open-this/identity-facts.yaml"); + let check = |value: &Value| decode(&serde_json::to_vec(value).unwrap(), format); + assert!(check(&report).is_ok()); + + for (pointer, value) in [ + ("/command", json!("explain")), + ("/status", json!("domain-refusal")), + ("/artifacts/0/sha256", json!("synthetic-private-digest")), + ("/artifacts/0/byteLength", json!(0)), + ("/explanation/identityFacts/claims", json!(65)), + ] { + let mut refused = report.clone(); + *refused.pointer_mut(pointer).unwrap() = value; + let issue = check(&refused).unwrap_err(); + assert_eq!(issue.path, pointer); + assert!(!issue.message.contains("synthetic-private-digest")); + assert!(issue.source.unwrap().column.is_some()); + } + + let mut wrong_kind = report; + wrong_kind["kind"] = json!("PlatformIdentityFacts"); + let issue = check(&wrong_kind).unwrap_err(); + assert_eq!(issue.path, "/kind"); + assert!(issue.message.contains("BRegCtlReport")); + assert!(decode(BREG_IDENTITY_FACTS.as_bytes(), Format::CaseworkReport).is_err()); +} + +#[test] +fn breg_reports_native_integer_bounds_through_diagnostic_references() { + let format = Format::BregIdentityFactsReport; + for (pointer, value) in [ + ("/diagnostics/0/source/column", 0), + ("/diagnostics/0/source/line", MAXIMUM_DOCUMENT_BYTES + 2), + ] { + let mut report: Value = serde_json::from_str(BREG_IDENTITY_FACTS).unwrap(); + *report.pointer_mut(pointer).unwrap() = json!(value); + let issue = decode(&serde_json::to_vec(&report).unwrap(), format).unwrap_err(); + assert_eq!(issue.path, pointer); + assert_eq!(issue.code, "config.out-of-range"); + assert!(issue.message.contains("from 1 to 1048577")); + } +} + #[test] fn plain_reader_refuses_duplicate_trailing_and_oversized_json() { assert!(parse(br#"{"a":{"b":1,"b":2}}"#).is_err()); diff --git a/crates/registry-rstack/src/cli.rs b/crates/registry-rstack/src/cli.rs index e3f52b7fe9..1bb245d61f 100644 --- a/crates/registry-rstack/src/cli.rs +++ b/crates/registry-rstack/src/cli.rs @@ -262,7 +262,7 @@ struct ClientGenerate { enum DevCommand { /// Validate a development plan or the structure of a saved owner report without starting services. #[command( - after_help = "Examples:\n rstack dev check ./my-registry-project\n rstack dev check --owner-report ./report.json --owner-report-format casework-report" + after_help = "Examples:\n rstack dev check ./my-registry-project\n rstack dev check --owner-report ./report.json --owner-report-format casework-report\n rstack dev check --owner-report ./identity-facts-report.json --owner-report-format breg-identity-facts-report" )] Check { /// Project directory containing dev.yaml and, when it declares audiences, service.yaml. @@ -277,7 +277,7 @@ enum DevCommand { )] owner_report: Option, /// Exact saved document format. - #[arg(long, requires = "owner_report", conflicts_with = "project", value_parser = ["casework-report"])] + #[arg(long, requires = "owner_report", conflicts_with = "project", value_parser = ["casework-report", "breg-identity-facts-report"])] owner_report_format: Option, /// Refuse an unaccepted warning. /// Development posture listings do not count. @@ -2610,6 +2610,14 @@ mod tests { "--deny-warnings", ]) .is_ok()); + assert!(parse(&[ + "--owner-report", + "./report.json", + "--owner-report-format", + "breg-identity-facts-report", + "--deny-warnings", + ]) + .is_ok()); for args in [ &[][..], &["--owner-report", "./report.json"], diff --git a/docs/site/scripts/generate-breg-configuration.mjs b/docs/site/scripts/generate-breg-configuration.mjs index 98fbde9f21..d9d65763a0 100644 --- a/docs/site/scripts/generate-breg-configuration.mjs +++ b/docs/site/scripts/generate-breg-configuration.mjs @@ -47,8 +47,8 @@ const DEV_CONTRACTS = [ }, ].map(contract('tooling', undefined, 'products/platform/generated/dev')); -// Files `bregctl` reads beside a project: adopter tooling, published by the -// `tool-schema` example under products/breg/generated/tools. +// Adopter tooling files and saved reports, published by the `tool-schema` +// example under products/breg/generated/tools. const BREG_TOOL_CONTRACTS = [ { id: 'example-scenarios', @@ -86,6 +86,12 @@ const BREG_TOOL_CONTRACTS = [ file: 'tools/model-selection.v1alpha1.schema.json', reference: 'reference/bregctl-publicschema-wizard.mdx', }, + { + id: 'ctl-report', + title: 'Saved identity-facts-report.json', + file: 'tools/ctl-report.v1alpha1.schema.json', + reference: 'operate/advanced/generate-identity-configuration.mdx', + }, ].map(contract('tooling')); // The tool files listed in the order an adopter meets them; the generated diff --git a/docs/site/scripts/generate-breg-configuration.test.mjs b/docs/site/scripts/generate-breg-configuration.test.mjs index dcc80f4d31..c47cf022a9 100644 --- a/docs/site/scripts/generate-breg-configuration.test.mjs +++ b/docs/site/scripts/generate-breg-configuration.test.mjs @@ -64,7 +64,7 @@ test('BReg covers every committed tool schema, in the order an adopter meets the ...await committed('products/platform/generated/dev'), ].sort(), TOOL_CONTRACTS.map((entry) => entry.file).sort()); assert.deepEqual(TOOL_CONTRACTS.map((entry) => entry.id), ['rstack-dev', 'rstack-service', 'rstack-journeys', 'example-scenarios', - 'journeys', 'schema-test-credentials', 'migration-descriptor', 'backup-binding', 'model-selection']); + 'journeys', 'schema-test-credentials', 'migration-descriptor', 'backup-binding', 'model-selection', 'ctl-report']); }); test('BReg tool and service references read the committed schemas they name', async () => { @@ -92,6 +92,11 @@ test('BReg tool and service references read the committed schemas they name', as assert.ok(projectDev.has('products[].product')); assert.ok(fields('tools', 'rstack-journeys').has('journeys[].steps[].expect.status')); + const savedReport = fields('tools', 'ctl-report'); + assert.deepEqual(savedReport.get('kind').values, ['BRegCtlReport']); + assert.deepEqual(savedReport.get('command').values, ['generate']); + assert.deepEqual(savedReport.get('status').values, ['complete']); + const descriptor = fields('tools', 'migration-descriptor'); assert.deepEqual(descriptor.get('steps[].type').values, ['chunked-backfill', 'field-encryption-backfill', 'transactional-sql']); diff --git a/docs/site/src/content/docs/operate/advanced/generate-identity-configuration.mdx b/docs/site/src/content/docs/operate/advanced/generate-identity-configuration.mdx index ff7af52ba9..3c9fdd7b16 100644 --- a/docs/site/src/content/docs/operate/advanced/generate-identity-configuration.mdx +++ b/docs/site/src/content/docs/operate/advanced/generate-identity-configuration.mdx @@ -103,6 +103,22 @@ file, and renders the result. {/* Evidence: crates/registry-thunderid-tooling/src/identity_generate.rs, generate(), and key_file_refusal(); crates/registry-casework/src/config.rs authentication.oidc.humanIdentity and representedHuman. */} +## Check a saved BReg identity-facts report + +If you saved the JSON report from a completed `bregctl --format json generate identity-facts` +run, check its structure offline with the same Registry Stack version. + +```bash +rstack dev check --owner-report ./identity-facts-report.json \ + --owner-report-format breg-identity-facts-report +``` + +The check validates the report envelope, counts and artifact metadata. The identity generator +reads the `PlatformIdentityFacts` YAML file separately and checks its contents. + +{/* Evidence: crates/registry-rstack-dev/src/owner_report.rs, check_file; + crates/registry-bregctl/src/lib.rs, generate_identity_facts. */} + ## Prerequisites - A same-version binary for each product you select. If a binary is missing, the command names diff --git a/products/platform/config-formats.yaml b/products/platform/config-formats.yaml index e8b8283d9c..294353b88c 100644 --- a/products/platform/config-formats.yaml +++ b/products/platform/config-formats.yaml @@ -1404,6 +1404,7 @@ formats: files: [] syntax: json audience: generated + passiveReport: true stability: unpromised current: apiVersion: id.registrystack.org/formats/breg/ctl-report/v1alpha1 @@ -1420,11 +1421,15 @@ formats: origin: generated generator: cargo run -p registry-bregctl --features schema --example tool-schema -- --output products/breg/generated/tools driftCheck: products/breg/scripts/check-tool-schemas.sh - reader: none + reader: + crate: registry-rstack-dev + file: crates/registry-rstack-dev/src/owner_report.rs + function: check_file + type: untyped emittedBy: file: crates/registry-bregctl/src/lib.rs symbol: write_ctl_report - check: none + check: rstack dev check --owner-report {file} --owner-report-format breg-identity-facts-report example: products/breg/examples/formats/identity-facts-report.json conformance: none securityMembers: [] From dd964dea3f9213c775f23e9f95a2e3908b4e1c76 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 18:58:31 +0000 Subject: [PATCH 052/183] feat(evidence): provision databases for held Evidence stores Signed-off-by: Jeremi Joslin (cherry picked from commit c3a3620500352014ca01a4013d5736806c81c92a) --- Cargo.lock | 2 + crates/registry-evidencectl/Cargo.toml | 6 +- .../authoring/store-provision.schema.json | 160 +++++++++ crates/registry-evidencectl/src/lib.rs | 48 ++- crates/registry-evidencectl/src/schema.rs | 29 ++ .../src/store_provision.rs | 306 ++++++++++++++++++ .../tests/store_provision.rs | 234 ++++++++++++++ .../docs/configure/evidence-oid4vci.mdx | 12 + products/evidence/OPERATOR-CONTRACT.md | 22 ++ .../examples/formats/store-provision.yaml | 11 + 10 files changed, 817 insertions(+), 13 deletions(-) create mode 100644 crates/registry-evidencectl/schemas/authoring/store-provision.schema.json create mode 100644 crates/registry-evidencectl/src/store_provision.rs create mode 100644 crates/registry-evidencectl/tests/store_provision.rs create mode 100644 products/evidence/examples/formats/store-provision.yaml diff --git a/Cargo.lock b/Cargo.lock index 908cca90db..a2a6c18d68 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -7359,6 +7359,7 @@ dependencies = [ "inquire", "jsonschema", "p256", + "percent-encoding", "pkcs1", "pkcs8 0.10.2", "rand 0.9.5", @@ -7377,6 +7378,7 @@ dependencies = [ "registry-platform-crypto", "registry-platform-httpsec", "registry-platform-loopback", + "registry-platform-provision", "registry-platform-yaml", "registry-rstack-dev", "registry-thunderid-tooling", diff --git a/crates/registry-evidencectl/Cargo.toml b/crates/registry-evidencectl/Cargo.toml index b4691acb4c..73e65ca45b 100644 --- a/crates/registry-evidencectl/Cargo.toml +++ b/crates/registry-evidencectl/Cargo.toml @@ -42,10 +42,12 @@ registry-cli-reference.workspace = true registry-platform-crypto.workspace = true registry-platform-httpsec = { workspace = true, features = ["server"] } registry-platform-loopback.workspace = true +registry-platform-provision = { workspace = true, features = ["cli"] } registry-platform-yaml.workspace = true registry-rstack-dev.workspace = true registry-thunderid-tooling.workspace = true p256.workspace = true +percent-encoding = "2" # `jwk from-pem` reads a PEM SubjectPublicKeyInfo or PKCS #1 public key. pkcs1.workspace = true pkcs8 = { workspace = true, features = ["pem"] } @@ -66,7 +68,8 @@ schemars = { workspace = true, optional = true } [features] # The generator for the committed schemas of the documents this crate owns. -schema = ["dep:schemars", "registry-evidence-authoring/schema"] +schema = ["dep:schemars", "registry-evidence-authoring/schema", "registry-platform-config/schema"] +postgres-test = [] [[example]] name = "authoring-schema" @@ -77,4 +80,5 @@ registry-adapter-engine.workspace = true registry-evidence.workspace = true registry-evidence-authoring.workspace = true registry-platform-crypto = { workspace = true, features = ["test-support"] } +registry-platform-provision = { workspace = true, features = ["test-support"] } tower.workspace = true diff --git a/crates/registry-evidencectl/schemas/authoring/store-provision.schema.json b/crates/registry-evidencectl/schemas/authoring/store-provision.schema.json new file mode 100644 index 0000000000..e84a7877b1 --- /dev/null +++ b/crates/registry-evidencectl/schemas/authoring/store-provision.schema.json @@ -0,0 +1,160 @@ +{ + "$defs": { + "DatabaseConfig": { + "additionalProperties": false, + "description": "The PostgreSQL connection a stateful runtime uses. Both URLs are secret\nreferences and may name the same secret.", + "properties": { + "caBundleRef": { + "$ref": "#/$defs/SecretReference", + "description": "Secret reference to a PEM root certificate the connection trusts.\nAbsent, the connection trusts the platform's root certificates." + }, + "migrationUrlRef": { + "$ref": "#/$defs/SecretReference", + "description": "Secret reference to the migration connection URL." + }, + "runtimeUrlRef": { + "$ref": "#/$defs/SecretReference", + "description": "Secret reference to the least-privileged runtime connection URL." + }, + "testOnlyPlaintext": { + "default": false, + "description": "Allow a plaintext connection. Refused outside test builds.", + "type": "boolean" + }, + "transport": { + "$ref": "#/$defs/DatabaseTransport", + "description": "How the connection is protected. Absent means `verified-tls`. A\nplaintext transport must match the database hosts, and cannot be\nwritten beside `testOnlyPlaintext`.", + "x-registry-development-only": [ + "platform.posture.database-private-plaintext" + ] + } + }, + "required": [ + "runtimeUrlRef", + "migrationUrlRef" + ], + "type": "object" + }, + "DatabaseTransport": { + "description": "How a PostgreSQL connection is protected.", + "oneOf": [ + { + "const": "verified-tls", + "description": "TLS with verification. `caBundleRef` is optional.", + "type": "string" + }, + { + "const": "loopback-plaintext", + "description": "No TLS. Every host must be a Unix socket, a numeric loopback address\nor `localhost`.", + "type": "string" + }, + { + "const": "private-network-plaintext", + "description": "No TLS, in development only. Every host must also be loopback, a\nsocket, a private IPv4 address (RFC 1918), an IPv6 unique local\naddress (`fc00::/7`), or a name that resolves only to such addresses.", + "type": "string" + } + ] + }, + "EnvironmentSecretProviderConfig": { + "additionalProperties": false, + "description": "The environment secret provider. It takes no settings.", + "type": "object" + }, + "FileSecretProviderConfig": { + "additionalProperties": false, + "description": "The file secret provider.", + "properties": { + "root": { + "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" + } + }, + "required": [ + "root" + ], + "type": "object" + }, + "SecretProvidersConfig": { + "additionalProperties": false, + "anyOf": [ + { + "properties": { + "file": { + "$ref": "#/$defs/FileSecretProviderConfig" + } + }, + "required": [ + "file" + ] + }, + { + "properties": { + "environment": { + "$ref": "#/$defs/EnvironmentSecretProviderConfig" + } + }, + "required": [ + "environment" + ] + } + ], + "description": "The secret providers a runtime enables. A reference is resolved only by a\nprovider declared here: `secret:file/name` under `file.root`, and\n`secret:env/NAME` only when `environment: {}` is present.", + "properties": { + "environment": { + "$ref": "#/$defs/EnvironmentSecretProviderConfig", + "description": "Enables `secret:env/NAME` references, read from the process\nenvironment. Declared as an empty mapping: `environment: {}`." + }, + "file": { + "$ref": "#/$defs/FileSecretProviderConfig", + "description": "Enables `secret:file/name` references, read from files under `root`." + } + }, + "type": "object" + }, + "SecretReference": { + "description": "An exact secret reference: secret:file/name, resolved under secretProviders.file.root, or secret:env/NAME, resolved only when secretProviders.environment is declared.", + "pattern": "^(?:secret:env/[A-Z][A-Z0-9_]{0,127}|secret:file/[a-z][a-z0-9._-]{0,127})$", + "type": "string" + }, + "Store": { + "enum": [ + "status", + "oid4vci" + ], + "type": "string" + } + }, + "$id": "https://id.registrystack.org/schemas/evidence/store-provision/store-provision.v1alpha1.schema.json", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "properties": { + "apiVersion": { + "const": "id.registrystack.org/formats/evidence/store-provision/v1alpha1", + "type": "string" + }, + "database": { + "$ref": "#/$defs/DatabaseConfig" + }, + "kind": { + "const": "EvidenceStoreProvisionConfig", + "type": "string" + }, + "secretProviders": { + "$ref": "#/$defs/SecretProvidersConfig" + }, + "store": { + "$ref": "#/$defs/Store", + "description": "The Evidence PostgreSQL store this database is reserved for." + } + }, + "required": [ + "apiVersion", + "kind", + "store", + "database", + "secretProviders" + ], + "title": "Evidence store provisioning config", + "type": "object" +} diff --git a/crates/registry-evidencectl/src/lib.rs b/crates/registry-evidencectl/src/lib.rs index ad4fd9d7f4..a74210d554 100644 --- a/crates/registry-evidencectl/src/lib.rs +++ b/crates/registry-evidencectl/src/lib.rs @@ -43,6 +43,7 @@ mod scaffold; mod source_cli; mod source_import; mod source_mock; +mod store_provision; mod suggest; mod target; mod tooling; @@ -90,6 +91,8 @@ enum Command { Types(normalized::TypesArgs), /// Check a normalized project and, when selected, deployment closure, or one tooling file, offline. Check(CheckArgs), + /// Create split PostgreSQL roles and an empty database for a held Evidence store. + Provision(registry_platform_provision::ProvisionArgs), /// Explain the authored inventory and optional target-owned governance. Explain(ExplainArgs), /// Run the project's synthetic Evidence fixtures. @@ -181,7 +184,7 @@ enum CliFormat { ArgGroup::new("checked") .required(true) .multiple(false) - .args(["project", "file"]) + .args(["project", "file", "store_provision_config"]) ))] struct CheckArgs { #[arg( @@ -190,13 +193,16 @@ struct CheckArgs { help = "Declared posture: development or production. Unset means production." )] posture: Option, - /// Editable Evidence project directory. Required unless --file is given. + /// Editable Evidence project directory. Required unless --file or --store-provision-config is given. project: Option, /// Check one tooling file on its own, offline: a client profile, reviewed /// contracts, a ThunderID task connection or session file, a source-import /// baseline or journal, a source resolution file, or a source export manifest. #[arg(long, conflicts_with_all = ["project", "target", "production"])] file: Option, + /// Check a store provisioning file offline without resolving secrets. + #[arg(long, value_name = "FILE", conflicts_with_all = ["target", "production"])] + store_provision_config: Option, /// Explicit deployment target whose governance and runtime structure are checked. #[arg(long)] target: Option, @@ -365,16 +371,22 @@ fn cli_command() -> clap::Command { let command = HUMAN_ONLY_COMMANDS .iter() .fold(Cli::command(), |command, path| narrow_format(command, path)); - command.mut_subcommand("runtime", |subcommand| { - subcommand.arg( - clap::Arg::new("output_format") - .long("format") - .value_name("FORMAT") - .default_value("human") - .hide(true) - .value_parser(clap::builder::EnumValueParser::::new()), - ) - }) + command + .mut_subcommand("provision", |subcommand| { + subcommand.mut_arg("runtime_config", |argument| { + argument.help("Provisioning-only Evidence store file") + }) + }) + .mut_subcommand("runtime", |subcommand| { + subcommand.arg( + clap::Arg::new("output_format") + .long("format") + .value_name("FORMAT") + .default_value("human") + .hide(true) + .value_parser(clap::builder::EnumValueParser::::new()), + ) + }) } fn narrow_format(command: clap::Command, path: &[&str]) -> clap::Command { @@ -586,6 +598,7 @@ fn run_entry() -> ExitCode { } let posture_flag = match &cli.command { Command::Check(args) => Some(args.posture.as_deref()), + Command::Provision(args) => Some(args.posture.as_deref()), Command::Package(args) => Some(args.posture.as_deref()), Command::Test(args) => Some(args.posture.as_deref()), Command::Fixtures(fixtures::FixturesCommand::Run(args)) => Some(args.posture.as_deref()), @@ -687,11 +700,22 @@ fn run_entry() -> ExitCode { ) } Command::Types(args) => normalized::generate_types(args, format), + Command::Provision(args) => Ok(store_provision::run(&args, format, posture)), Command::Check(CheckArgs { file: Some(file), deny_warnings, .. }) => Ok(file_check::run(&file, format, deny_warnings)), + Command::Check(CheckArgs { + store_provision_config: Some(file), + deny_warnings, + .. + }) => Ok(store_provision::check( + &file, + format, + deny_warnings, + posture, + )), Command::Check(args) => { let artifact = project_of(&args).display().to_string(); safe_command( diff --git a/crates/registry-evidencectl/src/schema.rs b/crates/registry-evidencectl/src/schema.rs index d3cd7ba773..96bc78018a 100644 --- a/crates/registry-evidencectl/src/schema.rs +++ b/crates/registry-evidencectl/src/schema.rs @@ -14,6 +14,7 @@ use registry_evidence_authoring::schema::publish; use crate::source_import::{ resolution_schema, RESOLUTION_API_VERSION, RESOLUTION_KIND, RESOLUTION_SCHEMA_ID, }; +use crate::store_provision::{self, StoreProvisionDocument}; /// The schema for one local access client under `access/clients/`. pub const ACCESS_CLIENT_SCHEMA_FILE: &str = "access-client.schema.json"; @@ -23,6 +24,8 @@ pub const MOCK_PLAN_SCHEMA_FILE: &str = "mock-plan.schema.json"; /// The schema for one source import resolution file. pub const SOURCE_RESOLUTION_SCHEMA_FILE: &str = "source-resolution.schema.json"; +/// The schema for the operator-only database provisioning input. +pub const STORE_PROVISION_SCHEMA_FILE: &str = "store-provision.schema.json"; /// Every generated schema this crate owns, keyed by the filename it is /// committed under. @@ -59,6 +62,15 @@ pub fn documents() -> Result, serde_json::Error> (RESOLUTION_API_VERSION, RESOLUTION_KIND), )?, ), + ( + STORE_PROVISION_SCHEMA_FILE, + publish( + serde_json::to_value(schemars::schema_for!(StoreProvisionDocument))?, + "Evidence store provisioning config", + store_provision::SCHEMA_ID, + (store_provision::API_VERSION, store_provision::KIND), + )?, + ), ])) } @@ -70,6 +82,7 @@ mod tests { )] use super::{ documents, ACCESS_CLIENT_SCHEMA_FILE, MOCK_PLAN_SCHEMA_FILE, SOURCE_RESOLUTION_SCHEMA_FILE, + STORE_PROVISION_SCHEMA_FILE, }; fn compile(file: &str) -> jsonschema::JSONSchema { @@ -94,6 +107,7 @@ mod tests { ACCESS_CLIENT_SCHEMA_FILE, MOCK_PLAN_SCHEMA_FILE, SOURCE_RESOLUTION_SCHEMA_FILE, + STORE_PROVISION_SCHEMA_FILE, ] ); for (file, generated) in documents().expect("schemas generate") { @@ -107,6 +121,21 @@ mod tests { } } + #[test] + fn store_provision_schema_checks_the_example_and_its_envelope() { + let schema = compile(STORE_PROVISION_SCHEMA_FILE); + let mut example: serde_json::Value = serde_norway::from_str(include_str!(concat!( + env!("CARGO_MANIFEST_DIR"), + "/../../products/evidence/examples/formats/store-provision.yaml" + ))) + .expect("the store provision example is YAML"); + assert!(schema.is_valid(&example)); + example["store"] = serde_json::json!("oid4vci"); + assert!(schema.is_valid(&example)); + example["apiVersion"] = serde_json::json!("wrong-version"); + assert!(!schema.is_valid(&example)); + } + #[test] fn an_access_client_with_an_unusable_issuer_is_turned_away() { let schema = compile(ACCESS_CLIENT_SCHEMA_FILE); diff --git a/crates/registry-evidencectl/src/store_provision.rs b/crates/registry-evidencectl/src/store_provision.rs new file mode 100644 index 0000000000..315322b68a --- /dev/null +++ b/crates/registry-evidencectl/src/store_provision.rs @@ -0,0 +1,306 @@ +// SPDX-License-Identifier: Apache-2.0 +//! Operator-only database provisioning for the two held PostgreSQL stores. + +use std::{path::Path, process::ExitCode}; + +use registry_platform_config::{ + describe_secret_failure, DatabaseConfig, DatabaseTransport, DeclaredPosture, + RuntimeConfigLoader, RuntimeEnvelope, SecretProvidersConfig, DEFAULT_STAND_IN, +}; +use registry_platform_provision::{ + provision_transport, run_provision, ProductDatabase, ProvisionArgs, ProvisionInput, + SchemaLayout, +}; +use registry_platform_yaml::{Diagnostic, Report, Source}; +use serde::Deserialize; +use zeroize::Zeroizing; + +use crate::{report, OutputFormat}; + +pub(crate) const API_VERSION: &str = + "id.registrystack.org/formats/evidence/store-provision/v1alpha1"; +pub(crate) const KIND: &str = "EvidenceStoreProvisionConfig"; +const SPLIT_ROLES_REQUIRED: &str = "evidence.store-provision.split-roles-required"; +#[cfg(feature = "schema")] +pub(crate) const SCHEMA_ID: &str = + "https://id.registrystack.org/schemas/evidence/store-provision/store-provision.v1alpha1.schema.json"; + +#[derive(Deserialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde(rename_all = "kebab-case")] +enum Store { + Status, + Oid4vci, +} + +impl Store { + fn product(&self) -> ProductDatabase { + ProductDatabase { + product: match self { + Self::Status => "evidence-status", + Self::Oid4vci => "evidence-oid4vci", + }, + // Both stores create their schema in their separate migration. + layout: SchemaLayout::CreatedByApply, + btree_gist: false, + spatial: None, + } + } +} + +#[derive(Deserialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub(crate) struct StoreProvisionDocument { + #[cfg_attr(feature = "schema", schemars(skip))] + #[serde(rename = "apiVersion")] + _api_version: String, + #[cfg_attr(feature = "schema", schemars(skip))] + #[serde(rename = "kind")] + _kind: String, + /// The Evidence PostgreSQL store this database is reserved for. + store: Store, + database: DatabaseConfig, + secret_providers: SecretProvidersConfig, +} + +fn loader(declared: DeclaredPosture) -> RuntimeConfigLoader { + RuntimeConfigLoader::new( + RuntimeEnvelope { + api_version: API_VERSION, + kind: KIND, + }, + declared, + ) + .require_trusted_ownership() +} + +fn diagnostics(config: &StoreProvisionDocument, defers: impl Fn(&str) -> bool) -> Vec { + let mut findings = Vec::new(); + let mut block = |error: registry_platform_config::ConfigBlockError| { + findings.push(Diagnostic::error( + "evidence.store-provision.configuration", + &format!("/{}", error.field().replace('.', "/")), + error.to_string(), + "Correct the named field in the provisioning file.", + )); + }; + if let Err(error) = config.secret_providers.check() { + if !defers(&format!("/{}", error.field().replace('.', "/"))) { + block(error); + } + } + for (field, reference) in config.database.references() { + if !defers(&format!("/{}", field.replace('.', "/"))) { + if let Err(error) = config.secret_providers.check_reference(field, reference) { + block(error); + } + } + } + if config.database.migration_url_ref == config.database.runtime_url_ref + && !defers("/database/migrationUrlRef") + && !defers("/database/runtimeUrlRef") + { + findings.push(Diagnostic::error( + SPLIT_ROLES_REQUIRED, + "/database/runtimeUrlRef", + "the two URL references are identical", + "Use separate references for the migration and runtime login URLs.", + )); + } + if config.database.test_only_plaintext && !defers("/database/testOnlyPlaintext") { + findings.push(Diagnostic::error( + "evidence.store-provision.transport-refused", + "/database/testOnlyPlaintext", + "testOnlyPlaintext is unavailable for store provisioning", + "Use verified TLS or the explicit loopback-plaintext transport.", + )); + } + if !defers("/database/transport") + && provision_transport(&config.database) == DatabaseTransport::PrivateNetworkPlaintext + { + findings.push(Diagnostic::error( + "evidence.store-provision.transport-refused", + "/database/transport", + "store provisioning cannot use private-network-plaintext", + "Use verified TLS or the explicit loopback-plaintext transport.", + )); + } + findings +} + +fn unavailable_path() -> Diagnostic { + Diagnostic::error( + "evidence.store-provision.config-path", + "", + "the provisioning file path cannot be resolved", + "Pass an absolute path to the provisioning file.", + ) +} + +fn decoded_login(url: &str) -> Option { + let url = url::Url::parse(url).ok()?; + // Match the PostgreSQL URL reader's user-info decoding. The provisioner + // validates endpoint overrides and the rest of the URL before doing work. + percent_encoding::percent_decode_str(url.username()) + .decode_utf8() + .ok() + .map(|login| login.into_owned()) +} + +pub(crate) fn check( + path: &Path, + format: OutputFormat, + deny_warnings: bool, + declared: DeclaredPosture, +) -> ExitCode { + let (found, unavailable) = match std::path::absolute(path) { + Ok(path) => { + let checked = + loader(declared).check_offline::(&path, false, |pointer| { + match pointer { + "/store" => "status", + "/secretProviders/file/root" => "/deferred", + "/database/transport" => "verified-tls", + "/database/testOnlyPlaintext" => "false", + _ => DEFAULT_STAND_IN, + } + }); + let extra = checked.loaded.as_ref().map_or_else(Vec::new, |loaded| { + diagnostics(&loaded.config, |pointer| checked.defers(pointer)) + }); + let positioned = extra.into_iter().map(|finding| { + checked.error_at( + KIND, + &finding.code, + &finding.path, + finding.message, + finding.suggested_action, + ) + }); + (checked.report_with(KIND, positioned), checked.unavailable) + } + Err(_) => (Report::new(vec![unavailable_path()]), true), + }; + let exit = if unavailable { + report::OPERATIONAL_FAILURE_EXIT + } else if found.has_errors() || crate::check::refuses_warnings(&found, deny_warnings) { + report::DOMAIN_REFUSAL_EXIT + } else { + report::SUCCESS_EXIT + }; + if exit == report::SUCCESS_EXIT { + match format { + OutputFormat::Json => crate::print_report_with_posture( + &report::success( + "check", + "complete", + serde_json::json!({"diagnostics": found.to_json_value()}), + ), + Some(declared), + ), + OutputFormat::Human => print!("{}", found.render_human()), + } + } else { + crate::write_report_failure("check", exit, &found, format, Some(declared)); + } + ExitCode::from(exit) +} + +fn load(path: &Path, declared: DeclaredPosture) -> Result> { + let absolute = std::path::absolute(path).map_err(|_| vec![unavailable_path()])?; + let loaded = loader(declared) + .load::(&absolute) + .map_err(|error| error.diagnostics().to_vec())?; + let config = loaded.config; + let findings = diagnostics(&config, |_| false); + if !findings.is_empty() { + return Err(findings); + } + let refuse = |code: &str, pointer: &str, message: String, action: &str| { + let mut diagnostic = Diagnostic::error(code, pointer, message, action); + diagnostic.artifact = Some(KIND.to_owned()); + diagnostic.source = Some(Source { + file: path.display().to_string(), + line: None, + column: None, + }); + vec![diagnostic] + }; + let secrets = config + .secret_providers + .resolver(loaded.development.as_ref()) + .map_err(|error| { + refuse( + "evidence.store-provision.secret-provider", + "/secretProviders", + error.to_string(), + error.suggested_action(), + ) + })?; + let resolve = |member: &str, reference: &str| { + secrets.resolve(reference).map_err(|error| { + refuse( + "evidence.store-provision.secret-unavailable", + &format!("/database/{member}"), + describe_secret_failure(&format!("database.{member}"), reference, &error), + error.suggested_action(), + ) + }) + }; + 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(|_| { + refuse( + "evidence.store-provision.url-invalid", + &format!("/database/{member}"), + "the PostgreSQL URL secret is not UTF-8".to_owned(), + "Write a PostgreSQL URL in the secret.", + ) + }) + }; + let input = ProvisionInput { + product: config.store.product(), + migration_url: url("migrationUrlRef", &config.database.migration_url_ref)?, + runtime_url: url("runtimeUrlRef", &config.database.runtime_url_ref)?, + ca_pem: config + .database + .ca_bundle_ref + .as_deref() + .map(|reference| resolve("caBundleRef", reference)) + .transpose()? + .map(|secret| secret.expose_secret().to_vec()), + transport: provision_transport(&config.database), + }; + let logins = decoded_login(&input.migration_url).zip(decoded_login(&input.runtime_url)); + if logins.is_some_and(|(migration, runtime)| migration == runtime) { + return Err(refuse( + SPLIT_ROLES_REQUIRED, + "/database/runtimeUrlRef", + "the two URLs name the same PostgreSQL login".to_owned(), + "Give the migration and runtime URLs distinct PostgreSQL login names.", + )); + } + Ok(input) +} + +pub(crate) fn run( + args: &ProvisionArgs, + format: OutputFormat, + declared: DeclaredPosture, +) -> ExitCode { + let format = match format { + OutputFormat::Human => registry_platform_provision::cli::OutputFormat::Human, + OutputFormat::Json => registry_platform_provision::cli::OutputFormat::Json, + }; + run_provision( + "evidencectl", + registry_platform_buildinfo::DISPLAY_VERSION, + args, + format, + declared, + |path| load(path, declared), + ) +} diff --git a/crates/registry-evidencectl/tests/store_provision.rs b/crates/registry-evidencectl/tests/store_provision.rs new file mode 100644 index 0000000000..7a137faff0 --- /dev/null +++ b/crates/registry-evidencectl/tests/store_provision.rs @@ -0,0 +1,234 @@ +// SPDX-License-Identifier: Apache-2.0 + +use std::path::Path; +use std::process::{Command, Output}; + +fn config(directory: &Path, store: &str) -> std::path::PathBuf { + let path = directory.join("store-provision.yaml"); + std::fs::write( + &path, + format!( + "\ +apiVersion: id.registrystack.org/formats/evidence/store-provision/v1alpha1 +kind: EvidenceStoreProvisionConfig +store: {store} +database: + migrationUrlRef: secret:env/EVIDENCE_TEST_STORE_MIGRATION + runtimeUrlRef: secret:env/EVIDENCE_TEST_STORE_RUNTIME +secretProviders: + environment: {{}} +" + ), + ) + .expect("write operator configuration"); + path +} + +fn evidencectl() -> Command { + let mut command = Command::new(env!("CARGO_BIN_EXE_evidencectl")); + command + .env_remove("REGISTRY_STACK_POSTURE") + .env_remove("EVIDENCE_TEST_STORE_MIGRATION") + .env_remove("EVIDENCE_TEST_STORE_RUNTIME"); + command +} + +fn check(path: &Path) -> Output { + evidencectl() + .args(["--format", "json", "check", "--store-provision-config"]) + .arg(path) + .output() + .expect("run offline check") +} + +fn plan(path: &Path, migration_role: &str, runtime_role: &str) -> Output { + let endpoint = + |role: &str| format!("postgresql://{role}:synthetic-canary@db.example.test/store"); + evidencectl() + .args(["provision", "--print-sql", "--runtime-config"]) + .arg(path) + .env("EVIDENCE_TEST_STORE_MIGRATION", endpoint(migration_role)) + .env("EVIDENCE_TEST_STORE_RUNTIME", endpoint(runtime_role)) + .output() + .expect("plan provisioning") +} + +#[test] +fn both_store_documents_check_without_resolving_secrets() { + let directory = tempfile::tempdir().expect("private test directory"); + for store in ["status", "oid4vci"] { + let output = check(&config(directory.path(), store)); + assert!( + output.status.success(), + "{store} check: {:?}", + output.status + ); + let report: serde_json::Value = + serde_json::from_slice(&output.stdout).expect("check report"); + assert_eq!(report["status"], "complete"); + } +} + +#[test] +fn an_unknown_store_is_refused_offline() { + let directory = tempfile::tempdir().expect("private test directory"); + let output = check(&config(directory.path(), "unrecognised")); + assert_eq!(output.status.code(), Some(1)); + let report: serde_json::Value = serde_json::from_slice(&output.stdout).expect("check report"); + assert_eq!(report["diagnostics"][0]["path"], "/store"); +} + +#[test] +fn a_shared_url_reference_is_refused_without_resolving_it() { + let directory = tempfile::tempdir().expect("private test directory"); + let path = config(directory.path(), "status"); + let document = std::fs::read_to_string(&path).expect("read test configuration"); + std::fs::write( + &path, + document.replace( + "EVIDENCE_TEST_STORE_RUNTIME", + "EVIDENCE_TEST_STORE_MIGRATION", + ), + ) + .expect("write shared reference"); + let output = check(&path); + assert_eq!(output.status.code(), Some(1)); + let report: serde_json::Value = serde_json::from_slice(&output.stdout).expect("check report"); + assert_eq!(report["diagnostics"][0]["path"], "/database/runtimeUrlRef"); + assert_eq!( + report["diagnostics"][0]["code"], + "evidence.store-provision.split-roles-required" + ); +} + +#[test] +fn provisioning_plans_split_roles_and_leaves_migration_separate() { + let directory = tempfile::tempdir().expect("private test directory"); + for store in ["status", "oid4vci"] { + let output = plan(&config(directory.path(), store), "migration", "runtime"); + assert!(output.status.success(), "{store} plan: {:?}", output.status); + let sql = std::str::from_utf8(&output.stdout).expect("SQL text"); + assert!(sql.contains("CREATE ROLE \"migration\"")); + assert!(sql.contains("CREATE ROLE \"runtime\"")); + assert!(sql.contains("GRANT CREATE ON DATABASE \"store\" TO \"migration\"")); + assert!(!sql.contains("CREATE TABLE")); + assert!(!sql.contains("synthetic-canary")); + assert!(!sql.contains("SCRAM-SHA-256")); + } +} + +#[test] +fn a_shared_login_is_refused_even_when_one_url_encodes_it() { + let directory = tempfile::tempdir().expect("private test directory"); + let output = plan(&config(directory.path(), "status"), "same", "%73ame"); + assert!(!output.status.success()); + assert!(output.stdout.is_empty()); + let refusal = std::str::from_utf8(&output.stderr).expect("refusal text"); + assert!(refusal.contains("evidence.store-provision.split-roles-required")); + assert!(!refusal.contains("synthetic-canary")); +} + +/// Use the shared verified-TLS fixture. Both variables must point to a +/// disposable server, as in the other products' provisioning tests. +#[cfg(feature = "postgres-test")] +#[tokio::test] +async fn both_stores_provision_idempotently_without_migrating() { + use registry_platform_provision::test_support::{connect_verified, provision_test_env}; + + let (admin_url, ca) = provision_test_env(); + let admin = connect_verified(&admin_url, &ca, None).await; + let base = registry_platform_provision::admin_config(&admin_url, Some(&ca)) + .expect("parse the disposable TLS endpoint"); + let directory = tempfile::tempdir().expect("private test directory"); + for (store, schema) in [ + ("status", "evidence_status"), + ("oid4vci", "evidence_oid4vci"), + ] { + let suffix: u64 = rand::random(); + let database = format!("evidence_store_{suffix:x}"); + let migration = format!("evidence_mig_{suffix:x}"); + let runtime = format!("evidence_run_{suffix:x}"); + let url = |role: &str| { + format!( + "postgresql://{role}:synthetic-canary@{}:{}/{database}?sslmode=verify-full", + base.host(), + base.port() + ) + }; + let migration_url = url(&migration); + let runtime_url = url(&runtime); + let config_path = config(directory.path(), store); + let document = std::fs::read_to_string(&config_path).expect("read test configuration"); + std::fs::write( + &config_path, + document.replace( + "database:\n", + "database:\n caBundleRef: secret:env/EVIDENCE_TEST_STORE_CA\n", + ), + ) + .expect("add the disposable CA reference"); + for _ in 0..2 { + let output = evidencectl() + .args([ + "--format", + "json", + "provision", + "--admin-url-env", + "EVIDENCE_TEST_STORE_ADMIN", + "--runtime-config", + ]) + .arg(&config_path) + .env("EVIDENCE_TEST_STORE_MIGRATION", &migration_url) + .env("EVIDENCE_TEST_STORE_RUNTIME", &runtime_url) + .env( + "EVIDENCE_TEST_STORE_CA", + std::str::from_utf8(&ca).expect("fixture PEM"), + ) + .env("EVIDENCE_TEST_STORE_ADMIN", &admin_url) + .output() + .expect("invoke the provision command"); + assert!( + output.status.success(), + "{store} provision: {:?}", + output.status + ); + let report: serde_json::Value = + serde_json::from_slice(&output.stdout).expect("provision report"); + assert_eq!(report["roleMode"], "split"); + assert!(!String::from_utf8_lossy(&output.stdout).contains("synthetic-canary")); + } + let runtime_client = connect_verified(&runtime_url, &ca, None).await; + let migration_client = connect_verified(&migration_url, &ca, None).await; + let privilege = "SELECT has_database_privilege(current_database(), 'CREATE')"; + assert!(!runtime_client + .query_one(privilege, &[]) + .await + .unwrap() + .get::<_, bool>(0)); + assert!(migration_client + .query_one(privilege, &[]) + .await + .unwrap() + .get::<_, bool>(0)); + assert!(migration_client + .query_one("SELECT to_regnamespace($1) IS NULL", &[&schema]) + .await + .unwrap() + .get::<_, bool>(0)); + // The separate migration can create the store schema under its own role. + migration_client + .batch_execute(&format!("BEGIN; CREATE SCHEMA {schema}; ROLLBACK")) + .await + .expect("migration role can create the store schema"); + drop(runtime_client); + drop(migration_client); + admin + .batch_execute(&format!("DROP DATABASE {database} WITH (FORCE)")) + .await + .expect("clean up owned disposable database"); + admin + .batch_execute(&format!("DROP ROLE {migration}, {runtime}")) + .await + .expect("clean up owned disposable roles"); + } +} diff --git a/docs/site/src/content/docs/configure/evidence-oid4vci.mdx b/docs/site/src/content/docs/configure/evidence-oid4vci.mdx index 73f19764f0..a43cddb0b3 100644 --- a/docs/site/src/content/docs/configure/evidence-oid4vci.mdx +++ b/docs/site/src/content/docs/configure/evidence-oid4vci.mdx @@ -160,6 +160,18 @@ schema gives it, and `check` also enforces the rules a schema cannot hold: evidence.oid4vci.secret-file-root; products/evidence/examples/oid4vci-runtime/runtime.yaml. */} +## Prepare a PostgreSQL store for qualification + +To prepare a database for the OID4VCI store, follow +[Provision a PostgreSQL store for qualification](../../products/registry-evidence/operator-contract/#provision-a-postgresql-store-for-qualification) +and set `store: oid4vci` in the provisioning file. Provisioning prepares the +database and logins for a separate migration. `evidence-oid4vci serve` uses the +bounded in-memory store. + +{/* Evidence: crates/registry-evidencectl/src/store_provision.rs; + crates/registry-evidence-oid4vci/src/lib.rs; + crates/registry-evidence-oid4vci/src/storage/postgres.rs, migrate(). */} + ## Check offline Check the file before the service reads it: diff --git a/products/evidence/OPERATOR-CONTRACT.md b/products/evidence/OPERATOR-CONTRACT.md index 38c67a745c..842a8cdc20 100644 --- a/products/evidence/OPERATOR-CONTRACT.md +++ b/products/evidence/OPERATOR-CONTRACT.md @@ -68,6 +68,28 @@ constraint the authorization server issued the token under. An authorization server that binds tokens to DPoP keys or client certificates must issue Evidence clients unbound tokens. +### Provision a PostgreSQL store for qualification + +Use `evidencectl provision` to prepare a dedicated database and two PostgreSQL +logins for the status ledger or the OID4VCI store. Use +[`store-provision.yaml`](examples/formats/store-provision.yaml) as the operator +file. Set `store` to `status` or `oid4vci` and supply secret references for the +distinct migration and runtime login URLs. The URLs must name the same database +on the same server. Use the `database.caBundleRef` reference when the database +uses a private CA. + +Check the file with `evidencectl check --store-provision-config store-provision.yaml`. +The check reads no secret values. Review the plan with +`evidencectl provision --runtime-config store-provision.yaml --print-sql`. +The plan reads the configured database secrets and connects to no PostgreSQL server. +To execute it, replace `--print-sql` with `--admin-url-file `. +You can run the same provision command again to converge the same target. + +Provision grants database `CREATE` to the migration login and `CONNECT` to both +logins. On an existing database, check that the runtime login holds only the +intended privileges. The explicit store migration and its table grants are a +separate step. Neither served runtime selects the PostgreSQL store. + ## Governed bundle and operator runtime The operator supplies one atomic bundle containing the approved YAML, diff --git a/products/evidence/examples/formats/store-provision.yaml b/products/evidence/examples/formats/store-provision.yaml new file mode 100644 index 0000000000..391ebc91b8 --- /dev/null +++ b/products/evidence/examples/formats/store-provision.yaml @@ -0,0 +1,11 @@ +# yaml-language-server: $schema=https://id.registrystack.org/schemas/evidence/store-provision/store-provision.v1alpha1.schema.json +apiVersion: id.registrystack.org/formats/evidence/store-provision/v1alpha1 +kind: EvidenceStoreProvisionConfig +store: status +database: + migrationUrlRef: secret:file/migration-url + runtimeUrlRef: secret:file/runtime-url + caBundleRef: secret:file/postgres-ca +secretProviders: + file: + root: /run/evidence-store-secrets From d011b8cd1657dab57641cf72ee5e508bd1e88a1f Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 18:51:27 +0000 Subject: [PATCH 053/183] fix(journeys): shorten managed paths to the first read Signed-off-by: Jeremi Joslin (cherry picked from commit fb043dfd27490a1ccea7ca363a6ded2886a8fde8) --- products/platform/journeys/rstack-dev.sh | 52 +++++++++------- .../platform/journeys/test_journey_tables.py | 62 +++++++++++++++++-- 2 files changed, 88 insertions(+), 26 deletions(-) diff --git a/products/platform/journeys/rstack-dev.sh b/products/platform/journeys/rstack-dev.sh index f24b30b5b1..9a98926c89 100755 --- a/products/platform/journeys/rstack-dev.sh +++ b/products/platform/journeys/rstack-dev.sh @@ -488,7 +488,7 @@ unexpected_answer() { walk_product() { # shellcheck disable=SC2034 # token and token2 are set by name through issue_token local product=$1 work project tier plan_capable status=0 url message_id='' token='' token2='' workflow_revision='' uses_postgres - local first_read=0 documents_receipt='' + local first_read=0 documents_receipt='' standalone_plan_check=0 journey_product_field "$product" tier tier journey_product_field "$product" rstackDevPlan plan_capable journey_product_field "$product" usesPostgres uses_postgres @@ -512,23 +512,25 @@ walk_product() { fi journey_pass init - # plan: `rstack dev check` on the project init wrote. A product that init - # gave no plan for, and that the plan format cannot name, is given the plan - # a reader would write first. + # A generated plan is validated by start. Products without a supported + # starter still need a separate check to report what stops the reader. if [[ ! -f "$project/dev.yaml" && "$plan_capable" != true ]]; then write_probe_plan "$product" "$project" fi - journey_step plan --concepts development-plan --typed "rstack dev check $project" -- rstack_dev check "$project" || status=$? - if [[ $status -ne 0 ]]; then - if [[ ! -f "$project/dev.yaml" ]]; then - journey_needs plan hand-written-plan - else - fail_with_product_code plan "$JOURNEY_STEP_STDOUT" "$JOURNEY_STEP_STDERR" + if [[ ! -f "$project/dev.yaml" || "$plan_capable" != true ]]; then + standalone_plan_check=1 + journey_step plan --concepts development-plan --typed "rstack dev check $project" -- rstack_dev check "$project" || status=$? + if [[ $status -ne 0 ]]; then + if [[ ! -f "$project/dev.yaml" ]]; then + journey_needs plan hand-written-plan + else + fail_with_product_code plan "$JOURNEY_STEP_STDOUT" "$JOURNEY_STEP_STDERR" + fi + journey_cell_end + return 0 fi - journey_cell_end - return 0 + journey_pass plan fi - journey_pass plan # start: one command, after supplying the optional fixture endpoints. case "$product" in @@ -552,27 +554,28 @@ walk_product() { if ! jq -e 'all(.scenarios[]; .result == "passed")' "$START_FILE" >/dev/null; then journey_harness_failure "the start report of $product holds a journey that did not pass; see $START_FILE" fi + [[ $standalone_plan_check -eq 1 ]] || journey_pass plan journey_pass start local run=$RUN url=$(run_url "$product") recipe "$product" - # issuer: the issuer the run gave the product, read from the runtime file - # the report names. + # Check the issuer the runner generated before sending the request. The + # reader uses the header file from `dev token` directly. local runtime_file runtime_file=$(jq -er --arg product "$product" '.runtimeConfigs[$product]' "$START_FILE") || journey_harness_failure "the start report names no runtime file for $product" if [[ "$product" == evidence ]]; then - journey_step issuer --concepts issuer-url,jwks-uri,audience,allowed-clients,scope-claim -- \ - "$JOURNEY_BIN_DIR/evidence" check --posture development --runtime-config "$runtime_file" --format json + # Start already checks the Evidence target, activates its authority and + # runs the authenticated scenario against the generated YAML configuration. + [[ -s "$runtime_file" ]] || journey_harness_failure "the checked Evidence runtime file is missing or empty" elif [[ "$product" == discovery ]]; then printf '%s\n' "Discovery's public index has no issuer." else - journey_step issuer --concepts issuer-url,jwks-uri,audience,allowed-clients,scope-claim \ - --typed "jq read issuer settings $runtime_file" -- \ - jq -e '(.authentication.oidc // .deployment.authentication // .oidc).issuers + jq -e '(.authentication.oidc // .deployment.authentication // .oidc).issuers | select(type == "object" and length > 0) - | map_values({issuer, audience, allowedClients, scopeClaim, jwksSource: .jwksSource.type})' "$runtime_file" || + | map_values({issuer, audience, allowedClients, scopeClaim, jwksSource: .jwksSource.type})' \ + "$runtime_file" >"$work/issuer.json" || journey_harness_failure "cannot read the issuer of $product from $runtime_file" fi journey_pass issuer @@ -606,8 +609,13 @@ walk_product() { if [[ $status -ne 0 ]]; then unexpected_answer call fi + if [[ "$product" == messaging ]]; then + journey_http call --expect-status 200 --bearer token GET "$url/v1/messages/$message_id" || unexpected_answer call + jq -e --arg id "$message_id" '.id == $id' "$JOURNEY_STEP_STDOUT" >/dev/null || + journey_harness_failure "the message read did not return the submitted message" + fi journey_pass call - if [[ "$CALL_METHOD" == GET && -n "$PERSON" ]]; then + if [[ "$product" == messaging || ("$CALL_METHOD" == GET && -n "$PERSON") ]]; then journey_reached t1 first_read=1 fi diff --git a/products/platform/journeys/test_journey_tables.py b/products/platform/journeys/test_journey_tables.py index cb107b64bd..70c097f4f6 100644 --- a/products/platform/journeys/test_journey_tables.py +++ b/products/platform/journeys/test_journey_tables.py @@ -955,11 +955,20 @@ def walk(self, product, delivered): "$scratch" >"$scratch/runtime.json" : >"$scratch/audit.jsonl" : >"$scratch/audit.schedulingctl.jsonl" -init_command() { INIT_COMMAND=(true); } +write_starter() { mkdir -p "$1"; : >"$1/dev.yaml"; } +init_command() { INIT_COMMAND=(write_starter "$2"); } add_contact_hook() { :; } add_documents_hooks() { :; } +start_evidence_source() { :; } +stop_evidence_source() { :; } +measure_reader_action() { + if [[ "$delivered" == first-hour ]]; then + journey_step "$1" -- true + fi +} start_run() { local result=passed + measure_reader_action "$1" [[ "$1" != keep ]] || result=skipped RUN=$1-run START_FILE=$scratch/$1.json @@ -973,7 +982,7 @@ def walk(self, product, delivered): LIVE_RUNS+="$RUN"$'\n' } run_url() { printf '%s\n' 'http://127.0.0.1:49192'; } -issue_token() { :; } +issue_token() { measure_reader_action "$1"; } write_keep() { KEEP_PERSON=$PERSON KEEP_PATH=/retained @@ -1054,7 +1063,25 @@ def walk(self, product, delivered): esac fi case "$1" in - call) printf '%s\n' '{}' >"$JOURNEY_STEP_STDOUT" ;; + call) + measure_reader_action "$1" + JOURNEY_STEP_STDOUT=$scratch/response.json + if [[ "$CELL" == messaging ]]; then + case "${@: -2:1} ${!#}" in + 'POST http://127.0.0.1:49192/v1/messages') + message_id=message-1 + printf '%s\n' 'submit message' >>"$trace" + ;; + 'GET http://127.0.0.1:49192/v1/messages/message-1') + printf '%s\n' 'read submitted message' >>"$trace" + ;; + *) return 1 ;; + esac + printf '%s\n' '{"id":"message-1"}' >"$JOURNEY_STEP_STDOUT" + else + printf '%s\n' '{}' >"$JOURNEY_STEP_STDOUT" + fi + ;; hook) [[ "${!#}" == http://127.0.0.1:49191/received ]] printf '%s\n' 'read sink' >>"$trace" @@ -1079,13 +1106,21 @@ def walk(self, product, delivered): run_containers() { printf '%s\n' 'fake-container'; } journey_check_absent() { :; } -journey_init rstack-dev -- --product "$product" --out "$scratch/run" +options=() +[[ "$delivered" != first-hour ]] || options+=(--timed) +journey_init rstack-dev -- --product "$product" --out "$scratch/run" "${options[@]}" +JOURNEY_BIN_DIR=$scratch +printf '%s\n' '#!/usr/bin/env bash' 'exit 0' >"$scratch/evidence" +chmod +x "$scratch/evidence" if [[ "$delivered" == terminal-step ]]; then journey_cell_begin "$product" journey_unexercised stop else walk_product "$product" fi +if [[ "$delivered" == first-hour ]]; then + jq -r '.toT1.steps' "$scratch/run/$product/cell.json" >>"$trace" +fi journey_finish """ with tempfile.TemporaryDirectory() as directory: @@ -1102,6 +1137,25 @@ def walk(self, product, delivered): trace = trace_file.read_text(encoding="utf-8").splitlines() if trace_file.exists() else [] return result, outcomes, trace + def test_starter_first_read_uses_four_reader_commands(self): + result, outcomes, trace = self.walk("scheduling", "first-hour") + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertEqual(trace[-1], "4") + self.assertIn(("plan", "pass"), outcomes) + self.assertIn(("issuer", "pass"), outcomes) + + def test_messaging_reads_the_submitted_message_before_restart(self): + result, _, trace = self.walk("messaging", "first-hour") + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertEqual(trace[:2], ["submit message", "read submitted message"]) + self.assertEqual(trace[-1], "5") + + def test_evidence_first_read_uses_the_checked_start(self): + result, outcomes, trace = self.walk("evidence", "first-hour") + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertEqual(trace[-1], "4") + self.assertIn(("issuer", "pass"), outcomes) + def test_scheduling_reports_unexercised_and_keeps_walking(self): result, outcomes, trace = self.walk("scheduling", "no") self.assertEqual(result.returncode, 0, result.stdout + result.stderr) From c2f579dd79c6e7ef5b982207a6b3322c59be0502 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 19:10:24 +0000 Subject: [PATCH 054/183] feat(dev): bind managed Scheduling to one live task authority Signed-off-by: Jeremi Joslin --- crates/registry-rstack-dev/src/bindings.rs | 1 + .../registry-rstack-dev/src/external_breg.rs | 123 ++++++++++++++++-- crates/registry-rstack-dev/src/plan.rs | 119 ++++++++++++++++- crates/registry-rstack-dev/src/products.rs | 8 ++ .../run-a-project-with-rstack-dev.mdx | 17 +++ products/platform/config-formats.yaml | 18 ++- 6 files changed, 274 insertions(+), 12 deletions(-) diff --git a/crates/registry-rstack-dev/src/bindings.rs b/crates/registry-rstack-dev/src/bindings.rs index 84edefcc8a..cf07d0a5d3 100644 --- a/crates/registry-rstack-dev/src/bindings.rs +++ b/crates/registry-rstack-dev/src/bindings.rs @@ -1464,6 +1464,7 @@ mod tests { issuer: "https://identity.example.test/realms/dev".to_owned(), external_jwks_uri: None, external_breg: None, + external_scheduling: None, products: vec![ ProductPlan { product: Product::Breg, diff --git a/crates/registry-rstack-dev/src/external_breg.rs b/crates/registry-rstack-dev/src/external_breg.rs index 47b6042554..0d5740e67b 100644 --- a/crates/registry-rstack-dev/src/external_breg.rs +++ b/crates/registry-rstack-dev/src/external_breg.rs @@ -16,7 +16,8 @@ use std::{ use zeroize::Zeroizing; use crate::plan::{ - identifier, numeric_loopback_endpoint, require, SemanticRefusal, SemanticResult, + identifier, issuer_url, numeric_loopback_endpoint, require, Plan, Product, SemanticRefusal, + SemanticResult, }; #[derive(Deserialize, Serialize)] @@ -71,6 +72,111 @@ pub(super) struct TaskGrant { status_resource: String, } +impl TaskGrant { + pub(super) fn validate_for_scheduling( + &self, + root: &Path, + plan: &Plan, + audience: &str, + ) -> SemanticResult<()> { + let same_origin = |endpoint: &str| { + url::Url::parse(endpoint) + .ok() + .zip(url::Url::parse(&plan.issuer).ok()) + .is_some_and(|(endpoint, issuer)| endpoint.origin() == issuer.origin()) + }; + require( + plan.jwks_uri().is_some_and(same_origin), + "/externalJwksUri", + "The Scheduling fixture issuer and its key endpoint must have the same origin.", + "Use the key endpoint published by the configured external issuer.", + )?; + let check = |valid, field, reason, remedy| { + require( + valid, + &format!("/externalScheduling/taskGrant/{field}"), + reason, + remedy, + ) + }; + check( + issuer_url(self.source_issuer.as_str()), + "sourceIssuer", + "The Scheduling fixture needs an exact HTTPS assertion issuer name.", + "Use the issuer name in the Casework task grant.", + )?; + check( + identifier(&self.assertion_client) + && plan + .people + .values() + .filter(|person| { + person.client == self.assertion_client + && person.grants.contains_key(&Product::Scheduling) + }) + .count() + == 1, + "assertionClient", + "The assertion client must name exactly one planned Scheduling caller.", + "Use the exact external booking client in one Scheduling grant entry.", + )?; + check( + crate::products::is_loopback_run_issuer(self.status_url.as_str()), + "statusUrl", + "The task status connection must use a numeric loopback HTTP origin.", + "Use the exact Casework status service origin with its port.", + )?; + check( + numeric_loopback_endpoint(self.token_endpoint.as_str()) + && same_origin(self.token_endpoint.as_str()), + "tokenEndpoint", + "The task status token endpoint must use the exact external issuer origin.", + "Use the token endpoint published by the configured external issuer.", + )?; + check( + identifier(&self.status_client) && self.status_client != self.assertion_client, + "statusClient", + "The task status client must have its own identifier.", + "Use a separate external client registered for task status reads.", + )?; + check( + registry_platform_httputil::valid_resource_uri(audience) + && registry_platform_httputil::valid_resource_uri(&self.status_resource) + && self.status_resource != audience, + "statusResource", + "The status resource must be an absolute URI distinct from the Scheduling audience.", + "Use the Casework status resource configured for the status client.", + )?; + check( + root.canonicalize() + .is_ok_and(|root| private_fixture(&root, &self.status_key_ref).is_ok()), + "statusKeyRef", + "The task status key must be a readable owner-only fixture file.", + "Use a secret:file reference to the separate status key under fixture/ with mode 0600.", + ) + } + + pub(super) fn configure( + &self, + store: impl FnOnce(&[u8]) -> Result, + root: &Path, + issuer: &str, + config: &mut Value, + ) -> Result<()> { + let key = private_fixture(root, &self.status_key_ref)?; + let private_key_ref = store(&key)?; + config["authentication"]["oidc"]["issuers"]["main"]["assertionIssuers"] + [&self.assertion_client] = json!([self.source_issuer]); + config["taskGrantStatus"] = json!([{ + "sourceIssuer": self.source_issuer, "baseUrl": self.status_url, + "tokenEndpoint": self.token_endpoint, "clientAssertionAudience": issuer, + "clientId": self.status_client, "privateKeyRef": private_key_ref, + "statusResource": self.status_resource + }]); + Ok(()) + } +} + #[derive(Deserialize, Serialize)] #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] #[serde(rename_all = "camelCase", deny_unknown_fields)] @@ -243,15 +349,12 @@ impl ExternalBreg { }); } if let Some(grant) = &self.task_grant { - let key = private_fixture(root, &grant.status_key_ref)?; - config["authentication"]["oidc"]["issuers"]["main"]["assertionIssuers"] - [&grant.assertion_client] = json!([grant.source_issuer]); - config["taskGrantStatus"] = json!([{ - "sourceIssuer": grant.source_issuer, "baseUrl": grant.status_url, - "tokenEndpoint": grant.token_endpoint, "clientAssertionAudience": issuer, - "clientId": grant.status_client, "privateKeyRef": store("external-task-status-key", &key)?, - "statusResource": grant.status_resource - }]); + grant.configure( + |key| store("external-task-status-key", key), + root, + issuer, + config, + )?; } Ok(()) } diff --git a/crates/registry-rstack-dev/src/plan.rs b/crates/registry-rstack-dev/src/plan.rs index f3bb726607..b8ea7566e4 100644 --- a/crates/registry-rstack-dev/src/plan.rs +++ b/crates/registry-rstack-dev/src/plan.rs @@ -360,6 +360,9 @@ pub(super) struct Plan { /// Explicit connections from a development BReg to external fixture services. #[serde(default, skip_serializing_if = "Option::is_none")] pub external_breg: Option, + /// One external task grant and its live status provider for a Scheduling fixture. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub external_scheduling: Option, /// The products to start, each with its project directory and token audience. List each product at most once. pub products: Vec, /// The audience that products a person calls from a page will share: an absolute URI of at most 256 characters, with no fragment or user information. Only BReg can be a member, by setting its `audience` to the same value, whether or not it checks task grants. Casework keeps its own audience, Messaging takes no person token, and Evidence cannot join yet. Declaring `personAudience` alone changes nothing at run time. @@ -392,6 +395,13 @@ pub(super) struct Plan { pub preview: Option, } +#[derive(Deserialize, Serialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub(super) struct ExternalScheduling { + pub task_grant: super::external_breg::TaskGrant, +} + /// A generic Node application and its configuration command. All artifact paths are relative to the supplied built root. #[derive(Deserialize, Serialize)] #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] @@ -1355,6 +1365,23 @@ impl Plan { "Set issuer to the exact external issuer and externalJwksUri to its key endpoint.", )?; } + if let Some(binding) = &self.external_scheduling { + let scheduling = self + .products + .iter() + .find(|entry| entry.product == Product::Scheduling); + require( + self.jwks_uri().is_some() && scheduling.is_some(), + "/externalScheduling", + "An external Scheduling task grant needs Scheduling and an external issuer.", + "Select Scheduling and set issuer and externalJwksUri to the fixture issuer and its key endpoint.", + )?; + binding.task_grant.validate_for_scheduling( + root, + self, + &scheduling.expect("validated Scheduling product").audience, + )?; + } require( (self.issuer != "run" || self.application.is_some() @@ -2027,7 +2054,7 @@ impl JourneyFile { } } -fn issuer_url(value: &str) -> bool { +pub(super) fn issuer_url(value: &str) -> bool { value.len() <= 512 && ParsedUrl::parse(value).is_ok_and(|url| { url.scheme() == "https" @@ -2329,6 +2356,96 @@ mod tests { } } + #[test] + fn managed_scheduling_requires_the_exact_external_grant_binding() { + let (root, mut plan) = plan(json!({"id": "read", "product": "breg", + "as": "operator", "method": "GET", "path": "/v1/records", "expect": {"status": 200}})); + fs::write(root.path().join("scheduling.yaml"), "{}").unwrap(); + fs::create_dir(root.path().join("fixture")).unwrap(); + crate::write_private( + &root.path().join("fixture/status-key"), + b"synthetic fixture credential", + ) + .unwrap(); + plan.products = serde_json::from_value(json!([{ + "product": "scheduling", "project": ".", "audience": "urn:example:journey:scheduling" + }])) + .unwrap(); + plan.people = serde_json::from_value(json!({"booker": { + "subject": "booker", "client": "task-agent", + "grants": {"scheduling": {"profile": "booker", "scopes": ["scheduling:write"]}} + }})) + .unwrap(); + plan.issuer = "http://127.0.0.1:41000".to_owned(); + plan.external_jwks_uri = Some("http://127.0.0.1:41000/oauth2/jwks".to_owned()); + let binding = json!({"taskGrant": { + "sourceIssuer": "https://casework.journey.example", + "assertionClient": "task-agent", + "statusUrl": "http://127.0.0.1:41001", + "tokenEndpoint": "http://127.0.0.1:41000/oauth2/token", + "statusClient": "scheduling-status", + "statusKeyRef": "secret:file/status-key", + "statusResource": "urn:example:journey:casework" + }}); + plan.external_scheduling = Some(serde_json::from_value(binding.clone()).unwrap()); + plan.validate(root.path()) + .expect("fixed external Scheduling grant"); + let mut runtime = json!({"authentication": {"oidc": {"issuers": {"main": { + "allowedClients": ["task-agent"], "issuer": plan.issuer + }}}}}); + plan.external_scheduling + .as_ref() + .unwrap() + .task_grant + .configure( + |_| Ok("secret:file/run-task-status-key".to_owned()), + &root.path().canonicalize().unwrap(), + &plan.issuer, + &mut runtime, + ) + .unwrap(); + assert_eq!( + runtime["authentication"]["oidc"]["issuers"]["main"]["assertionIssuers"], + json!({"task-agent": ["https://casework.journey.example"]}) + ); + assert_eq!( + runtime["taskGrantStatus"], + json!([{ + "sourceIssuer": "https://casework.journey.example", + "baseUrl": "http://127.0.0.1:41001", + "tokenEndpoint": "http://127.0.0.1:41000/oauth2/token", + "clientAssertionAudience": "http://127.0.0.1:41000", + "clientId": "scheduling-status", + "privateKeyRef": "secret:file/run-task-status-key", + "statusResource": "urn:example:journey:casework" + }]) + ); + + for (field, value) in [ + ("sourceIssuer", "http://127.0.0.1:41001"), + ("assertionClient", "another-agent"), + ("statusUrl", "http://127.0.0.1:41001/arbitrary"), + ("tokenEndpoint", "http://127.0.0.1:41002/oauth2/token"), + ("statusClient", "task-agent"), + ("statusKeyRef", "secret:file/missing"), + ("statusResource", "urn:example:journey:scheduling"), + ] { + let mut mutated = binding.clone(); + mutated["taskGrant"][field] = json!(value); + plan.external_scheduling = Some(serde_json::from_value(mutated).unwrap()); + assert_eq!( + plan.validate(root.path()).unwrap_err().field, + format!("/externalScheduling/taskGrant/{field}") + ); + } + plan.external_scheduling = Some(serde_json::from_value(binding).unwrap()); + plan.external_jwks_uri = Some("http://127.0.0.1:41002/oauth2/jwks".to_owned()); + assert_eq!( + plan.validate(root.path()).unwrap_err().field, + "/externalJwksUri" + ); + } + #[test] fn a_fixed_external_hook_may_use_the_managed_development_issuer() { let (root, mut plan) = plan(json!({"id": "read", "product": "breg", diff --git a/crates/registry-rstack-dev/src/products.rs b/crates/registry-rstack-dev/src/products.rs index bf6411e885..c9cb96da7a 100644 --- a/crates/registry-rstack-dev/src/products.rs +++ b/crates/registry-rstack-dev/src/products.rs @@ -1579,6 +1579,14 @@ impl<'a> ProductRunner<'a> { config["authentication"] = json!({"oidc": issuer_set(oidc)}); if product == Product::Scheduling { config["taskGrantStatus"] = json!("unchecked-final-fifteen-minutes"); + if let Some(external) = &self.input.plan.external_scheduling { + external.task_grant.configure( + |bytes| self.secret("scheduling-external-task-status-key", bytes), + &self.input.project, + &self.input.plan.issuer, + &mut config, + )?; + } config["retention"] = json!({}); } else { config["storage"] = json!({"type": "database"}); diff --git a/docs/site/src/content/docs/configure/run-a-project-with-rstack-dev.mdx b/docs/site/src/content/docs/configure/run-a-project-with-rstack-dev.mdx index b7389d5f30..5420601f5f 100644 --- a/docs/site/src/content/docs/configure/run-a-project-with-rstack-dev.mdx +++ b/docs/site/src/content/docs/configure/run-a-project-with-rstack-dev.mdx @@ -507,6 +507,23 @@ and check that the receiver verifies its signature and records the expected even crates/registry-rstack-dev/src/products.rs, prepare_breg_hooks; crates/registry-rstack-dev/src/external_breg.rs, Hook, hook_key. */} +## Attach a Scheduling task grant fixture + +For a development run with an external issuer, use `externalScheduling.taskGrant` to bind one +named Scheduling caller to a Casework assertion authority. Put the caller's `assertionClient` +in one Scheduling entry under `people` and use the exact Casework `sourceIssuer` from its grant. +Put the issuer's JWKS endpoint in `externalJwksUri` on the same numeric loopback origin as `issuer`. + +Set `statusUrl` to the Casework loopback origin and `tokenEndpoint` to the external issuer's token +endpoint. Set `statusClient` to its separate status reader, `statusKeyRef` to its owner-only key +under `fixture/` and `statusResource` to the reader's Casework resource. Run `rstack dev check` +before `rstack dev start`. Scheduling checks the grant's current status with Casework before +booking and refuses the operation if it cannot verify that status. + +{/* Evidence: crates/registry-rstack-dev/src/plan.rs, managed_scheduling_requires_the_exact_external_grant_binding; + crates/registry-rstack-dev/src/external_breg.rs, TaskGrant; + crates/registry-rstack-dev/src/products.rs, additional_config. */} + ## The managed PostgreSQL server The run starts PostgreSQL for BReg, Casework, Messaging, Scheduling, Documents, Coordinator and diff --git a/products/platform/config-formats.yaml b/products/platform/config-formats.yaml index 294353b88c..8e4b1681d4 100644 --- a/products/platform/config-formats.yaml +++ b/products/platform/config-formats.yaml @@ -870,7 +870,23 @@ formats: whenOmitted: closed - pointer: /preview/breg/post whenOmitted: closed - restrictingMembers: [/issuer, /application/client, /application/callbackPath, /products/*/audience, /people/*/roles] + - pointer: /externalScheduling + whenOmitted: closed + - pointer: /externalScheduling/taskGrant/assertionClient + whenOmitted: refused + - pointer: /externalScheduling/taskGrant/sourceIssuer + whenOmitted: refused + - pointer: /externalScheduling/taskGrant/statusUrl + whenOmitted: refused + - pointer: /externalScheduling/taskGrant/tokenEndpoint + whenOmitted: refused + - pointer: /externalScheduling/taskGrant/statusClient + whenOmitted: refused + - pointer: /externalScheduling/taskGrant/statusKeyRef + whenOmitted: refused + - pointer: /externalScheduling/taskGrant/statusResource + whenOmitted: refused + restrictingMembers: [/issuer, /application/client, /application/callbackPath, /products/*/audience, /people/*/roles, /externalScheduling/taskGrant/assertionClient, /externalScheduling/taskGrant/sourceIssuer, /externalScheduling/taskGrant/statusUrl, /externalScheduling/taskGrant/tokenEndpoint, /externalScheduling/taskGrant/statusClient, /externalScheduling/taskGrant/statusKeyRef, /externalScheduling/taskGrant/statusResource] - id: rstack/journeys product: rstack title: Registry Stack authored development journeys From f5374f08db59c6d4ad4a722815c874ca7b669b29 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 19:07:53 +0000 Subject: [PATCH 055/183] test(journeys): verify managed Scheduling appointment hooks Signed-off-by: Jeremi Joslin (cherry picked from commit 0e49253d0bd299711194d187f4be4e987a94af95) --- products/platform/journeys/lib.sh | 43 +++ products/platform/journeys/own-provider.sh | 259 ++++++++++++++---- .../journeys/projects/composed_fixtures.py | 75 +++++ products/platform/journeys/rstack-dev.sh | 27 +- .../platform/journeys/test_journey_tables.py | 107 +++++++- 5 files changed, 435 insertions(+), 76 deletions(-) diff --git a/products/platform/journeys/lib.sh b/products/platform/journeys/lib.sh index 0cdf66ad8a..a96c13d074 100644 --- a/products/platform/journeys/lib.sh +++ b/products/platform/journeys/lib.sh @@ -1772,6 +1772,49 @@ journey_request_contract() { done } +# The managed sink authenticates the delivery. Correlate its captured envelope +# and signing headers to the operation, without accepting forwarded credentials. +signed_hook_matches() { + local expected=$1 + shift + jq -e --argjson expected "$expected" 'any(.[]; + . as $capture | (.body | fromjson?) as $event | + $event.type == $expected.type and $event.data == $expected.data and + ($expected.source == null or $event.source == $expected.source) and + ($event.id | type == "string" and length > 0) and + any($capture.headers[]; .name == "webhook-id" and .value == $event.id) and + any($capture.headers[]; .name == "webhook-timestamp" and (.value | test("^[0-9]+$"))) and + any($capture.headers[]; .name == "webhook-signature" and (.value | startswith("v1,"))) and + all($capture.headers[]; .name != "authorization" and .name != "cookie" and + .name != "registry-source-authorization" and .name != "proxy-authorization"))' "$@" >/dev/null +} + +signed_hook_received() { + curl --silent --fail --max-time 3 "$1" | signed_hook_matches "$2" +} + +# Confirm one Scheduling appointment with the caller's already admitted task +# grant. The caller supplies the hold request and chooses how to observe the +# resulting delivery. The grant reaches HTTP by variable name. +journey_scheduling_appointment() { + local origin=$1 work=$2 request=$3 bearer=$4 appointment_var=$5 + local _js_hold='' confirm=$work/appt-request.json + journey_http hook --expect-status 201 --bearer "$bearer" \ + --header 'Content-Type: application/json' \ + --header 'Idempotency-Key: journey-comp-hold-create' \ + --data-file "$request" --capture .holdId _js_hold \ + POST "$origin/v1/holds" || + journey_harness_failure "Scheduling hold creation failed (HTTP $JOURNEY_HTTP_STATUS, $JOURNEY_HTTP_PROBLEM_CODE)" + jq -cn --arg hold "$_js_hold" '{hold:$hold,admission:null}' >"$confirm" || + journey_harness_failure "cannot assemble the Scheduling confirmation request" + journey_http hook --expect-status 201 --bearer "$bearer" \ + --header 'Content-Type: application/json' \ + --header 'Idempotency-Key: journey-comp-appt-confirm' \ + --data-file "$confirm" --capture .appointmentId "$appointment_var" \ + POST "$origin/v1/appointments" || + journey_harness_failure "Scheduling appointment confirmation failed (HTTP $JOURNEY_HTTP_STATUS, $JOURNEY_HTTP_PROBLEM_CODE)" +} + # journey_http STEP [--bearer VAR] [--header 'Name: value']... [--form K=V]... # [--form-secret K=SECRET]... [--data-file FILE] [--cookie-jar NAME] # [--location] [--expect-status NNN] [--capture FILTER VAR]... [--capture-secret FILTER VAR]... diff --git a/products/platform/journeys/own-provider.sh b/products/platform/journeys/own-provider.sh index e2c06721cc..4c57637193 100755 --- a/products/platform/journeys/own-provider.sh +++ b/products/platform/journeys/own-provider.sh @@ -114,7 +114,8 @@ select_journey_init_args() { INIT_JOURNEY_NAME=own-provider INIT_DEFAULT_EXPECTED=$JOURNEY_LIB_DIR/expected-failures.yaml select_journey_init_args "$@" -journey_init "$INIT_JOURNEY_NAME" --default-expected "$INIT_DEFAULT_EXPECTED" --value-option issuer -- "$@" +journey_init "$INIT_JOURNEY_NAME" --default-expected "$INIT_DEFAULT_EXPECTED" \ + --value-option issuer --value-option scheduling-runtime -- "$@" REALM=registry-journey POSTGRES_IMAGE=postgres:18.7@sha256:2ea8630df176ad090ec92136dee850397c5af8781e4bcf2e4162593691c61bbc @@ -141,6 +142,17 @@ keycloak | thunderid) ;; ;; esac +journey_option_value scheduling-runtime SCHEDULING_RUNTIME +SCHEDULING_RUNTIME=${SCHEDULING_RUNTIME:-standalone} +case "$SCHEDULING_RUNTIME" in +standalone) ;; +managed) + [[ "$ISSUER_KIND" == thunderid && $JOURNEY_KEEP -eq 0 && "${JOURNEY_PRODUCTS[*]}" == scheduling ]] || + journey_usage_error "--scheduling-runtime managed requires --issuer thunderid --product scheduling and no --keep" + ;; +*) journey_usage_error "--scheduling-runtime $SCHEDULING_RUNTIME: choose standalone or managed" ;; +esac + KEYCLOAK_IMAGE='' THUNDERID_IMAGE='' JOURNEY_ISSUER_BIN='' @@ -406,6 +418,60 @@ stop_thunderid_sessions() { } journey_at_cleanup stop_thunderid_sessions +COMPOSED_MANAGED_RUN='' +COMPOSED_MANAGED_ROOT=$SECRETS/scheduling-managed + +composed_managed_dev() { + RSTACK_DEV_STATE_DIR="$COMPOSED_MANAGED_ROOT/state" \ + RSTACK_SCHEDULING_BIN="$SERVER_BIN" RSTACK_SCHEDULINGCTL_BIN="$TOOL_BIN" \ + "$COMPOSED_RSTACK_BIN" --install-root "$COMPOSED_MANAGED_ROOT/install" --format json dev "$@" +} + +stop_composed_managed_scheduling() { + [[ -n "$COMPOSED_MANAGED_RUN" ]] || return 0 + composed_managed_dev stop "$COMPOSED_MANAGED_RUN" >/dev/null || return 1 + COMPOSED_MANAGED_RUN='' +} + +cleanup_composed_managed_scheduling() { + stop_composed_managed_scheduling || return 1 + [[ ! -d "$COMPOSED_MANAGED_ROOT" ]] || + python3 -c 'import shutil, sys; shutil.rmtree(sys.argv[1])' "$COMPOSED_MANAGED_ROOT" +} +journey_at_cleanup cleanup_composed_managed_scheduling + +composed_managed_start() ( + unset RSTACK_DEV_DATABASE_CA + composed_managed_dev start "$@" +) + +start_composed_managed_scheduling() { + local _cms_project=$1 _cms_report=$2 _cms_url='' + IFS= read -r _cms_url <"$ADMIN_URL_FILE" || [[ -n "$_cms_url" ]] || + journey_harness_failure "cannot read the disposable PostgreSQL admin URL" + RSTACK_DEV_DATABASE_URL="$_cms_url?sslmode=disable" \ + journey_step hook --timeout 120 --typed "rstack dev start $_cms_project" -- \ + composed_managed_start "$_cms_project" || + journey_harness_failure "managed Scheduling did not start; see $JOURNEY_STEP_STDERR" + COMPOSED_MANAGED_RUN=$(jq -er '.run_id | strings | select(test("^[0-9a-f]{32}$"))' "$JOURNEY_STEP_STDOUT") || + journey_harness_failure "managed Scheduling start report has no run ID" + copy_file "$JOURNEY_STEP_STDOUT" "$_cms_report" +} + +composed_scheduling_url() { + jq -er '.products.scheduling | select(test("^http://127[.]0[.]0[.]1:[0-9]+$"))' "$1" +} + +assert_composed_scheduling_authority_refused() { + local origin=$1 request=$2 key=$3 + journey_http hook --expect-status 401 --bearer exchanged_token \ + --header 'Content-Type: application/json' --header "Idempotency-Key: $key" \ + --data-file "$request" POST "$origin/v1/holds" || + journey_harness_failure "managed Scheduling did not refuse the exchanged bearer with HTTP 401" + jq -e '.code == "authentication.refused" and .failedCheck == "token-assertion-issuer"' "$JOURNEY_STEP_STDOUT" >/dev/null || + journey_harness_failure "managed Scheduling did not refuse at token-assertion-issuer" +} + # read_secret NAME VAR: the value of a generated secret into VAR. read_secret() { local _kc_path @@ -2339,6 +2405,7 @@ composed_scheduling_hook() { local breg_final=$comp/breg-final breg_final_rt=$comp/breg-final-runtime.yaml breg_final_build=$comp/breg-final-build local sched_proj=$comp/sched-project sched_pkg=$comp/sched-package sched_rt=$comp/sched-runtime.yaml local task_conn=$comp/task-connection.json receipt=$comp/scheduling-hook.json + local managed_report=$comp/managed-scheduling.json bound_plan=$comp/managed-dev-plan.json local day start_time local breg_url cw_url sched_url comp_hook_out='' comp_cw_out='' # shellcheck disable=SC2034 # journey_process_log sets comp_cw_err while refreshing comp_cw_out @@ -2547,21 +2614,37 @@ JSON # 5) Build, package, provision & apply composed Scheduling with appointment-observer hook. day=$(python3 -c 'from datetime import datetime, timedelta, timezone; print((datetime.now(timezone.utc) + timedelta(days=2)).strftime("%Y-%m-%d"))') start_time="${day}T10:00:00Z" + if [[ "$SCHEDULING_RUNTIME" == managed ]]; then + mkdir -m 700 -- "$COMPOSED_MANAGED_ROOT" "$COMPOSED_MANAGED_ROOT/state" "$COMPOSED_MANAGED_ROOT/install" + sched_proj=$COMPOSED_MANAGED_ROOT/project + journey_step hook -- "$TOOL_BIN" init --template standalone-exact-time "$COMPOSED_MANAGED_ROOT/starter" || + journey_harness_failure "cannot initialize the managed Scheduling fixture" + mkdir -m 700 -- "$sched_proj" + copy_file "$COMPOSED_MANAGED_ROOT/starter/runtime.example.yaml" "$sched_proj/runtime.example.yaml" + fi python3 "$PROJECTS_DIR/composed_fixtures.py" scheduling-project "$sched_proj" --day "$day" || journey_harness_failure "cannot write composed Scheduling project" - journey_step hook -- "$TOOL_BIN" package --output "$sched_pkg" "$sched_proj" || - journey_harness_failure "composed Scheduling package failed; see $JOURNEY_STEP_STDERR" - python3 "$PROJECTS_DIR/composed_fixtures.py" scheduling-runtime "$sched_rt" \ - --port "$sched_port" --metrics-port "$sched_metrics_port" --secrets "$SECRETS" \ - --package "$sched_pkg" --audit "$comp/sched-audit.ndjson" \ - --issuer "$comp_tid_issuer" --casework-port "$cw_port" --hook-port "$hook_port" || - journey_harness_failure "cannot write composed Scheduling runtime" - journey_step hook -- "$TOOL_BIN" provision --runtime-config "$sched_rt" --admin-url-file "$ADMIN_URL_FILE" --posture development || - journey_harness_failure "composed Scheduling provision failed; see $JOURNEY_STEP_STDERR" - journey_step hook -- "$TOOL_BIN" apply --runtime-config "$sched_rt" --posture development --format json || - journey_harness_failure "composed Scheduling apply failed; see $JOURNEY_STEP_STDERR" - journey_step hook -- "$TOOL_BIN" records apply --runtime-config "$sched_rt" "$sched_proj/records.yaml" --posture development --format json || - journey_harness_failure "composed Scheduling records apply failed; see $JOURNEY_STEP_STDERR" + if [[ "$SCHEDULING_RUNTIME" == managed ]]; then + python3 "$PROJECTS_DIR/composed_fixtures.py" scheduling-managed-plan "$sched_proj" \ + --issuer "$comp_tid_issuer" --jwks "$comp_tid_issuer/oauth2/jwks" \ + --casework-port "$cw_port" --agent-subject "$agent_sub" --status-key "$SECRETS/comp-sched-status-key" || + journey_harness_failure "cannot write the managed Scheduling plan" + copy_file "$sched_proj/dev.yaml" "$bound_plan" + else + journey_step hook -- "$TOOL_BIN" package --output "$sched_pkg" "$sched_proj" || + journey_harness_failure "composed Scheduling package failed; see $JOURNEY_STEP_STDERR" + python3 "$PROJECTS_DIR/composed_fixtures.py" scheduling-runtime "$sched_rt" \ + --port "$sched_port" --metrics-port "$sched_metrics_port" --secrets "$SECRETS" \ + --package "$sched_pkg" --audit "$comp/sched-audit.ndjson" \ + --issuer "$comp_tid_issuer" --casework-port "$cw_port" --hook-port "$hook_port" || + journey_harness_failure "cannot write composed Scheduling runtime" + journey_step hook -- "$TOOL_BIN" provision --runtime-config "$sched_rt" --admin-url-file "$ADMIN_URL_FILE" --posture development || + journey_harness_failure "composed Scheduling provision failed; see $JOURNEY_STEP_STDERR" + journey_step hook -- "$TOOL_BIN" apply --runtime-config "$sched_rt" --posture development --format json || + journey_harness_failure "composed Scheduling apply failed; see $JOURNEY_STEP_STDERR" + journey_step hook -- "$TOOL_BIN" records apply --runtime-config "$sched_rt" "$sched_proj/records.yaml" --posture development --format json || + journey_harness_failure "composed Scheduling records apply failed; see $JOURNEY_STEP_STDERR" + fi python3 "$PROJECTS_DIR/composed_fixtures.py" task-connection "$task_conn" \ --casework-port "$cw_port" --issuer "$comp_tid_issuer" --secrets "$SECRETS" || @@ -2572,13 +2655,15 @@ JSON cw_url=http://127.0.0.1:$cw_port sched_url=http://127.0.0.1:$sched_port - journey_start hook comp-hook-receiver -- python3 "$PROJECTS_DIR/hook-receiver.py" \ - "$hook_port" /scheduling-events appointment-observer "$SECRETS/comp-sched-hook-hmac" "$receipt" || - journey_harness_failure "composed Scheduling hook receiver failed to start" - comp_hook_out=$JOURNEY_STEP_STDOUT - journey_ready hook comp-hook-receiver --timeout 30 -- \ - curl --silent --show-error --fail --output /dev/null "http://127.0.0.1:$hook_port/ready" || - journey_harness_failure "composed Scheduling hook receiver did not answer /ready" + if [[ "$SCHEDULING_RUNTIME" == standalone ]]; then + journey_start hook comp-hook-receiver -- python3 "$PROJECTS_DIR/hook-receiver.py" \ + "$hook_port" /scheduling-events appointment-observer "$SECRETS/comp-sched-hook-hmac" "$receipt" || + journey_harness_failure "composed Scheduling hook receiver failed to start" + comp_hook_out=$JOURNEY_STEP_STDOUT + journey_ready hook comp-hook-receiver --timeout 30 -- \ + curl --silent --show-error --fail --output /dev/null "http://127.0.0.1:$hook_port/ready" || + journey_harness_failure "composed Scheduling hook receiver did not answer /ready" + fi journey_start hook comp-breg --settle 2 -- "$breg_bin" --posture development --runtime-config "$breg_final_rt" || journey_harness_failure "composed BReg failed to start" @@ -2597,11 +2682,13 @@ JSON jq -e '[.keys[]? | select(.kid == "journey-task-authority")] | length == 1' >/dev/null || journey_harness_failure "composed Casework did not publish journey-task-authority on /.well-known/jwks.json" - journey_start hook comp-scheduling --settle 2 -- "$SERVER_BIN" --posture development --runtime-config "$sched_rt" serve || - journey_harness_failure "composed Scheduling failed to start" - journey_ready hook comp-scheduling --timeout 90 -- \ - curl --silent --show-error --fail --output /dev/null "$sched_url/ready" || - journey_harness_failure "composed Scheduling did not become ready" + if [[ "$SCHEDULING_RUNTIME" == standalone ]]; then + journey_start hook comp-scheduling --settle 2 -- "$SERVER_BIN" --posture development --runtime-config "$sched_rt" serve || + journey_harness_failure "composed Scheduling failed to start" + journey_ready hook comp-scheduling --timeout 90 -- \ + curl --silent --show-error --fail --output /dev/null "$sched_url/ready" || + journey_harness_failure "composed Scheduling did not become ready" + fi # 7) Bootstrap Casework directory. # shellcheck disable=SC2034 # read by name through journey_http --bearer @@ -2767,6 +2854,15 @@ JSON journey_harness_failure "exchanged Scheduling task grant token lacks scalar Scheduling audience" # 13) Negative check: ordinary task-agent token without a task grant is refused by Scheduling POST /v1/holds. + if [[ "$SCHEDULING_RUNTIME" == managed ]]; then + # The same real exchanged bearer must be refused without an explicit + # assertion-authority binding. Use a separate stopped/restarted run. + jq 'del(.externalScheduling)' "$bound_plan" >"$sched_proj/dev.yaml" || + journey_harness_failure "cannot assemble the unbound managed Scheduling control" + start_composed_managed_scheduling "$sched_proj" "$comp/unbound-scheduling.json" + sched_url=$(composed_scheduling_url "$comp/unbound-scheduling.json") || + journey_harness_failure "the unbound Scheduling run has no loopback address" + fi thunderid_fetch_token "$comp_tid_root" "$comp_reg" task-agent ordinary_agent_token "urn:example:journey:scheduling" token_has_scalar_audience ordinary_agent_token "urn:example:journey:scheduling" || journey_harness_failure "composed ordinary task-agent token lacks string scalar Scheduling audience" @@ -2777,49 +2873,102 @@ JSON jq -cn --arg start "$start_time" --arg app "$app_id" --arg duplicate_key "cross-product-$app_id" --argjson rev "$sched_rev" \ '{offering:"application-review",start:$start,party:{recipients:1,attendees:1},channel:"assisted",duplicateKey:$duplicate_key,policyRevision:$rev,windowRevision:null,capabilities:[],prerequisites:[],externalReferences:[{product:"breg",recordType:"application",identifier:$app}]}' \ >"$comp/hold-request.json" + if [[ "$SCHEDULING_RUNTIME" == managed ]]; then + assert_composed_scheduling_authority_refused "$sched_url" "$comp/hold-request.json" journey-comp-unbound-authority + stop_composed_managed_scheduling || journey_harness_failure "cannot stop the unbound managed Scheduling control" + + # The genuine exchanged token also fails when the same named client is + # bound to a different authority. Only this disposable plan is varied. + jq '.externalScheduling.taskGrant.sourceIssuer = "https://unrelated.casework.journey.example"' \ + "$bound_plan" >"$sched_proj/dev.yaml" || + journey_harness_failure "cannot assemble the wrong-authority managed Scheduling control" + start_composed_managed_scheduling "$sched_proj" "$comp/wrong-authority-scheduling.json" + sched_url=$(composed_scheduling_url "$comp/wrong-authority-scheduling.json") || + journey_harness_failure "the wrong-authority Scheduling run has no loopback address" + assert_composed_scheduling_authority_refused "$sched_url" "$comp/hold-request.json" journey-comp-wrong-authority + stop_composed_managed_scheduling || journey_harness_failure "cannot stop the wrong-authority managed Scheduling control" + + copy_file "$bound_plan" "$sched_proj/dev.yaml" + start_composed_managed_scheduling "$sched_proj" "$managed_report" + sched_url=$(composed_scheduling_url "$managed_report") || + journey_harness_failure "the managed Scheduling run has no loopback address" + local managed_config + managed_config=$(jq -er '.runtimeConfigs.scheduling' "$managed_report") || + journey_harness_failure "the managed Scheduling run did not report its runtime configuration" + jq -e --slurpfile plan "$bound_plan" ' + $plan[0].externalScheduling.taskGrant as $binding | + .authentication.oidc.issuers.main as $issuer | + $issuer.issuer == $plan[0].issuer and $issuer.audience == $plan[0].products[0].audience and + $issuer.allowedClients == [$binding.assertionClient] and + $issuer.assertionIssuers == {($binding.assertionClient): [$binding.sourceIssuer]} and + (.taskGrantStatus | type == "array" and length == 1) and + (.taskGrantStatus[0] | .sourceIssuer == $binding.sourceIssuer and .baseUrl == $binding.statusUrl and + .tokenEndpoint == $binding.tokenEndpoint and .clientAssertionAudience == $issuer.issuer and + .clientId == $binding.statusClient and .statusResource == $binding.statusResource and + (.privateKeyRef | startswith("secret:file/")))' "$managed_config" >"$comp/managed-status-binding.json" || + journey_harness_failure "managed Scheduling did not project the exact live Casework status binding" + journey_http hook --bearer ordinary_agent_token GET "$sched_url/v1/scheduling" || + journey_harness_failure "the managed Scheduling policy metadata request failed" + jq -e --argjson revision "$sched_rev" '.policyRevision == $revision' "$JOURNEY_STEP_STDOUT" >/dev/null || + journey_harness_failure "the managed Scheduling run did not load the same booking policy revision" + fi journey_http hook --expect-status 403 --bearer ordinary_agent_token \ --header 'Content-Type: application/json' \ --header 'Idempotency-Key: journey-comp-hold-no-grant' \ --data-file "$comp/hold-request.json" \ POST "$sched_url/v1/holds" || journey_harness_failure "composed Scheduling did not refuse grantless hold with HTTP 403 (got HTTP $JOURNEY_HTTP_STATUS)" + [[ "$JOURNEY_HTTP_PROBLEM_CODE" == operation.not-authorized ]] || + journey_harness_failure "composed Scheduling returned an unexpected grantless hold problem code" + if [[ "$SCHEDULING_RUNTIME" == managed ]]; then + jq -e '.failedCheck == "task-grant-missing"' "$JOURNEY_STEP_STDOUT" >/dev/null || + journey_harness_failure "managed Scheduling grantless hold did not refuse at task-grant-missing" + fi # 14) Positive check: create hold and confirm appointment with the exchanged grant, # then verify signed Standard Webhooks appointment-observer delivery. - local hold_id='' appt_id='' - journey_http hook --expect-status 201 --bearer exchanged_token \ - --header 'Content-Type: application/json' \ - --header 'Idempotency-Key: journey-comp-hold-create' \ - --data-file "$comp/hold-request.json" \ - --capture .holdId hold_id \ - POST "$sched_url/v1/holds" || - journey_harness_failure "composed Scheduling hold creation failed (HTTP $JOURNEY_HTTP_STATUS, $JOURNEY_HTTP_PROBLEM_CODE)" - jq -cn --arg hold "$hold_id" '{hold:$hold,admission:null}' >"$comp/appt-request.json" - journey_http hook --expect-status 201 --bearer exchanged_token \ - --header 'Content-Type: application/json' \ - --header 'Idempotency-Key: journey-comp-appt-confirm' \ - --data-file "$comp/appt-request.json" \ - --capture .appointmentId appt_id \ - POST "$sched_url/v1/appointments" || - journey_harness_failure "composed Scheduling appointment confirmation failed (HTTP $JOURNEY_HTTP_STATUS, $JOURNEY_HTTP_PROBLEM_CODE)" + local appt_id='' + journey_scheduling_appointment "$sched_url" "$comp" "$comp/hold-request.json" exchanged_token appt_id [[ -n "$appt_id" ]] || journey_harness_failure "composed Scheduling appointment response carried no appointmentId" - journey_ready hook comp-hook-receiver --timeout 45 -- test -s "$receipt" || - journey_harness_failure "composed Scheduling hook receiver did not accept the signed appointment-observer hook" - # shellcheck disable=SC2016 # jq binds its own variables - journey_step hook -- jq -e --arg appt "$appt_id" \ - '.type == "appointment-observer" and .data.appointmentId == $appt and .data.state == "confirmed"' \ - "$receipt" || - journey_harness_failure "composed Scheduling signed hook did not carry appointment-observer for appointment $appt_id" + if [[ "$SCHEDULING_RUNTIME" == managed ]]; then + local sink expected + sink=$(jq -er '.hookSinks.scheduling.receivedUrl | select(test("^http://127[.]0[.]0[.]1:[0-9]+/received$"))' "$managed_report") || + journey_harness_failure "managed Scheduling did not report a loopback hook sink" + expected=$(jq -cn --arg id "$appt_id" '{type:"appointment-observer", source:"urn:registrystack:scheduling:journey-composed-scheduling",data:{appointmentId:$id,state:"confirmed"}}') + journey_poll 45 -- signed_hook_received "$sink" "$expected" || + journey_harness_failure "the managed Scheduling hook sink did not receive the signed appointment" + journey_http hook GET "$sink" || journey_harness_failure "the managed Scheduling hook sink did not answer" + signed_hook_matches "$expected" "$JOURNEY_STEP_STDOUT" || + journey_harness_failure "the managed Scheduling hook receipt does not match the confirmed appointment" + # A subsequent write with the same issued bearer needs a fresh status + # result. Stop our disposable Casework after proving the appointment. + journey_stop hook comp-casework || journey_harness_failure "composed Casework ignored SIGTERM" + journey_http hook --expect-status 503 --bearer exchanged_token \ + --header 'Content-Type: application/json' --header 'Idempotency-Key: journey-comp-status-unavailable' \ + --data-file "$comp/hold-request.json" POST "$sched_url/v1/holds" || + journey_harness_failure "managed Scheduling returned HTTP $JOURNEY_HTTP_STATUS when live status was unavailable" + [[ "$JOURNEY_HTTP_PROBLEM_CODE" == service.unavailable ]] || + journey_harness_failure "managed Scheduling did not report service.unavailable for the stopped status authority" + stop_composed_managed_scheduling || journey_harness_failure "managed Scheduling did not stop" + else + journey_ready hook comp-hook-receiver --timeout 45 -- test -s "$receipt" || + journey_harness_failure "composed Scheduling hook receiver did not accept the signed appointment-observer hook" + # shellcheck disable=SC2016 # jq binds its own variables + journey_step hook -- jq -e --arg appt "$appt_id" \ + '.type == "appointment-observer" and .data.appointmentId == $appt and .data.state == "confirmed"' \ + "$receipt" || + journey_harness_failure "composed Scheduling signed hook did not carry appointment-observer for appointment $appt_id" + journey_stop hook comp-scheduling || journey_harness_failure "composed Scheduling ignored SIGTERM" + journey_stop hook comp-hook-receiver || journey_harness_failure "composed Scheduling hook receiver ignored SIGTERM" + journey_step hook -- assert_signed_hook_acceptance "$comp_hook_out" /scheduling-events appointment-observer || + journey_harness_failure "composed Scheduling signed hook acceptance record did not confirm HMAC receiver authority without inbound credential headers" + journey_stop hook comp-casework || journey_harness_failure "composed Casework ignored SIGTERM" + fi # 15) Stop composed processes and composed ThunderID session cleanly, then # restore the outer standalone session variables. - journey_stop hook comp-scheduling || journey_harness_failure "composed Scheduling ignored SIGTERM" - journey_stop hook comp-casework || journey_harness_failure "composed Casework ignored SIGTERM" journey_stop hook comp-breg || journey_harness_failure "composed BReg ignored SIGTERM" - journey_stop hook comp-hook-receiver || journey_harness_failure "composed Scheduling hook receiver ignored SIGTERM" - journey_step hook -- assert_signed_hook_acceptance "$comp_hook_out" /scheduling-events appointment-observer || - journey_harness_failure "composed Scheduling signed hook acceptance record did not confirm HMAC receiver authority without inbound credential headers" stop_thunderid_session "$comp_tid_root" || journey_harness_failure "cannot stop composed ThunderID session" TID_ROOT=$saved_tid_root @@ -2982,7 +3131,9 @@ if [[ ${#PRIMARY[@]} -gt 0 ]]; then fi done fi + [[ "$SCHEDULING_RUNTIME" != managed ]] || BIN_OPTS+=(--package registry-rstack) journey_resolve_binaries ${BIN_OPTS[@]+"${BIN_OPTS[@]}"} "${PRIMARY[@]}" + [[ "$SCHEDULING_RUNTIME" != managed ]] || journey_bin rstack COMPOSED_RSTACK_BIN if [[ "$ISSUER_KIND" == thunderid && $NEEDS_ISSUER -eq 1 ]]; then journey_resolve_example registry-thunderid-tooling session journey-issuer JOURNEY_ISSUER_BIN fi diff --git a/products/platform/journeys/projects/composed_fixtures.py b/products/platform/journeys/projects/composed_fixtures.py index 01889f2300..5e1ab947c2 100644 --- a/products/platform/journeys/projects/composed_fixtures.py +++ b/products/platform/journeys/projects/composed_fixtures.py @@ -7,7 +7,10 @@ import hashlib import json import os +import shutil +import stat from pathlib import Path +from urllib.parse import urlsplit SOURCE = "journey-source" AUTHORITY = "https://casework.journey.example" @@ -740,6 +743,69 @@ def cmd_scheduling_project(args: argparse.Namespace) -> None: ) +def cmd_scheduling_managed_plan(args: argparse.Namespace) -> None: + root = Path(args.directory) + issuer = urlsplit(args.issuer) + jwks = urlsplit(args.jwks) + if (issuer.scheme != "http" or issuer.hostname != "127.0.0.1" or not issuer.port + or issuer.path or issuer.query or issuer.fragment or issuer.username + or (jwks.scheme, jwks.netloc) != (issuer.scheme, issuer.netloc) + or not jwks.path or jwks.query or jwks.fragment): + raise SystemExit("managed Scheduling requires the exact numeric loopback issuer and its same-origin JWKS") + + example = root / "runtime.example.yaml" + example_source = example.read_text(encoding="utf-8") + empty_destinations = "\ndestinations: {}\n" + if example_source.count(empty_destinations) != 1: + raise SystemExit("managed Scheduling needs the starter's empty runtime destinations") + + fixture = root / "fixture" + key_name = "scheduling-status.jwk" + with os.fdopen(os.open(args.status_key, os.O_RDONLY | os.O_NOFOLLOW), "rb") as source: + metadata = os.fstat(source.fileno()) + if not stat.S_ISREG(metadata.st_mode) or metadata.st_uid != os.getuid() or metadata.st_mode & 0o077: + raise SystemExit("managed Scheduling needs an owner-only fixture status key") + fixture.mkdir(mode=0o700) + fd = os.open(fixture / key_name, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) + with os.fdopen(fd, "wb") as destination: + shutil.copyfileobj(source, destination) + + example.write_text(example_source.replace(empty_destinations, """ +destinations: + hooks: + appointment-events: + url: http://127.0.0.1:1/events + hmacSha256KeyRef: secret:file/unused-example-hook-key + attemptTimeoutMilliseconds: 2000 + maximumAttempts: 5 +"""), encoding="utf-8") + write_json(root / "dev-journeys.yaml", { + "apiVersion": "id.registrystack.org/formats/rstack/journeys/v1alpha1", + "kind": "RStackJourneys", "journeys": [], + }) + write_json(root / "dev.yaml", { + "apiVersion": "id.registrystack.org/formats/rstack/dev/v1alpha1", + "kind": "RStackDev", + "issuer": args.issuer, + "externalJwksUri": args.jwks, + "products": [{"product": "scheduling", "project": ".", "audience": SCHEDULING_RESOURCE}], + "people": {"task-agent": { + "subject": args.agent_subject, "client": "task-agent", + "grants": {"scheduling": {"profile": "reader", "scopes": ["scheduling:read"]}}, + }}, + "journeyFile": "dev-journeys.yaml", + "externalScheduling": {"taskGrant": { + "sourceIssuer": AUTHORITY, + "assertionClient": "task-agent", + "statusUrl": f"http://127.0.0.1:{args.casework_port}", + "tokenEndpoint": f"{args.issuer}/oauth2/token", + "statusClient": "scheduling-status", + "statusKeyRef": f"secret:file/{key_name}", + "statusResource": CASEWORK_RESOURCE, + }}, + }) + + def cmd_scheduling_runtime(args: argparse.Namespace) -> None: runtime = { "apiVersion": "id.registrystack.org/formats/scheduling/runtime/v1alpha1", @@ -885,6 +951,15 @@ def main() -> None: p.add_argument("--day", required=True) p.set_defaults(func=cmd_scheduling_project) + p = sub.add_parser("scheduling-managed-plan") + p.add_argument("directory") + p.add_argument("--issuer", required=True) + p.add_argument("--jwks", required=True) + p.add_argument("--casework-port", type=int, required=True) + p.add_argument("--agent-subject", required=True) + p.add_argument("--status-key", required=True) + p.set_defaults(func=cmd_scheduling_managed_plan) + p = sub.add_parser("scheduling-runtime") p.add_argument("output") p.add_argument("--port", type=int, required=True) diff --git a/products/platform/journeys/rstack-dev.sh b/products/platform/journeys/rstack-dev.sh index 9a98926c89..499f8f4481 100755 --- a/products/platform/journeys/rstack-dev.sh +++ b/products/platform/journeys/rstack-dev.sh @@ -637,6 +637,12 @@ walk_product() { documents_ready_hook "$work" "$url" token documents_receipt journey_pass hook ;; + scheduling) + # The named reader has catalogue access. Booking needs an exchanged task + # grant and a trusted assertion issuer binding on the managed runtime. + printf '%s\n' 'Scheduling appointment observer needs a verified task grant and its assertion issuer binding.' + journey_unexercised hook + ;; *) journey_unexercised hook ;; esac @@ -794,27 +800,6 @@ hook_received() { curl --silent --fail --max-time 3 "$1" | breg_hook_matches "$2" } -# The managed sink authenticates the delivery. Correlate its captured envelope -# and signing headers to the operation, without accepting forwarded credentials. -signed_hook_matches() { - local expected=$1 - shift - jq -e --argjson expected "$expected" 'any(.[]; - . as $capture | (.body | fromjson?) as $event | - $event.type == $expected.type and $event.data == $expected.data and - ($expected.source == null or $event.source == $expected.source) and - ($event.id | type == "string" and length > 0) and - any($capture.headers[]; .name == "webhook-id" and .value == $event.id) and - any($capture.headers[]; .name == "webhook-timestamp" and (.value | test("^[0-9]+$"))) and - any($capture.headers[]; .name == "webhook-signature" and (.value | startswith("v1,"))) and - all($capture.headers[]; .name != "authorization" and .name != "cookie" and - .name != "registry-source-authorization" and .name != "proxy-authorization"))' "$@" >/dev/null -} - -signed_hook_received() { - curl --silent --fail --max-time 3 "$1" | signed_hook_matches "$2" -} - managed_hook_url() { local product=$1 value value=$(jq -er --arg product "$product" '.hookSinks[$product].receivedUrl | strings | select(length > 0)' "$START_FILE") || diff --git a/products/platform/journeys/test_journey_tables.py b/products/platform/journeys/test_journey_tables.py index 70c097f4f6..e289fc43a9 100644 --- a/products/platform/journeys/test_journey_tables.py +++ b/products/platform/journeys/test_journey_tables.py @@ -186,6 +186,59 @@ def test_scheduling_rejects_missing_proof_even_when_stop_passes(self): self.assertIn(diagnostic, result.stdout + result.stderr) self.assertEqual("cell ended" in result.stdout, code == 0) + def test_book_and_confirm_use_the_same_named_grant(self): + driver = r""" +source "$1/lib.sh" +scratch=$2 mode=$3 +appointment='' +printf '%s\n' '{"offering":"application-review"}' >"$scratch/hold-request.json" +journey_harness_failure() { printf '%s\n' "$1" >&2; exit 3; } +journey_http() { + [[ "$1 $2 $3 $4 $5" == 'hook --expect-status 201 --bearer approved_booking' ]] + local request_file capture + while [[ $# -gt 2 ]]; do + case "$1" in + --data-file) request_file=$2; shift 2 ;; + --capture) capture=$3; shift 3 ;; + *) shift ;; + esac + done + [[ "$1" == POST ]] + case "$2" in + http://127.0.0.1:49192/v1/holds) + [[ "$request_file" == "$scratch/hold-request.json" ]] + printf '%s\n' 'hold requested' + if [[ "$mode" == refuse ]]; then + JOURNEY_HTTP_STATUS=403 JOURNEY_HTTP_PROBLEM_CODE=operation.not-authorized + return 1 + fi + printf -v "$capture" '%s' held-id + ;; + http://127.0.0.1:49192/v1/appointments) + jq -e '. == {hold:"held-id",admission:null}' "$request_file" >/dev/null + printf '%s\n' 'appointment confirmed' + printf -v "$capture" '%s' confirmed-id + ;; + *) return 1 ;; + esac +} +journey_scheduling_appointment http://127.0.0.1:49192 "$scratch" "$scratch/hold-request.json" approved_booking appointment +printf '%s\n' "$appointment" +""" + for mode, code, steps in ( + ("approve", 0, ["hold requested", "appointment confirmed", "confirmed-id"]), + ("refuse", 3, ["hold requested"]), + ): + with self.subTest(mode=mode), tempfile.TemporaryDirectory() as directory: + result = subprocess.run( + ["bash", "-euo", "pipefail", "-c", driver, "scheduling-booking", str(TABLES), directory, mode], + capture_output=True, text=True, timeout=10, + ) + self.assertEqual(result.returncode, code, result.stderr) + self.assertEqual(result.stdout.splitlines(), steps) + if mode == "refuse": + self.assertIn("HTTP 403, operation.not-authorized", result.stderr) + class PassRule(unittest.TestCase): @classmethod @@ -940,7 +993,7 @@ def walk(self, product, delivered): functions = [] for name in ( "walk_product", "recipe", "hook_received", "breg_hook_matches", - "managed_hook_url", "check_managed_hook", "signed_hook_received", "signed_hook_matches", + "managed_hook_url", "check_managed_hook", "documents_ready_hook", "documents_ready_matches", ): match = re.search(rf"^{name}\(\) \{{\n.*?^\}}\n", script, re.M | re.S) @@ -1159,6 +1212,7 @@ def test_evidence_first_read_uses_the_checked_start(self): def test_scheduling_reports_unexercised_and_keeps_walking(self): result, outcomes, trace = self.walk("scheduling", "no") self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertIn("needs a verified task grant and its assertion issuer binding", result.stdout) self.assertEqual([row for row in outcomes if row[0] == "hook"], [("hook", "unexercised")]) self.assertIn("scheduling hook: unexercised", result.stderr) self.assertEqual(outcomes[-3:], [("keep", "pass"), ("attach", "pass"), ("stop", "pass")]) @@ -1328,6 +1382,57 @@ def test_composed_fixtures_writes_valid_registration_and_runtimes(self): self.assertEqual(cw_rt["listener"]["bind"], "0.0.0.0:18100") self.assertEqual(cw_rt["listener"]["networkExposure"], "container-private") + def test_managed_scheduling_fixture_names_one_grant_and_live_status_client(self): + script = TABLES / "projects" / "composed_fixtures.py" + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + key = root / "status-input" + key.write_bytes(b"fixture status key\n") + key.chmod(0o600) + issuer = "http://127.0.0.1:18080" + jwks = issuer + "/oauth2/jwks" + project = root / "managed" + project.mkdir() + example = project / "runtime.example.yaml" + example.write_text("kind: SchedulingRuntimeConfig\ndestinations: {}\n", encoding="utf-8") + command = ["python3", str(script), "scheduling-managed-plan", str(project), + "--issuer", issuer, "--jwks", jwks, "--casework-port", "18100", + "--agent-subject", "fixture-agent", "--status-key", str(key)] + rejected = command.copy() + rejected[rejected.index(jwks)] = "http://127.0.0.1:18009/oauth2/jwks" + result = subprocess.run(rejected, capture_output=True, text=True) + self.assertNotEqual(result.returncode, 0) + self.assertIn("same-origin JWKS", result.stderr) + key.chmod(0o640) + result = subprocess.run(command, capture_output=True, text=True) + self.assertNotEqual(result.returncode, 0) + self.assertIn("owner-only fixture status key", result.stderr) + self.assertFalse((project / "fixture").exists()) + self.assertFalse((project / "dev.yaml").exists()) + key.chmod(0o600) + subprocess.run(command, check=True, capture_output=True) + plan = json.loads((project / "dev.yaml").read_text(encoding="utf-8")) + self.assertEqual(plan["externalJwksUri"], jwks) + self.assertEqual(plan["products"], [{"product": "scheduling", "project": ".", + "audience": "urn:example:journey:scheduling"}]) + self.assertEqual(plan["people"], {"task-agent": { + "subject": "fixture-agent", "client": "task-agent", + "grants": {"scheduling": {"profile": "reader", "scopes": ["scheduling:read"]}}, + }}) + self.assertEqual(plan["externalScheduling"], {"taskGrant": { + "sourceIssuer": "https://casework.journey.example", "assertionClient": "task-agent", + "statusUrl": "http://127.0.0.1:18100", "tokenEndpoint": issuer + "/oauth2/token", + "statusClient": "scheduling-status", "statusKeyRef": "secret:file/scheduling-status.jwk", + "statusResource": "urn:example:journey:casework", + }}) + self.assertEqual(json.loads((project / plan["journeyFile"]).read_text())["journeys"], []) + copied = project / "fixture/scheduling-status.jwk" + self.assertEqual(copied.read_bytes(), key.read_bytes()) + self.assertEqual(copied.stat().st_mode & 0o777, 0o600) + self.assertEqual(copied.parent.stat().st_mode & 0o777, 0o700) + destinations = yaml.safe_load(example.read_text())["destinations"] + self.assertEqual(set(destinations["hooks"]), {"appointment-events"}) + class TokenAudienceAndWrongAgentChecks(unittest.TestCase): @staticmethod From a6ed70a722b1dc7370d4c888829672c7756b78d1 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 19:11:12 +0000 Subject: [PATCH 056/183] fix(session): check literal route bindings and their assembly digest Signed-off-by: Jeremi Joslin --- crates/registry-session/src/gateway.rs | 11 ++ crates/registry-session/src/gateway/verify.rs | 28 +++-- crates/registry-session/src/lib.rs | 4 +- crates/registry-session/src/schema.rs | 65 +++++++++- crates/registry-session/tests/binary.rs | 102 +++++++++++---- .../src/content/docs/configure/session.mdx | 7 +- products/platform/config-formats.yaml | 32 +++++ .../examples/session/checked-routes.json | 23 ++++ ...ssion-route-inventory.v1alpha1.schema.json | 118 ++++++++++++++++++ 9 files changed, 352 insertions(+), 38 deletions(-) create mode 100644 products/platform/examples/session/checked-routes.json create mode 100644 products/platform/generated/session-runtime/session-route-inventory.v1alpha1.schema.json diff --git a/crates/registry-session/src/gateway.rs b/crates/registry-session/src/gateway.rs index 2566d393ce..50226f5f49 100644 --- a/crates/registry-session/src/gateway.rs +++ b/crates/registry-session/src/gateway.rs @@ -237,6 +237,15 @@ fn load_gateway_config( continue; } for index in 0..count { + if checked_routes { + let field = if list == "modules" { + "signIns" + } else { + "signIn" + }; + let binding = format!("/{list}/{index}/{field}"); + require(&binding, file.defers_within(&binding)); + } for field in ["id", "prefix", "upstream", "product"] { let pointer = format!("/{list}/{index}/{field}"); require( @@ -829,6 +838,8 @@ mod verify; pub use verify::{ verify_assembled, write_standalone, write_verified_route_inventory, StandaloneTls, }; +#[cfg(feature = "schema")] +pub(crate) use verify::{ROUTE_INVENTORY_API_VERSION, ROUTE_INVENTORY_KIND}; #[cfg(test)] mod tests { diff --git a/crates/registry-session/src/gateway/verify.rs b/crates/registry-session/src/gateway/verify.rs index 97757c879b..67258f23fa 100644 --- a/crates/registry-session/src/gateway/verify.rs +++ b/crates/registry-session/src/gateway/verify.rs @@ -18,10 +18,9 @@ use std::{ path::Path, }; -use registry_platform_config::{ListenerNetworkExposure, TlsTermination}; +use registry_platform_config::{sha256_uri, ListenerNetworkExposure, TlsTermination}; use registry_platform_yaml::{Reader, Refusal, ScalarHook, ScalarSite, ScalarStyle}; use serde_json::{json, Value}; -use sha2::{Digest, Sha256}; use super::*; use crate::config::ModuleProduct; @@ -29,6 +28,9 @@ use crate::wire::SOURCE_PROFILE_HEADER; /// The most bytes of an assembled configuration `--verify-assembled` reads. const MAXIMUM_ASSEMBLED_BYTES: u64 = 16 * 1024 * 1024; +pub(crate) const ROUTE_INVENTORY_API_VERSION: &str = + "id.registrystack.org/formats/platform/session-route-inventory/v1alpha1"; +pub(crate) const ROUTE_INVENTORY_KIND: &str = "PlatformSessionRouteInventory"; const MANAGER_TYPE: &str = "type.googleapis.com/envoy.extensions.filters.network.http_connection_manager.v3.HttpConnectionManager"; @@ -672,6 +674,16 @@ pub fn write_verified_route_inventory( "Select a disjoint BReg module prefix that rewrites to the product root.", )); } + if config.pages.iter().any(|page| { + !page + .prefix + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || b"/._:~-".contains(&byte)) + }) { + return Err(standalone_refusal( + "Use checked page prefixes made of letters, digits, or /._:~-.", + )); + } if config.pages.iter().any(|page| { config.modules.iter().any(|module| { lies_under(&page.prefix, &module.prefix) || lies_under(&module.prefix, &page.prefix) @@ -700,17 +712,11 @@ pub fn write_verified_route_inventory( .iter() .map(|page| json!({"prefix": page.prefix, "signIn": page.sign_in.as_str()})) .collect(); - let assembly_bytes = serde_json::to_vec(&document) - .map_err(|_| standalone_refusal("Could not serialize the verified assembly."))?; - let gateway_sha256: String = Sha256::digest(assembly_bytes) - .iter() - .map(|byte| format!("{byte:02x}")) - .collect(); let inventory = json!({ - "apiVersion": "id.registrystack.org/formats/platform/session-route-inventory/v1alpha1", - "kind": "PlatformSessionRouteInventory", + "apiVersion": ROUTE_INVENTORY_API_VERSION, + "kind": ROUTE_INVENTORY_KIND, "publicOrigin": config.public_origin.as_str().trim_end_matches('/'), - "gatewaySha256": gateway_sha256, + "gatewayDigest": sha256_uri(&assembly_bytes), "modules": modules, "pages": pages, }); diff --git a/crates/registry-session/src/lib.rs b/crates/registry-session/src/lib.rs index a60a0d15f5..80c70798f8 100644 --- a/crates/registry-session/src/lib.rs +++ b/crates/registry-session/src/lib.rs @@ -141,7 +141,7 @@ pub fn command() -> Command { Arg::new("route-inventory-out") .long("route-inventory-out") .value_name("FILE") - .help("Write browser paths for the selected BReg route from a verified loopback HTTPS assembly") + .help("Write browser paths for the selected Base Registry Engine route from a verified loopback HTTPS assembly") .requires_all(["verify-assembled", "checked-route"]) .value_parser(value_parser!(PathBuf)), ) @@ -149,7 +149,7 @@ pub fn command() -> Command { Arg::new("checked-route") .long("checked-route") .value_name("ID") - .help("Select the BReg product module for the browser route inventory") + .help("Select the Base Registry Engine module for the browser route inventory") .requires("route-inventory-out"), ) .arg( diff --git a/crates/registry-session/src/schema.rs b/crates/registry-session/src/schema.rs index 5a76b259a4..14cf1dbabf 100644 --- a/crates/registry-session/src/schema.rs +++ b/crates/registry-session/src/schema.rs @@ -7,6 +7,8 @@ use std::{borrow::Cow, collections::BTreeMap}; +use registry_platform_yaml::{Digest, LocalId, Url}; +use schemars::generate::SchemaSettings; use schemars::{json_schema, JsonSchema, Schema, SchemaGenerator}; use serde_json::{json, Value}; @@ -14,12 +16,18 @@ use crate::config::{ Authority, ClaimName, ClusterName, FilterName, HostName, ModuleAudience, ResourceUri, RewritePrefix, RuntimeConfig, ScopeToken, RUNTIME_API_VERSION, RUNTIME_KIND, }; +use crate::gateway::{ROUTE_INVENTORY_API_VERSION, ROUTE_INVENTORY_KIND}; /// The `$id` of the runtime schema. pub const RUNTIME_SCHEMA_ID: &str = "https://id.registrystack.org/schemas/platform/session-runtime/session-runtime.v1alpha1.schema.json"; /// The file name of the committed runtime schema. pub const RUNTIME_SCHEMA_FILE: &str = "session-runtime.schema.json"; +/// The `$id` of the checked browser route inventory schema. +pub const ROUTE_INVENTORY_SCHEMA_ID: &str = + "https://id.registrystack.org/schemas/platform/session-route-inventory/session-route-inventory.v1alpha1.schema.json"; +/// The file name of the committed checked route inventory schema. +pub const ROUTE_INVENTORY_SCHEMA_FILE: &str = "session-route-inventory.v1alpha1.schema.json"; /// Every generated schema, by file name, as the bytes to commit. pub fn schema_documents() -> Result, serde_json::Error> { @@ -43,7 +51,62 @@ pub fn schema_documents() -> Result, serde_json:: ]); let mut rendered = serde_json::to_string_pretty(&runtime)?; rendered.push('\n'); - Ok([(RUNTIME_SCHEMA_FILE, rendered)].into()) + let mut inventory = serde_json::to_string_pretty(&route_inventory_schema())?; + inventory.push('\n'); + Ok([ + (RUNTIME_SCHEMA_FILE, rendered), + (ROUTE_INVENTORY_SCHEMA_FILE, inventory), + ] + .into()) +} + +fn route_inventory_schema() -> Value { + let mut generator = SchemaSettings::draft2020_12().into_generator(); + let id = generator.subschema_for::(); + let digest = generator.subschema_for::(); + let mut origin = json!(generator.subschema_for::()); + origin["pattern"] = json!("^https://127(?:\\.[0-9]{1,3}){3}(?::[0-9]{1,5})?$"); + json!({ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": ROUTE_INVENTORY_SCHEMA_ID, + "$defs": generator.take_definitions(true), + "title": "Checked Registry Session route inventory", + "description": "One Base Registry Engine browser route and its page bindings from an exact, verified Envoy JSON file.", + "type": "object", + "additionalProperties": false, + "required": ["apiVersion", "kind", "publicOrigin", "gatewayDigest", "modules", "pages"], + "properties": { + "apiVersion": {"type": "string", "const": ROUTE_INVENTORY_API_VERSION}, + "kind": {"type": "string", "const": ROUTE_INVENTORY_KIND}, + "publicOrigin": origin, + "gatewayDigest": digest, + "modules": { + "type": "array", "minItems": 1, "maxItems": 1, + "items": { + "type": "object", "additionalProperties": false, + "required": ["id", "product", "prefix", "prefixRewrite", "signIns"], + "properties": { + "id": id, + "product": {"type": "string", "const": "breg"}, + "prefix": {"type": "string", "maxLength": 256, "pattern": "^/(?:(?!\\.\\.?/)[A-Za-z0-9._:-]+/)+$"}, + "prefixRewrite": {"type": "string", "const": "/"}, + "signIns": {"type": "array", "minItems": 1, "maxItems": 64, "uniqueItems": true, "items": id} + } + } + }, + "pages": { + "type": "array", "maxItems": 64, "uniqueItems": true, + "items": { + "type": "object", "additionalProperties": false, + "required": ["prefix", "signIn"], + "properties": { + "prefix": {"type": "string", "maxLength": 256, "pattern": "^/(?:(?!\\.\\.?(?:/|$))[A-Za-z0-9._:~-]+(?:/|$))+$"}, + "signIn": id + } + } + } + } + }) } /// File audit requires an absolute path. Stdout accepts no file-only setting. diff --git a/crates/registry-session/tests/binary.rs b/crates/registry-session/tests/binary.rs index d584f56418..5f341e2830 100644 --- a/crates/registry-session/tests/binary.rs +++ b/crates/registry-session/tests/binary.rs @@ -277,11 +277,9 @@ fn gateway_writes_a_deterministic_checked_standalone_configuration() { fn gateway_inventory_requires_the_exact_verified_assembly() { let root = tempfile::tempdir().expect("directory"); let runtime = root.path().join("runtime.yaml"); - std::fs::write( - &runtime, - standalone_runtime().replace("https://app.example", "https://127.0.0.1:8080"), - ) - .expect("runtime"); + let runtime_source = + standalone_runtime().replace("https://app.example", "https://127.0.0.1:8080"); + std::fs::write(&runtime, &runtime_source).expect("runtime"); let assembly = root.path().join("envoy.json"); let routes = root.path().join("routes.json"); let certificate = root.path().join("cert.pem"); @@ -302,23 +300,26 @@ fn gateway_inventory_requires_the_exact_verified_assembly() { assert_eq!(verify().0, 1, "ordinary plaintext assembly must not export"); assert!(!routes.exists()); - let (exit, _, stderr) = run_command( - runtime_command(&runtime) - .args(["gateway", "envoy", "--standalone-out"]) - .arg(&assembly) - .args([ - "--listen", - "127.0.0.1:8080", - "--upstream", - "registry=127.0.0.1:8100", - "--upstream", - "pages=127.0.0.1:8200", - ]) - .arg("--tls-certificate") - .arg(&certificate) - .arg("--tls-key") - .arg(&key), - ); + let assemble = || { + run_command( + runtime_command(&runtime) + .args(["gateway", "envoy", "--standalone-out"]) + .arg(&assembly) + .args([ + "--listen", + "127.0.0.1:8080", + "--upstream", + "registry=127.0.0.1:8100", + "--upstream", + "pages=127.0.0.1:8200", + ]) + .arg("--tls-certificate") + .arg(&certificate) + .arg("--tls-key") + .arg(&key), + ) + }; + let (exit, _, stderr) = assemble(); assert_eq!(exit, 0, "{stderr}"); let (exit, _, stderr) = verify(); assert_eq!(exit, 0, "{stderr}"); @@ -326,6 +327,26 @@ fn gateway_inventory_requires_the_exact_verified_assembly() { let inventory: serde_json::Value = serde_json::from_slice(&first).expect("JSON inventory"); assert_eq!(inventory["kind"], "PlatformSessionRouteInventory"); assert_eq!(inventory["publicOrigin"], "https://127.0.0.1:8080"); + let digest = |file: &std::path::Path| { + let bytes = std::fs::read(file).expect("assembly bytes"); + registry_platform_config::sha256_uri(&bytes) + }; + assert_eq!(inventory["gatewayDigest"], digest(&assembly)); + #[cfg(feature = "schema")] + { + use registry_session::schema::{schema_documents, ROUTE_INVENTORY_SCHEMA_FILE}; + let schemas = schema_documents().expect("Session schemas"); + let schema = serde_json::from_str(&schemas[ROUTE_INVENTORY_SCHEMA_FILE]) + .expect("inventory schema is JSON"); + let validator = jsonschema::JSONSchema::options() + .with_draft(jsonschema::Draft::Draft202012) + .compile(&schema) + .expect("inventory schema compiles"); + assert!( + validator.is_valid(&inventory), + "native inventory violates its schema" + ); + } assert_eq!( inventory["modules"], json!([{ @@ -356,6 +377,26 @@ fn gateway_inventory_requires_the_exact_verified_assembly() { assert_eq!(exit, 0, "{stderr}"); assert_eq!(std::fs::read(&routes).expect("regenerated routes"), first); + for (field, deferred) in [ + ( + "module sign-ins", + runtime_source.replace( + " audience: person\n", + " audience: person\n signIns: [citizen, '${MODULE_SIGN_IN}']\n", + ), + ), + ( + "page sign-in", + runtime_source.replace(" signIn: citizen", " signIn: '${PAGE_SIGN_IN}'"), + ), + ] { + assert_ne!(deferred, runtime_source); + std::fs::write(&runtime, deferred).expect("deferred runtime"); + assert_eq!(verify().0, 1, "refuse deferred {field}"); + assert_eq!(std::fs::read(&routes).expect("retained inventory"), first); + } + std::fs::write(&runtime, &runtime_source).expect("restore literal test fixture"); + assert_eq!(export(&key).0, 1, "refuse to overwrite the gateway TLS key"); assert_eq!( std::fs::read_to_string(&key).expect("original key placeholder"), @@ -376,6 +417,15 @@ fn gateway_inventory_requires_the_exact_verified_assembly() { assert!(!certificate.exists()); let contents = std::fs::read_to_string(&assembly).expect("Envoy configuration"); + std::fs::write(&assembly, format!("{contents}\n")).expect("reformat assembly"); + assert_eq!(verify().0, 0, "whitespace remains valid JSON"); + let reformatted = std::fs::read(&routes).expect("new inventory digest"); + let changed: serde_json::Value = serde_json::from_slice(&reformatted).expect("JSON inventory"); + assert_eq!(changed["gatewayDigest"], digest(&assembly)); + assert_ne!(changed["gatewayDigest"], inventory["gatewayDigest"]); + std::fs::write(&assembly, &contents).expect("restore original assembly bytes"); + assert_eq!(verify().0, 0); + std::fs::write( &assembly, contents.replacen("\"static_resources\"", "static_resources", 1), @@ -404,6 +454,14 @@ fn gateway_inventory_requires_the_exact_verified_assembly() { std::fs::write(&assembly, remote.to_string()).expect("mutate upstream address"); assert_eq!(verify().0, 1); assert_eq!(std::fs::read(&routes).expect("retained inventory"), first); + + let unsafe_page = runtime_source.replace("/apply/", "/apply;/"); + assert_ne!(unsafe_page, runtime_source); + std::fs::write(&runtime, unsafe_page).expect("runtime with broader page prefix"); + let (exit, _, stderr) = assemble(); + assert_eq!(exit, 0, "{stderr}"); + assert_eq!(verify().0, 1, "refuse a page path that live checks reject"); + assert_eq!(std::fs::read(&routes).expect("retained inventory"), first); } #[test] diff --git a/docs/site/src/content/docs/configure/session.mdx b/docs/site/src/content/docs/configure/session.mdx index 7f09e99219..46d48ebb99 100644 --- a/docs/site/src/content/docs/configure/session.mdx +++ b/docs/site/src/content/docs/configure/session.mdx @@ -297,8 +297,11 @@ registry-session --runtime-config /etc/registry-session/runtime.yaml gateway env ``` The export checks the standalone Envoy JSON and records the selected BReg product route, -its admitted sign-in kinds and the page bindings. Use it with the assembly that produced it. -Envoy and Session check live requests, and the product authorizes the operation. +its admitted sign-in kinds and the page bindings. Write the sign-in names literally and keep +page paths to letters, digits and `/._:~-`. +The `gatewayDigest` is SHA-256 over the exact Envoy JSON file bytes, including whitespace. +Use the inventory with those bytes. Envoy and Session check live requests, and the product +authorizes the operation. {/* Evidence: crates/registry-session/src/gateway/verify.rs, validate_checked_transport, verify_checked_transport, write_verified_route_inventory; diff --git a/products/platform/config-formats.yaml b/products/platform/config-formats.yaml index 8e4b1681d4..1f31c927ef 100644 --- a/products/platform/config-formats.yaml +++ b/products/platform/config-formats.yaml @@ -276,6 +276,38 @@ formats: whenOmitted: closed restrictingMembers: [] + - id: platform/session-route-inventory + product: platform + title: Checked Registry Session browser route inventory + files: [] + syntax: json + audience: generated + stability: experimental + current: + apiVersion: id.registrystack.org/formats/platform/session-route-inventory/v1alpha1 + kind: PlatformSessionRouteInventory + checkedBy: + file: crates/registry-session/src/gateway/verify.rs + symbol: ROUTE_INVENTORY_API_VERSION + target: + apiVersion: id.registrystack.org/formats/platform/session-route-inventory/v1alpha1 + kind: PlatformSessionRouteInventory + schema: + path: products/platform/generated/session-runtime/session-route-inventory.v1alpha1.schema.json + id: https://id.registrystack.org/schemas/platform/session-route-inventory/session-route-inventory.v1alpha1.schema.json + origin: generated + generator: cargo run -p registry-session --features schema --example session-runtime-schema -- --output products/platform/generated/session-runtime + driftCheck: crates/registry-session/src/schema.rs + reader: none + emittedBy: + file: crates/registry-session/src/gateway/verify.rs + symbol: write_verified_route_inventory + check: none + example: products/platform/examples/session/checked-routes.json + conformance: none + securityMembers: [] + restrictingMembers: [] + # breg - id: breg/project product: breg diff --git a/products/platform/examples/session/checked-routes.json b/products/platform/examples/session/checked-routes.json new file mode 100644 index 0000000000..3b2033bfae --- /dev/null +++ b/products/platform/examples/session/checked-routes.json @@ -0,0 +1,23 @@ +{ + "apiVersion": "id.registrystack.org/formats/platform/session-route-inventory/v1alpha1", + "gatewayDigest": "sha256:56635e6d5a33bb8026b95d06912c4be2a9e725ce66b389126830c3c31d69bcae", + "kind": "PlatformSessionRouteInventory", + "modules": [ + { + "id": "businesses", + "prefix": "/registry/businesses/", + "prefixRewrite": "/", + "product": "breg", + "signIns": [ + "registrar" + ] + } + ], + "pages": [ + { + "prefix": "/apply/", + "signIn": "registrar" + } + ], + "publicOrigin": "https://127.0.0.1:8443" +} diff --git a/products/platform/generated/session-runtime/session-route-inventory.v1alpha1.schema.json b/products/platform/generated/session-runtime/session-route-inventory.v1alpha1.schema.json new file mode 100644 index 0000000000..2fecc18432 --- /dev/null +++ b/products/platform/generated/session-runtime/session-route-inventory.v1alpha1.schema.json @@ -0,0 +1,118 @@ +{ + "$defs": { + "Digest": { + "description": "A SHA-256 digest: `sha256:` followed by 64 lowercase hex digits.", + "pattern": "^sha256:[0-9a-f]{64}$", + "type": "string" + }, + "LocalId": { + "description": "A local identifier: a lowercase letter, then up to 63 lowercase letters, digits, `_`, or `-`.", + "pattern": "^[a-z][a-z0-9_-]{0,63}$", + "type": "string" + }, + "Url": { + "description": "An absolute http or https URL with a host preserved as written, no user information, and no backslash, whitespace or control character. DNS case and equivalent IPv6 literals are permitted.", + "format": "uri", + "maxLength": 2048, + "pattern": "^[Hh][Tt][Tt][Pp][Ss]?://[^/?#@\\u005C\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000]+([/?#][^\\u005C\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000]*)?$", + "type": "string" + } + }, + "$id": "https://id.registrystack.org/schemas/platform/session-route-inventory/session-route-inventory.v1alpha1.schema.json", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "description": "One Base Registry Engine browser route and its page bindings from an exact, verified Envoy JSON file.", + "properties": { + "apiVersion": { + "const": "id.registrystack.org/formats/platform/session-route-inventory/v1alpha1", + "type": "string" + }, + "gatewayDigest": { + "$ref": "#/$defs/Digest" + }, + "kind": { + "const": "PlatformSessionRouteInventory", + "type": "string" + }, + "modules": { + "items": { + "additionalProperties": false, + "properties": { + "id": { + "$ref": "#/$defs/LocalId" + }, + "prefix": { + "maxLength": 256, + "pattern": "^/(?:(?!\\.\\.?/)[A-Za-z0-9._:-]+/)+$", + "type": "string" + }, + "prefixRewrite": { + "const": "/", + "type": "string" + }, + "product": { + "const": "breg", + "type": "string" + }, + "signIns": { + "items": { + "$ref": "#/$defs/LocalId" + }, + "maxItems": 64, + "minItems": 1, + "type": "array", + "uniqueItems": true + } + }, + "required": [ + "id", + "product", + "prefix", + "prefixRewrite", + "signIns" + ], + "type": "object" + }, + "maxItems": 1, + "minItems": 1, + "type": "array" + }, + "pages": { + "items": { + "additionalProperties": false, + "properties": { + "prefix": { + "maxLength": 256, + "pattern": "^/(?:(?!\\.\\.?(?:/|$))[A-Za-z0-9._:~-]+(?:/|$))+$", + "type": "string" + }, + "signIn": { + "$ref": "#/$defs/LocalId" + } + }, + "required": [ + "prefix", + "signIn" + ], + "type": "object" + }, + "maxItems": 64, + "type": "array", + "uniqueItems": true + }, + "publicOrigin": { + "$ref": "#/$defs/Url", + "pattern": "^https://127(?:\\.[0-9]{1,3}){3}(?::[0-9]{1,5})?$" + } + }, + "required": [ + "apiVersion", + "kind", + "publicOrigin", + "gatewayDigest", + "modules", + "pages" + ], + "title": "Checked Registry Session route inventory", + "type": "object" +} From 3f59b13853e387d0942acab97bd08335c5dd4962 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 19:11:12 +0000 Subject: [PATCH 057/183] fix(evidence): make store provisioning checks conform to the operator contract Signed-off-by: Jeremi Joslin --- crates/registry-cli-docs/src/lib.rs | 7 ++- crates/registry-evidencectl/src/lib.rs | 7 ++- .../src/store_provision.rs | 41 ++++++++++----- .../tests/store_provision.rs | 50 +++++++++++++++++++ products/evidence/OPERATOR-CONTRACT.md | 3 +- .../examples/formats/store-provision.yaml | 1 + products/platform/config-formats.yaml | 42 ++++++++++++++++ 7 files changed, 135 insertions(+), 16 deletions(-) diff --git a/crates/registry-cli-docs/src/lib.rs b/crates/registry-cli-docs/src/lib.rs index 7bcd41c234..822423ccb2 100644 --- a/crates/registry-cli-docs/src/lib.rs +++ b/crates/registry-cli-docs/src/lib.rs @@ -1108,7 +1108,12 @@ mod tests { let evidencectl_check = find_command(&catalog.binaries, "evidencectl check"); assert!(evidencectl_check.constraints.iter().any(|constraint| { constraint.kind == ConstraintKind::RequiredExactlyOne - && constraint.arguments == ["[PROJECT]", "--file "] + && constraint.arguments + == [ + "[PROJECT]", + "--file ", + "--store-provision-config ", + ] })); let mock_serve = find_command(&catalog.binaries, "evidencectl source mock serve"); diff --git a/crates/registry-evidencectl/src/lib.rs b/crates/registry-evidencectl/src/lib.rs index a74210d554..39f420d415 100644 --- a/crates/registry-evidencectl/src/lib.rs +++ b/crates/registry-evidencectl/src/lib.rs @@ -203,6 +203,9 @@ struct CheckArgs { /// Check a store provisioning file offline without resolving secrets. #[arg(long, value_name = "FILE", conflicts_with_all = ["target", "production"])] store_provision_config: Option, + /// Resolve text substitutions in the provisioning file from the environment. + #[arg(long, requires = "store_provision_config")] + environment: bool, /// Explicit deployment target whose governance and runtime structure are checked. #[arg(long)] target: Option, @@ -374,7 +377,7 @@ fn cli_command() -> clap::Command { command .mut_subcommand("provision", |subcommand| { subcommand.mut_arg("runtime_config", |argument| { - argument.help("Provisioning-only Evidence store file") + argument.help("Runtime configuration file for Evidence store provisioning") }) }) .mut_subcommand("runtime", |subcommand| { @@ -709,11 +712,13 @@ fn run_entry() -> ExitCode { Command::Check(CheckArgs { store_provision_config: Some(file), deny_warnings, + environment, .. }) => Ok(store_provision::check( &file, format, deny_warnings, + environment, posture, )), Command::Check(args) => { diff --git a/crates/registry-evidencectl/src/store_provision.rs b/crates/registry-evidencectl/src/store_provision.rs index 315322b68a..f0a1fd2189 100644 --- a/crates/registry-evidencectl/src/store_provision.rs +++ b/crates/registry-evidencectl/src/store_provision.rs @@ -12,7 +12,7 @@ use registry_platform_provision::{ SchemaLayout, }; use registry_platform_yaml::{Diagnostic, Report, Source}; -use serde::Deserialize; +use serde::{Deserialize, Deserializer}; use zeroize::Zeroizing; use crate::{report, OutputFormat}; @@ -25,14 +25,27 @@ const SPLIT_ROLES_REQUIRED: &str = "evidence.store-provision.split-roles-require pub(crate) const SCHEMA_ID: &str = "https://id.registrystack.org/schemas/evidence/store-provision/store-provision.v1alpha1.schema.json"; -#[derive(Deserialize)] #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] -#[serde(rename_all = "kebab-case")] +#[cfg_attr(feature = "schema", schemars(rename_all = "kebab-case"))] enum Store { Status, Oid4vci, } +impl<'de> Deserialize<'de> for Store { + fn deserialize>(deserializer: D) -> Result { + let name = String::deserialize(deserializer)?; + match name.as_str() { + "status" => Ok(Self::Status), + "oid4vci" => Ok(Self::Oid4vci), + _ => Err(serde::de::Error::unknown_variant( + &name, + &["status", "oid4vci"], + )), + } + } +} + impl Store { fn product(&self) -> ProductDatabase { ProductDatabase { @@ -152,20 +165,22 @@ pub(crate) fn check( path: &Path, format: OutputFormat, deny_warnings: bool, + environment: bool, declared: DeclaredPosture, ) -> ExitCode { let (found, unavailable) = match std::path::absolute(path) { Ok(path) => { - let checked = - loader(declared).check_offline::(&path, false, |pointer| { - match pointer { - "/store" => "status", - "/secretProviders/file/root" => "/deferred", - "/database/transport" => "verified-tls", - "/database/testOnlyPlaintext" => "false", - _ => DEFAULT_STAND_IN, - } - }); + let checked = loader(declared).check_offline::( + &path, + environment, + |pointer| match pointer { + "/store" => "status", + "/secretProviders/file/root" => "/deferred", + "/database/transport" => "verified-tls", + "/database/testOnlyPlaintext" => "false", + _ => DEFAULT_STAND_IN, + }, + ); let extra = checked.loaded.as_ref().map_or_else(Vec::new, |loaded| { diagnostics(&loaded.config, |pointer| checked.defers(pointer)) }); diff --git a/crates/registry-evidencectl/tests/store_provision.rs b/crates/registry-evidencectl/tests/store_provision.rs index 7a137faff0..2efeaea35c 100644 --- a/crates/registry-evidencectl/tests/store_provision.rs +++ b/crates/registry-evidencectl/tests/store_provision.rs @@ -78,6 +78,56 @@ fn an_unknown_store_is_refused_offline() { assert_eq!(report["diagnostics"][0]["path"], "/store"); } +#[test] +fn store_name_requires_a_string() { + let directory = tempfile::tempdir().expect("private test directory"); + for store in ["true", "3", "2.5"] { + let output = check(&config(directory.path(), store)); + assert_eq!(output.status.code(), Some(1)); + let report: serde_json::Value = + serde_json::from_slice(&output.stdout).expect("check report"); + assert_eq!(report["diagnostics"][0]["path"], "/store"); + assert_eq!(report["diagnostics"][0]["code"], "config.expected-string"); + } +} + +#[test] +fn provisioning_check_resolves_authored_text_only_when_requested() { + let directory = tempfile::tempdir().expect("private test directory"); + let path = config(directory.path(), "status"); + let document = std::fs::read_to_string(&path).expect("read test configuration"); + std::fs::write(&path, document.replace( + "database:\n", + "database:\n transport: \"${EVIDENCE_TEST_TRANSPORT:?synthetic-private-diagnostic}\"\n", + )).expect("write a deferred transport setting"); + assert!(check(&path).status.success()); + + let inspect = |transport: Option<&str>| { + let mut command = evidencectl(); + command + .args([ + "--format", + "json", + "check", + "--environment", + "--store-provision-config", + ]) + .arg(&path) + .env_remove("EVIDENCE_TEST_TRANSPORT"); + if let Some(transport) = transport { + command.env("EVIDENCE_TEST_TRANSPORT", transport); + } + command.output().expect("run provisioning check") + }; + assert!(inspect(Some("verified-tls")).status.success()); + let refused = inspect(None); + assert_eq!(refused.status.code(), Some(1)); + assert!(!String::from_utf8_lossy(&refused.stdout).contains("synthetic-private-diagnostic")); + let report: serde_json::Value = serde_json::from_slice(&refused.stdout).expect("check report"); + assert_eq!(report["diagnostics"][0]["code"], "config.substitution"); + assert_eq!(report["diagnostics"][0]["path"], "/database/transport"); +} + #[test] fn a_shared_url_reference_is_refused_without_resolving_it() { let directory = tempfile::tempdir().expect("private test directory"); diff --git a/products/evidence/OPERATOR-CONTRACT.md b/products/evidence/OPERATOR-CONTRACT.md index 842a8cdc20..ed704378fc 100644 --- a/products/evidence/OPERATOR-CONTRACT.md +++ b/products/evidence/OPERATOR-CONTRACT.md @@ -79,7 +79,8 @@ on the same server. Use the `database.caBundleRef` reference when the database uses a private CA. Check the file with `evidencectl check --store-provision-config store-provision.yaml`. -The check reads no secret values. Review the plan with +Use `--environment` to fill text expressions from the current environment during +the check. The check leaves database secret references unresolved. Review the plan with `evidencectl provision --runtime-config store-provision.yaml --print-sql`. The plan reads the configured database secrets and connects to no PostgreSQL server. To execute it, replace `--print-sql` with `--admin-url-file `. diff --git a/products/evidence/examples/formats/store-provision.yaml b/products/evidence/examples/formats/store-provision.yaml index 391ebc91b8..ec883d4f3f 100644 --- a/products/evidence/examples/formats/store-provision.yaml +++ b/products/evidence/examples/formats/store-provision.yaml @@ -3,6 +3,7 @@ apiVersion: id.registrystack.org/formats/evidence/store-provision/v1alpha1 kind: EvidenceStoreProvisionConfig store: status database: + transport: verified-tls migrationUrlRef: secret:file/migration-url runtimeUrlRef: secret:file/runtime-url caBundleRef: secret:file/postgres-ca diff --git a/products/platform/config-formats.yaml b/products/platform/config-formats.yaml index 1f31c927ef..629c2d855d 100644 --- a/products/platform/config-formats.yaml +++ b/products/platform/config-formats.yaml @@ -2732,6 +2732,48 @@ formats: - pointer: /package/expectedDigest whenOmitted: open restrictingMembers: [] + - id: evidence/store-provision + product: evidence + title: Evidence store provisioning config + files: [store-provision.yaml] + syntax: yaml + audience: operator + stability: unpromised + current: + apiVersion: id.registrystack.org/formats/evidence/store-provision/v1alpha1 + kind: EvidenceStoreProvisionConfig + checkedBy: + file: crates/registry-evidencectl/src/store_provision.rs + symbol: API_VERSION + target: + apiVersion: id.registrystack.org/formats/evidence/store-provision/v1alpha1 + kind: EvidenceStoreProvisionConfig + schema: + path: crates/registry-evidencectl/schemas/authoring/store-provision.schema.json + id: https://id.registrystack.org/schemas/evidence/store-provision/store-provision.v1alpha1.schema.json + origin: generated + generator: cargo run -p registry-evidencectl --features schema --example authoring-schema -- --output crates/registry-evidencectl/schemas/authoring + driftCheck: products/evidence/scripts/check-authoring-schema.sh + reader: + crate: registry-evidencectl + file: crates/registry-evidencectl/src/store_provision.rs + function: load + type: StoreProvisionDocument + check: evidencectl check --store-provision-config {file} + example: products/evidence/examples/formats/store-provision.yaml + conformance: + requiredText: /store + optionalText: /database/transport + integer: none + boolean: none + securityMembers: + - pointer: /database/migrationUrlRef + whenOmitted: refused + - pointer: /database/runtimeUrlRef + whenOmitted: refused + - pointer: /database/caBundleRef + whenOmitted: open + restrictingMembers: [/store] - id: evidence/codelist product: evidence title: Evidence code list From 2f2127db6f5478ac45b5b2e1ec01f0a7606646fb Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 19:14:13 +0000 Subject: [PATCH 058/183] docs(evidence): publish the store provisioning reference Signed-off-by: Jeremi Joslin --- docs/site/scripts/generate-evidence-configuration.mjs | 7 +++++++ docs/site/scripts/generate-evidence-configuration.test.mjs | 2 ++ 2 files changed, 9 insertions(+) diff --git a/docs/site/scripts/generate-evidence-configuration.mjs b/docs/site/scripts/generate-evidence-configuration.mjs index 4db0eba1ed..d373cd183c 100644 --- a/docs/site/scripts/generate-evidence-configuration.mjs +++ b/docs/site/scripts/generate-evidence-configuration.mjs @@ -111,6 +111,13 @@ export const CONTRACTS = [ status: 'tooling', reference: AUTHORING_REFERENCE, }, + { + id: 'store-provision', + file: 'crates/registry-evidencectl/schemas/authoring/store-provision.schema.json', + title: 'store-provision.yaml', + status: 'tooling', + reference: 'products/evidence/OPERATOR-CONTRACT.md', + }, { id: 'oid4vci-runtime', file: 'products/evidence/generated/oid4vci-runtime/oid4vci-runtime.schema.json', diff --git a/docs/site/scripts/generate-evidence-configuration.test.mjs b/docs/site/scripts/generate-evidence-configuration.test.mjs index 4534cd5b90..0b2a3d9a28 100644 --- a/docs/site/scripts/generate-evidence-configuration.test.mjs +++ b/docs/site/scripts/generate-evidence-configuration.test.mjs @@ -660,6 +660,8 @@ test('every published schema declares whether it is frozen or adopter tooling', assert.equal(byId.get('authoring-project').status, 'tooling'); assert.equal(byId.get('authoring-target').status, 'tooling'); assert.equal(byId.get('authoring-target-authority').status, 'tooling'); + assert.equal(byId.get('store-provision').status, 'tooling'); + assert.equal(byId.get('store-provision').reference, 'products/evidence/OPERATOR-CONTRACT.md'); assert.equal(byId.get('oid4vci-runtime').status, 'beta'); assert.equal(byId.get('oid4vp-runtime').status, 'beta'); }); From b8228a4b219b903ad6b9baf7ff9a52376f44064d Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 19:09:22 +0000 Subject: [PATCH 059/183] refactor(adapter): select signed event transport before activation Signed-off-by: Jeremi Joslin (cherry picked from commit 08ba09afac9c35cf5e68c7f598b8a1e2d7a1b500) --- .../src/runtime_destination.rs | 98 +++++++++++++------ .../signed_coordinator_event_postgres.rs | 90 ++++++++++++++++- 2 files changed, 156 insertions(+), 32 deletions(-) diff --git a/crates/registry-adapter-job/src/runtime_destination.rs b/crates/registry-adapter-job/src/runtime_destination.rs index 5dea3ec2ae..be28eed68e 100644 --- a/crates/registry-adapter-job/src/runtime_destination.rs +++ b/crates/registry-adapter-job/src/runtime_destination.rs @@ -24,6 +24,11 @@ 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_httputil::{ + destination::EventDestinationPolicy, + select::{select_destination, TransportClass}, +}; +#[cfg(feature = "signed-coordinator-event")] use registry_platform_yaml::ExternalId; use registry_platform_yaml::{BoundedU64, LocalId, SecretReference, Url}; use serde::Deserialize; @@ -106,16 +111,15 @@ 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, .. } => { + #[cfg(feature = "direct-breg")] + drop(resolve_destination_keys(resolver, &bindings)?); let configured = bindings .get(binding) .ok_or_else(|| missing_binding(binding))?; #[cfg(feature = "direct-breg")] { - drop(keys); activate_direct( program, configured, @@ -142,7 +146,7 @@ pub async fn activate_destination<'a>( configured, &runtime.core, resolver, - keys, + &bindings, runtime.posture.posture(), ) } @@ -155,9 +159,8 @@ pub async fn activate_destination<'a>( } } -/// Check destination feature and runtime binding shape without resolving a -/// secret or opening a network connection. `adapter-job check` uses this -/// before it reports success. +/// Check the destination feature, runtime binding and signed event transport +/// without resolving a secret or opening a network connection. pub fn check_destination_runtime( job: &AdapterJob, runtime: &JobRuntimeConfig, @@ -178,14 +181,28 @@ pub fn check_destination_runtime( revised_receiver, .. }, RuntimeDestinationBinding::SignedCoordinatorEvent { + #[cfg(feature = "signed-coordinator-event")] + base_url, revised_receiver: configured_revised, + #[cfg(feature = "signed-coordinator-event")] + tls_trust_profile, .. }, - ) => check_revised_receiver( - binding, - revised_receiver.is_some(), - configured_revised.is_some(), - ), + ) => { + check_revised_receiver( + binding, + revised_receiver.is_some(), + configured_revised.is_some(), + )?; + #[cfg(feature = "signed-coordinator-event")] + signed_destination_policy( + binding, + base_url, + &runtime.core, + tls_trust_profile.is_some(), + )?; + Ok(()) + } _ => Err("the runtime destination kind does not match the job destination".to_string()), } } @@ -561,19 +578,50 @@ fn take_receiver_keys(keys: &mut BTreeMap, path: &str) -> D DeliveryKeys::new(current, previous).expect("the inventory validated distinct key bytes") } +#[cfg(feature = "signed-coordinator-event")] +fn signed_destination_policy( + binding: &LocalId, + base_url: &Url, + core: &AdapterEndpointBindings, + configured_tls: bool, +) -> Result { + let refused = "the signed-event destination policy was refused"; + // Transport inference admits HTTPS and loopback HTTP. Source CIDRs keep + // their existing role in the fixed event policy's address checks. + let selected = + select_destination(&base_url.to_url(), None, &[]).map_err(|_| refused.to_owned())?; + let private_cidrs = core + .allowed_private_cidrs + .iter() + .map(registry_adapter_core::Cidr::network) + .collect::>(); + // The original URL must be a bare origin, and HTTPS retains its existing + // profile and DNS policy. + let policy = EventDestinationPolicy::new( + binding.as_str(), + base_url.as_str(), + selected.profile(), + &private_cidrs, + ) + .map_err(|_| refused.to_owned())?; + if configured_tls && selected.transport() != TransportClass::VerifiedTls { + return Err("the signed-event destination TLS material was refused".to_owned()); + } + Ok(policy) +} + #[cfg(feature = "signed-coordinator-event")] fn activate_signed<'a>( program: &'a JobProgram, configured: &RuntimeDestinationBinding, core: &AdapterEndpointBindings, resolver: &SecretResolver, - mut keys: BTreeMap, + bindings: &BTreeMap, posture: registry_platform_config::Posture, ) -> Result, String> { use registry_adapter_connectors::coordinator_event::{ CoordinatorEventConnector, CoordinatorEventReceiver, }; - use registry_platform_httputil::destination::{DestinationProfile, EventDestinationPolicy}; let JobDestination::SignedCoordinatorEvent { binding, @@ -602,28 +650,18 @@ fn activate_signed<'a>( revised_receiver.is_some(), configured_revised.is_some(), )?; + let mut policy = + signed_destination_policy(binding, base_url, core, tls_trust_profile.is_some())? + .with_peer_policy(registry_platform_httputil::PeerPolicy::from_posture( + posture, + )); + let mut keys = resolve_destination_keys(resolver, bindings)?; 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::LoopbackHttp - }; - let private_cidrs = core - .allowed_private_cidrs - .iter() - .map(registry_adapter_core::Cidr::network) - .collect::>(); - let mut policy = - EventDestinationPolicy::new(binding.as_str(), base_url.as_str(), profile, &private_cidrs) - .map_err(|_| "the signed-event destination policy was refused".to_string())? - .with_peer_policy(registry_platform_httputil::PeerPolicy::from_posture( - posture, - )); if tls_trust_profile.is_some() { let endpoint = tls_endpoint(binding, base_url, tls_trust_profile.clone())?; let materials = 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 78e2e85151..45e2054b43 100644 --- a/crates/registry-adapter-job/tests/signed_coordinator_event_postgres.rs +++ b/crates/registry-adapter-job/tests/signed_coordinator_event_postgres.rs @@ -29,7 +29,7 @@ use registry_adapter_engine::job::{compile_job, JobProgram}; use registry_adapter_engine::job_sources::JobRuntimeConfig; use registry_adapter_job::destination::{DeliverableItem, HandOffOutcome, JobDestination}; use registry_adapter_job::pass::{run_pass, PassOptions, PassReport, StopReason}; -use registry_adapter_job::runtime_destination::activate_destination; +use registry_adapter_job::runtime_destination::{activate_destination, check_destination_runtime}; use registry_adapter_job::signed_coordinator_event::{ receiver_identity, CoordinatorReceiverDigestContext, SignedCoordinatorEventDestination, SignedCoordinatorEventReceiver, @@ -162,6 +162,8 @@ async fn isolated_store() -> Pool { #[tokio::test(flavor = "multi_thread")] async fn runtime_binding_activates_the_signed_destination_without_fallback() { const KEY_ENV: &str = "ADAPTER_JOB_SIGNED_DESTINATION_TEST_KEY"; + const RECEIVER_DIGEST: &str = "SELECT receiver_identity FROM adapter_job_items \ + WHERE job_id = 'case-daily' AND item_key = 'submissions/a'"; struct EnvironmentGuard; impl Drop for EnvironmentGuard { fn drop(&mut self) { @@ -177,6 +179,7 @@ async fn runtime_binding_activates_the_signed_destination_without_fallback() { .await .expect("the signed receiver binds"); let address = listener.local_addr().expect("the receiver address"); + let base_url = format!("http://127.0.0.1:{}/", address.port()); let app = Router::new() .route(TARGET, post(admit)) .with_state(receiver.clone()); @@ -203,7 +206,7 @@ async fn runtime_binding_activates_the_signed_destination_without_fallback() { runtime["destinations"] = json!({ "coordinator-test": { "type": "signed-coordinator-event", - "baseUrl": format!("http://127.0.0.1:{}/", address.port()), + "baseUrl": &base_url, "hmacSha256KeyRef": format!("secret:env/{KEY_ENV}"), "attemptTimeoutMilliseconds": 2000 } @@ -221,6 +224,7 @@ async fn runtime_binding_activates_the_signed_destination_without_fallback() { let program = compile_job(&fixture.pack, &fixture.job, &fixture.runtime).expect("the job compiles"); let runtime = JobRuntimeConfig::load(&fixture.runtime).expect("the runtime snapshot loads"); + check_destination_runtime(&program.job, &runtime).expect("the signed destination checks"); let resolver = SecretResolver::new([SecretProvider::Environment], "") .expect("the environment secret resolver starts"); let destination = activate_destination(&program, &runtime, &resolver) @@ -249,6 +253,18 @@ async fn runtime_binding_activates_the_signed_destination_without_fallback() { assert_eq!(pending.sequence, 1); assert!(pending.run_id.is_none()); assert!(!pending.admitted_before); + let expected_identity = receiver_identity(&CoordinatorReceiverDigestContext { + binding: "coordinator-test", + base_url: &base_url, + tls_trust_profile: None, + workflow: "case-ingestion", + trigger: "submitted", + source: "urn:registry-adapter:job:case-daily", + event_type: "org.example.case-submitted.v1", + data_schema: "urn:example:schema:case-submitted:v1", + }); + let pending_identity: Vec = client.query_one(RECEIVER_DIGEST, &[]).await.unwrap().get(0); + assert_eq!(pending_identity, expected_identity); let state = store::read_state(&client, "case-daily") .await .unwrap() @@ -275,11 +291,81 @@ async fn runtime_binding_activates_the_signed_destination_without_fallback() { assert_eq!(acknowledged.sequence, pending.sequence); assert_eq!(acknowledged.last_digest, pending.last_digest); assert!(acknowledged.run_id.is_some()); + let retried_identity: Vec = client.query_one(RECEIVER_DIGEST, &[]).await.unwrap().get(0); + assert_eq!(retried_identity, pending_identity); let bodies = receiver.bodies.lock().expect("the receiver body lock"); assert_eq!(bodies.len(), 2); assert_eq!(bodies[0], bodies[1], "a retry preserves envelope bytes"); } +#[tokio::test] +async fn signed_destination_refuses_invalid_transports_and_origins_before_keys() { + let fixture = job_fixture::JobFixture::start( + job_fixture::PAGE_SCRIPT, + vec![], + job_fixture::Edits::Ordered, + ) + .await; + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + let missing_key = tempfile::tempdir().expect("an empty directory for the missing key"); + let resolver = SecretResolver::new([SecretProvider::File], missing_key.path()) + .expect("the file resolver starts"); + let mut document: serde_json::Value = + serde_json::from_slice(&std::fs::read(&fixture.runtime).unwrap()).unwrap(); + let policy_refused = "the signed-event destination policy was refused"; + for (base_url, tls_trust_profile, expected) in [ + // The job fixture intentionally lists a CIDR covering this address. + ( + "http://192.168.10.8:41001/".to_owned(), + None, + policy_refused, + ), + ( + format!("http://{address}/?resource=unexpected"), + None, + policy_refused, + ), + ("https://localhost:41001/".to_owned(), None, policy_refused), + ( + format!("http://{address}/"), + Some("private-ca"), + "the signed-event destination TLS material was refused", + ), + ] { + document["destinations"] = json!({ + "coordinator-test": { + "type": "signed-coordinator-event", + "baseUrl": base_url, + "hmacSha256KeyRef": "secret:file/missing-key", + "attemptTimeoutMilliseconds": 2000 + } + }); + if let Some(profile) = tls_trust_profile { + document["destinations"]["coordinator-test"]["tlsTrustProfile"] = json!(profile); + } + std::fs::write(&fixture.runtime, serde_json::to_vec(&document).unwrap()).unwrap(); + let program = compile_job(&fixture.pack, &fixture.job, &fixture.runtime).unwrap(); + let runtime = JobRuntimeConfig::load(&fixture.runtime).unwrap(); + assert_eq!( + check_destination_runtime(&program.job, &runtime).unwrap_err(), + expected + ); + assert_eq!( + activate_destination(&program, &runtime, &resolver) + .await + .err() + .as_deref(), + Some(expected) + ); + } + assert!( + tokio::time::timeout(Duration::from_millis(100), listener.accept()) + .await + .is_err() + ); +} + #[tokio::test(flavor = "multi_thread")] async fn a_lost_signed_event_answer_recovers_one_run_through_the_job_store() { let receiver = Receiver::default(); From d82538f002461ac7473c1541f1dc63c4dc7156f6 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 19:18:33 +0000 Subject: [PATCH 060/183] fix(journeys): read the Messaging starter receipt at T1 Signed-off-by: Jeremi Joslin (cherry picked from commit 578b6b2b7cba24cbc35897fc7e48cf2a245fd253) --- products/platform/journeys/concepts.yaml | 2 + products/platform/journeys/rstack-dev.sh | 46 ++++++++++++------- .../platform/journeys/test_journey_tables.py | 31 ++++++++----- 3 files changed, 51 insertions(+), 28 deletions(-) diff --git a/products/platform/journeys/concepts.yaml b/products/platform/journeys/concepts.yaml index c1f2249b5a..570f005e74 100644 --- a/products/platform/journeys/concepts.yaml +++ b/products/platform/journeys/concepts.yaml @@ -58,6 +58,8 @@ concepts: meaning: The run identifier and its time to live. - id: header-file meaning: The file that holds a ready authorisation header. + - id: idempotency-key + meaning: The key that identifies the original submission for a receipt read. - id: short-lived-token meaning: A token with a five minute lifetime. - id: runtime-file diff --git a/products/platform/journeys/rstack-dev.sh b/products/platform/journeys/rstack-dev.sh index 499f8f4481..6086a1e969 100755 --- a/products/platform/journeys/rstack-dev.sh +++ b/products/platform/journeys/rstack-dev.sh @@ -210,7 +210,7 @@ recipe() { messaging) PERSON=case-system CALL_METHOD=POST - CALL_PATH=/v1/messages + CALL_PATH=/v1/messages/receipt CALL_BODY='{"senderProfile":"reminders-sms","to":{"phone":"+15555550100"},"template":{"id":"appointment-reminder-sms","version":"1"},"locale":"en","data":{"name":"Ada Lovelace","day":"2026-10-01","office":"Central Registry Office"}}' ;; breg) @@ -400,9 +400,11 @@ write_keep() { field='.requestId' ;; messaging) - KEEP_PATH=/v1/messages/$message_id - KEEP_EXPECT=$message_id - return + path=/v1/messages + body=$CALL_BODY + field='.id' + options+=(--expect-status 202 + --typed "curl -H @HEADER_FILE -H 'Idempotency-Key:journey-keep' --json '$body' $url$path") ;; scheduling) local config @@ -433,20 +435,23 @@ write_keep() { [[ "$product" != casework ]] || write_path="$path?accessProfile=requester" journey_http "$step" "${options[@]}" --data-file "$work/keep-body.json" --capture "$field" saved_id "$method" "$url$write_path" || unexpected_answer "$step" case "$product" in - breg | coordinator) KEEP_PATH=$path/$saved_id ;; + breg | coordinator | messaging) KEEP_PATH=$path/$saved_id ;; casework) KEEP_PATH=$path/$saved_id ;; adapter) KEEP_PATH=$path ;; esac KEEP_EXPECT=$saved_id + if [[ "$product" == messaging && "$saved_id" == "$message_id" ]]; then + journey_harness_failure "the retention send did not create a distinct message" + fi } # start_run STEP PROJECT: `rstack dev start` on PROJECT as part of STEP. Sets # RUN, BASE_URL and START_FILE (the report) on success. Returns the command's # status; the caller records the outcome. start_run() { - local step=$1 project=$2 status=0 - journey_step "$step" --timeout 240 --concepts run-id-and-ttl,journey-file \ - --typed "rstack dev start $project" -- rstack_dev start "$project" || status=$? + local step=$1 project=$2 status=0 project_arg=./${2##*/} + journey_step "$step" --cwd "${project%/*}" --timeout 240 --concepts run-id-and-ttl,journey-file \ + --typed "rstack dev start $project_arg" -- rstack_dev start "$project_arg" || status=$? START_FILE=$JOURNEY_STEP_STDOUT if [[ $status -eq 0 ]]; then RUN=$(jq -er '.run_id' "$START_FILE") || journey_harness_failure "the start report of $CELL names no run id; see $START_FILE" @@ -503,8 +508,8 @@ walk_product() { project=$work/project # init: the product's own init. - init_command "$product" "$project" - journey_step init --concepts project -- "${INIT_COMMAND[@]}" || status=$? + init_command "$product" ./project + journey_step init --cwd "$work" --concepts project -- "${INIT_COMMAND[@]}" || status=$? if [[ $status -ne 0 ]]; then fail_with_product_code init "$JOURNEY_STEP_STDOUT" "$JOURNEY_STEP_STDERR" journey_cell_end @@ -600,19 +605,22 @@ walk_product() { case "$product" in coordinator) call_options+=(--capture '.workflowRevision' workflow_revision) ;; casework) CALL_PATH+='?accessProfile=staff' ;; + messaging) + # Start already submitted the exact starter request. The receipt route + # uses its original request and key and does not submit another message. + printf '%s\n' "$CALL_BODY" >"$work/call-body.json" + call_options+=(--expect-status 200 --header 'Content-Type: application/json' --header 'Idempotency-Key: send-a-reminder-sms' + --data-file "$work/call-body.json" --capture '.id | strings | select(length > 0)' message_id --concepts idempotency-key + --typed "curl -H @HEADER_FILE -H 'Idempotency-Key:send-a-reminder-sms' --json '$CALL_BODY' $url$CALL_PATH") + ;; esac - if [[ -n "$CALL_BODY" ]]; then - printf '%s\n' "$CALL_BODY" | journey_write_file "$work/call-body.json" - call_options+=(--header 'Content-Type: application/json' --header 'Idempotency-Key: journey-first-call' --data-file "$work/call-body.json" --capture '.id' message_id) - fi journey_http call "${call_options[@]}" "$CALL_METHOD" "$url$CALL_PATH" || status=$? if [[ $status -ne 0 ]]; then unexpected_answer call fi if [[ "$product" == messaging ]]; then - journey_http call --expect-status 200 --bearer token GET "$url/v1/messages/$message_id" || unexpected_answer call - jq -e --arg id "$message_id" '.id == $id' "$JOURNEY_STEP_STDOUT" >/dev/null || - journey_harness_failure "the message read did not return the submitted message" + jq -e --arg id "$message_id" '.links.self == ("/v1/messages/" + $id)' "$JOURNEY_STEP_STDOUT" >/dev/null || + journey_harness_failure "the starter message receipt did not identify its retained message" fi journey_pass call if [[ "$product" == messaging || ("$CALL_METHOD" == GET && -n "$PERSON") ]]; then @@ -703,6 +711,10 @@ walk_product() { documents_ready_matches "$documents_receipt" "$JOURNEY_STEP_STDOUT" || journey_harness_failure "the retained document no longer identifies the ready version" fi + if [[ "$product" == messaging ]]; then + jq -e --arg id "$KEEP_EXPECT" '.id == $id' "$JOURNEY_STEP_STDOUT" >/dev/null || + journey_harness_failure "the retained read did not return the distinct message sent before restart" + fi if [[ "$method" == GET && $first_read -eq 0 ]]; then journey_reached t1 fi diff --git a/products/platform/journeys/test_journey_tables.py b/products/platform/journeys/test_journey_tables.py index e289fc43a9..b10beeeccf 100644 --- a/products/platform/journeys/test_journey_tables.py +++ b/products/platform/journeys/test_journey_tables.py @@ -1121,16 +1121,16 @@ def walk(self, product, delivered): JOURNEY_STEP_STDOUT=$scratch/response.json if [[ "$CELL" == messaging ]]; then case "${@: -2:1} ${!#}" in - 'POST http://127.0.0.1:49192/v1/messages') - message_id=message-1 - printf '%s\n' 'submit message' >>"$trace" - ;; - 'GET http://127.0.0.1:49192/v1/messages/message-1') - printf '%s\n' 'read submitted message' >>"$trace" + 'POST http://127.0.0.1:49192/v1/messages/receipt') + [[ " $* " == *' Idempotency-Key: send-a-reminder-sms '* ]] + [[ " $* " == *' --concepts idempotency-key '* ]] + message_id=starter-message + printf '%s\n' 'read starter message receipt' >>"$trace" + jq -c . "$work/call-body.json" >>"$trace" ;; *) return 1 ;; esac - printf '%s\n' '{"id":"message-1"}' >"$JOURNEY_STEP_STDOUT" + printf '%s\n' '{"id":"starter-message","links":{"self":"/v1/messages/starter-message"}}' >"$JOURNEY_STEP_STDOUT" else printf '%s\n' '{}' >"$JOURNEY_STEP_STDOUT" fi @@ -1146,7 +1146,11 @@ def walk(self, product, delivered): ;; keep) printf '%s\n' 'read retained record' >>"$trace" - printf '%s\n' '{"recordId":"retained-id"}' >"$JOURNEY_STEP_STDOUT" + if [[ "$CELL" == messaging ]]; then + printf '%s\n' '{"id":"retained-id"}' >"$JOURNEY_STEP_STDOUT" + else + printf '%s\n' '{"recordId":"retained-id"}' >"$JOURNEY_STEP_STDOUT" + fi ;; *) return 1 ;; esac @@ -1197,11 +1201,16 @@ def test_starter_first_read_uses_four_reader_commands(self): self.assertIn(("plan", "pass"), outcomes) self.assertIn(("issuer", "pass"), outcomes) - def test_messaging_reads_the_submitted_message_before_restart(self): + def test_messaging_reads_the_starter_receipt_in_four_reader_commands(self): result, _, trace = self.walk("messaging", "first-hour") self.assertEqual(result.returncode, 0, result.stdout + result.stderr) - self.assertEqual(trace[:2], ["submit message", "read submitted message"]) - self.assertEqual(trace[-1], "5") + self.assertEqual(trace[0], "read starter message receipt") + example = REPO / "products/messaging/examples/starter/dev-journeys.yaml" + starter = yaml.safe_load(example.read_text(encoding="utf-8")) + journey = next(journey for journey in starter["journeys"] if journey["id"] == "send-a-reminder-sms") + self.assertEqual(json.loads(trace[1]), journey["steps"][0]["body"]) + self.assertEqual(trace[2], "write messaging") + self.assertEqual(trace[-1], "4") def test_evidence_first_read_uses_the_checked_start(self): result, outcomes, trace = self.walk("evidence", "first-hour") From 4d4f2bd93f00dccf9bea2910422d8f72d3bd7454 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 19:21:15 +0000 Subject: [PATCH 061/183] refactor(breg): select signed webhook transport centrally Signed-off-by: Jeremi Joslin (cherry picked from commit 17be1cc83ea08fcb66af2ba570f2055e35e6a532) --- crates/registry-breg/src/event_destination.rs | 114 ++++++++++++++++-- 1 file changed, 105 insertions(+), 9 deletions(-) diff --git a/crates/registry-breg/src/event_destination.rs b/crates/registry-breg/src/event_destination.rs index f8dd6096cf..942aea3859 100644 --- a/crates/registry-breg/src/event_destination.rs +++ b/crates/registry-breg/src/event_destination.rs @@ -17,10 +17,11 @@ use registry_platform_crypto::delivery_signature::{ use registry_platform_hooks::delivery::{UrlDestination, UrlDestinationParts}; use registry_platform_httputil::destination::{ DestinationDnsFamily, DestinationProfile, DestinationTlsMaterial, EventDestinationPolicy, - EventDestinationRequestTemplate, MAX_DESTINATION_PRIVATE_CIDRS, - MAX_DESTINATION_REQUEST_BODY_BYTES, MAX_DESTINATION_REQUEST_HEADER_BYTES, - MAX_DESTINATION_TARGET_BYTES, + EventDestinationRequestTemplate, MAX_DESTINATION_ORIGIN_URL_BYTES, + MAX_DESTINATION_PRIVATE_CIDRS, MAX_DESTINATION_REQUEST_BODY_BYTES, + MAX_DESTINATION_REQUEST_HEADER_BYTES, MAX_DESTINATION_TARGET_BYTES, }; +use registry_platform_httputil::select::{select_destination, TransportClass}; use serde::Deserialize; use serde_json::{json, Value}; use sha2::{Digest, Sha256}; @@ -472,7 +473,7 @@ impl EventDestinationConfig { let policy = EventDestinationPolicy::new_with_dns_family( logical_id, &self.origin, - self.network_profile.platform(), + self.network_profile.select(&self.origin)?, &self.allowed_private_cidrs, self.dns_family.platform(), ) @@ -632,13 +633,24 @@ impl<'de> Deserialize<'de> for EventDestinationNetworkProfile { } impl EventDestinationNetworkProfile { - fn platform(self) -> DestinationProfile { - match self { - Self::ProductionHttps => DestinationProfile::ProductionHttps, - Self::LoopbackHttp => DestinationProfile::LoopbackHttp, + fn select(self, origin: &str) -> ConfigResult { + let transport = match self { + Self::ProductionHttps => TransportClass::VerifiedTls, + Self::LoopbackHttp => TransportClass::LoopbackPlaintext, #[cfg(feature = "postgres-test")] - Self::PinnedLoopbackHttpsTest => DestinationProfile::PinnedLoopbackHttpsTest, + Self::PinnedLoopbackHttpsTest => { + return Ok(DestinationProfile::PinnedLoopbackHttpsTest) + } + }; + if origin.len() > MAX_DESTINATION_ORIGIN_URL_BYTES { + return Err(EventDestinationConfigError); } + let url = url::Url::parse(origin).map_err(|_| EventDestinationConfigError)?; + // The fixed policy keeps the authored origin and its existing DNS + // address-family and range constraints. + select_destination(&url, Some(transport), &[]) + .map(|selected| selected.profile()) + .map_err(|_| EventDestinationConfigError) } /// The word the binding digest is computed over. The digest is stored @@ -801,3 +813,87 @@ fn canonical_binding_digest(value: &Value) -> Result { canonicalize_json(value).map_err(|_| EventDestinationActivationError::InvalidBinding)?; Ok(format!("sha256:{}", hex::encode(Sha256::digest(canonical)))) } + +#[cfg(test)] +mod tests { + use super::*; + + fn configured_policy( + origin: &str, + profile: &str, + dns_family: &str, + cidrs: &[&str], + ) -> ConfigResult { + let binding = serde_json::from_value(json!({ + "origin": origin, + "path": "/events", + "networkProfile": profile, + "dnsFamily": dns_family, + "allowedPrivateCidrs": cidrs, + "hmacSha256KeyRef": "secret:file/hook-key", + "classificationCeiling": "internal", + "deliveryCeilings": { + "attemptTimeoutMilliseconds": 2500, + "maximumAttempts": 3, + }, + })) + .expect("a well-formed authored binding"); + EventDestinationConfig::from_raw("events", binding)?.platform_binding("events") + } + + #[test] + fn event_bindings_keep_their_configured_dns_family() { + let private_https = configured_policy( + "https://events.example/", + "production-https", + "ipv4-only", + &["10.42.0.0/24"], + ) + .expect("private HTTPS receiver with IPv4-only DNS"); + assert_eq!(private_https.dns_family(), DestinationDnsFamily::Ipv4Only); + + let loopback = configured_policy( + "http://[::1]:8100/", + "loopback-http", + "dual-stack-strict", + &[], + ) + .expect("loopback HTTP receiver"); + assert_eq!(loopback.dns_family(), DestinationDnsFamily::DualStackStrict); + } + + #[test] + fn event_bindings_refuse_mismatched_profiles_and_invalid_origins() { + for (origin, profile) in [ + ("http://10.42.0.2/", "loopback-http"), + ("http://127.0.0.1/", "production-https"), + ("https://127.0.0.1/", "loopback-http"), + ("https://localhost/", "production-https"), + ("https://events.example/unexpected", "production-https"), + ] { + assert!( + configured_policy(origin, profile, "dual-stack-strict", &["10.42.0.0/24"]).is_err(), + "{origin} using {profile}" + ); + } + assert!(configured_policy( + "https://events.example/", + "production-https", + "ipv4-only", + &["fd00::/8"], + ) + .is_err()); + } + + #[cfg(feature = "postgres-test")] + #[test] + fn pinned_test_profile_still_accepts_local_https() { + configured_policy( + "https://localhost:8100/", + "pinned-loopback-https-test", + "dual-stack-strict", + &[], + ) + .expect("native pinned TLS fixture binding"); + } +} From b7d442ceccfafbf3684e4622d62779b4979bd82d Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 19:38:23 +0000 Subject: [PATCH 062/183] fix(session): bind checked inventory to live sign-in routes Signed-off-by: Jeremi Joslin --- crates/registry-session/src/gateway/verify.rs | 61 +++++++--- crates/registry-session/src/schema.rs | 24 ++-- crates/registry-session/tests/binary.rs | 105 ++++++++++++------ .../run-a-project-with-rstack-dev.mdx | 3 +- .../src/content/docs/configure/session.mdx | 15 ++- .../src/content/docs/security/session.mdx | 7 +- .../examples/session/checked-routes.json | 15 ++- ...ssion-route-inventory.v1alpha1.schema.json | 47 ++++++-- 8 files changed, 197 insertions(+), 80 deletions(-) diff --git a/crates/registry-session/src/gateway/verify.rs b/crates/registry-session/src/gateway/verify.rs index 67258f23fa..1a7d7878ce 100644 --- a/crates/registry-session/src/gateway/verify.rs +++ b/crates/registry-session/src/gateway/verify.rs @@ -366,6 +366,7 @@ fn standalone_document( "@type": "type.googleapis.com/envoy.extensions.transport_sockets.tls.v3.DownstreamTlsContext", "common_tls_context": { "alpn_protocols": ["h2", "http/1.1"], + "tls_params": {"tls_minimum_protocol_version": "TLSv1_2"}, "tls_certificates": [{ "certificate_chain": {"filename": certificate}, "private_key": {"filename": key}, @@ -525,6 +526,7 @@ fn verify_checked_transport<'a>( if document != &wanted { return Err(refusal()); } + verify_document(&expected, document)?; Ok(tls) } @@ -614,10 +616,9 @@ pub fn verify_assembled( Ok(loaded.posture) } -/// Project the browser-facing routes only after verifying the same runtime and -/// assembly as the gateway checks. Upstream addresses and credentials are -/// absent. The operation catalogue and products still decide what a route can -/// call and who can call it. +/// Project the checked gateway routes without upstream addresses or credentials. +/// The selected module supplies the browser client binding. The product still +/// decides what a route can call and who can call it. pub fn write_verified_route_inventory( runtime_config: &Path, assembled: &Path, @@ -625,9 +626,7 @@ pub fn write_verified_route_inventory( selection: &str, posture: DeclaredPosture, ) -> Result { - let loaded = load_gateway_config(runtime_config, posture, true).map_err(|_| { - standalone_refusal("Supply a valid and literal Session runtime for checked route export.") - })?; + let loaded = load_gateway_config(runtime_config, posture, true)?; let config = &loaded.config; let assembly_bytes = read_assembly_bytes(assembled).map_err(|_| { standalone_refusal("Supply a readable, valid Envoy assembly for checked route export.") @@ -674,14 +673,18 @@ pub fn write_verified_route_inventory( "Select a disjoint BReg module prefix that rewrites to the product root.", )); } - if config.pages.iter().any(|page| { - !page - .prefix + let route_prefixes = config + .modules + .iter() + .map(|module| &module.prefix) + .chain(config.pages.iter().map(|page| &page.prefix)); + if route_prefixes.into_iter().any(|prefix| { + !prefix .bytes() .all(|byte| byte.is_ascii_alphanumeric() || b"/._:~-".contains(&byte)) }) { return Err(standalone_refusal( - "Use checked page prefixes made of letters, digits, or /._:~-.", + "Use checked route prefixes made of letters, digits, or /._:~-.", )); } if config.pages.iter().any(|page| { @@ -697,26 +700,50 @@ pub fn write_verified_route_inventory( .sign_ins .iter() .map(|entry| entry.id.as_str()) - .filter(|id| module.admits(id)) .collect::>(); - if sign_ins.is_empty() || sign_ins.len() > 64 || config.pages.len() > 64 { + if !sign_ins.iter().any(|id| module.admits(id)) + || sign_ins.len() > 64 + || config.pages.len() > 64 + || config.modules.len() > 64 + { return Err(standalone_refusal( - "Checked routes require one to 64 admitted sign-in kinds and at most 64 pages.", + "Checked routes require an admitted sign-in and at most 64 sign-ins, modules and pages.", )); } - let modules = [ - json!({"id": module.id.as_str(), "product": "breg", "prefix": module.prefix, "prefixRewrite": rewrite, "signIns": sign_ins}), - ]; + let modules: Vec<_> = config + .modules + .iter() + .map(|module| { + let admitted: Vec<_> = sign_ins.iter().filter(|id| module.admits(id)).collect(); + let mut route = + json!({"id": module.id.as_str(), "prefix": module.prefix, "signIns": admitted}); + if let Some(product) = module.product { + route["product"] = json!(product.as_str()); + } + if let Some(rewrite) = module + .upstream + .as_ref() + .and_then(|upstream| upstream.prefix_rewrite.as_ref()) + { + route["prefixRewrite"] = json!(rewrite.as_str()); + } + route + }) + .collect(); let pages: Vec<_> = config .pages .iter() .map(|page| json!({"prefix": page.prefix, "signIn": page.sign_in.as_str()})) .collect(); + let projection = serde_json::to_vec(&json!({"modules": modules, "pages": pages})) + .map_err(|_| standalone_refusal("Could not serialize the sign-in projection."))?; let inventory = json!({ "apiVersion": ROUTE_INVENTORY_API_VERSION, "kind": ROUTE_INVENTORY_KIND, "publicOrigin": config.public_origin.as_str().trim_end_matches('/'), "gatewayDigest": sha256_uri(&assembly_bytes), + "signInDigest": sha256_uri(&projection), + "selectedModule": selection, "modules": modules, "pages": pages, }); diff --git a/crates/registry-session/src/schema.rs b/crates/registry-session/src/schema.rs index 14cf1dbabf..c74649b04f 100644 --- a/crates/registry-session/src/schema.rs +++ b/crates/registry-session/src/schema.rs @@ -13,8 +13,8 @@ use schemars::{json_schema, JsonSchema, Schema, SchemaGenerator}; use serde_json::{json, Value}; use crate::config::{ - Authority, ClaimName, ClusterName, FilterName, HostName, ModuleAudience, ResourceUri, - RewritePrefix, RuntimeConfig, ScopeToken, RUNTIME_API_VERSION, RUNTIME_KIND, + Authority, ClaimName, ClusterName, FilterName, HostName, ModuleAudience, ModuleProduct, + ResourceUri, RewritePrefix, RuntimeConfig, ScopeToken, RUNTIME_API_VERSION, RUNTIME_KIND, }; use crate::gateway::{ROUTE_INVENTORY_API_VERSION, ROUTE_INVENTORY_KIND}; @@ -64,6 +64,8 @@ fn route_inventory_schema() -> Value { let mut generator = SchemaSettings::draft2020_12().into_generator(); let id = generator.subschema_for::(); let digest = generator.subschema_for::(); + let product = generator.subschema_for::(); + let rewrite = generator.subschema_for::(); let mut origin = json!(generator.subschema_for::()); origin["pattern"] = json!("^https://127(?:\\.[0-9]{1,3}){3}(?::[0-9]{1,5})?$"); json!({ @@ -71,26 +73,28 @@ fn route_inventory_schema() -> Value { "$id": ROUTE_INVENTORY_SCHEMA_ID, "$defs": generator.take_definitions(true), "title": "Checked Registry Session route inventory", - "description": "One Base Registry Engine browser route and its page bindings from an exact, verified Envoy JSON file.", + "description": "Every configured module and page in a verified Envoy assembly, with one selected Base Registry Engine browser binding. Routes use the longest matching prefix at a path segment boundary.", "type": "object", "additionalProperties": false, - "required": ["apiVersion", "kind", "publicOrigin", "gatewayDigest", "modules", "pages"], + "required": ["apiVersion", "kind", "publicOrigin", "gatewayDigest", "signInDigest", "selectedModule", "modules", "pages"], "properties": { "apiVersion": {"type": "string", "const": ROUTE_INVENTORY_API_VERSION}, "kind": {"type": "string", "const": ROUTE_INVENTORY_KIND}, "publicOrigin": origin, "gatewayDigest": digest, + "signInDigest": digest, + "selectedModule": id, "modules": { - "type": "array", "minItems": 1, "maxItems": 1, + "type": "array", "minItems": 1, "maxItems": 64, "uniqueItems": true, "items": { "type": "object", "additionalProperties": false, - "required": ["id", "product", "prefix", "prefixRewrite", "signIns"], + "required": ["id", "prefix", "signIns"], "properties": { "id": id, - "product": {"type": "string", "const": "breg"}, - "prefix": {"type": "string", "maxLength": 256, "pattern": "^/(?:(?!\\.\\.?/)[A-Za-z0-9._:-]+/)+$"}, - "prefixRewrite": {"type": "string", "const": "/"}, - "signIns": {"type": "array", "minItems": 1, "maxItems": 64, "uniqueItems": true, "items": id} + "product": product, + "prefix": {"type": "string", "maxLength": 256, "pattern": "^/(?:(?!\\.\\.?(?:/|$))[A-Za-z0-9._:~-]+(?:/|$))+$"}, + "prefixRewrite": rewrite, + "signIns": {"type": "array", "maxItems": 64, "uniqueItems": true, "items": id} } } }, diff --git a/crates/registry-session/tests/binary.rs b/crates/registry-session/tests/binary.rs index 5f341e2830..2ac341ce30 100644 --- a/crates/registry-session/tests/binary.rs +++ b/crates/registry-session/tests/binary.rs @@ -277,8 +277,16 @@ fn gateway_writes_a_deterministic_checked_standalone_configuration() { fn gateway_inventory_requires_the_exact_verified_assembly() { let root = tempfile::tempdir().expect("directory"); let runtime = root.path().join("runtime.yaml"); - let runtime_source = - standalone_runtime().replace("https://app.example", "https://127.0.0.1:8080"); + let runtime_source = standalone_runtime() + .replace("https://app.example", "https://127.0.0.1:8080") + .replace( + "session:\n", + " reviewer:\n clientId: reviewer-app\n clientSecretRef: secret:file/reviewer-secret\n scopes: [registry:read]\nsession:\n", + ) + .replace( + "pages:\n", + " - id: functions\n product: breg\n prefix: /api/functions/\n audience: person\n upstream: {cluster: functions, prefixRewrite: /functions/}\npages:\n", + ); std::fs::write(&runtime, &runtime_source).expect("runtime"); let assembly = root.path().join("envoy.json"); let routes = root.path().join("routes.json"); @@ -296,37 +304,51 @@ fn gateway_inventory_requires_the_exact_verified_assembly() { ) }; let verify = || export(&routes); - generate_standalone(&runtime, &assembly); - assert_eq!(verify().0, 1, "ordinary plaintext assembly must not export"); - assert!(!routes.exists()); - - let assemble = || { - run_command( - runtime_command(&runtime) - .args(["gateway", "envoy", "--standalone-out"]) - .arg(&assembly) - .args([ - "--listen", - "127.0.0.1:8080", - "--upstream", - "registry=127.0.0.1:8100", - "--upstream", - "pages=127.0.0.1:8200", - ]) + let assemble = |tls| { + let mut command = runtime_command(&runtime); + command + .args(["gateway", "envoy", "--standalone-out"]) + .arg(&assembly) + .args([ + "--listen", + "127.0.0.1:8080", + "--upstream", + "registry=127.0.0.1:8100", + "--upstream", + "pages=127.0.0.1:8200", + "--upstream", + "functions=127.0.0.1:8300", + ]); + if tls { + command .arg("--tls-certificate") .arg(&certificate) .arg("--tls-key") - .arg(&key), - ) + .arg(&key); + } + run_command(&mut command) }; - let (exit, _, stderr) = assemble(); + assert_eq!(assemble(false).0, 0); + assert_eq!(verify().0, 1, "ordinary plaintext assembly must not export"); + assert!(!routes.exists()); + let (exit, _, stderr) = assemble(true); assert_eq!(exit, 0, "{stderr}"); + let assembled: serde_json::Value = + serde_json::from_slice(&std::fs::read(&assembly).expect("assembly")).expect("Envoy JSON"); + assert_eq!( + assembled.pointer(concat!( + "/static_resources/listeners/0/filter_chains/0/transport_socket/typed_config", + "/common_tls_context/tls_params/tls_minimum_protocol_version" + )), + Some(&json!("TLSv1_2")) + ); let (exit, _, stderr) = verify(); assert_eq!(exit, 0, "{stderr}"); let first = std::fs::read(&routes).expect("route inventory"); let inventory: serde_json::Value = serde_json::from_slice(&first).expect("JSON inventory"); assert_eq!(inventory["kind"], "PlatformSessionRouteInventory"); assert_eq!(inventory["publicOrigin"], "https://127.0.0.1:8080"); + assert_eq!(inventory["selectedModule"], "breg"); let digest = |file: &std::path::Path| { let bytes = std::fs::read(file).expect("assembly bytes"); registry_platform_config::sha256_uri(&bytes) @@ -349,13 +371,12 @@ fn gateway_inventory_requires_the_exact_verified_assembly() { } assert_eq!( inventory["modules"], - json!([{ - "id": "breg", - "product": "breg", - "prefix": "/api/registry/", - "prefixRewrite": "/", - "signIns": ["citizen"] - }]) + json!([ + {"id": "breg", "product": "breg", "prefix": "/api/registry/", + "prefixRewrite": "/", "signIns": ["citizen", "reviewer"]}, + {"id": "functions", "product": "breg", "prefix": "/api/functions/", + "prefixRewrite": "/functions/", "signIns": ["citizen", "reviewer"]} + ]) ); assert_eq!( inventory["pages"], @@ -377,12 +398,25 @@ fn gateway_inventory_requires_the_exact_verified_assembly() { assert_eq!(exit, 0, "{stderr}"); assert_eq!(std::fs::read(&routes).expect("regenerated routes"), first); + let changed_sign_in = runtime_source.replace(" signIn: citizen", " signIn: reviewer"); + assert_ne!(changed_sign_in, runtime_source); + std::fs::write(&runtime, changed_sign_in).expect("changed sign-in"); + assert_eq!(verify().0, 0); + let changed: serde_json::Value = + serde_json::from_slice(&std::fs::read(&routes).expect("updated inventory")).unwrap(); + assert_eq!(changed["gatewayDigest"], inventory["gatewayDigest"]); + assert_ne!(changed["signInDigest"], inventory["signInDigest"]); + assert_eq!(changed["pages"][0]["signIn"], "reviewer"); + std::fs::write(&runtime, &runtime_source).expect("restore literal test fixture"); + assert_eq!(verify().0, 0); + assert_eq!(std::fs::read(&routes).expect("restored inventory"), first); + for (field, deferred) in [ ( "module sign-ins", runtime_source.replace( " audience: person\n", - " audience: person\n signIns: [citizen, '${MODULE_SIGN_IN}']\n", + " audience: person\n signIns: [citizen, reviewer, '${MODULE_SIGN_IN}']\n", ), ), ( @@ -392,7 +426,14 @@ fn gateway_inventory_requires_the_exact_verified_assembly() { ] { assert_ne!(deferred, runtime_source); std::fs::write(&runtime, deferred).expect("deferred runtime"); - assert_eq!(verify().0, 1, "refuse deferred {field}"); + let (exit, _, error) = verify(); + assert_eq!(exit, 1, "refuse deferred {field}"); + let pointer = if field == "module sign-ins" { + "/modules/0/signIns" + } else { + "/pages/0/signIn" + }; + assert!(error.contains(pointer), "{error}"); assert_eq!(std::fs::read(&routes).expect("retained inventory"), first); } std::fs::write(&runtime, &runtime_source).expect("restore literal test fixture"); @@ -458,7 +499,7 @@ fn gateway_inventory_requires_the_exact_verified_assembly() { let unsafe_page = runtime_source.replace("/apply/", "/apply;/"); assert_ne!(unsafe_page, runtime_source); std::fs::write(&runtime, unsafe_page).expect("runtime with broader page prefix"); - let (exit, _, stderr) = assemble(); + let (exit, _, stderr) = assemble(true); assert_eq!(exit, 0, "{stderr}"); assert_eq!(verify().0, 1, "refuse a page path that live checks reject"); assert_eq!(std::fs::read(&routes).expect("retained inventory"), first); diff --git a/docs/site/src/content/docs/configure/run-a-project-with-rstack-dev.mdx b/docs/site/src/content/docs/configure/run-a-project-with-rstack-dev.mdx index 5420601f5f..b8867b6ab0 100644 --- a/docs/site/src/content/docs/configure/run-a-project-with-rstack-dev.mdx +++ b/docs/site/src/content/docs/configure/run-a-project-with-rstack-dev.mdx @@ -516,7 +516,8 @@ Put the issuer's JWKS endpoint in `externalJwksUri` on the same numeric loopback Set `statusUrl` to the Casework loopback origin and `tokenEndpoint` to the external issuer's token endpoint. Set `statusClient` to its separate status reader, `statusKeyRef` to its owner-only key -under `fixture/` and `statusResource` to the reader's Casework resource. Run `rstack dev check` +under `fixture/` and `statusResource` to the reader's Casework resource. If the run also attaches a +Base Registry Engine task grant, register a separate status client and key for each product. Run `rstack dev check` before `rstack dev start`. Scheduling checks the grant's current status with Casework before booking and refuses the operation if it cannot verify that status. diff --git a/docs/site/src/content/docs/configure/session.mdx b/docs/site/src/content/docs/configure/session.mdx index 46d48ebb99..8f9c1cc302 100644 --- a/docs/site/src/content/docs/configure/session.mdx +++ b/docs/site/src/content/docs/configure/session.mdx @@ -296,12 +296,15 @@ registry-session --runtime-config /etc/registry-session/runtime.yaml gateway env --checked-route breg ``` -The export checks the standalone Envoy JSON and records the selected BReg product route, -its admitted sign-in kinds and the page bindings. Write the sign-in names literally and keep -page paths to letters, digits and `/._:~-`. -The `gatewayDigest` is SHA-256 over the exact Envoy JSON file bytes, including whitespace. -Use the inventory with those bytes. Envoy and Session check live requests, and the product -authorizes the operation. +The export records every configured module and page with its sign-in bindings. It names the +selected BReg module for browser client generation. Routes use the longest matching prefix +at a path segment boundary. Write sign-in names literally and keep the route paths to +letters, digits and `/._:~-`. + +The `gatewayDigest` covers the exact Envoy JSON file bytes, including whitespace. The +`signInDigest` covers the module and page sign-in projection. Both use SHA-256. Re-export +after a runtime change and deploy the checked assembly with its matching runtime file. +Envoy and Session check live requests, and the product authorizes the operation. {/* Evidence: crates/registry-session/src/gateway/verify.rs, validate_checked_transport, verify_checked_transport, write_verified_route_inventory; diff --git a/docs/site/src/content/docs/security/session.mdx b/docs/site/src/content/docs/security/session.mdx index 20ebaae20f..799cad9775 100644 --- a/docs/site/src/content/docs/security/session.mdx +++ b/docs/site/src/content/docs/security/session.mdx @@ -5,7 +5,7 @@ status: current owner: registry-docs source_repos: - registry-stack -last_reviewed: "2026-11-27" +last_reviewed: "2026-12-01" doc_type: explanation locale: en standards_referenced: [] @@ -78,12 +78,17 @@ A module's `signIns` list routes kinds of sessions, but grants no product permis A private bind alone does not establish that restriction. 4. Regenerate the gateway fragments after every runtime change. Splice them and verify the assembled static configuration before deploying it. + For a checked standalone assembly, regenerate the assembly and re-export the inventory after + every runtime change. The inventory describes every configured module and page and names one + selected browser binding. Its two digests bind the Envoy JSON bytes and the sign-in projection. + Envoy and Session enforce the live routing and sign-in policy. 5. Terminate TLS in front of the public listener. The service accepts `development-loopback` only in development posture. Use it for local HTTP in a browser that supports `Secure` cookies on loopback. For checked browser route export, use the dedicated loopback HTTPS Envoy assembly and deploy the verified configuration. The browser verifies the ingress certificate. The operator controls the gateway namespace, private Session sockets and upstream endpoints. + The standalone HTTPS assembly requires TLS 1.2 or later. 6. Name every host HTTP filter in `gateway.hostFilters`. Retain a filter on a module or page only through `upstream.keepHostFilters`. A retained filter must preserve the path, route cache and authorisation header. diff --git a/products/platform/examples/session/checked-routes.json b/products/platform/examples/session/checked-routes.json index 3b2033bfae..8bfb0ee170 100644 --- a/products/platform/examples/session/checked-routes.json +++ b/products/platform/examples/session/checked-routes.json @@ -1,6 +1,6 @@ { "apiVersion": "id.registrystack.org/formats/platform/session-route-inventory/v1alpha1", - "gatewayDigest": "sha256:56635e6d5a33bb8026b95d06912c4be2a9e725ce66b389126830c3c31d69bcae", + "gatewayDigest": "sha256:32c5a92f7b5f7f446b196f96cfab1d856a395cb8587be13dc44de4330ea95091", "kind": "PlatformSessionRouteInventory", "modules": [ { @@ -11,6 +11,15 @@ "signIns": [ "registrar" ] + }, + { + "id": "functions", + "prefix": "/api/functions/", + "prefixRewrite": "/functions/", + "product": "breg", + "signIns": [ + "registrar" + ] } ], "pages": [ @@ -19,5 +28,7 @@ "signIn": "registrar" } ], - "publicOrigin": "https://127.0.0.1:8443" + "publicOrigin": "https://127.0.0.1:8443", + "selectedModule": "businesses", + "signInDigest": "sha256:7c31878d23b2a2d12e0766bafa78f8c220d4d05481b1dcc36650030095552ce9" } diff --git a/products/platform/generated/session-runtime/session-route-inventory.v1alpha1.schema.json b/products/platform/generated/session-runtime/session-route-inventory.v1alpha1.schema.json index 2fecc18432..c43ded35a7 100644 --- a/products/platform/generated/session-runtime/session-route-inventory.v1alpha1.schema.json +++ b/products/platform/generated/session-runtime/session-route-inventory.v1alpha1.schema.json @@ -10,6 +10,27 @@ "pattern": "^[a-z][a-z0-9_-]{0,63}$", "type": "string" }, + "ModuleProduct": { + "description": "Maintained products a module can declare, independent of the module's id.", + "enum": [ + "adapter", + "breg", + "casework", + "coordinator", + "documents", + "evidence", + "messaging", + "render", + "scheduling" + ], + "type": "string" + }, + "RewritePrefix": { + "maxLength": 256, + "minLength": 1, + "pattern": "^/(?!.*[%\\\\?#])[!-~]*$", + "type": "string" + }, "Url": { "description": "An absolute http or https URL with a host preserved as written, no user information, and no backslash, whitespace or control character. DNS case and equivalent IPv6 literals are permitted.", "format": "uri", @@ -21,7 +42,7 @@ "$id": "https://id.registrystack.org/schemas/platform/session-route-inventory/session-route-inventory.v1alpha1.schema.json", "$schema": "https://json-schema.org/draft/2020-12/schema", "additionalProperties": false, - "description": "One Base Registry Engine browser route and its page bindings from an exact, verified Envoy JSON file.", + "description": "Every configured module and page in a verified Envoy assembly, with one selected Base Registry Engine browser binding. Routes use the longest matching prefix at a path segment boundary.", "properties": { "apiVersion": { "const": "id.registrystack.org/formats/platform/session-route-inventory/v1alpha1", @@ -43,39 +64,35 @@ }, "prefix": { "maxLength": 256, - "pattern": "^/(?:(?!\\.\\.?/)[A-Za-z0-9._:-]+/)+$", + "pattern": "^/(?:(?!\\.\\.?(?:/|$))[A-Za-z0-9._:~-]+(?:/|$))+$", "type": "string" }, "prefixRewrite": { - "const": "/", - "type": "string" + "$ref": "#/$defs/RewritePrefix" }, "product": { - "const": "breg", - "type": "string" + "$ref": "#/$defs/ModuleProduct" }, "signIns": { "items": { "$ref": "#/$defs/LocalId" }, "maxItems": 64, - "minItems": 1, "type": "array", "uniqueItems": true } }, "required": [ "id", - "product", "prefix", - "prefixRewrite", "signIns" ], "type": "object" }, - "maxItems": 1, + "maxItems": 64, "minItems": 1, - "type": "array" + "type": "array", + "uniqueItems": true }, "pages": { "items": { @@ -103,6 +120,12 @@ "publicOrigin": { "$ref": "#/$defs/Url", "pattern": "^https://127(?:\\.[0-9]{1,3}){3}(?::[0-9]{1,5})?$" + }, + "selectedModule": { + "$ref": "#/$defs/LocalId" + }, + "signInDigest": { + "$ref": "#/$defs/Digest" } }, "required": [ @@ -110,6 +133,8 @@ "kind", "publicOrigin", "gatewayDigest", + "signInDigest", + "selectedModule", "modules", "pages" ], From cb1525697b4b4ab8fcacc00d00d07c77662b74b5 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 19:38:23 +0000 Subject: [PATCH 063/183] fix(rstack): separate Scheduling and BReg status credentials Signed-off-by: Jeremi Joslin --- .../registry-rstack-dev/src/external_breg.rs | 93 +++++++++++++++++++ crates/registry-rstack-dev/src/plan.rs | 9 ++ 2 files changed, 102 insertions(+) diff --git a/crates/registry-rstack-dev/src/external_breg.rs b/crates/registry-rstack-dev/src/external_breg.rs index 0d5740e67b..f1065ab0f5 100644 --- a/crates/registry-rstack-dev/src/external_breg.rs +++ b/crates/registry-rstack-dev/src/external_breg.rs @@ -3,6 +3,7 @@ use anyhow::{ensure, Context, Result}; use registry_platform_config::{SecretProvider, SecretReference}; +use registry_platform_crypto::PrivateJwk; use registry_platform_yaml::{BoundedU32, LocalId, Url}; use serde::{Deserialize, Serialize}; use serde_json::{json, Value}; @@ -73,6 +74,33 @@ pub(super) struct TaskGrant { } impl TaskGrant { + pub(super) fn require_distinct_status(&self, other: &Self, root: &Path) -> SemanticResult<()> { + require( + self.status_client != other.status_client, + "/externalScheduling/taskGrant/statusClient", + "Scheduling and BReg must use different task status clients.", + "Register a separate Scheduling task status client.", + )?; + let canonical = root.canonicalize().ok(); + let thumbprint = |reference| { + let key = private_fixture(canonical.as_deref()?, reference).ok()?; + PrivateJwk::parse(std::str::from_utf8(&key).ok()?) + .ok()? + .public() + .jkt() + .ok() + }; + let distinct = thumbprint(&self.status_key_ref) + .zip(thumbprint(&other.status_key_ref)) + .is_some_and(|(scheduling, breg)| scheduling != breg); + require( + distinct, + "/externalScheduling/taskGrant/statusKeyRef", + "Scheduling and BReg need valid, distinct private JWKs for task status.", + "Use a separate owner-only key for each task status client.", + ) + } + pub(super) fn validate_for_scheduling( &self, root: &Path, @@ -387,8 +415,73 @@ fn require_loopback_endpoint(field: &str, value: &str) -> SemanticResult<()> { #[cfg(test)] mod tests { use super::*; + use registry_platform_crypto::{generate_private_jwk, GeneratedKeyAlgorithm}; use std::{fs, os::unix::fs::PermissionsExt}; + #[test] + fn scheduling_and_breg_status_clients_and_signing_keys_are_separate() { + let directory = tempfile::tempdir().unwrap(); + let root = directory.path().canonicalize().unwrap(); + std::fs::create_dir(root.join("fixture")).unwrap(); + let key = generate_private_jwk(GeneratedKeyAlgorithm::Ed25519).unwrap(); + let mut same_key = key.clone(); + same_key.kid = Some("renamed-key".to_owned()); + let different_key = generate_private_jwk(GeneratedKeyAlgorithm::Ed25519).unwrap(); + for (path, key) in [ + ("breg-key", key), + ("same-key", same_key), + ("scheduling-key", different_key), + ] { + #[derive(Serialize)] + struct FixtureKey<'a> { + kty: &'a str, + kid: &'a str, + alg: &'a str, + crv: &'a str, + x: &'a str, + d: &'a str, + } + let fixture = FixtureKey { + kty: &key.kty, + kid: key.kid.as_deref().unwrap(), + alg: key.alg.as_deref().unwrap(), + crv: key.crv.as_deref().unwrap(), + x: key.x.as_deref().unwrap(), + d: key.d.as_deref().unwrap(), + }; + let bytes = Zeroizing::new(serde_json::to_vec(&fixture).unwrap()); + crate::write_private(&root.join("fixture").join(path), &bytes).unwrap(); + } + let grant = |client, name| -> TaskGrant { + serde_json::from_value(json!({ + "sourceIssuer": "https://casework.journey.example", + "assertionClient": "task-agent", + "statusUrl": "http://127.0.0.1:41001", + "tokenEndpoint": "http://127.0.0.1:41000/oauth2/token", + "statusClient": client, + "statusKeyRef": format!("secret:file/{name}"), + "statusResource": "urn:example:journey:casework" + })) + .unwrap() + }; + let breg = grant("breg-status", "breg-key"); + for (client, file, field) in [ + ("breg-status", "scheduling-key", "statusClient"), + ("scheduling-status", "breg-key", "statusKeyRef"), + ("scheduling-status", "same-key", "statusKeyRef"), + ] { + let refusal = grant(client, file) + .require_distinct_status(&breg, &root) + .unwrap_err(); + assert!(refusal + .to_string() + .starts_with(&format!("dev.yaml /externalScheduling/taskGrant/{field}:"))); + } + grant("scheduling-status", "scheduling-key") + .require_distinct_status(&breg, &root) + .unwrap(); + } + #[test] fn fixture_keys_refuse_group_access_symlinks_and_paths_outside_the_project() { let scratch = tempfile::tempdir().unwrap(); diff --git a/crates/registry-rstack-dev/src/plan.rs b/crates/registry-rstack-dev/src/plan.rs index b8ea7566e4..d139fc1254 100644 --- a/crates/registry-rstack-dev/src/plan.rs +++ b/crates/registry-rstack-dev/src/plan.rs @@ -1381,6 +1381,15 @@ impl Plan { self, &scheduling.expect("validated Scheduling product").audience, )?; + if let Some(breg_grant) = self + .external_breg + .as_ref() + .and_then(|breg| breg.task_grant.as_ref()) + { + binding + .task_grant + .require_distinct_status(breg_grant, root)?; + } } require( (self.issuer != "run" From 9cfbbdd792a04a8b11a76a958bedb7e14ce71b08 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 19:36:15 +0000 Subject: [PATCH 064/183] test(journeys): exercise managed BReg Compose attachments Signed-off-by: Jeremi Joslin (cherry picked from commit ed6436c0f1a28bf53ef56a2fc0bb55142e014ce5) --- products/platform/journeys/lib.sh | 25 +++ products/platform/journeys/own-provider.sh | 25 --- .../projects/check-private-postgres.py | 32 ++++ .../journeys/projects/hook-receiver.py | 6 +- .../projects/rstack-attachments.compose.yaml | 29 ++++ .../journeys/projects/rstack-attachments.sh | 157 ++++++++++++++++++ products/platform/journeys/rstack-dev.sh | 46 ++++- .../platform/journeys/test_journey_tables.py | 56 ++++++- 8 files changed, 338 insertions(+), 38 deletions(-) create mode 100644 products/platform/journeys/projects/check-private-postgres.py create mode 100644 products/platform/journeys/projects/rstack-attachments.compose.yaml create mode 100644 products/platform/journeys/projects/rstack-attachments.sh diff --git a/products/platform/journeys/lib.sh b/products/platform/journeys/lib.sh index a96c13d074..95bfb155ee 100644 --- a/products/platform/journeys/lib.sh +++ b/products/platform/journeys/lib.sh @@ -1772,6 +1772,31 @@ journey_request_contract() { done } +# assert_signed_hook_acceptance LOG_FILE EXPECTED_PATH EXPECTED_TYPE: verify +# the hook receiver logged one value-free acceptance record proving Standard +# Webhooks HMAC-SHA256 receiver authority without inbound credential headers. +assert_signed_hook_acceptance() { + local log_file=$1 expected_path=$2 expected_type=$3 + # shellcheck disable=SC2016 # jq binds its own variables + jq -e -s --arg path "$expected_path" --arg type "$expected_type" ' + length == 1 + and (.[0] | + .event == "signed-hook-accepted" + and .path == $path + and .eventType == $type + and .signatureVerified == true + and .receiverAuthority == "standard-webhooks-hmac-sha256" + and .inboundCredentialHeaders == false + and (.headerNames | type == "array") + and (.headerNames | index("webhook-signature") != null) + and (.headerNames | index("authorization") == null) + and (.headerNames | index("registry-source-authorization") == null) + and (.headerNames | index("proxy-authorization") == null) + and (.headerNames | index("cookie") == null) + ) + ' "$log_file" >/dev/null +} + # The managed sink authenticates the delivery. Correlate its captured envelope # and signing headers to the operation, without accepting forwarded credentials. signed_hook_matches() { diff --git a/products/platform/journeys/own-provider.sh b/products/platform/journeys/own-provider.sh index 4c57637193..39f4c33f9f 100755 --- a/products/platform/journeys/own-provider.sh +++ b/products/platform/journeys/own-provider.sh @@ -2198,31 +2198,6 @@ step_call() { CELL_OVER=1 } -# assert_signed_hook_acceptance LOG_FILE EXPECTED_PATH EXPECTED_TYPE: verify -# the hook receiver logged one value-free acceptance record proving Standard -# Webhooks HMAC-SHA256 receiver authority without inbound credential headers. -assert_signed_hook_acceptance() { - local log_file=$1 expected_path=$2 expected_type=$3 - # shellcheck disable=SC2016 # jq binds its own variables - jq -e -s --arg path "$expected_path" --arg type "$expected_type" ' - length == 1 - and (.[0] | - .event == "signed-hook-accepted" - and .path == $path - and .eventType == $type - and .signatureVerified == true - and .receiverAuthority == "standard-webhooks-hmac-sha256" - and .inboundCredentialHeaders == false - and (.headerNames | type == "array") - and (.headerNames | index("webhook-signature") != null) - and (.headerNames | index("authorization") == null) - and (.headerNames | index("registry-source-authorization") == null) - and (.headerNames | index("proxy-authorization") == null) - and (.headerNames | index("cookie") == null) - ) - ' "$log_file" >/dev/null -} - # assert_wrong_agent_grant_refused ISSUER_BIN TID_ROOT TASK_CONN CLIENT GRANT_ID: # run `journey-issuer grant` for an unintended agent and succeed only when it # exits non-zero, emits no stdout or header file, and reports the exact diff --git a/products/platform/journeys/projects/check-private-postgres.py b/products/platform/journeys/projects/check-private-postgres.py new file mode 100644 index 0000000000..ec575be2e5 --- /dev/null +++ b/products/platform/journeys/projects/check-private-postgres.py @@ -0,0 +1,32 @@ +"""Check both BReg child URL references without reporting credential values.""" + +import json +import sys +from pathlib import Path +from urllib.parse import parse_qs, urlsplit + + +def check(config_path, address): + config = json.loads(config_path.read_text(encoding="utf-8")) + database = config["database"] + if database["transport"] != "private-network-plaintext": + raise ValueError("unexpected PostgreSQL transport") + root = Path(config["secretProviders"]["file"]["root"]).resolve(strict=True) + for role in ("runtime", "migration"): + prefix, name = database[role + "UrlRef"].rsplit("/", 1) + if prefix != "secret:file" or not name: + raise ValueError("expected a local file reference for each database role") + secret = (root / name).resolve(strict=True) + if secret.parent != root: + raise ValueError("database URL file must be inside the run's secret directory") + url = urlsplit(secret.read_text(encoding="utf-8").strip()) + if url.hostname != address or url.port != 5432 or parse_qs(url.query) != {"sslmode": ["disable"]}: + raise ValueError("database role did not pin the expected private endpoint and transport") + + +if __name__ == "__main__": + try: + check(Path(sys.argv[1]), sys.argv[2]) + except (OSError, KeyError, TypeError, ValueError): + raise SystemExit("BReg's generated PostgreSQL roles did not use the checked private Compose transport") from None + print(json.dumps({"transport": "private-network-plaintext", "rolesPinned": ["runtime", "migration"]})) diff --git a/products/platform/journeys/projects/hook-receiver.py b/products/platform/journeys/projects/hook-receiver.py index 3d7a7a2295..fdacbbb3f3 100644 --- a/products/platform/journeys/projects/hook-receiver.py +++ b/products/platform/journeys/projects/hook-receiver.py @@ -62,7 +62,9 @@ def verify_signed_delivery(path, expected_path, headers, body, key, expected_typ return 204, record -def main(port, expected_path, expected_type, key_path, receipt): +def main(port, expected_path, expected_type, key_path, receipt, bind_address="127.0.0.1"): + if bind_address not in ("127.0.0.1", "0.0.0.0"): + raise SystemExit("receiver must bind loopback or the Compose container interface") key = Path(key_path).read_bytes() path = Path(receipt) @@ -105,7 +107,7 @@ def do_POST(self): pending.replace(path) self.reply(204) - with HTTPServer(("127.0.0.1", int(port)), Receiver) as server: + with HTTPServer((bind_address, int(port)), Receiver) as server: server.serve_forever() diff --git a/products/platform/journeys/projects/rstack-attachments.compose.yaml b/products/platform/journeys/projects/rstack-attachments.compose.yaml new file mode 100644 index 0000000000..37b93f249f --- /dev/null +++ b/products/platform/journeys/projects/rstack-attachments.compose.yaml @@ -0,0 +1,29 @@ +services: + db: + image: postgres:18.7@sha256:e754b839f447639b7004895f4d8a4bfcb4e9dbe3a1bc035f27f646562a16fd61 + pull_policy: never + environment: + POSTGRES_PASSWORD_FILE: /run/secrets/db-password + secrets: [db-password] + healthcheck: + test: [CMD, pg_isready, --host, 127.0.0.1, --username, postgres] + interval: 1s + timeout: 1s + retries: 20 + tmpfs: [/var/lib/postgresql] + receiver: + image: mcr.microsoft.com/playwright:v1.60.0-noble@sha256:9bd26ad900bb5e0f4dee75839e957a89ae89c2b7ab1e76050e559790e946b948 + pull_policy: never + user: "${RSTACK_JOURNEY_RECEIVER_USER:?}" + entrypoint: [python3, /receiver.py] + command: ["8109", /events, contact-created, /run/secrets/hook-key, /receipts/event.json, "0.0.0.0"] + ports: ["127.0.0.1::8109"] + volumes: + - "${RSTACK_JOURNEY_RECEIVER_SCRIPT:?}:/receiver.py:ro" + - "${RSTACK_JOURNEY_RECEIVER_RECEIPTS:?}:/receipts" + secrets: [hook-key] +secrets: + db-password: + file: "${RSTACK_JOURNEY_DB_PASSWORD_FILE:?}" + hook-key: + file: "${RSTACK_JOURNEY_HOOK_KEY_FILE:?}" diff --git a/products/platform/journeys/projects/rstack-attachments.sh b/products/platform/journeys/projects/rstack-attachments.sh new file mode 100644 index 0000000000..8ec8e27614 --- /dev/null +++ b/products/platform/journeys/projects/rstack-attachments.sh @@ -0,0 +1,157 @@ +#!/usr/bin/env bash +set -euo pipefail + +ATTACHMENT_COMPOSE_ACTIVE=0 +ATTACHMENT_COMPOSE_PROJECT='' +ATTACHMENT_HOOK_KEY='' +ATTACHMENT_DB_PASSWORD='' +ATTACHMENT_FIXTURE_KEY='' +ATTACHMENT_RECEIPTS='' + +attachment_compose() { + RSTACK_JOURNEY_RECEIVER_USER="$(id -u):$(id -g)" \ + RSTACK_JOURNEY_RECEIVER_SCRIPT="$JOURNEY_LIB_DIR/projects/hook-receiver.py" \ + RSTACK_JOURNEY_RECEIVER_RECEIPTS="$ATTACHMENT_RECEIPTS" \ + RSTACK_JOURNEY_DB_PASSWORD_FILE="$ATTACHMENT_DB_PASSWORD" \ + RSTACK_JOURNEY_HOOK_KEY_FILE="$ATTACHMENT_HOOK_KEY" \ + docker compose --env-file /dev/null --project-name "$ATTACHMENT_COMPOSE_PROJECT" \ + --file "$JOURNEY_LIB_DIR/projects/rstack-attachments.compose.yaml" "$@" +} + +stop_compose_attachments() { + local status=0 + if [[ "$ATTACHMENT_COMPOSE_ACTIVE" == 1 ]]; then + attachment_compose down || status=1 + fi + if [[ -n "$ATTACHMENT_FIXTURE_KEY" && -e "$ATTACHMENT_FIXTURE_KEY" ]]; then + rm -- "$ATTACHMENT_FIXTURE_KEY" || status=1 + fi + return "$status" +} + +prepare_compose_attachments() { + local project=$1 work=$2 origin existing + ATTACHMENT_COMPOSE_PROJECT="$JOURNEY_CONTAINER_PREFIX-attachments-$JOURNEY_RUN_ID" + ATTACHMENT_RECEIPTS=$work/receiver + mkdir -m 700 -- "$ATTACHMENT_RECEIPTS" "$project/fixture" + journey_secret_new compose-hook-key 32 + journey_secret_new compose-db-password 24 + journey_secret_path compose-hook-key ATTACHMENT_HOOK_KEY + journey_secret_path compose-db-password ATTACHMENT_DB_PASSWORD + ATTACHMENT_FIXTURE_KEY=$project/fixture/contact-hmac + install -m 600 -- "$ATTACHMENT_HOOK_KEY" "$ATTACHMENT_FIXTURE_KEY" + + existing=$(docker ps -aq --filter "label=com.docker.compose.project=$ATTACHMENT_COMPOSE_PROJECT") || + journey_harness_failure "cannot check ownership of the disposable Compose project" + [[ -z "$existing" ]] || journey_harness_failure "the Compose project name already exists" + existing=$(docker network ls -q --filter "name=^${ATTACHMENT_COMPOSE_PROJECT}_default$") || + journey_harness_failure "cannot check ownership of the disposable Compose network" + [[ -z "$existing" ]] || journey_harness_failure "the Compose network name already exists" + ATTACHMENT_COMPOSE_ACTIVE=1 + attachment_compose up --wait --wait-timeout 60 || journey_harness_failure "the disposable Compose services did not start" + origin=$(attachment_compose port receiver 8109) || journey_harness_failure "the sibling hook receiver has no port" + [[ "$origin" =~ ^127\.0\.0\.1:[0-9]+$ ]] || journey_harness_failure "the sibling receiver must publish loopback only" + journey_poll 30 -- curl --silent --fail --max-time 2 --output /dev/null "http://$origin/ready" || + journey_harness_failure "the sibling hook receiver did not become ready" + local unsigned + unsigned=$(curl --silent --show-error --max-time 5 --output /dev/null --write-out '%{http_code}' \ + --json '{}' "http://$origin/events") || journey_harness_failure "the unsigned hook control could not reach the receiver" + [[ "$unsigned" == 403 && ! -e "$ATTACHMENT_RECEIPTS/event.json" ]] || + journey_harness_failure "the sibling receiver did not refuse the unsigned control without a capture" + printf '%s\n' 'The sibling receiver refused the unsigned hook with HTTP 403.' + cat >>"$project/dev.yaml" </dev/null || + journey_harness_failure "the sibling hook run unexpectedly started an internal BReg sink" + # shellcheck disable=SC2016 # jq binds $id. + journey_poll 45 -- jq -e --arg id "$expected" ' + .type == "contact-created" and .data.recordId == $id and .data.values.name == "A retained contact"' \ + "$ATTACHMENT_RECEIPTS/event.json" >/dev/null || + journey_harness_failure "the sibling receiver did not capture the signed event for the exact contact" + jq -e --arg id "$expected" 'select(.data.recordId == $id)' "$ATTACHMENT_RECEIPTS/event.json" \ + >"$ATTACHMENT_RECEIPTS/$phase-event.json" || journey_harness_failure "the sibling receiver capture changed before readback" + event=$(jq -er '.id | strings | select(length > 0)' "$ATTACHMENT_RECEIPTS/$phase-event.json") || + journey_harness_failure "the sibling receiver capture has no event ID" + attachment_compose logs --no-color --no-log-prefix receiver | + jq -Rc --arg id "$event" 'fromjson? | select(.eventId == $id)' >"$report" || + journey_harness_failure "cannot read the sibling receiver acceptance log" + assert_signed_hook_acceptance "$report" /events contact-created || + journey_harness_failure "the sibling receiver did not confirm signature verification without caller credentials" +} + +verify_compose_services_running() { + local service + for service in db receiver; do + [[ -n "$(attachment_compose ps --status running --quiet "$service")" ]] || + journey_harness_failure "stopping rstack also stopped the developer-owned Compose $service" + done + printf '%s\n' 'Both developer-owned Compose services remained running after rstack stopped.' +} + +private_compose_database_address() { + local container=$1 network=$2 + docker inspect "$container" | jq -er --arg network "$network" ' + .[0] | select((.NetworkSettings.Networks | keys) == [$network]) + | select([(.HostConfig.PortBindings // {})[]? | .[]?] == []) + | select([(.NetworkSettings.Ports // {})[]? | .[]?] == []) + | .NetworkSettings.Networks[$network].IPAddress + | select(test("^(10\\.|172\\.(1[6-9]|2[0-9]|3[01])\\.|192\\.168\\.)[0-9.]+$"))' +} + +expect_implicit_compose_refusal() { + local project=$1 reply status=0 run + reply=$(rstack_dev start "$project") || status=$? + if [[ "$status" == 0 ]]; then + run=$(jq -er '.run_id' <<<"$reply") || return 1 + rstack_dev stop "$run" >/dev/null || return 1 + printf '%s\n' 'Private plaintext unexpectedly started without an explicit transport selector.' >&2 + return 1 + fi + printf '%s\n' "$reply" + [[ "$status" == 1 ]] && jq -e ' + .error.class == "domain" and (.error.message | contains("numeric loopback"))' <<<"$reply" >/dev/null +} + +attach_compose_database() { + # shellcheck disable=SC2034 # issue_token and --bearer read token by name. + local project=$1 work=$2 container address password admin_base origin token='' contact='' + stop_live_runs || journey_harness_failure "cannot stop the managed run before Compose attachment" + container=$(attachment_compose ps --quiet db) || journey_harness_failure "cannot locate the Compose database" + [[ "$container" =~ ^[0-9a-f]{64}$ ]] || journey_harness_failure "expected one disposable Compose database" + address=$(private_compose_database_address "$container" "${ATTACHMENT_COMPOSE_PROJECT}_default") || + journey_harness_failure "the Compose database must have one numeric private address and no published port" + IFS= read -r password <"$ATTACHMENT_DB_PASSWORD" + admin_base="postgresql://postgres:$password@$address:5432/postgres" + RSTACK_DEV_DATABASE_URL="$admin_base?sslmode=disable" \ + journey_step attach --typed 'rstack dev start with implicit private plaintext' -- \ + expect_implicit_compose_refusal "$project" || + journey_harness_failure "implicit private plaintext did not return the expected loopback refusal" + RSTACK_DEV_DATABASE_URL="$admin_base?transport=private-network-plaintext" start_run attach "$project" || + journey_harness_failure "explicit private Compose attachment did not start; see $JOURNEY_STEP_STDOUT" + local config + config=$(jq -er '.runtimeConfigs.breg' "$START_FILE") || journey_harness_failure "the attached run names no BReg config" + journey_step attach -- python3 "$JOURNEY_LIB_DIR/projects/check-private-postgres.py" "$config" "$address" || + journey_harness_failure "BReg did not pin the private Compose address for both database roles" + origin=$(run_url breg) + issue_token attach "$RUN" editor token || journey_harness_failure "cannot issue the attached BReg editor credential" + journey_http attach --expect-status 201 --bearer token --header 'Content-Type: application/json' \ + --header 'Idempotency-Key: journey-compose-attached-contact' --data-file "$work/keep-body.json" \ + --capture .data.recordId contact POST "$origin/v1/records/contacts" || unexpected_answer attach + verify_sibling_hook "$contact" attached + journey_http attach --expect-status 200 --bearer token GET "$origin/v1/records/contacts/$contact" || unexpected_answer attach + jq -e --arg id "$contact" '.data.recordId == $id' "$JOURNEY_STEP_STDOUT" >/dev/null || + journey_harness_failure "the attached BReg read did not return the contact written on the Compose database" + journey_pass attach +} diff --git a/products/platform/journeys/rstack-dev.sh b/products/platform/journeys/rstack-dev.sh index 6086a1e969..3b474a2b45 100755 --- a/products/platform/journeys/rstack-dev.sh +++ b/products/platform/journeys/rstack-dev.sh @@ -21,13 +21,29 @@ # Run it from anywhere: # products/platform/journeys/rstack-dev.sh --bin-dir DIR [--product ID]... # [--out DIR] [--expected FILE [--strict]] [--keep] +# Use --product breg --attachments compose for the sibling receiver and +# unpublished private PostgreSQL attachment proof. set -euo pipefail # shellcheck disable=SC1091 # lib.sh is checked on its own source "$(dirname -- "${BASH_SOURCE[0]}")/lib.sh" -journey_init rstack-dev -- "$@" +journey_init rstack-dev --value-option attachments -- "$@" +journey_option_value attachments RSTACK_ATTACHMENTS +RSTACK_ATTACHMENTS=${RSTACK_ATTACHMENTS:-loopback} +case "$RSTACK_ATTACHMENTS" in +loopback) ;; +compose) + [[ "${JOURNEY_PRODUCTS[*]}" == breg && "$JOURNEY_KEEP" == 0 ]] || + journey_usage_error "--attachments compose requires --product breg and no --keep" + docker compose version >/dev/null || journey_usage_error "--attachments compose requires Docker Compose" + # shellcheck source=/dev/null # The opt-in fixture shares this runner's lifecycle. + source "$JOURNEY_LIB_DIR/projects/rstack-attachments.sh" + journey_at_cleanup stop_compose_attachments + ;; +*) journey_usage_error "--attachments $RSTACK_ATTACHMENTS: choose loopback or compose" ;; +esac journey_require_docker # The tools every selected product's init needs, and rstack itself. @@ -539,7 +555,10 @@ walk_product() { # start: one command, after supplying the optional fixture endpoints. case "$product" in - breg) add_contact_hook "$project" ;; + breg) + add_contact_hook "$project" + [[ "$RSTACK_ATTACHMENTS" != compose ]] || prepare_compose_attachments "$project" "$work" + ;; documents) add_documents_hooks "$project" ;; casework) # Use the generated test person's issuer for the starter's @@ -633,12 +652,16 @@ walk_product() { breg) local sink write_keep "$product" "$work" "$project" "$url" "$run" - sink=$(jq -er '.bregHookSink.receivedUrl' "$START_FILE") - journey_poll 30 -- hook_received "$sink" "$KEEP_EXPECT" || - journey_harness_failure "the BReg hook sink did not receive the retained contact's creation event" - journey_http hook GET "$sink" || unexpected_answer hook - breg_hook_matches "$KEEP_EXPECT" "$JOURNEY_STEP_STDOUT" || - journey_harness_failure "the BReg hook receipt does not contain the retained contact's creation event" + if [[ "$RSTACK_ATTACHMENTS" == compose ]]; then + verify_sibling_hook "$KEEP_EXPECT" managed + else + sink=$(jq -er '.bregHookSink.receivedUrl' "$START_FILE") + journey_poll 30 -- hook_received "$sink" "$KEEP_EXPECT" || + journey_harness_failure "the BReg hook sink did not receive the retained contact's creation event" + journey_http hook GET "$sink" || unexpected_answer hook + breg_hook_matches "$KEEP_EXPECT" "$JOURNEY_STEP_STDOUT" || + journey_harness_failure "the BReg hook receipt does not contain the retained contact's creation event" + fi journey_pass hook ;; documents) @@ -733,7 +756,11 @@ walk_product() { # attach: only products with a database accept a PostgreSQL server. if [[ "$uses_postgres" == true ]]; then - attach_database "$project" || status=$? + if [[ "$RSTACK_ATTACHMENTS" == compose ]]; then + attach_compose_database "$project" "$work" || status=$? + else + attach_database "$project" || status=$? + fi if [[ $status -ne 0 ]]; then stop_live_runs journey_cell_end @@ -752,6 +779,7 @@ walk_product() { journey_poll 30 -- state_is_empty || journey_harness_failure "the state of run $last did not go after its stop" journey_check_absent "$(run_containers "$last" | head -n 1)" "$(run_containers "$last" | tail -n 1)" || journey_harness_failure "a container of run $last remains after its stop" + [[ "$RSTACK_ATTACHMENTS" != compose ]] || verify_compose_services_running journey_pass stop [[ "$product" != evidence ]] || stop_evidence_source journey_cell_end diff --git a/products/platform/journeys/test_journey_tables.py b/products/platform/journeys/test_journey_tables.py index b10beeeccf..4db9fab726 100644 --- a/products/platform/journeys/test_journey_tables.py +++ b/products/platform/journeys/test_journey_tables.py @@ -1004,6 +1004,8 @@ def walk(self, product, delivered): scratch=$2 product=$3 delivered=$4 trace=$scratch/trace LIVE_RUNS='' +RSTACK_ATTACHMENTS=loopback +[[ "$delivered" != sibling-attachments ]] || RSTACK_ATTACHMENTS=compose printf '{"authentication":{"oidc":{"issuers":{"fixture":{}}}},"audit":{"path":"%s/audit.jsonl"}}\n' \ "$scratch" >"$scratch/runtime.json" : >"$scratch/audit.jsonl" @@ -1012,6 +1014,9 @@ def walk(self, product, delivered): init_command() { INIT_COMMAND=(write_starter "$2"); } add_contact_hook() { :; } add_documents_hooks() { :; } +prepare_compose_attachments() { printf '%s\n' 'prepare Compose attachments' >>"$trace"; } +verify_sibling_hook() { printf 'check sibling hook %s\n' "$1" >>"$trace"; } +verify_compose_services_running() { printf '%s\n' 'Compose services outlive rstack' >>"$trace"; } start_evidence_source() { :; } stop_evidence_source() { :; } measure_reader_action() { @@ -1160,6 +1165,7 @@ def walk(self, product, delivered): edit_for_restart() { :; } audit_was_appended() { :; } attach_database() { journey_pass attach; } +attach_compose_database() { printf '%s\n' 'attach private Compose database' >>"$trace"; journey_pass attach; } run_containers() { printf '%s\n' 'fake-container'; } journey_check_absent() { :; } @@ -1201,6 +1207,15 @@ def test_starter_first_read_uses_four_reader_commands(self): self.assertIn(("plan", "pass"), outcomes) self.assertIn(("issuer", "pass"), outcomes) + def test_breg_compose_attachments_requires_the_sibling_hook_and_private_database(self): + result, outcomes, trace = self.walk("breg", "sibling-attachments") + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertIn(("hook", "pass"), outcomes) + self.assertIn(("attach", "pass"), outcomes) + self.assertEqual(trace, ["prepare Compose attachments", "write breg", "check sibling hook retained-id", + "read retained record", "attach private Compose database", + "Compose services outlive rstack"]) + def test_messaging_reads_the_starter_receipt_in_four_reader_commands(self): result, _, trace = self.walk("messaging", "first-hour") self.assertEqual(result.returncode, 0, result.stdout + result.stderr) @@ -1274,6 +1289,43 @@ def test_documents_refuses_unmatched_capture_or_readback(self): self.assertEqual(trace, []) +class DevelopmentAttachments(unittest.TestCase): + def test_compose_keeps_postgres_unpublished_and_receiver_loopback_only(self): + fixture = yaml.safe_load((TABLES / "projects/rstack-attachments.compose.yaml").read_text()) + database = fixture["services"]["db"] + receiver = fixture["services"]["receiver"] + self.assertNotIn("ports", database) + self.assertNotIn("network_mode", database) + self.assertNotIn("network_mode", receiver) + self.assertEqual(receiver["ports"], ["127.0.0.1::8109"]) + self.assertEqual(database["secrets"], ["db-password"]) + self.assertEqual(receiver["secrets"], ["hook-key"]) + for service in (database, receiver): + self.assertRegex(service["image"], r"@sha256:[0-9a-f]{64}$") + self.assertEqual(service["pull_policy"], "never") + + def test_private_postgres_check_requires_the_exact_endpoint_for_both_roles(self): + script = TABLES / "projects/check-private-postgres.py" + address = "172.20.0.4" + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + config = root / "runtime.json" + for role in ("runtime", "migration"): + (root / role).write_text(f"postgresql://test:test@{address}:5432/fixture?sslmode=disable") + config.write_text(json.dumps({ + "secretProviders": {"file": {"root": str(root)}}, + "database": {"transport": "private-network-plaintext", "runtimeUrlRef": "secret:file/runtime", + "migrationUrlRef": "secret:file/migration"}, + })) + command = ["python3", str(script), str(config), address] + accepted = subprocess.run(command, check=True, capture_output=True, text=True) + self.assertEqual(json.loads(accepted.stdout)["rolesPinned"], ["runtime", "migration"]) + (root / "migration").write_text("postgresql://test:test@172.20.0.5:5432/fixture?sslmode=disable") + refused = subprocess.run(command, capture_output=True, text=True) + self.assertNotEqual(refused.returncode, 0) + self.assertNotIn("postgresql://", refused.stderr) + + class HookReceiverAndAdapterSource(unittest.TestCase): def test_hook_receiver_signature_verification(self): spec = importlib.util.spec_from_file_location( @@ -1312,9 +1364,9 @@ def test_hook_receiver_signature_verification(self): self.assertEqual(wrong_key_status, 403) def test_assert_signed_hook_acceptance_validates_value_free_record(self): - script = (TABLES / "own-provider.sh").read_text(encoding="utf-8") + script = (TABLES / "lib.sh").read_text(encoding="utf-8") match = re.search(r"^assert_signed_hook_acceptance\(\) \{\n.*?^\}\n", script, re.S | re.M) - self.assertIsNotNone(match, "own-provider must define assert_signed_hook_acceptance") + self.assertIsNotNone(match, "lib must define assert_signed_hook_acceptance") good = { "event": "signed-hook-accepted", "path": "/scheduling-events", From 62278f7f457f6dfc5c9d583f77c83e13d12e8317 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 19:44:10 +0000 Subject: [PATCH 065/183] fix(journeys): reap managed Scheduling startup before cleanup Signed-off-by: Jeremi Joslin (cherry picked from commit a3e5294b5252f91eeceaf41aa629cdff6c215e46) --- products/platform/journeys/lib.sh | 9 +- products/platform/journeys/own-provider.sh | 47 ++++-- .../platform/journeys/test_journey_tables.py | 138 ++++++++++++++++++ 3 files changed, 176 insertions(+), 18 deletions(-) diff --git a/products/platform/journeys/lib.sh b/products/platform/journeys/lib.sh index 95bfb155ee..bc226f9649 100644 --- a/products/platform/journeys/lib.sh +++ b/products/platform/journeys/lib.sh @@ -2630,8 +2630,7 @@ journey__cleanup_problem() { _journey_cleanup_failures+="$*"$'\n' } -journey__stop_processes() { - local index pid failed=0 +journey__stop_foreground() { if [[ -n "$_journey_watchdog_pid" ]]; then journey__end_watchdog "$_journey_watchdog_pid" _journey_watchdog_pid='' @@ -2640,6 +2639,10 @@ journey__stop_processes() { journey__terminate "$_journey_foreground_pid" "$JOURNEY_KILL_GRACE" _journey_foreground_pid='' fi +} + +journey__stop_processes() { + local index pid failed=0 for ((index = 0; index < ${#_journey_process_pids[@]}; index++)); do pid=${_journey_process_pids[$index]} [[ -n "$pid" ]] || continue @@ -2786,6 +2789,8 @@ journey__dispose_secrets() { journey__cleanup() { local index failed=0 + # A cancelled step can still be writing the state inspected by its cleanup hook. + journey__stop_foreground for ((index = ${#_journey_cleanup_hooks[@]} - 1; index >= 0; index--)); do if ! "${_journey_cleanup_hooks[$index]}"; then journey__cleanup_problem "cleanup hook ${_journey_cleanup_hooks[$index]} failed" diff --git a/products/platform/journeys/own-provider.sh b/products/platform/journeys/own-provider.sh index 39f4c33f9f..b78bda8c99 100755 --- a/products/platform/journeys/own-provider.sh +++ b/products/platform/journeys/own-provider.sh @@ -421,37 +421,52 @@ journey_at_cleanup stop_thunderid_sessions COMPOSED_MANAGED_RUN='' COMPOSED_MANAGED_ROOT=$SECRETS/scheduling-managed -composed_managed_dev() { - RSTACK_DEV_STATE_DIR="$COMPOSED_MANAGED_ROOT/state" \ - RSTACK_SCHEDULING_BIN="$SERVER_BIN" RSTACK_SCHEDULINGCTL_BIN="$TOOL_BIN" \ - "$COMPOSED_RSTACK_BIN" --install-root "$COMPOSED_MANAGED_ROOT/install" --format json dev "$@" -} - stop_composed_managed_scheduling() { - [[ -n "$COMPOSED_MANAGED_RUN" ]] || return 0 - composed_managed_dev stop "$COMPOSED_MANAGED_RUN" >/dev/null || return 1 + local state=$COMPOSED_MANAGED_ROOT/state run_id=$COMPOSED_MANAGED_RUN run + [[ ! -L "$COMPOSED_MANAGED_ROOT" && ! -L "$state" ]] || return 1 + if [[ -z "$run_id" ]]; then + # A launcher can create state before its startup report returns. + # This private directory belongs to this fixture alone. + for run in "$state/"*; do + [[ "${run##*/}" =~ ^[0-9a-f]{32}$ ]] || continue + [[ -d "$run" && ! -L "$run" && -z "$run_id" ]] || return 1 + run_id=${run##*/} + done + fi + [[ -n "$run_id" ]] || return 0 + run=$state/$run_id + if [[ -L "$run" ]] || + ! RSTACK_DEV_STATE_DIR="$state" RSTACK_SCHEDULING_BIN="$SERVER_BIN" RSTACK_SCHEDULINGCTL_BIN="$TOOL_BIN" \ + "$COMPOSED_RSTACK_BIN" --install-root "$COMPOSED_MANAGED_ROOT/install" --format json dev stop "$run_id" >/dev/null || + [[ -e "$run" || -L "$run" ]]; then + printf 'Managed Scheduling did not stop. Recovery state retained at %s.\n' "$run" >&2 + return 1 + fi COMPOSED_MANAGED_RUN='' } cleanup_composed_managed_scheduling() { - stop_composed_managed_scheduling || return 1 + if ! stop_composed_managed_scheduling; then + journey__cleanup_problem "managed Scheduling recovery state retained at $COMPOSED_MANAGED_ROOT" + return 1 + fi [[ ! -d "$COMPOSED_MANAGED_ROOT" ]] || python3 -c 'import shutil, sys; shutil.rmtree(sys.argv[1])' "$COMPOSED_MANAGED_ROOT" } journey_at_cleanup cleanup_composed_managed_scheduling -composed_managed_start() ( - unset RSTACK_DEV_DATABASE_CA - composed_managed_dev start "$@" -) - start_composed_managed_scheduling() { local _cms_project=$1 _cms_report=$2 _cms_url='' + # rstack start can spend up to 60 seconds stopping its supervisor after TERM. + local JOURNEY_KILL_GRACE=$((JOURNEY_KILL_GRACE < 65 ? 65 : JOURNEY_KILL_GRACE)) IFS= read -r _cms_url <"$ADMIN_URL_FILE" || [[ -n "$_cms_url" ]] || journey_harness_failure "cannot read the disposable PostgreSQL admin URL" - RSTACK_DEV_DATABASE_URL="$_cms_url?sslmode=disable" \ + # env execs rstack in the same PID watched by journey_step. + RSTACK_DEV_DATABASE_URL="$_cms_url?sslmode=disable" RSTACK_DEV_STATE_DIR="$COMPOSED_MANAGED_ROOT/state" \ + RSTACK_SCHEDULING_BIN="$SERVER_BIN" RSTACK_SCHEDULINGCTL_BIN="$TOOL_BIN" \ journey_step hook --timeout 120 --typed "rstack dev start $_cms_project" -- \ - composed_managed_start "$_cms_project" || + env -u RSTACK_DEV_DATABASE_CA "$COMPOSED_RSTACK_BIN" --install-root "$COMPOSED_MANAGED_ROOT/install" \ + --format json dev start "$_cms_project" || journey_harness_failure "managed Scheduling did not start; see $JOURNEY_STEP_STDERR" COMPOSED_MANAGED_RUN=$(jq -er '.run_id | strings | select(test("^[0-9a-f]{32}$"))' "$JOURNEY_STEP_STDOUT") || journey_harness_failure "managed Scheduling start report has no run ID" diff --git a/products/platform/journeys/test_journey_tables.py b/products/platform/journeys/test_journey_tables.py index 4db9fab726..da8e5ba5a1 100644 --- a/products/platform/journeys/test_journey_tables.py +++ b/products/platform/journeys/test_journey_tables.py @@ -1326,6 +1326,144 @@ def test_private_postgres_check_requires_the_exact_endpoint_for_both_roles(self) self.assertNotIn("postgresql://", refused.stderr) +class ManagedSchedulingStartup(unittest.TestCase): + def run_interrupted_start(self, mode, stop_failure=False): + source = (TABLES / "own-provider.sh").read_text(encoding="utf-8") + managed = source[source.index("COMPOSED_MANAGED_RUN=''\n"): + source.index("composed_scheduling_url() {")] + driver = r""" +source "$1/lib.sh" +journey_init own-provider -- --product scheduling --out "$FIXTURE/run" +journey_cell_begin scheduling +SECRETS=$JOURNEY_OUT/secrets +ADMIN_URL_FILE=$FIXTURE/admin-url +COMPOSED_RSTACK_BIN=$FIXTURE/launcher +SERVER_BIN=$COMPOSED_RSTACK_BIN TOOL_BIN=$COMPOSED_RSTACK_BIN +if [[ "$2" == timeout ]]; then + eval "$(declare -f journey__watchdog | sed '1s/journey__watchdog/fixture_watchdog/')" + journey__watchdog() { + [[ "$2" != 120 ]] || set -- "$1" 2 "$3" "$4" + fixture_watchdog "$@" + } +fi +""" + managed + r""" +start_composed_managed_scheduling "$FIXTURE" "$FIXTURE/start.json" +journey_finish +""" + launcher = r"""#!/usr/bin/env python3 +import os +import shutil +import signal +import subprocess +import sys +import time +from pathlib import Path + +fixture = Path(os.environ["FIXTURE"]) +run = Path(os.environ["RSTACK_DEV_STATE_DIR"]) / ("a" * 32) +if sys.argv[6] == "stop": + if os.environ.get("RSTACK_SCHEDULINGCTL_BIN") != sys.argv[0]: + sys.exit(6) + if sys.argv[7] != run.name or not (run / "recovery").exists(): + sys.exit(7) + if not (fixture / "term").exists() or not (fixture / "child-stopped").exists(): + sys.exit(8) + (fixture / "stop").touch() + if os.environ["STOP_FAILURE"] == "1": + sys.exit(9) + shutil.rmtree(run) + sys.exit(0) + +child = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(8)"]) + +def terminate(_signal, _frame): + (fixture / "term").touch() + sys.exit(143) + +signal.signal(signal.SIGTERM, terminate) +try: + run.mkdir(parents=True) + (run / "recovery").write_text("owned recovery fixture", encoding="utf-8") + (fixture / "pids.tmp").write_text(f"{os.getpid()} {child.pid}", encoding="utf-8") + (fixture / "pids.tmp").rename(fixture / "pids") + time.sleep(7) +finally: + child.terminate() + child.wait(timeout=2) + (fixture / "child-stopped").touch() +""" + with tempfile.TemporaryDirectory() as directory: + fixture = Path(directory) + (fixture / "admin-url").write_text("postgresql://fixture@127.0.0.1/test") + executable = fixture / "launcher" + executable.write_text(launcher, encoding="utf-8") + executable.chmod(0o700) + pids = fixture / "pids" + with subprocess.Popen( + ["bash", "-euo", "pipefail", "-c", driver, + "managed-scheduling-start", str(TABLES), mode], + env={**os.environ, "JOURNEY_TABLES_DIR": str(TABLES), + "FIXTURE": directory, "STOP_FAILURE": str(int(stop_failure))}, + stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, + start_new_session=True, + ) as process: + try: + deadline = time.monotonic() + 8 + while not pids.exists() and process.poll() is None and time.monotonic() < deadline: + time.sleep(0.02) + if not pids.exists(): + _, errors = process.communicate(timeout=10) + self.fail(f"managed launcher never reached startup: {errors}") + if mode == "cancel": + process.terminate() + _, errors = process.communicate(timeout=10) + term_seen = (fixture / "term").exists() + stop_seen = (fixture / "stop").exists() + managed_root = fixture / "run/secrets/scheduling-managed" + retained = (managed_root / "state" / ("a" * 32) / "recovery").is_file() + live = [] + for pid in pids.read_text(encoding="utf-8").split(): + status = subprocess.run( + ["ps", "-o", "stat=", "-p", pid], capture_output=True, text=True, + ).stdout.strip() + if status and not status.startswith("Z"): + live.append(pid) + report = json.loads((fixture / "run/run.json").read_text(encoding="utf-8")) + self.assertEqual(process.returncode, 143 if mode == "cancel" else 3, errors) + if mode == "timeout": + self.assertIn("did not finish within 120 seconds", report["harnessFailure"]) + self.assertFalse((fixture / "start.json").exists(), "unexpected start report") + self.assertEqual( + (term_seen, stop_seen, live, retained), + (True, True, [], stop_failure), errors, + ) + self.assertEqual(managed_root.exists(), stop_failure) + failures = report["cleanup"]["failures"] + self.assertEqual( + "cleanup hook cleanup_composed_managed_scheduling failed" in failures, + stop_failure, failures, + ) + if not stop_failure: + self.assertEqual(failures, [], errors) + else: + self.assertIn(f"managed Scheduling recovery state retained at {managed_root}", failures) + finally: + # The group contains only the fixture. Reap any escaped + # fake launcher and child when running against a broken runner. + subprocess.run( + ["kill", "-TERM", "--", f"-{process.pid}"], capture_output=True, + ) + + def test_startup_timeout_reaches_launcher_and_waits_for_child(self): + self.run_interrupted_start("timeout") + + def test_cancellation_before_run_id_stops_owned_state_after_launcher(self): + self.run_interrupted_start("cancel") + + def test_failed_shutdown_keeps_owned_recovery_state(self): + self.run_interrupted_start("cancel", stop_failure=True) + + class HookReceiverAndAdapterSource(unittest.TestCase): def test_hook_receiver_signature_verification(self): spec = importlib.util.spec_from_file_location( From c807bf9b5a5bae11440a2db35ac5880d3e86b5f2 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 19:32:16 +0000 Subject: [PATCH 066/183] refactor(evidence): centralize wallet delivery transport checks Signed-off-by: Jeremi Joslin (cherry picked from commit 4724ea195d16fece91a642e16d6abd87dfcd09e7) --- .../registry-evidence-oid4vci/src/config.rs | 91 ++++++++++++++----- 1 file changed, 68 insertions(+), 23 deletions(-) diff --git a/crates/registry-evidence-oid4vci/src/config.rs b/crates/registry-evidence-oid4vci/src/config.rs index 95504951db..f2ba0c41b8 100644 --- a/crates/registry-evidence-oid4vci/src/config.rs +++ b/crates/registry-evidence-oid4vci/src/config.rs @@ -26,9 +26,10 @@ use registry_platform_config::{ SecretProvidersConfig, SecretReference, DEFAULT_STAND_IN, }; use registry_platform_httputil::client::{ - is_loopback_host, valid_resource_uri, valid_scope_token, MAXIMUM_REQUESTED_SCOPES, - MAXIMUM_REQUESTED_SCOPE_BYTES, MAXIMUM_SCOPE_PARAMETER_BYTES, + valid_resource_uri, valid_scope_token, MAXIMUM_REQUESTED_SCOPES, MAXIMUM_REQUESTED_SCOPE_BYTES, + MAXIMUM_SCOPE_PARAMETER_BYTES, }; +use registry_platform_httputil::select::{select_credential_destination, select_destination}; use registry_platform_yaml::{ shape_union, BoundedU32, BoundedU64, Diagnostic, ExternalId, Invalid, Report, Severity, UniqueList, Url, @@ -1328,7 +1329,7 @@ impl DeliveryDocument { } for (pointer, origin) in self.called_origins() { url_query_or_fragment_findings(pointer, origin, findings); - https_origin_findings(pointer, origin, findings); + https_origin_findings(pointer, origin, OutboundOriginRole::Credential, findings); } for (id, entry) in self.offers.issuers.iter() { let prefix = format!("{OFFER_ISSUERS}/{}", id.as_str()); @@ -1336,7 +1337,12 @@ impl DeliveryDocument { let issuer_path = format!("{prefix}/issuer"); url_query_or_fragment_findings(&issuer_path, &provider.issuer, findings); if !provider.allow_insecure_http { - https_origin_findings(&issuer_path, &provider.issuer, findings); + https_origin_findings( + &issuer_path, + &provider.issuer, + OutboundOriginRole::OfferMetadata, + findings, + ); } let source_path = format!("{prefix}/jwksSource"); match &provider.jwks_source { @@ -1344,7 +1350,12 @@ impl DeliveryDocument { let pointer = format!("{source_path}/uri"); url_query_or_fragment_findings(&pointer, uri, findings); if !provider.allow_insecure_http { - https_origin_findings(&pointer, uri, findings); + https_origin_findings( + &pointer, + uri, + OutboundOriginRole::OfferMetadata, + findings, + ); } } _ => findings.push(Finding::error( @@ -1692,21 +1703,31 @@ fn normalized_credential_issuer(written: &str) -> &str { written.trim_end_matches('/') } -/// Require HTTPS for a called origin outside loopback. +enum OutboundOriginRole { + Credential, + OfferMetadata, +} + +/// Require protected transport for a called origin or a strict offer key source. /// The reader refuses URLs without a host or with embedded credentials. -fn https_origin_findings(pointer: &str, origin: &Url, findings: &mut Vec) { - if !origin.is_https() - && !origin - .to_url() - .host() - .as_ref() - .is_some_and(is_loopback_host) - { - let action = if pointer.starts_with(OFFER_ISSUERS) { - "Write an HTTPS or loopback HTTP URL, or use allowInsecureHttp: true in the issuer entry with development for HTTP beyond loopback." - } else { - "Write an HTTPS or loopback HTTP URL." - }; +fn https_origin_findings( + pointer: &str, + origin: &Url, + role: OutboundOriginRole, + findings: &mut Vec, +) { + let url = origin.to_url(); + let (selected, action) = match role { + OutboundOriginRole::Credential => ( + select_credential_destination(&url, None, &[]), + "Write an HTTPS or loopback HTTP URL.", + ), + OutboundOriginRole::OfferMetadata => ( + select_destination(&url, None, &[]), + "Write an HTTPS or loopback HTTP URL, or use allowInsecureHttp: true in the issuer entry with development for HTTP beyond loopback.", + ), + }; + if selected.is_err() { findings.push(Finding::error( HTTPS_REQUIRED, pointer, @@ -2328,10 +2349,34 @@ store: #[test] fn posture_strict_called_origins_allow_loopback_http_only() { - let loopback = VALID.replace("https://evidence.example.org", "http://127.0.0.1:8080"); - assert!(load_from(&loopback).is_ok()); - let private = VALID.replace("https://evidence.example.org", "http://10.0.0.5"); - assert_refused_with(&private, HTTPS_REQUIRED); + for (original, path, suffix) in [ + ("https://evidence.example.org", "/evidence/baseUrl", ""), + ( + "https://mint.example.org/token", + "/tokenClient/tokenEndpoint", + "/token", + ), + ] { + for host in ["127.0.0.1", "[::1]", "localhost"] { + let text = VALID.replace(original, &format!("http://{host}:8080{suffix}")); + assert!(load_from(&text).is_ok(), "{path} at {host}"); + assert!(!check(&text, false) + .diagnostics + .iter() + .any(|d| d.severity == Severity::Error)); + } + for host in ["10.0.0.5", "receiver.localhost"] { + let text = VALID.replace(original, &format!("http://{host}:8080{suffix}")); + let error = load_from(&text).expect_err("non-loopback plaintext is refused"); + let offline = check(&text, false); + for diagnostics in [error.diagnostics(), offline.diagnostics.as_slice()] { + assert_eq!(diagnostics.len(), 1, "{path} at {host}"); + assert_eq!(diagnostics[0].code, HTTPS_REQUIRED); + assert_eq!(diagnostics[0].path, path); + assert!(!diagnostics[0].message.contains(host)); + } + } + } } #[test] From f5d867cf214296624220bf6aba67ea90279a5277 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 19:58:19 +0000 Subject: [PATCH 067/183] fix(journeys): reap promotion startup and validate Adapter checks Signed-off-by: Jeremi Joslin (cherry picked from commit 34f6bf462af2fa6e44b8e50f79a87321a7c5447f) --- products/platform/journeys/README.md | 17 +- products/platform/journeys/promote.sh | 74 +++++--- .../platform/journeys/test_journey_tables.py | 159 ++++++++++++++++++ products/platform/journeys/test_lib.sh | 2 + 4 files changed, 229 insertions(+), 23 deletions(-) diff --git a/products/platform/journeys/README.md b/products/platform/journeys/README.md index de96d0d80f..99ad1feebf 100644 --- a/products/platform/journeys/README.md +++ b/products/platform/journeys/README.md @@ -108,6 +108,17 @@ and grant exchange, commit a hold and an appointment, and verify a signed appointment hook correlated to that appointment. A skipped hook cannot satisfy the ThunderID cell. +Run the same composed check with a managed Scheduling runtime by passing +`--issuer thunderid --product scheduling --scheduling-runtime managed` to +`own-provider.sh`, using a prebuilt `rstack`, `schedulingctl`, and the composed +fixture tools. Use `expected-failures-thunderid.yaml` for the strict run. The +managed dev plan binds the named `task-agent` client to the exact Casework +assertion issuer and uses a separate status client to check live Casework +grant status. The journey checks the missing and wrong authority, an ordinary +bearer without a grant, and the signed hook for the confirmed appointment. +The generic `rstack-dev.sh` Scheduling smoke reports its hook as unexercised +without this composed fixture. + ## Adapter promotion The Adapter facade uses loopback PostgreSQL and a disposable Basic Auth source. @@ -164,14 +175,16 @@ T1 is captured at the first successful authenticated read. If the local journey's first operation is a write, its authenticated readback can provide T1. T2 is captured after the runner has verified the write across a restart and checked delivery for paths that exercise a hook. The current local T2 -receipts cover BReg, Coordinator, and Messaging. +receipts cover BReg, Coordinator, Documents, and Messaging. Threshold outcomes are report-only in CI. The functional ratchet controls journey acceptance, and comparison code errors fail the harness. Promote uses its functional ratchet. Its `productionRefusals` field counts distinct codes matched by the initial production startup and check. It is `null` until the comparison was measured, and `0` when the comparison found no refusals. -The existing `total.refusalsMet` counts refusals across the cell. +`total.refusalsMet` counts blocking or explicitly counted refusals across the +cell, including matched production refusals. An expected HTTP refusal that +satisfies a negative control stays in the step receipt as a passing assertion. The stock Keycloak BReg editor requests an optional client scope for the fixture's static claims. Keycloak keeps the issued `scope` claim unchanged. diff --git a/products/platform/journeys/promote.sh b/products/platform/journeys/promote.sh index 87aa6d1f17..6f996fca9a 100755 --- a/products/platform/journeys/promote.sh +++ b/products/platform/journeys/promote.sh @@ -285,44 +285,56 @@ port_is_free() { # attempt has an answer, so a refused start is an observation. # shellcheck disable=SC2329 # run through journey_step production_start() { - local pid attempt=0 state='' + local stop_grace=$1 pid deadline interrupted=0 state='' + # Record signals even between starting the server and saving its PID. + # This watched shell owns the child until it has reaped it. + trap 'interrupted=129' HUP + trap 'interrupted=130' INT + trap 'interrupted=143' TERM "${SERVE_COMMAND[@]}" & pid=$! - while ((attempt < 60)); do - if ! kill -0 "$pid" 2>/dev/null; then + deadline=$((SECONDS + 30)) + while ((interrupted == 0 && SECONDS < deadline)); do + if ! journey__process_alive "$pid"; then state=refused break fi - if curl --silent --fail --output /dev/null "http://127.0.0.1:$PORT$READY_PATH"; then + if curl --silent --fail --max-time 1 --output /dev/null "http://127.0.0.1:$PORT$READY_PATH"; then state=started break fi sleep 0.5 - attempt=$((attempt + 1)) done - if [[ -z "$state" ]]; then - printf 'the product neither answered %s nor exited within 30 seconds\n' "$READY_PATH" >&2 - kill -TERM "$pid" 2>/dev/null || true - wait "$pid" 2>/dev/null || true - return 1 - fi if [[ "$state" == refused ]]; then wait "$pid" 2>/dev/null || printf 'the product exited with status %s\n' "$?" >&2 else - kill -TERM "$pid" - for attempt in $(seq 1 100); do - kill -0 "$pid" 2>/dev/null || break - sleep 0.1 + while :; do + journey__terminate "$pid" "$stop_grace" + # A trapped signal can interrupt wait before the child exits. + journey__process_alive "$pid" || break done - if kill -0 "$pid" 2>/dev/null; then - kill -KILL "$pid" + # shellcheck disable=SC2154 # journey__terminate sets this status. + if [[ $_journey_terminate_killed -eq 1 ]]; then printf 'the product ignored SIGTERM and was killed\n' >&2 + return "$((interrupted == 0 ? 1 : interrupted))" fi - wait "$pid" 2>/dev/null || true + fi + ((interrupted == 0)) || return "$interrupted" + if [[ -z "$state" ]]; then + printf 'the product neither answered %s nor exited within 30 seconds\n' "$READY_PATH" >&2 + return 1 fi printf '%s\n' "$state" >"$STATE_FILE" } +observe_production_start() { + local stop_grace=$JOURNEY_KILL_GRACE + # Leave the wrapper enough time to finish a readiness probe, then stop + # and reap the server before its own watchdog can escalate. + local JOURNEY_KILL_GRACE=$((stop_grace + 4)) + journey_step start-as-production --timeout 90 --typed "${SERVE_COMMAND[*]##*/}" -- production_start "$stop_grace" +} + # production_check: the production check, whatever it answers. Its exit status # goes to stderr; its report is the step's stdout. # shellcheck disable=SC2329 # run through journey_step @@ -332,6 +344,20 @@ production_check() { printf 'check exit status %s\n' "$status" >&2 } +adapter_check_envelope() { + jq -e -s --arg exit "$2" ' + ({"0":"complete","1":"domain-refusal","2":"usage-error","3":"operational-failure"}[$exit]) as $status | + length == 1 and (.[0] | + type == "object" and + .apiVersion == "id.registrystack.org/formats/adapter/ctl-report/v1alpha1" and + .kind == "AdapterCtlReport" and .command == "check" and + $status != null and .status == $status and .ok == ($exit == "0") and + (.diagnostics | type == "array" and ($exit == "0" or length > 0) and + all(.[]; type == "object" and (.code | type == "string" and length > 0) and + (.message | type == "string") and + ($exit == "0" or (.suggestedAction | type == "string" and length > 0)))))' "$1" >/dev/null 2>&1 +} + # The stock own-provider paths for these products use narrow loopback transport # and explicit clients, both permitted in production. Any actual refusal still # takes the remediation path, even for these products. @@ -538,7 +564,7 @@ walk_product() { # start-as-production STATE_FILE=$JOURNEY_OUT/$product/production-start.state port_is_free "$PORT" || journey_harness_failure "port $PORT is in use; promote cannot start $product on it" - journey_step start-as-production --timeout 90 --typed "${SERVE_COMMAND[*]##*/}" -- production_start || + observe_production_start || journey_harness_failure "the start of $product neither answered nor exited; see $JOURNEY_STEP_STDERR" [[ -f "$STATE_FILE" ]] || journey_harness_failure "the start attempt of $product left no state; see $JOURNEY_STEP_STDERR" START_CODES=$(diagnostic_codes "$JOURNEY_STEP_STDOUT" "$JOURNEY_STEP_STDERR") @@ -553,11 +579,17 @@ walk_product() { # refusals journey_step refusals --typed "${CHECK_COMMAND[*]##*/}" -- production_check || journey_harness_failure "the production check of $product did not run; see $JOURNEY_STEP_STDERR" - CHECK_CODES=$(diagnostic_codes "$JOURNEY_STEP_STDOUT" "$JOURNEY_STEP_STDERR") + check_status=$(sed -n 's/^check exit status \([0-9][0-9]*\)$/\1/p' "$JOURNEY_STEP_STDERR") + if [[ "$product" == adapter ]]; then + adapter_check_envelope "$JOURNEY_STEP_STDOUT" "$check_status" || + journey_harness_failure "Adapter production check report must be one check envelope matching its exit status; see $JOURNEY_STEP_STDOUT" + CHECK_CODES=$(diagnostic_codes "$JOURNEY_STEP_STDOUT") + else + CHECK_CODES=$(diagnostic_codes "$JOURNEY_STEP_STDOUT" "$JOURNEY_STEP_STDERR") + fi if [[ "$CHECK_CODES" != "$START_CODES" ]]; then journey_harness_failure "the production check of $product lists [${CHECK_CODES//$'\n'/ }] and its start lists [${START_CODES//$'\n'/ }]; the two lists must be equal (see $JOURNEY_STEP_STDOUT)" fi - check_status=$(sed -n 's/^check exit status \([0-9][0-9]*\)$/\1/p' "$JOURNEY_STEP_STDERR") production_case=$(production_outcome "$product" "$(<"$STATE_FILE")" "$check_status" "$CHECK_CODES") case "$production_case" in invalid) diff --git a/products/platform/journeys/test_journey_tables.py b/products/platform/journeys/test_journey_tables.py index da8e5ba5a1..7c10167b5a 100644 --- a/products/platform/journeys/test_journey_tables.py +++ b/products/platform/journeys/test_journey_tables.py @@ -18,6 +18,7 @@ import json import os import re +import signal import subprocess import tempfile import time @@ -649,6 +650,164 @@ def test_zero_diagnostics_requires_a_successful_check_and_an_explicit_case(self) self.assertEqual(result.strip(), expected) +class AdapterPromotion(unittest.TestCase): + def run_promotion(self, mode, check_report="", check_exit=0, stubborn=False): + source = (TABLES / "promote.sh").read_text(encoding="utf-8") + start = source[source.index("# diagnostic_codes FILE"): + source.index("# FIX_TABLE:")] + walk = re.search(r"^walk_product\(\) \{\n.*?^\}\n", source, re.M | re.S) + self.assertIsNotNone(walk) + driver = r""" +source "$1/lib.sh" +journey_init promote -- --product adapter --out "$FIXTURE/run" +FROM=$FIXTURE/input +recorded=$FROM/work/adapter +mkdir -p "$recorded" +printf 'fixture response\n' >"$recorded/call.response" +printf 'fixture contract\n' >"$recorded/call.contract" +printf 'aud\n' >"$recorded/call.claims" +input_outcome() { printf -v "$2" finished; } +locate_input() { PORT=12345; READY_PATH=/ready; } +recipe() { SERVE_COMMAND=("$FIXTURE/adapter"); CHECK_COMMAND=(fixture_check); } +call_recipe() { CALL_METHOD=POST; CALL_PATH=/v1/records/person; CALL_OPTIONS=(); } +take_over_input() { :; } +curl() { [[ "$MODE" == check && -f "$FIXTURE/pid" ]]; } +fixture_check() { printf '%s' "$CHECK_REPORT"; return "$CHECK_EXIT"; } +fetch_token() { printf -v "$2" fixture; } +apply_fix() { [[ "$1" == adapter.config.invalid-fixture ]]; } +journey_claim_names() { printf 'aud\n'; } +journey_request_contract() { printf 'fixture contract\n'; } +journey_start() { :; } +journey_ready() { :; } +journey_http() { JOURNEY_HTTP_STATUS=201; JOURNEY_STEP_STDOUT=$recorded/call.response; } +journey_stop() { :; } +if [[ "$MODE" == timeout ]]; then + eval "$(declare -f journey__watchdog | sed '1s/journey__watchdog/fixture_watchdog/')" + journey__watchdog() { + [[ "$2" != 90 ]] || set -- "$1" 2 "$3" "$4" + fixture_watchdog "$@" + } +fi +""" + start + "\nport_is_free() { :; }\n" + walk.group(0) + "\nwalk_product adapter\njourney_finish\n" + adapter = r"""#!/usr/bin/env python3 +import os +import signal +import sys +import time +from pathlib import Path + +if os.environ["MODE"] == "refusal": + print("error[adapter.config.invalid-fixture] synthetic refusal", file=sys.stderr) + sys.exit(1) + +fixture = Path(os.environ["FIXTURE"]) + +def terminate(_signal, _frame): + (fixture / "term").touch() + if os.environ["STUBBORN"] != "1": + sys.exit(143) + +signal.signal(signal.SIGTERM, terminate) +(fixture / "pid.tmp").write_text(str(os.getpid())) +(fixture / "pid.tmp").rename(fixture / "pid") +time.sleep(8) +""" + with tempfile.TemporaryDirectory() as directory: + fixture = Path(directory) + executable = fixture / "adapter" + executable.write_text(adapter, encoding="utf-8") + executable.chmod(0o700) + with subprocess.Popen( + ["bash", "-euo", "pipefail", "-c", driver, "promote-adapter", str(TABLES)], + env={**os.environ, "JOURNEY_TABLES_DIR": str(TABLES), + "JOURNEY_KILL_GRACE": "1", "FIXTURE": directory, "MODE": mode, + "CHECK_REPORT": check_report, "CHECK_EXIT": str(check_exit), + "STUBBORN": str(int(stubborn))}, + stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, start_new_session=True, + ) as process: + try: + pid_file = fixture / "pid" + if mode == "cancel": + deadline = time.monotonic() + 8 + while not pid_file.exists() and process.poll() is None and time.monotonic() < deadline: + time.sleep(0.02) + self.assertTrue(pid_file.exists(), "Adapter never reached startup") + process.terminate() + _, errors = process.communicate(timeout=14) + run = fixture / "run" + report = json.loads((run / "run.json").read_text(encoding="utf-8")) + if mode in ("timeout", "cancel"): + self.assertTrue(pid_file.exists(), errors) + status = subprocess.run( + ["ps", "-o", "stat=", "-p", pid_file.read_text()], + capture_output=True, text=True, + ).stdout.strip() + self.assertEqual( + ((fixture / "term").exists(), bool(status and not status.startswith("Z"))), + (True, False), errors, + ) + self.assertFalse((run / "adapter/production-start.state").exists()) + self.assertEqual(report["cleanup"]["failures"], [], errors) + summary = run / "summary.json" + return report, json.loads(summary.read_text()) if summary.exists() else None + finally: + # The group contains only the fixture, including an escaped + # fake Adapter when the runner under test is broken. + try: + os.killpg(process.pid, signal.SIGKILL) + except ProcessLookupError: + self.assertIsNotNone(process.poll()) + + def test_startup_watchdog_stops_the_server(self): + report, _ = self.run_promotion("timeout") + self.assertEqual(report["exitStatus"], 3) + self.assertIn("did not finish within 90 seconds", report["harnessFailure"]) + + def test_cancellation_reaps_the_server_even_if_term_is_ignored(self): + report, _ = self.run_promotion("cancel", stubborn=True) + self.assertEqual(report["exitStatus"], 143) + + @staticmethod + def envelope(**fields): + return json.dumps({ + "apiVersion": "id.registrystack.org/formats/adapter/ctl-report/v1alpha1", + "kind": "AdapterCtlReport", "command": "check", "status": "complete", + "ok": True, "diagnostics": [], **fields, + }) + + def test_unmatched_check_envelope_fails_before_refusal_count(self): + valid = self.envelope() + cases = { + "blank": "", "malformed": '{"ok":', "two objects": valid + "\n" + valid, + "wrong command": self.envelope(command="provision"), + "wrong outcome": self.envelope(ok=False), + "wrong diagnostics": self.envelope(diagnostics={}), + "malformed diagnostic": self.envelope(diagnostics=[{"code": "bad", "message": 1}]), + } + for label, output in cases.items(): + with self.subTest(label=label): + report, summary = self.run_promotion("check", output) + self.assertEqual(report["exitStatus"], 3) + self.assertIn("Adapter production check report", report["harnessFailure"]) + self.assertIsNone(summary) + + def test_valid_check_counts_distinct_matched_refusals(self): + refusal = {"code": "adapter.config.invalid-fixture", "message": "synthetic refusal", + "suggestedAction": "Correct the fixture."} + cases = ( + ("check", self.envelope(), 0, 0), + ("refusal", self.envelope(ok=False, status="domain-refusal", + diagnostics=[refusal, refusal]), 1, 1), + ) + for mode, output, exit_status, count in cases: + with self.subTest(mode=mode): + report, summary = self.run_promotion(mode, output, check_exit=exit_status) + self.assertEqual(report["exitStatus"], 0, report["harnessFailure"]) + cell, = summary["cells"] + self.assertEqual(cell["productionRefusals"], count) + self.assertEqual(cell["total"]["refusalsMet"], count) + + class LoggedStage(unittest.TestCase): """`logged_stage` maps the last refusal line's `failed_check` label onto a stage word.""" diff --git a/products/platform/journeys/test_lib.sh b/products/platform/journeys/test_lib.sh index fc94e323fa..b5bb73992d 100644 --- a/products/platform/journeys/test_lib.sh +++ b/products/platform/journeys/test_lib.sh @@ -1819,6 +1819,8 @@ case_http() { drive 0 SCENARIO=http EXPECT_REFUSAL=1 -- --product alpha check "the observed 401 remains in the HTTP transcript" has "HTTP/1.1 401" "$out/alpha/call.http" check "the checked refusal passes the journey step" has $'alpha\tcall\tpass\t-' "$out/cells.tsv" + check_equal "a passing expected HTTP refusal adds no reader friction" 0 \ + "$(json '.cells[] | select(.product == "alpha") | .total.refusalsMet' "$out/summary.json")" begin_case http-source-bearer printf '{"access_token":"%s"}\n' "$token" >"$state/http-body.1" From d5c1b77ca79d96883289db4546a25611faad46d3 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 20:01:08 +0000 Subject: [PATCH 068/183] test(session): verify module sign-in drift and prefix refusal Signed-off-by: Jeremi Joslin --- crates/registry-session/src/gateway/verify.rs | 9 ++++- crates/registry-session/tests/binary.rs | 38 +++++++++++++++---- .../src/content/docs/configure/session.mdx | 8 ++-- 3 files changed, 43 insertions(+), 12 deletions(-) diff --git a/crates/registry-session/src/gateway/verify.rs b/crates/registry-session/src/gateway/verify.rs index 1a7d7878ce..ac8a474abc 100644 --- a/crates/registry-session/src/gateway/verify.rs +++ b/crates/registry-session/src/gateway/verify.rs @@ -656,13 +656,18 @@ pub fn write_verified_route_inventory( .map(|prefix| prefix.as_str()); let overlap = |other: &str| lies_under(&module.prefix, other) || lies_under(other, &module.prefix); - if rewrite != Some("/") - || module.prefix.len() > 256 + if module.prefix.len() > 256 || !module.prefix.ends_with('/') || !module .prefix .bytes() .all(|byte| byte.is_ascii_alphanumeric() || b"/._:-".contains(&byte)) + { + return Err(standalone_refusal( + "Use letters, digits or /._:- and a trailing slash in the selected BReg prefix.", + )); + } + if rewrite != Some("/") || config .modules .iter() diff --git a/crates/registry-session/tests/binary.rs b/crates/registry-session/tests/binary.rs index 2ac341ce30..fe30a66565 100644 --- a/crates/registry-session/tests/binary.rs +++ b/crates/registry-session/tests/binary.rs @@ -407,6 +407,23 @@ fn gateway_inventory_requires_the_exact_verified_assembly() { assert_eq!(changed["gatewayDigest"], inventory["gatewayDigest"]); assert_ne!(changed["signInDigest"], inventory["signInDigest"]); assert_eq!(changed["pages"][0]["signIn"], "reviewer"); + + let restricted_function = runtime_source.replace( + " prefix: /api/functions/\n audience: person", + " prefix: /api/functions/\n audience: person\n signIns: [reviewer]", + ); + assert_ne!(restricted_function, runtime_source); + std::fs::write(&runtime, restricted_function).expect("changed function admission"); + let (exit, _, stderr) = verify(); + assert_eq!(exit, 0, "{stderr}"); + let changed: serde_json::Value = + serde_json::from_slice(&std::fs::read(&routes).expect("changed function inventory")) + .unwrap(); + assert_eq!(changed["gatewayDigest"], inventory["gatewayDigest"]); + assert_eq!(changed["pages"], inventory["pages"]); + assert_eq!(changed["modules"][1]["signIns"], json!(["reviewer"])); + assert_ne!(changed["signInDigest"], inventory["signInDigest"]); + std::fs::write(&runtime, &runtime_source).expect("restore literal test fixture"); assert_eq!(verify().0, 0); assert_eq!(std::fs::read(&routes).expect("restored inventory"), first); @@ -496,13 +513,20 @@ fn gateway_inventory_requires_the_exact_verified_assembly() { assert_eq!(verify().0, 1); assert_eq!(std::fs::read(&routes).expect("retained inventory"), first); - let unsafe_page = runtime_source.replace("/apply/", "/apply;/"); - assert_ne!(unsafe_page, runtime_source); - std::fs::write(&runtime, unsafe_page).expect("runtime with broader page prefix"); - let (exit, _, stderr) = assemble(true); - assert_eq!(exit, 0, "{stderr}"); - assert_eq!(verify().0, 1, "refuse a page path that live checks reject"); - assert_eq!(std::fs::read(&routes).expect("retained inventory"), first); + for (prefix, changed) in [ + ("page", runtime_source.replace("/apply/", "/apply;/")), + ( + "module", + runtime_source.replace("/api/functions/", "/api/functions;/"), + ), + ] { + assert_ne!(changed, runtime_source); + std::fs::write(&runtime, changed).expect("runtime with a broader route prefix"); + let (exit, _, stderr) = assemble(true); + assert_eq!(exit, 0, "{stderr}"); + assert_eq!(verify().0, 1, "refuse unsafe {prefix} path"); + assert_eq!(std::fs::read(&routes).expect("retained inventory"), first); + } } #[test] diff --git a/docs/site/src/content/docs/configure/session.mdx b/docs/site/src/content/docs/configure/session.mdx index 8f9c1cc302..b1a9b5899a 100644 --- a/docs/site/src/content/docs/configure/session.mdx +++ b/docs/site/src/content/docs/configure/session.mdx @@ -299,11 +299,13 @@ registry-session --runtime-config /etc/registry-session/runtime.yaml gateway env The export records every configured module and page with its sign-in bindings. It names the selected BReg module for browser client generation. Routes use the longest matching prefix at a path segment boundary. Write sign-in names literally and keep the route paths to -letters, digits and `/._:~-`. +letters, digits and `/._:~-`. The selected BReg prefix omits `~` and ends with a slash. The `gatewayDigest` covers the exact Envoy JSON file bytes, including whitespace. The -`signInDigest` covers the module and page sign-in projection. Both use SHA-256. Re-export -after a runtime change and deploy the checked assembly with its matching runtime file. +`signInDigest` covers the compact JSON object containing `modules` and `pages`, with +object keys in lexicographic order and array order preserved. Both use SHA-256. After +a runtime change, re-export against the assembly and use the fresh inventory. +Deploy the checked assembly with its matching runtime file. Envoy and Session check live requests, and the product authorizes the operation. {/* Evidence: crates/registry-session/src/gateway/verify.rs, validate_checked_transport, From d6f09f99f13a669f8f836f22338ac4d6fa161a38 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 20:01:08 +0000 Subject: [PATCH 069/183] test(rstack): check task status identity separation through plans Signed-off-by: Jeremi Joslin --- .../registry-rstack-dev/src/external_breg.rs | 19 +---- crates/registry-rstack-dev/src/plan.rs | 72 +++++++++++++++++++ 2 files changed, 73 insertions(+), 18 deletions(-) diff --git a/crates/registry-rstack-dev/src/external_breg.rs b/crates/registry-rstack-dev/src/external_breg.rs index f1065ab0f5..98ca725314 100644 --- a/crates/registry-rstack-dev/src/external_breg.rs +++ b/crates/registry-rstack-dev/src/external_breg.rs @@ -432,24 +432,7 @@ mod tests { ("same-key", same_key), ("scheduling-key", different_key), ] { - #[derive(Serialize)] - struct FixtureKey<'a> { - kty: &'a str, - kid: &'a str, - alg: &'a str, - crv: &'a str, - x: &'a str, - d: &'a str, - } - let fixture = FixtureKey { - kty: &key.kty, - kid: key.kid.as_deref().unwrap(), - alg: key.alg.as_deref().unwrap(), - crv: key.crv.as_deref().unwrap(), - x: key.x.as_deref().unwrap(), - d: key.d.as_deref().unwrap(), - }; - let bytes = Zeroizing::new(serde_json::to_vec(&fixture).unwrap()); + let bytes = crate::bindings::encode_private_jwk(&key).unwrap(); crate::write_private(&root.join("fixture").join(path), &bytes).unwrap(); } let grant = |client, name| -> TaskGrant { diff --git a/crates/registry-rstack-dev/src/plan.rs b/crates/registry-rstack-dev/src/plan.rs index d139fc1254..65094c5717 100644 --- a/crates/registry-rstack-dev/src/plan.rs +++ b/crates/registry-rstack-dev/src/plan.rs @@ -2455,6 +2455,78 @@ mod tests { ); } + #[test] + fn plan_refuses_cross_product_task_status_credential_reuse() { + let (root, mut plan) = plan(json!({ + "id": "read", "product": "breg", "as": "operator", "method": "GET", + "path": "/v1/records", "expect": {"status": 200} + })); + fs::create_dir(root.path().join("schedule")).unwrap(); + fs::write(root.path().join("schedule/scheduling.yaml"), "{}").unwrap(); + fs::create_dir(root.path().join("fixture")).unwrap(); + for file in ["breg-status", "scheduling-status"] { + let key = registry_platform_crypto::generate_private_jwk( + registry_platform_crypto::GeneratedKeyAlgorithm::Es256, + ) + .unwrap(); + let bytes = crate::bindings::encode_private_jwk(&key).unwrap(); + crate::write_private(&root.path().join("fixture").join(file), &bytes).unwrap(); + } + plan.products.push( + serde_json::from_value(json!({ + "product": "scheduling", "project": "schedule", + "audience": "urn:example:journey:scheduling" + })) + .unwrap(), + ); + plan.people.insert( + "booker".to_owned(), + serde_json::from_value(json!({ + "subject": "booker", "client": "task-agent", + "grants": {"scheduling": {"profile": "booker", "scopes": ["scheduling:write"]}} + })) + .unwrap(), + ); + plan.issuer = "http://127.0.0.1:41000".to_owned(); + plan.external_jwks_uri = Some("http://127.0.0.1:41000/oauth2/jwks".to_owned()); + let task_grant = |issuer, client, key| { + json!({"taskGrant": { + "sourceIssuer": issuer, "assertionClient": "task-agent", + "statusUrl": "http://127.0.0.1:41001", + "tokenEndpoint": "http://127.0.0.1:41000/oauth2/token", + "statusClient": client, "statusKeyRef": format!("secret:file/{key}"), + "statusResource": "urn:example:journey:casework" + }}) + }; + plan.external_breg = Some( + serde_json::from_value(task_grant( + "http://127.0.0.1:41001", + "breg-status", + "breg-status", + )) + .unwrap(), + ); + for (client, key, refused_field) in [ + ("scheduling-status", "scheduling-status", None), + ("breg-status", "scheduling-status", Some("statusClient")), + ("scheduling-status", "breg-status", Some("statusKeyRef")), + ] { + plan.external_scheduling = Some( + serde_json::from_value(task_grant("https://casework.journey.example", client, key)) + .unwrap(), + ); + let validation = plan.validate(root.path()); + if let Some(field) = refused_field { + assert_eq!( + validation.unwrap_err().field, + format!("/externalScheduling/taskGrant/{field}") + ); + } else { + validation.expect("separate task-status identities"); + } + } + } + #[test] fn a_fixed_external_hook_may_use_the_managed_development_issuer() { let (root, mut plan) = plan(json!({"id": "read", "product": "breg", From 03420558ec7bdefdec3620bd7236145279ea0a9b Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 20:02:14 +0000 Subject: [PATCH 070/183] test(deploy): prove isolated registrar sign-out Signed-off-by: Jeremi Joslin (cherry picked from commit 751813e81589c4ef6544254b0d8fc10f48d146b6) --- .../examples/business-registration/README.md | 30 ++- .../identity-deployment.yaml | 10 + .../business-registration/tests/browser.mjs | 207 ++++++++++++++++++ .../tests/test_compose.py | 8 + .../business-registration/thunderid.sh | 1 + 5 files changed, 252 insertions(+), 4 deletions(-) create mode 100644 deploy/examples/business-registration/tests/browser.mjs diff --git a/deploy/examples/business-registration/README.md b/deploy/examples/business-registration/README.md index f770c98329..f0e58f1a3e 100644 --- a/deploy/examples/business-registration/README.md +++ b/deploy/examples/business-registration/README.md @@ -3,7 +3,7 @@ Run the business-registration preview's compiled function and static page with Registry Session, Envoy, ThunderID, BReg and PostgreSQL. The application opens at `https://127.0.0.1:8443/apply/`. Use a disposable project and synthetic -registrar. The example uses production posture and verified TLS with loopback +registrars. The example uses production posture and verified TLS with loopback host bindings. The browser receives an opaque Session cookie. Envoy checks it and supplies @@ -67,7 +67,7 @@ package receipt. | `thunderid/bootstrap.yaml` | A copy of [thunderid.yaml](thunderid.yaml), used once with writable backing stores | | `thunderid/deployment.yaml` | The same ThunderID base plus the generated store settings, used by the issuer after setup | | `thunderid/bootstrap-secrets/` | `DB_CONFIG_PASSWORD` and `ADMIN_PASSWORD` for the one-shot setup | -| `thunderid/secrets/` | `DB_CONFIG_PASSWORD`, `REGISTRAR_CLIENT_SECRET`, and `REGISTRAR_PASSWORD` for serving | +| `thunderid/secrets/` | `DB_CONFIG_PASSWORD`, `REGISTRAR_CLIENT_SECRET`, `REGISTRAR_PASSWORD`, and `SECOND_REGISTRAR_PASSWORD` for serving | | `thunderid/resources/`, `thunderid/front-gateway/`, `thunderid/identity-receipt.json` | Output of identity generation | | `gateway/envoy.json` | Reviewed complete Envoy configuration from the matching Session CLI | | `gateway-checked/`, `relay/`, `breg/audit/`, `session/audit/` | Empty private directories owned by the instance UID | @@ -76,7 +76,8 @@ The Session client secret equals `REGISTRAR_CLIENT_SECRET`. Both ThunderID `DB_CONFIG_PASSWORD` files carry the value in `postgres/thunderid-password`. The PostgreSQL files must be readable by the image's UID 999 and the ThunderID secrets by UID 10001. Give private keys and secret files mode 0600. -Use distinct random values for admin, registrar, database and audit credentials. +Use distinct random values for admin, both registrar passwords, database and +audit credentials. BReg URLs target `postgres:5432`; runtime and migration use different roles and passwords and point at the same registry database. BReg's CA file carries `postgres-ca.pem`. Configure the local browser to resolve @@ -157,7 +158,8 @@ done ``` The ThunderID setup job creates the built-in password flow first. The serving -issuer then loads the registrar app and user from the generated resources. +issuer then loads the registrar app and two synthetic users from the generated +resources. Before BReg starts, a one-shot checks the issuer's HTTPS discovery document and signing keys from BReg's network namespace. The setup containers are for fresh state. PostgreSQL data and ThunderID signing @@ -174,5 +176,25 @@ refusals, the sign-in redirect, and Session and origin refusals. Then open register a synthetic business. The page should show its Record ID from BReg. Verify the Record through the same BReg route and registrar session. +For the two-person browser check, use a Playwright installation with Chromium +and set `PLAYWRIGHT_MODULE` to the absolute path of its module entry point. Set +`REFERENCE_TEST_CHROMIUM` if you use a separately installed Chromium executable. +Set `REFERENCE_TEST_PASSWORD_DIR` to a private directory containing owner-only +copies of the two synthetic registrar password files. The check pins the +fixture certificates and resolves the issuer to loopback inside Chromium. + +```bash +node "$RECIPE/tests/browser.mjs" \ + "$PLAYWRIGHT_MODULE" "$REFERENCE_CONFIG" "$REFERENCE_TEST_PASSWORD_DIR" "$BUSINESS_BUNDLE" +``` + +The test signs in two distinct registrars for the central office in separate +browser contexts with one BReg audience. Each uses the frozen page to register +a business and reads back its exact BReg Record. The test signs out the first +registrar through a top-level form and verifies that the old session cookie +is refused, the protected page asks for sign-in again, and the second registrar +can still read its Record. It checks application requests for browser-sent +Authorization headers throughout. + Release-candidate smoke wiring, published Session and Coordinator images, and the `rstack dev` route-parity gate are v0.52 work. diff --git a/deploy/examples/business-registration/identity-deployment.yaml b/deploy/examples/business-registration/identity-deployment.yaml index 43a47ebd08..8cc5566963 100644 --- a/deploy/examples/business-registration/identity-deployment.yaml +++ b/deploy/examples/business-registration/identity-deployment.yaml @@ -26,3 +26,13 @@ users: grants: - product: breg accessProfiles: [business-registrar] + - id: reference-registrar-two + username: reference-registrar-two + email: reference-registrar-two@example.invalid + passwordRef: secret:env/SECOND_REGISTRAR_PASSWORD + claims: + registry_actor_kind: human + registry_office: central + grants: + - product: breg + accessProfiles: [business-registrar] diff --git a/deploy/examples/business-registration/tests/browser.mjs b/deploy/examples/business-registration/tests/browser.mjs new file mode 100644 index 0000000000..e2a7a5a043 --- /dev/null +++ b/deploy/examples/business-registration/tests/browser.mjs @@ -0,0 +1,207 @@ +import assert from 'node:assert/strict' +import { createHash, randomUUID, X509Certificate } from 'node:crypto' +import { readFile } from 'node:fs/promises' +import { isAbsolute, join } from 'node:path' +import { pathToFileURL } from 'node:url' + +const [playwright, config, passwords, bundle] = process.argv.slice(2) +if (![playwright, config, passwords, bundle].every(path => path && isAbsolute(path))) { + throw new Error('Pass absolute paths to the Playwright module, reference inputs, test passwords, and frozen bundle.') +} + +const origin = 'https://127.0.0.1:8443' +const issuer = 'https://identity.reference.test:9443' +const apply = origin + '/apply/' +const cookieName = '__Host-registry-session' +const accessProfile = 'business-registrar' +const registrars = [ + { username: 'reference-registrar', password: 'REGISTRAR_PASSWORD' }, + { username: 'reference-registrar-two', password: 'SECOND_REGISTRAR_PASSWORD' }, +] +const identity = JSON.parse(await readFile(join(config, 'thunderid', 'identity-receipt.json'), 'utf8')) +const pins = await Promise.all(['app', 'issuer'].map(async name => { + const certificate = new X509Certificate(await readFile(join(config, name + '-tls', name + '.crt'))) + return createHash('sha256').update(certificate.publicKey.export({ type: 'spki', format: 'der' })).digest('base64') +})) +const { chromium } = await import(pathToFileURL(playwright)) +const browser = await chromium.launch({ + executablePath: process.env.REFERENCE_TEST_CHROMIUM, + args: [ + '--host-resolver-rules=MAP identity.reference.test 127.0.0.1', + '--no-proxy-server', + '--ignore-certificate-errors-spki-list=' + pins.join(','), + ], +}) +const authorizationHeaders = [] + +async function startRegistrar(person) { + const context = await browser.newContext() + const page = await context.newPage() + page.setDefaultTimeout(15_000) + page.on('request', request => { + if (new URL(request.url()).origin === origin) authorizationHeaders.push(request.headerValue('authorization')) + }) + await page.goto(apply) + await page.waitForURL(url => url.origin === issuer) + await page.getByRole('textbox', { name: /username/i }).fill(person.username) + await page.locator('input[type=password]').fill((await readFile(join(passwords, person.password), 'utf8')).trim()) + await page.getByRole('button', { name: /sign in/i }).click() + await page.waitForURL(apply) + const { signIn, claims } = await sessionIdentity(page) + assert.equal(signIn, 'registrar') + assert.ok(typeof claims?.sub === 'string' && claims.sub.length > 0) + assert.equal(claims.sub, identity.users[person.username].sub) + return { context, page, subject: claims.sub } +} + +async function sessionIdentity(page) { + return page.evaluate(async () => { + const response = await fetch('/session/me') + return response.ok ? response.json() : {} + }) +} + +async function checkAssets(page) { + const manifest = JSON.parse(await readFile(join(bundle, 'manifest.json'), 'utf8')) + const assets = {} + for (const [file, suffix] of [['index.html', ''], ['app.js', 'app.js'], ['service.css', 'service.css']]) { + const expected = createHash('sha256').update(await readFile(join(bundle, manifest.staticOutput, file))).digest('hex') + const actual = await page.evaluate(async path => { + const response = await fetch(path) + const hash = new Uint8Array(await crypto.subtle.digest('SHA-256', await response.arrayBuffer())) + return { status: response.status, digest: Array.from(hash, byte => byte.toString(16).padStart(2, '0')).join('') } + }, '/apply/' + suffix) + assert.equal(actual.status, 200) + assert.equal(actual.digest, expected) + assets[file] = actual.digest + } + return assets +} + +async function register(page, name) { + const legalName = 'Synthetic business for ' + name + const registrationNumber = 'LOGOUT-' + randomUUID().slice(0, 8) + await page.locator('#legal-name').fill(legalName) + await page.locator('#registration-number').fill(registrationNumber) + const response = page.waitForResponse(item => + item.url() === origin + '/api/functions/register-business' && item.request().method() === 'POST') + await page.getByRole('button', { name: 'Register business', exact: true }).click() + const submitted = await response + assert.equal(submitted.status(), 200) + const { recordId } = await submitted.json() + assert.match(recordId, /^[0-9a-f-]{36}$/i) + await page.getByRole('heading', { name: 'Business registered' }).waitFor() + assert.equal(await page.locator('#record-id').textContent(), recordId) + return { recordId, legalName, registrationNumber, registeringOffice: 'central' } +} + +function recordPath(recordId) { + return '/registry/businesses/v1/records/businesses/' + encodeURIComponent(recordId) +} + +async function readRecord(page, recordId) { + return page.evaluate(async ({ path, profile }) => { + const response = await fetch(path, { + cache: 'no-store', + headers: { 'Registry-Client': 'page', 'Registry-Access-Profile': profile }, + }) + return { status: response.status, body: await response.json() } + }, { path: recordPath(recordId), profile: accessProfile }) +} + +async function navigateToRecord(page, recordId) { + // The signed-out document's CSP forbids fetch. Navigate with the same page binding instead. + await page.setExtraHTTPHeaders({ + 'Registry-Client': 'page', + 'Registry-Access-Profile': accessProfile, + 'Cache-Control': 'no-cache', + }) + try { + return await page.goto(origin + recordPath(recordId)) + } finally { + await page.setExtraHTTPHeaders({}) + } +} + +async function assertOwnRecord(page, expected) { + const { status, body } = await readRecord(page, expected.recordId) + assert.equal(status, 200) + const { recordId, domainData } = body.data + const { legalName, registrationNumber, registeringOffice } = domainData + assert.deepEqual({ recordId, legalName, registrationNumber, registeringOffice }, expected) +} + +async function signOut(page) { + stage = 'submit the first registrar sign-out form' + const response = page.waitForResponse(item => + item.url() === origin + '/session/sign-out' && item.request().method() === 'POST') + // The frozen page is unchanged. Submit a top-level form as a service's own page would. + await page.evaluate(() => { + const form = document.createElement('form') + form.method = 'post' + form.action = '/session/sign-out' + const button = document.createElement('button') + button.textContent = 'Sign out for acceptance test' + form.append(button) + document.body.append(form) + }) + await page.getByRole('button', { name: 'Sign out for acceptance test' }).click() + assert.equal((await response).status(), 303) + stage = 'return from the issuer to the signed-out page' + await page.waitForURL(origin + '/session/signed-out') +} + +let stage = 'sign in two registrars' +let report +try { + const first = await startRegistrar(registrars[0]) + const second = await startRegistrar(registrars[1]) + assert.notEqual(first.subject, second.subject) + stage = 'verify assets and register both businesses' + const assetSha256 = await checkAssets(first.page) + const firstRecord = await register(first.page, registrars[0].username) + const secondRecord = await register(second.page, registrars[1].username) + assert.notEqual(firstRecord.recordId, secondRecord.recordId) + + stage = 'verify both exact BReg readbacks' + await assertOwnRecord(first.page, firstRecord) + await assertOwnRecord(second.page, secondRecord) + + stage = 'sign out the first registrar and refuse its old session' + const cookie = (await first.context.cookies(origin)).find(item => item.name === cookieName) + assert.ok(cookie?.secure && cookie.httpOnly) + await signOut(first.page) + stage = 'refuse the first registrar without a session cookie' + assert.ok(!(await first.context.cookies(origin)).some(item => item.name === cookieName)) + assert.equal((await navigateToRecord(first.page, firstRecord.recordId)).status(), 401) + stage = 'refuse the first registrar with the stale cookie' + await first.context.addCookies([cookie]) + const stale = await navigateToRecord(first.page, firstRecord.recordId) + const sentCookie = await stale.request().headerValue('cookie') + assert.ok(sentCookie?.split(';').some(item => item.trim() === cookie.name + '=' + cookie.value)) + assert.equal(stale.status(), 401) + assert.equal(await stale.headerValue('registry-session-answer'), '1') + assert.equal((await stale.json()).code, 'session.expired') + stage = 'require a new issuer sign-in for the protected page' + await first.page.goto(apply) + await first.page.waitForURL(url => url.origin === issuer) + await first.page.getByRole('textbox', { name: /username/i }).waitFor() + + stage = 'verify that the second registrar is still signed in' + assert.equal((await sessionIdentity(second.page)).claims?.sub, second.subject) + await assertOwnRecord(second.page, secondRecord) + assert.ok((await Promise.all(authorizationHeaders)).every(value => value === null)) + report = { + distinctSubjects: true, separateContexts: true, assetSha256, formSubmissions: [200, 200], + owningRecordReads: [200, 200], + first: { signOut: 303, recordAfterSignOut: 401, staleCookieSent: true, staleCookie: 401, signInRequired: true }, + second: { sameSubjectAfterFirstSignOut: true, owningRead: 200 }, + noBrowserAuthorizationHeader: true, + } +} catch (error) { + console.error('Reference browser test stopped at ' + stage + ' (' + error.name + ').') + process.exitCode = 1 +} finally { + await browser.close() +} +if (report) console.log(JSON.stringify(report, null, 2)) diff --git a/deploy/examples/business-registration/tests/test_compose.py b/deploy/examples/business-registration/tests/test_compose.py index cdf540f87c..c8fc4a380f 100644 --- a/deploy/examples/business-registration/tests/test_compose.py +++ b/deploy/examples/business-registration/tests/test_compose.py @@ -82,3 +82,11 @@ def test_breg_waits_for_the_issuer_from_its_own_namespace(self): self.services["breg"]["depends_on"]["issuer-ready"]["condition"], "service_completed_successfully" ) self.assertTrue(all(mount["read_only"] for mount in readiness["volumes"])) + + def test_browser_registrars_have_separate_passwords_for_the_supported_office(self): + users = (EXAMPLE / "identity-deployment.yaml").read_text().split("\nusers:\n", 1)[1] + first, second = users.split(" - id: reference-registrar-two\n") + self.assertIn("secret:env/REGISTRAR_PASSWORD", first) + self.assertIn("registry_office: central", first) + self.assertIn("secret:env/SECOND_REGISTRAR_PASSWORD", second) + self.assertIn("registry_office: central", second) diff --git a/deploy/examples/business-registration/thunderid.sh b/deploy/examples/business-registration/thunderid.sh index 2116e5d375..2383b04cea 100644 --- a/deploy/examples/business-registration/thunderid.sh +++ b/deploy/examples/business-registration/thunderid.sh @@ -21,6 +21,7 @@ case "${1:-}" in serve) read_secret REGISTRAR_CLIENT_SECRET read_secret REGISTRAR_PASSWORD + read_secret SECOND_REGISTRAR_PASSWORD exec ./start.sh ;; setup) From c594ef536285f538e971a79621bf658c0f71103c Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 20:04:20 +0000 Subject: [PATCH 071/183] fix(journeys): preserve aligned Casework starter files Signed-off-by: Jeremi Joslin (cherry picked from commit d8dd4796ee77ccb64cfc7caa730ad46d50873179) --- products/platform/journeys/rstack-dev.sh | 7 ++++--- .../platform/journeys/test_journey_tables.py | 21 +++++++++++++++++++ 2 files changed, 25 insertions(+), 3 deletions(-) diff --git a/products/platform/journeys/rstack-dev.sh b/products/platform/journeys/rstack-dev.sh index 3b474a2b45..df9cf059b6 100755 --- a/products/platform/journeys/rstack-dev.sh +++ b/products/platform/journeys/rstack-dev.sh @@ -561,9 +561,10 @@ walk_product() { ;; documents) add_documents_hooks "$project" ;; casework) - # Use the generated test person's issuer for the starter's - # trusted producer on this disposable project. - perl -pi -e 's@^ issuer: http://127[.]0[.]0[.]1:8093$@ issuer: https://identity.casework.example.test@' "$project/casework.yaml" + # Released starters can still name the old loopback issuer. + if grep -Fxq ' issuer: http://127.0.0.1:8093' "$project/casework.yaml"; then + perl -pi -e 's@^ issuer: http://127[.]0[.]0[.]1:8093$@ issuer: https://identity.casework.example.test@' "$project/casework.yaml" + fi ;; adapter) start_adapter_source "$project" "$work" ;; evidence) start_evidence_source "$project" ;; diff --git a/products/platform/journeys/test_journey_tables.py b/products/platform/journeys/test_journey_tables.py index 7c10167b5a..246e423f68 100644 --- a/products/platform/journeys/test_journey_tables.py +++ b/products/platform/journeys/test_journey_tables.py @@ -1115,6 +1115,27 @@ def test_promote_refuses_thunderid_run_directory(self): class CaseworkProducerFixture(unittest.TestCase): + def test_managed_starter_only_rewrites_the_released_issuer(self): + source = (TABLES / "rstack-dev.sh").read_text(encoding="utf-8") + start = source[source.index("# start: one command"):source.index("start_run start")] + case = re.search(r"^\tcasework\)\n(.*?)^\t\t;;", start, re.M | re.S) + self.assertIsNotNone(case) + legacy = "http://127.0.0.1:8093" + aligned = "https://identity.casework.example.test" + for issuer in (legacy, aligned): + with self.subTest(issuer=issuer), tempfile.TemporaryDirectory() as directory: + project = Path(directory) + policy = project / "casework.yaml" + policy.write_text(f" issuer: {issuer}\n subject: fixture-subject\n", encoding="utf-8") + inode = policy.stat().st_ino + subprocess.run( + ["bash", "-eu", "-c", 'project=$1\n' + case.group(1), "casework-starter", directory], + check=True, timeout=5, + ) + self.assertEqual(policy.read_text(), f" issuer: {aligned}\n subject: fixture-subject\n") + if issuer == aligned: + self.assertEqual(policy.stat().st_ino, inode) + def test_binds_either_standalone_starter_issuer(self): script = (TABLES / "own-provider.sh").read_text(encoding="utf-8") functions = [] From 5b6c651508da7761a3d607002d404b951f728632 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 20:06:24 +0000 Subject: [PATCH 072/183] docs(casework): staff the starter queue without replacing its files Signed-off-by: Jeremi Joslin --- .../docs/configure/casework-directory.mdx | 21 ++++---- .../src/content/docs/configure/casework.mdx | 4 +- .../content/docs/tutorials/first-casework.mdx | 53 +++++++++++-------- 3 files changed, 43 insertions(+), 35 deletions(-) diff --git a/docs/site/src/content/docs/configure/casework-directory.mdx b/docs/site/src/content/docs/configure/casework-directory.mdx index 3b393598df..e1bd101070 100644 --- a/docs/site/src/content/docs/configure/casework-directory.mdx +++ b/docs/site/src/content/docs/configure/casework-directory.mdx @@ -36,15 +36,16 @@ Only an [access profile](../../reference/glossary/#access-profile) with the `adm ## Seed it for the development run -A new directory is empty. The run's journey, `dev-journeys.yaml`, seated the team with the same -bootstrap call a deployment uses, as the plan's `administrator` person: - -```yaml title="dev-journeys.yaml" test-excerpt="tutorial-work/casework/dev-journeys.yaml" -body: - teamId: decisions-team - staff: [{issuer: https://identity.casework.example.test, subject: staff}] - supervisors: [] - queueId: decisions +A new directory is empty. In the tutorial, the plan's `administrator` seated the team +using the same bootstrap call a deployment uses. The body is in `directory-bootstrap.json`. + +```json title="directory-bootstrap.json" test-excerpt="tutorial-work/casework/directory-bootstrap.json" +{ + "teamId": "decisions-team", + "queueId": "decisions", + "staff": [{"issuer": "https://identity.casework.example.test", "subject": "staff"}], + "supervisors": [] +} ``` The body names one team and the one declared queue it serves. Its staff and supervisors are an @@ -95,7 +96,7 @@ A deployment's first administrator creates the first team with one call, naming } ``` -```sh test-skip="the run's journey already seeded its directory, so revision 0 is refused" +```sh test-skip="the tutorial already bootstrapped this directory, so revision 0 is refused" curl -sS --fail-with-body --header @"$(headers_for administrator)" \ --header 'Content-Type: application/json' \ --header 'If-Match: "0"' \ diff --git a/docs/site/src/content/docs/configure/casework.mdx b/docs/site/src/content/docs/configure/casework.mdx index 9142040947..435789efbb 100644 --- a/docs/site/src/content/docs/configure/casework.mdx +++ b/docs/site/src/content/docs/configure/casework.mdx @@ -27,8 +27,8 @@ still going. ## Read the project files -`casework.yaml` is the policy. `dev.yaml` and `dev-journeys.yaml`, which you wrote in the -tutorial, describe the local run for `rstack dev`. `fixtures/` holds the cases `test` proves, and +`casework.yaml` is the policy. The generated `dev.yaml` and `dev-journeys.yaml` describe the +local run for `rstack dev`. `fixtures/` holds the cases `test` proves, and `runtime.example.yaml` is a starting runtime configuration for a deployment. `.casework/schemas/` holds the JSON Schemas your editor reads through each file's first-line comment. Check the project as it stands: diff --git a/docs/site/src/content/docs/tutorials/first-casework.mdx b/docs/site/src/content/docs/tutorials/first-casework.mdx index 4b118a1ad1..ea91b08158 100644 --- a/docs/site/src/content/docs/tutorials/first-casework.mdx +++ b/docs/site/src/content/docs/tutorials/first-casework.mdx @@ -115,28 +115,8 @@ issuer and subject in `casework.yaml`. {/* Evidence: crates/registry-caseworkctl/src/project.rs, STANDALONE_YAML, development_plan. */} -A new Casework directory has no staff. Replace `dev-journeys.yaml` to have the administrator -seat one team on the `decisions` queue and put the person `staff` in it: - -```yaml title="dev-journeys.yaml" test-file -apiVersion: id.registrystack.org/formats/rstack/journeys/v1alpha1 -kind: RStackJourneys -journeys: - - id: staff-the-queue - steps: - - id: staff-the-queue - product: casework - as: administrator - method: POST - path: /v1/directory/bootstrap - headers: {If-Match: '"0"', Idempotency-Key: staff-the-queue} - body: - teamId: decisions-team - staff: [{issuer: https://identity.casework.example.test, subject: staff}] - supervisors: [] - queueId: decisions - expect: {status: 200} -``` +Keep the generated `dev.yaml` and `dev-journeys.yaml`. The starter journey checks the +running service. You'll staff the empty directory with the administrator after startup. ## Start the run @@ -150,7 +130,7 @@ run_id="$(jq -r .run_id run.json)" casework_url="$(jq -r .products.casework run.json)" ``` -PostgreSQL runs in Docker, and the run has seated one staff team. Its state, keys and logs live in +PostgreSQL runs in Docker. Its state, keys and logs live in the run's own owner-only directory, outside your project. Each call below needs a short-lived token for one of the plan's people. This function asks for one and prints the header file to pass to curl: @@ -163,6 +143,33 @@ headers_for() { {/* Evidence: crates/registry-rstack-dev/src/lib.rs; crates/registry-rstack/tests/dev_run.rs, casework_alone_runs_end_to_end; products/casework/examples/standalone-decision/dev.yaml. */} +## Staff the review queue + +Save the directory bootstrap as `directory-bootstrap.json`. It seats one team on +the `decisions` queue and names the staff person's issuer and subject from `dev.yaml`. + +```json title="directory-bootstrap.json" test-file +{ + "teamId": "decisions-team", + "queueId": "decisions", + "staff": [{"issuer": "https://identity.casework.example.test", "subject": "staff"}], + "supervisors": [] +} +``` + +Send it as the administrator. The `If-Match` header names revision zero, the empty directory. + +```sh +curl -sS --fail-with-body --header @"$(headers_for administrator)" \ + --header 'Content-Type: application/json' \ + --header 'If-Match: "0"' \ + --header 'Idempotency-Key: staff-the-queue' \ + --data @directory-bootstrap.json "$casework_url/v1/directory/bootstrap" +``` + +{/* Evidence: crates/registry-casework/src/http.rs, bootstrap(); + crates/registry-casework-core/src/http.rs, BootstrapDirectoryRequest. */} + ## Submit a ReviewRequest Save the request. It names the policy, the subject under review, and the snapshot a reviewer will From f8c6d0a4838bb8fce31ed752da6441a5ecc961f0 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 20:24:09 +0000 Subject: [PATCH 073/183] fix(rstack): scope lint expectation to the JSON Schema callback Signed-off-by: Jeremi Joslin --- crates/registry-rstack-dev/src/owner_report.rs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/crates/registry-rstack-dev/src/owner_report.rs b/crates/registry-rstack-dev/src/owner_report.rs index 13c3b88bf8..95477b8fa4 100644 --- a/crates/registry-rstack-dev/src/owner_report.rs +++ b/crates/registry-rstack-dev/src/owner_report.rs @@ -548,6 +548,10 @@ struct ExactInteger { nullable: bool, } +#[expect( + clippy::result_large_err, + reason = "jsonschema requires its keyword factory to return ValidationError by value" +)] fn exact_integer<'a>( parent: &'a serde_json::Map, _: &'a Value, From b062d1b72cde1a1a09723b5e63d448cf1130df40 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 20:18:09 +0000 Subject: [PATCH 074/183] test(journeys): measure Casework missing-scope diagnostics Signed-off-by: Jeremi Joslin --- products/platform/journeys/rstack-dev.sh | 59 ++++++++++++++++++- .../platform/journeys/test_journey_tables.py | 59 +++++++++++++++++++ 2 files changed, 116 insertions(+), 2 deletions(-) diff --git a/products/platform/journeys/rstack-dev.sh b/products/platform/journeys/rstack-dev.sh index df9cf059b6..e72f5988e5 100755 --- a/products/platform/journeys/rstack-dev.sh +++ b/products/platform/journeys/rstack-dev.sh @@ -23,13 +23,24 @@ # [--out DIR] [--expected FILE [--strict]] [--keep] # Use --product breg --attachments compose for the sibling receiver and # unpublished private PostgreSQL attachment proof. +# Use --product casework --planted-error casework-missing-scope for the +# disposable scope diagnostic probe after T1. set -euo pipefail # shellcheck disable=SC1091 # lib.sh is checked on its own source "$(dirname -- "${BASH_SOURCE[0]}")/lib.sh" -journey_init rstack-dev --value-option attachments -- "$@" +journey_init rstack-dev --value-option attachments --value-option planted-error -- "$@" +journey_option_value planted-error RSTACK_PLANTED_ERROR +case "$RSTACK_PLANTED_ERROR" in +'') ;; +casework-missing-scope) + [[ "${JOURNEY_PRODUCTS[*]}" == casework && "$JOURNEY_KEEP" == 0 ]] || + journey_usage_error "--planted-error casework-missing-scope requires --product casework and no --keep" + ;; +*) journey_usage_error "--planted-error $RSTACK_PLANTED_ERROR: choose casework-missing-scope" ;; +esac journey_option_value attachments RSTACK_ATTACHMENTS RSTACK_ATTACHMENTS=${RSTACK_ATTACHMENTS:-loopback} case "$RSTACK_ATTACHMENTS" in @@ -498,6 +509,43 @@ issue_token() { journey_secret_register "token-$variable" "$variable" } +# Scope fixtures share an inert scope so both signed tokens remain access +# tokens. Their only authorization difference is the required staff scope. +prepare_casework_scope_probe() { + perl -0pi -e ' + my $entry = qr/^ staff:\n((?:^ {4}[^\n]*\n)+)/m; + !/^ staff-missing-scope:/m && /$entry/ or die "expected a generated staff plan entry\n"; + my $staff = $1; + my $control = $staff; + my $required = " - casework:staff\n"; + my $shared = " - casework:diagnostic-control\n"; + $control =~ s/^\Q$required\E/$shared/m or die "generated staff scope is missing\n"; + $staff =~ s/^\Q$required\E/$required$shared/m or die "generated staff scope is missing\n"; + s/$entry/ staff:\n$staff staff-missing-scope:\n$control/; + ' "$1" +} + +record_casework_scope_probe() { + # shellcheck disable=SC2034 # issue_token and --bearer use control by name. + local run=$1 url=$2 path=$3 work=$4 control='' trace + issue_token call "$run" staff-missing-scope control || + journey_harness_failure "cannot issue the Casework missing-scope control" + journey_http call --expect-status 403 --bearer control GET "$url$path" || + journey_harness_failure "Casework did not refuse the missing-scope control with HTTP 403" + journey_count errors-that-say-what-to-change 0 + trace=$(jq -er 'select(.code == "profile.not-authorized" and .failedCheck == "scope") + | .traceId | strings | select(test("^[0-9a-f]{32}$"))' "$JOURNEY_STEP_STDOUT") || return 0 + # shellcheck disable=SC2016 # jq binds $trace. + if journey_poll 5 -- jq -Rse --arg trace "$trace" ' + first(split("\n")[] | fromjson? | .fields | + select(.trace_id == $trace and .failed_check == "scope" + and .scope_claim == "scope" and .required_scope == "casework:staff") | + {trace_id, failed_check, scope_claim, required_scope})' \ + "$STATE_DIR/$run/logs/casework-runtime.log" >"$work/casework-scope-diagnostic.json"; then + journey_count errors-that-say-what-to-change + fi +} + # unexpected_answer STEP: the call answered with a status this journey has no # code for. It is a harness failure so that a new kind of refusal is looked at # and named, never recorded under a code the product did not print. @@ -565,6 +613,10 @@ walk_product() { if grep -Fxq ' issuer: http://127.0.0.1:8093' "$project/casework.yaml"; then perl -pi -e 's@^ issuer: http://127[.]0[.]0[.]1:8093$@ issuer: https://identity.casework.example.test@' "$project/casework.yaml" fi + if [[ "${RSTACK_PLANTED_ERROR:-}" == casework-missing-scope ]]; then + prepare_casework_scope_probe "$project/dev.yaml" || + journey_harness_failure "cannot prepare the Casework missing-scope control" + fi ;; adapter) start_adapter_source "$project" "$work" ;; evidence) start_evidence_source "$project" ;; @@ -642,11 +694,14 @@ walk_product() { jq -e --arg id "$message_id" '.links.self == ("/v1/messages/" + $id)' "$JOURNEY_STEP_STDOUT" >/dev/null || journey_harness_failure "the starter message receipt did not identify its retained message" fi - journey_pass call if [[ "$product" == messaging || ("$CALL_METHOD" == GET && -n "$PERSON") ]]; then journey_reached t1 first_read=1 fi + if [[ "$product" == casework && "${RSTACK_PLANTED_ERROR:-}" == casework-missing-scope ]]; then + record_casework_scope_probe "$run" "$url" "$CALL_PATH" "$work" + fi + journey_pass call # The BReg and Documents writes also test retention after restart. case "$product" in diff --git a/products/platform/journeys/test_journey_tables.py b/products/platform/journeys/test_journey_tables.py index 246e423f68..dcbb284427 100644 --- a/products/platform/journeys/test_journey_tables.py +++ b/products/platform/journeys/test_journey_tables.py @@ -1115,6 +1115,65 @@ def test_promote_refuses_thunderid_run_directory(self): class CaseworkProducerFixture(unittest.TestCase): + def test_planted_scope_counts_only_the_correlated_actionable_diagnostic(self): + source = (TABLES / "rstack-dev.sh").read_text(encoding="utf-8") + probe = re.search(r"^record_casework_scope_probe\(\) \{\n.*?^\}\n", source, re.M | re.S) + self.assertIsNotNone(probe) + driver = r""" +STATE_DIR=$1 +JOURNEY_STEP_STDOUT=$1/response.json +issue_token() { :; } +journey_http() { [[ "$*" == "call --expect-status 403 --bearer control GET http://localhost/read" ]]; } +journey_harness_failure() { printf '%s\n' "$1" >&2; exit 3; } +journey_poll() { shift 2; "$@"; } +journey_count() { printf '%s\n' "${2:-1}"; } +record_casework_scope_probe sample http://localhost /read "$1" +""" + trace = "01a2333e0412314aaf6d6dbbe6fd98c0" + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + (root / "response.json").write_text(json.dumps({ + "code": "profile.not-authorized", "failedCheck": "scope", "traceId": trace, + }), encoding="utf-8") + logs = root / "sample/logs" + logs.mkdir(parents=True) + for label, overrides, count in (("matching", {}, "0\n1"), ("other trace", {"trace_id": "other"}, "0"), + ("missing remedy", {"required_scope": ""}, "0")): + with self.subTest(label=label): + (logs / "casework-runtime.log").write_text(json.dumps({"fields": { + "trace_id": trace, "failed_check": "scope", "scope_claim": "scope", + "required_scope": "casework:staff", **overrides, + }}), encoding="utf-8") + result = subprocess.check_output( + ["bash", "-eu", "-c", probe.group(0) + driver, "casework-scope-count", directory], + text=True, timeout=5, + ) + self.assertEqual(result.strip(), count) + + def test_planted_scope_fixture_preserves_staff_authority_and_only_omits_required_scope(self): + source = (TABLES / "rstack-dev.sh").read_text(encoding="utf-8") + prepare = re.search(r"^prepare_casework_scope_probe\(\) \{\n.*?^\}\n", source, re.M | re.S) + self.assertIsNotNone(prepare) + with tempfile.TemporaryDirectory() as directory: + path = Path(directory) / "dev.yaml" + original = {"client": "staff", "subject": "staff", "grants": {"casework": { + "claims": {"registry_actor_kind": "human"}, "profile": "staff", "scopes": ["casework:staff"], + }}} + path.write_text(yaml.safe_dump({"people": {"staff": original, "supervisor": {"client": "supervisor"}}, + "products": [{"product": "casework"}]}), encoding="utf-8") + subprocess.run( + ["bash", "-eu", "-c", prepare.group(0) + '\nprepare_casework_scope_probe "$1"', + "casework-scope-probe", str(path)], check=True, timeout=5, + ) + people = yaml.safe_load(path.read_text(encoding="utf-8"))["people"] + staff, control = people["staff"], people["staff-missing-scope"] + scopes = staff["grants"]["casework"].pop("scopes") + control_scopes = control["grants"]["casework"].pop("scopes") + self.assertEqual(staff, control) + self.assertEqual(set(scopes) - set(control_scopes), {"casework:staff"}) + self.assertTrue(control_scopes and set(control_scopes) < set(scopes)) + self.assertEqual(people["supervisor"], {"client": "supervisor"}) + def test_managed_starter_only_rewrites_the_released_issuer(self): source = (TABLES / "rstack-dev.sh").read_text(encoding="utf-8") start = source[source.index("# start: one command"):source.index("start_run start")] From f6113b8f5d59e245feb491367694656cf8a3340d Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 20:38:46 +0000 Subject: [PATCH 075/183] fix(release): classify the Session binary as a distribution-only asset With the Session gate set, its numbered payloads had no release unit owner and rstack refused the unclassified binary. Add a held session unit and list registry-session beside the language server as a standalone asset that rstack never installs. Signed-off-by: Jeremi Joslin --- crates/registry-rstack/src/model.rs | 2 +- crates/registry-rstack/tests/release_manifest.rs | 14 ++++++++++++++ release/scripts/rstack_components.py | 2 +- release/scripts/test_release_units.py | 13 +++++++++++++ release/scripts/test_rstack_components.py | 12 ++++++++++++ release/units.yaml | 10 ++++++++++ 6 files changed, 51 insertions(+), 2 deletions(-) diff --git a/crates/registry-rstack/src/model.rs b/crates/registry-rstack/src/model.rs index 7192f6debe..1f8f7df973 100644 --- a/crates/registry-rstack/src/model.rs +++ b/crates/registry-rstack/src/model.rs @@ -11,7 +11,7 @@ const RELEASE_SCHEMAS: [&str; 2] = [ const PLATFORMS: [&str; 3] = ["linux-amd64", "linux-arm64", "macos-arm64"]; // Binaries published as standalone release assets that rstack never installs. // Mirrors DISTRIBUTION_ONLY_BINARIES in release/scripts/rstack_components.py. -const DISTRIBUTION_ONLY_BINARIES: [&str; 1] = ["registry-language-server"]; +const DISTRIBUTION_ONLY_BINARIES: [&str; 2] = ["registry-language-server", "registry-session"]; #[derive(Debug, Clone, Deserialize, Serialize)] #[serde(deny_unknown_fields)] diff --git a/crates/registry-rstack/tests/release_manifest.rs b/crates/registry-rstack/tests/release_manifest.rs index 574d34ed9c..1f8e96ae8c 100644 --- a/crates/registry-rstack/tests/release_manifest.rs +++ b/crates/registry-rstack/tests/release_manifest.rs @@ -245,6 +245,18 @@ fn distribution_only_language_server_needs_no_component() { .contains_key("language-server")); } +#[test] +fn distribution_only_session_needs_no_component() { + let mut value = stack_v3_document(); + for platform in ["linux-amd64", "linux-arm64", "macos-arm64.tar.gz"] { + push_binary_payload(&mut value, &format!("registry-session-v0.44.0-{platform}")); + } + + let manifest = ReleaseManifest::parse(&serde_json::to_vec(&value).unwrap()) + .expect("the session service is a release asset, not an rstack component"); + assert!(!manifest.components.components.contains_key("session")); +} + #[test] fn unclassified_binary_payload_is_rejected() { for name in [ @@ -253,6 +265,8 @@ fn unclassified_binary_payload_is_rejected() { "registry-language-server-v0.44.0-windows-amd64", "registry-language-server-v0.44.0-macos-arm64", "registry-language-server-extra-v0.44.0-linux-amd64", + "registry-session-v0.44.0-macos-arm64", + "registry-session-v0.44.0-windows-amd64", ] { let mut value = stack_v3_document(); push_binary_payload(&mut value, name); diff --git a/release/scripts/rstack_components.py b/release/scripts/rstack_components.py index f7032e34ff..e9b838a22b 100644 --- a/release/scripts/rstack_components.py +++ b/release/scripts/rstack_components.py @@ -82,7 +82,7 @@ # These release binaries are consumed directly and are deliberately not # installed as product components by rstack. -DISTRIBUTION_ONLY_BINARIES = {"registry-language-server"} +DISTRIBUTION_ONLY_BINARIES = {"registry-language-server", "registry-session"} def _binary_name(asset_name: str, tag: str) -> tuple[str, str]: diff --git a/release/scripts/test_release_units.py b/release/scripts/test_release_units.py index d494d57819..a299c8e965 100644 --- a/release/scripts/test_release_units.py +++ b/release/scripts/test_release_units.py @@ -41,6 +41,7 @@ def test_registry_maps_every_approved_release_unit(self) -> None: "messaging", "render", "scheduling", + "session", }, set(registry.names), ) @@ -69,6 +70,18 @@ def test_language_server_owns_only_its_standalone_artifacts(self) -> None: ), ) + def test_session_owns_only_its_native_platform_artifacts(self) -> None: + registry = self.module.load_registry() + unit = registry.get("session") + self.assertEqual(("registry-session",), unit.members) + for name in ( + "registry-session-v0.51.0-linux-amd64", + "registry-session-v0.51.0-linux-arm64", + "registry-session-v0.51.0-macos-arm64.tar.gz", + ): + with self.subTest(name=name): + self.assertEqual("session", registry.artifact_owner(name)) + def test_discovery_identity_and_candidate_roster_are_unit_scoped(self) -> None: self.assertEqual("v1.2.3", self.module.asset_tag("1.2.3")) self.assertEqual( diff --git a/release/scripts/test_rstack_components.py b/release/scripts/test_rstack_components.py index 7b327d8eae..c8b39abf50 100644 --- a/release/scripts/test_rstack_components.py +++ b/release/scripts/test_rstack_components.py @@ -6,6 +6,7 @@ import json import re import unittest +from unittest import mock from pathlib import Path from release.scripts import release_candidate, rstack_components @@ -90,6 +91,17 @@ def test_language_server_remains_a_distribution_only_binary(self) -> None: rstack_components.DISTRIBUTION_ONLY_BINARIES, ) + def test_session_is_a_distribution_only_binary_when_it_joins_the_release(self) -> None: + with mock.patch.object(release_candidate.release_roster, "SESSION_FIRST_RELEASE", (0, 51, 0)): + current = payloads("0.51.0") + self.assertIn( + "registry-session-v0.51.0-linux-amd64", + {payload["name"] for payload in current}, + ) + document = rstack_components.build_component_manifest("0.51.0", current) + self.assertNotIn("session", document["components"]) + self.assertIn("registry-session", rstack_components.DISTRIBUTION_ONLY_BINARIES) + def test_rstack_validator_exempts_the_same_distribution_only_binaries(self) -> None: model = ( Path(__file__).resolve().parents[2] / "crates/registry-rstack/src/model.rs" diff --git a/release/units.yaml b/release/units.yaml index d39b6b88a0..3b2b1c3df8 100644 --- a/release/units.yaml +++ b/release/units.yaml @@ -153,6 +153,16 @@ "artifact_patterns": ["scheduling-v*-*", "scheduling-install.sh", "schedulingctl-v*-*"], "dependencies": [], "candidate": null + }, + "session": { + "display_name": "Registry Session", + "status": "held", + "tag_prefix": "session/", + "asset_prefix": "registry-session", + "members": ["registry-session"], + "artifact_patterns": ["registry-session-v*-*"], + "dependencies": [], + "candidate": null } } } From 6a189f033f2df3e5ac9a877107162cb548653055 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 20:40:56 +0000 Subject: [PATCH 076/183] feat(release): ship the Session binary from v0.51.0 Session has passed its paired preview and production sign-in proofs and both review gates, so numbered releases now carry registry-session for Linux amd64, Linux arm64 and macOS arm64. Nightly profiles keep their frozen inventory. The changelog tells v0.44.0 to v0.50.0 rstack users to reinstall, as the v0.47.0 language server did. Signed-off-by: Jeremi Joslin --- AGENTS.md | 5 +++-- crates/registry-session/README.md | 6 ++++-- .../scripts/generate-cli-reference.test.mjs | 6 +++--- .../src/content/docs/configure/session.mdx | 4 ++-- .../content/docs/reference/api-stability.mdx | 3 +-- docs/site/src/data/cli-reference.yaml | 2 +- products/platform/AGENTS.md | 2 +- products/platform/CHANGELOG.md | 7 +++++++ products/platform/README.md | 4 ++-- release/NIGHTLY.md | 6 +++--- release/OPERATIONS.md | 6 ++++-- release/VERIFY.md | 6 +++--- release/scripts/release_roster.py | 5 +++-- release/scripts/test_registry_release.py | 20 ++++++++++++++----- .../scripts/test_registry_release_plans.py | 2 ++ release/scripts/test_release_roster.py | 16 ++++++++------- 16 files changed, 63 insertions(+), 37 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 7f18798c38..fff41273da 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -362,8 +362,9 @@ Envoy gateway. It holds a person's tokens in memory and answers the gateway's per-call check. It issues no token and adds no product authority. Among workspace crates it depends on `registry-platform-*` only, and no product crate depends on it. It runs as one replica, with a check listener private to -the gateway. It is held out of releases while `SESSION_FIRST_RELEASE` in -`release/scripts/release_roster.py` is unset. +the gateway. Numbered releases ship its binary from v0.51.0, as +`SESSION_FIRST_RELEASE` in `release/scripts/release_roster.py` sets. `rstack` +does not install it. The adopter demo is maintained separately in [`registrystack/solmara-lab`](https://github.com/registrystack/solmara-lab). diff --git a/crates/registry-session/README.md b/crates/registry-session/README.md index ae746385a3..70209fce28 100644 --- a/crates/registry-session/README.md +++ b/crates/registry-session/README.md @@ -8,8 +8,10 @@ bearer token to attach. The service checks. It never proxies. This is not an identity provider or a token issuer. It uses the configured identity provider's authorization-code and refresh-token flows. Sessions and pending sign-ins live only in memory, in one replica. A restart loses them. -The binary is source-build only while `SESSION_FIRST_RELEASE` in -`release/scripts/release_roster.py` is unset. +Numbered releases ship the binary for Linux amd64, Linux arm64 and macOS arm64 +from v0.51.0, as `SESSION_FIRST_RELEASE` in +`release/scripts/release_roster.py` sets. It is a standalone release asset: +`rstack` does not install it, and it has no installer or container image. ## Configuration and commands diff --git a/docs/site/scripts/generate-cli-reference.test.mjs b/docs/site/scripts/generate-cli-reference.test.mjs index 0d5aa2aabe..fb22e980b4 100644 --- a/docs/site/scripts/generate-cli-reference.test.mjs +++ b/docs/site/scripts/generate-cli-reference.test.mjs @@ -98,14 +98,14 @@ test('renders the committed catalogue while keeping the job host unreviewed and assert.doesNotMatch(pages.get('index.mdx'), /\(\.\/adapter-job\/\)/u); }); -test('keeps the session service unreviewed and source-build-only', async () => { +test('keeps the session service unreviewed with its numbered-release asset', async () => { const repoRoot = fileURLToPath(new URL('../../../', import.meta.url)); const docsRoot = fileURLToPath(new URL('../', import.meta.url)); const catalog = validateCatalog(await loadCatalog(repoRoot)); assert.ok(catalog.binaries.some((binary) => binary.name === 'registry-session')); const metadata = YAML.parse(await readFile(join(docsRoot, 'src/data/cli-reference.yaml'), 'utf8')); assert.ok(metadata.unreviewed_binaries.includes('registry-session')); - assert.ok(metadata.source_build_only_binaries.includes('registry-session')); + assert.ok(!metadata.source_build_only_binaries.includes('registry-session')); const pages = renderCatalog(catalog, metadata); for (const name of [ 'registry-session.mdx', @@ -114,7 +114,7 @@ test('keeps the session service unreviewed and source-build-only', async () => { ]) { assert.match(pages.get(name), /status: draft\ndraft: true/u); assert.match(pages.get(name), /last_reviewed: "unreviewed"/u); - assert.match(pages.get(name), /It has no numbered-release asset/u); + assert.doesNotMatch(pages.get(name), /no numbered-release asset/u); } assert.doesNotMatch(pages.get('index.mdx'), /\(\.\/registry-session\/\)/u); }); diff --git a/docs/site/src/content/docs/configure/session.mdx b/docs/site/src/content/docs/configure/session.mdx index b1a9b5899a..8d4b57a09f 100644 --- a/docs/site/src/content/docs/configure/session.mdx +++ b/docs/site/src/content/docs/configure/session.mdx @@ -25,8 +25,8 @@ The service is a relying party, not an identity provider or token issuer. It uses authorisation-code sign-in with PKCE and obtains one token set per distinct audience. The provider must return JWT access tokens with a readable audience, a lifetime and refresh tokens. -Build `registry-session` from the workspace source with `cargo build --locked -p registry-session`. -It is held out of numbered releases. +Numbered releases from v0.51.0 publish `registry-session` for Linux amd64, Linux arm64 and macOS arm64, beside the release's `SHA256SUMS`. +`rstack` does not install it: download the asset for your platform, or build it from the workspace source with `cargo build --locked -p registry-session`. Use `registry-session --help` for its command tree. {/* Evidence: crates/registry-session/src/signin.rs authorization_location, complete; diff --git a/docs/site/src/content/docs/reference/api-stability.mdx b/docs/site/src/content/docs/reference/api-stability.mdx index fcaa81795a..18bed508e7 100644 --- a/docs/site/src/content/docs/reference/api-stability.mdx +++ b/docs/site/src/content/docs/reference/api-stability.mdx @@ -148,8 +148,7 @@ release without deprecation: Engine, Casework, an external HTTP service, or the evaluation host, and are promised Registry Document Store is held out of the 1.0 release. -The session service is source-build only while `SESSION_FIRST_RELEASE` is unset. -No release script builds, stages or publishes `registry-session` yet. +Numbered releases ship the session service binary, `registry-session`, from v0.51.0. Before `v1.0.0`, one breaking release moves the promised products' version strings from `v1alpha1` to stable versions, so a `v1alpha1` version string that a 1.x release reads or writes diff --git a/docs/site/src/data/cli-reference.yaml b/docs/site/src/data/cli-reference.yaml index 499eb78b0c..c44a06ee35 100644 --- a/docs/site/src/data/cli-reference.yaml +++ b/docs/site/src/data/cli-reference.yaml @@ -12,4 +12,4 @@ status: current last_reviewed: 2026-11-28 unreviewed_binaries: [adapter, adapter-job, adapterctl, coordinator, coordinatorctl, documents, documentsctl, evidence-oid4vp, manifest, registry-mcp, registry-session, rstack, discovery, discoveryctl] -source_build_only_binaries: [adapter-job, evidence-oid4vp, registry-mcp, registry-session] +source_build_only_binaries: [adapter-job, evidence-oid4vp, registry-mcp] diff --git a/products/platform/AGENTS.md b/products/platform/AGENTS.md index 3f1d2fdbee..ec9675ce6f 100644 --- a/products/platform/AGENTS.md +++ b/products/platform/AGENTS.md @@ -12,7 +12,7 @@ fragments. `registry-session` depends on `registry-platform-*` workspace crates only. No product crate depends on it. It issues no tokens and owns no product authorisation. Keep its check listener private to the gateway and run one replica. `SESSION_FIRST_RELEASE` in `release/scripts/release_roster.py` -holds it out of releases while unset. +adds its binary to numbered releases from v0.51.0. Platform also owns [the configuration conventions](CONFIG-CONVENTIONS.md), the rules every product's configuration formats follow, and the shared reader diff --git a/products/platform/CHANGELOG.md b/products/platform/CHANGELOG.md index 6cba08e2f4..9bc55fb206 100644 --- a/products/platform/CHANGELOG.md +++ b/products/platform/CHANGELOG.md @@ -2,6 +2,13 @@ ## Unreleased +- Numbered releases ship `registry-session` for Linux amd64, Linux arm64 and + macOS arm64. It is a standalone release asset: `rstack` does not install it, + and it has no installer or container image. Upgrade: `rstack update` from + v0.44.0 to v0.50.0 refuses this release, because those `rstack` versions do + not recognise the `registry-session` asset. Run this release's `rstack` + installer as for a first installation, naming the components you use. + Later updates work from this release. - `rstack dev` can attach to PostgreSQL on an isolated development network when the administrator URL selects `transport=private-network-plaintext`. The runner pins the checked numeric address in the generated product URLs. diff --git a/products/platform/README.md b/products/platform/README.md index 24a8a87744..75f437c85e 100644 --- a/products/platform/README.md +++ b/products/platform/README.md @@ -18,8 +18,8 @@ Platform also owns the [session service](../../crates/registry-session/README.md `registry-session`. It holds a person's tokens on the server and answers an Envoy gateway's per-call check. It uses only platform workspace dependencies, and no product crate depends on it. Sessions live in memory in one replica. -The check listener is private to the gateway. The service stays source-build -only while `SESSION_FIRST_RELEASE` is unset. +The check listener is private to the gateway. Numbered releases ship its +binary from v0.51.0, as `SESSION_FIRST_RELEASE` sets. ## Crates diff --git a/release/NIGHTLY.md b/release/NIGHTLY.md index 505faa045e..4bb4a8550d 100644 --- a/release/NIGHTLY.md +++ b/release/NIGHTLY.md @@ -59,9 +59,9 @@ to v2.4 and v2.5 respectively, from the base version that version; `nightly.json`, the asset name, and its checksum authenticate the exact nightly source. No profile carries the Registry Document Store, which stays held out while -`DOCUMENTS_FIRST_RELEASE` is `None`. The session service is also held out -while `SESSION_FIRST_RELEASE` is `None`. No release script builds -`registry-session` yet. An incompatible inventory requires a +`DOCUMENTS_FIRST_RELEASE` is `None`. No profile carries `registry-session` +either: `SESSION_FIRST_RELEASE` adds it to numbered releases only, and the +frozen nightly inventories keep their existing set. An incompatible inventory requires a new schema and profile. The reader still accepts frozen `registry-stack.nightly.v1` manifests, including historical v0.39.0 nightlies that carried Relay, so an existing channel head can be reconciled and advanced diff --git a/release/OPERATIONS.md b/release/OPERATIONS.md index ba18a049c1..d942284971 100644 --- a/release/OPERATIONS.md +++ b/release/OPERATIONS.md @@ -216,8 +216,10 @@ exclude its image, binaries, installers, and client namespace. `RENDER_FIRST_RELEASE`, and `EVIDENCE_OID4VCI_IMAGE_FIRST_RELEASE` in `release/scripts/release_roster.py` own those boundaries. The Document Store is held out of every release while `DOCUMENTS_FIRST_RELEASE` is `None`. -The session service is held out while `SESSION_FIRST_RELEASE` is `None`. -No release script builds, stages or publishes `registry-session` yet. +`SESSION_FIRST_RELEASE` adds the `registry-session` binary for Linux amd64, +Linux arm64 and macOS arm64 from `v0.51.0`. It is a standalone asset of the +`session` release unit, not an `rstack` component, and has no image or +installer. The existing OID4VCI binary stays in earlier inventories. v0.38.0 also adds the Linux amd64 `discoveryctl` asset beside the existing Discovery runtime asset, completing the released authoring and runtime pair. Earlier releases require operators to diff --git a/release/VERIFY.md b/release/VERIFY.md index afce0e149b..1be92c8099 100644 --- a/release/VERIFY.md +++ b/release/VERIFY.md @@ -285,9 +285,9 @@ Registry Adapter binaries join in `v0.46.0`, as set by The Registry Document Store is held out of every release while `DOCUMENTS_FIRST_RELEASE` is `None`, and no release roster names it. `SESSION_FIRST_RELEASE` controls the `registry-session` binary for numbered -Linux amd64, Linux arm64 and macOS arm64 payloads. It remains unset pending -native release qualification. Session has no image or installer in this -roster, and the frozen nightly profiles keep their existing inventory. +Linux amd64, Linux arm64 and macOS arm64 payloads from `v0.51.0`. Session has +no image or installer in this roster, `rstack` does not install it, and the +frozen nightly profiles keep their existing inventory. `BREG_SERVICES_FIRST_RELEASE`, `MESSAGING_FIRST_RELEASE`, `RENDER_FIRST_RELEASE`, `EVIDENCE_OID4VCI_IMAGE_FIRST_RELEASE`, and the three Coordinator release constants in `release/scripts/release_roster.py` diff --git a/release/scripts/release_roster.py b/release/scripts/release_roster.py index f3ec613e85..12dcd8c463 100644 --- a/release/scripts/release_roster.py +++ b/release/scripts/release_roster.py @@ -69,7 +69,8 @@ it is releasable. ``SESSION_FIRST_RELEASE`` decides which numbered release first includes the -``registry-session`` binary in the native platform builds. Its image and +``registry-session`` binary in the native platform builds, from v0.51.0. It is +a standalone release asset that ``rstack`` does not install. Its image and the frozen nightly inventories are independent of this gate. ``PYTHON_311_ABI_FIRST_RELEASE`` is the single place that decides which @@ -113,7 +114,7 @@ DOCUMENTS_FIRST_RELEASE: tuple[int, int, int] | None = None -SESSION_FIRST_RELEASE: tuple[int, int, int] | None = None +SESSION_FIRST_RELEASE: tuple[int, int, int] | None = (0, 51, 0) COORDINATOR_BINARY_FIRST_RELEASE: tuple[int, int, int] = (0, 44, 0) diff --git a/release/scripts/test_registry_release.py b/release/scripts/test_registry_release.py index a6065eb0fa..6a686752ef 100755 --- a/release/scripts/test_registry_release.py +++ b/release/scripts/test_registry_release.py @@ -3964,6 +3964,8 @@ def released(version: str) -> dict[str, str]: inventory.update({"rstack": version, "rstack-installer": version}) if module.release_roster.language_server_in_release(version_tuple): inventory["registry-language-server"] = version + if module.release_roster.session_in_release(version_tuple): + inventory["registry-session"] = version if module.release_roster.scheduling_installer_in_release(version_tuple): inventory["scheduling-installer"] = version if version_tuple >= (0, 39, 0): @@ -4088,6 +4090,8 @@ def released(version: str) -> dict[str, str]: inventory.update({"rstack": version, "rstack-installer": version}) if roster.language_server_in_release(version_tuple): inventory["registry-language-server"] = version + if roster.session_in_release(version_tuple): + inventory["registry-session"] = version if roster.scheduling_installer_in_release(version_tuple): inventory["scheduling-installer"] = version inventory.update({f"{name}-installer": version for name in module.release_roster.additional_installers(version_tuple)}) @@ -4120,11 +4124,13 @@ def released(version: str) -> dict[str, str]: before_session = released("0.50.0") at_session = released("0.51.0") session = "registry-session" - with mock.patch.object(module.release_roster, "SESSION_FIRST_RELEASE", (0, 51, 0)): - self.assertEqual([], module.artifact_inventory_errors("0.50.0", before_session)) - self.assertTrue(module.artifact_inventory_errors("0.50.0", before_session | {session: "0.50.0"})) - self.assertTrue(module.artifact_inventory_errors("0.51.0", at_session)) - self.assertEqual([], module.artifact_inventory_errors("0.51.0", at_session | {session: "0.51.0"})) + self.assertNotIn(session, before_session) + self.assertEqual("0.51.0", at_session[session]) + self.assertEqual([], module.artifact_inventory_errors("0.50.0", before_session)) + self.assertTrue(module.artifact_inventory_errors("0.50.0", before_session | {session: "0.50.0"})) + self.assertEqual([], module.artifact_inventory_errors("0.51.0", at_session)) + without_session = {name: value for name, value in at_session.items() if name != session} + self.assertTrue(module.artifact_inventory_errors("0.51.0", without_session)) # Holding the image does not hold the independently released binaries. with mock.patch.object( @@ -4255,6 +4261,8 @@ def test_breg_services_release_surface_begins_at_their_first_release( current.update({"rstack": version, "rstack-installer": version}) if module.release_roster.language_server_in_release(version_tuple): current["registry-language-server"] = version + if module.release_roster.session_in_release(version_tuple): + current["registry-session"] = version if module.release_roster.scheduling_installer_in_release(version_tuple): current["scheduling-installer"] = version current.update({f"{name}-installer": version for name in module.release_roster.additional_installers(version_tuple)}) @@ -6212,6 +6220,8 @@ def write_manifest( artifacts["rstack-installer"] = version if load_release_roster().language_server_in_release(version_tuple): artifacts["registry-language-server"] = version + if load_release_roster().session_in_release(version_tuple): + artifacts["registry-session"] = version if load_release_roster().scheduling_installer_in_release(version_tuple): artifacts["scheduling-installer"] = version if version_tuple >= (0, 39, 0): diff --git a/release/scripts/test_registry_release_plans.py b/release/scripts/test_registry_release_plans.py index c2a73948d8..0e479f25e9 100644 --- a/release/scripts/test_registry_release_plans.py +++ b/release/scripts/test_registry_release_plans.py @@ -177,6 +177,8 @@ def manifest(version: str, release_id: str, source_ref: str, status: str) -> dic inventory += ("rstack", "rstack-installer") if REGISTRY_RELEASE.release_roster.language_server_in_release(version_tuple): inventory += ("registry-language-server",) + if REGISTRY_RELEASE.release_roster.session_in_release(version_tuple): + inventory += ("registry-session",) if REGISTRY_RELEASE.release_roster.scheduling_installer_in_release(version_tuple): inventory += ("scheduling-installer",) if version_tuple >= (0, 39, 0): diff --git a/release/scripts/test_release_roster.py b/release/scripts/test_release_roster.py index ef760bad06..f98e3871bd 100644 --- a/release/scripts/test_release_roster.py +++ b/release/scripts/test_release_roster.py @@ -115,14 +115,16 @@ def test_document_store_is_held_out_of_every_release(self) -> None: self.assertFalse(release_roster.documents_in_release((0, 43, 99))) self.assertTrue(release_roster.documents_in_release((0, 44, 0))) - def test_session_service_is_held_out_of_every_release(self) -> None: - self.assertIsNone(release_roster.SESSION_FIRST_RELEASE) - for version in ((0, 48, 0), (0, 49, 0), (1, 0, 0)): + def test_session_service_joins_the_numbered_v0_51_0_release(self) -> None: + binary = ("registry-session", "registry-session") + self.assertEqual((0, 51, 0), release_roster.SESSION_FIRST_RELEASE) + for version in ((0, 48, 0), (0, 49, 0), (0, 50, 0)): self.assertFalse(release_roster.session_in_release(version)) - self.assertNotIn( - ("registry-session", "registry-session"), - release_roster.additional_platform_builds(version), - ) + self.assertNotIn(binary, release_roster.additional_platform_builds(version)) + for version in ((0, 51, 0), (1, 0, 0)): + self.assertTrue(release_roster.session_in_release(version)) + self.assertIn(binary, release_roster.additional_platform_builds(version)) + self.assertNotIn(binary, release_roster.additional_platform_builds(version, nightly=True)) def test_session_first_release_adds_its_native_binary_to_the_roster(self) -> None: binary = ("registry-session", "registry-session") From b81a0e095679f1b815bc819525f3346c630eb7de Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 20:47:47 +0000 Subject: [PATCH 077/183] feat(platform): accept Compose secret mounts explicitly and read public documents as public A Docker Compose secret mount appears root-owned at mode 0444, which the strict secret rule refuses. The file provider's explicit mountPolicy: compose-native production setting admits exactly that shape under the declared root, and startup and check report it. A static JWKS or CA bundle is not a secret, so every runtime now reads it through one shared public-document read that drops only the group and world read checks; owner, link, write and walk checks still apply. Signed-off-by: Jeremi Joslin --- crates/registry-adapter-core/src/runtime.rs | 6 +- crates/registry-adapter-engine/src/load.rs | 4 +- crates/registry-adapter-job/src/store.rs | 2 +- crates/registry-adapter/src/serve.rs | 4 +- .../registry-adapterctl/src/job_provision.rs | 8 +- crates/registry-adapterctl/src/provision.rs | 8 +- .../src/action_evidence_config.rs | 4 +- crates/registry-breg/src/event_destination.rs | 2 +- crates/registry-breg/src/runtime_config.rs | 8 +- crates/registry-bregctl/src/provision.rs | 8 +- crates/registry-casework/src/config.rs | 16 +- crates/registry-casework/src/store.rs | 16 +- crates/registry-caseworkctl/src/provision.rs | 2 +- .../schema/connections.schema.json | 15 +- crates/registry-cli-api/src/connection.rs | 2 +- crates/registry-coordinator/src/access.rs | 2 +- .../src/access/token_characterisation.rs | 4 +- crates/registry-coordinator/src/deployment.rs | 2 +- crates/registry-coordinator/src/provision.rs | 13 +- .../tests/static_key_set.rs | 2 +- .../registry-coordinator/tests/support/mod.rs | 4 +- crates/registry-documents/src/config.rs | 16 +- crates/registry-documents/src/store.rs | 16 +- crates/registry-documentsctl/src/provision.rs | 8 +- crates/registry-evidence-oid4vp/src/auth.rs | 2 +- .../src/store_provision.rs | 8 +- crates/registry-mcp-edge/src/config.rs | 15 +- crates/registry-messaging/src/config.rs | 8 +- crates/registry-messaging/src/providers.rs | 15 +- .../registry-messaging/src/smtp/settings.rs | 12 +- crates/registry-messaging/src/store.rs | 16 +- crates/registry-messagingctl/src/provision.rs | 8 +- crates/registry-platform-config/src/blocks.rs | 58 ++++++- .../src/blocks_tests.rs | 53 ++++++- .../registry-platform-config/src/secrets.rs | 138 +++++++++++++---- .../src/secrets_tests.rs | 146 +++++++++++++++++- .../registry-platform-objectstore/src/s3.rs | 9 +- .../src/task_grant/config.rs | 2 +- crates/registry-render/src/auth.rs | 7 +- crates/registry-render/src/runtime.rs | 13 ++ crates/registry-render/src/seal.rs | 7 +- crates/registry-scheduling/src/config.rs | 8 +- crates/registry-scheduling/src/store.rs | 16 +- .../registry-schedulingctl/src/provision.rs | 8 +- .../docs/security/hardening-checklist.mdx | 34 ++-- .../src/content/docs/security/messaging.mdx | 11 +- .../schemas/job-runtime.v1alpha1.schema.json | 15 +- .../schemas/runtime.v1alpha1.schema.json | 15 +- .../mcp-runtime/mcp-runtime.schema.json | 15 +- .../review-runtime/review-runtime.schema.json | 15 +- .../generated/runtime/runtime.schema.json | 15 +- .../generated/runtime/runtime.schema.json | 15 +- .../generated/runtime/runtime.schema.json | 15 +- .../generated/runtime/runtime.schema.json | 15 +- .../oid4vci-runtime.schema.json | 15 +- .../oid4vp-runtime/oid4vp-runtime.schema.json | 15 +- .../generated/runtime/runtime.schema.json | 15 +- products/platform/CHANGELOG.md | 12 ++ .../mcp-runtime/mcp-runtime.schema.json | 15 +- .../runtime-config-blocks.schema.json | 15 +- .../session-runtime.schema.json | 15 +- .../schemas/task-connection.schema.json | 15 +- products/render/schemas/runtime.schema.json | 15 +- .../generated/runtime/runtime.schema.json | 15 +- 64 files changed, 864 insertions(+), 169 deletions(-) diff --git a/crates/registry-adapter-core/src/runtime.rs b/crates/registry-adapter-core/src/runtime.rs index 8e766523eb..2d1b7c1cb0 100644 --- a/crates/registry-adapter-core/src/runtime.rs +++ b/crates/registry-adapter-core/src/runtime.rs @@ -807,9 +807,9 @@ mod tests { id: LocalId::new("case-deployment").expect("id"), endpoints: UniqueIdList::new(vec![binding()]).expect("unique"), secret_providers: Some(SecretProvidersConfig { - file: Some(registry_platform_config::FileSecretProviderConfig { - root: "/run/secrets/adapter".into(), - }), + file: Some(registry_platform_config::FileSecretProviderConfig::new( + "/run/secrets/adapter".into(), + )), environment: None, }), outbound_tls: Some(OutboundTls { diff --git a/crates/registry-adapter-engine/src/load.rs b/crates/registry-adapter-engine/src/load.rs index 998fb86cd8..35c0fd49ee 100644 --- a/crates/registry-adapter-engine/src/load.rs +++ b/crates/registry-adapter-engine/src/load.rs @@ -2158,9 +2158,7 @@ audit: {retentionDays: 90} std::fs::set_permissions(&token, std::fs::Permissions::from_mode(0o600)) .expect("private mode"); let providers = SecretProvidersConfig { - file: Some(FileSecretProviderConfig { - root: root.path().to_path_buf(), - }), + file: Some(FileSecretProviderConfig::new(root.path().to_path_buf())), environment: None, }; diff --git a/crates/registry-adapter-job/src/store.rs b/crates/registry-adapter-job/src/store.rs index 5dc4a03766..2c51791e9c 100644 --- a/crates/registry-adapter-job/src/store.rs +++ b/crates/registry-adapter-job/src/store.rs @@ -745,7 +745,7 @@ fn tls_connector( .map_err(|_| invalid("no platform root certificate could be loaded")); }; let protected = resolver - .resolve(reference.as_str()) + .resolve_public_document(reference.as_str()) .map_err(|error| store_secret_error("caBundleRef", reference.as_str(), &error))?; postgres_tls_from_pem(protected.expose_secret()).map_err(|_| { StoreError::Pool("store.caBundleRef: put a usable PEM CA bundle in the secret".to_owned()) diff --git a/crates/registry-adapter/src/serve.rs b/crates/registry-adapter/src/serve.rs index 9350638609..f8dc460e39 100644 --- a/crates/registry-adapter/src/serve.rs +++ b/crates/registry-adapter/src/serve.rs @@ -277,7 +277,7 @@ async fn issuer_keys( ), JwksSource::Static { document_ref } | JwksSource::TestIssuer { document_ref } => { let document = resolver - .resolve(document_ref) + .resolve_public_document(document_ref) .map_err(|_| invalid("the static key document could not be resolved"))?; let jwks = parse_static_jwks(document.expose_secret()).map_err(|error| { match error { @@ -425,7 +425,7 @@ fn tls_connector( } if let Some(reference) = &config.ca_bundle_ref { let certificate = resolver - .resolve(reference) + .resolve_public_document(reference) .map_err(|_| invalid("the trusted root could not be resolved"))?; let mut roots = rustls::RootCertStore::empty(); use rustls::pki_types::pem::PemObject as _; diff --git a/crates/registry-adapterctl/src/job_provision.rs b/crates/registry-adapterctl/src/job_provision.rs index 714783bd35..df6bc745b5 100644 --- a/crates/registry-adapterctl/src/job_provision.rs +++ b/crates/registry-adapterctl/src/job_provision.rs @@ -80,7 +80,13 @@ pub(crate) fn load( ) })?; let resolve = |member: &str, reference: &SecretReference| { - resolver.resolve(reference.as_str()).map_err(|error| { + // The CA bundle is a public document; the URLs are secrets. + let read = if member == "caBundleRef" { + resolver.resolve_public_document(reference.as_str()) + } else { + resolver.resolve(reference.as_str()) + }; + read.map_err(|error| { refuse( &format!("/store/{member}"), describe_secret_failure(&format!("store.{member}"), reference.as_str(), &error), diff --git a/crates/registry-adapterctl/src/provision.rs b/crates/registry-adapterctl/src/provision.rs index 8d10db71a1..88ba0eb0f3 100644 --- a/crates/registry-adapterctl/src/provision.rs +++ b/crates/registry-adapterctl/src/provision.rs @@ -78,7 +78,13 @@ pub(crate) fn load( ) })?; let resolve = |member: &str, reference: &str| { - secrets.resolve(reference).map_err(|error| { + // The CA bundle is a public document; the URLs are secrets. + let read = if member == "caBundleRef" { + secrets.resolve_public_document(reference) + } else { + secrets.resolve(reference) + }; + read.map_err(|error| { refuse( "config.refused", &format!("/database/{member}"), diff --git a/crates/registry-breg/src/action_evidence_config.rs b/crates/registry-breg/src/action_evidence_config.rs index ef601cf818..dbf9ef48e9 100644 --- a/crates/registry-breg/src/action_evidence_config.rs +++ b/crates/registry-breg/src/action_evidence_config.rs @@ -95,14 +95,14 @@ pub fn activate( .as_ref() .map(|reference| { secrets - .resolve_reference(reference) + .resolve_public_document_reference(reference) .map(|secret| secret.expose_secret().to_vec()) .map_err(|_| Error::Secret) }) .transpose()?; let token_provider = token_provider(binding, secrets, ca_bundle.as_deref())?; let keys = secrets - .resolve_reference(&binding.trusted_jwks_ref) + .resolve_public_document_reference(&binding.trusted_jwks_ref) .map_err(|_| Error::Secret)?; let jwks = registry_platform_crypto::parse_json_strict(keys.expose_secret()) .map_err(|_| Error::InvalidBinding)?; diff --git a/crates/registry-breg/src/event_destination.rs b/crates/registry-breg/src/event_destination.rs index 942aea3859..146ac86eb7 100644 --- a/crates/registry-breg/src/event_destination.rs +++ b/crates/registry-breg/src/event_destination.rs @@ -496,7 +496,7 @@ impl EventDestinationConfig { let ca_bundle = tls .ca_bundle_ref .as_ref() - .map(|reference| secrets.resolve_reference(reference)) + .map(|reference| secrets.resolve_public_document_reference(reference)) .transpose()?; let client_identity = tls .client_identity_ref diff --git a/crates/registry-breg/src/runtime_config.rs b/crates/registry-breg/src/runtime_config.rs index 9adc280ea2..ee74636545 100644 --- a/crates/registry-breg/src/runtime_config.rs +++ b/crates/registry-breg/src/runtime_config.rs @@ -1748,7 +1748,7 @@ impl RuntimeConfig { .with_attempt_timeout(self.operational_timeouts.http_request) .with_connect_timeout(self.operational_timeouts.http_request); if let Some(reference) = &oauth.ca_bundle_ref { - let ca = resolver.resolve_reference(reference)?; + let ca = resolver.resolve_public_document_reference(reference)?; provider = provider.with_trusted_root_certificates(ca.expose_secret().to_vec()); } Arc::new( @@ -2223,7 +2223,9 @@ impl RuntimeConfig { }; let connection = match &self.database.ca_bundle_ref { Some(roots_ref) => { - let roots = self.secret_resolver()?.resolve_reference(roots_ref)?; + let roots = self + .secret_resolver()? + .resolve_public_document_reference(roots_ref)?; ConnectionConfig::require_tls_config_with_roots_pem( postgres, roots.expose_secret(), @@ -3309,7 +3311,7 @@ impl OidcVerifierConfig { } OidcJwksSource::Static { document_ref } => { let document = resolver - .resolve_reference(document_ref) + .resolve_public_document_reference(document_ref) .map_err(|_| RuntimeConfigError::InvalidOidc)?; if document.is_empty() || u64::try_from(document.len()) diff --git a/crates/registry-bregctl/src/provision.rs b/crates/registry-bregctl/src/provision.rs index c0d4680736..7b1c23c9ff 100644 --- a/crates/registry-bregctl/src/provision.rs +++ b/crates/registry-bregctl/src/provision.rs @@ -93,7 +93,13 @@ pub(crate) fn load( .secret_resolver() .map_err(|error| runtime_file_refused(&absolute, &error))?; let resolve = |member: &str, reference| { - secrets.resolve_reference(reference).map_err(|_| { + // The CA bundle is a public document; the URLs are secrets. + let read = if member == "caBundleRef" { + secrets.resolve_public_document_reference(reference) + } else { + secrets.resolve_reference(reference) + }; + read.map_err(|_| { refused( "config.refused", &format!("/database/{member}"), diff --git a/crates/registry-casework/src/config.rs b/crates/registry-casework/src/config.rs index 9992084b05..28c15649f8 100644 --- a/crates/registry-casework/src/config.rs +++ b/crates/registry-casework/src/config.rs @@ -1881,13 +1881,15 @@ async fn issuer_keys( issuer: id.to_owned(), reason, }; - let document = secrets.resolve(document_ref).map_err(|error| { - jwks_secret(describe_secret_failure( - &format!("authentication.oidc.issuers.{id}.jwksSource.documentRef"), - document_ref, - &error, - )) - })?; + let document = secrets + .resolve_public_document(document_ref) + .map_err(|error| { + jwks_secret(describe_secret_failure( + &format!("authentication.oidc.issuers.{id}.jwksSource.documentRef"), + document_ref, + &error, + )) + })?; let jwks = parse_static_jwks(document.expose_secret()).map_err(|error| match error { OidcError::StaticKeySet(refusal) => jwks_secret(refusal.to_string()), diff --git a/crates/registry-casework/src/store.rs b/crates/registry-casework/src/store.rs index 85bd647f3c..97817bac20 100644 --- a/crates/registry-casework/src/store.rs +++ b/crates/registry-casework/src/store.rs @@ -706,13 +706,15 @@ fn tls_connector( return Err(StoreError::Configuration); } if let Some(reference) = &config.ca_bundle_ref { - let certificate = secrets.resolve(reference).map_err(|error| { - StoreError::SecretConfiguration(describe_secret_failure( - "database.caBundleRef", - reference, - &error, - )) - })?; + let certificate = secrets + .resolve_public_document(reference) + .map_err(|error| { + StoreError::SecretConfiguration(describe_secret_failure( + "database.caBundleRef", + reference, + &error, + )) + })?; let mut roots = rustls::RootCertStore::empty(); use rustls::pki_types::pem::PemObject as _; let mut count = 0usize; diff --git a/crates/registry-caseworkctl/src/provision.rs b/crates/registry-caseworkctl/src/provision.rs index c84aae73fd..b5c1ae4cfa 100644 --- a/crates/registry-caseworkctl/src/provision.rs +++ b/crates/registry-caseworkctl/src/provision.rs @@ -78,7 +78,7 @@ fn load(path: &Path, declared: DeclaredPosture) -> Result {} - None => providers.file = Some(FileSecretProviderConfig { root }), + None => providers.file = Some(FileSecretProviderConfig::new(root)), } Ok(reference) } diff --git a/crates/registry-coordinator/src/access.rs b/crates/registry-coordinator/src/access.rs index ecad3c0531..f68377dbdf 100644 --- a/crates/registry-coordinator/src/access.rs +++ b/crates/registry-coordinator/src/access.rs @@ -717,7 +717,7 @@ impl IssuerConfig { let value = secrets .resolver(development) .map_err(|_| refused())? - .resolve(document_ref) + .resolve_public_document(document_ref) .map_err(|_| refused())?; Arc::new(JwksFetcher::new_static( parse_static_jwks(value.expose_secret()).map_err(|error| match error { diff --git a/crates/registry-coordinator/src/access/token_characterisation.rs b/crates/registry-coordinator/src/access/token_characterisation.rs index 8773788073..dd4c0a4438 100644 --- a/crates/registry-coordinator/src/access/token_characterisation.rs +++ b/crates/registry-coordinator/src/access/token_characterisation.rs @@ -213,7 +213,9 @@ fn static_secrets(root: &std::path::Path, signer: &TokenSigner) -> SecretProvide .expect("owner-only key file"); } SecretProvidersConfig { - file: Some(registry_platform_config::FileSecretProviderConfig { root: root_path }), + file: Some(registry_platform_config::FileSecretProviderConfig::new( + root_path, + )), environment: None, } } diff --git a/crates/registry-coordinator/src/deployment.rs b/crates/registry-coordinator/src/deployment.rs index 51e0d371b2..bac4b4f091 100644 --- a/crates/registry-coordinator/src/deployment.rs +++ b/crates/registry-coordinator/src/deployment.rs @@ -639,7 +639,7 @@ fn tls( let _ = rustls::crypto::ring::default_provider().install_default(); if let Some(r) = &database.ca_bundle_ref { let value = secrets - .resolve(r) + .resolve_public_document(r) .map_err(|_| fail("make the database TLS root available"))?; use rustls::pki_types::pem::PemObject as _; let mut roots = rustls::RootCertStore::empty(); diff --git a/crates/registry-coordinator/src/provision.rs b/crates/registry-coordinator/src/provision.rs index 349a34a588..e470e2b681 100644 --- a/crates/registry-coordinator/src/provision.rs +++ b/crates/registry-coordinator/src/provision.rs @@ -94,9 +94,16 @@ fn load(path: &Path, declared: DeclaredPosture) -> Result Some( - secret_text(&resolver, reference, "/database/caBundleRef") - .map_err(|diagnostic| vec![*diagnostic])? - .as_bytes() + resolver + .resolve_public_document(reference) + .map_err(|_| { + vec![*refusal( + "/database/caBundleRef", + "the referenced CA bundle could not be read", + "Make the CA bundle the runtime file names available to this command.", + )] + })? + .expose_secret() .to_vec(), ), None => None, diff --git a/crates/registry-coordinator/tests/static_key_set.rs b/crates/registry-coordinator/tests/static_key_set.rs index 6e5d8f8330..266a899028 100644 --- a/crates/registry-coordinator/tests/static_key_set.rs +++ b/crates/registry-coordinator/tests/static_key_set.rs @@ -30,7 +30,7 @@ async fn build(document: &Value) -> Result<(), registry_coordinator::Coordinator 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 }), + file: Some(FileSecretProviderConfig::new(root_path)), environment: None, }; let envelope = RuntimeEnvelope { diff --git a/crates/registry-coordinator/tests/support/mod.rs b/crates/registry-coordinator/tests/support/mod.rs index bcbf639a78..9a60cbf788 100644 --- a/crates/registry-coordinator/tests/support/mod.rs +++ b/crates/registry-coordinator/tests/support/mod.rs @@ -80,9 +80,7 @@ pub fn config( event_sources: BTreeMap::new(), deployment: None, secret_providers: SecretProvidersConfig { - file: Some(FileSecretProviderConfig { - root: root.to_path_buf(), - }), + file: Some(FileSecretProviderConfig::new(root.to_path_buf())), environment: Some(EnvironmentSecretProviderConfig {}), }, database: registry_platform_config::DatabaseConfig { diff --git a/crates/registry-documents/src/config.rs b/crates/registry-documents/src/config.rs index 9615637320..defeeba877 100644 --- a/crates/registry-documents/src/config.rs +++ b/crates/registry-documents/src/config.rs @@ -767,13 +767,15 @@ impl RuntimeConfig { network.declared_jwks_fetch_policy(), ), JwksSource::Static { document_ref } | JwksSource::TestIssuer { document_ref } => { - let document = secrets.resolve(document_ref).map_err(|error| { - RuntimeConfigError::OidcJwksSecret(describe_secret_failure( - &document_field, - document_ref, - &error, - )) - })?; + let document = secrets + .resolve_public_document(document_ref) + .map_err(|error| { + RuntimeConfigError::OidcJwksSecret(describe_secret_failure( + &document_field, + document_ref, + &error, + )) + })?; let jwks = parse_static_key_set(&document_field, document.expose_secret())?; JwksFetcher::new_static(jwks, JwksFetcherConfig::defaults()) } diff --git a/crates/registry-documents/src/store.rs b/crates/registry-documents/src/store.rs index d3f8081f7d..338df54c31 100644 --- a/crates/registry-documents/src/store.rs +++ b/crates/registry-documents/src/store.rs @@ -385,13 +385,15 @@ fn tls_connector( return Err(StoreError::Configuration); } if let Some(reference) = &config.ca_bundle_ref { - let certificate = secrets.resolve(reference).map_err(|error| { - StoreError::SecretConfiguration(describe_secret_failure( - "database.caBundleRef", - reference, - &error, - )) - })?; + let certificate = secrets + .resolve_public_document(reference) + .map_err(|error| { + StoreError::SecretConfiguration(describe_secret_failure( + "database.caBundleRef", + reference, + &error, + )) + })?; let mut roots = rustls::RootCertStore::empty(); use rustls::pki_types::pem::PemObject as _; let mut count = 0usize; diff --git a/crates/registry-documentsctl/src/provision.rs b/crates/registry-documentsctl/src/provision.rs index a5118bdacc..df4cca3d74 100644 --- a/crates/registry-documentsctl/src/provision.rs +++ b/crates/registry-documentsctl/src/provision.rs @@ -71,7 +71,13 @@ pub(crate) fn load( ) })?; let resolve = |member: &str, reference: &str| { - secrets.resolve(reference).map_err(|error| { + // The CA bundle is a public document; the URLs are secrets. + let read = if member == "caBundleRef" { + secrets.resolve_public_document(reference) + } else { + secrets.resolve(reference) + }; + read.map_err(|error| { refuse( "config.refused", &format!("/database/{member}"), diff --git a/crates/registry-evidence-oid4vp/src/auth.rs b/crates/registry-evidence-oid4vp/src/auth.rs index 8625098d2f..d58f669a2d 100644 --- a/crates/registry-evidence-oid4vp/src/auth.rs +++ b/crates/registry-evidence-oid4vp/src/auth.rs @@ -221,7 +221,7 @@ impl TokenAuthenticator { } JwksSource::Static { document_ref } | JwksSource::TestIssuer { document_ref } => { let document = secrets - .resolve(document_ref) + .resolve_public_document(document_ref) .map_err(|_| AuthSetupError::StaticKeySecret)?; let jwks = parse_static_jwks(document.expose_secret()) .map_err(|error| AuthSetupError::StaticKeySet(error.to_string()))?; diff --git a/crates/registry-evidencectl/src/store_provision.rs b/crates/registry-evidencectl/src/store_provision.rs index f0a1fd2189..01e64afc46 100644 --- a/crates/registry-evidencectl/src/store_provision.rs +++ b/crates/registry-evidencectl/src/store_provision.rs @@ -254,7 +254,13 @@ fn load(path: &Path, declared: DeclaredPosture) -> Result { let field = format!("{base}.jwksSource.documentRef"); - let secret = secrets.resolve(document_ref).map_err(|error| { - IssuerBuildError::Secret { - field: field.clone(), - reference: document_ref.clone(), - error, - } - })?; + let secret = + secrets + .resolve_public_document(document_ref) + .map_err(|error| IssuerBuildError::Secret { + field: field.clone(), + reference: document_ref.clone(), + error, + })?; let keys = parse_static_jwks(secret.expose_secret()).map_err(|error| { IssuerBuildError::StaticKeySet { field: field.clone(), diff --git a/crates/registry-messaging/src/config.rs b/crates/registry-messaging/src/config.rs index 203cd5ea30..fa9921dde9 100644 --- a/crates/registry-messaging/src/config.rs +++ b/crates/registry-messaging/src/config.rs @@ -1250,12 +1250,12 @@ impl RuntimeConfig { } OidcJwksSource::Static { document_ref } | OidcJwksSource::TestIssuer { document_ref } => { - let document = secrets.resolve(document_ref).map_err(|error| { - RuntimeConfigError::OidcJwksSecret { + let document = secrets + .resolve_public_document(document_ref) + .map_err(|error| RuntimeConfigError::OidcJwksSecret { issuer: id.to_owned(), message: describe_secret_failure(&document_field, document_ref, &error), - } - })?; + })?; 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 diff --git a/crates/registry-messaging/src/providers.rs b/crates/registry-messaging/src/providers.rs index 6cb3a06c4a..f7db2e9287 100644 --- a/crates/registry-messaging/src/providers.rs +++ b/crates/registry-messaging/src/providers.rs @@ -91,9 +91,18 @@ pub fn activate_providers( .to_owned(), ) })?; - Some(resolve(secrets, "bundleRef", &profile.bundle_ref).map_err( - |reason| refused(format!("tlsTrustProfiles.{name}: {reason}")), - )?) + Some( + secrets + .resolve_public_document(&profile.bundle_ref) + .map_err(|error| { + let reason = describe_secret_failure( + "bundleRef", + &profile.bundle_ref, + &error, + ); + refused(format!("tlsTrustProfiles.{name}: {reason}")) + })?, + ) } }; let provider = Arc::new( diff --git a/crates/registry-messaging/src/smtp/settings.rs b/crates/registry-messaging/src/smtp/settings.rs index ee5ad1ce32..1203b3da2c 100644 --- a/crates/registry-messaging/src/smtp/settings.rs +++ b/crates/registry-messaging/src/smtp/settings.rs @@ -310,9 +310,15 @@ impl SmtpProviderSettings { fn tls_parameters(&self, secrets: &SecretResolver) -> Result { let mut builder = TlsParameters::builder(self.host.clone()); if let Some(reference) = &self.ca_bundle_ref { - let pem = secrets.resolve(reference).map_err(|error| { - SmtpSettingsError::Secret(describe_secret_failure("caBundleRef", reference, &error)) - })?; + let pem = secrets + .resolve_public_document(reference) + .map_err(|error| { + SmtpSettingsError::Secret(describe_secret_failure( + "caBundleRef", + reference, + &error, + )) + })?; let certificates = CertificateDer::pem_slice_iter(pem.expose_secret()) .collect::, _>>() .map_err(|_| SmtpSettingsError::InvalidTrustedRootCertificate)?; diff --git a/crates/registry-messaging/src/store.rs b/crates/registry-messaging/src/store.rs index a242049777..502cf4b469 100644 --- a/crates/registry-messaging/src/store.rs +++ b/crates/registry-messaging/src/store.rs @@ -460,13 +460,15 @@ fn tls_connector( return Err(StoreError::Configuration); } if let Some(reference) = &config.ca_bundle_ref { - let certificate = secrets.resolve(reference).map_err(|error| { - StoreError::SecretConfiguration(describe_secret_failure( - "database.caBundleRef", - reference, - &error, - )) - })?; + let certificate = secrets + .resolve_public_document(reference) + .map_err(|error| { + StoreError::SecretConfiguration(describe_secret_failure( + "database.caBundleRef", + reference, + &error, + )) + })?; let mut roots = rustls::RootCertStore::empty(); use rustls::pki_types::pem::PemObject as _; let mut count = 0usize; diff --git a/crates/registry-messagingctl/src/provision.rs b/crates/registry-messagingctl/src/provision.rs index 8388648e78..e826deaa0c 100644 --- a/crates/registry-messagingctl/src/provision.rs +++ b/crates/registry-messagingctl/src/provision.rs @@ -75,7 +75,13 @@ pub(crate) fn load( ) })?; let resolve = |member: &str, reference: &str| { - secrets.resolve(reference).map_err(|error| { + // The CA bundle is a public document; the URLs are secrets. + let read = if member == "caBundleRef" { + secrets.resolve_public_document(reference) + } else { + secrets.resolve(reference) + }; + read.map_err(|error| { refuse( "config.refused", &format!("/database/{member}"), diff --git a/crates/registry-platform-config/src/blocks.rs b/crates/registry-platform-config/src/blocks.rs index 74ea24fbda..c6e035e9bd 100644 --- a/crates/registry-platform-config/src/blocks.rs +++ b/crates/registry-platform-config/src/blocks.rs @@ -138,9 +138,52 @@ pub struct FileSecretProviderConfig { /// 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. + /// mode bits and logs a warning. A public document, such as a static JWKS + /// or a CA bundle, may also be readable by group and others. #[cfg_attr(feature = "schema", schemars(extend("pattern" = "^/")))] pub root: PathBuf, + /// `compose-native` also accepts a root-owned regular file with one hard + /// link and mode exactly 0444, the shape of a Docker Compose secret mount. + /// Every user in the container can read such a file. Startup and `check` + /// report this explicit production setting. Absent, the stricter rule + /// above applies. + #[serde(default, skip_serializing_if = "Option::is_none")] + #[cfg_attr(feature = "schema", schemars(with = "Stated"))] + mount_policy: Option>, +} + +impl FileSecretProviderConfig { + /// The standard file provider, with the strict production permission policy. + #[must_use] + pub fn new(root: PathBuf) -> Self { + Self { + root, + mount_policy: None, + } + } +} + +static COMPOSE_NATIVE_SECRET_MOUNT: ExplicitProductionSetting = ExplicitProductionSetting { + code: "platform.posture.compose-native-secret-mount", + key: "mountPolicy", + summary: "The file secret provider accepts root-owned, mode 0444 Compose mounts", +}; + +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)] +#[serde(rename_all = "kebab-case")] +enum SecretMountPolicy { + ComposeNative, +} + +impl ExplicitClass for SecretMountPolicy { + const SETTINGS: &'static [&'static ExplicitProductionSetting] = &[&COMPOSE_NATIVE_SECRET_MOUNT]; + + fn explicit_setting(&self) -> Option<&'static ExplicitProductionSetting> { + match self { + Self::ComposeNative => Some(&COMPOSE_NATIVE_SECRET_MOUNT), + } + } } /// The environment secret provider. It takes no settings. @@ -218,7 +261,18 @@ impl SecretProvidersConfig { .as_ref() .map_or_else(|| Path::new(""), |file| file.root.as_path()), ) - .map(|resolver| resolver.in_development(witness)) + .map(|resolver| { + let resolver = resolver.in_development(witness); + if self.file.as_ref().is_some_and(|file| { + file.mount_policy + .as_ref() + .is_some_and(|policy| *policy.get() == SecretMountPolicy::ComposeNative) + }) { + resolver.with_compose_native_mounts() + } else { + resolver + } + }) } } diff --git a/crates/registry-platform-config/src/blocks_tests.rs b/crates/registry-platform-config/src/blocks_tests.rs index 328904befa..22d7c16419 100644 --- a/crates/registry-platform-config/src/blocks_tests.rs +++ b/crates/registry-platform-config/src/blocks_tests.rs @@ -91,7 +91,7 @@ fn secret_providers_resolver_relaxes_secret_file_permissions_only_with_a_develop .expect("set 0644"); let config = SecretProvidersConfig { - file: Some(FileSecretProviderConfig { root: canonical }), + file: Some(FileSecretProviderConfig::new(canonical)), environment: None, }; @@ -128,6 +128,57 @@ fn secret_providers_resolver_relaxes_secret_file_permissions_only_with_a_develop assert_eq!(secret.expose_secret(), b"shared-secret-canary"); } +#[test] +fn compose_native_mount_is_an_explicit_production_setting_at_its_member() { + #[derive(Deserialize)] + #[serde(rename_all = "camelCase")] + struct Runtime { + secret_providers: SecretProvidersConfig, + } + + let loader = crate::RuntimeConfigLoader::new( + crate::RuntimeEnvelope { + api_version: "registry.registrystack.org/example/v1alpha1", + kind: "ExampleRuntimeConfig", + }, + crate::DeclaredPosture { + posture: crate::Posture::Production, + source: crate::PostureSource::Flag, + }, + ); + let strict = "apiVersion: registry.registrystack.org/example/v1alpha1\nkind: ExampleRuntimeConfig\nsecretProviders:\n file:\n root: /run/secrets\n"; + let omitted = loader.parse_str::(strict, |_| None).unwrap(); + assert!(omitted.posture.explicit_settings().is_empty()); + + let explicit = format!("{strict} mountPolicy: compose-native\n"); + let loaded = loader.parse_str::(&explicit, |_| None).unwrap(); + assert!(loaded.development.is_none()); + loaded.config.secret_providers.check().unwrap(); + let [notice] = loaded.posture.explicit_settings() else { + panic!("one explicit setting is recorded"); + }; + assert_eq!( + notice.setting.code, + "platform.posture.compose-native-secret-mount" + ); + assert_eq!( + notice.pointer.as_deref(), + Some("/secretProviders/file/mountPolicy") + ); + assert!(notice.position.is_some()); + assert!(loaded + .posture + .ready_member() + .get("explicitProductionSettings") + .is_none()); + assert!(loader + .parse_str::( + &explicit.replace("compose-native", "allow-world-readable"), + |_| None + ) + .is_err()); +} + #[test] fn database_debug_redacts_every_reference() { let database: DatabaseConfig = read_block( diff --git a/crates/registry-platform-config/src/secrets.rs b/crates/registry-platform-config/src/secrets.rs index b259994bea..106c64b3f0 100644 --- a/crates/registry-platform-config/src/secrets.rs +++ b/crates/registry-platform-config/src/secrets.rs @@ -393,12 +393,25 @@ impl fmt::Debug for ProtectedSecret { /// 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. +/// warning for a process that declared development. The file provider's +/// explicit `mountPolicy: compose-native` setting also accepts a root-owned, +/// single-link regular file with mode exactly 0444. A public document read +/// through [`Self::resolve_public_document`] skips only the group and world +/// read checks. #[derive(Debug)] pub struct SecretResolver { providers: BTreeSet, file_root: PathBuf, + file_access: FileAccess, +} + +#[derive(Clone, Copy, Debug, Default)] +struct FileAccess { development: bool, + compose_native: bool, + /// A public document such as a JWKS or a CA bundle: anyone may read it, + /// so only who can change it is checked. + public_document: bool, } impl SecretResolver { @@ -411,7 +424,7 @@ impl SecretResolver { Self { providers: BTreeSet::new(), file_root: PathBuf::new(), - development: false, + file_access: FileAccess::default(), } } @@ -430,22 +443,40 @@ impl SecretResolver { Ok(Self { providers, file_root, - development: false, + file_access: FileAccess::default(), }) } /// 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. + /// it the resolver keeps the configured production rule. #[must_use] pub fn in_development(mut self, witness: Option<&DevelopmentWitness>) -> Self { - self.development = witness.is_some(); + self.file_access.development = witness.is_some(); + self + } + + pub(crate) fn with_compose_native_mounts(mut self) -> Self { + self.file_access.compose_native = true; 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> { + self.inspect_with(reference, self.file_access) + } + + /// [`Self::inspect_reference`] for a public document, with the rule + /// [`Self::resolve_public_document_reference`] applies. + pub fn inspect_public_document(&self, reference: &SecretReference) -> Result<(), SecretError> { + self.inspect_with(reference, self.public_access()) + } + + fn inspect_with( + &self, + reference: &SecretReference, + access: FileAccess, + ) -> Result<(), SecretError> { if !self.providers.contains(&reference.provider()) { return Err(SecretError::ProviderDisabled); } @@ -454,11 +485,40 @@ impl SecretResolver { .map(|_| ()) .ok_or(SecretError::Unavailable), SecretProvider::File => { - open_secret_file(&self.file_root, reference.name(), self.development).map(|_| ()) + open_secret_file(&self.file_root, reference.name(), access).map(|_| ()) } } } + /// Resolve a public document, such as a static JWKS or a PEM CA bundle, + /// named by a `secret:env/NAME` or `secret:file/name` reference. + /// + /// Public documents are not secrets: a file may be readable by group and + /// others, so a root-owned mode 0444 Compose mount loads with no setting. + /// Every other file check still applies: a single-link regular file owned + /// by root or the runtime user, with no group or world write and no + /// execute or special bit, reached by the root-confined walk. The caller + /// still parses and checks the document itself. + pub fn resolve_public_document(&self, reference: &str) -> Result { + let reference = SecretReference::parse(reference)?; + self.resolve_public_document_reference(&reference) + } + + /// [`Self::resolve_public_document`] for an already parsed reference. + pub fn resolve_public_document_reference( + &self, + reference: &SecretReference, + ) -> Result { + validate_secret(self.read_with(reference, self.public_access())?.0) + } + + fn public_access(&self) -> FileAccess { + FileAccess { + public_document: true, + ..self.file_access + } + } + /// Resolve one exact `secret:env/NAME` or `secret:file/name` reference. pub fn resolve(&self, reference: &str) -> Result { let reference = SecretReference::parse(reference)?; @@ -482,6 +542,14 @@ impl SecretResolver { pub fn resolve_binary_reference( &self, reference: &SecretReference, + ) -> Result { + self.read_with(reference, self.file_access) + } + + fn read_with( + &self, + reference: &SecretReference, + access: FileAccess, ) -> Result { if !self.providers.contains(&reference.provider()) { return Err(SecretError::ProviderDisabled); @@ -489,9 +557,7 @@ impl SecretResolver { let bytes = match reference.provider() { SecretProvider::Environment => read_environment(reference.name())?, - SecretProvider::File => { - read_secret_file(&self.file_root, reference.name(), self.development)? - } + SecretProvider::File => read_secret_file(&self.file_root, reference.name(), access)?, }; validate_binary_secret(bytes) } @@ -519,9 +585,9 @@ pub const MAX_SECRET_LINKS: usize = 8; fn read_secret_file( root: &Path, name: &str, - development: bool, + access: FileAccess, ) -> Result>, SecretError> { - read_bounded(open_secret_file(root, name, development)?) + read_bounded(open_secret_file(root, name, access)?) } /// What the rule looks at in an opened file. @@ -549,7 +615,7 @@ enum FileKind { fn judge( facts: Facts, euid: u32, - development: bool, + access: FileAccess, ) -> Result, SecretFileCheck> { use SecretFileCheck::{ GroupAccess, HardLinked, ModeBits, NotRegular, Owner, WorldReadable, WorldWritable, @@ -567,19 +633,31 @@ fn judge( if facts.mode & 0o002 != 0 { return Err(WorldWritable); } + if access.compose_native && facts.uid == 0 && facts.mode == 0o444 { + return Ok(Vec::new()); + } 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); + if access.public_document { + if facts.mode & 0o030 != 0 { + failed.push(GroupAccess); + } + if facts.mode & 0o7101 != 0 || (own && facts.mode & 0o400 == 0) { + failed.push(ModeBits); + } + } else { + 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()) { + match (access.development, failed.first()) { (false, Some(check)) => Err(*check), _ => Ok(failed), } @@ -588,7 +666,7 @@ fn judge( /// Walk `name` from the root by openat steps, following only relative /// downward links, then judge the descriptor that will be read. #[cfg(unix)] -fn open_secret_file(root: &Path, name: &str, development: bool) -> Result { +fn open_secret_file(root: &Path, name: &str, access: FileAccess) -> Result { use rustix::{ fs::{Mode, OFlags}, io::Errno, @@ -652,12 +730,12 @@ fn open_secret_file(root: &Path, name: &str, development: bool) -> Result Result<(), SecretError> { +fn judge_file(file: &File, access: FileAccess) -> Result<(), SecretError> { use std::os::unix::fs::{FileTypeExt as _, MetadataExt as _, PermissionsExt as _}; let metadata = file.metadata().map_err(|_| SecretError::Read)?; @@ -679,7 +757,7 @@ fn judge_file(file: &File, development: bool) -> Result<(), SecretError> { mode: metadata.permissions().mode() & 0o7777, nlink: metadata.nlink(), }; - match judge(facts, rustix::process::geteuid().as_raw(), development) { + match judge(facts, rustix::process::geteuid().as_raw(), access) { Err(check) => Err(SecretError::UnsafeFile(check)), Ok(warnings) => { for check in warnings { @@ -701,13 +779,13 @@ fn judge_file(file: &File, development: bool) -> Result<(), SecretError> { fn read_secret_file( root: &Path, name: &str, - development: bool, + access: FileAccess, ) -> Result>, SecretError> { - read_bounded(open_secret_file(root, name, development)?) + read_bounded(open_secret_file(root, name, access)?) } #[cfg(not(unix))] -fn open_secret_file(root: &Path, name: &str, _development: bool) -> Result { +fn open_secret_file(root: &Path, name: &str, _access: FileAccess) -> 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() { diff --git a/crates/registry-platform-config/src/secrets_tests.rs b/crates/registry-platform-config/src/secrets_tests.rs index a09e5f8a0c..51acf33774 100644 --- a/crates/registry-platform-config/src/secrets_tests.rs +++ b/crates/registry-platform-config/src/secrets_tests.rs @@ -88,18 +88,100 @@ fn the_decision_table_gives_one_answer_per_owner_mode_and_posture() { 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)), + observed(judge(f, *euid, FileAccess::default())), *production, "{row} in production" ); assert_eq!( - observed(judge(f, *euid, true)), + observed(judge( + f, + *euid, + FileAccess { + development: true, + ..FileAccess::default() + } + )), *development, "{row} in development" ); } } +#[test] +fn compose_native_adds_only_root_owned_single_link_mode_0444() { + use FileKind::{Directory, Regular}; + use Outcome::{Load, Refuse}; + const APP: u32 = 10001; + let access = FileAccess { + compose_native: true, + ..FileAccess::default() + }; + for (uid, mode, kind, nlink, expected) in [ + (0, 0o444, Regular, 1, Load), + (0, 0o440, Regular, 1, Load), + (APP, 0o400, Regular, 1, Load), + (APP, 0o444, Regular, 1, Refuse(WorldReadable)), + (10002, 0o444, Regular, 1, Refuse(Owner)), + (0, 0o644, Regular, 1, Refuse(WorldReadable)), + (0, 0o464, Regular, 1, Refuse(WorldReadable)), + (0, 0o446, Regular, 1, Refuse(WorldWritable)), + (0, 0o444, Regular, 2, Refuse(HardLinked)), + (0, 0o444, Directory, 1, Refuse(NotRegular)), + ] { + assert_eq!( + observed(judge(facts(kind, uid, mode, nlink), APP, access)), + expected + ); + } +} + +#[test] +fn a_public_document_drops_only_the_read_checks() { + use FileKind::{Directory, Regular}; + use Outcome::{Load, Refuse, Warn}; + const APP: u32 = 10001; + let production = FileAccess { + public_document: true, + ..FileAccess::default() + }; + let development = FileAccess { + development: true, + ..production + }; + #[rustfmt::skip] + let rows: &[(&str, u32, u32, FileKind, u64, Outcome, Outcome)] = &[ + ("compose JWKS", 0, 0o444, Regular, 1, Load, Load), + ("root 0644", 0, 0o644, Regular, 1, Load, Load), + ("root 0640", 0, 0o640, Regular, 1, Load, Load), + ("own 0444", APP, 0o444, Regular, 1, Load, Load), + ("own 0644", APP, 0o644, Regular, 1, Load, Load), + ("own 0400", APP, 0o400, Regular, 1, Load, Load), + ("group write", 0, 0o464, Regular, 1, Refuse(GroupAccess), Warn(&[GroupAccess])), + ("own group w", APP, 0o664, Regular, 1, Refuse(GroupAccess), Warn(&[GroupAccess])), + ("group exec", 0, 0o454, Regular, 1, Refuse(GroupAccess), Warn(&[GroupAccess])), + ("world exec", 0, 0o445, Regular, 1, Refuse(ModeBits), Warn(&[ModeBits])), + ("owner exec", APP, 0o544, Regular, 1, Refuse(ModeBits), Warn(&[ModeBits])), + ("setuid", 0, 0o4444, Regular, 1, Refuse(ModeBits), Warn(&[ModeBits])), + ("world write", 0, 0o446, Regular, 1, Refuse(WorldWritable), Refuse(WorldWritable)), + ("other owner", 10002, 0o444, Regular, 1, Refuse(Owner), Refuse(Owner)), + ("hard linked", 0, 0o444, Regular, 2, Refuse(HardLinked), Refuse(HardLinked)), + ("directory", 0, 0o555, Directory, 1, Refuse(NotRegular), Refuse(NotRegular)), + ]; + for (row, uid, mode, kind, nlink, in_production, in_development) in rows { + let f = facts(*kind, *uid, *mode, *nlink); + assert_eq!( + observed(judge(f, APP, production)), + *in_production, + "{row} in production" + ); + assert_eq!( + observed(judge(f, APP, development)), + *in_development, + "{row} in development" + ); + } +} + #[test] fn every_check_has_a_unique_code_a_value_free_message_and_a_full_stop_fix() { let all = [ @@ -216,6 +298,66 @@ mod filesystem { .map(|secret| secret.expose_secret().to_vec()) } + fn load_public(resolver: &SecretResolver, name: &str) -> Result, SecretError> { + resolver + .resolve_public_document(&format!("secret:file/{name}")) + .map(|document| document.expose_secret().to_vec()) + } + + #[test] + fn a_world_readable_public_document_loads_without_any_secret_setting() { + let root = tempfile::tempdir().expect("root"); + write(root.path(), "jwks.json", 0o444); + write(root.path(), "ca.pem", 0o644); + let resolver = resolver(root.path()); + assert_eq!( + load_public(&resolver, "jwks.json").expect("loads"), + b"file-canary" + ); + assert_eq!( + load_public(&resolver, "ca.pem").expect("loads"), + b"file-canary" + ); + let reference = SecretReference::parse("secret:file/jwks.json").expect("reference"); + resolver + .inspect_public_document(&reference) + .expect("the check gives the same verdict"); + assert_eq!( + load(&resolver, "jwks.json"), + Err(SecretError::UnsafeFile(WorldReadable)), + "a secret read keeps the strict rule" + ); + assert_eq!( + resolver.inspect_reference(&reference), + Err(SecretError::UnsafeFile(WorldReadable)) + ); + } + + #[test] + fn a_writable_or_escaping_public_document_is_refused() { + let root = tempfile::tempdir().expect("root"); + write(root.path(), "group-writable.json", 0o664); + write(root.path(), "world-writable.json", 0o666); + let outside = tempfile::tempdir().expect("outside"); + write(outside.path(), "jwks.json", 0o444); + symlink(outside.path().join("jwks.json"), root.path().join("escape")).expect("link"); + let resolver = resolver(root.path()); + assert_eq!( + load_public(&resolver, "group-writable.json"), + Err(SecretError::UnsafeFile(GroupAccess)) + ); + assert_eq!( + load_public(&resolver, "world-writable.json"), + Err(SecretError::UnsafeFile(WorldWritable)) + ); + assert_eq!( + load_public(&resolver, "escape"), + load(&resolver, "escape"), + "an absolute link is refused as it is for a secret" + ); + assert!(load_public(&resolver, "escape").is_err()); + } + #[test] fn a_relative_link_inside_the_root_loads_the_file_it_names() { let root = tempfile::tempdir().expect("root"); diff --git a/crates/registry-platform-objectstore/src/s3.rs b/crates/registry-platform-objectstore/src/s3.rs index 15ae9aea63..26f8d28534 100644 --- a/crates/registry-platform-objectstore/src/s3.rs +++ b/crates/registry-platform-objectstore/src/s3.rs @@ -218,8 +218,13 @@ impl S3Settings { .connect_timeout(connect_timeout(self.timeout)) .destination(&self.destination); if let Some(reference) = &self.ca_bundle_ref { - builder = - builder.trusted_root_certificates(resolve(reference)?.expose_secret().to_vec()); + builder = builder.trusted_root_certificates( + resolver + .resolve_public_document_reference(reference) + .map_err(|_| ObjectStoreError::Secret)? + .expose_secret() + .to_vec(), + ); } let scope = hex::encode(Sha256::digest(scope_input.as_bytes())); let binding_digest = binding_digest(namespace, &self.bucket_url, &self.region, &scope)?; diff --git a/crates/registry-platform-oidc/src/task_grant/config.rs b/crates/registry-platform-oidc/src/task_grant/config.rs index bb0501ca76..f172f2c9d7 100644 --- a/crates/registry-platform-oidc/src/task_grant/config.rs +++ b/crates/registry-platform-oidc/src/task_grant/config.rs @@ -145,7 +145,7 @@ impl TaskGrantStatusRegistry { let ca = config .ca_bundle_ref .as_ref() - .map(|reference| secrets.resolve_reference(reference)) + .map(|reference| secrets.resolve_public_document_reference(reference)) .transpose() .map_err(|_| TaskGrantError::Configuration)?; let mut token = PrivateKeyJwtConfig::new( diff --git a/crates/registry-render/src/auth.rs b/crates/registry-render/src/auth.rs index dc275abfa9..65073d5040 100644 --- a/crates/registry-render/src/auth.rs +++ b/crates/registry-render/src/auth.rs @@ -71,9 +71,12 @@ async fn entry_verifier( } registry_platform_config::JwksSource::Static { document_ref } | registry_platform_config::JwksSource::TestIssuer { document_ref } => { - let bytes = crate::runtime::resolve_secret(runtime, witness, document_ref)?; + let document = crate::runtime::resolve_public_document(runtime, witness, document_ref) + .map_err(|error| { + RenderProblem::new(ProblemKind::RuntimeInvalid, format!("{error}")) + })?; let keys = - registry_platform_oidc::parse_static_jwks(&bytes).map_err(|error| match error { + registry_platform_oidc::parse_static_jwks(document.expose_secret()).map_err(|error| match error { OidcError::StaticKeySet(refused) => RenderProblem::new( ProblemKind::RuntimeInvalid, format!( diff --git a/crates/registry-render/src/runtime.rs b/crates/registry-render/src/runtime.rs index d6cc696eb8..371a6814fe 100644 --- a/crates/registry-render/src/runtime.rs +++ b/crates/registry-render/src/runtime.rs @@ -2221,6 +2221,19 @@ pub fn resolve_protected_secret( .resolve(reference) } +/// Resolve a public document, such as a static JWKS or a PEM CA bundle, under +/// the providers the runtime declares. Group and other may read the file. +pub fn resolve_public_document( + runtime: &RenderRuntime, + witness: Option<&DevelopmentWitness>, + reference: &str, +) -> Result { + runtime + .secret_providers + .resolver(witness)? + .resolve_public_document(reference) +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/registry-render/src/seal.rs b/crates/registry-render/src/seal.rs index 0d0a120481..f02ff67847 100644 --- a/crates/registry-render/src/seal.rs +++ b/crates/registry-render/src/seal.rs @@ -1199,8 +1199,8 @@ impl TimestampAuthority { let Some(reference) = authority.ca_bundle_ref.as_deref() else { return Self::new(seal_id, authority, None, peer_policy); }; - let bundle = crate::runtime::resolve_protected_secret(runtime, witness, reference) - .map_err(|error| { + let bundle = crate::runtime::resolve_public_document(runtime, witness, reference).map_err( + |error| { refusal( seal_id, "timestampAuthority/caBundleRef", @@ -1212,7 +1212,8 @@ impl TimestampAuthority { "Provide the timestamp authority's PEM CA bundle under the secret provider \ the reference names.", ) - })?; + }, + )?; Self::new( seal_id, authority, diff --git a/crates/registry-scheduling/src/config.rs b/crates/registry-scheduling/src/config.rs index 0f8b2328a2..ce061cf4d2 100644 --- a/crates/registry-scheduling/src/config.rs +++ b/crates/registry-scheduling/src/config.rs @@ -1339,12 +1339,12 @@ impl RuntimeConfig { ) } JwksSource::Static { document_ref } | JwksSource::TestIssuer { document_ref } => { - let document = secrets.resolve(document_ref).map_err(|error| { - RuntimeConfigError::OidcJwksSecret { + let document = secrets + .resolve_public_document(document_ref) + .map_err(|error| RuntimeConfigError::OidcJwksSecret { issuer: id.to_owned(), message: describe_secret_failure(&document_field, document_ref, &error), - } - })?; + })?; let jwks = parse_static_jwks(document.expose_secret()).map_err(|error| { match error { // The operator's document broke a key set rule: say diff --git a/crates/registry-scheduling/src/store.rs b/crates/registry-scheduling/src/store.rs index d70eebedb7..ead4b590e5 100644 --- a/crates/registry-scheduling/src/store.rs +++ b/crates/registry-scheduling/src/store.rs @@ -5693,13 +5693,15 @@ fn tls_connector( return Err(StoreError::Configuration); } if let Some(reference) = &config.ca_bundle_ref { - let certificate = secrets.resolve(reference).map_err(|error| { - StoreError::SecretConfiguration(describe_secret_failure( - "database.caBundleRef", - reference, - &error, - )) - })?; + let certificate = secrets + .resolve_public_document(reference) + .map_err(|error| { + StoreError::SecretConfiguration(describe_secret_failure( + "database.caBundleRef", + reference, + &error, + )) + })?; let mut roots = rustls::RootCertStore::empty(); use rustls::pki_types::pem::PemObject as _; let mut count = 0usize; diff --git a/crates/registry-schedulingctl/src/provision.rs b/crates/registry-schedulingctl/src/provision.rs index a4d30ea8db..34c1aedacf 100644 --- a/crates/registry-schedulingctl/src/provision.rs +++ b/crates/registry-schedulingctl/src/provision.rs @@ -75,7 +75,13 @@ pub(crate) fn load( ) })?; let resolve = |member: &str, reference: &str| { - secrets.resolve(reference).map_err(|error| { + // The CA bundle is a public document; the URLs are secrets. + let read = if member == "caBundleRef" { + secrets.resolve_public_document(reference) + } else { + secrets.resolve(reference) + }; + read.map_err(|error| { refuse( "config.refused", &format!("/database/{member}"), diff --git a/docs/site/src/content/docs/security/hardening-checklist.mdx b/docs/site/src/content/docs/security/hardening-checklist.mdx index 3e8a54adec..d14ae2b4f1 100644 --- a/docs/site/src/content/docs/security/hardening-checklist.mdx +++ b/docs/site/src/content/docs/security/hardening-checklist.mdx @@ -93,6 +93,11 @@ A file the runtime user owns with any group access is refused. Group read is acc file root owns. Give that file's group to the runtime user alone, because every member of the group can read the secret. On a plain host that is every member of the group in `/etc/group`. +Two inputs widen only the read checks. The explicit `secretProviders.file.mountPolicy: compose-native` +setting also accepts a root-owned file at mode exactly `0444`, the Docker Compose secret shape. A +[public document](#public-configuration-files), such as a static JWKS or a CA bundle, may be read by +group and others with no setting. + Registry Evidence and both wallet adapters require a real secret root directory owned by root or the runtime account. The runtime must be able to open and search it. Clear group and other write bits in both postures, even on a read-only mount. `evidencectl doctor` checks the same root rule. @@ -123,11 +128,19 @@ refusal holds in development. Production refuses all of them. on a memory-backed volume. - **The Helm chart.** The chart stages each secret into a memory volume owned by the runtime user at mode `0400`, which the rule accepts. It does not use `fsGroup`. See the chart's README. -- **Docker Compose.** Set ownership and mode on the host. Compose ignores `uid`, `gid`, and - `mode` for [file-backed service secrets](https://docs.docker.com/reference/compose-file/container-spec/#secrets). - Mount the directory read-only and verify the numeric IDs and permissions inside the container. - Follow the [Messaging Compose setup](../../operate/messaging/#mount-secret-files-with-docker-compose) - for a directory bind and replacement procedure. +- **Docker Compose.** Compose ignores `uid`, `gid`, and `mode` for + [file-backed service secrets](https://docs.docker.com/reference/compose-file/container-spec/#secrets), + and on some hosts presents each file root-owned at mode `0444`, which the default rule refuses. + Either set ownership and mode on the host, mount the directory read-only and verify the numeric + IDs and permissions inside the container, or write + `secretProviders.file.mountPolicy: compose-native`. That setting admits only a root-owned + regular file with one link and mode exactly `0444` under the declared root. Every user in the + container can read such a file, so use it in a container that runs one service under one + runtime identity. Startup and the production check report the setting as + `platform.posture.compose-native-secret-mount`. Writable files, other owners, extra links and + paths outside the root stay refused. The + [Messaging Compose setup](../../operate/messaging/#mount-secret-files-with-docker-compose) + shows both routes. {/* Evidence: crates/registry-evidence/src/bundle.rs, validate_secret_root; deploy/helm/registry-stack/templates/evidence-deployment.yaml, stage-evidence-inputs; @@ -138,9 +151,12 @@ refusal holds in development. Production refuses all of them. Protect who can replace public trust material. Replacing an issuer's static JWKS or a CA bundle changes which keys or certificates your deployment trusts. -- If an input such as `jwksSource.documentRef` or `database.caBundleRef` references - `secret:file/`, stage it with the same owner, mode and link rules as the other files under - `secretProviders.file.root`. +- A static JWKS or a CA bundle is a public document, not a secret. An input such as + `jwksSource.documentRef` or `database.caBundleRef` may reference `secret:file/`. The + runtime then reads it under `secretProviders.file.root` with the walk, owner and link rules of a + secret, but group and other may read it. A root-owned Compose mount at mode `0444` needs no + setting. Group or other write access, an execute bit, another owner or a second link is still + refused. The runtime still parses the JWKS or PEM before use. - If a runtime checks its configuration path with the shared trusted path rule, give it an absolute, normalised path without symbolic links. In production, root or the runtime user must own the file and its ancestors. Clear group and other write access. The rule permits a root-owned sticky @@ -151,7 +167,7 @@ changes which keys or certificates your deployment trusts. {/* Evidence: crates/registry-platform-config/src/blocks.rs, JwksSource, DatabaseConfig; crates/registry-platform-config/src/loader.rs, require_trusted_runtime_path; - crates/registry-platform-config/src/secrets.rs, SecretResolver, open_secret_file. */} + crates/registry-platform-config/src/secrets.rs, SecretResolver, resolve_public_document, open_secret_file. */} ## Check BReg and Casework authority diff --git a/docs/site/src/content/docs/security/messaging.mdx b/docs/site/src/content/docs/security/messaging.mdx index 4b6ccfc23a..7307ba028c 100644 --- a/docs/site/src/content/docs/security/messaging.mdx +++ b/docs/site/src/content/docs/security/messaging.mdx @@ -360,6 +360,13 @@ The boundaries hold only if your deployment does the following. queued, `unknown` and retained callback work has settled; or drain or cancel those messages first. Same receiver credential rotation needs none of this. +14. Write `secretProviders.file.mountPolicy: compose-native` only for a container that runs + Messaging alone under one runtime identity. + The setting accepts root-owned Compose secret mounts at mode `0444`, which every user in the + container can read. + Startup and `messagingctl check` report it as `platform.posture.compose-native-secret-mount`. + Without it, stage the secret directory with the hardened owner and mode instead. + A static JWKS or CA bundle is a public document and needs no setting. {/* Evidence: crates/registry-messaging-core/src/package.rs idempotent_submit, accept_duplicates; crates/registry-messaging/src/package.rs a_symbolic_link_anywhere_in_the_package_is_refused; @@ -370,7 +377,9 @@ The boundaries hold only if your deployment does the following. crates/registry-messaging/src/config.rs runtime_reads_the_explicit_http_issuer_opt_in; crates/registry-messaging/src/http_provider/aws_tests.rs aws_settings; crates/registry-messaging/tests/postgres_messages.rs - an_exact_retry_across_an_audit_key_rotation_replays_and_never_sends_again. */} + an_exact_retry_across_an_audit_key_rotation_replays_and_never_sends_again; + crates/registry-platform-config/src/blocks.rs COMPOSE_NATIVE_SECRET_MOUNT; + crates/registry-platform-config/src/secrets.rs resolve_public_document. */} ## Accepted residuals diff --git a/products/adapter/schemas/job-runtime.v1alpha1.schema.json b/products/adapter/schemas/job-runtime.v1alpha1.schema.json index 8cd2717407..43fe2b3acf 100644 --- a/products/adapter/schemas/job-runtime.v1alpha1.schema.json +++ b/products/adapter/schemas/job-runtime.v1alpha1.schema.json @@ -123,8 +123,15 @@ "additionalProperties": false, "description": "The file secret provider.", "properties": { + "mountPolicy": { + "$ref": "#/$defs/SecretMountPolicy", + "description": "`compose-native` also accepts a root-owned regular file with one hard\nlink and mode exactly 0444, the shape of a Docker Compose secret mount.\nEvery user in the container can read such a file. Startup and `check`\nreport this explicit production setting. Absent, the stricter rule\nabove applies.", + "x-registry-explicit-production": [ + "platform.posture.compose-native-secret-mount" + ] + }, "root": { - "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.", + "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. A public document, such as a static JWKS\nor a CA bundle, may also be readable by group and others.", "pattern": "^/", "type": "string" } @@ -850,6 +857,12 @@ } ] }, + "SecretMountPolicy": { + "enum": [ + "compose-native" + ], + "type": "string" + }, "SecretProvidersConfig": { "additionalProperties": false, "anyOf": [ diff --git a/products/adapter/schemas/runtime.v1alpha1.schema.json b/products/adapter/schemas/runtime.v1alpha1.schema.json index ba0b9c1e61..757a51fcb0 100644 --- a/products/adapter/schemas/runtime.v1alpha1.schema.json +++ b/products/adapter/schemas/runtime.v1alpha1.schema.json @@ -306,8 +306,15 @@ "additionalProperties": false, "description": "The file secret provider.", "properties": { + "mountPolicy": { + "$ref": "#/$defs/SecretMountPolicy", + "description": "`compose-native` also accepts a root-owned regular file with one hard\nlink and mode exactly 0444, the shape of a Docker Compose secret mount.\nEvery user in the container can read such a file. Startup and `check`\nreport this explicit production setting. Absent, the stricter rule\nabove applies.", + "x-registry-explicit-production": [ + "platform.posture.compose-native-secret-mount" + ] + }, "root": { - "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.", + "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. A public document, such as a static JWKS\nor a CA bundle, may also be readable by group and others.", "pattern": "^/", "type": "string" } @@ -699,6 +706,12 @@ "$ref": "#/$defs/ExternalId", "description": "The name of the claim that carries scopes." }, + "SecretMountPolicy": { + "enum": [ + "compose-native" + ], + "type": "string" + }, "SecretProvidersConfig": { "additionalProperties": false, "anyOf": [ diff --git a/products/breg/generated/mcp-runtime/mcp-runtime.schema.json b/products/breg/generated/mcp-runtime/mcp-runtime.schema.json index 6a59ea013e..9c6e2a9ba6 100644 --- a/products/breg/generated/mcp-runtime/mcp-runtime.schema.json +++ b/products/breg/generated/mcp-runtime/mcp-runtime.schema.json @@ -222,8 +222,15 @@ "additionalProperties": false, "description": "The file secret provider.", "properties": { + "mountPolicy": { + "$ref": "#/$defs/SecretMountPolicy", + "description": "`compose-native` also accepts a root-owned regular file with one hard\nlink and mode exactly 0444, the shape of a Docker Compose secret mount.\nEvery user in the container can read such a file. Startup and `check`\nreport this explicit production setting. Absent, the stricter rule\nabove applies.", + "x-registry-explicit-production": [ + "platform.posture.compose-native-secret-mount" + ] + }, "root": { - "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.", + "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. A public document, such as a static JWKS\nor a CA bundle, may also be readable by group and others.", "pattern": "^/", "type": "string" } @@ -625,6 +632,12 @@ "pattern": "^[!#-\\[\\]-~]+$", "type": "string" }, + "SecretMountPolicy": { + "enum": [ + "compose-native" + ], + "type": "string" + }, "SecretProvidersConfig": { "additionalProperties": false, "anyOf": [ diff --git a/products/breg/generated/review-runtime/review-runtime.schema.json b/products/breg/generated/review-runtime/review-runtime.schema.json index 6c87764833..f6e1dbce9b 100644 --- a/products/breg/generated/review-runtime/review-runtime.schema.json +++ b/products/breg/generated/review-runtime/review-runtime.schema.json @@ -127,8 +127,15 @@ "additionalProperties": false, "description": "The file secret provider.", "properties": { + "mountPolicy": { + "$ref": "#/$defs/SecretMountPolicy", + "description": "`compose-native` also accepts a root-owned regular file with one hard\nlink and mode exactly 0444, the shape of a Docker Compose secret mount.\nEvery user in the container can read such a file. Startup and `check`\nreport this explicit production setting. Absent, the stricter rule\nabove applies.", + "x-registry-explicit-production": [ + "platform.posture.compose-native-secret-mount" + ] + }, "root": { - "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.", + "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. A public document, such as a static JWKS\nor a CA bundle, may also be readable by group and others.", "pattern": "^/", "type": "string" } @@ -274,6 +281,12 @@ "pattern": "^[!#-\\[\\]-~]+$", "type": "string" }, + "SecretMountPolicy": { + "enum": [ + "compose-native" + ], + "type": "string" + }, "SecretProvidersConfig": { "additionalProperties": false, "anyOf": [ diff --git a/products/breg/generated/runtime/runtime.schema.json b/products/breg/generated/runtime/runtime.schema.json index 622232a8bc..78313319d4 100644 --- a/products/breg/generated/runtime/runtime.schema.json +++ b/products/breg/generated/runtime/runtime.schema.json @@ -716,8 +716,15 @@ "additionalProperties": false, "description": "The file secret provider.", "properties": { + "mountPolicy": { + "$ref": "#/$defs/SecretMountPolicy", + "description": "`compose-native` also accepts a root-owned regular file with one hard\nlink and mode exactly 0444, the shape of a Docker Compose secret mount.\nEvery user in the container can read such a file. Startup and `check`\nreport this explicit production setting. Absent, the stricter rule\nabove applies.", + "x-registry-explicit-production": [ + "platform.posture.compose-native-secret-mount" + ] + }, "root": { - "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.", + "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. A public document, such as a static JWKS\nor a CA bundle, may also be readable by group and others.", "pattern": "^/", "type": "string" } @@ -2340,6 +2347,12 @@ "$ref": "#/$defs/ExternalId", "description": "The name of the claim that carries scopes." }, + "SecretMountPolicy": { + "enum": [ + "compose-native" + ], + "type": "string" + }, "SecretProvidersConfig": { "additionalProperties": false, "anyOf": [ diff --git a/products/casework/generated/runtime/runtime.schema.json b/products/casework/generated/runtime/runtime.schema.json index 9c5aca82d1..6608e9dee5 100644 --- a/products/casework/generated/runtime/runtime.schema.json +++ b/products/casework/generated/runtime/runtime.schema.json @@ -552,8 +552,15 @@ "additionalProperties": false, "description": "The file secret provider.", "properties": { + "mountPolicy": { + "$ref": "#/$defs/SecretMountPolicy", + "description": "`compose-native` also accepts a root-owned regular file with one hard\nlink and mode exactly 0444, the shape of a Docker Compose secret mount.\nEvery user in the container can read such a file. Startup and `check`\nreport this explicit production setting. Absent, the stricter rule\nabove applies.", + "x-registry-explicit-production": [ + "platform.posture.compose-native-secret-mount" + ] + }, "root": { - "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.", + "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. A public document, such as a static JWKS\nor a CA bundle, may also be readable by group and others.", "pattern": "^/", "type": "string" } @@ -799,6 +806,12 @@ "$ref": "#/$defs/ExternalId", "description": "The name of the claim that carries scopes." }, + "SecretMountPolicy": { + "enum": [ + "compose-native" + ], + "type": "string" + }, "SecretProvidersConfig": { "additionalProperties": false, "anyOf": [ diff --git a/products/coordinator/generated/runtime/runtime.schema.json b/products/coordinator/generated/runtime/runtime.schema.json index df12c4babe..b87878db7e 100644 --- a/products/coordinator/generated/runtime/runtime.schema.json +++ b/products/coordinator/generated/runtime/runtime.schema.json @@ -779,8 +779,15 @@ "additionalProperties": false, "description": "The file secret provider.", "properties": { + "mountPolicy": { + "$ref": "#/$defs/SecretMountPolicy", + "description": "`compose-native` also accepts a root-owned regular file with one hard\nlink and mode exactly 0444, the shape of a Docker Compose secret mount.\nEvery user in the container can read such a file. Startup and `check`\nreport this explicit production setting. Absent, the stricter rule\nabove applies.", + "x-registry-explicit-production": [ + "platform.posture.compose-native-secret-mount" + ] + }, "root": { - "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.", + "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. A public document, such as a static JWKS\nor a CA bundle, may also be readable by group and others.", "pattern": "^/", "type": "string" } @@ -1088,6 +1095,12 @@ "$ref": "#/$defs/ExternalId", "description": "The name of the claim that carries scopes." }, + "SecretMountPolicy": { + "enum": [ + "compose-native" + ], + "type": "string" + }, "SecretProvidersConfig": { "additionalProperties": false, "anyOf": [ diff --git a/products/documents/generated/runtime/runtime.schema.json b/products/documents/generated/runtime/runtime.schema.json index 5578a36259..9d29d68160 100644 --- a/products/documents/generated/runtime/runtime.schema.json +++ b/products/documents/generated/runtime/runtime.schema.json @@ -305,8 +305,15 @@ "additionalProperties": false, "description": "The file secret provider.", "properties": { + "mountPolicy": { + "$ref": "#/$defs/SecretMountPolicy", + "description": "`compose-native` also accepts a root-owned regular file with one hard\nlink and mode exactly 0444, the shape of a Docker Compose secret mount.\nEvery user in the container can read such a file. Startup and `check`\nreport this explicit production setting. Absent, the stricter rule\nabove applies.", + "x-registry-explicit-production": [ + "platform.posture.compose-native-secret-mount" + ] + }, "root": { - "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.", + "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. A public document, such as a static JWKS\nor a CA bundle, may also be readable by group and others.", "pattern": "^/", "type": "string" } @@ -631,6 +638,12 @@ "$ref": "#/$defs/ExternalId", "description": "The name of the claim that carries scopes." }, + "SecretMountPolicy": { + "enum": [ + "compose-native" + ], + "type": "string" + }, "SecretProvidersConfig": { "additionalProperties": false, "anyOf": [ diff --git a/products/evidence/generated/oid4vci-runtime/oid4vci-runtime.schema.json b/products/evidence/generated/oid4vci-runtime/oid4vci-runtime.schema.json index 47d436e6a1..75b9566696 100644 --- a/products/evidence/generated/oid4vci-runtime/oid4vci-runtime.schema.json +++ b/products/evidence/generated/oid4vci-runtime/oid4vci-runtime.schema.json @@ -182,8 +182,15 @@ "additionalProperties": false, "description": "The file secret provider.", "properties": { + "mountPolicy": { + "$ref": "#/$defs/SecretMountPolicy", + "description": "`compose-native` also accepts a root-owned regular file with one hard\nlink and mode exactly 0444, the shape of a Docker Compose secret mount.\nEvery user in the container can read such a file. Startup and `check`\nreport this explicit production setting. Absent, the stricter rule\nabove applies.", + "x-registry-explicit-production": [ + "platform.posture.compose-native-secret-mount" + ] + }, "root": { - "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.", + "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. A public document, such as a static JWKS\nor a CA bundle, may also be readable by group and others.", "pattern": "^/", "type": "string" } @@ -549,6 +556,12 @@ "$ref": "#/$defs/ExternalId", "description": "The name of the claim that carries scopes." }, + "SecretMountPolicy": { + "enum": [ + "compose-native" + ], + "type": "string" + }, "SecretProvidersConfig": { "additionalProperties": false, "anyOf": [ diff --git a/products/evidence/generated/oid4vp-runtime/oid4vp-runtime.schema.json b/products/evidence/generated/oid4vp-runtime/oid4vp-runtime.schema.json index faaa870574..959afaf9eb 100644 --- a/products/evidence/generated/oid4vp-runtime/oid4vp-runtime.schema.json +++ b/products/evidence/generated/oid4vp-runtime/oid4vp-runtime.schema.json @@ -309,8 +309,15 @@ "additionalProperties": false, "description": "The file secret provider.", "properties": { + "mountPolicy": { + "$ref": "#/$defs/SecretMountPolicy", + "description": "`compose-native` also accepts a root-owned regular file with one hard\nlink and mode exactly 0444, the shape of a Docker Compose secret mount.\nEvery user in the container can read such a file. Startup and `check`\nreport this explicit production setting. Absent, the stricter rule\nabove applies.", + "x-registry-explicit-production": [ + "platform.posture.compose-native-secret-mount" + ] + }, "root": { - "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.", + "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. A public document, such as a static JWKS\nor a CA bundle, may also be readable by group and others.", "pattern": "^/", "type": "string" } @@ -613,6 +620,12 @@ "$ref": "#/$defs/ExternalId", "description": "The name of the claim that carries scopes." }, + "SecretMountPolicy": { + "enum": [ + "compose-native" + ], + "type": "string" + }, "SecretProvidersConfig": { "additionalProperties": false, "anyOf": [ diff --git a/products/messaging/generated/runtime/runtime.schema.json b/products/messaging/generated/runtime/runtime.schema.json index 336fdbf157..3b883e4755 100644 --- a/products/messaging/generated/runtime/runtime.schema.json +++ b/products/messaging/generated/runtime/runtime.schema.json @@ -288,8 +288,15 @@ "additionalProperties": false, "description": "The file secret provider.", "properties": { + "mountPolicy": { + "$ref": "#/$defs/SecretMountPolicy", + "description": "`compose-native` also accepts a root-owned regular file with one hard\nlink and mode exactly 0444, the shape of a Docker Compose secret mount.\nEvery user in the container can read such a file. Startup and `check`\nreport this explicit production setting. Absent, the stricter rule\nabove applies.", + "x-registry-explicit-production": [ + "platform.posture.compose-native-secret-mount" + ] + }, "root": { - "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.", + "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. A public document, such as a static JWKS\nor a CA bundle, may also be readable by group and others.", "pattern": "^/", "type": "string" } @@ -956,6 +963,12 @@ "$ref": "#/$defs/ExternalId", "description": "The name of the claim that carries scopes." }, + "SecretMountPolicy": { + "enum": [ + "compose-native" + ], + "type": "string" + }, "SecretProvidersConfig": { "additionalProperties": false, "anyOf": [ diff --git a/products/platform/CHANGELOG.md b/products/platform/CHANGELOG.md index 9bc55fb206..5be6a25189 100644 --- a/products/platform/CHANGELOG.md +++ b/products/platform/CHANGELOG.md @@ -2,6 +2,18 @@ ## Unreleased +- The file secret provider accepts `mountPolicy: compose-native`, an explicit + production setting that also admits a root-owned, single-link regular file + with mode exactly `0444`, the Docker Compose secret mount shape, under the + declared root. Startup and `check` report + `platform.posture.compose-native-secret-mount`. The default rule still + refuses that shape, and writable files, other owners, extra links and paths + outside the root stay refused in every case. +- Every runtime reads a static JWKS (`jwksSource.documentRef`) and every CA + bundle (`caBundleRef`, Messaging `tlsTrustProfiles.*.bundleRef`) as a public + document: group and other may read the file, with no setting. Owner, link, + write and walk checks still apply, and the document is still parsed before + use. - Numbered releases ship `registry-session` for Linux amd64, Linux arm64 and macOS arm64. It is a standalone release asset: `rstack` does not install it, and it has no installer or container image. Upgrade: `rstack update` from diff --git a/products/platform/generated/mcp-runtime/mcp-runtime.schema.json b/products/platform/generated/mcp-runtime/mcp-runtime.schema.json index 69fd075797..be01339097 100644 --- a/products/platform/generated/mcp-runtime/mcp-runtime.schema.json +++ b/products/platform/generated/mcp-runtime/mcp-runtime.schema.json @@ -310,8 +310,15 @@ "additionalProperties": false, "description": "The file secret provider.", "properties": { + "mountPolicy": { + "$ref": "#/$defs/SecretMountPolicy", + "description": "`compose-native` also accepts a root-owned regular file with one hard\nlink and mode exactly 0444, the shape of a Docker Compose secret mount.\nEvery user in the container can read such a file. Startup and `check`\nreport this explicit production setting. Absent, the stricter rule\nabove applies.", + "x-registry-explicit-production": [ + "platform.posture.compose-native-secret-mount" + ] + }, "root": { - "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.", + "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. A public document, such as a static JWKS\nor a CA bundle, may also be readable by group and others.", "pattern": "^/", "type": "string" } @@ -836,6 +843,12 @@ "pattern": "^[!#-\\[\\]-~]+$", "type": "string" }, + "SecretMountPolicy": { + "enum": [ + "compose-native" + ], + "type": "string" + }, "SecretProvidersConfig": { "additionalProperties": false, "anyOf": [ diff --git a/products/platform/generated/runtime-config-blocks.schema.json b/products/platform/generated/runtime-config-blocks.schema.json index 2a274bd183..508178e1dc 100644 --- a/products/platform/generated/runtime-config-blocks.schema.json +++ b/products/platform/generated/runtime-config-blocks.schema.json @@ -589,8 +589,15 @@ "additionalProperties": false, "description": "The file secret provider.", "properties": { + "mountPolicy": { + "$ref": "#/$defs/SecretMountPolicy", + "description": "`compose-native` also accepts a root-owned regular file with one hard\nlink and mode exactly 0444, the shape of a Docker Compose secret mount.\nEvery user in the container can read such a file. Startup and `check`\nreport this explicit production setting. Absent, the stricter rule\nabove applies.", + "x-registry-explicit-production": [ + "platform.posture.compose-native-secret-mount" + ] + }, "root": { - "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.", + "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. A public document, such as a static JWKS\nor a CA bundle, may also be readable by group and others.", "pattern": "^/", "type": "string" } @@ -972,6 +979,12 @@ "$ref": "#/$defs/ExternalId", "description": "The name of the claim that carries scopes." }, + "SecretMountPolicy": { + "enum": [ + "compose-native" + ], + "type": "string" + }, "SecretProvidersConfig": { "additionalProperties": false, "anyOf": [ diff --git a/products/platform/generated/session-runtime/session-runtime.schema.json b/products/platform/generated/session-runtime/session-runtime.schema.json index dcf7cf8336..2db6d6be04 100644 --- a/products/platform/generated/session-runtime/session-runtime.schema.json +++ b/products/platform/generated/session-runtime/session-runtime.schema.json @@ -145,8 +145,15 @@ "additionalProperties": false, "description": "The file secret provider.", "properties": { + "mountPolicy": { + "$ref": "#/$defs/SecretMountPolicy", + "description": "`compose-native` also accepts a root-owned regular file with one hard\nlink and mode exactly 0444, the shape of a Docker Compose secret mount.\nEvery user in the container can read such a file. Startup and `check`\nreport this explicit production setting. Absent, the stricter rule\nabove applies.", + "x-registry-explicit-production": [ + "platform.posture.compose-native-secret-mount" + ] + }, "root": { - "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.", + "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. A public document, such as a static JWKS\nor a CA bundle, may also be readable by group and others.", "pattern": "^/", "type": "string" } @@ -563,6 +570,12 @@ "pattern": "^[!#-\\[\\]-~]+$", "type": "string" }, + "SecretMountPolicy": { + "enum": [ + "compose-native" + ], + "type": "string" + }, "SecretProvidersConfig": { "additionalProperties": false, "anyOf": [ diff --git a/products/platform/schemas/task-connection.schema.json b/products/platform/schemas/task-connection.schema.json index 8d7dcf5b10..1c20d44531 100644 --- a/products/platform/schemas/task-connection.schema.json +++ b/products/platform/schemas/task-connection.schema.json @@ -16,8 +16,15 @@ "additionalProperties": false, "description": "The file secret provider.", "properties": { + "mountPolicy": { + "$ref": "#/$defs/SecretMountPolicy", + "description": "`compose-native` also accepts a root-owned regular file with one hard\nlink and mode exactly 0444, the shape of a Docker Compose secret mount.\nEvery user in the container can read such a file. Startup and `check`\nreport this explicit production setting. Absent, the stricter rule\nabove applies.", + "x-registry-explicit-production": [ + "platform.posture.compose-native-secret-mount" + ] + }, "root": { - "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.", + "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. A public document, such as a static JWKS\nor a CA bundle, may also be readable by group and others.", "pattern": "^/", "type": "string" } @@ -27,6 +34,12 @@ ], "type": "object" }, + "SecretMountPolicy": { + "enum": [ + "compose-native" + ], + "type": "string" + }, "SecretProvidersConfig": { "additionalProperties": false, "anyOf": [ diff --git a/products/render/schemas/runtime.schema.json b/products/render/schemas/runtime.schema.json index 2a6e343038..a88318513b 100644 --- a/products/render/schemas/runtime.schema.json +++ b/products/render/schemas/runtime.schema.json @@ -177,8 +177,15 @@ "additionalProperties": false, "description": "The file secret provider.", "properties": { + "mountPolicy": { + "$ref": "#/$defs/SecretMountPolicy", + "description": "`compose-native` also accepts a root-owned regular file with one hard\nlink and mode exactly 0444, the shape of a Docker Compose secret mount.\nEvery user in the container can read such a file. Startup and `check`\nreport this explicit production setting. Absent, the stricter rule\nabove applies.", + "x-registry-explicit-production": [ + "platform.posture.compose-native-secret-mount" + ] + }, "root": { - "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.", + "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. A public document, such as a static JWKS\nor a CA bundle, may also be readable by group and others.", "pattern": "^/", "type": "string" } @@ -708,6 +715,12 @@ } ] }, + "SecretMountPolicy": { + "enum": [ + "compose-native" + ], + "type": "string" + }, "SecretProvidersConfig": { "additionalProperties": false, "anyOf": [ diff --git a/products/scheduling/generated/runtime/runtime.schema.json b/products/scheduling/generated/runtime/runtime.schema.json index 308e1f008d..7e108ef536 100644 --- a/products/scheduling/generated/runtime/runtime.schema.json +++ b/products/scheduling/generated/runtime/runtime.schema.json @@ -332,8 +332,15 @@ "additionalProperties": false, "description": "The file secret provider.", "properties": { + "mountPolicy": { + "$ref": "#/$defs/SecretMountPolicy", + "description": "`compose-native` also accepts a root-owned regular file with one hard\nlink and mode exactly 0444, the shape of a Docker Compose secret mount.\nEvery user in the container can read such a file. Startup and `check`\nreport this explicit production setting. Absent, the stricter rule\nabove applies.", + "x-registry-explicit-production": [ + "platform.posture.compose-native-secret-mount" + ] + }, "root": { - "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.", + "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. A public document, such as a static JWKS\nor a CA bundle, may also be readable by group and others.", "pattern": "^/", "type": "string" } @@ -920,6 +927,12 @@ "$ref": "#/$defs/ExternalId", "description": "The name of the claim that carries scopes." }, + "SecretMountPolicy": { + "enum": [ + "compose-native" + ], + "type": "string" + }, "SecretProvidersConfig": { "additionalProperties": false, "anyOf": [ From 4381a083f6f42773c8b3164251bf0cc881276709 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 21:13:32 +0000 Subject: [PATCH 078/183] fix(evidence): classify provision as a JSON-reporting command evidencectl provision forwards --format json to the shared provisioning report, but the command classification test did not list it, so the lib suite failed. Also drop a needless borrow that clippy refuses. Signed-off-by: Jeremi Joslin --- crates/registry-evidencectl/src/lib.rs | 1 + crates/registry-evidencectl/src/store_provision.rs | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/crates/registry-evidencectl/src/lib.rs b/crates/registry-evidencectl/src/lib.rs index 39f420d415..93724e8f3f 100644 --- a/crates/registry-evidencectl/src/lib.rs +++ b/crates/registry-evidencectl/src/lib.rs @@ -1771,6 +1771,7 @@ mod tests { "target explain", "tooling editor", "oid4vci check", + "provision", ]; /// Protocol and artifact output, or a foreground service without a report. diff --git a/crates/registry-evidencectl/src/store_provision.rs b/crates/registry-evidencectl/src/store_provision.rs index 01e64afc46..7c0c86876b 100644 --- a/crates/registry-evidencectl/src/store_provision.rs +++ b/crates/registry-evidencectl/src/store_provision.rs @@ -93,7 +93,7 @@ fn diagnostics(config: &StoreProvisionDocument, defers: impl Fn(&str) -> bool) - let mut block = |error: registry_platform_config::ConfigBlockError| { findings.push(Diagnostic::error( "evidence.store-provision.configuration", - &format!("/{}", error.field().replace('.', "/")), + format!("/{}", error.field().replace('.', "/")), error.to_string(), "Correct the named field in the provisioning file.", )); From 7e4a1884664d380fe0264b906356cec4785f6b3d Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 21:34:54 +0000 Subject: [PATCH 079/183] fix(dev): check the external Scheduling caller after roles resolve Main resolves test people from service roles before the resolved plan exists, so the external Scheduling binding keeps its structural checks generic and checks its one planned caller on the resolved plan. The saved-report test now reads the fixture's version instead of naming one. Signed-off-by: Jeremi Joslin --- .../registry-rstack-dev/src/external_breg.rs | 33 ++++++++++++------- .../src/owner_report_tests.rs | 12 +++++-- crates/registry-rstack-dev/src/plan.rs | 3 ++ crates/registry-rstack-dev/src/roles.rs | 2 ++ 4 files changed, 35 insertions(+), 15 deletions(-) diff --git a/crates/registry-rstack-dev/src/external_breg.rs b/crates/registry-rstack-dev/src/external_breg.rs index 98ca725314..31249ffe58 100644 --- a/crates/registry-rstack-dev/src/external_breg.rs +++ b/crates/registry-rstack-dev/src/external_breg.rs @@ -101,10 +101,28 @@ impl TaskGrant { ) } - pub(super) fn validate_for_scheduling( + /// Once people are resolved from their roles, the assertion client must + /// name exactly one planned Scheduling caller. + pub(super) fn validate_scheduling_caller(&self, plan: &Plan) -> SemanticResult<()> { + require( + plan.people + .values() + .filter(|person| { + person.client == self.assertion_client + && person.grants.contains_key(&Product::Scheduling) + }) + .count() + == 1, + "/externalScheduling/taskGrant/assertionClient", + "The assertion client must name exactly one planned Scheduling caller.", + "Use the exact external booking client in one Scheduling grant entry.", + ) + } + + pub(super) fn validate_for_scheduling( &self, root: &Path, - plan: &Plan, + plan: &Plan, audience: &str, ) -> SemanticResult<()> { let same_origin = |endpoint: &str| { @@ -134,16 +152,7 @@ impl TaskGrant { "Use the issuer name in the Casework task grant.", )?; check( - identifier(&self.assertion_client) - && plan - .people - .values() - .filter(|person| { - person.client == self.assertion_client - && person.grants.contains_key(&Product::Scheduling) - }) - .count() - == 1, + identifier(&self.assertion_client), "assertionClient", "The assertion client must name exactly one planned Scheduling caller.", "Use the exact external booking client in one Scheduling grant entry.", diff --git a/crates/registry-rstack-dev/src/owner_report_tests.rs b/crates/registry-rstack-dev/src/owner_report_tests.rs index 4a650da70b..9ac0446b1a 100644 --- a/crates/registry-rstack-dev/src/owner_report_tests.rs +++ b/crates/registry-rstack-dev/src/owner_report_tests.rs @@ -221,9 +221,15 @@ fn saved_report_retains_positions_and_numeric_bounds_without_echoing_input() { #[test] fn saved_report_retains_unknown_key_locations_and_all_envelope_refusals() { - let source = CASEWORK.replace( - "\"version\": \"0.49.0-dev\"", - "\"version\": \"0.49.0-dev\",\n \"private-canary-one\": true,\n \"private-canary-two\": false", + let version = CASEWORK + .lines() + .find(|line| line.starts_with(" \"version\": ")) + .expect("the saved report states its version") + .trim_end_matches(','); + let source = CASEWORK.replacen( + version, + &format!("{version},\n \"private-canary-one\": true,\n \"private-canary-two\": false"), + 1, ); let (report, exit) = check_bytes("synthetic.json", source.as_bytes(), Format::CaseworkReport); assert_eq!(exit, 1); diff --git a/crates/registry-rstack-dev/src/plan.rs b/crates/registry-rstack-dev/src/plan.rs index 65094c5717..b4f5d7c6c1 100644 --- a/crates/registry-rstack-dev/src/plan.rs +++ b/crates/registry-rstack-dev/src/plan.rs @@ -1741,6 +1741,9 @@ impl Plan { ), )?; } + if let Some(binding) = &self.external_scheduling { + binding.task_grant.validate_scheduling_caller(self)?; + } self.bindings.validate(self)?; Ok(()) } diff --git a/crates/registry-rstack-dev/src/roles.rs b/crates/registry-rstack-dev/src/roles.rs index 292c02571f..584e3e8e5b 100644 --- a/crates/registry-rstack-dev/src/roles.rs +++ b/crates/registry-rstack-dev/src/roles.rs @@ -168,6 +168,7 @@ pub(super) fn resolve( issuer, external_jwks_uri, external_breg, + external_scheduling, products, person_audience, people, @@ -257,6 +258,7 @@ pub(super) fn resolve( issuer, external_jwks_uri, external_breg, + external_scheduling, products, person_audience, people: resolved, From 6b442a1a2a1bbcc0eadf51f1303e75bdd11c86cf Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 21:34:54 +0000 Subject: [PATCH 080/183] chore: regenerate the CLI catalogue, dev schema and Coordinator client on the rebased lane Signed-off-by: Jeremi Joslin --- clients/typescript/generated/coordinator.ts | 186 +++++----- crates/registry-cli-docs/catalog.json | 318 +++++++++++++++++- .../generated/dev/dev.v1alpha1.schema.json | 16 + 3 files changed, 411 insertions(+), 109 deletions(-) diff --git a/clients/typescript/generated/coordinator.ts b/clients/typescript/generated/coordinator.ts index ad11e93780..56e5c25f4e 100644 --- a/clients/typescript/generated/coordinator.ts +++ b/clients/typescript/generated/coordinator.ts @@ -1,5 +1,5 @@ // Generated for Stack version 0.50.0, client version 0.50.0. -// Source SHA-256 f329e651d18e54a7409383f43a7eff83463c9fbfacf5c072eeb15cc035311e68 +// Source SHA-256 bfc1de8b64985751de37a6f66efbca724d2878101aa47b15cb40a4192e76ffc2 // Unconstrained JSON /components/schemas/HookEnvelope/properties/data // Unconstrained JSON /components/schemas/RunStatus/properties/output // Unconstrained JSON /components/schemas/Start/properties/input @@ -40,7 +40,7 @@ export interface Operations { "ready": { input: CallOptions & { accept?: "application/json" | "*/*" }; required: false; output: ({ "developmentSettings": (Array<({ "code": (string); "pointer": (string) })>); "posture": ("production" | "development"); "ready": (boolean); "status": "ready" }) } "completeExecutionRecovery": { input: CallOptions & ({ body: Schema_ExecutionRecovery }) & { accept?: "application/json" | "*/*" }; required: true; output: Schema_ExecutionReviewed } "doctor": { input: CallOptions & { accept?: "application/json" | "*/*" }; required: false; output: Schema_Doctor } - "admitEvent": { input: CallOptions & { path: { "workflow": (string); "trigger": (string) } } & { headers: { "webhook-id": (string); "webhook-timestamp": (string); "webhook-signature": (string) } } & ({ body: Uint8Array }); required: true; output: undefined } + "admitEvent": { input: CallOptions & { path: { "workflowId": (string); "triggerId": (string) } } & { headers: { "webhook-id": (string); "webhook-timestamp": (string); "webhook-signature": (string) } } & ({ body: Uint8Array }); required: true; output: undefined } "releaseAdmissionHold": { input: CallOptions & ({ body: Schema_AdmissionRelease }) & { accept?: "application/json" | "*/*" }; required: true; output: Schema_AdmissionHold } "releaseRestoreHold": { input: CallOptions & ({ body: Schema_Reason }) & { accept?: "application/json" | "*/*" }; required: true; output: Schema_Hold } "restoreHold": { input: CallOptions & ({ body: Schema_Reason }) & { accept?: "application/json" | "*/*" }; required: true; output: Schema_Hold } @@ -48,13 +48,13 @@ export interface Operations { "receiveReviewCompletion": { input: CallOptions & { headers: { "Registry-Recipient-Binding": (string); "webhook-id": (string); "webhook-timestamp": (string); "webhook-signature": (string) } } & ({ body: Uint8Array }); required: true; output: undefined } "listRuns": { input: CallOptions & { query?: { "limit"?: (number); "cursor"?: (string); "state"?: ("running" | "finished" | "failed" | "cancelled" | "cancelled-after-effect" | "expired" | "attention" | "cancel-requested") & (string); "attention"?: (boolean); "proposal"?: (string); "turn"?: ("party" | "official" | "nobody") & (string); "outcome"?: (string) } } & { accept?: "application/json" | "*/*" }; required: false; output: Schema_RunList } "startRun": { input: CallOptions & ({ body: Schema_Start }) & { accept?: "application/json" | "*/*" }; required: true; output: Schema_RunStatus } - "runStatus": { input: CallOptions & { path: { "run": (string) } } & { accept?: "application/json" | "*/*" }; required: true; output: Schema_RunStatus } - "cancelRun": { input: CallOptions & { path: { "run": (string) } } & ({ body: Schema_Reason }) & { accept?: "application/json" | "*/*" }; required: true; output: Schema_RunStatus } - "checkNow": { input: CallOptions & { path: { "run": (string) } } & ({ body: Schema_CheckNow }) & { accept?: "application/json" | "*/*" }; required: true; output: Schema_CheckNowResult } - "inspectRun": { input: CallOptions & { path: { "run": (string) } } & { accept?: "application/json" | "*/*" }; required: true; output: Schema_RunInspection } - "reconcileRun": { input: CallOptions & { path: { "run": (string) } } & ({ body: Schema_Reason }) & { accept?: "application/json" | "*/*" }; required: true; output: Schema_RunInspection } - "retrySame": { input: CallOptions & { path: { "run": (string) } } & ({ body: Schema_Reason }) & { accept?: "application/json" | "*/*" }; required: true; output: Schema_RetryScheduled } - "workflowContract": { input: CallOptions & { path: { "workflow": (string) } } & { accept?: "application/json" | "*/*" }; required: true; output: Schema_WorkflowContract } + "runStatus": { input: CallOptions & { path: { "runId": (string) } } & { accept?: "application/json" | "*/*" }; required: true; output: Schema_RunStatus } + "cancelRun": { input: CallOptions & { path: { "runId": (string) } } & ({ body: Schema_Reason }) & { accept?: "application/json" | "*/*" }; required: true; output: Schema_RunStatus } + "checkNow": { input: CallOptions & { path: { "runId": (string) } } & ({ body: Schema_CheckNow }) & { accept?: "application/json" | "*/*" }; required: true; output: Schema_CheckNowResult } + "inspectRun": { input: CallOptions & { path: { "runId": (string) } } & { accept?: "application/json" | "*/*" }; required: true; output: Schema_RunInspection } + "reconcileRun": { input: CallOptions & { path: { "runId": (string) } } & ({ body: Schema_Reason }) & { accept?: "application/json" | "*/*" }; required: true; output: Schema_RunInspection } + "retrySame": { input: CallOptions & { path: { "runId": (string) } } & ({ body: Schema_Reason }) & { accept?: "application/json" | "*/*" }; required: true; output: Schema_RetryScheduled } + "workflowContract": { input: CallOptions & { path: { "workflowId": (string) } } & { accept?: "application/json" | "*/*" }; required: true; output: Schema_WorkflowContract } } const rules: Record = Object.fromEntries([ @@ -108,13 +108,13 @@ const rules: Record = Object.fromEntries([ ["/paths/~1v1~1doctor/get/responses/405/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"request.method-not-allowed\"]}}}]}")], ["/paths/~1v1~1doctor/get/responses/500/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"runtime.failure\"]}}}]}")], ["/paths/~1v1~1doctor/get/responses/503/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"audit.response-unavailable\",\"service.unavailable\"]}}}]}")], - ["/paths/~1v1~1events~1{workflow}~1{trigger}/post/responses/400/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"event.invalid\",\"input.invalid\",\"request.invalid\"]}}}]}")], - ["/paths/~1v1~1events~1{workflow}~1{trigger}/post/responses/401/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"event.unauthenticated\"]}}}]}")], - ["/paths/~1v1~1events~1{workflow}~1{trigger}/post/responses/405/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"request.method-not-allowed\"]}}}]}")], - ["/paths/~1v1~1events~1{workflow}~1{trigger}/post/responses/409/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"admission.held\",\"admission.recovery-only\",\"binding.conflict\",\"binding.live-conflict\",\"definition.refused\",\"deployment.activation-changed\",\"deployment.refused\",\"execution.held\",\"idempotency.key-reused\"]}}}]}")], - ["/paths/~1v1~1events~1{workflow}~1{trigger}/post/responses/413/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"event.too-large\",\"request.body-too-large\"]}}}]}")], - ["/paths/~1v1~1events~1{workflow}~1{trigger}/post/responses/500/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"runtime.failure\"]}}}]}")], - ["/paths/~1v1~1events~1{workflow}~1{trigger}/post/responses/503/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"audit.response-unavailable\",\"service.unavailable\"]}}}]}")], + ["/paths/~1v1~1events~1{workflowId}~1{triggerId}/post/responses/400/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"event.invalid\",\"input.invalid\",\"request.invalid\"]}}}]}")], + ["/paths/~1v1~1events~1{workflowId}~1{triggerId}/post/responses/401/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"event.unauthenticated\"]}}}]}")], + ["/paths/~1v1~1events~1{workflowId}~1{triggerId}/post/responses/405/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"request.method-not-allowed\"]}}}]}")], + ["/paths/~1v1~1events~1{workflowId}~1{triggerId}/post/responses/409/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"admission.held\",\"admission.recovery-only\",\"binding.conflict\",\"binding.live-conflict\",\"definition.refused\",\"deployment.activation-changed\",\"deployment.refused\",\"execution.held\",\"idempotency.key-reused\"]}}}]}")], + ["/paths/~1v1~1events~1{workflowId}~1{triggerId}/post/responses/413/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"event.too-large\",\"request.body-too-large\"]}}}]}")], + ["/paths/~1v1~1events~1{workflowId}~1{triggerId}/post/responses/500/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"runtime.failure\"]}}}]}")], + ["/paths/~1v1~1events~1{workflowId}~1{triggerId}/post/responses/503/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"audit.response-unavailable\",\"service.unavailable\"]}}}]}")], ["/paths/~1v1~1release-admission-hold/post/responses/200/content/application~1json/schema", JSON.parse("{\"$ref\":\"/components/schemas/AdmissionHold\"}")], ["/paths/~1v1~1release-admission-hold/post/responses/400/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"request.invalid\",\"request.reason-invalid\"]}}}]}")], ["/paths/~1v1~1release-admission-hold/post/responses/401/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"authentication.refused\"]}}}]}")], @@ -177,75 +177,75 @@ const rules: Record = Object.fromEntries([ ["/paths/~1v1~1runs/post/responses/415/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"request.unsupported-media-type\"]}}}]}")], ["/paths/~1v1~1runs/post/responses/500/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"runtime.failure\"]}}}]}")], ["/paths/~1v1~1runs/post/responses/503/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"audit.response-unavailable\",\"service.unavailable\"]}}}]}")], - ["/paths/~1v1~1runs~1{run}/get/responses/200/content/application~1json/schema", JSON.parse("{\"$ref\":\"/components/schemas/RunStatus\"}")], - ["/paths/~1v1~1runs~1{run}/get/responses/400/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"request.invalid\"]}}}]}")], - ["/paths/~1v1~1runs~1{run}/get/responses/401/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"authentication.refused\"]}}}]}")], - ["/paths/~1v1~1runs~1{run}/get/responses/403/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"operation.not-authorized\"]}}}]}")], - ["/paths/~1v1~1runs~1{run}/get/responses/404/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"run.not-visible\"]}}}]}")], - ["/paths/~1v1~1runs~1{run}/get/responses/405/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"request.method-not-allowed\"]}}}]}")], - ["/paths/~1v1~1runs~1{run}/get/responses/500/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"runtime.failure\"]}}}]}")], - ["/paths/~1v1~1runs~1{run}/get/responses/503/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"audit.response-unavailable\",\"service.unavailable\"]}}}]}")], - ["/paths/~1v1~1runs~1{run}~1cancel/post/responses/200/content/application~1json/schema", JSON.parse("{\"$ref\":\"/components/schemas/RunStatus\"}")], - ["/paths/~1v1~1runs~1{run}~1cancel/post/responses/400/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"request.invalid\",\"request.reason-invalid\"]}}}]}")], - ["/paths/~1v1~1runs~1{run}~1cancel/post/responses/401/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"authentication.refused\"]}}}]}")], - ["/paths/~1v1~1runs~1{run}~1cancel/post/responses/403/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"operation.not-authorized\"]}}}]}")], - ["/paths/~1v1~1runs~1{run}~1cancel/post/responses/404/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"run.not-visible\"]}}}]}")], - ["/paths/~1v1~1runs~1{run}~1cancel/post/responses/405/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"request.method-not-allowed\"]}}}]}")], - ["/paths/~1v1~1runs~1{run}~1cancel/post/responses/409/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"run.definition-incompatible\"]}}}]}")], - ["/paths/~1v1~1runs~1{run}~1cancel/post/responses/413/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"request.body-too-large\"]}}}]}")], - ["/paths/~1v1~1runs~1{run}~1cancel/post/responses/415/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"request.unsupported-media-type\"]}}}]}")], - ["/paths/~1v1~1runs~1{run}~1cancel/post/responses/500/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"runtime.failure\"]}}}]}")], - ["/paths/~1v1~1runs~1{run}~1cancel/post/responses/503/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"audit.response-unavailable\",\"service.unavailable\"]}}}]}")], - ["/paths/~1v1~1runs~1{run}~1check/post/responses/200/content/application~1json/schema", JSON.parse("{\"$ref\":\"/components/schemas/CheckNowResult\"}")], - ["/paths/~1v1~1runs~1{run}~1check/post/responses/400/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"request.invalid\"]}}}]}")], - ["/paths/~1v1~1runs~1{run}~1check/post/responses/401/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"authentication.refused\"]}}}]}")], - ["/paths/~1v1~1runs~1{run}~1check/post/responses/403/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"operation.not-authorized\"]}}}]}")], - ["/paths/~1v1~1runs~1{run}~1check/post/responses/404/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"run.not-visible\"]}}}]}")], - ["/paths/~1v1~1runs~1{run}~1check/post/responses/405/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"request.method-not-allowed\"]}}}]}")], - ["/paths/~1v1~1runs~1{run}~1check/post/responses/409/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"check.not-waiting\"]}}}]}")], - ["/paths/~1v1~1runs~1{run}~1check/post/responses/413/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"request.body-too-large\"]}}}]}")], - ["/paths/~1v1~1runs~1{run}~1check/post/responses/415/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"request.unsupported-media-type\"]}}}]}")], - ["/paths/~1v1~1runs~1{run}~1check/post/responses/500/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"runtime.failure\"]}}}]}")], - ["/paths/~1v1~1runs~1{run}~1check/post/responses/503/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"audit.response-unavailable\",\"service.unavailable\"]}}}]}")], - ["/paths/~1v1~1runs~1{run}~1inspect/get/responses/200/content/application~1json/schema", JSON.parse("{\"$ref\":\"/components/schemas/RunInspection\"}")], - ["/paths/~1v1~1runs~1{run}~1inspect/get/responses/400/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"request.invalid\"]}}}]}")], - ["/paths/~1v1~1runs~1{run}~1inspect/get/responses/401/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"authentication.refused\"]}}}]}")], - ["/paths/~1v1~1runs~1{run}~1inspect/get/responses/403/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"operation.not-authorized\"]}}}]}")], - ["/paths/~1v1~1runs~1{run}~1inspect/get/responses/404/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"run.not-visible\"]}}}]}")], - ["/paths/~1v1~1runs~1{run}~1inspect/get/responses/405/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"request.method-not-allowed\"]}}}]}")], - ["/paths/~1v1~1runs~1{run}~1inspect/get/responses/409/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"binding.conflict\",\"definition.refused\",\"run.payload-erased\"]}}}]}")], - ["/paths/~1v1~1runs~1{run}~1inspect/get/responses/500/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"runtime.failure\"]}}}]}")], - ["/paths/~1v1~1runs~1{run}~1inspect/get/responses/503/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"audit.response-unavailable\",\"service.unavailable\"]}}}]}")], - ["/paths/~1v1~1runs~1{run}~1reconcile/post/responses/200/content/application~1json/schema", JSON.parse("{\"$ref\":\"/components/schemas/RunInspection\"}")], - ["/paths/~1v1~1runs~1{run}~1reconcile/post/responses/400/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"request.invalid\",\"request.reason-invalid\"]}}}]}")], - ["/paths/~1v1~1runs~1{run}~1reconcile/post/responses/401/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"authentication.refused\"]}}}]}")], - ["/paths/~1v1~1runs~1{run}~1reconcile/post/responses/403/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"operation.not-authorized\"]}}}]}")], - ["/paths/~1v1~1runs~1{run}~1reconcile/post/responses/404/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"run.not-visible\"]}}}]}")], - ["/paths/~1v1~1runs~1{run}~1reconcile/post/responses/405/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"request.method-not-allowed\"]}}}]}")], - ["/paths/~1v1~1runs~1{run}~1reconcile/post/responses/409/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"binding.conflict\",\"definition.refused\",\"reconcile.raced\",\"reconcile.refused\",\"reconcile.unsupported\",\"run.definition-incompatible\",\"run.payload-erased\"]}}}]}")], - ["/paths/~1v1~1runs~1{run}~1reconcile/post/responses/413/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"request.body-too-large\"]}}}]}")], - ["/paths/~1v1~1runs~1{run}~1reconcile/post/responses/415/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"request.unsupported-media-type\"]}}}]}")], - ["/paths/~1v1~1runs~1{run}~1reconcile/post/responses/500/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"runtime.failure\"]}}}]}")], - ["/paths/~1v1~1runs~1{run}~1reconcile/post/responses/503/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"audit.response-unavailable\",\"service.unavailable\"]}}}]}")], - ["/paths/~1v1~1runs~1{run}~1retry-same/post/responses/200/content/application~1json/schema", JSON.parse("{\"$ref\":\"/components/schemas/RetryScheduled\"}")], - ["/paths/~1v1~1runs~1{run}~1retry-same/post/responses/400/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"request.invalid\",\"request.reason-invalid\"]}}}]}")], - ["/paths/~1v1~1runs~1{run}~1retry-same/post/responses/401/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"authentication.refused\"]}}}]}")], - ["/paths/~1v1~1runs~1{run}~1retry-same/post/responses/403/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"operation.not-authorized\"]}}}]}")], - ["/paths/~1v1~1runs~1{run}~1retry-same/post/responses/404/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"run.not-visible\"]}}}]}")], - ["/paths/~1v1~1runs~1{run}~1retry-same/post/responses/405/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"request.method-not-allowed\"]}}}]}")], - ["/paths/~1v1~1runs~1{run}~1retry-same/post/responses/409/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"binding.conflict\",\"definition.refused\",\"evaluation.uncertain\",\"mutation.uncertain\",\"receipt.expired\",\"retry.refused\",\"run.definition-incompatible\",\"run.payload-erased\"]}}}]}")], - ["/paths/~1v1~1runs~1{run}~1retry-same/post/responses/413/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"request.body-too-large\"]}}}]}")], - ["/paths/~1v1~1runs~1{run}~1retry-same/post/responses/415/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"request.unsupported-media-type\"]}}}]}")], - ["/paths/~1v1~1runs~1{run}~1retry-same/post/responses/500/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"runtime.failure\"]}}}]}")], - ["/paths/~1v1~1runs~1{run}~1retry-same/post/responses/503/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"audit.response-unavailable\",\"service.unavailable\"]}}}]}")], - ["/paths/~1v1~1workflows~1{workflow}/get/responses/200/content/application~1json/schema", JSON.parse("{\"$ref\":\"/components/schemas/WorkflowContract\"}")], - ["/paths/~1v1~1workflows~1{workflow}/get/responses/401/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"authentication.refused\"]}}}]}")], - ["/paths/~1v1~1workflows~1{workflow}/get/responses/403/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"operation.not-authorized\"]}}}]}")], - ["/paths/~1v1~1workflows~1{workflow}/get/responses/404/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"workflow.not-served\"]}}}]}")], - ["/paths/~1v1~1workflows~1{workflow}/get/responses/405/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"request.method-not-allowed\"]}}}]}")], - ["/paths/~1v1~1workflows~1{workflow}/get/responses/409/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"deployment.activation-changed\",\"deployment.refused\"]}}}]}")], - ["/paths/~1v1~1workflows~1{workflow}/get/responses/500/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"runtime.failure\"]}}}]}")], - ["/paths/~1v1~1workflows~1{workflow}/get/responses/503/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"audit.response-unavailable\",\"service.unavailable\"]}}}]}")], + ["/paths/~1v1~1runs~1{runId}/get/responses/200/content/application~1json/schema", JSON.parse("{\"$ref\":\"/components/schemas/RunStatus\"}")], + ["/paths/~1v1~1runs~1{runId}/get/responses/400/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"request.invalid\"]}}}]}")], + ["/paths/~1v1~1runs~1{runId}/get/responses/401/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"authentication.refused\"]}}}]}")], + ["/paths/~1v1~1runs~1{runId}/get/responses/403/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"operation.not-authorized\"]}}}]}")], + ["/paths/~1v1~1runs~1{runId}/get/responses/404/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"run.not-visible\"]}}}]}")], + ["/paths/~1v1~1runs~1{runId}/get/responses/405/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"request.method-not-allowed\"]}}}]}")], + ["/paths/~1v1~1runs~1{runId}/get/responses/500/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"runtime.failure\"]}}}]}")], + ["/paths/~1v1~1runs~1{runId}/get/responses/503/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"audit.response-unavailable\",\"service.unavailable\"]}}}]}")], + ["/paths/~1v1~1runs~1{runId}~1cancel/post/responses/200/content/application~1json/schema", JSON.parse("{\"$ref\":\"/components/schemas/RunStatus\"}")], + ["/paths/~1v1~1runs~1{runId}~1cancel/post/responses/400/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"request.invalid\",\"request.reason-invalid\"]}}}]}")], + ["/paths/~1v1~1runs~1{runId}~1cancel/post/responses/401/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"authentication.refused\"]}}}]}")], + ["/paths/~1v1~1runs~1{runId}~1cancel/post/responses/403/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"operation.not-authorized\"]}}}]}")], + ["/paths/~1v1~1runs~1{runId}~1cancel/post/responses/404/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"run.not-visible\"]}}}]}")], + ["/paths/~1v1~1runs~1{runId}~1cancel/post/responses/405/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"request.method-not-allowed\"]}}}]}")], + ["/paths/~1v1~1runs~1{runId}~1cancel/post/responses/409/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"run.definition-incompatible\"]}}}]}")], + ["/paths/~1v1~1runs~1{runId}~1cancel/post/responses/413/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"request.body-too-large\"]}}}]}")], + ["/paths/~1v1~1runs~1{runId}~1cancel/post/responses/415/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"request.unsupported-media-type\"]}}}]}")], + ["/paths/~1v1~1runs~1{runId}~1cancel/post/responses/500/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"runtime.failure\"]}}}]}")], + ["/paths/~1v1~1runs~1{runId}~1cancel/post/responses/503/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"audit.response-unavailable\",\"service.unavailable\"]}}}]}")], + ["/paths/~1v1~1runs~1{runId}~1check/post/responses/200/content/application~1json/schema", JSON.parse("{\"$ref\":\"/components/schemas/CheckNowResult\"}")], + ["/paths/~1v1~1runs~1{runId}~1check/post/responses/400/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"request.invalid\"]}}}]}")], + ["/paths/~1v1~1runs~1{runId}~1check/post/responses/401/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"authentication.refused\"]}}}]}")], + ["/paths/~1v1~1runs~1{runId}~1check/post/responses/403/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"operation.not-authorized\"]}}}]}")], + ["/paths/~1v1~1runs~1{runId}~1check/post/responses/404/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"run.not-visible\"]}}}]}")], + ["/paths/~1v1~1runs~1{runId}~1check/post/responses/405/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"request.method-not-allowed\"]}}}]}")], + ["/paths/~1v1~1runs~1{runId}~1check/post/responses/409/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"check.not-waiting\"]}}}]}")], + ["/paths/~1v1~1runs~1{runId}~1check/post/responses/413/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"request.body-too-large\"]}}}]}")], + ["/paths/~1v1~1runs~1{runId}~1check/post/responses/415/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"request.unsupported-media-type\"]}}}]}")], + ["/paths/~1v1~1runs~1{runId}~1check/post/responses/500/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"runtime.failure\"]}}}]}")], + ["/paths/~1v1~1runs~1{runId}~1check/post/responses/503/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"audit.response-unavailable\",\"service.unavailable\"]}}}]}")], + ["/paths/~1v1~1runs~1{runId}~1inspect/get/responses/200/content/application~1json/schema", JSON.parse("{\"$ref\":\"/components/schemas/RunInspection\"}")], + ["/paths/~1v1~1runs~1{runId}~1inspect/get/responses/400/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"request.invalid\"]}}}]}")], + ["/paths/~1v1~1runs~1{runId}~1inspect/get/responses/401/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"authentication.refused\"]}}}]}")], + ["/paths/~1v1~1runs~1{runId}~1inspect/get/responses/403/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"operation.not-authorized\"]}}}]}")], + ["/paths/~1v1~1runs~1{runId}~1inspect/get/responses/404/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"run.not-visible\"]}}}]}")], + ["/paths/~1v1~1runs~1{runId}~1inspect/get/responses/405/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"request.method-not-allowed\"]}}}]}")], + ["/paths/~1v1~1runs~1{runId}~1inspect/get/responses/409/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"binding.conflict\",\"definition.refused\",\"run.payload-erased\"]}}}]}")], + ["/paths/~1v1~1runs~1{runId}~1inspect/get/responses/500/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"runtime.failure\"]}}}]}")], + ["/paths/~1v1~1runs~1{runId}~1inspect/get/responses/503/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"audit.response-unavailable\",\"service.unavailable\"]}}}]}")], + ["/paths/~1v1~1runs~1{runId}~1reconcile/post/responses/200/content/application~1json/schema", JSON.parse("{\"$ref\":\"/components/schemas/RunInspection\"}")], + ["/paths/~1v1~1runs~1{runId}~1reconcile/post/responses/400/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"request.invalid\",\"request.reason-invalid\"]}}}]}")], + ["/paths/~1v1~1runs~1{runId}~1reconcile/post/responses/401/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"authentication.refused\"]}}}]}")], + ["/paths/~1v1~1runs~1{runId}~1reconcile/post/responses/403/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"operation.not-authorized\"]}}}]}")], + ["/paths/~1v1~1runs~1{runId}~1reconcile/post/responses/404/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"run.not-visible\"]}}}]}")], + ["/paths/~1v1~1runs~1{runId}~1reconcile/post/responses/405/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"request.method-not-allowed\"]}}}]}")], + ["/paths/~1v1~1runs~1{runId}~1reconcile/post/responses/409/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"binding.conflict\",\"definition.refused\",\"reconcile.raced\",\"reconcile.refused\",\"reconcile.unsupported\",\"run.definition-incompatible\",\"run.payload-erased\"]}}}]}")], + ["/paths/~1v1~1runs~1{runId}~1reconcile/post/responses/413/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"request.body-too-large\"]}}}]}")], + ["/paths/~1v1~1runs~1{runId}~1reconcile/post/responses/415/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"request.unsupported-media-type\"]}}}]}")], + ["/paths/~1v1~1runs~1{runId}~1reconcile/post/responses/500/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"runtime.failure\"]}}}]}")], + ["/paths/~1v1~1runs~1{runId}~1reconcile/post/responses/503/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"audit.response-unavailable\",\"service.unavailable\"]}}}]}")], + ["/paths/~1v1~1runs~1{runId}~1retry-same/post/responses/200/content/application~1json/schema", JSON.parse("{\"$ref\":\"/components/schemas/RetryScheduled\"}")], + ["/paths/~1v1~1runs~1{runId}~1retry-same/post/responses/400/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"request.invalid\",\"request.reason-invalid\"]}}}]}")], + ["/paths/~1v1~1runs~1{runId}~1retry-same/post/responses/401/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"authentication.refused\"]}}}]}")], + ["/paths/~1v1~1runs~1{runId}~1retry-same/post/responses/403/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"operation.not-authorized\"]}}}]}")], + ["/paths/~1v1~1runs~1{runId}~1retry-same/post/responses/404/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"run.not-visible\"]}}}]}")], + ["/paths/~1v1~1runs~1{runId}~1retry-same/post/responses/405/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"request.method-not-allowed\"]}}}]}")], + ["/paths/~1v1~1runs~1{runId}~1retry-same/post/responses/409/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"binding.conflict\",\"definition.refused\",\"evaluation.uncertain\",\"mutation.uncertain\",\"receipt.expired\",\"retry.refused\",\"run.definition-incompatible\",\"run.payload-erased\"]}}}]}")], + ["/paths/~1v1~1runs~1{runId}~1retry-same/post/responses/413/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"request.body-too-large\"]}}}]}")], + ["/paths/~1v1~1runs~1{runId}~1retry-same/post/responses/415/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"request.unsupported-media-type\"]}}}]}")], + ["/paths/~1v1~1runs~1{runId}~1retry-same/post/responses/500/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"runtime.failure\"]}}}]}")], + ["/paths/~1v1~1runs~1{runId}~1retry-same/post/responses/503/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"audit.response-unavailable\",\"service.unavailable\"]}}}]}")], + ["/paths/~1v1~1workflows~1{workflowId}/get/responses/200/content/application~1json/schema", JSON.parse("{\"$ref\":\"/components/schemas/WorkflowContract\"}")], + ["/paths/~1v1~1workflows~1{workflowId}/get/responses/401/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"authentication.refused\"]}}}]}")], + ["/paths/~1v1~1workflows~1{workflowId}/get/responses/403/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"operation.not-authorized\"]}}}]}")], + ["/paths/~1v1~1workflows~1{workflowId}/get/responses/404/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"workflow.not-served\"]}}}]}")], + ["/paths/~1v1~1workflows~1{workflowId}/get/responses/405/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"request.method-not-allowed\"]}}}]}")], + ["/paths/~1v1~1workflows~1{workflowId}/get/responses/409/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"deployment.activation-changed\",\"deployment.refused\"]}}}]}")], + ["/paths/~1v1~1workflows~1{workflowId}/get/responses/500/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"runtime.failure\"]}}}]}")], + ["/paths/~1v1~1workflows~1{workflowId}/get/responses/503/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"audit.response-unavailable\",\"service.unavailable\"]}}}]}")], ]) const routes: Record = Object.create(null) type Definition = Omit & { problems?: Record; responses: Record> } @@ -254,7 +254,7 @@ const definitions: Record = Object.fromEntries([ ["ready", JSON.parse("{\"method\":\"GET\",\"path\":\"/ready\",\"responses\":{\"200\":[{\"mediaType\":\"application/json\",\"mode\":\"json\",\"rule\":\"/paths/~1ready/get/responses/200/content/application~1json/schema\"}]},\"keyed\":false,\"mutating\":false,\"problems\":{\"405\":\"/paths/~1ready/get/responses/405/content/application~1problem+json/schema\"}}")], ["completeExecutionRecovery", JSON.parse("{\"method\":\"POST\",\"path\":\"/v1/complete-execution-recovery\",\"responses\":{\"200\":[{\"mediaType\":\"application/json\",\"mode\":\"json\",\"rule\":\"/paths/~1v1~1complete-execution-recovery/post/responses/200/content/application~1json/schema\"}]},\"keyed\":false,\"mutating\":true,\"requestMediaTypes\":[\"application/json\"],\"requestMediaType\":\"application/json\",\"problems\":{\"400\":\"/paths/~1v1~1complete-execution-recovery/post/responses/400/content/application~1problem+json/schema\",\"401\":\"/paths/~1v1~1complete-execution-recovery/post/responses/401/content/application~1problem+json/schema\",\"403\":\"/paths/~1v1~1complete-execution-recovery/post/responses/403/content/application~1problem+json/schema\",\"405\":\"/paths/~1v1~1complete-execution-recovery/post/responses/405/content/application~1problem+json/schema\",\"409\":\"/paths/~1v1~1complete-execution-recovery/post/responses/409/content/application~1problem+json/schema\",\"413\":\"/paths/~1v1~1complete-execution-recovery/post/responses/413/content/application~1problem+json/schema\",\"415\":\"/paths/~1v1~1complete-execution-recovery/post/responses/415/content/application~1problem+json/schema\",\"500\":\"/paths/~1v1~1complete-execution-recovery/post/responses/500/content/application~1problem+json/schema\",\"503\":\"/paths/~1v1~1complete-execution-recovery/post/responses/503/content/application~1problem+json/schema\"}}")], ["doctor", JSON.parse("{\"method\":\"GET\",\"path\":\"/v1/doctor\",\"responses\":{\"200\":[{\"mediaType\":\"application/json\",\"mode\":\"json\",\"rule\":\"/paths/~1v1~1doctor/get/responses/200/content/application~1json/schema\"}]},\"keyed\":false,\"mutating\":false,\"problems\":{\"401\":\"/paths/~1v1~1doctor/get/responses/401/content/application~1problem+json/schema\",\"403\":\"/paths/~1v1~1doctor/get/responses/403/content/application~1problem+json/schema\",\"405\":\"/paths/~1v1~1doctor/get/responses/405/content/application~1problem+json/schema\",\"500\":\"/paths/~1v1~1doctor/get/responses/500/content/application~1problem+json/schema\",\"503\":\"/paths/~1v1~1doctor/get/responses/503/content/application~1problem+json/schema\"}}")], - ["admitEvent", JSON.parse("{\"method\":\"POST\",\"path\":\"/v1/events/{workflow}/{trigger}\",\"responses\":{\"204\":[{\"mode\":\"empty\"}]},\"keyed\":false,\"signed\":true,\"mutating\":true,\"requestMediaTypes\":[\"application/json\"],\"requestMediaType\":\"application/json\",\"problems\":{\"400\":\"/paths/~1v1~1events~1{workflow}~1{trigger}/post/responses/400/content/application~1problem+json/schema\",\"401\":\"/paths/~1v1~1events~1{workflow}~1{trigger}/post/responses/401/content/application~1problem+json/schema\",\"405\":\"/paths/~1v1~1events~1{workflow}~1{trigger}/post/responses/405/content/application~1problem+json/schema\",\"409\":\"/paths/~1v1~1events~1{workflow}~1{trigger}/post/responses/409/content/application~1problem+json/schema\",\"413\":\"/paths/~1v1~1events~1{workflow}~1{trigger}/post/responses/413/content/application~1problem+json/schema\",\"500\":\"/paths/~1v1~1events~1{workflow}~1{trigger}/post/responses/500/content/application~1problem+json/schema\",\"503\":\"/paths/~1v1~1events~1{workflow}~1{trigger}/post/responses/503/content/application~1problem+json/schema\"}}")], + ["admitEvent", JSON.parse("{\"method\":\"POST\",\"path\":\"/v1/events/{workflowId}/{triggerId}\",\"responses\":{\"204\":[{\"mode\":\"empty\"}]},\"keyed\":false,\"signed\":true,\"mutating\":true,\"requestMediaTypes\":[\"application/json\"],\"requestMediaType\":\"application/json\",\"problems\":{\"400\":\"/paths/~1v1~1events~1{workflowId}~1{triggerId}/post/responses/400/content/application~1problem+json/schema\",\"401\":\"/paths/~1v1~1events~1{workflowId}~1{triggerId}/post/responses/401/content/application~1problem+json/schema\",\"405\":\"/paths/~1v1~1events~1{workflowId}~1{triggerId}/post/responses/405/content/application~1problem+json/schema\",\"409\":\"/paths/~1v1~1events~1{workflowId}~1{triggerId}/post/responses/409/content/application~1problem+json/schema\",\"413\":\"/paths/~1v1~1events~1{workflowId}~1{triggerId}/post/responses/413/content/application~1problem+json/schema\",\"500\":\"/paths/~1v1~1events~1{workflowId}~1{triggerId}/post/responses/500/content/application~1problem+json/schema\",\"503\":\"/paths/~1v1~1events~1{workflowId}~1{triggerId}/post/responses/503/content/application~1problem+json/schema\"}}")], ["releaseAdmissionHold", JSON.parse("{\"method\":\"POST\",\"path\":\"/v1/release-admission-hold\",\"responses\":{\"200\":[{\"mediaType\":\"application/json\",\"mode\":\"json\",\"rule\":\"/paths/~1v1~1release-admission-hold/post/responses/200/content/application~1json/schema\"}]},\"keyed\":false,\"mutating\":true,\"requestMediaTypes\":[\"application/json\"],\"requestMediaType\":\"application/json\",\"problems\":{\"400\":\"/paths/~1v1~1release-admission-hold/post/responses/400/content/application~1problem+json/schema\",\"401\":\"/paths/~1v1~1release-admission-hold/post/responses/401/content/application~1problem+json/schema\",\"403\":\"/paths/~1v1~1release-admission-hold/post/responses/403/content/application~1problem+json/schema\",\"405\":\"/paths/~1v1~1release-admission-hold/post/responses/405/content/application~1problem+json/schema\",\"409\":\"/paths/~1v1~1release-admission-hold/post/responses/409/content/application~1problem+json/schema\",\"413\":\"/paths/~1v1~1release-admission-hold/post/responses/413/content/application~1problem+json/schema\",\"415\":\"/paths/~1v1~1release-admission-hold/post/responses/415/content/application~1problem+json/schema\",\"500\":\"/paths/~1v1~1release-admission-hold/post/responses/500/content/application~1problem+json/schema\",\"503\":\"/paths/~1v1~1release-admission-hold/post/responses/503/content/application~1problem+json/schema\"}}")], ["releaseRestoreHold", JSON.parse("{\"method\":\"POST\",\"path\":\"/v1/release-restore-hold\",\"responses\":{\"200\":[{\"mediaType\":\"application/json\",\"mode\":\"json\",\"rule\":\"/paths/~1v1~1release-restore-hold/post/responses/200/content/application~1json/schema\"}]},\"keyed\":false,\"mutating\":true,\"requestMediaTypes\":[\"application/json\"],\"requestMediaType\":\"application/json\",\"problems\":{\"400\":\"/paths/~1v1~1release-restore-hold/post/responses/400/content/application~1problem+json/schema\",\"401\":\"/paths/~1v1~1release-restore-hold/post/responses/401/content/application~1problem+json/schema\",\"403\":\"/paths/~1v1~1release-restore-hold/post/responses/403/content/application~1problem+json/schema\",\"405\":\"/paths/~1v1~1release-restore-hold/post/responses/405/content/application~1problem+json/schema\",\"409\":\"/paths/~1v1~1release-restore-hold/post/responses/409/content/application~1problem+json/schema\",\"413\":\"/paths/~1v1~1release-restore-hold/post/responses/413/content/application~1problem+json/schema\",\"415\":\"/paths/~1v1~1release-restore-hold/post/responses/415/content/application~1problem+json/schema\",\"500\":\"/paths/~1v1~1release-restore-hold/post/responses/500/content/application~1problem+json/schema\",\"503\":\"/paths/~1v1~1release-restore-hold/post/responses/503/content/application~1problem+json/schema\"}}")], ["restoreHold", JSON.parse("{\"method\":\"POST\",\"path\":\"/v1/restore-hold\",\"responses\":{\"200\":[{\"mediaType\":\"application/json\",\"mode\":\"json\",\"rule\":\"/paths/~1v1~1restore-hold/post/responses/200/content/application~1json/schema\"}]},\"keyed\":false,\"mutating\":true,\"requestMediaTypes\":[\"application/json\"],\"requestMediaType\":\"application/json\",\"problems\":{\"400\":\"/paths/~1v1~1restore-hold/post/responses/400/content/application~1problem+json/schema\",\"401\":\"/paths/~1v1~1restore-hold/post/responses/401/content/application~1problem+json/schema\",\"403\":\"/paths/~1v1~1restore-hold/post/responses/403/content/application~1problem+json/schema\",\"405\":\"/paths/~1v1~1restore-hold/post/responses/405/content/application~1problem+json/schema\",\"413\":\"/paths/~1v1~1restore-hold/post/responses/413/content/application~1problem+json/schema\",\"415\":\"/paths/~1v1~1restore-hold/post/responses/415/content/application~1problem+json/schema\",\"500\":\"/paths/~1v1~1restore-hold/post/responses/500/content/application~1problem+json/schema\",\"503\":\"/paths/~1v1~1restore-hold/post/responses/503/content/application~1problem+json/schema\"}}")], @@ -262,13 +262,13 @@ const definitions: Record = Object.fromEntries([ ["receiveReviewCompletion", JSON.parse("{\"method\":\"POST\",\"path\":\"/v1/review-completions\",\"responses\":{\"204\":[{\"mode\":\"empty\"}]},\"keyed\":false,\"signed\":true,\"mutating\":true,\"requestMediaTypes\":[\"application/json\"],\"requestMediaType\":\"application/json\",\"problems\":{\"400\":\"/paths/~1v1~1review-completions/post/responses/400/content/application~1problem+json/schema\",\"401\":\"/paths/~1v1~1review-completions/post/responses/401/content/application~1problem+json/schema\",\"405\":\"/paths/~1v1~1review-completions/post/responses/405/content/application~1problem+json/schema\",\"413\":\"/paths/~1v1~1review-completions/post/responses/413/content/application~1problem+json/schema\",\"415\":\"/paths/~1v1~1review-completions/post/responses/415/content/application~1problem+json/schema\",\"503\":\"/paths/~1v1~1review-completions/post/responses/503/content/application~1problem+json/schema\"}}")], ["listRuns", JSON.parse("{\"method\":\"GET\",\"path\":\"/v1/runs\",\"responses\":{\"200\":[{\"mediaType\":\"application/json\",\"mode\":\"json\",\"rule\":\"/paths/~1v1~1runs/get/responses/200/content/application~1json/schema\"}]},\"keyed\":false,\"mutating\":false,\"problems\":{\"400\":\"/paths/~1v1~1runs/get/responses/400/content/application~1problem+json/schema\",\"401\":\"/paths/~1v1~1runs/get/responses/401/content/application~1problem+json/schema\",\"403\":\"/paths/~1v1~1runs/get/responses/403/content/application~1problem+json/schema\",\"405\":\"/paths/~1v1~1runs/get/responses/405/content/application~1problem+json/schema\",\"500\":\"/paths/~1v1~1runs/get/responses/500/content/application~1problem+json/schema\",\"503\":\"/paths/~1v1~1runs/get/responses/503/content/application~1problem+json/schema\"}}")], ["startRun", JSON.parse("{\"method\":\"POST\",\"path\":\"/v1/runs\",\"responses\":{\"200\":[{\"mediaType\":\"application/json\",\"mode\":\"json\",\"rule\":\"/paths/~1v1~1runs/post/responses/200/content/application~1json/schema\"}]},\"keyed\":true,\"mutating\":true,\"requestMediaTypes\":[\"application/json\"],\"requestMediaType\":\"application/json\",\"problems\":{\"400\":\"/paths/~1v1~1runs/post/responses/400/content/application~1problem+json/schema\",\"401\":\"/paths/~1v1~1runs/post/responses/401/content/application~1problem+json/schema\",\"403\":\"/paths/~1v1~1runs/post/responses/403/content/application~1problem+json/schema\",\"404\":\"/paths/~1v1~1runs/post/responses/404/content/application~1problem+json/schema\",\"405\":\"/paths/~1v1~1runs/post/responses/405/content/application~1problem+json/schema\",\"409\":\"/paths/~1v1~1runs/post/responses/409/content/application~1problem+json/schema\",\"413\":\"/paths/~1v1~1runs/post/responses/413/content/application~1problem+json/schema\",\"415\":\"/paths/~1v1~1runs/post/responses/415/content/application~1problem+json/schema\",\"500\":\"/paths/~1v1~1runs/post/responses/500/content/application~1problem+json/schema\",\"503\":\"/paths/~1v1~1runs/post/responses/503/content/application~1problem+json/schema\"}}")], - ["runStatus", JSON.parse("{\"method\":\"GET\",\"path\":\"/v1/runs/{run}\",\"responses\":{\"200\":[{\"mediaType\":\"application/json\",\"mode\":\"json\",\"rule\":\"/paths/~1v1~1runs~1{run}/get/responses/200/content/application~1json/schema\"}]},\"keyed\":false,\"mutating\":false,\"problems\":{\"400\":\"/paths/~1v1~1runs~1{run}/get/responses/400/content/application~1problem+json/schema\",\"401\":\"/paths/~1v1~1runs~1{run}/get/responses/401/content/application~1problem+json/schema\",\"403\":\"/paths/~1v1~1runs~1{run}/get/responses/403/content/application~1problem+json/schema\",\"404\":\"/paths/~1v1~1runs~1{run}/get/responses/404/content/application~1problem+json/schema\",\"405\":\"/paths/~1v1~1runs~1{run}/get/responses/405/content/application~1problem+json/schema\",\"500\":\"/paths/~1v1~1runs~1{run}/get/responses/500/content/application~1problem+json/schema\",\"503\":\"/paths/~1v1~1runs~1{run}/get/responses/503/content/application~1problem+json/schema\"}}")], - ["cancelRun", JSON.parse("{\"method\":\"POST\",\"path\":\"/v1/runs/{run}/cancel\",\"responses\":{\"200\":[{\"mediaType\":\"application/json\",\"mode\":\"json\",\"rule\":\"/paths/~1v1~1runs~1{run}~1cancel/post/responses/200/content/application~1json/schema\"}]},\"keyed\":false,\"mutating\":true,\"requestMediaTypes\":[\"application/json\"],\"requestMediaType\":\"application/json\",\"problems\":{\"400\":\"/paths/~1v1~1runs~1{run}~1cancel/post/responses/400/content/application~1problem+json/schema\",\"401\":\"/paths/~1v1~1runs~1{run}~1cancel/post/responses/401/content/application~1problem+json/schema\",\"403\":\"/paths/~1v1~1runs~1{run}~1cancel/post/responses/403/content/application~1problem+json/schema\",\"404\":\"/paths/~1v1~1runs~1{run}~1cancel/post/responses/404/content/application~1problem+json/schema\",\"405\":\"/paths/~1v1~1runs~1{run}~1cancel/post/responses/405/content/application~1problem+json/schema\",\"409\":\"/paths/~1v1~1runs~1{run}~1cancel/post/responses/409/content/application~1problem+json/schema\",\"413\":\"/paths/~1v1~1runs~1{run}~1cancel/post/responses/413/content/application~1problem+json/schema\",\"415\":\"/paths/~1v1~1runs~1{run}~1cancel/post/responses/415/content/application~1problem+json/schema\",\"500\":\"/paths/~1v1~1runs~1{run}~1cancel/post/responses/500/content/application~1problem+json/schema\",\"503\":\"/paths/~1v1~1runs~1{run}~1cancel/post/responses/503/content/application~1problem+json/schema\"}}")], - ["checkNow", JSON.parse("{\"method\":\"POST\",\"path\":\"/v1/runs/{run}/check\",\"responses\":{\"200\":[{\"mediaType\":\"application/json\",\"mode\":\"json\",\"rule\":\"/paths/~1v1~1runs~1{run}~1check/post/responses/200/content/application~1json/schema\"}]},\"keyed\":false,\"mutating\":true,\"requestMediaTypes\":[\"application/json\"],\"requestMediaType\":\"application/json\",\"problems\":{\"400\":\"/paths/~1v1~1runs~1{run}~1check/post/responses/400/content/application~1problem+json/schema\",\"401\":\"/paths/~1v1~1runs~1{run}~1check/post/responses/401/content/application~1problem+json/schema\",\"403\":\"/paths/~1v1~1runs~1{run}~1check/post/responses/403/content/application~1problem+json/schema\",\"404\":\"/paths/~1v1~1runs~1{run}~1check/post/responses/404/content/application~1problem+json/schema\",\"405\":\"/paths/~1v1~1runs~1{run}~1check/post/responses/405/content/application~1problem+json/schema\",\"409\":\"/paths/~1v1~1runs~1{run}~1check/post/responses/409/content/application~1problem+json/schema\",\"413\":\"/paths/~1v1~1runs~1{run}~1check/post/responses/413/content/application~1problem+json/schema\",\"415\":\"/paths/~1v1~1runs~1{run}~1check/post/responses/415/content/application~1problem+json/schema\",\"500\":\"/paths/~1v1~1runs~1{run}~1check/post/responses/500/content/application~1problem+json/schema\",\"503\":\"/paths/~1v1~1runs~1{run}~1check/post/responses/503/content/application~1problem+json/schema\"}}")], - ["inspectRun", JSON.parse("{\"method\":\"GET\",\"path\":\"/v1/runs/{run}/inspect\",\"responses\":{\"200\":[{\"mediaType\":\"application/json\",\"mode\":\"json\",\"rule\":\"/paths/~1v1~1runs~1{run}~1inspect/get/responses/200/content/application~1json/schema\"}]},\"keyed\":false,\"mutating\":false,\"problems\":{\"400\":\"/paths/~1v1~1runs~1{run}~1inspect/get/responses/400/content/application~1problem+json/schema\",\"401\":\"/paths/~1v1~1runs~1{run}~1inspect/get/responses/401/content/application~1problem+json/schema\",\"403\":\"/paths/~1v1~1runs~1{run}~1inspect/get/responses/403/content/application~1problem+json/schema\",\"404\":\"/paths/~1v1~1runs~1{run}~1inspect/get/responses/404/content/application~1problem+json/schema\",\"405\":\"/paths/~1v1~1runs~1{run}~1inspect/get/responses/405/content/application~1problem+json/schema\",\"409\":\"/paths/~1v1~1runs~1{run}~1inspect/get/responses/409/content/application~1problem+json/schema\",\"500\":\"/paths/~1v1~1runs~1{run}~1inspect/get/responses/500/content/application~1problem+json/schema\",\"503\":\"/paths/~1v1~1runs~1{run}~1inspect/get/responses/503/content/application~1problem+json/schema\"}}")], - ["reconcileRun", JSON.parse("{\"method\":\"POST\",\"path\":\"/v1/runs/{run}/reconcile\",\"responses\":{\"200\":[{\"mediaType\":\"application/json\",\"mode\":\"json\",\"rule\":\"/paths/~1v1~1runs~1{run}~1reconcile/post/responses/200/content/application~1json/schema\"}]},\"keyed\":false,\"mutating\":true,\"requestMediaTypes\":[\"application/json\"],\"requestMediaType\":\"application/json\",\"problems\":{\"400\":\"/paths/~1v1~1runs~1{run}~1reconcile/post/responses/400/content/application~1problem+json/schema\",\"401\":\"/paths/~1v1~1runs~1{run}~1reconcile/post/responses/401/content/application~1problem+json/schema\",\"403\":\"/paths/~1v1~1runs~1{run}~1reconcile/post/responses/403/content/application~1problem+json/schema\",\"404\":\"/paths/~1v1~1runs~1{run}~1reconcile/post/responses/404/content/application~1problem+json/schema\",\"405\":\"/paths/~1v1~1runs~1{run}~1reconcile/post/responses/405/content/application~1problem+json/schema\",\"409\":\"/paths/~1v1~1runs~1{run}~1reconcile/post/responses/409/content/application~1problem+json/schema\",\"413\":\"/paths/~1v1~1runs~1{run}~1reconcile/post/responses/413/content/application~1problem+json/schema\",\"415\":\"/paths/~1v1~1runs~1{run}~1reconcile/post/responses/415/content/application~1problem+json/schema\",\"500\":\"/paths/~1v1~1runs~1{run}~1reconcile/post/responses/500/content/application~1problem+json/schema\",\"503\":\"/paths/~1v1~1runs~1{run}~1reconcile/post/responses/503/content/application~1problem+json/schema\"}}")], - ["retrySame", JSON.parse("{\"method\":\"POST\",\"path\":\"/v1/runs/{run}/retry-same\",\"responses\":{\"200\":[{\"mediaType\":\"application/json\",\"mode\":\"json\",\"rule\":\"/paths/~1v1~1runs~1{run}~1retry-same/post/responses/200/content/application~1json/schema\"}]},\"keyed\":false,\"mutating\":true,\"requestMediaTypes\":[\"application/json\"],\"requestMediaType\":\"application/json\",\"problems\":{\"400\":\"/paths/~1v1~1runs~1{run}~1retry-same/post/responses/400/content/application~1problem+json/schema\",\"401\":\"/paths/~1v1~1runs~1{run}~1retry-same/post/responses/401/content/application~1problem+json/schema\",\"403\":\"/paths/~1v1~1runs~1{run}~1retry-same/post/responses/403/content/application~1problem+json/schema\",\"404\":\"/paths/~1v1~1runs~1{run}~1retry-same/post/responses/404/content/application~1problem+json/schema\",\"405\":\"/paths/~1v1~1runs~1{run}~1retry-same/post/responses/405/content/application~1problem+json/schema\",\"409\":\"/paths/~1v1~1runs~1{run}~1retry-same/post/responses/409/content/application~1problem+json/schema\",\"413\":\"/paths/~1v1~1runs~1{run}~1retry-same/post/responses/413/content/application~1problem+json/schema\",\"415\":\"/paths/~1v1~1runs~1{run}~1retry-same/post/responses/415/content/application~1problem+json/schema\",\"500\":\"/paths/~1v1~1runs~1{run}~1retry-same/post/responses/500/content/application~1problem+json/schema\",\"503\":\"/paths/~1v1~1runs~1{run}~1retry-same/post/responses/503/content/application~1problem+json/schema\"}}")], - ["workflowContract", JSON.parse("{\"method\":\"GET\",\"path\":\"/v1/workflows/{workflow}\",\"responses\":{\"200\":[{\"mediaType\":\"application/json\",\"mode\":\"json\",\"rule\":\"/paths/~1v1~1workflows~1{workflow}/get/responses/200/content/application~1json/schema\"}]},\"keyed\":false,\"mutating\":false,\"problems\":{\"401\":\"/paths/~1v1~1workflows~1{workflow}/get/responses/401/content/application~1problem+json/schema\",\"403\":\"/paths/~1v1~1workflows~1{workflow}/get/responses/403/content/application~1problem+json/schema\",\"404\":\"/paths/~1v1~1workflows~1{workflow}/get/responses/404/content/application~1problem+json/schema\",\"405\":\"/paths/~1v1~1workflows~1{workflow}/get/responses/405/content/application~1problem+json/schema\",\"409\":\"/paths/~1v1~1workflows~1{workflow}/get/responses/409/content/application~1problem+json/schema\",\"500\":\"/paths/~1v1~1workflows~1{workflow}/get/responses/500/content/application~1problem+json/schema\",\"503\":\"/paths/~1v1~1workflows~1{workflow}/get/responses/503/content/application~1problem+json/schema\"}}")], + ["runStatus", JSON.parse("{\"method\":\"GET\",\"path\":\"/v1/runs/{runId}\",\"responses\":{\"200\":[{\"mediaType\":\"application/json\",\"mode\":\"json\",\"rule\":\"/paths/~1v1~1runs~1{runId}/get/responses/200/content/application~1json/schema\"}]},\"keyed\":false,\"mutating\":false,\"problems\":{\"400\":\"/paths/~1v1~1runs~1{runId}/get/responses/400/content/application~1problem+json/schema\",\"401\":\"/paths/~1v1~1runs~1{runId}/get/responses/401/content/application~1problem+json/schema\",\"403\":\"/paths/~1v1~1runs~1{runId}/get/responses/403/content/application~1problem+json/schema\",\"404\":\"/paths/~1v1~1runs~1{runId}/get/responses/404/content/application~1problem+json/schema\",\"405\":\"/paths/~1v1~1runs~1{runId}/get/responses/405/content/application~1problem+json/schema\",\"500\":\"/paths/~1v1~1runs~1{runId}/get/responses/500/content/application~1problem+json/schema\",\"503\":\"/paths/~1v1~1runs~1{runId}/get/responses/503/content/application~1problem+json/schema\"}}")], + ["cancelRun", JSON.parse("{\"method\":\"POST\",\"path\":\"/v1/runs/{runId}/cancel\",\"responses\":{\"200\":[{\"mediaType\":\"application/json\",\"mode\":\"json\",\"rule\":\"/paths/~1v1~1runs~1{runId}~1cancel/post/responses/200/content/application~1json/schema\"}]},\"keyed\":false,\"mutating\":true,\"requestMediaTypes\":[\"application/json\"],\"requestMediaType\":\"application/json\",\"problems\":{\"400\":\"/paths/~1v1~1runs~1{runId}~1cancel/post/responses/400/content/application~1problem+json/schema\",\"401\":\"/paths/~1v1~1runs~1{runId}~1cancel/post/responses/401/content/application~1problem+json/schema\",\"403\":\"/paths/~1v1~1runs~1{runId}~1cancel/post/responses/403/content/application~1problem+json/schema\",\"404\":\"/paths/~1v1~1runs~1{runId}~1cancel/post/responses/404/content/application~1problem+json/schema\",\"405\":\"/paths/~1v1~1runs~1{runId}~1cancel/post/responses/405/content/application~1problem+json/schema\",\"409\":\"/paths/~1v1~1runs~1{runId}~1cancel/post/responses/409/content/application~1problem+json/schema\",\"413\":\"/paths/~1v1~1runs~1{runId}~1cancel/post/responses/413/content/application~1problem+json/schema\",\"415\":\"/paths/~1v1~1runs~1{runId}~1cancel/post/responses/415/content/application~1problem+json/schema\",\"500\":\"/paths/~1v1~1runs~1{runId}~1cancel/post/responses/500/content/application~1problem+json/schema\",\"503\":\"/paths/~1v1~1runs~1{runId}~1cancel/post/responses/503/content/application~1problem+json/schema\"}}")], + ["checkNow", JSON.parse("{\"method\":\"POST\",\"path\":\"/v1/runs/{runId}/check\",\"responses\":{\"200\":[{\"mediaType\":\"application/json\",\"mode\":\"json\",\"rule\":\"/paths/~1v1~1runs~1{runId}~1check/post/responses/200/content/application~1json/schema\"}]},\"keyed\":false,\"mutating\":true,\"requestMediaTypes\":[\"application/json\"],\"requestMediaType\":\"application/json\",\"problems\":{\"400\":\"/paths/~1v1~1runs~1{runId}~1check/post/responses/400/content/application~1problem+json/schema\",\"401\":\"/paths/~1v1~1runs~1{runId}~1check/post/responses/401/content/application~1problem+json/schema\",\"403\":\"/paths/~1v1~1runs~1{runId}~1check/post/responses/403/content/application~1problem+json/schema\",\"404\":\"/paths/~1v1~1runs~1{runId}~1check/post/responses/404/content/application~1problem+json/schema\",\"405\":\"/paths/~1v1~1runs~1{runId}~1check/post/responses/405/content/application~1problem+json/schema\",\"409\":\"/paths/~1v1~1runs~1{runId}~1check/post/responses/409/content/application~1problem+json/schema\",\"413\":\"/paths/~1v1~1runs~1{runId}~1check/post/responses/413/content/application~1problem+json/schema\",\"415\":\"/paths/~1v1~1runs~1{runId}~1check/post/responses/415/content/application~1problem+json/schema\",\"500\":\"/paths/~1v1~1runs~1{runId}~1check/post/responses/500/content/application~1problem+json/schema\",\"503\":\"/paths/~1v1~1runs~1{runId}~1check/post/responses/503/content/application~1problem+json/schema\"}}")], + ["inspectRun", JSON.parse("{\"method\":\"GET\",\"path\":\"/v1/runs/{runId}/inspect\",\"responses\":{\"200\":[{\"mediaType\":\"application/json\",\"mode\":\"json\",\"rule\":\"/paths/~1v1~1runs~1{runId}~1inspect/get/responses/200/content/application~1json/schema\"}]},\"keyed\":false,\"mutating\":false,\"problems\":{\"400\":\"/paths/~1v1~1runs~1{runId}~1inspect/get/responses/400/content/application~1problem+json/schema\",\"401\":\"/paths/~1v1~1runs~1{runId}~1inspect/get/responses/401/content/application~1problem+json/schema\",\"403\":\"/paths/~1v1~1runs~1{runId}~1inspect/get/responses/403/content/application~1problem+json/schema\",\"404\":\"/paths/~1v1~1runs~1{runId}~1inspect/get/responses/404/content/application~1problem+json/schema\",\"405\":\"/paths/~1v1~1runs~1{runId}~1inspect/get/responses/405/content/application~1problem+json/schema\",\"409\":\"/paths/~1v1~1runs~1{runId}~1inspect/get/responses/409/content/application~1problem+json/schema\",\"500\":\"/paths/~1v1~1runs~1{runId}~1inspect/get/responses/500/content/application~1problem+json/schema\",\"503\":\"/paths/~1v1~1runs~1{runId}~1inspect/get/responses/503/content/application~1problem+json/schema\"}}")], + ["reconcileRun", JSON.parse("{\"method\":\"POST\",\"path\":\"/v1/runs/{runId}/reconcile\",\"responses\":{\"200\":[{\"mediaType\":\"application/json\",\"mode\":\"json\",\"rule\":\"/paths/~1v1~1runs~1{runId}~1reconcile/post/responses/200/content/application~1json/schema\"}]},\"keyed\":false,\"mutating\":true,\"requestMediaTypes\":[\"application/json\"],\"requestMediaType\":\"application/json\",\"problems\":{\"400\":\"/paths/~1v1~1runs~1{runId}~1reconcile/post/responses/400/content/application~1problem+json/schema\",\"401\":\"/paths/~1v1~1runs~1{runId}~1reconcile/post/responses/401/content/application~1problem+json/schema\",\"403\":\"/paths/~1v1~1runs~1{runId}~1reconcile/post/responses/403/content/application~1problem+json/schema\",\"404\":\"/paths/~1v1~1runs~1{runId}~1reconcile/post/responses/404/content/application~1problem+json/schema\",\"405\":\"/paths/~1v1~1runs~1{runId}~1reconcile/post/responses/405/content/application~1problem+json/schema\",\"409\":\"/paths/~1v1~1runs~1{runId}~1reconcile/post/responses/409/content/application~1problem+json/schema\",\"413\":\"/paths/~1v1~1runs~1{runId}~1reconcile/post/responses/413/content/application~1problem+json/schema\",\"415\":\"/paths/~1v1~1runs~1{runId}~1reconcile/post/responses/415/content/application~1problem+json/schema\",\"500\":\"/paths/~1v1~1runs~1{runId}~1reconcile/post/responses/500/content/application~1problem+json/schema\",\"503\":\"/paths/~1v1~1runs~1{runId}~1reconcile/post/responses/503/content/application~1problem+json/schema\"}}")], + ["retrySame", JSON.parse("{\"method\":\"POST\",\"path\":\"/v1/runs/{runId}/retry-same\",\"responses\":{\"200\":[{\"mediaType\":\"application/json\",\"mode\":\"json\",\"rule\":\"/paths/~1v1~1runs~1{runId}~1retry-same/post/responses/200/content/application~1json/schema\"}]},\"keyed\":false,\"mutating\":true,\"requestMediaTypes\":[\"application/json\"],\"requestMediaType\":\"application/json\",\"problems\":{\"400\":\"/paths/~1v1~1runs~1{runId}~1retry-same/post/responses/400/content/application~1problem+json/schema\",\"401\":\"/paths/~1v1~1runs~1{runId}~1retry-same/post/responses/401/content/application~1problem+json/schema\",\"403\":\"/paths/~1v1~1runs~1{runId}~1retry-same/post/responses/403/content/application~1problem+json/schema\",\"404\":\"/paths/~1v1~1runs~1{runId}~1retry-same/post/responses/404/content/application~1problem+json/schema\",\"405\":\"/paths/~1v1~1runs~1{runId}~1retry-same/post/responses/405/content/application~1problem+json/schema\",\"409\":\"/paths/~1v1~1runs~1{runId}~1retry-same/post/responses/409/content/application~1problem+json/schema\",\"413\":\"/paths/~1v1~1runs~1{runId}~1retry-same/post/responses/413/content/application~1problem+json/schema\",\"415\":\"/paths/~1v1~1runs~1{runId}~1retry-same/post/responses/415/content/application~1problem+json/schema\",\"500\":\"/paths/~1v1~1runs~1{runId}~1retry-same/post/responses/500/content/application~1problem+json/schema\",\"503\":\"/paths/~1v1~1runs~1{runId}~1retry-same/post/responses/503/content/application~1problem+json/schema\"}}")], + ["workflowContract", JSON.parse("{\"method\":\"GET\",\"path\":\"/v1/workflows/{workflowId}\",\"responses\":{\"200\":[{\"mediaType\":\"application/json\",\"mode\":\"json\",\"rule\":\"/paths/~1v1~1workflows~1{workflowId}/get/responses/200/content/application~1json/schema\"}]},\"keyed\":false,\"mutating\":false,\"problems\":{\"401\":\"/paths/~1v1~1workflows~1{workflowId}/get/responses/401/content/application~1problem+json/schema\",\"403\":\"/paths/~1v1~1workflows~1{workflowId}/get/responses/403/content/application~1problem+json/schema\",\"404\":\"/paths/~1v1~1workflows~1{workflowId}/get/responses/404/content/application~1problem+json/schema\",\"405\":\"/paths/~1v1~1workflows~1{workflowId}/get/responses/405/content/application~1problem+json/schema\",\"409\":\"/paths/~1v1~1workflows~1{workflowId}/get/responses/409/content/application~1problem+json/schema\",\"500\":\"/paths/~1v1~1workflows~1{workflowId}/get/responses/500/content/application~1problem+json/schema\",\"503\":\"/paths/~1v1~1workflows~1{workflowId}/get/responses/503/content/application~1problem+json/schema\"}}")], ]) for (const [id, definition] of Object.entries(definitions)) { const responses: Operation["responses"] = {} diff --git a/crates/registry-cli-docs/catalog.json b/crates/registry-cli-docs/catalog.json index 1db71b3d5f..27384f14fa 100644 --- a/crates/registry-cli-docs/catalog.json +++ b/crates/registry-cli-docs/catalog.json @@ -13563,7 +13563,7 @@ { "name": "check", "invocation": "coordinatorctl check", - "about": "Validate the workflow, functions and root YAML companions offline", + "about": "Validate the workflow, Transforms and root YAML companions offline", "long_about": null, "usage": "coordinatorctl check [OPTIONS]", "arguments": [], @@ -13669,7 +13669,7 @@ { "name": "explain", "invocation": "coordinatorctl explain", - "about": "Explain a checked graph, mappings and execution bounds offline, or the helpers Functions may call", + "about": "Explain a checked graph, mappings and execution bounds offline, or the helpers Transforms may call", "long_about": null, "usage": "coordinatorctl explain [OPTIONS] --project \n coordinatorctl explain ", "arguments": [], @@ -13728,11 +13728,11 @@ "constraints": [], "subcommands": [ { - "name": "functions", - "invocation": "coordinatorctl explain functions", - "about": "List the helpers a pure Function may call, with the interpreter ABI and limits", + "name": "transforms", + "invocation": "coordinatorctl explain transforms", + "about": "List the helpers a pure Transform may call, with the interpreter ABI and limits", "long_about": null, - "usage": "coordinatorctl explain functions [OPTIONS]", + "usage": "coordinatorctl explain transforms [OPTIONS]", "arguments": [], "options": [ { @@ -19399,11 +19399,11 @@ "invocation": "evidencectl check", "about": "Check a normalized project and, when selected, deployment closure, or one tooling file, offline", "long_about": null, - "usage": "evidencectl check [OPTIONS] >", + "usage": "evidencectl check [OPTIONS] |--store-provision-config >", "arguments": [ { "display": "[PROJECT]", - "description": "Editable Evidence project directory. Required unless --file is given", + "description": "Editable Evidence project directory. Required unless --file or --store-provision-config is given", "always_required": false, "repeatable": false, "default_values": [], @@ -19430,6 +19430,24 @@ "possible_values": [], "environment": null }, + { + "display": "--store-provision-config ", + "description": "Check a store provisioning file offline without resolving secrets", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--environment", + "description": "Resolve text substitutions in the provisioning file from the environment", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, { "display": "--target ", "description": "Explicit deployment target whose governance and runtime structure are checked", @@ -19488,7 +19506,15 @@ "when": null, "arguments": [ "[PROJECT]", - "--file " + "--file ", + "--store-provision-config " + ] + }, + { + "kind": "requires-all", + "when": "--environment", + "arguments": [ + "--store-provision-config " ] }, { @@ -19506,6 +19532,14 @@ "--production" ] }, + { + "kind": "mutually-exclusive", + "when": null, + "arguments": [ + "--file ", + "--store-provision-config " + ] + }, { "kind": "mutually-exclusive", "when": null, @@ -19521,6 +19555,30 @@ "--file ", "[PROJECT]" ] + }, + { + "kind": "mutually-exclusive", + "when": null, + "arguments": [ + "--production", + "--store-provision-config " + ] + }, + { + "kind": "mutually-exclusive", + "when": null, + "arguments": [ + "--store-provision-config ", + "--target " + ] + }, + { + "kind": "mutually-exclusive", + "when": null, + "arguments": [ + "--store-provision-config ", + "[PROJECT]" + ] } ], "subcommands": [] @@ -23647,6 +23705,112 @@ "constraints": [], "subcommands": [] }, + { + "name": "provision", + "invocation": "evidencectl provision", + "about": "Create split PostgreSQL roles and an empty database for a held Evidence store", + "long_about": null, + "usage": "evidencectl provision [OPTIONS] --runtime-config ", + "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 for Evidence store provisioning", + "always_required": true, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--format ", + "description": "Emit the selected command's report in this format. `junit` is accepted only by `test` and `fixtures run`", + "always_required": false, + "repeatable": false, + "default_values": [ + "human" + ], + "possible_values": [ + "human", + "json", + "junit" + ], + "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": "runtime", "invocation": "evidencectl runtime", @@ -27551,6 +27715,24 @@ "possible_values": [], "environment": null }, + { + "display": "--route-inventory-out ", + "description": "Write browser paths for the selected Base Registry Engine route from a verified loopback HTTPS assembly", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--checked-route ", + "description": "Select the Base Registry Engine module for the browser route inventory", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, { "display": "--standalone-out ", "description": "Write one complete Envoy JSON configuration using loopback listeners and upstreams", @@ -27578,6 +27760,24 @@ "possible_values": [], "environment": null }, + { + "display": "--tls-certificate ", + "description": "Absolute filename of the certificate chain for dedicated loopback HTTPS", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--tls-key ", + "description": "Absolute filename of the Envoy TLS private key", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, { "display": "--posture ", "description": "Declared posture: development or production. Unset means production.", @@ -27608,6 +27808,22 @@ "--standalone-out " ] }, + { + "kind": "requires-all", + "when": "--route-inventory-out ", + "arguments": [ + "--verify-assembled ", + "--checked-route " + ] + }, + { + "kind": "requires-all", + "when": "--checked-route ", + "arguments": [ + "--verify-assembled ", + "--route-inventory-out " + ] + }, { "kind": "requires-all", "when": "--standalone-out ", @@ -27623,6 +27839,24 @@ "--standalone-out " ] }, + { + "kind": "requires-all", + "when": "--tls-certificate ", + "arguments": [ + "--listen
", + "--standalone-out ", + "--tls-key " + ] + }, + { + "kind": "requires-all", + "when": "--tls-key ", + "arguments": [ + "--standalone-out ", + "--tls-certificate ", + "--listen
" + ] + }, { "kind": "mutually-exclusive", "when": null, @@ -29838,14 +30072,14 @@ { "name": "check", "invocation": "rstack dev check", - "about": "Validate a development plan without starting services", + "about": "Validate a development plan or the structure of a saved owner report without starting services", "long_about": null, - "usage": "rstack dev check [OPTIONS] ", + "usage": "rstack dev check [OPTIONS] [PROJECT]", "arguments": [ { - "display": "", + "display": "[PROJECT]", "description": "Project directory containing dev.yaml and, when it declares audiences, service.yaml", - "always_required": true, + "always_required": false, "repeatable": false, "default_values": [], "possible_values": [], @@ -29853,6 +30087,27 @@ } ], "options": [ + { + "display": "--owner-report ", + "description": "Saved JSON report to check structurally", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--owner-report-format ", + "description": "Exact saved document format", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [ + "casework-report", + "breg-identity-facts-report" + ], + "environment": null + }, { "display": "--deny-warnings", "description": "Refuse an unaccepted warning. Development posture listings do not count", @@ -29886,7 +30141,38 @@ "environment": null } ], - "constraints": [], + "constraints": [ + { + "kind": "requires-all", + "when": "--owner-report ", + "arguments": [ + "--owner-report-format " + ] + }, + { + "kind": "requires-all", + "when": "--owner-report-format ", + "arguments": [ + "--owner-report " + ] + }, + { + "kind": "mutually-exclusive", + "when": null, + "arguments": [ + "--owner-report ", + "[PROJECT]" + ] + }, + { + "kind": "mutually-exclusive", + "when": null, + "arguments": [ + "--owner-report-format ", + "[PROJECT]" + ] + } + ], "subcommands": [] }, { @@ -29918,7 +30204,7 @@ }, { "display": "--database-url ", - "description": "PostgreSQL administrator URL (verified TLS, or loopback with sslmode=disable). Defaults to RSTACK_DEV_DATABASE_URL; without either, the run starts its own PostgreSQL server in Docker", + "description": "PostgreSQL administrator URL. Defaults to verified TLS. For development, select loopback plaintext with sslmode=disable or private network plaintext with transport=private-network-plaintext. Defaults to RSTACK_DEV_DATABASE_URL; without either, the run starts its own PostgreSQL server in Docker", "always_required": false, "repeatable": false, "default_values": [], @@ -30161,7 +30447,7 @@ }, { "display": "--database-url ", - "description": "PostgreSQL administrator URL for --recover (verified TLS, or loopback with sslmode=disable). Defaults to RSTACK_DEV_DATABASE_URL; a run that started its own server needs none", + "description": "The same PostgreSQL administrator URL used at start, including its transport choice. Defaults to RSTACK_DEV_DATABASE_URL; a run that started its own server needs none", "always_required": false, "repeatable": false, "default_values": [], diff --git a/products/platform/generated/dev/dev.v1alpha1.schema.json b/products/platform/generated/dev/dev.v1alpha1.schema.json index e2de0691ec..47bb499528 100644 --- a/products/platform/generated/dev/dev.v1alpha1.schema.json +++ b/products/platform/generated/dev/dev.v1alpha1.schema.json @@ -390,6 +390,18 @@ "pattern": "^[^\\u0000-\\u001F\\u007F-\\u009F]+$", "type": "string" }, + "ExternalScheduling": { + "additionalProperties": false, + "properties": { + "taskGrant": { + "$ref": "#/$defs/TaskGrant" + } + }, + "required": [ + "taskGrant" + ], + "type": "object" + }, "Hook": { "additionalProperties": false, "properties": { @@ -768,6 +780,10 @@ "$ref": "#/$defs/Url", "description": "JWKS endpoint for an externally managed issuer. When set, the runner\ndelegates authentication to that issuer and does not mint person tokens." }, + "externalScheduling": { + "$ref": "#/$defs/ExternalScheduling", + "description": "One external task grant and its live status provider for a Scheduling fixture." + }, "issuer": { "anyOf": [ { From 31fa352271b0f3988fc8284b33166a0fe6adb5aa Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 18:24:17 +0000 Subject: [PATCH 081/183] docs(previews): show when a service needs a flow Signed-off-by: Jeremi Joslin --- .../business-registration/README.md | 10 ++++++++-- .../service-previews/medical-renewal/README.md | 13 ++++++++++--- 2 files changed, 18 insertions(+), 5 deletions(-) diff --git a/products/platform/examples/service-previews/business-registration/README.md b/products/platform/examples/service-previews/business-registration/README.md index 2357392424..b57d9a5d99 100644 --- a/products/platform/examples/service-previews/business-registration/README.md +++ b/products/platform/examples/service-previews/business-registration/README.md @@ -5,6 +5,12 @@ printed URL, enter a synthetic business name and registration number such as `BR-BROWSER-2026-001` and select **Register business**. The confirmation reads the new business Record from BReg. +The form check and registration fit in one request. A service function +prepares the input and asks BReg to run the registration Action under the +registrar's authority. The function holds no authority of its own. If your +registration procedure must wait for an officer's decision or has steps that +someone needs to review, put those steps in a Coordinator flow. + - [service.yaml](service.yaml) names the register, frontend and function. - [The BReg project](project/registry.yaml) defines the Record, unique registration number, Action and registrar access profile. @@ -12,7 +18,7 @@ the new business Record from BReg. the same Action. - [dev.yaml](dev.yaml) selects the synthetic registrar and permits business reads and the registration function. -- [The registration function](functions/register-business/index.ts) receives - a typed BReg client for the request and invokes the Action as the registrar. +- [The registration service function](functions/register-business/index.ts) + receives a typed BReg client for the request. - [The page code](web/src/page.ts) calls the function and reads the created Record with the generated client. diff --git a/products/platform/examples/service-previews/medical-renewal/README.md b/products/platform/examples/service-previews/medical-renewal/README.md index 8cef0bc573..61531f06ad 100644 --- a/products/platform/examples/service-previews/medical-renewal/README.md +++ b/products/platform/examples/service-previews/medical-renewal/README.md @@ -5,14 +5,21 @@ printed URL, review the synthetic holder's medical licence and select **Renew licence**. The confirmation reads the updated expiry of 30 June 2028 from BReg. +The holder reviews the licence before submitting the form. A service function +then prepares the renewal and asks BReg to run the Action under the holder's +authority. The renewal fits in one request. If your renewal procedure must +wait for someone else to decide or has steps that someone needs to review, +put those steps in a Coordinator flow. + - [service.yaml](service.yaml) names the register, frontend and function. - [The BReg project](project/registry.yaml) defines the records, Action and access profiles. [The startup journey](dev-journeys.yaml) issues the licence through BReg before the browser opens. - [dev.yaml](dev.yaml) selects the synthetic holder and permits licence reads, the Action's target-conditions check and the renewal function. -- [The renewal function](functions/renew/index.ts) receives a typed BReg client - for the request. Its [handler](functions/renew/renew.ts) checks the request - and carries the reviewed revision and the same attempt key through a retry. +- [The renewal service function](functions/renew/index.ts) receives a typed BReg + client for the request. Its [handler](functions/renew/renew.ts) checks the + request and carries the reviewed revision and the same attempt key through a + retry. - [The page code](web/src/page.ts) presents the review and confirmation and keeps the attempt key for a retry. From 39a22a0f40e7d96ce970fa558b1869c5df3d9748 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 20:03:08 +0000 Subject: [PATCH 082/183] fix(preview): generate and admit bounded BReg revision routes Signed-off-by: Jeremi Joslin --- clients/typescript/generate.ts | 20 ++++--- clients/typescript/preview/build.mjs | 7 +-- clients/typescript/preview/gateway.mjs | 18 +++++-- .../typescript/preview/tests/preview.test.mjs | 50 +++++++++++++++++- clients/typescript/tests/generator.test.ts | 52 +++++++++++++++++++ crates/registry-rstack-dev/src/plan.rs | 6 +++ crates/registry-rstack-dev/src/preview.rs | 38 ++++++++------ 7 files changed, 157 insertions(+), 34 deletions(-) diff --git a/clients/typescript/generate.ts b/clients/typescript/generate.ts index 0ad6eba692..d976d9e134 100644 --- a/clients/typescript/generate.ts +++ b/clients/typescript/generate.ts @@ -154,20 +154,25 @@ const record = '[a-z0-9][a-z0-9-]*' const bregRoutes = [ 'records/' + record + '(?::(?:lookup|batch|snapshot|current|as-of)|/ingestion-runs' + '(?:/\\{run_id\\}(?:/(?:cancel|chunks(?:/\\{chunk_index\\}/receipt)?))?)?|/\\{record_id\\}' + - '(?:/(?:' + record + '|attachments/' + record + '))?)?', + '(?:/(?:' + record + '|attachments/' + record + '|revisions/\\{revision\\}))?)?', 'actions/' + record + '(?:/(?:proposals|availability|target-conditions))?', 'proposals(?:/review-context|/\\{proposal_id\\}(?:/(?:apply|cancel|edit|rebase|retry|revise|review-context|' + - 'review-status|task-grant-context|submit|submissions/\\{submission_version\\}|attachments/' + record + '))?)?', + 'review-status|task-grant-context|submit|submissions/\\{submission_version\\}|attachments/' + record + + '|additions/(?:' + record + '|\\{addition_id\\})|asks/\\{ask_id\\}/answer))?)?', 'statistics/' + record + '(?::(?:live|exact)|/releases(?::series|/\\{period\\}' + - '(?:/versions(?::dry-run|/\\{version\\}(?:/withdrawal)?))?)?)', + '(?:/versions(?::dry-run|/\\{version\\}(?:/withdrawal)?)?)?)?)', + 'external-views/' + record + '/' + record + '/records(?:/\\{root\\}(?:/refresh)?)?', + 'external-refresh-plans/\\{plan\\}/source-changes', 'review-completions', ] const bregRoute = new RegExp('^/v1/(?:' + bregRoutes.join('|') + ')$') -// A record patch can target fields of different types, so BReg leaves its value open. +// BReg leaves patch values open because they can target fields of different types. const bregPatchValue = new RegExp( - '^/paths/~1v1~1records~1' + record + '~1\\{record_id\\}/patch/requestBody/content/' + - 'application~1json-patch\\+json/schema/items/properties/value$', + '^/paths/~1v1~1records~1' + record + + '(?:~1\\{record_id\\}/patch/requestBody/content/application~1json-patch\\+json/schema/items' + + '|:batch/post/requestBody/content/application~1json/schema/properties/items/items/oneOf/1/properties/patch/items)' + + '/properties/value$', 'u', ) @@ -756,7 +761,8 @@ export function generate(source: string, settings: Settings = {}): string { mode = 'json' validationRoots.add(schemaAt) } - else if (media === 'application/dc+sd-jwt' || media.endsWith('+jwt')) mode = 'text' + else if (media === 'application/dc+sd-jwt' || media.endsWith('+jwt') + || (breg && method === 'get' && path.startsWith('/v1/statistics/') && media === 'text/csv')) mode = 'text' else if (media === '*/*' || media === 'application/octet-stream' || media === 'application/pdf') mode = 'binary' else mode = fail(schemaAt, 'unsupported success media') responseMedia.add(media) diff --git a/clients/typescript/preview/build.mjs b/clients/typescript/preview/build.mjs index da94701b36..e90f877dfd 100644 --- a/clients/typescript/preview/build.mjs +++ b/clients/typescript/preview/build.mjs @@ -53,10 +53,11 @@ async function runGenerator(plan, staged) { '--output', join(staged, 'generated', 'service.ts'), ], { cwd: staged, timeout: 90_000, maxBuffer: 1024 * 1024 }) } catch (error) { - if (/cannot start Proposals/u.test(String(error.stderr ?? ''))) { - throw new Error('The preview actor cannot start Proposals in this project. Select a preview actor whose BReg profile can start Proposals.') + const diagnostic = String(error.stderr ?? '').trim() + if (/cannot start Proposals/u.test(diagnostic)) { + throw new Error(diagnostic + '\nSelect a preview actor whose BReg profile can start Proposals.') } - throw new Error('Preview client generation failed. Check the native project and install matching BReg tools.') + throw new Error(diagnostic || 'Preview client generation failed. Check the native project and install matching BReg tools.') } } diff --git a/clients/typescript/preview/gateway.mjs b/clients/typescript/preview/gateway.mjs index 2ce51fac61..81cbecb9e8 100644 --- a/clients/typescript/preview/gateway.mjs +++ b/clients/typescript/preview/gateway.mjs @@ -10,6 +10,9 @@ const maxStaticSize = 32 * 1024 * 1024 const timeout = 15_000 const segment = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/u const uuid = /^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/iu +const revision = /^[1-9][0-9]{0,18}$/u +const maximumRevision = '9223372036854775807' +const recordParameter = part => part === '{recordId}' || part === '{record_id}' const contentTypes = new Map([ ['.css', 'text/css; charset=utf-8'], ['.html', 'text/html; charset=utf-8'], @@ -31,9 +34,10 @@ class RequestError extends Error { function compilePaths(paths = []) { if (!Array.isArray(paths)) throw new Error('Expected a list of preview routes per method.') return paths.map((path) => { - const parts = typeof path === 'string' && path.startsWith('/v1/') ? path.slice(1).split('/') : [] - if (parts.length < 2 || parts.filter(part => part === '{recordId}').length > 1 || !parts.every(part => segment.test(part) || part === '{recordId}')) { - throw new Error('Expected an exact /v1/ preview route with {recordId} for a Record ID.') + const parts = typeof path === 'string' && path.length <= 256 && path.startsWith('/v1/') ? path.slice(1).split('/') : [] + if (parts.length < 2 || parts.filter(recordParameter).length > 1 || parts.filter(part => part === '{revision}').length > 1 + || !parts.every(part => segment.test(part) || recordParameter(part) || part === '{revision}')) { + throw new Error('Expected an exact /v1/ preview route with distinct Record ID and revision parameters.') } return parts }) @@ -58,8 +62,12 @@ export function previewPolicy(preview) { allowsBreg(method, path) { const parts = path.slice(1).split('/') return routes.get(method)?.some(route => - route.length === parts.length && route.every((part, index) => - part === '{recordId}' ? uuid.test(parts[index]) : part === parts[index]), + route.length === parts.length && route.every((part, index) => { + const value = parts[index] + if (recordParameter(part)) return uuid.test(value) + if (part === '{revision}') return revision.test(value) && (value.length < maximumRevision.length || value <= maximumRevision) + return part === value + }), ) }, } diff --git a/clients/typescript/preview/tests/preview.test.mjs b/clients/typescript/preview/tests/preview.test.mjs index 097b9a796d..a7d28e215c 100644 --- a/clients/typescript/preview/tests/preview.test.mjs +++ b/clients/typescript/preview/tests/preview.test.mjs @@ -1,15 +1,61 @@ import { strict as assert } from 'node:assert' -import { mkdtemp, mkdir, rm, symlink, writeFile } from 'node:fs/promises' +import { mkdtemp, mkdir, realpath, rm, symlink, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' import { createServer, request } from 'node:http' import { test } from 'node:test' import { startFunctionHost } from '../host.mjs' -import { collectStaticFiles, startPreviewGateway } from '../gateway.mjs' +import { collectStaticFiles, previewPolicy, startPreviewGateway } from '../gateway.mjs' import { prepareRuntimeConfig } from '../config.mjs' import { buildPreview } from '../build.mjs' import { createHash } from 'node:crypto' +test('preview policy matches both Record revision parameters without expanding methods or routes', () => { + const recordId = '00000000-0000-0000-0000-000000000001' + const root = '/v1/records/applications/' + for (const id of ['{record_id}', '{recordId}']) { + const policy = previewPolicy({ page: '/', functions: [], breg: { get: [root + id + '/revisions/{revision}'] } }) + assert.equal(policy.allowsBreg('GET', root + recordId + '/revisions/2'), true) + assert.equal(policy.allowsBreg('GET', root + recordId + '/revisions/9223372036854775807'), true) + assert.equal(policy.allowsBreg('POST', root + recordId + '/revisions/2'), false) + for (const suffix of ['0', '-1', '2%2fother', '9223372036854775808', '2/another']) { + assert.equal(policy.allowsBreg('GET', root + recordId + '/revisions/' + suffix), false) + } + assert.equal(policy.allowsBreg('GET', root + 'not-a-uuid/revisions/2'), false) + } + for (const path of [root + '{anything}', root + '{recordId}/{record_id}', root + '{recordId}/revisions/{revision}/{revision}']) { + assert.throws(() => previewPolicy({ page: '/', functions: [], breg: { get: [path] } }), /preview route/u) + } +}) + +test('preview build forwards the generator diagnostic', async (t) => { + const root = await realpath(await mkdtemp(join(tmpdir(), 'registry-preview-diagnostic-'))) + t.after(() => rm(root, { recursive: true })) + const file = join(root, 'service.yaml') + const ui = join(root, 'web') + const entry = join(root, 'functions', 'renew', 'index.ts') + const generator = join(root, 'generator') + await mkdir(ui) + await mkdir(join(root, 'functions', 'renew'), { recursive: true }) + await writeFile(file, 'fixture declaration') + await writeFile(entry, 'export default () => {}') + const diagnostic = '/paths/~1v1~1records~1fixture/get: unsupported fixture schema' + await writeFile(generator, `#!/bin/sh\nprintf '%s\\n' '${diagnostic}' >&2\nexit 1\n`, { mode: 0o700 }) + const execPath = process.execPath + process.execPath = generator + try { + await assert.rejects(buildPreview({ + file, workspaceRoot: root, declarationDigest: createHash('sha256').update('fixture declaration').digest('hex'), + product: { id: 'licenses', member: 'licenses', project: root, profile: 'holder' }, + ui: { project: ui, output: join(ui, 'dist') }, + functions: { renew: entry }, + preview: { page: '/', breg: {}, functions: ['renew'] }, + }, join(root, 'artifact')), { message: diagnostic }) + } finally { + process.execPath = execPath + } +}) + test('prepare binds the run to the declaration, product, audience and loopback address', async (t) => { const root = await mkdtemp(join(tmpdir(), 'registry-preview-test-')) t.after(() => rm(root, { recursive: true })) diff --git a/clients/typescript/tests/generator.test.ts b/clients/typescript/tests/generator.test.ts index f0ad4982b7..3d8798023a 100644 --- a/clients/typescript/tests/generator.test.ts +++ b/clients/typescript/tests/generator.test.ts @@ -26,6 +26,58 @@ test('BReg refuses paths outside the route scheme', () => { const input = { ...document({ type: 'string' }), paths: { '/v1/foreign': {} } } assert.throws(() => generate(JSON.stringify(input), { breg: true }), /\/paths\/~1v1~1foreign/) }) +test('BReg generates a typed call for Record revision reads', () => { + const path = '/v1/records/applications/{record_id}/revisions/{revision}' + const input = { ...document({ type: 'string' }), paths: { [path]: { get: { + operationId: 'readApplicationRevision', + parameters: [ + { in: 'path', name: 'record_id', required: true, schema: { type: 'string', format: 'uuid' } }, + { in: 'path', name: 'revision', required: true, schema: { type: 'integer', minimum: 1 } }, + ], + responses: { 200: { description: 'ok', content: { 'application/json': { schema: { type: 'string' } } } } }, + } } } } + const output = generate(JSON.stringify(input), { breg: true }) + assert.match(output, /"readApplicationRevision": \{ input:.*"record_id": \(string\); "revision": \(number\)/u) + assert.ok(output.includes(path)) + const unsupported = { ...input, paths: { [path.replace('{revision}', '{other}')]: input.paths[path] } } + assert.throws(() => generate(JSON.stringify(unsupported), { breg: true }), /outside BReg route scheme/u) +}) +test('BReg accepts the route families emitted by the native fixture set', () => { + for (const path of [ + '/v1/statistics/entry-counts/releases/{period}/versions', + '/v1/external-refresh-plans/{plan}/source-changes', + '/v1/external-views/licence-holder-indexed/holder/records', + '/v1/external-views/licence-holder-indexed/holder/records/{root}', + '/v1/external-views/licence-holder-indexed/holder/records/{root}/refresh', + '/v1/proposals/{proposal_id}/additions/supporting', + '/v1/proposals/{proposal_id}/additions/{addition_id}', + '/v1/proposals/{proposal_id}/asks/{ask_id}/answer', + ]) assert.doesNotThrow(() => generate(JSON.stringify({ ...document({ type: 'string' }), paths: { [path]: {} } }), { breg: true }), path) +}) + +test('BReg generates a CSV alternative on statistical releases', () => { + const path = '/v1/statistics/entry-counts/releases/{period}' + const operation = { operationId: 'publishedRelease', parameters: [ + { in: 'path', name: 'period', required: true, schema: { type: 'string' } }, + ], responses: { 200: { description: 'ok', content: { 'text/csv': { schema: { type: 'string' } } } } } } + const input = { ...document({ type: 'string' }), paths: { [path]: { get: operation } } } + assert.match(generate(JSON.stringify(input), { breg: true }), /WireText<"text\/csv">/u) + const nonStatistic = { ...input, paths: { '/v1/records/entries': { get: { ...operation, parameters: [] } } } } + assert.throws(() => generate(JSON.stringify(nonStatistic), { breg: true }), /unsupported success media/u) +}) + +test('BReg generates only the native batch patch value as unconstrained JSON', () => { + const batchPatch = (field: string) => ({ type: 'object', properties: { items: { type: 'array', items: { oneOf: [ + { type: 'string', const: 'other' }, + { type: 'object', properties: { patch: { type: 'array', items: { type: 'object', properties: { [field]: true } } } } }, + ] } } } }) + const input = (field: string) => ({ ...document({ type: 'string' }), paths: { + '/v1/records/entries:batch': { post: { operationId: 'batchEntries', responses: success, + requestBody: { content: { 'application/json': { schema: batchPatch(field) } } } } }, + } }) + assert.ok(generate(JSON.stringify(input('value')), { breg: true }).includes('// Unconstrained JSON ')) + assert.throws(() => generate(JSON.stringify(input('extra')), { breg: true }), /outside the reviewed allowlist/u) +}) test('a generated module exports its Client over a Transport and no factory', () => { const output = generate(JSON.stringify({ ...document({ type: 'string' }), info: { title: 'licence-registry' } })) assert.match(output, /^export class Client \{$/mu) diff --git a/crates/registry-rstack-dev/src/plan.rs b/crates/registry-rstack-dev/src/plan.rs index b4f5d7c6c1..aa4e0bfbc8 100644 --- a/crates/registry-rstack-dev/src/plan.rs +++ b/crates/registry-rstack-dev/src/plan.rs @@ -3936,6 +3936,10 @@ mod preview_tests { "/v1/records/licences/{recordId}", true )); + for id in ["{recordId}", "{record_id}"] { + let path = format!("/v1/records/applications/{id}/revisions/{{revision}}"); + assert!(super::super::preview::valid_path(&path, true), "{path}"); + } assert!(super::super::preview::valid_path("/check.html", false)); for path in [ "//elsewhere", @@ -3945,6 +3949,8 @@ mod preview_tests { "/v1/records?accessProfile=admin", "/v1/records/{anything}", "/v1/records/{recordId}/{recordId}", + "/v1/records/{recordId}/{record_id}", + "/v1/records/{recordId}/revisions/{revision}/{revision}", "/v1/records/#fragment", ] { assert!(!super::super::preview::valid_path(path, true), "{path}"); diff --git a/crates/registry-rstack-dev/src/preview.rs b/crates/registry-rstack-dev/src/preview.rs index 7026d7895e..e910e7bf58 100644 --- a/crates/registry-rstack-dev/src/preview.rs +++ b/crates/registry-rstack-dev/src/preview.rs @@ -181,7 +181,7 @@ impl Preview { return plan::refuse( &format!("/preview/breg/{method}"), "Preview routes need bounded literal BReg paths.", - "Use /v1/ paths with at most one {recordId} path segment, without query strings.", + "Use /v1/ paths with distinct Record ID and revision segments ({recordId}, {record_id}, {revision}), without query strings.", ).map_err(Into::into); } } @@ -253,23 +253,27 @@ pub(super) fn valid_path(path: &str, parameter: bool) -> bool { let Some(rest) = path.strip_prefix('/') else { return false; }; - let mut segments = rest.split('/'); + let mut record_id = false; + let mut revision = false; path.len() <= 256 - && segments - .clone() - .filter(|segment| *segment == "{recordId}") - .count() - <= 1 - && segments.all(|part| { - (parameter && part == "{recordId}") - || (part.len() <= 128 - && part - .as_bytes() - .first() - .is_some_and(u8::is_ascii_alphanumeric) - && part.bytes().all(|byte| { - byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.') - })) + && rest.split('/').all(|part| { + if parameter { + match part { + "{recordId}" | "{record_id}" => { + return !std::mem::replace(&mut record_id, true) + } + "{revision}" => return !std::mem::replace(&mut revision, true), + _ => {} + } + } + part.len() <= 128 + && part + .as_bytes() + .first() + .is_some_and(u8::is_ascii_alphanumeric) + && part + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.')) }) } From 42d29bde18c700362af98b2a36125ad03504f89a Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 21:38:18 +0000 Subject: [PATCH 083/183] docs(messaging): lead the Compose guide with the explicit native secret mount Compose's native file secrets need mountPolicy: compose-native. The guide now shows that route and how check and startup report it, and keeps the hardened custodian directory as the alternative. Signed-off-by: Jeremi Joslin --- .../src/content/docs/operate/messaging.mdx | 48 ++++++++++++++++++- 1 file changed, 47 insertions(+), 1 deletion(-) diff --git a/docs/site/src/content/docs/operate/messaging.mdx b/docs/site/src/content/docs/operate/messaging.mdx index d552d9a266..e883c02eb0 100644 --- a/docs/site/src/content/docs/operate/messaging.mdx +++ b/docs/site/src/content/docs/operate/messaging.mdx @@ -216,7 +216,53 @@ breaks the join between records written before and after. ### Mount secret files with Docker Compose -Use the release image's default UID and GID `65532:65532` on a Linux Docker host. +Compose's native file secrets are the shortest route. Compose ignores the `uid`, `gid`, and +`mode` you declare for a file-backed secret, and on some hosts the container sees each file +owned by root at mode `0444`. The default secret rule refuses that shape. Accept it explicitly in +the runtime file: + +```yaml +secretProviders: + file: + root: /run/secrets + mountPolicy: compose-native +``` + +The setting admits only a regular file owned by root, with one hard link and mode exactly `0444`, +under the declared root. Every user in the container can read those files, so run Messaging alone +in its container under one runtime identity. Group or world write access, another owner, a +second link, and a path outside the root are still refused. A static JWKS or a CA bundle is a +public document and needs no setting. + +Compose mounts each secret at `/run/secrets/`. Declare each serving credential as a +Compose secret whose name matches its `secret:file/` reference: + +```yaml +services: + messaging: + read_only: true + secrets: + - smtp-password +secrets: + smtp-password: + file: ${MESSAGING_SMTP_PASSWORD_FILE:?set MESSAGING_SMTP_PASSWORD_FILE} +``` + +Declare `runtime-database-url`, `messaging-audit-key`, `smtp-username`, `sms-gateway-token`, and +`sms-gateway-callback-key` the same way. Keep the migration credential out of the serving service. + +`messagingctl check --production` prints +`Explicit production setting platform.posture.compose-native-secret-mount at /secretProviders/file/mountPolicy`, +and startup logs `explicit production setting in use` with the same code. Without the setting, +startup refuses the first secret file with `platform.secret-file.world-readable`. + +{/* Evidence: crates/registry-platform-config/src/blocks.rs, COMPOSE_NATIVE_SECRET_MOUNT; + crates/registry-platform-config/src/secrets.rs, judge and resolve_public_document; + crates/registry-platform-config/src/posture.rs, log_startup. */} + +#### Use a hardened secret directory + +Omit `mountPolicy` to keep the stricter rule. Use the release image's default UID and GID `65532:65532` on a Linux Docker host. Have the secret custodian create a dedicated directory owned by root, group `65532`, mode `0750`. Use regular files owned by root, group `65532`, mode `0440`, with exactly one hard link each. On the host, grant group `65532` only to the secret custodian. Restrict ACLs to the From 10f135a5dbcd767824ca11ed7a4cf58e0187e3e9 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 21:40:14 +0000 Subject: [PATCH 084/183] docs(breg): read the first tutorial's dev files from the scaffold The first BReg tutorial replaced the dev.yaml and dev-journeys.yaml that bregctl init writes, so a reader's files no longer matched the starter. The scaffold already runs as is: every tests/journeys.yaml step names its actor, and the single profile purpose stays valid under roles. Show both files as excerpts instead of replacing them. Signed-off-by: Jeremi Joslin --- .../src/content/docs/tutorials/first-breg.mdx | 34 ++++++++----------- 1 file changed, 14 insertions(+), 20 deletions(-) diff --git a/docs/site/src/content/docs/tutorials/first-breg.mdx b/docs/site/src/content/docs/tutorials/first-breg.mdx index b11b1ebdca..02b6617226 100644 --- a/docs/site/src/content/docs/tutorials/first-breg.mdx +++ b/docs/site/src/content/docs/tutorials/first-breg.mdx @@ -120,13 +120,11 @@ accessProfiles: `rstack dev` runs the project on your machine from a development plan. The plan lists the products to run and the synthetic people who call them, with the claims each person's test token carries. -`rstack breg init` wrote a starter `service.yaml`, `dev.yaml` and `dev-journeys.yaml`. Replace `dev.yaml` with this -plan, which gives the test caller `editor` the claim `zone-a` and `foreign-editor` the claim -`zone-b`: +`rstack breg init` already wrote the plan you need, so you do not change any file in this step. +Open `dev.yaml`. It gives the test caller `editor` the claim `zone-a` and `foreign-editor` the +claim `zone-b`: -```yaml title="dev.yaml" test-file -apiVersion: id.registrystack.org/formats/rstack/dev/v1alpha1 -kind: RStackDev +```yaml title="dev.yaml" test-excerpt="dev.yaml" issuer: https://identity.directory.example.test products: - {product: breg, project: ., audience: "urn:example:local-directory"} @@ -137,31 +135,27 @@ people: roles: [directory-editor] claims: breg: {jurisdiction: zone-a} + purposes: {breg: directory-administration} foreign-editor: subject: synthetic-foreign-editor client: directory-editor roles: [directory-editor] claims: breg: {jurisdiction: zone-b} -# Both people match the profile, so each journey step names its person. -schemaTestPeople: - directory-contact: - create-contact: editor - read-contact: editor - conceal-contact-outside-jurisdiction: foreign-editor - obtain-email-condition: editor - update-contact-email: editor - read-updated-contact: editor - start-registration: editor - submit-registration: editor + purposes: {breg: directory-administration} +# Both people match the editor profile, so each schema-test step names its person. journeyFile: dev-journeys.yaml ``` +Each person's `roles` entry refers to a role in `service.yaml`, which selects the +`directory-editor` access profile for them. Each step in `tests/journeys.yaml` names the person who +runs it with `actor`. + The plan's `journeyFile` names the HTTP requests that `rstack dev` sends once the registry is -running. Replace `dev-journeys.yaml` at the project root with a journey that adds one contact in -`zone-a` as `editor` and reads it back. +running. Open `dev-journeys.yaml` at the project root. Its journey adds one contact in `zone-a` as +`editor` and reads it back: -```yaml title="dev-journeys.yaml" test-file +```yaml title="dev-journeys.yaml" test-excerpt="dev-journeys.yaml" apiVersion: id.registrystack.org/formats/rstack/journeys/v1alpha1 kind: RStackJourneys journeys: From ff7402b83e965ce9bc9c7c4a4d52b90b725fddb9 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 22:02:46 +0000 Subject: [PATCH 085/183] test(dev): box the saved-report test diagnostic clippy::result_large_err refuses the unboxed Diagnostic error in the owner report test helper. Signed-off-by: Jeremi Joslin --- crates/registry-rstack-dev/src/owner_report_tests.rs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/crates/registry-rstack-dev/src/owner_report_tests.rs b/crates/registry-rstack-dev/src/owner_report_tests.rs index 9ac0446b1a..4a7c1704e9 100644 --- a/crates/registry-rstack-dev/src/owner_report_tests.rs +++ b/crates/registry-rstack-dev/src/owner_report_tests.rs @@ -7,12 +7,14 @@ const CASEWORK: &str = const BREG_IDENTITY_FACTS: &str = include_str!("../../../products/breg/examples/formats/identity-facts-report.json"); -fn decode(bytes: &[u8], format: Format) -> Result<(), Diagnostic> { +fn decode(bytes: &[u8], format: Format) -> Result<(), Box> { let (report, exit) = check_bytes("synthetic.json", bytes, format); if exit == 0 { Ok(()) } else { - Err(report.into_diagnostics().into_iter().next().unwrap()) + Err(Box::new( + report.into_diagnostics().into_iter().next().unwrap(), + )) } } From 403ecfef80b5619869b72c066b3e191bce1f5915 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 22:02:46 +0000 Subject: [PATCH 086/183] fix(identifiers): catalogue the ctl-report, store-provision and Session route inventory schemas The lane added three public schema IDs that the identifier reference closure refused. The Session route inventory gets its own schema source, and the regenerated catalogue lists all three. Signed-off-by: Jeremi Joslin --- .../identifiers/contracts/catalog-source.json | 8 + .../identifiers/generated/catalog.v1.json | 206 +++++++++++------- 2 files changed, 138 insertions(+), 76 deletions(-) diff --git a/products/identifiers/contracts/catalog-source.json b/products/identifiers/contracts/catalog-source.json index 11b9d4ce38..dcfd97f4b7 100644 --- a/products/identifiers/contracts/catalog-source.json +++ b/products/identifiers/contracts/catalog-source.json @@ -309,6 +309,14 @@ "compatibilityLine": "v1alpha1", "description": "Registry Stack session service runtime configuration JSON Schema." }, + { + "glob": "products/platform/generated/session-runtime/session-route-inventory.v1alpha1.schema.json", + "sourcePath": "crates/registry-session/src/schema.rs", + "owner": "platform", + "status": "active", + "compatibilityLine": "v1alpha1", + "description": "Checked Registry Session browser route inventory JSON Schema." + }, { "glob": "products/platform/generated/mcp-runtime/*.schema.json", "sourcePath": "crates/registry-mcp/src/schema.rs", diff --git a/products/identifiers/generated/catalog.v1.json b/products/identifiers/generated/catalog.v1.json index 23eec07fc8..0bb695ff75 100644 --- a/products/identifiers/generated/catalog.v1.json +++ b/products/identifiers/generated/catalog.v1.json @@ -1847,7 +1847,7 @@ "description": "Starts stay held after a restore until an operator releases the admission hold.", "source": { "path": "crates/registry-coordinator/src/problem.rs", - "sha256": "45d584b668b183e59a2328f935f6caa523b3fef2d2e727e7d1faa98079d9e49f" + "sha256": "597d0f3d8488bd54437563b6149baa8410f6d44e16a7143e37bf990d0fd1f3de" }, "problem": { "code": "admission.held", @@ -1866,7 +1866,7 @@ "description": "This instance runs in recovery-only mode and admits no runs. Send starts to the ordinary service.", "source": { "path": "crates/registry-coordinator/src/problem.rs", - "sha256": "45d584b668b183e59a2328f935f6caa523b3fef2d2e727e7d1faa98079d9e49f" + "sha256": "597d0f3d8488bd54437563b6149baa8410f6d44e16a7143e37bf990d0fd1f3de" }, "problem": { "code": "admission.recovery-only", @@ -1885,7 +1885,7 @@ "description": "The operation may have completed, but its audited result could not be released. Inspect the run before repeating the operation.", "source": { "path": "crates/registry-coordinator/src/problem.rs", - "sha256": "45d584b668b183e59a2328f935f6caa523b3fef2d2e727e7d1faa98079d9e49f" + "sha256": "597d0f3d8488bd54437563b6149baa8410f6d44e16a7143e37bf990d0fd1f3de" }, "problem": { "code": "audit.response-unavailable", @@ -1904,7 +1904,7 @@ "description": "The caller credential or completion signature is missing, invalid, or expired.", "source": { "path": "crates/registry-coordinator/src/problem.rs", - "sha256": "45d584b668b183e59a2328f935f6caa523b3fef2d2e727e7d1faa98079d9e49f" + "sha256": "597d0f3d8488bd54437563b6149baa8410f6d44e16a7143e37bf990d0fd1f3de" }, "problem": { "code": "authentication.refused", @@ -1923,7 +1923,7 @@ "description": "The run's original connection settings differ from this service's runtime configuration.", "source": { "path": "crates/registry-coordinator/src/problem.rs", - "sha256": "45d584b668b183e59a2328f935f6caa523b3fef2d2e727e7d1faa98079d9e49f" + "sha256": "597d0f3d8488bd54437563b6149baa8410f6d44e16a7143e37bf990d0fd1f3de" }, "problem": { "code": "binding.conflict", @@ -1942,7 +1942,7 @@ "description": "Connection settings that runs in progress use differ from this service's runtime configuration.", "source": { "path": "crates/registry-coordinator/src/problem.rs", - "sha256": "45d584b668b183e59a2328f935f6caa523b3fef2d2e727e7d1faa98079d9e49f" + "sha256": "597d0f3d8488bd54437563b6149baa8410f6d44e16a7143e37bf990d0fd1f3de" }, "problem": { "code": "binding.live-conflict", @@ -1961,7 +1961,7 @@ "description": "That step is not waiting.", "source": { "path": "crates/registry-coordinator/src/problem.rs", - "sha256": "45d584b668b183e59a2328f935f6caa523b3fef2d2e727e7d1faa98079d9e49f" + "sha256": "597d0f3d8488bd54437563b6149baa8410f6d44e16a7143e37bf990d0fd1f3de" }, "problem": { "code": "check.not-waiting", @@ -1977,10 +1977,10 @@ "compatibilityLine": "v1alpha1", "owner": "coordinator", "title": "Workflow definition refused", - "description": "The workflow's workflow definition, one of its mappings or one of its functions refused the request.", + "description": "The workflow's workflow definition, one of its mappings or one of its Transforms refused the request.", "source": { "path": "crates/registry-coordinator/src/problem.rs", - "sha256": "45d584b668b183e59a2328f935f6caa523b3fef2d2e727e7d1faa98079d9e49f" + "sha256": "597d0f3d8488bd54437563b6149baa8410f6d44e16a7143e37bf990d0fd1f3de" }, "problem": { "code": "definition.refused", @@ -1999,7 +1999,7 @@ "description": "An apply changed the active packages after this service started. Restart it with the runtime file that apply used.", "source": { "path": "crates/registry-coordinator/src/problem.rs", - "sha256": "45d584b668b183e59a2328f935f6caa523b3fef2d2e727e7d1faa98079d9e49f" + "sha256": "597d0f3d8488bd54437563b6149baa8410f6d44e16a7143e37bf990d0fd1f3de" }, "problem": { "code": "deployment.activation-changed", @@ -2018,7 +2018,7 @@ "description": "The deployment's activation, runtime configuration or state key custody check failed.", "source": { "path": "crates/registry-coordinator/src/problem.rs", - "sha256": "45d584b668b183e59a2328f935f6caa523b3fef2d2e727e7d1faa98079d9e49f" + "sha256": "597d0f3d8488bd54437563b6149baa8410f6d44e16a7143e37bf990d0fd1f3de" }, "problem": { "code": "deployment.refused", @@ -2037,7 +2037,7 @@ "description": "An evaluation may have completed at its provider, so the run is never evaluated again.", "source": { "path": "crates/registry-coordinator/src/problem.rs", - "sha256": "45d584b668b183e59a2328f935f6caa523b3fef2d2e727e7d1faa98079d9e49f" + "sha256": "597d0f3d8488bd54437563b6149baa8410f6d44e16a7143e37bf990d0fd1f3de" }, "problem": { "code": "evaluation.uncertain", @@ -2056,7 +2056,7 @@ "description": "The signed event must satisfy the accepted canonical envelope and typed event contract.", "source": { "path": "crates/registry-coordinator/src/problem.rs", - "sha256": "45d584b668b183e59a2328f935f6caa523b3fef2d2e727e7d1faa98079d9e49f" + "sha256": "597d0f3d8488bd54437563b6149baa8410f6d44e16a7143e37bf990d0fd1f3de" }, "problem": { "code": "event.invalid", @@ -2075,7 +2075,7 @@ "description": "The signed event exceeds the event value profile: 131072 canonical bytes, 32 levels of nesting, 4096 values, 256 items per array, 256 members per object, and 16384 bytes per string. Have the producer project fewer or smaller fields into the event.", "source": { "path": "crates/registry-coordinator/src/problem.rs", - "sha256": "45d584b668b183e59a2328f935f6caa523b3fef2d2e727e7d1faa98079d9e49f" + "sha256": "597d0f3d8488bd54437563b6149baa8410f6d44e16a7143e37bf990d0fd1f3de" }, "problem": { "code": "event.too-large", @@ -2094,7 +2094,7 @@ "description": "Send a fresh signed delivery from the exact configured source to its accepted trigger.", "source": { "path": "crates/registry-coordinator/src/problem.rs", - "sha256": "45d584b668b183e59a2328f935f6caa523b3fef2d2e727e7d1faa98079d9e49f" + "sha256": "597d0f3d8488bd54437563b6149baa8410f6d44e16a7143e37bf990d0fd1f3de" }, "problem": { "code": "event.unauthenticated", @@ -2113,7 +2113,7 @@ "description": "Execution is under restore hold until an operator releases it.", "source": { "path": "crates/registry-coordinator/src/problem.rs", - "sha256": "45d584b668b183e59a2328f935f6caa523b3fef2d2e727e7d1faa98079d9e49f" + "sha256": "597d0f3d8488bd54437563b6149baa8410f6d44e16a7143e37bf990d0fd1f3de" }, "problem": { "code": "execution.held", @@ -2132,7 +2132,7 @@ "description": "Supply an Idempotency-Key header of 1 to 256 bytes.", "source": { "path": "crates/registry-coordinator/src/problem.rs", - "sha256": "45d584b668b183e59a2328f935f6caa523b3fef2d2e727e7d1faa98079d9e49f" + "sha256": "597d0f3d8488bd54437563b6149baa8410f6d44e16a7143e37bf990d0fd1f3de" }, "problem": { "code": "idempotency.key-invalid", @@ -2151,7 +2151,7 @@ "description": "This idempotency key already started a run with different input.", "source": { "path": "crates/registry-coordinator/src/problem.rs", - "sha256": "45d584b668b183e59a2328f935f6caa523b3fef2d2e727e7d1faa98079d9e49f" + "sha256": "597d0f3d8488bd54437563b6149baa8410f6d44e16a7143e37bf990d0fd1f3de" }, "problem": { "code": "idempotency.key-reused", @@ -2170,7 +2170,7 @@ "description": "The start input does not satisfy the workflow's declared input schema and value bounds.", "source": { "path": "crates/registry-coordinator/src/problem.rs", - "sha256": "45d584b668b183e59a2328f935f6caa523b3fef2d2e727e7d1faa98079d9e49f" + "sha256": "597d0f3d8488bd54437563b6149baa8410f6d44e16a7143e37bf990d0fd1f3de" }, "problem": { "code": "input.invalid", @@ -2189,7 +2189,7 @@ "description": "A mutation may have completed at its provider, so the run never sends it again. Reconcile it when its operation offers a read-only receipt lookup; otherwise inspect or cancel the run.", "source": { "path": "crates/registry-coordinator/src/problem.rs", - "sha256": "45d584b668b183e59a2328f935f6caa523b3fef2d2e727e7d1faa98079d9e49f" + "sha256": "597d0f3d8488bd54437563b6149baa8410f6d44e16a7143e37bf990d0fd1f3de" }, "problem": { "code": "mutation.uncertain", @@ -2208,7 +2208,7 @@ "description": "The caller's policy does not allow this operation.", "source": { "path": "crates/registry-coordinator/src/problem.rs", - "sha256": "45d584b668b183e59a2328f935f6caa523b3fef2d2e727e7d1faa98079d9e49f" + "sha256": "597d0f3d8488bd54437563b6149baa8410f6d44e16a7143e37bf990d0fd1f3de" }, "problem": { "code": "operation.not-authorized", @@ -2227,7 +2227,7 @@ "description": "The original command's receipt can no longer be recovered. This is not evidence that the command was not sent.", "source": { "path": "crates/registry-coordinator/src/problem.rs", - "sha256": "45d584b668b183e59a2328f935f6caa523b3fef2d2e727e7d1faa98079d9e49f" + "sha256": "597d0f3d8488bd54437563b6149baa8410f6d44e16a7143e37bf990d0fd1f3de" }, "problem": { "code": "receipt.expired", @@ -2246,7 +2246,7 @@ "description": "The run's progress changed while it was being reconciled. Inspect it again.", "source": { "path": "crates/registry-coordinator/src/problem.rs", - "sha256": "45d584b668b183e59a2328f935f6caa523b3fef2d2e727e7d1faa98079d9e49f" + "sha256": "597d0f3d8488bd54437563b6149baa8410f6d44e16a7143e37bf990d0fd1f3de" }, "problem": { "code": "reconcile.raced", @@ -2265,7 +2265,7 @@ "description": "Reconcile applies only to a held mutation with a prepared command, its original binding and no active lease.", "source": { "path": "crates/registry-coordinator/src/problem.rs", - "sha256": "45d584b668b183e59a2328f935f6caa523b3fef2d2e727e7d1faa98079d9e49f" + "sha256": "597d0f3d8488bd54437563b6149baa8410f6d44e16a7143e37bf990d0fd1f3de" }, "problem": { "code": "reconcile.refused", @@ -2284,7 +2284,7 @@ "description": "The held operation has no original-result lookup.", "source": { "path": "crates/registry-coordinator/src/problem.rs", - "sha256": "45d584b668b183e59a2328f935f6caa523b3fef2d2e727e7d1faa98079d9e49f" + "sha256": "597d0f3d8488bd54437563b6149baa8410f6d44e16a7143e37bf990d0fd1f3de" }, "problem": { "code": "reconcile.unsupported", @@ -2303,7 +2303,7 @@ "description": "The request body exceeds the accepted size: 65536 bytes for a JSON request, or 1048576 bytes for a signed event delivery.", "source": { "path": "crates/registry-coordinator/src/problem.rs", - "sha256": "45d584b668b183e59a2328f935f6caa523b3fef2d2e727e7d1faa98079d9e49f" + "sha256": "597d0f3d8488bd54437563b6149baa8410f6d44e16a7143e37bf990d0fd1f3de" }, "problem": { "code": "request.body-too-large", @@ -2322,7 +2322,7 @@ "description": "The request could not be read as a Coordinator request.", "source": { "path": "crates/registry-coordinator/src/problem.rs", - "sha256": "45d584b668b183e59a2328f935f6caa523b3fef2d2e727e7d1faa98079d9e49f" + "sha256": "597d0f3d8488bd54437563b6149baa8410f6d44e16a7143e37bf990d0fd1f3de" }, "problem": { "code": "request.invalid", @@ -2341,7 +2341,7 @@ "description": "The list limit must be between 1 and 100.", "source": { "path": "crates/registry-coordinator/src/problem.rs", - "sha256": "45d584b668b183e59a2328f935f6caa523b3fef2d2e727e7d1faa98079d9e49f" + "sha256": "597d0f3d8488bd54437563b6149baa8410f6d44e16a7143e37bf990d0fd1f3de" }, "problem": { "code": "request.limit-out-of-range", @@ -2360,7 +2360,7 @@ "description": "The route exists but not for this method.", "source": { "path": "crates/registry-coordinator/src/problem.rs", - "sha256": "45d584b668b183e59a2328f935f6caa523b3fef2d2e727e7d1faa98079d9e49f" + "sha256": "597d0f3d8488bd54437563b6149baa8410f6d44e16a7143e37bf990d0fd1f3de" }, "problem": { "code": "request.method-not-allowed", @@ -2379,7 +2379,7 @@ "description": "The requested route does not exist.", "source": { "path": "crates/registry-coordinator/src/problem.rs", - "sha256": "45d584b668b183e59a2328f935f6caa523b3fef2d2e727e7d1faa98079d9e49f" + "sha256": "597d0f3d8488bd54437563b6149baa8410f6d44e16a7143e37bf990d0fd1f3de" }, "problem": { "code": "request.not-found", @@ -2398,7 +2398,7 @@ "description": "The reason or recovery reference must be a bounded reference without personal data or control characters.", "source": { "path": "crates/registry-coordinator/src/problem.rs", - "sha256": "45d584b668b183e59a2328f935f6caa523b3fef2d2e727e7d1faa98079d9e49f" + "sha256": "597d0f3d8488bd54437563b6149baa8410f6d44e16a7143e37bf990d0fd1f3de" }, "problem": { "code": "request.reason-invalid", @@ -2417,7 +2417,7 @@ "description": "The retention cutoff must be in the past and the limit between 1 and 100.", "source": { "path": "crates/registry-coordinator/src/problem.rs", - "sha256": "45d584b668b183e59a2328f935f6caa523b3fef2d2e727e7d1faa98079d9e49f" + "sha256": "597d0f3d8488bd54437563b6149baa8410f6d44e16a7143e37bf990d0fd1f3de" }, "problem": { "code": "request.retention-invalid", @@ -2436,7 +2436,7 @@ "description": "The request body could not be processed.", "source": { "path": "crates/registry-coordinator/src/problem.rs", - "sha256": "45d584b668b183e59a2328f935f6caa523b3fef2d2e727e7d1faa98079d9e49f" + "sha256": "597d0f3d8488bd54437563b6149baa8410f6d44e16a7143e37bf990d0fd1f3de" }, "problem": { "code": "request.unprocessable", @@ -2455,7 +2455,7 @@ "description": "The request body is not JSON.", "source": { "path": "crates/registry-coordinator/src/problem.rs", - "sha256": "45d584b668b183e59a2328f935f6caa523b3fef2d2e727e7d1faa98079d9e49f" + "sha256": "597d0f3d8488bd54437563b6149baa8410f6d44e16a7143e37bf990d0fd1f3de" }, "problem": { "code": "request.unsupported-media-type", @@ -2474,7 +2474,7 @@ "description": "This recovery action requires execution to be under restore hold.", "source": { "path": "crates/registry-coordinator/src/problem.rs", - "sha256": "45d584b668b183e59a2328f935f6caa523b3fef2d2e727e7d1faa98079d9e49f" + "sha256": "597d0f3d8488bd54437563b6149baa8410f6d44e16a7143e37bf990d0fd1f3de" }, "problem": { "code": "restore.hold-required", @@ -2493,7 +2493,7 @@ "description": "Held work no longer matches its protected definition or prepared command.", "source": { "path": "crates/registry-coordinator/src/problem.rs", - "sha256": "45d584b668b183e59a2328f935f6caa523b3fef2d2e727e7d1faa98079d9e49f" + "sha256": "597d0f3d8488bd54437563b6149baa8410f6d44e16a7143e37bf990d0fd1f3de" }, "problem": { "code": "restore.lease-incompatible", @@ -2512,7 +2512,7 @@ "description": "Execution history must be complete and the prior deployment fenced before recovery is reviewed.", "source": { "path": "crates/registry-coordinator/src/problem.rs", - "sha256": "45d584b668b183e59a2328f935f6caa523b3fef2d2e727e7d1faa98079d9e49f" + "sha256": "597d0f3d8488bd54437563b6149baa8410f6d44e16a7143e37bf990d0fd1f3de" }, "problem": { "code": "restore.review-required", @@ -2531,7 +2531,7 @@ "description": "Held work remains unresolved, so the restore hold cannot be released.", "source": { "path": "crates/registry-coordinator/src/problem.rs", - "sha256": "45d584b668b183e59a2328f935f6caa523b3fef2d2e727e7d1faa98079d9e49f" + "sha256": "597d0f3d8488bd54437563b6149baa8410f6d44e16a7143e37bf990d0fd1f3de" }, "problem": { "code": "restore.unresolved", @@ -2550,7 +2550,7 @@ "description": "Retry-same applies only to held work before its original deadline.", "source": { "path": "crates/registry-coordinator/src/problem.rs", - "sha256": "45d584b668b183e59a2328f935f6caa523b3fef2d2e727e7d1faa98079d9e49f" + "sha256": "597d0f3d8488bd54437563b6149baa8410f6d44e16a7143e37bf990d0fd1f3de" }, "problem": { "code": "retry.refused", @@ -2569,7 +2569,7 @@ "description": "This service's Coordinator version cannot interpret the run's pinned definition.", "source": { "path": "crates/registry-coordinator/src/problem.rs", - "sha256": "45d584b668b183e59a2328f935f6caa523b3fef2d2e727e7d1faa98079d9e49f" + "sha256": "597d0f3d8488bd54437563b6149baa8410f6d44e16a7143e37bf990d0fd1f3de" }, "problem": { "code": "run.definition-incompatible", @@ -2588,7 +2588,7 @@ "description": "No run with this identifier is visible to the caller.", "source": { "path": "crates/registry-coordinator/src/problem.rs", - "sha256": "45d584b668b183e59a2328f935f6caa523b3fef2d2e727e7d1faa98079d9e49f" + "sha256": "597d0f3d8488bd54437563b6149baa8410f6d44e16a7143e37bf990d0fd1f3de" }, "problem": { "code": "run.not-visible", @@ -2607,7 +2607,7 @@ "description": "Retention erased this run's payloads, so it can no longer be retried or reconciled.", "source": { "path": "crates/registry-coordinator/src/problem.rs", - "sha256": "45d584b668b183e59a2328f935f6caa523b3fef2d2e727e7d1faa98079d9e49f" + "sha256": "597d0f3d8488bd54437563b6149baa8410f6d44e16a7143e37bf990d0fd1f3de" }, "problem": { "code": "run.payload-erased", @@ -2626,7 +2626,7 @@ "description": "Coordinator could not complete the request.", "source": { "path": "crates/registry-coordinator/src/problem.rs", - "sha256": "45d584b668b183e59a2328f935f6caa523b3fef2d2e727e7d1faa98079d9e49f" + "sha256": "597d0f3d8488bd54437563b6149baa8410f6d44e16a7143e37bf990d0fd1f3de" }, "problem": { "code": "runtime.failure", @@ -2645,7 +2645,7 @@ "description": "A dependency of the Coordinator, such as its database, audit stream or token verifier, is unavailable. Try again after the service recovers.", "source": { "path": "crates/registry-coordinator/src/problem.rs", - "sha256": "45d584b668b183e59a2328f935f6caa523b3fef2d2e727e7d1faa98079d9e49f" + "sha256": "597d0f3d8488bd54437563b6149baa8410f6d44e16a7143e37bf990d0fd1f3de" }, "problem": { "code": "service.unavailable", @@ -2664,7 +2664,7 @@ "description": "This deployment does not serve the named workflow.", "source": { "path": "crates/registry-coordinator/src/problem.rs", - "sha256": "45d584b668b183e59a2328f935f6caa523b3fef2d2e727e7d1faa98079d9e49f" + "sha256": "597d0f3d8488bd54437563b6149baa8410f6d44e16a7143e37bf990d0fd1f3de" }, "problem": { "code": "workflow.not-served", @@ -2683,7 +2683,7 @@ "description": "The expected workflow revision differs from the active revision or the original admission.", "source": { "path": "crates/registry-coordinator/src/problem.rs", - "sha256": "45d584b668b183e59a2328f935f6caa523b3fef2d2e727e7d1faa98079d9e49f" + "sha256": "597d0f3d8488bd54437563b6149baa8410f6d44e16a7143e37bf990d0fd1f3de" }, "problem": { "code": "workflow.revision-mismatch", @@ -5267,7 +5267,7 @@ }, "artifact": { "path": "products/adapter/schemas/job-runtime.v1alpha1.schema.json", - "sha256": "0449f7d543ff800396616fe2464f8feefb4288d1e3efc67caf1d97f8e7e93083", + "sha256": "867bd2e4a48ffa4e639002d8b19522804d6716903c99508c2a4d4436a3b96398", "mediaType": "application/schema+json" } }, @@ -5447,7 +5447,7 @@ }, "artifact": { "path": "products/adapter/schemas/runtime.v1alpha1.schema.json", - "sha256": "c50ad7d98f4b14b07c89614872d9fe3963cd68590014e6a995dba4ef0d4229ff", + "sha256": "99d3b0f61717e804fde996a4f042d375a3957e4f6e07bd9d313ef31c1310529c", "mediaType": "application/schema+json" } }, @@ -5533,7 +5533,7 @@ "description": "Base Registry Engine tool-file JSON Schemas at version v1alpha1.", "source": { "path": "crates/registry-bregctl/src/tool_schema.rs", - "sha256": "7b301a42961b96b2ba696f0c6a412275ed7dc21fb03e18d42e66a57e7c05440a" + "sha256": "d9192db9db98a1242472bbc5002b6998a3dec17dfb05d7fbd2068d1353a52684" }, "artifact": { "path": "products/breg/generated/tools/backup-binding.v1alpha1.schema.json", @@ -5541,6 +5541,24 @@ "mediaType": "application/schema+json" } }, + { + "uri": "https://id.registrystack.org/schemas/breg/ctl-report/ctl-report.v1alpha1.schema.json", + "kind": "schema", + "status": "active", + "compatibilityLine": "v1alpha1", + "owner": "breg", + "title": "Completed BReg identity facts command report", + "description": "Base Registry Engine tool-file JSON Schemas at version v1alpha1.", + "source": { + "path": "crates/registry-bregctl/src/tool_schema.rs", + "sha256": "d9192db9db98a1242472bbc5002b6998a3dec17dfb05d7fbd2068d1353a52684" + }, + "artifact": { + "path": "products/breg/generated/tools/ctl-report.v1alpha1.schema.json", + "sha256": "6513298c7020104c036804abd150c61f28d18b7b38113a489b84f67335dc40ef", + "mediaType": "application/schema+json" + } + }, { "uri": "https://id.registrystack.org/schemas/breg/event-record-view/event-record-view.v1alpha1.schema.json", "kind": "schema", @@ -5587,7 +5605,7 @@ "description": "Base Registry Engine tool-file JSON Schemas at version v1alpha1.", "source": { "path": "crates/registry-bregctl/src/tool_schema.rs", - "sha256": "7b301a42961b96b2ba696f0c6a412275ed7dc21fb03e18d42e66a57e7c05440a" + "sha256": "d9192db9db98a1242472bbc5002b6998a3dec17dfb05d7fbd2068d1353a52684" }, "artifact": { "path": "products/breg/generated/tools/example-scenarios.v1alpha1.schema.json", @@ -5605,7 +5623,7 @@ "description": "Base Registry Engine tool-file JSON Schemas at version v1.", "source": { "path": "crates/registry-bregctl/src/tool_schema.rs", - "sha256": "7b301a42961b96b2ba696f0c6a412275ed7dc21fb03e18d42e66a57e7c05440a" + "sha256": "d9192db9db98a1242472bbc5002b6998a3dec17dfb05d7fbd2068d1353a52684" }, "artifact": { "path": "products/breg/generated/tools/journeys.v1.schema.json", @@ -5645,7 +5663,7 @@ }, "artifact": { "path": "products/breg/generated/mcp-runtime/mcp-runtime.schema.json", - "sha256": "2e625db395d51c21d1c3c5f02d4373ccc585c5c16ffceb247e3af61b2c3de808", + "sha256": "a1272f3d77f9a8e27425e8613d3a2cf76cb37e60eb90c6473660b9f7e0d3da8c", "mediaType": "application/schema+json" } }, @@ -5659,7 +5677,7 @@ "description": "Base Registry Engine tool-file JSON Schemas at version v1alpha1.", "source": { "path": "crates/registry-bregctl/src/tool_schema.rs", - "sha256": "7b301a42961b96b2ba696f0c6a412275ed7dc21fb03e18d42e66a57e7c05440a" + "sha256": "d9192db9db98a1242472bbc5002b6998a3dec17dfb05d7fbd2068d1353a52684" }, "artifact": { "path": "products/breg/generated/tools/migration-descriptor.v1alpha1.schema.json", @@ -5695,7 +5713,7 @@ "description": "Base Registry Engine tool-file JSON Schemas at version v1alpha1.", "source": { "path": "crates/registry-bregctl/src/tool_schema.rs", - "sha256": "7b301a42961b96b2ba696f0c6a412275ed7dc21fb03e18d42e66a57e7c05440a" + "sha256": "d9192db9db98a1242472bbc5002b6998a3dec17dfb05d7fbd2068d1353a52684" }, "artifact": { "path": "products/breg/generated/tools/model-selection.v1alpha1.schema.json", @@ -5789,7 +5807,7 @@ }, "artifact": { "path": "products/breg/generated/review-runtime/review-runtime.schema.json", - "sha256": "28f0d22758368cef7718da05186ba475e4051308f3df1ab9452b5bec39b53112", + "sha256": "ec5d87d3668095586a821abd7a0f8b998bdad11f10123392188de6808bd129d9", "mediaType": "application/schema+json" } }, @@ -5825,7 +5843,7 @@ }, "artifact": { "path": "products/breg/generated/runtime/runtime.schema.json", - "sha256": "6a2681e545da5d44a2d2bc2912797cc481dc39089eafd712acf738c478a5a7b0", + "sha256": "d04c498a9cf820332b5d8a9f09b61e215bc0c3dca6d770b49e67cf4844626d9e", "mediaType": "application/schema+json" } }, @@ -5839,7 +5857,7 @@ "description": "Base Registry Engine tool-file JSON Schemas at version v1.", "source": { "path": "crates/registry-bregctl/src/tool_schema.rs", - "sha256": "7b301a42961b96b2ba696f0c6a412275ed7dc21fb03e18d42e66a57e7c05440a" + "sha256": "d9192db9db98a1242472bbc5002b6998a3dec17dfb05d7fbd2068d1353a52684" }, "artifact": { "path": "products/breg/generated/tools/schema-test-credentials.v1.schema.json", @@ -5933,7 +5951,7 @@ }, "artifact": { "path": "products/casework/generated/runtime/runtime.schema.json", - "sha256": "f24571d637629b2d913ec6efb88944306c84dcd2b00ea8e03848049fd7574201", + "sha256": "43f97b7653608f98df7093fde327d515d76380213350af7c85d027e609c70099", "mediaType": "application/schema+json" } }, @@ -5947,11 +5965,11 @@ "description": "Registry Coordinator deterministic fixture authoring JSON Schema.", "source": { "path": "crates/registry-coordinator/src/scenarios.rs", - "sha256": "a3b78b3da6f9fcec6f5e40416295ae5ad481cdcdfb770c6bb1715e0fd7dfc3c9" + "sha256": "8ef5c37541be5c83c60fa82c20d615b79287df941b33c34b8d6a12ed83d562d9" }, "artifact": { "path": "products/coordinator/generated/fixture/fixture.schema.json", - "sha256": "1802438e02edad82557153c88818bbe2ffa8e243679f6d0306b811edc1adedb3", + "sha256": "7817d78eff4d92363247ecae6d7b672a4c25f51e46ec3b6507f403e55416830d", "mediaType": "application/schema+json" } }, @@ -5965,11 +5983,11 @@ "description": "Registry Coordinator portable project authoring JSON Schema.", "source": { "path": "crates/registry-coordinator/src/authoring.rs", - "sha256": "233ac8ce1b8f2a7c52bc39a2b48f55ba9ffc1c00be6dea1821089c9736ed8122" + "sha256": "5a69b78d0bd226766a8acaa1d25620309f3294b05aeef34250ea2cea6c6db267" }, "artifact": { "path": "products/coordinator/generated/project/project.schema.json", - "sha256": "69e53bda51ef36c2540769d13af80eaa09f6768b44d8379b79fe0886c7a53555", + "sha256": "4e6aec4ae96ea5a85738802f64e30cb7a4af439ec43fdf0c5b9d8cbe6d96e7ad", "mediaType": "application/schema+json" } }, @@ -5987,7 +6005,7 @@ }, "artifact": { "path": "products/coordinator/generated/runtime/runtime.schema.json", - "sha256": "131466a7fe178d178cd7121eddd15a7bd9229c36a570ad378cd2bff5658c7e7f", + "sha256": "24839c55d2b01edab884dcc18ee1324689dbd52fe958fba51fe55cc5b15d2099", "mediaType": "application/schema+json" } }, @@ -6149,7 +6167,7 @@ }, "artifact": { "path": "products/documents/generated/runtime/runtime.schema.json", - "sha256": "fdf6aa6c21a03c67c7cd656c55155f052d904637d14eadab49434dfd6b28cd8f", + "sha256": "d076eeea14926df9c8812c5e01f1a1e6dbfb2556e490404d848203ee67492de7", "mediaType": "application/schema+json" } }, @@ -6311,7 +6329,7 @@ }, "artifact": { "path": "products/evidence/generated/oid4vci-runtime/oid4vci-runtime.schema.json", - "sha256": "d0b24a5fd3be64a975e6132022e74e95e7258af054466b8b068c78e85e64e870", + "sha256": "01a20c74693699d6be5c62584edbf3137e49fbf2f3c2c4c5616004a873b5b765", "mediaType": "application/schema+json" } }, @@ -6329,7 +6347,7 @@ }, "artifact": { "path": "products/evidence/generated/oid4vp-runtime/oid4vp-runtime.schema.json", - "sha256": "a299d83c097229892bc82765782e86b7852bad3fddd4124d33b8b84ec0d66ca0", + "sha256": "81d70d9488a0bd7cdbaf897ad016fe9cca86b862b5ee5e6b891279b0197a52d6", "mediaType": "application/schema+json" } }, @@ -6387,6 +6405,24 @@ "mediaType": "application/schema+json" } }, + { + "uri": "https://id.registrystack.org/schemas/evidence/store-provision/store-provision.v1alpha1.schema.json", + "kind": "schema", + "status": "active", + "compatibilityLine": "v1alpha1", + "owner": "evidence", + "title": "Evidence store provisioning config", + "description": "Evidence authoring project marker and question JSON Schema.", + "source": { + "path": "crates/registry-evidence-authoring/src/schema.rs", + "sha256": "62464b27cb80552652f785f820ed3655cc9d48aa65dba30dcaea5696c5e79f70" + }, + "artifact": { + "path": "crates/registry-evidencectl/schemas/authoring/store-provision.schema.json", + "sha256": "ad586d201fb64370c09ec18bf9c6aa57f3a8833aaecac7ba748f09dc0bc36d51", + "mediaType": "application/schema+json" + } + }, { "uri": "https://id.registrystack.org/schemas/evidence/target-authority/target-authority.v1alpha1.schema.json", "kind": "schema", @@ -6545,7 +6581,7 @@ }, "artifact": { "path": "products/messaging/generated/runtime/runtime.schema.json", - "sha256": "a455dc4f8c409aa72b599b905b92270cbc0940d465ce57ad86c302b1c5e2974d", + "sha256": "5f42d3706e2b6ad00a430288c7c637395bbee43b8b7635fc0ceb990bebeb788d", "mediaType": "application/schema+json" } }, @@ -6617,7 +6653,7 @@ }, "artifact": { "path": "crates/registry-cli-api/schema/connections.schema.json", - "sha256": "8885a96cae62ec9a421f6327ec7b9d165991b6d7996763d20d018c3d7d249f39", + "sha256": "9d757eeac7bfd9a08ac7d421d6dd4620344d924becd31a77bcf7aec87d8e6b6c", "mediaType": "application/schema+json" } }, @@ -6689,7 +6725,7 @@ }, "artifact": { "path": "products/platform/generated/mcp-runtime/mcp-runtime.schema.json", - "sha256": "f8e707b47f804f8c8fb44589dda071ab0eab14593185ec9c9376bfc88455f9f7", + "sha256": "943bb3a53811c35e5cb9a3457a7c5225586e26dbea99b50b005825e5cd5df86a", "mediaType": "application/schema+json" } }, @@ -6703,7 +6739,7 @@ "description": "rstack error report JSON Schema.", "source": { "path": "crates/registry-rstack/src/cli.rs", - "sha256": "bcfb6c9aaa0911db294ea36fec384039ff55bc06ad84d9669bc78071a648d6b4" + "sha256": "c0fe7cb20b590714dd367fffab20a33ef4e3afb4272811d7e34b34bcb7757495" }, "artifact": { "path": "products/platform/schemas/rstack-dev-error.v1.schema.json", @@ -6711,6 +6747,24 @@ "mediaType": "application/schema+json" } }, + { + "uri": "https://id.registrystack.org/schemas/platform/session-route-inventory/session-route-inventory.v1alpha1.schema.json", + "kind": "schema", + "status": "active", + "compatibilityLine": "v1alpha1", + "owner": "platform", + "title": "Checked Registry Session route inventory", + "description": "Checked Registry Session browser route inventory JSON Schema.", + "source": { + "path": "crates/registry-session/src/schema.rs", + "sha256": "e80a34bb3965ff9d2cea8cdae58dc748db23ecb23c29eb53981f5b2abdc88665" + }, + "artifact": { + "path": "products/platform/generated/session-runtime/session-route-inventory.v1alpha1.schema.json", + "sha256": "b732312a4fb335fd6c1afcd6d146a5f3a402cc65a9a32a5c3be54c9541a6951f", + "mediaType": "application/schema+json" + } + }, { "uri": "https://id.registrystack.org/schemas/platform/session-runtime/session-runtime.v1alpha1.schema.json", "kind": "schema", @@ -6721,11 +6775,11 @@ "description": "Registry Stack session service runtime configuration JSON Schema.", "source": { "path": "crates/registry-session/src/schema.rs", - "sha256": "280ac4ba91fc96ef4421ccc9deac1bab492036b8e48f48c197ff4c2bbf817091" + "sha256": "e80a34bb3965ff9d2cea8cdae58dc748db23ecb23c29eb53981f5b2abdc88665" }, "artifact": { "path": "products/platform/generated/session-runtime/session-runtime.schema.json", - "sha256": "65afffcd321fa818de14a7f568ee36ee8f42ac621d686a0c58bc0bba163ddf8c", + "sha256": "c80019fe44d6032107978be57e1380b2fb060b527f535a4a1705b733b2517f01", "mediaType": "application/schema+json" } }, @@ -6743,7 +6797,7 @@ }, "artifact": { "path": "products/platform/schemas/task-connection.schema.json", - "sha256": "aa6f4dded82d3614a2ce83916b0e916c63b12def7678a9eab9eb8aa67e55a7dd", + "sha256": "d1e3b34b174de0afb1cf1c87895f51273541305d451e3fcb9891393448ebd745", "mediaType": "application/schema+json" } }, @@ -6815,7 +6869,7 @@ }, "artifact": { "path": "products/render/schemas/runtime.schema.json", - "sha256": "056770ac3ae7f273b82d4593ec2403c3706763e61c432d0615d8e6437c796d46", + "sha256": "f08bea3ff05ebcae08042409cc4616834460308489c220cc06d8e729b7e02bd7", "mediaType": "application/schema+json" } }, @@ -6833,7 +6887,7 @@ }, "artifact": { "path": "products/platform/generated/dev/dev.v1alpha1.schema.json", - "sha256": "b22f51c0b03704dfab13513765c70acc631e4a01807703bbfb279dc9120afcde", + "sha256": "88c6a55a99fa1df179ecbf0899a62755831e2052b65ad16d53856776e80d6617", "mediaType": "application/schema+json" } }, @@ -6941,7 +6995,7 @@ }, "artifact": { "path": "products/scheduling/generated/runtime/runtime.schema.json", - "sha256": "3994ba81be800176372d33491965eb6f756d0426d3262135bf500cce1d6a6949", + "sha256": "a631ed1da44c6778cc9574284c697ea60a824ebd26d338e5ec3e825262cec440", "mediaType": "application/schema+json" } }, From 3b5534d98099af575d9a7bb10cc5754c0e11273b Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 22:20:50 +0000 Subject: [PATCH 087/183] fix(session): state the port check without a double negation clippy::nonminimal_bool refuses the negated is_some_and in the Envoy authority check. is_none_or keeps the same behaviour. Signed-off-by: Jeremi Joslin --- crates/registry-session/src/gateway/verify.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/registry-session/src/gateway/verify.rs b/crates/registry-session/src/gateway/verify.rs index ac8a474abc..fea51f48fe 100644 --- a/crates/registry-session/src/gateway/verify.rs +++ b/crates/registry-session/src/gateway/verify.rs @@ -318,10 +318,10 @@ fn standalone_document( expected.clusters.extend(custom); } - let strip_port = !expected + let strip_port = expected .authority .rsplit_once(':') - .is_some_and(|(_, port)| port.parse::().is_ok()); + .is_none_or(|(_, port)| port.parse::().is_err()); let mut filters = expected.filters.clone(); filters.push(json!({ "name": "envoy.filters.http.router", From b23b18bf2d03e3dcbd2e354a971a74305d2cbdd6 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 21:29:11 +0000 Subject: [PATCH 088/183] test(platform-config): pin that mountPolicy switches the resolver Without the member the resolver keeps the strict file rule; with it the resolver admits Compose mounts. Deleting the switch, or applying it unconditionally, now fails a test. Refs #2882. Signed-off-by: Jeremi Joslin --- crates/registry-platform-config/src/blocks_tests.rs | 13 +++++++++++++ crates/registry-platform-config/src/secrets.rs | 7 +++++++ 2 files changed, 20 insertions(+) diff --git a/crates/registry-platform-config/src/blocks_tests.rs b/crates/registry-platform-config/src/blocks_tests.rs index 22d7c16419..74291cc22f 100644 --- a/crates/registry-platform-config/src/blocks_tests.rs +++ b/crates/registry-platform-config/src/blocks_tests.rs @@ -149,11 +149,24 @@ fn compose_native_mount_is_an_explicit_production_setting_at_its_member() { let strict = "apiVersion: registry.registrystack.org/example/v1alpha1\nkind: ExampleRuntimeConfig\nsecretProviders:\n file:\n root: /run/secrets\n"; let omitted = loader.parse_str::(strict, |_| None).unwrap(); assert!(omitted.posture.explicit_settings().is_empty()); + assert!(!omitted + .config + .secret_providers + .resolver(None) + .unwrap() + .admits_compose_native_mounts()); let explicit = format!("{strict} mountPolicy: compose-native\n"); let loaded = loader.parse_str::(&explicit, |_| None).unwrap(); assert!(loaded.development.is_none()); loaded.config.secret_providers.check().unwrap(); + // The member, and only the member, switches the resolver to the Compose rule. + assert!(loaded + .config + .secret_providers + .resolver(None) + .unwrap() + .admits_compose_native_mounts()); let [notice] = loaded.posture.explicit_settings() else { panic!("one explicit setting is recorded"); }; diff --git a/crates/registry-platform-config/src/secrets.rs b/crates/registry-platform-config/src/secrets.rs index 106c64b3f0..b705974b52 100644 --- a/crates/registry-platform-config/src/secrets.rs +++ b/crates/registry-platform-config/src/secrets.rs @@ -460,6 +460,13 @@ impl SecretResolver { self } + /// Whether this resolver admits root-owned mode 0444 Compose mounts, so a + /// test can prove which configurations switch the rule on. + #[cfg(test)] + pub(crate) fn admits_compose_native_mounts(&self) -> bool { + self.file_access.compose_native + } + /// 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> { From 990012018f6dbeb3528ecb4a9df78aeceb255fd4 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 21:30:51 +0000 Subject: [PATCH 089/183] feat(platform-config): expose whether the file provider states compose-native A product whose contract keeps the strict secret file rule needs to see the member to refuse it. The resolver reads the same accessor. Refs #2882. Signed-off-by: Jeremi Joslin --- crates/registry-platform-config/src/blocks.rs | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-) diff --git a/crates/registry-platform-config/src/blocks.rs b/crates/registry-platform-config/src/blocks.rs index c6e035e9bd..2127ba6dc9 100644 --- a/crates/registry-platform-config/src/blocks.rs +++ b/crates/registry-platform-config/src/blocks.rs @@ -248,6 +248,18 @@ impl SecretProvidersConfig { providers } + /// Whether the file provider states `mountPolicy: compose-native`. A + /// product whose contract keeps the strict file rule refuses the block + /// when this is true. + #[must_use] + pub fn compose_native_mounts(&self) -> bool { + self.file.as_ref().is_some_and(|file| { + file.mount_policy + .as_ref() + .is_some_and(|policy| *policy.get() == SecretMountPolicy::ComposeNative) + }) + } + /// A resolver for exactly the providers this block enables. When the /// process holds a [`DevelopmentWitness`], the file provider relaxes the /// read and mode-bit checks to a warning. @@ -263,11 +275,7 @@ impl SecretProvidersConfig { ) .map(|resolver| { let resolver = resolver.in_development(witness); - if self.file.as_ref().is_some_and(|file| { - file.mount_policy - .as_ref() - .is_some_and(|policy| *policy.get() == SecretMountPolicy::ComposeNative) - }) { + if self.compose_native_mounts() { resolver.with_compose_native_mounts() } else { resolver From eab9d406607ffa15c0b7b8bba4f943f9a52494f4 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 21:30:51 +0000 Subject: [PATCH 090/183] fix(evidence): refuse compose-native secret mounts under the Version 1 key rule Evidence, the OID4VCI delivery service and the OID4VP verifier keep the frozen rule that a key file is never readable by other users, so each refuses secretProviders.file.mountPolicy with a positioned diagnostic and the strict remedy. The runtime contract, operator contract and security invariant matrix stay true. Refs #2882. Signed-off-by: Jeremi Joslin --- .../registry-evidence-oid4vci/src/config.rs | 8 ++++ .../tests/check_command.rs | 25 ++++++++++ crates/registry-evidence-oid4vp/src/config.rs | 8 ++++ .../tests/check_command.rs | 25 ++++++++++ crates/registry-evidence/src/config.rs | 48 +++++++++++++++++++ 5 files changed, 114 insertions(+) diff --git a/crates/registry-evidence-oid4vci/src/config.rs b/crates/registry-evidence-oid4vci/src/config.rs index f2ba0c41b8..0fe4f48d01 100644 --- a/crates/registry-evidence-oid4vci/src/config.rs +++ b/crates/registry-evidence-oid4vci/src/config.rs @@ -1416,6 +1416,14 @@ impl DeliveryDocument { } fn secret_findings(&self, findings: &mut Vec) { + if self.secret_providers.compose_native_mounts() { + findings.push(Finding::error( + "evidence.oid4vci.secret-providers", + "/secretProviders/file/mountPolicy", + "the wallet delivery service keeps the Evidence Version 1 secret file rule, so it does not accept mountPolicy", + "Remove mountPolicy. Stage each secret file owned by the runtime user with mode 0400 or 0600, or owned by root with no bits outside 0640.", + )); + } if let Err(error) = self.secret_providers.check() { findings.push(match error.kind() { ConfigBlockErrorKind::RelativePath => Finding::error( diff --git a/crates/registry-evidence-oid4vci/tests/check_command.rs b/crates/registry-evidence-oid4vci/tests/check_command.rs index dc2feaa835..4a90e8985f 100644 --- a/crates/registry-evidence-oid4vci/tests/check_command.rs +++ b/crates/registry-evidence-oid4vci/tests/check_command.rs @@ -319,3 +319,28 @@ fn writable_secret_root_passes_offline_check_and_is_refused_by_serve_and_inspect ); } } + +#[test] +fn compose_native_secret_mounts_are_refused_under_the_version_1_key_rule() { + let text = example().replace( + " root: /run/secrets/evidence-oid4vci\n", + " root: /run/secrets/evidence-oid4vci\n mountPolicy: compose-native\n", + ); + assert_ne!(text, example(), "the member is written"); + let (_root, path) = write(&text); + + let output = check(&path, &["--format", "json"]); + assert_eq!(output.status.code(), Some(1)); + let document = json(&output); + assert!( + document["diagnostics"] + .as_array() + .unwrap() + .iter() + .any( + |diagnostic| diagnostic["code"] == "evidence.oid4vci.secret-providers" + && diagnostic["path"] == "/secretProviders/file/mountPolicy" + ), + "{document}" + ); +} diff --git a/crates/registry-evidence-oid4vp/src/config.rs b/crates/registry-evidence-oid4vp/src/config.rs index 1d108f8ee9..c888be2f4e 100644 --- a/crates/registry-evidence-oid4vp/src/config.rs +++ b/crates/registry-evidence-oid4vp/src/config.rs @@ -1387,6 +1387,14 @@ impl VerifierDocument { } fn secret_findings(&self, findings: &mut Vec) { + if self.secret_providers.compose_native_mounts() { + findings.push(Finding::error( + "evidence.oid4vp.secret-providers", + "/secretProviders/file/mountPolicy", + "the wallet presentation service keeps the Evidence Version 1 secret file rule, so it does not accept mountPolicy", + "Remove mountPolicy. Stage each secret file owned by the runtime user with mode 0400 or 0600, or owned by root with no bits outside 0640.", + )); + } if let Err(error) = self.secret_providers.check() { findings.push(match error.kind() { ConfigBlockErrorKind::RelativePath => Finding::error( diff --git a/crates/registry-evidence-oid4vp/tests/check_command.rs b/crates/registry-evidence-oid4vp/tests/check_command.rs index 1a2141f4a2..b956f5960c 100644 --- a/crates/registry-evidence-oid4vp/tests/check_command.rs +++ b/crates/registry-evidence-oid4vp/tests/check_command.rs @@ -204,3 +204,28 @@ fn an_explicitly_empty_claims_list_is_refused() { assert_eq!(output.status.code(), Some(1), "{output:?}"); assert_eq!(json(&output)["ok"], false); } + +#[test] +fn compose_native_secret_mounts_are_refused_under_the_version_1_key_rule() { + let text = example().replace( + " root: /run/secrets/evidence-oid4vp\n", + " root: /run/secrets/evidence-oid4vp\n mountPolicy: compose-native\n", + ); + assert_ne!(text, example(), "the member is written"); + let (_root, path) = write(&text); + + let output = check(&path, &["--format", "json"]); + assert_eq!(output.status.code(), Some(1)); + let document = json(&output); + assert!( + document["diagnostics"] + .as_array() + .unwrap() + .iter() + .any( + |diagnostic| diagnostic["code"] == "evidence.oid4vp.secret-providers" + && diagnostic["path"] == "/secretProviders/file/mountPolicy" + ), + "{document}" + ); +} diff --git a/crates/registry-evidence/src/config.rs b/crates/registry-evidence/src/config.rs index 9f7de935b4..976ce4c2e7 100644 --- a/crates/registry-evidence/src/config.rs +++ b/crates/registry-evidence/src/config.rs @@ -2496,6 +2496,9 @@ pub const RUNTIME_PACKAGE_CODE: &str = "evidence.runtime.invalid-package"; pub const RUNTIME_LISTENER_CODE: &str = "evidence.runtime.invalid-listener"; pub const RUNTIME_METRICS_LISTENER_CODE: &str = "evidence.runtime.invalid-metrics-listener"; pub const RUNTIME_SECRET_PROVIDERS_CODE: &str = "evidence.runtime.invalid-secret-providers"; +/// The remedy when an Evidence runtime states `mountPolicy`: its frozen +/// Version 1 rule never lets other users read a key file. +pub const COMPOSE_NATIVE_REFUSED_ACTION: &str = "Remove mountPolicy. Stage each secret file owned by the runtime user with mode 0400 or 0600, or owned by root with no bits outside 0640."; pub const RUNTIME_SIGNER_CODE: &str = "evidence.runtime.invalid-signer"; pub const RUNTIME_AUDIT_CODE: &str = "evidence.runtime.invalid-audit"; pub const RUNTIME_OUTBOUND_TLS_CODE: &str = "evidence.runtime.invalid-outbound-tls"; @@ -2842,6 +2845,17 @@ impl RuntimeConfig { )); } } + if self.secret_providers.compose_native_mounts() { + findings.push(RuntimeFinding::at_value( + RUNTIME_SECRET_PROVIDERS_CODE, + "/secretProviders/file/mountPolicy", + ConfigError::InvalidField( + "Evidence keeps the Version 1 secret file rule, so it does not accept mountPolicy", + "secretProviders.file.mountPolicy", + ), + COMPOSE_NATIVE_REFUSED_ACTION, + )); + } self.signer .findings(&self.secret_providers, providers_enabled, &mut findings); self.audit.findings(&mut findings); @@ -10926,6 +10940,40 @@ outboundTls: ) } + #[test] + fn a_compose_native_secret_mount_is_refused_under_the_version_1_key_rule() { + let findings = |text: &str| { + RuntimeConfig::decode_yaml_with( + text.as_bytes(), + DeclaredPosture { + posture: Posture::Production, + source: PostureSource::Default, + }, + |_| None, + ) + .expect("the shared reader accepts the member") + .config + .findings() + }; + let stated = LOADER_RUNTIME_DOCUMENT.replace( + "file: {root: /run/secrets/registry-evidence}", + "file: {root: /run/secrets/registry-evidence, mountPolicy: compose-native}", + ); + assert_ne!(stated, LOADER_RUNTIME_DOCUMENT, "the member is written"); + let refused = findings(&stated); + assert!( + refused + .iter() + .any(|finding| finding.code == RUNTIME_SECRET_PROVIDERS_CODE + && finding.pointer == "/secretProviders/file/mountPolicy" + && finding.action == COMPOSE_NATIVE_REFUSED_ACTION), + "{refused:?}" + ); + assert!(!findings(LOADER_RUNTIME_DOCUMENT) + .iter() + .any(|finding| finding.pointer == "/secretProviders/file/mountPolicy")); + } + #[test] fn a_runtime_file_with_the_retired_api_version_is_refused_with_the_replacement_named() { let retired = LOADER_RUNTIME_DOCUMENT.replace( From 7444eb6371694a81a0107b79647993c12d877bdd Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 21:32:22 +0000 Subject: [PATCH 091/183] feat(platform-config): add a strict secret provider block for operator-local files Saved CLI connections and task connections are read outside any runtime, so nothing reports an explicit production setting for them. Their block enables the same providers without mountPolicy, so the strict file rule always applies. Refs #2882. Signed-off-by: Jeremi Joslin --- crates/registry-platform-config/src/blocks.rs | 74 +++++++++++++++++++ crates/registry-platform-config/src/lib.rs | 8 +- 2 files changed, 78 insertions(+), 4 deletions(-) diff --git a/crates/registry-platform-config/src/blocks.rs b/crates/registry-platform-config/src/blocks.rs index 2127ba6dc9..bea318364a 100644 --- a/crates/registry-platform-config/src/blocks.rs +++ b/crates/registry-platform-config/src/blocks.rs @@ -284,6 +284,80 @@ impl SecretProvidersConfig { } } +/// The secret providers of an operator-local file read outside any runtime, +/// such as a saved CLI connection or a task connection. It enables the same +/// providers as [`SecretProvidersConfig`] but has no `mountPolicy`: nothing +/// reports an explicit production setting for these files, so the strict +/// file rule always applies and the member is refused as unknown. +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[cfg_attr( + feature = "schema", + schemars(extend("anyOf" = [ + {"required": ["file"], "properties": {"file": {"$ref": "#/$defs/StrictFileSecretProviderConfig"}}}, + {"required": ["environment"], "properties": {"environment": {"$ref": "#/$defs/EnvironmentSecretProviderConfig"}}} + ])) +)] +#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct StrictSecretProvidersConfig { + /// Enables `secret:file/name` references, read from files under `root`. + #[serde(default, skip_serializing_if = "Option::is_none")] + #[cfg_attr(feature = "schema", schemars(with = "StrictFileSecretProviderConfig"))] + pub file: Option, + /// Enables `secret:env/NAME` references, read from the process + /// environment. Declared as an empty mapping: `environment: {}`. + #[serde(default, skip_serializing_if = "Option::is_none")] + #[cfg_attr(feature = "schema", schemars(with = "EnvironmentSecretProviderConfig"))] + pub environment: Option, +} + +/// The file secret provider of an operator-local file. +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct StrictFileSecretProviderConfig { + /// 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 user running the tool with mode 0400 or 0600, or owned by root with + /// no access beyond group read (0440 or 0640) when that user is not root. + #[cfg_attr(feature = "schema", schemars(extend("pattern" = "^/")))] + pub root: PathBuf, +} + +impl StrictSecretProvidersConfig { + /// The same providers as a runtime block with no `mountPolicy`, which is + /// how every check and the resolver read them. + #[must_use] + pub fn as_runtime_block(&self) -> SecretProvidersConfig { + SecretProvidersConfig { + file: self + .file + .as_ref() + .map(|file| FileSecretProviderConfig::new(file.root.clone())), + environment: self.environment.clone(), + } + } + + /// See [`SecretProvidersConfig::check`]. + pub fn check(&self) -> Result<(), ConfigBlockError> { + self.as_runtime_block().check() + } + + /// See [`SecretProvidersConfig::check_reference`]. + pub fn check_reference(&self, field: &str, raw: &str) -> Result<(), ConfigBlockError> { + self.as_runtime_block().check_reference(field, raw) + } + + /// A resolver with the strict file rule. See [`SecretProvidersConfig::resolver`]. + pub fn resolver( + &self, + witness: Option<&DevelopmentWitness>, + ) -> Result { + self.as_runtime_block().resolver(witness) + } +} + /// Explain one refused secret reference without disclosing what it protects. /// /// The reference is operator-authored text read from a configuration file, so diff --git a/crates/registry-platform-config/src/lib.rs b/crates/registry-platform-config/src/lib.rs index e2fc8a6ddd..d8038ce1eb 100644 --- a/crates/registry-platform-config/src/lib.rs +++ b/crates/registry-platform-config/src/lib.rs @@ -43,10 +43,10 @@ pub use blocks::{ JwksSource, ListenerBind, ListenerConfig, ListenerNetworkExposure, MetricsListenerConfig, ObjectStorageConfig, OidcClientsConfig, OidcIssuerConfig, OidcPackageClientsConfig, PackageClients, PackageClientsError, PackageConfig, PackageDigestMismatch, PermittedTransport, - 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, + PrivateListenerConfig, SecretProvidersConfig, StrictFileSecretProviderConfig, + StrictSecretProvidersConfig, 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, MAX_ASSERTION_ISSUER_CLIENT_BYTES, MAX_ATTEMPT_TIMEOUT_MILLISECONDS, MAX_HOOK_ATTEMPTS, MAX_HOOK_ATTEMPT_TIMEOUT_MILLISECONDS, MAX_HOOK_DESTINATIONS, MAX_LISTENER_BIND_CHARACTERS, From 555c02042461848ab7f685fb27600c6609912931 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 21:32:23 +0000 Subject: [PATCH 092/183] fix(cli-api,thunderid-tooling): refuse mountPolicy in connection files The saved-connection and task-connection files use the strict provider block, so mountPolicy is an unknown key there. Their schemas are regenerated with the other generated files. Refs #2882. Signed-off-by: Jeremi Joslin --- crates/registry-cli-api/src/connection.rs | 20 +++++++------- .../tests/connection_store.rs | 27 +++++++++++++++++++ .../examples/journey-fixture/grant.rs | 4 +-- .../src/task_connection.rs | 22 +++++++++++++-- 4 files changed, 59 insertions(+), 14 deletions(-) diff --git a/crates/registry-cli-api/src/connection.rs b/crates/registry-cli-api/src/connection.rs index 6842e2b80f..0799a9f566 100644 --- a/crates/registry-cli-api/src/connection.rs +++ b/crates/registry-cli-api/src/connection.rs @@ -10,8 +10,8 @@ use std::{ use clap::{Args, Subcommand}; use fs2::FileExt as _; use registry_platform_config::{ - AuthoredExpressions, EnvironmentSecretProviderConfig, FileSecretProviderConfig, - SecretProvidersConfig, SecretReference, + AuthoredExpressions, EnvironmentSecretProviderConfig, SecretReference, + StrictFileSecretProviderConfig, StrictSecretProvidersConfig, }; use registry_platform_crypto::PrivateJwk; use registry_platform_httputil::client::{ @@ -176,7 +176,7 @@ struct SavedConnection { #[serde(default, skip_serializing_if = "Option::is_none")] trusted_root_certificates_file: Option, #[serde(default, skip_serializing_if = "Option::is_none")] - secret_providers: Option, + secret_providers: Option, auth: SavedAuth, } @@ -544,7 +544,7 @@ fn add(path: &Path, product: &str, mut args: AddConnectionArgs) -> Result<(), Ap } fn saved_auth( - secret_providers: &mut Option, + secret_providers: &mut Option, mut args: AddConnectionArgs, ) -> Result { let choices = usize::from(args.anonymous) @@ -776,7 +776,7 @@ fn secret( } fn resolve_secret( - providers: Option<&SecretProvidersConfig>, + providers: Option<&StrictSecretProvidersConfig>, reference: &SecretReference, ) -> Result { let providers = providers.ok_or(ApiError::Credential)?; @@ -791,7 +791,7 @@ fn resolve_secret( } fn file_reference( - secret_providers: &mut Option, + secret_providers: &mut Option, path: &Path, ) -> Result { let canonical = path @@ -810,7 +810,7 @@ fn file_reference( "the secret file name must use lowercase letters, digits, '.', '_' or '-'".to_owned(), ) })?; - let providers = secret_providers.get_or_insert_with(SecretProvidersConfig::default); + let providers = secret_providers.get_or_insert_with(StrictSecretProvidersConfig::default); match &providers.file { Some(existing) if existing.root != root => { return Err(ApiError::Usage( @@ -819,7 +819,7 @@ fn file_reference( )); } Some(_) => {} - None => providers.file = Some(FileSecretProviderConfig::new(root)), + None => providers.file = Some(StrictFileSecretProviderConfig { root }), } Ok(reference) } @@ -838,14 +838,14 @@ fn canonical_public_file(path: &Path) -> Result { } fn environment_reference( - secret_providers: &mut Option, + secret_providers: &mut Option, name: &str, ) -> Result { let reference = SecretReference::parse(format!("secret:env/{name}")).map_err(|_| { ApiError::Usage("the token environment variable name is invalid".to_owned()) })?; secret_providers - .get_or_insert_with(SecretProvidersConfig::default) + .get_or_insert_with(StrictSecretProvidersConfig::default) .environment = Some(EnvironmentSecretProviderConfig::default()); Ok(reference) } diff --git a/crates/registry-cli-api/tests/connection_store.rs b/crates/registry-cli-api/tests/connection_store.rs index 9c111e58ba..225d4e89cb 100644 --- a/crates/registry-cli-api/tests/connection_store.rs +++ b/crates/registry-cli-api/tests/connection_store.rs @@ -553,3 +553,30 @@ fn saved_connections_add_show_use_reread_credentials_and_acquire_private_key_jwt b"failure" ); } + +#[test] +fn a_saved_connection_file_refuses_the_compose_mount_policy() { + let _lock = ENVIRONMENT_LOCK + .lock() + .unwrap_or_else(|poison| poison.into_inner()); + let temporary = TempDir::new().unwrap(); + let file = temporary.path().join("connections.yaml"); + let strict = "apiVersion: id.registrystack.org/formats/platform/cli-connections/v1alpha1\nkind: PlatformCliConnections\nconnections:\n - product: breg\n name: offline\n baseUrl: https://registry.example.test/api\n secretProviders:\n file:\n root: /run/registry-cli\n auth:\n type: bearer\n tokenRef: secret:file/token\n"; + let check = |text: &str| { + fs::write(&file, text).unwrap(); + run_connection( + "breg", + ConnectionCommand::Check(CheckConnectionArgs { + file: file.clone(), + deny_warnings: false, + }), + ) + }; + check(strict).expect("the strict provider block passes the offline check"); + let stated = strict.replace( + " root: /run/registry-cli\n", + " root: /run/registry-cli\n mountPolicy: compose-native\n", + ); + let error = check(&stated).expect_err("a saved connection file has no mountPolicy"); + assert_eq!(error.exit_code(), 1); +} diff --git a/crates/registry-thunderid-tooling/examples/journey-fixture/grant.rs b/crates/registry-thunderid-tooling/examples/journey-fixture/grant.rs index f4ec322e2c..7e69792eec 100644 --- a/crates/registry-thunderid-tooling/examples/journey-fixture/grant.rs +++ b/crates/registry-thunderid-tooling/examples/journey-fixture/grant.rs @@ -5,7 +5,7 @@ use std::io::{Read, Write}; use std::os::unix::fs::{DirBuilderExt, MetadataExt, OpenOptionsExt}; use std::path::{Path, PathBuf}; -use registry_platform_config::{SecretProvidersConfig, SecretReference}; +use registry_platform_config::{SecretReference, StrictSecretProvidersConfig}; use registry_platform_crypto::PrivateJwk; use registry_platform_httputil::PeerPolicy; use registry_thunderid_tooling::{ @@ -31,7 +31,7 @@ struct Connection { token_endpoint: String, client_assertion_audience: String, bootstrap_resource: String, - secret_providers: SecretProvidersConfig, + secret_providers: StrictSecretProvidersConfig, clients: BTreeMap, } diff --git a/crates/registry-thunderid-tooling/src/task_connection.rs b/crates/registry-thunderid-tooling/src/task_connection.rs index 800e808cf8..be11bff5f7 100644 --- a/crates/registry-thunderid-tooling/src/task_connection.rs +++ b/crates/registry-thunderid-tooling/src/task_connection.rs @@ -9,7 +9,9 @@ use std::collections::BTreeMap; -use registry_platform_config::{ConfigBlockErrorKind, SecretProvidersConfig, SecretReference}; +use registry_platform_config::{ + ConfigBlockErrorKind, SecretReference, StrictSecretProvidersConfig, +}; use registry_platform_yaml::{ escape_pointer_segment, ApiVersion, Decoded, Diagnostic, Document, EnvelopeRule, Expect, ExternalId, FormatSpec, Reader, RemovedKey, Report, Severity, UniqueList, Url, @@ -78,7 +80,7 @@ pub(crate) struct TaskConnection { /// assertion: an absolute URI without a fragment or user information. pub(crate) bootstrap_resource: ExternalId, /// The providers that resolve each client's `assertionKeyRef`. - pub(crate) secret_providers: SecretProvidersConfig, + pub(crate) secret_providers: StrictSecretProvidersConfig, /// The registered clients, by client id: 1 to 32. A client id is 1 to /// 64 lowercase letters, digits, or `-`, since it also names the header /// file a grant is written to. @@ -454,6 +456,22 @@ clients: ); } + #[test] + fn a_task_connection_refuses_the_compose_mount_policy() { + let text = VALID.replace( + " root: /home/operator/.task-keys\n", + " root: /home/operator/.task-keys\n mountPolicy: compose-native\n", + ); + assert_ne!(text, VALID, "the member is written"); + assert_eq!( + codes(&text), + [pair( + "config.unknown-key", + "/secretProviders/file/mountPolicy" + )] + ); + } + #[test] fn endpoints_are_https_or_loopback_http_without_a_query() { for (endpoint, accepted) in [ From bf6cd5170b4d4156c735033e64b8f992f22c4c54 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 21:33:16 +0000 Subject: [PATCH 093/183] fix(evidencectl): refuse the Compose mount policy in doctor, as the runtime does The Evidence runtime refuses secretProviders.file.mountPolicy under its Version 1 key rule, so doctor reports the same refusal before judging the secret files strictly. Refs #2882. Signed-off-by: Jeremi Joslin --- crates/registry-evidencectl/src/doctor.rs | 18 ++++++++++++ crates/registry-evidencectl/tests/doctor.rs | 31 +++++++++++++++++++++ 2 files changed, 49 insertions(+) diff --git a/crates/registry-evidencectl/src/doctor.rs b/crates/registry-evidencectl/src/doctor.rs index e3d8ac1f16..53391a11b9 100644 --- a/crates/registry-evidencectl/src/doctor.rs +++ b/crates/registry-evidencectl/src/doctor.rs @@ -302,6 +302,24 @@ fn check_secrets( let mut root_run = CheckRun::new("secret root", project); root_run.read_declaration(); + // Evidence keeps the Version 1 secret file rule and refuses the Compose + // mount policy, so doctor refuses it too. Every other file then gets the + // strict verdict the runtime gives below. + if runtime + .get("secretProviders") + .and_then(|providers| providers.get("file")) + .and_then(|file| file.get("mountPolicy")) + .is_some() + { + root_run.refuse( + runtime_path, + "/secretProviders/file/mountPolicy (evidence.runtime.invalid-secret-providers): \ + Evidence keeps the Version 1 secret file rule, so it does not accept mountPolicy. \ + Remove mountPolicy. Stage each secret file owned by the runtime user with mode \ + 0400 or 0600, or owned by root with no bits outside 0640." + .to_owned(), + ); + } if let Err(error) = registry_platform_config::validate_secret_root(&root) { let diagnostic = error.diagnostic(); root_run.refuse( diff --git a/crates/registry-evidencectl/tests/doctor.rs b/crates/registry-evidencectl/tests/doctor.rs index 9cf4f7dbf5..f03954fb1b 100644 --- a/crates/registry-evidencectl/tests/doctor.rs +++ b/crates/registry-evidencectl/tests/doctor.rs @@ -84,6 +84,37 @@ fn doctor_passes_a_frozen_project_and_leaves_the_public_key_beside_it_alone() { ); } +#[test] +fn doctor_refuses_the_compose_mount_policy_as_the_runtime_does() { + let workspace = tempfile::tempdir().expect("tempdir"); + let project = workspace.path().join("project"); + provision(&project); + provision_bearer_token(&project); + set_mode(&project.join("secrets"), 0o750); + let runtime = project.join("runtime.yaml"); + let text = fs::read_to_string(&runtime).expect("runtime fixture"); + let stated = text.replace( + " root: secrets\n", + " root: secrets\n mountPolicy: compose-native\n", + ); + assert_ne!(stated, text, "the member is written"); + fs::write(&runtime, stated).expect("runtime fixture"); + + freeze(&project); + let output = doctor(&project, &[]); + unfreeze(&project); + + let stdout = stdout_of(&output); + assert!( + !output.status.success(), + "doctor passed a mount policy the runtime refuses:\n{stdout}" + ); + assert!( + stdout.contains("/secretProviders/file/mountPolicy"), + "{stdout}" + ); +} + #[test] fn doctor_names_every_artifact_whose_mode_the_runtime_refuses() { let workspace = tempfile::tempdir().expect("tempdir"); From 694c425f8b2d0a7db6c6a195a7bddfab985a2e09 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 21:33:16 +0000 Subject: [PATCH 094/183] fix(schedulingctl): read secrets through the runtime's own resolver records, intents and activation built a resolver by hand, dropping the file mount policy and the development witness. They now use the runtime block's resolver, so the tool and the runtime agree. Refs #2882. Signed-off-by: Jeremi Joslin --- crates/registry-schedulingctl/src/records.rs | 25 +++++++------------- 1 file changed, 8 insertions(+), 17 deletions(-) diff --git a/crates/registry-schedulingctl/src/records.rs b/crates/registry-schedulingctl/src/records.rs index d0ec950cd5..dc309bbdba 100644 --- a/crates/registry-schedulingctl/src/records.rs +++ b/crates/registry-schedulingctl/src/records.rs @@ -18,7 +18,7 @@ use std::fs; use std::path::Path; use anyhow::{anyhow, Context, Result}; -use registry_platform_config::{SecretProvider, SecretResolver}; +use registry_platform_config::SecretResolver; use registry_scheduling::audit::{with_event_id, SchedulingAudit}; use registry_scheduling::config::RuntimeConfig; use registry_scheduling::runtime::open_audit; @@ -223,23 +223,14 @@ fn counts(facts: &SchedulingFacts) -> Value { }) } +/// The runtime's own resolver: the providers it enables, its file mount +/// policy and its development witness, so the tool reads a secret exactly +/// as the runtime does. pub(crate) fn secret_resolver(config: &RuntimeConfig) -> Result { - let mut providers = Vec::new(); - if config.secret_providers.file.is_some() { - providers.push(SecretProvider::File); - } - if config.secret_providers.environment.is_some() { - providers.push(SecretProvider::Environment); - } - SecretResolver::new( - providers, - config - .secret_providers - .file - .as_ref() - .map_or_else(|| Path::new(""), |file| file.root.as_path()), - ) - .context("configuring the Scheduling secret providers") + config + .secret_providers + .resolver(config.development_witness()) + .context("configuring the Scheduling secret providers") } #[cfg(test)] From 9c8c9d4206cc9a73cd74fd138177add8230714f3 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 21:37:07 +0000 Subject: [PATCH 095/183] feat(platform-config): name database members and render explicit settings DatabaseMember says which read each database reference takes: the CA bundle is a public document, the URLs are secrets. FoundExplicitSetting and PostureReport render the one-line notice the check commands print. Refs #2882. Signed-off-by: Jeremi Joslin --- crates/registry-platform-config/src/blocks.rs | 56 ++++++++++++++++++- .../src/blocks_tests.rs | 38 +++++++++++++ crates/registry-platform-config/src/lib.rs | 19 ++++--- .../registry-platform-config/src/posture.rs | 23 ++++++++ 4 files changed, 126 insertions(+), 10 deletions(-) diff --git a/crates/registry-platform-config/src/blocks.rs b/crates/registry-platform-config/src/blocks.rs index bea318364a..900c5f1ef2 100644 --- a/crates/registry-platform-config/src/blocks.rs +++ b/crates/registry-platform-config/src/blocks.rs @@ -20,7 +20,8 @@ use serde::{Deserialize, Deserializer, Serialize, Serializer}; use crate::{ DestinationTransport, DevelopmentClass, DevelopmentOnlyRefused, DevelopmentSetting, DevelopmentWitness, ExplicitClass, ExplicitProductionSetting, Gated, PrivateRanges, - SecretError, SecretProvider, SecretReference, SecretResolver, Stated, MAX_SECRET_BYTES, + ProtectedSecret, SecretError, SecretProvider, SecretReference, SecretResolver, Stated, + MAX_SECRET_BYTES, }; /// The schema pattern of a field that must name an enabled secret provider. @@ -420,6 +421,59 @@ pub struct DatabaseConfig { pub transport: Option>, } +/// One secret reference of a database block, and how a tool reads it: the CA +/// bundle is a public document, and each URL is a secret. A provisioning tool +/// names the member it reads, so the read follows the member and a renamed key +/// cannot fall back to the wrong rule. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum DatabaseMember { + RuntimeUrl, + MigrationUrl, + CaBundle, +} + +impl DatabaseMember { + /// The member's key in the database block. + #[must_use] + pub fn key(self) -> &'static str { + match self { + Self::RuntimeUrl => "runtimeUrlRef", + Self::MigrationUrl => "migrationUrlRef", + Self::CaBundle => "caBundleRef", + } + } + + /// Read the member's reference with the rule the member takes. + pub fn read( + self, + resolver: &SecretResolver, + reference: &str, + ) -> Result { + match self { + Self::CaBundle => resolver.resolve_public_document(reference), + Self::RuntimeUrl | Self::MigrationUrl => resolver.resolve(reference), + } + } + + /// [`Self::read`] for a parsed reference. + pub fn read_reference( + self, + resolver: &SecretResolver, + reference: &SecretReference, + ) -> Result { + match self { + Self::CaBundle => resolver.resolve_public_document_reference(reference), + Self::RuntimeUrl | Self::MigrationUrl => resolver.resolve_reference(reference), + } + } +} + +impl fmt::Display for DatabaseMember { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter.write_str(self.key()) + } +} + impl fmt::Debug for DatabaseConfig { fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter diff --git a/crates/registry-platform-config/src/blocks_tests.rs b/crates/registry-platform-config/src/blocks_tests.rs index 74291cc22f..bc28f71074 100644 --- a/crates/registry-platform-config/src/blocks_tests.rs +++ b/crates/registry-platform-config/src/blocks_tests.rs @@ -78,6 +78,44 @@ fn the_resolver_enables_exactly_the_declared_providers() { )); } +#[cfg(unix)] +#[test] +fn a_database_ca_bundle_reads_as_a_public_document_and_a_url_as_a_secret() { + use std::os::unix::fs::PermissionsExt as _; + + let root = tempfile::tempdir().expect("tempdir"); + let canonical = std::fs::canonicalize(root.path()).expect("canonical root"); + let shared = canonical.join("shared"); + std::fs::write(&shared, b"-----BEGIN CERTIFICATE-----\n").expect("write file"); + std::fs::set_permissions(&shared, std::fs::Permissions::from_mode(0o644)).expect("set 0644"); + let resolver = SecretProvidersConfig { + file: Some(FileSecretProviderConfig::new(canonical)), + environment: None, + } + .resolver(None) + .expect("production resolver"); + + assert_eq!(DatabaseMember::CaBundle.key(), "caBundleRef"); + assert_eq!(DatabaseMember::MigrationUrl.to_string(), "migrationUrlRef"); + assert!(DatabaseMember::CaBundle + .read(&resolver, "secret:file/shared") + .is_ok()); + let reference = SecretReference::parse("secret:file/shared").unwrap(); + assert!(DatabaseMember::CaBundle + .read_reference(&resolver, &reference) + .is_ok()); + for member in [DatabaseMember::RuntimeUrl, DatabaseMember::MigrationUrl] { + assert_eq!( + member.read(&resolver, "secret:file/shared").unwrap_err(), + SecretError::UnsafeFile(crate::SecretFileCheck::WorldReadable) + ); + assert_eq!( + member.read_reference(&resolver, &reference).unwrap_err(), + SecretError::UnsafeFile(crate::SecretFileCheck::WorldReadable) + ); + } +} + #[cfg(unix)] #[test] fn secret_providers_resolver_relaxes_secret_file_permissions_only_with_a_development_witness() { diff --git a/crates/registry-platform-config/src/lib.rs b/crates/registry-platform-config/src/lib.rs index d8038ce1eb..1d4a4afa14 100644 --- a/crates/registry-platform-config/src/lib.rs +++ b/crates/registry-platform-config/src/lib.rs @@ -38,15 +38,16 @@ pub use blocks::{ is_sha256_label, plaintext_host_addresses, published_http_issuer_setting, resolve_database_host, url_hook_destinations, AdmittedClients, AttachmentVerifierConfig, AttemptTimeoutMilliseconds, AuditKeyConfig, AuditKeyCustody, CheckedHost, ConfigBlockError, - ConfigBlockErrorKind, DatabaseConfig, DatabaseHost, DatabaseTransport, DatabaseTransportError, - EnvironmentSecretProviderConfig, FileSecretProviderConfig, HostResolver, InsecureHttp, - JwksSource, ListenerBind, ListenerConfig, ListenerNetworkExposure, MetricsListenerConfig, - ObjectStorageConfig, OidcClientsConfig, OidcIssuerConfig, OidcPackageClientsConfig, - PackageClients, PackageClientsError, PackageConfig, PackageDigestMismatch, PermittedTransport, - PrivateListenerConfig, SecretProvidersConfig, StrictFileSecretProviderConfig, - StrictSecretProvidersConfig, 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, + ConfigBlockErrorKind, DatabaseConfig, DatabaseHost, DatabaseMember, DatabaseTransport, + DatabaseTransportError, EnvironmentSecretProviderConfig, FileSecretProviderConfig, + HostResolver, InsecureHttp, JwksSource, ListenerBind, ListenerConfig, ListenerNetworkExposure, + MetricsListenerConfig, ObjectStorageConfig, OidcClientsConfig, OidcIssuerConfig, + OidcPackageClientsConfig, PackageClients, PackageClientsError, PackageConfig, + PackageDigestMismatch, PermittedTransport, PrivateListenerConfig, SecretProvidersConfig, + StrictFileSecretProviderConfig, StrictSecretProvidersConfig, 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, MAX_ASSERTION_ISSUER_CLIENT_BYTES, MAX_ATTEMPT_TIMEOUT_MILLISECONDS, MAX_HOOK_ATTEMPTS, MAX_HOOK_ATTEMPT_TIMEOUT_MILLISECONDS, MAX_HOOK_DESTINATIONS, MAX_LISTENER_BIND_CHARACTERS, diff --git a/crates/registry-platform-config/src/posture.rs b/crates/registry-platform-config/src/posture.rs index 22065ef648..ba82c72fa4 100644 --- a/crates/registry-platform-config/src/posture.rs +++ b/crates/registry-platform-config/src/posture.rs @@ -451,6 +451,20 @@ pub struct FoundExplicitSetting { pub origin: SettingOrigin, } +impl FoundExplicitSetting { + /// The one line a command prints for this setting, as the check commands + /// print it: the code, the member and what the setting relaxes. + #[must_use] + pub fn notice(&self) -> String { + format!( + "Explicit production setting {} at {}. {}.", + self.setting.code, + self.pointer.as_deref().unwrap_or_default(), + self.setting.summary + ) + } +} + /// What one decode found: the development-only settings a [`Gated`] recorded /// and the explicit production settings a [`Stated`] recorded. #[derive(Clone, Debug, Default)] @@ -559,6 +573,15 @@ impl PostureReport { &self.explicit } + /// [`FoundExplicitSetting::notice`] for each explicit production setting. + #[must_use] + pub fn explicit_setting_notices(&self) -> Vec { + self.explicit + .iter() + .map(FoundExplicitSetting::notice) + .collect() + } + /// The one decision. Production refuses every recorded setting and /// development accepts and lists them, under the same codes. #[must_use] From 8e715bcaab7c425bc720db1051553b8fcf9508aa Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 21:37:07 +0000 Subject: [PATCH 096/183] feat(provision): read each database member by kind and print explicit settings The provisioning tools pass a DatabaseMember instead of matching the caBundleRef string, so a renamed key cannot fall back to the wrong read. Each tool hands the runner the explicit production settings its runtime file states, and the runner prints them on stderr as the runtime logs them. The Evidence store-provision document uses the strict provider block, so it refuses mountPolicy like the Evidence runtime. Refs #2882. Signed-off-by: Jeremi Joslin --- .../registry-adapterctl/src/job_provision.rs | 20 ++++++------- crates/registry-adapterctl/src/provision.rs | 26 ++++++++--------- crates/registry-bregctl/src/provision.rs | 19 ++++++------- crates/registry-caseworkctl/src/provision.rs | 2 ++ crates/registry-coordinator/src/provision.rs | 7 ++++- crates/registry-documentsctl/src/provision.rs | 27 ++++++++++-------- .../src/store_provision.rs | 27 +++++++++--------- crates/registry-messagingctl/src/provision.rs | 23 ++++++++------- crates/registry-platform-provision/src/cli.rs | 28 +++++++++++++++++++ .../registry-schedulingctl/src/provision.rs | 23 ++++++++------- 10 files changed, 115 insertions(+), 87 deletions(-) diff --git a/crates/registry-adapterctl/src/job_provision.rs b/crates/registry-adapterctl/src/job_provision.rs index df6bc745b5..04d74553d4 100644 --- a/crates/registry-adapterctl/src/job_provision.rs +++ b/crates/registry-adapterctl/src/job_provision.rs @@ -4,7 +4,7 @@ use std::path::Path; use registry_adapter::engine::job_sources::{job_runtime_diagnostic, JobRuntimeConfig}; use registry_adapter_core::ADAPTER_JOB_RUNTIME_KIND; -use registry_platform_config::{describe_secret_failure, DeclaredPosture}; +use registry_platform_config::{describe_secret_failure, DatabaseMember, DeclaredPosture}; use registry_platform_provision::{ provision_transport, ProductDatabase, ProvisionInput, SchemaLayout, }; @@ -79,13 +79,8 @@ pub(crate) fn load( error.suggested_action(), ) })?; - let resolve = |member: &str, reference: &SecretReference| { - // The CA bundle is a public document; the URLs are secrets. - let read = if member == "caBundleRef" { - resolver.resolve_public_document(reference.as_str()) - } else { - resolver.resolve(reference.as_str()) - }; + let resolve = |member: DatabaseMember, reference: &SecretReference| { + let read = member.read(&resolver, reference.as_str()); read.map_err(|error| { refuse( &format!("/store/{member}"), @@ -94,7 +89,7 @@ pub(crate) fn load( ) }) }; - let url = |member: &str, reference: &SecretReference| { + let url = |member: DatabaseMember, reference: &SecretReference| { let secret = resolve(member, reference)?; std::str::from_utf8(secret.expose_secret()) .map(|text| Zeroizing::new(text.trim().to_owned())) @@ -113,14 +108,15 @@ pub(crate) fn load( btree_gist: false, spatial: None, }, - migration_url: url("migrationUrlRef", migration)?, - runtime_url: url("runtimeUrlRef", &store.runtime_url_ref)?, + migration_url: url(DatabaseMember::MigrationUrl, migration)?, + runtime_url: url(DatabaseMember::RuntimeUrl, &store.runtime_url_ref)?, ca_pem: store .ca_bundle_ref .as_ref() - .map(|reference| resolve("caBundleRef", reference)) + .map(|reference| resolve(DatabaseMember::CaBundle, reference)) .transpose()? .map(|secret| secret.expose_secret().to_vec()), transport: provision_transport(&store.database_config()), + explicit_settings: runtime.posture.explicit_setting_notices(), }) } diff --git a/crates/registry-adapterctl/src/provision.rs b/crates/registry-adapterctl/src/provision.rs index 88ba0eb0f3..449dc3b821 100644 --- a/crates/registry-adapterctl/src/provision.rs +++ b/crates/registry-adapterctl/src/provision.rs @@ -11,8 +11,8 @@ use registry_adapter_core::{ ADAPTER_RUNTIME_KIND, }; use registry_platform_config::{ - describe_secret_failure, DeclaredPosture, RuntimeConfigLoader, RuntimeEnvelope, SecretProvider, - SecretResolver, + describe_secret_failure, DatabaseMember, DeclaredPosture, RuntimeConfigLoader, RuntimeEnvelope, + SecretProvider, SecretResolver, }; use registry_platform_provision::{ provision_transport, ProductDatabase, ProvisionInput, SchemaLayout, @@ -64,6 +64,7 @@ pub(crate) fn load( .removed_keys(ADAPTER_FACADE_REMOVED_KEYS) .load::(&absolute) .map_err(|error| error.diagnostics().to_vec())?; + let explicit_settings = loaded.posture.explicit_setting_notices(); let config = loaded.config; let secrets = match config.secret_providers.as_ref() { Some(providers) => providers.resolver(loaded.development.as_ref()), @@ -77,13 +78,8 @@ pub(crate) fn load( "Correct secretProviders in the runtime file, then run provision again.", ) })?; - let resolve = |member: &str, reference: &str| { - // The CA bundle is a public document; the URLs are secrets. - let read = if member == "caBundleRef" { - secrets.resolve_public_document(reference) - } else { - secrets.resolve(reference) - }; + let resolve = |member: DatabaseMember, reference: &str| { + let read = member.read(&secrets, reference); read.map_err(|error| { refuse( "config.refused", @@ -93,7 +89,7 @@ pub(crate) fn load( ) }) }; - let url = |member: &str, reference: &str| { + let url = |member: DatabaseMember, reference: &str| { let secret = resolve(member, reference)?; std::str::from_utf8(secret.expose_secret()) .map(|text| Zeroizing::new(text.trim().to_owned())) @@ -106,13 +102,16 @@ pub(crate) fn load( ) }) }; - let migration_url = url("migrationUrlRef", &config.database.migration_url_ref)?; - let runtime_url = url("runtimeUrlRef", &config.database.runtime_url_ref)?; + let migration_url = url( + DatabaseMember::MigrationUrl, + &config.database.migration_url_ref, + )?; + let runtime_url = url(DatabaseMember::RuntimeUrl, &config.database.runtime_url_ref)?; let ca_pem = config .database .ca_bundle_ref .as_deref() - .map(|reference| resolve("caBundleRef", reference)) + .map(|reference| resolve(DatabaseMember::CaBundle, reference)) .transpose()? .map(|secret| secret.expose_secret().to_vec()); Ok(ProvisionInput { @@ -121,5 +120,6 @@ pub(crate) fn load( runtime_url, ca_pem, transport: provision_transport(&config.database), + explicit_settings, }) } diff --git a/crates/registry-bregctl/src/provision.rs b/crates/registry-bregctl/src/provision.rs index 7b1c23c9ff..03f4e1c559 100644 --- a/crates/registry-bregctl/src/provision.rs +++ b/crates/registry-bregctl/src/provision.rs @@ -16,6 +16,7 @@ use registry_breg::runtime_config::{ load_runtime_config_without_package_root, RuntimeConfig, RuntimeConfigError, RUNTIME_CONFIG_KIND, }; +use registry_platform_config::DatabaseMember; use registry_platform_provision::{ provision_transport, ProductDatabase, ProvisionInput, SchemaLayout, Spatial, }; @@ -92,13 +93,8 @@ pub(crate) fn load( let secrets = config .secret_resolver() .map_err(|error| runtime_file_refused(&absolute, &error))?; - let resolve = |member: &str, reference| { - // The CA bundle is a public document; the URLs are secrets. - let read = if member == "caBundleRef" { - secrets.resolve_public_document_reference(reference) - } else { - secrets.resolve_reference(reference) - }; + let resolve = |member: DatabaseMember, reference| { + let read = member.read_reference(&secrets, reference); read.map_err(|_| { refused( "config.refused", @@ -108,7 +104,7 @@ pub(crate) fn load( ) }) }; - let url = |member: &str, reference| { + let url = |member: DatabaseMember, reference| { let secret = resolve(member, reference)?; std::str::from_utf8(secret.expose_secret()) .map(|text| Zeroizing::new(text.trim().to_owned())) @@ -122,11 +118,11 @@ pub(crate) fn load( }) }; let database = config.database(); - let migration_url = url("migrationUrlRef", database.migration_url_ref())?; - let runtime_url = url("runtimeUrlRef", database.runtime_url_ref())?; + let migration_url = url(DatabaseMember::MigrationUrl, database.migration_url_ref())?; + let runtime_url = url(DatabaseMember::RuntimeUrl, database.runtime_url_ref())?; let ca_pem = database .ca_bundle_ref() - .map(|reference| resolve("caBundleRef", reference)) + .map(|reference| resolve(DatabaseMember::CaBundle, reference)) .transpose()? .map(|secret| secret.expose_secret().to_vec()); let spatial = package @@ -144,5 +140,6 @@ pub(crate) fn load( runtime_url, ca_pem, transport: provision_transport(database.transport_config()), + explicit_settings: config.posture_report().explicit_setting_notices(), }) } diff --git a/crates/registry-caseworkctl/src/provision.rs b/crates/registry-caseworkctl/src/provision.rs index b5c1ae4cfa..bf8b0e0f88 100644 --- a/crates/registry-caseworkctl/src/provision.rs +++ b/crates/registry-caseworkctl/src/provision.rs @@ -49,6 +49,7 @@ fn load(path: &Path, declared: DeclaredPosture) -> Result Result Result RuntimeConfigLoader { @@ -253,13 +253,8 @@ fn load(path: &Path, declared: DeclaredPosture) -> Result Result Result>, /// How the runtime connects to PostgreSQL, from `database.transport`. pub transport: DatabaseTransport, + /// One notice per explicit production setting the runtime file states, + /// from [`registry_platform_config::FoundExplicitSetting::notice`]. The + /// runner writes each to stderr, as the runtime logs it at startup. + pub explicit_settings: Vec, } /// Result class of a run, as in every other verb's report. @@ -796,6 +800,11 @@ fn run_with( return output.refusal(&report); } }; + for notice in &input.explicit_settings { + // A notice that cannot reach stderr leaves nothing else to tell; the + // run continues and the report still carries its outcome. + let _ = writeln!(output.stderr, "{notice}"); + } report.product = Some(input.product.product.to_owned()); let dotted_section = section.replace('/', "."); let (Some(migration), Some(runtime)) = ( @@ -1160,6 +1169,7 @@ mod tests { runtime_url: Zeroizing::new(runtime.to_owned()), ca_pem: None, transport: DatabaseTransport::VerifiedTls, + explicit_settings: Vec::new(), } } @@ -1394,6 +1404,22 @@ mod tests { // ---- print mode ---- + #[test] + fn the_runtime_file_explicit_settings_are_printed_on_stderr() { + let notice = "Explicit production setting platform.posture.compose-native-secret-mount at /secretProviders/file/mountPolicy. The file secret provider accepts root-owned, mode 0444 Compose mounts."; + for arguments in [ + &["--print-sql"][..], + &["--print-sql", "--format", "json"][..], + ] { + let mut input = split_input(); + input.explicit_settings = vec![notice.to_owned()]; + let run = execute_run(arguments, None, Ok(input), &must_not_run); + assert_eq!(run.exit, 0, "{}", run.all_output()); + assert!(run.stderr.contains(notice), "{arguments:?}: {}", run.stderr); + assert!(!run.stdout.contains(notice), "{arguments:?}"); + } + } + #[test] fn print_mode_writes_only_the_script_to_stdout() { let run = execute_run(&["--print-sql"], None, Ok(split_input()), &must_not_run); @@ -2683,6 +2709,7 @@ mod tests { runtime_url: input.runtime_url.clone(), ca_pem: None, transport: DatabaseTransport::LoopbackPlaintext, + explicit_settings: Vec::new(), }), &created_everything, declared, @@ -2941,6 +2968,7 @@ mod postgres_tests { )), ca_pem: Some(ca.clone()), transport: DatabaseTransport::VerifiedTls, + explicit_settings: Vec::new(), }; let _cleanup = Cleanup { admin: admin_config(&admin_url, Some(&ca)).expect("administrator config"), diff --git a/crates/registry-schedulingctl/src/provision.rs b/crates/registry-schedulingctl/src/provision.rs index 34c1aedacf..d123514d9d 100644 --- a/crates/registry-schedulingctl/src/provision.rs +++ b/crates/registry-schedulingctl/src/provision.rs @@ -6,7 +6,7 @@ use std::path::Path; -use registry_platform_config::describe_secret_failure; +use registry_platform_config::{describe_secret_failure, DatabaseMember}; use registry_platform_provision::{ provision_transport, ProductDatabase, ProvisionInput, SchemaLayout, }; @@ -74,13 +74,8 @@ pub(crate) fn load( "Correct secretProviders in the runtime file, then run provision again.", ) })?; - let resolve = |member: &str, reference: &str| { - // The CA bundle is a public document; the URLs are secrets. - let read = if member == "caBundleRef" { - secrets.resolve_public_document(reference) - } else { - secrets.resolve(reference) - }; + let resolve = |member: DatabaseMember, reference: &str| { + let read = member.read(&secrets, reference); read.map_err(|error| { refuse( "config.refused", @@ -90,7 +85,7 @@ pub(crate) fn load( ) }) }; - let url = |member: &str, reference: &str| { + let url = |member: DatabaseMember, reference: &str| { let secret = resolve(member, reference)?; std::str::from_utf8(secret.expose_secret()) .map(|text| Zeroizing::new(text.trim().to_owned())) @@ -103,13 +98,16 @@ pub(crate) fn load( ) }) }; - let migration_url = url("migrationUrlRef", &config.database.migration_url_ref)?; - let runtime_url = url("runtimeUrlRef", &config.database.runtime_url_ref)?; + let migration_url = url( + DatabaseMember::MigrationUrl, + &config.database.migration_url_ref, + )?; + let runtime_url = url(DatabaseMember::RuntimeUrl, &config.database.runtime_url_ref)?; let ca_pem = config .database .ca_bundle_ref .as_deref() - .map(|reference| resolve("caBundleRef", reference)) + .map(|reference| resolve(DatabaseMember::CaBundle, reference)) .transpose()? .map(|secret| secret.expose_secret().to_vec()); Ok(ProvisionInput { @@ -118,5 +116,6 @@ pub(crate) fn load( runtime_url, ca_pem, transport: provision_transport(&config.database), + explicit_settings: config.posture_report().explicit_setting_notices(), }) } From 6ea31b06e6d280cbdf005f617c4b21794ad96ec6 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 21:39:37 +0000 Subject: [PATCH 097/183] fix(platform-config): word public-document refusals for public documents A refused public document (a static JWKS or a CA bundle) now reports UnsafePublicDocument with public wording and remedies, never the secret file's mode advice. A public document holding a PEM private key block is refused, since it may be readable by everyone. The callers that match secret errors exhaustively gain the two arms. Refs #2882. Signed-off-by: Jeremi Joslin --- crates/registry-adapter-engine/src/load.rs | 2 + .../registry-adapter-job/src/hook_ingress.rs | 2 + crates/registry-breg/src/runtime_config.rs | 21 ++++- crates/registry-platform-config/src/blocks.rs | 10 +++ .../registry-platform-config/src/secrets.rs | 85 ++++++++++++++++++- .../src/secrets_tests.rs | 78 +++++++++++++++-- 6 files changed, 187 insertions(+), 11 deletions(-) diff --git a/crates/registry-adapter-engine/src/load.rs b/crates/registry-adapter-engine/src/load.rs index 35c0fd49ee..cb725c69b6 100644 --- a/crates/registry-adapter-engine/src/load.rs +++ b/crates/registry-adapter-engine/src/load.rs @@ -517,6 +517,8 @@ fn secret_refusal_fix(error: &SecretError) -> &'static str { "create the file under secretProviders.file.root or set the variable" } SecretError::UnsafeFile(check) => check.suggested_action(), + SecretError::UnsafePublicDocument(check) => check.public_suggested_action(), + SecretError::PrivateKeyInPublicDocument => error.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" diff --git a/crates/registry-adapter-job/src/hook_ingress.rs b/crates/registry-adapter-job/src/hook_ingress.rs index e4f67c6c31..22b6849e76 100644 --- a/crates/registry-adapter-job/src/hook_ingress.rs +++ b/crates/registry-adapter-job/src/hook_ingress.rs @@ -436,6 +436,8 @@ fn resolve_member( } SecretError::Unavailable => "the secret file is missing", SecretError::UnsafeFile(check) => check.suggested_action(), + SecretError::UnsafePublicDocument(check) => check.public_suggested_action(), + SecretError::PrivateKeyInPublicDocument => error.suggested_action(), SecretError::Read => "the secret file could not be read", SecretError::InvalidValue => "the secret is empty or contains a NUL byte", SecretError::ProviderDisabled => { diff --git a/crates/registry-breg/src/runtime_config.rs b/crates/registry-breg/src/runtime_config.rs index ee74636545..37725e8c2b 100644 --- a/crates/registry-breg/src/runtime_config.rs +++ b/crates/registry-breg/src/runtime_config.rs @@ -545,6 +545,10 @@ pub enum RuntimeConfigError { Secret, #[error("runtime configuration secret file refused: {} ({})", .0.message(), .0.code())] SecretFile(SecretFileCheck), + #[error("runtime configuration public document refused: {} ({})", .0.public_message(), .0.code())] + PublicDocumentFile(SecretFileCheck), + #[error("runtime configuration public document holds a PEM private key block")] + PublicDocumentPrivateKey, } /// The config path of the exposure key a wildcard metrics refusal names. @@ -597,7 +601,10 @@ impl RuntimeConfigError { Self::InvalidBounds => "breg.runtime.invalid-bounds", Self::PoolBudgetExceeded => "breg.runtime.pool-budget-exceeded", Self::InvalidWasmExecution => "breg.runtime.invalid-wasm-execution", - Self::Secret | Self::SecretFile(_) => "breg.runtime.secret", + Self::Secret + | Self::SecretFile(_) + | Self::PublicDocumentFile(_) + | Self::PublicDocumentPrivateKey => "breg.runtime.secret", } } @@ -606,7 +613,11 @@ impl RuntimeConfigError { fn path(&self) -> &str { match self { Self::Reader(refusal) => &refusal.deciding_diagnostic().path, - Self::InvalidBinding | Self::Secret | Self::SecretFile(_) => "", + Self::InvalidBinding + | Self::Secret + | Self::SecretFile(_) + | Self::PublicDocumentFile(_) + | Self::PublicDocumentPrivateKey => "", Self::InvalidExternalSource { path, .. } | Self::InvalidDeliveryKey { path, .. } | Self::DuplicateCompletionRecipient { path, .. } => path, @@ -746,6 +757,10 @@ impl RuntimeConfigError { "Make every secret reference resolve through the declared secret providers." } Self::SecretFile(check) => check.suggested_action(), + Self::PublicDocumentFile(check) => check.public_suggested_action(), + Self::PublicDocumentPrivateKey => { + SecretError::PrivateKeyInPublicDocument.suggested_action() + } } } @@ -818,6 +833,8 @@ impl From for RuntimeConfigError { fn from(error: SecretError) -> Self { match error { SecretError::UnsafeFile(check) => Self::SecretFile(check), + SecretError::UnsafePublicDocument(check) => Self::PublicDocumentFile(check), + SecretError::PrivateKeyInPublicDocument => Self::PublicDocumentPrivateKey, _ => Self::Secret, } } diff --git a/crates/registry-platform-config/src/blocks.rs b/crates/registry-platform-config/src/blocks.rs index 900c5f1ef2..c898b2d388 100644 --- a/crates/registry-platform-config/src/blocks.rs +++ b/crates/registry-platform-config/src/blocks.rs @@ -384,6 +384,16 @@ pub fn describe_secret_failure(field: &str, _reference: &str, error: &SecretErro check.code(), check.suggested_action() ), + SecretError::UnsafePublicDocument(check) => format!( + "{} ({}). {}", + check.public_message(), + check.code(), + check.public_suggested_action() + ), + SecretError::PrivateKeyInPublicDocument => format!( + "the public document holds a PEM private key block. {}", + error.suggested_action() + ), SecretError::Read => "the secret could not be read".to_owned(), SecretError::InvalidValue => format!( "the secret value must be non-empty text of at most {MAX_SECRET_BYTES} bytes \ diff --git a/crates/registry-platform-config/src/secrets.rs b/crates/registry-platform-config/src/secrets.rs index b705974b52..844e4a3831 100644 --- a/crates/registry-platform-config/src/secrets.rs +++ b/crates/registry-platform-config/src/secrets.rs @@ -193,6 +193,13 @@ pub enum SecretError { Unavailable, #[error("the referenced secret file is unsafe")] UnsafeFile(SecretFileCheck), + /// A public document's file failed a check. The check is the one a + /// secret file fails, worded for a document anyone may read. + #[error("the referenced public document file is unsafe")] + UnsafePublicDocument(SecretFileCheck), + /// A public document holds a PEM private key block. + #[error("the referenced public document holds a private key")] + PrivateKeyInPublicDocument, #[error("the referenced secret could not be read")] Read, #[error("the referenced secret value is invalid")] @@ -218,6 +225,10 @@ impl SecretError { "Create the secret under the configured provider, or correct the name." } Self::UnsafeFile(check) => check.suggested_action(), + Self::UnsafePublicDocument(check) => check.public_suggested_action(), + Self::PrivateKeyInPublicDocument => { + "Put only certificates or public keys in the document, and keep the private key in its own secret file." + } 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." @@ -326,6 +337,51 @@ impl SecretFileCheck { } } + /// [`Self::message`] for a public document such as a JWKS or a CA bundle. + #[must_use] + pub const fn public_message(self) -> &'static str { + match self { + Self::LinkLeavesRoot => { + "the public document is reached through a link that leaves secretProviders.file.root" + } + Self::TooManyLinks => "the public document is reached through more than 8 links", + Self::CannotOpen => "the runtime user cannot open the public document", + Self::NotRegular => "the public document is not a regular file", + Self::HardLinked => "the public document has more than one hard link", + Self::Owner => "the public document is owned by neither the runtime user nor root", + Self::WorldWritable => { + "users outside the file's owner and group can write the public document" + } + Self::WorldReadable | Self::GroupAccess => "the public document's group can write or execute it", + Self::ModeBits => { + "the public document has an execute, setuid, setgid or sticky bit, or its owner cannot read it" + } + } + } + + /// [`Self::suggested_action`] for a public document: anyone may read it, + /// so only who can change it matters. + #[must_use] + pub const fn public_suggested_action(self) -> &'static str { + match self { + Self::LinkLeavesRoot + | Self::TooManyLinks + | Self::NotRegular + | Self::HardLinked => self.suggested_action(), + Self::CannotOpen => { + "Let the runtime user read the file, for example mode 0644, or 0444 owned by root." + } + Self::Owner => "Give the file to the runtime user or to root.", + Self::WorldWritable => "Remove write access for others (chmod o-w).", + Self::WorldReadable | Self::GroupAccess => { + "Remove group write and execute (chmod g-wx)." + } + Self::ModeBits => { + "Clear the execute, setuid, setgid and sticky bits, and let the owner read the file, for example mode 0644." + } + } + } + /// Whether a development process loads the file with a warning instead of /// refusing it. Production refuses every check. #[must_use] @@ -477,6 +533,7 @@ impl SecretResolver { /// [`Self::resolve_public_document_reference`] applies. pub fn inspect_public_document(&self, reference: &SecretReference) -> Result<(), SecretError> { self.inspect_with(reference, self.public_access()) + .map_err(public_document_error) } fn inspect_with( @@ -516,7 +573,17 @@ impl SecretResolver { &self, reference: &SecretReference, ) -> Result { - validate_secret(self.read_with(reference, self.public_access())?.0) + let document = validate_secret( + self.read_with(reference, self.public_access()) + .map_err(public_document_error)? + .0, + )?; + // A public document may be readable by everyone, so a private key + // staged in it by mistake is refused rather than loaded. + if holds_pem_private_key(document.expose_secret()) { + return Err(SecretError::PrivateKeyInPublicDocument); + } + Ok(document) } fn public_access(&self) -> FileAccess { @@ -670,6 +737,22 @@ fn judge( } } +/// A file refusal from a public-document read names the public document. +fn public_document_error(error: SecretError) -> SecretError { + match error { + SecretError::UnsafeFile(check) => SecretError::UnsafePublicDocument(check), + other => other, + } +} + +/// Whether `bytes` hold a PEM private key block of any kind: PKCS #8 +/// (encrypted or not), RSA, EC, DSA or OpenSSH. +fn holds_pem_private_key(bytes: &[u8]) -> bool { + bytes + .windows(b"PRIVATE KEY-----".len()) + .any(|window| window == b"PRIVATE KEY-----") +} + /// Walk `name` from the root by openat steps, following only relative /// downward links, then judge the descriptor that will be read. #[cfg(unix)] diff --git a/crates/registry-platform-config/src/secrets_tests.rs b/crates/registry-platform-config/src/secrets_tests.rs index 51acf33774..cc943c4057 100644 --- a/crates/registry-platform-config/src/secrets_tests.rs +++ b/crates/registry-platform-config/src/secrets_tests.rs @@ -344,18 +344,80 @@ mod filesystem { let resolver = resolver(root.path()); assert_eq!( load_public(&resolver, "group-writable.json"), - Err(SecretError::UnsafeFile(GroupAccess)) + Err(SecretError::UnsafePublicDocument(GroupAccess)) ); assert_eq!( load_public(&resolver, "world-writable.json"), - Err(SecretError::UnsafeFile(WorldWritable)) + Err(SecretError::UnsafePublicDocument(WorldWritable)) ); - assert_eq!( - load_public(&resolver, "escape"), - load(&resolver, "escape"), - "an absolute link is refused as it is for a secret" - ); - assert!(load_public(&resolver, "escape").is_err()); + // An absolute link is refused by the check that refuses it for a + // secret, worded for a public document. + match (load_public(&resolver, "escape"), load(&resolver, "escape")) { + ( + Err(SecretError::UnsafePublicDocument(public)), + Err(SecretError::UnsafeFile(secret)), + ) => assert_eq!(public, secret), + other => panic!("{other:?}"), + } + } + + #[test] + fn a_public_document_refusal_gives_public_document_advice() { + let root = tempfile::tempdir().expect("root"); + write(root.path(), "group-writable.json", 0o664); + let error = load_public(&resolver(root.path()), "group-writable.json").unwrap_err(); + let SecretError::UnsafePublicDocument(check) = error else { + panic!("{error:?}"); + }; + for text in [ + check.public_message(), + check.public_suggested_action(), + error.suggested_action(), + ] { + assert!(!text.contains("secret file"), "{text}"); + assert!(!text.contains("0400 or 0600"), "{text}"); + } + let described = crate::describe_secret_failure("jwksSource.documentRef", "", &error); + assert!(described.contains("public document"), "{described}"); + assert!(!described.contains("0400 or 0600"), "{described}"); + } + + #[test] + fn a_public_document_holding_a_private_key_is_refused() { + let root = tempfile::tempdir().expect("root"); + for (name, block) in [ + ("pkcs8.pem", "PRIVATE KEY"), + ("rsa.pem", "RSA PRIVATE KEY"), + ("ec.pem", "EC PRIVATE KEY"), + ("encrypted.pem", "ENCRYPTED PRIVATE KEY"), + ] { + let path = root.path().join(name); + fs::write( + &path, + format!( + "-----BEGIN CERTIFICATE-----\nMIIB\n-----END CERTIFICATE-----\n\ + -----BEGIN {block}-----\nMIIE\n-----END {block}-----\n" + ), + ) + .expect("write"); + fs::set_permissions(&path, fs::Permissions::from_mode(0o644)).expect("mode"); + } + let resolver = resolver(root.path()); + for name in ["pkcs8.pem", "rsa.pem", "ec.pem", "encrypted.pem"] { + assert_eq!( + load_public(&resolver, name), + Err(SecretError::PrivateKeyInPublicDocument), + "{name}" + ); + } + let bundle = root.path().join("ca.pem"); + fs::write( + &bundle, + "-----BEGIN CERTIFICATE-----\nMIIB\n-----END CERTIFICATE-----\n", + ) + .expect("write"); + fs::set_permissions(&bundle, fs::Permissions::from_mode(0o644)).expect("mode"); + assert!(load_public(&resolver, "ca.pem").is_ok()); } #[test] From 3c3b1186cb1b103c35f63a9ede86601f9830551e Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 21:39:37 +0000 Subject: [PATCH 098/183] fix(breg): refuse a private member in the Evidence trusted key set trustedJwksRef may now name a world-readable file, so it is parsed with the shared public key-set rule, which refuses private and symmetric members, as every other static JWKS read does. Refs #2882. Signed-off-by: Jeremi Joslin --- .../src/action_evidence_config.rs | 31 +++++++++++++++++-- 1 file changed, 29 insertions(+), 2 deletions(-) diff --git a/crates/registry-breg/src/action_evidence_config.rs b/crates/registry-breg/src/action_evidence_config.rs index dbf9ef48e9..f3613baf8d 100644 --- a/crates/registry-breg/src/action_evidence_config.rs +++ b/crates/registry-breg/src/action_evidence_config.rs @@ -104,7 +104,9 @@ pub fn activate( let keys = secrets .resolve_public_document_reference(&binding.trusted_jwks_ref) .map_err(|_| Error::Secret)?; - let jwks = registry_platform_crypto::parse_json_strict(keys.expose_secret()) + // The key set may be readable by everyone, so it must hold public keys + // only: a private or symmetric member is refused, not loaded. + let jwks = registry_platform_oidc::public_jwks_document(keys.expose_secret()) .map_err(|_| Error::InvalidBinding)?; let jwks = serde_json::from_value(jwks).map_err(|_| Error::InvalidBinding)?; let mut config = registry_evidence_client::EvidenceClientConfig::new( @@ -422,11 +424,36 @@ mod tests { }; assert!(activate( &compiled, - &BTreeMap::from([("farmer-registry".into(), binding)]), + &BTreeMap::from([("farmer-registry".into(), binding.clone())]), &secrets, registry_platform_httputil::PeerPolicy::RefuseDevelopmentPeer, ) .unwrap() .is_some()); + + // The same key set with a private member staged by mistake. + let public = std::fs::read_to_string(directory.path().join("jwks")).unwrap(); + let private = public.replacen( + "\"kty\": \"EC\",", + "\"kty\": \"EC\",\n \"d\": \"AAAA\",", + 1, + ); + assert_ne!(private, public, "the private member is written"); + let path = directory.path().join("private-jwks"); + std::fs::write(&path, private).unwrap(); + std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o644)).unwrap(); + let binding = EvidenceProviderConfig { + trusted_jwks_ref: SecretReference::parse("secret:file/private-jwks").unwrap(), + ..binding + }; + assert!(matches!( + activate( + &compiled, + &BTreeMap::from([("farmer-registry".into(), binding)]), + &secrets, + registry_platform_httputil::PeerPolicy::RefuseDevelopmentPeer, + ), + Err(crate::runtime_config::RuntimeConfigError::InvalidBinding) + )); } } From e23b5932a977fed8c282169574dd728cd53d4f7c Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 21:54:11 +0000 Subject: [PATCH 099/183] docs(platform-config): describe the strict provider block in plain words Its schema description named a Rust type, and its root description omitted the development relaxation the resolver still applies. Refs #2882. Signed-off-by: Jeremi Joslin --- crates/registry-platform-config/src/blocks.rs | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/crates/registry-platform-config/src/blocks.rs b/crates/registry-platform-config/src/blocks.rs index c898b2d388..e83af5b844 100644 --- a/crates/registry-platform-config/src/blocks.rs +++ b/crates/registry-platform-config/src/blocks.rs @@ -287,9 +287,9 @@ impl SecretProvidersConfig { /// The secret providers of an operator-local file read outside any runtime, /// such as a saved CLI connection or a task connection. It enables the same -/// providers as [`SecretProvidersConfig`] but has no `mountPolicy`: nothing -/// reports an explicit production setting for these files, so the strict -/// file rule always applies and the member is refused as unknown. +/// providers as a runtime's `secretProviders` without the Compose mount +/// policy: nothing reports an explicit production setting for these files, +/// so the strict file rule always applies. #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] #[cfg_attr( feature = "schema", @@ -322,6 +322,8 @@ pub struct StrictFileSecretProviderConfig { /// The file it reaches must be a regular file with one hard link, owned by /// the user running the tool with mode 0400 or 0600, or owned by root with /// no access beyond group read (0440 or 0640) when that user is not root. + /// A command 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, } From 23a3a3329e914372147ef3d810cab1541a1e778d Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 21:54:11 +0000 Subject: [PATCH 100/183] chore: regenerate the store-provision and connection schemas Generated by each format's own generator after the operator-local files moved to the strict secret provider block. Refs #2882. Signed-off-by: Jeremi Joslin --- .../schema/connections.schema.json | 59 ++++++++----------- .../authoring/store-provision.schema.json | 40 ++++++------- .../schemas/task-connection.schema.json | 39 ++++-------- 3 files changed, 56 insertions(+), 82 deletions(-) diff --git a/crates/registry-cli-api/schema/connections.schema.json b/crates/registry-cli-api/schema/connections.schema.json index 975f6c6318..436564ffb4 100644 --- a/crates/registry-cli-api/schema/connections.schema.json +++ b/crates/registry-cli-api/schema/connections.schema.json @@ -12,28 +12,6 @@ "pattern": "^[^\\u0000-\\u001F\\u007F-\\u009F]+$", "type": "string" }, - "FileSecretProviderConfig": { - "additionalProperties": false, - "description": "The file secret provider.", - "properties": { - "mountPolicy": { - "$ref": "#/$defs/SecretMountPolicy", - "description": "`compose-native` also accepts a root-owned regular file with one hard\nlink and mode exactly 0444, the shape of a Docker Compose secret mount.\nEvery user in the container can read such a file. Startup and `check`\nreport this explicit production setting. Absent, the stricter rule\nabove applies.", - "x-registry-explicit-production": [ - "platform.posture.compose-native-secret-mount" - ] - }, - "root": { - "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. A public document, such as a static JWKS\nor a CA bundle, may also be readable by group and others.", - "pattern": "^/", - "type": "string" - } - }, - "required": [ - "root" - ], - "type": "object" - }, "LocalId": { "description": "A local identifier: a lowercase letter, then up to 63 lowercase letters, digits, `_`, or `-`.", "pattern": "^[a-z][a-z0-9_-]{0,63}$", @@ -176,7 +154,7 @@ "secretProviders": { "anyOf": [ { - "$ref": "#/$defs/SecretProvidersConfig" + "$ref": "#/$defs/StrictSecretProvidersConfig" }, { "type": "null" @@ -198,19 +176,33 @@ ], "type": "object" }, - "SecretMountPolicy": { - "enum": [ - "compose-native" - ], + "SecretReference": { + "description": "An exact secret reference: secret:file/name, resolved under secretProviders.file.root, or secret:env/NAME, resolved only when secretProviders.environment is declared.", + "pattern": "^(?:secret:env/[A-Z][A-Z0-9_]{0,127}|secret:file/[a-z][a-z0-9._-]{0,127})$", "type": "string" }, - "SecretProvidersConfig": { + "StrictFileSecretProviderConfig": { + "additionalProperties": false, + "description": "The file secret provider of an operator-local file.", + "properties": { + "root": { + "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 user running the tool with mode 0400 or 0600, or owned by root with\nno access beyond group read (0440 or 0640) when that user is not root.\nA command that declared development loads a file with looser read or\nmode bits and logs a warning.", + "pattern": "^/", + "type": "string" + } + }, + "required": [ + "root" + ], + "type": "object" + }, + "StrictSecretProvidersConfig": { "additionalProperties": false, "anyOf": [ { "properties": { "file": { - "$ref": "#/$defs/FileSecretProviderConfig" + "$ref": "#/$defs/StrictFileSecretProviderConfig" } }, "required": [ @@ -228,24 +220,19 @@ ] } ], - "description": "The secret providers a runtime enables. A reference is resolved only by a\nprovider declared here: `secret:file/name` under `file.root`, and\n`secret:env/NAME` only when `environment: {}` is present.", + "description": "The secret providers of an operator-local file read outside any runtime,\nsuch as a saved CLI connection or a task connection. It enables the same\nproviders as a runtime's `secretProviders` without the Compose mount\npolicy: nothing reports an explicit production setting for these files,\nso the strict file rule always applies.", "properties": { "environment": { "$ref": "#/$defs/EnvironmentSecretProviderConfig", "description": "Enables `secret:env/NAME` references, read from the process\nenvironment. Declared as an empty mapping: `environment: {}`." }, "file": { - "$ref": "#/$defs/FileSecretProviderConfig", + "$ref": "#/$defs/StrictFileSecretProviderConfig", "description": "Enables `secret:file/name` references, read from files under `root`." } }, "type": "object" }, - "SecretReference": { - "description": "An exact secret reference: secret:file/name, resolved under secretProviders.file.root, or secret:env/NAME, resolved only when secretProviders.environment is declared.", - "pattern": "^(?:secret:env/[A-Z][A-Z0-9_]{0,127}|secret:file/[a-z][a-z0-9._-]{0,127})$", - "type": "string" - }, "Url": { "description": "An absolute http or https URL with a host preserved as written, no user information, and no backslash, whitespace or control character. DNS case and equivalent IPv6 literals are permitted.", "format": "uri", diff --git a/crates/registry-evidencectl/schemas/authoring/store-provision.schema.json b/crates/registry-evidencectl/schemas/authoring/store-provision.schema.json index e84a7877b1..5fd67ff3be 100644 --- a/crates/registry-evidencectl/schemas/authoring/store-provision.schema.json +++ b/crates/registry-evidencectl/schemas/authoring/store-provision.schema.json @@ -60,12 +60,24 @@ "description": "The environment secret provider. It takes no settings.", "type": "object" }, - "FileSecretProviderConfig": { + "SecretReference": { + "description": "An exact secret reference: secret:file/name, resolved under secretProviders.file.root, or secret:env/NAME, resolved only when secretProviders.environment is declared.", + "pattern": "^(?:secret:env/[A-Z][A-Z0-9_]{0,127}|secret:file/[a-z][a-z0-9._-]{0,127})$", + "type": "string" + }, + "Store": { + "enum": [ + "status", + "oid4vci" + ], + "type": "string" + }, + "StrictFileSecretProviderConfig": { "additionalProperties": false, - "description": "The file secret provider.", + "description": "The file secret provider of an operator-local file.", "properties": { "root": { - "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.", + "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 user running the tool with mode 0400 or 0600, or owned by root with\nno access beyond group read (0440 or 0640) when that user is not root.\nA command that declared development loads a file with looser read or\nmode bits and logs a warning.", "pattern": "^/", "type": "string" } @@ -75,13 +87,13 @@ ], "type": "object" }, - "SecretProvidersConfig": { + "StrictSecretProvidersConfig": { "additionalProperties": false, "anyOf": [ { "properties": { "file": { - "$ref": "#/$defs/FileSecretProviderConfig" + "$ref": "#/$defs/StrictFileSecretProviderConfig" } }, "required": [ @@ -99,30 +111,18 @@ ] } ], - "description": "The secret providers a runtime enables. A reference is resolved only by a\nprovider declared here: `secret:file/name` under `file.root`, and\n`secret:env/NAME` only when `environment: {}` is present.", + "description": "The secret providers of an operator-local file read outside any runtime,\nsuch as a saved CLI connection or a task connection. It enables the same\nproviders as a runtime's `secretProviders` without the Compose mount\npolicy: nothing reports an explicit production setting for these files,\nso the strict file rule always applies.", "properties": { "environment": { "$ref": "#/$defs/EnvironmentSecretProviderConfig", "description": "Enables `secret:env/NAME` references, read from the process\nenvironment. Declared as an empty mapping: `environment: {}`." }, "file": { - "$ref": "#/$defs/FileSecretProviderConfig", + "$ref": "#/$defs/StrictFileSecretProviderConfig", "description": "Enables `secret:file/name` references, read from files under `root`." } }, "type": "object" - }, - "SecretReference": { - "description": "An exact secret reference: secret:file/name, resolved under secretProviders.file.root, or secret:env/NAME, resolved only when secretProviders.environment is declared.", - "pattern": "^(?:secret:env/[A-Z][A-Z0-9_]{0,127}|secret:file/[a-z][a-z0-9._-]{0,127})$", - "type": "string" - }, - "Store": { - "enum": [ - "status", - "oid4vci" - ], - "type": "string" } }, "$id": "https://id.registrystack.org/schemas/evidence/store-provision/store-provision.v1alpha1.schema.json", @@ -141,7 +141,7 @@ "type": "string" }, "secretProviders": { - "$ref": "#/$defs/SecretProvidersConfig" + "$ref": "#/$defs/StrictSecretProvidersConfig" }, "store": { "$ref": "#/$defs/Store", diff --git a/products/platform/schemas/task-connection.schema.json b/products/platform/schemas/task-connection.schema.json index 1c20d44531..16110d47f3 100644 --- a/products/platform/schemas/task-connection.schema.json +++ b/products/platform/schemas/task-connection.schema.json @@ -12,19 +12,17 @@ "pattern": "^[^\\u0000-\\u001F\\u007F-\\u009F]+$", "type": "string" }, - "FileSecretProviderConfig": { + "SecretReference": { + "description": "An exact secret reference: secret:file/name, resolved under secretProviders.file.root, or secret:env/NAME, resolved only when secretProviders.environment is declared.", + "pattern": "^(?:secret:env/[A-Z][A-Z0-9_]{0,127}|secret:file/[a-z][a-z0-9._-]{0,127})$", + "type": "string" + }, + "StrictFileSecretProviderConfig": { "additionalProperties": false, - "description": "The file secret provider.", + "description": "The file secret provider of an operator-local file.", "properties": { - "mountPolicy": { - "$ref": "#/$defs/SecretMountPolicy", - "description": "`compose-native` also accepts a root-owned regular file with one hard\nlink and mode exactly 0444, the shape of a Docker Compose secret mount.\nEvery user in the container can read such a file. Startup and `check`\nreport this explicit production setting. Absent, the stricter rule\nabove applies.", - "x-registry-explicit-production": [ - "platform.posture.compose-native-secret-mount" - ] - }, "root": { - "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. A public document, such as a static JWKS\nor a CA bundle, may also be readable by group and others.", + "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 user running the tool with mode 0400 or 0600, or owned by root with\nno access beyond group read (0440 or 0640) when that user is not root.\nA command that declared development loads a file with looser read or\nmode bits and logs a warning.", "pattern": "^/", "type": "string" } @@ -34,19 +32,13 @@ ], "type": "object" }, - "SecretMountPolicy": { - "enum": [ - "compose-native" - ], - "type": "string" - }, - "SecretProvidersConfig": { + "StrictSecretProvidersConfig": { "additionalProperties": false, "anyOf": [ { "properties": { "file": { - "$ref": "#/$defs/FileSecretProviderConfig" + "$ref": "#/$defs/StrictFileSecretProviderConfig" } }, "required": [ @@ -64,24 +56,19 @@ ] } ], - "description": "The secret providers a runtime enables. A reference is resolved only by a\nprovider declared here: `secret:file/name` under `file.root`, and\n`secret:env/NAME` only when `environment: {}` is present.", + "description": "The secret providers of an operator-local file read outside any runtime,\nsuch as a saved CLI connection or a task connection. It enables the same\nproviders as a runtime's `secretProviders` without the Compose mount\npolicy: nothing reports an explicit production setting for these files,\nso the strict file rule always applies.", "properties": { "environment": { "$ref": "#/$defs/EnvironmentSecretProviderConfig", "description": "Enables `secret:env/NAME` references, read from the process\nenvironment. Declared as an empty mapping: `environment: {}`." }, "file": { - "$ref": "#/$defs/FileSecretProviderConfig", + "$ref": "#/$defs/StrictFileSecretProviderConfig", "description": "Enables `secret:file/name` references, read from files under `root`." } }, "type": "object" }, - "SecretReference": { - "description": "An exact secret reference: secret:file/name, resolved under secretProviders.file.root, or secret:env/NAME, resolved only when secretProviders.environment is declared.", - "pattern": "^(?:secret:env/[A-Z][A-Z0-9_]{0,127}|secret:file/[a-z][a-z0-9._-]{0,127})$", - "type": "string" - }, "TaskClient": { "additionalProperties": false, "description": "One registered client.", @@ -194,7 +181,7 @@ "type": "string" }, "secretProviders": { - "$ref": "#/$defs/SecretProvidersConfig", + "$ref": "#/$defs/StrictSecretProvidersConfig", "description": "The providers that resolve each client's `assertionKeyRef`." }, "tokenEndpoint": { From 639115ea61aaa2816c1386f6c7e0b7c9fa4646ec Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 21:55:25 +0000 Subject: [PATCH 101/183] feat(registry-mcp): report explicit production settings in check The runtime accepts settings that relax a default, such as the Compose mount policy, and logs them at startup. check now lists them too, in its JSON report and as a notice on stderr. Refs #2882. Signed-off-by: Jeremi Joslin --- crates/registry-mcp/src/config.rs | 22 +++++++- crates/registry-mcp/src/main.rs | 85 ++++++++++++++++++++----------- crates/registry-mcp/tests/cli.rs | 26 ++++++++++ 3 files changed, 101 insertions(+), 32 deletions(-) diff --git a/crates/registry-mcp/src/config.rs b/crates/registry-mcp/src/config.rs index 253a836f06..ad0e8e3f6e 100644 --- a/crates/registry-mcp/src/config.rs +++ b/crates/registry-mcp/src/config.rs @@ -260,8 +260,28 @@ impl RuntimeConfig { environment: bool, declared: DeclaredPosture, ) -> (Report, bool) { + let (report, unavailable, _) = Self::check_with_settings(path, environment, declared); + (report, unavailable) + } + + /// [`Self::check_status_with_posture`], with the explicit production + /// settings the file states, which `check` reports beside its diagnostics. + pub fn check_with_settings( + path: &Path, + environment: bool, + declared: DeclaredPosture, + ) -> ( + Report, + bool, + Vec, + ) { let (checked, report) = read_runtime(path, environment, declared); - (report, checked.unavailable) + let settings = checked + .loaded + .as_ref() + .map(|loaded| loaded.posture.explicit_settings().to_vec()) + .unwrap_or_default(); + (report, checked.unavailable, settings) } pub fn validate( &self, diff --git a/crates/registry-mcp/src/main.rs b/crates/registry-mcp/src/main.rs index 5e09f9bf07..5a6de47303 100644 --- a/crates/registry-mcp/src/main.rs +++ b/crates/registry-mcp/src/main.rs @@ -111,36 +111,54 @@ async fn main() -> ExitCode { if let Command::Check(arguments) = cli.command { let given = &runtime_config; - let (report, unavailable) = match registry_breg_mcp::check::absolute_runtime_path(given) { - Some(path) => { - let (mut report, unavailable) = RuntimeConfig::check_status_with_posture( - &path, - arguments.environment, - declared, - ); - registry_breg_mcp::check::restore_diagnostic_path( - report.diagnostics_mut(), - &path, - given, - ); - (report, unavailable) - } - None => { - use registry_platform_yaml::{Diagnostic, Report, Source}; - let mut diagnostic = Diagnostic::error( - "platform.runtime-config.unavailable", - "", - "the runtime file path could not be made absolute", - "Name the runtime file by an absolute path, then run the check again.", - ); - diagnostic.source = Some(Source { - file: given.display().to_string(), - line: None, - column: None, + let (report, unavailable, settings) = + match registry_breg_mcp::check::absolute_runtime_path(given) { + Some(path) => { + let (mut report, unavailable, settings) = + RuntimeConfig::check_with_settings(&path, arguments.environment, declared); + registry_breg_mcp::check::restore_diagnostic_path( + report.diagnostics_mut(), + &path, + given, + ); + (report, unavailable, settings) + } + None => { + use registry_platform_yaml::{Diagnostic, Report, Source}; + let mut diagnostic = Diagnostic::error( + "platform.runtime-config.unavailable", + "", + "the runtime file path could not be made absolute", + "Name the runtime file by an absolute path, then run the check again.", + ); + diagnostic.source = Some(Source { + file: given.display().to_string(), + line: None, + column: None, + }); + (Report::new(vec![diagnostic]), true, Vec::new()) + } + }; + // Each explicit production setting the file states, as every check + // reports it: a fact for review, not a diagnostic. + let explicit: Vec = settings + .iter() + .map(|found| { + let mut line = serde_json::json!({ + "code": found.setting.code, + "file": given.display().to_string(), + "summary": found.setting.summary, }); - (Report::new(vec![diagnostic]), true) - } - }; + if let Some(pointer) = &found.pointer { + line["pointer"] = pointer.as_str().into(); + } + if let Some(position) = found.position { + line["line"] = position.line.into(); + line["column"] = position.column.into(); + } + line + }) + .collect(); let failed = unavailable || report.has_errors() || (arguments.deny_warnings @@ -154,9 +172,14 @@ async fn main() -> ExitCode { }; eprintln!("{headline}\n{}", report.render_human()); } - Format::Human => print!("{}", report.render_human()), + Format::Human => { + for found in &settings { + eprintln!("{}", found.notice()); + } + print!("{}", report.render_human()); + } Format::Json => match serde_json::to_string_pretty( - &serde_json::json!({"ok":!failed,"command":"check","status":if unavailable {"operational-failure"} else if failed {"domain-refusal"} else {"complete"},"apiVersion":"id.registrystack.org/formats/platform/mcp-ctl-report/v1alpha1","kind":"PlatformMcpCtlReport","version":env!("CARGO_PKG_VERSION"),"filesChecked":1,"errors":report.error_count(),"warnings":report.warning_count(),"diagnostics":report.to_json_value(),"posture":{"value":declared.posture.as_str(),"source":declared.source.as_str()}}), + &serde_json::json!({"ok":!failed,"command":"check","status":if unavailable {"operational-failure"} else if failed {"domain-refusal"} else {"complete"},"apiVersion":"id.registrystack.org/formats/platform/mcp-ctl-report/v1alpha1","kind":"PlatformMcpCtlReport","version":env!("CARGO_PKG_VERSION"),"filesChecked":1,"errors":report.error_count(),"warnings":report.warning_count(),"diagnostics":report.to_json_value(),"posture":{"value":declared.posture.as_str(),"source":declared.source.as_str()},"explicitProductionSettings":explicit}), ) { Ok(json) => println!("{json}"), Err(_) => { diff --git a/crates/registry-mcp/tests/cli.rs b/crates/registry-mcp/tests/cli.rs index 906af94f68..4a1b9e7223 100644 --- a/crates/registry-mcp/tests/cli.rs +++ b/crates/registry-mcp/tests/cli.rs @@ -251,6 +251,32 @@ fn the_shipped_example_passes_a_production_check() { assert_eq!(report["diagnostics"], serde_json::json!([]), "{report}"); } +#[test] +fn check_reports_the_explicit_production_settings_the_file_states() { + let directory = private_fixture_directory().unwrap(); + let plain = std::fs::read_to_string(example()).unwrap(); + let path = stage_runtime(directory.path().join("plain.yaml"), plain.as_bytes()); + let (exit, report) = check_json(&path, &[]); + assert_eq!(exit, Some(0), "{report}"); + assert_eq!(report["explicitProductionSettings"], serde_json::json!([])); + + let stated = plain.replace( + "secretProviders:\n environment: {}\n", + "secretProviders:\n environment: {}\n file:\n root: /run/registry-mcp/secrets\n mountPolicy: compose-native\n", + ); + assert_ne!(stated, plain, "the member is written"); + let path = stage_runtime(directory.path().join("stated.yaml"), stated.as_bytes()); + let (exit, report) = check_json(&path, &[]); + assert_eq!(exit, Some(0), "{report}"); + let settings = report["explicitProductionSettings"].as_array().unwrap(); + assert!( + settings.iter().any(|setting| setting["code"] + == "platform.posture.compose-native-secret-mount" + && setting["pointer"] == "/secretProviders/file/mountPolicy"), + "{report}" + ); +} + #[test] fn the_shipped_example_separates_the_public_resource_from_the_listener() { use registry_mcp::config::{ProviderConfig, RuntimeConfig}; From 20b3209d68777d74d2455a3b05154d9c146ac2bf Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 21:56:16 +0000 Subject: [PATCH 102/183] feat(registry-session): report explicit production settings in check The service accepts settings that relax a default, such as the Compose mount policy, and logs them at startup. check now lists them too, in its JSON report and as a notice on stderr. Refs #2882. Signed-off-by: Jeremi Joslin --- crates/registry-session/README.md | 4 ++- crates/registry-session/src/config.rs | 9 +++++ crates/registry-session/src/offline.rs | 48 ++++++++++++++++++++++--- crates/registry-session/tests/binary.rs | 37 +++++++++++++++++++ 4 files changed, 92 insertions(+), 6 deletions(-) diff --git a/crates/registry-session/README.md b/crates/registry-session/README.md index 70209fce28..a301d4453a 100644 --- a/crates/registry-session/README.md +++ b/crates/registry-session/README.md @@ -44,7 +44,9 @@ audit destination before listening. `registry-session --runtime-config /absolute/path/session-runtime.yaml check` checks the same runtime model offline. It reads no secret, calls no provider, opens no socket and writes no audit file. `--format json` writes a -`PlatformSessionCtlReport`. It exits 0 when accepted, 1 when refused (or on +`PlatformSessionCtlReport`, which lists each explicit production setting the +file states under `explicitProductionSettings`. The human output prints each +as a notice on stderr. It exits 0 when accepted, 1 when refused (or on a warning with `--deny-warnings`), 2 for usage errors and 3 for unreadable input. Without `--environment`, environment expressions are checked only for syntax and position. `--identity-receipt /absolute/path/identity-receipt.json` diff --git a/crates/registry-session/src/config.rs b/crates/registry-session/src/config.rs index f6e76399b0..ecb17ebed3 100644 --- a/crates/registry-session/src/config.rs +++ b/crates/registry-session/src/config.rs @@ -972,6 +972,9 @@ pub struct RuntimeCheck { /// Whether a member that decides a kind's audiences holds an expression /// the check did not substitute, so the audiences it derived are stand-ins. pub deferred_audiences: bool, + /// The explicit production settings the file states, which `check` + /// reports beside its diagnostics. + pub explicit_settings: Vec, } /// The route a request path belongs to. @@ -1245,6 +1248,11 @@ pub(crate) fn read_runtime_file( let deferred_audiences = check.loaded.as_ref().is_some_and(|loaded| { deferred_audience_inputs(&loaded.config, &|pointer| check.defers(pointer)) }); + let explicit_settings = check + .loaded + .as_ref() + .map(|loaded| loaded.posture.explicit_settings().to_vec()) + .unwrap_or_default(); if refused { check.loaded = None; } @@ -1254,6 +1262,7 @@ pub(crate) fn read_runtime_file( diagnostics, unavailable, deferred_audiences, + explicit_settings, }, ) } diff --git a/crates/registry-session/src/offline.rs b/crates/registry-session/src/offline.rs index 7ff0e006bc..be856a0592 100644 --- a/crates/registry-session/src/offline.rs +++ b/crates/registry-session/src/offline.rs @@ -64,13 +64,16 @@ struct CtlReport { errors: usize, warnings: usize, diagnostics: serde_json::Value, + /// Each explicit production setting the file states: a fact for review, + /// not a diagnostic. + explicit_production_settings: Vec, } /// Run `registry-session check` and report every finding (CFG-DIAG-4): exit 0 when /// nothing was refused, 1 when something was or a warning was reported under /// `--deny-warnings`, and 3 when the file could not be read. pub fn run(request: &CheckRequest<'_>, stdout: &mut dyn Write, stderr: &mut dyn Write) -> u8 { - let (mut diagnostics, mut unavailable) = + let (mut diagnostics, mut unavailable, settings) = check_runtime_file(request.runtime, request.environment, request.posture); if let (Some(receipt), false) = (request.identity_receipt, diagnostics.iter().any(is_error)) { let (found, unreadable) = receipt_diagnostics( @@ -107,6 +110,10 @@ pub fn run(request: &CheckRequest<'_>, stdout: &mut dyn Write, stderr: &mut dyn errors: report.error_count(), warnings: report.warning_count(), diagnostics: report.to_json_value(), + explicit_production_settings: settings + .iter() + .map(|found| setting_line(found, request.runtime)) + .collect(), }; let written = serde_json::to_writer_pretty(&mut *stdout, &document) .map_err(std::io::Error::other) @@ -116,6 +123,11 @@ pub fn run(request: &CheckRequest<'_>, stdout: &mut dyn Write, stderr: &mut dyn } } OutputFormat::Human if exit == 0 => { + for found in &settings { + if writeln!(stderr, "{}", found.notice()).is_err() { + return OPERATIONAL_FAILURE_EXIT; + } + } if stdout.write_all(report.render_human().as_bytes()).is_err() { return OPERATIONAL_FAILURE_EXIT; } @@ -134,14 +146,40 @@ pub fn run(request: &CheckRequest<'_>, stdout: &mut dyn Write, stderr: &mut dyn exit } +/// One explicit production setting as the JSON report lists it, with the +/// members every check report uses for it. +fn setting_line( + found: ®istry_platform_config::FoundExplicitSetting, + runtime: &Path, +) -> serde_json::Value { + let mut line = serde_json::json!({ + "code": found.setting.code, + "file": runtime.display().to_string(), + "summary": found.setting.summary, + }); + if let Some(pointer) = &found.pointer { + line["pointer"] = pointer.as_str().into(); + } + if let Some(position) = found.position { + line["line"] = position.line.into(); + line["column"] = position.column.into(); + } + line +} + /// Check the runtime file at `path` as given: the loader needs an absolute, /// lexically normal path, and every diagnostic names the file as given. -/// Returns the findings and whether the file could not be read at all. +/// Returns the findings, whether the file could not be read at all, and the +/// explicit production settings it states. fn check_runtime_file( path: &Path, environment: bool, posture: DeclaredPosture, -) -> (Vec, bool) { +) -> ( + Vec, + bool, + Vec, +) { let given = path.display().to_string(); let Some(absolute) = absolute_lexical(path) else { let mut diagnostic = Diagnostic::error( @@ -155,7 +193,7 @@ fn check_runtime_file( line: None, column: None, }); - return (vec![diagnostic], true); + return (vec![diagnostic], true, Vec::new()); }; let checked = crate::config::check_runtime(&absolute, environment, posture); let absolute = absolute.display().to_string(); @@ -176,7 +214,7 @@ fn check_runtime_file( diagnostic }) .collect(); - (diagnostics, checked.unavailable) + (diagnostics, checked.unavailable, checked.explicit_settings) } /// `path` made absolute against the working directory, with `.` and `..` diff --git a/crates/registry-session/tests/binary.rs b/crates/registry-session/tests/binary.rs index fe30a66565..693cc17ba5 100644 --- a/crates/registry-session/tests/binary.rs +++ b/crates/registry-session/tests/binary.rs @@ -117,6 +117,43 @@ async fn the_offline_check_passes_a_good_file_and_reports_json() { assert_eq!(report["kind"], "PlatformSessionCtlReport"); } +#[tokio::test] +async fn the_offline_check_reports_the_explicit_production_settings() { + let harness = Harness::start().await; + let runtime = runtime_file(&harness); + let (code, stdout, stderr) = run(&runtime, &["--format", "json"]); + assert_eq!(code, 0, "{stderr}"); + let report: serde_json::Value = serde_json::from_str(&stdout).expect("json report"); + assert_eq!(report["explicitProductionSettings"], json!([])); + + let text = std::fs::read_to_string(&runtime).expect("runtime file"); + let stated = text.replacen( + "secretProviders:\n file:\n", + "secretProviders:\n file:\n mountPolicy: compose-native\n", + 1, + ); + assert_ne!(stated, text, "the member is written"); + std::fs::write(&runtime, stated).expect("rewrite the runtime file"); + let (code, stdout, stderr) = run(&runtime, &["--format", "json"]); + assert_eq!(code, 0, "{stderr}"); + let report: serde_json::Value = serde_json::from_str(&stdout).expect("json report"); + let settings = report["explicitProductionSettings"].as_array().unwrap(); + assert!( + settings.iter().any(|setting| setting["code"] + == "platform.posture.compose-native-secret-mount" + && setting["pointer"] == "/secretProviders/file/mountPolicy"), + "{report}" + ); + let (code, _, stderr) = run(&runtime, &[]); + assert_eq!(code, 0, "{stderr}"); + assert!( + stderr.contains( + "Explicit production setting platform.posture.compose-native-secret-mount at /secretProviders/file/mountPolicy." + ), + "{stderr}" + ); +} + #[tokio::test] async fn a_receipt_that_matches_passes_and_a_typo_fails_naming_the_kind() { let harness = Harness::start().await; From c17cf242eac57f8a6eeebc63cd0a334e8eb29301 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 21:58:06 +0000 Subject: [PATCH 103/183] test: pin the Compose mount policy and public reads at product call sites Messaging and Scheduling check list the setting and record it for the startup log. A world-readable static key set loads at the Messaging runtime, and a world-readable CA bundle loads at messagingctl provision, which also prints the setting's notice. Reverting any of these call sites to the secret read now fails a test. Refs #2882. Signed-off-by: Jeremi Joslin --- crates/registry-messaging/src/config.rs | 22 ++++++++- crates/registry-messagingctl/src/lib.rs | 42 ++++++++++++++++ .../tests/provision_cli.rs | 39 +++++++++++++++ crates/registry-schedulingctl/src/lib.rs | 48 +++++++++++++++++++ 4 files changed, 150 insertions(+), 1 deletion(-) diff --git a/crates/registry-messaging/src/config.rs b/crates/registry-messaging/src/config.rs index fa9921dde9..4db247638f 100644 --- a/crates/registry-messaging/src/config.rs +++ b/crates/registry-messaging/src/config.rs @@ -2370,6 +2370,15 @@ pub(crate) mod tests { /// key source from it. #[cfg(unix)] async fn static_key_source(document: &str) -> Result<(), RuntimeConfigError> { + static_key_source_with_mode(document, 0o600).await + } + + /// [`static_key_source`] with the key set file at `mode`. + #[cfg(unix)] + async fn static_key_source_with_mode( + document: &str, + mode: u32, + ) -> Result<(), RuntimeConfigError> { use std::os::unix::fs::PermissionsExt as _; let root = tempfile::tempdir_in(std::env::temp_dir().canonicalize().unwrap()).unwrap(); @@ -2378,7 +2387,7 @@ pub(crate) mod tests { 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(); + std::fs::set_permissions(&file, std::fs::Permissions::from_mode(mode)).unwrap(); let mut runtime = runtime_value(root.path()); runtime["authentication"]["oidc"]["issuers"]["main"]["jwksSource"] = json!({"type": "static", "documentRef": "secret:file/issuer-jwks"}); @@ -2403,6 +2412,17 @@ pub(crate) mod tests { key } + /// A key set is a public document: a world-readable file loads, where a + /// secret at the same mode is refused. + #[cfg(unix)] + #[tokio::test] + async fn a_world_readable_static_key_set_loads_as_a_public_document() { + let document = json!({"keys": [static_key(json!({}))]}); + static_key_source_with_mode(&document.to_string(), 0o644) + .await + .expect("a world-readable key set loads"); + } + #[cfg(unix)] #[tokio::test] async fn a_static_key_set_with_members_it_does_not_know_loads() { diff --git a/crates/registry-messagingctl/src/lib.rs b/crates/registry-messagingctl/src/lib.rs index 713486fa54..64bcd67ab0 100644 --- a/crates/registry-messagingctl/src/lib.rs +++ b/crates/registry-messagingctl/src/lib.rs @@ -2817,6 +2817,48 @@ audit: ); } + #[test] + fn the_compose_mount_policy_is_listed_by_check_and_recorded_for_startup() { + let (root, path) = project(""); + let text = std::fs::read_to_string(&path).unwrap(); + let providers = "secretProviders:\n environment: {}\n"; + assert!(text.contains(providers), "{text}"); + let secrets = root.path().canonicalize().unwrap().join("secrets"); + std::fs::write( + &path, + text.replace( + providers, + &format!( + "{providers} file:\n root: {}\n mountPolicy: compose-native\n", + secrets.display() + ), + ), + ) + .unwrap(); + let (exit, report) = check_json(&path); + assert_eq!(exit, ExitCode::SUCCESS, "{report}"); + assert!( + report["explicitProductionSettings"] + .as_array() + .unwrap() + .iter() + .any( + |line| line["code"] == "platform.posture.compose-native-secret-mount" + && line["pointer"] == "/secretProviders/file/mountPolicy" + ), + "{report}" + ); + // Startup logs every setting the loaded posture records. + let config = RuntimeConfig::load(&path, registry_messaging::config::DEFAULT_POSTURE) + .expect("the runtime file loads"); + assert!(config + .posture_report() + .explicit_setting_notices() + .iter() + .any(|notice| notice + .contains("compose-native-secret-mount at /secretProviders/file/mountPolicy"))); + } + #[test] fn a_check_lists_the_explicit_production_settings_the_runtime_states() { let (_root, path) = project(""); diff --git a/crates/registry-messagingctl/tests/provision_cli.rs b/crates/registry-messagingctl/tests/provision_cli.rs index 60e448a720..31e6a1aeab 100644 --- a/crates/registry-messagingctl/tests/provision_cli.rs +++ b/crates/registry-messagingctl/tests/provision_cli.rs @@ -191,6 +191,45 @@ fn print_sql_writes_the_script_and_no_password() { } } +#[test] +fn a_world_readable_ca_bundle_loads_and_the_mount_policy_is_noticed() { + let directory = scratch(); + let runtime = write_runtime(directory.path()); + // A CA bundle is a public document: a mode 0644 file loads, where a + // secret at that mode is refused. + let ca = directory.path().join("secrets").join("database-ca.pem"); + std::fs::write( + &ca, + "-----BEGIN CERTIFICATE-----\nMIIB\n-----END CERTIFICATE-----\n", + ) + .unwrap(); + std::fs::set_permissions(&ca, std::fs::Permissions::from_mode(0o644)).unwrap(); + let text = std::fs::read_to_string(&runtime).unwrap(); + let stated = text + .replace( + " migrationUrlRef: secret:file/migration-database-url\n", + " migrationUrlRef: secret:file/migration-database-url\n caBundleRef: secret:file/database-ca.pem\n", + ) + .replace( + "secretProviders:\n file:\n", + "secretProviders:\n file:\n mountPolicy: compose-native\n", + ); + assert_eq!(stated.matches("caBundleRef").count(), 1, "{stated}"); + assert!(stated.contains("mountPolicy"), "{stated}"); + std::fs::write(&runtime, stated).unwrap(); + + 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.contains( + "Explicit production setting platform.posture.compose-native-secret-mount at /secretProviders/file/mountPolicy." + ), + "{stderr}" + ); +} + #[test] fn print_sql_as_json_reports_nothing_executed() { let directory = scratch(); diff --git a/crates/registry-schedulingctl/src/lib.rs b/crates/registry-schedulingctl/src/lib.rs index bb22fa267f..ae7ec5e094 100644 --- a/crates/registry-schedulingctl/src/lib.rs +++ b/crates/registry-schedulingctl/src/lib.rs @@ -2676,6 +2676,54 @@ mod tests { assert_eq!(report["status"], "operational-failure"); } + #[test] + fn the_compose_mount_policy_is_listed_by_check_and_recorded_for_startup() { + let (root, project) = initialized("standalone-exact-time"); + let runtime = runtime_config(root.path(), &project); + let text = std::fs::read_to_string(&runtime).unwrap(); + let providers = "secretProviders:\n file:\n"; + assert!(text.contains(providers), "{text}"); + std::fs::write( + &runtime, + text.replacen( + providers, + &format!("{providers} mountPolicy: compose-native\n"), + 1, + ), + ) + .unwrap(); + let (exit, report, _) = run_json(&[ + "check", + project.to_str().unwrap(), + "--runtime-config", + runtime.to_str().unwrap(), + ]); + assert_eq!(exit, ExitCode::SUCCESS, "{report}"); + assert!( + report["explicitProductionSettings"] + .as_array() + .unwrap() + .iter() + .any( + |line| line["code"] == "platform.posture.compose-native-secret-mount" + && line["pointer"] == "/secretProviders/file/mountPolicy" + ), + "{report}" + ); + // Startup logs every setting the loaded posture records. + let config = registry_scheduling::config::RuntimeConfig::load( + &runtime, + registry_scheduling::config::DEFAULT_POSTURE, + ) + .expect("the runtime file loads"); + assert!(config + .posture_report() + .explicit_setting_notices() + .iter() + .any(|notice| notice + .contains("compose-native-secret-mount at /secretProviders/file/mountPolicy"))); + } + /// `check --runtime-config` lists the settings the file states on purpose /// as facts for a reviewer. They never change the verdict. #[test] From fd16470e8d543dccee717612f69f32dbcdecfd02 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 21:58:25 +0000 Subject: [PATCH 104/183] fix(render): name secretProviders when a static key set's provider fails The switch to the public read lost the secretProviders: prefix that every other reference Render resolves keeps for a provider it cannot build. Refs #2882. Signed-off-by: Jeremi Joslin --- crates/registry-render/src/auth.rs | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/crates/registry-render/src/auth.rs b/crates/registry-render/src/auth.rs index 65073d5040..576c3fc5eb 100644 --- a/crates/registry-render/src/auth.rs +++ b/crates/registry-render/src/auth.rs @@ -71,7 +71,19 @@ async fn entry_verifier( } registry_platform_config::JwksSource::Static { document_ref } | registry_platform_config::JwksSource::TestIssuer { document_ref } => { - let document = crate::runtime::resolve_public_document(runtime, witness, document_ref) + // A provider that cannot be built is named as such, as every other + // reference this runtime resolves names it. + let resolver = runtime + .secret_providers + .resolver(witness) + .map_err(|error| { + RenderProblem::new( + ProblemKind::RuntimeInvalid, + format!("secretProviders: {error}"), + ) + })?; + let document = resolver + .resolve_public_document(document_ref) .map_err(|error| { RenderProblem::new(ProblemKind::RuntimeInvalid, format!("{error}")) })?; From 074cbf6e95af7d32a48c541f58c4ef50576f7da5 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 21:58:25 +0000 Subject: [PATCH 105/183] docs(platform-config): word the mountPolicy description without position The member sorts above root in every generated schema, so the absent case names root instead of pointing at a rule above. The runtime schemas are regenerated with the other generated files. Refs #2882. Signed-off-by: Jeremi Joslin --- crates/registry-platform-config/src/blocks.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/registry-platform-config/src/blocks.rs b/crates/registry-platform-config/src/blocks.rs index e83af5b844..e4fa6641f5 100644 --- a/crates/registry-platform-config/src/blocks.rs +++ b/crates/registry-platform-config/src/blocks.rs @@ -146,8 +146,8 @@ pub struct FileSecretProviderConfig { /// `compose-native` also accepts a root-owned regular file with one hard /// link and mode exactly 0444, the shape of a Docker Compose secret mount. /// Every user in the container can read such a file. Startup and `check` - /// report this explicit production setting. Absent, the stricter rule - /// above applies. + /// report this explicit production setting. Without it, only the file + /// shapes `root` describes are accepted. #[serde(default, skip_serializing_if = "Option::is_none")] #[cfg_attr(feature = "schema", schemars(with = "Stated"))] mount_policy: Option>, From 738b3f73bc6594809cdc808e85a9dc6da2c0bc82 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 22:00:14 +0000 Subject: [PATCH 106/183] docs: document the Compose mount policy and public-document reads per product Each security page points at the hardening checklist for the setting, and Evidence's says it refuses it. The checklist cites the code and tests and notes the root-runtime asymmetry. Deployment posture, the Render code table, the platform-config README and the product changelogs name the setting, trustedJwksRef, the provision tools and the new refusals. Refs #2882. Signed-off-by: Jeremi Joslin --- crates/registry-platform-config/README.md | 24 ++++++++++++++--- .../docs/operate/deployment-posture.mdx | 8 +++--- .../docs/reference/render-configuration.mdx | 1 + docs/site/src/content/docs/security/breg.mdx | 7 +++++ .../src/content/docs/security/casework.mdx | 7 +++++ .../src/content/docs/security/coordinator.mdx | 7 +++++ .../src/content/docs/security/documents.mdx | 7 +++++ .../src/content/docs/security/evidence.mdx | 6 +++++ .../docs/security/hardening-checklist.mdx | 24 +++++++++++++---- .../site/src/content/docs/security/render.mdx | 7 +++++ .../src/content/docs/security/scheduling.mdx | 7 +++++ products/breg/CHANGELOG.md | 3 +++ products/evidence/CHANGELOG.md | 5 ++++ products/platform/CHANGELOG.md | 26 ++++++++++++++----- 14 files changed, 121 insertions(+), 18 deletions(-) diff --git a/crates/registry-platform-config/README.md b/crates/registry-platform-config/README.md index 5ba2ff1409..900eb4f813 100644 --- a/crates/registry-platform-config/README.md +++ b/crates/registry-platform-config/README.md @@ -12,7 +12,8 @@ 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 +A secret file is read through one rule, with two explicit widenings described +below. 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 @@ -25,6 +26,17 @@ and `SecretError::suggested_action()` gives the fix for any failure. `SecretResolver::inspect_reference` runs the same checks without reading the bytes. +The file provider's `mountPolicy: compose-native` also accepts a root-owned, +single-link file at mode exactly 0444, the Docker Compose secret mount shape. +It is an explicit production setting: startup, `check` and the `provision` +tools report it. A public document, such as a static JWKS or a CA bundle, is +read with `resolve_public_document`, which keeps the walk, owner, link and +write checks but lets group and others read the file. Its refusals are +`SecretError::UnsafePublicDocument`, worded for a public document, and it +refuses a file holding a PEM private key block +(`SecretError::PrivateKeyInPublicDocument`). `inspect_public_document` checks +one without reading it. + ## Loader `RuntimeConfigLoader` reads one runtime configuration file named by an @@ -111,9 +123,15 @@ accepted reference through the explicitly enabled environment or file provider. - `SecretProvidersConfig`: `file.root` enables `secret:file/name`, and `environment: {}` enables `secret:env/NAME`. At least one must be declared, - and a reference to an undeclared provider is refused. + and a reference to an undeclared provider is refused. `file.mountPolicy` + is the Compose mount setting above, and `compose_native_mounts()` lets a + product whose contract keeps the strict rule refuse it. +- `StrictSecretProvidersConfig`: the same providers without `mountPolicy`, for + operator-local files read outside any runtime, such as saved CLI + connections and task connections. - `DatabaseConfig`: `runtimeUrlRef`, `migrationUrlRef`, and an optional - `caBundleRef`. + `caBundleRef`. `DatabaseMember` names each of them and reads it with the + rule it takes: the CA bundle as a public document, each URL as a secret. - `DestinationTransport`: `verified-tls`, `loopback-plaintext` or `private-network-plaintext`. Only the last is an explicit production setting. - `PrivateRanges`: the `allowedPrivateCidrs` list of `PrivateRange` values from diff --git a/docs/site/src/content/docs/operate/deployment-posture.mdx b/docs/site/src/content/docs/operate/deployment-posture.mdx index 8ffae6cd6b..4ffca6f2c5 100644 --- a/docs/site/src/content/docs/operate/deployment-posture.mdx +++ b/docs/site/src/content/docs/operate/deployment-posture.mdx @@ -86,8 +86,10 @@ Explicit production settings are valid in every posture. They represent deliberate operator choices that relax a stricter default, such as `accessTokenType: JWT`, a custom `scopeClaim`, issuer-level `actorKind` or `clientActorKinds`, loopback HTTP issuer URLs, `private-network-plaintext` observer hook destinations in -Document Store and Registry Scheduling, or -`anonymousHttps: operator-approved` in Registry Adapter. +Document Store and Registry Scheduling, +`anonymousHttps: operator-approved` in Registry Adapter, or +`secretProviders.file.mountPolicy: compose-native`, which accepts root-owned Docker Compose +secret mounts at mode `0444` (Registry Evidence and both wallet adapters refuse it). Explicit production settings never refuse and are never diagnostics or warnings: @@ -98,7 +100,7 @@ Explicit production settings never refuse and are never diagnostics or warnings: {/* Evidence: crates/registry-platform-config/src/posture.rs, DevelopmentClass, Gated, ExplicitClass, Stated, PostureReport, ready_member, log_startup, has_denied_warnings; - crates/registry-platform-config/src/blocks.rs, DatabaseTransport; + crates/registry-platform-config/src/blocks.rs, DatabaseTransport, COMPOSE_NATIVE_SECRET_MOUNT; crates/registry-platform-config/src/caller_issuers.rs, ExplicitProductionSetting; crates/registry-platform-config/src/destination.rs, private-network-plaintext; crates/registry-cli-report/tests/envelope.rs, explicitProductionSettings. */} diff --git a/docs/site/src/content/docs/reference/render-configuration.mdx b/docs/site/src/content/docs/reference/render-configuration.mdx index de6e2011bf..ccefe92cc8 100644 --- a/docs/site/src/content/docs/reference/render-configuration.mdx +++ b/docs/site/src/content/docs/reference/render-configuration.mdx @@ -162,6 +162,7 @@ Serve and `check` report these as runtime problems at the position of the key. | `render.runtime.seal-not-bound` | A document type names a seal `signing.seals` does not bind (error). | | `render.runtime.seal-unused` | A runtime seal is named by no document type (warning). | | `render.posture.seals-not-served` | Document types name seals and the runtime has no `signing` block. Production refuses the combination. Development warns and renders the documents unsealed. | +| `platform.posture.compose-native-secret-mount` | `secretProviders.file.mountPolicy` is `compose-native`, so the file provider also accepts a root-owned, single-link file at mode `0444`, which every user in the container can read. Production accepts it as an explicit setting: `serve` logs it and `check --format json` lists it under `explicitProductionSettings`. `/ready` does not report it. | | `platform.posture.unrestricted-clients` | An issuer entry's `allowedClients` is `unrestricted`, so OIDC admits every client that issuer verifies. Production accepts it as an explicit setting: `serve` logs it and `check --format json` lists it under `explicitProductionSettings`. `/ready` does not report it. | `test-seal` reports `render.posture.test-signing` when you run it in production. diff --git a/docs/site/src/content/docs/security/breg.mdx b/docs/site/src/content/docs/security/breg.mdx index 898775d3f2..9554193437 100644 --- a/docs/site/src/content/docs/security/breg.mdx +++ b/docs/site/src/content/docs/security/breg.mdx @@ -862,6 +862,13 @@ and its ancestors. Deny other write access in every posture and group write acce If data subjects must see Proposal review reads and attachment downloads, cover them in your own audit, because they write no subject-log entry. +Secret files follow the [hardening checklist](../hardening-checklist/#secret-files). The +explicit `secretProviders.file.mountPolicy: compose-native` setting lets every user in the +container read root-owned `0444` secret mounts. Write it only for a container that runs this +service alone under one runtime identity. + +{/* Evidence: crates/registry-platform-config/src/blocks.rs, COMPOSE_NATIVE_SECRET_MOUNT. */} + ## Accepted residuals The residuals are ordered by operator impact. diff --git a/docs/site/src/content/docs/security/casework.mdx b/docs/site/src/content/docs/security/casework.mdx index ce300d4488..22ec3378a0 100644 --- a/docs/site/src/content/docs/security/casework.mdx +++ b/docs/site/src/content/docs/security/casework.mdx @@ -299,6 +299,13 @@ The residuals refer to these obligations by number. (`CASEWORK-SEC-16`). Producer profiles, which are services, share one claim among themselves. +Secret files follow the [hardening checklist](../hardening-checklist/#secret-files). The +explicit `secretProviders.file.mountPolicy: compose-native` setting lets every user in the +container read root-owned `0444` secret mounts. Write it only for a container that runs this +service alone under one runtime identity. + +{/* Evidence: crates/registry-platform-config/src/blocks.rs, COMPOSE_NATIVE_SECRET_MOUNT. */} + ## Accepted residuals Each residual lists the condition, the consequence, the mitigation, and the related matrix diff --git a/docs/site/src/content/docs/security/coordinator.mdx b/docs/site/src/content/docs/security/coordinator.mdx index 150a5b50fa..f8d21c5075 100644 --- a/docs/site/src/content/docs/security/coordinator.mdx +++ b/docs/site/src/content/docs/security/coordinator.mdx @@ -927,6 +927,13 @@ The residuals refer to them by number. caller_policies_list_the_exact_subjects_they_admit, every_connection_credential_states_its_client_assertion_audience. */} +Secret files follow the [hardening checklist](../hardening-checklist/#secret-files). The +explicit `secretProviders.file.mountPolicy: compose-native` setting lets every user in the +container read root-owned `0444` secret mounts. Write it only for a container that runs this +service alone under one runtime identity. + +{/* Evidence: crates/registry-platform-config/src/blocks.rs, COMPOSE_NATIVE_SECRET_MOUNT. */} + ## Accepted residuals Each residual names the condition under which it applies, its consequence, and the mitigation. diff --git a/docs/site/src/content/docs/security/documents.mdx b/docs/site/src/content/docs/security/documents.mdx index 58aa1cf5fd..9c19416504 100644 --- a/docs/site/src/content/docs/security/documents.mdx +++ b/docs/site/src/content/docs/security/documents.mdx @@ -223,6 +223,13 @@ The guarantees hold only when you meet these obligations. an_exhausted_transfer_budget_refuses_uploads_and_downloads; crates/registry-documents/src/config.rs allow_insecure_http. */} +Secret files follow the [hardening checklist](../hardening-checklist/#secret-files). The +explicit `secretProviders.file.mountPolicy: compose-native` setting lets every user in the +container read root-owned `0444` secret mounts. Write it only for a container that runs this +service alone under one runtime identity. + +{/* Evidence: crates/registry-platform-config/src/blocks.rs, COMPOSE_NATIVE_SECRET_MOUNT. */} + ## Accepted residuals Related rows are the neighbouring enforced behaviour, not the residual itself. diff --git a/docs/site/src/content/docs/security/evidence.mdx b/docs/site/src/content/docs/security/evidence.mdx index ab3ddf3b30..1229548ba5 100644 --- a/docs/site/src/content/docs/security/evidence.mdx +++ b/docs/site/src/content/docs/security/evidence.mdx @@ -501,6 +501,12 @@ holds the duties no service-side control can hold for you: products/evidence/contracts/runtime.schema.yaml, secretProviders; crates/registry-evidence/src/bundle.rs, validate_read_only. */} +Registry Evidence and both wallet adapters refuse `secretProviders.file.mountPolicy`, so their +key files keep the owner-only rule on Docker Compose too. See the +[hardening checklist](../hardening-checklist/#secret-files). + +{/* Evidence: crates/registry-evidence/src/config.rs, COMPOSE_NATIVE_REFUSED_ACTION. */} + ## Report a vulnerability Report a suspected vulnerability through the process in diff --git a/docs/site/src/content/docs/security/hardening-checklist.mdx b/docs/site/src/content/docs/security/hardening-checklist.mdx index d14ae2b4f1..8f13456ea9 100644 --- a/docs/site/src/content/docs/security/hardening-checklist.mdx +++ b/docs/site/src/content/docs/security/hardening-checklist.mdx @@ -137,12 +137,22 @@ refusal holds in development. Production refuses all of them. regular file with one link and mode exactly `0444` under the declared root. Every user in the container can read such a file, so use it in a container that runs one service under one runtime identity. Startup and the production check report the setting as - `platform.posture.compose-native-secret-mount`. Writable files, other owners, extra links and - paths outside the root stay refused. The + `platform.posture.compose-native-secret-mount`, and the `provision` tools print it when they + read the runtime file. Writable files, other owners, extra links and paths outside the root + stay refused. A runtime that runs as root gains only the `0444` shape: stage its own files at + `0400` or `0600`, because a root-owned `0440` file is still refused. Registry Evidence and both + wallet adapters refuse the setting, since their key rule never lets other users read a key + file. Saved CLI connections and task connection files do not accept it. + The [Messaging Compose setup](../../operate/messaging/#mount-secret-files-with-docker-compose) shows both routes. {/* Evidence: crates/registry-evidence/src/bundle.rs, validate_secret_root; + crates/registry-platform-config/src/blocks.rs, COMPOSE_NATIVE_SECRET_MOUNT, StrictSecretProvidersConfig; + crates/registry-platform-config/src/secrets_tests.rs, compose_native_adds_only_root_owned_single_link_mode_0444; + crates/registry-platform-config/src/blocks_tests.rs, compose_native_mount_is_an_explicit_production_setting_at_its_member; + crates/registry-evidence/src/config.rs, COMPOSE_NATIVE_REFUSED_ACTION; + crates/registry-platform-provision/src/cli.rs, the_runtime_file_explicit_settings_are_printed_on_stderr; deploy/helm/registry-stack/templates/evidence-deployment.yaml, stage-evidence-inputs; deploy/helm/registry-stack/README.md, Images and workload security. */} @@ -156,7 +166,9 @@ changes which keys or certificates your deployment trusts. runtime then reads it under `secretProviders.file.root` with the walk, owner and link rules of a secret, but group and other may read it. A root-owned Compose mount at mode `0444` needs no setting. Group or other write access, an execute bit, another owner or a second link is still - refused. The runtime still parses the JWKS or PEM before use. + refused, with a fix worded for a public document. A file that holds a PEM private key block is + refused, and a key set with a private or symmetric member is refused, so key material staged in + the wrong file never loads. The runtime still parses the JWKS or PEM before use. - If a runtime checks its configuration path with the shared trusted path rule, give it an absolute, normalised path without symbolic links. In production, root or the runtime user must own the file and its ancestors. Clear group and other write access. The rule permits a root-owned sticky @@ -165,9 +177,11 @@ changes which keys or certificates your deployment trusts. product's production configuration check, then confirm readiness. To verify a CA or key set, also exercise an operation that connects to the configured peer or verifies its token. -{/* Evidence: crates/registry-platform-config/src/blocks.rs, JwksSource, DatabaseConfig; +{/* Evidence: crates/registry-platform-config/src/blocks.rs, JwksSource, DatabaseConfig, DatabaseMember; crates/registry-platform-config/src/loader.rs, require_trusted_runtime_path; - crates/registry-platform-config/src/secrets.rs, SecretResolver, resolve_public_document, open_secret_file. */} + crates/registry-platform-config/src/secrets.rs, SecretResolver, resolve_public_document, open_secret_file; + crates/registry-platform-config/src/secrets_tests.rs, a_public_document_drops_only_the_read_checks, a_public_document_holding_a_private_key_is_refused; + crates/registry-breg/src/action_evidence_config.rs, public_jwks_document. */} ## Check BReg and Casework authority diff --git a/docs/site/src/content/docs/security/render.mdx b/docs/site/src/content/docs/security/render.mdx index 1a5e076457..238998c31c 100644 --- a/docs/site/src/content/docs/security/render.mdx +++ b/docs/site/src/content/docs/security/render.mdx @@ -217,6 +217,13 @@ rules only. crates/registry-render/src/pdf_signature.rs sealable_holds_pdf_a_1_2_and_3_to_their_string_length_limits. */} +Secret files follow the [hardening checklist](../hardening-checklist/#secret-files). The +explicit `secretProviders.file.mountPolicy: compose-native` setting lets every user in the +container read root-owned `0444` secret mounts. Write it only for a container that runs this +service alone under one runtime identity. + +{/* Evidence: crates/registry-platform-config/src/blocks.rs, COMPOSE_NATIVE_SECRET_MOUNT. */} + ## How refusals are recorded For OIDC bearer requests, Render matches the exact entry in `authentication.oidc.issuers`. diff --git a/docs/site/src/content/docs/security/scheduling.mdx b/docs/site/src/content/docs/security/scheduling.mdx index 85bc2bda3d..ee594067b7 100644 --- a/docs/site/src/content/docs/security/scheduling.mdx +++ b/docs/site/src/content/docs/security/scheduling.mdx @@ -202,6 +202,13 @@ The guarantees hold only when you meet these obligations. crates/registry-schedulingctl/tests/activation_postgres.rs an_apply_whose_response_audit_entry_is_refused_reports_it_applied_unaudited. */} +Secret files follow the [hardening checklist](../hardening-checklist/#secret-files). The +explicit `secretProviders.file.mountPolicy: compose-native` setting lets every user in the +container read root-owned `0444` secret mounts. Write it only for a container that runs this +service alone under one runtime identity. + +{/* Evidence: crates/registry-platform-config/src/blocks.rs, COMPOSE_NATIVE_SECRET_MOUNT. */} + ## Accepted residuals Each residual names the condition under which it applies, its consequence, the operator diff --git a/products/breg/CHANGELOG.md b/products/breg/CHANGELOG.md index 5f688e05c8..aed26eb2eb 100644 --- a/products/breg/CHANGELOG.md +++ b/products/breg/CHANGELOG.md @@ -2,6 +2,9 @@ ## Unreleased +- The Evidence provider `trustedJwksRef` key set is read as a public document + and refused when it holds a private or symmetric member. + ## 0.49.0 - 2026-12-01 - BREAKING: `bregctl data export` JSONL uses `recordId` and `revisionId` in place of v0.48.0's `recordIdentifier` and `revisionIdentifier`. Migration: Update export file consumers for both keys. Finish an in-progress export with the matching v0.48.0 `bregctl`, serving runtime, and compiled package before upgrading, or start a fresh output and checkpoint pair after upgrading. Convert archived exports on a separate copy to preserve any checkpoint digest. diff --git a/products/evidence/CHANGELOG.md b/products/evidence/CHANGELOG.md index d07ee62f37..4b4e5beaf4 100644 --- a/products/evidence/CHANGELOG.md +++ b/products/evidence/CHANGELOG.md @@ -2,6 +2,11 @@ ## Unreleased +- Evidence, the OID4VCI delivery service and the OID4VP verifier refuse + `secretProviders.file.mountPolicy`, keeping the Version 1 rule that a key + file is never readable by other users. `evidencectl doctor` reports the same + refusal, and the store-provision document does not accept the member. + ## 0.49.0 - 2026-12-01 - BREAKING: Evidence project, bundle, authority, audit, and client lookup declarations use `lookups` and single references use `lookup`. Migration: From v0.48.0, keep the previous binary, bundle, runtime file, authority store, and the active and numeric sealed files for both the service audit and its activation companion (`evidence.jsonl` and `evidence.activation.jsonl` for an `audit.path` of `evidence.jsonl`). Read authority with the v0.48.0 `evidence authority history --runtime-config OLD_RUNTIME`. Inspect the production audit JSON Lines using the matching release's audit schema and activation contract. Copy the authored project and target without the generated authority state. Set fresh `package.root` and `audit.path` values in the copy before packaging, and preserve or explicitly bind its referenced secrets and source extract. Rename `selectorProfiles` to `lookups` and `selectorProfile` (Python `selector_profile`) to `lookup` where the contract renamed those fields. Migrate the target issuer into `authentication.oidc.issuers`. Run `evidencectl package --target TARGET --output CANDIDATE PROJECT` and install the rebuilt bundle at the new package root. The fresh authority root is derived from the copied target directory. Run `evidence authority activate --runtime-config FILE --document CANDIDATE/compiled-authority.yaml`. Confirm sequence 1 in `evidence authority history --runtime-config FILE`, run `evidence check --runtime-config FILE --require-runtime-dependencies`, and start Evidence with `evidence serve --runtime-config FILE`. Verify a fresh signed assertion, its access and disclosure records in the new service stream, and the activation pair in the new activation companion before resuming traffic. diff --git a/products/platform/CHANGELOG.md b/products/platform/CHANGELOG.md index 5be6a25189..cb0b2b5559 100644 --- a/products/platform/CHANGELOG.md +++ b/products/platform/CHANGELOG.md @@ -5,15 +5,27 @@ - The file secret provider accepts `mountPolicy: compose-native`, an explicit production setting that also admits a root-owned, single-link regular file with mode exactly `0444`, the Docker Compose secret mount shape, under the - declared root. Startup and `check` report + declared root. Startup, `check` (including `registry-mcp check` and + `registry-session check`) and the `provision` tools report `platform.posture.compose-native-secret-mount`. The default rule still refuses that shape, and writable files, other owners, extra links and paths - outside the root stay refused in every case. -- Every runtime reads a static JWKS (`jwksSource.documentRef`) and every CA - bundle (`caBundleRef`, Messaging `tlsTrustProfiles.*.bundleRef`) as a public - document: group and other may read the file, with no setting. Owner, link, - write and walk checks still apply, and the document is still parsed before - use. + outside the root stay refused in every case. Registry Evidence and both + wallet adapters refuse the setting, and saved CLI connections and task + connection files do not accept it. +- Every runtime reads a static JWKS (`jwksSource.documentRef`, BReg + `trustedJwksRef`) and every CA bundle (`caBundleRef`, Messaging + `tlsTrustProfiles.*.bundleRef`) as a public document, and so do the + `provision` tools for `database.caBundleRef`: group and other may read the + file, with no setting. Owner, link, write and walk checks still apply, and + the document is still parsed before use. A public document that holds a PEM + private key block is refused, and a refused public document is described + with public-document wording. +- BREAKING for Rust callers of `registry-platform-config`: `SecretError` gains + `UnsafePublicDocument` and `PrivateKeyInPublicDocument`, and + `ProvisionInput` gains `explicit_settings`. Migration: add arms for the two + variants to exhaustive matches (`SecretFileCheck::public_message` and + `public_suggested_action` give their text), and fill `explicit_settings` + from `PostureReport::explicit_setting_notices`. - Numbered releases ship `registry-session` for Linux amd64, Linux arm64 and macOS arm64. It is a standalone release asset: `rstack` does not install it, and it has no installer or container image. Upgrade: `rstack update` from From 472203a2d0ba9526d6786c1d9aa62a4e16a40bde Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 22:12:23 +0000 Subject: [PATCH 107/183] chore: regenerate schemas The runtime schemas carry the reworded mountPolicy description. Each was written by its own generator; the CLI catalog was regenerated and did not change. Refs #2882. Signed-off-by: Jeremi Joslin --- products/adapter/schemas/job-runtime.v1alpha1.schema.json | 2 +- products/adapter/schemas/runtime.v1alpha1.schema.json | 2 +- products/breg/generated/mcp-runtime/mcp-runtime.schema.json | 2 +- .../breg/generated/review-runtime/review-runtime.schema.json | 2 +- products/breg/generated/runtime/runtime.schema.json | 2 +- products/casework/generated/runtime/runtime.schema.json | 2 +- products/coordinator/generated/runtime/runtime.schema.json | 2 +- products/documents/generated/runtime/runtime.schema.json | 2 +- .../generated/oid4vci-runtime/oid4vci-runtime.schema.json | 2 +- .../generated/oid4vp-runtime/oid4vp-runtime.schema.json | 2 +- products/messaging/generated/runtime/runtime.schema.json | 2 +- products/platform/generated/mcp-runtime/mcp-runtime.schema.json | 2 +- products/platform/generated/runtime-config-blocks.schema.json | 2 +- .../generated/session-runtime/session-runtime.schema.json | 2 +- products/render/schemas/runtime.schema.json | 2 +- products/scheduling/generated/runtime/runtime.schema.json | 2 +- 16 files changed, 16 insertions(+), 16 deletions(-) diff --git a/products/adapter/schemas/job-runtime.v1alpha1.schema.json b/products/adapter/schemas/job-runtime.v1alpha1.schema.json index 43fe2b3acf..65edca9821 100644 --- a/products/adapter/schemas/job-runtime.v1alpha1.schema.json +++ b/products/adapter/schemas/job-runtime.v1alpha1.schema.json @@ -125,7 +125,7 @@ "properties": { "mountPolicy": { "$ref": "#/$defs/SecretMountPolicy", - "description": "`compose-native` also accepts a root-owned regular file with one hard\nlink and mode exactly 0444, the shape of a Docker Compose secret mount.\nEvery user in the container can read such a file. Startup and `check`\nreport this explicit production setting. Absent, the stricter rule\nabove applies.", + "description": "`compose-native` also accepts a root-owned regular file with one hard\nlink and mode exactly 0444, the shape of a Docker Compose secret mount.\nEvery user in the container can read such a file. Startup and `check`\nreport this explicit production setting. Without it, only the file\nshapes `root` describes are accepted.", "x-registry-explicit-production": [ "platform.posture.compose-native-secret-mount" ] diff --git a/products/adapter/schemas/runtime.v1alpha1.schema.json b/products/adapter/schemas/runtime.v1alpha1.schema.json index 757a51fcb0..1292518000 100644 --- a/products/adapter/schemas/runtime.v1alpha1.schema.json +++ b/products/adapter/schemas/runtime.v1alpha1.schema.json @@ -308,7 +308,7 @@ "properties": { "mountPolicy": { "$ref": "#/$defs/SecretMountPolicy", - "description": "`compose-native` also accepts a root-owned regular file with one hard\nlink and mode exactly 0444, the shape of a Docker Compose secret mount.\nEvery user in the container can read such a file. Startup and `check`\nreport this explicit production setting. Absent, the stricter rule\nabove applies.", + "description": "`compose-native` also accepts a root-owned regular file with one hard\nlink and mode exactly 0444, the shape of a Docker Compose secret mount.\nEvery user in the container can read such a file. Startup and `check`\nreport this explicit production setting. Without it, only the file\nshapes `root` describes are accepted.", "x-registry-explicit-production": [ "platform.posture.compose-native-secret-mount" ] diff --git a/products/breg/generated/mcp-runtime/mcp-runtime.schema.json b/products/breg/generated/mcp-runtime/mcp-runtime.schema.json index 9c6e2a9ba6..670c75ac18 100644 --- a/products/breg/generated/mcp-runtime/mcp-runtime.schema.json +++ b/products/breg/generated/mcp-runtime/mcp-runtime.schema.json @@ -224,7 +224,7 @@ "properties": { "mountPolicy": { "$ref": "#/$defs/SecretMountPolicy", - "description": "`compose-native` also accepts a root-owned regular file with one hard\nlink and mode exactly 0444, the shape of a Docker Compose secret mount.\nEvery user in the container can read such a file. Startup and `check`\nreport this explicit production setting. Absent, the stricter rule\nabove applies.", + "description": "`compose-native` also accepts a root-owned regular file with one hard\nlink and mode exactly 0444, the shape of a Docker Compose secret mount.\nEvery user in the container can read such a file. Startup and `check`\nreport this explicit production setting. Without it, only the file\nshapes `root` describes are accepted.", "x-registry-explicit-production": [ "platform.posture.compose-native-secret-mount" ] diff --git a/products/breg/generated/review-runtime/review-runtime.schema.json b/products/breg/generated/review-runtime/review-runtime.schema.json index f6e1dbce9b..17e32d145f 100644 --- a/products/breg/generated/review-runtime/review-runtime.schema.json +++ b/products/breg/generated/review-runtime/review-runtime.schema.json @@ -129,7 +129,7 @@ "properties": { "mountPolicy": { "$ref": "#/$defs/SecretMountPolicy", - "description": "`compose-native` also accepts a root-owned regular file with one hard\nlink and mode exactly 0444, the shape of a Docker Compose secret mount.\nEvery user in the container can read such a file. Startup and `check`\nreport this explicit production setting. Absent, the stricter rule\nabove applies.", + "description": "`compose-native` also accepts a root-owned regular file with one hard\nlink and mode exactly 0444, the shape of a Docker Compose secret mount.\nEvery user in the container can read such a file. Startup and `check`\nreport this explicit production setting. Without it, only the file\nshapes `root` describes are accepted.", "x-registry-explicit-production": [ "platform.posture.compose-native-secret-mount" ] diff --git a/products/breg/generated/runtime/runtime.schema.json b/products/breg/generated/runtime/runtime.schema.json index 78313319d4..d147742477 100644 --- a/products/breg/generated/runtime/runtime.schema.json +++ b/products/breg/generated/runtime/runtime.schema.json @@ -718,7 +718,7 @@ "properties": { "mountPolicy": { "$ref": "#/$defs/SecretMountPolicy", - "description": "`compose-native` also accepts a root-owned regular file with one hard\nlink and mode exactly 0444, the shape of a Docker Compose secret mount.\nEvery user in the container can read such a file. Startup and `check`\nreport this explicit production setting. Absent, the stricter rule\nabove applies.", + "description": "`compose-native` also accepts a root-owned regular file with one hard\nlink and mode exactly 0444, the shape of a Docker Compose secret mount.\nEvery user in the container can read such a file. Startup and `check`\nreport this explicit production setting. Without it, only the file\nshapes `root` describes are accepted.", "x-registry-explicit-production": [ "platform.posture.compose-native-secret-mount" ] diff --git a/products/casework/generated/runtime/runtime.schema.json b/products/casework/generated/runtime/runtime.schema.json index 6608e9dee5..9a872c2c64 100644 --- a/products/casework/generated/runtime/runtime.schema.json +++ b/products/casework/generated/runtime/runtime.schema.json @@ -554,7 +554,7 @@ "properties": { "mountPolicy": { "$ref": "#/$defs/SecretMountPolicy", - "description": "`compose-native` also accepts a root-owned regular file with one hard\nlink and mode exactly 0444, the shape of a Docker Compose secret mount.\nEvery user in the container can read such a file. Startup and `check`\nreport this explicit production setting. Absent, the stricter rule\nabove applies.", + "description": "`compose-native` also accepts a root-owned regular file with one hard\nlink and mode exactly 0444, the shape of a Docker Compose secret mount.\nEvery user in the container can read such a file. Startup and `check`\nreport this explicit production setting. Without it, only the file\nshapes `root` describes are accepted.", "x-registry-explicit-production": [ "platform.posture.compose-native-secret-mount" ] diff --git a/products/coordinator/generated/runtime/runtime.schema.json b/products/coordinator/generated/runtime/runtime.schema.json index b87878db7e..26f0669f7e 100644 --- a/products/coordinator/generated/runtime/runtime.schema.json +++ b/products/coordinator/generated/runtime/runtime.schema.json @@ -781,7 +781,7 @@ "properties": { "mountPolicy": { "$ref": "#/$defs/SecretMountPolicy", - "description": "`compose-native` also accepts a root-owned regular file with one hard\nlink and mode exactly 0444, the shape of a Docker Compose secret mount.\nEvery user in the container can read such a file. Startup and `check`\nreport this explicit production setting. Absent, the stricter rule\nabove applies.", + "description": "`compose-native` also accepts a root-owned regular file with one hard\nlink and mode exactly 0444, the shape of a Docker Compose secret mount.\nEvery user in the container can read such a file. Startup and `check`\nreport this explicit production setting. Without it, only the file\nshapes `root` describes are accepted.", "x-registry-explicit-production": [ "platform.posture.compose-native-secret-mount" ] diff --git a/products/documents/generated/runtime/runtime.schema.json b/products/documents/generated/runtime/runtime.schema.json index 9d29d68160..f3a7eeec38 100644 --- a/products/documents/generated/runtime/runtime.schema.json +++ b/products/documents/generated/runtime/runtime.schema.json @@ -307,7 +307,7 @@ "properties": { "mountPolicy": { "$ref": "#/$defs/SecretMountPolicy", - "description": "`compose-native` also accepts a root-owned regular file with one hard\nlink and mode exactly 0444, the shape of a Docker Compose secret mount.\nEvery user in the container can read such a file. Startup and `check`\nreport this explicit production setting. Absent, the stricter rule\nabove applies.", + "description": "`compose-native` also accepts a root-owned regular file with one hard\nlink and mode exactly 0444, the shape of a Docker Compose secret mount.\nEvery user in the container can read such a file. Startup and `check`\nreport this explicit production setting. Without it, only the file\nshapes `root` describes are accepted.", "x-registry-explicit-production": [ "platform.posture.compose-native-secret-mount" ] diff --git a/products/evidence/generated/oid4vci-runtime/oid4vci-runtime.schema.json b/products/evidence/generated/oid4vci-runtime/oid4vci-runtime.schema.json index 75b9566696..834ebdc45e 100644 --- a/products/evidence/generated/oid4vci-runtime/oid4vci-runtime.schema.json +++ b/products/evidence/generated/oid4vci-runtime/oid4vci-runtime.schema.json @@ -184,7 +184,7 @@ "properties": { "mountPolicy": { "$ref": "#/$defs/SecretMountPolicy", - "description": "`compose-native` also accepts a root-owned regular file with one hard\nlink and mode exactly 0444, the shape of a Docker Compose secret mount.\nEvery user in the container can read such a file. Startup and `check`\nreport this explicit production setting. Absent, the stricter rule\nabove applies.", + "description": "`compose-native` also accepts a root-owned regular file with one hard\nlink and mode exactly 0444, the shape of a Docker Compose secret mount.\nEvery user in the container can read such a file. Startup and `check`\nreport this explicit production setting. Without it, only the file\nshapes `root` describes are accepted.", "x-registry-explicit-production": [ "platform.posture.compose-native-secret-mount" ] diff --git a/products/evidence/generated/oid4vp-runtime/oid4vp-runtime.schema.json b/products/evidence/generated/oid4vp-runtime/oid4vp-runtime.schema.json index 959afaf9eb..db104eb886 100644 --- a/products/evidence/generated/oid4vp-runtime/oid4vp-runtime.schema.json +++ b/products/evidence/generated/oid4vp-runtime/oid4vp-runtime.schema.json @@ -311,7 +311,7 @@ "properties": { "mountPolicy": { "$ref": "#/$defs/SecretMountPolicy", - "description": "`compose-native` also accepts a root-owned regular file with one hard\nlink and mode exactly 0444, the shape of a Docker Compose secret mount.\nEvery user in the container can read such a file. Startup and `check`\nreport this explicit production setting. Absent, the stricter rule\nabove applies.", + "description": "`compose-native` also accepts a root-owned regular file with one hard\nlink and mode exactly 0444, the shape of a Docker Compose secret mount.\nEvery user in the container can read such a file. Startup and `check`\nreport this explicit production setting. Without it, only the file\nshapes `root` describes are accepted.", "x-registry-explicit-production": [ "platform.posture.compose-native-secret-mount" ] diff --git a/products/messaging/generated/runtime/runtime.schema.json b/products/messaging/generated/runtime/runtime.schema.json index 3b883e4755..98672fd462 100644 --- a/products/messaging/generated/runtime/runtime.schema.json +++ b/products/messaging/generated/runtime/runtime.schema.json @@ -290,7 +290,7 @@ "properties": { "mountPolicy": { "$ref": "#/$defs/SecretMountPolicy", - "description": "`compose-native` also accepts a root-owned regular file with one hard\nlink and mode exactly 0444, the shape of a Docker Compose secret mount.\nEvery user in the container can read such a file. Startup and `check`\nreport this explicit production setting. Absent, the stricter rule\nabove applies.", + "description": "`compose-native` also accepts a root-owned regular file with one hard\nlink and mode exactly 0444, the shape of a Docker Compose secret mount.\nEvery user in the container can read such a file. Startup and `check`\nreport this explicit production setting. Without it, only the file\nshapes `root` describes are accepted.", "x-registry-explicit-production": [ "platform.posture.compose-native-secret-mount" ] diff --git a/products/platform/generated/mcp-runtime/mcp-runtime.schema.json b/products/platform/generated/mcp-runtime/mcp-runtime.schema.json index be01339097..0d59c64a31 100644 --- a/products/platform/generated/mcp-runtime/mcp-runtime.schema.json +++ b/products/platform/generated/mcp-runtime/mcp-runtime.schema.json @@ -312,7 +312,7 @@ "properties": { "mountPolicy": { "$ref": "#/$defs/SecretMountPolicy", - "description": "`compose-native` also accepts a root-owned regular file with one hard\nlink and mode exactly 0444, the shape of a Docker Compose secret mount.\nEvery user in the container can read such a file. Startup and `check`\nreport this explicit production setting. Absent, the stricter rule\nabove applies.", + "description": "`compose-native` also accepts a root-owned regular file with one hard\nlink and mode exactly 0444, the shape of a Docker Compose secret mount.\nEvery user in the container can read such a file. Startup and `check`\nreport this explicit production setting. Without it, only the file\nshapes `root` describes are accepted.", "x-registry-explicit-production": [ "platform.posture.compose-native-secret-mount" ] diff --git a/products/platform/generated/runtime-config-blocks.schema.json b/products/platform/generated/runtime-config-blocks.schema.json index 508178e1dc..fb523197a7 100644 --- a/products/platform/generated/runtime-config-blocks.schema.json +++ b/products/platform/generated/runtime-config-blocks.schema.json @@ -591,7 +591,7 @@ "properties": { "mountPolicy": { "$ref": "#/$defs/SecretMountPolicy", - "description": "`compose-native` also accepts a root-owned regular file with one hard\nlink and mode exactly 0444, the shape of a Docker Compose secret mount.\nEvery user in the container can read such a file. Startup and `check`\nreport this explicit production setting. Absent, the stricter rule\nabove applies.", + "description": "`compose-native` also accepts a root-owned regular file with one hard\nlink and mode exactly 0444, the shape of a Docker Compose secret mount.\nEvery user in the container can read such a file. Startup and `check`\nreport this explicit production setting. Without it, only the file\nshapes `root` describes are accepted.", "x-registry-explicit-production": [ "platform.posture.compose-native-secret-mount" ] diff --git a/products/platform/generated/session-runtime/session-runtime.schema.json b/products/platform/generated/session-runtime/session-runtime.schema.json index 2db6d6be04..2b746747f8 100644 --- a/products/platform/generated/session-runtime/session-runtime.schema.json +++ b/products/platform/generated/session-runtime/session-runtime.schema.json @@ -147,7 +147,7 @@ "properties": { "mountPolicy": { "$ref": "#/$defs/SecretMountPolicy", - "description": "`compose-native` also accepts a root-owned regular file with one hard\nlink and mode exactly 0444, the shape of a Docker Compose secret mount.\nEvery user in the container can read such a file. Startup and `check`\nreport this explicit production setting. Absent, the stricter rule\nabove applies.", + "description": "`compose-native` also accepts a root-owned regular file with one hard\nlink and mode exactly 0444, the shape of a Docker Compose secret mount.\nEvery user in the container can read such a file. Startup and `check`\nreport this explicit production setting. Without it, only the file\nshapes `root` describes are accepted.", "x-registry-explicit-production": [ "platform.posture.compose-native-secret-mount" ] diff --git a/products/render/schemas/runtime.schema.json b/products/render/schemas/runtime.schema.json index a88318513b..2d93323b55 100644 --- a/products/render/schemas/runtime.schema.json +++ b/products/render/schemas/runtime.schema.json @@ -179,7 +179,7 @@ "properties": { "mountPolicy": { "$ref": "#/$defs/SecretMountPolicy", - "description": "`compose-native` also accepts a root-owned regular file with one hard\nlink and mode exactly 0444, the shape of a Docker Compose secret mount.\nEvery user in the container can read such a file. Startup and `check`\nreport this explicit production setting. Absent, the stricter rule\nabove applies.", + "description": "`compose-native` also accepts a root-owned regular file with one hard\nlink and mode exactly 0444, the shape of a Docker Compose secret mount.\nEvery user in the container can read such a file. Startup and `check`\nreport this explicit production setting. Without it, only the file\nshapes `root` describes are accepted.", "x-registry-explicit-production": [ "platform.posture.compose-native-secret-mount" ] diff --git a/products/scheduling/generated/runtime/runtime.schema.json b/products/scheduling/generated/runtime/runtime.schema.json index 7e108ef536..1a2795d840 100644 --- a/products/scheduling/generated/runtime/runtime.schema.json +++ b/products/scheduling/generated/runtime/runtime.schema.json @@ -334,7 +334,7 @@ "properties": { "mountPolicy": { "$ref": "#/$defs/SecretMountPolicy", - "description": "`compose-native` also accepts a root-owned regular file with one hard\nlink and mode exactly 0444, the shape of a Docker Compose secret mount.\nEvery user in the container can read such a file. Startup and `check`\nreport this explicit production setting. Absent, the stricter rule\nabove applies.", + "description": "`compose-native` also accepts a root-owned regular file with one hard\nlink and mode exactly 0444, the shape of a Docker Compose secret mount.\nEvery user in the container can read such a file. Startup and `check`\nreport this explicit production setting. Without it, only the file\nshapes `root` describes are accepted.", "x-registry-explicit-production": [ "platform.posture.compose-native-secret-mount" ] From 9e41962c98c7c0930d5a5242e4c1b7059d816c10 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 22:21:27 +0000 Subject: [PATCH 108/183] test(evidence-oid4vci): write the schema test's reference offers as issuer entries A pre-existing bug on main, found during the #2882 checks and independent of it: the offer boundary moved to offers.issuers. in 69516adf3, but the schema test's reference deployment still wrote the flat issuer members, so the test (run only with --features schema) failed on its first assertion. The refusals now aim at the issuer entry, and the retired duplicate-audience case is replaced by an empty issuer map, which the schema refuses with minProperties. Signed-off-by: Jeremi Joslin --- .../registry-evidence-oid4vci/src/schema.rs | 27 ++++++++++++------- 1 file changed, 17 insertions(+), 10 deletions(-) diff --git a/crates/registry-evidence-oid4vci/src/schema.rs b/crates/registry-evidence-oid4vci/src/schema.rs index c38d313e1b..0e6d3658ec 100644 --- a/crates/registry-evidence-oid4vci/src/schema.rs +++ b/crates/registry-evidence-oid4vci/src/schema.rs @@ -156,13 +156,20 @@ mod tests { "clientAssertionAudience": "https://mint.example.org" }, "offers": { - "issuer": "https://mint.example.org", - "jwksUri": "https://mint.example.org/.well-known/jwks.json", - "audiences": ["https://wallet.example.org"], - "algorithms": ["EdDSA"], - "allowedClients": ["adopter-front-end"], - "requiredScopes": ["oid4vci:offer"], - "maximumTokenLifetimeSeconds": 900 + "issuers": { + "primary": { + "issuer": "https://mint.example.org", + "jwksSource": { + "type": "uri", + "uri": "https://mint.example.org/.well-known/jwks.json" + }, + "audience": "https://wallet.example.org", + "algorithms": ["EdDSA"], + "allowedClients": ["adopter-front-end"], + "maximumTokenLifetimeSeconds": 900 + } + }, + "requiredScopes": ["oid4vci:offer"] }, "store": { "maximumOffers": 4096, @@ -218,7 +225,7 @@ mod tests { document["tokenClient"]["privateKeyRef"] = Value::from("/run/secrets/client.jwk") })); assert!(refused(&|document| { - document["offers"]["allowedClients"] = serde_json::json!([]) + document["offers"]["issuers"]["primary"]["allowedClients"] = serde_json::json!([]) })); assert!(refused(&|document| { document["offers"]["requiredScopes"] = Value::from("anything") @@ -230,13 +237,13 @@ mod tests { .remove("requiredScopes"); })); assert!(refused(&|document| { - document["offers"]["audiences"] = serde_json::json!(["a", "a"]) + document["offers"]["issuers"] = serde_json::json!({}) })); assert!(refused(&|document| { document["store"]["maximumOffers"] = Value::from(255) })); assert!(!refused(&|document| { - document["offers"]["allowedClients"] = Value::from("unrestricted") + document["offers"]["issuers"]["primary"]["allowedClients"] = Value::from("unrestricted") })); } From f95d24a8187029a188319d9f5bc5df8423f5b291 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 22:24:29 +0000 Subject: [PATCH 109/183] fix(preview): load business registration assets by relative URL The Compose reference host serves the preview page under the Session route /apply/, where root-absolute /app.js and /service.css match no route and the page renders without its script and styles. Relative references resolve to the same files at / under rstack dev and under /apply/ in the reference. Signed-off-by: Jeremi Joslin --- .../examples/business-registration/README.md | 6 ++-- .../tests/test_page_assets.py | 34 +++++++++++++++++++ .../web/public/index.html | 4 +-- 3 files changed, 39 insertions(+), 5 deletions(-) create mode 100644 deploy/examples/business-registration/tests/test_page_assets.py diff --git a/deploy/examples/business-registration/README.md b/deploy/examples/business-registration/README.md index f0e58f1a3e..b68c7a940e 100644 --- a/deploy/examples/business-registration/README.md +++ b/deploy/examples/business-registration/README.md @@ -36,9 +36,9 @@ project needs its own input, audit, checked-config and socket directories. Generate the preview bundle with the matching preview builder. The recipe uses its `manifest.json`, `functions/register-business.mjs`, and the three files in the manifest's `staticOutput` directory, `index.html`, `app.js` and -`service.css`. Use a build whose page references its assets by relative URL so -the same page can run under `/apply/`. The digest covers each of these five -files and its relative path. Derive it once from the reviewed build, then +`service.css`. The page loads its assets by relative URL, so the same page +runs at `/` under `rstack dev` and at `/apply/` here. The digest covers each of +these five files and its relative path. Derive it once from the reviewed build, then include that value in the instance's input file. ```bash diff --git a/deploy/examples/business-registration/tests/test_page_assets.py b/deploy/examples/business-registration/tests/test_page_assets.py new file mode 100644 index 0000000000..07882eb1f9 --- /dev/null +++ b/deploy/examples/business-registration/tests/test_page_assets.py @@ -0,0 +1,34 @@ +"""Check that the preview page this recipe serves under /apply/ loads its own assets.""" + +from html.parser import HTMLParser +from pathlib import Path +import unittest + + +ROOT = Path(__file__).resolve().parents[4] +PAGE = ROOT / "products/platform/examples/service-previews/business-registration/web/public/index.html" + + +class AssetReferences(HTMLParser): + def __init__(self): + super().__init__() + self.references = [] + + def handle_starttag(self, tag, attrs): + values = dict(attrs) + if tag == "link" and values.get("rel") == "stylesheet": + self.references.append(values["href"]) + elif tag == "script" and "src" in values: + self.references.append(values["src"]) + + +class PreviewPageAssets(unittest.TestCase): + def test_page_assets_resolve_under_any_page_route(self): + # rstack dev serves the page at / and the Session page route serves it at /apply/. + parser = AssetReferences() + parser.feed(PAGE.read_text(encoding="utf-8")) + self.assertEqual(sorted(parser.references), ["app.js", "service.css"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/products/platform/examples/service-previews/business-registration/web/public/index.html b/products/platform/examples/service-previews/business-registration/web/public/index.html index 3a3eebfb2f..17b146d9b8 100644 --- a/products/platform/examples/service-previews/business-registration/web/public/index.html +++ b/products/platform/examples/service-previews/business-registration/web/public/index.html @@ -4,8 +4,8 @@ Register a business - - + + From 48dfbbb0e2bc265336a3c5c59f294da543daa493 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 22:25:56 +0000 Subject: [PATCH 110/183] fix(deploy): assign reference registrars through service roles The roles baseline refuses grants in an identity deployment and reads the roles from a sibling service.yaml, so rstack identity generate refused the reference file. The registrar role matches the preview's own service.yaml, and the generated resources and front gateway are unchanged. Signed-off-by: Jeremi Joslin --- .../business-registration/identity-deployment.yaml | 14 +++----------- deploy/examples/business-registration/service.yaml | 9 +++++++++ 2 files changed, 12 insertions(+), 11 deletions(-) create mode 100644 deploy/examples/business-registration/service.yaml diff --git a/deploy/examples/business-registration/identity-deployment.yaml b/deploy/examples/business-registration/identity-deployment.yaml index 8cc5566963..45e8c8c243 100644 --- a/deploy/examples/business-registration/identity-deployment.yaml +++ b/deploy/examples/business-registration/identity-deployment.yaml @@ -12,27 +12,19 @@ sessionApps: postLogoutRedirectUris: [https://127.0.0.1:8443/session/signed-out] products: [breg] tokenAttributes: [registry_actor_kind, registry_office] - grants: - - product: breg - accessProfiles: [business-registrar] + roles: [registrar] users: - id: reference-registrar username: reference-registrar email: reference-registrar@example.invalid passwordRef: secret:env/REGISTRAR_PASSWORD claims: - registry_actor_kind: human registry_office: central - grants: - - product: breg - accessProfiles: [business-registrar] + roles: [registrar] - id: reference-registrar-two username: reference-registrar-two email: reference-registrar-two@example.invalid passwordRef: secret:env/SECOND_REGISTRAR_PASSWORD claims: - registry_actor_kind: human registry_office: central - grants: - - product: breg - accessProfiles: [business-registrar] + roles: [registrar] diff --git a/deploy/examples/business-registration/service.yaml b/deploy/examples/business-registration/service.yaml new file mode 100644 index 0000000000..ae754caf1b --- /dev/null +++ b/deploy/examples/business-registration/service.yaml @@ -0,0 +1,9 @@ +apiVersion: id.registrystack.org/formats/rstack/service/v1alpha1 +kind: RStackService +# Identity generation reads these roles beside identity-deployment.yaml. They +# match the business-registration preview's own service.yaml. +roles: + registrar: + actorKind: human + claims: [registry_office] + accessProfiles: {breg: [business-registrar]} From f8b321279c5d76b59fc0dd340469e0c45e59538a Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 22:25:56 +0000 Subject: [PATCH 111/183] test(deploy): run the reference host's Node tests in the deployment suite The deployment CI job runs only Python tests under deploy/, so the host's digest pin, bundle confinement, body limit and method refusals never ran. The wrapper installs the locked dependencies in a scratch copy and skips only without Node.js and npm. The page host now sends the preview CSP, and a startup failure names its error code. Signed-off-by: Jeremi Joslin --- .../examples/business-registration/host.mjs | 10 ++++-- .../business-registration/tests/host.test.mjs | 4 +++ .../tests/test_host_node.py | 35 +++++++++++++++++++ 3 files changed, 47 insertions(+), 2 deletions(-) create mode 100644 deploy/examples/business-registration/tests/test_host_node.py diff --git a/deploy/examples/business-registration/host.mjs b/deploy/examples/business-registration/host.mjs index 9349b467d1..069c4f6330 100644 --- a/deploy/examples/business-registration/host.mjs +++ b/deploy/examples/business-registration/host.mjs @@ -71,7 +71,12 @@ function requestPage(request, assets) { return new Response(null, { status: 405, headers: { allow: 'GET, HEAD' } }) } return new Response(request.method === 'GET' ? bytes : null, { - headers: { 'content-type': pages.get(path), 'x-content-type-options': 'nosniff' }, + headers: { + 'content-type': pages.get(path), + 'x-content-type-options': 'nosniff', + // The same policy the rstack dev preview gateway sends with the page. + 'content-security-policy': "default-src 'self'; base-uri 'none'; frame-ancestors 'none'", + }, }) } @@ -125,7 +130,8 @@ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) const message = error.message === 'The preview bundle digest differs from the deployment pin.' ? error.message : 'The reference host could not load its checked bundle or start its private listeners.' - console.error(message) + // The error code (for example ENOENT or EADDRINUSE) names the cause without file contents. + console.error(error?.code ? `${message} (${error.code})` : message) process.exitCode = 1 } } diff --git a/deploy/examples/business-registration/tests/host.test.mjs b/deploy/examples/business-registration/tests/host.test.mjs index d9a79d5529..4accdddacc 100644 --- a/deploy/examples/business-registration/tests/host.test.mjs +++ b/deploy/examples/business-registration/tests/host.test.mjs @@ -46,6 +46,10 @@ test('loads the checked bundle and serves only the declared function and page as assert.equal((await page.text()), 'index.html') assert.equal(page.headers.get('content-type'), 'text/html; charset=utf-8') assert.equal(page.headers.get('x-content-type-options'), 'nosniff') + assert.equal( + page.headers.get('content-security-policy'), + "default-src 'self'; base-uri 'none'; frame-ancestors 'none'", + ) assert.equal((await fetch(host.pagesOrigin + '/app.js', { method: 'HEAD' })).status, 200) assert.equal((await fetch(host.pagesOrigin + '/app.js', { method: 'POST' })).status, 405) for (const path of ['/manifest.json', '/functions/register-business.mjs', '/project/web/dist/index.html']) { diff --git a/deploy/examples/business-registration/tests/test_host_node.py b/deploy/examples/business-registration/tests/test_host_node.py new file mode 100644 index 0000000000..2130488aa2 --- /dev/null +++ b/deploy/examples/business-registration/tests/test_host_node.py @@ -0,0 +1,35 @@ +"""Run the Node reference host's own tests from the deployment suite.""" + +from pathlib import Path +import shutil +import subprocess +import tempfile +import unittest + + +EXAMPLE = Path(__file__).resolve().parents[1] +NODE = shutil.which("node") +NPM = shutil.which("npm") + + +@unittest.skipUnless(NODE and NPM, "Node.js and npm are needed to test the reference host") +class ReferenceHost(unittest.TestCase): + def test_host_node_suite_passes(self): + # Install the locked dependencies in a scratch copy so the recipe stays unchanged. + with tempfile.TemporaryDirectory(prefix="reference-host-") as scratch: + work = Path(scratch) + for name in ("package.json", "package-lock.json", "host.mjs"): + shutil.copy2(EXAMPLE / name, work / name) + shutil.copytree(EXAMPLE / "tests", work / "tests") + for command in ( + [NPM, "ci", "--ignore-scripts", "--no-audit", "--no-fund"], + [NPM, "test"], + ): + result = subprocess.run(command, cwd=work, capture_output=True, text=True) + self.assertEqual( + result.returncode, 0, f"{' '.join(command[1:])} failed:\n{result.stdout}\n{result.stderr}" + ) + + +if __name__ == "__main__": + unittest.main() From 076977658b58fa45f5128dc181620cc481fd294c Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 22:28:32 +0000 Subject: [PATCH 112/183] docs(deploy): make the business registration reference runnable as written A first-time operator could not prepare, own or remove the reference from the guide: bundle, certificate and identity steps were prose, the root-only ownership step was implicit, and nothing removed volumes, images or bind directories. Name the two plain HTTP issuer hops and the residual reach instead of claiming verified TLS throughout, and target the first release that ships registry-session. Signed-off-by: Jeremi Joslin --- .../examples/business-registration/README.md | 186 +++++++++++++++--- 1 file changed, 163 insertions(+), 23 deletions(-) diff --git a/deploy/examples/business-registration/README.md b/deploy/examples/business-registration/README.md index b68c7a940e..e48d40f3a8 100644 --- a/deploy/examples/business-registration/README.md +++ b/deploy/examples/business-registration/README.md @@ -3,8 +3,10 @@ Run the business-registration preview's compiled function and static page with Registry Session, Envoy, ThunderID, BReg and PostgreSQL. The application opens at `https://127.0.0.1:8443/apply/`. Use a disposable project and synthetic -registrars. The example uses production posture and verified TLS with loopback -host bindings. +registrars. The example uses production posture and loopback host bindings. +Product, Session and database connections use verified TLS. Two issuer hops on +internal Docker networks are plain HTTP, as described in +[Plain HTTP issuer hops](#plain-http-issuer-hops). The browser receives an opaque Session cookie. Envoy checks it and supplies the registrar's access token on the private function and registry routes. @@ -12,19 +14,55 @@ The function uses that token for the existing BReg Action. BReg applies its own access profile, issuer, scope and row rules. The Node host has read-only bundle files and no database or issuer credentials. +## Plain HTTP issuer hops + +The edge terminates issuer TLS at `127.0.0.1:9443`. Behind it, two hops carry +issuer traffic as plain HTTP: + +- The edge sends issuer requests to `identity-gateway:8080` on the + `issuer-front` network. +- The identity gateway sends them to ThunderID on port 8090 on the + `identity-backend` network. ThunderID also listens on the + `identity-database` network, which it shares with PostgreSQL. + +These hops carry registrar passwords from the sign-in form, the Session client +secret, authorization codes, and access, ID and refresh tokens. The reference +accepts them because each network is internal, has only those members, and +every container drops all capabilities. The generated front gateway addresses +ThunderID by its service name, `thunderid:8090`, so the gateway cannot share +ThunderID's network namespace without putting plain ThunderID on the edge's +network. Treat any process that can join these networks as able to read issuer +traffic. A deployment across hosts needs TLS on both hops. + +Other reach is wider than the function needs: + +- The function host shares BReg's network namespace, so it can reach + `postgres:5432`. `pg_hba.conf` admits any role over TLS, including the + `postgres` superuser, from any address on the database network. +- The `ingress` network is not internal, so the Session and gateway namespace + has outbound internet access. +- The Node host accepts any well-formed bearer token on its private function + route. Any host process running as `REFERENCE_UID` can connect to the relay + sockets directly. BReg still verifies every token, so such a caller gains no + registry authority. + ## Prepare the deployment inputs -Use Docker Compose v2 on Linux amd64. Set `RECIPE` to the absolute path of this -directory and prepare a fresh private directory for `REFERENCE_CONFIG`. Stage -`breg`, `bregctl` and `registry-session` in `REFERENCE_ARTIFACTS`. Verify the -matching BReg release binaries against their manifest. Use a matching native -Session binary verified against the local candidate's artifact receipt until -Session is available in a numbered release. +Use Linux amd64 with Docker Engine, the Compose v2 plugin, `openssl`, `curl`, +`jq` and root access through `sudo` for the ownership step. The host test also +needs Node.js 24 with npm, and the two-person browser check needs Playwright. +Set `RECIPE` to the absolute path of this directory and prepare a fresh private +directory for `REFERENCE_CONFIG`. + +Use Registry Stack v0.51.0 or later. From v0.51.0, numbered releases ship +`registry-session` as a standalone asset beside the `rstack` installer. Stage +`breg`, `bregctl` and `registry-session` from the same release in +`REFERENCE_ARTIFACTS`, and verify each against the release manifest. Set these inputs in your shell and in a Compose environment file. Use absolute paths. Set `REFERENCE_UID` and `REFERENCE_GID` if the nonroot owner of these -inputs differs from 1000. Both Envoy relays use this same UID. Each Compose -project needs its own input, audit, checked-config and socket directories. +inputs differs from 1000. Both Envoy relays use this same UID. Run one instance +per host: the host ports 8443 and 9443 are fixed. | Variable | Value | | --- | --- | @@ -33,13 +71,32 @@ project needs its own input, audit, checked-config and socket directories. | `BUSINESS_BUNDLE` | Build output of the business-registration preview | | `BUSINESS_BUNDLE_SHA256` | Runtime file digest of the reviewed preview build | -Generate the preview bundle with the matching preview builder. The recipe uses -its `manifest.json`, `functions/register-business.mjs`, and the three files in +Build the preview bundle by starting the preview with `rstack dev`. Set +`PREVIEW` to the `products/platform/examples/service-previews/business-registration` +directory of the release source and `BUSINESS_BUNDLE` to a new empty directory. +The run writes its compiled preview into an `application-preview` directory +under its state directory. Copy the files before you stop the run. + +```bash +RSTACK_DEV_STATE_DIR=$(mktemp -d) +export RSTACK_DEV_STATE_DIR +(cd "$PREVIEW" && rstack dev start . --ttl 30m) | tee "$RSTACK_DEV_STATE_DIR/run.txt" +run=$(awk '$1 == "Run" {print $2}' "$RSTACK_DEV_STATE_DIR/run.txt") +built=$(find "$RSTACK_DEV_STATE_DIR" -type d -path "*$run*" -name application-preview) +static=$(jq -r .staticOutput "$built/manifest.json") +install -d "$BUSINESS_BUNDLE/functions" "$BUSINESS_BUNDLE/$static" +install -m 0644 "$built/manifest.json" "$BUSINESS_BUNDLE/" +install -m 0644 "$built/functions/register-business.mjs" "$BUSINESS_BUNDLE/functions/" +install -m 0644 "$built/$static/"{index.html,app.js,service.css} "$BUSINESS_BUNDLE/$static/" +rstack dev stop "$run" +``` + +The recipe uses the bundle's `manifest.json`, `functions/register-business.mjs`, and the three files in the manifest's `staticOutput` directory, `index.html`, `app.js` and `service.css`. The page loads its assets by relative URL, so the same page runs at `/` under `rstack dev` and at `/apply/` here. The digest covers each of -these five files and its relative path. Derive it once from the reviewed build, then -include that value in the instance's input file. +these five files and its relative path. Derive it once from the reviewed build, +then include that value in the instance's input file. ```bash bundle_host=$(docker build --quiet "$RECIPE") @@ -72,10 +129,33 @@ package receipt. | `gateway/envoy.json` | Reviewed complete Envoy configuration from the matching Session CLI | | `gateway-checked/`, `relay/`, `breg/audit/`, `session/audit/` | Empty private directories owned by the instance UID | +Make the three TLS pairs from one disposable CA. Keep the CA key in a private +directory outside `REFERENCE_CONFIG`, set as `REFERENCE_CA`. + +```bash +umask 077 +mkdir -p "$REFERENCE_CA" "$REFERENCE_CONFIG"/{app-tls,issuer-tls,postgres,trust} +ca="$REFERENCE_CA/reference-ca" +openssl req -x509 -newkey ec -pkeyopt ec_paramgen_curve:P-256 -nodes -days 30 \ + -subj "/CN=Business registration reference CA" \ + -addext basicConstraints=critical,CA:TRUE -addext keyUsage=critical,keyCertSign,cRLSign \ + -keyout "$ca.key" -out "$ca.pem" +issue() { # issue DIRECTORY NAME SUBJECT_ALT_NAME + openssl req -newkey ec -pkeyopt ec_paramgen_curve:P-256 -nodes -subj "/CN=$2" \ + -keyout "$1/$2.key" -out "$REFERENCE_CA/$2.csr" + openssl x509 -req -in "$REFERENCE_CA/$2.csr" -CA "$ca.pem" -CAkey "$ca.key" -days 30 \ + -extfile <(printf 'subjectAltName=%s\nextendedKeyUsage=serverAuth\nbasicConstraints=critical,CA:FALSE\n' "$3") \ + -out "$1/$2.crt" +} +issue "$REFERENCE_CONFIG/app-tls" app IP:127.0.0.1 +issue "$REFERENCE_CONFIG/issuer-tls" issuer DNS:identity.reference.test +issue "$REFERENCE_CONFIG/postgres" server DNS:postgres +install -m 0644 "$ca.pem" "$REFERENCE_CONFIG/trust/https-ca.pem" +install -m 0644 "$ca.pem" "$REFERENCE_CONFIG/trust/postgres-ca.pem" +``` + The Session client secret equals `REGISTRAR_CLIENT_SECRET`. Both ThunderID `DB_CONFIG_PASSWORD` files carry the value in `postgres/thunderid-password`. -The PostgreSQL files must be readable by the image's UID 999 and the -ThunderID secrets by UID 10001. Give private keys and secret files mode 0600. Use distinct random values for admin, both registrar passwords, database and audit credentials. BReg URLs target `postgres:5432`; runtime and migration use different roles and @@ -84,12 +164,29 @@ passwords and point at the same registry database. BReg's CA file carries `identity.reference.test` to `127.0.0.1` and trust the HTTPS CA. Generate the issuer inputs with the matching `rstack identity generate thunderid` -command and [identity-deployment.yaml](identity-deployment.yaml). Use the -preview's BReg project and a host-side copy of the BReg runtime file whose -package and secret-provider roots exist and are readable. The private resource -files carry references to the secret names above. Stage the generated -`resources/`, `front-gateway/` and `identity-receipt.json` at the paths in the -table. Merge the generated ThunderID store settings into the serving deployment +command, [identity-deployment.yaml](identity-deployment.yaml) and the registrar +role in [service.yaml](service.yaml). Use the preview's BReg project and a +host-side copy of the BReg runtime file whose package and secret-provider roots +point at the staged admin inputs. Check the runtime as a production runtime and +pin the expected issuer. The private resource files carry references to the +secret names above. + +```bash +identity_work=$(mktemp -d) +sed -e "s|/run/breg/secrets|$REFERENCE_CONFIG/breg/admin/secrets|" \ + -e "s|/run/breg/package|$REFERENCE_CONFIG/breg/admin/package|" \ + "$REFERENCE_CONFIG/breg/admin/runtime.yaml" >"$identity_work/breg-runtime.yaml" +rstack identity generate thunderid --deployment "$RECIPE/identity-deployment.yaml" \ + --breg-project "$PREVIEW/project" --breg-runtime-config "$identity_work/breg-runtime.yaml" \ + --breg-production --expected-issuer https://identity.reference.test:9443 \ + --output "$identity_work/generated" +install -d -m 0700 "$REFERENCE_CONFIG/thunderid/resources" "$REFERENCE_CONFIG/thunderid/front-gateway" +install -m 0600 "$identity_work/generated/resources/resources.yaml" "$REFERENCE_CONFIG/thunderid/resources/" +install -m 0600 "$identity_work/generated/front-gateway/envoy.yaml" "$REFERENCE_CONFIG/thunderid/front-gateway/" +install -m 0600 "$identity_work/generated/identity-receipt.json" "$REFERENCE_CONFIG/thunderid/" +``` + +Merge the generated ThunderID store settings into the serving deployment file, retaining the supplied `server`, `jwt`, `crypto` and `database` blocks. The generated issuer, application registration, subject claims and registrar scope must agree with the BReg and Session files. @@ -127,10 +224,26 @@ separate gateway namespace. The two Envoy relays connect these namespaces over three private owner-only Unix sockets. The host app port passes TLS through to the Session-checked gateway. +### Set ownership and modes + +Each container reads its inputs under its own UID. Compose mounts each path +directly, so the modes of the parent directories do not matter to the +containers. + +| Paths under `REFERENCE_CONFIG` | Owner | Mode | Read by | +| --- | --- | --- | --- | +| `postgres/` and everything in it | 999:999, needs root | directories 0700, files 0600 | PostgreSQL, which refuses a key that its user does not own | +| `thunderid/bootstrap.yaml`, `thunderid/deployment.yaml`, `thunderid/resources/`, `thunderid/secrets/`, `thunderid/bootstrap-secrets/` | 10001:10001, needs root | directories 0700, files 0600 | ThunderID setup and the serving issuer | +| `trust/` | `REFERENCE_UID` | directory 0755, files 0644 | Every service, including ThunderID through `PGSSLROOTCERT` | +| Everything else | `REFERENCE_UID`:`REFERENCE_GID` | directories 0700, keys and secrets 0600 | Envoy, Session, BReg, the gateway check and the Node host | + +Apply the root-owned rows after the schema files are staged, in the next +section. + ## Start with empty state Set `REFERENCE_ENV` to the absolute path of the Compose environment file. -Choose a unique project name. Extract the database scripts before starting +Extract the database scripts before starting PostgreSQL. The initialization script creates only ThunderID's four databases and applies the matching schemas as the ThunderID role. @@ -144,6 +257,12 @@ for schema in config:configdb entity:entitydb runtime_transient:runtime_transien "dbscripts/${schema#*:}/postgres.sql" > "$REFERENCE_CONFIG/postgres/schema/${schema%%:*}.sql" done +sudo chown -R 999:999 "$REFERENCE_CONFIG/postgres" +sudo chmod -R u=rwX,go= "$REFERENCE_CONFIG/postgres" +thunderid_inputs=("$REFERENCE_CONFIG"/thunderid/{bootstrap.yaml,deployment.yaml,resources,secrets,bootstrap-secrets}) +sudo chown -R 10001:10001 "${thunderid_inputs[@]}" +sudo chmod -R u=rwX,go= "${thunderid_inputs[@]}" + "${compose[@]}" up --detach --wait postgres "${compose[@]}" run -T --rm thunderid-setup @@ -167,6 +286,9 @@ and encryption material live in project-owned volumes. `docker compose stop` preserves those volumes. Session state is in memory and a Session restart requires signing in again. +After setup, remove the bootstrap administrator password, or move it offline: +`sudo rm "$REFERENCE_CONFIG/thunderid/bootstrap-secrets/ADMIN_PASSWORD"`. + ## Check the routes Run `bash "$RECIPE/tests/smoke.sh" "$REFERENCE_CONFIG/trust/https-ca.pem"`. @@ -196,5 +318,23 @@ is refused, the protected page asks for sign-in again, and the second registrar can still read its Record. It checks application requests for browser-sent Authorization headers throughout. +## Remove the instance + +Stop the containers and remove the project's volumes, networks and the +locally built application image. Then remove the bundle digest image. + +```bash +"${compose[@]}" --profile setup down --volumes --remove-orphans --rmi local +docker image rm "$bundle_host" +``` + +The containers write into the private bind directories: audit JSONL files +under `breg/audit/` and `session/audit/`, relay sockets under `relay/`, the +checked `gateway-checked/envoy.json`, and the staged `postgres/schema/` files. +Keep the audit files if you need them, then delete `REFERENCE_CONFIG` with root, +because some files belong to UIDs 999 and 10001. Also delete `REFERENCE_CA`, +`BUSINESS_BUNDLE`, the identity work directory and the preview run's +`RSTACK_DEV_STATE_DIR`. + Release-candidate smoke wiring, published Session and Coordinator images, and the `rstack dev` route-parity gate are v0.52 work. From 988ad5aea0d0f46c42d677c0787efbc71f639ab1 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 22:36:34 +0000 Subject: [PATCH 113/183] fix(deploy): keep issuer key material read-only and PostgreSQL unprivileged The serving ThunderID could rewrite its signing and encryption material, and PostgreSQL was the one service without no-new-privileges. A Compose run of the reference passed its smoke probe and two-registrar browser check with both restrictions, and a fresh initdb works under no-new-privileges. Signed-off-by: Jeremi Joslin --- deploy/examples/business-registration/compose.yaml | 10 ++++++---- .../business-registration/tests/test_compose.py | 11 +++++++++++ 2 files changed, 17 insertions(+), 4 deletions(-) diff --git a/deploy/examples/business-registration/compose.yaml b/deploy/examples/business-registration/compose.yaml index 5b9d164bb9..777591157f 100644 --- a/deploy/examples/business-registration/compose.yaml +++ b/deploy/examples/business-registration/compose.yaml @@ -175,8 +175,9 @@ services: - ${REFERENCE_CONFIG}/thunderid/resources:/opt/thunderid/config/resources:ro - ${REFERENCE_CONFIG}/thunderid/secrets:/run/identity-secrets:ro - &issuer-trust ${REFERENCE_CONFIG}/trust:/run/trust:ro - - &issuer-certs issuer-certs:/opt/thunderid/config/certs - - &issuer-secrets issuer-secrets:/opt/thunderid/config/secrets + # Only the one-shot setup writes the issuer's signing and encryption material. + - issuer-certs:/opt/thunderid/config/certs:ro + - issuer-secrets:/opt/thunderid/config/secrets:ro thunderid-setup: <<: *thunderid @@ -188,11 +189,12 @@ services: - ${REFERENCE_CONFIG}/thunderid/bootstrap.yaml:/opt/thunderid/deployment.yaml:ro - ${REFERENCE_CONFIG}/thunderid/bootstrap-secrets:/run/identity-secrets:ro - *issuer-trust - - *issuer-certs - - *issuer-secrets + - issuer-certs:/opt/thunderid/config/certs + - issuer-secrets:/opt/thunderid/config/secrets postgres: image: postgres:17.11@sha256:ff87138949ad9a46f32ff23bd6852b52ce024a13dffe9b4087be98292cdd3b4f + security_opt: [no-new-privileges:true] environment: POSTGRES_PASSWORD_FILE: /run/postgres/bootstrap-password command: diff --git a/deploy/examples/business-registration/tests/test_compose.py b/deploy/examples/business-registration/tests/test_compose.py index c8fc4a380f..e27d87d98a 100644 --- a/deploy/examples/business-registration/tests/test_compose.py +++ b/deploy/examples/business-registration/tests/test_compose.py @@ -75,6 +75,17 @@ def test_one_shots_keep_bootstrap_authority_out_of_serving_mounts(self): self.assertFalse(any("/config/resources" in mount["target"] for mount in boot)) self.assertFalse(any("/breg/admin" in mount["source"] for mount in self.services["breg"]["volumes"])) + def test_only_issuer_setup_writes_signing_material(self): + def issuer_volumes(name): + return {mount["source"]: mount.get("read_only", False) + for mount in self.services[name]["volumes"] if mount["type"] == "volume"} + self.assertEqual(issuer_volumes("thunderid"), {"issuer-certs": True, "issuer-secrets": True}) + self.assertEqual(issuer_volumes("thunderid-setup"), {"issuer-certs": False, "issuer-secrets": False}) + + def test_every_service_refuses_new_privileges(self): + for name, service in self.services.items(): + self.assertIn("no-new-privileges:true", service.get("security_opt", []), name) + def test_breg_waits_for_the_issuer_from_its_own_namespace(self): readiness = self.services["issuer-ready"] self.assertEqual(readiness["network_mode"], self.services["breg"]["network_mode"]) From 7709e570627fa6d9d0115158b8a96492d96e6d7c Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 22:36:34 +0000 Subject: [PATCH 114/183] docs(deploy): correct the reference steps a Compose run exposed ThunderID could not read the PostgreSQL CA because the certificate step left trust/ at mode 0700. The preview bundle run left a kept development volume, and the package step did not say how to sign schema-test tokens before the reference issuer exists. Signed-off-by: Jeremi Joslin --- deploy/examples/business-registration/README.md | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/deploy/examples/business-registration/README.md b/deploy/examples/business-registration/README.md index e48d40f3a8..09e4627685 100644 --- a/deploy/examples/business-registration/README.md +++ b/deploy/examples/business-registration/README.md @@ -88,7 +88,7 @@ install -d "$BUSINESS_BUNDLE/functions" "$BUSINESS_BUNDLE/$static" install -m 0644 "$built/manifest.json" "$BUSINESS_BUNDLE/" install -m 0644 "$built/functions/register-business.mjs" "$BUSINESS_BUNDLE/functions/" install -m 0644 "$built/$static/"{index.html,app.js,service.css} "$BUSINESS_BUNDLE/$static/" -rstack dev stop "$run" +rstack dev stop --clean "$run" ``` The recipe uses the bundle's `manifest.json`, `functions/register-business.mjs`, and the three files in @@ -107,7 +107,10 @@ docker run --rm --network none \ Name the sealed BReg package from that preview project in both BReg inputs. Follow the [BReg test and package steps](../../../docs/site/src/content/docs/operate/breg.mdx) -with a separate schema-test database. Use the same package and recorded digest +with a separate schema-test database. The reference issuer is not running yet, +so give the test runtime a static JWKS (`jwksSource.documentRef`) for a +synthetic signing key and sign the schema-test tokens with that key. Use the +same package and recorded digest for activation and serving. Set `BREG_PACKAGE_DIGEST` in your shell from the package receipt. @@ -152,6 +155,7 @@ issue "$REFERENCE_CONFIG/issuer-tls" issuer DNS:identity.reference.test issue "$REFERENCE_CONFIG/postgres" server DNS:postgres install -m 0644 "$ca.pem" "$REFERENCE_CONFIG/trust/https-ca.pem" install -m 0644 "$ca.pem" "$REFERENCE_CONFIG/trust/postgres-ca.pem" +chmod 0755 "$REFERENCE_CONFIG/trust" ``` The Session client secret equals `REGISTRAR_CLIENT_SECRET`. Both ThunderID From 124fcf2a1158beeb4d17a395da05553253e37d83 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 21:55:28 +0000 Subject: [PATCH 115/183] feat(platform): use one product inventory for dev and service plans dev.yaml now declares its products with the service.yaml mapping and keys token audiences by project ID, and a directory holds exactly one inventory. The retired list form is refused with the mapping named, so the refusal is the migration guide. The shared inventory also names the Adapter, Discovery, Documents, Render and Scheduling projects the runner starts. Refusals and unavailable helpers now point at the authored dev.yaml or service.yaml location rather than the native plan index. Signed-off-by: Jeremi Joslin --- .../src/init_from_model/render.rs | 9 +- crates/registry-caseworkctl/src/project.rs | 3 +- .../src/service_compiler.rs | 149 ++++++++++--- .../src/service_compiler/tests.rs | 210 ++++++++++++++++++ crates/registry-rstack-dev/src/plan.rs | 97 ++++---- crates/registry-rstack-dev/src/products.rs | 6 + .../registry-rstack-dev/tests/dev_schema.rs | 53 +++-- crates/registry-rstack/src/cli.rs | 48 ++-- crates/registry-rstack/tests/dev.rs | 22 +- crates/registry-rstack/tests/dev_run.rs | 67 +++--- .../generate-breg-configuration.test.mjs | 3 +- .../run-a-project-with-rstack-dev.mdx | 20 +- .../derive-a-registry-from-publicschema.mdx | 7 +- .../src/content/docs/tutorials/first-breg.mdx | 7 +- .../tutorials/first-evidence-assertion.mdx | 7 +- .../docs/tutorials/first-messaging.mdx | 5 +- .../adapter/examples/dev-starter/dev.yaml | 5 +- products/breg/acceptance/facility/dev.yaml | 7 +- .../acceptance/generated-identifiers/dev.yaml | 7 +- .../acceptance/issuer-portability/dev.yaml | 7 +- .../reviewed-evidence-journey/dev.yaml | 11 +- .../acceptance/spatial-service-sites/dev.yaml | 7 +- products/breg/evidence/registry/dev.yaml | 9 +- .../breg/examples/external-views/dev.yaml | 9 +- products/breg/examples/facility/dev.yaml | 7 +- products/breg/examples/minimal/dev.yaml | 7 +- .../generic-operator-workflows/dev.yaml | 7 +- .../multi-reference-array-claim/dev.yaml | 7 +- products/breg/loadtest/support/loadenv.py | 4 +- .../examples/standalone-decision/dev.yaml | 5 +- .../examples/delayed-follow-up/dev.yaml | 7 +- .../source-registry/dev.yaml | 9 +- products/discovery/examples/starter/dev.yaml | 5 +- .../examples/development-starter/dev.yaml | 5 +- products/evidence/examples/fhir/dev.yaml | 7 +- .../evidence/examples/standalone/dev.yaml | 7 +- products/messaging/examples/starter/dev.yaml | 5 +- products/platform/CHANGELOG.md | 1 + products/platform/config-formats.yaml | 10 +- .../projects/breg-project-dev/dev.yaml | 9 +- .../projects/breg-project-dev/service.yaml | 5 - products/platform/examples/licensing/dev.yaml | 11 +- .../generated/dev/dev.v1alpha1.schema.json | 99 +++++++-- .../dev/service.v1alpha1.schema.json | 15 ++ products/platform/journeys/rstack-dev.sh | 10 +- products/render/examples/starter/dev.yaml | 5 +- .../examples/resource-reservations/dev.yaml | 5 +- .../standalone-arrival-window/dev.yaml | 5 +- .../examples/standalone-exact-time/dev.yaml | 5 +- 49 files changed, 792 insertions(+), 245 deletions(-) create mode 100644 crates/registry-platform-config/src/service_compiler/tests.rs diff --git a/crates/registry-bregctl/src/init_from_model/render.rs b/crates/registry-bregctl/src/init_from_model/render.rs index 7124567959..3c9d39f357 100644 --- a/crates/registry-bregctl/src/init_from_model/render.rs +++ b/crates/registry-bregctl/src/init_from_model/render.rs @@ -65,9 +65,12 @@ fn development_plan(plan: &Plan) -> String { yaml.line(0, "kind: RStackDev"); yaml.entry(0, "issuer", &base_iri(plan)); yaml.line(0, "products:"); - yaml.line(1, "- product: breg"); - yaml.line(2, "project: ."); - yaml.entry(2, "audience", &format!("urn:example:{}", plan.registry_id)); + yaml.line(1, "breg:"); + yaml.line(2, "projects:"); + yaml.line(3, "breg:"); + yaml.line(4, "path: ."); + yaml.line(0, "audiences:"); + yaml.entry(1, "breg", &format!("urn:example:{}", plan.registry_id)); yaml.line(0, "people:"); let callers = [ Some((OPERATOR_PROFILE, operator_principal(plan))), diff --git a/crates/registry-caseworkctl/src/project.rs b/crates/registry-caseworkctl/src/project.rs index 8bbe66a7f2..a9a976f216 100644 --- a/crates/registry-caseworkctl/src/project.rs +++ b/crates/registry-caseworkctl/src/project.rs @@ -349,7 +349,8 @@ fn development_plan(project: &CaseworkProject) -> Result<(String, String, String "apiVersion": "id.registrystack.org/formats/rstack/dev/v1alpha1", "kind": "RStackDev", "issuer": issuer, - "products": [{"product": "casework", "project": ".", "audience": "urn:example:casework"}], + "products": {"casework": {"path": "."}}, + "audiences": {"casework": "urn:example:casework"}, "people": people, "journeyFile": "dev-journeys.yaml", }))?; diff --git a/crates/registry-platform-config/src/service_compiler.rs b/crates/registry-platform-config/src/service_compiler.rs index 7c396dc900..9ee01f6db0 100644 --- a/crates/registry-platform-config/src/service_compiler.rs +++ b/crates/registry-platform-config/src/service_compiler.rs @@ -88,11 +88,16 @@ struct ManifestReference { #[serde(deny_unknown_fields)] #[cfg_attr(feature = "schema", derive(schemars::JsonSchema), schemars(extend("minProperties" = 1)))] struct ProductReferences { + adapter: Option, breg: Option, casework: Option, coordinator: Option, + discovery: Option, + documents: Option, evidence: Option, messaging: Option, + render: Option, + scheduling: Option, } #[derive(Deserialize)] @@ -130,6 +135,12 @@ pub fn service_schema() -> schemars::Schema { schemars::schema_for!(ServiceFile) } +/// The product inventory mapping shared by `service.yaml` and `dev.yaml`. +#[cfg(feature = "schema")] +pub fn product_inventory_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema { + generator.subschema_for::() +} + #[cfg(feature = "schema")] fn roles_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema { let mut roles = local_index::(generator); @@ -287,7 +298,14 @@ pub fn plan(file: &Path, options: Options<'_>) -> Result { let settings = Reader::new(path.display().to_string()) .with_hook(&mut AuthoredExpressions) .read(&read(&path)?, &Expect::one(&DEV_FORMAT))?; - let projection = project_dev(root, &settings, &products, doc)?; + let projection = if settings.span_of("/products").is_none() { + project_dev(root, &settings, &products, doc)? + } else if products.is_empty() { + let entries = dev_inventory(root, &settings)?; + project_dev(root, &settings, &entries, &settings)? + } else { + return Err(two_inventories(&settings)); + }; (Some(root.to_owned()), Some(projection.native)) } None => (None, None), @@ -340,13 +358,42 @@ fn read_service(file: &Path, workspace: Option<&Path>) -> Result Result<(Document, Vec), Report> { - let ServiceDocument { +/// The one product inventory of a development directory: the `products` of +/// its `dev.yaml`, or else those of a sibling `service.yaml`. Returns the +/// document that declares the inventory and its entries. +fn development_inventory( + root: &Path, + settings: &Document, +) -> Result<(Document, Vec), Report> { + let service_file = root.join("service.yaml"); + let service = service_file + .exists() + .then(|| read_service(&service_file, Some(root))) + .transpose()?; + if settings.span_of("/products").is_some() { + if service + .as_ref() + .is_some_and(|service| service.decoded.value.products.is_some()) + { + return Err(two_inventories(settings)); + } + return Ok((settings.clone(), dev_inventory(root, settings)?)); + } + let Some(ServiceDocument { file, workspace, decoded, .. - } = read_service(&root.join("service.yaml"), Some(root))?; + }) = service + else { + return Err(problem( + settings, + "rstack.service.projects", + "/products", + "The development plan needs product projects.", + "Declare the native products to start under products in dev.yaml.", + )); + }; let directory = file .parent() .expect("a readable service file has a directory"); @@ -356,23 +403,62 @@ fn development_inventory(root: &Path) -> Result<(Document, Vec), Report "rstack.service.projects", "/products", "The development plan needs product projects.", - "Declare the native products to start in service.yaml.", + "Declare the native products to start in dev.yaml or service.yaml.", ) })?; let entries = products(references, &decoded.document, directory, &workspace)?; Ok((decoded.document, entries)) } +/// The products declared in development settings, resolved against their +/// directory. +fn dev_inventory(root: &Path, settings: &Document) -> Result, Report> { + if settings + .to_json_value() + .pointer("/products") + .is_some_and(Value::is_array) + { + return Err(problem( + settings, + "rstack.dev.products-list", + "/products", + "The development products are a mapping of product kinds, not a list.", + "Write each product as products..projects..path (products..path for Casework and Messaging) and move its audience to audiences..", + )); + } + let workspace = root.canonicalize().map_err(|_| unreadable(root))?; + let references = settings.decode_at::("/products")?; + products(references, settings, &workspace, &workspace) +} + +fn two_inventories(settings: &Document) -> Report { + problem( + settings, + "rstack.service.dev-products", + "/products", + "The service file already declares the development products.", + "Declare the products in one file: remove them from these development settings, or from service.yaml.", + ) +} + +fn read_settings(root: &Path) -> Result { + let file = root.join("dev.yaml"); + Reader::new(file.display().to_string()) + .with_hook(&mut AuthoredExpressions) + .read(&read(&file)?, &Expect::one(&DEV_FORMAT)) +} + /// The native component kinds the launcher needs to select a development host. pub fn development_product_kinds(root: &Path) -> Result, Report> { - let (_, entries) = development_inventory(root)?; + let (_, entries) = development_inventory(root, &read_settings(root)?)?; Ok(entries.into_iter().map(|entry| entry.product).collect()) } -/// Apply the service beside dev.yaml while leaving native dev validation to its runner. +/// Apply the directory's product inventory to dev.yaml while leaving native +/// dev validation to its runner. pub fn development_plan(root: &Path, settings: &Document) -> Result { - let (service, entries) = development_inventory(root)?; - project_dev(root, settings, &entries, &service) + let (inventory, entries) = development_inventory(root, settings)?; + project_dev(root, settings, &entries, &inventory) } fn products( @@ -424,8 +510,13 @@ fn products( } } for (kind, manifest, reference) in [ + ("adapter", "project.yaml", references.adapter), ("casework", "casework.yaml", references.casework), + ("discovery", "origins.yaml", references.discovery), + ("documents", "documents.yaml", references.documents), ("messaging", "messaging.yaml", references.messaging), + ("render", "render.yaml", references.render), + ("scheduling", "scheduling.yaml", references.scheduling), ] { if let Some(reference) = reference { let source = format!("/products/{kind}/path"); @@ -577,7 +668,7 @@ pub struct DevelopmentPlan { } pub struct DevelopmentSources { - service: Document, + inventory: Document, products: Vec, } @@ -587,10 +678,10 @@ struct ProductSource { } impl DevelopmentSources { - /// Locate a native plan field in one of the two authored documents. + /// Locate a native plan field in the settings or the inventory document. pub fn locate<'a>(&'a self, settings: &'a Document, path: &'a str) -> (&'a Document, &'a str) { if path == "/products" { - return (&self.service, path); + return (&self.inventory, path); } if let Some(rest) = path.strip_prefix("/products/") { let (index, field) = rest.split_once('/').unwrap_or((rest, "")); @@ -602,7 +693,7 @@ impl DevelopmentSources { return if field == "audience" { (settings, &source.audience) } else { - (&self.service, &source.project) + (&self.inventory, &source.project) }; } } @@ -614,24 +705,15 @@ fn project_dev( root: &Path, doc: &Document, products: &[Product], - service: &Document, + inventory: &Document, ) -> Result { if products.is_empty() { return Err(problem( - service, + inventory, "rstack.service.projects", "/products", "The development plan needs product projects.", - "Declare the native products to start in service.yaml.", - )); - } - if doc.span_of("/products").is_some() { - return Err(problem( - doc, - "rstack.service.dev-products", - "/products", - "The service file supplies the development products.", - "Remove products from the development settings and give each service product an audience.", + "Declare the native products to start in dev.yaml or service.yaml.", )); } let mut audiences = doc.decode_at::>("/audiences")?; @@ -641,7 +723,7 @@ fn project_dev( for product in products { if !kinds.insert(product.product) { return Err(problem( - service, + inventory, "rstack.service.dev-product", &product.source, "The development runner accepts one project per product kind.", @@ -650,7 +732,7 @@ fn project_dev( } let relative = product.project.strip_prefix(root).map_err(|_| { problem( - service, + inventory, "rstack.service.dev-root", &product.source, "The development runner requires project paths inside the development directory.", @@ -667,8 +749,8 @@ fn project_dev( doc, "rstack.service.dev-audience", "/audiences", - "A service product needs a development audience.", - "Set audiences for all declared service product IDs.", + "A development product needs an audience.", + "Set audiences for all declared product IDs.", )); }; native_products @@ -683,8 +765,8 @@ fn project_dev( doc, "rstack.service.dev-audience", &format!("/audiences/{}", extra.as_str()), - "A development audience names an unknown service product.", - "Remove the audience or add its product to the service file.", + "A development audience names an unknown product.", + "Remove the audience or add its product to the inventory.", )); } let mut dev = doc.to_json_value(); @@ -696,7 +778,7 @@ fn project_dev( Ok(DevelopmentPlan { native: dev, sources: DevelopmentSources { - service: service.clone(), + inventory: inventory.clone(), products: sources, }, }) @@ -805,3 +887,6 @@ fn problem(doc: &Document, code: &str, pointer: &str, message: &str, next: &str) }); doc.report_with([diagnostic]) } + +#[cfg(test)] +mod tests; diff --git a/crates/registry-platform-config/src/service_compiler/tests.rs b/crates/registry-platform-config/src/service_compiler/tests.rs new file mode 100644 index 0000000000..62e806d0e8 --- /dev/null +++ b/crates/registry-platform-config/src/service_compiler/tests.rs @@ -0,0 +1,210 @@ +use super::*; + +const DEV_HEADER: &str = "apiVersion: id.registrystack.org/formats/rstack/dev/v1alpha1 +kind: RStackDev +issuer: https://issuer.example.test +journeyFile: dev-journeys.yaml +"; + +const SERVICE_HEADER: &str = + "apiVersion: id.registrystack.org/formats/rstack/service/v1alpha1\nkind: RStackService\n"; + +const DEV_INVENTORY: &str = "products: + breg: + projects: + breg: {path: registry} + casework: {path: casework} +audiences: + breg: urn:example:registry + casework: urn:example:casework +"; + +struct Directory { + _directory: tempfile::TempDir, + root: PathBuf, +} + +impl Directory { + fn new(dev: &str) -> Self { + let directory = tempfile::tempdir().unwrap(); + let root = directory.path().canonicalize().unwrap(); + for (project, manifest) in [("registry", "registry.yaml"), ("casework", "casework.yaml")] { + fs::create_dir(root.join(project)).unwrap(); + fs::write(root.join(project).join(manifest), "").unwrap(); + } + fs::write(root.join("dev.yaml"), format!("{DEV_HEADER}{dev}")).unwrap(); + Self { + _directory: directory, + root, + } + } + + fn service(self, body: &str) -> Self { + fs::write( + self.root.join("service.yaml"), + format!("{SERVICE_HEADER}{body}"), + ) + .unwrap(); + self + } + + fn settings(&self) -> Document { + let file = self.root.join("dev.yaml"); + Reader::new(file.display().to_string()) + .read(&fs::read(&file).unwrap(), &Expect::one(&DEV_FORMAT)) + .unwrap() + } + + fn plan(&self) -> Result { + development_plan(&self.root, &self.settings()) + } +} + +fn refusal(report: Report) -> Diagnostic { + let [diagnostic] = report.diagnostics() else { + panic!("expected exactly one diagnostic: {report}"); + }; + diagnostic.clone() +} + +fn source_file(diagnostic: &Diagnostic) -> String { + let file = &diagnostic + .source + .as_ref() + .expect("a located diagnostic") + .file; + Path::new(file) + .file_name() + .unwrap() + .to_string_lossy() + .into_owned() +} + +#[test] +fn a_dev_owned_inventory_projects_native_products_without_a_service_file() { + let directory = Directory::new(DEV_INVENTORY); + let plan = directory.plan().expect("the dev inventory projects"); + assert_eq!( + plan.native["products"], + json!([ + {"product": "breg", "project": "registry", "audience": "urn:example:registry"}, + {"product": "casework", "project": "casework", "audience": "urn:example:casework"}, + ]) + ); + assert!(plan.native.get("audiences").is_none()); + assert_eq!( + development_product_kinds(&directory.root).unwrap(), + ["breg", "casework"] + ); +} + +#[test] +fn a_roles_only_service_file_leaves_the_inventory_with_dev() { + let directory = Directory::new(DEV_INVENTORY) + .service("roles:\n clerk:\n actorKind: service\n accessProfiles: {breg: [clerk]}\n"); + let plan = directory.plan().expect("the dev inventory projects"); + assert_eq!(plan.native["products"][0]["product"], "breg"); +} + +#[test] +fn a_sibling_service_inventory_still_supplies_the_products() { + let directory = Directory::new("audiences: {records: urn:example:registry}\n") + .service("products:\n breg:\n projects:\n records: {path: registry}\n"); + let plan = directory.plan().expect("the service inventory projects"); + assert_eq!( + plan.native["products"], + json!([{"product": "breg", "project": "registry", "audience": "urn:example:registry"}]) + ); + assert_eq!( + development_product_kinds(&directory.root).unwrap(), + ["breg"] + ); +} + +#[test] +fn two_inventories_in_one_directory_are_refused_at_the_dev_products() { + let directory = Directory::new(DEV_INVENTORY) + .service("products:\n breg:\n projects:\n breg: {path: registry}\n"); + let diagnostic = refusal(directory.plan().err().expect("two inventories")); + assert_eq!(diagnostic.code, "rstack.service.dev-products"); + assert_eq!(diagnostic.path, "/products"); + assert_eq!(source_file(&diagnostic), "dev.yaml"); + assert!(development_product_kinds(&directory.root).is_err()); +} + +#[test] +fn the_retired_product_list_is_refused_with_the_mapping_named() { + let directory = Directory::new( + "products:\n - {product: breg, project: registry, audience: urn:example:registry}\naudiences: {breg: urn:example:registry}\n", + ); + let diagnostic = refusal(directory.plan().err().expect("the list is retired")); + assert_eq!(diagnostic.code, "rstack.dev.products-list"); + assert_eq!(diagnostic.path, "/products"); + assert!( + diagnostic + .suggested_action + .contains("products..projects..path") + && diagnostic.suggested_action.contains("audiences."), + "{}", + diagnostic.suggested_action + ); +} + +#[test] +fn a_directory_without_an_inventory_names_dev_yaml() { + let directory = Directory::new("audiences: {breg: urn:example:registry}\n"); + let diagnostic = refusal(directory.plan().err().expect("no inventory")); + assert_eq!(diagnostic.code, "rstack.service.projects"); + assert_eq!(source_file(&diagnostic), "dev.yaml"); +} + +#[test] +fn dev_inventory_refusals_point_into_dev_yaml() { + let directory = Directory::new(&DEV_INVENTORY.replace("{path: registry}", "{path: missing}")); + let diagnostic = refusal(directory.plan().err().expect("missing project")); + assert_eq!(diagnostic.path, "/products/breg/projects/breg/path"); + assert_eq!(source_file(&diagnostic), "dev.yaml"); + + let directory = + Directory::new(&DEV_INVENTORY.replace(" casework: urn:example:casework\n", "")); + let diagnostic = refusal(directory.plan().err().expect("missing audience")); + assert_eq!(diagnostic.code, "rstack.service.dev-audience"); + assert_eq!(diagnostic.path, "/audiences"); + assert_eq!(source_file(&diagnostic), "dev.yaml"); +} + +#[test] +fn an_explicit_dev_config_uses_its_own_inventory_beside_a_roles_only_service() { + let directory = Directory::new(DEV_INVENTORY) + .service("roles:\n clerk:\n actorKind: service\n accessProfiles: {breg: [clerk]}\n"); + let dev = directory.root.join("dev.yaml"); + let plan = plan( + &directory.root.join("service.yaml"), + Options { + workspace_root: None, + dev_config: Some(&dev), + checked_routes: None, + route_selections: &[], + for_client: false, + }, + ) + .expect("the roles-only service plans with the dev inventory"); + assert_eq!( + plan.dev_plan.expect("a dev projection")["products"][1], + json!({"product": "casework", "project": "casework", "audience": "urn:example:casework"}) + ); +} + +#[test] +fn single_project_runner_products_take_a_path() { + let directory = Directory::new( + "products:\n scheduling: {path: scheduling}\naudiences: {scheduling: urn:example:scheduling}\n", + ); + fs::create_dir(directory.root.join("scheduling")).unwrap(); + fs::write(directory.root.join("scheduling/scheduling.yaml"), "").unwrap(); + let plan = directory.plan().expect("a scheduling project"); + assert_eq!( + plan.native["products"], + json!([{"product": "scheduling", "project": "scheduling", "audience": "urn:example:scheduling"}]) + ); +} diff --git a/crates/registry-rstack-dev/src/plan.rs b/crates/registry-rstack-dev/src/plan.rs index aa4e0bfbc8..026e1a0698 100644 --- a/crates/registry-rstack-dev/src/plan.rs +++ b/crates/registry-rstack-dev/src/plan.rs @@ -103,33 +103,34 @@ pub(crate) fn schema() -> schemars::Schema { audiences.insert("minProperties".to_owned(), 1.into()); audiences.insert( "description".to_owned(), - "Token audiences keyed by the product IDs declared in service.yaml.".into(), + "Token audiences keyed by project ID: the member name under projects, or the product kind for a single path.".into(), + ); + let mut products = + registry_platform_config::service_compiler::product_inventory_schema(&mut generator); + products.insert( + "description".to_owned(), + "The products to start, as in service.yaml. Leave it out when a sibling service.yaml declares products.".into(), ); let mut schema = generator.into_root_schema_for::>(); - // The composed reader projects audiences into products before decoding Plan. - schema + // The composed reader projects products and audiences into the native + // product list before decoding Plan. + let properties = schema .get_mut("properties") .and_then(Value::as_object_mut) - .expect("Plan has a properties mapping") - .insert("audiences".to_owned(), audiences.to_value()); - schema + .expect("Plan has a properties mapping"); + properties.insert("products".to_owned(), products.to_value()); + properties.insert("audiences".to_owned(), audiences.to_value()); + let required = schema .get_mut("required") .and_then(Value::as_array_mut) - .expect("Plan has required properties") - .retain(|property| property != "products"); - schema.insert( - "oneOf".to_owned(), - serde_json::json!([ - {"required": ["products"]}, - {"required": ["audiences"]} - ]), - ); + .expect("Plan has required properties"); + required.retain(|property| property != "products"); + required.push("audiences".into()); schema.insert( "allOf".to_owned(), serde_json::json!([{ "if": {"required": ["preview"]}, "then": { - "required": ["audiences"], "properties": {"issuer": {"const": "run"}}, "not": {"required": ["application"]} } @@ -1076,10 +1077,8 @@ fn read_plan(root: &Path) -> Result<(AuthoredPlan, AuthoredDigests)> { super::preview::verify_native_source(source, expected)?; } } - let (value, service) = resolved.map_err(|error| match error.downcast::() { - Ok(refusal) => source_refusal_report(&document, sources.as_ref(), &refusal).into(), - Err(error) => error, - })?; + let (value, service) = + resolved.map_err(|error| authored_error(&document, sources.as_ref(), error))?; Ok(( AuthoredPlan { value, @@ -1110,17 +1109,6 @@ fn decode_authored_plan( remedy: WRITE_THE_VALUE, }) .read(&bytes, &Expect::one(&FORMAT))?; - if document.span_of("/audiences").is_none() { - let value = document.decode()?; - return Ok(( - AuthoredPlan { - value, - document, - sources: None, - }, - digest, - )); - } let projection = registry_platform_config::service_compiler::development_plan(root, &document)?; let bytes = serde_json::to_vec(&projection.native)?; let decoded = Reader::new(&name) @@ -1155,6 +1143,30 @@ fn refusal_report(decoded: &AuthoredPlan, refusal: &SemanticRefu source_refusal_report(&decoded.document, decoded.sources.as_ref(), refusal) } +/// A plan refusal, or an unavailable product helper, at the authored location +/// of its native plan field. Other errors pass through unchanged. +fn authored_error( + document: &Document, + sources: Option<&DevelopmentSources>, + error: anyhow::Error, +) -> anyhow::Error { + let error = match error.downcast::() { + Ok(refusal) => return source_refusal_report(document, sources, &refusal).into(), + Err(error) => error, + }; + match error.downcast::() { + Ok(unavailable) => { + let field = sources + .map_or(unavailable.field(), |sources| { + sources.locate(document, unavailable.field()).1 + }) + .to_owned(); + unavailable.at(&field).into() + } + Err(error) => error, + } +} + fn source_refusal_report( document: &Document, sources: Option<&DevelopmentSources>, @@ -1236,10 +1248,11 @@ pub(crate) fn check(root: &Path) -> Result { let inspection = match inspection { Ok(inspection) => inspection, Err(error) => { - return match error.downcast::() { - Ok(refusal) => Err(refusal_report(&decoded, &refusal).into()), - Err(error) => Err(error), - } + return Err(authored_error( + &decoded.document, + decoded.sources.as_ref(), + error, + )) } }; validate_application_authority(&decoded.value, &inspection) @@ -2256,6 +2269,7 @@ mod tests { #[test] fn authored_role_and_fixture_errors_point_to_the_offending_item_or_key() { let root = tempfile::tempdir().unwrap(); + fs::write(root.path().join("registry.yaml"), "fixture").unwrap(); for (person, code, path) in [ ( "roles: [reader, reader]", @@ -2271,7 +2285,7 @@ mod tests { fs::write( root.path().join("dev.yaml"), format!( - "apiVersion: {API_VERSION}\nkind: {KIND}\nissuer: run\nproducts: []\npeople: {{reader: {{subject: reader, client: reader, {person}}}}}\njourneyFile: dev-journeys.yaml\n" + "apiVersion: {API_VERSION}\nkind: {KIND}\nissuer: run\nproducts: {{breg: {{projects: {{breg: {{path: .}}}}}}}}\naudiences: {{breg: urn:test:breg}}\npeople: {{reader: {{subject: reader, client: reader, {person}}}}}\njourneyFile: dev-journeys.yaml\n" ), ) .unwrap(); @@ -2294,13 +2308,11 @@ mod tests { fs::write(project.path().join("registry.yaml"), "fixture").unwrap(); fs::write(project.path().join("dev-journeys.yaml"), "fixture").unwrap(); fs::write(project.path().join("dev.yaml"), format!( - "apiVersion: {API_VERSION}\nkind: {KIND}\nissuer: https://issuer.example.test\nproducts: [{{product: breg, project: ., audience: urn:test:breg}}]\njourneyFile: dev-journeys.yaml\npeople: {{reader: {{subject: reader, client: reader, roles: [reader]}}}}\n" + "apiVersion: {API_VERSION}\nkind: {KIND}\nissuer: https://issuer.example.test\nproducts: {{breg: {{projects: {{breg: {{path: .}}}}}}}}\naudiences: {{breg: urn:test:breg}}\njourneyFile: dev-journeys.yaml\npeople: {{reader: {{subject: reader, client: reader, roles: [reader]}}}}\n" )).unwrap(); + // The inventory reader opens service.yaml first and refuses the link. let error = load(project.path()).err().unwrap().to_string(); - assert!( - error.contains("resolves outside the development project"), - "{error}" - ); + assert!(error.contains("rstack.service.read"), "{error}"); } fn plan(step: Value) -> (tempfile::TempDir, Plan) { @@ -2967,7 +2979,8 @@ journeys: [] .unwrap(); let valid = json!({ "issuer": "https://issuer.example.invalid", - "products": [{"product": "breg", "project": ".", "audience": "registry"}], + "products": {"breg": {"projects": {"breg": {"path": "."}}}}, + "audiences": {"breg": "registry"}, "people": {"operator": { "subject": "operator", "client": "operator-client", "roles": ["operator"] diff --git a/crates/registry-rstack-dev/src/products.rs b/crates/registry-rstack-dev/src/products.rs index c9cb96da7a..2c15759e49 100644 --- a/crates/registry-rstack-dev/src/products.rs +++ b/crates/registry-rstack-dev/src/products.rs @@ -2619,6 +2619,12 @@ impl InspectionUnavailable { &self.field } + /// The same refusal at the authored location of its native plan field. + pub(super) fn at(mut self, field: &str) -> Self { + field.clone_into(&mut self.field); + self + } + pub(super) fn reason(&self) -> &str { &self.reason } diff --git a/crates/registry-rstack-dev/tests/dev_schema.rs b/crates/registry-rstack-dev/tests/dev_schema.rs index 0be4e1bb61..c51a1a2a0e 100644 --- a/crates/registry-rstack-dev/tests/dev_schema.rs +++ b/crates/registry-rstack-dev/tests/dev_schema.rs @@ -113,42 +113,55 @@ fn the_plan_schema_names_the_rstack_dev_format() { } #[test] -fn the_dev_schema_accepts_either_native_products_or_service_audiences() { +fn the_dev_schema_takes_the_service_inventory_and_requires_audiences() { let documents = documents().expect("the development schemas generate"); let schema = compile(&documents["dev.v1alpha1.schema.json"]); - let native = example(EXAMPLES[0].1); - assert!(schema.is_valid(&native)); + let plan = example(EXAMPLES[0].1); + assert!(schema.is_valid(&plan)); - let mut composed = native; - let products = composed + let mut without_audiences = plan.clone(); + without_audiences .as_object_mut() .expect("the development example is a mapping") - .remove("products") - .expect("the native development example declares its products"); - assert!(!schema.is_valid(&composed)); + .remove("audiences"); + assert!( + !schema.is_valid(&without_audiences), + "audiences are required" + ); - let audiences = json!({"licences": "urn:example:licences", "casework": "urn:example:casework"}); - composed["audiences"] = audiences.clone(); + let mut service_owned = plan.clone(); + service_owned + .as_object_mut() + .expect("the development example is a mapping") + .remove("products"); assert!( - schema.is_valid(&composed), - "the runner accepts service audiences" + schema.is_valid(&service_owned), + "a sibling service.yaml may own the inventory" ); + for products in [ + json!([{"product": "breg", "project": "registry", "audience": "urn:example:licences"}]), + json!({"unknown": {"path": "registry"}}), + json!({"casework": {"projects": {"casework": {"path": "casework"}}}}), + ] { + let mut changed = plan.clone(); + changed["products"] = products; + assert!(!schema.is_valid(&changed), "{changed}"); + } + + let audiences = plan["audiences"].clone(); + let mut changed = plan; for invalid in [ json!({}), json!({"licences.branch": "urn:example:licences"}), json!({"licences": ""}), json!({"licences": null}), ] { - composed["audiences"] = invalid; - assert!(!schema.is_valid(&composed), "{composed}"); + changed["audiences"] = invalid; + assert!(!schema.is_valid(&changed), "{changed}"); } - composed["audiences"] = audiences; - composed["products"] = products; - assert!( - !schema.is_valid(&composed), - "the two product sources are exclusive" - ); + changed["audiences"] = audiences; + assert!(schema.is_valid(&changed)); } #[test] diff --git a/crates/registry-rstack/src/cli.rs b/crates/registry-rstack/src/cli.rs index 1bb245d61f..9a2d48a022 100644 --- a/crates/registry-rstack/src/cli.rs +++ b/crates/registry-rstack/src/cli.rs @@ -1994,10 +1994,11 @@ impl DevNeeds { } } -/// The hosting products the project's dev.yaml lists under -/// `/products/*/product`, in hosting order. A missing, unreadable, oversized -/// or unparsable plan, or one without a products list, lists none: the first -/// available host then reports the real plan error, with the positioned +/// The hosting products the project's inventory names, in hosting order: the +/// product kinds under dev.yaml `products`, or else those of the sibling +/// service.yaml when dev.yaml only gives `audiences`. A missing, unreadable, +/// oversized or unparsable plan, or one without an inventory, lists none: the +/// first available host then reports the real plan error, with the positioned /// diagnostics every product gives for a malformed configuration file. fn plan_dev_products(project: &std::path::Path) -> Vec<&'static DevHost> { use registry_platform_yaml::{NodeValue, Reader, MAXIMUM_DOCUMENT_BYTES}; @@ -2013,30 +2014,25 @@ fn plan_dev_products(project: &std::path::Path) -> Vec<&'static DevHost> { let Ok(Some(root)) = Reader::new(file.display().to_string()).scan(&bytes) else { return Vec::new(); }; - if root.pointer("/audiences").is_some() { - let Ok(kinds) = service_plan::development_product_kinds(project) else { - return Vec::new(); - }; - return DEV_HOSTS + match root.pointer("/products").map(|node| &node.value) { + Some(NodeValue::Mapping(_)) => DEV_HOSTS .iter() - .filter(|host| kinds.contains(&host.component)) - .collect(); - } - let Some(NodeValue::Sequence(entries)) = root.pointer("/products").map(|node| &node.value) - else { - return Vec::new(); - }; - DEV_HOSTS - .iter() - .filter(|host| { - entries.iter().any(|entry| { - matches!( - entry.pointer("/product").map(|node| &node.value), - Some(NodeValue::String(text)) if text.text == host.component - ) + .filter(|host| { + root.pointer(&format!("/products/{}", host.component)) + .is_some() }) - }) - .collect() + .collect(), + None if root.pointer("/audiences").is_some() => { + let Ok(kinds) = service_plan::development_product_kinds(project) else { + return Vec::new(); + }; + DEV_HOSTS + .iter() + .filter(|host| kinds.contains(&host.component)) + .collect() + } + _ => Vec::new(), + } } /// The refusal when no host is available for an action that any host serves. diff --git a/crates/registry-rstack/tests/dev.rs b/crates/registry-rstack/tests/dev.rs index 5a5fae55f6..2126544891 100644 --- a/crates/registry-rstack/tests/dev.rs +++ b/crates/registry-rstack/tests/dev.rs @@ -619,15 +619,23 @@ fn root_and_dev_help_need_no_installation_or_binary_overrides() { fn write_plan(project: &Path, products: &[&str]) { let entries: Vec = products .iter() - .map(|product| { - format!(" - {{product: {product}, project: {product}, audience: \"urn:example:{product}\"}}\n") + .map(|product| match *product { + "breg" | "coordinator" | "evidence" => { + format!(" {product}: {{projects: {{{product}: {{path: {product}}}}}}}\n") + } + _ => format!(" {product}: {{path: {product}}}\n"), }) .collect(); + let audiences: Vec = products + .iter() + .map(|product| format!(" {product}: \"urn:example:{product}\"\n")) + .collect(); fs::write( project.join("dev.yaml"), format!( - "issuer: https://issuer.example\nproducts:\n{}", - entries.concat() + "issuer: https://issuer.example\nproducts:\n{}audiences:\n{}", + entries.concat(), + audiences.concat() ), ) .unwrap(); @@ -1086,11 +1094,11 @@ fn missing_breg_names_the_install_command_before_the_overrides() { } #[test] -fn casework_text_outside_the_products_list_does_not_require_casework() { +fn casework_text_outside_the_inventory_does_not_require_casework() { let tools = SourceTools::new(); fs::write( tools.project.join("dev.yaml"), - "# product: casework\nissuer: https://issuer.example\nproducts:\n - {product: breg, project: breg, audience: \"urn:example:breg\"}\njourneyFile: dev-journeys.yaml\nnotes:\n - name: \"product: casework\"\n", + "# casework: {path: casework}\nissuer: https://issuer.example\nproducts:\n breg: {projects: {breg: {path: breg}}}\naudiences:\n breg: \"urn:example:breg\"\njourneyFile: dev-journeys.yaml\nnotes:\n casework: {path: casework}\n", ) .unwrap(); let output = tools @@ -1114,7 +1122,7 @@ fn unreadable_plan_is_reported_by_the_first_available_host() { for plan in [ Some("products: [\n"), Some("issuer: https://issuer.example\n"), - Some("products:\n - {product: unrecognised, project: c, audience: c}\n"), + Some("products:\n unrecognised: {path: c}\naudiences: {unrecognised: c}\n"), None, ] { match plan { diff --git a/crates/registry-rstack/tests/dev_run.rs b/crates/registry-rstack/tests/dev_run.rs index bf26f3ce76..924b5d7420 100644 --- a/crates/registry-rstack/tests/dev_run.rs +++ b/crates/registry-rstack/tests/dev_run.rs @@ -182,7 +182,7 @@ fn launcher_selects_scheduling_for_a_scheduling_only_plan() { fs::set_permissions(&probe, fs::Permissions::from_mode(0o700)).unwrap(); fs::write( scratch.path().join("dev.yaml"), - "products: [{product: scheduling}]\n", + "products: {scheduling: {path: .}}\naudiences: {scheduling: urn:example:scheduling}\n", ) .unwrap(); let output = Command::new(env!("CARGO_BIN_EXE_rstack")) @@ -524,7 +524,7 @@ fn project(root: &std::path::Path, extra: &str) { apiVersion: id.registrystack.org/formats/rstack/dev/v1alpha1\n\ kind: RStackDev\n\ issuer: https://issuer.example.invalid\n\ -products:\n - {{product: breg, project: ., audience: registry}}\n\ +products:\n breg: {{projects: {{breg: {{path: .}}}}}}\naudiences:\n breg: registry\n\ people:\n operator:\n subject: operator\n client: operator-client\n roles: [operator]\n\ journeyFile: dev-journeys.yaml\n\ {extra}" @@ -1035,7 +1035,7 @@ fn semantic_project(root: &std::path::Path, product: &str, step_extra: &str) { "apiVersion: id.registrystack.org/formats/rstack/dev/v1alpha1\n\ kind: RStackDev\n\ issuer: https://issuer.example.invalid\n\ -products:\n - {product: breg, project: ., audience: private-audience-marker}\n\ +products:\n breg: {projects: {breg: {path: .}}}\naudiences:\n breg: private-audience-marker\n\ people:\n operator:\n subject: private-subject-marker\n client: private-client-marker\n roles: [operator]\n\ journeyFile: dev-journeys.yaml\n", ) @@ -1267,7 +1267,7 @@ fn casework_reference_project( "apiVersion: id.registrystack.org/formats/rstack/dev/v1alpha1\n\ kind: RStackDev\n\ issuer: https://issuer.example.invalid\n\ -products:\n - {{product: breg, project: ., audience: \"urn:example:registry\"}}\n - {{product: casework, project: casework, audience: \"urn:example:review\"}}\n\ +products:\n breg: {{projects: {{breg: {{path: .}}}}}}\n casework: {{path: casework}}\naudiences:\n breg: \"urn:example:registry\"\n casework: \"urn:example:review\"\n\ people:\n operator:\n subject: operator\n client: operator-client\n roles: [operator]\n reviewer:\n subject: reviewer\n client: reviewer-client\n roles: [reviewer]\n\ journeyFile: dev-journeys.yaml\n\ {bindings}" @@ -1353,7 +1353,7 @@ fn composed_project(root: &std::path::Path) -> String { fs::write(root.join("service.yaml"), DIRECT_SERVICE).unwrap(); let dev_file = root.join("dev.yaml"); let dev = fs::read_to_string(&dev_file).unwrap().replace( - "products:\n - {product: breg, project: ., audience: registry}\n", + "products:\n breg: {projects: {breg: {path: .}}}\naudiences:\n breg: registry\n", "audiences: {demo: registry}\n", ); fs::write(dev_file, &dev).unwrap(); @@ -1387,7 +1387,7 @@ fn check_assembles_products_from_service_without_writing_a_dev_plan() { fn check_rejects_competing_native_and_composed_product_lists() { let scratch = tempfile::tempdir().unwrap(); let state = scratch.path().join("state"); - project(scratch.path(), "audiences: {demo: registry}\n"); + project(scratch.path(), ""); fs::write(scratch.path().join("service.yaml"), DIRECT_SERVICE).unwrap(); let output = check(scratch.path(), &state, true); @@ -1420,7 +1420,7 @@ fn check_rejects_competing_native_and_composed_product_lists() { "{report}" ); assert!( - message.contains("The service file supplies the development products."), + message.contains("The service file already declares the development products."), "{report}" ); assert!(!state.exists()); @@ -1827,7 +1827,10 @@ fn check_and_start_refuse_a_fixture_symlink_outside_the_breg_project() { fs::write(scratch.path().join("breg/registry.yaml"), "fixture\n").unwrap(); let plan = fs::read_to_string(scratch.path().join("dev.yaml")) .unwrap() - .replace("product: breg, project: .", "product: breg, project: breg"); + .replace( + "breg: {projects: {breg: {path: .}}}", + "breg: {projects: {breg: {path: breg}}}", + ); fs::write(scratch.path().join("dev.yaml"), plan).unwrap(); fs::create_dir(scratch.path().join("breg/tests")).unwrap(); std::os::unix::fs::symlink( @@ -1841,7 +1844,7 @@ fn check_and_start_refuse_a_fixture_symlink_outside_the_breg_project() { assert_eq!(checked.status.code(), Some(1), "{checked:?}"); let report: serde_json::Value = serde_json::from_slice(&checked.stdout).unwrap(); let diagnostic = &report["diagnostics"][0]; - assert_eq!(diagnostic["path"], "/products/0/project"); + assert_eq!(diagnostic["path"], "/products/breg/projects/breg/path"); assert_eq!( diagnostic["message"], "The BReg fixture journeys file must be a readable regular file inside the BReg product project." @@ -1858,7 +1861,10 @@ fn check_and_start_refuse_a_fixture_symlink_outside_the_breg_project() { let report: serde_json::Value = serde_json::from_slice(&started.stdout).unwrap(); assert_error_envelope(&report, "domain"); let error = report["error"]["message"].as_str().unwrap(); - assert!(error.contains("/products/0/project"), "{error}"); + assert!( + error.contains("/products/breg/projects/breg/path"), + "{error}" + ); assert!(error.contains("fixture journeys file must be"), "{error}"); assert!(error.contains("without linking it outside"), "{error}"); assert!(!state.exists()); @@ -1949,8 +1955,8 @@ fn check_refuses_a_breg_project_directory_that_resolves_outside_the_project() { let plan = fs::read_to_string(scratch.path().join("dev.yaml")) .unwrap() .replace( - "product: breg, project: .", - "product: breg, project: linked-breg", + "breg: {projects: {breg: {path: .}}}", + "breg: {projects: {breg: {path: linked-breg}}}", ); fs::write(scratch.path().join("dev.yaml"), plan).unwrap(); @@ -1959,10 +1965,10 @@ fn check_refuses_a_breg_project_directory_that_resolves_outside_the_project() { assert_eq!(result.status.code(), Some(1), "{result:?}"); let report: serde_json::Value = serde_json::from_slice(&result.stdout).unwrap(); let diagnostic = &report["diagnostics"][0]; - assert_eq!(diagnostic["path"], "/products/0/project"); + assert_eq!(diagnostic["path"], "/products/breg/projects/breg/path"); assert_eq!( diagnostic["message"], - "The product project resolves outside the development project." + "This path must resolve to a directory inside the workspace." ); assert!(!state.exists()); } @@ -2048,7 +2054,7 @@ fn check_renders_both_locations_of_a_duplicate_key() { assert!(result.stdout.is_empty()); let human = String::from_utf8(result.stderr).unwrap(); assert!(human.starts_with("error[yaml.duplicate-key] "), "{human}"); - assert!(human.contains("dev.yaml:13:1 /issuer"), "{human}"); + assert!(human.contains("dev.yaml:15:1 /issuer"), "{human}"); assert!(human.contains("dev.yaml:4:1 /issuer"), "{human}"); assert!( human.contains("next: Keep one definition of the key."), @@ -2233,7 +2239,7 @@ fn start_rejects_a_role_with_no_breg_profile_facts_before_allocating_state() { "apiVersion: id.registrystack.org/formats/rstack/dev/v1alpha1\n\ kind: RStackDev\n\ issuer: https://issuer.example.invalid\n\ -products:\n - {product: breg, project: ., audience: registry}\n\ +products:\n breg: {projects: {breg: {path: .}}}\naudiences:\n breg: registry\n\ people:\n editor:\n subject: editor\n client: editor-client\n roles: [editor]\n claims: {breg: {jurisdiction: zone-a}}\n unused:\n subject: unused\n client: unused-client\n roles: [unused]\n\ journeyFile: dev-journeys.yaml\n", ) @@ -2411,9 +2417,9 @@ fn check_refuses_binding_configuration_the_products_would_refuse_at_the_plan_fie ), ( "audience", - "audience: \"urn:example:registry\"", - "audience: registry", - "/products/0/audience", + "breg: \"urn:example:registry\"", + "breg: registry", + "/audiences/breg", "Casework refuses", ), ] { @@ -2461,7 +2467,7 @@ fn check_refuses_a_context_provider_binding_with_the_rule_caseworkctl_check_name let text = fs::read_to_string(&dev).unwrap(); fs::write( &dev, - text.replace("audience: \"urn:example:registry\"", "audience: registry"), + text.replace("breg: \"urn:example:registry\"", "breg: registry"), ) .unwrap(); @@ -2471,7 +2477,7 @@ fn check_refuses_a_context_provider_binding_with_the_rule_caseworkctl_check_name let report: serde_json::Value = serde_json::from_slice(&checked.stdout).unwrap(); assert_eq!(report["status"], "domain-refusal"); let diagnostic = &report["diagnostics"][0]; - assert_eq!(diagnostic["path"], "/products/0/audience"); + assert_eq!(diagnostic["path"], "/audiences/breg"); assert_eq!( diagnostic["message"], "Casework refuses the binding configuration the run writes from this value: \ @@ -2510,7 +2516,7 @@ fragment or userinfo." let report: serde_json::Value = serde_json::from_slice(&unavailable.stdout).unwrap(); assert_eq!(report["status"], "operational-failure"); let diagnostic = &report["diagnostics"][0]; - assert_eq!(diagnostic["path"], "/products/1/project"); + assert_eq!(diagnostic["path"], "/products/casework/path"); assert_eq!( diagnostic["message"], "The selected `caseworkctl` helper could not check the Casework configuration the run writes: caseworkctl check did not report a result for the binding." @@ -2560,7 +2566,7 @@ fn check_distinguishes_an_unavailable_casework_helper_from_an_invalid_project() let report: serde_json::Value = serde_json::from_slice(&unavailable.stdout).unwrap(); assert_eq!(report["status"], "operational-failure"); let diagnostic = &report["diagnostics"][0]; - assert_eq!(diagnostic["path"], "/products/1/project"); + assert_eq!(diagnostic["path"], "/products/casework/path"); assert_eq!(diagnostic["code"], "rstack.dev.check-unavailable"); assert!( diagnostic["message"] @@ -2598,7 +2604,7 @@ fn check_distinguishes_an_unavailable_casework_helper_from_an_invalid_project() let report: serde_json::Value = serde_json::from_slice(&helper_failure.stdout).unwrap(); assert_eq!(report["status"], "operational-failure"); let diagnostic = &report["diagnostics"][0]; - assert_eq!(diagnostic["path"], "/products/1/project"); + assert_eq!(diagnostic["path"], "/products/casework/path"); assert_eq!(diagnostic["code"], "rstack.dev.check-unavailable"); assert!( diagnostic["message"] @@ -2630,7 +2636,7 @@ fn check_distinguishes_an_unavailable_casework_helper_from_an_invalid_project() let report: serde_json::Value = serde_json::from_slice(&invalid.stdout).unwrap(); assert_eq!(report["status"], "domain-refusal"); let diagnostic = &report["diagnostics"][0]; - assert_eq!(diagnostic["path"], "/products/1/project"); + assert_eq!(diagnostic["path"], "/products/casework/path"); assert_eq!( diagnostic["message"], "The owning casework tool refused this project's identity facts (casework.project.invalid)." @@ -2648,7 +2654,7 @@ fn a_malformed_plan_names_its_field_before_allocating_run_state() { let state = scratch.path().join("state"); fs::write( scratch.path().join("dev.yaml"), - "apiVersion: id.registrystack.org/formats/rstack/dev/v1alpha1\nkind: RStackDev\nissuer: https://example.test\nproducts: [{product: unrecognised, project: registry, audience: test}]\npeople: {}\njourneyFile: dev-journeys.yaml\n", + "apiVersion: id.registrystack.org/formats/rstack/dev/v1alpha1\nkind: RStackDev\nissuer: https://example.test\nproducts: {unrecognised: {path: registry}}\naudiences: {unrecognised: test}\npeople: {}\njourneyFile: dev-journeys.yaml\n", ) .unwrap(); // The plan lists no hosting product, so the first available host reports @@ -2662,7 +2668,7 @@ fn a_malformed_plan_names_its_field_before_allocating_run_state() { report["error"]["message"] .as_str() .unwrap() - .contains("/products/0/product"), + .contains("/products/unrecognised"), "{report}" ); assert!(!state.exists()); @@ -2770,7 +2776,8 @@ fn worker_restores_a_valid_plan_whose_captured_input_exceeds_512_kib() { "apiVersion": "id.registrystack.org/formats/rstack/dev/v1alpha1", "kind": "RStackDev", "issuer": "https://issuer.example.invalid", - "products": [{"product": "breg", "project": ".", "audience": "registry"}], + "products": {"breg": {"projects": {"breg": {"path": "."}}}}, + "audiences": {"breg": "registry"}, "people": {"operator": { "subject": "operator", "client": "operator-client", "roles": ["operator"] @@ -3014,7 +3021,9 @@ fn casework_only_project(root: &std::path::Path) { "kind: RStackDev\n", "issuer: https://issuer.example.invalid\n", "products:\n", - " - {product: casework, project: casework, audience: \"urn:example:review\"}\n", + " casework: {path: casework}\n", + "audiences:\n", + " casework: \"urn:example:review\"\n", "people:\n", " staff:\n", " subject: staff\n", diff --git a/docs/site/scripts/generate-breg-configuration.test.mjs b/docs/site/scripts/generate-breg-configuration.test.mjs index c47cf022a9..2265349948 100644 --- a/docs/site/scripts/generate-breg-configuration.test.mjs +++ b/docs/site/scripts/generate-breg-configuration.test.mjs @@ -89,7 +89,8 @@ test('BReg tool and service references read the committed schemas they name', as const projectDev = fields('tools', 'rstack-dev'); assert.deepEqual(projectDev.get('kind').values, ['RStackDev']); - assert.ok(projectDev.has('products[].product')); + assert.ok(projectDev.has('products.breg.projects.*.path')); + assert.ok(projectDev.has('audiences.*')); assert.ok(fields('tools', 'rstack-journeys').has('journeys[].steps[].expect.status')); const savedReport = fields('tools', 'ctl-report'); diff --git a/docs/site/src/content/docs/configure/run-a-project-with-rstack-dev.mdx b/docs/site/src/content/docs/configure/run-a-project-with-rstack-dev.mdx index b8867b6ab0..d49d180b5e 100644 --- a/docs/site/src/content/docs/configure/run-a-project-with-rstack-dev.mdx +++ b/docs/site/src/content/docs/configure/run-a-project-with-rstack-dev.mdx @@ -376,13 +376,17 @@ Stop the run with `rstack dev stop "$RUN"`. To adapt a plan to your own project, change these parts and leave the structure alone: - `issuer` names the identity issuer the local test tokens claim. Use a name that is yours. -- `products` lists each product's project directory and token audience, in any order. Name any - nonempty subset of `breg`, `casework`, `evidence`, `messaging`, `scheduling`, - `documents`, `coordinator`, `adapter`, `render` and `discovery`. The run starts - BReg before Casework. An application needs BReg. +- `products` maps each product kind to its project directory, the same shape as `service.yaml`. + BReg, Coordinator and Evidence name their projects under `projects` + (`products.breg.projects.breg.path`); `casework`, `messaging`, `scheduling`, `documents`, + `adapter`, `render` and `discovery` take one `path`. Use one project of each kind. The run + starts BReg before Casework. An application needs BReg. A directory has one inventory: when + a sibling `service.yaml` declares `products`, leave them out of `dev.yaml`. +- `audiences` gives each project its token audience, keyed by its project ID (the member name + under `projects`, or the product kind for a single `path`). - `personAudience` is optional. It names one audience, an absolute URI, that products a person - calls from a page will share. Only BReg can be a member, by setting its `audience` to the same - value. It may be a member whether or not it checks task grants, because it is the one member + calls from a page will share. Only BReg can be a member, by setting its entry in `audiences` + to the same value. It may be a member whether or not it checks task grants, because it is the one member allowed to. Casework keeps its own audience, Messaging takes no person token, and Evidence cannot join yet, so `check` and `start` refuse each of them as a member. Declaring `personAudience` alone changes nothing at run time. Every other audience must stay distinct. @@ -471,7 +475,7 @@ fields. ## Use an issuer you run Set `issuer` to the exact token issuer and `externalJwksUri` to its public key endpoint. -Use numeric loopback HTTP with an explicit port for the issuer, key endpoint and external BReg connections. Keep each product's audience in its `products` entry. +Use numeric loopback HTTP with an explicit port for the issuer, key endpoint and external BReg connections. Keep each product's audience in `audiences`. Tokens from an issuer you run carry no development mark, so use an issuer that only this run trusts. BReg expects RS256 access tokens from an external issuer. @@ -677,7 +681,7 @@ Supply person-specific claim values in the person's product-keyed `claims` mappi The run derives scopes and purposes from the product facts for the selected profiles. Each selected profile receives the test person's subject in its principal claim. The products enforce their ordinary permissions. -Every product keeps its own audience. `personAudience` records the audience that products a person calls from a page will share. Only BReg can take it, by setting its `audience` to the same value. +Every product keeps its own audience. `personAudience` records the audience that products a person calls from a page will share. Only BReg can take it, by setting its entry in `audiences` to the same value. Set `actor` on each step in the BReg project's `tests/journeys.yaml` to choose the test person by ID. When each step names its actor and the run uses its own issuer, the rehearsal obtains each bearer in memory. The run obtains the normal schema-test receipt before packaging. diff --git a/docs/site/src/content/docs/tutorials/derive-a-registry-from-publicschema.mdx b/docs/site/src/content/docs/tutorials/derive-a-registry-from-publicschema.mdx index ecb69dd237..3dcbce3163 100644 --- a/docs/site/src/content/docs/tutorials/derive-a-registry-from-publicschema.mdx +++ b/docs/site/src/content/docs/tutorials/derive-a-registry-from-publicschema.mdx @@ -227,7 +227,12 @@ apiVersion: id.registrystack.org/formats/rstack/dev/v1alpha1 kind: RStackDev issuer: https://identity.household.example.test products: - - {product: breg, project: ., audience: "urn:example:household-registry"} + breg: + projects: + breg: + path: . +audiences: + breg: "urn:example:household-registry" people: operator: subject: household-registry-operator diff --git a/docs/site/src/content/docs/tutorials/first-breg.mdx b/docs/site/src/content/docs/tutorials/first-breg.mdx index 02b6617226..559455591b 100644 --- a/docs/site/src/content/docs/tutorials/first-breg.mdx +++ b/docs/site/src/content/docs/tutorials/first-breg.mdx @@ -127,7 +127,12 @@ claim `zone-b`: ```yaml title="dev.yaml" test-excerpt="dev.yaml" issuer: https://identity.directory.example.test products: - - {product: breg, project: ., audience: "urn:example:local-directory"} + breg: + projects: + breg: + path: . +audiences: + breg: "urn:example:local-directory" people: editor: subject: synthetic-directory-editor diff --git a/docs/site/src/content/docs/tutorials/first-evidence-assertion.mdx b/docs/site/src/content/docs/tutorials/first-evidence-assertion.mdx index d012a8a293..c15732928f 100644 --- a/docs/site/src/content/docs/tutorials/first-evidence-assertion.mdx +++ b/docs/site/src/content/docs/tutorials/first-evidence-assertion.mdx @@ -161,7 +161,12 @@ apiVersion: id.registrystack.org/formats/rstack/dev/v1alpha1 kind: RStackDev issuer: run products: - - {product: evidence, project: ., audience: "urn:example:resource:standalone-evidence"} + evidence: + projects: + evidence: + path: . +audiences: + evidence: "urn:example:resource:standalone-evidence" people: caller: subject: "urn:registrystack:evidence:local:client:example-caller" diff --git a/docs/site/src/content/docs/tutorials/first-messaging.mdx b/docs/site/src/content/docs/tutorials/first-messaging.mdx index 73ebb066ec..8ac44663f2 100644 --- a/docs/site/src/content/docs/tutorials/first-messaging.mdx +++ b/docs/site/src/content/docs/tutorials/first-messaging.mdx @@ -81,7 +81,10 @@ reports ready. The plan holds no keys and no addresses: ```yaml title="dev.yaml" test-excerpt="tutorial-work/notices/dev.yaml" issuer: https://identity.starter.example.test products: - - {product: messaging, project: ., audience: "urn:example:messaging"} + messaging: + path: . +audiences: + messaging: "urn:example:messaging" people: case-system: subject: case-system diff --git a/products/adapter/examples/dev-starter/dev.yaml b/products/adapter/examples/dev-starter/dev.yaml index e274de8086..0765c6784c 100644 --- a/products/adapter/examples/dev-starter/dev.yaml +++ b/products/adapter/examples/dev-starter/dev.yaml @@ -3,7 +3,10 @@ apiVersion: id.registrystack.org/formats/rstack/dev/v1alpha1 kind: RStackDev issuer: https://identity.starter.example.test products: - - {product: adapter, project: ., audience: "urn:example:adapter"} + adapter: + path: . +audiences: + adapter: "urn:example:adapter" people: reader: subject: starter-reader diff --git a/products/breg/acceptance/facility/dev.yaml b/products/breg/acceptance/facility/dev.yaml index c8c2911286..d86658c668 100644 --- a/products/breg/acceptance/facility/dev.yaml +++ b/products/breg/acceptance/facility/dev.yaml @@ -4,7 +4,12 @@ kind: RStackDev # BReg alone. The project-root dev-journeys.yaml holds the run's HTTP requests. issuer: https://identity.facility.example.test products: - - {product: breg, project: ., audience: "urn:example:facility-registry"} + breg: + projects: + breg: + path: . +audiences: + breg: "urn:example:facility-registry" people: facility-operator: subject: synthetic-facility-operator diff --git a/products/breg/acceptance/generated-identifiers/dev.yaml b/products/breg/acceptance/generated-identifiers/dev.yaml index 4f4f9a16ea..fc14412f2a 100644 --- a/products/breg/acceptance/generated-identifiers/dev.yaml +++ b/products/breg/acceptance/generated-identifiers/dev.yaml @@ -5,7 +5,12 @@ kind: RStackDev # key under this logical issuer. issuer: https://identity.identifiers.example.test products: - - {product: breg, project: ., audience: "urn:example:generated-identifiers"} + breg: + projects: + breg: + path: . +audiences: + breg: "urn:example:generated-identifiers" people: clerk-a: subject: synthetic-clerk-a diff --git a/products/breg/acceptance/issuer-portability/dev.yaml b/products/breg/acceptance/issuer-portability/dev.yaml index ea27d913e5..f8926cbe3a 100644 --- a/products/breg/acceptance/issuer-portability/dev.yaml +++ b/products/breg/acceptance/issuer-portability/dev.yaml @@ -6,7 +6,12 @@ kind: RStackDev # root so bregctl discovers native schema checks under tests/ independently. issuer: https://identity.portability.example.test products: - - {product: breg, project: ., audience: "urn:example:issuer-portability"} + breg: + projects: + breg: + path: . +audiences: + breg: "urn:example:issuer-portability" people: clerk-service: subject: urn:institution:service-clerk diff --git a/products/breg/acceptance/reviewed-evidence-journey/dev.yaml b/products/breg/acceptance/reviewed-evidence-journey/dev.yaml index a27097f2ee..aa3ca3e072 100644 --- a/products/breg/acceptance/reviewed-evidence-journey/dev.yaml +++ b/products/breg/acceptance/reviewed-evidence-journey/dev.yaml @@ -3,8 +3,15 @@ apiVersion: id.registrystack.org/formats/rstack/dev/v1alpha1 kind: RStackDev issuer: https://issuer.example.test products: - - {product: breg, project: registry, audience: "urn:journey:breg"} - - {product: casework, project: casework, audience: "urn:journey:casework"} + breg: + projects: + breg: + path: registry + casework: + path: casework +audiences: + breg: "urn:journey:breg" + casework: "urn:journey:casework" bindings: bregReviewAuthority: {id: casework, producer: registry, identity: producer} caseworkContextProvider: {id: registry, identity: context-status, action: correct-status} diff --git a/products/breg/acceptance/spatial-service-sites/dev.yaml b/products/breg/acceptance/spatial-service-sites/dev.yaml index bca4e01c4d..7c3cf385fd 100644 --- a/products/breg/acceptance/spatial-service-sites/dev.yaml +++ b/products/breg/acceptance/spatial-service-sites/dev.yaml @@ -5,7 +5,12 @@ kind: RStackDev # at the project root and BReg's native schema checks under tests/. issuer: https://identity.service-sites.example.test products: - - {product: breg, project: ., audience: "urn:example:service-sites"} + breg: + projects: + breg: + path: . +audiences: + breg: "urn:example:service-sites" people: operator: subject: synthetic-service-site-admin diff --git a/products/breg/evidence/registry/dev.yaml b/products/breg/evidence/registry/dev.yaml index dea45ba6ac..ca1323f235 100644 --- a/products/breg/evidence/registry/dev.yaml +++ b/products/breg/evidence/registry/dev.yaml @@ -3,9 +3,12 @@ apiVersion: id.registrystack.org/formats/rstack/dev/v1alpha1 kind: RStackDev issuer: https://identity.evidence.example.test products: - - product: breg - project: . - audience: urn:example:evidence-registry + breg: + projects: + breg: + path: . +audiences: + breg: urn:example:evidence-registry people: operator: subject: generic-registry-operator diff --git a/products/breg/examples/external-views/dev.yaml b/products/breg/examples/external-views/dev.yaml index 2aefa7a286..7556746dab 100644 --- a/products/breg/examples/external-views/dev.yaml +++ b/products/breg/examples/external-views/dev.yaml @@ -3,9 +3,12 @@ apiVersion: id.registrystack.org/formats/rstack/dev/v1alpha1 kind: RStackDev issuer: https://fixture-issuer.example.test/licensing products: - - product: breg - project: . - audience: urn:breg:external-views-fixture + breg: + projects: + breg: + path: . +audiences: + breg: urn:breg:external-views-fixture people: officer: subject: synthetic-licensing-officer diff --git a/products/breg/examples/facility/dev.yaml b/products/breg/examples/facility/dev.yaml index a07bb123d4..56296ed27c 100644 --- a/products/breg/examples/facility/dev.yaml +++ b/products/breg/examples/facility/dev.yaml @@ -6,7 +6,12 @@ kind: RStackDev # and BReg's native schema checks under tests/. issuer: https://identity.facility.example.test products: - - {product: breg, project: ., audience: "urn:example:facility-registry"} + breg: + projects: + breg: + path: . +audiences: + breg: "urn:example:facility-registry" people: operator-editor: subject: synthetic-operator-editor diff --git a/products/breg/examples/minimal/dev.yaml b/products/breg/examples/minimal/dev.yaml index 5d1b35a6cd..be2763a58f 100644 --- a/products/breg/examples/minimal/dev.yaml +++ b/products/breg/examples/minimal/dev.yaml @@ -6,7 +6,12 @@ kind: RStackDev # holds the run's HTTP requests at the project root. issuer: https://identity.directory.example.test products: - - {product: breg, project: ., audience: "urn:example:local-directory"} + breg: + projects: + breg: + path: . +audiences: + breg: "urn:example:local-directory" people: editor: subject: synthetic-directory-editor diff --git a/products/breg/fixtures/generic-operator-workflows/dev.yaml b/products/breg/fixtures/generic-operator-workflows/dev.yaml index 28ad478abf..1e18f33aca 100644 --- a/products/breg/fixtures/generic-operator-workflows/dev.yaml +++ b/products/breg/fixtures/generic-operator-workflows/dev.yaml @@ -8,7 +8,12 @@ kind: RStackDev # dev-journeys.yaml holds the run's HTTP requests. issuer: https://identity.generic-registry.example.test products: - - {product: breg, project: ., audience: "urn:example:generic-registry"} + breg: + projects: + breg: + path: . +audiences: + breg: "urn:example:generic-registry" people: operator: subject: generic-registry-operator diff --git a/products/breg/fixtures/multi-reference-array-claim/dev.yaml b/products/breg/fixtures/multi-reference-array-claim/dev.yaml index 926b0b4819..b63b264693 100644 --- a/products/breg/fixtures/multi-reference-array-claim/dev.yaml +++ b/products/breg/fixtures/multi-reference-array-claim/dev.yaml @@ -6,7 +6,12 @@ kind: RStackDev # allowed_jurisdictions claim, so each refusal step names its person. issuer: https://identity.permits.example.test products: - - {product: breg, project: ., audience: "urn:example:permit-registry"} + breg: + projects: + breg: + path: . +audiences: + breg: "urn:example:permit-registry" people: reference-loader: subject: synthetic-reference-loader diff --git a/products/breg/loadtest/support/loadenv.py b/products/breg/loadtest/support/loadenv.py index 8d71e12beb..a304d4ee4a 100755 --- a/products/breg/loadtest/support/loadenv.py +++ b/products/breg/loadtest/support/loadenv.py @@ -32,7 +32,9 @@ kind: RStackDev issuer: https://identity.loadtest.example.test products: - - {product: breg, project: ., audience: "urn:example:business-establishments"} + breg: {projects: {breg: {path: .}}} +audiences: + breg: "urn:example:business-establishments" people: loadtest-driver: subject: synthetic-business-operator diff --git a/products/casework/examples/standalone-decision/dev.yaml b/products/casework/examples/standalone-decision/dev.yaml index 8f0ae3414c..cb5bf471d0 100644 --- a/products/casework/examples/standalone-decision/dev.yaml +++ b/products/casework/examples/standalone-decision/dev.yaml @@ -6,7 +6,10 @@ kind: RStackDev # throwaway local key under this name. issuer: https://identity.standalone.example.test products: - - {product: casework, project: ., audience: "urn:example:standalone-decision"} + casework: + path: . +audiences: + casework: "urn:example:standalone-decision" people: administrator: subject: administrator diff --git a/products/coordinator/examples/delayed-follow-up/dev.yaml b/products/coordinator/examples/delayed-follow-up/dev.yaml index 9ffb968ae2..95e331c5b5 100644 --- a/products/coordinator/examples/delayed-follow-up/dev.yaml +++ b/products/coordinator/examples/delayed-follow-up/dev.yaml @@ -3,7 +3,12 @@ apiVersion: id.registrystack.org/formats/rstack/dev/v1alpha1 kind: RStackDev issuer: https://identity.starter.example.test products: - - {product: coordinator, project: ., audience: "urn:example:coordinator"} + coordinator: + projects: + coordinator: + path: . +audiences: + coordinator: "urn:example:coordinator" people: reader: subject: starter-reader diff --git a/products/coordinator/examples/earlier-appointment-alerts/source-registry/dev.yaml b/products/coordinator/examples/earlier-appointment-alerts/source-registry/dev.yaml index 7feeb74741..417f45d58f 100644 --- a/products/coordinator/examples/earlier-appointment-alerts/source-registry/dev.yaml +++ b/products/coordinator/examples/earlier-appointment-alerts/source-registry/dev.yaml @@ -3,9 +3,12 @@ apiVersion: id.registrystack.org/formats/rstack/dev/v1alpha1 kind: RStackDev issuer: https://identity.alerts.example.test products: - - product: breg - project: . - audience: urn:example:earlier-appointment-alert-source + breg: + projects: + breg: + path: . +audiences: + breg: urn:example:earlier-appointment-alert-source people: alert-administrator: subject: alert-administrator diff --git a/products/discovery/examples/starter/dev.yaml b/products/discovery/examples/starter/dev.yaml index 040fb9451a..bcaec3bce0 100644 --- a/products/discovery/examples/starter/dev.yaml +++ b/products/discovery/examples/starter/dev.yaml @@ -3,6 +3,9 @@ apiVersion: id.registrystack.org/formats/rstack/dev/v1alpha1 kind: RStackDev issuer: https://identity.starter.example.test products: - - {product: discovery, project: ., audience: "urn:example:discovery"} + discovery: + path: . +audiences: + discovery: "urn:example:discovery" people: {} journeyFile: dev-journeys.yaml diff --git a/products/documents/examples/development-starter/dev.yaml b/products/documents/examples/development-starter/dev.yaml index 6abc4b0d3a..5fb52b2156 100644 --- a/products/documents/examples/development-starter/dev.yaml +++ b/products/documents/examples/development-starter/dev.yaml @@ -3,7 +3,10 @@ apiVersion: id.registrystack.org/formats/rstack/dev/v1alpha1 kind: RStackDev issuer: https://identity.starter.example.test products: - - {product: documents, project: ., audience: "urn:example:documents"} + documents: + path: . +audiences: + documents: "urn:example:documents" people: reader: subject: starter-reader diff --git a/products/evidence/examples/fhir/dev.yaml b/products/evidence/examples/fhir/dev.yaml index 14176b7949..be3e0b4b6b 100644 --- a/products/evidence/examples/fhir/dev.yaml +++ b/products/evidence/examples/fhir/dev.yaml @@ -8,7 +8,12 @@ kind: RStackDev # README shows: `python3 serve-source.py`. issuer: run products: - - {product: evidence, project: ., audience: "urn:example:resource:fhir-record-evidence"} + evidence: + projects: + evidence: + path: . +audiences: + evidence: "urn:example:resource:fhir-record-evidence" people: caller: subject: "urn:registrystack:evidence:local:client:fhir-client" diff --git a/products/evidence/examples/standalone/dev.yaml b/products/evidence/examples/standalone/dev.yaml index e54d6d454a..9f31d5b15d 100644 --- a/products/evidence/examples/standalone/dev.yaml +++ b/products/evidence/examples/standalone/dev.yaml @@ -9,7 +9,12 @@ kind: RStackDev # `python3 serve-source.py --port 8081`. issuer: run products: - - {product: evidence, project: ., audience: "urn:example:resource:standalone-evidence"} + evidence: + projects: + evidence: + path: . +audiences: + evidence: "urn:example:resource:standalone-evidence" people: caller: subject: "urn:registrystack:evidence:local:client:example-caller" diff --git a/products/messaging/examples/starter/dev.yaml b/products/messaging/examples/starter/dev.yaml index 047a3f1059..a3eca02ce6 100644 --- a/products/messaging/examples/starter/dev.yaml +++ b/products/messaging/examples/starter/dev.yaml @@ -8,7 +8,10 @@ kind: RStackDev # carries registry_actor_kind. issuer: https://identity.starter.example.test products: - - {product: messaging, project: ., audience: "urn:example:messaging"} + messaging: + path: . +audiences: + messaging: "urn:example:messaging" people: case-system: subject: case-system diff --git a/products/platform/CHANGELOG.md b/products/platform/CHANGELOG.md index cb0b2b5559..f4c2e7d695 100644 --- a/products/platform/CHANGELOG.md +++ b/products/platform/CHANGELOG.md @@ -2,6 +2,7 @@ ## Unreleased +- BREAKING: `dev.yaml` declares its products with the same mapping as `service.yaml`, and `rstack dev` refuses the list form with `rstack.dev.products-list`. Migration: replace each `- {product: KIND, project: PATH, audience: AUDIENCE}` entry with `products.KIND.projects.KIND.path: PATH` for `breg`, `coordinator` and `evidence`, or `products.KIND.path: PATH` for the other products, and move the audience to `audiences.KIND: AUDIENCE`. A directory has one inventory: when its `service.yaml` declares `products`, keep only `audiences` in `dev.yaml`. `service.yaml` also accepts `adapter`, `discovery`, `documents`, `render` and `scheduling` projects. - The file secret provider accepts `mountPolicy: compose-native`, an explicit production setting that also admits a root-owned, single-link regular file with mode exactly `0444`, the Docker Compose secret mount shape, under the diff --git a/products/platform/config-formats.yaml b/products/platform/config-formats.yaml index 629c2d855d..1ef1bf567d 100644 --- a/products/platform/config-formats.yaml +++ b/products/platform/config-formats.yaml @@ -876,7 +876,7 @@ formats: whenOmitted: refused - pointer: /application/prepareVersion whenOmitted: refused - - pointer: /products/*/audience + - pointer: /audiences/* whenOmitted: refused - pointer: /people/*/roles whenOmitted: refused @@ -918,7 +918,7 @@ formats: whenOmitted: refused - pointer: /externalScheduling/taskGrant/statusResource whenOmitted: refused - restrictingMembers: [/issuer, /application/client, /application/callbackPath, /products/*/audience, /people/*/roles, /externalScheduling/taskGrant/assertionClient, /externalScheduling/taskGrant/sourceIssuer, /externalScheduling/taskGrant/statusUrl, /externalScheduling/taskGrant/tokenEndpoint, /externalScheduling/taskGrant/statusClient, /externalScheduling/taskGrant/statusKeyRef, /externalScheduling/taskGrant/statusResource] + restrictingMembers: [/issuer, /application/client, /application/callbackPath, /audiences/*, /people/*/roles, /externalScheduling/taskGrant/assertionClient, /externalScheduling/taskGrant/sourceIssuer, /externalScheduling/taskGrant/statusUrl, /externalScheduling/taskGrant/tokenEndpoint, /externalScheduling/taskGrant/statusClient, /externalScheduling/taskGrant/statusKeyRef, /externalScheduling/taskGrant/statusResource] - id: rstack/journeys product: rstack title: Registry Stack authored development journeys @@ -992,17 +992,17 @@ formats: function: read_service type: ServiceFile check: rstack service check {file} - example: products/platform/conformance/projects/breg-project-dev/service.yaml + example: products/platform/examples/service-previews/business-registration/service.yaml conformance: requiredText: none optionalText: none integer: none boolean: none idList: none - set: /roles/operator/accessProfiles/breg + set: /roles/registrar/accessProfiles/breg reference: none operand: none - relativePath: /products/breg/projects/records/path + relativePath: /products/breg/projects/businesses/path securityMembers: [] restrictingMembers: [] - id: breg/example-scenarios diff --git a/products/platform/conformance/projects/breg-project-dev/dev.yaml b/products/platform/conformance/projects/breg-project-dev/dev.yaml index 7d211eb13e..f89ed8a100 100644 --- a/products/platform/conformance/projects/breg-project-dev/dev.yaml +++ b/products/platform/conformance/projects/breg-project-dev/dev.yaml @@ -3,9 +3,12 @@ apiVersion: id.registrystack.org/formats/rstack/dev/v1alpha1 kind: RStackDev issuer: https://issuer.example.invalid products: - - product: breg - project: registry - audience: urn:example:registry + breg: + projects: + breg: + path: registry +audiences: + breg: urn:example:registry people: operator: subject: operator diff --git a/products/platform/conformance/projects/breg-project-dev/service.yaml b/products/platform/conformance/projects/breg-project-dev/service.yaml index e3900321ec..b4128d1937 100644 --- a/products/platform/conformance/projects/breg-project-dev/service.yaml +++ b/products/platform/conformance/projects/breg-project-dev/service.yaml @@ -6,8 +6,3 @@ roles: actorKind: service accessProfiles: breg: [operator] -products: - breg: - projects: - records: - path: registry diff --git a/products/platform/examples/licensing/dev.yaml b/products/platform/examples/licensing/dev.yaml index 3047928c3b..8f945d86fc 100644 --- a/products/platform/examples/licensing/dev.yaml +++ b/products/platform/examples/licensing/dev.yaml @@ -3,8 +3,15 @@ apiVersion: id.registrystack.org/formats/rstack/dev/v1alpha1 kind: RStackDev issuer: https://identity.licensing.example.test products: - - {product: breg, project: registry, audience: "urn:example:licensing:registry"} - - {product: casework, project: casework, audience: "urn:example:licensing:review"} + breg: + projects: + breg: + path: registry + casework: + path: casework +audiences: + breg: "urn:example:licensing:registry" + casework: "urn:example:licensing:review" people: applicant: subject: applicant diff --git a/products/platform/generated/dev/dev.v1alpha1.schema.json b/products/platform/generated/dev/dev.v1alpha1.schema.json index 47bb499528..c284677e26 100644 --- a/products/platform/generated/dev/dev.v1alpha1.schema.json +++ b/products/platform/generated/dev/dev.v1alpha1.schema.json @@ -427,6 +427,26 @@ "pattern": "^[a-z][a-z0-9_-]{0,63}$", "type": "string" }, + "NamedProjects": { + "additionalProperties": false, + "properties": { + "projects": { + "additionalProperties": { + "$ref": "#/$defs/ProjectReference" + }, + "description": "Projects keyed by service product ID. BReg IDs form the generated client member names.", + "minProperties": 1, + "propertyNames": { + "$ref": "#/$defs/LocalId" + }, + "type": "object" + } + }, + "required": [ + "projects" + ], + "type": "object" + }, "Preview": { "additionalProperties": false, "properties": { @@ -499,6 +519,56 @@ ], "type": "object" }, + "ProductReferences": { + "additionalProperties": false, + "minProperties": 1, + "properties": { + "adapter": { + "$ref": "#/$defs/ProjectReference" + }, + "breg": { + "$ref": "#/$defs/NamedProjects" + }, + "casework": { + "$ref": "#/$defs/ProjectReference" + }, + "coordinator": { + "$ref": "#/$defs/NamedProjects" + }, + "discovery": { + "$ref": "#/$defs/ProjectReference" + }, + "documents": { + "$ref": "#/$defs/ProjectReference" + }, + "evidence": { + "$ref": "#/$defs/NamedProjects" + }, + "messaging": { + "$ref": "#/$defs/ProjectReference" + }, + "render": { + "$ref": "#/$defs/ProjectReference" + }, + "scheduling": { + "$ref": "#/$defs/ProjectReference" + } + }, + "type": "object" + }, + "ProjectReference": { + "additionalProperties": false, + "properties": { + "path": { + "description": "Directory containing the product's native project file, relative to this service file.", + "type": "string" + } + }, + "required": [ + "path" + ], + "type": "object" + }, "ReviewAuthority": { "additionalProperties": false, "properties": { @@ -726,26 +796,11 @@ "issuer": { "const": "run" } - }, - "required": [ - "audiences" - ] + } } } ], "description": "The development plan: the products to start, the test people who call them, and the journeys to run.", - "oneOf": [ - { - "required": [ - "products" - ] - }, - { - "required": [ - "audiences" - ] - } - ], "properties": { "apiVersion": { "const": "id.registrystack.org/formats/rstack/dev/v1alpha1", @@ -760,7 +815,7 @@ "additionalProperties": { "$ref": "#/$defs/ExternalId" }, - "description": "Token audiences keyed by the product IDs declared in service.yaml.", + "description": "Token audiences keyed by project ID: the member name under projects, or the product kind for a single path.", "minProperties": 1, "propertyNames": { "$ref": "#/$defs/LocalId" @@ -827,11 +882,8 @@ "description": "Local browser preview for a composed service and one synthetic actor." }, "products": { - "description": "The products to start, each with its project directory and token audience. List each product at most once.", - "items": { - "$ref": "#/$defs/ProductPlan" - }, - "type": "array" + "$ref": "#/$defs/ProductReferences", + "description": "The products to start, as in service.yaml. Leave it out when a sibling service.yaml declares products." }, "schemaTestPeople": { "additionalProperties": { @@ -863,7 +915,8 @@ "kind", "issuer", "people", - "journeyFile" + "journeyFile", + "audiences" ], "title": "Registry Stack development plan", "type": "object" diff --git a/products/platform/generated/dev/service.v1alpha1.schema.json b/products/platform/generated/dev/service.v1alpha1.schema.json index 3d4879b18c..f3be3a3e4f 100644 --- a/products/platform/generated/dev/service.v1alpha1.schema.json +++ b/products/platform/generated/dev/service.v1alpha1.schema.json @@ -56,6 +56,9 @@ "additionalProperties": false, "minProperties": 1, "properties": { + "adapter": { + "$ref": "#/$defs/ProjectReference" + }, "breg": { "$ref": "#/$defs/NamedProjects" }, @@ -65,11 +68,23 @@ "coordinator": { "$ref": "#/$defs/NamedProjects" }, + "discovery": { + "$ref": "#/$defs/ProjectReference" + }, + "documents": { + "$ref": "#/$defs/ProjectReference" + }, "evidence": { "$ref": "#/$defs/NamedProjects" }, "messaging": { "$ref": "#/$defs/ProjectReference" + }, + "render": { + "$ref": "#/$defs/ProjectReference" + }, + "scheduling": { + "$ref": "#/$defs/ProjectReference" } }, "type": "object" diff --git a/products/platform/journeys/rstack-dev.sh b/products/platform/journeys/rstack-dev.sh index e72f5988e5..a9a9a8b442 100755 --- a/products/platform/journeys/rstack-dev.sh +++ b/products/platform/journeys/rstack-dev.sh @@ -216,13 +216,19 @@ init_command() { # allows, so a refusal is about the product and not about the plan's other # parts. write_probe_plan() { - local product=$1 project=$2 + local product=$1 project=$2 inventory + case "$product" in + breg | coordinator | evidence) inventory="{projects: {$product: {path: .}}}" ;; + *) inventory="{path: .}" ;; + esac journey_write_file "$project/dev.yaml" --concepts development-plan,issuer-name,audience < Date: Tue, 1 Dec 2026 22:17:33 +0000 Subject: [PATCH 116/183] fix(platform): finish the dev.yaml inventory migration from review Migrate the remaining harnesses that wrote the list form (the rstack-dev script CI runs, the Evidence load test and the Coordinator native-service harness), name every single-path product kind in the migration refusal, and refuse a browser preview whose products are not in service.yaml. Relate the service.yaml inventory in the two-inventory refusal, locate an unavailable helper in its authored file, name an outside service.yaml link as written, and register the dev.yaml project path for conformance. Signed-off-by: Jeremi Joslin --- .../registry-bregctl/tests/local_package.rs | 2 +- .../src/service_compiler.rs | 30 +++++--- .../src/service_compiler/tests.rs | 19 +++-- crates/registry-rstack-dev/src/lib.rs | 6 +- crates/registry-rstack-dev/src/plan.rs | 39 ++++++++-- crates/registry-rstack-dev/src/preview.rs | 14 +--- crates/registry-rstack-dev/src/products.rs | 10 ++- .../registry-rstack-dev/tests/dev_schema.rs | 6 +- crates/registry-rstack/tests/dev_run.rs | 74 +++++++++++++++++++ .../coordinator/scripts/test-real-services.py | 21 ++++-- products/evidence/loadtest/support/loadenv.py | 4 +- .../evidence/loadtest/support/test_harness.py | 5 ++ products/platform/config-formats.yaml | 2 +- products/platform/scripts/test-rstack-dev.py | 14 ++-- 14 files changed, 185 insertions(+), 61 deletions(-) diff --git a/crates/registry-bregctl/tests/local_package.rs b/crates/registry-bregctl/tests/local_package.rs index 62802079d4..6e774987e8 100644 --- a/crates/registry-bregctl/tests/local_package.rs +++ b/crates/registry-bregctl/tests/local_package.rs @@ -22,7 +22,7 @@ fn project(root: &std::path::Path, extra: &str) { apiVersion: id.registrystack.org/formats/rstack/dev/v1alpha1\n\ kind: RStackDev\n\ issuer: https://issuer.example.invalid\n\ -products:\n - {{product: breg, project: ., audience: registry}}\n\ +products:\n breg: {{projects: {{breg: {{path: .}}}}}}\naudiences:\n breg: registry\n\ people:\n operator:\n subject: operator\n client: operator-client\n roles: [operator]\n\ journeyFile: dev-journeys.yaml\n\ {extra}" diff --git a/crates/registry-platform-config/src/service_compiler.rs b/crates/registry-platform-config/src/service_compiler.rs index 9ee01f6db0..384346f968 100644 --- a/crates/registry-platform-config/src/service_compiler.rs +++ b/crates/registry-platform-config/src/service_compiler.rs @@ -104,7 +104,7 @@ struct ProductReferences { #[serde(deny_unknown_fields)] #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] struct NamedProjects { - /// Projects keyed by service product ID. BReg IDs form the generated client member names. + /// Projects keyed by project ID. In a service, BReg IDs form the generated client member names. #[cfg_attr( feature = "schema", schemars(schema_with = "local_index::", extend("minProperties" = 1)) @@ -116,7 +116,7 @@ struct NamedProjects { #[serde(deny_unknown_fields)] #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] struct ProjectReference { - /// Directory containing the product's native project file, relative to this service file. + /// Directory containing the product's native project file, relative to the file that declares it. path: PathBuf, } @@ -304,7 +304,7 @@ pub fn plan(file: &Path, options: Options<'_>) -> Result { let entries = dev_inventory(root, &settings)?; project_dev(root, &settings, &entries, &settings)? } else { - return Err(two_inventories(&settings)); + return Err(two_inventories(&settings, doc)); }; (Some(root.to_owned()), Some(projection.native)) } @@ -333,14 +333,16 @@ struct ServiceDocument { } fn read_service(file: &Path, workspace: Option<&Path>) -> Result { - let file = file.canonicalize().map_err(|_| unreadable(file))?; + // Refusals name the path as written, never where a link resolves. + let authored = file; + let file = file.canonicalize().map_err(|_| unreadable(authored))?; let directory = file.parent().ok_or_else(|| unreadable(&file))?; let workspace = match workspace { Some(root) => root.canonicalize().map_err(|_| unreadable(root))?, None => directory.to_owned(), }; if !file.starts_with(&workspace) || !workspace.is_dir() { - return Err(unreadable(&file)); + return Err(unreadable(authored)); } let decoded = Reader::new(file.display().to_string()) .with_hook(&mut AuthoredExpressions) @@ -371,11 +373,11 @@ fn development_inventory( .then(|| read_service(&service_file, Some(root))) .transpose()?; if settings.span_of("/products").is_some() { - if service + if let Some(service) = service .as_ref() - .is_some_and(|service| service.decoded.value.products.is_some()) + .filter(|service| service.decoded.value.products.is_some()) { - return Err(two_inventories(settings)); + return Err(two_inventories(settings, &service.decoded.document)); } return Ok((settings.clone(), dev_inventory(root, settings)?)); } @@ -423,7 +425,7 @@ fn dev_inventory(root: &Path, settings: &Document) -> Result, Repor "rstack.dev.products-list", "/products", "The development products are a mapping of product kinds, not a list.", - "Write each product as products..projects..path (products..path for Casework and Messaging) and move its audience to audiences..", + "Write each product as products..projects..path for breg, coordinator and evidence, or products..path for every other kind, and move its audience to audiences..", )); } let workspace = root.canonicalize().map_err(|_| unreadable(root))?; @@ -431,14 +433,18 @@ fn dev_inventory(root: &Path, settings: &Document) -> Result, Repor products(references, settings, &workspace, &workspace) } -fn two_inventories(settings: &Document) -> Report { - problem( +fn two_inventories(settings: &Document, service: &Document) -> Report { + let mut report = problem( settings, "rstack.service.dev-products", "/products", "The service file already declares the development products.", "Declare the products in one file: remove them from these development settings, or from service.yaml.", - ) + ); + if let Some(diagnostic) = report.diagnostics_mut().first_mut() { + service.add_related_value(diagnostic, "/products", "the service file's products"); + } + report } fn read_settings(root: &Path) -> Result { diff --git a/crates/registry-platform-config/src/service_compiler/tests.rs b/crates/registry-platform-config/src/service_compiler/tests.rs index 62e806d0e8..904b9d6ade 100644 --- a/crates/registry-platform-config/src/service_compiler/tests.rs +++ b/crates/registry-platform-config/src/service_compiler/tests.rs @@ -129,6 +129,12 @@ fn two_inventories_in_one_directory_are_refused_at_the_dev_products() { assert_eq!(diagnostic.code, "rstack.service.dev-products"); assert_eq!(diagnostic.path, "/products"); assert_eq!(source_file(&diagnostic), "dev.yaml"); + let [related] = diagnostic.related.as_slice() else { + panic!("expected the service inventory as the related location"); + }; + assert!(related.file.ends_with("service.yaml"), "{}", related.file); + assert_eq!(related.path, "/products"); + assert_eq!(related.line, Some(4)); assert!(development_product_kinds(&directory.root).is_err()); } @@ -140,14 +146,13 @@ fn the_retired_product_list_is_refused_with_the_mapping_named() { let diagnostic = refusal(directory.plan().err().expect("the list is retired")); assert_eq!(diagnostic.code, "rstack.dev.products-list"); assert_eq!(diagnostic.path, "/products"); - assert!( - diagnostic - .suggested_action - .contains("products..projects..path") - && diagnostic.suggested_action.contains("audiences."), - "{}", - diagnostic.suggested_action + assert_eq!( + diagnostic.suggested_action, + "Write each product as products..projects..path for breg, coordinator and evidence, or products..path for every other kind, and move its audience to audiences.." ); + let source = diagnostic.source.as_ref().expect("a located diagnostic"); + assert_eq!((source.line, source.column), (Some(6), Some(3))); + assert_eq!(source_file(&diagnostic), "dev.yaml"); } #[test] diff --git a/crates/registry-rstack-dev/src/lib.rs b/crates/registry-rstack-dev/src/lib.rs index 8ddc19f915..8de46d2668 100644 --- a/crates/registry-rstack-dev/src/lib.rs +++ b/crates/registry-rstack-dev/src/lib.rs @@ -939,12 +939,14 @@ fn check( Ok(report) => (report, DOMAIN_REFUSAL_EXIT), Err(error) => { if let Some(unavailable) = error.downcast_ref::() { - let report = Report::new(vec![Diagnostic::error( + let mut diagnostic = Diagnostic::error( "rstack.dev.check-unavailable", unavailable.field(), unavailable.reason(), unavailable.remedy(), - )]); + ); + diagnostic.source = unavailable.source().cloned(); + let report = Report::new(vec![diagnostic]); return write_check_report( report, OPERATIONAL_FAILURE_EXIT, diff --git a/crates/registry-rstack-dev/src/plan.rs b/crates/registry-rstack-dev/src/plan.rs index 026e1a0698..54ad647604 100644 --- a/crates/registry-rstack-dev/src/plan.rs +++ b/crates/registry-rstack-dev/src/plan.rs @@ -120,6 +120,12 @@ pub(crate) fn schema() -> schemars::Schema { .expect("Plan has a properties mapping"); properties.insert("products".to_owned(), products.to_value()); properties.insert("audiences".to_owned(), audiences.to_value()); + // The native product list item is internal once products is the mapping. + schema + .get_mut("$defs") + .and_then(Value::as_object_mut) + .expect("Plan has definitions") + .remove("ProductPlan"); let required = schema .get_mut("required") .and_then(Value::as_array_mut) @@ -132,7 +138,7 @@ pub(crate) fn schema() -> schemars::Schema { "if": {"required": ["preview"]}, "then": { "properties": {"issuer": {"const": "run"}}, - "not": {"required": ["application"]} + "not": {"anyOf": [{"required": ["application"]}, {"required": ["products"]}]} } }]), ); @@ -1156,12 +1162,17 @@ fn authored_error( }; match error.downcast::() { Ok(unavailable) => { - let field = sources - .map_or(unavailable.field(), |sources| { - sources.locate(document, unavailable.field()).1 - }) - .to_owned(); - unavailable.at(&field).into() + let (source, field) = sources.map_or((document, unavailable.field()), |sources| { + sources.locate(document, unavailable.field()) + }); + let position = source.span_of(field).map(|span| span.start); + let located = registry_platform_yaml::Source { + file: source.file().to_owned(), + line: position.map(|position| position.line), + column: position.map(|position| position.column), + }; + let field = field.to_owned(); + unavailable.at(&field, located).into() } Err(error) => error, } @@ -1282,7 +1293,15 @@ fn preview_plan( let Some(preview) = &decoded.value.preview else { return Ok(None); }; - let build = preview.build_plan(root, &decoded.value, decoded.sources.is_some()); + if decoded.document.span_of("/products").is_some() { + let refusal = SemanticRefusal::new( + "/products", + "A browser preview takes its products from the sibling service.yaml.", + "Declare the one BReg project under products in service.yaml and keep only audiences in dev.yaml.", + ); + return Err(refusal_report(decoded, &refusal).into()); + } + let build = preview.build_plan(root, &decoded.value); match build { Ok(build) => { anyhow::ensure!( @@ -2313,6 +2332,10 @@ mod tests { // The inventory reader opens service.yaml first and refuses the link. let error = load(project.path()).err().unwrap().to_string(); assert!(error.contains("rstack.service.read"), "{error}"); + assert!( + !error.contains(&outside.path().display().to_string()), + "{error}" + ); } fn plan(step: Value) -> (tempfile::TempDir, Plan) { diff --git a/crates/registry-rstack-dev/src/preview.rs b/crates/registry-rstack-dev/src/preview.rs index e910e7bf58..5299724d69 100644 --- a/crates/registry-rstack-dev/src/preview.rs +++ b/crates/registry-rstack-dev/src/preview.rs @@ -64,21 +64,15 @@ pub(super) struct PreviewProduct { } impl Preview { - pub(super) fn build_plan( - &self, - root: &Path, - native: &plan::Plan, - composed: bool, - ) -> Result { + pub(super) fn build_plan(&self, root: &Path, native: &plan::Plan) -> Result { let refusal = || { plan::refuse( "/preview", - "A browser preview requires one named BReg, a UI, declared functions, issuer run, and a composed plan.", - "Set audiences by product ID and remove any explicit application or external issuer from this preview.", + "A browser preview requires one named BReg in service.yaml, a UI, declared functions, and issuer run.", + "Declare the one BReg project under products in service.yaml, set its audience in dev.yaml, and remove any explicit application or external issuer from this preview.", ) }; - if !composed - || native.application.is_some() + if native.application.is_some() || native.issuer != "run" || native.products.len() != 1 || native.products[0].product != Product::Breg diff --git a/crates/registry-rstack-dev/src/products.rs b/crates/registry-rstack-dev/src/products.rs index 2c15759e49..a815e9f92a 100644 --- a/crates/registry-rstack-dev/src/products.rs +++ b/crates/registry-rstack-dev/src/products.rs @@ -2602,6 +2602,7 @@ pub(super) struct ProductInspection { #[error("{reason}")] pub(super) struct InspectionUnavailable { field: String, + source: Option, reason: String, remedy: String, } @@ -2610,6 +2611,7 @@ impl InspectionUnavailable { fn new(field: &str, reason: &str, remedy: &str) -> Self { Self { field: field.to_owned(), + source: None, reason: reason.to_owned(), remedy: remedy.to_owned(), } @@ -2619,9 +2621,15 @@ impl InspectionUnavailable { &self.field } + /// The authored file and position of the field, once located. + pub(super) fn source(&self) -> Option<®istry_platform_yaml::Source> { + self.source.as_ref() + } + /// The same refusal at the authored location of its native plan field. - pub(super) fn at(mut self, field: &str) -> Self { + pub(super) fn at(mut self, field: &str, source: registry_platform_yaml::Source) -> Self { field.clone_into(&mut self.field); + self.source = Some(source); self } diff --git a/crates/registry-rstack-dev/tests/dev_schema.rs b/crates/registry-rstack-dev/tests/dev_schema.rs index c51a1a2a0e..b51e06b193 100644 --- a/crates/registry-rstack-dev/tests/dev_schema.rs +++ b/crates/registry-rstack-dev/tests/dev_schema.rs @@ -430,12 +430,10 @@ fn the_preview_examples_satisfy_the_composed_dev_and_service_schemas() { settings["issuer"] = json!("https://example.invalid"); assert!(!dev.is_valid(&settings), "a preview uses the run issuer"); settings["issuer"] = json!("run"); - settings.as_object_mut().unwrap().remove("audiences"); - settings["products"] = - json!([{"product":"breg", "project":"project", "audience":"urn:test:preview"}]); + settings["products"] = json!({"breg": {"projects": {"businesses": {"path": "project"}}}}); assert!( !dev.is_valid(&settings), - "a preview needs a composed service" + "a preview takes its products from service.yaml" ); } } diff --git a/crates/registry-rstack/tests/dev_run.rs b/crates/registry-rstack/tests/dev_run.rs index 924b5d7420..9295f9f8e1 100644 --- a/crates/registry-rstack/tests/dev_run.rs +++ b/crates/registry-rstack/tests/dev_run.rs @@ -2042,6 +2042,36 @@ fn old_kind_is_refused_with_the_new_name() { assert!(!state.exists()); } +#[test] +fn check_refuses_the_retired_product_list_in_dev_yaml() { + let scratch = tempfile::tempdir().unwrap(); + let state = scratch.path().join("state"); + project(scratch.path(), ""); + let dev = scratch.path().join("dev.yaml"); + let mapping = "products:\n breg: {projects: {breg: {path: .}}}\n"; + let text = fs::read_to_string(&dev).unwrap(); + assert!(text.contains(mapping), "{text}"); + fs::write( + &dev, + text.replace( + mapping, + "products:\n - {product: breg, project: ., audience: registry}\n", + ), + ) + .unwrap(); + + let result = check(scratch.path(), &state, true); + + assert_eq!(result.status.code(), Some(1), "{result:?}"); + let report: serde_json::Value = serde_json::from_slice(&result.stdout).unwrap(); + let diagnostic = &report["diagnostics"][0]; + assert_eq!(diagnostic["code"], "rstack.dev.products-list", "{report}"); + assert_eq!(diagnostic["path"], "/products", "{report}"); + assert_eq!(diagnostic["source"]["file"], utf8(&dev), "{report}"); + assert!(diagnostic["source"]["line"].is_u64(), "{report}"); + assert!(!state.exists()); +} + #[test] fn check_renders_both_locations_of_a_duplicate_key() { let scratch = tempfile::tempdir().unwrap(); @@ -2568,6 +2598,12 @@ fn check_distinguishes_an_unavailable_casework_helper_from_an_invalid_project() let diagnostic = &report["diagnostics"][0]; assert_eq!(diagnostic["path"], "/products/casework/path"); assert_eq!(diagnostic["code"], "rstack.dev.check-unavailable"); + assert_eq!( + diagnostic["source"]["file"], + utf8(&scratch.path().join("dev.yaml")), + "{report}" + ); + assert!(diagnostic["source"]["line"].is_u64(), "{report}"); assert!( diagnostic["message"] .as_str() @@ -2606,6 +2642,12 @@ fn check_distinguishes_an_unavailable_casework_helper_from_an_invalid_project() let diagnostic = &report["diagnostics"][0]; assert_eq!(diagnostic["path"], "/products/casework/path"); assert_eq!(diagnostic["code"], "rstack.dev.check-unavailable"); + assert_eq!( + diagnostic["source"]["file"], + utf8(&scratch.path().join("dev.yaml")), + "{report}" + ); + assert!(diagnostic["source"]["line"].is_u64(), "{report}"); assert!( diagnostic["message"] .as_str() @@ -4333,6 +4375,38 @@ fn preview_check_is_offline_and_reports_invalid_actor_and_routes() { "{diagnostic}" ); assert!(!state.exists()); + + // A preview takes its products from service.yaml, not from dev.yaml. + let products = "products:\n breg:\n projects:\n demo: {path: .}\n"; + assert!(original.contains(products), "{original}"); + fs::write(&service, original.replace(products, "")).unwrap(); + fs::write( + project.join("dev.yaml"), + format!( + "{}{preview}", + dev.replace( + "audiences: {demo: registry}\n", + &format!("{products}audiences: {{demo: registry}}\n"), + ) + ), + ) + .unwrap(); + let refused = check(project, &state, true); + assert_eq!(refused.status.code(), Some(1), "{refused:?}"); + let report: serde_json::Value = serde_json::from_slice(&refused.stdout).unwrap(); + let diagnostic = &report["diagnostics"][0]; + assert_eq!(diagnostic["path"], "/products", "{report}"); + assert_eq!( + diagnostic["source"]["file"], + utf8(&project.join("dev.yaml")), + "{report}" + ); + assert_eq!( + diagnostic["message"], + "A browser preview takes its products from the sibling service.yaml." + ); + assert!(!state.exists()); + fs::write(project.join("dev.yaml"), format!("{dev}{preview}")).unwrap(); fs::write(&service, original).unwrap(); let started = dev_json(&state, &["start", utf8(project)]); diff --git a/products/coordinator/scripts/test-real-services.py b/products/coordinator/scripts/test-real-services.py index 380b0e0a8a..aab32f6bd1 100644 --- a/products/coordinator/scripts/test-real-services.py +++ b/products/coordinator/scripts/test-real-services.py @@ -698,12 +698,18 @@ def start_dev_issuer(self, breg_project, coordinator_project): "kind": "RStackDev", "issuer": "https://dev-issuer.local.test", "journeyFile": "dev-journeys.yaml", - "products": [ - {"product": "breg", "project": "breg", "audience": self.issuer_resource}, - {"product": "casework", "project": "casework", "audience": self.casework_resource}, - {"product": "messaging", "project": "messaging", "audience": "urn:example:messaging"}, - {"product": "coordinator", "project": "coordinator", "audience": COORDINATOR_RESOURCE}, - ], + "products": { + "breg": {"projects": {"breg": {"path": "breg"}}}, + "casework": {"path": "casework"}, + "messaging": {"path": "messaging"}, + "coordinator": {"projects": {"coordinator": {"path": "coordinator"}}}, + }, + "audiences": { + "breg": self.issuer_resource, + "casework": self.casework_resource, + "messaging": "urn:example:messaging", + "coordinator": COORDINATOR_RESOURCE, + }, "people": { alias: { "subject": principal, "client": alias, "roles": [alias], @@ -1000,7 +1006,8 @@ def fixture_key(client, purpose): private(project / "dev.yaml", { "apiVersion": "id.registrystack.org/formats/rstack/dev/v1alpha1", "kind": "RStackDev", "issuer": issuer, "externalJwksUri": issuer + "/oauth2/jwks", - "products": [{"product": "breg", "project": ".", "audience": resource}], + "products": {"breg": {"projects": {"breg": {"path": "."}}}}, + "audiences": {"breg": resource}, "people": people, "journeyFile": "dev-journeys.yaml", "externalBreg": external, }) private(project / "dev-journeys.yaml", { diff --git a/products/evidence/loadtest/support/loadenv.py b/products/evidence/loadtest/support/loadenv.py index efc71dd536..bd73ba5778 100755 --- a/products/evidence/loadtest/support/loadenv.py +++ b/products/evidence/loadtest/support/loadenv.py @@ -178,7 +178,9 @@ def dev_plan(clients: int) -> str: "kind: RStackDev", "issuer: run", "products:", - f' - {{product: evidence, project: ., audience: "{DEV_AUDIENCE}"}}', + " evidence: {projects: {evidence: {path: .}}}", + "audiences:", + f' evidence: "{DEV_AUDIENCE}"', "people:", ] for client in client_ids(clients): diff --git a/products/evidence/loadtest/support/test_harness.py b/products/evidence/loadtest/support/test_harness.py index cb31dd5b1b..6a028ae091 100644 --- a/products/evidence/loadtest/support/test_harness.py +++ b/products/evidence/loadtest/support/test_harness.py @@ -308,6 +308,11 @@ def test_local_project_adds_a_bounded_synthetic_source_and_refuses_reuse(self) - dev_plan = (project / "dev.yaml").read_text(encoding="utf-8") self.assertIn("kind: RStackDev", dev_plan) self.assertIn("issuer: run", dev_plan) + self.assertIn( + "products:\n evidence: {projects: {evidence: {path: .}}}\n" + f'audiences:\n evidence: "{loadenv.DEV_AUDIENCE}"\n', + dev_plan, + ) self.assertIn("journeyFile: dev-journeys.yaml", dev_plan) self.assertEqual(dev_plan.count("roles: [standalone-service]"), 3) self.assertEqual((project / "service.yaml").read_bytes(), (canonical / "service.yaml").read_bytes()) diff --git a/products/platform/config-formats.yaml b/products/platform/config-formats.yaml index 1ef1bf567d..5f97332f3a 100644 --- a/products/platform/config-formats.yaml +++ b/products/platform/config-formats.yaml @@ -850,7 +850,7 @@ formats: set: /people/operator/roles reference: none operand: none - relativePath: none + relativePath: /products/breg/projects/breg/path securityMembers: - pointer: /issuer whenOmitted: refused diff --git a/products/platform/scripts/test-rstack-dev.py b/products/platform/scripts/test-rstack-dev.py index 916d42b128..7136d71226 100644 --- a/products/platform/scripts/test-rstack-dev.py +++ b/products/platform/scripts/test-rstack-dev.py @@ -1313,7 +1313,8 @@ def spatial_project(root, name): "apiVersion": "id.registrystack.org/formats/rstack/dev/v1alpha1", "kind": "RStackDev", "issuer": "https://spatial-smoke.example.invalid", - "products": [{"product": "breg", "project": "registry", "audience": "breg"}], + "products": {"breg": {"projects": {"breg": {"path": "registry"}}}}, + "audiences": {"breg": "breg"}, "people": people, "journey": { "id": "spatial-smoke", @@ -1465,9 +1466,8 @@ def encrypted_project(root, name): "apiVersion": "id.registrystack.org/formats/rstack/dev/v1alpha1", "kind": "RStackDev", "issuer": "https://directory-smoke.example.invalid", - "products": [ - {"product": "breg", "project": "registry", "audience": "directory"} - ], + "products": {"breg": {"projects": {"breg": {"path": "registry"}}}}, + "audiences": {"breg": "directory"}, "people": { alias: { "subject": principal, @@ -1765,13 +1765,13 @@ def verify_offline_plan(root, bin_dir, project): ) shutil.copyfile(NATIVE_REVIEW / "service.yaml", binding / "service.yaml") authored = (NATIVE_REVIEW / "dev.yaml").read_text() - audience = 'audience: "urn:journey:breg"' + audience = 'breg: "urn:journey:breg"' assert authored.count(audience) == 1 - (binding / "dev.yaml").write_text(authored.replace(audience, "audience: registry")) + (binding / "dev.yaml").write_text(authored.replace(audience, "breg: registry")) refused = dev(bin_dir, check_env, binding, "check", ".", expected=1) [diagnostic] = refused["diagnostics"] assert refused["status"] == "domain-refusal" - assert diagnostic["path"] == "/products/0/audience" + assert diagnostic["path"] == "/audiences/breg" assert diagnostic["message"].startswith("Casework refuses"), diagnostic assert ( "contextProviders.registry.humanSourceAuthentication.audience: " From fe521fe7be4c161141eeeebc77411adb62fdc7af Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 22:29:32 +0000 Subject: [PATCH 117/183] fix(dev): place projected plan diagnostics at their authored keys A composed dev.yaml is decoded from its projection, so the reader's positions point into JSON. Keep the reader's choice of key, value or whole file, move related notes into the authored file, and regenerate the dev and service schemas for the review fixes. Name the unavailable-helper location so it is not read as an error source. Signed-off-by: Jeremi Joslin --- crates/registry-rstack-dev/src/lib.rs | 2 +- crates/registry-rstack-dev/src/plan.rs | 36 +++++++++++++++- crates/registry-rstack-dev/src/products.rs | 12 +++--- .../generated/dev/dev.v1alpha1.schema.json | 41 ++++++------------- .../dev/service.v1alpha1.schema.json | 4 +- 5 files changed, 57 insertions(+), 38 deletions(-) diff --git a/crates/registry-rstack-dev/src/lib.rs b/crates/registry-rstack-dev/src/lib.rs index 8de46d2668..f8299600cd 100644 --- a/crates/registry-rstack-dev/src/lib.rs +++ b/crates/registry-rstack-dev/src/lib.rs @@ -945,7 +945,7 @@ fn check( unavailable.reason(), unavailable.remedy(), ); - diagnostic.source = unavailable.source().cloned(); + diagnostic.source = unavailable.location().cloned(); let report = Report::new(vec![diagnostic]); return write_check_report( report, diff --git a/crates/registry-rstack-dev/src/plan.rs b/crates/registry-rstack-dev/src/plan.rs index 54ad647604..ad9f2ae3a3 100644 --- a/crates/registry-rstack-dev/src/plan.rs +++ b/crates/registry-rstack-dev/src/plan.rs @@ -1120,18 +1120,52 @@ fn decode_authored_plan( let decoded = Reader::new(&name) .decode::>(&bytes, &Expect::one(&FORMAT)) .map_err(|mut report| { + // The reader positioned these diagnostics in the projected JSON. + // Keep its choice of key, value or whole file, and place each one + // and its related notes in the authored file. + let projected = Reader::new(&name).read(&bytes, &Expect::one(&FORMAT)).ok(); for diagnostic in report.diagnostics_mut() { + let original = diagnostic + .source + .as_ref() + .map(|source| (source.line, source.column)); + let at_key = projected + .as_ref() + .and_then(|json| json.key_span_of(&diagnostic.path)) + .is_some_and(|span| { + original == Some((Some(span.start.line), Some(span.start.column))) + }); let (source, path) = projection.sources.locate(&document, &diagnostic.path); - let authored = source.diagnostic_at_value( + let place = if at_key { + Document::diagnostic_at_key + } else { + Document::diagnostic_at_value + }; + let mut authored = place( + source, diagnostic.severity, &diagnostic.code, path, &diagnostic.message, &diagnostic.suggested_action, ); + if original.is_some_and(|(line, _)| line.is_none()) { + if let Some(authored) = authored.source.as_mut() { + authored.line = None; + authored.column = None; + } + } diagnostic.path = authored.path; diagnostic.source = authored.source; diagnostic.artifact = authored.artifact; + for related in &mut diagnostic.related { + let (source, path) = projection.sources.locate(&document, &related.path); + let position = source.span_of(path).map(|span| span.start); + related.file = source.file().to_owned(); + related.line = position.map(|position| position.line); + related.column = position.map(|position| position.column); + related.path = path.to_owned(); + } } report })?; diff --git a/crates/registry-rstack-dev/src/products.rs b/crates/registry-rstack-dev/src/products.rs index a815e9f92a..1fef38b82e 100644 --- a/crates/registry-rstack-dev/src/products.rs +++ b/crates/registry-rstack-dev/src/products.rs @@ -2602,7 +2602,7 @@ pub(super) struct ProductInspection { #[error("{reason}")] pub(super) struct InspectionUnavailable { field: String, - source: Option, + location: Option, reason: String, remedy: String, } @@ -2611,7 +2611,7 @@ impl InspectionUnavailable { fn new(field: &str, reason: &str, remedy: &str) -> Self { Self { field: field.to_owned(), - source: None, + location: None, reason: reason.to_owned(), remedy: remedy.to_owned(), } @@ -2622,14 +2622,14 @@ impl InspectionUnavailable { } /// The authored file and position of the field, once located. - pub(super) fn source(&self) -> Option<®istry_platform_yaml::Source> { - self.source.as_ref() + pub(super) fn location(&self) -> Option<®istry_platform_yaml::Source> { + self.location.as_ref() } /// The same refusal at the authored location of its native plan field. - pub(super) fn at(mut self, field: &str, source: registry_platform_yaml::Source) -> Self { + pub(super) fn at(mut self, field: &str, location: registry_platform_yaml::Source) -> Self { field.clone_into(&mut self.field); - self.source = Some(source); + self.location = Some(location); self } diff --git a/products/platform/generated/dev/dev.v1alpha1.schema.json b/products/platform/generated/dev/dev.v1alpha1.schema.json index c284677e26..49de653b2e 100644 --- a/products/platform/generated/dev/dev.v1alpha1.schema.json +++ b/products/platform/generated/dev/dev.v1alpha1.schema.json @@ -434,7 +434,7 @@ "additionalProperties": { "$ref": "#/$defs/ProjectReference" }, - "description": "Projects keyed by service product ID. BReg IDs form the generated client member names.", + "description": "Projects keyed by project ID. In a service, BReg IDs form the generated client member names.", "minProperties": 1, "propertyNames": { "$ref": "#/$defs/LocalId" @@ -495,30 +495,6 @@ ], "type": "string" }, - "ProductPlan": { - "additionalProperties": false, - "description": "One product to start and where its project lives.", - "properties": { - "audience": { - "$ref": "#/$defs/ExternalId", - "description": "Token audience this product accepts: 1 to 256 characters without whitespace or control characters, distinct from the other products' audiences. BReg may instead equal `personAudience`." - }, - "product": { - "$ref": "#/$defs/Product", - "description": "Which product to start." - }, - "project": { - "description": "Relative path from the plan's directory to the product project, or `.` for the plan's own directory. It must contain the product’s project manifest.", - "type": "string" - } - }, - "required": [ - "product", - "project", - "audience" - ], - "type": "object" - }, "ProductReferences": { "additionalProperties": false, "minProperties": 1, @@ -560,7 +536,7 @@ "additionalProperties": false, "properties": { "path": { - "description": "Directory containing the product's native project file, relative to this service file.", + "description": "Directory containing the product's native project file, relative to the file that declares it.", "type": "string" } }, @@ -788,8 +764,17 @@ }, "then": { "not": { - "required": [ - "application" + "anyOf": [ + { + "required": [ + "application" + ] + }, + { + "required": [ + "products" + ] + } ] }, "properties": { diff --git a/products/platform/generated/dev/service.v1alpha1.schema.json b/products/platform/generated/dev/service.v1alpha1.schema.json index f3be3a3e4f..260d935d50 100644 --- a/products/platform/generated/dev/service.v1alpha1.schema.json +++ b/products/platform/generated/dev/service.v1alpha1.schema.json @@ -39,7 +39,7 @@ "additionalProperties": { "$ref": "#/$defs/ProjectReference" }, - "description": "Projects keyed by service product ID. BReg IDs form the generated client member names.", + "description": "Projects keyed by project ID. In a service, BReg IDs form the generated client member names.", "minProperties": 1, "propertyNames": { "$ref": "#/$defs/LocalId" @@ -93,7 +93,7 @@ "additionalProperties": false, "properties": { "path": { - "description": "Directory containing the product's native project file, relative to this service file.", + "description": "Directory containing the product's native project file, relative to the file that declares it.", "type": "string" } }, From d74c2660ee7d2c3d4f6f3e6551a1cf2aa32df496 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 22:53:52 +0000 Subject: [PATCH 118/183] chore(identifiers): regenerate the catalogue for the carried schema changes Signed-off-by: Jeremi Joslin --- .../identifiers/generated/catalog.v1.json | 46 +++++++++---------- 1 file changed, 23 insertions(+), 23 deletions(-) diff --git a/products/identifiers/generated/catalog.v1.json b/products/identifiers/generated/catalog.v1.json index 0bb695ff75..521b6ffd92 100644 --- a/products/identifiers/generated/catalog.v1.json +++ b/products/identifiers/generated/catalog.v1.json @@ -5267,7 +5267,7 @@ }, "artifact": { "path": "products/adapter/schemas/job-runtime.v1alpha1.schema.json", - "sha256": "867bd2e4a48ffa4e639002d8b19522804d6716903c99508c2a4d4436a3b96398", + "sha256": "fd12314109d5ecacf116c9489f928fdb22dc7a5459c79096005b0d887f34d2d2", "mediaType": "application/schema+json" } }, @@ -5447,7 +5447,7 @@ }, "artifact": { "path": "products/adapter/schemas/runtime.v1alpha1.schema.json", - "sha256": "99d3b0f61717e804fde996a4f042d375a3957e4f6e07bd9d313ef31c1310529c", + "sha256": "114aa69242ef4bda35c5ebdf71530fd9551b5b365890ef8a440d1df23db7028e", "mediaType": "application/schema+json" } }, @@ -5663,7 +5663,7 @@ }, "artifact": { "path": "products/breg/generated/mcp-runtime/mcp-runtime.schema.json", - "sha256": "a1272f3d77f9a8e27425e8613d3a2cf76cb37e60eb90c6473660b9f7e0d3da8c", + "sha256": "8b759e11301ca05eadb951aff39dfbb31b05481e68d222b4237c66661edc06f1", "mediaType": "application/schema+json" } }, @@ -5807,7 +5807,7 @@ }, "artifact": { "path": "products/breg/generated/review-runtime/review-runtime.schema.json", - "sha256": "ec5d87d3668095586a821abd7a0f8b998bdad11f10123392188de6808bd129d9", + "sha256": "7009f1c4301a93861873dd849b7abbc1193637a2ac2c84fd9b2fbfcd52378e01", "mediaType": "application/schema+json" } }, @@ -5843,7 +5843,7 @@ }, "artifact": { "path": "products/breg/generated/runtime/runtime.schema.json", - "sha256": "d04c498a9cf820332b5d8a9f09b61e215bc0c3dca6d770b49e67cf4844626d9e", + "sha256": "e99a03becdfdf693da8cbdd8e37319a4c1ce2f9c1588ec78c4813005e9f0f0c2", "mediaType": "application/schema+json" } }, @@ -5951,7 +5951,7 @@ }, "artifact": { "path": "products/casework/generated/runtime/runtime.schema.json", - "sha256": "43f97b7653608f98df7093fde327d515d76380213350af7c85d027e609c70099", + "sha256": "d7119a087c77192b099034d1304922118b9be1a9efa2e04adcab533629fa0f1f", "mediaType": "application/schema+json" } }, @@ -6005,7 +6005,7 @@ }, "artifact": { "path": "products/coordinator/generated/runtime/runtime.schema.json", - "sha256": "24839c55d2b01edab884dcc18ee1324689dbd52fe958fba51fe55cc5b15d2099", + "sha256": "e13ad43e7b12338611fc69a0e2c9c0def7dbe42ff7655cdb7180f0c4d719d3c5", "mediaType": "application/schema+json" } }, @@ -6167,7 +6167,7 @@ }, "artifact": { "path": "products/documents/generated/runtime/runtime.schema.json", - "sha256": "d076eeea14926df9c8812c5e01f1a1e6dbfb2556e490404d848203ee67492de7", + "sha256": "493af8d7b9a450903138e999f63142e128807e50cfb7a27f429269b50cc013d2", "mediaType": "application/schema+json" } }, @@ -6325,11 +6325,11 @@ "description": "Evidence OID4VCI delivery runtime configuration JSON Schema.", "source": { "path": "crates/registry-evidence-oid4vci/src/schema.rs", - "sha256": "a68d455ad4aae15031875f71af0047197cac6224aaa5f62f5c4a8cc936527224" + "sha256": "4765ede33c3ad60e6defd1fd4f7fb59180dd0f9ab04280e8d83a0e5f25081a5d" }, "artifact": { "path": "products/evidence/generated/oid4vci-runtime/oid4vci-runtime.schema.json", - "sha256": "01a20c74693699d6be5c62584edbf3137e49fbf2f3c2c4c5616004a873b5b765", + "sha256": "39cf28ae80e6eee04ace9474c6652d52659167d847073d54ff01e72a322150ab", "mediaType": "application/schema+json" } }, @@ -6347,7 +6347,7 @@ }, "artifact": { "path": "products/evidence/generated/oid4vp-runtime/oid4vp-runtime.schema.json", - "sha256": "81d70d9488a0bd7cdbaf897ad016fe9cca86b862b5ee5e6b891279b0197a52d6", + "sha256": "b228e4e511c6c6afc2b5ac12edd322a9ee1f977f59f7907586bd81fde567a01b", "mediaType": "application/schema+json" } }, @@ -6419,7 +6419,7 @@ }, "artifact": { "path": "crates/registry-evidencectl/schemas/authoring/store-provision.schema.json", - "sha256": "ad586d201fb64370c09ec18bf9c6aa57f3a8833aaecac7ba748f09dc0bc36d51", + "sha256": "c89de9234b9e92ef6c92f88a32fa3e91dfaa07dee510f7a2cb03aef1f69f917b", "mediaType": "application/schema+json" } }, @@ -6581,7 +6581,7 @@ }, "artifact": { "path": "products/messaging/generated/runtime/runtime.schema.json", - "sha256": "5f42d3706e2b6ad00a430288c7c637395bbee43b8b7635fc0ceb990bebeb788d", + "sha256": "f950af9d9b58006890d657dfd910722ec268e71b9beabc18eede9ab521d0b85a", "mediaType": "application/schema+json" } }, @@ -6653,7 +6653,7 @@ }, "artifact": { "path": "crates/registry-cli-api/schema/connections.schema.json", - "sha256": "9d757eeac7bfd9a08ac7d421d6dd4620344d924becd31a77bcf7aec87d8e6b6c", + "sha256": "d826fdedf9db4049195664fc483db6749180dcd0335863ab56d548fddfbd1a45", "mediaType": "application/schema+json" } }, @@ -6667,7 +6667,7 @@ "description": "Report of the shared `provision` command that creates a product's PostgreSQL roles, database, schemas and extensions.", "source": { "path": "crates/registry-platform-provision/src/cli.rs", - "sha256": "29625dd439514b1351a0d36cba1102895a13416aa65a5675a10435d71bb4549b" + "sha256": "d5c59e2cdb955f33a5806c825ae9be6204a11797adf0afb05865e807827293c2" }, "artifact": { "path": "crates/registry-platform-provision/schema/provision-report.schema.json", @@ -6725,7 +6725,7 @@ }, "artifact": { "path": "products/platform/generated/mcp-runtime/mcp-runtime.schema.json", - "sha256": "943bb3a53811c35e5cb9a3457a7c5225586e26dbea99b50b005825e5cd5df86a", + "sha256": "ea22c026fe461327a97b37dd2534b78255570b7df9bd75772b31f386a8e883ca", "mediaType": "application/schema+json" } }, @@ -6739,7 +6739,7 @@ "description": "rstack error report JSON Schema.", "source": { "path": "crates/registry-rstack/src/cli.rs", - "sha256": "c0fe7cb20b590714dd367fffab20a33ef4e3afb4272811d7e34b34bcb7757495" + "sha256": "0d9a9654fefbc7fb5ab8bce66129be190c984bfe31aa1e1ac550e62c96d36ffb" }, "artifact": { "path": "products/platform/schemas/rstack-dev-error.v1.schema.json", @@ -6779,7 +6779,7 @@ }, "artifact": { "path": "products/platform/generated/session-runtime/session-runtime.schema.json", - "sha256": "c80019fe44d6032107978be57e1380b2fb060b527f535a4a1705b733b2517f01", + "sha256": "3139024000f51fbd4715b1ed048775e5277a920fe026a23a5cb750ccc5ea1de3", "mediaType": "application/schema+json" } }, @@ -6797,7 +6797,7 @@ }, "artifact": { "path": "products/platform/schemas/task-connection.schema.json", - "sha256": "d1e3b34b174de0afb1cf1c87895f51273541305d451e3fcb9891393448ebd745", + "sha256": "f579e5d0289e8d7ead2b442f29c346ff7cece9bb245197cb38616c271562f484", "mediaType": "application/schema+json" } }, @@ -6869,7 +6869,7 @@ }, "artifact": { "path": "products/render/schemas/runtime.schema.json", - "sha256": "f08bea3ff05ebcae08042409cc4616834460308489c220cc06d8e729b7e02bd7", + "sha256": "f2d3e0cb18bae70a57b1d6e85b03bdbb0ed8712d06e68744747666b10fff806a", "mediaType": "application/schema+json" } }, @@ -6887,7 +6887,7 @@ }, "artifact": { "path": "products/platform/generated/dev/dev.v1alpha1.schema.json", - "sha256": "88c6a55a99fa1df179ecbf0899a62755831e2052b65ad16d53856776e80d6617", + "sha256": "f4d72b0fbb16c1f1205cca3f80ae81a6bb46da44962ec74a5872a37589c50761", "mediaType": "application/schema+json" } }, @@ -6923,7 +6923,7 @@ }, "artifact": { "path": "products/platform/generated/dev/service.v1alpha1.schema.json", - "sha256": "e410d8aec61cc9029f3a22c03e8435476870b6a4c5166b2ae2231f6bd00b4618", + "sha256": "113e37bc3da27cf106f96c8ba1d48ab00c238adf3d0eaec02c1aeb0454afb16b", "mediaType": "application/schema+json" } }, @@ -6995,7 +6995,7 @@ }, "artifact": { "path": "products/scheduling/generated/runtime/runtime.schema.json", - "sha256": "a631ed1da44c6778cc9574284c697ea60a824ebd26d338e5ec3e825262cec440", + "sha256": "cbcef9c994e7f822c5b3385ed621777cbb1dc27467852943d18ecee04f965839", "mediaType": "application/schema+json" } }, From 43a851192219b1dab84e89ab76fe6ff80b132ac5 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 22:33:22 +0000 Subject: [PATCH 119/183] fix(evidence): keep mountPolicy out of the wallet adapters' published schemas The OID4VCI and OID4VP readers refuse the Compose mount policy under the Evidence key rule, so their generated runtime schemas no longer offer it. A shared helper drops the member and its definition. Refs #2882. Signed-off-by: Jeremi Joslin --- crates/registry-evidence-oid4vci/src/schema.rs | 7 +++++++ crates/registry-evidence-oid4vp/src/schema.rs | 7 +++++++ crates/registry-platform-config/src/schema.rs | 15 +++++++++++++++ .../oid4vci-runtime/oid4vci-runtime.schema.json | 13 ------------- .../oid4vp-runtime/oid4vp-runtime.schema.json | 13 ------------- 5 files changed, 29 insertions(+), 26 deletions(-) diff --git a/crates/registry-evidence-oid4vci/src/schema.rs b/crates/registry-evidence-oid4vci/src/schema.rs index 0e6d3658ec..ed2ed486f9 100644 --- a/crates/registry-evidence-oid4vci/src/schema.rs +++ b/crates/registry-evidence-oid4vci/src/schema.rs @@ -26,6 +26,8 @@ use crate::config::{ pub fn runtime_documents() -> Result, serde_json::Error> { let mut derived = serde_json::to_value(schemars::schema_for!(DeliveryDocument))?; refuse_null_outside_shared_blocks(&mut derived)?; + // The reader refuses the Compose mount policy under the Evidence key rule. + registry_platform_config::schema::without_compose_mount_policy(&mut derived); set_const(&mut derived, "apiVersion", OID4VCI_RUNTIME_API_VERSION); set_const(&mut derived, "kind", OID4VCI_RUNTIME_KIND); let mut object = match derived { @@ -214,6 +216,11 @@ mod tests { !schema.is_valid(&document) }; assert!(refused(&|document| document["version"] = Value::from(1))); + // The Evidence key rule refuses the Compose mount policy, so the + // published contract does not offer it. + assert!(refused(&|document| { + document["secretProviders"]["file"]["mountPolicy"] = Value::from("compose-native") + })); assert!(refused(&|document| { document["tokenClient"]["privateKeyFile"] = Value::from("client.jwk") })); diff --git a/crates/registry-evidence-oid4vp/src/schema.rs b/crates/registry-evidence-oid4vp/src/schema.rs index 0e7a29af3d..39ad8c661e 100644 --- a/crates/registry-evidence-oid4vp/src/schema.rs +++ b/crates/registry-evidence-oid4vp/src/schema.rs @@ -26,6 +26,8 @@ use crate::config::{ pub fn runtime_documents() -> Result, serde_json::Error> { let mut derived = serde_json::to_value(schemars::schema_for!(VerifierDocument))?; refuse_null_outside_shared_blocks(&mut derived)?; + // The reader refuses the Compose mount policy under the Evidence key rule. + registry_platform_config::schema::without_compose_mount_policy(&mut derived); set_const(&mut derived, "apiVersion", OID4VP_RUNTIME_API_VERSION); set_const(&mut derived, "kind", OID4VP_RUNTIME_KIND); let mut object = match derived { @@ -213,6 +215,11 @@ mod tests { !schema.is_valid(&document) }; assert!(refused(&|document| document["version"] = Value::from(1))); + // The Evidence key rule refuses the Compose mount policy, so the + // published contract does not offer it. + assert!(refused(&|document| { + document["secretProviders"]["file"]["mountPolicy"] = Value::from("compose-native") + })); assert!(refused(&|document| document["sessions"] = Value::Null)); assert!(refused( &|document| document["policies"] = serde_json::json!([]) diff --git a/crates/registry-platform-config/src/schema.rs b/crates/registry-platform-config/src/schema.rs index d5bdddbe88..98f0e4103f 100644 --- a/crates/registry-platform-config/src/schema.rs +++ b/crates/registry-platform-config/src/schema.rs @@ -62,6 +62,21 @@ pub fn shared_blocks_document() -> Result { Ok(rendered) } +/// Remove the Compose mount policy from a runtime schema whose product keeps +/// the strict secret file rule and refuses `secretProviders.file.mountPolicy`, +/// so the published contract does not offer a member the reader refuses. +pub fn without_compose_mount_policy(schema: &mut Value) { + if let Some(properties) = schema + .pointer_mut("/$defs/FileSecretProviderConfig/properties") + .and_then(Value::as_object_mut) + { + properties.remove("mountPolicy"); + } + if let Some(definitions) = schema.pointer_mut("/$defs").and_then(Value::as_object_mut) { + definitions.remove("SecretMountPolicy"); + } +} + /// Root `allOf` members stating that a static JWKS document at /// `authentication.oidc.issuers..jwksSource.documentRef` names a secret /// provider by its prefix, so a configuration where any issuer entry carries diff --git a/products/evidence/generated/oid4vci-runtime/oid4vci-runtime.schema.json b/products/evidence/generated/oid4vci-runtime/oid4vci-runtime.schema.json index 834ebdc45e..f34c65d944 100644 --- a/products/evidence/generated/oid4vci-runtime/oid4vci-runtime.schema.json +++ b/products/evidence/generated/oid4vci-runtime/oid4vci-runtime.schema.json @@ -182,13 +182,6 @@ "additionalProperties": false, "description": "The file secret provider.", "properties": { - "mountPolicy": { - "$ref": "#/$defs/SecretMountPolicy", - "description": "`compose-native` also accepts a root-owned regular file with one hard\nlink and mode exactly 0444, the shape of a Docker Compose secret mount.\nEvery user in the container can read such a file. Startup and `check`\nreport this explicit production setting. Without it, only the file\nshapes `root` describes are accepted.", - "x-registry-explicit-production": [ - "platform.posture.compose-native-secret-mount" - ] - }, "root": { "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. A public document, such as a static JWKS\nor a CA bundle, may also be readable by group and others.", "pattern": "^/", @@ -556,12 +549,6 @@ "$ref": "#/$defs/ExternalId", "description": "The name of the claim that carries scopes." }, - "SecretMountPolicy": { - "enum": [ - "compose-native" - ], - "type": "string" - }, "SecretProvidersConfig": { "additionalProperties": false, "anyOf": [ diff --git a/products/evidence/generated/oid4vp-runtime/oid4vp-runtime.schema.json b/products/evidence/generated/oid4vp-runtime/oid4vp-runtime.schema.json index db104eb886..08b329a96e 100644 --- a/products/evidence/generated/oid4vp-runtime/oid4vp-runtime.schema.json +++ b/products/evidence/generated/oid4vp-runtime/oid4vp-runtime.schema.json @@ -309,13 +309,6 @@ "additionalProperties": false, "description": "The file secret provider.", "properties": { - "mountPolicy": { - "$ref": "#/$defs/SecretMountPolicy", - "description": "`compose-native` also accepts a root-owned regular file with one hard\nlink and mode exactly 0444, the shape of a Docker Compose secret mount.\nEvery user in the container can read such a file. Startup and `check`\nreport this explicit production setting. Without it, only the file\nshapes `root` describes are accepted.", - "x-registry-explicit-production": [ - "platform.posture.compose-native-secret-mount" - ] - }, "root": { "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. A public document, such as a static JWKS\nor a CA bundle, may also be readable by group and others.", "pattern": "^/", @@ -620,12 +613,6 @@ "$ref": "#/$defs/ExternalId", "description": "The name of the claim that carries scopes." }, - "SecretMountPolicy": { - "enum": [ - "compose-native" - ], - "type": "string" - }, "SecretProvidersConfig": { "additionalProperties": false, "anyOf": [ From 0694f0e61370995403108bfd80e1c764264c5f2d Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 22:33:31 +0000 Subject: [PATCH 120/183] docs: add the Compose mount caveat to Session and Adapter, and state where it applies Session and the Adapter accept the setting, so their security pages carry the same caveat as the others. The deployment posture page no longer says a refused member is an explicit setting. Refs #2882. Signed-off-by: Jeremi Joslin --- docs/site/src/content/docs/operate/deployment-posture.mdx | 3 ++- docs/site/src/content/docs/security/adapter.mdx | 7 +++++++ docs/site/src/content/docs/security/session.mdx | 7 +++++++ 3 files changed, 16 insertions(+), 1 deletion(-) diff --git a/docs/site/src/content/docs/operate/deployment-posture.mdx b/docs/site/src/content/docs/operate/deployment-posture.mdx index 4ffca6f2c5..4527e1587a 100644 --- a/docs/site/src/content/docs/operate/deployment-posture.mdx +++ b/docs/site/src/content/docs/operate/deployment-posture.mdx @@ -89,7 +89,8 @@ loopback HTTP issuer URLs, `private-network-plaintext` observer hook destination Document Store and Registry Scheduling, `anonymousHttps: operator-approved` in Registry Adapter, or `secretProviders.file.mountPolicy: compose-native`, which accepts root-owned Docker Compose -secret mounts at mode `0444` (Registry Evidence and both wallet adapters refuse it). +secret mounts at mode `0444`. Registry Evidence and both wallet adapters do not accept that +member, so it is never an explicit production setting there. Explicit production settings never refuse and are never diagnostics or warnings: diff --git a/docs/site/src/content/docs/security/adapter.mdx b/docs/site/src/content/docs/security/adapter.mdx index 5ff94b44b8..a8265cf611 100644 --- a/docs/site/src/content/docs/security/adapter.mdx +++ b/docs/site/src/content/docs/security/adapter.mdx @@ -90,6 +90,13 @@ Configured hook ingress increments it for credential and rate-limit refusals. Th crates/registry-adapter-job/src/hook_ingress.rs, validate_hook_runtime, refused_hook_requests_are_counted_by_reason, each_refused_credential_is_counted_under_its_check_with_an_unchanged_answer. */} +Secret files follow the [hardening checklist](../hardening-checklist/#secret-files). The +explicit `secretProviders.file.mountPolicy: compose-native` setting lets every user in the +container read root-owned `0444` secret mounts. Write it only for a container that runs this +service alone under one runtime identity. + +{/* Evidence: crates/registry-platform-config/src/blocks.rs, COMPOSE_NATIVE_SECRET_MOUNT. */} + ## Next - [Configure caller and source access](../../configure/adapter/#authorisation-and-secrets) diff --git a/docs/site/src/content/docs/security/session.mdx b/docs/site/src/content/docs/security/session.mdx index 799cad9775..9130bc5f7f 100644 --- a/docs/site/src/content/docs/security/session.mdx +++ b/docs/site/src/content/docs/security/session.mdx @@ -105,6 +105,13 @@ A module's `signIns` list routes kinds of sessions, but grants no product permis crates/registry-session/src/public.rs sign_out; crates/registry-session/README.md. */} +Secret files follow the [hardening checklist](../hardening-checklist/#secret-files). The +explicit `secretProviders.file.mountPolicy: compose-native` setting lets every user in the +container read root-owned `0444` secret mounts. Write it only for a container that runs this +service alone under one runtime identity. + +{/* Evidence: crates/registry-platform-config/src/blocks.rs, COMPOSE_NATIVE_SECRET_MOUNT. */} + ## Accepted residuals ### SESSION-RES-01: a restart loses sessions From 37a5f417dbde072600cbe6ad1e5c4ba6e77763d1 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 22:33:52 +0000 Subject: [PATCH 121/183] fix(platform): refuse OpenPGP private key blocks in public documents The public-document read refused PEM and OpenSSH private keys but not an armored OpenPGP key block. The CHANGELOG now marks the refusal BREAKING and names the migration for a combined certificate and key file. Refs #2882. Signed-off-by: Jeremi Joslin --- crates/registry-platform-config/src/secrets.rs | 10 +++++----- .../registry-platform-config/src/secrets_tests.rs | 13 ++++++++++++- products/platform/CHANGELOG.md | 11 ++++++++--- 3 files changed, 25 insertions(+), 9 deletions(-) diff --git a/crates/registry-platform-config/src/secrets.rs b/crates/registry-platform-config/src/secrets.rs index 844e4a3831..8a8c09ec5a 100644 --- a/crates/registry-platform-config/src/secrets.rs +++ b/crates/registry-platform-config/src/secrets.rs @@ -745,12 +745,12 @@ fn public_document_error(error: SecretError) -> SecretError { } } -/// Whether `bytes` hold a PEM private key block of any kind: PKCS #8 -/// (encrypted or not), RSA, EC, DSA or OpenSSH. +/// Whether `bytes` hold an armored private key block of any kind: PKCS #8 +/// (encrypted or not), RSA, EC, DSA, OpenSSH or OpenPGP. fn holds_pem_private_key(bytes: &[u8]) -> bool { - bytes - .windows(b"PRIVATE KEY-----".len()) - .any(|window| window == b"PRIVATE KEY-----") + [&b"PRIVATE KEY-----"[..], &b"PRIVATE KEY BLOCK-----"[..]] + .iter() + .any(|label| bytes.windows(label.len()).any(|window| window == *label)) } /// Walk `name` from the root by openat steps, following only relative diff --git a/crates/registry-platform-config/src/secrets_tests.rs b/crates/registry-platform-config/src/secrets_tests.rs index cc943c4057..478956289b 100644 --- a/crates/registry-platform-config/src/secrets_tests.rs +++ b/crates/registry-platform-config/src/secrets_tests.rs @@ -390,6 +390,9 @@ mod filesystem { ("rsa.pem", "RSA PRIVATE KEY"), ("ec.pem", "EC PRIVATE KEY"), ("encrypted.pem", "ENCRYPTED PRIVATE KEY"), + ("openssh.pem", "OPENSSH PRIVATE KEY"), + ("dsa.pem", "DSA PRIVATE KEY"), + ("pgp.asc", "PGP PRIVATE KEY BLOCK"), ] { let path = root.path().join(name); fs::write( @@ -403,7 +406,15 @@ mod filesystem { fs::set_permissions(&path, fs::Permissions::from_mode(0o644)).expect("mode"); } let resolver = resolver(root.path()); - for name in ["pkcs8.pem", "rsa.pem", "ec.pem", "encrypted.pem"] { + for name in [ + "pkcs8.pem", + "rsa.pem", + "ec.pem", + "encrypted.pem", + "openssh.pem", + "dsa.pem", + "pgp.asc", + ] { assert_eq!( load_public(&resolver, name), Err(SecretError::PrivateKeyInPublicDocument), diff --git a/products/platform/CHANGELOG.md b/products/platform/CHANGELOG.md index f4c2e7d695..c3c862657e 100644 --- a/products/platform/CHANGELOG.md +++ b/products/platform/CHANGELOG.md @@ -18,9 +18,14 @@ `tlsTrustProfiles.*.bundleRef`) as a public document, and so do the `provision` tools for `database.caBundleRef`: group and other may read the file, with no setting. Owner, link, write and walk checks still apply, and - the document is still parsed before use. A public document that holds a PEM - private key block is refused, and a refused public document is described - with public-document wording. + the document is still parsed before use. A refused public document is + described with public-document wording. +- BREAKING: a public document (a static JWKS or a CA bundle, including + `caBundleRef` read by the `provision` tools) that holds an armored private + key block (PEM, OpenSSH or OpenPGP) is refused, even when the file is + owner-only. Migration: if `caBundleRef` named a combined certificate and + key file, split the key into its own secret file and point + `caBundleRef` at the certificates alone. - BREAKING for Rust callers of `registry-platform-config`: `SecretError` gains `UnsafePublicDocument` and `PrivateKeyInPublicDocument`, and `ProvisionInput` gains `explicit_settings`. Migration: add arms for the two From f4da556e37d4fe3ec24de9fb54ecd4256d33d612 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 22:34:10 +0000 Subject: [PATCH 122/183] fix(platform): fail provision when its explicit-setting notice cannot be written The stderr notice is the only report of an explicit setting for a provision run, so a lost notice now ends the run as an operational failure, as registry-session check does. Refs #2882. Signed-off-by: Jeremi Joslin --- crates/registry-platform-provision/src/cli.rs | 42 +++++++++++++++++-- 1 file changed, 39 insertions(+), 3 deletions(-) diff --git a/crates/registry-platform-provision/src/cli.rs b/crates/registry-platform-provision/src/cli.rs index c3480e7cff..15e3e3e959 100644 --- a/crates/registry-platform-provision/src/cli.rs +++ b/crates/registry-platform-provision/src/cli.rs @@ -800,10 +800,12 @@ fn run_with( return output.refusal(&report); } }; + // The notice is the only report of an explicit setting for this run, so + // a notice that cannot reach stderr is an operational failure. for notice in &input.explicit_settings { - // A notice that cannot reach stderr leaves nothing else to tell; the - // run continues and the report still carries its outcome. - let _ = writeln!(output.stderr, "{notice}"); + if writeln!(output.stderr, "{notice}").is_err() { + return output.write_failed(false); + } } report.product = Some(input.product.product.to_owned()); let dotted_section = section.replace('/', "."); @@ -1420,6 +1422,40 @@ mod tests { } } + #[test] + fn an_explicit_setting_notice_that_cannot_be_written_is_an_operational_failure() { + struct Closed; + impl Write for Closed { + fn write(&mut self, _: &[u8]) -> std::io::Result { + Err(std::io::ErrorKind::BrokenPipe.into()) + } + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } + } + let mut input = split_input(); + input.explicit_settings = vec!["Explicit production setting".to_owned()]; + let args = parse(&["--print-sql", "--runtime-config", "runtime.yaml"]).expect("arguments"); + let mut stdout = Vec::new(); + let exit = run_with( + "casectl", + "database", + "1.2.3-test", + &args, + OutputFormat::Human, + registry_cli_report::declared_from(None, None).unwrap(), + |_| Ok(input), + &must_not_run, + &mut stdout, + &mut Closed, + ); + assert_eq!(exit, 3); + assert!( + stdout.is_empty(), + "the script must not follow a lost notice" + ); + } + #[test] fn print_mode_writes_only_the_script_to_stdout() { let run = execute_run(&["--print-sql"], None, Ok(split_input()), &must_not_run); From a0a38e4f5b3fa4e447b985a9bdf4367c5c3f998c Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 22:35:13 +0000 Subject: [PATCH 123/183] refactor(platform): share the explicit-setting report line with registry-mcp and session registry-mcp and registry-session built the explicitProductionSettings line by hand because their dependency gates keep registry-cli-report out. The line now lives in registry-platform-config, which both may use, and registry-cli-report re-exports it under its existing path. Refs #2882. Signed-off-by: Jeremi Joslin --- crates/registry-cli-report/src/lib.rs | 58 +------------------ crates/registry-mcp/src/main.rs | 17 +----- crates/registry-platform-config/src/lib.rs | 4 +- .../registry-platform-config/src/posture.rs | 58 +++++++++++++++++++ crates/registry-session/src/offline.rs | 30 +++------- 5 files changed, 71 insertions(+), 96 deletions(-) diff --git a/crates/registry-cli-report/src/lib.rs b/crates/registry-cli-report/src/lib.rs index 991655380e..eb1daa70e0 100644 --- a/crates/registry-cli-report/src/lib.rs +++ b/crates/registry-cli-report/src/lib.rs @@ -3,7 +3,7 @@ use std::io::{self, Write}; -use registry_platform_config::FoundExplicitSetting; +pub use registry_platform_config::ExplicitSettingLine; #[doc(hidden)] pub use registry_platform_posture::declared_from; /// The declaration used by CLI report producers. @@ -79,62 +79,6 @@ pub struct Report<'a> { explicit_settings: Option>, } -/// One explicit production setting an operator stated, as a `check` report -/// lists it: a setting valid in every posture that relaxes something and is -/// worth a reviewer's attention. It is a list of facts, not a diagnostic, so -/// `--deny-warnings` is unaffected. The summary is value-free. -/// -/// `file` names the document `pointer` refers to, such as the runtime file or -/// the package, and is left out when absent. `pointer`, `line` and `column` -/// are left out when unknown. -#[derive(Clone, Debug, Eq, PartialEq)] -pub struct ExplicitSettingLine { - pub code: String, - pub file: Option, - pub pointer: Option, - pub line: Option, - pub column: Option, - pub summary: String, -} - -impl ExplicitSettingLine { - /// The line a `check` report lists for `found`. `file` names the document - /// the pointer refers to: the runtime file, or the package for a setting - /// found there. - #[must_use] - pub fn from_found(found: &FoundExplicitSetting, file: Option<&str>) -> Self { - Self { - code: found.setting.code.to_owned(), - file: file.map(ToOwned::to_owned), - pointer: found.pointer.clone(), - line: found.position.map(|position| position.line), - column: found.position.map(|position| position.column), - summary: found.setting.summary.to_owned(), - } - } -} - -impl Serialize for ExplicitSettingLine { - fn serialize(&self, serializer: S) -> Result { - let mut map = serializer.serialize_map(None)?; - map.serialize_entry("code", &self.code)?; - if let Some(file) = &self.file { - map.serialize_entry("file", file)?; - } - if let Some(pointer) = &self.pointer { - map.serialize_entry("pointer", pointer)?; - } - if let Some(line) = self.line { - map.serialize_entry("line", &line)?; - } - if let Some(column) = self.column { - map.serialize_entry("column", &column)?; - } - map.serialize_entry("summary", &self.summary)?; - map.end() - } -} - impl<'a> Report<'a> { /// Check the product's envelope and attach the binary's build identity. /// Command-specific status words become outcomes; result classes stay fixed. diff --git a/crates/registry-mcp/src/main.rs b/crates/registry-mcp/src/main.rs index 5a6de47303..afa41e6b61 100644 --- a/crates/registry-mcp/src/main.rs +++ b/crates/registry-mcp/src/main.rs @@ -141,22 +141,11 @@ async fn main() -> ExitCode { }; // Each explicit production setting the file states, as every check // reports it: a fact for review, not a diagnostic. - let explicit: Vec = settings + let file = given.display().to_string(); + let explicit: Vec<_> = settings .iter() .map(|found| { - let mut line = serde_json::json!({ - "code": found.setting.code, - "file": given.display().to_string(), - "summary": found.setting.summary, - }); - if let Some(pointer) = &found.pointer { - line["pointer"] = pointer.as_str().into(); - } - if let Some(position) = found.position { - line["line"] = position.line.into(); - line["column"] = position.column.into(); - } - line + registry_platform_config::ExplicitSettingLine::from_found(found, Some(&file)) }) .collect(); let failed = unavailable diff --git a/crates/registry-platform-config/src/lib.rs b/crates/registry-platform-config/src/lib.rs index 1d4a4afa14..dd91290fd8 100644 --- a/crates/registry-platform-config/src/lib.rs +++ b/crates/registry-platform-config/src/lib.rs @@ -86,8 +86,8 @@ pub use posture::{ declared_from_with_production_alias, declared_with_production_alias, has_denied_warnings, CollectedSettings, DeclaredPosture, DevelopmentClass, DevelopmentOnlyRefused, DevelopmentSetting, DevelopmentWitness, ExplicitClass, ExplicitProductionSetting, - FoundExplicitSetting, FoundSetting, Gated, Posture, PostureError, PostureReport, PostureSource, - SettingOrigin, Stated, DEVELOPMENT, POSTURE_ENV, + ExplicitSettingLine, FoundExplicitSetting, FoundSetting, Gated, Posture, PostureError, + PostureReport, PostureSource, SettingOrigin, Stated, DEVELOPMENT, POSTURE_ENV, }; pub use secrets::{ validate_secret_root, ProtectedSecret, SecretError, SecretFileCheck, SecretProvider, diff --git a/crates/registry-platform-config/src/posture.rs b/crates/registry-platform-config/src/posture.rs index ba82c72fa4..d6af2beaf2 100644 --- a/crates/registry-platform-config/src/posture.rs +++ b/crates/registry-platform-config/src/posture.rs @@ -442,6 +442,64 @@ pub struct ExplicitProductionSetting { pub summary: &'static str, } +/// One explicit production setting an operator stated, as a `check` report +/// lists it: a setting valid in every posture that relaxes something and is +/// worth a reviewer's attention. It is a list of facts, not a diagnostic, so +/// `--deny-warnings` is unaffected. The summary is value-free. +/// +/// `file` names the document `pointer` refers to, such as the runtime file or +/// the package, and is left out when absent. `pointer`, `line` and `column` +/// are left out when unknown. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct ExplicitSettingLine { + pub code: String, + pub file: Option, + pub pointer: Option, + pub line: Option, + pub column: Option, + pub summary: String, +} + +impl ExplicitSettingLine { + /// The line a `check` report lists for `found`. `file` names the document + /// the pointer refers to: the runtime file, or the package for a setting + /// found there. + #[must_use] + pub fn from_found(found: &FoundExplicitSetting, file: Option<&str>) -> Self { + Self { + code: found.setting.code.to_owned(), + file: file.map(ToOwned::to_owned), + pointer: found.pointer.clone(), + line: found.position.map(|position| position.line), + column: found.position.map(|position| position.column), + summary: found.setting.summary.to_owned(), + } + } +} + +impl Serialize for ExplicitSettingLine { + fn serialize(&self, serializer: S) -> Result { + use serde::ser::SerializeMap as _; + + let mut map = serializer.serialize_map(None)?; + map.serialize_entry("code", &self.code)?; + if let Some(file) = &self.file { + map.serialize_entry("file", file)?; + } + if let Some(pointer) = &self.pointer { + map.serialize_entry("pointer", pointer)?; + } + if let Some(line) = self.line { + map.serialize_entry("line", &line)?; + } + if let Some(column) = self.column { + map.serialize_entry("column", &column)?; + } + map.serialize_entry("summary", &self.summary)?; + map.end() + } +} + /// An [`ExplicitProductionSetting`] found in a process's configuration. #[derive(Clone, Debug)] pub struct FoundExplicitSetting { diff --git a/crates/registry-session/src/offline.rs b/crates/registry-session/src/offline.rs index be856a0592..f17411e011 100644 --- a/crates/registry-session/src/offline.rs +++ b/crates/registry-session/src/offline.rs @@ -66,7 +66,7 @@ struct CtlReport { diagnostics: serde_json::Value, /// Each explicit production setting the file states: a fact for review, /// not a diagnostic. - explicit_production_settings: Vec, + explicit_production_settings: Vec, } /// Run `registry-session check` and report every finding (CFG-DIAG-4): exit 0 when @@ -112,7 +112,12 @@ pub fn run(request: &CheckRequest<'_>, stdout: &mut dyn Write, stderr: &mut dyn diagnostics: report.to_json_value(), explicit_production_settings: settings .iter() - .map(|found| setting_line(found, request.runtime)) + .map(|found| { + registry_platform_config::ExplicitSettingLine::from_found( + found, + Some(&request.runtime.display().to_string()), + ) + }) .collect(), }; let written = serde_json::to_writer_pretty(&mut *stdout, &document) @@ -146,27 +151,6 @@ pub fn run(request: &CheckRequest<'_>, stdout: &mut dyn Write, stderr: &mut dyn exit } -/// One explicit production setting as the JSON report lists it, with the -/// members every check report uses for it. -fn setting_line( - found: ®istry_platform_config::FoundExplicitSetting, - runtime: &Path, -) -> serde_json::Value { - let mut line = serde_json::json!({ - "code": found.setting.code, - "file": runtime.display().to_string(), - "summary": found.setting.summary, - }); - if let Some(pointer) = &found.pointer { - line["pointer"] = pointer.as_str().into(); - } - if let Some(position) = found.position { - line["line"] = position.line.into(); - line["column"] = position.column.into(); - } - line -} - /// Check the runtime file at `path` as given: the loader needs an absolute, /// lexically normal path, and every diagnostic names the file as given. /// Returns the findings, whether the file could not be read at all, and the From 9b4992634a5712915a221c8ef25089c518d0dbd5 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 22:35:43 +0000 Subject: [PATCH 124/183] test: pin the mountPolicy refusal pointer and a second provision notice The saved-connection test now asserts the unknown-key diagnostic at the member, not only the exit code, and Document Store provision is checked to print the Compose mount notice on stderr. Refs #2882. Signed-off-by: Jeremi Joslin --- .../tests/connection_store.rs | 10 +++++++ .../tests/provision_cli.rs | 26 +++++++++++++++++++ 2 files changed, 36 insertions(+) diff --git a/crates/registry-cli-api/tests/connection_store.rs b/crates/registry-cli-api/tests/connection_store.rs index 225d4e89cb..9f966552a3 100644 --- a/crates/registry-cli-api/tests/connection_store.rs +++ b/crates/registry-cli-api/tests/connection_store.rs @@ -579,4 +579,14 @@ fn a_saved_connection_file_refuses_the_compose_mount_policy() { ); let error = check(&stated).expect_err("a saved connection file has no mountPolicy"); assert_eq!(error.exit_code(), 1); + let report = registry_cli_api::inspect_connections_file(&file).unwrap(); + assert!( + report + .diagnostics() + .iter() + .any(|diagnostic| diagnostic.code == "config.unknown-key" + && diagnostic.path == "/connections/0/secretProviders/file/mountPolicy"), + "{}", + report.render_human() + ); } diff --git a/crates/registry-documentsctl/tests/provision_cli.rs b/crates/registry-documentsctl/tests/provision_cli.rs index 0d93017c62..8fd0345eef 100644 --- a/crates/registry-documentsctl/tests/provision_cli.rs +++ b/crates/registry-documentsctl/tests/provision_cli.rs @@ -200,6 +200,32 @@ fn print_sql_writes_the_script_and_no_password() { } } +#[test] +fn print_sql_notices_the_compose_mount_policy_on_stderr() { + let directory = scratch(); + let runtime = write_runtime(directory.path()); + let text = std::fs::read_to_string(&runtime).unwrap(); + let stated = text.replacen( + "secretProviders:\n file:\n", + "secretProviders:\n file:\n mountPolicy: compose-native\n", + 1, + ); + assert_ne!(stated, text, "the member is written"); + std::fs::write(&runtime, stated).unwrap(); + + 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.contains( + "Explicit production setting platform.posture.compose-native-secret-mount at /secretProviders/file/mountPolicy." + ), + "{stderr}" + ); + assert!(!stdout.contains("compose-native"), "{stdout}"); +} + #[test] fn print_sql_as_json_reports_nothing_executed() { let directory = scratch(); From 05ba0ebf4af1bf0b624ebf8248eaa2628d738e6e Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 23:03:16 +0000 Subject: [PATCH 125/183] chore(identifiers): regenerate the catalogue for the wallet adapter schemas Signed-off-by: Jeremi Joslin --- products/identifiers/generated/catalog.v1.json | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/products/identifiers/generated/catalog.v1.json b/products/identifiers/generated/catalog.v1.json index 521b6ffd92..4e522bd884 100644 --- a/products/identifiers/generated/catalog.v1.json +++ b/products/identifiers/generated/catalog.v1.json @@ -6325,11 +6325,11 @@ "description": "Evidence OID4VCI delivery runtime configuration JSON Schema.", "source": { "path": "crates/registry-evidence-oid4vci/src/schema.rs", - "sha256": "4765ede33c3ad60e6defd1fd4f7fb59180dd0f9ab04280e8d83a0e5f25081a5d" + "sha256": "1e8069df07d75e21d6d15dfcbe92e45d2fd2fed29d8c6d162953bdb679c3f0cd" }, "artifact": { "path": "products/evidence/generated/oid4vci-runtime/oid4vci-runtime.schema.json", - "sha256": "39cf28ae80e6eee04ace9474c6652d52659167d847073d54ff01e72a322150ab", + "sha256": "27a3505caef33020b803fd9dd67bec9d0569a8eaba86dafef6c0232166e2c098", "mediaType": "application/schema+json" } }, @@ -6343,11 +6343,11 @@ "description": "Evidence OpenID4VP verifier runtime configuration JSON Schema.", "source": { "path": "crates/registry-evidence-oid4vp/src/schema.rs", - "sha256": "dce7ef9451a6324883cc24cab52f6107603fd4089976abe56d0952d14f0d2bf2" + "sha256": "aa27124852e5186e3604be21886c994fe1ceb3b512495fcb56aab9925fccc114" }, "artifact": { "path": "products/evidence/generated/oid4vp-runtime/oid4vp-runtime.schema.json", - "sha256": "b228e4e511c6c6afc2b5ac12edd322a9ee1f977f59f7907586bd81fde567a01b", + "sha256": "eefcd80bf783e37968ed22da6eb80891d82f901e5fd0549e10ce2aabcea3c65f", "mediaType": "application/schema+json" } }, @@ -6667,7 +6667,7 @@ "description": "Report of the shared `provision` command that creates a product's PostgreSQL roles, database, schemas and extensions.", "source": { "path": "crates/registry-platform-provision/src/cli.rs", - "sha256": "d5c59e2cdb955f33a5806c825ae9be6204a11797adf0afb05865e807827293c2" + "sha256": "69249d1cd4b43379aa5f4a7c15bddfe443650f49bdb7477c9f068a5468f4f22f" }, "artifact": { "path": "crates/registry-platform-provision/schema/provision-report.schema.json", From a5cd15a5a479cf560684c95662bcad13bcd940f0 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 23:18:05 +0000 Subject: [PATCH 126/183] fix(platform): publish the strict secret providers as a shared block The wallet adapters stripped mountPolicy from the shared file provider in their schemas, which the configuration conformance gate refuses as a re-declared shared block. They now embed the strict block unchanged; their readers still refuse the member with a positioned finding. Refs #2882. Signed-off-by: Jeremi Joslin --- .../schema/connections.schema.json | 6 +- .../registry-evidence-oid4vci/src/config.rs | 9 +- .../registry-evidence-oid4vci/src/schema.rs | 2 - crates/registry-evidence-oid4vp/src/config.rs | 9 +- crates/registry-evidence-oid4vp/src/schema.rs | 2 - .../authoring/store-provision.schema.json | 6 +- crates/registry-platform-config/src/blocks.rs | 20 ++-- crates/registry-platform-config/src/schema.rs | 18 +-- .../oid4vci-runtime.schema.json | 108 +++++++++--------- .../oid4vp-runtime/oid4vp-runtime.schema.json | 108 +++++++++--------- products/platform/CHANGELOG.md | 4 + .../runtime-config-blocks.schema.json | 52 +++++++++ .../schemas/task-connection.schema.json | 6 +- .../scripts/check-config-conformance.py | 4 +- 14 files changed, 203 insertions(+), 151 deletions(-) diff --git a/crates/registry-cli-api/schema/connections.schema.json b/crates/registry-cli-api/schema/connections.schema.json index 436564ffb4..34aabe761c 100644 --- a/crates/registry-cli-api/schema/connections.schema.json +++ b/crates/registry-cli-api/schema/connections.schema.json @@ -183,10 +183,10 @@ }, "StrictFileSecretProviderConfig": { "additionalProperties": false, - "description": "The file secret provider of an operator-local file.", + "description": "The file secret provider without the Compose mount policy.", "properties": { "root": { - "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 user running the tool with mode 0400 or 0600, or owned by root with\nno access beyond group read (0440 or 0640) when that user is not root.\nA command that declared development loads a file with looser read or\nmode bits and logs a warning.", + "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 user running the process with mode 0400 or 0600, or owned by root\nwith no access beyond group read (0440 or 0640) when that user is not\nroot. A process that declared development loads a file with looser read\nor mode bits and logs a warning.", "pattern": "^/", "type": "string" } @@ -220,7 +220,7 @@ ] } ], - "description": "The secret providers of an operator-local file read outside any runtime,\nsuch as a saved CLI connection or a task connection. It enables the same\nproviders as a runtime's `secretProviders` without the Compose mount\npolicy: nothing reports an explicit production setting for these files,\nso the strict file rule always applies.", + "description": "The secret providers without the Compose mount policy, so the strict file\nrule always applies. An operator-local file read outside any runtime, such\nas a saved CLI connection or a task connection, uses it because nothing\nreports an explicit production setting for that file. A runtime whose keys\nkeep the strict rule publishes it as the shape of its `secretProviders`.", "properties": { "environment": { "$ref": "#/$defs/EnvironmentSecretProviderConfig", diff --git a/crates/registry-evidence-oid4vci/src/config.rs b/crates/registry-evidence-oid4vci/src/config.rs index 0fe4f48d01..0f04400cba 100644 --- a/crates/registry-evidence-oid4vci/src/config.rs +++ b/crates/registry-evidence-oid4vci/src/config.rs @@ -709,7 +709,14 @@ pub struct DeliveryDocument { /// endpoint exists. #[serde(default)] pub metrics_listener: Option, - /// The secret providers `tokenClient.privateKeyRef` may name. + /// The secret providers `tokenClient.privateKeyRef` may name. The file provider takes no + /// `mountPolicy`: these keys keep the strict file rule. + // The schema publishes the shared strict block; the reader keeps the + // runtime block so it can refuse `mountPolicy` with a positioned finding. + #[cfg_attr( + feature = "schema", + schemars(with = "registry_platform_config::StrictSecretProvidersConfig") + )] pub secret_providers: SecretProvidersConfig, /// The required durable audit journal for offer attribution and delivery /// outcomes. `stdout` is available for a collector-managed deployment; diff --git a/crates/registry-evidence-oid4vci/src/schema.rs b/crates/registry-evidence-oid4vci/src/schema.rs index ed2ed486f9..b2c5446c35 100644 --- a/crates/registry-evidence-oid4vci/src/schema.rs +++ b/crates/registry-evidence-oid4vci/src/schema.rs @@ -26,8 +26,6 @@ use crate::config::{ pub fn runtime_documents() -> Result, serde_json::Error> { let mut derived = serde_json::to_value(schemars::schema_for!(DeliveryDocument))?; refuse_null_outside_shared_blocks(&mut derived)?; - // The reader refuses the Compose mount policy under the Evidence key rule. - registry_platform_config::schema::without_compose_mount_policy(&mut derived); set_const(&mut derived, "apiVersion", OID4VCI_RUNTIME_API_VERSION); set_const(&mut derived, "kind", OID4VCI_RUNTIME_KIND); let mut object = match derived { diff --git a/crates/registry-evidence-oid4vp/src/config.rs b/crates/registry-evidence-oid4vp/src/config.rs index c888be2f4e..fcd7006433 100644 --- a/crates/registry-evidence-oid4vp/src/config.rs +++ b/crates/registry-evidence-oid4vp/src/config.rs @@ -684,7 +684,14 @@ pub struct VerifierDocument { /// endpoint exists. #[serde(default)] pub metrics_listener: Option, - /// The secret providers the `*Ref` members may name. + /// The secret providers the `*Ref` members may name. The file provider takes no + /// `mountPolicy`: these keys keep the strict file rule. + // The schema publishes the shared strict block; the reader keeps the + // runtime block so it can refuse `mountPolicy` with a positioned finding. + #[cfg_attr( + feature = "schema", + schemars(with = "registry_platform_config::StrictSecretProvidersConfig") + )] pub secret_providers: SecretProvidersConfig, /// The required durable audit journal. pub audit: AuditDocument, diff --git a/crates/registry-evidence-oid4vp/src/schema.rs b/crates/registry-evidence-oid4vp/src/schema.rs index 39ad8c661e..c53d5cbf00 100644 --- a/crates/registry-evidence-oid4vp/src/schema.rs +++ b/crates/registry-evidence-oid4vp/src/schema.rs @@ -26,8 +26,6 @@ use crate::config::{ pub fn runtime_documents() -> Result, serde_json::Error> { let mut derived = serde_json::to_value(schemars::schema_for!(VerifierDocument))?; refuse_null_outside_shared_blocks(&mut derived)?; - // The reader refuses the Compose mount policy under the Evidence key rule. - registry_platform_config::schema::without_compose_mount_policy(&mut derived); set_const(&mut derived, "apiVersion", OID4VP_RUNTIME_API_VERSION); set_const(&mut derived, "kind", OID4VP_RUNTIME_KIND); let mut object = match derived { diff --git a/crates/registry-evidencectl/schemas/authoring/store-provision.schema.json b/crates/registry-evidencectl/schemas/authoring/store-provision.schema.json index 5fd67ff3be..dee8594c27 100644 --- a/crates/registry-evidencectl/schemas/authoring/store-provision.schema.json +++ b/crates/registry-evidencectl/schemas/authoring/store-provision.schema.json @@ -74,10 +74,10 @@ }, "StrictFileSecretProviderConfig": { "additionalProperties": false, - "description": "The file secret provider of an operator-local file.", + "description": "The file secret provider without the Compose mount policy.", "properties": { "root": { - "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 user running the tool with mode 0400 or 0600, or owned by root with\nno access beyond group read (0440 or 0640) when that user is not root.\nA command that declared development loads a file with looser read or\nmode bits and logs a warning.", + "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 user running the process with mode 0400 or 0600, or owned by root\nwith no access beyond group read (0440 or 0640) when that user is not\nroot. A process that declared development loads a file with looser read\nor mode bits and logs a warning.", "pattern": "^/", "type": "string" } @@ -111,7 +111,7 @@ ] } ], - "description": "The secret providers of an operator-local file read outside any runtime,\nsuch as a saved CLI connection or a task connection. It enables the same\nproviders as a runtime's `secretProviders` without the Compose mount\npolicy: nothing reports an explicit production setting for these files,\nso the strict file rule always applies.", + "description": "The secret providers without the Compose mount policy, so the strict file\nrule always applies. An operator-local file read outside any runtime, such\nas a saved CLI connection or a task connection, uses it because nothing\nreports an explicit production setting for that file. A runtime whose keys\nkeep the strict rule publishes it as the shape of its `secretProviders`.", "properties": { "environment": { "$ref": "#/$defs/EnvironmentSecretProviderConfig", diff --git a/crates/registry-platform-config/src/blocks.rs b/crates/registry-platform-config/src/blocks.rs index e4fa6641f5..7faf8e148d 100644 --- a/crates/registry-platform-config/src/blocks.rs +++ b/crates/registry-platform-config/src/blocks.rs @@ -285,11 +285,11 @@ impl SecretProvidersConfig { } } -/// The secret providers of an operator-local file read outside any runtime, -/// such as a saved CLI connection or a task connection. It enables the same -/// providers as a runtime's `secretProviders` without the Compose mount -/// policy: nothing reports an explicit production setting for these files, -/// so the strict file rule always applies. +/// The secret providers without the Compose mount policy, so the strict file +/// rule always applies. An operator-local file read outside any runtime, such +/// as a saved CLI connection or a task connection, uses it because nothing +/// reports an explicit production setting for that file. A runtime whose keys +/// keep the strict rule publishes it as the shape of its `secretProviders`. #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] #[cfg_attr( feature = "schema", @@ -312,7 +312,7 @@ pub struct StrictSecretProvidersConfig { pub environment: Option, } -/// The file secret provider of an operator-local file. +/// The file secret provider without the Compose mount policy. #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] #[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] @@ -320,10 +320,10 @@ pub struct StrictFileSecretProviderConfig { /// 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 user running the tool with mode 0400 or 0600, or owned by root with - /// no access beyond group read (0440 or 0640) when that user is not root. - /// A command that declared development loads a file with looser read or - /// mode bits and logs a warning. + /// the user running the process with mode 0400 or 0600, or owned by root + /// with no access beyond group read (0440 or 0640) when that user 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, } diff --git a/crates/registry-platform-config/src/schema.rs b/crates/registry-platform-config/src/schema.rs index 98f0e4103f..2bd0eb004a 100644 --- a/crates/registry-platform-config/src/schema.rs +++ b/crates/registry-platform-config/src/schema.rs @@ -6,7 +6,7 @@ use crate::blocks::{ AttachmentVerifierConfig, AuditKeyConfig, DatabaseConfig, JwksSource, ListenerConfig, MetricsListenerConfig, ObjectStorageConfig, OidcClientsConfig, OidcIssuerConfig, OidcPackageClientsConfig, PackageConfig, PrivateListenerConfig, SecretProvidersConfig, - TaskGrantStatusConfig, UrlHookDestinationConfig, + StrictSecretProvidersConfig, TaskGrantStatusConfig, UrlHookDestinationConfig, }; use crate::caller_issuers::{ AccessProfileClients, AllowedClients, CallerIssuerCore, CallerIssuers, ClientList, @@ -22,6 +22,7 @@ pub const SHARED_BLOCKS_SCHEMA_FILE: &str = "runtime-config-blocks.schema.json"; #[allow(dead_code)] struct SharedBlocks { secret_providers: SecretProvidersConfig, + strict_secret_providers: StrictSecretProvidersConfig, database: DatabaseConfig, jwks_source: JwksSource, package: PackageConfig, @@ -62,21 +63,6 @@ pub fn shared_blocks_document() -> Result { Ok(rendered) } -/// Remove the Compose mount policy from a runtime schema whose product keeps -/// the strict secret file rule and refuses `secretProviders.file.mountPolicy`, -/// so the published contract does not offer a member the reader refuses. -pub fn without_compose_mount_policy(schema: &mut Value) { - if let Some(properties) = schema - .pointer_mut("/$defs/FileSecretProviderConfig/properties") - .and_then(Value::as_object_mut) - { - properties.remove("mountPolicy"); - } - if let Some(definitions) = schema.pointer_mut("/$defs").and_then(Value::as_object_mut) { - definitions.remove("SecretMountPolicy"); - } -} - /// Root `allOf` members stating that a static JWKS document at /// `authentication.oidc.issuers..jwksSource.documentRef` names a secret /// provider by its prefix, so a configuration where any issuer entry carries diff --git a/products/evidence/generated/oid4vci-runtime/oid4vci-runtime.schema.json b/products/evidence/generated/oid4vci-runtime/oid4vci-runtime.schema.json index f34c65d944..f83e6925b9 100644 --- a/products/evidence/generated/oid4vci-runtime/oid4vci-runtime.schema.json +++ b/products/evidence/generated/oid4vci-runtime/oid4vci-runtime.schema.json @@ -178,21 +178,6 @@ "pattern": "^[^\\u0000-\\u001F\\u007F-\\u009F]+$", "type": "string" }, - "FileSecretProviderConfig": { - "additionalProperties": false, - "description": "The file secret provider.", - "properties": { - "root": { - "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. A public document, such as a static JWKS\nor a CA bundle, may also be readable by group and others.", - "pattern": "^/", - "type": "string" - } - }, - "required": [ - "root" - ], - "type": "object" - }, "IdentifierRestriction": { "anyOf": [ { @@ -549,43 +534,6 @@ "$ref": "#/$defs/ExternalId", "description": "The name of the claim that carries scopes." }, - "SecretProvidersConfig": { - "additionalProperties": false, - "anyOf": [ - { - "properties": { - "file": { - "$ref": "#/$defs/FileSecretProviderConfig" - } - }, - "required": [ - "file" - ] - }, - { - "properties": { - "environment": { - "$ref": "#/$defs/EnvironmentSecretProviderConfig" - } - }, - "required": [ - "environment" - ] - } - ], - "description": "The secret providers a runtime enables. A reference is resolved only by a\nprovider declared here: `secret:file/name` under `file.root`, and\n`secret:env/NAME` only when `environment: {}` is present.", - "properties": { - "environment": { - "$ref": "#/$defs/EnvironmentSecretProviderConfig", - "description": "Enables `secret:env/NAME` references, read from the process\nenvironment. Declared as an empty mapping: `environment: {}`." - }, - "file": { - "$ref": "#/$defs/FileSecretProviderConfig", - "description": "Enables `secret:file/name` references, read from files under `root`." - } - }, - "type": "object" - }, "SecretReference": { "description": "An exact secret reference: secret:file/name, resolved under secretProviders.file.root, or secret:env/NAME, resolved only when secretProviders.environment is declared.", "pattern": "^(?:secret:env/[A-Z][A-Z0-9_]{0,127}|secret:file/[a-z][a-z0-9._-]{0,127})$", @@ -638,6 +586,58 @@ }, "type": "object" }, + "StrictFileSecretProviderConfig": { + "additionalProperties": false, + "description": "The file secret provider without the Compose mount policy.", + "properties": { + "root": { + "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 user running the process with mode 0400 or 0600, or owned by root\nwith no access beyond group read (0440 or 0640) when that user is not\nroot. A process that declared development loads a file with looser read\nor mode bits and logs a warning.", + "pattern": "^/", + "type": "string" + } + }, + "required": [ + "root" + ], + "type": "object" + }, + "StrictSecretProvidersConfig": { + "additionalProperties": false, + "anyOf": [ + { + "properties": { + "file": { + "$ref": "#/$defs/StrictFileSecretProviderConfig" + } + }, + "required": [ + "file" + ] + }, + { + "properties": { + "environment": { + "$ref": "#/$defs/EnvironmentSecretProviderConfig" + } + }, + "required": [ + "environment" + ] + } + ], + "description": "The secret providers without the Compose mount policy, so the strict file\nrule always applies. An operator-local file read outside any runtime, such\nas a saved CLI connection or a task connection, uses it because nothing\nreports an explicit production setting for that file. A runtime whose keys\nkeep the strict rule publishes it as the shape of its `secretProviders`.", + "properties": { + "environment": { + "$ref": "#/$defs/EnvironmentSecretProviderConfig", + "description": "Enables `secret:env/NAME` references, read from the process\nenvironment. Declared as an empty mapping: `environment: {}`." + }, + "file": { + "$ref": "#/$defs/StrictFileSecretProviderConfig", + "description": "Enables `secret:file/name` references, read from files under `root`." + } + }, + "type": "object" + }, "TokenClientDocument": { "additionalProperties": false, "description": "The identity this service authenticates to its token issuer with.", @@ -752,8 +752,8 @@ "description": "Request budgets. Absent means the defaults of each member." }, "secretProviders": { - "$ref": "#/$defs/SecretProvidersConfig", - "description": "The secret providers `tokenClient.privateKeyRef` may name." + "$ref": "#/$defs/StrictSecretProvidersConfig", + "description": "The secret providers `tokenClient.privateKeyRef` may name. The file provider takes no\n`mountPolicy`: these keys keep the strict file rule." }, "store": { "$ref": "#/$defs/StoreDocument", diff --git a/products/evidence/generated/oid4vp-runtime/oid4vp-runtime.schema.json b/products/evidence/generated/oid4vp-runtime/oid4vp-runtime.schema.json index 08b329a96e..4d42f9ee68 100644 --- a/products/evidence/generated/oid4vp-runtime/oid4vp-runtime.schema.json +++ b/products/evidence/generated/oid4vp-runtime/oid4vp-runtime.schema.json @@ -305,21 +305,6 @@ "pattern": "^[^\\u0000-\\u001F\\u007F-\\u009F]+$", "type": "string" }, - "FileSecretProviderConfig": { - "additionalProperties": false, - "description": "The file secret provider.", - "properties": { - "root": { - "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. A public document, such as a static JWKS\nor a CA bundle, may also be readable by group and others.", - "pattern": "^/", - "type": "string" - } - }, - "required": [ - "root" - ], - "type": "object" - }, "IssuerActorKind": { "$ref": "#/$defs/DeclaredActorKind", "description": "The kind every token from one issuer is treated as." @@ -613,43 +598,6 @@ "$ref": "#/$defs/ExternalId", "description": "The name of the claim that carries scopes." }, - "SecretProvidersConfig": { - "additionalProperties": false, - "anyOf": [ - { - "properties": { - "file": { - "$ref": "#/$defs/FileSecretProviderConfig" - } - }, - "required": [ - "file" - ] - }, - { - "properties": { - "environment": { - "$ref": "#/$defs/EnvironmentSecretProviderConfig" - } - }, - "required": [ - "environment" - ] - } - ], - "description": "The secret providers a runtime enables. A reference is resolved only by a\nprovider declared here: `secret:file/name` under `file.root`, and\n`secret:env/NAME` only when `environment: {}` is present.", - "properties": { - "environment": { - "$ref": "#/$defs/EnvironmentSecretProviderConfig", - "description": "Enables `secret:env/NAME` references, read from the process\nenvironment. Declared as an empty mapping: `environment: {}`." - }, - "file": { - "$ref": "#/$defs/FileSecretProviderConfig", - "description": "Enables `secret:file/name` references, read from files under `root`." - } - }, - "type": "object" - }, "SecretReference": { "description": "An exact secret reference: secret:file/name, resolved under secretProviders.file.root, or secret:env/NAME, resolved only when secretProviders.environment is declared.", "pattern": "^(?:secret:env/[A-Z][A-Z0-9_]{0,127}|secret:file/[a-z][a-z0-9._-]{0,127})$", @@ -704,6 +652,58 @@ "type": "array", "uniqueItems": true }, + "StrictFileSecretProviderConfig": { + "additionalProperties": false, + "description": "The file secret provider without the Compose mount policy.", + "properties": { + "root": { + "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 user running the process with mode 0400 or 0600, or owned by root\nwith no access beyond group read (0440 or 0640) when that user is not\nroot. A process that declared development loads a file with looser read\nor mode bits and logs a warning.", + "pattern": "^/", + "type": "string" + } + }, + "required": [ + "root" + ], + "type": "object" + }, + "StrictSecretProvidersConfig": { + "additionalProperties": false, + "anyOf": [ + { + "properties": { + "file": { + "$ref": "#/$defs/StrictFileSecretProviderConfig" + } + }, + "required": [ + "file" + ] + }, + { + "properties": { + "environment": { + "$ref": "#/$defs/EnvironmentSecretProviderConfig" + } + }, + "required": [ + "environment" + ] + } + ], + "description": "The secret providers without the Compose mount policy, so the strict file\nrule always applies. An operator-local file read outside any runtime, such\nas a saved CLI connection or a task connection, uses it because nothing\nreports an explicit production setting for that file. A runtime whose keys\nkeep the strict rule publishes it as the shape of its `secretProviders`.", + "properties": { + "environment": { + "$ref": "#/$defs/EnvironmentSecretProviderConfig", + "description": "Enables `secret:env/NAME` references, read from the process\nenvironment. Declared as an empty mapping: `environment: {}`." + }, + "file": { + "$ref": "#/$defs/StrictFileSecretProviderConfig", + "description": "Enables `secret:file/name` references, read from files under `root`." + } + }, + "type": "object" + }, "TokenIssuer": { "additionalProperties": false, "description": "One authorized token issuer entry.", @@ -1079,8 +1079,8 @@ "description": "Request-rate limits." }, "secretProviders": { - "$ref": "#/$defs/SecretProvidersConfig", - "description": "The secret providers the `*Ref` members may name." + "$ref": "#/$defs/StrictSecretProvidersConfig", + "description": "The secret providers the `*Ref` members may name. The file provider takes no\n`mountPolicy`: these keys keep the strict file rule." }, "sessions": { "$ref": "#/$defs/SessionsDocument", diff --git a/products/platform/CHANGELOG.md b/products/platform/CHANGELOG.md index c3c862657e..2bde922007 100644 --- a/products/platform/CHANGELOG.md +++ b/products/platform/CHANGELOG.md @@ -26,6 +26,10 @@ owner-only. Migration: if `caBundleRef` named a combined certificate and key file, split the key into its own secret file and point `caBundleRef` at the certificates alone. +- The shared runtime blocks document publishes `StrictSecretProvidersConfig` + and `StrictFileSecretProviderConfig`, the secret providers without + `mountPolicy`. The Evidence OID4VCI and OID4VP runtime schemas embed them, + so the published contract does not offer a member those runtimes refuse. - BREAKING for Rust callers of `registry-platform-config`: `SecretError` gains `UnsafePublicDocument` and `PrivateKeyInPublicDocument`, and `ProvisionInput` gains `explicit_settings`. Migration: add arms for the two diff --git a/products/platform/generated/runtime-config-blocks.schema.json b/products/platform/generated/runtime-config-blocks.schema.json index fb523197a7..0731c5e335 100644 --- a/products/platform/generated/runtime-config-blocks.schema.json +++ b/products/platform/generated/runtime-config-blocks.schema.json @@ -1027,6 +1027,58 @@ "pattern": "^(?:secret:env/[A-Z][A-Z0-9_]{0,127}|secret:file/[a-z][a-z0-9._-]{0,127})$", "type": "string" }, + "StrictFileSecretProviderConfig": { + "additionalProperties": false, + "description": "The file secret provider without the Compose mount policy.", + "properties": { + "root": { + "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 user running the process with mode 0400 or 0600, or owned by root\nwith no access beyond group read (0440 or 0640) when that user is not\nroot. A process that declared development loads a file with looser read\nor mode bits and logs a warning.", + "pattern": "^/", + "type": "string" + } + }, + "required": [ + "root" + ], + "type": "object" + }, + "StrictSecretProvidersConfig": { + "additionalProperties": false, + "anyOf": [ + { + "properties": { + "file": { + "$ref": "#/$defs/StrictFileSecretProviderConfig" + } + }, + "required": [ + "file" + ] + }, + { + "properties": { + "environment": { + "$ref": "#/$defs/EnvironmentSecretProviderConfig" + } + }, + "required": [ + "environment" + ] + } + ], + "description": "The secret providers without the Compose mount policy, so the strict file\nrule always applies. An operator-local file read outside any runtime, such\nas a saved CLI connection or a task connection, uses it because nothing\nreports an explicit production setting for that file. A runtime whose keys\nkeep the strict rule publishes it as the shape of its `secretProviders`.", + "properties": { + "environment": { + "$ref": "#/$defs/EnvironmentSecretProviderConfig", + "description": "Enables `secret:env/NAME` references, read from the process\nenvironment. Declared as an empty mapping: `environment: {}`." + }, + "file": { + "$ref": "#/$defs/StrictFileSecretProviderConfig", + "description": "Enables `secret:file/name` references, read from files under `root`." + } + }, + "type": "object" + }, "TaskGrantStatusConfig": { "additionalProperties": false, "description": "One task authority whose grants a runtime checks for fresh status, and the\nruntime's own credentials for that check, written as one entry of\n`taskGrantStatus`. The status route and scope default to Casework's.", diff --git a/products/platform/schemas/task-connection.schema.json b/products/platform/schemas/task-connection.schema.json index 16110d47f3..4327f25cb8 100644 --- a/products/platform/schemas/task-connection.schema.json +++ b/products/platform/schemas/task-connection.schema.json @@ -19,10 +19,10 @@ }, "StrictFileSecretProviderConfig": { "additionalProperties": false, - "description": "The file secret provider of an operator-local file.", + "description": "The file secret provider without the Compose mount policy.", "properties": { "root": { - "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 user running the tool with mode 0400 or 0600, or owned by root with\nno access beyond group read (0440 or 0640) when that user is not root.\nA command that declared development loads a file with looser read or\nmode bits and logs a warning.", + "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 user running the process with mode 0400 or 0600, or owned by root\nwith no access beyond group read (0440 or 0640) when that user is not\nroot. A process that declared development loads a file with looser read\nor mode bits and logs a warning.", "pattern": "^/", "type": "string" } @@ -56,7 +56,7 @@ ] } ], - "description": "The secret providers of an operator-local file read outside any runtime,\nsuch as a saved CLI connection or a task connection. It enables the same\nproviders as a runtime's `secretProviders` without the Compose mount\npolicy: nothing reports an explicit production setting for these files,\nso the strict file rule always applies.", + "description": "The secret providers without the Compose mount policy, so the strict file\nrule always applies. An operator-local file read outside any runtime, such\nas a saved CLI connection or a task connection, uses it because nothing\nreports an explicit production setting for that file. A runtime whose keys\nkeep the strict rule publishes it as the shape of its `secretProviders`.", "properties": { "environment": { "$ref": "#/$defs/EnvironmentSecretProviderConfig", diff --git a/products/platform/scripts/check-config-conformance.py b/products/platform/scripts/check-config-conformance.py index e1ae75866d..7acb0d2cf4 100755 --- a/products/platform/scripts/check-config-conformance.py +++ b/products/platform/scripts/check-config-conformance.py @@ -705,13 +705,13 @@ class Row: "AccessTokenType", "DeclaredActorKind", "EnvironmentSecretProviderConfig", - "FileSecretProviderConfig", "IssuerActorKind", "ListenerBind", "MetricsListenerConfig", "ScopeClaimName", - "SecretProvidersConfig", "SecretReference", + "StrictFileSecretProviderConfig", + "StrictSecretProvidersConfig", ), reference_refusal=TestRef( "crates/registry-evidence-oid4vci/src/config.rs", From 2a31533856b636f154971a3b25c46537e45cfdb6 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 23:37:44 +0000 Subject: [PATCH 127/183] chore(identifiers): regenerate the catalogue for the strict secret provider block Signed-off-by: Jeremi Joslin --- products/identifiers/generated/catalog.v1.json | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/products/identifiers/generated/catalog.v1.json b/products/identifiers/generated/catalog.v1.json index 4e522bd884..d7c6db2fb1 100644 --- a/products/identifiers/generated/catalog.v1.json +++ b/products/identifiers/generated/catalog.v1.json @@ -6325,11 +6325,11 @@ "description": "Evidence OID4VCI delivery runtime configuration JSON Schema.", "source": { "path": "crates/registry-evidence-oid4vci/src/schema.rs", - "sha256": "1e8069df07d75e21d6d15dfcbe92e45d2fd2fed29d8c6d162953bdb679c3f0cd" + "sha256": "c5961b898a660417c39ce3a0552c53bfc397fe269588a3971f51214264e2ff0d" }, "artifact": { "path": "products/evidence/generated/oid4vci-runtime/oid4vci-runtime.schema.json", - "sha256": "27a3505caef33020b803fd9dd67bec9d0569a8eaba86dafef6c0232166e2c098", + "sha256": "026c2168ecd30d5333c4d8e4fbea7831c6ea65ead80f5d95846634ee88c2a076", "mediaType": "application/schema+json" } }, @@ -6343,11 +6343,11 @@ "description": "Evidence OpenID4VP verifier runtime configuration JSON Schema.", "source": { "path": "crates/registry-evidence-oid4vp/src/schema.rs", - "sha256": "aa27124852e5186e3604be21886c994fe1ceb3b512495fcb56aab9925fccc114" + "sha256": "b1129ebae14366ae175246d9da6223e957ee19a4ebb57e69706621b982378031" }, "artifact": { "path": "products/evidence/generated/oid4vp-runtime/oid4vp-runtime.schema.json", - "sha256": "eefcd80bf783e37968ed22da6eb80891d82f901e5fd0549e10ce2aabcea3c65f", + "sha256": "4a8784546a9c990eece05f794e1cfd9d87691c310c39d637a1aae9e3bddebf02", "mediaType": "application/schema+json" } }, @@ -6419,7 +6419,7 @@ }, "artifact": { "path": "crates/registry-evidencectl/schemas/authoring/store-provision.schema.json", - "sha256": "c89de9234b9e92ef6c92f88a32fa3e91dfaa07dee510f7a2cb03aef1f69f917b", + "sha256": "6421b53f8cbe33174ed88cb0daa83951754a4fc7f98385274d8782a1b960741c", "mediaType": "application/schema+json" } }, @@ -6653,7 +6653,7 @@ }, "artifact": { "path": "crates/registry-cli-api/schema/connections.schema.json", - "sha256": "d826fdedf9db4049195664fc483db6749180dcd0335863ab56d548fddfbd1a45", + "sha256": "46eedf1ea8f63a1b6397244234ea690f0ebce68d45527cb28d216db9470c819c", "mediaType": "application/schema+json" } }, @@ -6797,7 +6797,7 @@ }, "artifact": { "path": "products/platform/schemas/task-connection.schema.json", - "sha256": "f579e5d0289e8d7ead2b442f29c346ff7cece9bb245197cb38616c271562f484", + "sha256": "0d65d121798aadf8f321d2ccac71ccdd05808d269de79be5157277a56c191b25", "mediaType": "application/schema+json" } }, From 1e90a6cae3bb7a11663cf13cbbc62910c702013f Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 23:39:42 +0000 Subject: [PATCH 128/183] docs(platform): state the public-document rule on the strict file provider The strict file block now says, as the runtime block does, that a public document such as a static JWKS or a CA bundle may be readable by group and others. Regenerated with each schema's generator. Refs #2882. Signed-off-by: Jeremi Joslin --- crates/registry-cli-api/schema/connections.schema.json | 2 +- .../schemas/authoring/store-provision.schema.json | 2 +- crates/registry-platform-config/src/blocks.rs | 3 ++- .../generated/oid4vci-runtime/oid4vci-runtime.schema.json | 2 +- .../generated/oid4vp-runtime/oid4vp-runtime.schema.json | 2 +- products/platform/generated/runtime-config-blocks.schema.json | 2 +- products/platform/schemas/task-connection.schema.json | 2 +- 7 files changed, 8 insertions(+), 7 deletions(-) diff --git a/crates/registry-cli-api/schema/connections.schema.json b/crates/registry-cli-api/schema/connections.schema.json index 34aabe761c..24879c69c2 100644 --- a/crates/registry-cli-api/schema/connections.schema.json +++ b/crates/registry-cli-api/schema/connections.schema.json @@ -186,7 +186,7 @@ "description": "The file secret provider without the Compose mount policy.", "properties": { "root": { - "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 user running the process with mode 0400 or 0600, or owned by root\nwith no access beyond group read (0440 or 0640) when that user is not\nroot. A process that declared development loads a file with looser read\nor mode bits and logs a warning.", + "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 user running the process with mode 0400 or 0600, or owned by root\nwith no access beyond group read (0440 or 0640) when that user is not\nroot. A process that declared development loads a file with looser read\nor mode bits and logs a warning. A public document, such as a static\nJWKS or a CA bundle, may also be readable by group and others.", "pattern": "^/", "type": "string" } diff --git a/crates/registry-evidencectl/schemas/authoring/store-provision.schema.json b/crates/registry-evidencectl/schemas/authoring/store-provision.schema.json index dee8594c27..ee545f8823 100644 --- a/crates/registry-evidencectl/schemas/authoring/store-provision.schema.json +++ b/crates/registry-evidencectl/schemas/authoring/store-provision.schema.json @@ -77,7 +77,7 @@ "description": "The file secret provider without the Compose mount policy.", "properties": { "root": { - "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 user running the process with mode 0400 or 0600, or owned by root\nwith no access beyond group read (0440 or 0640) when that user is not\nroot. A process that declared development loads a file with looser read\nor mode bits and logs a warning.", + "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 user running the process with mode 0400 or 0600, or owned by root\nwith no access beyond group read (0440 or 0640) when that user is not\nroot. A process that declared development loads a file with looser read\nor mode bits and logs a warning. A public document, such as a static\nJWKS or a CA bundle, may also be readable by group and others.", "pattern": "^/", "type": "string" } diff --git a/crates/registry-platform-config/src/blocks.rs b/crates/registry-platform-config/src/blocks.rs index 7faf8e148d..5b1081935b 100644 --- a/crates/registry-platform-config/src/blocks.rs +++ b/crates/registry-platform-config/src/blocks.rs @@ -323,7 +323,8 @@ pub struct StrictFileSecretProviderConfig { /// the user running the process with mode 0400 or 0600, or owned by root /// with no access beyond group read (0440 or 0640) when that user is not /// root. A process that declared development loads a file with looser read - /// or mode bits and logs a warning. + /// or mode bits and logs a warning. A public document, such as a static + /// JWKS or a CA bundle, may also be readable by group and others. #[cfg_attr(feature = "schema", schemars(extend("pattern" = "^/")))] pub root: PathBuf, } diff --git a/products/evidence/generated/oid4vci-runtime/oid4vci-runtime.schema.json b/products/evidence/generated/oid4vci-runtime/oid4vci-runtime.schema.json index f83e6925b9..7504007b90 100644 --- a/products/evidence/generated/oid4vci-runtime/oid4vci-runtime.schema.json +++ b/products/evidence/generated/oid4vci-runtime/oid4vci-runtime.schema.json @@ -591,7 +591,7 @@ "description": "The file secret provider without the Compose mount policy.", "properties": { "root": { - "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 user running the process with mode 0400 or 0600, or owned by root\nwith no access beyond group read (0440 or 0640) when that user is not\nroot. A process that declared development loads a file with looser read\nor mode bits and logs a warning.", + "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 user running the process with mode 0400 or 0600, or owned by root\nwith no access beyond group read (0440 or 0640) when that user is not\nroot. A process that declared development loads a file with looser read\nor mode bits and logs a warning. A public document, such as a static\nJWKS or a CA bundle, may also be readable by group and others.", "pattern": "^/", "type": "string" } diff --git a/products/evidence/generated/oid4vp-runtime/oid4vp-runtime.schema.json b/products/evidence/generated/oid4vp-runtime/oid4vp-runtime.schema.json index 4d42f9ee68..4d5330d100 100644 --- a/products/evidence/generated/oid4vp-runtime/oid4vp-runtime.schema.json +++ b/products/evidence/generated/oid4vp-runtime/oid4vp-runtime.schema.json @@ -657,7 +657,7 @@ "description": "The file secret provider without the Compose mount policy.", "properties": { "root": { - "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 user running the process with mode 0400 or 0600, or owned by root\nwith no access beyond group read (0440 or 0640) when that user is not\nroot. A process that declared development loads a file with looser read\nor mode bits and logs a warning.", + "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 user running the process with mode 0400 or 0600, or owned by root\nwith no access beyond group read (0440 or 0640) when that user is not\nroot. A process that declared development loads a file with looser read\nor mode bits and logs a warning. A public document, such as a static\nJWKS or a CA bundle, may also be readable by group and others.", "pattern": "^/", "type": "string" } diff --git a/products/platform/generated/runtime-config-blocks.schema.json b/products/platform/generated/runtime-config-blocks.schema.json index 0731c5e335..beb3dd8570 100644 --- a/products/platform/generated/runtime-config-blocks.schema.json +++ b/products/platform/generated/runtime-config-blocks.schema.json @@ -1032,7 +1032,7 @@ "description": "The file secret provider without the Compose mount policy.", "properties": { "root": { - "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 user running the process with mode 0400 or 0600, or owned by root\nwith no access beyond group read (0440 or 0640) when that user is not\nroot. A process that declared development loads a file with looser read\nor mode bits and logs a warning.", + "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 user running the process with mode 0400 or 0600, or owned by root\nwith no access beyond group read (0440 or 0640) when that user is not\nroot. A process that declared development loads a file with looser read\nor mode bits and logs a warning. A public document, such as a static\nJWKS or a CA bundle, may also be readable by group and others.", "pattern": "^/", "type": "string" } diff --git a/products/platform/schemas/task-connection.schema.json b/products/platform/schemas/task-connection.schema.json index 4327f25cb8..256fd72a8c 100644 --- a/products/platform/schemas/task-connection.schema.json +++ b/products/platform/schemas/task-connection.schema.json @@ -22,7 +22,7 @@ "description": "The file secret provider without the Compose mount policy.", "properties": { "root": { - "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 user running the process with mode 0400 or 0600, or owned by root\nwith no access beyond group read (0440 or 0640) when that user is not\nroot. A process that declared development loads a file with looser read\nor mode bits and logs a warning.", + "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 user running the process with mode 0400 or 0600, or owned by root\nwith no access beyond group read (0440 or 0640) when that user is not\nroot. A process that declared development loads a file with looser read\nor mode bits and logs a warning. A public document, such as a static\nJWKS or a CA bundle, may also be readable by group and others.", "pattern": "^/", "type": "string" } From 6e52df500a41d7a4c61e46bb1e199485b5afb5dd Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 20:34:13 +0000 Subject: [PATCH 129/183] feat(coordinator): call a named service function without product authority Add service.invoke-function/v1 beside external.command/v1. A workflow names one function declared in service.yaml with serviceFunction; a type: service-function runtime connection binds the function host, that one function and a credential for the host alone. check refuses a missing name, a name the connection does not bind, and a function credential whose resource, client or signing key matches a product or external connection, so the function host token is never one a product accepts and any record change stays a separate product step. Calls reuse the external command path: frozen Idempotency-Key, no redirects, bounded bodies, held ambiguity and a required interpret Function. Refs #2888 Signed-off-by: Jeremi Joslin --- crates/registry-coordinator/src/adapters.rs | 38 ++ crates/registry-coordinator/src/authoring.rs | 53 ++- crates/registry-coordinator/src/contracts.rs | 22 ++ crates/registry-coordinator/src/definition.rs | 32 +- .../registry-coordinator/src/external_http.rs | 72 +++- crates/registry-coordinator/src/operations.rs | 15 +- crates/registry-coordinator/src/protocol.rs | 7 + crates/registry-coordinator/src/runtime.rs | 120 +++++- crates/registry-coordinator/src/scenarios.rs | 6 +- crates/registry-coordinator/src/worker.rs | 4 +- .../service-function/fixtures/drafted.yaml | 24 ++ .../fixtures/not-eligible.yaml | 24 ++ .../fixtures/unrecognised-answer-holds.yaml | 17 + .../fixtures/service-function/functions.rhai | 18 + .../fixtures/service-function/runtime.yaml | 26 ++ .../fixtures/service-function/workflow.yaml | 106 ++++++ .../tests/service_function.rs | 253 +++++++++++++ .../tests/service_function_postgres.rs | 221 +++++++++++ .../tests/service_function_project.rs | 345 ++++++++++++++++++ .../content/docs/configure/coordinator.mdx | 26 +- .../reference/coordinator-configuration.mdx | 45 ++- .../src/content/docs/security/coordinator.mdx | 89 ++++- products/coordinator/CHANGELOG.md | 1 + .../openapi/coordinator.openapi.json | 3 +- .../generated/operations/README.md | 68 ++++ .../generated/operations/catalog.json | 86 +++++ ...e-function.v1.declared-refusal.schema.json | 18 + ...rvice.invoke-function.v1.input.schema.json | 7 + ...vice.invoke-function.v1.output.schema.json | 20 + .../generated/project/project.schema.json | 11 +- .../generated/runtime/runtime.schema.json | 53 +++ products/coordinator/scripts/test-postgres.sh | 2 +- 32 files changed, 1793 insertions(+), 39 deletions(-) create mode 100644 crates/registry-coordinator/tests/fixtures/service-function/fixtures/drafted.yaml create mode 100644 crates/registry-coordinator/tests/fixtures/service-function/fixtures/not-eligible.yaml create mode 100644 crates/registry-coordinator/tests/fixtures/service-function/fixtures/unrecognised-answer-holds.yaml create mode 100644 crates/registry-coordinator/tests/fixtures/service-function/functions.rhai create mode 100644 crates/registry-coordinator/tests/fixtures/service-function/runtime.yaml create mode 100644 crates/registry-coordinator/tests/fixtures/service-function/workflow.yaml create mode 100644 crates/registry-coordinator/tests/service_function.rs create mode 100644 crates/registry-coordinator/tests/service_function_postgres.rs create mode 100644 crates/registry-coordinator/tests/service_function_project.rs create mode 100644 products/coordinator/generated/operations/service.invoke-function.v1.declared-refusal.schema.json create mode 100644 products/coordinator/generated/operations/service.invoke-function.v1.input.schema.json create mode 100644 products/coordinator/generated/operations/service.invoke-function.v1.output.schema.json diff --git a/crates/registry-coordinator/src/adapters.rs b/crates/registry-coordinator/src/adapters.rs index 3c7d9aa169..efe16b71d2 100644 --- a/crates/registry-coordinator/src/adapters.rs +++ b/crates/registry-coordinator/src/adapters.rs @@ -64,6 +64,8 @@ enum Connection { Payments(Box), Casework(Box), External(Box), + /// One bound service function, reached only by `service.invoke-function/v1`. + ServiceFunction(Box), Decision(Box), } @@ -213,6 +215,26 @@ impl HttpAdapters { connections.insert(name.clone(), Connection::External(Box::new(connection))); continue; } + if let Some(binding) = configured.service_function() { + let auth = &binding.authorization; + let key_bytes = secrets + .resolve_reference(&auth.signing_key_ref) + .map_err(|_| config_error())?; + let key_text = + std::str::from_utf8(key_bytes.expose_secret()).map_err(|_| config_error())?; + let key = PrivateJwk::parse(key_text).map_err(|_| config_error())?; + let provider = Arc::new( + tokens(auth, key, &auth.resource, &auth.scopes).map_err(|_| config_error())?, + ); + let connection = crate::external_http::ExternalHttpConnection::service_function( + binding, provider, + )?; + connections.insert( + name.clone(), + Connection::ServiceFunction(Box::new(connection)), + ); + continue; + } if let Some(binding) = configured.decision() { let connection = crate::decision::DecisionConnection::new(binding, Arc::clone(&secrets))?; @@ -1088,6 +1110,16 @@ impl AdapterSet for HttpAdapters { }; connection.command(&request.input, key, final_attempt).await } + ( + Some(Connection::ServiceFunction(connection)), + Operation::InvokeServiceFunction, + None, + ) => { + let Some(key) = &request.idempotency_key else { + return refused("invalid-command"); + }; + connection.command(&request.input, key, final_attempt).await + } _ => self.call_prepared(request, prepared).await, } } @@ -1103,6 +1135,12 @@ impl AdapterSet for HttpAdapters { }; connection.command(&request.input, key, false).await } + (Some(Connection::ServiceFunction(connection)), Operation::InvokeServiceFunction) => { + let Some(key) = &request.idempotency_key else { + return refused("invalid-command"); + }; + connection.command(&request.input, key, false).await + } ( Some(Connection::Breg { client, options, .. diff --git a/crates/registry-coordinator/src/authoring.rs b/crates/registry-coordinator/src/authoring.rs index 339fbcc310..ca0c39501d 100644 --- a/crates/registry-coordinator/src/authoring.rs +++ b/crates/registry-coordinator/src/authoring.rs @@ -163,13 +163,20 @@ struct AuthoredOperation { /// Fix a Messaging template version, its locales and its data schema. #[serde(default)] template: Option, + /// The one service function `service.invoke-function/v1` calls, as the + /// service's `service.yaml` declares it. Required on, and accepted only + /// on, that Operation. The runtime connection binds its host and + /// credential; the workflow supplies neither. + #[serde(default)] + service_function: Option, /// An optional typed response specialization for the bounded external GET - /// or external command Operation. + /// or external command Operation, or the service function Operation. #[serde(default)] response_schema: Option, /// The typed pure Transform that interprets an external command's provider /// response into an accepted result, a declared refusal or an uncertain - /// outcome. Required on, and accepted only on, `external.command/v1`. + /// outcome. Required on, and accepted only on, `external.command/v1` and + /// `service.invoke-function/v1`. #[serde(default)] interpret: Option, /// Named bounded completion contracts; the host enforces their observation semantics. @@ -1280,31 +1287,54 @@ fn compile(project: CoordinatorProject, path: &Path) -> Result { &imported, ) .map_err(|error| error.at("workflow.yaml", contract_field))?; + match ( + uses == Operation::InvokeServiceFunction, + &operation.service_function, + ) { + (true, None) => { + return Err(schema_error( + format!("/operations/{id}/serviceFunction"), + "service.invoke-function/v1 requires serviceFunction: the one function declared in service.yaml that this Operation calls", + )); + } + (false, Some(_)) => { + return Err(schema_error( + format!("/operations/{id}/serviceFunction"), + "only service.invoke-function/v1 accepts a serviceFunction", + )); + } + _ => {} + } if operation.response_schema.is_some() - && !matches!(uses, Operation::ExternalGet | Operation::ExternalCommand) + && !matches!( + uses, + Operation::ExternalGet + | Operation::ExternalCommand + | Operation::InvokeServiceFunction + ) { return Err(schema_error( format!("/operations/{id}/responseSchema"), - "only the bounded external GET and external command profiles accept a response specialization", + "only the bounded external GET, external command and service function profiles accept a response specialization", )); } - match (uses, operation.interpret) { - (Operation::ExternalCommand, Some(interpret)) => { + match (uses.interprets_response(), operation.interpret) { + (true, Some(interpret)) => { command_interpreters.insert(id.clone(), interpret); } - (Operation::ExternalCommand, None) => { + (true, None) => { return Err(schema_error( format!("/operations/{id}/interpret"), - "external.command/v1 requires interpret: the Transform that turns the provider response into an accepted result, a declared refusal or an uncertain outcome", + &format!("{} requires interpret: the Transform that turns the provider response into an accepted result, a declared refusal or an uncertain outcome", uses.as_str()), )); } - (_, Some(_)) => { + (false, Some(_)) => { return Err(schema_error( format!("/operations/{id}/interpret"), - "only external.command/v1 accepts an interpretation Transform", + "only external.command/v1 and service.invoke-function/v1 accept an interpretation Transform", )); } - (_, None) => {} + (false, None) => {} } let mut completions = BTreeMap::new(); if uses == Operation::SubmitReviewRequest { @@ -1363,6 +1393,7 @@ fn compile(project: CoordinatorProject, path: &Path) -> Result { revision: String::new(), interpret: None, response: None, + service_function: operation.service_function.map(LocalId::into_string), action: contract.action, label: operation.label, description: operation.description, diff --git a/crates/registry-coordinator/src/contracts.rs b/crates/registry-coordinator/src/contracts.rs index efa16f2389..9d89435172 100644 --- a/crates/registry-coordinator/src/contracts.rs +++ b/crates/registry-coordinator/src/contracts.rs @@ -1277,6 +1277,28 @@ mod derived { ) } + /// The function body is a JSON object a pinned pure Transform builds; the + /// output is the bounded function host response the pinned interpretation + /// Transform receives, as for an external command. + pub(super) fn invoke_service_function() -> (Value, Value) { + let mut response = output::(); + response["description"] = json!( + "The bounded function host response. The operation's interpret \ + Transform receives it with the request body and returns the step \ + result, a declared refusal, or an uncertain outcome." + ); + ( + json!({ + "$schema":"https://json-schema.org/draft/2020-12/schema", + "type":"object", + "description":"The request body, sent as the exact JSON object to the \ + one service function the connection binds.", + "additionalProperties":true + }), + response, + ) + } + pub(super) fn evaluate() -> (Value, Value) { (evaluation_input(), output::()) } diff --git a/crates/registry-coordinator/src/definition.rs b/crates/registry-coordinator/src/definition.rs index 2b3d45be7c..0909cc7293 100644 --- a/crates/registry-coordinator/src/definition.rs +++ b/crates/registry-coordinator/src/definition.rs @@ -392,6 +392,11 @@ pub struct ResolvedOperation { /// interpreted accepted result. #[serde(default, skip_serializing_if = "Option::is_none")] pub response: Option, + /// The one service function, declared in `service.yaml`, that + /// `service.invoke-function/v1` calls. Present only on that operation; the + /// runtime connection must bind the same function. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub service_function: Option, /// Exact imported specialization, when the owning product exports one. #[serde(default, skip_serializing_if = "Option::is_none")] pub action: Option, @@ -1402,16 +1407,20 @@ fn seal_revisions(workflow: &mut Workflow, sources: &BTreeMap) - if let Some(response) = &operation.response { identity["response"] = semantic_schema(response); } + if let Some(function) = &operation.service_function { + identity["serviceFunction"] = serde_json::json!(function); + } operation.revision = semantic_hash(&identity)?; } Ok(()) } -/// An external command pins one interpretation Transform over its exact -/// command and response schemas, and its output and refusal are exactly what -/// that Transform declares. No other operation carries an interpretation. +/// An external command or service function call pins one interpretation +/// Transform over its exact command and response schemas, and its output and +/// refusal are exactly what that Transform declares. No other operation +/// carries an interpretation. fn command_interpretation_valid(flow: &Workflow, operation: &ResolvedOperation) -> bool { - if operation.uses != Operation::ExternalCommand { + if !operation.uses.interprets_response() { return operation.interpret.is_none() && operation.response.is_none(); } let (Some(interpret), Some(response)) = (&operation.interpret, &operation.response) else { @@ -1813,6 +1822,21 @@ fn workflow_findings(flow: &Workflow) -> Vec { findings.push(authored("definition.abi", &format!("/operations/{alias}/interpret"), "the command interpretation does not match its host-enforced Operation contract", "Recompile the canonical project; local metadata cannot change how a provider response is interpreted.")); } + let names_function = operation + .service_function + .as_deref() + .is_some_and(|name| registry_platform_yaml::LocalId::new(name).is_ok()); + if (operation.uses == Operation::InvokeServiceFunction) != names_function + || (operation.uses != Operation::InvokeServiceFunction + && operation.service_function.is_some()) + { + findings.push(authored( + "definition.abi", + &format!("/operations/{alias}/serviceFunction"), + "the operation does not name exactly one valid service function", + "Recompile the canonical project with its checked service function name.", + )); + } } for (name, step) in &flow.steps { if let Step::Call { call, .. } = step { diff --git a/crates/registry-coordinator/src/external_http.rs b/crates/registry-coordinator/src/external_http.rs index c6fa2cb42a..51ca1b64ae 100644 --- a/crates/registry-coordinator/src/external_http.rs +++ b/crates/registry-coordinator/src/external_http.rs @@ -1,7 +1,9 @@ // SPDX-License-Identifier: Apache-2.0 -//! Configured, bounded external JSON reads and one configured external command. -//! A read never sends a mutation. A command sends one JSON object by POST to -//! the operator's configured command path and nowhere else. +//! Configured, bounded external JSON reads, one configured external command, +//! and one bound service function. A read never sends a mutation. A command +//! sends one JSON object by POST to the operator's configured command path and +//! nowhere else; a service function call sends one to the function host's +//! route for the one function the connection binds. use std::{collections::BTreeMap, sync::Arc, time::Duration}; @@ -11,7 +13,7 @@ use registry_platform_httputil::{ client::{RetryAfter, TokenProvider}, read_bounded, BoundedReadError, FetchUrlError, FetchUrlPolicy, ServiceBaseUrl, }; -use registry_platform_yaml::{BoundedU64, ExternalId, ForeignValue, UniqueList}; +use registry_platform_yaml::{BoundedU64, ExternalId, ForeignValue, LocalId, UniqueList}; use serde::{Deserialize, Deserializer, Serialize}; use serde_json::Value; use url::{Host, Url}; @@ -51,6 +53,59 @@ pub struct ExternalHttpConfig { pub maximum_response_bytes: BoundedU64<1, { crate::operations::MAXIMUM_HTTP_RESPONSE_BYTES }>, } +/// One service function declared in the service's `service.yaml`, bound by the +/// deployment to its function host and to a credential for that host alone. +/// The workflow names the function; it never supplies the destination or the +/// credential. The function host serves the function at `functions/` +/// under the base URL. +#[derive(Clone, Serialize, Deserialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct ServiceFunctionConfig { + #[serde(deserialize_with = "endpoint")] + #[cfg_attr(feature = "schema", schemars(with = "registry_platform_yaml::Url"))] + #[cfg_attr(feature = "schema", schemars(extend("pattern" = "^[^\\s\\\\]+$")))] + pub base_url: Url, + /// The one function this connection binds, as `service.yaml` declares it. + pub function: LocalId, + /// The function host credential. Its client, key and resource are the + /// function host's own and are never a product connection's, so the token + /// carries no product authority. + #[cfg_attr(feature = "schema", schemars(extend("not" = serde_json::json!({"required":["taskAuthority"]}))))] + pub authorization: AuthorizationConfig, + /// Local JSON Schema for the complete {status, body} response. + #[cfg_attr(feature = "schema", schemars(extend("x-registry-foreign" = "json-schema-2020-12")))] + pub response_schema: ForeignValue, + #[serde(default = "default_timeout")] + pub attempt_timeout_milliseconds: + BoundedU64<1, { crate::operations::HTTP_REQUEST_TIMEOUT_MILLISECONDS }>, + #[serde(default = "default_response_bytes")] + pub maximum_response_bytes: BoundedU64<1, { crate::operations::MAXIMUM_HTTP_RESPONSE_BYTES }>, +} + +impl ServiceFunctionConfig { + /// The bounded HTTP transport for the one function route: its only path + /// is the command path, and the credential is always present. + pub(crate) fn transport(&self) -> ExternalHttpConfig { + let route = ExternalId::new(format!("functions/{}", self.function.as_str())) + .expect("a local identifier yields a bounded relative path"); + ExternalHttpConfig { + base_url: self.base_url.clone(), + paths: UniqueList::new(vec![route.clone()]).expect("one path is unique"), + query_parameters: None, + authorization: Some(self.authorization.clone()), + command_path: Some(route), + response_schema: self.response_schema.clone(), + attempt_timeout_milliseconds: self.attempt_timeout_milliseconds, + maximum_response_bytes: self.maximum_response_bytes, + } + } + + pub fn findings(&self, prefix: &str) -> Vec { + self.transport().findings(prefix) + } +} + fn endpoint<'de, D: Deserializer<'de>>(d: D) -> std::result::Result { let written = registry_platform_yaml::Url::deserialize(d)?; if written.as_str().contains('\\') || written.as_str().chars().any(char::is_whitespace) { @@ -221,6 +276,15 @@ impl ExternalHttpConnection { }) } + /// The connection to one bound service function. Calls reach it only + /// through [`Self::command`], under the function host credential. + pub fn service_function( + config: &ServiceFunctionConfig, + tokens: Arc, + ) -> Result { + Self::new(&config.transport(), Some(tokens)) + } + /// One attempt at the configured read. Before the final attempt, a busy or /// failing gateway (429, 502, 503 or 504) is retryable with the wait its /// `Retry-After` names; on the final attempt the workflow receives it as diff --git a/crates/registry-coordinator/src/operations.rs b/crates/registry-coordinator/src/operations.rs index d671f9d3f1..8618487451 100644 --- a/crates/registry-coordinator/src/operations.rs +++ b/crates/registry-coordinator/src/operations.rs @@ -150,12 +150,17 @@ impl OperationDescriptor { "connectTimeoutMilliseconds":HTTP_CONNECT_TIMEOUT_MILLISECONDS, "maximumMutationRetries":HTTP_MUTATION_RETRIES }); - if matches!(self.product, "external-http" | "evaluation") { + if matches!( + self.product, + "external-http" | "service-function" | "evaluation" + ) { let fields = http.as_object_mut().expect("HTTP contract is an object"); fields.remove("connectTimeoutMilliseconds"); fields.insert("connectionMayLowerLimits".into(), json!(true)); fields.insert("redirects".into(), json!("refused")); - if self.id == Operation::ExternalCommand.as_str() { + if self.id == Operation::ExternalCommand.as_str() + || self.id == Operation::InvokeServiceFunction.as_str() + { fields.insert( "maximumRequestBytes".into(), json!(MAXIMUM_HTTP_RESPONSE_BYTES), @@ -358,6 +363,7 @@ macro_rules! operation_catalog { RequestDisbursement => "payments.request-disbursement/v1", receipt_reconciled_mutation("payments"), request_disbursement; ReadDisbursement => "payments.read-disbursement/v1", read("payments"), read_disbursement; RecordProviderConfirmation => "payments.record-provider-confirmation/v1", mutation("payments", false, false), record_provider_confirmation; + InvokeServiceFunction => "service.invoke-function/v1", declared_mutation("service-function", false, false), invoke_service_function; } }; } @@ -494,6 +500,10 @@ mod tests { Operation::RecordProviderConfirmation, "payments.record-provider-confirmation/v1", ), + ( + Operation::InvokeServiceFunction, + "service.invoke-function/v1", + ), ]; assert_eq!( descriptors() @@ -647,6 +657,7 @@ mod tests { Operation::RecordReceipt, Operation::RequestDisbursement, Operation::RecordProviderConfirmation, + Operation::InvokeServiceFunction, ]; let allowed_mutations = [ Operation::SubmitMessage, diff --git a/crates/registry-coordinator/src/protocol.rs b/crates/registry-coordinator/src/protocol.rs index 49e2f14030..95c308bae0 100644 --- a/crates/registry-coordinator/src/protocol.rs +++ b/crates/registry-coordinator/src/protocol.rs @@ -71,6 +71,7 @@ impl Operation { | Self::StartProposal | Self::SubmitProposal | Self::ExternalCommand + | Self::InvokeServiceFunction | Self::RequestCollection | Self::RecordReceipt | Self::RequestDisbursement @@ -78,6 +79,12 @@ impl Operation { ) } + /// Calls whose bounded provider response becomes a step result only + /// through the operation's pinned interpretation Transform. + pub fn interprets_response(self) -> bool { + matches!(self, Self::ExternalCommand | Self::InvokeServiceFunction) + } + pub fn is_read(self) -> bool { self.descriptor().effect == crate::operations::EffectKind::Read } diff --git a/crates/registry-coordinator/src/runtime.rs b/crates/registry-coordinator/src/runtime.rs index 20084f7317..c355c6cad2 100644 --- a/crates/registry-coordinator/src/runtime.rs +++ b/crates/registry-coordinator/src/runtime.rs @@ -237,6 +237,7 @@ pub enum ConnectionConfig { Payments(PaymentConnectionConfig), Scheduling(Box), ExternalHttp(crate::external_http::ExternalHttpConfig), + ServiceFunction(crate::external_http::ServiceFunctionConfig), Evaluation(crate::decision::DecisionConfig), } registry_platform_yaml::tagged_union!(ConnectionConfig); @@ -423,7 +424,7 @@ impl ConnectionConfig { None, c.result_check_seconds, ), - Self::ExternalHttp(_) | Self::Evaluation(_) => return None, + Self::ExternalHttp(_) | Self::ServiceFunction(_) | Self::Evaluation(_) => return None, }; Some(ProductBinding { product, @@ -445,6 +446,13 @@ impl ConnectionConfig { } } + pub fn service_function(&self) -> Option<&crate::external_http::ServiceFunctionConfig> { + match self { + Self::ServiceFunction(config) => Some(config), + _ => None, + } + } + pub fn decision(&self) -> Option<&crate::decision::DecisionConfig> { match self { Self::Evaluation(config) => Some(config), @@ -463,7 +471,7 @@ impl ConnectionConfig { Self::Payments(c) => Some(&mut c.authorization), Self::Scheduling(c) => Some(&mut c.authorization), Self::CaseworkReviewProducer(c) => Some(&mut c.authorization), - Self::ExternalHttp(_) | Self::Evaluation(_) => None, + Self::ExternalHttp(_) | Self::ServiceFunction(_) | Self::Evaluation(_) => None, } } @@ -496,6 +504,7 @@ impl ConnectionConfig { Self::Payments(_) => "payments", Self::Scheduling(_) => "scheduling", Self::ExternalHttp(_) => "external-http", + Self::ServiceFunction(_) => "service-function", Self::Evaluation(_) => "evaluation", } } @@ -515,6 +524,7 @@ impl Serialize for ConnectionConfig { Self::Payments(c) => ("payments", serde_json::to_value(c)), Self::Scheduling(c) => ("scheduling", serde_json::to_value(c)), Self::ExternalHttp(c) => ("external-http", serde_json::to_value(c)), + Self::ServiceFunction(c) => ("service-function", serde_json::to_value(c)), Self::Evaluation(c) => ("evaluation", serde_json::to_value(c)), }; let mut value = value.map_err(serde::ser::Error::custom)?; @@ -837,6 +847,13 @@ impl RuntimeConfig { &self.secret_providers, )); } + } else if let Some(function) = binding.service_function() { + errors.extend(function.findings(&field)); + errors.extend(function.authorization.secret_reference_finding( + &format!("{field}.authorization"), + &self.secret_providers, + )); + errors.extend(self.function_credential_findings(&field, function)); } else if let Some(binding) = binding.decision() { errors.extend(binding.findings(&field)); if let Some(reference) = binding.token_ref() { @@ -1034,6 +1051,52 @@ impl RuntimeConfig { self.validate_workflow_effect_bindings(workflow) } + /// A service function credential is for its function host alone. Its + /// resource, client and signing key may not be any product or external + /// connection's, so the token it yields is never one a product accepts and + /// a function holds no record authority through it. + fn function_credential_findings( + &self, + field: &str, + function: &crate::external_http::ServiceFunctionConfig, + ) -> Vec { + let own = &function.authorization; + let mut others = Vec::new(); + for binding in self.connections.values() { + if let Some(product) = binding.product_binding() { + others.push(product.authorization); + others.extend(product.observation_authorization); + } else if let Some(external) = binding.external_http() { + others.extend(external.authorization.as_ref()); + } + } + let mut errors = Vec::new(); + for (member, reused) in [ + ( + "resource", + others.iter().any(|other| other.resource == own.resource), + ), + ( + "clientId", + others.iter().any(|other| other.client_id == own.client_id), + ), + ( + "signingKeyRef", + others + .iter() + .any(|other| other.signing_key_ref == own.signing_key_ref), + ), + ] { + if reused { + errors.push(config_error( + &format!("{field}.authorization.{member}"), + "give the service function host its own resource, client and signing key; a product or external connection's credential would let the function act with product authority", + )); + } + } + errors + } + /// Retained Runs require their effect bindings, independently of whether /// the event source that admitted them is still enabled for new starts. fn validate_workflow_effect_bindings( @@ -1091,6 +1154,34 @@ impl RuntimeConfig { call.connection, ))); } + if call.operation == crate::protocol::Operation::InvokeServiceFunction { + let named = workflow + .operations + .get(&call.alias) + .and_then(|operation| operation.service_function.as_deref()); + let bound = self + .connections + .get(&call.connection) + .and_then(ConnectionConfig::service_function) + .map(|binding| binding.function.as_str()); + if bound.is_some() && named != bound { + return Err(CoordinatorError::new( + "workflow-binding", + format!( + "the connection does not bind the service function {}", + named.unwrap_or("the operation names") + ), + ) + .at( + "workflow.yaml", + format!("/operations/{}/serviceFunction", call.alias), + ) + .suggest(format!( + "Name a function declared in service.yaml and bound as connections.{}.function in runtime.yaml, or add one service-function connection for it.", + call.connection + ))); + } + } if call.operation == crate::protocol::Operation::ExternalCommand && self .connections @@ -1181,6 +1272,31 @@ impl RuntimeConfig { identities.insert(name, identity); continue; } + if let Some(binding) = self + .connections + .get(name) + .and_then(ConnectionConfig::service_function) + { + let mut identity = serde_json::to_value(binding).map_err(|_| { + config_error("connections", "correct the service function binding model") + })?; + if let Some(auth) = identity + .get_mut("authorization") + .and_then(serde_json::Value::as_object_mut) + { + auth.remove("signingKeyRef"); + if let Some(scopes) = auth + .get_mut("scopes") + .and_then(serde_json::Value::as_array_mut) + { + scopes.sort_by(|a, b| a.as_str().cmp(&b.as_str())); + } + } + identity["product"] = json!("service-function"); + identity["abi"] = json!("coordinator-service-function/v1"); + identities.insert(name, identity); + continue; + } let binding = self.connections[name] .product_binding() .expect("validated product binding"); diff --git a/crates/registry-coordinator/src/scenarios.rs b/crates/registry-coordinator/src/scenarios.rs index 28b6c9405d..360b6a0be1 100644 --- a/crates/registry-coordinator/src/scenarios.rs +++ b/crates/registry-coordinator/src/scenarios.rs @@ -941,7 +941,7 @@ fn execute(definition: &Definition, scenario: &Scenario) -> Result Result { - if call.operation != crate::protocol::Operation::ExternalCommand { + if !call.operation.interprets_response() { return Err(error( "scenario.reply", format!("/replies/{step}/{index}"), format!("step {step} calls {operation}, which takes no provider response reply"), - "Use response only for external.command/v1; use success for this operation's output.", + "Use response only for external.command/v1 or service.invoke-function/v1; use success for this operation's output.", )); } definition.operation_contract(call)? diff --git a/crates/registry-coordinator/src/worker.rs b/crates/registry-coordinator/src/worker.rs index e55e8f1fda..6b11b8b0a3 100644 --- a/crates/registry-coordinator/src/worker.rs +++ b/crates/registry-coordinator/src/worker.rs @@ -735,9 +735,7 @@ impl Worker { // A command's provider response becomes its step result only // through the project's pinned interpretation Transform. let result = match result { - CallOutcome::Success(response) - if request.operation == crate::protocol::Operation::ExternalCommand => - { + CallOutcome::Success(response) if request.operation.interprets_response() => { crate::external_http::interpret_command( &definition, call, diff --git a/crates/registry-coordinator/tests/fixtures/service-function/fixtures/drafted.yaml b/crates/registry-coordinator/tests/fixtures/service-function/fixtures/drafted.yaml new file mode 100644 index 0000000000..bfed482cd8 --- /dev/null +++ b/crates/registry-coordinator/tests/fixtures/service-function/fixtures/drafted.yaml @@ -0,0 +1,24 @@ +# yaml-language-server: $schema=https://id.registrystack.org/schemas/coordinator/fixture/fixture.v1alpha1.schema.json +apiVersion: id.registrystack.org/formats/coordinator/fixture/v1alpha1 +kind: CoordinatorFixture +id: drafted +admittedAt: '2026-12-01T00:00:00Z' +input: + reference: application-001 +replies: + draft: + - type: response + value: + status: 200 + body: + draftId: draft-001 +expect: + path: + - draft + - drafted + state: completed + outcome: + type: named + value: drafted + output: + draftId: draft-001 diff --git a/crates/registry-coordinator/tests/fixtures/service-function/fixtures/not-eligible.yaml b/crates/registry-coordinator/tests/fixtures/service-function/fixtures/not-eligible.yaml new file mode 100644 index 0000000000..da5ba94519 --- /dev/null +++ b/crates/registry-coordinator/tests/fixtures/service-function/fixtures/not-eligible.yaml @@ -0,0 +1,24 @@ +# yaml-language-server: $schema=https://id.registrystack.org/schemas/coordinator/fixture/fixture.v1alpha1.schema.json +apiVersion: id.registrystack.org/formats/coordinator/fixture/v1alpha1 +kind: CoordinatorFixture +id: not-eligible +admittedAt: '2026-12-01T00:00:00Z' +input: + reference: application-002 +replies: + draft: + - type: response + value: + status: 422 + body: + reason: not-eligible +expect: + path: + - draft + - not-drafted + state: completed + outcome: + type: named + value: not-drafted + output: + refusalCode: not-eligible diff --git a/crates/registry-coordinator/tests/fixtures/service-function/fixtures/unrecognised-answer-holds.yaml b/crates/registry-coordinator/tests/fixtures/service-function/fixtures/unrecognised-answer-holds.yaml new file mode 100644 index 0000000000..13b5d006da --- /dev/null +++ b/crates/registry-coordinator/tests/fixtures/service-function/fixtures/unrecognised-answer-holds.yaml @@ -0,0 +1,17 @@ +# yaml-language-server: $schema=https://id.registrystack.org/schemas/coordinator/fixture/fixture.v1alpha1.schema.json +apiVersion: id.registrystack.org/formats/coordinator/fixture/v1alpha1 +kind: CoordinatorFixture +id: unrecognised-answer-holds +admittedAt: '2026-12-01T00:00:00Z' +input: + reference: application-003 +replies: + draft: + - type: response + value: + status: 403 + body: {} +expect: + path: + - draft + state: uncertain diff --git a/crates/registry-coordinator/tests/fixtures/service-function/functions.rhai b/crates/registry-coordinator/tests/fixtures/service-function/functions.rhai new file mode 100644 index 0000000000..edda0e484b --- /dev/null +++ b/crates/registry-coordinator/tests/fixtures/service-function/functions.rhai @@ -0,0 +1,18 @@ +// Pure Function ABI: one typed object of named inputs, one typed output. +fn draft_request(args) { + #{reference: args.request.reference} +} + +// Only a recognised answer settles the call. Anything else is uncertain, so +// the run holds for same-command recovery instead of guessing. +fn draft_outcome(args) { + let status = args.response.status; + let body = args.response.body; + if status == 200 && "draftId" in body { + return #{state: "accepted", result: #{draftId: body.draftId}}; + } + if status == 422 && "reason" in body && body.reason == "not-eligible" { + return #{state: "refused", code: "not-eligible"}; + } + #{state: "uncertain"} +} diff --git a/crates/registry-coordinator/tests/fixtures/service-function/runtime.yaml b/crates/registry-coordinator/tests/fixtures/service-function/runtime.yaml new file mode 100644 index 0000000000..4122e81e01 --- /dev/null +++ b/crates/registry-coordinator/tests/fixtures/service-function/runtime.yaml @@ -0,0 +1,26 @@ +apiVersion: id.registrystack.org/formats/coordinator/runtime/v1alpha1 +kind: CoordinatorRuntimeConfig +secretProviders: + environment: {} + file: {root: /run/secrets/coordinator} +database: + runtimeUrlRef: secret:env/COORDINATOR_TEST_DATABASE_URL + migrationUrlRef: secret:env/COORDINATOR_TEST_DATABASE_URL +namespace: coordinator_notices +connections: + notices: + type: service-function + baseUrl: http://127.0.0.1:9020/ + function: draft-notice + authorization: + tokenEndpoint: http://127.0.0.1:8090/token + clientAssertionAudience: http://127.0.0.1:8090 + clientId: coordinator-functions + signingKeyRef: secret:file/function-client-key + resource: urn:example:notice-functions + scopes: [functions:invoke] + responseSchema: + type: object + required: [status, body] + properties: + status: {type: integer} diff --git a/crates/registry-coordinator/tests/fixtures/service-function/workflow.yaml b/crates/registry-coordinator/tests/fixtures/service-function/workflow.yaml new file mode 100644 index 0000000000..6527be60c3 --- /dev/null +++ b/crates/registry-coordinator/tests/fixtures/service-function/workflow.yaml @@ -0,0 +1,106 @@ +apiVersion: id.registrystack.org/formats/coordinator/project/v1alpha1 +kind: CoordinatorProject +project: + id: notice-draft + version: "1" + +types: + notice-input: + type: object + additionalProperties: false + required: [reference] + properties: + reference: {type: string, minLength: 1, maxLength: 64} + draft-response: + type: object + additionalProperties: false + required: [status, body] + properties: + status: {type: integer, minimum: 200, maximum: 499} + body: + type: object + additionalProperties: false + properties: + draftId: {type: string, minLength: 1, maxLength: 64} + reason: {type: string, minLength: 1, maxLength: 64} + draft: + type: object + additionalProperties: false + required: [draftId] + properties: + draftId: {type: string, minLength: 1, maxLength: 64} + draft-outcome: + oneOf: + - type: object + additionalProperties: false + required: [state, result] + properties: + state: {type: string, const: accepted} + result: {typeRef: draft} + - type: object + additionalProperties: false + required: [state, code] + properties: + state: {type: string, const: refused} + code: {type: string, enum: [not-eligible]} + - type: object + additionalProperties: false + required: [state] + properties: + state: {type: string, const: uncertain} + +transforms: + draft-request: + runtime: rhai + source: functions.rhai + entrypoint: draft_request + inputs: + request: {typeRef: notice-input} + output: {operationInput: draft-notice} + draft-outcome: + runtime: rhai + source: functions.rhai + entrypoint: draft_outcome + inputs: + command: {operationInput: draft-notice} + response: {operationOutput: draft-notice} + output: {typeRef: draft-outcome} + +operations: + draft-notice: + uses: service.invoke-function/v1 + connection: notices + serviceFunction: draft-notice + responseSchema: {typeRef: draft-response} + interpret: draft-outcome + +workflow: + input: {typeRef: notice-input} + deadlineSeconds: 900 + start: draft + steps: + draft: + label: Draft the notice + type: call + operation: draft-notice + input: + type: transform + transform: draft-request + inputs: + request: {type: input} + next: drafted + onDeclaredRefusal: not-drafted + drafted: + type: finish + outcome: drafted + output: + type: fields + fields: + draftId: {type: step, step: draft, path: /draftId} + not-drafted: + type: finish + outcome: not-drafted + output: {type: step, step: draft} + outcomes: + drafted: {typeRef: draft} + not-drafted: {operationRefusal: draft-notice} diff --git a/crates/registry-coordinator/tests/service_function.rs b/crates/registry-coordinator/tests/service_function.rs new file mode 100644 index 0000000000..9bd99a43f6 --- /dev/null +++ b/crates/registry-coordinator/tests/service_function.rs @@ -0,0 +1,253 @@ +// SPDX-License-Identifier: Apache-2.0 +//! `service.invoke-function/v1` over a loopback function host: one POST to the +//! one function the deployment binds, under the connection's own function-host +//! credential. That credential is never a product's, so the function holds no +//! record authority of its own. +use std::sync::Arc; + +use registry_coordinator::{ + contracts::contract, + external_http::{ExternalHttpConnection, ServiceFunctionConfig}, + protocol::{CallOutcome, Operation}, + runtime::{RuntimeConfig, API_VERSION, KIND}, +}; +use registry_platform_httputil::client::StaticToken; +use serde_json::{json, Value}; +use wiremock::{ + matchers::{body_json, header, method, path}, + Mock, MockServer, ResponseTemplate, +}; + +const REQUEST_ID: &str = "synthetic-function-request-id"; +const TOKEN: &str = "synthetic-function-host-token-canary"; + +fn response_schema() -> Value { + json!({ + "type":"object", "required":["status","body"], "additionalProperties":false, + "properties":{ + "status":{"type":"integer","minimum":100,"maximum":599}, + "body":{"anyOf":[{"type":"null"},{"type":"object","maxProperties":8}]} + } + }) +} + +fn function_authorization() -> Value { + json!({ + "tokenEndpoint":"http://127.0.0.1:9999/token", "clientId":"coordinator-functions", + "clientAssertionAudience":"http://127.0.0.1:9999", + "signingKeyRef":"secret:file/function-client-key", + "resource":"urn:example:notice-functions", + "scopes":["functions:invoke"] + }) +} + +fn binding(base: &str) -> Value { + json!({ + "baseUrl":base, "function":"draft-notice", + "authorization":function_authorization(), + "responseSchema":response_schema() + }) +} + +fn connection(base: &str) -> ExternalHttpConnection { + let config: ServiceFunctionConfig = serde_json::from_value(binding(base)).unwrap(); + let tokens = Arc::new(StaticToken::new(TOKEN).unwrap()); + ExternalHttpConnection::service_function(&config, tokens).unwrap() +} + +fn describe(outcome: &CallOutcome) -> String { + match outcome { + CallOutcome::Success(reply) => format!("success:{}", reply["status"]), + CallOutcome::Uncertain { code } => format!("uncertain:{code}"), + CallOutcome::Refused { code } => format!("refused:{code}"), + CallOutcome::Retryable { code, .. } => format!("retryable:{code}"), + CallOutcome::UncertainRetryable { code, .. } => format!("uncertain-retryable:{code}"), + _ => "other".into(), + } +} + +fn body() -> Value { + json!({"reference":"application-body-canary"}) +} + +#[tokio::test] +async fn a_call_posts_to_the_bound_function_with_the_function_host_credential() { + let server = MockServer::start().await; + Mock::given(method("POST")) + .and(path("/service/functions/draft-notice")) + .and(header("idempotency-key", REQUEST_ID)) + .and(header("content-type", "application/json")) + .and(header("authorization", format!("Bearer {TOKEN}").as_str())) + .and(body_json(body())) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({"draftId":"draft-001"}))) + .expect(1) + .mount(&server) + .await; + let connection = connection(&format!("{}/service/", server.uri())); + match connection.command(&body(), REQUEST_ID, false).await { + CallOutcome::Success(reply) => { + assert_eq!(reply, json!({"status":200,"body":{"draftId":"draft-001"}})); + assert_eq!( + contract(Operation::InvokeServiceFunction).check_output(&reply), + Ok(()) + ); + } + _ => panic!("the bound function answers"), + } + server.verify().await; +} + +#[tokio::test] +async fn a_refusal_is_handed_to_the_interpretation_and_a_redirect_is_not_followed() { + let server = MockServer::start().await; + Mock::given(method("POST")) + .and(path("/functions/draft-notice")) + .respond_with(ResponseTemplate::new(403).set_body_json(json!({}))) + .expect(1) + .mount(&server) + .await; + let refused = connection(&server.uri()) + .command(&body(), REQUEST_ID, false) + .await; + // The status reaches the pinned interpretation; the host claims no failure. + assert!( + matches!(&refused, CallOutcome::Success(reply) if reply["status"] == 403), + "{}", + describe(&refused) + ); + + let redirecting = MockServer::start().await; + Mock::given(method("POST")) + .and(path("/functions/draft-notice")) + .respond_with( + ResponseTemplate::new(307).insert_header("location", "/functions/publish-notice"), + ) + .expect(1) + .mount(&redirecting) + .await; + let redirected = connection(&redirecting.uri()) + .command(&body(), REQUEST_ID, false) + .await; + assert!( + matches!(&redirected, CallOutcome::Uncertain { code } if code == "external-redirect"), + "{}", + describe(&redirected) + ); + assert_eq!(redirecting.received_requests().await.unwrap().len(), 1); +} + +#[test] +fn the_function_name_is_one_local_identifier() { + for invalid in ["../admin", "draft/notice", "Draft", "", "a?b"] { + let mut document = binding("https://functions.example.test/"); + document["function"] = json!(invalid); + assert!( + serde_json::from_value::(document).is_err(), + "{invalid}" + ); + } +} + +fn breg_connection() -> Value { + json!({ + "type":"breg", "baseUrl":"http://127.0.0.1:9021", "profile":"coordinator", + "authorization":{ + "tokenEndpoint":"http://127.0.0.1:9999/token", + "clientAssertionAudience":"http://127.0.0.1:9999", + "clientId":"coordinator-registry", + "signingKeyRef":"secret:file/registry-client-key", + "resource":"urn:example:registry", + "scopes":["records:write"] + } + }) +} + +fn runtime_document() -> Value { + let mut function = binding("http://127.0.0.1:9020/"); + function["type"] = json!("service-function"); + json!({ + "apiVersion":API_VERSION,"kind":KIND, + "secretProviders":{"environment":{}}, + "database":{ + "runtimeUrlRef":"secret:env/COORDINATOR_FUNCTION_TEST_UNRESOLVED_DATABASE", + "migrationUrlRef":"secret:env/COORDINATOR_FUNCTION_TEST_UNRESOLVED_DATABASE" + }, + "namespace":"coordinator_function_test", + "connections":{"notices":function, "registry":breg_connection()} + }) +} + +fn load(document: &Value) -> registry_coordinator::Result { + let root = tempfile::tempdir().unwrap(); + let directory = root.path().canonicalize().unwrap(); + let mut document = document.clone(); + document["secretProviders"]["file"] = json!({"root":directory}); + let path = directory.join("runtime.yaml"); + std::fs::write(&path, serde_json::to_vec(&document).unwrap()).unwrap(); + RuntimeConfig::load(&path) +} + +#[test] +fn the_bound_function_is_part_of_the_binding_digest() { + let accepted = load(&runtime_document()).unwrap(); + let digest = accepted.binding_digest().unwrap(); + let mut changed = runtime_document(); + changed["connections"]["notices"]["function"] = json!("publish-notice"); + assert_ne!(load(&changed).unwrap().binding_digest().unwrap(), digest); +} + +#[test] +fn a_service_function_connection_requires_its_own_credential() { + let mut anonymous = runtime_document(); + anonymous["connections"]["notices"] + .as_object_mut() + .unwrap() + .remove("authorization"); + assert!(load(&anonymous).is_err()); + + let mut task = runtime_document(); + task["connections"]["notices"]["authorization"]["taskAuthority"] = json!({ + "baseUrl":"http://127.0.0.1:9022", "issuer":"https://identity.example.test", + "subject":"coordinator", "exchangeAudience":"urn:example:tasks", + "bootstrapResource":"urn:example:tasks" + }); + let error = load(&task) + .err() + .expect("a function call cannot acquire task authority"); + assert!( + error.field.as_deref().unwrap().contains("taskAuthority"), + "{error:?}" + ); +} + +#[test] +fn a_service_function_credential_is_never_a_product_credential() { + // The function host token must not be one a product accepts, and the + // connection must not reuse a product connection's client identity or key. + for (member, value) in [ + ("resource", "urn:example:registry"), + ("clientId", "coordinator-registry"), + ("signingKeyRef", "secret:file/registry-client-key"), + ] { + let mut document = runtime_document(); + document["connections"]["notices"]["authorization"][member] = json!(value); + let error = load(&document) + .err() + .unwrap_or_else(|| panic!("a reused product {member} is refused")); + assert!( + error + .field + .as_deref() + .unwrap_or_default() + .contains(&format!("/connections/notices/authorization/{member}")), + "{member}: {error:?}" + ); + assert!( + error + .suggested_action + .as_deref() + .is_some_and(|action| action.contains("product")), + "{member}: {error:?}" + ); + } +} diff --git a/crates/registry-coordinator/tests/service_function_postgres.rs b/crates/registry-coordinator/tests/service_function_postgres.rs new file mode 100644 index 0000000000..18c01dbe26 --- /dev/null +++ b/crates/registry-coordinator/tests/service_function_postgres.rs @@ -0,0 +1,221 @@ +// SPDX-License-Identifier: Apache-2.0 +//! `service.invoke-function/v1` over real HTTP and durable PostgreSQL: the +//! run records the step and its typed result, the function host receives the +//! frozen request id and the function host credential, and nothing an operator +//! reads carries the request body, request id or credential. +#![cfg(feature = "postgres-test")] + +use std::sync::{Arc, Mutex}; + +use async_trait::async_trait; +use registry_coordinator::{ + definition::Definition, + external_http::{ExternalHttpConnection, ServiceFunctionConfig}, + protocol::{AdapterSet, CallOutcome, CallRequest, Operation}, + store::Store, + worker::Worker, +}; +use registry_platform_httputil::client::StaticToken; +use serde_json::{json, Value}; +use uuid::Uuid; +use wiremock::{ + matchers::{body_json, header, header_exists, method, path}, + Mock, MockServer, ResponseTemplate, +}; + +const REFERENCE: &str = "application-body-canary"; +const TOKEN: &str = "synthetic-function-host-token-canary"; +const BINDING: &str = "service-function-binding"; + +/// The runtime's service function adapter, recording each frozen request id. +struct FunctionAdapter { + connection: ExternalHttpConnection, + keys: Arc>>, +} + +#[async_trait] +impl AdapterSet for FunctionAdapter { + fn binding_digest(&self) -> &str { + BINDING + } + + async fn call(&self, request: &CallRequest) -> CallOutcome { + self.call_attempt(request, None, false).await + } + + async fn call_attempt( + &self, + request: &CallRequest, + prepared: Option<&[u8]>, + final_attempt: bool, + ) -> CallOutcome { + assert_eq!(request.operation, Operation::InvokeServiceFunction); + assert_eq!(request.connection, "notices"); + assert!( + prepared.is_none(), + "a function call has no prepared evidence" + ); + let key = request + .idempotency_key + .clone() + .expect("a function call carries its frozen request id"); + self.keys.lock().unwrap().push(key.clone()); + self.connection + .command(&request.input, &key, final_attempt) + .await + } +} + +struct Harness { + _project: tempfile::TempDir, + definition: Definition, + store: Arc, + keys: Arc>>, +} + +impl Harness { + async fn new() -> Self { + let project = tempfile::tempdir().unwrap(); + let source = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("tests/fixtures/service-function"); + for name in ["workflow.yaml", "functions.rhai"] { + std::fs::copy(source.join(name), project.path().join(name)).unwrap(); + } + let definition = Definition::load(project.path()).expect("the function fixture compiles"); + let url = std::env::var("COORDINATOR_TEST_DATABASE_URL") + .expect("disposable PostgreSQL is required"); + let namespace = format!("coordinator_{}", Uuid::new_v4().simple()); + let store = Arc::new(Store::connect(&url, &namespace).await.unwrap()); + store.migrate().await.unwrap(); + Self { + _project: project, + definition, + store, + keys: Arc::default(), + } + } + + /// The operator's binding: the host, function and credential come only + /// from here. + fn worker(&self, base: &str) -> Worker { + let config: ServiceFunctionConfig = serde_json::from_value(json!({ + "baseUrl":base, "function":"draft-notice", + "responseSchema":{"type":"object"}, + "authorization":{ + "tokenEndpoint":"http://127.0.0.1:9999/token", + "clientId":"coordinator-functions", + "clientAssertionAudience":"http://127.0.0.1:9999", + "signingKeyRef":"secret:file/function-client-key", + "resource":"urn:example:notice-functions", "scopes":["functions:invoke"] + } + })) + .unwrap(); + let tokens = Arc::new(StaticToken::new(TOKEN).unwrap()); + let adapters = Arc::new(FunctionAdapter { + connection: ExternalHttpConnection::service_function(&config, tokens).unwrap(), + keys: self.keys.clone(), + }); + Worker::new(self.store.clone(), adapters) + } + + async fn run(&self, base: &str) -> Value { + let run = self + .store + .admit( + &self.definition, + json!({"reference":REFERENCE}), + "service-function-producer", + &Uuid::new_v4().to_string(), + BINDING, + ) + .await + .unwrap(); + let worker = self.worker(base); + let mut quiet = false; + for _ in 0..8 { + if !worker.tick().await.unwrap() { + quiet = true; + break; + } + } + assert!(quiet, "bounded workflow did not quiesce"); + let inspection = + serde_json::to_value(self.store.inspect(run, BINDING).await.unwrap()).unwrap(); + let status = serde_json::to_string(&self.store.status(run).await.unwrap()).unwrap(); + let keys = self.keys.lock().unwrap().clone(); + assert_eq!(keys.len(), 1, "one frozen request is sent once"); + for text in [inspection.to_string(), status] { + assert!(!text.contains(REFERENCE)); + assert!(!text.contains(TOKEN)); + assert!(!text.contains(keys[0].as_str())); + } + inspection + } +} + +#[tokio::test] +async fn an_accepted_function_call_records_the_step_and_its_typed_result() { + let h = Harness::new().await; + let server = MockServer::start().await; + Mock::given(method("POST")) + .and(path("/functions/draft-notice")) + .and(header_exists("idempotency-key")) + .and(header("authorization", format!("Bearer {TOKEN}").as_str())) + .and(body_json(json!({"reference":REFERENCE}))) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({"draftId":"draft-001"}))) + .expect(1) + .mount(&server) + .await; + let inspection = h.run(&server.uri()).await; + assert_eq!(inspection["run"]["state"], "finished"); + assert_eq!(inspection["run"]["outcome"], "drafted"); + assert_eq!(inspection["run"]["output"], json!({"draftId":"draft-001"})); + let effect = &inspection["effects"][0]; + assert_eq!(effect["state"], "accepted"); + assert_eq!(effect["step"], "draft"); + assert_eq!(effect["operation"]["id"], "service.invoke-function/v1"); + assert_eq!(effect["operation"]["product"], "service-function"); + let received = server.received_requests().await.unwrap(); + assert_eq!( + received[0].headers["idempotency-key"].to_str().unwrap(), + h.keys.lock().unwrap()[0], + "the function host receives the frozen request id" + ); +} + +#[tokio::test] +async fn a_declared_refusal_takes_the_workflow_refusal_route() { + let h = Harness::new().await; + let server = MockServer::start().await; + Mock::given(method("POST")) + .and(path("/functions/draft-notice")) + .respond_with(ResponseTemplate::new(422).set_body_json(json!({"reason":"not-eligible"}))) + .expect(1) + .mount(&server) + .await; + let inspection = h.run(&server.uri()).await; + assert_eq!(inspection["run"]["outcome"], "not-drafted"); + assert_eq!( + inspection["run"]["output"], + json!({"refusalCode":"not-eligible"}) + ); + assert_eq!( + inspection["effects"], + json!([]), + "a refusal claims no effect" + ); +} + +#[tokio::test] +async fn an_authority_refusal_the_interpretation_does_not_recognise_holds_the_run() { + let h = Harness::new().await; + let server = MockServer::start().await; + Mock::given(method("POST")) + .and(path("/functions/draft-notice")) + .respond_with(ResponseTemplate::new(403).set_body_json(json!({}))) + .expect(1) + .mount(&server) + .await; + let inspection = h.run(&server.uri()).await; + assert_ne!(inspection["run"]["state"], "finished", "{inspection}"); +} diff --git a/crates/registry-coordinator/tests/service_function_project.rs b/crates/registry-coordinator/tests/service_function_project.rs new file mode 100644 index 0000000000..59bb7054fa --- /dev/null +++ b/crates/registry-coordinator/tests/service_function_project.rs @@ -0,0 +1,345 @@ +// SPDX-License-Identifier: Apache-2.0 +//! Authoring, checking and synthetic scenarios for +//! `service.invoke-function/v1`. A project names one service function declared +//! in the service's `service.yaml`, a pure Transform that builds its body, and a +//! pure Transform that interprets the answer. The runtime file alone binds the +//! function host, the function and the credential. +use registry_coordinator::{ + definition::{Definition, Step}, + protocol::Operation, + scenarios, +}; +use serde_json::{json, Value}; +use std::{fs, path::Path, process::Command}; + +const WORKFLOW: &str = include_str!("fixtures/service-function/workflow.yaml"); +const FUNCTIONS: &str = include_str!("fixtures/service-function/functions.rhai"); +const RUNTIME: &str = include_str!("fixtures/service-function/runtime.yaml"); +const FIXTURE_DRAFTED: &str = include_str!("fixtures/service-function/fixtures/drafted.yaml"); +const FIXTURE_NOT_ELIGIBLE: &str = + include_str!("fixtures/service-function/fixtures/not-eligible.yaml"); +const FIXTURE_HOLDS: &str = + include_str!("fixtures/service-function/fixtures/unrecognised-answer-holds.yaml"); + +fn replaced(text: &str, replacements: &[(&str, &str)]) -> String { + let mut text = text.to_owned(); + for (from, to) in replacements { + assert!(text.contains(from), "{from}"); + text = text.replacen(from, to, 1); + } + text +} + +fn project(root: &Path, replacements: &[(&str, &str)]) { + fs::write(root.join("workflow.yaml"), replaced(WORKFLOW, replacements)).unwrap(); + fs::write(root.join("functions.rhai"), FUNCTIONS).unwrap(); +} + +fn cli(arguments: &[&str]) -> std::process::Output { + Command::new(env!("CARGO_BIN_EXE_coordinatorctl")) + .args(arguments) + .env_remove("COORDINATOR_TEST_DATABASE_URL") + .output() + .unwrap() +} + +fn check(root: &Path) -> (i32, Value) { + let output = cli(&[ + "--format", + "json", + "check", + "--project", + root.to_str().unwrap(), + ]); + let report = serde_json::from_slice(&output.stdout).unwrap_or_else(|_| { + panic!( + "a JSON check report: {}", + String::from_utf8_lossy(&output.stdout) + ) + }); + (output.status.code().unwrap(), report) +} + +/// The findings `check` reports for a project that must be refused. +fn refused(replacements: &[(&str, &str)]) -> Vec { + let root = tempfile::tempdir().unwrap(); + project(root.path(), replacements); + let (exit, report) = check(root.path()); + assert_eq!(exit, 1, "{report}"); + report["diagnostics"].as_array().unwrap().clone() +} + +fn finding<'a>(findings: &'a [Value], path: &str, expected: &[&str]) -> &'a Value { + let found = findings + .iter() + .find(|finding| finding["path"] == path) + .unwrap_or_else(|| panic!("no finding at {path}: {findings:#?}")); + let message = found["message"].as_str().unwrap(); + for text in expected { + assert!(message.contains(text), "{text}: {message}"); + } + found +} + +/// The project checked against one runtime file. +fn check_with_runtime(runtime: &str) -> (i32, Value) { + let root = tempfile::tempdir().unwrap(); + project(root.path(), &[]); + fs::write(root.path().join("runtime.yaml"), runtime).unwrap(); + check(root.path()) +} + +fn binding_finding(runtime: &str) -> Value { + let (exit, report) = check_with_runtime(runtime); + assert_eq!(exit, 1, "{report}"); + report["diagnostics"] + .as_array() + .unwrap() + .iter() + .find(|finding| finding["code"] == "coordinator.runtime.workflow-binding") + .unwrap_or_else(|| panic!("no workflow binding finding: {report}")) + .clone() +} + +#[test] +fn a_named_service_function_checks_and_explains_without_its_destination() { + let (exit, report) = check_with_runtime(RUNTIME); + assert_eq!(exit, 0, "{report}"); + let rendered = report.to_string(); + assert!(!rendered.contains("FUNCTION_CLIENT_KEY"), "{rendered}"); + + let root = tempfile::tempdir().unwrap(); + project(root.path(), &[]); + let output = cli(&[ + "--format", + "json", + "explain", + "--project", + root.path().to_str().unwrap(), + ]); + assert!(output.status.success()); + let text = String::from_utf8(output.stdout).unwrap(); + assert!(!text.contains("127.0.0.1"), "{text}"); + let explained: Value = serde_json::from_str(&text).unwrap(); + let draft = explained["steps"] + .as_array() + .unwrap() + .iter() + .find(|step| step["id"] == "draft") + .unwrap(); + assert_eq!(draft["uses"], "service.invoke-function/v1"); + assert_eq!(draft["product"], "service-function"); + assert_eq!(draft["mutating"], true); + assert_eq!(draft["recovery"], "same-command"); + assert_eq!(draft["onDeclaredRefusal"], "not-drafted"); + assert_eq!( + explained["operations"]["draft-notice"]["serviceFunction"], + "draft-notice" + ); + let http = &explained["operationContracts"]["service.invoke-function/v1"]["limits"]["http"]; + assert_eq!(http["maximumRequestBytes"], 65_536); + assert_eq!(http["redirects"], "refused"); +} + +#[test] +fn the_named_function_is_part_of_the_operation_revision() { + let root = tempfile::tempdir().unwrap(); + project(root.path(), &[]); + let definition = Definition::load(root.path()).unwrap(); + let operation = &definition.workflow.operations["draft-notice"]; + assert_eq!(operation.uses, Operation::InvokeServiceFunction); + assert_eq!(operation.service_function.as_deref(), Some("draft-notice")); + + let other = tempfile::tempdir().unwrap(); + project( + other.path(), + &[( + "serviceFunction: draft-notice", + "serviceFunction: publish-notice", + )], + ); + let renamed = Definition::load(other.path()).unwrap(); + assert_ne!( + renamed.workflow.operations["draft-notice"].revision, + operation.revision + ); + + // A restored snapshot cannot swap the named function. + let snapshot = definition.snapshot().unwrap(); + let swapped = snapshot.replacen( + "\"serviceFunction\":\"draft-notice\"", + "\"serviceFunction\":\"publish-notice\"", + 1, + ); + assert_ne!(swapped, snapshot); + assert!(Definition::from_snapshot(&swapped).is_err()); +} + +#[test] +fn a_missing_function_name_is_refused_at_the_operation() { + let findings = refused(&[(" serviceFunction: draft-notice\n", "")]); + finding( + &findings, + "/operations/draft-notice/serviceFunction", + &["service.invoke-function/v1", "serviceFunction"], + ); +} + +#[test] +fn a_function_name_must_be_a_local_identifier() { + let findings = refused(&[("serviceFunction: draft-notice", "serviceFunction: ../admin")]); + assert!( + findings.iter().any(|finding| finding["path"] + .as_str() + .unwrap_or_default() + .starts_with("/operations/draft-notice/serviceFunction")), + "{findings:#?}" + ); +} + +#[test] +fn only_the_service_function_operation_names_a_function() { + let findings = refused(&[( + "uses: service.invoke-function/v1", + "uses: external.command/v1", + )]); + finding( + &findings, + "/operations/draft-notice/serviceFunction", + &["only service.invoke-function/v1"], + ); +} + +#[test] +fn the_interpretation_is_required_on_the_service_function() { + let findings = refused(&[(" interpret: draft-outcome\n", "")]); + finding( + &findings, + "/operations/draft-notice/interpret", + &["service.invoke-function/v1", "interpret"], + ); +} + +#[test] +fn an_unbound_function_name_is_refused_against_the_runtime_binding() { + let unbound = + binding_finding(&RUNTIME.replace("function: draft-notice", "function: publish-notice")); + assert_eq!(unbound["path"], "/operations/draft-notice/serviceFunction"); + assert!( + unbound["message"] + .as_str() + .unwrap() + .contains("draft-notice"), + "{unbound}" + ); + + // No connection of the workflow's logical name. + let missing = binding_finding(&RUNTIME.replace(" notices:", " other-notices:")); + assert_eq!(missing["path"], "/connections/notices"); + + // An external HTTP connection cannot carry a service function call. + let external = binding_finding(&replaced( + RUNTIME, + &[ + ("type: service-function", "type: external-http"), + ( + " function: draft-notice\n", + " paths: [drafts]\n commandPath: drafts\n", + ), + ], + )); + assert_eq!(external["path"], "/connections/notices"); +} + +#[test] +fn the_workflow_cannot_name_a_destination_or_credential() { + for member in [ + " baseUrl: http://127.0.0.1:9030/\n", + " function: publish-notice\n", + " headers: {Authorization: Bearer x}\n", + " authorization: {token: x}\n", + ] { + let findings = refused(&[( + " interpret: draft-outcome\n", + &format!(" interpret: draft-outcome\n{member}"), + )]); + assert!( + findings.iter().any(|finding| finding["path"] + .as_str() + .unwrap_or_default() + .starts_with("/operations/draft-notice")), + "{member}: {findings:#?}" + ); + } +} + +fn scenario_reports(fixture: &str) -> Vec { + let root = tempfile::tempdir().unwrap(); + project(root.path(), &[]); + let definition = Definition::load(root.path()).unwrap(); + let document = scenarios::decode(fixture, "fixture.yaml").unwrap(); + scenarios::check(&definition, &document).unwrap() +} + +#[test] +fn scenarios_record_the_step_through_the_pinned_interpretation() { + let drafted = scenario_reports(FIXTURE_DRAFTED).remove(0); + assert_eq!(drafted.state, "completed"); + assert_eq!(drafted.output, Some(json!({"draftId":"draft-001"}))); + assert_eq!(drafted.call_attempts["draft"], 1); + assert_eq!(drafted.frozen_commands, 1); + + let refused = scenario_reports(FIXTURE_NOT_ELIGIBLE).remove(0); + assert_eq!(refused.outcome.as_deref(), Some("not-drafted")); + assert_eq!(refused.output, Some(json!({"refusalCode":"not-eligible"}))); + + // An authority refusal the interpretation does not recognise holds the + // run instead of reading as a settled answer. + let held = scenario_reports(FIXTURE_HOLDS).remove(0); + assert_eq!(held.state, "uncertain"); + assert_eq!(held.path, ["draft"]); +} + +#[test] +fn a_function_reply_reaches_its_result_only_through_the_interpret_transform() { + let root = tempfile::tempdir().unwrap(); + project(root.path(), &[]); + let definition = Definition::load(root.path()).unwrap(); + let source = replaced( + FIXTURE_DRAFTED, + &[( + " - type: response\n value:\n status: 200\n body:\n draftId: draft-001\n", + " - type: success\n value: {draftId: draft-001}\n", + )], + ); + let document = scenarios::decode(&source, "fixture.yaml").unwrap(); + let error = scenarios::check(&definition, &document) + .err() + .expect("a synthetic result skips the interpretation"); + assert_eq!(error.code, "scenario.reply"); + assert!( + error.message.contains("service.invoke-function/v1"), + "{}", + error.message + ); +} + +#[test] +fn the_step_output_is_the_accepted_result() { + let root = tempfile::tempdir().unwrap(); + project(root.path(), &[]); + let definition = Definition::load(root.path()).unwrap(); + let Some(Step::Call { call, .. }) = definition.workflow.steps.get("draft") else { + panic!("draft is a call"); + }; + let contract = definition.operation_contract(call).unwrap(); + assert!(contract + .check_output(&json!({"draftId":"draft-001"})) + .is_ok()); + assert!(contract + .check_output(&json!({"status":200,"body":{"draftId":"draft-001"}})) + .is_err()); + assert!(contract + .check_refusal(&json!({"refusalCode":"not-eligible"})) + .is_ok()); +} diff --git a/docs/site/src/content/docs/configure/coordinator.mdx b/docs/site/src/content/docs/configure/coordinator.mdx index 976f784ddf..5583798052 100644 --- a/docs/site/src/content/docs/configure/coordinator.mdx +++ b/docs/site/src/content/docs/configure/coordinator.mdx @@ -743,7 +743,7 @@ A selector that needs a verified claim and no field values cannot be reached by | 401, 403, or 404 other than `lookup.unresolved` | A failure of the lookup through the ordinary error path, never `unresolved`. | BReg answers one value-free `lookup.unresolved` whether no record matched, two matched, the row is hidden from the profile, or a claim was missing, so neither Coordinator nor the workflow can tell those apart. -For that reason `check` refuses an `onDeclaredRefusal` that routes `unresolved` straight to a step that creates or changes a record, with `definition.unresolved-route`: `breg.invoke-action/v1`, `breg.start-proposal/v1`, `breg.submit-proposal/v1`, and `external.command/v1`, whose effect Coordinator cannot see. +For that reason `check` refuses an `onDeclaredRefusal` that routes `unresolved` straight to a step that creates or changes a record, with `definition.unresolved-route`: `breg.invoke-action/v1`, `breg.start-proposal/v1`, `breg.submit-proposal/v1`, `external.command/v1`, and `service.invoke-function/v1`, whose effect Coordinator cannot see. "Not found, so create" makes a duplicate when two records match or one is hidden. Route to a finish, another read, or a Casework review request, and change data from a later step once a person or that read has decided. Only the direct route is refused: a step that cannot write a record (a Casework review request, a message, a scheduling call, a proposal cancellation) is allowed, and so is a mutation later on the path. @@ -942,6 +942,30 @@ The operation has no original-result receipt, so `reconcile` cannot settle it. crates/registry-coordinator/tests/external_command_project.rs scenario.reply; crates/registry-coordinator/tests/external_command_postgres.rs. */} +## Call a service function + +`service.invoke-function/v1` calls one function the service declares in `service.yaml`. +The alias names it with `serviceFunction`; the runtime connection binds the function host, the same function, and a credential for that host alone. +The call is an external command in every other respect: a pure Transform builds the JSON body, a required `interpret` Transform reads the `{status, body}` answer, and recovery, retries and fixtures follow [Call an external provider](#call-an-external-provider). + +```yaml +operations: + draft-notice: + uses: service.invoke-function/v1 + connection: notice-drafts + serviceFunction: draft-notice + responseSchema: {typeRef: draft-response} + interpret: draft-outcome +``` + +`check` refuses an alias without `serviceFunction`, a `serviceFunction` on any other operation, and an alias whose connection binds another function. +A function holds no record authority: the function host credential is never one a product accepts. +Write any record change as its own step, such as a `breg.invoke-action/v1` call, under the run's BReg connection. +The reference page covers the [connection](../../reference/coordinator-configuration/#service-function-connections). + +{/* Evidence: crates/registry-coordinator/tests/service_function_project.rs; + crates/registry-coordinator/tests/service_function_postgres.rs. */} + ## Import record and template contracts Import a BReg record schema when you want fixtures to reject field names the record type does not serve. diff --git a/docs/site/src/content/docs/reference/coordinator-configuration.mdx b/docs/site/src/content/docs/reference/coordinator-configuration.mdx index 7157bba68b..ef328524d3 100644 --- a/docs/site/src/content/docs/reference/coordinator-configuration.mdx +++ b/docs/site/src/content/docs/reference/coordinator-configuration.mdx @@ -105,7 +105,7 @@ at most {reference.operations[0].maximum_call_attempts} attempts of ## Connections `runtime.yaml` declares every logical connection in one `connections` map, at most sixteen names. -Each entry selects its complete contract with `type`: `breg`, `casework-review-producer`, `messaging`, `payments`, `scheduling`, `external-http`, or `evaluation`. +Each entry selects its complete contract with `type`: `breg`, `casework-review-producer`, `messaging`, `payments`, `scheduling`, `external-http`, `service-function`, or `evaluation`. The [deployment runbook](../../operate/coordinator/) covers the rest of the `deployment` block. {/* Evidence: crates/registry-coordinator/src/runtime.rs ConnectionConfig. */} @@ -202,6 +202,49 @@ Coordinator trusts a 429 to mean the provider did not process the command, so th crates/registry-coordinator/src/runtime.rs command_path; crates/registry-coordinator/tests/external_command.rs. */} +### Service function connections + +A `service-function` connection serves `service.invoke-function/v1` and binds exactly one service function, as the service's `service.yaml` declares it. +Set `baseUrl` to the function host, `function` to the function's identifier, the required `authorization`, and the required `responseSchema` for `{status, body}`. +Coordinator sends each call as one POST to `functions/` under `baseUrl`. +The attempt timeout, response size and request body bounds are those of an external command. +Use HTTPS for institutional endpoints; HTTP requires numeric loopback. +`authorization.taskAuthority` is refused. + +Add one connection for each function a workflow calls. +The credential is for the function host alone: its `resource`, `clientId` and `signingKeyRef` must differ from those of every product and external connection in the same file, and the runtime refuses a match. +A function therefore holds no record authority through the call, and a record change stays a separate BReg step in the workflow. + +```yaml +connections: + notice-drafts: + type: service-function + baseUrl: https://functions.example.org/ + function: draft-notice + authorization: + tokenEndpoint: https://issuer.example.org/oauth/token + clientAssertionAudience: https://issuer.example.org + clientId: coordinator-notice-functions + signingKeyRef: secret:file/notice-functions-jwk + resource: https://functions.example.org + scopes: + - functions:draft-notice + responseSchema: + type: object + required: + - status + - body + properties: + status: + type: integer +``` + +The function host must pass the `Idempotency-Key` it receives to any effect the function makes, as an external provider must deduplicate on it. + +{/* Evidence: crates/registry-coordinator/src/external_http.rs ServiceFunctionConfig; + crates/registry-coordinator/src/runtime.rs function_credential_findings; + crates/registry-coordinator/tests/service_function.rs. */} + ### Payment connections A `payments` connection serves the native payment operations over the Registry Adapter payment host. diff --git a/docs/site/src/content/docs/security/coordinator.mdx b/docs/site/src/content/docs/security/coordinator.mdx index f8d21c5075..39d7eae5da 100644 --- a/docs/site/src/content/docs/security/coordinator.mdx +++ b/docs/site/src/content/docs/security/coordinator.mdx @@ -13,15 +13,15 @@ standards_referenced: [] This page states what Registry Coordinator holds, what it does not hold, and what you must do for its guarantees to hold. -Each guarantee carries a stable identifier from `COORDINATOR-INV-01` to `COORDINATOR-INV-15`, and -each accepted residual risk one from `COORDINATOR-RES-01` to `COORDINATOR-RES-27`. +Each guarantee carries a stable identifier from `COORDINATOR-INV-01` to `COORDINATOR-INV-17`, and +each accepted residual risk one from `COORDINATOR-RES-01` to `COORDINATOR-RES-28`. Terms follow [Author a Coordinator workflow](../../configure/coordinator/). Deployment steps are in [Deploy Registry Coordinator](../../operate/coordinator/). ## Scope and trust boundaries - The operator owns the runtime configuration: connection base URLs, the external command path, - credentials, issuer settings, the Base Registry Engine (BReg) connection profile and the Registry + the service function each `service-function` connection binds, credentials, issuer settings, the Base Registry Engine (BReg) connection profile and the Registry Adapter payment connection. Operator configuration is trusted; workflow data is not. - A workflow author writes a project that Coordinator freezes into a definition. @@ -30,6 +30,8 @@ Deployment steps are in [Deploy Registry Coordinator](../../operate/coordinator/ operation catalogue does. - Providers decide every effect a run requests: Registry Casework, Registry Scheduling, BReg, the Registry Adapter payment host and external HTTP providers. + A service function is not a provider of record authority: Coordinator calls it with a credential + for its function host only, so a record change stays a separate step to the owning product. Coordinator holds workload identity, not decision authority, and each receiving product still authorises the call. - Coordinator verifies the access token against the matching entry in @@ -860,6 +862,67 @@ unknown, a timeout or a missing receipt authorises release or replacement. provider_confirmation_report_is_one_exact_keyed_command, disbursement_completion_settles_only_terminal_exactly_bound_state. */} +### COORDINATOR-INV-17: a service function call holds no product authority + +Threat: `service.invoke-function/v1` calls code a service declares in `service.yaml`, outside every +product's authorization. +A workflow could steer the call to another function, host or credential. +A deployment could hand the function host a token a product accepts, such as the BReg connection's +credential, so a function that forwards its incoming bearer would change records under the +Coordinator's product authority without a product step in the workflow. + +Enforcement: + +- The workflow names the function (`serviceFunction`) and supplies only the JSON body a pure + Transform builds. + The runtime connection (`type: service-function`) fixes the function host `baseUrl`, the one + bound `function`, and the credential. + Coordinator sends one POST to `functions/` under `baseUrl` and nowhere else; the + function name is a local identifier, so it cannot add a path segment. +- `coordinatorctl check` refuses an alias without `serviceFunction`, a `serviceFunction` on any + other operation, and an alias whose function is not the one its connection binds + (`workflow-binding`). + A connection of another type cannot carry the call. + The function name is part of the Operation revision and the connection's binding digest, so a + live Run cannot be moved to another function. +- The connection requires its own `authorization` and refuses `taskAuthority`. + The runtime refuses a `resource`, `clientId` or `signingKeyRef` equal to any product or external + connection's credential (`coordinator.runtime-config.refused` at that member), so the function + host token is never one a product accepts. + A function that forwards that token to BReg is refused by BReg; any record change is a separate + BReg Action or Proposal step under the run's own connection. +- The call is an external command in every other respect (COORDINATOR-INV-03): the request id is + frozen before the first send and sent as `Idempotency-Key`, redirects are never followed, bodies + and responses are bounded, an ambiguous exchange holds the run, and only the pinned + interpretation Transform turns the response into an accepted result or a declared refusal. + Nothing an operator reads carries the body, request id or credential. + +Refused: a workflow-chosen function, host, header or credential; a function the connection does not +bind; an anonymous function connection; a function credential shared with a product or external +connection; task authority on a function connection. + +{/* Evidence: crates/registry-coordinator/src/runtime.rs function_credential_findings, + validate_workflow_effect_bindings; + crates/registry-coordinator/src/external_http.rs ServiceFunctionConfig; + crates/registry-coordinator/tests/service_function.rs + a_call_posts_to_the_bound_function_with_the_function_host_credential, + a_refusal_is_handed_to_the_interpretation_and_a_redirect_is_not_followed, + the_function_name_is_one_local_identifier, + the_bound_function_is_part_of_the_binding_digest, + a_service_function_connection_requires_its_own_credential, + a_service_function_credential_is_never_a_product_credential; + crates/registry-coordinator/tests/service_function_project.rs + a_missing_function_name_is_refused_at_the_operation, + only_the_service_function_operation_names_a_function, + an_unbound_function_name_is_refused_against_the_runtime_binding, + the_workflow_cannot_name_a_destination_or_credential, + the_named_function_is_part_of_the_operation_revision, + a_function_reply_reaches_its_result_only_through_the_interpret_transform; + crates/registry-coordinator/tests/service_function_postgres.rs + an_accepted_function_call_records_the_step_and_its_typed_result, + a_declared_refusal_takes_the_workflow_refusal_route, + an_authority_refusal_the_interpretation_does_not_recognise_holds_the_run. */} + ## Operator obligations The guarantees hold only when you meet these obligations. @@ -914,6 +977,11 @@ The residuals refer to them by number. identities. Investigate an unresolved original-request receipt before any same-command recovery or cancellation decision (COORDINATOR-INV-16). +15. Give each `service-function` connection a client, signing key and resource that only its + function host accepts, scoped to the one function it binds, and add one connection per bound + function. + Run the function host so that the function forwards the `Idempotency-Key` it receives to any + effect it makes, as obligation 1 asks of an external provider (COORDINATOR-INV-17). {/* Evidence: crates/registry-coordinator/tests/external_command_postgres.rs a_lost_acknowledgement_holds_and_retry_same_sends_the_same_command; @@ -1214,6 +1282,21 @@ Each residual names the condition under which it applies, its consequence, and t a_run_whose_retained_definition_does_not_restore_is_held_alone, an_unreadable_snapshot_or_store_outage_fails_the_check_and_holds_nothing. */} +### COORDINATOR-RES-28: a function credential is distinct, not proven unusable at a product + +- Condition: a `service-function` connection names a resource, client and signing key no other + connection in the same runtime file uses. +- Consequence: Coordinator cannot see the authorization server or the products of other + deployments, so it cannot prove that the function host token is refused everywhere else. + An authorization server that mints the same audience for that resource, or a product that + accepts the function host resource, would give a function product authority. +- Mitigation: obligation 15; register the function host resource only for the function host at the + authorization server, and never list it as a product audience. + +{/* Evidence: crates/registry-coordinator/src/runtime.rs function_credential_findings; + crates/registry-coordinator/tests/service_function.rs + a_service_function_credential_is_never_a_product_credential. */} + ## Report a vulnerability Report a suspected vulnerability through the process in diff --git a/products/coordinator/CHANGELOG.md b/products/coordinator/CHANGELOG.md index 6f74ab51fe..b8b6d0ec93 100644 --- a/products/coordinator/CHANGELOG.md +++ b/products/coordinator/CHANGELOG.md @@ -3,6 +3,7 @@ ## Unreleased - BREAKING: Name the bounded Rhai computations in a Coordinator workflow Transforms. Rename `functions` to `transforms` and use `type: transform` with a `transform` member in mappings. Use `coordinatorctl explain transforms` for the interpreter helpers and update diagnostic consumers from `coordinator.function.*` to `coordinator.transform.*`. Retained definition snapshots keep their reader and revision format. +- Add `service.invoke-function/v1`, which calls one service function declared in `service.yaml`. The workflow names it with `serviceFunction`. A `type: service-function` runtime connection binds the function host, that one function and a credential for the host alone. `check` refuses a missing name, a name the connection does not bind, and a function credential whose resource, client or signing key matches a product or external connection, so a function holds no record authority. Calls follow external command recovery and require an `interpret` Transform. ## 0.49.0 - 2026-12-01 diff --git a/products/coordinator/generated/openapi/coordinator.openapi.json b/products/coordinator/generated/openapi/coordinator.openapi.json index 2d32d9e97c..c8bab9ae5f 100644 --- a/products/coordinator/generated/openapi/coordinator.openapi.json +++ b/products/coordinator/generated/openapi/coordinator.openapi.json @@ -491,7 +491,8 @@ "payments.record-receipt/v1", "payments.request-disbursement/v1", "payments.read-disbursement/v1", - "payments.record-provider-confirmation/v1" + "payments.record-provider-confirmation/v1", + "service.invoke-function/v1" ], "type": "string" }, diff --git a/products/coordinator/generated/operations/README.md b/products/coordinator/generated/operations/README.md index 57754e4b99..d958a37aa5 100644 --- a/products/coordinator/generated/operations/README.md +++ b/products/coordinator/generated/operations/README.md @@ -36,6 +36,7 @@ Each catalog operation has an input contract, the type its adapter decodes, and | [`payments.request-disbursement/v1`](#payments.request-disbursement/v1) | 1 | `payments` | mutation | required | none | hold-after-dispatch | read | none | | [`payments.read-disbursement/v1`](#payments.read-disbursement/v1) | 1 | `payments` | read | none | none | read-again | none | none | | [`payments.record-provider-confirmation/v1`](#payments.record-provider-confirmation/v1) | 1 | `payments` | mutation | required | none | same-command | none | none | +| [`service.invoke-function/v1`](#service.invoke-function/v1) | 1 | `service-function` | mutation | required | none | same-command | none | [`onDeclaredRefusal`](service.invoke-function.v1.declared-refusal.schema.json) | ## breg.read-record/v1 @@ -2352,6 +2353,73 @@ Output ([`payments.record-provider-confirmation.v1.output.schema.json`](payments No other members are accepted. +## service.invoke-function/v1 + +Host execution and completion contract: + +```json +{ + "authority": "current-bound-connection-authority", + "completionObservation": null, + "connectionInterface": "service-function", + "identity": { + "effect": "mutation", + "id": "service.invoke-function/v1", + "keyRequirement": "required", + "product": "service-function", + "readReceipt": false, + "recovery": "same-command", + "requiresPreparation": false, + "version": 1 + }, + "limits": { + "attemptTimeoutSeconds": 10, + "http": { + "attemptTimeoutMilliseconds": 2000, + "connectionMayLowerLimits": true, + "maximumMutationRetries": 0, + "maximumRequestBytes": 65536, + "maximumResponseBytes": 65536, + "redirects": "refused" + }, + "maximumCallAttempts": 10, + "maximumCallRetryDelaySeconds": 300, + "maximumConcurrentAttemptsPerRun": 1, + "maximumPreparationBytes": 65536, + "maximumRunDurationSeconds": 31536000, + "value": { + "maximumArrayItems": 256, + "maximumBytes": 131072, + "maximumDepth": 32, + "maximumNodes": 4096, + "maximumObjectMembers": 256, + "maximumStringBytes": 16384 + } + } +} +``` + +Input ([`service.invoke-function.v1.input.schema.json`](service.invoke-function.v1.input.schema.json)): + +Any JSON value. + +Output ([`service.invoke-function.v1.output.schema.json`](service.invoke-function.v1.output.schema.json)): + +| Member | Type | Required | +|---|---|---| +| `body` | any | yes | +| `status` | integer | yes | + +Other members are tolerated. + +Declared-refusal output ([`service.invoke-function.v1.declared-refusal.schema.json`](service.invoke-function.v1.declared-refusal.schema.json)): + +| Member | Type | Required | +|---|---|---| +| `refusalCode` | string | yes | + +No other members are accepted. + ## Completions A `wait-for` step observes a named completion on an accepted Operation. The host reads the authoritative result under current connection authority, using the saved command and exact correlation. A terminal result continues through `next` as the step output. A step reached by `onTimeout` has no completion output. Authenticated signals only wake an eligible read and never carry the result. Durable read spacing, the observation budget and the original deadline survive retries and restarts. diff --git a/products/coordinator/generated/operations/catalog.json b/products/coordinator/generated/operations/catalog.json index d152b1b43c..78079b1767 100644 --- a/products/coordinator/generated/operations/catalog.json +++ b/products/coordinator/generated/operations/catalog.json @@ -7712,5 +7712,91 @@ "title": "scheduling.reschedule-appointment/v1 output", "type": "object" } + }, + "service.invoke-function/v1": { + "declaredRefusal": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "description": "One package-declared business refusal from a validated product response.\n\nThe code is deliberately absent from `Debug`; callers must opt in to reading\nor serializing it for an authored refusal branch.", + "properties": { + "refusalCode": { + "maxLength": 128, + "minLength": 1, + "pattern": "^[^\\u0000-\\u001F\\u007F-\\u009F]+$", + "type": "string" + } + }, + "required": [ + "refusalCode" + ], + "title": "service.invoke-function/v1 declared-refusal output", + "type": "object" + }, + "host": { + "authority": "current-bound-connection-authority", + "completionObservation": null, + "connectionInterface": "service-function", + "identity": { + "effect": "mutation", + "id": "service.invoke-function/v1", + "keyRequirement": "required", + "product": "service-function", + "readReceipt": false, + "recovery": "same-command", + "requiresPreparation": false, + "version": 1 + }, + "limits": { + "attemptTimeoutSeconds": 10, + "http": { + "attemptTimeoutMilliseconds": 2000, + "connectionMayLowerLimits": true, + "maximumMutationRetries": 0, + "maximumRequestBytes": 65536, + "maximumResponseBytes": 65536, + "redirects": "refused" + }, + "maximumCallAttempts": 10, + "maximumCallRetryDelaySeconds": 300, + "maximumConcurrentAttemptsPerRun": 1, + "maximumPreparationBytes": 65536, + "maximumRunDurationSeconds": 31536000, + "value": { + "maximumArrayItems": 256, + "maximumBytes": 131072, + "maximumDepth": 32, + "maximumNodes": 4096, + "maximumObjectMembers": 256, + "maximumStringBytes": 16384 + } + } + }, + "input": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": true, + "description": "The request body, sent as the exact JSON object to the one service function the connection binds.", + "title": "service.invoke-function/v1 input", + "type": "object" + }, + "output": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "description": "The bounded function host response. The operation's interpret Transform receives it with the request body and returns the step result, a declared refusal, or an uncertain outcome.", + "properties": { + "body": { + "description": "The parsed JSON response body, or null for an empty body." + }, + "status": { + "maximum": 65535, + "minimum": 0, + "type": "integer" + } + }, + "required": [ + "status", + "body" + ], + "title": "service.invoke-function/v1 output", + "type": "object" + } } } diff --git a/products/coordinator/generated/operations/service.invoke-function.v1.declared-refusal.schema.json b/products/coordinator/generated/operations/service.invoke-function.v1.declared-refusal.schema.json new file mode 100644 index 0000000000..9db6c263f8 --- /dev/null +++ b/products/coordinator/generated/operations/service.invoke-function.v1.declared-refusal.schema.json @@ -0,0 +1,18 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "description": "One package-declared business refusal from a validated product response.\n\nThe code is deliberately absent from `Debug`; callers must opt in to reading\nor serializing it for an authored refusal branch.", + "properties": { + "refusalCode": { + "maxLength": 128, + "minLength": 1, + "pattern": "^[^\\u0000-\\u001F\\u007F-\\u009F]+$", + "type": "string" + } + }, + "required": [ + "refusalCode" + ], + "title": "service.invoke-function/v1 declared-refusal output", + "type": "object" +} diff --git a/products/coordinator/generated/operations/service.invoke-function.v1.input.schema.json b/products/coordinator/generated/operations/service.invoke-function.v1.input.schema.json new file mode 100644 index 0000000000..f430a06dd7 --- /dev/null +++ b/products/coordinator/generated/operations/service.invoke-function.v1.input.schema.json @@ -0,0 +1,7 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": true, + "description": "The request body, sent as the exact JSON object to the one service function the connection binds.", + "title": "service.invoke-function/v1 input", + "type": "object" +} diff --git a/products/coordinator/generated/operations/service.invoke-function.v1.output.schema.json b/products/coordinator/generated/operations/service.invoke-function.v1.output.schema.json new file mode 100644 index 0000000000..f8f5edb3e6 --- /dev/null +++ b/products/coordinator/generated/operations/service.invoke-function.v1.output.schema.json @@ -0,0 +1,20 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "description": "The bounded function host response. The operation's interpret Transform receives it with the request body and returns the step result, a declared refusal, or an uncertain outcome.", + "properties": { + "body": { + "description": "The parsed JSON response body, or null for an empty body." + }, + "status": { + "maximum": 65535, + "minimum": 0, + "type": "integer" + } + }, + "required": [ + "status", + "body" + ], + "title": "service.invoke-function/v1 output", + "type": "object" +} diff --git a/products/coordinator/generated/project/project.schema.json b/products/coordinator/generated/project/project.schema.json index 533b3328f0..022a923337 100644 --- a/products/coordinator/generated/project/project.schema.json +++ b/products/coordinator/generated/project/project.schema.json @@ -347,7 +347,7 @@ }, "interpret": { "$ref": "#/$defs/LocalId", - "description": "The typed pure Transform that interprets an external command's provider\nresponse into an accepted result, a declared refusal or an uncertain\noutcome. Required on, and accepted only on, `external.command/v1`." + "description": "The typed pure Transform that interprets an external command's provider\nresponse into an accepted result, a declared refusal or an uncertain\noutcome. Required on, and accepted only on, `external.command/v1` and\n`service.invoke-function/v1`." }, "label": { "$ref": "#/$defs/DisplayText", @@ -359,7 +359,11 @@ }, "responseSchema": { "$ref": "#/$defs/Schema", - "description": "An optional typed response specialization for the bounded external GET\nor external command Operation." + "description": "An optional typed response specialization for the bounded external GET\nor external command Operation, or the service function Operation." + }, + "serviceFunction": { + "$ref": "#/$defs/LocalId", + "description": "The one service function `service.invoke-function/v1` calls, as the\nservice's `service.yaml` declares it. Required on, and accepted only\non, that Operation. The runtime connection binds its host and\ncredential; the workflow supplies neither." }, "template": { "$ref": "#/$defs/TemplateReference", @@ -961,7 +965,8 @@ "payments.record-receipt/v1", "payments.request-disbursement/v1", "payments.read-disbursement/v1", - "payments.record-provider-confirmation/v1" + "payments.record-provider-confirmation/v1", + "service.invoke-function/v1" ], "type": "string" }, diff --git a/products/coordinator/generated/runtime/runtime.schema.json b/products/coordinator/generated/runtime/runtime.schema.json index 26f0669f7e..b0217fceec 100644 --- a/products/coordinator/generated/runtime/runtime.schema.json +++ b/products/coordinator/generated/runtime/runtime.schema.json @@ -471,6 +471,59 @@ ], "type": "object" }, + { + "additionalProperties": false, + "description": "One service function declared in the service's `service.yaml`, bound by the\ndeployment to its function host and to a credential for that host alone.\nThe workflow names the function; it never supplies the destination or the\ncredential. The function host serves the function at `functions/`\nunder the base URL.", + "properties": { + "attemptTimeoutMilliseconds": { + "default": 2000, + "format": "uint64", + "maximum": 2000, + "minimum": 1, + "type": "integer" + }, + "authorization": { + "$ref": "#/$defs/AuthorizationConfig", + "description": "The function host credential. Its client, key and resource are the\nfunction host's own and are never a product connection's, so the token\ncarries no product authority.", + "not": { + "required": [ + "taskAuthority" + ] + } + }, + "baseUrl": { + "$ref": "#/$defs/Url", + "pattern": "^[^\\s\\\\]+$" + }, + "function": { + "$ref": "#/$defs/LocalId", + "description": "The one function this connection binds, as `service.yaml` declares it." + }, + "maximumResponseBytes": { + "default": 65536, + "format": "uint64", + "maximum": 65536, + "minimum": 1, + "type": "integer" + }, + "responseSchema": { + "description": "Local JSON Schema for the complete {status, body} response.", + "x-registry-foreign": "json-schema-2020-12" + }, + "type": { + "const": "service-function", + "type": "string" + } + }, + "required": [ + "type", + "baseUrl", + "function", + "authorization", + "responseSchema" + ], + "type": "object" + }, { "additionalProperties": false, "properties": { diff --git a/products/coordinator/scripts/test-postgres.sh b/products/coordinator/scripts/test-postgres.sh index 85f5595ff3..517301e015 100755 --- a/products/coordinator/scripts/test-postgres.sh +++ b/products/coordinator/scripts/test-postgres.sh @@ -33,7 +33,7 @@ cargo test --locked -p registry-coordinator --features postgres-test --lib \ --test postgres_state --test service_deadline --test recovery_audit --test read_lease_recovery \ --test messaging_integration --test process_restart \ --test deployment_postgres --test refusal_golden --test review_wait_postgres \ - --test external_wait_postgres --test external_command_postgres \ + --test external_wait_postgres --test external_command_postgres --test service_function_postgres \ --test standalone_review_postgres --test compare_worker_postgres \ --test read_in_force_postgres --test breg_proposal_wait_postgres \ --test calendar_trigger_authoring From f5b66b41dc2f97487b231156cf5680afe8e57601 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 20:40:35 +0000 Subject: [PATCH 130/183] feat(coordinator): accept a function host key as the service function credential A service-function connection names exactly one credential: an OAuth client or a hostKeyRef key only the function host accepts, sent as the bearer. rstack dev supplies one per run for the preview function host. A host key that matches a product, external or evaluation credential is refused. Signed-off-by: Jeremi Joslin --- crates/registry-coordinator/src/adapters.rs | 39 +++++-- .../registry-coordinator/src/external_http.rs | 30 +++-- crates/registry-coordinator/src/runtime.rs | 86 ++++++++++----- .../tests/service_function.rs | 104 ++++++++++++++++++ .../reference/coordinator-configuration.mdx | 6 +- .../src/content/docs/security/coordinator.mdx | 15 ++- .../generated/runtime/runtime.schema.json | 7 +- 7 files changed, 235 insertions(+), 52 deletions(-) diff --git a/crates/registry-coordinator/src/adapters.rs b/crates/registry-coordinator/src/adapters.rs index efe16b71d2..b706989435 100644 --- a/crates/registry-coordinator/src/adapters.rs +++ b/crates/registry-coordinator/src/adapters.rs @@ -216,16 +216,35 @@ impl HttpAdapters { continue; } if let Some(binding) = configured.service_function() { - let auth = &binding.authorization; - let key_bytes = secrets - .resolve_reference(&auth.signing_key_ref) - .map_err(|_| config_error())?; - let key_text = - std::str::from_utf8(key_bytes.expose_secret()).map_err(|_| config_error())?; - let key = PrivateJwk::parse(key_text).map_err(|_| config_error())?; - let provider = Arc::new( - tokens(auth, key, &auth.resource, &auth.scopes).map_err(|_| config_error())?, - ); + let provider: Arc = + match (&binding.authorization, &binding.host_key_ref) { + (Some(auth), None) => { + let key_bytes = secrets + .resolve_reference(&auth.signing_key_ref) + .map_err(|_| config_error())?; + let key_text = std::str::from_utf8(key_bytes.expose_secret()) + .map_err(|_| config_error())?; + let key = PrivateJwk::parse(key_text).map_err(|_| config_error())?; + Arc::new( + tokens(auth, key, &auth.resource, &auth.scopes) + .map_err(|_| config_error())?, + ) + } + (None, Some(reference)) => { + let key = secrets + .resolve_reference(reference) + .map_err(|_| config_error())?; + let text = std::str::from_utf8(key.expose_secret()) + .map_err(|_| config_error())?; + Arc::new( + registry_platform_httputil::client::StaticToken::new( + text.trim_end_matches('\n'), + ) + .map_err(|_| config_error())?, + ) + } + _ => return Err(config_error()), + }; let connection = crate::external_http::ExternalHttpConnection::service_function( binding, provider, )?; diff --git a/crates/registry-coordinator/src/external_http.rs b/crates/registry-coordinator/src/external_http.rs index 51ca1b64ae..674ce038f8 100644 --- a/crates/registry-coordinator/src/external_http.rs +++ b/crates/registry-coordinator/src/external_http.rs @@ -19,6 +19,7 @@ use serde_json::Value; use url::{Host, Url}; use crate::{protocol::CallOutcome, runtime::AuthorizationConfig, CoordinatorError, Result}; +use registry_platform_config::SecretReference; /// The reviewed directory contract and environment-specific destination. #[derive(Clone, Serialize, Deserialize)] @@ -68,11 +69,18 @@ pub struct ServiceFunctionConfig { pub base_url: Url, /// The one function this connection binds, as `service.yaml` declares it. pub function: LocalId, - /// The function host credential. Its client, key and resource are the - /// function host's own and are never a product connection's, so the token - /// carries no product authority. + /// An OAuth client credential for the function host. Its client, key and + /// resource are the function host's own and are never a product + /// connection's, so the token carries no product authority. Exactly one of + /// `authorization` and `hostKeyRef` is required. + #[serde(default, skip_serializing_if = "Option::is_none")] #[cfg_attr(feature = "schema", schemars(extend("not" = serde_json::json!({"required":["taskAuthority"]}))))] - pub authorization: AuthorizationConfig, + pub authorization: Option, + /// A static key only the function host accepts, sent as the bearer token. + /// `rstack dev` generates one for each run; an operator recipe supplies + /// its own. Exactly one of `authorization` and `hostKeyRef` is required. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub host_key_ref: Option, /// Local JSON Schema for the complete {status, body} response. #[cfg_attr(feature = "schema", schemars(extend("x-registry-foreign" = "json-schema-2020-12")))] pub response_schema: ForeignValue, @@ -93,7 +101,7 @@ impl ServiceFunctionConfig { base_url: self.base_url.clone(), paths: UniqueList::new(vec![route.clone()]).expect("one path is unique"), query_parameters: None, - authorization: Some(self.authorization.clone()), + authorization: self.authorization.clone(), command_path: Some(route), response_schema: self.response_schema.clone(), attempt_timeout_milliseconds: self.attempt_timeout_milliseconds, @@ -277,12 +285,20 @@ impl ExternalHttpConnection { } /// The connection to one bound service function. Calls reach it only - /// through [`Self::command`], under the function host credential. + /// through [`Self::command`], under the function host credential: the + /// OAuth client's tokens or the static host key. pub fn service_function( config: &ServiceFunctionConfig, tokens: Arc, ) -> Result { - Self::new(&config.transport(), Some(tokens)) + let transport = config.transport(); + let oauth = transport + .authorization + .is_some() + .then(|| Arc::clone(&tokens)); + let mut connection = Self::new(&transport, oauth)?; + connection.tokens = Some(tokens); + Ok(connection) } /// One attempt at the configured read. Before the final attempt, a busy or diff --git a/crates/registry-coordinator/src/runtime.rs b/crates/registry-coordinator/src/runtime.rs index c355c6cad2..f2bc450a21 100644 --- a/crates/registry-coordinator/src/runtime.rs +++ b/crates/registry-coordinator/src/runtime.rs @@ -849,10 +849,31 @@ impl RuntimeConfig { } } else if let Some(function) = binding.service_function() { errors.extend(function.findings(&field)); - errors.extend(function.authorization.secret_reference_finding( - &format!("{field}.authorization"), - &self.secret_providers, - )); + match (&function.authorization, &function.host_key_ref) { + (Some(authorization), None) => { + errors.extend(authorization.secret_reference_finding( + &format!("{field}.authorization"), + &self.secret_providers, + )); + } + (None, Some(reference)) => { + let member = format!("{field}.hostKeyRef"); + if self + .secret_providers + .check_reference(&member, reference.as_str()) + .is_err() + { + errors.push(config_error( + &member, + "enable the secret provider named by the function host key reference", + )); + } + } + _ => errors.push(config_error( + &field, + "give the service function connection exactly one credential: authorization for an OAuth client, or hostKeyRef for a key only the function host accepts", + )), + } errors.extend(self.function_credential_findings(&field, function)); } else if let Some(binding) = binding.decision() { errors.extend(binding.findings(&field)); @@ -1060,38 +1081,44 @@ impl RuntimeConfig { field: &str, function: &crate::external_http::ServiceFunctionConfig, ) -> Vec { - let own = &function.authorization; let mut others = Vec::new(); + let mut other_keys = Vec::new(); for binding in self.connections.values() { if let Some(product) = binding.product_binding() { others.push(product.authorization); others.extend(product.observation_authorization); } else if let Some(external) = binding.external_http() { others.extend(external.authorization.as_ref()); + } else if let Some(reference) = binding.decision().and_then(|d| d.token_ref()) { + other_keys.push(reference); } } + other_keys.extend(others.iter().map(|other| &other.signing_key_ref)); + let action = "give the service function host its own resource, client and key; a product or external connection's credential would let the function act with product authority"; let mut errors = Vec::new(); - for (member, reused) in [ - ( - "resource", - others.iter().any(|other| other.resource == own.resource), - ), - ( - "clientId", - others.iter().any(|other| other.client_id == own.client_id), - ), - ( - "signingKeyRef", - others - .iter() - .any(|other| other.signing_key_ref == own.signing_key_ref), - ), - ] { - if reused { - errors.push(config_error( - &format!("{field}.authorization.{member}"), - "give the service function host its own resource, client and signing key; a product or external connection's credential would let the function act with product authority", - )); + if let Some(own) = &function.authorization { + for (member, reused) in [ + ( + "resource", + others.iter().any(|other| other.resource == own.resource), + ), + ( + "clientId", + others.iter().any(|other| other.client_id == own.client_id), + ), + ("signingKeyRef", other_keys.contains(&&own.signing_key_ref)), + ] { + if reused { + errors.push(config_error( + &format!("{field}.authorization.{member}"), + action, + )); + } + } + } + if let Some(reference) = &function.host_key_ref { + if other_keys.contains(&reference) { + errors.push(config_error(&format!("{field}.hostKeyRef"), action)); } } errors @@ -1292,6 +1319,13 @@ impl RuntimeConfig { scopes.sort_by(|a, b| a.as_str().cmp(&b.as_str())); } } + // Rotating the host key changes no binding, as rotating a + // signing key does not. + if let Some(binding) = identity.as_object_mut() { + if binding.remove("hostKeyRef").is_some() { + binding.insert("credential".into(), json!("host-key")); + } + } identity["product"] = json!("service-function"); identity["abi"] = json!("coordinator-service-function/v1"); identities.insert(name, identity); diff --git a/crates/registry-coordinator/tests/service_function.rs b/crates/registry-coordinator/tests/service_function.rs index 9bd99a43f6..00ce16b6b6 100644 --- a/crates/registry-coordinator/tests/service_function.rs +++ b/crates/registry-coordinator/tests/service_function.rs @@ -251,3 +251,107 @@ fn a_service_function_credential_is_never_a_product_credential() { ); } } + +/// A runtime whose function connection carries a static host key instead of +/// an OAuth client, the way `rstack dev` and an operator recipe supply one. +fn host_key_document(base: &str) -> Value { + let mut document = runtime_document(); + let notices = &mut document["connections"]["notices"]; + notices["baseUrl"] = json!(base); + notices.as_object_mut().unwrap().remove("authorization"); + notices["hostKeyRef"] = json!("secret:file/function-host-key"); + document +} + +#[tokio::test] +async fn a_host_key_credential_is_sent_as_the_bearer_to_the_bound_function() { + const HOST_KEY: &str = "synthetic-function-host-key-canary"; + let server = MockServer::start().await; + Mock::given(method("POST")) + .and(path("/functions/draft-notice")) + .and(header( + "authorization", + format!("Bearer {HOST_KEY}").as_str(), + )) + .and(header("idempotency-key", REQUEST_ID)) + .and(body_json(body())) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({"draftId":"draft-001"}))) + .expect(1) + .mount(&server) + .await; + let root = tempfile::tempdir().unwrap(); + let directory = root.path().canonicalize().unwrap(); + let key = directory.join("function-host-key"); + std::fs::write(&key, HOST_KEY).unwrap(); + std::fs::set_permissions(&key, std::os::unix::fs::PermissionsExt::from_mode(0o600)).unwrap(); + let mut document = host_key_document(&format!("{}/", server.uri())); + document["connections"] + .as_object_mut() + .unwrap() + .remove("registry"); + document["secretProviders"]["file"] = json!({"root":directory}); + let path = directory.join("runtime.yaml"); + std::fs::write(&path, serde_json::to_vec(&document).unwrap()).unwrap(); + let config = RuntimeConfig::load(&path).unwrap(); + let adapters = registry_coordinator::adapters::HttpAdapters::new(&config).unwrap(); + let request = registry_coordinator::protocol::CallRequest { + connection: "notices".into(), + operation: Operation::InvokeServiceFunction, + input: body(), + idempotency_key: Some(REQUEST_ID.into()), + operation_contract: None, + }; + let outcome = + registry_coordinator::protocol::AdapterSet::call_attempt(&adapters, &request, None, false) + .await; + assert!( + matches!(&outcome, CallOutcome::Success(reply) if reply["status"] == 200), + "{}", + describe(&outcome) + ); + server.verify().await; +} + +#[test] +fn a_function_connection_names_exactly_one_credential() { + assert!(load(&host_key_document("http://127.0.0.1:9020/")).is_ok()); + + let mut both = host_key_document("http://127.0.0.1:9020/"); + both["connections"]["notices"]["authorization"] = function_authorization(); + let error = load(&both).err().expect("two credentials are refused"); + assert!( + error + .field + .as_deref() + .unwrap_or_default() + .contains("/connections/notices"), + "{error:?}" + ); + + let mut neither = host_key_document("http://127.0.0.1:9020/"); + neither["connections"]["notices"] + .as_object_mut() + .unwrap() + .remove("hostKeyRef"); + assert!( + load(&neither).is_err(), + "an anonymous function connection is refused" + ); +} + +#[test] +fn a_host_key_is_never_a_product_signing_key() { + let mut document = host_key_document("http://127.0.0.1:9020/"); + document["connections"]["notices"]["hostKeyRef"] = json!("secret:file/registry-client-key"); + let error = load(&document) + .err() + .expect("a product signing key reused as a host key is refused"); + assert!( + error + .field + .as_deref() + .unwrap_or_default() + .contains("/connections/notices/hostKeyRef"), + "{error:?}" + ); +} diff --git a/docs/site/src/content/docs/reference/coordinator-configuration.mdx b/docs/site/src/content/docs/reference/coordinator-configuration.mdx index ef328524d3..069bed0546 100644 --- a/docs/site/src/content/docs/reference/coordinator-configuration.mdx +++ b/docs/site/src/content/docs/reference/coordinator-configuration.mdx @@ -205,14 +205,16 @@ Coordinator trusts a 429 to mean the provider did not process the command, so th ### Service function connections A `service-function` connection serves `service.invoke-function/v1` and binds exactly one service function, as the service's `service.yaml` declares it. -Set `baseUrl` to the function host, `function` to the function's identifier, the required `authorization`, and the required `responseSchema` for `{status, body}`. +Set `baseUrl` to the function host, `function` to the function's identifier, exactly one credential, and the required `responseSchema` for `{status, body}`. +The credential is either `authorization`, an OAuth client for the function host, or `hostKeyRef`, a secret reference to a key only the function host accepts, sent as the bearer token. +`rstack dev` supplies `baseUrl` and a per-run `hostKeyRef` for the preview function host. Coordinator sends each call as one POST to `functions/` under `baseUrl`. The attempt timeout, response size and request body bounds are those of an external command. Use HTTPS for institutional endpoints; HTTP requires numeric loopback. `authorization.taskAuthority` is refused. Add one connection for each function a workflow calls. -The credential is for the function host alone: its `resource`, `clientId` and `signingKeyRef` must differ from those of every product and external connection in the same file, and the runtime refuses a match. +The credential is for the function host alone: its `resource`, `clientId`, `signingKeyRef` or `hostKeyRef` must differ from those of every product, external and evaluation connection in the same file, and the runtime refuses a match. A function therefore holds no record authority through the call, and a record change stays a separate BReg step in the workflow. ```yaml diff --git a/docs/site/src/content/docs/security/coordinator.mdx b/docs/site/src/content/docs/security/coordinator.mdx index 39d7eae5da..361fb0ecfd 100644 --- a/docs/site/src/content/docs/security/coordinator.mdx +++ b/docs/site/src/content/docs/security/coordinator.mdx @@ -885,10 +885,12 @@ Enforcement: A connection of another type cannot carry the call. The function name is part of the Operation revision and the connection's binding digest, so a live Run cannot be moved to another function. -- The connection requires its own `authorization` and refuses `taskAuthority`. - The runtime refuses a `resource`, `clientId` or `signingKeyRef` equal to any product or external - connection's credential (`coordinator.runtime-config.refused` at that member), so the function - host token is never one a product accepts. +- The connection requires exactly one credential: an OAuth `authorization` without `taskAuthority`, + or a `hostKeyRef` key only the function host accepts. + `rstack dev` generates a per-run host key for the preview function host. + The runtime refuses a `resource`, `clientId`, `signingKeyRef` or `hostKeyRef` equal to any + product, external or evaluation connection's credential (`coordinator.runtime-config.refused` at + that member), so the function host credential is never one a product accepts. A function that forwards that token to BReg is refused by BReg; any record change is a separate BReg Action or Proposal step under the run's own connection. - The call is an external command in every other respect (COORDINATOR-INV-03): the request id is @@ -910,7 +912,10 @@ connection; task authority on a function connection. the_function_name_is_one_local_identifier, the_bound_function_is_part_of_the_binding_digest, a_service_function_connection_requires_its_own_credential, - a_service_function_credential_is_never_a_product_credential; + a_service_function_credential_is_never_a_product_credential, + a_host_key_credential_is_sent_as_the_bearer_to_the_bound_function, + a_function_connection_names_exactly_one_credential, + a_host_key_is_never_a_product_signing_key; crates/registry-coordinator/tests/service_function_project.rs a_missing_function_name_is_refused_at_the_operation, only_the_service_function_operation_names_a_function, diff --git a/products/coordinator/generated/runtime/runtime.schema.json b/products/coordinator/generated/runtime/runtime.schema.json index b0217fceec..e3f995c378 100644 --- a/products/coordinator/generated/runtime/runtime.schema.json +++ b/products/coordinator/generated/runtime/runtime.schema.json @@ -484,7 +484,7 @@ }, "authorization": { "$ref": "#/$defs/AuthorizationConfig", - "description": "The function host credential. Its client, key and resource are the\nfunction host's own and are never a product connection's, so the token\ncarries no product authority.", + "description": "An OAuth client credential for the function host. Its client, key and\nresource are the function host's own and are never a product\nconnection's, so the token carries no product authority. Exactly one of\n`authorization` and `hostKeyRef` is required.", "not": { "required": [ "taskAuthority" @@ -499,6 +499,10 @@ "$ref": "#/$defs/LocalId", "description": "The one function this connection binds, as `service.yaml` declares it." }, + "hostKeyRef": { + "$ref": "#/$defs/SecretReference", + "description": "A static key only the function host accepts, sent as the bearer token.\n`rstack dev` generates one for each run; an operator recipe supplies\nits own. Exactly one of `authorization` and `hostKeyRef` is required." + }, "maximumResponseBytes": { "default": 65536, "format": "uint64", @@ -519,7 +523,6 @@ "type", "baseUrl", "function", - "authorization", "responseSchema" ], "type": "object" From a2f1e6ac1b655e4740a072a461aef37502dd7190 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 20:51:57 +0000 Subject: [PATCH 131/183] fix(coordinator): refuse every declared product credential on a function host Compare the service function credential against normalised product and external resources, task authority audiences and the Coordinator's own issuer audience, name the colliding connection, and compare resolved key material at startup. Test the production adapter path, a lost acknowledgement and a final-attempt 503, give taskAuthority its own remedy, and say in diagnostics and docs that check matches the runtime binding while rstack dev checks service.yaml. Refs #2888 Signed-off-by: Jeremi Joslin --- crates/registry-coordinator/src/adapters.rs | 74 ++++ crates/registry-coordinator/src/authoring.rs | 11 +- crates/registry-coordinator/src/definition.rs | 3 +- .../registry-coordinator/src/external_http.rs | 26 +- crates/registry-coordinator/src/runtime.rs | 102 +++-- .../tests/service_function.rs | 408 +++++++++++++++++- .../tests/service_function_postgres.rs | 7 +- .../tests/service_function_project.rs | 50 ++- .../content/docs/configure/coordinator.mdx | 8 +- .../src/content/docs/operate/coordinator.mdx | 2 +- .../reference/coordinator-configuration.mdx | 14 +- .../src/content/docs/security/coordinator.mdx | 113 +++-- products/coordinator/CHANGELOG.md | 2 +- .../generated/project/project.schema.json | 2 +- .../generated/runtime/runtime.schema.json | 4 +- 15 files changed, 730 insertions(+), 96 deletions(-) diff --git a/crates/registry-coordinator/src/adapters.rs b/crates/registry-coordinator/src/adapters.rs index b706989435..dbe62d644d 100644 --- a/crates/registry-coordinator/src/adapters.rs +++ b/crates/registry-coordinator/src/adapters.rs @@ -192,6 +192,7 @@ impl HttpAdapters { .resolver(config.development.as_ref()) .map_err(|_| config_error())?, ); + distinct_function_keys(config, &secrets)?; let mut connections = BTreeMap::new(); for (name, configured) in &config.connections { if let Some(binding) = configured.external_http() { @@ -464,6 +465,79 @@ impl HttpAdapters { } } +/// A service function host never holds the key of another connection, even +/// under another secret reference: a JWK is compared by its RFC 7638 +/// thumbprint, any other key by a digest of its bytes. The refusal names the +/// two connections and no key value. +fn distinct_function_keys( + config: &RuntimeConfig, + secrets: ®istry_platform_config::SecretResolver, +) -> Result<()> { + use sha2::Digest as _; + let identity = |reference: ®istry_platform_config::SecretReference| -> Result { + let secret = secrets + .resolve_reference(reference) + .map_err(|_| config_error())?; + let bytes = secret.expose_secret(); + let jwk = std::str::from_utf8(bytes) + .ok() + .and_then(|text| PrivateJwk::parse(text).ok()) + .and_then(|key| key.public().jkt().ok()); + Ok(match jwk { + Some(thumbprint) => format!("jwk:{thumbprint}"), + None => format!("bytes:{}", hex::encode(sha2::Sha256::digest(bytes))), + }) + }; + let mut functions = Vec::new(); + let mut others = Vec::new(); + for (name, configured) in &config.connections { + if let Some(function) = configured.service_function() { + for reference in function + .authorization + .as_ref() + .map(|auth| &auth.signing_key_ref) + .into_iter() + .chain(function.host_key_ref.as_ref()) + { + functions.push((name, identity(reference)?)); + } + continue; + } + let mut references = Vec::new(); + if let Some(product) = configured.product_binding() { + references.push(&product.authorization.signing_key_ref); + references.extend( + product + .observation_authorization + .map(|auth| &auth.signing_key_ref), + ); + } else if let Some(external) = configured.external_http() { + references.extend( + external + .authorization + .as_ref() + .map(|auth| &auth.signing_key_ref), + ); + } else if let Some(reference) = configured.decision().and_then(|d| d.token_ref()) { + references.push(reference); + } + for reference in references { + others.push((name, identity(reference)?)); + } + } + for (function, key) in &functions { + if let Some((other, _)) = others.iter().find(|(_, value)| value == key) { + return Err(CoordinatorError::new( + "coordinator.runtime-config.refused", + format!("connections {function} and {other} resolve to the same key; a service function host must hold a key no other connection uses"), + ) + .at("runtime.yaml", format!("/connections/{function}")) + .suggest(format!("Give connections.{function} its own key, distinct from connections.{other}."))); + } + } + Ok(()) +} + pub(crate) fn refused(code: &str) -> CallOutcome { CallOutcome::Refused { code: code.to_owned(), diff --git a/crates/registry-coordinator/src/authoring.rs b/crates/registry-coordinator/src/authoring.rs index ca0c39501d..05af11f6fd 100644 --- a/crates/registry-coordinator/src/authoring.rs +++ b/crates/registry-coordinator/src/authoring.rs @@ -163,10 +163,11 @@ struct AuthoredOperation { /// Fix a Messaging template version, its locales and its data schema. #[serde(default)] template: Option, - /// The one service function `service.invoke-function/v1` calls, as the - /// service's `service.yaml` declares it. Required on, and accepted only - /// on, that Operation. The runtime connection binds its host and - /// credential; the workflow supplies neither. + /// The one service function `service.invoke-function/v1` calls. Required + /// on, and accepted only on, that Operation. `check` matches it against + /// the function the runtime connection binds; `rstack dev` also checks it + /// against `service.yaml`. The runtime connection binds the host and + /// credential, and the workflow supplies neither. #[serde(default)] service_function: Option, /// An optional typed response specialization for the bounded external GET @@ -1294,7 +1295,7 @@ fn compile(project: CoordinatorProject, path: &Path) -> Result { (true, None) => { return Err(schema_error( format!("/operations/{id}/serviceFunction"), - "service.invoke-function/v1 requires serviceFunction: the one function declared in service.yaml that this Operation calls", + "service.invoke-function/v1 requires serviceFunction: the one function this Operation calls, which its runtime connection must bind", )); } (false, Some(_)) => { diff --git a/crates/registry-coordinator/src/definition.rs b/crates/registry-coordinator/src/definition.rs index 0909cc7293..3f25cf7abf 100644 --- a/crates/registry-coordinator/src/definition.rs +++ b/crates/registry-coordinator/src/definition.rs @@ -392,8 +392,7 @@ pub struct ResolvedOperation { /// interpreted accepted result. #[serde(default, skip_serializing_if = "Option::is_none")] pub response: Option, - /// The one service function, declared in `service.yaml`, that - /// `service.invoke-function/v1` calls. Present only on that operation; the + /// The one service function `service.invoke-function/v1` calls. Present only on that operation; the /// runtime connection must bind the same function. #[serde(default, skip_serializing_if = "Option::is_none")] pub service_function: Option, diff --git a/crates/registry-coordinator/src/external_http.rs b/crates/registry-coordinator/src/external_http.rs index 674ce038f8..204024fb2e 100644 --- a/crates/registry-coordinator/src/external_http.rs +++ b/crates/registry-coordinator/src/external_http.rs @@ -54,8 +54,9 @@ pub struct ExternalHttpConfig { pub maximum_response_bytes: BoundedU64<1, { crate::operations::MAXIMUM_HTTP_RESPONSE_BYTES }>, } -/// One service function declared in the service's `service.yaml`, bound by the -/// deployment to its function host and to a credential for that host alone. +/// One service function, bound by the deployment to its function host and to a +/// credential for that host alone. `rstack dev` checks the name against the +/// service's `service.yaml`; an operator recipe binds a name it has checked. /// The workflow names the function; it never supplies the destination or the /// credential. The function host serves the function at `functions/` /// under the base URL. @@ -67,7 +68,7 @@ pub struct ServiceFunctionConfig { #[cfg_attr(feature = "schema", schemars(with = "registry_platform_yaml::Url"))] #[cfg_attr(feature = "schema", schemars(extend("pattern" = "^[^\\s\\\\]+$")))] pub base_url: Url, - /// The one function this connection binds, as `service.yaml` declares it. + /// The one function this connection binds. pub function: LocalId, /// An OAuth client credential for the function host. Its client, key and /// resource are the function host's own and are never a product @@ -110,7 +111,24 @@ impl ServiceFunctionConfig { } pub fn findings(&self, prefix: &str) -> Vec { - self.transport().findings(prefix) + let mut transport = self.transport(); + let task_authority = transport + .authorization + .as_mut() + .and_then(|authorization| authorization.task_authority.take()) + .is_some(); + let mut errors = transport.findings(prefix); + if task_authority { + errors.push( + CoordinatorError::new( + "coordinator.external-http.configuration", + "the service function credential was refused", + ) + .at("runtime.yaml", format!("{prefix}.authorization.taskAuthority")) + .suggest("Remove taskAuthority; a service function call runs under the function host credential alone and never under task authority."), + ); + } + errors } } diff --git a/crates/registry-coordinator/src/runtime.rs b/crates/registry-coordinator/src/runtime.rs index f2bc450a21..a321ad85da 100644 --- a/crates/registry-coordinator/src/runtime.rs +++ b/crates/registry-coordinator/src/runtime.rs @@ -1072,53 +1072,73 @@ impl RuntimeConfig { self.validate_workflow_effect_bindings(workflow) } - /// A service function credential is for its function host alone. Its - /// resource, client and signing key may not be any product or external - /// connection's, so the token it yields is never one a product accepts and - /// a function holds no record authority through it. + /// A service function credential is distinct from every credential and + /// product audience this runtime file declares: no resource equal, after + /// normalisation, to a product, external or task authority resource or to + /// the Coordinator's own audience, no shared client, and no shared key + /// reference. Startup also compares the resolved key material. Each + /// refusal names the colliding connection, never a value. fn function_credential_findings( &self, field: &str, function: &crate::external_http::ServiceFunctionConfig, ) -> Vec { - let mut others = Vec::new(); - let mut other_keys = Vec::new(); - for binding in self.connections.values() { + let mut resources: Vec<(String, &str)> = Vec::new(); + let mut clients: Vec<(&str, &str)> = Vec::new(); + let mut keys: Vec<(&str, &SecretReference)> = Vec::new(); + for (name, binding) in &self.connections { + let mut credentials: Vec<&AuthorizationConfig> = Vec::new(); if let Some(product) = binding.product_binding() { - others.push(product.authorization); - others.extend(product.observation_authorization); + credentials.push(product.authorization); + credentials.extend(product.observation_authorization); } else if let Some(external) = binding.external_http() { - others.extend(external.authorization.as_ref()); + credentials.extend(external.authorization.as_ref()); } else if let Some(reference) = binding.decision().and_then(|d| d.token_ref()) { - other_keys.push(reference); + keys.push((name, reference)); + } + for credential in credentials { + resources.push((normalised_resource(&credential.resource), name)); + if let Some(task) = &credential.task_authority { + resources.push((normalised_resource(&task.bootstrap_resource), name)); + resources.push((normalised_resource(&task.exchange_audience), name)); + } + clients.push((&credential.client_id, name)); + keys.push((name, &credential.signing_key_ref)); } } - other_keys.extend(others.iter().map(|other| &other.signing_key_ref)); - let action = "give the service function host its own resource, client and key; a product or external connection's credential would let the function act with product authority"; + if let Some(deployment) = &self.deployment { + for (_, issuer) in deployment.authentication.issuers.iter() { + resources.push(( + normalised_resource(&issuer.core.provider.audience), + "deployment.authentication", + )); + } + } + let refusal = |member: String, other: &str| { + config_error( + &format!("{field}.{member}"), + &format!("give the service function host its own resource, client and key; the value matches the credential of {other}, which would let the function act with that authority"), + ) + }; let mut errors = Vec::new(); if let Some(own) = &function.authorization { - for (member, reused) in [ - ( - "resource", - others.iter().any(|other| other.resource == own.resource), - ), - ( - "clientId", - others.iter().any(|other| other.client_id == own.client_id), - ), - ("signingKeyRef", other_keys.contains(&&own.signing_key_ref)), - ] { - if reused { - errors.push(config_error( - &format!("{field}.authorization.{member}"), - action, - )); - } + let resource = normalised_resource(&own.resource); + if let Some((_, other)) = resources.iter().find(|(value, _)| *value == resource) { + errors.push(refusal("authorization.resource".into(), other)); + } + if let Some((_, other)) = clients.iter().find(|(value, _)| *value == own.client_id) { + errors.push(refusal("authorization.clientId".into(), other)); + } + if let Some((other, _)) = keys + .iter() + .find(|(_, reference)| **reference == own.signing_key_ref) + { + errors.push(refusal("authorization.signingKeyRef".into(), other)); } } if let Some(reference) = &function.host_key_ref { - if other_keys.contains(&reference) { - errors.push(config_error(&format!("{field}.hostKeyRef"), action)); + if let Some((other, _)) = keys.iter().find(|(_, value)| *value == reference) { + errors.push(refusal("hostKeyRef".into(), other)); } } errors @@ -1204,7 +1224,7 @@ impl RuntimeConfig { format!("/operations/{}/serviceFunction", call.alias), ) .suggest(format!( - "Name a function declared in service.yaml and bound as connections.{}.function in runtime.yaml, or add one service-function connection for it.", + "Name the function bound as connections.{}.function in runtime.yaml, or add one service-function connection for this function.", call.connection ))); } @@ -1437,6 +1457,22 @@ fn runtime_id_collision_diagnostics( diagnostics } +/// The form a resource indicator is compared in: a URL with its scheme and +/// host in lower case, its default port dropped and a lone `/` path removed. +/// Any other identifier is compared exactly. +fn normalised_resource(resource: &str) -> String { + match Url::parse(resource) { + Ok(url) if url.has_host() => { + let text = url.to_string(); + match text.strip_suffix('/') { + Some(origin) if url.path() == "/" && url.query().is_none() => origin.to_owned(), + _ => text, + } + } + _ => resource.to_owned(), + } +} + fn config_error(field: &str, action: &str) -> CoordinatorError { CoordinatorError::new( "coordinator.runtime-config.refused", diff --git a/crates/registry-coordinator/tests/service_function.rs b/crates/registry-coordinator/tests/service_function.rs index 00ce16b6b6..c4f9f34212 100644 --- a/crates/registry-coordinator/tests/service_function.rs +++ b/crates/registry-coordinator/tests/service_function.rs @@ -246,7 +246,7 @@ fn a_service_function_credential_is_never_a_product_credential() { error .suggested_action .as_deref() - .is_some_and(|action| action.contains("product")), + .is_some_and(|action| action.contains("registry")), "{member}: {error:?}" ); } @@ -355,3 +355,409 @@ fn a_host_key_is_never_a_product_signing_key() { "{error:?}" ); } + +/// The refusal for one function resource, against the given runtime. +fn resource_refusal(mut document: Value, resource: &str) -> registry_coordinator::CoordinatorError { + document["connections"]["notices"]["authorization"]["resource"] = json!(resource); + load(&document) + .err() + .unwrap_or_else(|| panic!("the function resource {resource} is refused")) +} + +#[test] +fn a_function_resource_is_compared_after_normalisation() { + let mut document = runtime_document(); + document["connections"]["registry"]["authorization"]["resource"] = + json!("https://breg.example.org"); + for spelling in [ + "https://breg.example.org/", + "https://BREG.example.org", + "HTTPS://breg.example.org", + "https://breg.example.org:443/", + ] { + let error = resource_refusal(document.clone(), spelling); + assert!( + error + .field + .as_deref() + .unwrap_or_default() + .contains("/connections/notices/authorization/resource"), + "{spelling}: {error:?}" + ); + // The remedy names the colliding connection, never a value. + let action = error.suggested_action.as_deref().unwrap_or_default(); + assert!(action.contains("registry"), "{spelling}: {action}"); + assert!(!action.contains("breg.example.org"), "{spelling}: {action}"); + } + // Another path on the same origin is another resource. + document["connections"]["notices"]["authorization"]["resource"] = + json!("https://breg.example.org/functions"); + load(&document).unwrap(); +} + +#[test] +fn a_function_resource_is_never_a_casework_or_exchange_audience() { + let mut document = runtime_document(); + document["connections"]["registry"]["authorization"]["taskAuthority"] = json!({ + "baseUrl":"https://casework.example.org", "issuer":"https://casework.example.org", + "subject":"coordinator", "exchangeAudience":"https://issuer.example.org/oauth/token", + "bootstrapResource":"urn:example:casework" + }); + for audience in [ + "urn:example:casework", + "https://issuer.example.org/oauth/token", + ] { + resource_refusal(document.clone(), audience); + } +} + +#[test] +fn a_function_resource_is_never_a_scheduling_messaging_or_external_audience() { + let mut document = runtime_document(); + let connections = document["connections"].as_object_mut().unwrap(); + connections.insert( + "bookings".into(), + json!({ + "type":"scheduling", "baseUrl":"http://127.0.0.1:9022", + "authorization":{ + "tokenEndpoint":"http://127.0.0.1:9999/token", + "clientAssertionAudience":"http://127.0.0.1:9999", + "clientId":"coordinator-bookings", + "signingKeyRef":"secret:file/bookings-client-key", + "resource":"urn:example:scheduling", "scopes":["scheduling:book"], + "taskAuthority":{ + "baseUrl":"https://casework.example.org", "issuer":"https://casework.example.org", + "subject":"coordinator", "exchangeAudience":"urn:example:exchange", + "bootstrapResource":"urn:example:casework" + } + }, + "observationAuthorization":{ + "tokenEndpoint":"http://127.0.0.1:9999/token", + "clientAssertionAudience":"http://127.0.0.1:9999", + "clientId":"coordinator-bookings", + "signingKeyRef":"secret:file/bookings-client-key", + "resource":"urn:example:scheduling", "scopes":["scheduling:read"] + } + }), + ); + connections.insert( + "letters".into(), + json!({ + "type":"messaging", "baseUrl":"http://127.0.0.1:9023", + "authorization":{ + "tokenEndpoint":"http://127.0.0.1:9999/token", + "clientAssertionAudience":"http://127.0.0.1:9999", + "clientId":"coordinator-letters", + "signingKeyRef":"secret:file/letters-client-key", + "resource":"urn:example:messaging", "scopes":["messaging:send"] + } + }), + ); + connections.insert( + "legacy".into(), + json!({ + "type":"external-http", "baseUrl":"https://legacy.example.org/", + "paths":["requests/status"], "commandPath":"requests", + "authorization":{ + "tokenEndpoint":"http://127.0.0.1:9999/token", + "clientAssertionAudience":"http://127.0.0.1:9999", + "clientId":"coordinator-legacy", + "signingKeyRef":"secret:file/legacy-client-key", + "resource":"https://legacy.example.org", "scopes":["requests:create"] + }, + "responseSchema":{"type":"object"} + }), + ); + load(&document).unwrap(); + for (audience, connection) in [ + // An observation credential shares its primary resource by rule. + ("urn:example:scheduling", "bookings"), + ("urn:example:messaging", "letters"), + ("https://legacy.example.org/", "legacy"), + ] { + let error = resource_refusal(document.clone(), audience); + let action = error.suggested_action.as_deref().unwrap_or_default(); + assert!(action.contains(connection), "{audience}: {action}"); + } + let mut document = document.clone(); + document["connections"]["notices"]["authorization"]["clientId"] = json!("coordinator-letters"); + assert!(load(&document).is_err(), "a messaging client is refused"); +} + +#[test] +fn a_function_resource_is_never_the_coordinator_audience() { + let example = + include_str!("../../../products/coordinator/examples/delayed-follow-up/runtime.yaml"); + let function = " drafts:\n type: service-function\n baseUrl: http://127.0.0.1:9020/\n function: draft-notice\n authorization:\n tokenEndpoint: http://127.0.0.1:8090/token\n clientAssertionAudience: http://127.0.0.1:8090\n clientId: coordinator-functions\n signingKeyRef: secret:file/function-key\n resource: RESOURCE\n scopes: [functions:invoke]\n responseSchema: {type: object}\n"; + let write = |resource: &str| { + let root = tempfile::tempdir().unwrap(); + let path = root.path().canonicalize().unwrap().join("runtime.yaml"); + let text = example.replacen( + "connections:\n", + &format!("connections:\n{}", function.replace("RESOURCE", resource)), + 1, + ); + std::fs::write(&path, text).unwrap(); + RuntimeConfig::load(&path) + }; + write("urn:example:notice-functions").unwrap(); + let error = write("urn:example:coordinator") + .err() + .expect("the Coordinator's own audience is refused"); + assert!( + error + .field + .as_deref() + .unwrap_or_default() + .contains("/connections/drafts/authorization/resource"), + "{error:?}" + ); +} + +#[test] +fn a_taskauthority_refusal_names_the_service_function_remedy() { + let mut document = runtime_document(); + document["connections"]["notices"]["authorization"]["taskAuthority"] = json!({ + "baseUrl":"http://127.0.0.1:9022", "issuer":"https://identity.example.test", + "subject":"coordinator", "exchangeAudience":"urn:example:tasks", + "bootstrapResource":"urn:example:tasks" + }); + let error = load(&document).err().unwrap(); + let action = error.suggested_action.as_deref().unwrap_or_default(); + assert!(action.contains("service function"), "{action}"); + assert!(!action.contains("external GET"), "{action}"); +} + +/// Two distinct private signing keys. +const KEY: &str = registry_platform_testing::fixtures::ED25519_PRIVATE_JWK; +const OTHER_KEY: &str = registry_platform_testing::fixtures::ED25519_ROTATED_PRIVATE_JWK; + +/// A runtime file in a private secret directory holding the named secrets. +fn with_secrets(document: &Value, secrets: &[(&str, &str)]) -> (tempfile::TempDir, RuntimeConfig) { + use std::os::unix::fs::PermissionsExt; + let root = tempfile::tempdir().unwrap(); + let directory = root.path().canonicalize().unwrap(); + for (name, value) in secrets { + let path = directory.join(name); + std::fs::write(&path, value).unwrap(); + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)).unwrap(); + } + let mut document = document.clone(); + document["secretProviders"]["file"] = json!({"root":directory}); + let path = directory.join("runtime.yaml"); + std::fs::write(&path, serde_json::to_vec(&document).unwrap()).unwrap(); + let config = RuntimeConfig::load(&path).unwrap(); + (root, config) +} + +#[test] +fn the_same_signing_key_under_another_reference_is_refused_at_startup() { + let shared = KEY; + let (_root, config) = with_secrets( + &runtime_document(), + &[ + ("function-client-key", shared), + ("registry-client-key", shared), + ], + ); + let error = registry_coordinator::adapters::HttpAdapters::new(&config) + .err() + .expect("one key behind two references is refused"); + assert!(error.message.contains("notices"), "{error:?}"); + assert!(error.message.contains("registry"), "{error:?}"); + assert!(!error.message.contains(shared)); + + let (_root, config) = with_secrets( + &runtime_document(), + &[ + ("function-client-key", OTHER_KEY), + ("registry-client-key", shared), + ], + ); + registry_coordinator::adapters::HttpAdapters::new(&config).unwrap(); +} + +fn call(operation: Operation, key: Option<&str>) -> registry_coordinator::protocol::CallRequest { + registry_coordinator::protocol::CallRequest { + connection: "notices".into(), + operation, + input: body(), + idempotency_key: key.map(str::to_owned), + operation_contract: None, + } +} + +#[tokio::test] +async fn the_runtime_routes_a_function_call_with_its_oauth_token_and_frozen_request_id() { + use registry_coordinator::protocol::AdapterSet; + let token = MockServer::start().await; + Mock::given(method("POST")) + .and(path("/token")) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({ + "access_token":"fixture-function-token", "token_type":"Bearer", "expires_in":60, + "issued_token_type":"urn:ietf:params:oauth:token-type:access_token" + }))) + .mount(&token) + .await; + let host = MockServer::start().await; + Mock::given(method("POST")) + .and(path("/functions/draft-notice")) + .and(header("authorization", "Bearer fixture-function-token")) + .and(header("idempotency-key", REQUEST_ID)) + .and(body_json(body())) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({"draftId":"draft-001"}))) + .expect(1) + .mount(&host) + .await; + let mut document = runtime_document(); + document["connections"]["notices"]["baseUrl"] = json!(format!("{}/", host.uri())); + document["connections"]["notices"]["authorization"]["tokenEndpoint"] = + json!(format!("{}/token", token.uri())); + let (_root, config) = with_secrets( + &document, + &[ + ("function-client-key", OTHER_KEY), + ("registry-client-key", KEY), + ], + ); + let adapters = registry_coordinator::adapters::HttpAdapters::new(&config).unwrap(); + let outcome = adapters + .call_attempt( + &call(Operation::InvokeServiceFunction, Some(REQUEST_ID)), + None, + false, + ) + .await; + assert!( + matches!(&outcome, CallOutcome::Success(reply) if reply["status"] == 200), + "{}", + describe(&outcome) + ); + // A call without its frozen request id, and any other operation on the + // function connection, is refused before anything is sent. + for (operation, key) in [ + (Operation::InvokeServiceFunction, None), + (Operation::ExternalCommand, Some(REQUEST_ID)), + (Operation::ExternalGet, None), + ] { + let refused = adapters.call(&call(operation, key)).await; + assert!( + matches!(&refused, CallOutcome::Refused { .. }), + "{}: {}", + operation.as_str(), + describe(&refused) + ); + } + host.verify().await; +} + +#[tokio::test] +async fn a_lost_acknowledgement_is_uncertain_and_the_same_request_id_is_sent_again() { + use registry_coordinator::protocol::AdapterSet; + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + const HOST_KEY: &str = "synthetic-function-host-key-canary"; + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + let server = tokio::spawn(async move { + let mut seen = Vec::new(); + for attempt in 0..2 { + let (mut socket, _) = listener.accept().await.unwrap(); + let mut buffer = Vec::new(); + let mut chunk = [0_u8; 4096]; + while !buffer.windows(4).any(|window| window == b"\r\n\r\n") { + let read = socket.read(&mut chunk).await.unwrap(); + assert!(read > 0); + buffer.extend_from_slice(&chunk[..read]); + } + let head = String::from_utf8_lossy(&buffer).to_string(); + assert!( + head.starts_with("POST /functions/draft-notice HTTP/1.1\r\n"), + "{head}" + ); + let key = head + .lines() + .find_map(|line| { + let (name, value) = line.split_once(':')?; + name.eq_ignore_ascii_case("idempotency-key") + .then(|| value.trim().to_owned()) + }) + .unwrap(); + seen.push(key); + if attempt == 0 { + drop(socket); + continue; + } + let reply = br#"{"draftId":"draft-001"}"#; + let response = format!( + "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", + reply.len() + ); + socket.write_all(response.as_bytes()).await.unwrap(); + socket.write_all(reply).await.unwrap(); + socket.shutdown().await.unwrap(); + } + seen + }); + let document = host_key_document(&format!("http://{address}/")); + let (_root, config) = with_secrets( + &document, + &[ + ("function-host-key", HOST_KEY), + ("registry-client-key", KEY), + ], + ); + let adapters = registry_coordinator::adapters::HttpAdapters::new(&config).unwrap(); + let request = call(Operation::InvokeServiceFunction, Some(REQUEST_ID)); + let first = adapters.call_attempt(&request, None, false).await; + assert!( + matches!(&first, CallOutcome::Uncertain { code } if code == "transport-uncertain"), + "{}", + describe(&first) + ); + let second = adapters.call_attempt(&request, None, true).await; + assert!( + matches!(&second, CallOutcome::Success(reply) if reply["status"] == 200), + "{}", + describe(&second) + ); + let seen = tokio::time::timeout(std::time::Duration::from_secs(10), server) + .await + .unwrap() + .unwrap(); + assert_eq!(seen, [REQUEST_ID, REQUEST_ID]); +} + +#[tokio::test] +async fn a_busy_answer_on_the_final_attempt_holds_instead_of_retrying() { + use registry_coordinator::protocol::AdapterSet; + const HOST_KEY: &str = "synthetic-function-host-key-canary"; + let host = MockServer::start().await; + Mock::given(method("POST")) + .and(path("/functions/draft-notice")) + .respond_with(ResponseTemplate::new(503)) + .expect(2) + .mount(&host) + .await; + let (_root, config) = with_secrets( + &host_key_document(&format!("{}/", host.uri())), + &[ + ("function-host-key", HOST_KEY), + ("registry-client-key", KEY), + ], + ); + let adapters = registry_coordinator::adapters::HttpAdapters::new(&config).unwrap(); + let request = call(Operation::InvokeServiceFunction, Some(REQUEST_ID)); + let early = adapters.call_attempt(&request, None, false).await; + assert!( + matches!(&early, CallOutcome::UncertainRetryable { code, .. } if code == "external-unavailable"), + "{}", + describe(&early) + ); + let last = adapters.call_attempt(&request, None, true).await; + assert!( + matches!(&last, CallOutcome::Uncertain { code } if code == "external-uncertain"), + "{}", + describe(&last) + ); + host.verify().await; +} diff --git a/crates/registry-coordinator/tests/service_function_postgres.rs b/crates/registry-coordinator/tests/service_function_postgres.rs index 18c01dbe26..bd6304ee9b 100644 --- a/crates/registry-coordinator/tests/service_function_postgres.rs +++ b/crates/registry-coordinator/tests/service_function_postgres.rs @@ -217,5 +217,10 @@ async fn an_authority_refusal_the_interpretation_does_not_recognise_holds_the_ru .mount(&server) .await; let inspection = h.run(&server.uri()).await; - assert_ne!(inspection["run"]["state"], "finished", "{inspection}"); + assert_eq!(inspection["run"]["state"], "attention", "{inspection}"); + assert_eq!(inspection["run"]["uncertain"], true); + assert_eq!(inspection["run"]["failureCode"], "external-uncertain"); + assert_eq!(inspection["effects"][0]["step"], "draft"); + assert_eq!(inspection["effects"][0]["state"], "unknown"); + assert_eq!(inspection["recovery"]["retryAllowed"], true); } diff --git a/crates/registry-coordinator/tests/service_function_project.rs b/crates/registry-coordinator/tests/service_function_project.rs index 59bb7054fa..909eac0195 100644 --- a/crates/registry-coordinator/tests/service_function_project.rs +++ b/crates/registry-coordinator/tests/service_function_project.rs @@ -1,7 +1,7 @@ // SPDX-License-Identifier: Apache-2.0 //! Authoring, checking and synthetic scenarios for -//! `service.invoke-function/v1`. A project names one service function declared -//! in the service's `service.yaml`, a pure Transform that builds its body, and a +//! `service.invoke-function/v1`. A project names one service function, a pure +//! Transform that builds its body, and a //! pure Transform that interprets the answer. The runtime file alone binds the //! function host, the function and the credential. use registry_coordinator::{ @@ -343,3 +343,49 @@ fn the_step_output_is_the_accepted_result() { .check_refusal(&json!({"refusalCode":"not-eligible"})) .is_ok()); } + +#[test] +fn unresolved_routed_straight_to_a_service_function_is_refused() { + // The function's effect is unknown to Coordinator, so "not found, so call + // the function" is refused as "not found, so create" is. + let findings = refused(&[ + ( + "operations:\n", + "operations:\n find:\n uses: breg.lookup-record/v1\n connection: register\n", + ), + (" start: draft\n", " start: lookup\n"), + ( + " steps:\n", + concat!( + " steps:\n", + " lookup:\n", + " type: call\n", + " operation: find\n", + " input:\n", + " type: fields\n", + " fields:\n", + " entity: {type: literal, value: notices}\n", + " selector: {type: literal, value: by-reference}\n", + " values:\n", + " type: fields\n", + " fields:\n", + " reference: {type: input, path: /reference}\n", + " next: known\n", + " onDeclaredRefusal: draft\n", + " known:\n", + " type: finish\n", + " outcome: known\n", + ), + ), + ( + " outcomes:\n", + " outcomes:\n known: {type: \"null\"}\n", + ), + ]); + assert!( + findings + .iter() + .any(|finding| finding["code"] == "coordinator.definition.unresolved-route"), + "{findings:#?}" + ); +} diff --git a/docs/site/src/content/docs/configure/coordinator.mdx b/docs/site/src/content/docs/configure/coordinator.mdx index 5583798052..8e70c900a8 100644 --- a/docs/site/src/content/docs/configure/coordinator.mdx +++ b/docs/site/src/content/docs/configure/coordinator.mdx @@ -944,8 +944,9 @@ The operation has no original-result receipt, so `reconcile` cannot settle it. ## Call a service function -`service.invoke-function/v1` calls one function the service declares in `service.yaml`. -The alias names it with `serviceFunction`; the runtime connection binds the function host, the same function, and a credential for that host alone. +`service.invoke-function/v1` calls one service function. +The alias names it with `serviceFunction`. +The runtime connection binds the function host, the same function, and a credential for that host alone. The call is an external command in every other respect: a pure Transform builds the JSON body, a required `interpret` Transform reads the `{status, body}` answer, and recovery, retries and fixtures follow [Call an external provider](#call-an-external-provider). ```yaml @@ -959,7 +960,8 @@ operations: ``` `check` refuses an alias without `serviceFunction`, a `serviceFunction` on any other operation, and an alias whose connection binds another function. -A function holds no record authority: the function host credential is never one a product accepts. +It checks the name against the runtime connection only, and `rstack dev` also refuses a name the service's `service.yaml` does not declare. +The function host credential is distinct from every product credential and audience the runtime file declares, so the call gives the function none of them. Write any record change as its own step, such as a `breg.invoke-action/v1` call, under the run's BReg connection. The reference page covers the [connection](../../reference/coordinator-configuration/#service-function-connections). diff --git a/docs/site/src/content/docs/operate/coordinator.mdx b/docs/site/src/content/docs/operate/coordinator.mdx index 1f49c16706..11b173bb17 100644 --- a/docs/site/src/content/docs/operate/coordinator.mdx +++ b/docs/site/src/content/docs/operate/coordinator.mdx @@ -1057,7 +1057,7 @@ Before the final attempt, these external replies must carry at most one `Retry-A A date, duplicate field, malformed value, or longer wait stops the call with `external-unusable-retry-after`. Zero still follows the normal backoff schedule. -An `external.command/v1` call has no read-only receipt, so `reconcile` reports `reconciliation-unavailable`. +An `external.command/v1` or `service.invoke-function/v1` call has no read-only receipt, so `reconcile` reports `reconciliation-unavailable`. `retry-same` resends the frozen body with its original `Idempotency-Key`; before retrying, confirm with the provider that it still deduplicates that key. - Status 429 before the tenth attempt is a definite busy answer retried on the retry schedule; on the tenth attempt it ends the call with `external-rate-limited`. diff --git a/docs/site/src/content/docs/reference/coordinator-configuration.mdx b/docs/site/src/content/docs/reference/coordinator-configuration.mdx index 069bed0546..a7b9da3613 100644 --- a/docs/site/src/content/docs/reference/coordinator-configuration.mdx +++ b/docs/site/src/content/docs/reference/coordinator-configuration.mdx @@ -204,18 +204,24 @@ Coordinator trusts a 429 to mean the provider did not process the command, so th ### Service function connections -A `service-function` connection serves `service.invoke-function/v1` and binds exactly one service function, as the service's `service.yaml` declares it. +A `service-function` connection serves `service.invoke-function/v1` and binds exactly one service function. +`rstack dev` checks the name against the service's `service.yaml`, and an operator recipe binds a name it has checked. Set `baseUrl` to the function host, `function` to the function's identifier, exactly one credential, and the required `responseSchema` for `{status, body}`. The credential is either `authorization`, an OAuth client for the function host, or `hostKeyRef`, a secret reference to a key only the function host accepts, sent as the bearer token. `rstack dev` supplies `baseUrl` and a per-run `hostKeyRef` for the preview function host. Coordinator sends each call as one POST to `functions/` under `baseUrl`. The attempt timeout, response size and request body bounds are those of an external command. -Use HTTPS for institutional endpoints; HTTP requires numeric loopback. +Use HTTPS for institutional endpoints. +HTTP requires numeric loopback. `authorization.taskAuthority` is refused. Add one connection for each function a workflow calls. -The credential is for the function host alone: its `resource`, `clientId`, `signingKeyRef` or `hostKeyRef` must differ from those of every product, external and evaluation connection in the same file, and the runtime refuses a match. -A function therefore holds no record authority through the call, and a record change stays a separate BReg step in the workflow. +The credential is for the function host alone. +The runtime refuses a `resource` equal to a product or external connection's resource, a task authority `bootstrapResource` or `exchangeAudience`, or the Coordinator's own issuer audience, comparing URLs with the scheme and host in lower case, no default port and no lone trailing `/`. +It also refuses a `clientId`, `signingKeyRef` or `hostKeyRef` another connection uses, and at startup a key whose material another connection holds under another reference. +Each refusal names the colliding connection. +Bind every function host as `service-function`: an `external-http` connection gets none of these checks. +A record change stays a separate BReg step in the workflow. ```yaml connections: diff --git a/docs/site/src/content/docs/security/coordinator.mdx b/docs/site/src/content/docs/security/coordinator.mdx index 361fb0ecfd..0237761f2e 100644 --- a/docs/site/src/content/docs/security/coordinator.mdx +++ b/docs/site/src/content/docs/security/coordinator.mdx @@ -14,7 +14,7 @@ standards_referenced: [] This page states what Registry Coordinator holds, what it does not hold, and what you must do for its guarantees to hold. Each guarantee carries a stable identifier from `COORDINATOR-INV-01` to `COORDINATOR-INV-17`, and -each accepted residual risk one from `COORDINATOR-RES-01` to `COORDINATOR-RES-28`. +each accepted residual risk one from `COORDINATOR-RES-01` to `COORDINATOR-RES-29`. Terms follow [Author a Coordinator workflow](../../configure/coordinator/). Deployment steps are in [Deploy Registry Coordinator](../../operate/coordinator/). @@ -30,8 +30,9 @@ Deployment steps are in [Deploy Registry Coordinator](../../operate/coordinator/ operation catalogue does. - Providers decide every effect a run requests: Registry Casework, Registry Scheduling, BReg, the Registry Adapter payment host and external HTTP providers. - A service function is not a provider of record authority: Coordinator calls it with a credential - for its function host only, so a record change stays a separate step to the owning product. + A service function is not a provider of record authority. + Coordinator calls it with a credential distinct from every product credential the runtime file + declares, so a record change stays a separate step to the owning product. Coordinator holds workload identity, not decision authority, and each receiving product still authorises the call. - Coordinator verifies the access token against the matching entry in @@ -862,10 +863,10 @@ unknown, a timeout or a missing receipt authorises release or replacement. provider_confirmation_report_is_one_exact_keyed_command, disbursement_completion_settles_only_terminal_exactly_bound_state. */} -### COORDINATOR-INV-17: a service function call holds no product authority +### COORDINATOR-INV-17: a service function call holds no credential the runtime file gives a product -Threat: `service.invoke-function/v1` calls code a service declares in `service.yaml`, outside every -product's authorization. +Threat: `service.invoke-function/v1` calls code a service declares, outside every product's +authorization. A workflow could steer the call to another function, host or credential. A deployment could hand the function host a token a product accepts, such as the BReg connection's credential, so a function that forwards its incoming bearer would change records under the @@ -877,34 +878,47 @@ Enforcement: Transform builds. The runtime connection (`type: service-function`) fixes the function host `baseUrl`, the one bound `function`, and the credential. - Coordinator sends one POST to `functions/` under `baseUrl` and nowhere else; the - function name is a local identifier, so it cannot add a path segment. + Coordinator sends one POST to `functions/` under `baseUrl` and nowhere else. + The function name is a local identifier, so it cannot add a path segment. - `coordinatorctl check` refuses an alias without `serviceFunction`, a `serviceFunction` on any other operation, and an alias whose function is not the one its connection binds (`workflow-binding`). + It checks the name against the runtime connection only. + `rstack dev` also refuses a name the service's `service.yaml` does not declare. A connection of another type cannot carry the call. The function name is part of the Operation revision and the connection's binding digest, so a live Run cannot be moved to another function. -- The connection requires exactly one credential: an OAuth `authorization` without `taskAuthority`, +- The connection holds exactly one credential: an OAuth `authorization` without `taskAuthority`, or a `hostKeyRef` key only the function host accepts. `rstack dev` generates a per-run host key for the preview function host. - The runtime refuses a `resource`, `clientId`, `signingKeyRef` or `hostKeyRef` equal to any - product, external or evaluation connection's credential (`coordinator.runtime-config.refused` at - that member), so the function host credential is never one a product accepts. - A function that forwards that token to BReg is refused by BReg; any record change is a separate - BReg Action or Proposal step under the run's own connection. -- The call is an external command in every other respect (COORDINATOR-INV-03): the request id is - frozen before the first send and sent as `Idempotency-Key`, redirects are never followed, bodies - and responses are bounded, an ambiguous exchange holds the run, and only the pinned - interpretation Transform turns the response into an accepted result or a declared refusal. +- The credential is distinct from every credential and product audience the runtime file declares. + The runtime refuses a function `resource` equal to a product or external connection's + `resource`, a task authority `bootstrapResource` or `exchangeAudience`, or the Coordinator's own + `deployment.authentication.issuers.*.audience`. + URL resources are compared with the scheme and host in lower case, the default port dropped and a + lone `/` path removed. + It refuses a `clientId`, `signingKeyRef` or `hostKeyRef` such a connection uses. + Each refusal names the colliding connection and no value. + At startup the resolved keys are compared too, a JWK by its RFC 7638 thumbprint and any other key + by its bytes, so the same key under another reference is refused. +- The call is an external command in every other respect (COORDINATOR-INV-03). + The request id is frozen before the first send and sent as `Idempotency-Key`, redirects are never + followed, bodies and responses are bounded, an ambiguous exchange holds the run, and only the + pinned interpretation Transform turns the response into an accepted result or a declared refusal. Nothing an operator reads carries the body, request id or credential. -Refused: a workflow-chosen function, host, header or credential; a function the connection does not -bind; an anonymous function connection; a function credential shared with a product or external -connection; task authority on a function connection. +These checks prove only that the credential differs from the ones this file declares. +Whether a product elsewhere accepts the function host token is RES-28, and a function host bound as +`external-http` is not checked at all (RES-29). + +Refused: a workflow-chosen function, host, header or credential. +Also refused: a function the connection does not bind, a function connection with no credential or +two, a function credential matching a product, external or task authority credential or the +Coordinator's audience, and task authority on a function connection. {/* Evidence: crates/registry-coordinator/src/runtime.rs function_credential_findings, - validate_workflow_effect_bindings; + normalised_resource, validate_workflow_effect_bindings; + crates/registry-coordinator/src/adapters.rs distinct_function_keys; crates/registry-coordinator/src/external_http.rs ServiceFunctionConfig; crates/registry-coordinator/tests/service_function.rs a_call_posts_to_the_bound_function_with_the_function_host_credential, @@ -915,14 +929,23 @@ connection; task authority on a function connection. a_service_function_credential_is_never_a_product_credential, a_host_key_credential_is_sent_as_the_bearer_to_the_bound_function, a_function_connection_names_exactly_one_credential, - a_host_key_is_never_a_product_signing_key; + a_host_key_is_never_a_product_signing_key, + a_function_resource_is_compared_after_normalisation, + a_function_resource_is_never_a_casework_or_exchange_audience, + a_function_resource_is_never_a_scheduling_messaging_or_external_audience, + a_function_resource_is_never_the_coordinator_audience, + a_taskauthority_refusal_names_the_service_function_remedy, + the_same_signing_key_under_another_reference_is_refused_at_startup, + the_runtime_routes_a_function_call_with_its_oauth_token_and_frozen_request_id, + a_lost_acknowledgement_is_uncertain_and_the_same_request_id_is_sent_again. crates/registry-coordinator/tests/service_function_project.rs a_missing_function_name_is_refused_at_the_operation, only_the_service_function_operation_names_a_function, an_unbound_function_name_is_refused_against_the_runtime_binding, the_workflow_cannot_name_a_destination_or_credential, the_named_function_is_part_of_the_operation_revision, - a_function_reply_reaches_its_result_only_through_the_interpret_transform; + a_function_reply_reaches_its_result_only_through_the_interpret_transform, + unresolved_routed_straight_to_a_service_function_is_refused. crates/registry-coordinator/tests/service_function_postgres.rs an_accepted_function_call_records_the_step_and_its_typed_result, a_declared_refusal_takes_the_workflow_refusal_route, @@ -982,9 +1005,11 @@ The residuals refer to them by number. identities. Investigate an unresolved original-request receipt before any same-command recovery or cancellation decision (COORDINATOR-INV-16). -15. Give each `service-function` connection a client, signing key and resource that only its - function host accepts, scoped to the one function it binds, and add one connection per bound - function. +15. Bind every function host as `type: service-function`, never as `external-http`, so the + credential checks of COORDINATOR-INV-17 apply (RES-29). + Give each `service-function` connection a client, key and resource that only its function host + accepts, scoped to the one function it binds, and add one connection per bound function. + Register the function host resource only for the function host at the authorization server. Run the function host so that the function forwards the `Idempotency-Key` it receives to any effect it makes, as obligation 1 asks of an external provider (COORDINATOR-INV-17). @@ -1063,13 +1088,15 @@ Each residual names the condition under which it applies, its consequence, and t ### COORDINATOR-RES-07: no receipt settles an uncertain external command -- Condition: `external.command/v1` has no original-result receipt. -- Consequence: `reconcile` cannot settle an uncertain command. +- Condition: `external.command/v1` and `service.invoke-function/v1` have no original-result + receipt. +- Consequence: `reconcile` cannot settle an uncertain command or function call. - Mitigation: check the provider's records, then retry or cancel the held run. ### COORDINATOR-RES-08: an accepted result is the Transform's reading -- Condition: Coordinator does not independently verify the provider's effect. +- Condition: Coordinator does not independently verify the effect of an external command or a + service function call. - Consequence: a Transform that maps an ambiguous answer to `accepted` records an effect that may not have happened. - Mitigation: cover ambiguous answers in scenarios and review. @@ -1289,19 +1316,33 @@ Each residual names the condition under which it applies, its consequence, and t ### COORDINATOR-RES-28: a function credential is distinct, not proven unusable at a product -- Condition: a `service-function` connection names a resource, client and signing key no other - connection in the same runtime file uses. +- Condition: a `service-function` connection names a resource, client and key that no product, + external or task authority credential in the same runtime file uses. - Consequence: Coordinator cannot see the authorization server or the products of other deployments, so it cannot prove that the function host token is refused everywhere else. - An authorization server that mints the same audience for that resource, or a product that - accepts the function host resource, would give a function product authority. -- Mitigation: obligation 15; register the function host resource only for the function host at the - authorization server, and never list it as a product audience. + An authorization server that mints a product audience for the function host resource, or a + product that accepts the function host resource, would give a function product authority. +- Mitigation: obligation 15. + Register the function host resource only for the function host, and never list it as a product + audience. {/* Evidence: crates/registry-coordinator/src/runtime.rs function_credential_findings; crates/registry-coordinator/tests/service_function.rs a_service_function_credential_is_never_a_product_credential. */} +### COORDINATOR-RES-29: a function host bound as `external-http` is not checked + +- Condition: an operator binds a function host as `type: external-http` with a `commandPath` such + as `functions/`, and calls it with `external.command/v1`. +- Consequence: `external-http` credentials are never compared with product credentials, so that + connection can carry the BReg connection's resource, client and key, and a function that + forwards its bearer would act with product authority. +- Mitigation: obligation 15. + Bind function hosts as `service-function`. + A later release is planned to refuse product credentials on `external-http` connections too. + +{/* Evidence: crates/registry-coordinator/src/runtime.rs function_credential_findings. */} + ## Report a vulnerability Report a suspected vulnerability through the process in diff --git a/products/coordinator/CHANGELOG.md b/products/coordinator/CHANGELOG.md index b8b6d0ec93..6a68751c72 100644 --- a/products/coordinator/CHANGELOG.md +++ b/products/coordinator/CHANGELOG.md @@ -3,7 +3,7 @@ ## Unreleased - BREAKING: Name the bounded Rhai computations in a Coordinator workflow Transforms. Rename `functions` to `transforms` and use `type: transform` with a `transform` member in mappings. Use `coordinatorctl explain transforms` for the interpreter helpers and update diagnostic consumers from `coordinator.function.*` to `coordinator.transform.*`. Retained definition snapshots keep their reader and revision format. -- Add `service.invoke-function/v1`, which calls one service function declared in `service.yaml`. The workflow names it with `serviceFunction`. A `type: service-function` runtime connection binds the function host, that one function and a credential for the host alone. `check` refuses a missing name, a name the connection does not bind, and a function credential whose resource, client or signing key matches a product or external connection, so a function holds no record authority. Calls follow external command recovery and require an `interpret` Transform. +- Add `service.invoke-function/v1`, which calls one service function. The workflow names it with `serviceFunction`. A `type: service-function` runtime connection binds the function host, that one function and one credential for the host alone: an OAuth `authorization` or a `hostKeyRef` key. `check` refuses a missing name and a name the connection does not bind. The runtime refuses a function credential whose resource, client or key matches a product, external or task authority credential or the Coordinator's own audience, and compares resolved key material at startup. Calls follow external command recovery and require an `interpret` Transform. ## 0.49.0 - 2026-12-01 diff --git a/products/coordinator/generated/project/project.schema.json b/products/coordinator/generated/project/project.schema.json index 022a923337..ba614a461a 100644 --- a/products/coordinator/generated/project/project.schema.json +++ b/products/coordinator/generated/project/project.schema.json @@ -363,7 +363,7 @@ }, "serviceFunction": { "$ref": "#/$defs/LocalId", - "description": "The one service function `service.invoke-function/v1` calls, as the\nservice's `service.yaml` declares it. Required on, and accepted only\non, that Operation. The runtime connection binds its host and\ncredential; the workflow supplies neither." + "description": "The one service function `service.invoke-function/v1` calls. Required\non, and accepted only on, that Operation. `check` matches it against\nthe function the runtime connection binds; `rstack dev` also checks it\nagainst `service.yaml`. The runtime connection binds the host and\ncredential, and the workflow supplies neither." }, "template": { "$ref": "#/$defs/TemplateReference", diff --git a/products/coordinator/generated/runtime/runtime.schema.json b/products/coordinator/generated/runtime/runtime.schema.json index e3f995c378..e03f1fcfd2 100644 --- a/products/coordinator/generated/runtime/runtime.schema.json +++ b/products/coordinator/generated/runtime/runtime.schema.json @@ -473,7 +473,7 @@ }, { "additionalProperties": false, - "description": "One service function declared in the service's `service.yaml`, bound by the\ndeployment to its function host and to a credential for that host alone.\nThe workflow names the function; it never supplies the destination or the\ncredential. The function host serves the function at `functions/`\nunder the base URL.", + "description": "One service function, bound by the deployment to its function host and to a\ncredential for that host alone. `rstack dev` checks the name against the\nservice's `service.yaml`; an operator recipe binds a name it has checked.\nThe workflow names the function; it never supplies the destination or the\ncredential. The function host serves the function at `functions/`\nunder the base URL.", "properties": { "attemptTimeoutMilliseconds": { "default": 2000, @@ -497,7 +497,7 @@ }, "function": { "$ref": "#/$defs/LocalId", - "description": "The one function this connection binds, as `service.yaml` declares it." + "description": "The one function this connection binds." }, "hostKeyRef": { "$ref": "#/$defs/SecretReference", From 001fb300a68254f139ad1db5dc7df45af046eea8 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 21:00:14 +0000 Subject: [PATCH 132/183] feat(dev): bind Coordinator service functions to the preview function host rstack dev reserves the preview function host port before products start, keeping it with the Coordinator state, and writes a per-run host key. Each service-function connection gets that address and the key as its hostKeyRef, and a function the preview does not serve is refused. The preview host takes the reserved port and key from the run input and admits the gateway or a caller presenting the host key as its bearer, a key no product accepts. Refs #2888 Signed-off-by: Jeremi Joslin --- clients/typescript/preview/config.mjs | 15 +- clients/typescript/preview/host.mjs | 31 ++- clients/typescript/preview/run.mjs | 10 +- .../typescript/preview/tests/preview.test.mjs | 53 +++- crates/registry-rstack-dev/src/products.rs | 260 +++++++++++++++++- 5 files changed, 356 insertions(+), 13 deletions(-) diff --git a/clients/typescript/preview/config.mjs b/clients/typescript/preview/config.mjs index 9202fe02f1..171ad39bb6 100644 --- a/clients/typescript/preview/config.mjs +++ b/clients/typescript/preview/config.mjs @@ -59,10 +59,16 @@ export async function prepareRuntimeConfig({ artifact, deployment, run }) { || run.preview.productId !== artifact.product.id || run.preview.profile !== artifact.product.profile) { throw new Error('The preview product or audience differs from the checked plan.') } - const { authorizationFile } = run.preview + const { authorizationFile, functionHost } = run.preview if (typeof authorizationFile !== 'string' || !isAbsolute(authorizationFile)) { throw new Error('The preview needs an owner-only run authorization file.') } + const functionPort = functionHost?.port + if (!Number.isInteger(functionPort) || functionPort < 1 || functionPort > 65535 || functionPort === port + || `http://127.0.0.1:${functionPort}` === run.breg.baseUrl + || typeof functionHost.keyFile !== 'string' || !isAbsolute(functionHost.keyFile)) { + throw new Error('The preview needs the reserved function host port and owner-only host key file.') + } return { schema, runId: run.runId, origin, port, breg: run.breg, preview: run.preview } } @@ -77,6 +83,7 @@ async function checkCredentialPath(path, runFile) { export async function configure({ artifact, deployment, runFile }) { const config = await prepareRuntimeConfig({ artifact, deployment, run: await readJson(runFile) }) await checkCredentialPath(config.preview.authorizationFile, runFile) + await checkCredentialPath(config.preview.functionHost.keyFile, runFile) return config } @@ -94,6 +101,12 @@ export async function checkRuntimeConfig(configFile, artifact) { return checked } +export async function readHostKey(path) { + const key = /^([A-Za-z0-9_-]{32,256})\n?$/u.exec(await readFile(path, 'utf8'))?.[1] + if (!key) throw new Error('Expected the run function host key file.') + return key +} + export async function readAuthorization(path) { const line = await readFile(path, 'utf8') const authorization = /^Authorization: (Bearer [A-Za-z0-9._-]+)\r?\n?$/u.exec(line)?.[1] diff --git a/clients/typescript/preview/host.mjs b/clients/typescript/preview/host.mjs index 1c5dc2f564..c784bb1f6a 100644 --- a/clients/typescript/preview/host.mjs +++ b/clients/typescript/preview/host.mjs @@ -1,12 +1,39 @@ +import { timingSafeEqual } from 'node:crypto' import { serve } from 'srvx/node' export const maxRequestBodySize = 32_768 -export async function startFunctionHost(handlers, { authorize }) { +const hostKeyPattern = /^[A-Za-z0-9_-]{32,256}$/u + +function same(value, expected) { + const given = Buffer.from(value ?? '') + return given.length === expected.length && timingSafeEqual(given, expected) +} + +// The run's function host key admits two callers: the preview gateway, which +// relays the page's principal and names the key in its own header, and +// Coordinator, which presents the key itself as its bearer credential. No +// product accepts the key, so a function called by Coordinator holds no +// record authority. +export function functionHostAuthorizer(key) { + if (typeof key !== 'string' || !hostKeyPattern.test(key)) { + throw new TypeError('The function host needs a run host key.') + } + const relayed = Buffer.from(key) + const bearer = Buffer.from('Bearer ' + key) + return request => { + const header = request.headers.get('x-registry-preview-function') + return header === null + ? same(request.headers.get('authorization'), bearer) + : same(header, relayed) + } +} + +export async function startFunctionHost(handlers, { authorize, port = 0 }) { if (typeof authorize !== 'function') throw new TypeError('The private function host requires an authorization check.') const server = serve({ hostname: '127.0.0.1', - port: 0, + port, silent: true, gracefulShutdown: false, maxRequestBodySize, diff --git a/clients/typescript/preview/run.mjs b/clients/typescript/preview/run.mjs index c7cae5771a..ed52874072 100644 --- a/clients/typescript/preview/run.mjs +++ b/clients/typescript/preview/run.mjs @@ -1,9 +1,8 @@ -import { randomBytes } from 'node:crypto' import { writeFile } from 'node:fs/promises' import { dirname, join } from 'node:path' -import { artifactDirectory, checkRuntimeConfig, configEnvironment, readArtifact, readAuthorization } from './config.mjs' +import { artifactDirectory, checkRuntimeConfig, configEnvironment, readArtifact, readAuthorization, readHostKey } from './config.mjs' import { startPreviewGateway } from './gateway.mjs' -import { startFunctionHost } from './host.mjs' +import { functionHostAuthorizer, startFunctionHost } from './host.mjs' async function run() { const configFile = process.env[configEnvironment] @@ -24,9 +23,10 @@ async function run() { } } - const functionKey = randomBytes(32).toString('base64url') + const functionKey = await readHostKey(config.preview.functionHost.keyFile) const privateHost = await startFunctionHost(handlers, { - authorize: request => request.headers.get('x-registry-preview-function') === functionKey, + authorize: functionHostAuthorizer(functionKey), + port: config.preview.functionHost.port, }) let gateway try { diff --git a/clients/typescript/preview/tests/preview.test.mjs b/clients/typescript/preview/tests/preview.test.mjs index a7d28e215c..6a302a7a63 100644 --- a/clients/typescript/preview/tests/preview.test.mjs +++ b/clients/typescript/preview/tests/preview.test.mjs @@ -4,7 +4,7 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import { createServer, request } from 'node:http' import { test } from 'node:test' -import { startFunctionHost } from '../host.mjs' +import { functionHostAuthorizer, startFunctionHost } from '../host.mjs' import { collectStaticFiles, previewPolicy, startPreviewGateway } from '../gateway.mjs' import { prepareRuntimeConfig } from '../config.mjs' import { buildPreview } from '../build.mjs' @@ -63,16 +63,21 @@ test('prepare binds the run to the declaration, product, audience and loopback a const authorizationFile = join(root, 'authorization') await writeFile(deployment, 'service declaration') await writeFile(authorizationFile, 'Authorization: Bearer synthetic.actor.token\n', { mode: 0o600 }) + const keyFile = join(root, 'function-host-key') const declarationDigest = createHash('sha256').update('service declaration').digest('hex') const artifact = { declarationDigest, product: { id: 'licenses', member: 'licenses', audience: 'urn:preview', profile: 'holder' } } const run = { schema: 'registry-stack.local-service-preview/v1', runId: 'fixture-run', origin: 'http://127.0.0.1:23456', port: 23456, insecureLocal: true, breg: { baseUrl: 'http://127.0.0.1:34567', audience: 'urn:preview' }, - preview: { productId: 'licenses', profile: 'holder', authorizationFile, declarationDigest }, + preview: { + productId: 'licenses', profile: 'holder', authorizationFile, declarationDigest, + functionHost: { port: 45678, keyFile }, + }, } const valid = await prepareRuntimeConfig({ artifact, deployment, run }) assert.equal(valid.breg.baseUrl, run.breg.baseUrl) + assert.deepEqual(valid.preview.functionHost, { port: 45678, keyFile }) for (const invalid of [ { ...run, breg: { ...run.breg, audience: 'urn:wrong' } }, { ...run, breg: { ...run.breg, baseUrl: 'http://example.test:34567' } }, @@ -80,6 +85,11 @@ test('prepare binds the run to the declaration, product, audience and loopback a { ...run, preview: { ...run.preview, profile: 'wrong' } }, { ...run, preview: { ...run.preview, declarationDigest: 'wrong' } }, { ...run, port: 34567 }, + { ...run, preview: { ...run.preview, functionHost: undefined } }, + { ...run, preview: { ...run.preview, functionHost: { port: 23456, keyFile } } }, + { ...run, preview: { ...run.preview, functionHost: { port: 34567, keyFile } } }, + { ...run, preview: { ...run.preview, functionHost: { port: 0, keyFile } } }, + { ...run, preview: { ...run.preview, functionHost: { port: 45678, keyFile: 'relative-key' } } }, ]) { await assert.rejects(prepareRuntimeConfig({ artifact, deployment, run: invalid })) } @@ -199,3 +209,42 @@ test('build refuses a changed declaration or a linked function before staging', preview: { ...plan.preview, functions: ['linked'] }, }, join(root, 'artifact')), /source resolves outside/i) }) + +test('the function host binds its reserved port and admits only the run host key', async (t) => { + const key = 'synthetic-function-host-key-0123456789abcdefghij' + const authorize = functionHostAuthorizer(key) + const call = headers => new Request('http://127.0.0.1/functions/renew', { method: 'POST', headers }) + // The gateway relays the page's principal with the host key header. + assert.equal(authorize(call({ authorization: 'Bearer page.token', 'x-registry-preview-function': key })), true) + // Coordinator presents the host key itself as its bearer credential. + assert.equal(authorize(call({ authorization: 'Bearer ' + key })), true) + for (const headers of [ + { authorization: 'Bearer page.token' }, + { authorization: 'Bearer ' + key + 'x' }, + { authorization: 'Bearer page.token', 'x-registry-preview-function': 'wrong' }, + { authorization: 'Bearer ' + key, 'x-registry-preview-function': 'wrong' }, + ]) { + assert.equal(authorize(call(headers)), false, JSON.stringify(headers)) + } + assert.throws(() => functionHostAuthorizer('short')) + + const reservation = createServer() + await new Promise(resolve => reservation.listen(0, '127.0.0.1', resolve)) + const { port } = reservation.address() + await new Promise(resolve => reservation.close(resolve)) + let seen + const host = await startFunctionHost(new Map([ + ['renew', async request => { + seen = request.headers.get('authorization') + return new Response('renewed') + }], + ]), { authorize, port }) + t.after(() => host.close()) + assert.equal(host.origin, 'http://127.0.0.1:' + port) + const route = host.origin + '/functions/renew' + assert.equal((await fetch(route, { method: 'POST', headers: { authorization: 'Bearer other.token' } })).status, 401) + const answer = await fetch(route, { method: 'POST', headers: { authorization: 'Bearer ' + key } }) + assert.equal(await answer.text(), 'renewed') + // The function receives the host key, which no product accepts. + assert.equal(seen, 'Bearer ' + key) +}) diff --git a/crates/registry-rstack-dev/src/products.rs b/crates/registry-rstack-dev/src/products.rs index 1fef38b82e..9b239fad63 100644 --- a/crates/registry-rstack-dev/src/products.rs +++ b/crates/registry-rstack-dev/src/products.rs @@ -120,9 +120,22 @@ pub(super) struct ApplicationLaunch { pub(super) workdir: PathBuf, pub(super) environment: BTreeMap, pub(super) reservation: TcpListener, + /// The preview's private function host port, held until the host starts. + pub(super) function_host: Option, pub(super) health_path: String, } +/// The preview's private function host: a loopback port reserved before any +/// product starts, so Coordinator can name it, and a per-run key that only +/// the function host accepts. Coordinator presents the key as the bearer of +/// its service function calls; no product accepts it. +struct FunctionHost { + listener: RefCell>, + port: u16, + key_ref: String, + key_file: PathBuf, +} + pub(super) struct PreparedApplication { pub(super) launch: ApplicationLaunch, pub(super) client: Option, @@ -346,6 +359,7 @@ pub(super) struct ProductRunner<'a> { /// The loopback key set server Evidence's target names, stopped with the run. jwks: Option, coordinator_issuer: Option, + function_host: Option, /// The mock gateway Messaging's `http` providers send to, stopped with the /// run. gateway: Option, @@ -388,6 +402,7 @@ impl<'a> ProductRunner<'a> { issuer_listener: None, jwks: None, coordinator_issuer: None, + function_host: None, gateway: None, hook_sink: None, signed_hook_sinks: BTreeMap::new(), @@ -557,6 +572,7 @@ impl<'a> ProductRunner<'a> { &issuer.public_jwks(), )?); } + self.reserve_function_host()?; // Keep the reservations for later products until each is ready to bind. let ports: Vec<_> = self .input @@ -687,6 +703,7 @@ impl<'a> ProductRunner<'a> { let log = open_log(self.root, "application-runtime")?; command.stdout(log.try_clone()?).stderr(log); drop(launch.reservation); + drop(launch.function_host); let child = command .spawn() .context("cannot start application") @@ -792,6 +809,7 @@ impl<'a> ProductRunner<'a> { "profile": build.product.profile, "declarationDigest": build.declaration_digest, "authorizationFile": authorization_file, + "functionHost": self.function_host_input()?, }, }), None, @@ -870,6 +888,11 @@ impl<'a> ProductRunner<'a> { workdir: root.to_owned(), environment, reservation, + function_host: preview_artifact.and_then(|_| { + self.function_host + .as_ref() + .and_then(|host| host.listener.borrow_mut().take()) + }), health_path: plan.health_path.clone(), }, client, @@ -1628,6 +1651,7 @@ impl<'a> ProductRunner<'a> { authentication["accessProfiles"] = json!(profiles); let key = |file| self.retained_secret(name, file, random_key_bytes()?.as_slice()); let mut connections = runtime["connections"].clone(); + self.bind_service_functions(&mut connections)?; if let Some(connections) = connections.as_object_mut() { for (id, connection) in connections { registry_platform_yaml::LocalId::new(id.as_str()) @@ -1901,6 +1925,86 @@ impl<'a> ProductRunner<'a> { Ok(path) } + /// Reserve the preview function host before products start. The port is + /// kept with the Coordinator state, like its issuer, because a live + /// workflow binds the function host address. + fn reserve_function_host(&mut self) -> Result<()> { + if self.input.plan.preview.is_none() || self.function_host.is_some() { + return Ok(()); + } + let state = self + .input + .plan + .products + .iter() + .any(|entry| entry.product == Product::Coordinator) + .then(|| self.product_state("coordinator")) + .flatten(); + let listener = retained_loopback_listener( + state.as_deref(), + "preview-function-host-port", + "the preview function host", + )?; + let port = listener.local_addr()?.port(); + let key_ref = self.secret(FUNCTION_HOST_KEY, random_secret()?.as_bytes())?; + self.function_host = Some(FunctionHost { + listener: RefCell::new(Some(listener)), + port, + key_ref, + key_file: self.root.join(FUNCTION_HOST_KEY), + }); + Ok(()) + } + + /// Bind each `service-function` connection to the preview function host + /// and its per-run key. The function must be one the preview serves, + /// which `service.yaml` declares. + fn bind_service_functions(&self, connections: &mut Value) -> Result<()> { + let Some(connections) = connections.as_object_mut() else { + return Ok(()); + }; + for (id, connection) in connections { + if connection["type"] != "service-function" { + continue; + } + let host = self.function_host.as_ref().with_context(|| { + format!("Coordinator connection {id} calls a service function, which needs the preview function host. Declare preview.functions in dev.yaml.") + })?; + let function = connection["function"] + .as_str() + .with_context(|| format!("Coordinator connection {id} names no function"))?; + let served = self.input.plan.preview.as_ref().is_some_and(|preview| { + preview + .functions + .iter() + .any(|name| name.as_str() == function) + }); + ensure!( + served, + "Coordinator connection {id} binds function {function}, which the preview does not serve. Declare it in service.yaml functions and dev.yaml preview.functions." + ); + let object = connection + .as_object_mut() + .context("a Coordinator connection must be a mapping")?; + object.remove("authorization"); + object.insert( + "baseUrl".into(), + json!(format!("http://127.0.0.1:{}/", host.port)), + ); + object.insert("hostKeyRef".into(), json!(host.key_ref)); + } + Ok(()) + } + + /// The preview run input's function host member. + fn function_host_input(&self) -> Result { + let host = self + .function_host + .as_ref() + .context("missing preview function host reservation")?; + Ok(json!({"port": host.port, "keyFile": host.key_file})) + } + fn product_state(&self, name: &str) -> Option { self.input .project_state(self.root) @@ -2094,19 +2198,31 @@ fn needs_stable_issuer(runtime: &Value, external_jwks: Option<&str>) -> bool { } fn coordinator_issuer_listener(state: Option<&Path>) -> Result { + retained_loopback_listener( + state, + "coordinator-issuer-port", + "the Coordinator development issuer", + ) +} + +const FUNCTION_HOST_KEY: &str = "preview-function-host-key"; + +/// A loopback listener whose port is kept in the project state, so a resumed +/// run binds the same address its live workflows name. +fn retained_loopback_listener(state: Option<&Path>, name: &str, what: &str) -> Result { let Some(state) = state else { return Ok(TcpListener::bind((Ipv4Addr::LOCALHOST, 0))?); }; - let file = state.join("coordinator-issuer-port"); + let file = state.join(name); let port = match super::read_private(&file)? { Some(saved) => std::str::from_utf8(&saved)? .parse::() - .context("the retained Coordinator issuer port is invalid")? + .with_context(|| format!("the retained port of {what} is invalid"))? .get(), None => 0, }; let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, port)).with_context(|| { - format!("cannot bind the Coordinator development issuer on loopback port {port}, which is kept for resumable workflow connections. Start with --clean") + format!("cannot bind {what} on loopback port {port}, which is kept for resumable workflow connections. Start with --clean") })?; if port == 0 { write_private(&file, listener.local_addr()?.port().to_string().as_bytes())?; @@ -5326,6 +5442,7 @@ mod tests { workdir: root.to_path_buf(), environment, reservation, + function_host: None, health_path: "/health".to_owned(), }, port, @@ -5478,6 +5595,143 @@ mod tests { assert_eq!(restarted.local_addr().unwrap(), address); } + /// A Coordinator project whose runtime declares one service function + /// connection, run with a preview serving `served`. + fn function_runner_input(served: Option<&[&str]>) -> RunInput { + let mut input = breg_input(false); + input.plan.products = serde_json::from_value(json!([ + {"product": "breg", "project": ".", "audience": "registry"}, + {"product": "coordinator", "project": ".", "audience": "urn:example:local"} + ])) + .unwrap(); + input.plan.people.clear(); + input.plan.people.insert( + "tester".to_owned(), + serde_json::from_value(json!({ + "subject": "tester", "client": "console", + "grants": {"coordinator": {"profile": "local-console", "scopes": ["read"]}} + })) + .unwrap(), + ); + input.plan.preview = served.map(|functions| { + serde_json::from_value(json!({ + "actor": "tester", "page": "/", "breg": {}, "functions": functions + })) + .unwrap() + }); + input + } + + fn function_project(root: &Path) -> PathBuf { + let package = root.join("package"); + fs::create_dir(&package).unwrap(); + fs::write(package.join("SHA256SUMS"), b"test checksum file").unwrap(); + fs::write(root.join("workflow.yaml"), "project: {id: notices}").unwrap(); + fs::write( + root.join("runtime.yaml"), + "connections:\n drafts:\n type: service-function\n baseUrl: http://127.0.0.1:1/\n function: draft-notice\n authorization: {tokenEndpoint: 'http://127.0.0.1:1/token', clientAssertionAudience: 'http://127.0.0.1:1', clientId: authored, signingKeyRef: 'secret:file/authored-key', resource: 'urn:example:authored', scopes: [x]}\n responseSchema: {type: object}\n", + ) + .unwrap(); + package + } + + fn coordinator_config(runner: &ProductRunner, root: &Path, package: &Path) -> Result { + let database = DatabaseUrls { + runtime: "postgresql://runtime@localhost/database".to_owned(), + migration: "postgresql://migration@localhost/database".to_owned(), + transport: DatabaseTransport::VerifiedTls, + }; + runner.additional_config( + Product::Coordinator, + root, + "127.0.0.1:34567", + package, + Some(&database), + ) + } + + #[test] + fn a_service_function_connection_names_the_preview_host_and_its_run_key() { + use std::os::unix::fs::PermissionsExt; + let root = tempfile::tempdir().unwrap(); + let package = function_project(root.path()); + let terminate = AtomicBool::new(false); + let mut runner = ProductRunner::new( + Arc::new(function_runner_input(Some(&[ + "draft-notice", + "publish-notice", + ]))), + root.path(), + &terminate, + ) + .unwrap(); + runner.reserve_function_host().unwrap(); + let host = runner.function_host.as_ref().unwrap(); + let port = host.port; + let config = coordinator_config(&runner, root.path(), &package).unwrap(); + let drafts = &config["connections"]["drafts"]; + assert_eq!(drafts["baseUrl"], format!("http://127.0.0.1:{port}/")); + assert_eq!(drafts["hostKeyRef"], secret_ref(FUNCTION_HOST_KEY)); + assert!(drafts.get("authorization").is_none(), "{drafts}"); + + // The key is an owner-only bearer-safe secret in the run directory, + // the same file the preview host reads. + let key_file = root.path().join(FUNCTION_HOST_KEY); + let key = fs::read_to_string(&key_file).unwrap(); + assert!( + key.len() >= 32 + && key + .bytes() + .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_') + ); + assert_eq!( + fs::metadata(&key_file).unwrap().permissions().mode() & 0o777, + 0o600 + ); + assert_eq!( + runner.function_host_input().unwrap(), + json!({"port": port, "keyFile": key_file}) + ); + // The port stays reserved until the preview host starts. + assert!(TcpListener::bind((Ipv4Addr::LOCALHOST, port)).is_err()); + } + + #[test] + fn a_service_function_the_preview_does_not_serve_is_refused() { + let root = tempfile::tempdir().unwrap(); + let package = function_project(root.path()); + let terminate = AtomicBool::new(false); + let mut runner = ProductRunner::new( + Arc::new(function_runner_input(Some(&["publish-notice"]))), + root.path(), + &terminate, + ) + .unwrap(); + runner.reserve_function_host().unwrap(); + let error = coordinator_config(&runner, root.path(), &package) + .unwrap_err() + .to_string(); + assert!( + error.contains("draft-notice") && error.contains("service.yaml"), + "{error}" + ); + + let root = tempfile::tempdir().unwrap(); + let package = function_project(root.path()); + let mut runner = ProductRunner::new( + Arc::new(function_runner_input(None)), + root.path(), + &terminate, + ) + .unwrap(); + runner.reserve_function_host().unwrap(); + assert!(runner.function_host.is_none()); + let error = coordinator_config(&runner, root.path(), &package) + .unwrap_err() + .to_string(); + assert!(error.contains("preview.functions"), "{error}"); + } + #[test] fn additional_runtime_configuration_uses_run_authority_and_loopback() { let root = tempfile::tempdir().unwrap(); From fbfcc52a259c09743ebc78dd8bfba7415d074c7f Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 20:15:23 +0000 Subject: [PATCH 133/183] fix(client): keep the caller credential out of preview function handlers The generated defineFunction binding binds the request's bearer token to the typed Registry client, then passes the handler a copy of the request without Authorization so application logging never sees it. Refs #2866. Signed-off-by: Jeremi Joslin --- clients/typescript/generate-service.ts | 5 ++- .../typescript/tests/generate-preview.test.ts | 32 ++++++++++++++++--- .../docs/reference/typescript-clients.mdx | 5 +-- 3 files changed, 34 insertions(+), 8 deletions(-) diff --git a/clients/typescript/generate-service.ts b/clients/typescript/generate-service.ts index 41f7d0237f..0a37f78497 100644 --- a/clients/typescript/generate-service.ts +++ b/clients/typescript/generate-service.ts @@ -388,7 +388,10 @@ export function generatePreviewFunctionBinding(productId: string, member: string ' })', ' }', ' const client = createRegistryServerClient({ baseUrl, token: () => credential })[' + key + ']', - ' return handle(request, client)', + ' // The client carries the caller credential, so the handler gets a request without it.', + ' const headers = new Headers(request.headers)', + ' headers.delete("authorization")', + ' return handle(new Request(request, { headers }), client)', ' }', '}', '', diff --git a/clients/typescript/tests/generate-preview.test.ts b/clients/typescript/tests/generate-preview.test.ts index 69a74ca1fb..8e2141b161 100644 --- a/clients/typescript/tests/generate-preview.test.ts +++ b/clients/typescript/tests/generate-preview.test.ts @@ -10,7 +10,7 @@ const root = fileURLToPath(new URL('../', import.meta.url)) const fixture = fileURLToPath(new URL('./fixtures/breg-list.openapi.json', import.meta.url)) const { name, version } = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8')) as { name: string; version: string } -test('preview generation splits page and function bindings and scopes credentials to each request', t => { +test('preview generation splits page and function bindings and keeps request credentials out of handlers', t => { const dir = mkdtempSync(join(tmpdir(), 'registry-preview-generator-')) t.after(() => rmSync(dir, { recursive: true, force: true })) const compiler = join(dir, 'bregctl') @@ -83,22 +83,44 @@ await createRegistryClient().licences.list('licence', options) assert.equal(new URL(calls[0][0]).pathname, '/registry/licence-registry/v1/records/licences') assert.equal(calls[0][1].get('authorization'), null) assert.equal(calls[0][1].get('registry-client'), 'page') +const handled = new Map() +let completeAdmission +const bothAdmitted = new Promise(resolve => { completeAdmission = resolve }) const bind = defineFunction(async (request, licences) => { const profile = new URL(request.url).searchParams.get('profile') + assert.ok(!request.headers.has('authorization'), 'function handlers receive no Authorization header') + assert.equal(request.method, 'POST') + assert.equal(request.headers.get('content-type'), 'application/json') + assert.deepEqual(await request.json(), { profile }) + handled.set(profile, request.signal) + if (handled.size === 2) completeAdmission() + await bothAdmitted await licences.list('licence', profile === 'licence-holder' ? options : { accessProfile: 'licence-officer' }) return new Response(null, { status: 204 }) }) assert.throws(() => bind({ products: { licences: { baseUrl: 'http://127.0.0.1:54321' } } }), /Missing prepared BReg connection/) const handler = bind({ products: { 'licence-registry': { baseUrl: 'http://127.0.0.1:54321' } } }) -const request = (profile, credential) => new Request('http://127.0.0.1:6789/?profile=' + profile, - credential ? { headers: { authorization: 'Bearer ' + credential } } : {}) +const request = (profile, credential, signal) => { + const headers = { 'content-type': 'application/json' } + if (credential) headers.Authorization = 'Bearer ' + credential + return new Request('http://127.0.0.1:6789/?profile=' + profile, + { headers, method: 'POST', body: JSON.stringify({ profile }), signal }) +} assert.equal((await handler(request('licence-holder'))).status, 401) assert.equal((await handler(request('licence-holder', 'a,b'))).status, 401) assert.equal(calls.length, 1) +const holder = new AbortController() +const officer = new AbortController() +const holderRequest = request('licence-holder', 'synthetic-holder', holder.signal) +const officerRequest = request('licence-officer', 'synthetic-officer', officer.signal) await Promise.all([ - handler(request('licence-holder', 'synthetic-holder')), - handler(request('licence-officer', 'synthetic-officer')), + handler(holderRequest), + handler(officerRequest), ]) +assert.ok(holderRequest.headers.has('authorization') && officerRequest.headers.has('authorization')) +holder.abort() +assert.ok(handled.get('licence-holder').aborted) +assert.ok(!handled.get('licence-officer').aborted) assert.deepEqual(calls.slice(1).map(([url, headers]) => { const target = new URL(url) return [target.origin + target.pathname, target.searchParams.get('accessProfile'), headers.get('authorization')] diff --git a/docs/site/src/content/docs/reference/typescript-clients.mdx b/docs/site/src/content/docs/reference/typescript-clients.mdx index 49713da5ad..c3cae52796 100644 --- a/docs/site/src/content/docs/reference/typescript-clients.mdx +++ b/docs/site/src/content/docs/reference/typescript-clients.mdx @@ -156,8 +156,9 @@ generates three entry points in the owned build directory. Import `createRegistr from `generated/service.ts` and `functionPaths` from `generated/routes.ts` in your page. Function paths are relative to the preview origin. A function entry imports `defineFunction` from `generated/server.ts`. Its callback receives the request and a typed -client bound to that request's caller and the private BReg address. Keep the server entry in -the function's import graph. +client bound to that request's caller and the private BReg address. The binding removes the +`Authorization` header before the callback sees the request, so only the typed client holds +the caller's credential. Keep the server entry in the function's import graph. {/* Evidence: crates/registry-rstack/src/cli.rs; clients/typescript/generate-project.ts; From 11d0b81dfa7c31a37dc23d3936bbc9a56358199f Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 20:24:34 +0000 Subject: [PATCH 134/183] fix(client): give preview handlers a fresh request without credentials The srvx function host passes its own request class, which the native Request constructor cannot copy, so every hosted function answered 500. Build a fresh native request from its parts; it also leaves out the host's raw node headers, and drops Cookie and Proxy-Authorization as well as Authorization. Refs #2866. Signed-off-by: Jeremi Joslin --- clients/typescript/generate-service.ts | 10 ++-- .../typescript/tests/generate-preview.test.ts | 53 ++++++++++++++++++- .../docs/reference/typescript-clients.mdx | 8 +-- 3 files changed, 63 insertions(+), 8 deletions(-) diff --git a/clients/typescript/generate-service.ts b/clients/typescript/generate-service.ts index 0a37f78497..cf17029ce2 100644 --- a/clients/typescript/generate-service.ts +++ b/clients/typescript/generate-service.ts @@ -388,10 +388,14 @@ export function generatePreviewFunctionBinding(productId: string, member: string ' })', ' }', ' const client = createRegistryServerClient({ baseUrl, token: () => credential })[' + key + ']', - ' // The client carries the caller credential, so the handler gets a request without it.', + ' // The client carries the caller credential, so the handler gets a copy without credentials.', + ' // A fresh native request also leaves out a host\'s own request object and its raw headers.', ' const headers = new Headers(request.headers)', - ' headers.delete("authorization")', - ' return handle(new Request(request, { headers }), client)', + ' for (const name of ["authorization", "cookie", "proxy-authorization"]) headers.delete(name)', + ' const copy = new Request(request.url, {', + ' method: request.method, headers, body: request.body, duplex: "half", signal: request.signal,', + ' } as RequestInit)', + ' return handle(copy, client)', ' }', '}', '', diff --git a/clients/typescript/tests/generate-preview.test.ts b/clients/typescript/tests/generate-preview.test.ts index 8e2141b161..a81f8163b1 100644 --- a/clients/typescript/tests/generate-preview.test.ts +++ b/clients/typescript/tests/generate-preview.test.ts @@ -66,12 +66,15 @@ test('preview generation splits page and function bindings and keeps request cre '--outDir', compiled, join(generated, 'service.ts'), join(generated, 'server.ts'), join(generated, 'routes.ts')], { encoding: 'utf8' }) assert.equal(types.status, 0, types.stdout + types.stderr) - const run = spawnSync(process.execPath, ['--input-type=module', '-', compiled], { encoding: 'utf8', input: ` + const host = join(root, 'preview', 'host.mjs') + const run = spawnSync(process.execPath, ['--input-type=module', '-', compiled, host], { encoding: 'utf8', input: ` import assert from 'node:assert/strict' import { pathToFileURL } from 'node:url' const generated = pathToFileURL(process.argv[2] + '/') +const { startFunctionHost } = await import(pathToFileURL(process.argv[3])) globalThis.location = { origin: 'http://127.0.0.1:12345' } const calls = [] +const networkFetch = globalThis.fetch globalThis.fetch = async (url, init) => { calls.push([String(url), new Headers(init.headers)]) return Response.json({ items: [], pageInfo: { nextCursor: null } }) @@ -89,6 +92,8 @@ const bothAdmitted = new Promise(resolve => { completeAdmission = resolve }) const bind = defineFunction(async (request, licences) => { const profile = new URL(request.url).searchParams.get('profile') assert.ok(!request.headers.has('authorization'), 'function handlers receive no Authorization header') + assert.equal(request.headers.get('cookie'), null) + assert.equal(request.headers.get('proxy-authorization'), null) assert.equal(request.method, 'POST') assert.equal(request.headers.get('content-type'), 'application/json') assert.deepEqual(await request.json(), { profile }) @@ -101,7 +106,7 @@ const bind = defineFunction(async (request, licences) => { assert.throws(() => bind({ products: { licences: { baseUrl: 'http://127.0.0.1:54321' } } }), /Missing prepared BReg connection/) const handler = bind({ products: { 'licence-registry': { baseUrl: 'http://127.0.0.1:54321' } } }) const request = (profile, credential, signal) => { - const headers = { 'content-type': 'application/json' } + const headers = { 'content-type': 'application/json', cookie: 'session=browser', 'proxy-authorization': 'Basic cHJveHk6cHJveHk=' } if (credential) headers.Authorization = 'Bearer ' + credential return new Request('http://127.0.0.1:6789/?profile=' + profile, { headers, method: 'POST', body: JSON.stringify({ profile }), signal }) @@ -128,6 +133,50 @@ assert.deepEqual(calls.slice(1).map(([url, headers]) => { ['http://127.0.0.1:54321/v1/records/licences', 'licence-holder', 'Bearer synthetic-holder'], ['http://127.0.0.1:54321/v1/records/licences', 'licence-officer', 'Bearer synthetic-officer'], ]) + +// The same binding behind the real private function host, as a preview runs it. +const hosted = [] +let hostedAdmission +const bothHosted = new Promise(resolve => { hostedAdmission = resolve }) +const hostedHandler = defineFunction(async (request, licences) => { + const profile = new URL(request.url).searchParams.get('profile') + hosted.push([profile, request.method, request.headers.has('authorization'), request.headers.get('cookie'), + request.headers.get('proxy-authorization'), request.runtime, request.headers.get('content-type'), + request.headers.get('idempotency-key'), await request.json()]) + if (hosted.length === 2) hostedAdmission() + await bothHosted + await licences.list('licence', profile === 'licence-holder' ? options : { accessProfile: 'licence-officer' }) + return new Response(null, { status: 204 }) +})({ products: { 'licence-registry': { baseUrl: 'http://127.0.0.1:54322' } } }) +const functionKey = 'synthetic-function-key' +const server = await startFunctionHost(new Map([['renew', hostedHandler]]), { + authorize: request => request.headers.get('x-registry-preview-function') === functionKey, +}) +try { + const post = (profile, credential) => networkFetch(server.origin + '/functions/renew?profile=' + profile, { + method: 'POST', body: JSON.stringify({ profile }), + headers: { + authorization: 'Bearer ' + credential, 'x-registry-preview-function': functionKey, + 'content-type': 'application/json', 'idempotency-key': 'key-' + profile, + cookie: 'session=browser', 'proxy-authorization': 'Basic cHJveHk6cHJveHk=', + }, + }) + const statuses = await Promise.all([post('licence-holder', 'hosted-holder'), post('licence-officer', 'hosted-officer')]) + assert.deepEqual(statuses.map(response => response.status), [204, 204]) +} finally { + await server.close() +} +assert.deepEqual(hosted.sort(), [ + ['licence-holder', 'POST', false, null, null, undefined, 'application/json', 'key-licence-holder', { profile: 'licence-holder' }], + ['licence-officer', 'POST', false, null, null, undefined, 'application/json', 'key-licence-officer', { profile: 'licence-officer' }], +]) +assert.deepEqual(calls.slice(3).map(([url, headers]) => { + const target = new URL(url) + return [target.origin + target.pathname, target.searchParams.get('accessProfile'), headers.get('authorization')] +}).sort(), [ + ['http://127.0.0.1:54322/v1/records/licences', 'licence-holder', 'Bearer hosted-holder'], + ['http://127.0.0.1:54322/v1/records/licences', 'licence-officer', 'Bearer hosted-officer'], +]) ` }) assert.equal(run.status, 0, run.stderr) }) diff --git a/docs/site/src/content/docs/reference/typescript-clients.mdx b/docs/site/src/content/docs/reference/typescript-clients.mdx index c3cae52796..d60160093f 100644 --- a/docs/site/src/content/docs/reference/typescript-clients.mdx +++ b/docs/site/src/content/docs/reference/typescript-clients.mdx @@ -156,13 +156,15 @@ generates three entry points in the owned build directory. Import `createRegistr from `generated/service.ts` and `functionPaths` from `generated/routes.ts` in your page. Function paths are relative to the preview origin. A function entry imports `defineFunction` from `generated/server.ts`. Its callback receives the request and a typed -client bound to that request's caller and the private BReg address. The binding removes the -`Authorization` header before the callback sees the request, so only the typed client holds -the caller's credential. Keep the server entry in the function's import graph. +client bound to that request's caller and the private BReg address. The callback receives a +copy of the request without the `Authorization`, `Cookie` and `Proxy-Authorization` headers; +the typed client carries the caller's credential. Keep the server entry in the function's +import graph. {/* Evidence: crates/registry-rstack/src/cli.rs; clients/typescript/generate-project.ts; clients/typescript/generate-service.ts; + clients/typescript/preview/host.mjs; clients/typescript/tests/generate-preview.test.ts. */} ## Match the generator and runtime versions From e4f45a03edefda0e5fe55c1617070ba7999b7030 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 21:19:33 +0000 Subject: [PATCH 135/183] fix(coordinator): keep the function host key at the host and off every other key A Coordinator-called preview function receives a fixed placeholder bearer instead of the run host key, so the key never reaches a product, and the host key file is removed first at stop. A service function credential is also refused when it matches a review completion, event source, evaluation or deployment key, by reference and by key material, and each refusal names the member it matches as its related location. Resources compare with any trailing slash and URN prefix case normalised. Refs #2888 Signed-off-by: Jeremi Joslin --- clients/typescript/preview/host.mjs | 23 +- .../typescript/preview/tests/preview.test.mjs | 54 ++++- .../typescript/tests/generate-preview.test.ts | 35 ++- crates/registry-coordinator/src/adapters.rs | 42 ++-- .../registry-coordinator/src/external_http.rs | 6 +- crates/registry-coordinator/src/runtime.rs | 220 ++++++++++++++---- .../tests/service_function.rs | 180 ++++++++++++++ crates/registry-rstack-dev/src/lib.rs | 8 + crates/registry-rstack-dev/src/products.rs | 3 +- .../run-a-project-with-rstack-dev.mdx | 14 ++ .../reference/coordinator-configuration.mdx | 8 +- .../src/content/docs/security/coordinator.mdx | 26 ++- .../generated/runtime/runtime.schema.json | 2 +- 13 files changed, 517 insertions(+), 104 deletions(-) diff --git a/clients/typescript/preview/host.mjs b/clients/typescript/preview/host.mjs index c784bb1f6a..4238cdbc17 100644 --- a/clients/typescript/preview/host.mjs +++ b/clients/typescript/preview/host.mjs @@ -10,11 +10,15 @@ function same(value, expected) { return given.length === expected.length && timingSafeEqual(given, expected) } +// The fixed bearer a function called by Coordinator receives in place of the +// host key. It is not a secret and no product accepts it, so the key never +// leaves the host and the function holds no record authority. +export const coordinatorBearer = 'Bearer registry-preview-coordinator-call' + // The run's function host key admits two callers: the preview gateway, which // relays the page's principal and names the key in its own header, and -// Coordinator, which presents the key itself as its bearer credential. No -// product accepts the key, so a function called by Coordinator holds no -// record authority. +// Coordinator, which presents the key itself as its bearer credential. The +// check answers which caller it admitted, or false. export function functionHostAuthorizer(key) { if (typeof key !== 'string' || !hostKeyPattern.test(key)) { throw new TypeError('The function host needs a run host key.') @@ -23,9 +27,8 @@ export function functionHostAuthorizer(key) { const bearer = Buffer.from('Bearer ' + key) return request => { const header = request.headers.get('x-registry-preview-function') - return header === null - ? same(request.headers.get('authorization'), bearer) - : same(header, relayed) + if (header === null) return same(request.headers.get('authorization'), bearer) && 'coordinator' + return same(header, relayed) && 'gateway' } } @@ -47,11 +50,11 @@ export async function startFunctionHost(handlers, { authorize, port = 0 }) { const name = /^\/functions\/([a-z][a-z0-9_-]{0,63})$/u.exec(path)?.[1] const handler = handlers.get(name) if (request.method !== 'POST' || !handler) return new Response('Not Found', { status: 404 }) - if (!/^Bearer [A-Za-z0-9._-]+$/u.test(request.headers.get('authorization') ?? '') || - !authorize(request)) { - return new Response('Caller required', { status: 401 }) - } + const caller = /^Bearer [A-Za-z0-9._-]+$/u.test(request.headers.get('authorization') ?? '') && + authorize(request) + if (!caller) return new Response('Caller required', { status: 401 }) request.headers.delete('x-registry-preview-function') + if (caller === 'coordinator') request.headers.set('authorization', coordinatorBearer) return handler(request) }, }) diff --git a/clients/typescript/preview/tests/preview.test.mjs b/clients/typescript/preview/tests/preview.test.mjs index 6a302a7a63..f93c37b48c 100644 --- a/clients/typescript/preview/tests/preview.test.mjs +++ b/clients/typescript/preview/tests/preview.test.mjs @@ -1,12 +1,12 @@ import { strict as assert } from 'node:assert' -import { mkdtemp, mkdir, realpath, rm, symlink, writeFile } from 'node:fs/promises' +import { chmod, mkdir, mkdtemp, realpath, rm, symlink, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' import { createServer, request } from 'node:http' import { test } from 'node:test' -import { functionHostAuthorizer, startFunctionHost } from '../host.mjs' +import { coordinatorBearer, functionHostAuthorizer, startFunctionHost } from '../host.mjs' import { collectStaticFiles, previewPolicy, startPreviewGateway } from '../gateway.mjs' -import { prepareRuntimeConfig } from '../config.mjs' +import { configure, prepareRuntimeConfig, readHostKey } from '../config.mjs' import { buildPreview } from '../build.mjs' import { createHash } from 'node:crypto' @@ -215,9 +215,9 @@ test('the function host binds its reserved port and admits only the run host key const authorize = functionHostAuthorizer(key) const call = headers => new Request('http://127.0.0.1/functions/renew', { method: 'POST', headers }) // The gateway relays the page's principal with the host key header. - assert.equal(authorize(call({ authorization: 'Bearer page.token', 'x-registry-preview-function': key })), true) + assert.equal(authorize(call({ authorization: 'Bearer page.token', 'x-registry-preview-function': key })), 'gateway') // Coordinator presents the host key itself as its bearer credential. - assert.equal(authorize(call({ authorization: 'Bearer ' + key })), true) + assert.equal(authorize(call({ authorization: 'Bearer ' + key })), 'coordinator') for (const headers of [ { authorization: 'Bearer page.token' }, { authorization: 'Bearer ' + key + 'x' }, @@ -245,6 +245,46 @@ test('the function host binds its reserved port and admits only the run host key assert.equal((await fetch(route, { method: 'POST', headers: { authorization: 'Bearer other.token' } })).status, 401) const answer = await fetch(route, { method: 'POST', headers: { authorization: 'Bearer ' + key } }) assert.equal(await answer.text(), 'renewed') - // The function receives the host key, which no product accepts. - assert.equal(seen, 'Bearer ' + key) + // The function receives a fixed placeholder, never the host key. + assert.equal(seen, coordinatorBearer) +}) + +test('the run host key file must be owner-only, in the run directory, and well formed', async t => { + const root = await mkdtemp(join(tmpdir(), 'registry-preview-key-')) + t.after(() => rm(root, { recursive: true })) + const deployment = join(root, 'service.yaml') + await writeFile(deployment, 'service declaration') + const declarationDigest = createHash('sha256').update('service declaration').digest('hex') + const artifact = { declarationDigest, product: { id: 'licenses', member: 'licenses', audience: 'urn:preview', profile: 'holder' } } + const authorizationFile = join(root, 'authorization') + await writeFile(authorizationFile, 'Authorization: Bearer synthetic.actor.token\n', { mode: 0o600 }) + const keyFile = join(root, 'function-host-key') + const key = 'synthetic-function-host-key-0123456789abcdefghij' + const runFile = join(root, 'application-run.json') + await writeFile(runFile, JSON.stringify({ + schema: 'registry-stack.local-service-preview/v1', + runId: 'fixture-run', origin: 'http://127.0.0.1:23456', port: 23456, insecureLocal: true, + breg: { baseUrl: 'http://127.0.0.1:34567', audience: 'urn:preview' }, + preview: { + productId: 'licenses', profile: 'holder', authorizationFile, declarationDigest, + functionHost: { port: 45678, keyFile }, + }, + })) + await writeFile(keyFile, key + '\n', { mode: 0o600 }) + await configure({ artifact, deployment, runFile }) + assert.equal(await readHostKey(keyFile), key) + + await chmod(keyFile, 0o640) + await assert.rejects(configure({ artifact, deployment, runFile }), /owner-only/u) + await chmod(keyFile, 0o600) + await rm(keyFile) + await writeFile(join(root, 'elsewhere'), key, { mode: 0o600 }) + await symlink(join(root, 'elsewhere'), keyFile) + await assert.rejects(configure({ artifact, deployment, runFile }), /owner-only/u) + await rm(keyFile) + for (const malformed of ['short', key + ' extra', 'Bearer ' + key]) { + await writeFile(keyFile, malformed, { mode: 0o600 }) + await assert.rejects(readHostKey(keyFile), /host key/u) + await rm(keyFile) + } }) diff --git a/clients/typescript/tests/generate-preview.test.ts b/clients/typescript/tests/generate-preview.test.ts index a81f8163b1..dfc1e43ffc 100644 --- a/clients/typescript/tests/generate-preview.test.ts +++ b/clients/typescript/tests/generate-preview.test.ts @@ -71,7 +71,7 @@ test('preview generation splits page and function bindings and keeps request cre import assert from 'node:assert/strict' import { pathToFileURL } from 'node:url' const generated = pathToFileURL(process.argv[2] + '/') -const { startFunctionHost } = await import(pathToFileURL(process.argv[3])) +const { coordinatorBearer, functionHostAuthorizer, startFunctionHost } = await import(pathToFileURL(process.argv[3])) globalThis.location = { origin: 'http://127.0.0.1:12345' } const calls = [] const networkFetch = globalThis.fetch @@ -177,6 +177,39 @@ assert.deepEqual(calls.slice(3).map(([url, headers]) => { ['http://127.0.0.1:54322/v1/records/licences', 'licence-holder', 'Bearer hosted-holder'], ['http://127.0.0.1:54322/v1/records/licences', 'licence-officer', 'Bearer hosted-officer'], ]) + +// A Coordinator call presents the run host key as its bearer. The host admits +// it and hands the binding a fixed non-secret placeholder instead, so the key +// never leaves the host and the registry refuses the placeholder. +const hostKey = 'synthetic-run-function-host-key-0123456789' +const coordinatorHosted = [] +const coordinatorHandler = defineFunction(async (request, licences) => { + coordinatorHosted.push([request.headers.has('authorization'), request.headers.get('cookie'), + request.headers.get('proxy-authorization'), request.headers.get('idempotency-key')]) + await licences.list('licence', { accessProfile: 'licence-officer' }) + return new Response(null, { status: 204 }) +})({ products: { 'licence-registry': { baseUrl: 'http://127.0.0.1:54323' } } }) +const coordinatorHost = await startFunctionHost(new Map([['renew', coordinatorHandler]]), { + authorize: functionHostAuthorizer(hostKey), +}) +const before = calls.length +try { + const response = await networkFetch(coordinatorHost.origin + '/functions/renew', { + method: 'POST', body: '{}', + headers: { + authorization: 'Bearer ' + hostKey, 'content-type': 'application/json', 'idempotency-key': 'frozen-key', + cookie: 'session=browser', 'proxy-authorization': 'Basic cHJveHk6cHJveHk=', + }, + }) + assert.equal(response.status, 204) +} finally { + await coordinatorHost.close() +} +assert.deepEqual(coordinatorHosted, [[false, null, null, 'frozen-key']]) +const upstream = calls.slice(before) +assert.equal(upstream.length, 1) +assert.equal(upstream[0][1].get('authorization'), coordinatorBearer) +assert.ok(!JSON.stringify(upstream.map(([url, headers]) => [url, [...headers]])).includes(hostKey)) ` }) assert.equal(run.status, 0, run.stderr) }) diff --git a/crates/registry-coordinator/src/adapters.rs b/crates/registry-coordinator/src/adapters.rs index dbe62d644d..c480822a6f 100644 --- a/crates/registry-coordinator/src/adapters.rs +++ b/crates/registry-coordinator/src/adapters.rs @@ -465,10 +465,10 @@ impl HttpAdapters { } } -/// A service function host never holds the key of another connection, even -/// under another secret reference: a JWK is compared by its RFC 7638 -/// thumbprint, any other key by a digest of its bytes. The refusal names the -/// two connections and no key value. +/// A service function host never holds a key this runtime file gives +/// something else, even under another secret reference: a JWK is compared by +/// its RFC 7638 thumbprint, any other key by a digest of its bytes. The +/// refusal names the two locations and no key value. fn distinct_function_keys( config: &RuntimeConfig, secrets: ®istry_platform_config::SecretResolver, @@ -489,7 +489,6 @@ fn distinct_function_keys( }) }; let mut functions = Vec::new(); - let mut others = Vec::new(); for (name, configured) in &config.connections { if let Some(function) = configured.service_function() { for reference in function @@ -501,38 +500,23 @@ fn distinct_function_keys( { functions.push((name, identity(reference)?)); } - continue; - } - let mut references = Vec::new(); - if let Some(product) = configured.product_binding() { - references.push(&product.authorization.signing_key_ref); - references.extend( - product - .observation_authorization - .map(|auth| &auth.signing_key_ref), - ); - } else if let Some(external) = configured.external_http() { - references.extend( - external - .authorization - .as_ref() - .map(|auth| &auth.signing_key_ref), - ); - } else if let Some(reference) = configured.decision().and_then(|d| d.token_ref()) { - references.push(reference); - } - for reference in references { - others.push((name, identity(reference)?)); } } + if functions.is_empty() { + return Ok(()); + } + let mut others = Vec::new(); + for (location, reference) in config.other_key_references() { + others.push((location, identity(reference)?)); + } for (function, key) in &functions { if let Some((other, _)) = others.iter().find(|(_, value)| value == key) { return Err(CoordinatorError::new( "coordinator.runtime-config.refused", - format!("connections {function} and {other} resolve to the same key; a service function host must hold a key no other connection uses"), + format!("connections {function} and {other} resolve to the same key; a service function host must hold a key nothing else in this runtime uses"), ) .at("runtime.yaml", format!("/connections/{function}")) - .suggest(format!("Give connections.{function} its own key, distinct from connections.{other}."))); + .suggest(format!("Give connections.{function} its own key, distinct from {other}."))); } } Ok(()) diff --git a/crates/registry-coordinator/src/external_http.rs b/crates/registry-coordinator/src/external_http.rs index 204024fb2e..b4dc1d4339 100644 --- a/crates/registry-coordinator/src/external_http.rs +++ b/crates/registry-coordinator/src/external_http.rs @@ -71,9 +71,9 @@ pub struct ServiceFunctionConfig { /// The one function this connection binds. pub function: LocalId, /// An OAuth client credential for the function host. Its client, key and - /// resource are the function host's own and are never a product - /// connection's, so the token carries no product authority. Exactly one of - /// `authorization` and `hostKeyRef` is required. + /// resource must differ from every product, external and evaluation + /// credential this runtime file declares. Exactly one of `authorization` + /// and `hostKeyRef` is required. #[serde(default, skip_serializing_if = "Option::is_none")] #[cfg_attr(feature = "schema", schemars(extend("not" = serde_json::json!({"required":["taskAuthority"]}))))] pub authorization: Option, diff --git a/crates/registry-coordinator/src/runtime.rs b/crates/registry-coordinator/src/runtime.rs index a321ad85da..13f6c8c10d 100644 --- a/crates/registry-coordinator/src/runtime.rs +++ b/crates/registry-coordinator/src/runtime.rs @@ -730,6 +730,29 @@ impl RuntimeConfig { ); } } + // A credential collision also points at the member it matches. + for (name, binding) in &loaded.config.connections { + let Some(function) = binding.service_function() else { + continue; + }; + let field = format!("connections.{name}"); + for (member, other, _) in loaded + .config + .function_credential_collisions(&field, function) + { + let member = pointer(&member); + if let Some(diagnostic) = diagnostics + .iter_mut() + .find(|diagnostic| diagnostic.path == member) + { + checked.add_related_key( + diagnostic, + &other, + "the member this credential matches", + ); + } + } + } if let Some(deployment) = &loaded.config.deployment { diagnostics.extend( deployment @@ -874,7 +897,11 @@ impl RuntimeConfig { "give the service function connection exactly one credential: authorization for an OAuth client, or hostKeyRef for a key only the function host accepts", )), } - errors.extend(self.function_credential_findings(&field, function)); + errors.extend( + self.function_credential_collisions(&field, function) + .into_iter() + .map(|(_, _, error)| error), + ); } else if let Some(binding) = binding.decision() { errors.extend(binding.findings(&field)); if let Some(reference) = binding.token_ref() { @@ -1072,76 +1099,174 @@ impl RuntimeConfig { self.validate_workflow_effect_bindings(workflow) } - /// A service function credential is distinct from every credential and - /// product audience this runtime file declares: no resource equal, after - /// normalisation, to a product, external or task authority resource or to - /// the Coordinator's own audience, no shared client, and no shared key - /// reference. Startup also compares the resolved key material. Each - /// refusal names the colliding connection, never a value. - fn function_credential_findings( + /// Every key reference this runtime file gives something other than a + /// service function host, with the JSON pointer of the member that holds + /// it: product, external and evaluation credentials, review completion + /// keys, event source keys, and the deployment's own keys. + pub(crate) fn other_key_references(&self) -> Vec<(String, &SecretReference)> { + let mut keys = Vec::new(); + for (name, binding) in &self.connections { + let at = |member: &str| pointer(&format!("connections.{name}.{member}")); + if let Some(product) = binding.product_binding() { + keys.push(( + at("authorization.signingKeyRef"), + &product.authorization.signing_key_ref, + )); + if let Some(observation) = product.observation_authorization { + keys.push(( + at("observationAuthorization.signingKeyRef"), + &observation.signing_key_ref, + )); + } + if let Some(completion) = product.completion { + keys.push(( + at("completion.hmacSha256KeyRef"), + &completion.hmac_sha256_key_ref, + )); + if let Some(previous) = &completion.previous_hmac_sha256_key_ref { + keys.push((at("completion.previousHmacSha256KeyRef"), previous)); + } + } + } else if let Some(external) = binding.external_http() { + if let Some(authorization) = &external.authorization { + keys.push(( + at("authorization.signingKeyRef"), + &authorization.signing_key_ref, + )); + } + } else if let Some(reference) = binding.decision().and_then(|d| d.token_ref()) { + keys.push((at("authorization.bearer.tokenRef"), reference)); + } + } + for (source, config) in &self.event_sources { + for (workflow, triggers) in &config.triggers { + for (trigger, key) in &triggers.0 { + let at = |member: &str| { + format!( + "/eventSources/{}/triggers/{}/{}/{member}", + registry_platform_yaml::escape_pointer_segment(source), + registry_platform_yaml::escape_pointer_segment(workflow.as_str()), + registry_platform_yaml::escape_pointer_segment(trigger.as_str()), + ) + }; + keys.push((at("hmacSha256KeyRef"), &key.hmac_sha256_key_ref)); + if let Some(previous) = &key.previous_hmac_sha256_key_ref { + keys.push((at("previousHmacSha256KeyRef"), previous)); + } + } + } + } + if let Some(deployment) = &self.deployment { + keys.push(( + "/deployment/auditKeyRef".to_owned(), + &deployment.audit_key_ref, + )); + for (version, reference) in &deployment.state_keys { + keys.push(( + format!( + "/deployment/stateKeys/{}/keyRef", + registry_platform_yaml::escape_pointer_segment(version) + ), + reference, + )); + } + keys.push(( + "/deployment/admissionKeyRef".to_owned(), + &deployment.admission_key_ref, + )); + } + keys + } + + /// Each member of a service function credential that collides with a + /// credential, product audience or key this runtime file gives something + /// else, as the dotted field of the colliding member, the JSON pointer of + /// the member it matches, and the refusal. A resource is compared after + /// normalisation against product, external and task authority resources + /// and the Coordinator's own audience. Startup also compares the resolved + /// key material. Other service function connections are not compared. + fn function_credential_collisions( &self, field: &str, function: &crate::external_http::ServiceFunctionConfig, - ) -> Vec { - let mut resources: Vec<(String, &str)> = Vec::new(); - let mut clients: Vec<(&str, &str)> = Vec::new(); - let mut keys: Vec<(&str, &SecretReference)> = Vec::new(); + ) -> Vec<(String, String, CoordinatorError)> { + let mut resources: Vec<(String, String)> = Vec::new(); + let mut clients: Vec<(&str, String)> = Vec::new(); for (name, binding) in &self.connections { - let mut credentials: Vec<&AuthorizationConfig> = Vec::new(); + let mut credentials: Vec<(&str, &AuthorizationConfig)> = Vec::new(); if let Some(product) = binding.product_binding() { - credentials.push(product.authorization); - credentials.extend(product.observation_authorization); + credentials.push(("authorization", product.authorization)); + credentials.extend( + product + .observation_authorization + .map(|auth| ("observationAuthorization", auth)), + ); } else if let Some(external) = binding.external_http() { - credentials.extend(external.authorization.as_ref()); - } else if let Some(reference) = binding.decision().and_then(|d| d.token_ref()) { - keys.push((name, reference)); + credentials.extend( + external + .authorization + .as_ref() + .map(|auth| ("authorization", auth)), + ); } - for credential in credentials { - resources.push((normalised_resource(&credential.resource), name)); + for (member, credential) in credentials { + let at = |rest: &str| pointer(&format!("connections.{name}.{member}.{rest}")); + resources.push((normalised_resource(&credential.resource), at("resource"))); if let Some(task) = &credential.task_authority { - resources.push((normalised_resource(&task.bootstrap_resource), name)); - resources.push((normalised_resource(&task.exchange_audience), name)); + resources.push(( + normalised_resource(&task.bootstrap_resource), + at("taskAuthority.bootstrapResource"), + )); + resources.push(( + normalised_resource(&task.exchange_audience), + at("taskAuthority.exchangeAudience"), + )); } - clients.push((&credential.client_id, name)); - keys.push((name, &credential.signing_key_ref)); + clients.push((&credential.client_id, at("clientId"))); } } if let Some(deployment) = &self.deployment { - for (_, issuer) in deployment.authentication.issuers.iter() { + for (id, issuer) in deployment.authentication.issuers.iter() { resources.push(( normalised_resource(&issuer.core.provider.audience), - "deployment.authentication", + format!( + "/deployment/authentication/issuers/{}/audience", + registry_platform_yaml::escape_pointer_segment(id.as_str()) + ), )); } } - let refusal = |member: String, other: &str| { - config_error( - &format!("{field}.{member}"), - &format!("give the service function host its own resource, client and key; the value matches the credential of {other}, which would let the function act with that authority"), - ) + let keys = self.other_key_references(); + let refusal = |member: &str, other: &str| { + let member = format!("{field}.{member}"); + let error = config_error( + &member, + &format!("give the service function host its own resource, client and key; the value matches {other}, which would let the function act with that authority"), + ); + (member, other.to_owned(), error) }; - let mut errors = Vec::new(); + let mut collisions = Vec::new(); if let Some(own) = &function.authorization { let resource = normalised_resource(&own.resource); if let Some((_, other)) = resources.iter().find(|(value, _)| *value == resource) { - errors.push(refusal("authorization.resource".into(), other)); + collisions.push(refusal("authorization.resource", other)); } if let Some((_, other)) = clients.iter().find(|(value, _)| *value == own.client_id) { - errors.push(refusal("authorization.clientId".into(), other)); + collisions.push(refusal("authorization.clientId", other)); } if let Some((other, _)) = keys .iter() .find(|(_, reference)| **reference == own.signing_key_ref) { - errors.push(refusal("authorization.signingKeyRef".into(), other)); + collisions.push(refusal("authorization.signingKeyRef", other)); } } if let Some(reference) = &function.host_key_ref { if let Some((other, _)) = keys.iter().find(|(_, value)| *value == reference) { - errors.push(refusal("hostKeyRef".into(), other)); + collisions.push(refusal("hostKeyRef", other)); } } - errors + collisions } /// Retained Runs require their effect bindings, independently of whether @@ -1458,18 +1583,31 @@ fn runtime_id_collision_diagnostics( } /// The form a resource indicator is compared in: a URL with its scheme and -/// host in lower case, its default port dropped and a lone `/` path removed. -/// Any other identifier is compared exactly. +/// host in lower case, its default port dropped and one trailing `/` removed +/// from its path, or a URN with its `urn:` scheme and namespace identifier in +/// lower case. Any other identifier is compared exactly. fn normalised_resource(resource: &str) -> String { match Url::parse(resource) { Ok(url) if url.has_host() => { let text = url.to_string(); match text.strip_suffix('/') { - Some(origin) if url.path() == "/" && url.query().is_none() => origin.to_owned(), + Some(trimmed) if url.query().is_none() && url.fragment().is_none() => { + trimmed.to_owned() + } _ => text, } } - _ => resource.to_owned(), + _ => { + let mut parts = resource.splitn(3, ':'); + match (parts.next(), parts.next(), parts.next()) { + (Some(scheme), Some(namespace), Some(rest)) + if scheme.eq_ignore_ascii_case("urn") => + { + format!("urn:{}:{rest}", namespace.to_ascii_lowercase()) + } + _ => resource.to_owned(), + } + } } } diff --git a/crates/registry-coordinator/tests/service_function.rs b/crates/registry-coordinator/tests/service_function.rs index c4f9f34212..d512776a92 100644 --- a/crates/registry-coordinator/tests/service_function.rs +++ b/crates/registry-coordinator/tests/service_function.rs @@ -761,3 +761,183 @@ async fn a_busy_answer_on_the_final_attempt_holds_instead_of_retrying() { ); host.verify().await; } + +/// The diagnostics `check` reports for a runtime document, with their +/// related locations. +fn checked(document: &Value) -> Vec { + let root = tempfile::tempdir().unwrap(); + let directory = root.path().canonicalize().unwrap(); + let mut document = document.clone(); + document["secretProviders"]["file"] = json!({"root":directory}); + let path = directory.join("runtime.yaml"); + std::fs::write(&path, serde_json::to_vec(&document).unwrap()).unwrap(); + RuntimeConfig::check_file(&path, true).diagnostics +} + +/// The one diagnostic at `path`, which must name `related` as the colliding +/// location. +fn collision(document: &Value, path: &str, related: &str) { + let diagnostics = checked(document); + let found = diagnostics + .iter() + .find(|diagnostic| diagnostic.path == path) + .unwrap_or_else(|| panic!("no diagnostic at {path}: {diagnostics:#?}")); + assert!( + found.related.iter().any(|other| other.path == related), + "{path} names {related}: {found:#?}" + ); +} + +#[test] +fn a_credential_collision_names_the_colliding_member_as_related() { + let mut document = runtime_document(); + document["connections"]["notices"]["authorization"]["resource"] = json!("urn:example:registry"); + collision( + &document, + "/connections/notices/authorization/resource", + "/connections/registry/authorization/resource", + ); +} + +#[test] +fn a_function_resource_is_compared_with_any_trailing_slash_and_urn_case() { + let mut document = runtime_document(); + document["connections"]["registry"]["authorization"]["resource"] = + json!("https://breg.example.org/v1"); + resource_refusal(document.clone(), "https://breg.example.org/v1/"); + document["connections"]["registry"]["authorization"]["resource"] = + json!("urn:example:registry"); + resource_refusal(document.clone(), "URN:Example:registry"); + // The namespace-specific part of a URN keeps its case. + document["connections"]["notices"]["authorization"]["resource"] = json!("urn:example:REGISTRY"); + load(&document).unwrap(); +} + +fn evaluation_connection(token: &str) -> Value { + json!({ + "type":"evaluation", "protocol":"system-one", "baseUrl":"http://127.0.0.1:9024/", + "model":"synthetic-model", + "authorization":{"bearer":{"tokenRef":token, "principal":"coordinator"}} + }) +} + +#[test] +fn a_host_key_is_never_an_evaluation_completion_or_event_key() { + let mut document = host_key_document("http://127.0.0.1:9020/"); + document["connections"]["decide"] = evaluation_connection("secret:file/function-host-key"); + collision( + &document, + "/connections/notices/hostKeyRef", + "/connections/decide/authorization/bearer/tokenRef", + ); + + let mut document = host_key_document("http://127.0.0.1:9020/"); + document["connections"]["review"] = json!({ + "type":"casework-review-producer", "baseUrl":"http://127.0.0.1:9025", + "profile":"producer", "producer":"coordinator", + "authorization":{ + "tokenEndpoint":"http://127.0.0.1:9999/token", + "clientAssertionAudience":"http://127.0.0.1:9999", + "clientId":"coordinator-review", "signingKeyRef":"secret:file/review-client-key", + "resource":"urn:example:casework", "scopes":["casework:review"] + }, + "completion":{"recipientBinding":"coordinator-v1", "hmacSha256KeyRef":"secret:file/function-host-key"} + }); + collision( + &document, + "/connections/notices/hostKeyRef", + "/connections/review/completion/hmacSha256KeyRef", + ); + + let mut document = host_key_document("http://127.0.0.1:9020/"); + document["eventSources"] = json!({"registry-events": { + "source":"https://events.example.org", + "triggers":{"notice-draft":{"on-change":{"hmacSha256KeyRef":"secret:file/function-host-key"}}} + }}); + collision( + &document, + "/connections/notices/hostKeyRef", + "/eventSources/registry-events/triggers/notice-draft/on-change/hmacSha256KeyRef", + ); +} + +#[test] +fn a_host_key_is_never_a_deployment_key() { + let example = + include_str!("../../../products/coordinator/examples/delayed-follow-up/runtime.yaml"); + let function = " drafts:\n type: service-function\n baseUrl: http://127.0.0.1:9020/\n function: draft-notice\n hostKeyRef: KEY\n responseSchema: {type: object}\n"; + for (key, related) in [ + ("secret:file/audit-key", "/deployment/auditKeyRef"), + ("secret:file/state-key-1", "/deployment/stateKeys/1/keyRef"), + ("secret:file/admission-key", "/deployment/admissionKeyRef"), + ] { + let root = tempfile::tempdir().unwrap(); + let path = root.path().canonicalize().unwrap().join("runtime.yaml"); + std::fs::write( + &path, + example.replacen( + "connections:\n", + &format!("connections:\n{}", function.replace("KEY", key)), + 1, + ), + ) + .unwrap(); + let diagnostics = RuntimeConfig::check_file(&path, true).diagnostics; + let found = diagnostics + .iter() + .find(|diagnostic| diagnostic.path == "/connections/drafts/hostKeyRef") + .unwrap_or_else(|| panic!("{key}: {diagnostics:#?}")); + assert!( + found.related.iter().any(|other| other.path == related), + "{key}: {found:#?}" + ); + } +} + +#[test] +fn rotating_the_host_key_keeps_the_binding_and_changing_the_credential_kind_does_not() { + let document = host_key_document("http://127.0.0.1:9020/"); + let digest = load(&document).unwrap().binding_digest().unwrap(); + let mut rotated = document.clone(); + rotated["connections"]["notices"]["hostKeyRef"] = json!("secret:file/function-host-key-2"); + assert_eq!(load(&rotated).unwrap().binding_digest().unwrap(), digest); + assert_ne!( + load(&runtime_document()).unwrap().binding_digest().unwrap(), + digest + ); +} + +#[test] +fn the_same_host_key_or_jwk_under_another_form_is_refused_at_startup() { + const HOST_KEY: &str = "synthetic-function-host-key-canary"; + let mut document = host_key_document("http://127.0.0.1:9020/"); + document["connections"]["decide"] = evaluation_connection("secret:file/decision-token"); + let (_root, config) = with_secrets( + &document, + &[ + ("function-host-key", HOST_KEY), + ("decision-token", HOST_KEY), + ("registry-client-key", KEY), + ], + ); + let error = registry_coordinator::adapters::HttpAdapters::new(&config) + .err() + .expect("one host key behind two references is refused"); + assert!(error.message.contains("decide"), "{error:?}"); + + // The same JWK written again with its members in another order and + // spacing is the same key. + let parsed: serde_json::Map = serde_json::from_str(KEY).unwrap(); + let reordered = + serde_json::to_string_pretty(&parsed.into_iter().rev().collect::>()) + .unwrap(); + assert_ne!(reordered, KEY); + let (_root, config) = with_secrets( + &runtime_document(), + &[ + ("function-client-key", &reordered), + ("registry-client-key", KEY), + ], + ); + assert!(registry_coordinator::adapters::HttpAdapters::new(&config).is_err()); +} diff --git a/crates/registry-rstack-dev/src/lib.rs b/crates/registry-rstack-dev/src/lib.rs index f8299600cd..71167ad06b 100644 --- a/crates/registry-rstack-dev/src/lib.rs +++ b/crates/registry-rstack-dev/src/lib.rs @@ -2780,6 +2780,12 @@ fn remove_run_dir(root: &Path) -> Result<()> { } _ => {} } + match fs::remove_file(root.join(products::FUNCTION_HOST_KEY)) { + Err(error) if error.kind() != std::io::ErrorKind::NotFound => { + return Err(error).context("cannot remove the run's preview function host key"); + } + _ => {} + } fs::rename(root, &doomed).context("cannot remove run scratch files")?; fs::remove_dir_all(&doomed) .with_context(|| format!("cannot remove run scratch files at {}", doomed.display())) @@ -3925,6 +3931,7 @@ mod tests { let root = base.join(RUN_ID); private_directory(&root).unwrap(); fs::write(root.join(products::FIELD_KEY), "key").unwrap(); + fs::write(root.join(products::FUNCTION_HOST_KEY), "host-key").unwrap(); fs::write(root.join(REPORT), "{}").unwrap(); // A non-empty directory at the removal name makes the rename fail, as // an interrupted deletion would leave the run behind. @@ -3934,6 +3941,7 @@ mod tests { assert!(remove_run_dir(&root).is_err()); assert!(!root.join(products::FIELD_KEY).exists()); + assert!(!root.join(products::FUNCTION_HOST_KEY).exists()); assert!(root.join(REPORT).exists()); } diff --git a/crates/registry-rstack-dev/src/products.rs b/crates/registry-rstack-dev/src/products.rs index 9b239fad63..a91be141f5 100644 --- a/crates/registry-rstack-dev/src/products.rs +++ b/crates/registry-rstack-dev/src/products.rs @@ -2205,7 +2205,8 @@ fn coordinator_issuer_listener(state: Option<&Path>) -> Result { ) } -const FUNCTION_HOST_KEY: &str = "preview-function-host-key"; +/// The run file holding the preview function host key. +pub(super) const FUNCTION_HOST_KEY: &str = "preview-function-host-key"; /// A loopback listener whose port is kept in the project state, so a resumed /// run binds the same address its live workflows name. diff --git a/docs/site/src/content/docs/configure/run-a-project-with-rstack-dev.mdx b/docs/site/src/content/docs/configure/run-a-project-with-rstack-dev.mdx index d49d180b5e..e76a60dfd2 100644 --- a/docs/site/src/content/docs/configure/run-a-project-with-rstack-dev.mdx +++ b/docs/site/src/content/docs/configure/run-a-project-with-rstack-dev.mdx @@ -68,12 +68,26 @@ origin policy and provide no authentication of local processes. The separate function listener requires a private handoff from the gateway and returns 401 to an anonymous function request. +A Coordinator `service-function` connection calls a preview function directly. The run +reserves the function listener's loopback port before products start and writes one +owner-only host key for the run, which the Coordinator presents as its bearer. The function +listener then hands the function a fixed placeholder bearer instead of the key, so the key +never leaves the listener and no product accepts what the function receives. +The same function stays callable from the page through the gateway, with the page actor's +authority, so write a Coordinator-bound function for both callers. +One run key admits the gateway and the Coordinator to every preview function, not only the +one a connection binds. The reserved port is released a moment before the function listener +binds it, as the other reserved ports are, so another local process could take it in that +window and receive the key. + {/* Evidence: crates/registry-rstack/src/cli.rs; crates/registry-rstack-dev/src/preview.rs; crates/registry-platform-config/src/service_roles.rs, roles_from_document(); crates/registry-rstack-dev/src/products.rs; clients/typescript/preview/build.mjs; clients/typescript/preview/gateway.mjs; + clients/typescript/preview/host.mjs, functionHostAuthorizer, coordinatorBearer; + clients/typescript/tests/generate-preview.test.ts; products/platform/examples/service-previews/README.md; products/platform/scripts/test-service-previews.mjs. */} diff --git a/docs/site/src/content/docs/reference/coordinator-configuration.mdx b/docs/site/src/content/docs/reference/coordinator-configuration.mdx index a7b9da3613..88d54acdd5 100644 --- a/docs/site/src/content/docs/reference/coordinator-configuration.mdx +++ b/docs/site/src/content/docs/reference/coordinator-configuration.mdx @@ -217,8 +217,10 @@ HTTP requires numeric loopback. Add one connection for each function a workflow calls. The credential is for the function host alone. -The runtime refuses a `resource` equal to a product or external connection's resource, a task authority `bootstrapResource` or `exchangeAudience`, or the Coordinator's own issuer audience, comparing URLs with the scheme and host in lower case, no default port and no lone trailing `/`. -It also refuses a `clientId`, `signingKeyRef` or `hostKeyRef` another connection uses, and at startup a key whose material another connection holds under another reference. +The runtime refuses a `resource` equal to a product or external connection's resource, a task authority `bootstrapResource` or `exchangeAudience`, or the Coordinator's own issuer audience, comparing URLs with the scheme and host in lower case, no default port and no trailing `/`, and URNs with the `urn:` scheme and namespace identifier in lower case. +It also refuses a `clientId` or key reference that a product, external or evaluation connection, a review completion, an event source or the deployment's own keys use. +At startup it refuses a key whose material one of those holds under another reference. +Other `service-function` connections are not compared, so two function connections may share a function host credential. Each refusal names the colliding connection. Bind every function host as `service-function`: an `external-http` connection gets none of these checks. A record change stays a separate BReg step in the workflow. @@ -250,7 +252,7 @@ connections: The function host must pass the `Idempotency-Key` it receives to any effect the function makes, as an external provider must deduplicate on it. {/* Evidence: crates/registry-coordinator/src/external_http.rs ServiceFunctionConfig; - crates/registry-coordinator/src/runtime.rs function_credential_findings; + crates/registry-coordinator/src/runtime.rs function_credential_collisions, other_key_references; crates/registry-coordinator/tests/service_function.rs. */} ### Payment connections diff --git a/docs/site/src/content/docs/security/coordinator.mdx b/docs/site/src/content/docs/security/coordinator.mdx index 0237761f2e..ce2eef1109 100644 --- a/docs/site/src/content/docs/security/coordinator.mdx +++ b/docs/site/src/content/docs/security/coordinator.mdx @@ -890,17 +890,21 @@ Enforcement: live Run cannot be moved to another function. - The connection holds exactly one credential: an OAuth `authorization` without `taskAuthority`, or a `hostKeyRef` key only the function host accepts. - `rstack dev` generates a per-run host key for the preview function host. + `rstack dev` generates a per-run host key for the preview function host, and that host hands + a Coordinator-called function a fixed placeholder bearer, never the key. - The credential is distinct from every credential and product audience the runtime file declares. The runtime refuses a function `resource` equal to a product or external connection's `resource`, a task authority `bootstrapResource` or `exchangeAudience`, or the Coordinator's own `deployment.authentication.issuers.*.audience`. URL resources are compared with the scheme and host in lower case, the default port dropped and a - lone `/` path removed. - It refuses a `clientId`, `signingKeyRef` or `hostKeyRef` such a connection uses. - Each refusal names the colliding connection and no value. + trailing `/` removed, and URNs with the scheme and namespace identifier in lower case. + It refuses a `clientId` such a connection uses, and a `signingKeyRef` or `hostKeyRef` equal to + any product, external or evaluation credential, review completion key, event source key, or the + deployment's audit, state or admission key. + Each refusal names the colliding member as its related location, and no value. At startup the resolved keys are compared too, a JWK by its RFC 7638 thumbprint and any other key by its bytes, so the same key under another reference is refused. + Other `service-function` connections are not compared. - The call is an external command in every other respect (COORDINATOR-INV-03). The request id is frozen before the first send and sent as `Idempotency-Key`, redirects are never followed, bodies and responses are bounded, an ambiguous exchange holds the run, and only the @@ -916,7 +920,7 @@ Also refused: a function the connection does not bind, a function connection wit two, a function credential matching a product, external or task authority credential or the Coordinator's audience, and task authority on a function connection. -{/* Evidence: crates/registry-coordinator/src/runtime.rs function_credential_findings, +{/* Evidence: crates/registry-coordinator/src/runtime.rs function_credential_collisions, other_key_references, normalised_resource, validate_workflow_effect_bindings; crates/registry-coordinator/src/adapters.rs distinct_function_keys; crates/registry-coordinator/src/external_http.rs ServiceFunctionConfig; @@ -937,7 +941,13 @@ Coordinator's audience, and task authority on a function connection. a_taskauthority_refusal_names_the_service_function_remedy, the_same_signing_key_under_another_reference_is_refused_at_startup, the_runtime_routes_a_function_call_with_its_oauth_token_and_frozen_request_id, - a_lost_acknowledgement_is_uncertain_and_the_same_request_id_is_sent_again. + a_lost_acknowledgement_is_uncertain_and_the_same_request_id_is_sent_again, + a_credential_collision_names_the_colliding_member_as_related, + a_function_resource_is_compared_with_any_trailing_slash_and_urn_case, + a_host_key_is_never_an_evaluation_completion_or_event_key, + a_host_key_is_never_a_deployment_key, + rotating_the_host_key_keeps_the_binding_and_changing_the_credential_kind_does_not, + the_same_host_key_or_jwk_under_another_form_is_refused_at_startup. crates/registry-coordinator/tests/service_function_project.rs a_missing_function_name_is_refused_at_the_operation, only_the_service_function_operation_names_a_function, @@ -1326,7 +1336,7 @@ Each residual names the condition under which it applies, its consequence, and t Register the function host resource only for the function host, and never list it as a product audience. -{/* Evidence: crates/registry-coordinator/src/runtime.rs function_credential_findings; +{/* Evidence: crates/registry-coordinator/src/runtime.rs function_credential_collisions, other_key_references; crates/registry-coordinator/tests/service_function.rs a_service_function_credential_is_never_a_product_credential. */} @@ -1341,7 +1351,7 @@ Each residual names the condition under which it applies, its consequence, and t Bind function hosts as `service-function`. A later release is planned to refuse product credentials on `external-http` connections too. -{/* Evidence: crates/registry-coordinator/src/runtime.rs function_credential_findings. */} +{/* Evidence: crates/registry-coordinator/src/runtime.rs function_credential_collisions, other_key_references. */} ## Report a vulnerability diff --git a/products/coordinator/generated/runtime/runtime.schema.json b/products/coordinator/generated/runtime/runtime.schema.json index e03f1fcfd2..3b96285a14 100644 --- a/products/coordinator/generated/runtime/runtime.schema.json +++ b/products/coordinator/generated/runtime/runtime.schema.json @@ -484,7 +484,7 @@ }, "authorization": { "$ref": "#/$defs/AuthorizationConfig", - "description": "An OAuth client credential for the function host. Its client, key and\nresource are the function host's own and are never a product\nconnection's, so the token carries no product authority. Exactly one of\n`authorization` and `hostKeyRef` is required.", + "description": "An OAuth client credential for the function host. Its client, key and\nresource must differ from every product, external and evaluation\ncredential this runtime file declares. Exactly one of `authorization`\nand `hostKeyRef` is required.", "not": { "required": [ "taskAuthority" From 2c3d476f660a9255b4854e374096d158676c5937 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 21:36:52 +0000 Subject: [PATCH 136/183] feat(dev): bind the Coordinator as one Casework review producer A development plan may bind one Coordinator casework-review-producer connection to one existing Casework trusted producer. rstack dev checks the connection, producer, profile, completion destination and recipient against the Coordinator runtime and casework.yaml, rebinds only that producer to the run issuer under exact guards, gives the Coordinator a machine client on the run token endpoint, and binds Casework's completion hook to the Coordinator with one per-run key. A Coordinator review producer connection without the binding is refused. The workflow-binding refusal now names the runtime function as related. Refs #2888 Signed-off-by: Jeremi Joslin --- crates/registry-coordinator/src/adapters.rs | 2 +- crates/registry-coordinator/src/error.rs | 17 + .../registry-coordinator/src/project_check.rs | 10 + crates/registry-coordinator/src/runtime.rs | 7 +- .../tests/service_function_project.rs | 6 + crates/registry-rstack-dev/src/bindings.rs | 397 +++++++++++++- crates/registry-rstack-dev/src/plan.rs | 7 +- crates/registry-rstack-dev/src/products.rs | 512 +++++++++++++++--- .../run-a-project-with-rstack-dev.mdx | 50 ++ products/platform/config-formats.yaml | 6 + .../generated/dev/dev.v1alpha1.schema.json | 40 +- 11 files changed, 972 insertions(+), 82 deletions(-) diff --git a/crates/registry-coordinator/src/adapters.rs b/crates/registry-coordinator/src/adapters.rs index c480822a6f..8f214e6e8b 100644 --- a/crates/registry-coordinator/src/adapters.rs +++ b/crates/registry-coordinator/src/adapters.rs @@ -513,7 +513,7 @@ fn distinct_function_keys( if let Some((other, _)) = others.iter().find(|(_, value)| value == key) { return Err(CoordinatorError::new( "coordinator.runtime-config.refused", - format!("connections {function} and {other} resolve to the same key; a service function host must hold a key nothing else in this runtime uses"), + format!("connection {function} and {other} resolve to the same key; a service function host must hold a key nothing else in this runtime uses"), ) .at("runtime.yaml", format!("/connections/{function}")) .suggest(format!("Give connections.{function} its own key, distinct from {other}."))); diff --git a/crates/registry-coordinator/src/error.rs b/crates/registry-coordinator/src/error.rs index a7fcd29a1a..dca0711c92 100644 --- a/crates/registry-coordinator/src/error.rs +++ b/crates/registry-coordinator/src/error.rs @@ -175,6 +175,23 @@ impl CoordinatorError { self.suggested_action = Some(action.into().into_boxed_str()); self } + /// Name a second location that takes part in this refusal. The refusal + /// is then reported as one diagnostic that lists it as related. + #[must_use] + pub(crate) fn related(mut self, file: &str, pointer: &str, message: impl Into) -> Self { + let mut diagnostics = self.report().diagnostics().to_vec(); + if let Some(diagnostic) = diagnostics.first_mut() { + diagnostic.related.push(registry_platform_yaml::Related { + file: file.to_owned(), + line: None, + column: None, + path: pointer.to_owned(), + message: message.into(), + }); + } + self.diagnostics = diagnostics.into(); + self + } fn render(&self) -> String { if !self.diagnostics.is_empty() { return Report::new(self.diagnostics.to_vec()).render_human(); diff --git a/crates/registry-coordinator/src/project_check.rs b/crates/registry-coordinator/src/project_check.rs index 3d525d6182..f6ac57909a 100644 --- a/crates/registry-coordinator/src/project_check.rs +++ b/crates/registry-coordinator/src/project_check.rs @@ -126,6 +126,13 @@ fn workflow_binding_diagnostics( format!("/{}", field.replace('.', "/")) } }); + // A related runtime location the refusal names keeps its position here. + let related: Vec<(String, String)> = error + .diagnostics + .iter() + .flat_map(|diagnostic| diagnostic.related.iter()) + .map(|related| (related.path.clone(), related.message.clone())) + .collect(); let mut diagnostic = checked.error_at( runtime::KIND, "coordinator.runtime.workflow-binding", @@ -135,6 +142,9 @@ fn workflow_binding_diagnostics( "Use the same logical connection name in the project and runtime.".into() }), ); + for (path, message) in related { + checked.add_related_key(&mut diagnostic, &path, message); + } // A missing member has no span. Anchor it to its nearest existing runtime // container while retaining the missing path. if diagnostic diff --git a/crates/registry-coordinator/src/runtime.rs b/crates/registry-coordinator/src/runtime.rs index 13f6c8c10d..b0dff6dff4 100644 --- a/crates/registry-coordinator/src/runtime.rs +++ b/crates/registry-coordinator/src/runtime.rs @@ -1351,7 +1351,12 @@ impl RuntimeConfig { .suggest(format!( "Name the function bound as connections.{}.function in runtime.yaml, or add one service-function connection for this function.", call.connection - ))); + )) + .related( + "runtime.yaml", + &pointer(&format!("connections.{}.function", call.connection)), + "the function the connection binds", + )); } } if call.operation == crate::protocol::Operation::ExternalCommand diff --git a/crates/registry-coordinator/tests/service_function_project.rs b/crates/registry-coordinator/tests/service_function_project.rs index 909eac0195..f6d76b4f9e 100644 --- a/crates/registry-coordinator/tests/service_function_project.rs +++ b/crates/registry-coordinator/tests/service_function_project.rs @@ -225,6 +225,12 @@ fn an_unbound_function_name_is_refused_against_the_runtime_binding() { let unbound = binding_finding(&RUNTIME.replace("function: draft-notice", "function: publish-notice")); assert_eq!(unbound["path"], "/operations/draft-notice/serviceFunction"); + assert!( + unbound["related"].as_array().is_some_and(|related| related + .iter() + .any(|other| other["path"] == "/connections/notices/function")), + "{unbound}" + ); assert!( unbound["message"] .as_str() diff --git a/crates/registry-rstack-dev/src/bindings.rs b/crates/registry-rstack-dev/src/bindings.rs index cf07d0a5d3..3036a94db2 100644 --- a/crates/registry-rstack-dev/src/bindings.rs +++ b/crates/registry-rstack-dev/src/bindings.rs @@ -60,7 +60,7 @@ const TOKEN_LIFETIME_SECONDS: u64 = 300; const TOKEN_SERVER_SHUTDOWN_GRACE: Duration = Duration::from_secs(2); const CLOCK_LEEWAY_SECONDS: u64 = 5; -/// Run-local connections between BReg and Casework. Configuring either one requires both products. +/// Run-local connections between products. The BReg and Casework bindings require both products; the Coordinator review producer requires Coordinator and Casework. #[derive(Default, Deserialize, Serialize)] #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] #[serde(rename_all = "camelCase", deny_unknown_fields)] @@ -71,6 +71,33 @@ pub(super) struct Bindings { /// Connects Casework to BReg as a context provider. Casework authenticates to BReg as a machine identity. #[serde(default, skip_serializing_if = "Option::is_none")] pub(super) casework_context_provider: Option, + /// Connects the Coordinator to Casework as one trusted review producer. The Coordinator authenticates to Casework as a machine identity, and Casework wakes its waiting run through a completion hook. Development runs only. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub(super) coordinator_review_producer: Option, +} + +/// The Coordinator's Casework review producer connection that the run binds +/// to Casework. Casework trusts exactly the producer the connection names, for +/// the run issuer, only when its pinned issuer, profile and subject match the +/// guards; nothing here widens what Casework trusts. +#[derive(Deserialize, Serialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub(super) struct CoordinatorReviewProducer { + /// The Coordinator `runtime.yaml` connection of type `casework-review-producer`. Its `producer` names the Casework trusted producer. + #[cfg_attr(feature = "schema", schemars(with = "registry_platform_yaml::LocalId"))] + pub(super) connection: String, + /// The Casework trusted producer in `casework.yaml`. It must be the producer the connection names. + #[cfg_attr(feature = "schema", schemars(with = "registry_platform_yaml::LocalId"))] + pub(super) producer: String, + /// Name of the test person, in `people`, whose Casework grant the Coordinator uses to authenticate. Its profile and subject are the producer's. + #[cfg_attr(feature = "schema", schemars(with = "registry_platform_yaml::LocalId"))] + pub(super) identity: String, + /// The completion `destinationId` the producer names in `casework.yaml`. The run binds it to the Coordinator's completion endpoint with a per-run key. + #[cfg_attr(feature = "schema", schemars(with = "registry_platform_yaml::LocalId"))] + pub(super) completion_destination: String, + /// The exact source guards for binding this producer to the synthetic run issuer. An initiator guard is refused. + pub(super) run_issuer_binding: RunIssuerBinding, } /// A BReg review authority that the run connects to Casework. @@ -149,9 +176,13 @@ impl Bindings { self.breg_review_authority .as_ref() .is_some_and(|binding| binding.run_issuer_binding.is_some()) + || self.coordinator_review_producer.is_some() } pub(super) fn validate(&self, plan: &Plan) -> plan::SemanticResult<()> { + if let Some(binding) = &self.coordinator_review_producer { + validate_coordinator_review_producer(plan, binding)?; + } if self.breg_review_authority.is_none() && self.casework_context_provider.is_none() { return Ok(()); } @@ -207,6 +238,45 @@ impl Bindings { } } +const COORDINATOR_PRODUCER: &str = "/bindings/coordinatorReviewProducer"; + +fn validate_coordinator_review_producer( + plan: &Plan, + binding: &CoordinatorReviewProducer, +) -> plan::SemanticResult<()> { + plan::require( + product_position(plan, Product::Coordinator).is_some() + && product_position(plan, Product::Casework).is_some(), + "/bindings", + "The Coordinator review producer binding requires the Coordinator and Casework products.", + "Add both products to products, or remove bindings.coordinatorReviewProducer.", + )?; + for (member, value) in [ + ("connection", &binding.connection), + ("producer", &binding.producer), + ("completionDestination", &binding.completion_destination), + ] { + plan::require( + plan::identifier(value), + &format!("{COORDINATOR_PRODUCER}/{member}"), + "The value must be a local identifier.", + "Set it to a lowercase local identifier of at most 64 characters.", + )?; + } + require_machine_person( + plan, + &binding.identity, + Product::Casework, + &format!("{COORDINATOR_PRODUCER}/identity"), + )?; + plan::require( + binding.run_issuer_binding.initiator.is_none(), + &format!("{COORDINATOR_PRODUCER}/runIssuerBinding/initiator"), + "The Coordinator review producer binding binds only the producer to the run issuer.", + "Remove initiator: the Coordinator submits its own review requests.", + ) +} + fn product_position(plan: &Plan, product: Product) -> Option { plan.products .iter() @@ -415,6 +485,13 @@ struct TokenServer { } const BREG_REVIEW_CLIENT: &str = "breg-review-client"; +const COORDINATOR_REVIEW_CLIENT: &str = "coordinator-review-client"; +/// The run file holding the HMAC key Casework signs a Coordinator review +/// completion with and the Coordinator verifies it with. +pub(super) const COORDINATOR_COMPLETION_KEY: &str = "coordinator-review-completion-key"; +/// The Coordinator's review completion route, as `registry-review-protocol` +/// declares it. rstack dev depends on no product protocol crate. +const REVIEW_COMPLETIONS_PATH: &str = "/v1/review-completions"; const CASEWORK_CONTEXT_CLIENT: &str = "casework-context-client"; #[derive(Default)] @@ -435,15 +512,26 @@ impl RuntimeBindings { origins: &BTreeMap, ) -> Result { let bindings = &input.plan.bindings; - if bindings.breg_review_authority.is_none() && bindings.casework_context_provider.is_none() + if bindings.breg_review_authority.is_none() + && bindings.casework_context_provider.is_none() + && bindings.coordinator_review_producer.is_none() { return Ok(Self::default()); } bindings.validate(&input.plan)?; ensure!( - origins.contains_key(&Product::Breg) && origins.contains_key(&Product::Casework), + (bindings.breg_review_authority.is_none() + && bindings.casework_context_provider.is_none()) + || (origins.contains_key(&Product::Breg) + && origins.contains_key(&Product::Casework)), "run-local bindings require reserved BReg and Casework origins" ); + ensure!( + bindings.coordinator_review_producer.is_none() + || (origins.contains_key(&Product::Coordinator) + && origins.contains_key(&Product::Casework)), + "the Coordinator review producer binding requires reserved Coordinator and Casework origins" + ); let mut clients = Vec::new(); if let Some(binding) = &bindings.breg_review_authority { @@ -466,6 +554,22 @@ impl RuntimeBindings { &mut clients, )?; } + if let Some(binding) = &bindings.coordinator_review_producer { + prepare_binding( + root, + &input, + &binding.identity, + Product::Casework, + COORDINATOR_REVIEW_CLIENT, + &mut clients, + )?; + // Casework signs each completion with this key and the + // Coordinator verifies it: exact random bytes, owner-only, per run. + let mut key = Zeroizing::new([0_u8; 32]); + getrandom::fill(key.as_mut()) + .map_err(|_| anyhow::anyhow!("cannot generate the review completion key"))?; + write_private(&root.join(COORDINATOR_COMPLETION_KEY), key.as_ref())?; + } let server = start_token_server(input.clone(), issuer.clone(), clients)?; Ok(Self { server: Some(server), @@ -529,6 +633,12 @@ fn render( }); } Product::Casework => { + if let Some(binding) = plan.bindings.coordinator_review_producer.as_ref() { + config["destinations"]["hooks"][binding.completion_destination.as_str()] = json!({ + "url": format!("{}{REVIEW_COMPLETIONS_PATH}", origins[&Product::Coordinator]), + "hmacSha256KeyRef": format!("secret:file/{COORDINATOR_COMPLETION_KEY}"), + }); + } let Some(binding) = plan.bindings.casework_context_provider.as_ref() else { return; }; @@ -548,6 +658,43 @@ fn render( "clientAssertionKeyRef": client_assertion_key_ref, }); } + Product::Coordinator => { + let Some(binding) = plan.bindings.coordinator_review_producer.as_ref() else { + return; + }; + let Some(connection) = config["connections"] + .get_mut(binding.connection.as_str()) + .and_then(Value::as_object_mut) + else { + return; + }; + let person = &plan.people[&binding.identity]; + let grant = &person.grants[&Product::Casework]; + let (_, signing_key_ref) = client_refs(COORDINATOR_REVIEW_CLIENT); + connection.insert("baseUrl".into(), json!(origins[&Product::Casework])); + connection.insert("profile".into(), json!(grant.profile)); + connection.insert( + "authorization".into(), + json!({ + "tokenEndpoint": token_endpoint, + "clientAssertionAudience": issuer, + "clientId": person.client, + "signingKeyRef": signing_key_ref, + "resource": plan.product(Product::Casework).audience, + "scopes": grant.scopes, + }), + ); + if let Some(completion) = connection + .get_mut("completion") + .and_then(Value::as_object_mut) + { + completion.remove("previousHmacSha256KeyRef"); + completion.insert( + "hmacSha256KeyRef".into(), + json!(format!("secret:file/{COORDINATOR_COMPLETION_KEY}")), + ); + } + } // Evidence has no bindings: a caller reaches it with a test token. // Messaging has no bindings: a caller reaches it with a test token. _ => {} @@ -584,6 +731,7 @@ pub(super) fn render_for_check(plan: &Plan, product: Product, config: &mut Value let origins = BTreeMap::from([ (Product::Breg, CHECK_ORIGIN.to_owned()), (Product::Casework, CHECK_ORIGIN.to_owned()), + (Product::Coordinator, CHECK_ORIGIN.to_owned()), ]); render( plan, @@ -1516,6 +1664,7 @@ mod tests { identity: "context-reader".to_owned(), action: "reviewed-change".to_owned(), }), + coordinator_review_producer: None, }, journey_file: PathBuf::from("dev-journeys.yaml"), schema_test_people: BTreeMap::new(), @@ -2981,4 +3130,246 @@ mod tests { "{error}" ); } + + /// Casework and the Coordinator, with the Coordinator's `review` + /// connection bound as the `coordinator` producer. + fn coordinator_plan() -> Plan { + let mut value = plan(); + value.products = vec![ + ProductPlan { + product: Product::Casework, + project: PathBuf::from("casework"), + audience: "urn:dev:casework".to_owned(), + }, + ProductPlan { + product: Product::Coordinator, + project: PathBuf::from("coordinator"), + audience: "urn:dev:coordinator".to_owned(), + }, + ]; + value.people = BTreeMap::from([( + "coordinator-producer".to_owned(), + TestPerson { + subject: "coordinator-producer".to_owned(), + display_name: None, + client: "coordinator-review-client".to_owned(), + grants: BTreeMap::from([( + Product::Casework, + grant("coordinator-producer", "casework:review"), + )]), + }, + )]); + value.bindings = serde_json::from_value(json!({"coordinatorReviewProducer": { + "connection": "review", "producer": "coordinator", "identity": "coordinator-producer", + "completionDestination": "coordinator-wake", + "runIssuerBinding": {"producer": { + "expectedIssuer": "https://identity.example.test/producer", + "expectedProfile": "coordinator-producer", + "expectedSubject": "coordinator-producer" + }} + }})) + .unwrap(); + value + } + + fn coordinator_origins() -> BTreeMap { + BTreeMap::from([ + (Product::Casework, "http://127.0.0.1:31002".to_owned()), + (Product::Coordinator, "http://127.0.0.1:31003".to_owned()), + ]) + } + + #[test] + fn a_coordinator_review_producer_needs_its_products_identity_and_a_closed_guard() { + let value = coordinator_plan(); + value.bindings.validate(&value).unwrap(); + // The bound Coordinator and Casework pair may use the run issuer. + assert!(value.paired_run_binding()); + let refused = |change: fn(&mut Plan)| { + let mut value = coordinator_plan(); + change(&mut value); + value.bindings.validate(&value).unwrap_err().to_string() + }; + let error = refused(|plan| { + plan.products + .retain(|entry| entry.product != Product::Coordinator) + }); + assert!(error.contains("/bindings"), "{error}"); + let error = refused(|plan| { + plan.people + .get_mut("coordinator-producer") + .unwrap() + .grants + .clear(); + }); + assert!( + error.contains("/bindings/coordinatorReviewProducer/identity"), + "{error}" + ); + let error = refused(|plan| { + plan.bindings + .coordinator_review_producer + .as_mut() + .unwrap() + .connection = "Review".to_owned(); + }); + assert!( + error.contains("/bindings/coordinatorReviewProducer/connection"), + "{error}" + ); + let error = refused(|plan| { + plan.bindings + .coordinator_review_producer + .as_mut() + .unwrap() + .run_issuer_binding + .initiator = Some(RunInitiator { + expected_issuer: "https://identity.example.test/people".to_owned(), + trust: RunInitiatorTrust::RunTestPeople, + }); + }); + assert!( + error.contains("/bindings/coordinatorReviewProducer/runIssuerBinding/initiator"), + "{error}" + ); + } + + #[test] + fn the_coordinator_review_producer_renders_both_sides_with_one_run_key() { + use std::os::unix::fs::PermissionsExt; + let root = tempfile::tempdir().unwrap(); + let run = Arc::new(input(coordinator_plan())); + let issuer = Arc::new(Issuer::create(root.path()).unwrap()); + let runtime = + RuntimeBindings::prepare(root.path(), run.clone(), issuer, &coordinator_origins()) + .unwrap(); + let endpoint = runtime.server.as_ref().unwrap().endpoint.clone(); + + let mut casework = json!({}); + runtime.configure(Product::Casework, &mut casework); + assert_eq!( + casework["destinations"]["hooks"]["coordinator-wake"], + json!({ + "url": "http://127.0.0.1:31003/v1/review-completions", + "hmacSha256KeyRef": "secret:file/coordinator-review-completion-key" + }) + ); + + let mut coordinator = json!({"connections": { + "review": { + "type": "casework-review-producer", "baseUrl": "http://127.0.0.1:1", + "profile": "coordinator-producer", "producer": "coordinator", + "authorization": {"tokenEndpoint": "http://127.0.0.1:1/token", "clientId": "authored"}, + "completion": {"recipientBinding": "coordinator-v1", "hmacSha256KeyRef": "secret:file/authored"} + }, + "other": {"type": "breg", "baseUrl": "http://127.0.0.1:2"} + }}); + runtime.configure(Product::Coordinator, &mut coordinator); + assert_eq!( + coordinator["connections"]["review"], + json!({ + "type": "casework-review-producer", "baseUrl": "http://127.0.0.1:31002", + "profile": "coordinator-producer", "producer": "coordinator", + "authorization": { + "tokenEndpoint": endpoint, + "clientAssertionAudience": run.plan.issuer, + "clientId": "coordinator-review-client", + "signingKeyRef": "secret:file/coordinator-review-client-key", + "resource": "urn:dev:casework", + "scopes": ["casework:review"] + }, + "completion": { + "recipientBinding": "coordinator-v1", + "hmacSha256KeyRef": "secret:file/coordinator-review-completion-key" + } + }) + ); + assert_eq!( + coordinator["connections"]["other"], + json!({"type": "breg", "baseUrl": "http://127.0.0.1:2"}) + ); + + // One owner-only key of exact random bytes signs and verifies the wake-up. + let key = root.path().join("coordinator-review-completion-key"); + assert_eq!(std::fs::read(&key).unwrap().len(), 32); + assert_eq!( + std::fs::metadata(&key).unwrap().permissions().mode() & 0o777, + 0o600 + ); + + // Without the binding, nothing is rendered for either side. + let mut plain = coordinator_plan(); + plain.bindings = Bindings::default(); + let unbound = RuntimeBindings::prepare( + root.path(), + Arc::new(input(plain)), + Arc::new(Issuer::create(root.path()).unwrap()), + &coordinator_origins(), + ) + .unwrap(); + let mut untouched = json!({"connections": {"review": {"baseUrl": "http://127.0.0.1:1"}}}); + unbound.configure(Product::Coordinator, &mut untouched); + assert_eq!( + untouched, + json!({"connections": {"review": {"baseUrl": "http://127.0.0.1:1"}}}) + ); + } + + #[test] + fn the_coordinator_obtains_a_producer_token_from_the_run_token_server() { + use base64::Engine as _; + let root = tempfile::tempdir().unwrap(); + let mut run = input(coordinator_plan()); + // Casework names the subject claim for each profile it serves. + run.casework_principals + .insert("coordinator-producer".to_owned(), "sub".to_owned()); + let input = Arc::new(run); + let issuer = Arc::new(Issuer::create(root.path()).unwrap()); + let runtime = + RuntimeBindings::prepare(root.path(), input.clone(), issuer, &coordinator_origins()) + .unwrap(); + let mut coordinator = json!({"connections": {"review": { + "type": "casework-review-producer", "producer": "coordinator", + "completion": {"recipientBinding": "coordinator-v1", "hmacSha256KeyRef": "secret:file/authored"} + }}}); + runtime.configure(Product::Coordinator, &mut coordinator); + let authorization = &coordinator["connections"]["review"]["authorization"]; + let encoded = Zeroizing::new( + std::fs::read(root.path().join("coordinator-review-client-key")).unwrap(), + ); + let key = PrivateJwk::parse(std::str::from_utf8(&encoded).unwrap()).unwrap(); + // The client the Coordinator builds from its rendered authorization. + let provider = PrivateKeyJwt::new( + PrivateKeyJwtConfig::new( + authorization["tokenEndpoint"] + .as_str() + .unwrap() + .parse() + .unwrap(), + authorization["clientId"].as_str().unwrap(), + key, + ) + .with_audience(authorization["clientAssertionAudience"].as_str().unwrap()) + .with_resource(authorization["resource"].as_str().unwrap()) + .with_scopes(vec!["casework:review".to_owned()]), + ) + .unwrap(); + let token = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .unwrap() + .block_on(provider.bearer_token()) + .expect("the Coordinator obtains a producer token"); + let header = token.authorization_header_value(); + let compact = header.to_str().unwrap().trim_start_matches("Bearer "); + let claims: Value = serde_json::from_slice( + &base64::engine::general_purpose::URL_SAFE_NO_PAD + .decode(compact.split('.').nth(1).unwrap()) + .unwrap(), + ) + .unwrap(); + assert_eq!(claims["sub"], "coordinator-producer"); + assert_eq!(claims["aud"], "urn:dev:casework"); + assert_eq!(claims["iss"], input.plan.issuer); + } } diff --git a/crates/registry-rstack-dev/src/plan.rs b/crates/registry-rstack-dev/src/plan.rs index ad9f2ae3a3..9217f33be5 100644 --- a/crates/registry-rstack-dev/src/plan.rs +++ b/crates/registry-rstack-dev/src/plan.rs @@ -1357,9 +1357,12 @@ fn preview_plan( impl Plan { pub(super) fn paired_run_binding(&self) -> bool { + let has = |product| self.products.iter().any(|p| p.product == product); self.bindings.binds_run_issuer() - && self.products.iter().any(|p| p.product == Product::Breg) - && self.products.iter().any(|p| p.product == Product::Casework) + && has(Product::Casework) + && (has(Product::Breg) + || (self.bindings.coordinator_review_producer.is_some() + && has(Product::Coordinator))) } pub(super) fn runs_evidence(&self) -> bool { diff --git a/crates/registry-rstack-dev/src/products.rs b/crates/registry-rstack-dev/src/products.rs index a91be141f5..54d5724edd 100644 --- a/crates/registry-rstack-dev/src/products.rs +++ b/crates/registry-rstack-dev/src/products.rs @@ -27,7 +27,7 @@ use std::{ }; use super::{ - bindings::{Bindings, BregReviewAuthority, RunIssuerBinding, RuntimeBindings}, + bindings::{Bindings, RunIssuerBinding, RuntimeBindings}, browser::BrowserClient, clock, database::{Database, DatabaseUrls}, @@ -1687,7 +1687,12 @@ impl<'a> ProductRunner<'a> { } } } - return Ok(json!({ + if let Some(casework) = + product_root(&self.input.project, &self.input.plan, Product::Casework)? + { + checked_coordinator_review_producer(&self.input.plan, &casework.root, project)?; + } + let mut coordinator = json!({ "apiVersion": config["apiVersion"], "kind": "CoordinatorRuntimeConfig", "secretProviders": config["secretProviders"], @@ -1706,7 +1711,11 @@ impl<'a> ProductRunner<'a> { "stateKeys": {"1": {"keyRef": key("coordinator-state-key")?}}, "admissionKeyRef": key("coordinator-admission-key")?, } - })); + }); + if let Some(bindings) = &self.bindings { + bindings.configure(Product::Coordinator, &mut coordinator); + } + return Ok(coordinator); } Product::Adapter => { let template = authored_document(&project.join("runtime.example.yaml"))?; @@ -3097,6 +3106,9 @@ fn casework_principals( if has_run_source(plan) { checked_casework_run_issuer(plan, &project.root)?; } + if let Some(coordinator) = product_root(root, plan, Product::Coordinator)? { + checked_coordinator_review_producer(plan, &project.root, &coordinator.root)?; + } if let Some(binding) = &plan.bindings.casework_context_provider { check_casework_binding(&tool, &project, plan, binding, terminate)?; } @@ -3916,26 +3928,58 @@ pub(super) fn schema_people( Ok(bindings) } -/// The dev.yaml member that carries the run issuer binding. -const RUN_ISSUER_BINDING: &str = "/bindings/bregReviewAuthority/runIssuerBinding"; +/// One Casework producer a run binds to its issuer: the dev.yaml binding +/// that names it, the producer, the test person whose grant and subject it +/// uses, and the exact guards. +struct GuardedProducer<'a> { + binding: &'static str, + producer: &'a str, + identity: &'a str, + guard: &'a RunIssuerBinding, +} + +/// Every producer the plan binds to the run issuer. +fn guarded_producers(plan: &Plan) -> Vec> { + let mut producers = Vec::new(); + if let Some(binding) = &plan.bindings.breg_review_authority { + if let Some(guard) = &binding.run_issuer_binding { + producers.push(GuardedProducer { + binding: "/bindings/bregReviewAuthority", + producer: &binding.producer, + identity: &binding.identity, + guard, + }); + } + } + if let Some(binding) = &plan.bindings.coordinator_review_producer { + producers.push(GuardedProducer { + binding: "/bindings/coordinatorReviewProducer", + producer: &binding.producer, + identity: &binding.identity, + guard: &binding.run_issuer_binding, + }); + } + producers +} /// Writes the run's loopback issuer into a copy of the Casework project at -/// `bound`. The source project is never edited. The copy changes only the -/// selected producer's `issuer`, and its `trustedInitiatorIssuer` when the +/// `bound`. The source project is never edited. The copy changes only each +/// bound producer's `issuer`, and its `trustedInitiatorIssuer` when the /// binding names an initiator. The caller then runs the public `caseworkctl /// check` and `package` on the copy, which refuse every other policy error. fn bind_casework_run_issuer(plan: &Plan, project: &Path, bound: &Path) -> Result<()> { let mut document = checked_casework_run_issuer(plan, project)?; - let (binding, guard) = run_issuer_binding(plan)?; ensure!( is_loopback_run_issuer(&plan.issuer), "the run issuer {} is not a loopback URL of the form http://127.0.0.1:", plan.issuer ); - let entry = &mut document["trustedProducers"][&binding.producer]; - entry["issuer"] = json!(plan.issuer); - if guard.initiator.is_some() { - entry["trustedInitiatorIssuer"] = json!(plan.issuer); + for bound_producer in guarded_producers(plan) { + let entry = &mut document["trustedProducers"][bound_producer.producer]; + entry["issuer"] = json!(plan.issuer); + if bound_producer.guard.initiator.is_some() { + entry["trustedInitiatorIssuer"] = json!(plan.issuer); + } } copy_project(project, bound)?; write_private( @@ -3944,35 +3988,19 @@ fn bind_casework_run_issuer(plan: &Plan, project: &Path, bound: &Path) -> Result ) } -fn run_issuer_binding(plan: &Plan) -> Result<(&BregReviewAuthority, &RunIssuerBinding)> { - let binding = plan - .bindings - .breg_review_authority - .as_ref() - .context("the run issuer binding needs a review authority binding")?; - let guard = binding - .run_issuer_binding - .as_ref() - .context("the review authority binding has no run issuer binding")?; - Ok((binding, guard)) -} - /// Reads the Casework project's `casework.yaml` and refuses, at the dev.yaml /// pointer, a run issuer binding that does not match the trusted producer it /// names. `check` runs this before any product starts; `start` runs it again /// before binding the run issuer. fn checked_casework_run_issuer(plan: &Plan, project: &Path) -> Result { - let (binding, guard) = run_issuer_binding(plan)?; let refuse = |pointer: String, message: &str, action: &str| { anyhow::Error::from(plan::SemanticRefusal::new(&pointer, message, action)) }; - let identity = &plan.people[&binding.identity]; - let grant = &identity.grants[&Product::Casework]; - let person = format!( - "/people/{}", - registry_platform_yaml::escape_pointer_segment(&binding.identity) + let producers = guarded_producers(plan); + ensure!( + !producers.is_empty(), + "the plan binds no producer to the run issuer" ); - let source = project.join("casework.yaml"); let bytes = fs::read(&source).with_context(|| format!("cannot read {}", source.display()))?; let document = registry_platform_yaml::Reader::new(source.display().to_string()) @@ -3980,63 +4008,170 @@ fn checked_casework_run_issuer(plan: &Plan, project: &Path) -> Result { .map_err(|_| anyhow::anyhow!("{} is not valid YAML", source.display()))? .with_context(|| format!("{} is empty", source.display()))? .to_json_value(); - let producer = document["trustedProducers"][&binding.producer].clone(); - if !producer.is_object() { + for GuardedProducer { + binding, + producer: id, + identity: alias, + guard, + } in producers + { + let run_issuer_binding = format!("{binding}/runIssuerBinding"); + let identity = &plan.people[alias]; + let grant = &identity.grants[&Product::Casework]; + let person = format!( + "/people/{}", + registry_platform_yaml::escape_pointer_segment(alias) + ); + let producer = document["trustedProducers"][id].clone(); + if !producer.is_object() { + return Err(refuse( + format!("{binding}/producer"), + "The Casework project has no trusted producer with this ID.", + "Set producer to a trustedProducers entry in casework.yaml.", + )); + } + let text = |member: &str| producer[member].as_str().unwrap_or_default(); + let expected = &guard.producer; + if text("issuer") != expected.expected_issuer { + return Err(refuse( + format!("{run_issuer_binding}/producer/expectedIssuer"), + "The producer's issuer in casework.yaml is not the issuer the binding expects.", + "Set expectedIssuer to the issuer the Casework project pins for this producer.", + )); + } + if text("profile") != expected.expected_profile + || grant.profile != expected.expected_profile + { + return Err(refuse( + format!("{run_issuer_binding}/producer/expectedProfile"), + "The producer's profile in casework.yaml, the binding and the identity's Casework grant must be the same profile.", + "Set expectedProfile and the identity's Casework grant profile to the producer's profile.", + )); + } + if text("subject") != expected.expected_subject + || identity.subject != expected.expected_subject + { + return Err(refuse( + format!("{run_issuer_binding}/producer/expectedSubject"), + "The producer's subject in casework.yaml, the binding and the identity's subject must be the same subject.", + "Set expectedSubject and the identity's subject to the producer's subject.", + )); + } + let required = document["accessProfiles"][&expected.expected_profile]["requiredScopes"] + .as_array() + .cloned() + .unwrap_or_default(); + if let Some(missing) = required + .iter() + .filter_map(Value::as_str) + .find(|scope| !grant.scopes.iter().any(|granted| granted == scope)) + { + return Err(refuse( + format!("{person}/roles"), + &format!("The identity's Casework grant lacks the scope {missing} that the producer's profile requires."), + "Assign a role whose Casework profile supplies the required scope.", + )); + } + if let Some(initiator) = &guard.initiator { + if producer["trustedInitiatorIssuer"].as_str() + != Some(initiator.expected_issuer.as_str()) + { + return Err(refuse( + format!("{run_issuer_binding}/initiator/expectedIssuer"), + "The producer's trustedInitiatorIssuer in casework.yaml is not the issuer the binding expects.", + "Set expectedIssuer to the trustedInitiatorIssuer the Casework project pins for this producer.", + )); + } + } + } + Ok(document) +} + +/// Refuses, at the dev.yaml pointer, a Coordinator review producer the run +/// cannot bind exactly: a `casework-review-producer` connection without the +/// binding, a binding whose connection, producer, profile or completion does +/// not match the Coordinator runtime and `casework.yaml`, or a producer whose +/// guards do not match. `check` runs this before any product starts and +/// `start` again before rendering the Coordinator. +fn checked_coordinator_review_producer( + plan: &Plan, + casework: &Path, + coordinator: &Path, +) -> Result<()> { + const BINDING: &str = "/bindings/coordinatorReviewProducer"; + let refuse = |pointer: String, message: &str, action: &str| { + anyhow::Error::from(plan::SemanticRefusal::new(&pointer, message, action)) + }; + let runtime = authored_document(&coordinator.join("runtime.yaml"))?; + let Some(binding) = &plan.bindings.coordinator_review_producer else { + let producers = runtime["connections"] + .as_object() + .is_some_and(|connections| { + connections + .values() + .any(|connection| connection["type"] == "casework-review-producer") + }); + if producers + && plan + .products + .iter() + .any(|entry| entry.product == Product::Casework) + { + return Err(refuse( + "/bindings".to_owned(), + "A Coordinator casework-review-producer connection needs bindings.coordinatorReviewProducer before Casework trusts it in this run.", + "Add bindings.coordinatorReviewProducer naming the connection, producer, identity, completion destination and run issuer guards.", + )); + } + return Ok(()); + }; + let connection = &runtime["connections"][&binding.connection]; + if connection["type"] != "casework-review-producer" { return Err(refuse( - "/bindings/bregReviewAuthority/producer".to_owned(), - "The Casework project has no trusted producer with this ID.", - "Set producer to a trustedProducers entry in casework.yaml.", + format!("{BINDING}/connection"), + "The Coordinator runtime.yaml has no casework-review-producer connection with this name.", + "Set connection to the Coordinator connection that submits review requests to Casework.", )); } - let text = |member: &str| producer[member].as_str().unwrap_or_default(); - let expected = &guard.producer; - if text("issuer") != expected.expected_issuer { + if connection["producer"].as_str() != Some(binding.producer.as_str()) { return Err(refuse( - format!("{RUN_ISSUER_BINDING}/producer/expectedIssuer"), - "The producer's issuer in casework.yaml is not the issuer the binding expects.", - "Set expectedIssuer to the issuer the Casework project pins for this producer.", + format!("{BINDING}/producer"), + "The Coordinator connection names another Casework producer.", + "Set producer to the producer the Coordinator connection names.", )); } - if text("profile") != expected.expected_profile || grant.profile != expected.expected_profile { + let grant = &plan.people[&binding.identity].grants[&Product::Casework]; + if connection["profile"].as_str() != Some(grant.profile.as_str()) { return Err(refuse( - format!("{RUN_ISSUER_BINDING}/producer/expectedProfile"), - "The producer's profile in casework.yaml, the binding and the identity's Casework grant must be the same profile.", - "Set expectedProfile and the identity's Casework grant profile to the producer's profile.", + format!("{BINDING}/connection"), + "The Coordinator connection's profile is not the identity's Casework grant profile.", + "Set the connection's profile to the producer's Casework profile.", )); } - if text("subject") != expected.expected_subject || identity.subject != expected.expected_subject - { + let Some(recipient) = connection["completion"]["recipientBinding"].as_str() else { return Err(refuse( - format!("{RUN_ISSUER_BINDING}/producer/expectedSubject"), - "The producer's subject in casework.yaml, the binding and the identity's subject must be the same subject.", - "Set expectedSubject and the identity's subject to the producer's subject.", + format!("{BINDING}/connection"), + "The Coordinator connection has no completion, so Casework could not wake the waiting run.", + "Add completion with the recipientBinding casework.yaml names; the run supplies its key.", )); - } - let required = document["accessProfiles"][&expected.expected_profile]["requiredScopes"] - .as_array() - .cloned() - .unwrap_or_default(); - if let Some(missing) = required - .iter() - .filter_map(Value::as_str) - .find(|scope| !grant.scopes.iter().any(|granted| granted == scope)) - { + }; + let document = checked_casework_run_issuer(plan, casework)?; + let completion = &document["trustedProducers"][&binding.producer]["completion"]; + if completion["destinationId"].as_str() != Some(binding.completion_destination.as_str()) { return Err(refuse( - format!("{person}/roles"), - &format!("The identity's Casework grant lacks the scope {missing} that the producer's profile requires."), - "Assign a role whose Casework profile supplies the required scope.", + format!("{BINDING}/completionDestination"), + "The producer's completion destination in casework.yaml is not the binding's.", + "Set completionDestination to the producer's completion destinationId in casework.yaml.", )); } - if let Some(initiator) = &guard.initiator { - if producer["trustedInitiatorIssuer"].as_str() != Some(initiator.expected_issuer.as_str()) { - return Err(refuse( - format!("{RUN_ISSUER_BINDING}/initiator/expectedIssuer"), - "The producer's trustedInitiatorIssuer in casework.yaml is not the issuer the binding expects.", - "Set expectedIssuer to the trustedInitiatorIssuer the Casework project pins for this producer.", - )); - } + if completion["recipientBinding"].as_str() != Some(recipient) { + return Err(refuse( + format!("{BINDING}/connection"), + "The Coordinator connection's completion recipientBinding is not the one casework.yaml names for this producer.", + "Use the same recipientBinding in the Coordinator connection and the producer's completion.", + )); } - Ok(document) + Ok(()) } /// Only a reserved loopback run URL is bound, never a remote issuer. @@ -4385,9 +4520,238 @@ mod tests { identity: "context-reader".to_owned(), action: "review-action".to_owned(), }), + coordinator_review_producer: None, + } + } + + /// A Casework and Coordinator plan whose Coordinator `review` connection is + /// bound as the `coordinator` producer, with its casework.yaml and the + /// Coordinator runtime.yaml. + fn coordinator_producer_fixture() -> (Value, Value, Value) { + let plan = json!({ + "issuer": "http://127.0.0.1:41000/", + "products": [ + {"product": "casework", "project": "casework", "audience": "review"}, + {"product": "coordinator", "project": "coordinator", "audience": "urn:coordinator"} + ], + "people": {"coordinator": { + "subject": "coordinator-producer", "client": "coordinator-client", + "grants": {"casework": {"profile": "coordinator-producer", "scopes": ["review.write"]}} + }}, + "journeyFile": "dev-journeys.yaml", + "bindings": {"coordinatorReviewProducer": { + "connection": "review", "producer": "coordinator", "identity": "coordinator", + "completionDestination": "coordinator-wake", + "runIssuerBinding": {"producer": { + "expectedIssuer": PRODUCER_ISSUER, + "expectedProfile": "coordinator-producer", + "expectedSubject": "coordinator-producer" + }} + }} + }); + let casework = json!({ + "name": "synthetic-project", + "accessProfiles": {"coordinator-producer": {"requiredScopes": ["review.write"]}}, + "trustedProducers": { + "coordinator": { + "issuer": PRODUCER_ISSUER, "profile": "coordinator-producer", + "subject": "coordinator-producer", + "completion": {"destinationId": "coordinator-wake", "recipientBinding": "coordinator-v1"} + }, + "other-producer": {"issuer": "https://other.example.invalid/"} + } + }); + let coordinator = json!({"connections": {"review": { + "type": "casework-review-producer", "baseUrl": "http://127.0.0.1:1", + "profile": "coordinator-producer", "producer": "coordinator", + "completion": {"recipientBinding": "coordinator-v1", "hmacSha256KeyRef": "secret:file/authored"} + }}}); + (plan, casework, coordinator) + } + + fn coordinator_producer_projects( + root: &Path, + casework: &Value, + coordinator: &Value, + ) -> (PathBuf, PathBuf) { + let casework = write_casework_project(root, casework); + let project = root.join("coordinator"); + fs::create_dir(&project).unwrap(); + fs::write( + project.join("runtime.yaml"), + serde_norway::to_string(coordinator).unwrap(), + ) + .unwrap(); + (casework, project) + } + + #[test] + fn a_coordinator_review_producer_refuses_each_mismatch_at_its_pointer() { + type Break = fn(&mut Value, &mut Value, &mut Value); + const BINDING: &str = "/bindings/coordinatorReviewProducer"; + let cases: [(&str, String, Break); 12] = [ + ( + "the producer issuer differs from the binding", + format!("{BINDING}/runIssuerBinding/producer/expectedIssuer"), + |_, casework, _| { + casework["trustedProducers"]["coordinator"]["issuer"] = + json!("https://elsewhere.example.invalid/") + }, + ), + ( + "casework.yaml profile differs from the binding", + format!("{BINDING}/runIssuerBinding/producer/expectedProfile"), + |_, casework, _| { + casework["trustedProducers"]["coordinator"]["profile"] = json!("other-profile") + }, + ), + ( + "the identity subject differs from the binding", + format!("{BINDING}/runIssuerBinding/producer/expectedSubject"), + |plan, _, _| plan["people"]["coordinator"]["subject"] = json!("someone-else"), + ), + ( + "the producer is not in casework.yaml", + format!("{BINDING}/producer"), + |_, casework, _| { + casework["trustedProducers"] + .as_object_mut() + .unwrap() + .remove("coordinator"); + }, + ), + ( + "the connection is missing", + format!("{BINDING}/connection"), + |_, _, coordinator| { + coordinator["connections"] + .as_object_mut() + .unwrap() + .remove("review"); + }, + ), + ( + "the connection is of another type", + format!("{BINDING}/connection"), + |_, _, coordinator| coordinator["connections"]["review"]["type"] = json!("breg"), + ), + ( + "the connection names another producer", + format!("{BINDING}/producer"), + |_, _, coordinator| { + coordinator["connections"]["review"]["producer"] = json!("other-producer") + }, + ), + ( + "the connection profile differs from the grant", + format!("{BINDING}/connection"), + |_, _, coordinator| { + coordinator["connections"]["review"]["profile"] = json!("other-profile") + }, + ), + ( + "the producer has no completion destination", + format!("{BINDING}/completionDestination"), + |_, casework, _| { + casework["trustedProducers"]["coordinator"] + .as_object_mut() + .unwrap() + .remove("completion"); + }, + ), + ( + "the completion destination differs", + format!("{BINDING}/completionDestination"), + |_, casework, _| { + casework["trustedProducers"]["coordinator"]["completion"]["destinationId"] = + json!("elsewhere") + }, + ), + ( + "the recipient binding differs", + format!("{BINDING}/connection"), + |_, _, coordinator| { + coordinator["connections"]["review"]["completion"]["recipientBinding"] = + json!("other-v1") + }, + ), + ( + "the connection has no completion key", + format!("{BINDING}/connection"), + |_, _, coordinator| { + coordinator["connections"]["review"] + .as_object_mut() + .unwrap() + .remove("completion"); + }, + ), + ]; + let root = tempfile::tempdir().unwrap(); + for (index, (name, pointer, break_it)) in cases.into_iter().enumerate() { + let (mut plan, mut casework, mut coordinator) = coordinator_producer_fixture(); + break_it(&mut plan, &mut casework, &mut coordinator); + let case_root = root.path().join(index.to_string()); + fs::create_dir(&case_root).unwrap(); + let (casework, coordinator) = + coordinator_producer_projects(&case_root, &casework, &coordinator); + let plan: Plan = serde_json::from_value(plan).unwrap(); + let error = + checked_coordinator_review_producer(&plan, &casework, &coordinator).unwrap_err(); + let refusal = error + .downcast_ref::() + .unwrap_or_else(|| panic!("{name}: not a semantic refusal: {error}")); + assert!( + refusal + .to_string() + .starts_with(&format!("dev.yaml {pointer}: ")), + "{name}: {refusal}" + ); } } + #[test] + fn a_coordinator_casework_producer_without_its_binding_is_refused() { + let root = tempfile::tempdir().unwrap(); + let (mut plan, casework, coordinator) = coordinator_producer_fixture(); + plan.as_object_mut().unwrap().remove("bindings"); + let (casework, coordinator) = + coordinator_producer_projects(root.path(), &casework, &coordinator); + let plan: Plan = serde_json::from_value(plan).unwrap(); + let error = + checked_coordinator_review_producer(&plan, &casework, &coordinator).unwrap_err(); + let refusal = error.downcast_ref::().unwrap(); + assert!( + refusal.to_string().starts_with("dev.yaml /bindings: "), + "{refusal}" + ); + assert!( + refusal.to_string().contains("coordinatorReviewProducer"), + "{refusal}" + ); + } + + #[test] + fn a_bound_coordinator_producer_trusts_only_the_run_issuer_for_that_producer() { + let root = tempfile::tempdir().unwrap(); + let (plan, casework, coordinator) = coordinator_producer_fixture(); + let (project, coordinator) = + coordinator_producer_projects(root.path(), &casework, &coordinator); + let plan: Plan = serde_json::from_value(plan).unwrap(); + checked_coordinator_review_producer(&plan, &project, &coordinator).unwrap(); + assert!(has_run_source(&plan)); + let bound = root.path().join("bound"); + bind_casework_run_issuer(&plan, &project, &bound).unwrap(); + let document = authored_document(&bound.join("casework.yaml")).unwrap(); + assert_eq!( + document["trustedProducers"]["coordinator"]["issuer"], + plan.issuer + ); + assert_eq!( + document["trustedProducers"]["other-producer"]["issuer"], + "https://other.example.invalid/" + ); + } + #[test] fn breg_binding_ids_are_resolved_with_typed_value_free_refusals() { let bindings = product_bindings(); diff --git a/docs/site/src/content/docs/configure/run-a-project-with-rstack-dev.mdx b/docs/site/src/content/docs/configure/run-a-project-with-rstack-dev.mdx index e76a60dfd2..53a06ca3e6 100644 --- a/docs/site/src/content/docs/configure/run-a-project-with-rstack-dev.mdx +++ b/docs/site/src/content/docs/configure/run-a-project-with-rstack-dev.mdx @@ -73,6 +73,9 @@ reserves the function listener's loopback port before products start and writes owner-only host key for the run, which the Coordinator presents as its bearer. The function listener then hands the function a fixed placeholder bearer instead of the key, so the key never leaves the listener and no product accepts what the function receives. +Only the generated server binding hides the caller's headers from the handler. A function +that does not export that binding can read the raw request, which runs at the same trust +level as the function listener itself. The same function stays callable from the page through the gateway, with the page actor's authority, so write a Coordinator-bound function for both callers. One run key admits the gateway and the Coordinator to every preview function, not only the @@ -1023,6 +1026,53 @@ The worker holds the reservation until cleanup. crates/registry-rstack-dev/src/lib.rs casework-bound; crates/registry-rstack/tests/dev_run.rs casework_run_issuer_mismatch_names_the_dev_yaml_pointer. */} +### Bind the Coordinator as a Casework review producer + +A development plan with the Coordinator and Casework may bind one Coordinator +`casework-review-producer` connection to one existing Casework trusted producer. +Use `issuer: run`. A plan with such a connection and no binding is refused. + +```yaml +bindings: + coordinatorReviewProducer: + connection: review + producer: coordinator + identity: coordinator-producer + completionDestination: coordinator-wake + runIssuerBinding: + producer: + expectedIssuer: https://issuer.example.test + expectedProfile: coordinator-producer + expectedSubject: coordinator-producer +``` + +`check` refuses, at the `dev.yaml` pointer, a binding that does not match exactly: + +- the Coordinator `runtime.yaml` must name `connection` with type `casework-review-producer`, + the same `producer`, the identity's Casework grant profile, and a `completion`; +- `casework.yaml` must trust `producer` with exactly the expected issuer, profile and subject, + and the identity's subject, profile and scopes must match; +- the producer's `completion` must name `completionDestination` and the connection's + `recipientBinding`. + +An `initiator` guard is refused. The binding creates no producer, person, profile, client, +scope or grant. +`start` writes the run issuer into that one producer in a private copy of the Casework +project, as the BReg binding does. It gives the Coordinator connection the Casework origin, +the identity's Casework profile and a machine client on the run-local token endpoint, so its +token carries the identity's subject and Casework audience. It binds Casework's completion +destination to the Coordinator's review completion route. Both sides use one owner-only key +of random bytes written for the run, so Casework wakes the waiting run. +A live Coordinator run binds the connection's address, and the Casework origin changes with +each start. Let a waiting Coordinator run finish, or start with `--clean`, before you start again. + +{/* Evidence: crates/registry-rstack-dev/src/bindings.rs coordinatorReviewProducer, + the_coordinator_review_producer_renders_both_sides_with_one_run_key, + the_coordinator_obtains_a_producer_token_from_the_run_token_server; + crates/registry-rstack-dev/src/products.rs checked_coordinator_review_producer, + a_coordinator_review_producer_refuses_each_mismatch_at_its_pointer, + a_coordinator_casework_producer_without_its_binding_is_refused. */} + ### Explicit browser roles with separate human source credentials A paired BReg and Casework built application may declare `application.caseworkSourceCredentialRoles` as 1 through 32 distinct existing role identifiers. diff --git a/products/platform/config-formats.yaml b/products/platform/config-formats.yaml index 5f97332f3a..220cb2b651 100644 --- a/products/platform/config-formats.yaml +++ b/products/platform/config-formats.yaml @@ -892,6 +892,12 @@ formats: whenOmitted: refused - pointer: /bindings/bregReviewAuthority/runIssuerBinding/initiator whenOmitted: closed + - pointer: /bindings/coordinatorReviewProducer + whenOmitted: closed + - pointer: /bindings/coordinatorReviewProducer/runIssuerBinding + whenOmitted: refused + - pointer: /bindings/coordinatorReviewProducer/completionDestination + whenOmitted: refused - pointer: /preview whenOmitted: closed - pointer: /preview/actor diff --git a/products/platform/generated/dev/dev.v1alpha1.schema.json b/products/platform/generated/dev/dev.v1alpha1.schema.json index 49de653b2e..a13f8fafb8 100644 --- a/products/platform/generated/dev/dev.v1alpha1.schema.json +++ b/products/platform/generated/dev/dev.v1alpha1.schema.json @@ -274,7 +274,7 @@ }, "Bindings": { "additionalProperties": false, - "description": "Run-local connections between BReg and Casework. Configuring either one requires both products.", + "description": "Run-local connections between products. The BReg and Casework bindings require both products; the Coordinator review producer requires Coordinator and Casework.", "properties": { "bregReviewAuthority": { "$ref": "#/$defs/BregReviewAuthority", @@ -283,6 +283,10 @@ "caseworkContextProvider": { "$ref": "#/$defs/CaseworkContextProvider", "description": "Connects Casework to BReg as a context provider. Casework authenticates to BReg as a machine identity." + }, + "coordinatorReviewProducer": { + "$ref": "#/$defs/CoordinatorReviewProducer", + "description": "Connects the Coordinator to Casework as one trusted review producer. The Coordinator authenticates to Casework as a machine identity, and Casework wakes its waiting run through a completion hook. Development runs only." } }, "type": "object" @@ -339,6 +343,40 @@ ], "type": "object" }, + "CoordinatorReviewProducer": { + "additionalProperties": false, + "description": "The Coordinator's Casework review producer connection that the run binds\nto Casework. Casework trusts exactly the producer the connection names, for\nthe run issuer, only when its pinned issuer, profile and subject match the\nguards; nothing here widens what Casework trusts.", + "properties": { + "completionDestination": { + "$ref": "#/$defs/LocalId", + "description": "The completion `destinationId` the producer names in `casework.yaml`. The run binds it to the Coordinator's completion endpoint with a per-run key." + }, + "connection": { + "$ref": "#/$defs/LocalId", + "description": "The Coordinator `runtime.yaml` connection of type `casework-review-producer`. Its `producer` names the Casework trusted producer." + }, + "identity": { + "$ref": "#/$defs/LocalId", + "description": "Name of the test person, in `people`, whose Casework grant the Coordinator uses to authenticate. Its profile and subject are the producer's." + }, + "producer": { + "$ref": "#/$defs/LocalId", + "description": "The Casework trusted producer in `casework.yaml`. It must be the producer the connection names." + }, + "runIssuerBinding": { + "$ref": "#/$defs/RunIssuerBinding", + "description": "The exact source guards for binding this producer to the synthetic run issuer. An initiator guard is refused." + } + }, + "required": [ + "connection", + "producer", + "identity", + "completionDestination", + "runIssuerBinding" + ], + "type": "object" + }, "DerivedId": { "description": "A dotted development journey step identifier whose segments are local identifiers.", "maxLength": 64, From 8f0130c0f2301f1ac51f4c4b1a560266d8fe02b1 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 22:02:15 +0000 Subject: [PATCH 137/183] fix(dev): close the Coordinator review producer binding's widening paths Refuse a producer the BReg binding already binds and a second unbound casework-review-producer connection, give the binding a guard with no initiator member, check the same runtime document start renders, and remove the completion key first at stop. Tests now assert each refusal's own message, bind two producers together, compare the whole rebound document, prove fresh per-run keys that nothing else carries, and tie the completion route to the review protocol. A Coordinator error keeps its related location whatever position or remedy follows. Refs #2891 Signed-off-by: Jeremi Joslin --- crates/registry-coordinator/src/error.rs | 77 +++++++-- crates/registry-rstack-dev/src/bindings.rs | 159 ++++++++++++++---- crates/registry-rstack-dev/src/lib.rs | 12 ++ crates/registry-rstack-dev/src/plan.rs | 2 +- crates/registry-rstack-dev/src/products.rs | 128 +++++++++++--- .../run-a-project-with-rstack-dev.mdx | 14 +- .../src/content/docs/security/casework.mdx | 3 + .../src/content/docs/security/coordinator.mdx | 2 + products/platform/config-formats.yaml | 2 + .../generated/dev/dev.v1alpha1.schema.json | 17 +- 10 files changed, 342 insertions(+), 74 deletions(-) diff --git a/crates/registry-coordinator/src/error.rs b/crates/registry-coordinator/src/error.rs index dca0711c92..e9c774accd 100644 --- a/crates/registry-coordinator/src/error.rs +++ b/crates/registry-coordinator/src/error.rs @@ -24,6 +24,10 @@ pub struct CoordinatorError { pub(crate) refusal_detail: Option>, /// Whether this refusal rejected a development-marked token in production. pub(crate) development_assertion: bool, + /// Whether `diagnostics` is this error's own diagnostic, built only to + /// carry related locations, and so rebuilt when its position or remedy + /// changes. + pub(crate) related_only: bool, } #[derive(Debug)] @@ -48,6 +52,7 @@ impl CoordinatorError { check: None, refusal_detail: None, development_assertion: false, + related_only: false, } } /// Preserve all shared-reader findings and their authored positions. @@ -83,6 +88,7 @@ impl CoordinatorError { check: None, refusal_detail: None, development_assertion: false, + related_only: false, } } /// Name the check that refused the caller. @@ -166,22 +172,46 @@ impl CoordinatorError { } Report::new(vec![diagnostic]) } - pub fn at(mut self, file: impl Into, field: impl Into) -> Self { - self.file = Some(Box::new(file.into())); - self.field = Some(field.into().into_boxed_str()); - self + pub fn at(self, file: impl Into, field: impl Into) -> Self { + self.keeping_related(|error| { + error.file = Some(Box::new(file.into())); + error.field = Some(field.into().into_boxed_str()); + }) } - pub fn suggest(mut self, action: impl Into) -> Self { - self.suggested_action = Some(action.into().into_boxed_str()); - self + pub fn suggest(self, action: impl Into) -> Self { + self.keeping_related(|error| { + error.suggested_action = Some(action.into().into_boxed_str()); + }) + } + /// Apply `change` and keep any related locations already named. + fn keeping_related(mut self, change: impl FnOnce(&mut Self)) -> Self { + let related = if self.related_only { + self.related_only = false; + let diagnostics = std::mem::take(&mut self.diagnostics); + diagnostics + .into_vec() + .into_iter() + .next() + .map(|diagnostic| diagnostic.related) + } else { + None + }; + change(&mut self); + related.into_iter().flatten().fold(self, |error, related| { + error.related(&related.file, &related.path, related.message) + }) } - /// Name a second location that takes part in this refusal. The refusal - /// is then reported as one diagnostic that lists it as related. + /// Name another location that takes part in this refusal. It is reported + /// with the refusal whatever position or remedy is set before or after. #[must_use] pub(crate) fn related(mut self, file: &str, pointer: &str, message: impl Into) -> Self { - let mut diagnostics = self.report().diagnostics().to_vec(); - if let Some(diagnostic) = diagnostics.first_mut() { - diagnostic.related.push(registry_platform_yaml::Related { + if self.diagnostics.is_empty() { + self.diagnostics = self.report().diagnostics().to_vec().into(); + self.related_only = true; + } + let mut diagnostics = std::mem::take(&mut self.diagnostics).into_vec(); + if let Some(first) = diagnostics.first_mut() { + first.related.push(registry_platform_yaml::Related { file: file.to_owned(), line: None, column: None, @@ -214,3 +244,26 @@ impl CoordinatorError { } pub type Result = std::result::Result; + +#[cfg(test)] +mod related_tests { + use super::*; + + #[test] + fn a_related_location_survives_any_later_position_or_remedy() { + let error = CoordinatorError::new("workflow-binding", "the function is not bound") + .related( + "runtime.yaml", + "/connections/notices/function", + "the bound function", + ) + .at("workflow.yaml", "/operations/draft/serviceFunction") + .suggest("Bind the function."); + let report = error.report(); + let diagnostic = &report.diagnostics()[0]; + assert_eq!(diagnostic.path, "/operations/draft/serviceFunction"); + assert_eq!(diagnostic.suggested_action, "Bind the function."); + assert_eq!(diagnostic.related.len(), 1); + assert_eq!(diagnostic.related[0].path, "/connections/notices/function"); + } +} diff --git a/crates/registry-rstack-dev/src/bindings.rs b/crates/registry-rstack-dev/src/bindings.rs index 3036a94db2..f59cab6115 100644 --- a/crates/registry-rstack-dev/src/bindings.rs +++ b/crates/registry-rstack-dev/src/bindings.rs @@ -96,8 +96,8 @@ pub(super) struct CoordinatorReviewProducer { /// The completion `destinationId` the producer names in `casework.yaml`. The run binds it to the Coordinator's completion endpoint with a per-run key. #[cfg_attr(feature = "schema", schemars(with = "registry_platform_yaml::LocalId"))] pub(super) completion_destination: String, - /// The exact source guards for binding this producer to the synthetic run issuer. An initiator guard is refused. - pub(super) run_issuer_binding: RunIssuerBinding, + /// The exact source guards for binding this producer to the synthetic run issuer. It has no initiator guard. + pub(super) run_issuer_binding: ProducerIssuerBinding, } /// A BReg review authority that the run connects to Casework. @@ -131,6 +131,15 @@ pub(super) struct RunIssuerBinding { #[serde(default, skip_serializing_if = "Option::is_none")] pub initiator: Option, } +/// The run issuer guards of a binding that rebinds a producer only, never an +/// initiator. +#[derive(Deserialize, Serialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub(super) struct ProducerIssuerBinding { + pub producer: RunProducer, +} + #[derive(Deserialize, Serialize)] #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] #[serde(rename_all = "camelCase", deny_unknown_fields)] @@ -251,6 +260,16 @@ fn validate_coordinator_review_producer( "The Coordinator review producer binding requires the Coordinator and Casework products.", "Add both products to products, or remove bindings.coordinatorReviewProducer.", )?; + // Two machine identities never act as one Casework producer. + plan::require( + plan.bindings + .breg_review_authority + .as_ref() + .is_none_or(|other| other.producer != binding.producer), + &format!("{COORDINATOR_PRODUCER}/producer"), + "The BReg review authority binding already binds this Casework producer.", + "Bind a separate trusted producer for the Coordinator.", + )?; for (member, value) in [ ("connection", &binding.connection), ("producer", &binding.producer), @@ -268,13 +287,8 @@ fn validate_coordinator_review_producer( &binding.identity, Product::Casework, &format!("{COORDINATOR_PRODUCER}/identity"), - )?; - plan::require( - binding.run_issuer_binding.initiator.is_none(), - &format!("{COORDINATOR_PRODUCER}/runIssuerBinding/initiator"), - "The Coordinator review producer binding binds only the producer to the run issuer.", - "Remove initiator: the Coordinator submits its own review requests.", ) + .map(|_| ()) } fn product_position(plan: &Plan, product: Product) -> Option { @@ -3206,32 +3220,20 @@ mod tests { error.contains("/bindings/coordinatorReviewProducer/identity"), "{error}" ); - let error = refused(|plan| { - plan.bindings - .coordinator_review_producer - .as_mut() - .unwrap() - .connection = "Review".to_owned(); - }); - assert!( - error.contains("/bindings/coordinatorReviewProducer/connection"), - "{error}" - ); - let error = refused(|plan| { - plan.bindings - .coordinator_review_producer - .as_mut() - .unwrap() - .run_issuer_binding - .initiator = Some(RunInitiator { - expected_issuer: "https://identity.example.test/people".to_owned(), - trust: RunInitiatorTrust::RunTestPeople, - }); - }); - assert!( - error.contains("/bindings/coordinatorReviewProducer/runIssuerBinding/initiator"), - "{error}" - ); + // The schema has no initiator member for this binding. + let widened = serde_json::from_value::(json!({"coordinatorReviewProducer": { + "connection": "review", "producer": "coordinator", "identity": "coordinator-producer", + "completionDestination": "coordinator-wake", + "runIssuerBinding": { + "producer": { + "expectedIssuer": "https://identity.example.test/producer", + "expectedProfile": "coordinator-producer", + "expectedSubject": "coordinator-producer" + }, + "initiator": {"expectedIssuer": "https://identity.example.test/people", "trust": "run-test-people"} + } + }})); + assert!(widened.is_err()); } #[test] @@ -3372,4 +3374,93 @@ mod tests { assert_eq!(claims["aud"], "urn:dev:casework"); assert_eq!(claims["iss"], input.plan.issuer); } + + #[test] + fn one_casework_producer_is_bound_by_at_most_one_binding() { + let mut value = coordinator_plan(); + value.products.push(ProductPlan { + product: Product::Breg, + project: PathBuf::from("registry"), + audience: "urn:dev:breg".to_owned(), + }); + value.bindings.breg_review_authority = Some(BregReviewAuthority { + id: "casework".to_owned(), + producer: "coordinator".to_owned(), + identity: "coordinator-producer".to_owned(), + run_issuer_binding: None, + }); + let error = value.bindings.validate(&value).unwrap_err().to_string(); + assert!( + error.contains("/bindings/coordinatorReviewProducer/producer"), + "{error}" + ); + } + + #[test] + fn each_start_writes_a_fresh_completion_key_that_nothing_else_carries() { + let read = || { + let root = tempfile::tempdir().unwrap(); + let runtime = RuntimeBindings::prepare( + root.path(), + Arc::new(input(coordinator_plan())), + Arc::new(Issuer::create(root.path()).unwrap()), + &coordinator_origins(), + ) + .unwrap(); + let mut casework = json!({}); + runtime.configure(Product::Casework, &mut casework); + let mut coordinator = json!({"connections": {"review": { + "type": "casework-review-producer", "producer": "coordinator", + "completion": {"recipientBinding": "coordinator-v1", "hmacSha256KeyRef": "secret:file/authored"} + }}}); + runtime.configure(Product::Coordinator, &mut coordinator); + let key = std::fs::read(root.path().join(COORDINATOR_COMPLETION_KEY)).unwrap(); + // Only the key file holds the key: no other run file and no rendered + // configuration carries its bytes in any common encoding. + use base64::Engine as _; + let encodings = [ + key.iter() + .map(|byte| format!("{byte:02x}")) + .collect::(), + base64::engine::general_purpose::STANDARD.encode(&key), + base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(&key), + ]; + for rendered in [casework.to_string(), coordinator.to_string()] { + for encoded in &encodings { + assert!(!rendered.contains(encoded.as_str())); + } + } + for entry in std::fs::read_dir(root.path()).unwrap() { + let path = entry.unwrap().path(); + if path.file_name().unwrap() == COORDINATOR_COMPLETION_KEY || !path.is_file() { + continue; + } + let bytes = std::fs::read(&path).unwrap(); + assert!( + !bytes + .windows(key.len()) + .any(|window| window == key.as_slice()), + "{}", + path.display() + ); + let text = String::from_utf8_lossy(&bytes); + for encoded in &encodings { + assert!(!text.contains(encoded.as_str()), "{}", path.display()); + } + } + key + }; + assert_ne!(read(), read()); + } + + #[test] + fn the_completion_route_matches_the_review_protocol() { + let protocol = include_str!("../../registry-review-protocol/src/lib.rs"); + assert!( + protocol.contains(&format!( + "pub const REVIEW_COMPLETIONS_PATH: &str = \"{REVIEW_COMPLETIONS_PATH}\";" + )), + "the review protocol moved its completion route" + ); + } } diff --git a/crates/registry-rstack-dev/src/lib.rs b/crates/registry-rstack-dev/src/lib.rs index 71167ad06b..925a94fd37 100644 --- a/crates/registry-rstack-dev/src/lib.rs +++ b/crates/registry-rstack-dev/src/lib.rs @@ -2786,6 +2786,12 @@ fn remove_run_dir(root: &Path) -> Result<()> { } _ => {} } + match fs::remove_file(root.join(bindings::COORDINATOR_COMPLETION_KEY)) { + Err(error) if error.kind() != std::io::ErrorKind::NotFound => { + return Err(error).context("cannot remove the run's review completion key"); + } + _ => {} + } fs::rename(root, &doomed).context("cannot remove run scratch files")?; fs::remove_dir_all(&doomed) .with_context(|| format!("cannot remove run scratch files at {}", doomed.display())) @@ -3932,6 +3938,11 @@ mod tests { private_directory(&root).unwrap(); fs::write(root.join(products::FIELD_KEY), "key").unwrap(); fs::write(root.join(products::FUNCTION_HOST_KEY), "host-key").unwrap(); + fs::write( + root.join(bindings::COORDINATOR_COMPLETION_KEY), + "completion-key", + ) + .unwrap(); fs::write(root.join(REPORT), "{}").unwrap(); // A non-empty directory at the removal name makes the rename fail, as // an interrupted deletion would leave the run behind. @@ -3942,6 +3953,7 @@ mod tests { assert!(remove_run_dir(&root).is_err()); assert!(!root.join(products::FIELD_KEY).exists()); assert!(!root.join(products::FUNCTION_HOST_KEY).exists()); + assert!(!root.join(bindings::COORDINATOR_COMPLETION_KEY).exists()); assert!(root.join(REPORT).exists()); } diff --git a/crates/registry-rstack-dev/src/plan.rs b/crates/registry-rstack-dev/src/plan.rs index 9217f33be5..bab5e5aa91 100644 --- a/crates/registry-rstack-dev/src/plan.rs +++ b/crates/registry-rstack-dev/src/plan.rs @@ -1468,7 +1468,7 @@ impl Plan { || self.runs_evidence()) && ((self.application.is_none() && !self.bindings.binds_run_issuer()) || self.issuer == "run"), "/issuer", - "The run issuer requires a preview, an application, an explicitly bound BReg and Casework pair, or Evidence. Applications and run issuer bindings require issuer run.", + "The run issuer requires a preview, an application, an explicitly bound BReg or Coordinator review producer paired with Casework, or Evidence. Applications and run issuer bindings require issuer run.", "Use issuer `run` with a preview, an application, the exact paired runIssuerBinding, or Evidence. Other plans use a configured issuer.", )?; require( diff --git a/crates/registry-rstack-dev/src/products.rs b/crates/registry-rstack-dev/src/products.rs index 54d5724edd..8c80ccfb54 100644 --- a/crates/registry-rstack-dev/src/products.rs +++ b/crates/registry-rstack-dev/src/products.rs @@ -27,7 +27,7 @@ use std::{ }; use super::{ - bindings::{Bindings, RunIssuerBinding, RuntimeBindings}, + bindings::{Bindings, RunInitiator, RunProducer, RuntimeBindings}, browser::BrowserClient, clock, database::{Database, DatabaseUrls}, @@ -1690,7 +1690,7 @@ impl<'a> ProductRunner<'a> { if let Some(casework) = product_root(&self.input.project, &self.input.plan, Product::Casework)? { - checked_coordinator_review_producer(&self.input.plan, &casework.root, project)?; + checked_coordinator_review_runtime(&self.input.plan, &casework.root, &runtime)?; } let mut coordinator = json!({ "apiVersion": config["apiVersion"], @@ -3935,7 +3935,8 @@ struct GuardedProducer<'a> { binding: &'static str, producer: &'a str, identity: &'a str, - guard: &'a RunIssuerBinding, + guard: &'a RunProducer, + initiator: Option<&'a RunInitiator>, } /// Every producer the plan binds to the run issuer. @@ -3947,7 +3948,8 @@ fn guarded_producers(plan: &Plan) -> Vec> { binding: "/bindings/bregReviewAuthority", producer: &binding.producer, identity: &binding.identity, - guard, + guard: &guard.producer, + initiator: guard.initiator.as_ref(), }); } } @@ -3956,7 +3958,8 @@ fn guarded_producers(plan: &Plan) -> Vec> { binding: "/bindings/coordinatorReviewProducer", producer: &binding.producer, identity: &binding.identity, - guard: &binding.run_issuer_binding, + guard: &binding.run_issuer_binding.producer, + initiator: None, }); } producers @@ -3977,7 +3980,7 @@ fn bind_casework_run_issuer(plan: &Plan, project: &Path, bound: &Path) -> Result for bound_producer in guarded_producers(plan) { let entry = &mut document["trustedProducers"][bound_producer.producer]; entry["issuer"] = json!(plan.issuer); - if bound_producer.guard.initiator.is_some() { + if bound_producer.initiator.is_some() { entry["trustedInitiatorIssuer"] = json!(plan.issuer); } } @@ -4012,7 +4015,8 @@ fn checked_casework_run_issuer(plan: &Plan, project: &Path) -> Result { binding, producer: id, identity: alias, - guard, + guard: expected, + initiator, } in producers { let run_issuer_binding = format!("{binding}/runIssuerBinding"); @@ -4031,7 +4035,6 @@ fn checked_casework_run_issuer(plan: &Plan, project: &Path) -> Result { )); } let text = |member: &str| producer[member].as_str().unwrap_or_default(); - let expected = &guard.producer; if text("issuer") != expected.expected_issuer { return Err(refuse( format!("{run_issuer_binding}/producer/expectedIssuer"), @@ -4072,7 +4075,7 @@ fn checked_casework_run_issuer(plan: &Plan, project: &Path) -> Result { "Assign a role whose Casework profile supplies the required scope.", )); } - if let Some(initiator) = &guard.initiator { + if let Some(initiator) = initiator { if producer["trustedInitiatorIssuer"].as_str() != Some(initiator.expected_issuer.as_str()) { @@ -4098,11 +4101,17 @@ fn checked_coordinator_review_producer( casework: &Path, coordinator: &Path, ) -> Result<()> { + let runtime = authored_document(&coordinator.join("runtime.yaml"))?; + checked_coordinator_review_runtime(plan, casework, &runtime) +} + +/// The same check over a Coordinator runtime document already read, so +/// `start` checks exactly the document it renders. +fn checked_coordinator_review_runtime(plan: &Plan, casework: &Path, runtime: &Value) -> Result<()> { const BINDING: &str = "/bindings/coordinatorReviewProducer"; let refuse = |pointer: String, message: &str, action: &str| { anyhow::Error::from(plan::SemanticRefusal::new(&pointer, message, action)) }; - let runtime = authored_document(&coordinator.join("runtime.yaml"))?; let Some(binding) = &plan.bindings.coordinator_review_producer else { let producers = runtime["connections"] .as_object() @@ -4125,6 +4134,20 @@ fn checked_coordinator_review_producer( } return Ok(()); }; + let unbound = runtime["connections"] + .as_object() + .is_some_and(|connections| { + connections.iter().any(|(name, connection)| { + name != &binding.connection && connection["type"] == "casework-review-producer" + }) + }); + if unbound { + return Err(refuse( + format!("{BINDING}/connection"), + "Another Coordinator casework-review-producer connection has no binding, so Casework would not trust it in this run.", + "Keep one casework-review-producer connection, the one this binding names.", + )); + } let connection = &runtime["connections"][&binding.connection]; if connection["type"] != "casework-review-producer" { return Err(refuse( @@ -4588,11 +4611,14 @@ mod tests { #[test] fn a_coordinator_review_producer_refuses_each_mismatch_at_its_pointer() { type Break = fn(&mut Value, &mut Value, &mut Value); + // Each case names its pointer and a fragment of its own refusal, so + // two refusals at one pointer cannot stand in for each other. const BINDING: &str = "/bindings/coordinatorReviewProducer"; - let cases: [(&str, String, Break); 12] = [ + let cases: [(&str, String, &str, Break); 13] = [ ( "the producer issuer differs from the binding", format!("{BINDING}/runIssuerBinding/producer/expectedIssuer"), + "issuer in casework.yaml", |_, casework, _| { casework["trustedProducers"]["coordinator"]["issuer"] = json!("https://elsewhere.example.invalid/") @@ -4601,6 +4627,7 @@ mod tests { ( "casework.yaml profile differs from the binding", format!("{BINDING}/runIssuerBinding/producer/expectedProfile"), + "profile in casework.yaml", |_, casework, _| { casework["trustedProducers"]["coordinator"]["profile"] = json!("other-profile") }, @@ -4608,11 +4635,13 @@ mod tests { ( "the identity subject differs from the binding", format!("{BINDING}/runIssuerBinding/producer/expectedSubject"), + "subject in casework.yaml", |plan, _, _| plan["people"]["coordinator"]["subject"] = json!("someone-else"), ), ( "the producer is not in casework.yaml", format!("{BINDING}/producer"), + "no trusted producer", |_, casework, _| { casework["trustedProducers"] .as_object_mut() @@ -4623,6 +4652,7 @@ mod tests { ( "the connection is missing", format!("{BINDING}/connection"), + "no casework-review-producer connection", |_, _, coordinator| { coordinator["connections"] .as_object_mut() @@ -4633,11 +4663,13 @@ mod tests { ( "the connection is of another type", format!("{BINDING}/connection"), + "no casework-review-producer connection", |_, _, coordinator| coordinator["connections"]["review"]["type"] = json!("breg"), ), ( "the connection names another producer", format!("{BINDING}/producer"), + "names another Casework producer", |_, _, coordinator| { coordinator["connections"]["review"]["producer"] = json!("other-producer") }, @@ -4645,6 +4677,7 @@ mod tests { ( "the connection profile differs from the grant", format!("{BINDING}/connection"), + "profile is not the identity", |_, _, coordinator| { coordinator["connections"]["review"]["profile"] = json!("other-profile") }, @@ -4652,6 +4685,7 @@ mod tests { ( "the producer has no completion destination", format!("{BINDING}/completionDestination"), + "completion destination in casework.yaml", |_, casework, _| { casework["trustedProducers"]["coordinator"] .as_object_mut() @@ -4662,6 +4696,7 @@ mod tests { ( "the completion destination differs", format!("{BINDING}/completionDestination"), + "completion destination in casework.yaml", |_, casework, _| { casework["trustedProducers"]["coordinator"]["completion"]["destinationId"] = json!("elsewhere") @@ -4670,6 +4705,7 @@ mod tests { ( "the recipient binding differs", format!("{BINDING}/connection"), + "recipientBinding is not", |_, _, coordinator| { coordinator["connections"]["review"]["completion"]["recipientBinding"] = json!("other-v1") @@ -4678,6 +4714,7 @@ mod tests { ( "the connection has no completion key", format!("{BINDING}/connection"), + "has no completion", |_, _, coordinator| { coordinator["connections"]["review"] .as_object_mut() @@ -4685,9 +4722,18 @@ mod tests { .remove("completion"); }, ), + ( + "a second casework-review-producer connection is unbound", + format!("{BINDING}/connection"), + "Another Coordinator", + |_, _, coordinator| { + let second = coordinator["connections"]["review"].clone(); + coordinator["connections"]["second-review"] = second; + }, + ), ]; let root = tempfile::tempdir().unwrap(); - for (index, (name, pointer, break_it)) in cases.into_iter().enumerate() { + for (index, (name, pointer, fragment, break_it)) in cases.into_iter().enumerate() { let (mut plan, mut casework, mut coordinator) = coordinator_producer_fixture(); break_it(&mut plan, &mut casework, &mut coordinator); let case_root = root.path().join(index.to_string()); @@ -4703,7 +4749,8 @@ mod tests { assert!( refusal .to_string() - .starts_with(&format!("dev.yaml {pointer}: ")), + .starts_with(&format!("dev.yaml {pointer}: ")) + && refusal.to_string().contains(fragment), "{name}: {refusal}" ); } @@ -4734,21 +4781,62 @@ mod tests { fn a_bound_coordinator_producer_trusts_only_the_run_issuer_for_that_producer() { let root = tempfile::tempdir().unwrap(); let (plan, casework, coordinator) = coordinator_producer_fixture(); - let (project, coordinator) = + let (project, coordinator_project) = coordinator_producer_projects(root.path(), &casework, &coordinator); let plan: Plan = serde_json::from_value(plan).unwrap(); - checked_coordinator_review_producer(&plan, &project, &coordinator).unwrap(); + checked_coordinator_review_producer(&plan, &project, &coordinator_project).unwrap(); assert!(has_run_source(&plan)); let bound = root.path().join("bound"); bind_casework_run_issuer(&plan, &project, &bound).unwrap(); + // Only the bound producer's issuer changes; every other member of the + // document stays exactly as written. + let mut expected = casework.clone(); + expected["trustedProducers"]["coordinator"]["issuer"] = json!(plan.issuer); let document = authored_document(&bound.join("casework.yaml")).unwrap(); + assert_eq!(document, expected); + } + + #[test] + fn both_bound_producers_are_checked_and_rebound() { + let (breg_plan, breg_casework) = run_issuer_fixture(false); + let (mut plan, mut casework, _) = coordinator_producer_fixture(); + plan["products"] + .as_array_mut() + .unwrap() + .push(json!({"product": "breg", "project": "breg", "audience": "registry"})); + plan["people"]["authority"] = breg_plan["people"]["authority"].clone(); + plan["bindings"]["bregReviewAuthority"] = + breg_plan["bindings"]["bregReviewAuthority"].clone(); + casework["accessProfiles"]["review-producer"] = + breg_casework["accessProfiles"]["review-producer"].clone(); + casework["trustedProducers"]["producer"] = + breg_casework["trustedProducers"]["producer"].clone(); + let root = tempfile::tempdir().unwrap(); + let project = write_casework_project(root.path(), &casework); + let checked: Plan = serde_json::from_value(plan.clone()).unwrap(); + let bound = root.path().join("bound"); + bind_casework_run_issuer(&checked, &project, &bound).unwrap(); + let mut expected = casework.clone(); + expected["trustedProducers"]["producer"]["issuer"] = json!(checked.issuer); + expected["trustedProducers"]["coordinator"]["issuer"] = json!(checked.issuer); assert_eq!( - document["trustedProducers"]["coordinator"]["issuer"], - plan.issuer + authored_document(&bound.join("casework.yaml")).unwrap(), + expected ); - assert_eq!( - document["trustedProducers"]["other-producer"]["issuer"], - "https://other.example.invalid/" + + // The second producer's guards are checked as well as the first's. + let mut broken = casework.clone(); + broken["trustedProducers"]["coordinator"]["issuer"] = + json!("https://elsewhere.example.invalid/"); + let other = root.path().join("broken"); + fs::create_dir(&other).unwrap(); + let project = write_casework_project(&other, &broken); + let error = checked_casework_run_issuer(&checked, &project).unwrap_err(); + assert!( + error.to_string().contains( + "/bindings/coordinatorReviewProducer/runIssuerBinding/producer/expectedIssuer" + ), + "{error}" ); } diff --git a/docs/site/src/content/docs/configure/run-a-project-with-rstack-dev.mdx b/docs/site/src/content/docs/configure/run-a-project-with-rstack-dev.mdx index 53a06ca3e6..2e5c98a934 100644 --- a/docs/site/src/content/docs/configure/run-a-project-with-rstack-dev.mdx +++ b/docs/site/src/content/docs/configure/run-a-project-with-rstack-dev.mdx @@ -74,8 +74,8 @@ owner-only host key for the run, which the Coordinator presents as its bearer. T listener then hands the function a fixed placeholder bearer instead of the key, so the key never leaves the listener and no product accepts what the function receives. Only the generated server binding hides the caller's headers from the handler. A function -that does not export that binding can read the raw request, which runs at the same trust -level as the function listener itself. +runs inside the function listener's process, at its trust level, so a function that does not +export the generated binding reads the raw request, which by then carries the placeholder. The same function stays callable from the page through the gateway, with the page actor's authority, so write a Coordinator-bound function for both callers. One run key admits the gateway and the Coordinator to every preview function, not only the @@ -1051,12 +1051,16 @@ bindings: - the Coordinator `runtime.yaml` must name `connection` with type `casework-review-producer`, the same `producer`, the identity's Casework grant profile, and a `completion`; - `casework.yaml` must trust `producer` with exactly the expected issuer, profile and subject, - and the identity's subject, profile and scopes must match; + the identity's subject and profile must match, and its Casework grant must include the + profile's required scopes; - the producer's `completion` must name `completionDestination` and the connection's `recipientBinding`. -An `initiator` guard is refused. The binding creates no producer, person, profile, client, -scope or grant. +An `initiator` guard is refused, as is a producer the BReg review authority binding already +binds and a second `casework-review-producer` connection. The binding creates no producer, +person, profile, client, scope or grant: it registers the existing test person's `client` on +the run-local token endpoint with a per-run key. Like the BReg binding, the producer token carries +the identity's whole Casework grant, which may include scopes beyond the required ones. `start` writes the run issuer into that one producer in a private copy of the Casework project, as the BReg binding does. It gives the Coordinator connection the Casework origin, the identity's Casework profile and a machine client on the run-local token endpoint, so its diff --git a/docs/site/src/content/docs/security/casework.mdx b/docs/site/src/content/docs/security/casework.mdx index 22ec3378a0..812aa5c5b7 100644 --- a/docs/site/src/content/docs/security/casework.mdx +++ b/docs/site/src/content/docs/security/casework.mdx @@ -145,6 +145,9 @@ grants in [Registry Casework task grants](../../reference/casework-task-grants/) alongside the `casework` header file. Casework applies its usual client, profile, and human-identity checks ([run isolation](../../configure/run-a-project-with-rstack-dev/#run-isolation)). + A development binding may rewrite one named trusted producer's issuer to the run issuer, in a + private copy of the project and only when its pinned issuer, profile and subject match exact + guards. The source project and production Casework are unchanged. {/* Evidence: crates/registry-cli-api/README.md, Security boundary. */} - Separate credentials for the same human: every current-source provider binding requires `humanSourceAuthentication.audience`, distinct from every Casework issuer entry's audience, and diff --git a/docs/site/src/content/docs/security/coordinator.mdx b/docs/site/src/content/docs/security/coordinator.mdx index ce2eef1109..6c24b454a9 100644 --- a/docs/site/src/content/docs/security/coordinator.mdx +++ b/docs/site/src/content/docs/security/coordinator.mdx @@ -892,6 +892,8 @@ Enforcement: or a `hostKeyRef` key only the function host accepts. `rstack dev` generates a per-run host key for the preview function host, and that host hands a Coordinator-called function a fixed placeholder bearer, never the key. + It also generates a separate per-run review completion key, shared only by the run's Casework + completion hook and Coordinator connection, and removes both keys first when the run stops. - The credential is distinct from every credential and product audience the runtime file declares. The runtime refuses a function `resource` equal to a product or external connection's `resource`, a task authority `bootstrapResource` or `exchangeAudience`, or the Coordinator's own diff --git a/products/platform/config-formats.yaml b/products/platform/config-formats.yaml index 220cb2b651..fe4fa581f3 100644 --- a/products/platform/config-formats.yaml +++ b/products/platform/config-formats.yaml @@ -896,6 +896,8 @@ formats: whenOmitted: closed - pointer: /bindings/coordinatorReviewProducer/runIssuerBinding whenOmitted: refused + - pointer: /bindings/coordinatorReviewProducer/runIssuerBinding/producer + whenOmitted: refused - pointer: /bindings/coordinatorReviewProducer/completionDestination whenOmitted: refused - pointer: /preview diff --git a/products/platform/generated/dev/dev.v1alpha1.schema.json b/products/platform/generated/dev/dev.v1alpha1.schema.json index a13f8fafb8..fc0147ab16 100644 --- a/products/platform/generated/dev/dev.v1alpha1.schema.json +++ b/products/platform/generated/dev/dev.v1alpha1.schema.json @@ -364,8 +364,8 @@ "description": "The Casework trusted producer in `casework.yaml`. It must be the producer the connection names." }, "runIssuerBinding": { - "$ref": "#/$defs/RunIssuerBinding", - "description": "The exact source guards for binding this producer to the synthetic run issuer. An initiator guard is refused." + "$ref": "#/$defs/ProducerIssuerBinding", + "description": "The exact source guards for binding this producer to the synthetic run issuer. It has no initiator guard." } }, "required": [ @@ -517,6 +517,19 @@ ], "type": "object" }, + "ProducerIssuerBinding": { + "additionalProperties": false, + "description": "The run issuer guards of a binding that rebinds a producer only, never an\ninitiator.", + "properties": { + "producer": { + "$ref": "#/$defs/RunProducer" + } + }, + "required": [ + "producer" + ], + "type": "object" + }, "Product": { "description": "A product the development run can start.", "enum": [ From 2ade6e4ebba23958d29bcf959ba38c237d9bb53e Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 22:04:37 +0000 Subject: [PATCH 138/183] feat(dev): give one Coordinator BReg connection a development identity bindings.coordinatorBregClient registers one test person's client on the run-local token endpoint for one Coordinator breg connection. The person's BReg grant is the only source of the connection's profile and scopes, the authored authorization is replaced whole, and BReg's own access profile and Action rules decide every call. check refuses a connection that is not breg, delegates to task authority or names another profile, and every Coordinator binding is refused outside the development posture. Refs #2891 Signed-off-by: Jeremi Joslin --- crates/registry-rstack-dev/src/bindings.rs | 322 ++++++++++++++++++ crates/registry-rstack-dev/src/products.rs | 123 +++++++ .../run-a-project-with-rstack-dev.mdx | 28 ++ products/platform/config-formats.yaml | 2 + .../generated/dev/dev.v1alpha1.schema.json | 23 ++ 5 files changed, 498 insertions(+) diff --git a/crates/registry-rstack-dev/src/bindings.rs b/crates/registry-rstack-dev/src/bindings.rs index f59cab6115..3a2ab35806 100644 --- a/crates/registry-rstack-dev/src/bindings.rs +++ b/crates/registry-rstack-dev/src/bindings.rs @@ -74,6 +74,24 @@ pub(super) struct Bindings { /// Connects the Coordinator to Casework as one trusted review producer. The Coordinator authenticates to Casework as a machine identity, and Casework wakes its waiting run through a completion hook. Development runs only. #[serde(default, skip_serializing_if = "Option::is_none")] pub(super) coordinator_review_producer: Option, + /// Gives one Coordinator BReg connection a machine identity on the run's token endpoint, with exactly one test person's BReg grant. BReg's own access profile and Action rules decide every call. Development runs only. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub(super) coordinator_breg_client: Option, +} + +/// One Coordinator `breg` connection the run authenticates as one test +/// person. The person's BReg grant is the only source of the connection's +/// profile and scopes; nothing in dev.yaml adds to them. +#[derive(Deserialize, Serialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub(super) struct CoordinatorBregClient { + /// The Coordinator `runtime.yaml` connection of type `breg`, without task authority. + #[cfg_attr(feature = "schema", schemars(with = "registry_platform_yaml::LocalId"))] + pub(super) connection: String, + /// Name of the test person, in `people`, whose BReg grant the Coordinator uses. + #[cfg_attr(feature = "schema", schemars(with = "registry_platform_yaml::LocalId"))] + pub(super) identity: String, } /// The Coordinator's Casework review producer connection that the run binds @@ -192,6 +210,9 @@ impl Bindings { if let Some(binding) = &self.coordinator_review_producer { validate_coordinator_review_producer(plan, binding)?; } + if let Some(binding) = &self.coordinator_breg_client { + validate_coordinator_breg_client(plan, binding)?; + } if self.breg_review_authority.is_none() && self.casework_context_provider.is_none() { return Ok(()); } @@ -247,6 +268,49 @@ impl Bindings { } } +/// The Coordinator bindings exist only in development: any other declared +/// posture refuses them before a machine identity is created. +pub(super) fn development_only( + declaration: std::result::Result< + registry_platform_config::DeclaredPosture, + registry_platform_config::PostureError, + >, +) -> Result<()> { + super::require_development(declaration).map_err(|(code, message, action)| { + anyhow::anyhow!( + "{code}: {message}. The Coordinator bindings are development only. {action}" + ) + }) +} + +const COORDINATOR_BREG_CLIENT: &str = "/bindings/coordinatorBregClient"; + +fn validate_coordinator_breg_client( + plan: &Plan, + binding: &CoordinatorBregClient, +) -> plan::SemanticResult<()> { + plan::require( + product_position(plan, Product::Coordinator).is_some() + && product_position(plan, Product::Breg).is_some(), + "/bindings", + "The Coordinator BReg client binding requires the Coordinator and BReg products.", + "Add both products to products, or remove bindings.coordinatorBregClient.", + )?; + plan::require( + plan::identifier(&binding.connection), + &format!("{COORDINATOR_BREG_CLIENT}/connection"), + "The value must be a local identifier.", + "Set it to a lowercase local identifier of at most 64 characters.", + )?; + require_machine_person( + plan, + &binding.identity, + Product::Breg, + &format!("{COORDINATOR_BREG_CLIENT}/identity"), + ) + .map(|_| ()) +} + const COORDINATOR_PRODUCER: &str = "/bindings/coordinatorReviewProducer"; fn validate_coordinator_review_producer( @@ -500,6 +564,7 @@ struct TokenServer { const BREG_REVIEW_CLIENT: &str = "breg-review-client"; const COORDINATOR_REVIEW_CLIENT: &str = "coordinator-review-client"; +const COORDINATOR_BREG_CLIENT_FILE: &str = "coordinator-breg-client"; /// The run file holding the HMAC key Casework signs a Coordinator review /// completion with and the Coordinator verifies it with. pub(super) const COORDINATOR_COMPLETION_KEY: &str = "coordinator-review-completion-key"; @@ -529,10 +594,22 @@ impl RuntimeBindings { if bindings.breg_review_authority.is_none() && bindings.casework_context_provider.is_none() && bindings.coordinator_review_producer.is_none() + && bindings.coordinator_breg_client.is_none() { return Ok(Self::default()); } bindings.validate(&input.plan)?; + if bindings.coordinator_review_producer.is_some() + || bindings.coordinator_breg_client.is_some() + { + development_only(registry_platform_config::declared(None))?; + } + ensure!( + bindings.coordinator_breg_client.is_none() + || (origins.contains_key(&Product::Coordinator) + && origins.contains_key(&Product::Breg)), + "the Coordinator BReg client binding requires reserved Coordinator and BReg origins" + ); ensure!( (bindings.breg_review_authority.is_none() && bindings.casework_context_provider.is_none()) @@ -584,6 +661,16 @@ impl RuntimeBindings { .map_err(|_| anyhow::anyhow!("cannot generate the review completion key"))?; write_private(&root.join(COORDINATOR_COMPLETION_KEY), key.as_ref())?; } + if let Some(binding) = &bindings.coordinator_breg_client { + prepare_binding( + root, + &input, + &binding.identity, + Product::Breg, + COORDINATOR_BREG_CLIENT_FILE, + &mut clients, + )?; + } let server = start_token_server(input.clone(), issuer.clone(), clients)?; Ok(Self { server: Some(server), @@ -673,6 +760,32 @@ fn render( }); } Product::Coordinator => { + if let Some(binding) = plan.bindings.coordinator_breg_client.as_ref() { + if let Some(connection) = config["connections"] + .get_mut(binding.connection.as_str()) + .and_then(Value::as_object_mut) + { + // The grant alone supplies the profile and scopes, and the + // authorization is replaced whole, so no authored member + // such as task authority survives. + let person = &plan.people[&binding.identity]; + let grant = &person.grants[&Product::Breg]; + let (_, signing_key_ref) = client_refs(COORDINATOR_BREG_CLIENT_FILE); + connection.insert("baseUrl".into(), json!(origins[&Product::Breg])); + connection.insert("profile".into(), json!(grant.profile)); + connection.insert( + "authorization".into(), + json!({ + "tokenEndpoint": token_endpoint, + "clientAssertionAudience": issuer, + "clientId": person.client, + "signingKeyRef": signing_key_ref, + "resource": plan.product(Product::Breg).audience, + "scopes": grant.scopes, + }), + ); + } + } let Some(binding) = plan.bindings.coordinator_review_producer.as_ref() else { return; }; @@ -1679,6 +1792,7 @@ mod tests { action: "reviewed-change".to_owned(), }), coordinator_review_producer: None, + coordinator_breg_client: None, }, journey_file: PathBuf::from("dev-journeys.yaml"), schema_test_people: BTreeMap::new(), @@ -3463,4 +3577,212 @@ mod tests { "the review protocol moved its completion route" ); } + + /// BReg and the Coordinator, with the Coordinator's `registry` BReg + /// connection bound to the `coordinator-service` test person. + fn coordinator_breg_plan() -> Plan { + let mut value = plan(); + value.products = vec![ + ProductPlan { + product: Product::Breg, + project: PathBuf::from("registry"), + audience: "urn:dev:breg".to_owned(), + }, + ProductPlan { + product: Product::Coordinator, + project: PathBuf::from("coordinator"), + audience: "urn:dev:coordinator".to_owned(), + }, + ]; + value.people = BTreeMap::from([( + "coordinator-service".to_owned(), + TestPerson { + subject: "coordinator-service".to_owned(), + display_name: None, + client: "coordinator-breg-client".to_owned(), + grants: BTreeMap::from([( + Product::Breg, + grant("permit-coordinator", "registry:actions:invoke"), + )]), + }, + )]); + value.bindings = serde_json::from_value(json!({"coordinatorBregClient": { + "connection": "registry", "identity": "coordinator-service" + }})) + .unwrap(); + value + } + + fn coordinator_breg_origins() -> BTreeMap { + BTreeMap::from([ + (Product::Breg, "http://127.0.0.1:31001".to_owned()), + (Product::Coordinator, "http://127.0.0.1:31003".to_owned()), + ]) + } + + #[test] + fn a_coordinator_breg_client_needs_its_products_and_a_breg_identity() { + let value = coordinator_breg_plan(); + value.bindings.validate(&value).unwrap(); + let refused = |change: fn(&mut Plan)| { + let mut value = coordinator_breg_plan(); + change(&mut value); + value.bindings.validate(&value).unwrap_err().to_string() + }; + let error = refused(|plan| plan.products.retain(|entry| entry.product != Product::Breg)); + assert!(error.contains("/bindings"), "{error}"); + let error = refused(|plan| { + plan.people + .get_mut("coordinator-service") + .unwrap() + .grants + .clear(); + }); + assert!( + error.contains("/bindings/coordinatorBregClient/identity"), + "{error}" + ); + let error = refused(|plan| { + plan.bindings + .coordinator_breg_client + .as_mut() + .unwrap() + .connection = "Registry".to_owned(); + }); + assert!( + error.contains("/bindings/coordinatorBregClient/connection"), + "{error}" + ); + // dev.yaml has no member that adds a profile or scope. + let widened = serde_json::from_value::(json!({"coordinatorBregClient": { + "connection": "registry", "identity": "coordinator-service", + "scopes": ["registry:records:write"] + }})); + assert!(widened.is_err()); + } + + #[test] + fn the_coordinator_breg_client_takes_profile_and_scopes_from_the_grant_only() { + let root = tempfile::tempdir().unwrap(); + let run = Arc::new(input(coordinator_breg_plan())); + let issuer = Arc::new(Issuer::create(root.path()).unwrap()); + let runtime = RuntimeBindings::prepare( + root.path(), + run.clone(), + issuer, + &coordinator_breg_origins(), + ) + .unwrap(); + let endpoint = runtime.server.as_ref().unwrap().endpoint.clone(); + let mut coordinator = json!({"connections": { + "registry": { + "type": "breg", "baseUrl": "http://127.0.0.1:1", "profile": "authored-profile", + "authorization": {"tokenEndpoint": "http://127.0.0.1:1/token", "clientId": "authored", + "scopes": ["registry:records:write"], "resource": "urn:elsewhere"} + }, + "notices": {"type": "messaging", "baseUrl": "http://127.0.0.1:2"} + }}); + runtime.configure(Product::Coordinator, &mut coordinator); + assert_eq!( + coordinator["connections"]["registry"], + json!({ + "type": "breg", "baseUrl": "http://127.0.0.1:31001", + "profile": "permit-coordinator", + "authorization": { + "tokenEndpoint": endpoint, + "clientAssertionAudience": run.plan.issuer, + "clientId": "coordinator-breg-client", + "signingKeyRef": "secret:file/coordinator-breg-client-key", + "resource": "urn:dev:breg", + "scopes": ["registry:actions:invoke"] + } + }) + ); + assert_eq!( + coordinator["connections"]["notices"], + json!({"type": "messaging", "baseUrl": "http://127.0.0.1:2"}) + ); + } + + #[test] + fn the_coordinator_obtains_a_breg_token_for_its_bound_identity() { + use base64::Engine as _; + let root = tempfile::tempdir().unwrap(); + let run = Arc::new(input(coordinator_breg_plan())); + let issuer = Arc::new(Issuer::create(root.path()).unwrap()); + let runtime = RuntimeBindings::prepare( + root.path(), + run.clone(), + issuer, + &coordinator_breg_origins(), + ) + .unwrap(); + let mut coordinator = json!({"connections": {"registry": {"type": "breg"}}}); + runtime.configure(Product::Coordinator, &mut coordinator); + let authorization = &coordinator["connections"]["registry"]["authorization"]; + let encoded = + Zeroizing::new(std::fs::read(root.path().join("coordinator-breg-client-key")).unwrap()); + let key = PrivateJwk::parse(std::str::from_utf8(&encoded).unwrap()).unwrap(); + let provider = PrivateKeyJwt::new( + PrivateKeyJwtConfig::new( + authorization["tokenEndpoint"] + .as_str() + .unwrap() + .parse() + .unwrap(), + authorization["clientId"].as_str().unwrap(), + key, + ) + .with_audience(authorization["clientAssertionAudience"].as_str().unwrap()) + .with_resource(authorization["resource"].as_str().unwrap()) + .with_scopes(vec!["registry:actions:invoke".to_owned()]), + ) + .unwrap(); + let runtime_tokens = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .unwrap(); + let token = runtime_tokens + .block_on(provider.bearer_token()) + .expect("the Coordinator obtains a BReg token"); + let header = token.authorization_header_value(); + let compact = header.to_str().unwrap().trim_start_matches("Bearer "); + let claims: Value = serde_json::from_slice( + &base64::engine::general_purpose::URL_SAFE_NO_PAD + .decode(compact.split('.').nth(1).unwrap()) + .unwrap(), + ) + .unwrap(); + assert_eq!(claims["sub"], "coordinator-service"); + assert_eq!(claims["aud"], "urn:dev:breg"); + // A scope the grant does not hold is refused. + let encoded = + Zeroizing::new(std::fs::read(root.path().join("coordinator-breg-client-key")).unwrap()); + let key = PrivateJwk::parse(std::str::from_utf8(&encoded).unwrap()).unwrap(); + let wider = PrivateKeyJwt::new( + PrivateKeyJwtConfig::new( + authorization["tokenEndpoint"] + .as_str() + .unwrap() + .parse() + .unwrap(), + authorization["clientId"].as_str().unwrap(), + key, + ) + .with_audience(authorization["clientAssertionAudience"].as_str().unwrap()) + .with_resource(authorization["resource"].as_str().unwrap()) + .with_scopes(vec!["registry:records:write".to_owned()]), + ) + .unwrap(); + assert!(runtime_tokens.block_on(wider.bearer_token()).is_err()); + } + + #[test] + fn coordinator_bindings_are_refused_outside_development() { + use registry_platform_config::declared_from; + use std::ffi::OsStr; + assert!(development_only(declared_from(None, None)).is_ok()); + assert!(development_only(declared_from(None, Some(OsStr::new("development")))).is_ok()); + assert!(development_only(declared_from(None, Some(OsStr::new("production")))).is_err()); + } } diff --git a/crates/registry-rstack-dev/src/products.rs b/crates/registry-rstack-dev/src/products.rs index 8c80ccfb54..5814edc476 100644 --- a/crates/registry-rstack-dev/src/products.rs +++ b/crates/registry-rstack-dev/src/products.rs @@ -1692,6 +1692,7 @@ impl<'a> ProductRunner<'a> { { checked_coordinator_review_runtime(&self.input.plan, &casework.root, &runtime)?; } + checked_coordinator_breg_runtime(&self.input.plan, &runtime)?; let mut coordinator = json!({ "apiVersion": config["apiVersion"], "kind": "CoordinatorRuntimeConfig", @@ -2839,6 +2840,9 @@ pub(super) fn inspect_with( let breg_authority = breg_authority(root, plan, terminate, &tool)?; let casework_principals = casework_principals(root, plan, breg_authority.as_ref(), terminate, &tool)?; + if let Some(coordinator) = product_root(root, plan, Product::Coordinator)? { + checked_coordinator_breg_client(plan, &coordinator.root)?; + } Ok(ProductInspection { breg_authority, casework_principals, @@ -4197,6 +4201,53 @@ fn checked_coordinator_review_runtime(plan: &Plan, casework: &Path, runtime: &Va Ok(()) } +/// Refuses, at the dev.yaml pointer, a Coordinator BReg client binding whose +/// connection is not a `breg` connection without task authority, using the +/// identity's BReg grant profile. `check` runs this before any product starts +/// and `start` again before rendering the Coordinator. +fn checked_coordinator_breg_client(plan: &Plan, coordinator: &Path) -> Result<()> { + if plan.bindings.coordinator_breg_client.is_none() { + return Ok(()); + } + let runtime = authored_document(&coordinator.join("runtime.yaml"))?; + checked_coordinator_breg_runtime(plan, &runtime) +} + +/// The same check over a Coordinator runtime document already read, so +/// `start` checks exactly the document it renders. +fn checked_coordinator_breg_runtime(plan: &Plan, runtime: &Value) -> Result<()> { + const CONNECTION: &str = "/bindings/coordinatorBregClient/connection"; + let Some(binding) = &plan.bindings.coordinator_breg_client else { + return Ok(()); + }; + let refuse = |message: &str, action: &str| { + Err(anyhow::Error::from(plan::SemanticRefusal::new( + CONNECTION, message, action, + ))) + }; + let connection = &runtime["connections"][&binding.connection]; + if connection["type"] != "breg" { + return refuse( + "The Coordinator runtime.yaml has no breg connection with this name.", + "Set connection to the Coordinator connection that invokes BReg Actions.", + ); + } + if !connection["authorization"]["taskAuthority"].is_null() { + return refuse( + "The connection delegates to task authority, which this binding never supplies.", + "Remove taskAuthority from the bound connection.", + ); + } + let grant = &plan.people[&binding.identity].grants[&Product::Breg]; + if connection["profile"].as_str() != Some(grant.profile.as_str()) { + return refuse( + "The connection's profile is not the identity's BReg grant profile.", + "Set the connection's profile to the identity's BReg grant profile.", + ); + } + Ok(()) +} + /// Only a reserved loopback run URL is bound, never a remote issuer. pub(super) fn is_loopback_run_issuer(issuer: &str) -> bool { issuer @@ -4544,6 +4595,7 @@ mod tests { action: "review-action".to_owned(), }), coordinator_review_producer: None, + coordinator_breg_client: None, } } @@ -4840,6 +4892,77 @@ mod tests { ); } + #[test] + fn a_coordinator_breg_client_refuses_each_mismatch_at_its_connection() { + const CONNECTION: &str = "/bindings/coordinatorBregClient/connection"; + let plan: Plan = serde_json::from_value(json!({ + "issuer": "http://127.0.0.1:41000/", + "products": [ + {"product": "breg", "project": "breg", "audience": "registry"}, + {"product": "coordinator", "project": "coordinator", "audience": "urn:coordinator"} + ], + "people": {"coordinator": { + "subject": "coordinator-service", "client": "coordinator-client", + "grants": {"breg": {"profile": "permit-coordinator", "scopes": ["registry:actions:invoke"]}} + }}, + "journeyFile": "dev-journeys.yaml", + "bindings": {"coordinatorBregClient": {"connection": "registry", "identity": "coordinator"}} + })) + .unwrap(); + let connection = json!({ + "type": "breg", "baseUrl": "http://127.0.0.1:1", "profile": "permit-coordinator" + }); + type Break = fn(&mut Value); + let cases: [(&str, Break); 4] = [ + ("the connection is missing", |runtime| { + runtime["connections"] + .as_object_mut() + .unwrap() + .remove("registry"); + }), + ("the connection is of another type", |runtime| { + runtime["connections"]["registry"]["type"] = json!("messaging"); + }), + ("the connection names another profile", |runtime| { + runtime["connections"]["registry"]["profile"] = json!("permit-reader"); + }), + ("the connection delegates to task authority", |runtime| { + runtime["connections"]["registry"]["authorization"] = + json!({"taskAuthority": {"issuer": "https://casework.example"}}); + }), + ]; + let root = tempfile::tempdir().unwrap(); + for (index, (name, break_it)) in cases.into_iter().enumerate() { + let mut runtime = json!({"connections": {"registry": connection.clone()}}); + break_it(&mut runtime); + let project = root.path().join(index.to_string()); + fs::create_dir(&project).unwrap(); + fs::write( + project.join("runtime.yaml"), + serde_norway::to_string(&runtime).unwrap(), + ) + .unwrap(); + let error = checked_coordinator_breg_client(&plan, &project).unwrap_err(); + let refusal = error + .downcast_ref::() + .unwrap_or_else(|| panic!("{name}: not a semantic refusal: {error}")); + assert!( + refusal + .to_string() + .starts_with(&format!("dev.yaml {CONNECTION}: ")), + "{name}: {refusal}" + ); + } + let project = root.path().join("accepted"); + fs::create_dir(&project).unwrap(); + fs::write( + project.join("runtime.yaml"), + serde_norway::to_string(&json!({"connections": {"registry": connection}})).unwrap(), + ) + .unwrap(); + checked_coordinator_breg_client(&plan, &project).unwrap(); + } + #[test] fn breg_binding_ids_are_resolved_with_typed_value_free_refusals() { let bindings = product_bindings(); diff --git a/docs/site/src/content/docs/configure/run-a-project-with-rstack-dev.mdx b/docs/site/src/content/docs/configure/run-a-project-with-rstack-dev.mdx index 2e5c98a934..7c78522d57 100644 --- a/docs/site/src/content/docs/configure/run-a-project-with-rstack-dev.mdx +++ b/docs/site/src/content/docs/configure/run-a-project-with-rstack-dev.mdx @@ -1077,6 +1077,34 @@ each start. Let a waiting Coordinator run finish, or start with `--clean`, befor a_coordinator_review_producer_refuses_each_mismatch_at_its_pointer, a_coordinator_casework_producer_without_its_binding_is_refused. */} +### Give the Coordinator a BReg identity + +A development plan with the Coordinator and BReg may give one Coordinator `breg` connection +a machine identity on the run-local token endpoint: + +```yaml +bindings: + coordinatorBregClient: + connection: registry + identity: coordinator-service +``` + +The identity's BReg grant is the only source of the connection's profile and scopes. +`start` replaces the connection's `baseUrl` with the run's BReg origin and its whole +`authorization` with the run-local client, so no authored scope, resource or task authority +remains. BReg's own access profile and Action rules decide every call. +`check` refuses, at `/bindings/coordinatorBregClient/connection`, a connection that is not a +`breg` connection, delegates to task authority, or names a profile other than the identity's +BReg grant profile. Like every Coordinator binding, it is refused in any posture but +development. + +{/* Evidence: crates/registry-rstack-dev/src/bindings.rs coordinatorBregClient, + the_coordinator_breg_client_takes_profile_and_scopes_from_the_grant_only, + the_coordinator_obtains_a_breg_token_for_its_bound_identity, + coordinator_bindings_are_refused_outside_development; + crates/registry-rstack-dev/src/products.rs checked_coordinator_breg_client, + a_coordinator_breg_client_refuses_each_mismatch_at_its_connection. */} + ### Explicit browser roles with separate human source credentials A paired BReg and Casework built application may declare `application.caseworkSourceCredentialRoles` as 1 through 32 distinct existing role identifiers. diff --git a/products/platform/config-formats.yaml b/products/platform/config-formats.yaml index fe4fa581f3..d97c85b1f9 100644 --- a/products/platform/config-formats.yaml +++ b/products/platform/config-formats.yaml @@ -900,6 +900,8 @@ formats: whenOmitted: refused - pointer: /bindings/coordinatorReviewProducer/completionDestination whenOmitted: refused + - pointer: /bindings/coordinatorBregClient + whenOmitted: closed - pointer: /preview whenOmitted: closed - pointer: /preview/actor diff --git a/products/platform/generated/dev/dev.v1alpha1.schema.json b/products/platform/generated/dev/dev.v1alpha1.schema.json index fc0147ab16..4bcbfa7532 100644 --- a/products/platform/generated/dev/dev.v1alpha1.schema.json +++ b/products/platform/generated/dev/dev.v1alpha1.schema.json @@ -284,6 +284,10 @@ "$ref": "#/$defs/CaseworkContextProvider", "description": "Connects Casework to BReg as a context provider. Casework authenticates to BReg as a machine identity." }, + "coordinatorBregClient": { + "$ref": "#/$defs/CoordinatorBregClient", + "description": "Gives one Coordinator BReg connection a machine identity on the run's token endpoint, with exactly one test person's BReg grant. BReg's own access profile and Action rules decide every call. Development runs only." + }, "coordinatorReviewProducer": { "$ref": "#/$defs/CoordinatorReviewProducer", "description": "Connects the Coordinator to Casework as one trusted review producer. The Coordinator authenticates to Casework as a machine identity, and Casework wakes its waiting run through a completion hook. Development runs only." @@ -343,6 +347,25 @@ ], "type": "object" }, + "CoordinatorBregClient": { + "additionalProperties": false, + "description": "One Coordinator `breg` connection the run authenticates as one test\nperson. The person's BReg grant is the only source of the connection's\nprofile and scopes; nothing in dev.yaml adds to them.", + "properties": { + "connection": { + "$ref": "#/$defs/LocalId", + "description": "The Coordinator `runtime.yaml` connection of type `breg`, without task authority." + }, + "identity": { + "$ref": "#/$defs/LocalId", + "description": "Name of the test person, in `people`, whose BReg grant the Coordinator uses." + } + }, + "required": [ + "connection", + "identity" + ], + "type": "object" + }, "CoordinatorReviewProducer": { "additionalProperties": false, "description": "The Coordinator's Casework review producer connection that the run binds\nto Casework. Casework trusts exactly the producer the connection names, for\nthe run issuer, only when its pinned issuer, profile and subject match the\nguards; nothing here widens what Casework trusts.", From 3676c84b102beca8d5e236dc7e7565077aa02838 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 22:12:11 +0000 Subject: [PATCH 139/183] fix(dev): keep the Coordinator BReg identity dedicated to the Coordinator Refuse a coordinatorBregClient identity that another binding, a preview actor or a journey step uses, so BReg attributes only Coordinator calls to it, and refuse the binding with externalJwksUri, whose products would not trust the run-local endpoint's tokens. Run setup itself refuses the Coordinator bindings outside development, and each check case asserts its own message. Refs #2891 Signed-off-by: Jeremi Joslin --- crates/registry-rstack-dev/src/bindings.rs | 137 +++++++++++++++++- crates/registry-rstack-dev/src/plan.rs | 27 ++++ crates/registry-rstack-dev/src/preview.rs | 5 + crates/registry-rstack-dev/src/products.rs | 56 ++++--- .../run-a-project-with-rstack-dev.mdx | 3 + 5 files changed, 207 insertions(+), 21 deletions(-) diff --git a/crates/registry-rstack-dev/src/bindings.rs b/crates/registry-rstack-dev/src/bindings.rs index 3a2ab35806..8723bc10db 100644 --- a/crates/registry-rstack-dev/src/bindings.rs +++ b/crates/registry-rstack-dev/src/bindings.rs @@ -307,8 +307,45 @@ fn validate_coordinator_breg_client( &binding.identity, Product::Breg, &format!("{COORDINATOR_BREG_CLIENT}/identity"), + )?; + // BReg attributes every Coordinator call to this person, so no other + // binding or preview actor may act as it. + let shared = [ + plan.bindings + .breg_review_authority + .as_ref() + .map(|other| other.identity.as_str()), + plan.bindings + .casework_context_provider + .as_ref() + .map(|other| other.identity.as_str()), + plan.bindings + .coordinator_review_producer + .as_ref() + .map(|other| other.identity.as_str()), + ] + .into_iter() + .flatten() + .chain( + plan.preview + .iter() + .flat_map(|preview| preview.actor_names()), + ) + .any(|other| other == binding.identity); + plan::require( + !shared, + &format!("{COORDINATOR_BREG_CLIENT}/identity"), + "The Coordinator's BReg identity must be a dedicated machine person that no other binding or preview actor uses.", + "Declare a separate test person for the Coordinator's BReg grant.", + )?; + // The run-local token endpoint signs with the run's key, which BReg + // trusts only through the run's own key set. + plan::require( + plan.jwks_uri().is_none(), + COORDINATOR_BREG_CLIENT, + "The Coordinator BReg client binding needs the run's own key set, so it cannot use externalJwksUri.", + "Remove externalJwksUri, or remove bindings.coordinatorBregClient.", ) - .map(|_| ()) } const COORDINATOR_PRODUCER: &str = "/bindings/coordinatorReviewProducer"; @@ -589,6 +626,27 @@ impl RuntimeBindings { input: Arc, issuer: Arc, origins: &BTreeMap, + ) -> Result { + Self::prepare_in( + root, + input, + issuer, + origins, + registry_platform_config::declared(None), + ) + } + + /// Prepare under the declared posture, which refuses every Coordinator + /// binding outside development before any machine identity is created. + pub(super) fn prepare_in( + root: &Path, + input: Arc, + issuer: Arc, + origins: &BTreeMap, + posture: std::result::Result< + registry_platform_config::DeclaredPosture, + registry_platform_config::PostureError, + >, ) -> Result { let bindings = &input.plan.bindings; if bindings.breg_review_authority.is_none() @@ -602,7 +660,7 @@ impl RuntimeBindings { if bindings.coordinator_review_producer.is_some() || bindings.coordinator_breg_client.is_some() { - development_only(registry_platform_config::declared(None))?; + development_only(posture)?; } ensure!( bindings.coordinator_breg_client.is_none() @@ -3785,4 +3843,79 @@ mod tests { assert!(development_only(declared_from(None, Some(OsStr::new("development")))).is_ok()); assert!(development_only(declared_from(None, Some(OsStr::new("production")))).is_err()); } + + #[test] + fn the_coordinator_breg_identity_is_a_dedicated_machine_person() { + // Shared with the Casework context provider. + let mut shared = coordinator_breg_plan(); + shared.products.push(ProductPlan { + product: Product::Casework, + project: PathBuf::from("casework"), + audience: "urn:dev:casework".to_owned(), + }); + shared.bindings.casework_context_provider = Some(CaseworkContextProvider { + id: "registry".to_owned(), + identity: "coordinator-service".to_owned(), + action: "reviewed-change".to_owned(), + }); + let error = shared.bindings.validate(&shared).unwrap_err().to_string(); + assert!( + error.contains("/bindings/coordinatorBregClient/identity"), + "{error}" + ); + assert!(error.contains("dedicated"), "{error}"); + + // Shared with the preview actor. + let mut previewed = coordinator_breg_plan(); + previewed.preview = Some( + serde_json::from_value(json!({ + "actor": "coordinator-service", "page": "/", "breg": {}, "functions": ["renew"] + })) + .unwrap(), + ); + let error = previewed + .bindings + .validate(&previewed) + .unwrap_err() + .to_string(); + assert!( + error.contains("/bindings/coordinatorBregClient/identity"), + "{error}" + ); + } + + #[test] + fn the_coordinator_breg_client_needs_the_run_key_set() { + let mut external = coordinator_breg_plan(); + external.issuer = "http://127.0.0.1:41000".to_owned(); + external.external_jwks_uri = Some("http://127.0.0.1:41000/keys".to_owned()); + let error = external + .bindings + .validate(&external) + .unwrap_err() + .to_string(); + assert!(error.contains("/bindings/coordinatorBregClient"), "{error}"); + assert!(error.contains("externalJwksUri"), "{error}"); + } + + #[test] + fn run_setup_refuses_coordinator_bindings_outside_development() { + use registry_platform_config::declared_from; + use std::ffi::OsStr; + let root = tempfile::tempdir().unwrap(); + let refused = RuntimeBindings::prepare_in( + root.path(), + Arc::new(input(coordinator_breg_plan())), + Arc::new(Issuer::create(root.path()).unwrap()), + &coordinator_breg_origins(), + declared_from(None, Some(OsStr::new("production"))), + ); + let error = refused + .err() + .expect("a production posture is refused") + .to_string(); + assert!(error.contains("development only"), "{error}"); + // Nothing was registered for the refused run. + assert!(!root.path().join("coordinator-breg-client-key").exists()); + } } diff --git a/crates/registry-rstack-dev/src/plan.rs b/crates/registry-rstack-dev/src/plan.rs index bab5e5aa91..665f3c3d19 100644 --- a/crates/registry-rstack-dev/src/plan.rs +++ b/crates/registry-rstack-dev/src/plan.rs @@ -1854,6 +1854,17 @@ impl Journey { "The step must name a test person with a grant for its product.", "Set as to a test person that has a grant for this step's product.", )?; + require( + plan.bindings + .coordinator_breg_client + .as_ref() + .is_none_or(|binding| { + step.person.as_deref() != Some(binding.identity.as_str()) + }), + &format!("{field}/as"), + "A journey step cannot act as the Coordinator's dedicated BReg identity.", + "Set as to another test person.", + )?; require( valid_path(&step.path) && (step.path != ADAPTER_CONTRACT_PATH || step.product == Product::Adapter), &format!("{field}/path"), @@ -2394,6 +2405,22 @@ mod tests { (root, plan) } + #[test] + fn a_journey_cannot_act_as_the_coordinator_breg_identity() { + let (root, mut plan) = plan(json!({"id": "read", "product": "breg", + "as": "operator", "method": "GET", "path": "/v1/records", "expect": {"status": 200}})); + plan.bindings = serde_json::from_value(json!({"coordinatorBregClient": { + "connection": "registry", "identity": "operator" + }})) + .unwrap(); + let error = journey_file(root.path(), &plan) + .validate(&plan) + .unwrap_err() + .to_string(); + assert!(error.contains("/steps/0/as"), "{error}"); + assert!(error.contains("Coordinator"), "{error}"); + } + #[test] fn an_external_issuer_accepts_loopback_keys_and_requires_an_empty_journey_pack() { let (root, mut plan) = plan(json!({"id": "read", "product": "breg", diff --git a/crates/registry-rstack-dev/src/preview.rs b/crates/registry-rstack-dev/src/preview.rs index 5299724d69..44709ae1e3 100644 --- a/crates/registry-rstack-dev/src/preview.rs +++ b/crates/registry-rstack-dev/src/preview.rs @@ -64,6 +64,11 @@ pub(super) struct PreviewProduct { } impl Preview { + /// The synthetic identities the preview serves. + pub(super) fn actor_names(&self) -> Vec<&str> { + vec![self.actor.as_str()] + } + pub(super) fn build_plan(&self, root: &Path, native: &plan::Plan) -> Result { let refusal = || { plan::refuse( diff --git a/crates/registry-rstack-dev/src/products.rs b/crates/registry-rstack-dev/src/products.rs index 5814edc476..903da9101f 100644 --- a/crates/registry-rstack-dev/src/products.rs +++ b/crates/registry-rstack-dev/src/products.rs @@ -4913,26 +4913,43 @@ mod tests { "type": "breg", "baseUrl": "http://127.0.0.1:1", "profile": "permit-coordinator" }); type Break = fn(&mut Value); - let cases: [(&str, Break); 4] = [ - ("the connection is missing", |runtime| { - runtime["connections"] - .as_object_mut() - .unwrap() - .remove("registry"); - }), - ("the connection is of another type", |runtime| { - runtime["connections"]["registry"]["type"] = json!("messaging"); - }), - ("the connection names another profile", |runtime| { - runtime["connections"]["registry"]["profile"] = json!("permit-reader"); - }), - ("the connection delegates to task authority", |runtime| { - runtime["connections"]["registry"]["authorization"] = - json!({"taskAuthority": {"issuer": "https://casework.example"}}); - }), + // Each case names a fragment of its own refusal. + let cases: [(&str, &str, Break); 4] = [ + ( + "the connection is missing", + "no breg connection", + |runtime| { + runtime["connections"] + .as_object_mut() + .unwrap() + .remove("registry"); + }, + ), + ( + "the connection is of another type", + "no breg connection", + |runtime| { + runtime["connections"]["registry"]["type"] = json!("messaging"); + }, + ), + ( + "the connection names another profile", + "grant profile", + |runtime| { + runtime["connections"]["registry"]["profile"] = json!("permit-reader"); + }, + ), + ( + "the connection delegates to task authority", + "task authority", + |runtime| { + runtime["connections"]["registry"]["authorization"] = + json!({"taskAuthority": {"issuer": "https://casework.example"}}); + }, + ), ]; let root = tempfile::tempdir().unwrap(); - for (index, (name, break_it)) in cases.into_iter().enumerate() { + for (index, (name, fragment, break_it)) in cases.into_iter().enumerate() { let mut runtime = json!({"connections": {"registry": connection.clone()}}); break_it(&mut runtime); let project = root.path().join(index.to_string()); @@ -4949,7 +4966,8 @@ mod tests { assert!( refusal .to_string() - .starts_with(&format!("dev.yaml {CONNECTION}: ")), + .starts_with(&format!("dev.yaml {CONNECTION}: ")) + && refusal.to_string().contains(fragment), "{name}: {refusal}" ); } diff --git a/docs/site/src/content/docs/configure/run-a-project-with-rstack-dev.mdx b/docs/site/src/content/docs/configure/run-a-project-with-rstack-dev.mdx index 7c78522d57..67759b9477 100644 --- a/docs/site/src/content/docs/configure/run-a-project-with-rstack-dev.mdx +++ b/docs/site/src/content/docs/configure/run-a-project-with-rstack-dev.mdx @@ -1090,6 +1090,9 @@ bindings: ``` The identity's BReg grant is the only source of the connection's profile and scopes. +Use a dedicated machine person: BReg attributes every Coordinator call to it, so `check` +refuses an identity that another binding, a preview actor or a journey step uses, and a plan +with `externalJwksUri`, whose products would not trust the run-local endpoint's tokens. `start` replaces the connection's `baseUrl` with the run's BReg origin and its whole `authorization` with the run-local client, so no authored scope, resource or task authority remains. BReg's own access profile and Action rules decide every call. From fb62752ee435147e5cf7cd6057f86565806351f4 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 22:19:05 +0000 Subject: [PATCH 140/183] feat(dev): serve one preview page to several actors A preview may name an actors map instead of one actor. Each actor is a declared person with a BReg grant and lists the BReg, Casework and Coordinator paths it may reach, with a grant for each product. The run serves the same built page to each actor on its own loopback gateway origin, with that actor's own credential and pinned profile per product, and reports the origins and the per-actor origin substitution. The single-actor form is unchanged. Refs #2891 Signed-off-by: Jeremi Joslin --- clients/typescript/preview/build.mjs | 1 + clients/typescript/preview/config.mjs | 54 +- clients/typescript/preview/gateway.mjs | 120 +++-- clients/typescript/preview/run.mjs | 61 ++- .../typescript/preview/tests/preview.test.mjs | 137 +++++- crates/registry-rstack-dev/src/lib.rs | 31 +- crates/registry-rstack-dev/src/preview.rs | 460 ++++++++++++++++-- crates/registry-rstack-dev/src/products.rs | 98 +++- .../run-a-project-with-rstack-dev.mdx | 21 + .../generated/dev/dev.v1alpha1.schema.json | 32 +- 10 files changed, 888 insertions(+), 127 deletions(-) diff --git a/clients/typescript/preview/build.mjs b/clients/typescript/preview/build.mjs index e90f877dfd..57526d9838 100644 --- a/clients/typescript/preview/build.mjs +++ b/clients/typescript/preview/build.mjs @@ -197,6 +197,7 @@ export async function buildPreview(plan, directory) { version: versionLine, declarationDigest: plan.declarationDigest, product: plan.product, + routeProducts: plan.routeProducts ?? [], preview: plan.preview, functions: entries.map(([name]) => name), staticOutput: relative(directory, staticOutput), diff --git a/clients/typescript/preview/config.mjs b/clients/typescript/preview/config.mjs index 171ad39bb6..658d7c37b4 100644 --- a/clients/typescript/preview/config.mjs +++ b/clients/typescript/preview/config.mjs @@ -59,9 +59,13 @@ export async function prepareRuntimeConfig({ artifact, deployment, run }) { || run.preview.productId !== artifact.product.id || run.preview.profile !== artifact.product.profile) { throw new Error('The preview product or audience differs from the checked plan.') } - const { authorizationFile, functionHost } = run.preview - if (typeof authorizationFile !== 'string' || !isAbsolute(authorizationFile)) { - throw new Error('The preview needs an owner-only run authorization file.') + const { authorizationFile, functionHost, actors } = run.preview + if (artifact.preview?.actors === undefined) { + if (actors !== undefined || typeof authorizationFile !== 'string' || !isAbsolute(authorizationFile)) { + throw new Error('The preview needs an owner-only run authorization file.') + } + } else { + checkActors(artifact, run, actors) } const functionPort = functionHost?.port if (!Number.isInteger(functionPort) || functionPort < 1 || functionPort > 65535 || functionPort === port @@ -72,6 +76,42 @@ export async function prepareRuntimeConfig({ artifact, deployment, run }) { return { schema, runId: run.runId, origin, port, breg: run.breg, preview: run.preview } } +// Each actor has its own loopback origin, and for each product it may reach +// the product's origin and audience as checked, the access profile the +// gateway pins (none for the Coordinator), and its own credential file. +function checkActors(artifact, run, actors) { + const names = Object.keys(artifact.preview.actors) + const products = new Map((artifact.routeProducts ?? []).map(product => [product.id, product])) + products.set(artifact.product.id, { id: artifact.product.id, kind: 'breg', audience: artifact.product.audience }) + if (run.preview.authorizationFile !== undefined || !Array.isArray(actors) + || actors.map(actor => actor?.name).join() !== names.join()) { + throw new Error('The preview actors differ from the checked plan.') + } + const ports = new Set([run.preview.functionHost?.port, URL.parse(run.breg.baseUrl)?.port]) + actors.forEach((actor, index) => { + if (loopbackOrigin(actor.origin) !== `http://127.0.0.1:${actor.port}` || !Number.isInteger(actor.port) + || ports.has(actor.port) || ports.has(String(actor.port)) + || (index === 0 && (actor.origin !== run.origin || actor.port !== run.port))) { + throw new Error('Each preview actor needs its own reserved loopback address.') + } + ports.add(actor.port) + const routes = artifact.preview.actors[actor.name] + const entries = typeof actor.products === 'object' && actor.products !== null ? Object.entries(actor.products) : [] + const kinds = entries.map(([id]) => products.get(id)?.kind) + if (Object.keys(routes).some(kind => !kinds.includes(kind))) { + throw new Error('A preview actor reaches a product it has no credential for.') + } + for (const [id, product] of entries) { + const checked = products.get(id) + if (!checked || loopbackOrigin(product.baseUrl) === actor.origin || product.audience !== checked.audience + || (checked.kind === 'coordinator' ? product.profile !== null : typeof product.profile !== 'string') + || typeof product.authorizationFile !== 'string' || !isAbsolute(product.authorizationFile)) { + throw new Error('A preview actor product differs from the checked plan.') + } + } + }) +} + async function checkCredentialPath(path, runFile) { const file = await lstat(path) if (dirname(path) !== dirname(runFile) || !file.isFile() || file.isSymbolicLink() @@ -82,7 +122,13 @@ async function checkCredentialPath(path, runFile) { export async function configure({ artifact, deployment, runFile }) { const config = await prepareRuntimeConfig({ artifact, deployment, run: await readJson(runFile) }) - await checkCredentialPath(config.preview.authorizationFile, runFile) + if (config.preview.actors === undefined) { + await checkCredentialPath(config.preview.authorizationFile, runFile) + } else { + for (const actor of config.preview.actors) { + for (const product of Object.values(actor.products)) await checkCredentialPath(product.authorizationFile, runFile) + } + } await checkCredentialPath(config.preview.functionHost.keyFile, runFile) return config } diff --git a/clients/typescript/preview/gateway.mjs b/clients/typescript/preview/gateway.mjs index 81cbecb9e8..fac1fe52e8 100644 --- a/clients/typescript/preview/gateway.mjs +++ b/clients/typescript/preview/gateway.mjs @@ -12,7 +12,6 @@ const segment = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/u const uuid = /^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/iu const revision = /^[1-9][0-9]{0,18}$/u const maximumRevision = '9223372036854775807' -const recordParameter = part => part === '{recordId}' || part === '{record_id}' const contentTypes = new Map([ ['.css', 'text/css; charset=utf-8'], ['.html', 'text/html; charset=utf-8'], @@ -31,18 +30,39 @@ class RequestError extends Error { } } +// A route segment that stands for one product-assigned UUID. `{revision}` +// stands for one Record revision number. +const placeholders = new Set(['{recordId}', '{record_id}', '{taskId}', '{runId}']) + function compilePaths(paths = []) { if (!Array.isArray(paths)) throw new Error('Expected a list of preview routes per method.') return paths.map((path) => { const parts = typeof path === 'string' && path.length <= 256 && path.startsWith('/v1/') ? path.slice(1).split('/') : [] - if (parts.length < 2 || parts.filter(recordParameter).length > 1 || parts.filter(part => part === '{revision}').length > 1 - || !parts.every(part => segment.test(part) || recordParameter(part) || part === '{revision}')) { - throw new Error('Expected an exact /v1/ preview route with distinct Record ID and revision parameters.') + if (parts.length < 2 || parts.filter(part => placeholders.has(part)).length > 1 + || parts.filter(part => part === '{revision}').length > 1 + || !parts.every(part => segment.test(part) || placeholders.has(part) || part === '{revision}')) { + throw new Error('Expected an exact /v1/ preview route with at most one {recordId}, {taskId} or {runId} and at most one {revision}.') } return parts }) } +// The exact GET and POST routes one actor may reach on one product. +export function compileRoutes(routes = {}) { + const compiled = new Map([['GET', compilePaths(routes.get)], ['POST', compilePaths(routes.post)]]) + return (method, path) => { + const parts = path.slice(1).split('/') + return Boolean(compiled.get(method)?.some(route => + route.length === parts.length && route.every((part, index) => { + const value = parts[index] + if (placeholders.has(part)) return uuid.test(value) + if (part === '{revision}') return revision.test(value) && (value.length < maximumRevision.length || value <= maximumRevision) + return part === value + }), + )) + } +} + export function previewPolicy(preview) { const page = preview.page === '/' ? '/index.html' : preview.page if (typeof page !== 'string' || !/^\/(?:[A-Za-z0-9][A-Za-z0-9_-]*\/)*[A-Za-z0-9][A-Za-z0-9_-]*\.html$/u.test(page)) { @@ -52,24 +72,27 @@ export function previewPolicy(preview) { || new Set(preview.functions).size !== preview.functions.length) { throw new Error('Expected distinct preview function IDs.') } - const routes = new Map([ - ['GET', compilePaths(preview.breg.get)], - ['POST', compilePaths(preview.breg.post)], - ]) + if ((preview.actors === undefined) === (preview.breg === undefined)) { + throw new Error('Expected either one actor with BReg routes or an actors map.') + } + const actors = new Map() + if (preview.actors !== undefined) { + const entries = typeof preview.actors === 'object' && preview.actors !== null ? Object.entries(preview.actors) : [] + if (entries.length < 1 || entries.length > 8 || entries.some(([name, routes]) => !localId.test(name) + || typeof routes !== 'object' || routes === null + || Object.keys(routes).some(kind => !['breg', 'casework', 'coordinator'].includes(kind)))) { + throw new Error('Expected one to eight preview actors with breg, casework or coordinator routes.') + } + for (const [name, routes] of entries) { + actors.set(name, Object.fromEntries(Object.entries(routes).map(([kind, set]) => [kind, compileRoutes(set)]))) + } + } + const allowsBreg = preview.breg === undefined ? () => false : compileRoutes(preview.breg) return { page, functions: new Set(preview.functions), - allowsBreg(method, path) { - const parts = path.slice(1).split('/') - return routes.get(method)?.some(route => - route.length === parts.length && route.every((part, index) => { - const value = parts[index] - if (recordParameter(part)) return uuid.test(value) - if (part === '{revision}') return revision.test(value) && (value.length < maximumRevision.length || value <= maximumRevision) - return part === value - }), - ) - }, + actors, + allowsBreg, } } @@ -142,28 +165,51 @@ function sendError(response, status, message) { response.end(JSON.stringify({ message })) } +// The products one gateway reaches, keyed by service product ID. Each carries +// its loopback origin, the access profile the gateway pins (or null for a +// product that selects no profile by query), the routes the actor may use, +// and the actor's own credential for that product. +function gatewayProducts({ productId, profile, breg, authorization, preview, products }) { + if (products !== undefined) { + const entries = Object.entries(products) + if (!entries.length || entries.some(([id, product]) => !localId.test(id) + || typeof product.allows !== 'function' || typeof product.authorization !== 'function' + || !(product.profile === null || typeof product.profile === 'string'))) { + throw new Error('Expected preview products with routes, a profile and a credential.') + } + return new Map(entries.map(([id, product]) => [id, { ...product, origin: loopbackOrigin(product.origin) }])) + } + if (!localId.test(productId)) throw new Error('The preview needs a local product ID.') + return new Map([[productId, { + origin: loopbackOrigin(breg), profile, authorization, allows: compileRoutes(preview.breg), + }]]) +} + export async function startPreviewGateway({ origin: initialOrigin, port, productId, profile, breg, + products: declaredProducts, application, authorization, + functionAuthorization = authorization, publicDirectory, preview, functionKey, }) { - if (!localId.test(productId)) throw new Error('The preview needs a local product ID.') - const bregOrigin = loopbackOrigin(breg) + const products = gatewayProducts({ productId, profile, breg, authorization, preview, products: declaredProducts }) const applicationOrigin = loopbackOrigin(application) const policy = previewPolicy(preview) + if (typeof functionAuthorization !== 'function' && functionAuthorization !== null) { + throw new Error('The preview needs the actor credential for its functions, or null to serve none.') + } const files = await collectStaticFiles(publicDirectory) if (!files.has(policy.page)) throw new Error('The preview output is missing the configured HTML page.') - const registryPrefix = '/registry/' + productId let origin = initialOrigin - async function relay(request, response, target, privateFunction = false) { + async function relay(request, response, target, authorization, privateFunction = false) { const headers = new Headers({ authorization: await authorization() }) if (privateFunction && functionKey) headers.set('x-registry-preview-function', functionKey) for (const name of ['accept', 'content-type', 'if-match', 'idempotency-key']) { @@ -224,23 +270,29 @@ export async function startPreviewGateway({ || (method === 'POST' && headers.origin !== origin)) { throw new RequestError(403, 'Open the service page to make this request') } - if (method === 'POST' && rawPath.startsWith('/api/functions/') && !url.search) { + if (functionAuthorization && method === 'POST' && rawPath.startsWith('/api/functions/') && !url.search) { const name = rawPath.slice('/api/functions/'.length) if (policy.functions.has(name)) { - await relay(request, response, applicationOrigin + '/functions/' + name, true) + await relay(request, response, applicationOrigin + '/functions/' + name, functionAuthorization, true) return } } - if (rawPath.startsWith(registryPrefix + '/')) { - const bregPath = rawPath.slice(registryPrefix.length) - if (policy.allowsBreg(method, bregPath)) { - const requestedProfiles = url.searchParams.getAll('accessProfile') - if (requestedProfiles.length > 1 || requestedProfiles.some(value => value !== profile)) { - throw new RequestError(403, 'The request selects another access profile') - + const [, prefix, id, ...rest] = rawPath.split('/') + const product = prefix === 'registry' ? products.get(id) : undefined + if (product && rest.length) { + const productPath = '/' + rest.join('/') + if (product.allows(method, productPath)) { + if (product.profile === null) { + // A product that selects no profile by query takes no query at all. + if (url.search) throw new RequestError(404, 'Unknown preview route') + } else { + const requestedProfiles = url.searchParams.getAll('accessProfile') + if (requestedProfiles.length > 1 || requestedProfiles.some(value => value !== product.profile)) { + throw new RequestError(403, 'The request selects another access profile') + } + url.searchParams.set('accessProfile', product.profile) } - url.searchParams.set('accessProfile', profile) - await relay(request, response, bregOrigin + bregPath + url.search) + await relay(request, response, product.origin + productPath + url.search, product.authorization) return } } diff --git a/clients/typescript/preview/run.mjs b/clients/typescript/preview/run.mjs index ed52874072..5a0e3dbfcc 100644 --- a/clients/typescript/preview/run.mjs +++ b/clients/typescript/preview/run.mjs @@ -1,14 +1,19 @@ import { writeFile } from 'node:fs/promises' import { dirname, join } from 'node:path' import { artifactDirectory, checkRuntimeConfig, configEnvironment, readArtifact, readAuthorization, readHostKey } from './config.mjs' -import { startPreviewGateway } from './gateway.mjs' +import { compileRoutes, previewPolicy, startPreviewGateway } from './gateway.mjs' import { functionHostAuthorizer, startFunctionHost } from './host.mjs' async function run() { const configFile = process.env[configEnvironment] const artifact = await readArtifact() const config = await checkRuntimeConfig(configFile, artifact) - await readAuthorization(config.preview.authorizationFile) + const actors = config.preview.actors + for (const file of actors === undefined + ? [config.preview.authorizationFile] + : actors.flatMap(actor => Object.values(actor.products).map(product => product.authorizationFile))) { + await readAuthorization(file) + } const connection = Object.freeze({ ...config.breg }) const products = Object.freeze({ [artifact.product.id]: connection }) const handlers = new Map() @@ -28,30 +33,60 @@ async function run() { authorize: functionHostAuthorizer(functionKey), port: config.preview.functionHost.port, }) - let gateway + const gateways = [] try { await writeFile(join(dirname(configFile), 'application-preview-function-origin'), privateHost.origin + '\n', { flag: 'wx', mode: 0o600 }) - gateway = await startPreviewGateway({ - origin: config.origin, - port: config.port, - productId: artifact.product.id, - profile: artifact.product.profile, - breg: config.breg.baseUrl, + const shared = { application: privateHost.origin, - authorization: () => readAuthorization(config.preview.authorizationFile), publicDirectory: join(artifactDirectory, artifact.staticOutput), preview: artifact.preview, functionKey, - }) + } + if (actors === undefined) { + gateways.push(await startPreviewGateway({ + ...shared, + origin: config.origin, + port: config.port, + productId: artifact.product.id, + profile: artifact.product.profile, + breg: config.breg.baseUrl, + authorization: () => readAuthorization(config.preview.authorizationFile), + })) + } else { + // One gateway per actor, each on its own origin over the same static + // bytes, carrying only that actor's credentials and routes. + const policy = previewPolicy(artifact.preview) + const kinds = new Map((artifact.routeProducts ?? []).map(product => [product.id, product.kind])) + kinds.set(artifact.product.id, 'breg') + // The run checks readiness on the first actor's origin, so that + // gateway starts last, once every other actor's gateway listens. + for (const actor of [...actors].reverse()) { + const routes = policy.actors.get(actor.name) + const products = Object.fromEntries(Object.entries(actor.products).map(([id, product]) => [id, { + origin: product.baseUrl, + profile: product.profile, + authorization: () => readAuthorization(product.authorizationFile), + allows: routes[kinds.get(id)] ?? compileRoutes({}), + }])) + const breg = actor.products[artifact.product.id] + gateways.push(await startPreviewGateway({ + ...shared, + origin: actor.origin, + port: actor.port, + products, + functionAuthorization: breg ? () => readAuthorization(breg.authorizationFile) : null, + })) + } + } } catch (error) { - await privateHost.close() + await Promise.all([...gateways.map(gateway => gateway.close()), privateHost.close()]) throw error } let closing function close() { - closing ??= Promise.all([gateway.close(), privateHost.close()]).catch(() => { + closing ??= Promise.all([...gateways.map(gateway => gateway.close()), privateHost.close()]).catch(() => { console.error('Cannot close the preview listeners cleanly.') process.exitCode = 1 }) diff --git a/clients/typescript/preview/tests/preview.test.mjs b/clients/typescript/preview/tests/preview.test.mjs index f93c37b48c..91dc842c9d 100644 --- a/clients/typescript/preview/tests/preview.test.mjs +++ b/clients/typescript/preview/tests/preview.test.mjs @@ -5,7 +5,7 @@ import { join } from 'node:path' import { createServer, request } from 'node:http' import { test } from 'node:test' import { coordinatorBearer, functionHostAuthorizer, startFunctionHost } from '../host.mjs' -import { collectStaticFiles, previewPolicy, startPreviewGateway } from '../gateway.mjs' +import { collectStaticFiles, compileRoutes, previewPolicy, startPreviewGateway } from '../gateway.mjs' import { configure, prepareRuntimeConfig, readHostKey } from '../config.mjs' import { buildPreview } from '../build.mjs' import { createHash } from 'node:crypto' @@ -288,3 +288,138 @@ test('the run host key file must be owner-only, in the run directory, and well f await rm(keyFile) } }) + +test('an actors policy compiles per-product routes and is exclusive with the single-actor form', () => { + const actors = { + applicant: { breg: { post: ['/v1/actions/submit-application'] }, coordinator: { get: ['/v1/runs/{runId}'], post: ['/v1/runs'] } }, + officer: { casework: { get: ['/v1/review-tasks'], post: ['/v1/review-tasks/{taskId}/decisions'] } }, + } + const policy = previewPolicy({ page: '/', functions: ['assess-permit'], actors }) + assert.deepEqual([...policy.actors.keys()], ['applicant', 'officer']) + const run = '00000000-0000-4000-8000-000000000001' + assert.equal(policy.actors.get('applicant').coordinator('GET', '/v1/runs/' + run), true) + assert.equal(policy.actors.get('applicant').coordinator('GET', '/v1/runs/not-a-uuid'), false) + assert.equal(policy.actors.get('officer').casework('POST', '/v1/review-tasks/' + run + '/decisions'), true) + assert.equal(policy.actors.get('officer').breg, undefined) + assert.equal(policy.allowsBreg('GET', '/v1/records/licenses'), false) + for (const invalid of [ + { page: '/', functions: [], actors, breg: {} }, + { page: '/', functions: [] }, + { page: '/', functions: [], actors: {} }, + { page: '/', functions: [], actors: { Applicant: {} } }, + { page: '/', functions: [], actors: { applicant: { messaging: {} } } }, + { page: '/', functions: [], actors: { applicant: { coordinator: { get: ['/v1/runs/{runId}/{taskId}'] } } } }, + ]) { + assert.throws(() => previewPolicy(invalid), JSON.stringify(invalid)) + } + assert.equal(compileRoutes({ get: ['/v1/review-tasks/{taskId}'] })('GET', '/v1/review-tasks/' + run), true) +}) + +test('a gateway relays each product with its own credential, profile and routes', async (t) => { + const root = await mkdtemp(join(tmpdir(), 'registry-preview-products-')) + t.after(() => rm(root, { recursive: true })) + await writeFile(join(root, 'index.html'), '

Page

') + const seen = [] + const upstream = createServer((request, response) => { + seen.push([request.headers.host.split(':')[1], request.url, request.headers.authorization]) + response.writeHead(200, { 'content-type': 'application/json' }).end('{}') + }) + await new Promise(resolve => upstream.listen(0, '127.0.0.1', resolve)) + t.after(() => new Promise(resolve => upstream.close(resolve))) + const other = createServer((request, response) => { + seen.push(['other', request.url, request.headers.authorization]) + response.writeHead(403, { 'content-type': 'application/json' }).end('{"code":"profile.not-authorized"}') + }) + await new Promise(resolve => other.listen(0, '127.0.0.1', resolve)) + t.after(() => new Promise(resolve => other.close(resolve))) + const origin = server => 'http://127.0.0.1:' + server.address().port + const gateway = await startPreviewGateway({ + origin: null, port: 0, application: 'http://127.0.0.1:1', publicDirectory: root, + preview: { page: '/', functions: ['assess-permit'], actors: { applicant: {} } }, + functionAuthorization: () => 'Bearer applicant.breg', + products: { + 'permit-flow': { origin: origin(upstream), profile: null, authorization: () => 'Bearer applicant.coordinator', + allows: compileRoutes({ post: ['/v1/runs'] }) }, + 'permit-review': { origin: origin(other), profile: 'permit-requester', authorization: () => 'Bearer applicant.casework', + allows: compileRoutes({ post: ['/v1/review-tasks/{taskId}/decisions'] }) }, + }, + }) + t.after(() => gateway.close()) + const headers = { origin: gateway.origin, 'registry-client': 'page', 'content-type': 'application/json' } + const post = path => fetch(gateway.origin + path, { method: 'POST', headers, body: '{}' }) + assert.equal((await post('/registry/permit-flow/v1/runs')).status, 200) + assert.equal((await post('/registry/permit-flow/v1/runs?accessProfile=x')).status, 404) + assert.equal((await post('/registry/permit-flow/v1/other')).status, 404) + const task = '00000000-0000-4000-8000-000000000002' + const refused = await post('/registry/permit-review/v1/review-tasks/' + task + '/decisions') + // The owning product's own refusal reaches the page unchanged. + assert.equal(refused.status, 403) + assert.equal((await refused.json()).code, 'profile.not-authorized') + assert.equal((await post('/registry/permit-review/v1/review-tasks/' + task + '/decisions?accessProfile=permit-officer')).status, 403) + assert.equal((await post('/registry/unknown/v1/runs')).status, 404) + assert.deepEqual(seen.map(([, url, authorization]) => [url, authorization]), [ + ['/v1/runs', 'Bearer applicant.coordinator'], + ['/v1/review-tasks/' + task + '/decisions?accessProfile=permit-requester', 'Bearer applicant.casework'], + ]) +}) + +test('prepare checks each actor origin, product, profile and credential against the plan', async (t) => { + const root = await mkdtemp(join(tmpdir(), 'registry-preview-actors-')) + t.after(() => rm(root, { recursive: true })) + const deployment = join(root, 'service.yaml') + await writeFile(deployment, 'service declaration') + const declarationDigest = createHash('sha256').update('service declaration').digest('hex') + const artifact = { + declarationDigest, + product: { id: 'permits', member: 'permits', audience: 'urn:permits', profile: 'permit-applicant' }, + routeProducts: [ + { id: 'casework', kind: 'casework', audience: 'urn:review' }, + { id: 'permit-flow', kind: 'coordinator', audience: 'urn:flow' }, + ], + preview: { page: '/', functions: ['assess-permit'], actors: { + applicant: { breg: { post: ['/v1/actions/submit-application'] }, coordinator: { post: ['/v1/runs'] } }, + officer: { casework: { get: ['/v1/review-tasks'] } }, + } }, + } + const file = name => join(root, name) + const run = { + schema: 'registry-stack.local-service-preview/v1', + runId: 'fixture-run', origin: 'http://127.0.0.1:23456', port: 23456, insecureLocal: true, + breg: { baseUrl: 'http://127.0.0.1:34567', audience: 'urn:permits' }, + preview: { + productId: 'permits', profile: 'permit-applicant', declarationDigest, + functionHost: { port: 45678, keyFile: file('key') }, + actors: [ + { name: 'applicant', origin: 'http://127.0.0.1:23456', port: 23456, products: { + permits: { baseUrl: 'http://127.0.0.1:34567', audience: 'urn:permits', profile: 'permit-applicant', authorizationFile: file('a-breg') }, + 'permit-flow': { baseUrl: 'http://127.0.0.1:34568', audience: 'urn:flow', profile: null, authorizationFile: file('a-flow') }, + } }, + { name: 'officer', origin: 'http://127.0.0.1:23457', port: 23457, products: { + permits: { baseUrl: 'http://127.0.0.1:34567', audience: 'urn:permits', profile: 'permit-reader', authorizationFile: file('o-breg') }, + casework: { baseUrl: 'http://127.0.0.1:34569', audience: 'urn:review', profile: 'permit-officer', authorizationFile: file('o-casework') }, + } }, + ], + }, + } + const valid = await prepareRuntimeConfig({ artifact, deployment, run }) + assert.equal(valid.preview.actors.length, 2) + const changed = change => { + const copy = structuredClone(run) + change(copy.preview.actors) + return copy + } + for (const invalid of [ + changed(actors => actors.reverse()), + changed(actors => { actors[1].port = 23456; actors[1].origin = 'http://127.0.0.1:23456' }), + changed(actors => { actors[1].port = 45678; actors[1].origin = 'http://127.0.0.1:45678' }), + changed(actors => { delete actors[1].products.casework }), + changed(actors => { actors[0].products['permit-flow'].profile = 'permit-starter' }), + changed(actors => { actors[1].products.casework.profile = null }), + changed(actors => { actors[1].products.casework.audience = 'urn:other' }), + changed(actors => { actors[1].products.casework.authorizationFile = 'relative' }), + changed(actors => { actors[1].products.unknown = actors[1].products.casework }), + { ...run, preview: { ...run.preview, authorizationFile: file('single') } }, + ]) { + await assert.rejects(prepareRuntimeConfig({ artifact, deployment, run: invalid }), JSON.stringify(invalid.preview.actors?.map(actor => actor.name))) + } +}) diff --git a/crates/registry-rstack-dev/src/lib.rs b/crates/registry-rstack-dev/src/lib.rs index 925a94fd37..0ea244094f 100644 --- a/crates/registry-rstack-dev/src/lib.rs +++ b/crates/registry-rstack-dev/src/lib.rs @@ -1541,6 +1541,7 @@ fn worker(root: &Path, output: &mut dyn Write) -> Result<()> { .as_ref() .map(|_| root.join("application-preview")); let mut preview_signer = None; + let mut preview_actors = None; let prepared = catch_startup(|| { products.capture_preview_project()?; products.check()?; @@ -1718,6 +1719,7 @@ fn worker(root: &Path, output: &mut dyn Write) -> Result<()> { preview::authorization(root, &input, &issuer, clock()? + input.ttl_seconds)?; let prepared = products.prepare_application(&urls, Some((artifact, &authorization_file)))?; + let actors = prepared.actors.clone(); let origin = products.start_application(prepared.launch)?; let page = &input .plan @@ -1726,6 +1728,12 @@ fn worker(root: &Path, output: &mut dyn Write) -> Result<()> { .context("missing preview page")? .page; application_url = Some(format!("{origin}{page}")); + preview_actors = (!actors.is_empty()).then(|| { + actors + .iter() + .map(|(name, origin)| (name.clone(), format!("{origin}{page}"))) + .collect::>() + }); preview_signer = Some(issuer); } let expires_at = clock()? + input.ttl_seconds; @@ -1780,6 +1788,12 @@ fn worker(root: &Path, output: &mut dyn Write) -> Result<()> { (url, issuer) }); add_run_addresses(&mut report, &input.plan, application); + if let Some(actors) = &preview_actors { + // A development substitution: one gateway origin per actor, over + // the same page bytes, stands in for one origin with sign-in. + report["previewActors"] = json!(actors); + report["substitutions"] = json!(["one preview gateway origin per actor"]); + } if let (Some(state), Some(key)) = (&project_state, &input.project_key) { write_private(&state.join(format!("run-{}", input.run_id)), key.as_bytes())?; @@ -2774,11 +2788,20 @@ fn remove_run_dir(root: &Path) -> Result<()> { } _ => {} } - match fs::remove_file(root.join(preview::AUTHORIZATION_FILE)) { - Err(error) if error.kind() != std::io::ErrorKind::NotFound => { - return Err(error).context("cannot remove the run's preview authorization"); + for entry in fs::read_dir(root).context("cannot read the run directory")? { + let entry = entry.context("cannot read the run directory")?; + if entry + .file_name() + .to_str() + .is_some_and(|name| name.starts_with(preview::AUTHORIZATION_FILE)) + { + match fs::remove_file(entry.path()) { + Err(error) if error.kind() != std::io::ErrorKind::NotFound => { + return Err(error).context("cannot remove the run's preview authorization"); + } + _ => {} + } } - _ => {} } match fs::remove_file(root.join(products::FUNCTION_HOST_KEY)) { Err(error) if error.kind() != std::io::ErrorKind::NotFound => { diff --git a/crates/registry-rstack-dev/src/preview.rs b/crates/registry-rstack-dev/src/preview.rs index 44709ae1e3..68c0b77b57 100644 --- a/crates/registry-rstack-dev/src/preview.rs +++ b/crates/registry-rstack-dev/src/preview.rs @@ -23,17 +23,26 @@ pub(super) const HEALTH: &str = "/_rstack/ready"; #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] #[serde(deny_unknown_fields)] pub(super) struct Preview { - /// Synthetic development identity whose checked BReg grant is used on the server. - pub actor: LocalId, + /// Synthetic development identity whose checked BReg grant is used on the server. Use with `breg`, or use `actors` instead. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub actor: Option, /// Initial page on the loopback preview origin. pub page: String, - /// BReg paths exposed to the page, grouped by method. - pub breg: Routes, + /// BReg paths exposed to the page of the single `actor`, grouped by method. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub breg: Option, /// Declared functions to expose on the loopback preview origin. pub functions: UniqueList, + /// One to eight synthetic identities, each served on its own loopback gateway origin over the same page, with the product paths it may reach. Use instead of `actor` and `breg`. Every actor needs a BReg grant, and a grant for each other product it reaches. + #[serde(default, skip_serializing_if = "Option::is_none")] + #[cfg_attr( + feature = "schema", + schemars(schema_with = "super::plan::keyed_schema::") + )] + pub actors: Option>, } -#[derive(Deserialize, Serialize)] +#[derive(Default, Deserialize, Serialize)] #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] #[serde(deny_unknown_fields)] pub(super) struct Routes { @@ -43,6 +52,46 @@ pub(super) struct Routes { post: UniqueList, } +impl Routes { + fn is_empty(&self) -> bool { + self.get.is_empty() && self.post.is_empty() + } +} + +/// The product paths one preview actor may reach, grouped by product and +/// method. +#[derive(Default, Deserialize, Serialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde(deny_unknown_fields)] +pub(super) struct ActorRoutes { + #[serde(default, skip_serializing_if = "Routes::is_empty")] + breg: Routes, + #[serde(default, skip_serializing_if = "Routes::is_empty")] + casework: Routes, + #[serde(default, skip_serializing_if = "Routes::is_empty")] + coordinator: Routes, +} + +impl ActorRoutes { + fn by_product(&self) -> [(Product, &Routes); 3] { + [ + (Product::Breg, &self.breg), + (Product::Casework, &self.casework), + (Product::Coordinator, &self.coordinator), + ] + } +} + +/// A product the page reaches only through the gateway, without a +/// generated client. +#[derive(Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub(super) struct RouteProduct { + pub id: LocalId, + pub kind: String, + pub audience: String, +} + #[derive(Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub(super) struct BuildPlan { @@ -52,6 +101,8 @@ pub(super) struct BuildPlan { functions: BTreeMap, pub product: PreviewProduct, pub declaration_digest: String, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub route_products: Vec, } #[derive(Deserialize, Serialize)] @@ -66,7 +117,11 @@ pub(super) struct PreviewProduct { impl Preview { /// The synthetic identities the preview serves. pub(super) fn actor_names(&self) -> Vec<&str> { - vec![self.actor.as_str()] + self.actor + .iter() + .chain(self.actors.iter().flat_map(BTreeMap::keys)) + .map(LocalId::as_str) + .collect() } pub(super) fn build_plan(&self, root: &Path, native: &plan::Plan) -> Result { @@ -77,10 +132,32 @@ impl Preview { "Declare the one BReg project under products in service.yaml, set its audience in dev.yaml, and remove any explicit application or external issuer from this preview.", ) }; + let multi = self.actors.is_some(); + if (self.actor.is_some() || self.breg.is_some()) == multi + || self.actor.is_some() != self.breg.is_some() + { + return plan::refuse( + "/preview", + "A browser preview names either one actor with BReg routes or an actors map.", + "Use actor and breg for one identity, or actors for several.", + ) + .map_err(Into::into); + } + // Casework and the Coordinator are reachable only through actors. + let route_kinds = + |product: Product| multi && matches!(product, Product::Casework | Product::Coordinator); if native.application.is_some() || native.issuer != "run" - || native.products.len() != 1 - || native.products[0].product != Product::Breg + || native + .products + .iter() + .filter(|entry| entry.product == Product::Breg) + .count() + != 1 + || native + .products + .iter() + .any(|entry| entry.product != Product::Breg && !route_kinds(entry.product)) { return refusal().map_err(Into::into); } @@ -114,10 +191,27 @@ impl Preview { let Some(ui) = service.ui else { return refusal().map_err(Into::into); }; + let kind = |product: &service::Product| match product.product { + "breg" => Some(Product::Breg), + "casework" => Some(Product::Casework), + "coordinator" => Some(Product::Coordinator), + _ => None, + }; if service.file != service_file || service.functions.is_empty() - || service.products.len() != 1 - || service.products[0].product != "breg" + || service + .products + .iter() + .filter(|product| product.product == "breg") + .count() + != 1 + || service.products.iter().any(|product| { + kind(product).is_none_or(|product| { + product != Product::Breg + && (!route_kinds(product) + || !native.products.iter().any(|entry| entry.product == product)) + }) + }) { return refusal().map_err(Into::into); } @@ -151,11 +245,24 @@ impl Preview { ) .map_err(Into::into); } - let Some(grant) = native - .people - .get(self.actor.as_str()) - .and_then(|actor| actor.grants.get(&Product::Breg)) - else { + let profile = match (&self.actor, &self.actors) { + (Some(actor), None) => native + .people + .get(actor.as_str()) + .and_then(|actor| actor.grants.get(&Product::Breg)) + .map(|grant| grant.profile.clone()), + (None, Some(actors)) => { + check_actors(native, actors)?; + actors + .keys() + .next() + .and_then(|actor| native.people.get(actor.as_str())) + .and_then(|actor| actor.grants.get(&Product::Breg)) + .map(|grant| grant.profile.clone()) + } + _ => None, + }; + let Some(profile) = profile else { return plan::refuse( "/preview/actor", "The preview actor needs a BReg grant.", @@ -171,18 +278,8 @@ impl Preview { ) .map_err(Into::into); } - for (method, routes) in [("get", &self.breg.get), ("post", &self.breg.post)] { - if routes.len() > 64 - || routes - .iter() - .any(|route| !route.starts_with("/v1/") || !valid_path(route, true)) - { - return plan::refuse( - &format!("/preview/breg/{method}"), - "Preview routes need bounded literal BReg paths.", - "Use /v1/ paths with distinct Record ID and revision segments ({recordId}, {record_id}, {revision}), without query strings.", - ).map_err(Into::into); - } + if let Some(routes) = &self.breg { + check_routes(routes, "/preview/breg")?; } let selected = &self.functions; if selected.is_empty() @@ -198,10 +295,23 @@ impl Preview { ) .map_err(Into::into); } + let mut route_products: Vec = service + .products + .iter() + .filter_map(|product| { + let kind = kind(product).filter(|kind| *kind != Product::Breg)?; + Some(RouteProduct { + id: product.id.clone(), + kind: kind.name().to_owned(), + audience: native.product(kind).audience.clone(), + }) + }) + .collect(); + route_products.sort_by(|a, b| a.kind.cmp(&b.kind)); let product = service .products .into_iter() - .next() + .find(|product| product.product == "breg") .context("missing preview product")?; ensure!( product.project @@ -224,16 +334,86 @@ impl Preview { member: product.member.context("missing preview client member")?, project: product.project, audience: native.product(Product::Breg).audience.clone(), - profile: grant.profile.clone(), + profile, }, declaration_digest: Sha256::digest(&declaration) .iter() .map(|byte| format!("{byte:02x}")) .collect(), + route_products, }) } } +/// Bounded literal /v1/ paths with at most one product ID placeholder. +fn check_routes(routes: &Routes, field: &str) -> plan::SemanticResult<()> { + for (method, routes) in [("get", &routes.get), ("post", &routes.post)] { + if routes.len() > 64 + || routes + .iter() + .any(|route| !route.starts_with("/v1/") || !valid_path(route, true)) + { + return plan::refuse( + &format!("{field}/{method}"), + "Preview routes need bounded literal product paths.", + "Use /v1/ paths with at most one {recordId}, {record_id}, {taskId} or {runId} segment and at most one {revision} segment, without query strings.", + ); + } + } + Ok(()) +} + +/// Each actor is a declared synthetic identity with a BReg grant, and a grant +/// for every other product it reaches through bounded literal paths. +fn check_actors( + native: &plan::Plan, + actors: &BTreeMap, +) -> plan::SemanticResult<()> { + if actors.is_empty() || actors.len() > 8 { + return plan::refuse( + "/preview/actors", + "A preview has one to eight actors.", + "Declare between one and eight actors.", + ); + } + for (name, routes) in actors { + let field = format!("/preview/actors/{}", name.as_str()); + let Some(person) = native.people.get(name.as_str()) else { + return plan::refuse( + &field, + "The preview actor is not a declared synthetic identity.", + "Name a person declared in people.", + ); + }; + if !person.grants.contains_key(&Product::Breg) { + return plan::refuse( + &field, + "Each preview actor needs a BReg grant.", + "Give the person a BReg role.", + ); + } + for (product, routes) in routes.by_product() { + let field = format!("{field}/{}", product.name()); + if !routes.is_empty() && !person.grants.contains_key(&product) { + return plan::refuse( + &field, + "The preview actor has no grant for this product.", + "Give the person a role for this product, or remove its paths.", + ); + } + check_routes(routes, &field)?; + } + } + Ok(()) +} + +/// The authorization files a preview run writes: one for the single actor's +/// BReg grant, or one per actor and product it reaches. +pub(super) struct PreviewAuthorization { + pub single: Option, + pub actors: BTreeMap>, +} + fn valid_page(path: &str) -> bool { if path == "/" { return true; @@ -252,17 +432,18 @@ pub(super) fn valid_path(path: &str, parameter: bool) -> bool { let Some(rest) = path.strip_prefix('/') else { return false; }; - let mut record_id = false; + let placeholder = + |part: &str| matches!(part, "{recordId}" | "{record_id}" | "{taskId}" | "{runId}"); + let mut identifier = false; let mut revision = false; path.len() <= 256 && rest.split('/').all(|part| { if parameter { - match part { - "{recordId}" | "{record_id}" => { - return !std::mem::replace(&mut record_id, true) - } - "{revision}" => return !std::mem::replace(&mut revision, true), - _ => {} + if placeholder(part) { + return !std::mem::replace(&mut identifier, true); + } + if part == "{revision}" { + return !std::mem::replace(&mut revision, true); } } part.len() <= 128 @@ -281,21 +462,45 @@ pub(super) fn authorization( input: &RunInput, signer: &Issuer, run_expires: u64, -) -> Result { +) -> Result { let preview = input.plan.preview.as_ref().context("missing preview")?; - let person = input - .plan - .people - .get(preview.actor.as_str()) - .context("missing preview actor")?; let expires = issuer::token_expiry(run_expires, clock()?); - let bearer = signer.token(input, person, Product::Breg, expires)?; - let path = root.join(AUTHORIZATION_FILE); - write_private( - &path, - Zeroizing::new(format!("Authorization: Bearer {}\n", &*bearer)).as_bytes(), - )?; - Ok(path) + let write = |path: PathBuf, person, product| -> Result { + let bearer = signer.token(input, person, product, expires)?; + write_private( + &path, + Zeroizing::new(format!("Authorization: Bearer {}\n", &*bearer)).as_bytes(), + )?; + Ok(path) + }; + let mut written = PreviewAuthorization { + single: None, + actors: BTreeMap::new(), + }; + if let Some(actor) = &preview.actor { + let person = input + .plan + .people + .get(actor.as_str()) + .context("missing preview actor")?; + written.single = Some(write(root.join(AUTHORIZATION_FILE), person, Product::Breg)?); + } + for (name, routes) in preview.actors.iter().flatten() { + let person = input + .plan + .people + .get(name.as_str()) + .context("missing preview actor")?; + let mut files = BTreeMap::new(); + for (product, routes) in routes.by_product() { + if product == Product::Breg || !routes.is_empty() { + let file = format!("{AUTHORIZATION_FILE}-{}-{}", name.as_str(), product.name()); + files.insert(product, write(root.join(file), person, product)?); + } + } + written.actors.insert(name.as_str().to_owned(), files); + } + Ok(written) } pub(super) fn helper(root: &Path) -> Result { @@ -470,3 +675,160 @@ mod snapshot_tests { ); } } + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::{json, Value}; + + const SERVICE: &str = "\ +apiVersion: id.registrystack.org/formats/rstack/service/v1alpha1 +kind: RStackService +products: + breg: + projects: + permits: {path: project} + casework: {path: casework} + coordinator: + projects: + permit-flow: {path: coordinator} +ui: {project: web, output: dist} +functions: [assess-permit] +"; + + /// A service with BReg, Casework and the Coordinator, a UI and one + /// function, with stub native manifests. + fn project(root: &Path) { + for (directory, file) in [ + ("project", "registry.yaml"), + ("casework", "casework.yaml"), + ("coordinator", "workflow.yaml"), + ("web/src", "page.ts"), + ("functions/assess-permit", "index.ts"), + ] { + fs::create_dir_all(root.join(directory)).unwrap(); + fs::write(root.join(directory).join(file), "{}\n").unwrap(); + } + fs::create_dir_all(root.join("web/public")).unwrap(); + fs::write(root.join("service.yaml"), SERVICE).unwrap(); + } + + fn grant(profile: &str) -> Value { + json!({"profile": profile, "scopes": ["read"]}) + } + + /// An applicant and an officer, each on its own origin. + fn native(preview: Value) -> plan::Plan { + serde_json::from_value(json!({ + "issuer": "run", + "products": [ + {"product": "breg", "project": "project", "audience": "urn:permits"}, + {"product": "casework", "project": "casework", "audience": "urn:review"}, + {"product": "coordinator", "project": "coordinator", "audience": "urn:flow"} + ], + "people": { + "applicant": {"subject": "applicant", "client": "applicant-client", "grants": { + "breg": grant("permit-applicant"), "casework": grant("permit-requester"), + "coordinator": grant("permit-starter") + }}, + "officer": {"subject": "officer", "client": "officer-client", "grants": { + "breg": grant("permit-reader"), "casework": grant("permit-officer") + }} + }, + "journeyFile": "dev-journeys.yaml", + "preview": preview + })) + .unwrap() + } + + fn actors() -> Value { + json!({ + "page": "/", + "functions": ["assess-permit"], + "actors": { + "applicant": { + "breg": {"post": ["/v1/actions/submit-application"]}, + "casework": {"post": ["/v1/review-tasks/{taskId}/decisions"]}, + "coordinator": {"get": ["/v1/workflows/permit-flow", "/v1/runs/{runId}"], "post": ["/v1/runs"]} + }, + "officer": { + "breg": {"get": ["/v1/records/permits/{recordId}"]}, + "casework": {"get": ["/v1/review-tasks"], "post": ["/v1/review-tasks/{taskId}/claim", "/v1/review-tasks/{taskId}/decisions"]} + } + } + }) + } + + fn build(preview: Value) -> Result { + let root = tempfile::tempdir().unwrap(); + project(root.path()); + let plan = native(preview); + plan.preview + .as_ref() + .unwrap() + .build_plan(root.path(), &plan) + } + + fn pointer(preview: Value) -> String { + let Err(error) = build(preview) else { + panic!("the preview plan was accepted"); + }; + error + .downcast_ref::() + .unwrap_or_else(|| panic!("not a semantic refusal: {error:#}")) + .to_string() + } + + #[test] + fn an_actors_preview_reaches_casework_and_the_coordinator_as_route_products() { + let build = build(actors()).unwrap(); + assert_eq!(build.product.id.as_str(), "permits"); + // Each actor carries its own BReg grant, and the build takes the + // first actor's as the generated client's profile. + assert_eq!(build.product.profile, "permit-applicant"); + assert_eq!( + serde_json::to_value(&build.route_products).unwrap(), + json!([ + {"id": "casework", "kind": "casework", "audience": "urn:review"}, + {"id": "permit-flow", "kind": "coordinator", "audience": "urn:flow"} + ]) + ); + } + + #[test] + fn an_actors_preview_refuses_each_mismatch_at_its_pointer() { + let mut both = actors(); + both["actor"] = json!("applicant"); + assert!(pointer(both).starts_with("dev.yaml /preview: ")); + + let mut stranger = actors(); + stranger["actors"]["stranger"] = json!({"breg": {"get": ["/v1/records/permits"]}}); + assert!(pointer(stranger).starts_with("dev.yaml /preview/actors/stranger: ")); + + // The officer has no Coordinator grant, so it cannot reach the Coordinator. + let mut ungranted = actors(); + ungranted["actors"]["officer"]["coordinator"] = json!({"get": ["/v1/runs/{runId}"]}); + assert!(pointer(ungranted).starts_with("dev.yaml /preview/actors/officer/coordinator: ")); + + let mut route = actors(); + route["actors"]["officer"]["casework"]["get"] = json!(["/v1/review-tasks/../admin"]); + assert!(pointer(route).starts_with("dev.yaml /preview/actors/officer/casework/get: ")); + + let mut two = actors(); + two["actors"]["officer"]["casework"]["get"] = json!(["/v1/review-tasks/{taskId}/{runId}"]); + assert!(pointer(two).starts_with("dev.yaml /preview/actors/officer/casework/get: ")); + } + + #[test] + fn a_single_actor_preview_keeps_one_breg_product() { + let mut single = json!({ + "actor": "applicant", "page": "/", "functions": ["assess-permit"], + "breg": {"get": ["/v1/records/permits"]} + }); + // Casework and the Coordinator are reachable only through actors. + assert!(pointer(single.clone()).starts_with("dev.yaml /preview: ")); + single["breg"] = json!({}); + single.as_object_mut().unwrap().remove("actor"); + assert!(pointer(single).starts_with("dev.yaml /preview")); + } +} diff --git a/crates/registry-rstack-dev/src/products.rs b/crates/registry-rstack-dev/src/products.rs index 903da9101f..06316b6c7b 100644 --- a/crates/registry-rstack-dev/src/products.rs +++ b/crates/registry-rstack-dev/src/products.rs @@ -120,8 +120,10 @@ pub(super) struct ApplicationLaunch { pub(super) workdir: PathBuf, pub(super) environment: BTreeMap, pub(super) reservation: TcpListener, - /// The preview's private function host port, held until the host starts. - pub(super) function_host: Option, + /// Further loopback ports the application binds, such as the preview's + /// private function host and each further actor's gateway, held until + /// it starts. + pub(super) held: Vec, pub(super) health_path: String, } @@ -138,6 +140,8 @@ struct FunctionHost { pub(super) struct PreparedApplication { pub(super) launch: ApplicationLaunch, + /// Each preview actor and the loopback origin its gateway serves. + pub(super) actors: Vec<(String, String)>, pub(super) client: Option, } @@ -703,7 +707,7 @@ impl<'a> ProductRunner<'a> { let log = open_log(self.root, "application-runtime")?; command.stdout(log.try_clone()?).stderr(log); drop(launch.reservation); - drop(launch.function_host); + drop(launch.held); let child = command .spawn() .context("cannot start application") @@ -751,7 +755,7 @@ impl<'a> ProductRunner<'a> { pub(super) fn prepare_application( &self, urls: &BTreeMap, - preview_artifact: Option<(&Path, &Path)>, + preview_artifact: Option<(&Path, &super::preview::PreviewAuthorization)>, ) -> Result { self.ensure_active()?; let preview = self.input.preview.as_ref(); @@ -787,12 +791,71 @@ impl<'a> ProductRunner<'a> { .map_err(operational)?; let address = reservation.local_addr()?; let origin = format!("http://{address}"); - let (run, client) = if let Some((_, authorization_file)) = preview_artifact { + let mut held = Vec::new(); + let mut actor_origins = Vec::new(); + let (run, client) = if let Some((_, authorization)) = preview_artifact { let build = &preview.context("missing captured preview build")?.plan; ensure!( bounded_version(node, Some(&prepare))? == super::preview::VERSION, "The built preview helper version does not match this Stack version." ); + let mut run_preview = json!({ + "productId": build.product.id, + "profile": build.product.profile, + "declarationDigest": build.declaration_digest, + "functionHost": self.function_host_input()?, + }); + if let Some(file) = &authorization.single { + run_preview["authorizationFile"] = json!(file); + } else { + // One gateway origin per actor: the first takes the run's + // reserved address, every further actor its own. + let mut actors = Vec::new(); + for (index, (name, files)) in authorization.actors.iter().enumerate() { + let (actor_origin, port) = if index == 0 { + (origin.clone(), address.port()) + } else { + let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)) + .context("reserve preview actor loopback listener") + .map_err(operational)?; + let address = listener.local_addr()?; + held.push(listener); + (format!("http://{address}"), address.port()) + }; + let person = &self.input.plan.people[name]; + let mut products = serde_json::Map::new(); + for (product, file) in files { + let id = if *product == Product::Breg { + build.product.id.as_str().to_owned() + } else { + build + .route_products + .iter() + .find(|route| route.kind == product.name()) + .context("missing preview route product")? + .id + .as_str() + .to_owned() + }; + let profile = (*product != Product::Coordinator) + .then(|| person.grants[product].profile.clone()); + products.insert( + id, + json!({ + "baseUrl": urls[product], + "audience": self.input.plan.product(*product).audience, + "profile": profile, + "authorizationFile": file, + }), + ); + } + actor_origins.push((name.clone(), actor_origin.clone())); + actors.push(json!({ + "name": name, "origin": actor_origin, "port": port, "products": products, + })); + } + run_preview["actors"] = json!(actors); + } ( json!({ "schema": plan.config_schema, @@ -804,13 +867,7 @@ impl<'a> ProductRunner<'a> { "baseUrl": urls[&Product::Breg], "audience": self.input.plan.product(Product::Breg).audience, }, - "preview": { - "productId": build.product.id, - "profile": build.product.profile, - "declarationDigest": build.declaration_digest, - "authorizationFile": authorization_file, - "functionHost": self.function_host_input()?, - }, + "preview": run_preview, }), None, ) @@ -888,14 +945,19 @@ impl<'a> ProductRunner<'a> { workdir: root.to_owned(), environment, reservation, - function_host: preview_artifact.and_then(|_| { - self.function_host - .as_ref() - .and_then(|host| host.listener.borrow_mut().take()) - }), + held: preview_artifact + .and_then(|_| { + self.function_host + .as_ref() + .and_then(|host| host.listener.borrow_mut().take()) + }) + .into_iter() + .chain(held) + .collect(), health_path: plan.health_path.clone(), }, client, + actors: actor_origins, }) } @@ -6036,7 +6098,7 @@ mod tests { workdir: root.to_path_buf(), environment, reservation, - function_host: None, + held: Vec::new(), health_path: "/health".to_owned(), }, port, diff --git a/docs/site/src/content/docs/configure/run-a-project-with-rstack-dev.mdx b/docs/site/src/content/docs/configure/run-a-project-with-rstack-dev.mdx index 67759b9477..140c495e17 100644 --- a/docs/site/src/content/docs/configure/run-a-project-with-rstack-dev.mdx +++ b/docs/site/src/content/docs/configure/run-a-project-with-rstack-dev.mdx @@ -68,6 +68,27 @@ origin policy and provide no authentication of local processes. The separate function listener requires a private handoff from the gateway and returns 401 to an anonymous function request. +To show several identities at once, replace `actor` and `breg` with `actors`. Each actor is a +declared person with a BReg grant, and lists the BReg, Casework and Coordinator paths it may +reach, with a grant for each of those products. The run serves the same built page to each +actor on its own loopback gateway origin, with that actor's own credential and profile for each +product, and reports the origins under `previewActors`. One origin per actor is a development +substitution for one origin with real sign-in, listed under `substitutions` in the report. +Casework and the Coordinator are reachable only through `actors`, by their service product ID +under `/registry/`, and the Coordinator path takes no query. + +```yaml +preview: + page: / + functions: [assess-permit] + actors: + applicant: + breg: {post: [/v1/actions/submit-application]} + coordinator: {get: [/v1/workflows/permit-flow, "/v1/runs/{runId}"], post: [/v1/runs]} + officer: + casework: {get: [/v1/review-tasks], post: ["/v1/review-tasks/{taskId}/decisions"]} +``` + A Coordinator `service-function` connection calls a preview function directly. The run reserves the function listener's loopback port before products start and writes one owner-only host key for the run, which the Coordinator presents as its bearer. The function diff --git a/products/platform/generated/dev/dev.v1alpha1.schema.json b/products/platform/generated/dev/dev.v1alpha1.schema.json index 4bcbfa7532..9ce15fb8db 100644 --- a/products/platform/generated/dev/dev.v1alpha1.schema.json +++ b/products/platform/generated/dev/dev.v1alpha1.schema.json @@ -1,5 +1,21 @@ { "$defs": { + "ActorRoutes": { + "additionalProperties": false, + "description": "The product paths one preview actor may reach, grouped by product and\nmethod.", + "properties": { + "breg": { + "$ref": "#/$defs/Routes" + }, + "casework": { + "$ref": "#/$defs/Routes" + }, + "coordinator": { + "$ref": "#/$defs/Routes" + } + }, + "type": "object" + }, "ApplicationPlan": { "additionalProperties": false, "description": "A generic Node application and its configuration command. All artifact paths are relative to the supplied built root.", @@ -513,11 +529,21 @@ "properties": { "actor": { "$ref": "#/$defs/LocalId", - "description": "Synthetic development identity whose checked BReg grant is used on the server." + "description": "Synthetic development identity whose checked BReg grant is used on the server. Use with `breg`, or use `actors` instead." + }, + "actors": { + "additionalProperties": { + "$ref": "#/$defs/ActorRoutes" + }, + "description": "One to eight synthetic identities, each served on its own loopback gateway origin over the same page, with the product paths it may reach. Use instead of `actor` and `breg`. Every actor needs a BReg grant, and a grant for each other product it reaches.", + "propertyNames": { + "$ref": "#/$defs/LocalId" + }, + "type": "object" }, "breg": { "$ref": "#/$defs/Routes", - "description": "BReg paths exposed to the page, grouped by method." + "description": "BReg paths exposed to the page of the single `actor`, grouped by method." }, "functions": { "description": "Declared functions to expose on the loopback preview origin.", @@ -533,9 +559,7 @@ } }, "required": [ - "actor", "page", - "breg", "functions" ], "type": "object" From 946fe78a5f9188eaf64ea72f2debeff037811681 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 22:22:52 +0000 Subject: [PATCH 141/183] fix(dev): pin the Coordinator BReg client's whole replacement and recheck Pin that render replaces the authored authorization whole, including an authored task authority, and that start refuses a runtime document whose bound connection changed after check. Drop the run-setup posture call, which the supervisor's forced development posture made unreachable, and cite the entry gate that refuses other postures. Say that the token carries the person's whole BReg grant and list the machine client keys. Refs #2891 Signed-off-by: Jeremi Joslin --- crates/registry-rstack-dev/src/bindings.rs | 81 ++----------------- crates/registry-rstack-dev/src/products.rs | 61 ++++++++++++++ .../run-a-project-with-rstack-dev.mdx | 14 ++-- .../src/content/docs/security/coordinator.mdx | 2 + 4 files changed, 79 insertions(+), 79 deletions(-) diff --git a/crates/registry-rstack-dev/src/bindings.rs b/crates/registry-rstack-dev/src/bindings.rs index 8723bc10db..14888ab08b 100644 --- a/crates/registry-rstack-dev/src/bindings.rs +++ b/crates/registry-rstack-dev/src/bindings.rs @@ -1,7 +1,8 @@ // SPDX-License-Identifier: Apache-2.0 -//! Run-local bindings between BReg and Casework. +//! Run-local bindings between the products of one development run: BReg and +//! Casework, and the Coordinator's Casework review producer and BReg client. //! -//! The token endpoint exists only for one development run. It accepts the two +//! The token endpoint exists only for one development run. It accepts the //! machine identities the plan explicitly binds, verifies their private-key //! JWT assertions, and mints the same bounded product token a named test person //! would receive. Keys, tokens, and assertion identifiers never enter reports @@ -268,21 +269,6 @@ impl Bindings { } } -/// The Coordinator bindings exist only in development: any other declared -/// posture refuses them before a machine identity is created. -pub(super) fn development_only( - declaration: std::result::Result< - registry_platform_config::DeclaredPosture, - registry_platform_config::PostureError, - >, -) -> Result<()> { - super::require_development(declaration).map_err(|(code, message, action)| { - anyhow::anyhow!( - "{code}: {message}. The Coordinator bindings are development only. {action}" - ) - }) -} - const COORDINATOR_BREG_CLIENT: &str = "/bindings/coordinatorBregClient"; fn validate_coordinator_breg_client( @@ -626,27 +612,6 @@ impl RuntimeBindings { input: Arc, issuer: Arc, origins: &BTreeMap, - ) -> Result { - Self::prepare_in( - root, - input, - issuer, - origins, - registry_platform_config::declared(None), - ) - } - - /// Prepare under the declared posture, which refuses every Coordinator - /// binding outside development before any machine identity is created. - pub(super) fn prepare_in( - root: &Path, - input: Arc, - issuer: Arc, - origins: &BTreeMap, - posture: std::result::Result< - registry_platform_config::DeclaredPosture, - registry_platform_config::PostureError, - >, ) -> Result { let bindings = &input.plan.bindings; if bindings.breg_review_authority.is_none() @@ -657,11 +622,6 @@ impl RuntimeBindings { return Ok(Self::default()); } bindings.validate(&input.plan)?; - if bindings.coordinator_review_producer.is_some() - || bindings.coordinator_breg_client.is_some() - { - development_only(posture)?; - } ensure!( bindings.coordinator_breg_client.is_none() || (origins.contains_key(&Product::Coordinator) @@ -3736,7 +3696,10 @@ mod tests { "registry": { "type": "breg", "baseUrl": "http://127.0.0.1:1", "profile": "authored-profile", "authorization": {"tokenEndpoint": "http://127.0.0.1:1/token", "clientId": "authored", - "scopes": ["registry:records:write"], "resource": "urn:elsewhere"} + "scopes": ["registry:records:write"], "resource": "urn:elsewhere", + // Members the binding never writes must not survive either. + "taskAuthority": {"issuer": "https://casework.example"}, + "authoredOnly": "authored-value"} }, "notices": {"type": "messaging", "baseUrl": "http://127.0.0.1:2"} }}); @@ -3835,15 +3798,6 @@ mod tests { assert!(runtime_tokens.block_on(wider.bearer_token()).is_err()); } - #[test] - fn coordinator_bindings_are_refused_outside_development() { - use registry_platform_config::declared_from; - use std::ffi::OsStr; - assert!(development_only(declared_from(None, None)).is_ok()); - assert!(development_only(declared_from(None, Some(OsStr::new("development")))).is_ok()); - assert!(development_only(declared_from(None, Some(OsStr::new("production")))).is_err()); - } - #[test] fn the_coordinator_breg_identity_is_a_dedicated_machine_person() { // Shared with the Casework context provider. @@ -3897,25 +3851,4 @@ mod tests { assert!(error.contains("/bindings/coordinatorBregClient"), "{error}"); assert!(error.contains("externalJwksUri"), "{error}"); } - - #[test] - fn run_setup_refuses_coordinator_bindings_outside_development() { - use registry_platform_config::declared_from; - use std::ffi::OsStr; - let root = tempfile::tempdir().unwrap(); - let refused = RuntimeBindings::prepare_in( - root.path(), - Arc::new(input(coordinator_breg_plan())), - Arc::new(Issuer::create(root.path()).unwrap()), - &coordinator_breg_origins(), - declared_from(None, Some(OsStr::new("production"))), - ); - let error = refused - .err() - .expect("a production posture is refused") - .to_string(); - assert!(error.contains("development only"), "{error}"); - // Nothing was registered for the refused run. - assert!(!root.path().join("coordinator-breg-client-key").exists()); - } } diff --git a/crates/registry-rstack-dev/src/products.rs b/crates/registry-rstack-dev/src/products.rs index 06316b6c7b..0fedefcd8b 100644 --- a/crates/registry-rstack-dev/src/products.rs +++ b/crates/registry-rstack-dev/src/products.rs @@ -6306,6 +6306,67 @@ mod tests { ) } + #[test] + fn start_rechecks_the_bound_breg_connection_it_renders() { + // check passed earlier; the runtime.yaml start renders has since + // changed the bound connection's profile. + let root = tempfile::tempdir().unwrap(); + let package = root.path().join("package"); + fs::create_dir(&package).unwrap(); + fs::write(package.join("SHA256SUMS"), b"test checksum file").unwrap(); + fs::write(root.path().join("workflow.yaml"), "project: {id: permits}").unwrap(); + fs::write( + root.path().join("runtime.yaml"), + "connections:\n registry:\n type: breg\n baseUrl: http://127.0.0.1:1\n profile: changed-profile\n", + ) + .unwrap(); + let mut input = breg_input(false); + input.plan.products = serde_json::from_value(json!([ + {"product": "breg", "project": ".", "audience": "registry"}, + {"product": "coordinator", "project": ".", "audience": "urn:example:local"} + ])) + .unwrap(); + input.plan.people.clear(); + input.plan.people.insert( + "coordinator".to_owned(), + serde_json::from_value(json!({ + "subject": "coordinator-service", "client": "coordinator-client", + "grants": {"breg": {"profile": "permit-coordinator", "scopes": ["registry:actions:invoke"]}} + })) + .unwrap(), + ); + input.plan.bindings = serde_json::from_value(json!({"coordinatorBregClient": { + "connection": "registry", "identity": "coordinator" + }})) + .unwrap(); + let terminate = AtomicBool::new(false); + let runner = ProductRunner::new(Arc::new(input), root.path(), &terminate).unwrap(); + let database = DatabaseUrls { + runtime: "postgresql://runtime@localhost/database".to_owned(), + migration: "postgresql://migration@localhost/database".to_owned(), + transport: DatabaseTransport::VerifiedTls, + }; + let error = runner + .additional_config( + Product::Coordinator, + root.path(), + "127.0.0.1:34567", + &package, + Some(&database), + ) + .unwrap_err(); + let refusal = error + .downcast_ref::() + .unwrap_or_else(|| panic!("not a semantic refusal: {error:#}")); + assert!( + refusal + .to_string() + .starts_with("dev.yaml /bindings/coordinatorBregClient/connection: ") + && refusal.to_string().contains("grant profile"), + "{refusal}" + ); + } + #[test] fn a_service_function_connection_names_the_preview_host_and_its_run_key() { use std::os::unix::fs::PermissionsExt; diff --git a/docs/site/src/content/docs/configure/run-a-project-with-rstack-dev.mdx b/docs/site/src/content/docs/configure/run-a-project-with-rstack-dev.mdx index 140c495e17..9222ef5c6b 100644 --- a/docs/site/src/content/docs/configure/run-a-project-with-rstack-dev.mdx +++ b/docs/site/src/content/docs/configure/run-a-project-with-rstack-dev.mdx @@ -1110,7 +1110,8 @@ bindings: identity: coordinator-service ``` -The identity's BReg grant is the only source of the connection's profile and scopes. +The identity's BReg grant is the only source of the connection's profile and scopes, and the +Coordinator's token carries that whole grant. Use a dedicated machine person: BReg attributes every Coordinator call to it, so `check` refuses an identity that another binding, a preview actor or a journey step uses, and a plan with `externalJwksUri`, whose products would not trust the run-local endpoint's tokens. @@ -1119,15 +1120,18 @@ with `externalJwksUri`, whose products would not trust the run-local endpoint's remains. BReg's own access profile and Action rules decide every call. `check` refuses, at `/bindings/coordinatorBregClient/connection`, a connection that is not a `breg` connection, delegates to task authority, or names a profile other than the identity's -BReg grant profile. Like every Coordinator binding, it is refused in any posture but -development. +BReg grant profile, and `start` checks the runtime document it renders again. Like every +`rstack dev` binding, it exists only in development: `rstack dev check` and `start` refuse any +other declared posture before reading the plan. {/* Evidence: crates/registry-rstack-dev/src/bindings.rs coordinatorBregClient, the_coordinator_breg_client_takes_profile_and_scopes_from_the_grant_only, the_coordinator_obtains_a_breg_token_for_its_bound_identity, - coordinator_bindings_are_refused_outside_development; + crates/registry-rstack-dev/src/lib.rs require_development; + crates/registry-rstack/tests/dev_run.rs start_and_check_refuse_explicit_production_and_invalid_postures; crates/registry-rstack-dev/src/products.rs checked_coordinator_breg_client, - a_coordinator_breg_client_refuses_each_mismatch_at_its_connection. */} + a_coordinator_breg_client_refuses_each_mismatch_at_its_connection, + start_rechecks_the_bound_breg_connection_it_renders. */} ### Explicit browser roles with separate human source credentials diff --git a/docs/site/src/content/docs/security/coordinator.mdx b/docs/site/src/content/docs/security/coordinator.mdx index 6c24b454a9..07c4ac4ee2 100644 --- a/docs/site/src/content/docs/security/coordinator.mdx +++ b/docs/site/src/content/docs/security/coordinator.mdx @@ -894,6 +894,8 @@ Enforcement: a Coordinator-called function a fixed placeholder bearer, never the key. It also generates a separate per-run review completion key, shared only by the run's Casework completion hook and Coordinator connection, and removes both keys first when the run stops. + Its Coordinator bindings also register per-run machine client signing keys for the review + producer and BReg connections, on the run-local token endpoint only. - The credential is distinct from every credential and product audience the runtime file declares. The runtime refuses a function `resource` equal to a product or external connection's `resource`, a task authority `bootstrapResource` or `exchangeAudience`, or the Coordinator's own From ee6f73b93d8be2ebf5c4ba2e10de00eb2215d27b Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 23:08:22 +0000 Subject: [PATCH 142/183] fix(dev): pin each preview actor's isolation and report its origins Fold the C2 review of the multi-actor preview. - Each actor's gateway options come from actorGatewayOptions, tested over two actors: each gateway sends only its own credential per product, and its own BReg credential to the function host. Route kinds are looked up as own properties only. - configure() refuses an actor credential file that is not owner-only or is a link. Rust tests cover one 0600 file per actor and reached product with that product's audience, the actor run input (extracted as preview_actor_inputs), and stop removing actor files. - The terminal prints one Actor line per actor and a Substitution line. The substitution is "per-actor gateway origin (development)" and is appended to the report's substitutions. - An actors preview names no Proposal author, since each actor's origin pins its own BReg profile; a register with Proposals gets a build refusal that names the single-actor form. - An actors preview refuses two projects of one routed product, and the refusals for an empty map, nine actors, a later actor without BReg and a non-routed product are tested. Each runtime config guard has its own message, asserted by its test. - GET /_rstack/actor answers {"actor": NAME} with the actor that origin serves and carries no credential. It answers 403 unless the request sends Registry-Client: page with no foreign Origin and no cross-site Sec-Fetch-Site. Guards whose tests came after the code were proven by mutation: 12 JavaScript and 8 Rust mutants, all killed. Signed-off-by: Jeremi Joslin --- clients/typescript/preview/build.mjs | 42 ++- clients/typescript/preview/config.mjs | 23 +- clients/typescript/preview/gateway.mjs | 45 +++- clients/typescript/preview/run.mjs | 23 +- .../typescript/preview/tests/preview.test.mjs | 186 ++++++++++++- .../typescript/tests/generate-preview.test.ts | 3 + crates/registry-rstack-dev/src/lib.rs | 83 +++++- crates/registry-rstack-dev/src/preview.rs | 251 +++++++++++++++++- crates/registry-rstack-dev/src/products.rs | 142 ++++++---- .../run-a-project-with-rstack-dev.mdx | 17 +- 10 files changed, 705 insertions(+), 110 deletions(-) diff --git a/clients/typescript/preview/build.mjs b/clients/typescript/preview/build.mjs index 57526d9838..3cda37aab9 100644 --- a/clients/typescript/preview/build.mjs +++ b/clients/typescript/preview/build.mjs @@ -40,24 +40,38 @@ async function copySource(path, target, exclude) { }) } -async function runGenerator(plan, staged) { +// An actors preview names no Proposal author: each actor's gateway pins its own +// BReg profile, so no single author profile fits every actor's page. +export function generatorArguments(plan, staged) { const { id, member, profile } = plan.product const project = plan.sourceProject ?? plan.product.project + return [ + join(clientPackage, 'registry-generate.js'), + '--register', member + '=' + project, + '--route-prefix', member + '=/registry/' + id, + ...(plan.preview.actors === undefined ? ['--author-profile', member + '=' + profile] : []), + '--preview', ...plan.preview.functions.flatMap(name => ['--preview-function', name]), + '--output', join(staged, 'generated', 'service.ts'), + ] +} + +export function generationError(stderr, actors) { + const diagnostic = stderr.trim() + if (actors && /has Proposals, so the service description needs authorProfiles/u.test(diagnostic)) { + return new Error(diagnostic + '\nAn actors preview cannot start Proposals: no single actor profile authors them. Use the single-actor form for a register with Proposals.') + } + if (/cannot start Proposals/u.test(diagnostic)) { + return new Error(diagnostic + '\nSelect a preview actor whose BReg profile can start Proposals.') + } + return new Error(diagnostic || 'Preview client generation failed. Check the native project and install matching BReg tools.') +} + +async function runGenerator(plan, staged) { try { - await runFile(process.execPath, [ - join(clientPackage, 'registry-generate.js'), - '--register', member + '=' + project, - '--route-prefix', member + '=/registry/' + id, - '--author-profile', member + '=' + profile, - '--preview', ...plan.preview.functions.flatMap(name => ['--preview-function', name]), - '--output', join(staged, 'generated', 'service.ts'), - ], { cwd: staged, timeout: 90_000, maxBuffer: 1024 * 1024 }) + await runFile(process.execPath, generatorArguments(plan, staged), + { cwd: staged, timeout: 90_000, maxBuffer: 1024 * 1024 }) } catch (error) { - const diagnostic = String(error.stderr ?? '').trim() - if (/cannot start Proposals/u.test(diagnostic)) { - throw new Error(diagnostic + '\nSelect a preview actor whose BReg profile can start Proposals.') - } - throw new Error(diagnostic || 'Preview client generation failed. Check the native project and install matching BReg tools.') + throw generationError(String(error.stderr ?? ''), plan.preview.actors !== undefined) } } diff --git a/clients/typescript/preview/config.mjs b/clients/typescript/preview/config.mjs index 658d7c37b4..3b04538b4a 100644 --- a/clients/typescript/preview/config.mjs +++ b/clients/typescript/preview/config.mjs @@ -61,7 +61,8 @@ export async function prepareRuntimeConfig({ artifact, deployment, run }) { } const { authorizationFile, functionHost, actors } = run.preview if (artifact.preview?.actors === undefined) { - if (actors !== undefined || typeof authorizationFile !== 'string' || !isAbsolute(authorizationFile)) { + if (actors !== undefined) throw new Error('A single-actor preview takes no actors.') + if (typeof authorizationFile !== 'string' || !isAbsolute(authorizationFile)) { throw new Error('The preview needs an owner-only run authorization file.') } } else { @@ -83,15 +84,19 @@ function checkActors(artifact, run, actors) { const names = Object.keys(artifact.preview.actors) const products = new Map((artifact.routeProducts ?? []).map(product => [product.id, product])) products.set(artifact.product.id, { id: artifact.product.id, kind: 'breg', audience: artifact.product.audience }) - if (run.preview.authorizationFile !== undefined || !Array.isArray(actors) - || actors.map(actor => actor?.name).join() !== names.join()) { + if (run.preview.authorizationFile !== undefined) { + throw new Error('An actors preview takes no single authorization file.') + } + if (!Array.isArray(actors) || actors.map(actor => actor?.name).join() !== names.join()) { throw new Error('The preview actors differ from the checked plan.') } const ports = new Set([run.preview.functionHost?.port, URL.parse(run.breg.baseUrl)?.port]) actors.forEach((actor, index) => { + if (index === 0 && (actor.origin !== run.origin || actor.port !== run.port)) { + throw new Error('The first preview actor must serve the run origin.') + } if (loopbackOrigin(actor.origin) !== `http://127.0.0.1:${actor.port}` || !Number.isInteger(actor.port) - || ports.has(actor.port) || ports.has(String(actor.port)) - || (index === 0 && (actor.origin !== run.origin || actor.port !== run.port))) { + || ports.has(actor.port) || ports.has(String(actor.port))) { throw new Error('Each preview actor needs its own reserved loopback address.') } ports.add(actor.port) @@ -102,8 +107,12 @@ function checkActors(artifact, run, actors) { throw new Error('A preview actor reaches a product it has no credential for.') } for (const [id, product] of entries) { - const checked = products.get(id) - if (!checked || loopbackOrigin(product.baseUrl) === actor.origin || product.audience !== checked.audience + const checked = Object.hasOwn(Object.fromEntries(products), id) ? products.get(id) : undefined + if (!checked) throw new Error('A preview actor has a credential for a product the plan does not route.') + if (loopbackOrigin(product.baseUrl) === actor.origin) { + throw new Error("A preview actor reaches a product on the actor's own origin.") + } + if (product.audience !== checked.audience || (checked.kind === 'coordinator' ? product.profile !== null : typeof product.profile !== 'string') || typeof product.authorizationFile !== 'string' || !isAbsolute(product.authorizationFile)) { throw new Error('A preview actor product differs from the checked plan.') diff --git a/clients/typescript/preview/gateway.mjs b/clients/typescript/preview/gateway.mjs index fac1fe52e8..51a40ebeda 100644 --- a/clients/typescript/preview/gateway.mjs +++ b/clients/typescript/preview/gateway.mjs @@ -2,7 +2,7 @@ import { constants } from 'node:fs' import { lstat, open, readdir } from 'node:fs/promises' import { createServer } from 'node:http' import { extname, join } from 'node:path' -import { healthPath, localId, loopbackOrigin } from './config.mjs' +import { healthPath, localId, loopbackOrigin, readAuthorization } from './config.mjs' import { maxRequestBodySize } from './host.mjs' const maxResponseSize = 4 * 1024 * 1024 @@ -63,6 +63,37 @@ export function compileRoutes(routes = {}) { } } +// The gateway options for each actor, in plan order. An actor's gateway gets +// only that actor's credential files, and for each product only the routes the +// actor declares for its kind. Functions run under the actor's own BReg +// credential, and an actor without one serves no function route. +export function actorGatewayOptions(artifact, actors) { + const policy = previewPolicy(artifact.preview) + const kinds = new Map((artifact.routeProducts ?? []).map(product => [product.id, product.kind])) + kinds.set(artifact.product.id, 'breg') + const none = compileRoutes({}) + return actors.map(actor => { + const routes = policy.actors.get(actor.name) + const products = Object.fromEntries(Object.entries(actor.products).map(([id, product]) => { + const kind = kinds.get(id) + return [id, { + origin: product.baseUrl, + profile: product.profile, + authorization: () => readAuthorization(product.authorizationFile), + allows: kind !== undefined && Object.hasOwn(routes, kind) ? routes[kind] : none, + }] + })) + const breg = Object.hasOwn(actor.products, artifact.product.id) ? actor.products[artifact.product.id] : undefined + return { + origin: actor.origin, + port: actor.port, + actor: actor.name, + products, + functionAuthorization: breg ? () => readAuthorization(breg.authorizationFile) : null, + } + }) +} + export function previewPolicy(preview) { const page = preview.page === '/' ? '/index.html' : preview.page if (typeof page !== 'string' || !/^\/(?:[A-Za-z0-9][A-Za-z0-9_-]*\/)*[A-Za-z0-9][A-Za-z0-9_-]*\.html$/u.test(page)) { @@ -192,6 +223,7 @@ export async function startPreviewGateway({ profile, breg, products: declaredProducts, + actor = null, application, authorization, functionAuthorization = authorization, @@ -242,6 +274,17 @@ export async function startPreviewGateway({ response.writeHead(204, responseSecurity).end() return } + // The actor this origin serves, so one built page can show its controls. + // It carries no credential and answers only the page. + if (actor !== null && method === 'GET' && rawTarget === '/_rstack/actor') { + if (headers['registry-client'] !== 'page' || (headers.origin !== undefined && headers.origin !== origin) + || (headers['sec-fetch-site'] !== undefined && headers['sec-fetch-site'] !== 'same-origin')) { + throw new RequestError(403, 'Open the service page to make this request') + } + response.writeHead(200, { ...responseSecurity, 'content-type': 'application/json' }) + .end(JSON.stringify({ actor })) + return + } if (!rawPath.startsWith('/') || rawTarget.length > 8192 || rawTarget.includes('#') || (rawPath !== '/' && !rawPath.slice(1).split('/').every(part => segment.test(part)))) { throw new RequestError(404, 'Unknown preview route') diff --git a/clients/typescript/preview/run.mjs b/clients/typescript/preview/run.mjs index 5a0e3dbfcc..1087cb883f 100644 --- a/clients/typescript/preview/run.mjs +++ b/clients/typescript/preview/run.mjs @@ -1,7 +1,7 @@ import { writeFile } from 'node:fs/promises' import { dirname, join } from 'node:path' import { artifactDirectory, checkRuntimeConfig, configEnvironment, readArtifact, readAuthorization, readHostKey } from './config.mjs' -import { compileRoutes, previewPolicy, startPreviewGateway } from './gateway.mjs' +import { actorGatewayOptions, startPreviewGateway } from './gateway.mjs' import { functionHostAuthorizer, startFunctionHost } from './host.mjs' async function run() { @@ -56,27 +56,10 @@ async function run() { } else { // One gateway per actor, each on its own origin over the same static // bytes, carrying only that actor's credentials and routes. - const policy = previewPolicy(artifact.preview) - const kinds = new Map((artifact.routeProducts ?? []).map(product => [product.id, product.kind])) - kinds.set(artifact.product.id, 'breg') // The run checks readiness on the first actor's origin, so that // gateway starts last, once every other actor's gateway listens. - for (const actor of [...actors].reverse()) { - const routes = policy.actors.get(actor.name) - const products = Object.fromEntries(Object.entries(actor.products).map(([id, product]) => [id, { - origin: product.baseUrl, - profile: product.profile, - authorization: () => readAuthorization(product.authorizationFile), - allows: routes[kinds.get(id)] ?? compileRoutes({}), - }])) - const breg = actor.products[artifact.product.id] - gateways.push(await startPreviewGateway({ - ...shared, - origin: actor.origin, - port: actor.port, - products, - functionAuthorization: breg ? () => readAuthorization(breg.authorizationFile) : null, - })) + for (const options of actorGatewayOptions(artifact, actors).reverse()) { + gateways.push(await startPreviewGateway({ ...shared, ...options })) } } } catch (error) { diff --git a/clients/typescript/preview/tests/preview.test.mjs b/clients/typescript/preview/tests/preview.test.mjs index 91dc842c9d..31bdb81919 100644 --- a/clients/typescript/preview/tests/preview.test.mjs +++ b/clients/typescript/preview/tests/preview.test.mjs @@ -5,9 +5,9 @@ import { join } from 'node:path' import { createServer, request } from 'node:http' import { test } from 'node:test' import { coordinatorBearer, functionHostAuthorizer, startFunctionHost } from '../host.mjs' -import { collectStaticFiles, compileRoutes, previewPolicy, startPreviewGateway } from '../gateway.mjs' +import { actorGatewayOptions, collectStaticFiles, compileRoutes, previewPolicy, startPreviewGateway } from '../gateway.mjs' import { configure, prepareRuntimeConfig, readHostKey } from '../config.mjs' -import { buildPreview } from '../build.mjs' +import { buildPreview, generationError, generatorArguments } from '../build.mjs' import { createHash } from 'node:crypto' test('preview policy matches both Record revision parameters without expanding methods or routes', () => { @@ -336,6 +336,7 @@ test('a gateway relays each product with its own credential, profile and routes' const gateway = await startPreviewGateway({ origin: null, port: 0, application: 'http://127.0.0.1:1', publicDirectory: root, preview: { page: '/', functions: ['assess-permit'], actors: { applicant: {} } }, + actor: 'applicant', functionAuthorization: () => 'Bearer applicant.breg', products: { 'permit-flow': { origin: origin(upstream), profile: null, authorization: () => 'Bearer applicant.coordinator', @@ -357,6 +358,15 @@ test('a gateway relays each product with its own credential, profile and routes' assert.equal((await refused.json()).code, 'profile.not-authorized') assert.equal((await post('/registry/permit-review/v1/review-tasks/' + task + '/decisions?accessProfile=permit-officer')).status, 403) assert.equal((await post('/registry/unknown/v1/runs')).status, 404) + // The page learns which actor this origin serves, and nothing else. + const actor = await fetch(gateway.origin + '/_rstack/actor', { headers: { 'registry-client': 'page' } }) + assert.equal(actor.status, 200) + assert.deepEqual(await actor.json(), { actor: 'applicant' }) + assert.equal((await fetch(gateway.origin + '/_rstack/actor')).status, 403) + for (const foreign of [{ origin: 'http://127.0.0.1:1' }, { 'sec-fetch-site': 'cross-site' }]) { + const answer = await fetch(gateway.origin + '/_rstack/actor', { headers: { 'registry-client': 'page', ...foreign } }) + assert.equal(answer.status, 403, JSON.stringify(foreign)) + } assert.deepEqual(seen.map(([, url, authorization]) => [url, authorization]), [ ['/v1/runs', 'Bearer applicant.coordinator'], ['/v1/review-tasks/' + task + '/decisions?accessProfile=permit-requester', 'Bearer applicant.casework'], @@ -408,18 +418,166 @@ test('prepare checks each actor origin, product, profile and credential against change(copy.preview.actors) return copy } - for (const invalid of [ - changed(actors => actors.reverse()), - changed(actors => { actors[1].port = 23456; actors[1].origin = 'http://127.0.0.1:23456' }), - changed(actors => { actors[1].port = 45678; actors[1].origin = 'http://127.0.0.1:45678' }), - changed(actors => { delete actors[1].products.casework }), - changed(actors => { actors[0].products['permit-flow'].profile = 'permit-starter' }), - changed(actors => { actors[1].products.casework.profile = null }), - changed(actors => { actors[1].products.casework.audience = 'urn:other' }), - changed(actors => { actors[1].products.casework.authorizationFile = 'relative' }), - changed(actors => { actors[1].products.unknown = actors[1].products.casework }), - { ...run, preview: { ...run.preview, authorizationFile: file('single') } }, + for (const [invalid, message] of [ + [changed(actors => actors.reverse()), /actors differ from the checked plan/u], + [changed(actors => { actors[0].port = 23458; actors[0].origin = 'http://127.0.0.1:23458' }), /first preview actor must serve the run origin/u], + [changed(actors => { actors[1].port = 23456; actors[1].origin = 'http://127.0.0.1:23456' }), /own reserved loopback address/u], + [changed(actors => { actors[1].port = 45678; actors[1].origin = 'http://127.0.0.1:45678' }), /own reserved loopback address/u], + [changed(actors => { delete actors[1].products.casework }), /reaches a product it has no credential for/u], + [changed(actors => { actors[0].products['permit-flow'].profile = 'permit-starter' }), /actor product differs from the checked plan/u], + [changed(actors => { actors[1].products.casework.profile = null }), /actor product differs from the checked plan/u], + [changed(actors => { actors[1].products.casework.audience = 'urn:other' }), /actor product differs from the checked plan/u], + [changed(actors => { actors[1].products.casework.authorizationFile = 'relative' }), /actor product differs from the checked plan/u], + [changed(actors => { actors[1].products.casework.baseUrl = 'http://127.0.0.1:23457' }), /product on the actor's own origin/u], + [changed(actors => { actors[1].products.unknown = actors[1].products.casework }), /product the plan does not route/u], + [{ ...run, preview: { ...run.preview, authorizationFile: file('single') } }, /takes no single authorization file/u], ]) { - await assert.rejects(prepareRuntimeConfig({ artifact, deployment, run: invalid }), JSON.stringify(invalid.preview.actors?.map(actor => actor.name))) + await assert.rejects(prepareRuntimeConfig({ artifact, deployment, run: invalid }), message) + } + // The single-actor form takes no actors list. + const single = { ...artifact, preview: { page: '/', functions: [], breg: {} } } + await assert.rejects(prepareRuntimeConfig({ artifact: single, deployment, run }), /single-actor preview takes no actors/u) +}) + +test('configure refuses an actor credential file that is not owner-only or is a link', async t => { + const root = await mkdtemp(join(tmpdir(), 'registry-preview-actor-files-')) + t.after(() => rm(root, { recursive: true })) + const deployment = join(root, 'service.yaml') + await writeFile(deployment, 'service declaration') + const declarationDigest = createHash('sha256').update('service declaration').digest('hex') + const artifact = { + declarationDigest, + product: { id: 'permits', member: 'permits', audience: 'urn:permits', profile: 'permit-applicant' }, + routeProducts: [], + preview: { page: '/', functions: [], actors: { applicant: { breg: { get: ['/v1/records/permits'] } } } }, + } + const file = name => join(root, name) + const runFile = file('application-run.json') + await writeFile(runFile, JSON.stringify({ + schema: 'registry-stack.local-service-preview/v1', + runId: 'fixture-run', origin: 'http://127.0.0.1:23456', port: 23456, insecureLocal: true, + breg: { baseUrl: 'http://127.0.0.1:34567', audience: 'urn:permits' }, + preview: { + productId: 'permits', profile: 'permit-applicant', declarationDigest, + functionHost: { port: 45678, keyFile: file('key') }, + actors: [{ name: 'applicant', origin: 'http://127.0.0.1:23456', port: 23456, products: { + permits: { baseUrl: 'http://127.0.0.1:34567', audience: 'urn:permits', profile: 'permit-applicant', authorizationFile: file('a-breg') }, + } }], + }, + })) + await writeFile(file('key'), 'synthetic-function-host-key-0123456789abcdefghij\n', { mode: 0o600 }) + await writeFile(file('a-breg'), 'Authorization: Bearer applicant.permits\n', { mode: 0o600 }) + await configure({ artifact, deployment, runFile }) + await chmod(file('a-breg'), 0o640) + await assert.rejects(configure({ artifact, deployment, runFile }), /owner-only/u) + await rm(file('a-breg')) + await writeFile(file('elsewhere'), 'Authorization: Bearer applicant.permits\n', { mode: 0o600 }) + await symlink(file('elsewhere'), file('a-breg')) + await assert.rejects(configure({ artifact, deployment, runFile }), /owner-only/u) +}) + +test('each actor gateway carries only its own credentials and routes', async t => { + const root = await mkdtemp(join(tmpdir(), 'registry-preview-isolation-')) + t.after(() => rm(root, { recursive: true })) + await writeFile(join(root, 'index.html'), '

Page

') + const seen = [] + const upstream = createServer((request, response) => { + seen.push([request.url, request.headers.authorization]) + response.writeHead(200, { 'content-type': 'application/json' }).end('{}') + }) + await new Promise(resolve => upstream.listen(0, '127.0.0.1', resolve)) + t.after(() => new Promise(resolve => upstream.close(resolve))) + const base = 'http://127.0.0.1:' + upstream.address().port + const artifact = { + product: { id: 'permits', audience: 'urn:permits', profile: 'permit-applicant' }, + routeProducts: [ + { id: 'casework', kind: 'casework', audience: 'urn:review' }, + { id: 'permit-flow', kind: 'coordinator', audience: 'urn:flow' }, + ], + preview: { page: '/', functions: ['assess-permit'], actors: { + applicant: { breg: { post: ['/v1/actions/submit-application'] }, coordinator: { post: ['/v1/runs'] } }, + officer: { casework: { get: ['/v1/review-tasks'] } }, + } }, } + const credential = async (name, id) => { + const path = join(root, name + '-' + id) + await writeFile(path, 'Authorization: Bearer ' + name + '.' + id + '\n', { mode: 0o600 }) + return path + } + const product = async (name, id, profile) => ({ baseUrl: base, audience: 'urn:' + id, profile, authorizationFile: await credential(name, id) }) + const actors = [ + { name: 'applicant', origin: null, port: 0, products: { + permits: await product('applicant', 'permits', 'permit-applicant'), + 'permit-flow': await product('applicant', 'permit-flow', null), + } }, + { name: 'officer', origin: null, port: 0, products: { + permits: await product('officer', 'permits', 'permit-reader'), + casework: await product('officer', 'casework', 'permit-officer'), + } }, + ] + const options = actorGatewayOptions(artifact, actors) + assert.deepEqual(options.map(option => option.actor), ['applicant', 'officer']) + const gateways = {} + for (const option of options) { + gateways[option.actor] = await startPreviewGateway({ + ...option, application: base, publicDirectory: root, preview: artifact.preview, functionKey: 'k'.repeat(32), + }) + t.after(() => gateways[option.actor].close()) + } + const call = async (name, method, path) => { + const gateway = gateways[name] + const response = await fetch(gateway.origin + path, { + method, headers: { origin: gateway.origin, 'registry-client': 'page', 'content-type': 'application/json' }, + body: method === 'POST' ? '{}' : undefined, + }) + return response.status + } + assert.equal(await call('applicant', 'POST', '/registry/permits/v1/actions/submit-application'), 200) + assert.equal(await call('applicant', 'POST', '/registry/permit-flow/v1/runs'), 200) + assert.equal(await call('applicant', 'GET', '/registry/casework/v1/review-tasks'), 404) + assert.equal(await call('applicant', 'POST', '/api/functions/assess-permit'), 200) + assert.equal(await call('officer', 'GET', '/registry/casework/v1/review-tasks'), 200) + assert.equal(await call('officer', 'POST', '/registry/permit-flow/v1/runs'), 404) + assert.equal(await call('officer', 'POST', '/registry/permits/v1/actions/submit-application'), 404) + assert.equal(await call('officer', 'POST', '/api/functions/assess-permit'), 200) + assert.deepEqual(seen, [ + ['/v1/actions/submit-application?accessProfile=permit-applicant', 'Bearer applicant.permits'], + ['/v1/runs', 'Bearer applicant.permit-flow'], + ['/functions/assess-permit', 'Bearer applicant.permits'], + ['/v1/review-tasks?accessProfile=permit-officer', 'Bearer officer.casework'], + ['/functions/assess-permit', 'Bearer officer.permits'], + ]) +}) + +test('a gateway without a function credential serves no function route', async t => { + const root = await mkdtemp(join(tmpdir(), 'registry-preview-nofunction-')) + t.after(() => rm(root, { recursive: true })) + await writeFile(join(root, 'index.html'), '

Page

') + const gateway = await startPreviewGateway({ + origin: null, port: 0, application: 'http://127.0.0.1:1', publicDirectory: root, + preview: { page: '/', functions: ['assess-permit'], actors: { officer: {} } }, + actor: 'officer', functionAuthorization: null, + products: { casework: { origin: 'http://127.0.0.1:2', profile: 'permit-officer', + authorization: () => 'Bearer officer.casework', allows: compileRoutes({}) } }, + }) + t.after(() => gateway.close()) + const answer = await fetch(gateway.origin + '/api/functions/assess-permit', { + method: 'POST', headers: { origin: gateway.origin, 'registry-client': 'page', 'content-type': 'application/json' }, body: '{}', + }) + assert.equal(answer.status, 404) +}) + +test('an actors preview names no Proposal author and refuses a register with Proposals', () => { + const product = { id: 'permits', member: 'permits', project: '/project', profile: 'permit-applicant' } + const single = generatorArguments({ product, preview: { functions: ['assess-permit'] } }, '/staged') + assert.deepEqual(single.slice(single.indexOf('--author-profile'), single.indexOf('--author-profile') + 2), + ['--author-profile', 'permits=permit-applicant']) + const actors = generatorArguments({ product, preview: { functions: ['assess-permit'], actors: { applicant: {} } } }, '/staged') + assert.equal(actors.includes('--author-profile'), false) + assert.match(generationError('The register permits has Proposals, so the service description needs authorProfiles.', true).message, + /actors preview cannot start Proposals/u) + assert.match(generationError('The authorProfile "x" cannot start Proposals in permits.', false).message, + /Select a preview actor whose BReg profile can start Proposals/u) + assert.equal(generationError('generator diagnostic', true).message, 'generator diagnostic') + assert.match(generationError('', true).message, /Preview client generation failed/u) }) diff --git a/clients/typescript/tests/generate-preview.test.ts b/clients/typescript/tests/generate-preview.test.ts index dfc1e43ffc..e9c19f0cc0 100644 --- a/clients/typescript/tests/generate-preview.test.ts +++ b/clients/typescript/tests/generate-preview.test.ts @@ -43,6 +43,9 @@ test('preview generation splits page and function bindings and keeps request cre const refused = generateFrom(facility, '--author-profile', 'licences=facility-reader') assert.equal(refused.status, 1) assert.match(refused.stderr, /cannot start Proposals/u) + const unnamed = generateFrom(facility) + assert.equal(unnamed.status, 1) + assert.match(unnamed.stderr, /has Proposals, so the service description needs authorProfiles/u) const duplicate = generate('--preview-function', 'renew', '--preview-function', 'renew') assert.equal(duplicate.status, 1) assert.match(duplicate.stderr, /duplicate preview function/iu) diff --git a/crates/registry-rstack-dev/src/lib.rs b/crates/registry-rstack-dev/src/lib.rs index 0ea244094f..4b350848a6 100644 --- a/crates/registry-rstack-dev/src/lib.rs +++ b/crates/registry-rstack-dev/src/lib.rs @@ -755,6 +755,20 @@ fn error_report(error: &anyhow::Error) -> (Value, u8) { (report, code) } +/// The substitution a multi-actor preview makes for development. +const PREVIEW_ACTOR_SUBSTITUTION: &str = "per-actor gateway origin (development)"; + +/// Report each actor's origin and append the development substitution: one +/// gateway origin per actor, over the same page bytes, stands in for one +/// origin with sign-in. +fn add_preview_actors(report: &mut Value, actors: &BTreeMap) { + report["previewActors"] = json!(actors); + match report["substitutions"].as_array_mut() { + Some(substitutions) => substitutions.push(json!(PREVIEW_ACTOR_SUBSTITUTION)), + None => report["substitutions"] = json!([PREVIEW_ACTOR_SUBSTITUTION]), + } +} + fn emit(output: &mut dyn Write, report: &Value, machine: bool) -> std::io::Result<()> { if machine { return writeln!(output, "{report}"); @@ -862,6 +876,20 @@ fn emit(output: &mut dyn Write, report: &Value, machine: bool) -> std::io::Resul if let Some(application) = report["application"].as_str() { writeln!(output, " Application {application}")?; } + for (name, origin) in report["previewActors"].as_object().into_iter().flatten() { + writeln!( + output, + " Actor {name} {}", + origin.as_str().unwrap_or_default() + )?; + } + for substitution in report["substitutions"].as_array().into_iter().flatten() { + writeln!( + output, + " Substitution {}", + substitution.as_str().unwrap_or_default() + )?; + } for journey in report["scenarios"].as_array().into_iter().flatten() { let Some(result) = journey["result"].as_str() else { continue; @@ -1789,10 +1817,7 @@ fn worker(root: &Path, output: &mut dyn Write) -> Result<()> { }); add_run_addresses(&mut report, &input.plan, application); if let Some(actors) = &preview_actors { - // A development substitution: one gateway origin per actor, over - // the same page bytes, stands in for one origin with sign-in. - report["previewActors"] = json!(actors); - report["substitutions"] = json!(["one preview gateway origin per actor"]); + add_preview_actors(&mut report, actors); } if let (Some(state), Some(key)) = (&project_state, &input.project_key) { @@ -3187,6 +3212,46 @@ mod tests { assert!(text.contains("Application http://127.0.0.1:4201"), "{text}"); } + #[test] + fn preview_actors_append_the_development_substitution_and_print_each_origin() { + let mut report = json!({ + "run_id": RUN_ID, "status": "ready", + "application": "http://127.0.0.1:4201/", + "substitutions": ["earlier substitution"], + }); + add_preview_actors( + &mut report, + &BTreeMap::from([ + ("applicant".to_owned(), "http://127.0.0.1:4201/".to_owned()), + ("officer".to_owned(), "http://127.0.0.1:4202/".to_owned()), + ]), + ); + assert_eq!( + report["substitutions"], + json!(["earlier substitution", PREVIEW_ACTOR_SUBSTITUTION]) + ); + assert_eq!( + report["previewActors"], + json!({"applicant": "http://127.0.0.1:4201/", "officer": "http://127.0.0.1:4202/"}) + ); + let mut output = Vec::new(); + emit(&mut output, &report, false).unwrap(); + let text = String::from_utf8(output).unwrap(); + assert!( + text.contains(" Actor applicant http://127.0.0.1:4201/\n"), + "{text}" + ); + assert!( + text.contains(" Actor officer http://127.0.0.1:4202/\n"), + "{text}" + ); + assert!( + text.contains(" Substitution earlier substitution\n") + && text.contains(" Substitution per-actor gateway origin (development)\n"), + "{text}" + ); + } + #[test] fn human_run_report_gives_each_product_one_line_that_starts_with_its_name() { // The tutorials read a product's address with @@ -3966,6 +4031,13 @@ mod tests { "completion-key", ) .unwrap(); + let actor_files = [ + format!("{}-applicant-breg", preview::AUTHORIZATION_FILE), + format!("{}-officer-casework", preview::AUTHORIZATION_FILE), + ]; + for file in &actor_files { + fs::write(root.join(file), "Authorization: Bearer token\n").unwrap(); + } fs::write(root.join(REPORT), "{}").unwrap(); // A non-empty directory at the removal name makes the rename fail, as // an interrupted deletion would leave the run behind. @@ -3977,6 +4049,9 @@ mod tests { assert!(!root.join(products::FIELD_KEY).exists()); assert!(!root.join(products::FUNCTION_HOST_KEY).exists()); assert!(!root.join(bindings::COORDINATOR_COMPLETION_KEY).exists()); + for file in &actor_files { + assert!(!root.join(file).exists(), "{file}"); + } assert!(root.join(REPORT).exists()); } diff --git a/crates/registry-rstack-dev/src/preview.rs b/crates/registry-rstack-dev/src/preview.rs index 68c0b77b57..ef563ec312 100644 --- a/crates/registry-rstack-dev/src/preview.rs +++ b/crates/registry-rstack-dev/src/preview.rs @@ -308,6 +308,19 @@ impl Preview { }) .collect(); route_products.sort_by(|a, b| a.kind.cmp(&b.kind)); + // Each actor holds one credential per product kind, so a second + // project of a routed kind would have no credential to reach it. + if route_products + .windows(2) + .any(|pair| pair[0].kind == pair[1].kind) + { + return plan::refuse( + "/preview/actors", + "An actors preview reaches one project of each routed product.", + "Keep one Casework project and one Coordinator project in service.yaml.", + ) + .map_err(Into::into); + } let product = service .products .into_iter() @@ -760,8 +773,13 @@ functions: [assess-permit] } fn build(preview: Value) -> Result { + build_with(preview, |_| {}) + } + + fn build_with(preview: Value, edit: impl FnOnce(&Path)) -> Result { let root = tempfile::tempdir().unwrap(); project(root.path()); + edit(root.path()); let plan = native(preview); plan.preview .as_ref() @@ -770,7 +788,11 @@ functions: [assess-permit] } fn pointer(preview: Value) -> String { - let Err(error) = build(preview) else { + refusal(build(preview)) + } + + fn refusal(built: Result) -> String { + let Err(error) = built else { panic!("the preview plan was accepted"); }; error @@ -819,6 +841,233 @@ functions: [assess-permit] assert!(pointer(two).starts_with("dev.yaml /preview/actors/officer/casework/get: ")); } + #[test] + fn an_actors_preview_refuses_an_empty_or_oversized_map_and_a_later_actor_without_breg() { + let mut empty = actors(); + empty["actors"] = json!({}); + assert_eq!( + pointer(empty), + "dev.yaml /preview/actors: A preview has one to eight actors. Next: Declare between one and eight actors." + ); + + // Two declared actors and seven more make nine. + let mut nine = actors(); + for index in 0..7 { + nine["actors"][format!("extra{index}")] = json!({}); + } + assert_eq!( + pointer(nine), + "dev.yaml /preview/actors: A preview has one to eight actors. Next: Declare between one and eight actors." + ); + + // The officer is not first in name order, and has only a Casework grant. + let mut plan = native(actors()); + plan.people + .get_mut("officer") + .unwrap() + .grants + .remove(&Product::Breg); + let root = tempfile::tempdir().unwrap(); + project(root.path()); + assert_eq!( + refusal(plan.preview.as_ref().unwrap().build_plan(root.path(), &plan)), + "dev.yaml /preview/actors/officer: Each preview actor needs a BReg grant. Next: Give the person a BReg role." + ); + } + + #[test] + fn an_actors_preview_refuses_a_product_it_cannot_route() { + let messaging = build_with(actors(), |root| { + fs::create_dir_all(root.join("messaging")).unwrap(); + fs::write(root.join("messaging/messaging.yaml"), "{}\n").unwrap(); + fs::write( + root.join("service.yaml"), + SERVICE.replace("ui: {", " messaging: {path: messaging}\nui: {"), + ) + .unwrap(); + }); + assert!(refusal(messaging).starts_with("dev.yaml /preview: ")); + } + + #[test] + fn an_actors_preview_refuses_two_projects_of_one_routed_product() { + let two = build_with(actors(), |root| { + fs::create_dir_all(root.join("second")).unwrap(); + fs::write(root.join("second/workflow.yaml"), "{}\n").unwrap(); + fs::write( + root.join("service.yaml"), + SERVICE.replace( + " permit-flow: {path: coordinator}\n", + " permit-flow: {path: coordinator}\n second-flow: {path: second}\n", + ), + ) + .unwrap(); + }); + assert_eq!( + refusal(two), + "dev.yaml /preview/actors: An actors preview reaches one project of each routed product. Next: Keep one Casework project and one Coordinator project in service.yaml." + ); + } + + fn run_input() -> RunInput { + let mut plan = serde_json::to_value(native(actors())).unwrap(); + plan["issuer"] = json!("http://127.0.0.1:45678"); + serde_json::from_value(json!({ + "run_id": "0123456789abcdef0123456789abcdef", + "project": "/project", + "ttl_seconds": 1800, + "plan": plan, + "schema_people": [], + "breg_authority": {"principal": "sub", "purpose": false, + "requires_postgis": false, "encrypts_fields": false, "named_clients": []}, + "casework_principals": {"permit-requester": "sub", "permit-officer": "sub"}, + "binaries": {} + })) + .unwrap() + } + + fn claims(file: &Path) -> Value { + use base64::Engine as _; + let line = fs::read_to_string(file).unwrap(); + let token = line + .strip_prefix("Authorization: Bearer ") + .unwrap() + .trim_end(); + let payload = token.split('.').nth(1).unwrap(); + serde_json::from_slice( + &base64::engine::general_purpose::URL_SAFE_NO_PAD + .decode(payload) + .unwrap(), + ) + .unwrap() + } + + #[test] + fn authorization_writes_one_owner_only_file_per_actor_and_reached_product() { + use std::os::unix::fs::PermissionsExt; + let root = tempfile::tempdir().unwrap(); + let signer = Issuer::create(root.path()).unwrap(); + let mut input = run_input(); + // The officer reaches BReg only through its always-present grant. + input + .plan + .preview + .as_mut() + .unwrap() + .actors + .as_mut() + .unwrap() + .get_mut(&LocalId::new("officer").unwrap()) + .unwrap() + .breg = Routes::default(); + let written = authorization(root.path(), &input, &signer, clock().unwrap() + 1800).unwrap(); + assert!(written.single.is_none()); + let expected = [ + ("applicant", Product::Breg, "urn:permits", "applicant"), + ("applicant", Product::Casework, "urn:review", "applicant"), + ("applicant", Product::Coordinator, "urn:flow", "applicant"), + ("officer", Product::Breg, "urn:permits", "officer"), + ("officer", Product::Casework, "urn:review", "officer"), + ]; + let listed: Vec<(&str, Product)> = written + .actors + .iter() + .flat_map(|(name, files)| files.keys().map(move |product| (name.as_str(), *product))) + .collect(); + assert_eq!( + listed, + expected + .iter() + .map(|(name, product, ..)| (*name, *product)) + .collect::>() + ); + for (name, product, audience, subject) in expected { + let file = &written.actors[name][&product]; + assert_eq!( + file, + &root + .path() + .join(format!("{AUTHORIZATION_FILE}-{name}-{}", product.name())) + ); + assert_eq!( + fs::metadata(file).unwrap().permissions().mode() & 0o777, + 0o600 + ); + let claims = claims(file); + assert_eq!(claims["aud"], audience, "{name} {product:?}"); + assert_eq!(claims["sub"], subject, "{name} {product:?}"); + } + } + + #[test] + fn each_actor_run_input_carries_its_own_origin_products_and_profiles() { + let build = build(actors()).unwrap(); + let plan = native(actors()); + let file = |name: &str| PathBuf::from(format!("/run/{name}")); + let authorization = PreviewAuthorization { + single: None, + actors: BTreeMap::from([ + ( + "applicant".to_owned(), + BTreeMap::from([ + (Product::Breg, file("a-breg")), + (Product::Coordinator, file("a-flow")), + ]), + ), + ( + "officer".to_owned(), + BTreeMap::from([ + (Product::Breg, file("o-breg")), + (Product::Casework, file("o-casework")), + ]), + ), + ]), + }; + let urls = BTreeMap::from([ + (Product::Breg, "http://127.0.0.1:34567".to_owned()), + (Product::Casework, "http://127.0.0.1:34568".to_owned()), + (Product::Coordinator, "http://127.0.0.1:34569".to_owned()), + ]); + let super::super::products::PreviewActorInputs { + actors, + origins, + held, + } = super::super::products::preview_actor_inputs( + &plan, + &build, + &authorization, + &urls, + ("http://127.0.0.1:23456", 23456), + ) + .unwrap(); + assert_eq!(held.len(), 1); + let officer = format!("http://{}", held[0].local_addr().unwrap()); + assert_eq!( + origins, + [ + ("applicant".to_owned(), "http://127.0.0.1:23456".to_owned()), + ("officer".to_owned(), officer.clone()), + ] + ); + assert_eq!( + Value::from(actors), + json!([ + {"name": "applicant", "origin": "http://127.0.0.1:23456", "port": 23456, "products": { + "permits": {"baseUrl": "http://127.0.0.1:34567", "audience": "urn:permits", + "profile": "permit-applicant", "authorizationFile": "/run/a-breg"}, + "permit-flow": {"baseUrl": "http://127.0.0.1:34569", "audience": "urn:flow", + "profile": null, "authorizationFile": "/run/a-flow"}, + }}, + {"name": "officer", "origin": officer, "port": held[0].local_addr().unwrap().port(), "products": { + "permits": {"baseUrl": "http://127.0.0.1:34567", "audience": "urn:permits", + "profile": "permit-reader", "authorizationFile": "/run/o-breg"}, + "casework": {"baseUrl": "http://127.0.0.1:34568", "audience": "urn:review", + "profile": "permit-officer", "authorizationFile": "/run/o-casework"}, + }}, + ]) + ); + } + #[test] fn a_single_actor_preview_keeps_one_breg_product() { let mut single = json!({ diff --git a/crates/registry-rstack-dev/src/products.rs b/crates/registry-rstack-dev/src/products.rs index 0fedefcd8b..916f58479c 100644 --- a/crates/registry-rstack-dev/src/products.rs +++ b/crates/registry-rstack-dev/src/products.rs @@ -808,52 +808,19 @@ impl<'a> ProductRunner<'a> { if let Some(file) = &authorization.single { run_preview["authorizationFile"] = json!(file); } else { - // One gateway origin per actor: the first takes the run's - // reserved address, every further actor its own. - let mut actors = Vec::new(); - for (index, (name, files)) in authorization.actors.iter().enumerate() { - let (actor_origin, port) = if index == 0 { - (origin.clone(), address.port()) - } else { - let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)) - .context("reserve preview actor loopback listener") - .map_err(operational)?; - let address = listener.local_addr()?; - held.push(listener); - (format!("http://{address}"), address.port()) - }; - let person = &self.input.plan.people[name]; - let mut products = serde_json::Map::new(); - for (product, file) in files { - let id = if *product == Product::Breg { - build.product.id.as_str().to_owned() - } else { - build - .route_products - .iter() - .find(|route| route.kind == product.name()) - .context("missing preview route product")? - .id - .as_str() - .to_owned() - }; - let profile = (*product != Product::Coordinator) - .then(|| person.grants[product].profile.clone()); - products.insert( - id, - json!({ - "baseUrl": urls[product], - "audience": self.input.plan.product(*product).audience, - "profile": profile, - "authorizationFile": file, - }), - ); - } - actor_origins.push((name.clone(), actor_origin.clone())); - actors.push(json!({ - "name": name, "origin": actor_origin, "port": port, "products": products, - })); - } + let PreviewActorInputs { + actors, + origins, + held: listeners, + } = preview_actor_inputs( + &self.input.plan, + build, + authorization, + urls, + (&origin, address.port()), + )?; + held.extend(listeners); + actor_origins.extend(origins); run_preview["actors"] = json!(actors); } ( @@ -4263,6 +4230,89 @@ fn checked_coordinator_review_runtime(plan: &Plan, casework: &Path, runtime: &Va Ok(()) } +/// The run input for each preview actor, in name order: one gateway origin +/// per actor, the first on the run's reserved address and every further actor +/// on its own reserved listener, with a credential file, audience and pinned +/// profile (none for the Coordinator) for each product the actor reaches. +pub(super) struct PreviewActorInputs { + /// The `preview.actors` run input. + pub actors: Vec, + /// Each actor's name and gateway origin. + pub origins: Vec<(String, String)>, + /// The further actors' reserved listeners, held until their gateways bind. + pub held: Vec, +} + +pub(super) fn preview_actor_inputs( + plan: &Plan, + build: &super::preview::BuildPlan, + authorization: &super::preview::PreviewAuthorization, + urls: &BTreeMap, + first: (&str, u16), +) -> Result { + let mut actors = Vec::new(); + let mut origins = Vec::new(); + let mut held = Vec::new(); + for (index, (name, files)) in authorization.actors.iter().enumerate() { + let (actor_origin, port) = if index == 0 { + (first.0.to_owned(), first.1) + } else { + let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)) + .context("reserve preview actor loopback listener") + .map_err(operational)?; + let address = listener.local_addr()?; + held.push(listener); + (format!("http://{address}"), address.port()) + }; + let person = plan.people.get(name).context("missing preview actor")?; + let mut products = serde_json::Map::new(); + for (product, file) in files { + let id = if *product == Product::Breg { + build.product.id.as_str().to_owned() + } else { + build + .route_products + .iter() + .find(|route| route.kind == product.name()) + .context("missing preview route product")? + .id + .as_str() + .to_owned() + }; + let profile = if *product == Product::Coordinator { + None + } else { + Some( + person + .grants + .get(product) + .context("missing preview actor grant")? + .profile + .clone(), + ) + }; + products.insert( + id, + json!({ + "baseUrl": urls.get(product).context("missing preview product origin")?, + "audience": plan.product(*product).audience, + "profile": profile, + "authorizationFile": file, + }), + ); + } + origins.push((name.clone(), actor_origin.clone())); + actors.push(json!({ + "name": name, "origin": actor_origin, "port": port, "products": products, + })); + } + Ok(PreviewActorInputs { + actors, + origins, + held, + }) +} + /// Refuses, at the dev.yaml pointer, a Coordinator BReg client binding whose /// connection is not a `breg` connection without task authority, using the /// identity's BReg grant profile. `check` runs this before any product starts diff --git a/docs/site/src/content/docs/configure/run-a-project-with-rstack-dev.mdx b/docs/site/src/content/docs/configure/run-a-project-with-rstack-dev.mdx index 9222ef5c6b..f4bc234341 100644 --- a/docs/site/src/content/docs/configure/run-a-project-with-rstack-dev.mdx +++ b/docs/site/src/content/docs/configure/run-a-project-with-rstack-dev.mdx @@ -72,10 +72,21 @@ To show several identities at once, replace `actor` and `breg` with `actors`. Ea declared person with a BReg grant, and lists the BReg, Casework and Coordinator paths it may reach, with a grant for each of those products. The run serves the same built page to each actor on its own loopback gateway origin, with that actor's own credential and profile for each -product, and reports the origins under `previewActors`. One origin per actor is a development -substitution for one origin with real sign-in, listed under `substitutions` in the report. +product. The terminal prints one `Actor NAME URL` line for each actor, and the JSON report +lists the same origins under `previewActors`. The `application` URL is the first actor's, in +name order. One origin per actor is a development substitution for one origin with real +sign-in: the terminal prints it on a `Substitution` line, and the JSON report lists it under +`substitutions`. Casework and the Coordinator are reachable only through `actors`, by their service product ID -under `/registry/`, and the Coordinator path takes no query. +under `/registry/`, and the Coordinator path takes no query. An actors preview reaches one +Casework project and one Coordinator project at most. +Every actor has a BReg grant, so every preview function is callable from every actor's origin, +and runs under that actor's own BReg credential. +The generated client names no Proposal author in an actors preview, because each actor's +origin pins its own BReg profile. A register with Proposals therefore needs the single-actor +form, and the build refuses it in an actors preview. +A path may hold one `{recordId}`, `{taskId}` or `{runId}` segment, each matching only a UUID, +for any product. The name documents the path and does not restrict where it may appear. ```yaml preview: From ea1630bcc08de6bb91b10731e83bd9a09587d852 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 23:08:27 +0000 Subject: [PATCH 143/183] fix(dev): configure the review producer's completion destination for identity facts bf9631df0 bound Casework's completion destination only in the run's rendered runtime. The Casework identity-facts runtime that rstack dev check builds never declared it, so the real caseworkctl refused every plan with bindings.coordinatorReviewProducer (casework.runtime.unconfigured-review-completion-destination). The facts runtime now declares the bound destination as the run does. When the binding is missing or its completionDestination differs from the producer's, Casework's refusal at the Casework project path now comes before the binding's own dev.yaml diagnostic, because the binding check needs the grants the facts produce. The binding docs state that order, and the permit-review dev_run case pins it. Signed-off-by: Jeremi Joslin --- crates/registry-rstack-dev/src/bindings.rs | 2 +- crates/registry-rstack-dev/src/dev_facts.rs | 60 ++++++++++++++++++- crates/registry-rstack-dev/src/roles.rs | 4 ++ .../run-a-project-with-rstack-dev.mdx | 6 ++ 4 files changed, 70 insertions(+), 2 deletions(-) diff --git a/crates/registry-rstack-dev/src/bindings.rs b/crates/registry-rstack-dev/src/bindings.rs index 14888ab08b..3a2bef870a 100644 --- a/crates/registry-rstack-dev/src/bindings.rs +++ b/crates/registry-rstack-dev/src/bindings.rs @@ -593,7 +593,7 @@ const COORDINATOR_BREG_CLIENT_FILE: &str = "coordinator-breg-client"; pub(super) const COORDINATOR_COMPLETION_KEY: &str = "coordinator-review-completion-key"; /// The Coordinator's review completion route, as `registry-review-protocol` /// declares it. rstack dev depends on no product protocol crate. -const REVIEW_COMPLETIONS_PATH: &str = "/v1/review-completions"; +pub(super) const REVIEW_COMPLETIONS_PATH: &str = "/v1/review-completions"; const CASEWORK_CONTEXT_CLIENT: &str = "casework-context-client"; #[derive(Default)] diff --git a/crates/registry-rstack-dev/src/dev_facts.rs b/crates/registry-rstack-dev/src/dev_facts.rs index a1f471cd14..6d0f37aadc 100644 --- a/crates/registry-rstack-dev/src/dev_facts.rs +++ b/crates/registry-rstack-dev/src/dev_facts.rs @@ -40,6 +40,7 @@ pub(super) fn load( external_jwks_uri: Option<&str>, products: &[ProductPlan], clients: &BTreeSet, + completion_destination: Option<&str>, ) -> Result> { let scratch = tempfile::tempdir()?; let scratch_root = scratch.path().canonicalize()?; @@ -72,6 +73,7 @@ pub(super) fn load( issuer, external_jwks_uri, clients, + completion_destination, &terminate, ) })(); @@ -105,6 +107,7 @@ fn load_product_facts( issuer: &str, external_jwks_uri: Option<&str>, clients: &BTreeSet, + completion_destination: Option<&str>, terminate: &AtomicBool, ) -> Result { let product = plan.product; @@ -127,6 +130,7 @@ fn load_product_facts( issuer, external_jwks_uri, clients, + completion_destination, &file, terminate, )?; @@ -205,6 +209,7 @@ fn native_facts( issuer: &str, external_jwks_uri: Option<&str>, clients: &BTreeSet, + completion_destination: Option<&str>, output: &Path, terminate: &AtomicBool, ) -> Result<()> { @@ -227,7 +232,15 @@ fn native_facts( let config_file = if product == Product::Evidence { evidence_target(project, scratch, issuer, external_jwks_uri, &plan.audience)? } else { - let config = runtime_for_facts(plan, project, scratch, &package, issuer, clients)?; + let config = runtime_for_facts( + plan, + project, + scratch, + &package, + issuer, + clients, + completion_destination, + )?; write_private(&runtime, &serde_json::to_vec(&config)?)?; runtime }; @@ -329,6 +342,7 @@ fn runtime_for_facts( package: &Path, issuer: &str, clients: &BTreeSet, + completion_destination: Option<&str>, ) -> Result { let product = plan.product; let version = format!( @@ -379,6 +393,14 @@ fn runtime_for_facts( json!(clients); } } + // The run binds this destination to the Coordinator's completion + // endpoint, so the facts runtime declares it as the run will. + if let Some(destination) = completion_destination { + config["destinations"]["hooks"][destination] = json!({ + "url": format!("http://127.0.0.1:1{}", super::bindings::REVIEW_COMPLETIONS_PATH), + "hmacSha256KeyRef": "secret:file/coordinator-completion-key", + }); + } config["audit"] .as_object_mut() .expect("audit mapping") @@ -767,6 +789,42 @@ mod tests { assert!(coordinator_profiles_for_run(&runtime, &plan).is_err()); } + #[test] + fn casework_facts_configure_the_bound_completion_destination() { + let root = tempfile::tempdir().unwrap(); + let plan: ProductPlan = serde_json::from_value(json!({ + "product": "casework", "project": ".", "audience": "urn:casework", + })) + .unwrap(); + for destination in [None, Some("coordinator-wake")] { + let config = runtime_for_facts( + &plan, + root.path(), + root.path(), + &root.path().join("package"), + "https://issuer.example.test", + &BTreeSet::new(), + destination, + ) + .unwrap(); + let hooks = &config["destinations"]["hooks"]; + match destination { + None => assert!(config.get("destinations").is_none(), "{config}"), + Some(id) => { + assert_eq!(hooks.as_object().unwrap().len(), 1, "{config}"); + assert!(hooks[id]["url"] + .as_str() + .unwrap() + .ends_with(super::super::bindings::REVIEW_COMPLETIONS_PATH)); + assert!(hooks[id]["hmacSha256KeyRef"] + .as_str() + .unwrap() + .starts_with("secret:file/")); + } + } + } + } + #[test] fn evidence_facts_projection_uses_the_run_issuer_and_matching_claim_names() { let root = tempfile::tempdir().unwrap(); diff --git a/crates/registry-rstack-dev/src/roles.rs b/crates/registry-rstack-dev/src/roles.rs index 584e3e8e5b..244c4a2859 100644 --- a/crates/registry-rstack-dev/src/roles.rs +++ b/crates/registry-rstack-dev/src/roles.rs @@ -230,6 +230,10 @@ pub(super) fn resolve( .values() .map(|person| person.client.clone()) .collect(), + bindings + .coordinator_review_producer + .as_ref() + .map(|binding| binding.completion_destination.as_str()), )? }; if let Some(service) = &service_roles { diff --git a/docs/site/src/content/docs/configure/run-a-project-with-rstack-dev.mdx b/docs/site/src/content/docs/configure/run-a-project-with-rstack-dev.mdx index f4bc234341..51782f6e2c 100644 --- a/docs/site/src/content/docs/configure/run-a-project-with-rstack-dev.mdx +++ b/docs/site/src/content/docs/configure/run-a-project-with-rstack-dev.mdx @@ -1088,6 +1088,12 @@ bindings: - the producer's `completion` must name `completionDestination` and the connection's `recipientBinding`. +`check` reads each product's identity facts with the binding's completion destination +configured, as the run configures it. So when the binding is missing, or its +`completionDestination` differs from the producer's, Casework refuses the project first, at the +Casework project path, with `casework.runtime.unconfigured-review-completion-destination`. The +binding's own diagnostic at the `dev.yaml` pointer follows once Casework accepts the project. + An `initiator` guard is refused, as is a producer the BReg review authority binding already binds and a second `casework-review-producer` connection. The binding creates no producer, person, profile, client, scope or grant: it registers the existing test person's `client` on From b015bdfdc893a8e15a277e297aa67e6c1049d487 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 23:08:40 +0000 Subject: [PATCH 144/183] feat(dev): add the permit-review service preview One permit application runs through four products from one built page served to two actors. The applicant submits a BReg application and starts a Coordinator run. The run asks Casework for a review and waits. The officer claims and approves the task in Casework. The run then records an assessment from the assess-permit service function and records the decision in BReg through approve-application or refuse-application, which only the Coordinator's permit-coordinator profile may invoke. The applicant's own decision attempt is left for Casework to refuse. The Coordinator binds its Casework connection through bindings.coordinatorReviewProducer and its BReg connection through bindings.coordinatorBregClient. The Coordinator project carries approved and refused fixtures, and its BReg Action contract is generated by bregctl from the example's register. dev_run.rs runs rstack dev check on the example with the real bregctl, caseworkctl and coordinatorctl: the example passes, and seven edits are refused at their fields: - producer binding removed (Casework's completion-destination refusal); - producer binding and the producer's completion removed (/bindings); - a second, unbound casework-review-producer connection; - a completionDestination the producer does not name (Casework's refusal first); - the BReg connection's profile not the identity's grant profile; - the BReg binding naming the review connection; - the BReg identity shared with a preview actor. prepare-service-preview-locks.mjs stages the new example's lock too. The browser journey that runs it end to end follows separately. Signed-off-by: Jeremi Joslin --- crates/registry-rstack/tests/dev_run.rs | 140 +++++ .../service-previews/permit-review/README.md | 44 ++ .../permit-review/casework/casework.yaml | 75 +++ .../permit-review/coordinator/README.md | 17 + .../approved-assessed-and-recorded.yaml | 79 +++ .../rejected-recorded-without-assessment.yaml | 71 +++ .../permit-review/coordinator/functions.rhai | 38 ++ .../generated/permits.contract.json | 1 + .../permit-review/coordinator/runtime.yaml | 76 +++ .../permit-review/coordinator/workflow.yaml | 208 +++++++ .../permit-review/dev-journeys.yaml | 20 + .../service-previews/permit-review/dev.yaml | 69 +++ .../functions/assess-permit/assess.ts | 32 ++ .../functions/assess-permit/index.ts | 7 + .../permit-review/manifest.yaml | 3 + .../permit-review/package-lock.json | 528 ++++++++++++++++++ .../permit-review/package.json | 8 + .../permit-review/project/registry.yaml | 168 ++++++ .../permit-review/service.yaml | 40 ++ .../permit-review/web/public/index.html | 61 ++ .../permit-review/web/public/service.css | 29 + .../permit-review/web/src/page.ts | 177 ++++++ .../permit-review/web/tsconfig.json | 11 + .../scripts/prepare-service-preview-locks.mjs | 2 +- 24 files changed, 1903 insertions(+), 1 deletion(-) create mode 100644 products/platform/examples/service-previews/permit-review/README.md create mode 100644 products/platform/examples/service-previews/permit-review/casework/casework.yaml create mode 100644 products/platform/examples/service-previews/permit-review/coordinator/README.md create mode 100644 products/platform/examples/service-previews/permit-review/coordinator/fixtures/approved-assessed-and-recorded.yaml create mode 100644 products/platform/examples/service-previews/permit-review/coordinator/fixtures/rejected-recorded-without-assessment.yaml create mode 100644 products/platform/examples/service-previews/permit-review/coordinator/functions.rhai create mode 100644 products/platform/examples/service-previews/permit-review/coordinator/generated/permits.contract.json create mode 100644 products/platform/examples/service-previews/permit-review/coordinator/runtime.yaml create mode 100644 products/platform/examples/service-previews/permit-review/coordinator/workflow.yaml create mode 100644 products/platform/examples/service-previews/permit-review/dev-journeys.yaml create mode 100644 products/platform/examples/service-previews/permit-review/dev.yaml create mode 100644 products/platform/examples/service-previews/permit-review/functions/assess-permit/assess.ts create mode 100644 products/platform/examples/service-previews/permit-review/functions/assess-permit/index.ts create mode 100644 products/platform/examples/service-previews/permit-review/manifest.yaml create mode 100644 products/platform/examples/service-previews/permit-review/package-lock.json create mode 100644 products/platform/examples/service-previews/permit-review/package.json create mode 100644 products/platform/examples/service-previews/permit-review/project/registry.yaml create mode 100644 products/platform/examples/service-previews/permit-review/service.yaml create mode 100644 products/platform/examples/service-previews/permit-review/web/public/index.html create mode 100644 products/platform/examples/service-previews/permit-review/web/public/service.css create mode 100644 products/platform/examples/service-previews/permit-review/web/src/page.ts create mode 100644 products/platform/examples/service-previews/permit-review/web/tsconfig.json diff --git a/crates/registry-rstack/tests/dev_run.rs b/crates/registry-rstack/tests/dev_run.rs index 9295f9f8e1..0cf07b6c62 100644 --- a/crates/registry-rstack/tests/dev_run.rs +++ b/crates/registry-rstack/tests/dev_run.rs @@ -2484,6 +2484,146 @@ fn check_refuses_binding_configuration_the_products_would_refuse_at_the_plan_fie } } +/// `rstack dev check` over the permit-review preview, with the real BReg, +/// Casework and Coordinator tools, before any product starts. +fn check_permit_review(root: &std::path::Path, state: &std::path::Path) -> std::process::Output { + rstack_dev(state, true) + .args(["check", utf8(root), "--deny-warnings"]) + .env("RSTACK_CASEWORKCTL_BIN", host("caseworkctl")) + .env("RSTACK_COORDINATORCTL_BIN", host("coordinatorctl")) + .env("RSTACK_COORDINATOR_BIN", system_binary("false")) + .output() + .unwrap() +} + +#[test] +fn permit_review_check_refuses_each_widened_coordinator_binding_at_its_dev_yaml_field() { + let source = example_project("platform/examples/service-previews/permit-review"); + let copy = |root: &std::path::Path| { + fs::create_dir_all(root).unwrap(); + for entry in fs::read_dir(&source).unwrap() { + let entry = entry.unwrap(); + if entry.file_name() == "node_modules" { + continue; + } + let target = root.join(entry.file_name()); + if entry.file_type().unwrap().is_dir() { + copy_tree(&entry.path(), &target); + } else { + fs::copy(entry.path(), target).unwrap(); + } + } + }; + + let scratch = tempfile::tempdir().unwrap(); + let state = scratch.path().join("state"); + let root = scratch.path().join("permit-review"); + copy(&root); + let checked = check_permit_review(&root, &state); + assert!( + checked.status.success(), + "{} {}", + String::from_utf8_lossy(&checked.stdout), + String::from_utf8_lossy(&checked.stderr) + ); + assert!(!state.exists()); + + let unbound_review = concat!( + " review-copy:\n", + " type: casework-review-producer\n", + " baseUrl: https://casework.example.org\n", + " profile: coordinator-producer\n", + " producer: coordinator\n", + " authorization:\n", + " tokenEndpoint: https://identity.permit-review.example.test/oauth/token\n", + " clientAssertionAudience: https://identity.permit-review.example.test\n", + " clientId: coordinator-producer\n", + " signingKeyRef: secret:file/review-client-key\n", + " resource: urn:example:permit-review\n", + " scopes: [casework:permit:review]\n", + " completion:\n", + " recipientBinding: coordinator-copy\n", + " hmacSha256KeyRef: secret:file/review-completion-key\n", + " permits:\n", + ); + for (case, edits, path, message) in [ + ( + // Casework refuses first: its producer names a completion + // destination that only the binding configures. + "producer binding removed", + vec![("dev.yaml", " coordinatorReviewProducer:\n connection: review\n producer: coordinator\n identity: coordinator-producer\n completionDestination: coordinator-wake\n runIssuerBinding:\n producer:\n expectedIssuer: https://identity.permit-review.example.test\n expectedProfile: coordinator-producer\n expectedSubject: coordinator-producer\n", "")], + "/products/casework/path", + "The owning casework tool refused this project's identity facts (casework.runtime.unconfigured-review-completion-destination).", + ), + ( + "producer binding and completion removed", + vec![ + ("dev.yaml", " coordinatorReviewProducer:\n connection: review\n producer: coordinator\n identity: coordinator-producer\n completionDestination: coordinator-wake\n runIssuerBinding:\n producer:\n expectedIssuer: https://identity.permit-review.example.test\n expectedProfile: coordinator-producer\n expectedSubject: coordinator-producer\n", ""), + ( + "casework/casework.yaml", + " completion:\n destinationId: coordinator-wake\n recipientBinding: coordinator-v1\n", + "", + ), + ], + "/bindings", + "A Coordinator casework-review-producer connection needs bindings.coordinatorReviewProducer before Casework trusts it in this run.", + ), + ( + "second producer connection", + vec![("coordinator/runtime.yaml", " permits:\n", unbound_review)], + "/bindings/coordinatorReviewProducer/connection", + "Another Coordinator casework-review-producer connection has no binding, so Casework would not trust it in this run.", + ), + ( + // The facts runtime configures the binding's destination, so + // Casework refuses the producer's unconfigured one first. + "completion destination", + vec![("dev.yaml", "completionDestination: coordinator-wake", "completionDestination: another-wake")], + "/products/casework/path", + "The owning casework tool refused this project's identity facts (casework.runtime.unconfigured-review-completion-destination).", + ), + ( + "BReg profile", + vec![("coordinator/runtime.yaml", " profile: permit-coordinator\n", " profile: permit-reader\n")], + "/bindings/coordinatorBregClient/connection", + "The connection's profile is not the identity's BReg grant profile.", + ), + ( + "BReg connection", + vec![("dev.yaml", " connection: permits\n", " connection: review\n")], + "/bindings/coordinatorBregClient/connection", + "The Coordinator runtime.yaml has no breg connection with this name.", + ), + ( + "BReg identity shared with a preview actor", + vec![("dev.yaml", " connection: permits\n identity: coordinator-service\n", " connection: permits\n identity: applicant\n")], + "/bindings/coordinatorBregClient/identity", + "The Coordinator's BReg identity must be a dedicated machine person that no other binding or preview actor uses.", + ), + ] { + let scratch = tempfile::tempdir().unwrap(); + let state = scratch.path().join("state"); + let root = scratch.path().join("permit-review"); + copy(&root); + for (file, from, to) in edits { + let edited = root.join(file); + let text = fs::read_to_string(&edited).unwrap(); + assert_eq!(text.matches(from).count(), 1, "{case}: {file}"); + fs::write(&edited, text.replace(from, to)).unwrap(); + } + + let checked = check_permit_review(&root, &state); + + assert_eq!(checked.status.code(), Some(1), "{case}: {checked:?}"); + let report: serde_json::Value = serde_json::from_slice(&checked.stdout).unwrap(); + assert_eq!(report["status"], "domain-refusal", "{case}: {report}"); + let diagnostic = &report["diagnostics"][0]; + assert_eq!(diagnostic["path"], path, "{case}: {diagnostic}"); + assert_eq!(diagnostic["message"], message, "{case}: {diagnostic}"); + assert!(!state.exists(), "{case}"); + } +} + #[test] fn check_refuses_a_context_provider_binding_with_the_rule_caseworkctl_check_names() { let scratch = tempfile::tempdir().unwrap(); diff --git a/products/platform/examples/service-previews/permit-review/README.md b/products/platform/examples/service-previews/permit-review/README.md new file mode 100644 index 0000000000..96b0318006 --- /dev/null +++ b/products/platform/examples/service-previews/permit-review/README.md @@ -0,0 +1,44 @@ +# Apply for a reviewed permit + +This preview runs one permit application through four products. The applicant +submits it to BReg and starts a Coordinator run. The run asks Casework for a +review and waits. An officer approves it in Casework. The run then records an +assessment from the `assess-permit` service function and records the decision +in BReg under the Coordinator's own BReg profile. + +Start it using the [preview instructions](../README.md). It also needs +`casework`, `caseworkctl`, `coordinator` and `coordinatorctl` from the same +release. `rstack dev start` prints one URL per actor. Every URL serves the same +built page, and each origin acts for one synthetic person: + +- the applicant's origin submits an application, starts the run and follows it; +- the officer's origin lists the queue, claims a task and approves it. + +From the applicant's origin, enter a task ID in **Decide a review task**. +Casework refuses that decision with 403, because the applicant's Casework +profile may ask for a review but never decide one. + +Serving each actor from its own origin is a development substitution for a +real sign-in. A deployment serves one origin and signs each person in. + +- [service.yaml](service.yaml) names the products, the page, the function and + each role's access profiles. +- [The BReg project](project/registry.yaml) defines the application Record, + the applicant's submission Action and the two decision Actions that only the + Coordinator's profile may invoke. +- [The Casework project](casework/casework.yaml) defines the review policy, + the officers' queue and the Coordinator as its one trusted producer. +- [The Coordinator project](coordinator/workflow.yaml) asks for the review, + waits for its result, records the assessment and then the decision. Its + [fixtures](coordinator/fixtures) cover the approved and refused paths. +- [The assessment function](functions/assess-permit/index.ts) returns advice + from the application's activity and site. It holds no registry credential. +- [dev.yaml](dev.yaml) declares the synthetic people, binds the Coordinator's + Casework and BReg connections to run-local machine identities and lists each + actor's preview routes. +- [The startup journey](dev-journeys.yaml) staffs the officers' queue. +- [The page code](web/src/page.ts) asks its origin which actor it serves and + shows that actor's controls. + +A waiting run does not survive a restart of `rstack dev`, because the restarted +Casework has a new origin. Stop the preview with `--clean` and start again. diff --git a/products/platform/examples/service-previews/permit-review/casework/casework.yaml b/products/platform/examples/service-previews/permit-review/casework/casework.yaml new file mode 100644 index 0000000000..f2e7e6df63 --- /dev/null +++ b/products/platform/examples/service-previews/permit-review/casework/casework.yaml @@ -0,0 +1,75 @@ +# Casework owns the permit review: who may decide, the queue officers work, +# and the one producer it trusts to ask for a review. The Coordinator is that +# producer. Its issuer below is the logical name `rstack dev` rebinds to the +# run issuer under the exact guards in dev.yaml. +apiVersion: id.registrystack.org/formats/casework/project/v1alpha1 +kind: CaseworkProject +project: + id: permit-review + version: "1" +accessProfiles: + permit-officer: + principalClaim: sub + requiredScopes: [casework:permit:decide] + actsAs: staff + permit-supervisor: + principalClaim: sub + requiredScopes: [casework:permit:supervise] + actsAs: supervisor + permit-administrator: + principalClaim: sub + requiredScopes: [casework:permit:admin] + actsAs: administrator + permit-applicant: + principalClaim: sub + requiredScopes: [casework:permit:apply] + actsAs: requester + coordinator-producer: + principalClaim: sub + requiredScopes: [casework:permit:review] + actsAs: requester +queues: + permit-officers: + label: Permit applications awaiting review +reviewPolicies: + permit-review: + version: "1" + purpose: approval + context: {mode: submitted} + stages: + - id: decide + queue: permit-officers + decidingProfiles: [permit-officer] + requiredApprovals: 1 + retention: + terminalRetentionDays: 90 + accountabilityRetentionDays: 365 + displaySchema: + type: object + additionalProperties: false + required: [activity, site] + properties: + activity: {type: string, maxLength: 160} + site: {type: string, maxLength: 160} + outcomes: + approved: + label: Approve the permit + settlement: approved + reasonRequired: false + publicReason: optional + rejected: + label: Refuse the permit + settlement: rejected + reasonRequired: true + publicReason: required +trustedProducers: + coordinator: + profile: coordinator-producer + issuer: https://identity.permit-review.example.test + subject: coordinator-producer + sourceNamespaces: [permits] + reviewPolicies: [permit-review] + retention: {receiptRetentionDays: 30} + completion: + destinationId: coordinator-wake + recipientBinding: coordinator-v1 diff --git a/products/platform/examples/service-previews/permit-review/coordinator/README.md b/products/platform/examples/service-previews/permit-review/coordinator/README.md new file mode 100644 index 0000000000..c59a444ea0 --- /dev/null +++ b/products/platform/examples/service-previews/permit-review/coordinator/README.md @@ -0,0 +1,17 @@ +# Permit review workflow + +The Coordinator project for the [permit review preview](../README.md). + +`generated/permits.contract.json` is the BReg-generated Action export for +[the permit register](../project/registry.yaml). From the repository root, +regenerate it into a new directory and copy the export over the committed file: + +```sh +bregctl generate actions products/platform/examples/service-previews/permit-review/project --output /tmp/permits-actions +cp /tmp/permits-actions/generated/action-contracts.json \ + products/platform/examples/service-previews/permit-review/coordinator/generated/permits.contract.json +``` + +The runtime template names HTTPS reference endpoints and secret references. +Under `rstack dev`, the bindings in `dev.yaml` replace the review and permits +connections, and the preview function host replaces the assessor's. diff --git a/products/platform/examples/service-previews/permit-review/coordinator/fixtures/approved-assessed-and-recorded.yaml b/products/platform/examples/service-previews/permit-review/coordinator/fixtures/approved-assessed-and-recorded.yaml new file mode 100644 index 0000000000..55870f8d49 --- /dev/null +++ b/products/platform/examples/service-previews/permit-review/coordinator/fixtures/approved-assessed-and-recorded.yaml @@ -0,0 +1,79 @@ +# yaml-language-server: $schema=https://id.registrystack.org/schemas/coordinator/fixture/fixture.v1alpha1.schema.json +apiVersion: id.registrystack.org/formats/coordinator/fixture/v1alpha1 +kind: CoordinatorFixture +id: approved-assessed-and-recorded +admittedAt: '2026-12-01T09:00:00Z' +input: + applicationId: 00000000-0000-4000-8000-000000000001 + applicationRevision: '1' + applicationDigest: sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa + activity: Night resurfacing + site: North road +replies: + request-review: + - type: success + value: + requestId: 00000000-0000-4000-8000-000000000010 + subject: + source: permits + type: permit-application + id: 00000000-0000-4000-8000-000000000001 + version: '1' + digest: sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa + policy: + id: permit-review + version: '1' + digest: sha256:bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb + submissionDigest: sha256:cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc + assess: + - type: response + value: + status: 200 + body: + assessment: conditions + approve: + - type: success + value: + action: approve-application + applicationId: 00000000-0000-4000-8000-000000000002 + results: + decided-application: + recordType: permit-application + recordId: 00000000-0000-4000-8000-000000000001 + revision: 2 +waits: + await-review: + type: event + value: + resultId: 00000000-0000-4000-8000-000000000011 + requestId: 00000000-0000-4000-8000-000000000010 + subject: + source: permits + type: permit-application + id: 00000000-0000-4000-8000-000000000001 + version: '1' + digest: sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa + policy: + id: permit-review + version: '1' + digest: sha256:bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb + submissionDigest: sha256:cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc + status: approved + outcome: approved + completedAt: '2026-12-02T09:00:00Z' + availableUntil: '2027-01-02T09:00:00Z' +expect: + path: + - request-review + - await-review + - decide + - assess + - approve + - approved + state: completed + outcome: + type: named + value: approved + output: + assessment: conditions + resultId: 00000000-0000-4000-8000-000000000011 diff --git a/products/platform/examples/service-previews/permit-review/coordinator/fixtures/rejected-recorded-without-assessment.yaml b/products/platform/examples/service-previews/permit-review/coordinator/fixtures/rejected-recorded-without-assessment.yaml new file mode 100644 index 0000000000..824fb9ccd2 --- /dev/null +++ b/products/platform/examples/service-previews/permit-review/coordinator/fixtures/rejected-recorded-without-assessment.yaml @@ -0,0 +1,71 @@ +# yaml-language-server: $schema=https://id.registrystack.org/schemas/coordinator/fixture/fixture.v1alpha1.schema.json +apiVersion: id.registrystack.org/formats/coordinator/fixture/v1alpha1 +kind: CoordinatorFixture +id: rejected-recorded-without-assessment +admittedAt: '2026-12-01T09:00:00Z' +input: + applicationId: 00000000-0000-4000-8000-000000000001 + applicationRevision: '1' + applicationDigest: sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa + activity: Night resurfacing + site: North road +replies: + request-review: + - type: success + value: + requestId: 00000000-0000-4000-8000-000000000010 + subject: + source: permits + type: permit-application + id: 00000000-0000-4000-8000-000000000001 + version: '1' + digest: sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa + policy: + id: permit-review + version: '1' + digest: sha256:bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb + submissionDigest: sha256:cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc + refuse: + - type: success + value: + action: refuse-application + applicationId: 00000000-0000-4000-8000-000000000002 + results: + decided-application: + recordType: permit-application + recordId: 00000000-0000-4000-8000-000000000001 + revision: 2 +waits: + await-review: + type: event + value: + resultId: 00000000-0000-4000-8000-000000000011 + requestId: 00000000-0000-4000-8000-000000000010 + subject: + source: permits + type: permit-application + id: 00000000-0000-4000-8000-000000000001 + version: '1' + digest: sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa + policy: + id: permit-review + version: '1' + digest: sha256:bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb + submissionDigest: sha256:cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc + status: rejected + outcome: rejected + completedAt: '2026-12-02T09:00:00Z' + availableUntil: '2027-01-02T09:00:00Z' +expect: + path: + - request-review + - await-review + - decide + - refuse + - refused + state: completed + outcome: + type: named + value: refused + output: + resultId: 00000000-0000-4000-8000-000000000011 diff --git a/products/platform/examples/service-previews/permit-review/coordinator/functions.rhai b/products/platform/examples/service-previews/permit-review/coordinator/functions.rhai new file mode 100644 index 0000000000..b346e9b294 --- /dev/null +++ b/products/platform/examples/service-previews/permit-review/coordinator/functions.rhai @@ -0,0 +1,38 @@ +// Pure Function ABI: one typed object of named inputs, one typed output. + +// The page that starts the run supplies the application's revision and an +// opaque digest of it. Casework keeps them as the subject's version. +fn review_request(args) { + let input = args["input"]; + #{ + policy: #{id: "permit-review"}, + subject: #{ + source: "permits", + type: "permit-application", + id: input.applicationId, + version: input.applicationRevision, + digest: input.applicationDigest + }, + requesterReference: input.applicationId, + context: #{ + mode: "submitted", + snapshot: #{activity: input.activity, site: input.site} + } + } +} + +fn assess_request(args) { + let input = args["input"]; + #{applicationId: input.applicationId, activity: input.activity, site: input.site} +} + +// Only a recognised answer settles the call. Anything else is uncertain, so +// the run holds for same-command recovery instead of guessing. +fn assess_outcome(args) { + let status = args.response.status; + let body = args.response.body; + if status == 200 && "assessment" in body { + return #{state: "accepted", result: #{assessment: body.assessment}}; + } + #{state: "uncertain"} +} diff --git a/products/platform/examples/service-previews/permit-review/coordinator/generated/permits.contract.json b/products/platform/examples/service-previews/permit-review/coordinator/generated/permits.contract.json new file mode 100644 index 0000000000..0816d3623c --- /dev/null +++ b/products/platform/examples/service-previews/permit-review/coordinator/generated/permits.contract.json @@ -0,0 +1 @@ +{"actions":[{"display":{"description":"Record an approved review decision on one submitted application.","label":"Approve application"},"id":"approve-application","input":{"$id":"urn:breg:action:approve-application:invoke-input","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"input":{"additionalProperties":false,"properties":{"applicationId":{"format":"uuid","type":"string"}},"required":["applicationId"],"type":"object"},"preconditions":{"additionalProperties":false,"properties":{},"required":[],"type":"object"}},"required":["input"],"type":"object","x-registry-action":"approve-application","x-registry-requiredConditionKeys":[]},"mode":"immediate","output":{"$id":"urn:breg:action:approve-application:invoke-response","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"action":{"const":"approve-application"},"applicationId":{"format":"uuid","type":"string"},"results":{"additionalProperties":false,"properties":{"decided-application":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"const":"permit-application"},"revision":{"format":"int64","minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"}},"required":["decided-application"],"type":"object"}},"required":["action","applicationId","results"],"type":"object"},"revision":"sha256:002f25130195be270d98480a05336cab550e7ebca562263dbed5071d6659160a"},{"display":{"description":"Record a refused review decision on one submitted application.","label":"Refuse application"},"id":"refuse-application","input":{"$id":"urn:breg:action:refuse-application:invoke-input","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"input":{"additionalProperties":false,"properties":{"applicationId":{"format":"uuid","type":"string"}},"required":["applicationId"],"type":"object"},"preconditions":{"additionalProperties":false,"properties":{},"required":[],"type":"object"}},"required":["input"],"type":"object","x-registry-action":"refuse-application","x-registry-requiredConditionKeys":[]},"mode":"immediate","output":{"$id":"urn:breg:action:refuse-application:invoke-response","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"action":{"const":"refuse-application"},"applicationId":{"format":"uuid","type":"string"},"results":{"additionalProperties":false,"properties":{"decided-application":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"const":"permit-application"},"revision":{"format":"int64","minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"}},"required":["decided-application"],"type":"object"}},"required":["action","applicationId","results"],"type":"object"},"revision":"sha256:345ab8daadc77f82e59ff3923b39bcf036e7d86a3b6ad0899fe13f9e4b5ce3dc"},{"display":{"description":"Create a submitted permit application from bounded applicant input.","label":"Submit application"},"id":"submit-application","input":{"$id":"urn:breg:action:submit-application:invoke-input","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"input":{"additionalProperties":false,"properties":{"activity":{"maxLength":160,"minLength":1,"type":"string"},"site":{"maxLength":160,"minLength":1,"type":"string"}},"required":["activity","site"],"type":"object"},"preconditions":{"additionalProperties":false,"properties":{},"required":[],"type":"object"}},"required":["input"],"type":"object","x-registry-action":"submit-application","x-registry-requiredConditionKeys":[]},"mode":"immediate","output":{"$id":"urn:breg:action:submit-application:invoke-response","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"action":{"const":"submit-application"},"applicationId":{"format":"uuid","type":"string"},"results":{"additionalProperties":false,"properties":{"application":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"const":"permit-application"},"revision":{"format":"int64","minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"}},"required":["application"],"type":"object"}},"required":["action","applicationId","results"],"type":"object"},"revision":"sha256:cc7a9aa7902efd4871eb5f1b391d153b4194d57634157307cbafcdc5d4c306ce"}],"apiVersion":"id.registrystack.org/formats/breg/action-contracts/v1","kind":"BRegActionContracts"} \ No newline at end of file diff --git a/products/platform/examples/service-previews/permit-review/coordinator/runtime.yaml b/products/platform/examples/service-previews/permit-review/coordinator/runtime.yaml new file mode 100644 index 0000000000..5f79dc1ef9 --- /dev/null +++ b/products/platform/examples/service-previews/permit-review/coordinator/runtime.yaml @@ -0,0 +1,76 @@ +# yaml-language-server: $schema=https://id.registrystack.org/schemas/coordinator/runtime/runtime.v1alpha1.schema.json +apiVersion: id.registrystack.org/formats/coordinator/runtime/v1alpha1 +kind: CoordinatorRuntimeConfig +# Deployment references. Under `rstack dev` the bindings in dev.yaml replace +# each connection's address and credential with run-local ones, and the +# preview function host replaces the assessor's. +secretProviders: + environment: {} + file: + root: /run/registry-coordinator/secrets +database: + runtimeUrlRef: secret:env/COORDINATOR_DATABASE_URL + migrationUrlRef: secret:env/COORDINATOR_MIGRATION_URL +namespace: coordinator_permits +connections: + review: + type: casework-review-producer + baseUrl: https://casework.example.org + profile: coordinator-producer + producer: coordinator + authorization: + tokenEndpoint: https://identity.permit-review.example.test/oauth/token + clientAssertionAudience: https://identity.permit-review.example.test + clientId: coordinator-producer + signingKeyRef: secret:file/review-client-key + resource: urn:example:permit-review + scopes: [casework:permit:review] + completion: + recipientBinding: coordinator-v1 + hmacSha256KeyRef: secret:file/review-completion-key + permits: + type: breg + baseUrl: https://permits.example.org + profile: permit-coordinator + authorization: + tokenEndpoint: https://identity.permit-review.example.test/oauth/token + clientAssertionAudience: https://identity.permit-review.example.test + clientId: permit-coordinator + signingKeyRef: secret:file/permits-client-key + resource: urn:example:permits + scopes: [registry:permit:decide] + assessor: + type: service-function + baseUrl: https://functions.example.org/ + function: assess-permit + hostKeyRef: secret:file/assessor-host-key + responseSchema: {type: object} +deployment: + databaseId: permit-flow + runtimeRole: coordinator_runtime + packages: + - root: /opt/registry-coordinator/package + expectedDigest: sha256:0000000000000000000000000000000000000000000000000000000000000000 + listener: + bind: 127.0.0.1:8108 + tlsTermination: operator-controlled-upstream + authentication: + issuers: + main: + issuer: https://identity.permit-review.example.test + audience: urn:example:permit-flow + allowedClients: from-access-profiles + accessProfiles: + permit-starter: + requesterClients: [permit-applicant] + subjects: [applicant] + requiredScopes: [coordinator:permit:start] + workflows: [permit-flow] + actions: [status, start] + auditFile: /var/lib/registry-coordinator/audit.jsonl + auditKeyRef: secret:file/audit-key + activeStateKey: 1 + stateKeys: + "1": + keyRef: secret:file/state-key-1 + admissionKeyRef: secret:file/admission-key diff --git a/products/platform/examples/service-previews/permit-review/coordinator/workflow.yaml b/products/platform/examples/service-previews/permit-review/coordinator/workflow.yaml new file mode 100644 index 0000000000..a5e07434bd --- /dev/null +++ b/products/platform/examples/service-previews/permit-review/coordinator/workflow.yaml @@ -0,0 +1,208 @@ +# yaml-language-server: $schema=https://id.registrystack.org/schemas/coordinator/project/project.v1alpha1.schema.json +# One permit application: Casework decides, the assess-permit service function +# records an assessment, and BReg records the decision under the Coordinator's +# own BReg profile. The Coordinator owns none of those decisions. +apiVersion: id.registrystack.org/formats/coordinator/project/v1alpha1 +kind: CoordinatorProject +project: + id: permit-flow + version: '1' +contracts: + permits: + type: breg + source: generated/permits.contract.json +types: + workflow-input: + type: object + additionalProperties: false + required: [applicationId, applicationRevision, applicationDigest, activity, site] + properties: + applicationId: {type: string, format: uuid} + applicationRevision: {type: string, minLength: 1, maxLength: 64} + applicationDigest: {type: string, pattern: '^sha256:[0-9a-f]{64}$'} + activity: {type: string, minLength: 1, maxLength: 160} + site: {type: string, minLength: 1, maxLength: 160} + assess-response: + type: object + additionalProperties: false + required: [status, body] + properties: + status: {type: integer, minimum: 200, maximum: 499} + body: + type: object + additionalProperties: false + properties: + assessment: {type: string, enum: [standard, conditions]} + assessment: + type: object + additionalProperties: false + required: [assessment] + properties: + assessment: {type: string, enum: [standard, conditions]} + assess-outcome: + oneOf: + - type: object + additionalProperties: false + required: [state, result] + properties: + state: {type: string, const: accepted} + result: {typeRef: assessment} + - type: object + additionalProperties: false + required: [state] + properties: + state: {type: string, const: uncertain} +transforms: + review-request: + runtime: rhai + source: functions.rhai + entrypoint: review_request + inputs: + input: {typeRef: workflow-input} + output: {operationInput: request-review} + assess-request: + runtime: rhai + source: functions.rhai + entrypoint: assess_request + inputs: + input: {typeRef: workflow-input} + output: {operationInput: assess-permit} + assess-outcome: + runtime: rhai + source: functions.rhai + entrypoint: assess_outcome + inputs: + command: {operationInput: assess-permit} + response: {operationOutput: assess-permit} + output: {typeRef: assess-outcome} +operations: + request-review: + uses: casework.submit-review-request/v1 + connection: review + assess-permit: + uses: service.invoke-function/v1 + connection: assessor + serviceFunction: assess-permit + responseSchema: {typeRef: assess-response} + interpret: assess-outcome + approve-application: + uses: breg.invoke-action/v1 + connection: permits + action: {contract: permits, id: approve-application} + refuse-application: + uses: breg.invoke-action/v1 + connection: permits + action: {contract: permits, id: refuse-application} +workflow: + input: {typeRef: workflow-input} + deadlineSeconds: 2592000 + start: request-review + steps: + request-review: + label: Ask Casework for a review + type: call + operation: request-review + input: + type: transform + transform: review-request + inputs: + input: {type: input} + next: await-review + await-review: + label: Wait for the officer's decision + type: wait-for + timeoutSeconds: 1209600 + next: decide + onTimeout: review-timed-out + completion: {step: request-review, name: result} + decide: + type: choose + choose: {type: step, step: await-review, path: /status} + cases: + approved: assess + rejected: refuse + changes-requested: not-decided + answered: not-decided + cancelled: not-decided + superseded: not-decided + assess: + label: Assess the approved permit + type: call + operation: assess-permit + input: + type: transform + transform: assess-request + inputs: + input: {type: input} + next: approve + approve: + label: Record the approval in the register + type: call + operation: approve-application + input: + type: fields + fields: + input: + type: fields + fields: + applicationId: {type: input, path: /applicationId} + next: approved + refuse: + label: Record the refusal in the register + type: call + operation: refuse-application + input: + type: fields + fields: + input: + type: fields + fields: + applicationId: {type: input, path: /applicationId} + next: refused + approved: + type: finish + outcome: approved + output: + type: fields + fields: + assessment: {type: step, step: assess, path: /assessment} + resultId: {type: step, step: await-review, path: /resultId} + refused: + type: finish + outcome: refused + output: + type: fields + fields: + resultId: {type: step, step: await-review, path: /resultId} + not-decided: + type: finish + outcome: not-decided + output: + type: fields + fields: + status: {type: step, step: await-review, path: /status} + review-timed-out: + type: finish + outcome: review-timed-out + outcomes: + approved: + type: object + additionalProperties: false + required: [assessment, resultId] + properties: + assessment: {type: string, enum: [standard, conditions]} + resultId: {type: string, format: uuid} + refused: + type: object + additionalProperties: false + required: [resultId] + properties: + resultId: {type: string, format: uuid} + not-decided: + type: object + additionalProperties: false + required: [status] + properties: + status: {type: string} + review-timed-out: + type: 'null' diff --git a/products/platform/examples/service-previews/permit-review/dev-journeys.yaml b/products/platform/examples/service-previews/permit-review/dev-journeys.yaml new file mode 100644 index 0000000000..ed25eb8c2c --- /dev/null +++ b/products/platform/examples/service-previews/permit-review/dev-journeys.yaml @@ -0,0 +1,20 @@ +# yaml-language-server: $schema=https://id.registrystack.org/schemas/rstack/journeys/journeys.v1alpha1.schema.json +apiVersion: id.registrystack.org/formats/rstack/journeys/v1alpha1 +kind: RStackJourneys +journeys: + - id: staff-permit-officers + steps: + # The officer decides only once Casework staffs the queue with that + # person under the run's issuer. + - id: staff-the-queue + product: casework + as: administrator + method: POST + path: /v1/directory/bootstrap + headers: {If-Match: '"0"', Idempotency-Key: staff-permit-officers} + body: + teamId: permit-officers-team + staff: [{issuer: "{{run.issuer}}", subject: officer}] + supervisors: [] + queueId: permit-officers + expect: {status: 200} diff --git a/products/platform/examples/service-previews/permit-review/dev.yaml b/products/platform/examples/service-previews/permit-review/dev.yaml new file mode 100644 index 0000000000..a55cd0e405 --- /dev/null +++ b/products/platform/examples/service-previews/permit-review/dev.yaml @@ -0,0 +1,69 @@ +# yaml-language-server: $schema=https://id.registrystack.org/schemas/rstack/dev/dev.v1alpha1.schema.json +apiVersion: id.registrystack.org/formats/rstack/dev/v1alpha1 +kind: RStackDev +issuer: run +audiences: + permits: "urn:example:permits" + casework: "urn:example:permit-review" + permit-flow: "urn:example:permit-flow" +people: + applicant: + subject: applicant + client: permit-applicant + roles: [applicant] + claims: + breg: {registry_office: central} + officer: + subject: officer + client: permit-officer + roles: [officer] + claims: + breg: {registry_office: central} + administrator: + subject: administrator + client: permit-administrator + roles: [administrator] + coordinator-producer: + subject: coordinator-producer + client: coordinator-producer + roles: [coordinator-producer] + coordinator-service: + subject: coordinator-service + client: permit-coordinator + roles: [coordinator-service] + claims: + breg: {registry_office: central} +journeyFile: dev-journeys.yaml +bindings: + coordinatorReviewProducer: + connection: review + producer: coordinator + identity: coordinator-producer + completionDestination: coordinator-wake + runIssuerBinding: + producer: + expectedIssuer: https://identity.permit-review.example.test + expectedProfile: coordinator-producer + expectedSubject: coordinator-producer + coordinatorBregClient: + connection: permits + identity: coordinator-service +preview: + page: / + functions: [assess-permit] + actors: + applicant: + breg: + get: ["/v1/records/permit-applications/{recordId}"] + post: [/v1/actions/submit-application] + casework: + post: ["/v1/review-tasks/{taskId}/decisions"] + coordinator: + get: [/v1/workflows/permit-flow, "/v1/runs/{runId}"] + post: [/v1/runs] + officer: + breg: + get: ["/v1/records/permit-applications/{recordId}"] + casework: + get: [/v1/review-tasks] + post: ["/v1/review-tasks/{taskId}/claim", "/v1/review-tasks/{taskId}/decisions"] diff --git a/products/platform/examples/service-previews/permit-review/functions/assess-permit/assess.ts b/products/platform/examples/service-previews/permit-review/functions/assess-permit/assess.ts new file mode 100644 index 0000000000..87494b623d --- /dev/null +++ b/products/platform/examples/service-previews/permit-review/functions/assess-permit/assess.ts @@ -0,0 +1,32 @@ +export type Assessment = 'standard' | 'conditions' + +// Night work or work on a public road carries standard conditions. The +// assessment is advice the Coordinator records; it decides nothing. +export function assess(activity: string, site: string): Assessment { + const text = (activity + ' ' + site).toLowerCase() + return /\bnight\b|\broad\b/u.test(text) ? 'conditions' : 'standard' +} + +function bounded(value: unknown, maximumLength: number) { + if (typeof value !== 'string') return undefined + const text = value.trim() + return text.length > 0 && text.length <= maximumLength ? text : undefined +} + +function answer(body: object, status: number) { + return Response.json(body, { status, headers: { 'Cache-Control': 'no-store' } }) +} + +export async function handleAssessment(request: Request) { + if (request.method !== 'POST') return answer({ message: 'Send a POST request.' }, 405) + let submitted: { activity?: unknown; site?: unknown } | null + try { + submitted = await request.json() + } catch { + return answer({ message: 'Send the application details as JSON.' }, 400) + } + const activity = bounded(submitted?.activity, 160) + const site = bounded(submitted?.site, 160) + if (!activity || !site) return answer({ message: 'Send an activity and a site.' }, 400) + return answer({ assessment: assess(activity, site) }, 200) +} diff --git a/products/platform/examples/service-previews/permit-review/functions/assess-permit/index.ts b/products/platform/examples/service-previews/permit-review/functions/assess-permit/index.ts new file mode 100644 index 0000000000..2d53a8c07a --- /dev/null +++ b/products/platform/examples/service-previews/permit-review/functions/assess-permit/index.ts @@ -0,0 +1,7 @@ +import { defineFunction } from '../../generated/server.js' +import { handleAssessment } from './assess.js' + +// The Coordinator calls this function with its run host key, which the +// function host replaces with a placeholder. The function uses no registry +// client: it returns an assessment and records nothing itself. +export default defineFunction(async (request) => handleAssessment(request)) diff --git a/products/platform/examples/service-previews/permit-review/manifest.yaml b/products/platform/examples/service-previews/permit-review/manifest.yaml new file mode 100644 index 0000000000..ef5633aacc --- /dev/null +++ b/products/platform/examples/service-previews/permit-review/manifest.yaml @@ -0,0 +1,3 @@ +public_services: + - id: review-a-permit + title: Apply for a reviewed permit diff --git a/products/platform/examples/service-previews/permit-review/package-lock.json b/products/platform/examples/service-previews/permit-review/package-lock.json new file mode 100644 index 0000000000..3283b9bd6a --- /dev/null +++ b/products/platform/examples/service-previews/permit-review/package-lock.json @@ -0,0 +1,528 @@ +{ + "name": "permit-review", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "dependencies": { + "@registrystack/client": "file:registry-preview-client.tgz" + } + }, + "node_modules/@esbuild/aix-ppc64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.25.12.tgz", + "integrity": "sha512-Hhmwd6CInZ3dwpuGTF8fJG6yoWmsToE+vYgD4nytZVxcu1ulHpUQRAB1UJ8+N1Am3Mz4+xOByoQoSZf4D+CpkA==", + "cpu": [ + "ppc64" + ], + "license": "MIT", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.25.12.tgz", + "integrity": "sha512-VJ+sKvNA/GE7Ccacc9Cha7bpS8nyzVv0jdVgwNDaR4gDMC/2TTRc33Ip8qrNYUcpkOHUT5OZ0bUcNNVZQ9RLlg==", + "cpu": [ + "arm" + ], + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.25.12.tgz", + "integrity": "sha512-6AAmLG7zwD1Z159jCKPvAxZd4y/VTO0VkprYy+3N2FtJ8+BQWFXU+OxARIwA46c5tdD9SsKGZ/1ocqBS/gAKHg==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.25.12.tgz", + "integrity": "sha512-5jbb+2hhDHx5phYR2By8GTWEzn6I9UqR11Kwf22iKbNpYrsmRB18aX/9ivc5cabcUiAT/wM+YIZ6SG9QO6a8kg==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.25.12.tgz", + "integrity": "sha512-N3zl+lxHCifgIlcMUP5016ESkeQjLj/959RxxNYIthIg+CQHInujFuXeWbWMgnTo4cp5XVHqFPmpyu9J65C1Yg==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.25.12.tgz", + "integrity": "sha512-HQ9ka4Kx21qHXwtlTUVbKJOAnmG1ipXhdWTmNXiPzPfWKpXqASVcWdnf2bnL73wgjNrFXAa3yYvBSd9pzfEIpA==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.25.12.tgz", + "integrity": "sha512-gA0Bx759+7Jve03K1S0vkOu5Lg/85dou3EseOGUes8flVOGxbhDDh/iZaoek11Y8mtyKPGF3vP8XhnkDEAmzeg==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.25.12.tgz", + "integrity": "sha512-TGbO26Yw2xsHzxtbVFGEXBFH0FRAP7gtcPE7P5yP7wGy7cXK2oO7RyOhL5NLiqTlBh47XhmIUXuGciXEqYFfBQ==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.25.12.tgz", + "integrity": "sha512-lPDGyC1JPDou8kGcywY0YILzWlhhnRjdof3UlcoqYmS9El818LLfJJc3PXXgZHrHCAKs/Z2SeZtDJr5MrkxtOw==", + "cpu": [ + "arm" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.25.12.tgz", + "integrity": "sha512-8bwX7a8FghIgrupcxb4aUmYDLp8pX06rGh5HqDT7bB+8Rdells6mHvrFHHW2JAOPZUbnjUpKTLg6ECyzvas2AQ==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ia32": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.25.12.tgz", + "integrity": "sha512-0y9KrdVnbMM2/vG8KfU0byhUN+EFCny9+8g202gYqSSVMonbsCfLjUO+rCci7pM0WBEtz+oK/PIwHkzxkyharA==", + "cpu": [ + "ia32" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.25.12.tgz", + "integrity": "sha512-h///Lr5a9rib/v1GGqXVGzjL4TMvVTv+s1DPoxQdz7l/AYv6LDSxdIwzxkrPW438oUXiDtwM10o9PmwS/6Z0Ng==", + "cpu": [ + "loong64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-mips64el": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.25.12.tgz", + "integrity": "sha512-iyRrM1Pzy9GFMDLsXn1iHUm18nhKnNMWscjmp4+hpafcZjrr2WbT//d20xaGljXDBYHqRcl8HnxbX6uaA/eGVw==", + "cpu": [ + "mips64el" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ppc64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.25.12.tgz", + "integrity": "sha512-9meM/lRXxMi5PSUqEXRCtVjEZBGwB7P/D4yT8UG/mwIdze2aV4Vo6U5gD3+RsoHXKkHCfSxZKzmDssVlRj1QQA==", + "cpu": [ + "ppc64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-riscv64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.25.12.tgz", + "integrity": "sha512-Zr7KR4hgKUpWAwb1f3o5ygT04MzqVrGEGXGLnj15YQDJErYu/BGg+wmFlIDOdJp0PmB0lLvxFIOXZgFRrdjR0w==", + "cpu": [ + "riscv64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-s390x": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.25.12.tgz", + "integrity": "sha512-MsKncOcgTNvdtiISc/jZs/Zf8d0cl/t3gYWX8J9ubBnVOwlk65UIEEvgBORTiljloIWnBzLs4qhzPkJcitIzIg==", + "cpu": [ + "s390x" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.25.12.tgz", + "integrity": "sha512-uqZMTLr/zR/ed4jIGnwSLkaHmPjOjJvnm6TVVitAa08SLS9Z0VM8wIRx7gWbJB5/J54YuIMInDquWyYvQLZkgw==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.25.12.tgz", + "integrity": "sha512-xXwcTq4GhRM7J9A8Gv5boanHhRa/Q9KLVmcyXHCTaM4wKfIpWkdXiMog/KsnxzJ0A1+nD+zoecuzqPmCRyBGjg==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.25.12.tgz", + "integrity": "sha512-Ld5pTlzPy3YwGec4OuHh1aCVCRvOXdH8DgRjfDy/oumVovmuSzWfnSJg+VtakB9Cm0gxNO9BzWkj6mtO1FMXkQ==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.25.12.tgz", + "integrity": "sha512-fF96T6KsBo/pkQI950FARU9apGNTSlZGsv1jZBAlcLL1MLjLNIWPBkj5NlSz8aAzYKg+eNqknrUJ24QBybeR5A==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.25.12.tgz", + "integrity": "sha512-MZyXUkZHjQxUvzK7rN8DJ3SRmrVrke8ZyRusHlP+kuwqTcfWLyqMOE3sScPPyeIXN/mDJIfGXvcMqCgYKekoQw==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openharmony-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.25.12.tgz", + "integrity": "sha512-rm0YWsqUSRrjncSXGA7Zv78Nbnw4XL6/dzr20cyrQf7ZmRcsovpcRBdhD43Nuk3y7XIoW2OxMVvwuRvk9XdASg==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/sunos-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.25.12.tgz", + "integrity": "sha512-3wGSCDyuTHQUzt0nV7bocDy72r2lI33QL3gkDNGkod22EsYl04sMf0qLb8luNKTOmgF/eDEDP5BFNwoBKH441w==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.25.12.tgz", + "integrity": "sha512-rMmLrur64A7+DKlnSuwqUdRKyd3UE7oPJZmnljqEptesKM8wx9J8gx5u0+9Pq0fQQW8vqeKebwNXdfOyP+8Bsg==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-ia32": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.25.12.tgz", + "integrity": "sha512-HkqnmmBoCbCwxUKKNPBixiWDGCpQGVsrQfJoVGYLPT41XWF8lHuE5N6WhVia2n4o5QK5M4tYr21827fNhi4byQ==", + "cpu": [ + "ia32" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.25.12.tgz", + "integrity": "sha512-alJC0uCZpTFrSL0CCDjcgleBXPnCrEAhTBILpeAp7M/OFgoqtAetfBzX0xM00MUsVVPpVjlPuMbREqnZCXaTnA==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@registrystack/client": { + "version": "0.50.0", + "resolved": "file:registry-preview-client.tgz", + "integrity": "sha512-NPAHDsmoc12s97/ar9raWVPrmh5BsBsfo1frQSMPFxCKc+6RgPSvhTAs5Pxwk4RCr1GJm0vqzbOfc13UHDQxXA==", + "license": "Apache-2.0", + "dependencies": { + "esbuild": "0.25.12", + "srvx": "1.0.8", + "typescript": "5.9.3", + "yaml": "2.9.1" + }, + "bin": { + "registry-generate": "registry-generate.js", + "registry-preview": "preview/cli.mjs" + }, + "engines": { + "node": ">=24" + } + }, + "node_modules/esbuild": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.25.12.tgz", + "integrity": "sha512-bbPBYYrtZbkt6Os6FiTLCTFxvq4tt3JKall1vRwshA3fdVztsLAatFaZobhkBC8/BrPetoa0oksYoKXoG4ryJg==", + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.25.12", + "@esbuild/android-arm": "0.25.12", + "@esbuild/android-arm64": "0.25.12", + "@esbuild/android-x64": "0.25.12", + "@esbuild/darwin-arm64": "0.25.12", + "@esbuild/darwin-x64": "0.25.12", + "@esbuild/freebsd-arm64": "0.25.12", + "@esbuild/freebsd-x64": "0.25.12", + "@esbuild/linux-arm": "0.25.12", + "@esbuild/linux-arm64": "0.25.12", + "@esbuild/linux-ia32": "0.25.12", + "@esbuild/linux-loong64": "0.25.12", + "@esbuild/linux-mips64el": "0.25.12", + "@esbuild/linux-ppc64": "0.25.12", + "@esbuild/linux-riscv64": "0.25.12", + "@esbuild/linux-s390x": "0.25.12", + "@esbuild/linux-x64": "0.25.12", + "@esbuild/netbsd-arm64": "0.25.12", + "@esbuild/netbsd-x64": "0.25.12", + "@esbuild/openbsd-arm64": "0.25.12", + "@esbuild/openbsd-x64": "0.25.12", + "@esbuild/openharmony-arm64": "0.25.12", + "@esbuild/sunos-x64": "0.25.12", + "@esbuild/win32-arm64": "0.25.12", + "@esbuild/win32-ia32": "0.25.12", + "@esbuild/win32-x64": "0.25.12" + } + }, + "node_modules/srvx": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/srvx/-/srvx-1.0.8.tgz", + "integrity": "sha512-ngFS/J6St4PJfHRHGjr78xkPPtbyXtdMOLNE4x/XZunEK3OhV7aGUWMHf9WTUEy6wm1U0W4okkd82ZFFWRVQTw==", + "license": "MIT", + "bin": { + "srvx": "bin/srvx.mjs" + }, + "engines": { + "node": ">=20.16.0" + } + }, + "node_modules/typescript": { + "version": "5.9.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", + "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/yaml": { + "version": "2.9.1", + "resolved": "https://registry.npmjs.org/yaml/-/yaml-2.9.1.tgz", + "integrity": "sha512-3NxN8+78OdzbT7C/WjGsyfPAtJaN3FNDsWxv7Y7mcDsT/oOmgW8BpyQQFFBnvZE3j9Y2Sdz1ULFLezL7Eb2yFw==", + "license": "ISC", + "bin": { + "yaml": "bin.mjs" + }, + "engines": { + "node": ">= 14.6" + }, + "funding": { + "url": "https://github.com/sponsors/eemeli" + } + } + } +} diff --git a/products/platform/examples/service-previews/permit-review/package.json b/products/platform/examples/service-previews/permit-review/package.json new file mode 100644 index 0000000000..d40b7b9739 --- /dev/null +++ b/products/platform/examples/service-previews/permit-review/package.json @@ -0,0 +1,8 @@ +{ + "name": "permit-review", + "private": true, + "type": "module", + "dependencies": { + "@registrystack/client": "file:registry-preview-client.tgz" + } +} diff --git a/products/platform/examples/service-previews/permit-review/project/registry.yaml b/products/platform/examples/service-previews/permit-review/project/registry.yaml new file mode 100644 index 0000000000..c293fe752a --- /dev/null +++ b/products/platform/examples/service-previews/permit-review/project/registry.yaml @@ -0,0 +1,168 @@ +# The permit register owns the authoritative application Record, the +# applicant's submission Action and the decision Action. Only the +# Coordinator's service profile may record a decision. +apiVersion: id.registrystack.org/formats/breg/project/v1alpha1 +kind: BRegProject +project: + id: permit-register + canonicalBaseIri: https://permit-register.example.gov + version: 0.1.0 + defaultLanguage: en + display: + label: Permit register + description: Authoritative permit application Records. + +package: + sourceRevision: permit-register-0.1.0 + +datasets: + applications: + display: + label: Permit applications + description: Applications submitted for a permit. + +recordTypes: + permit-application: + route: permit-applications + primaryDataset: applications + mutationMode: mutable + display: + label: Permit application + titleField: activity + description: One application for a permit. + fields: + - {id: activity, type: string, required: true, minimumLength: 1, maximumLength: 160, classification: internal} + - {id: site, type: string, required: true, minimumLength: 1, maximumLength: 160, classification: internal} + - {id: office, type: string, required: true, minimumLength: 1, maximumLength: 40, classification: internal} + - {id: status, type: vocabulary-code, vocabulary: application-status, required: true, classification: internal} + +actions: + submit-application: + display: + label: Submit application + description: Create a submitted permit application from bounded applicant input. + execution: {mode: immediate} + inputs: + - {id: activity, type: string, required: true, minimumLength: 1, maximumLength: 160, classification: internal} + - {id: site, type: string, required: true, minimumLength: 1, maximumLength: 160, classification: internal} + plan: + type: fixed + effects: + - id: application + target: {recordType: permit-application} + operation: create + set: + activity: {fromInput: activity} + site: {fromInput: site} + office: {value: central} + status: {value: submitted} + approve-application: + display: + label: Approve application + description: Record an approved review decision on one submitted application. + execution: {mode: immediate, concurrency: current-revision} + inputs: + - {id: application, apiName: applicationId, type: reference, target: permit-application, required: true, classification: internal} + commitGuards: + targets: + - {input: application, field: status, equals: submitted, reason: not-submitted} + plan: + type: fixed + effects: + - id: decided-application + target: {fromInput: application} + operation: patch + set: + status: {value: approved} + refuse-application: + display: + label: Refuse application + description: Record a refused review decision on one submitted application. + execution: {mode: immediate, concurrency: current-revision} + inputs: + - {id: application, apiName: applicationId, type: reference, target: permit-application, required: true, classification: internal} + commitGuards: + targets: + - {input: application, field: status, equals: submitted, reason: not-submitted} + plan: + type: fixed + effects: + - id: decided-application + target: {fromInput: application} + operation: patch + set: + status: {value: refused} + +accessProfiles: + permit-applicant: + actorKind: human + requesterClients: [permit-applicant] + display: + label: Permit applicant + description: Submits permit applications and reads applications in the office. + principalClaim: sub + requiredScopes: ["registry:permit:apply"] + permissions: + records: + - recordType: permit-application + operations: [get] + readableFields: [activity, site, office, status] + rowBoundaries: + - {field: office, claim: registry_office, operator: equals} + actions: + - action: submit-application + operations: [invoke] + targets: + - recordType: permit-application + rowBoundaries: + - {field: office, claim: registry_office, operator: equals} + results: [application] + permit-reader: + actorKind: human + requesterClients: [permit-officer] + display: + label: Permit reader + description: Reads permit applications in the office. + principalClaim: sub + requiredScopes: ["registry:permit:read"] + permissions: + records: + - recordType: permit-application + operations: [get] + readableFields: [activity, site, office, status] + rowBoundaries: + - {field: office, claim: registry_office, operator: equals} + permit-coordinator: + actorKind: service + requesterClients: [permit-coordinator] + display: + label: Permit Coordinator + description: Records reviewed decisions on submitted applications. + principalClaim: sub + requiredScopes: ["registry:permit:decide"] + permissions: + records: + - recordType: permit-application + operations: [get] + readableFields: [activity, site, office, status] + rowBoundaries: + - {field: office, claim: registry_office, operator: equals} + actions: + - action: approve-application + operations: [invoke] + targets: + - recordType: permit-application + rowBoundaries: + - {field: office, claim: registry_office, operator: equals} + results: [decided-application] + - action: refuse-application + operations: [invoke] + targets: + - recordType: permit-application + rowBoundaries: + - {field: office, claim: registry_office, operator: equals} + results: [decided-application] + +vocabularies: + application-status: + values: [submitted, approved, refused] diff --git a/products/platform/examples/service-previews/permit-review/service.yaml b/products/platform/examples/service-previews/permit-review/service.yaml new file mode 100644 index 0000000000..5755e57c86 --- /dev/null +++ b/products/platform/examples/service-previews/permit-review/service.yaml @@ -0,0 +1,40 @@ +apiVersion: id.registrystack.org/formats/rstack/service/v1alpha1 +kind: RStackService +service: {manifest: manifest.yaml, publicService: review-a-permit} +products: + breg: + projects: + permits: {path: project} + casework: {path: casework} + coordinator: + projects: + permit-flow: {path: coordinator} +ui: {project: web, output: dist} +functions: [assess-permit] +roles: + applicant: + actorKind: human + claims: [registry_office] + accessProfiles: + breg: [permit-applicant] + casework: [permit-applicant] + coordinator: [permit-starter] + officer: + actorKind: human + claims: [registry_office] + accessProfiles: + breg: [permit-reader] + casework: [permit-officer] + administrator: + actorKind: human + accessProfiles: + casework: [permit-administrator] + coordinator-producer: + actorKind: service + accessProfiles: + casework: [coordinator-producer] + coordinator-service: + actorKind: service + claims: [registry_office] + accessProfiles: + breg: [permit-coordinator] diff --git a/products/platform/examples/service-previews/permit-review/web/public/index.html b/products/platform/examples/service-previews/permit-review/web/public/index.html new file mode 100644 index 0000000000..9e7d97d3a4 --- /dev/null +++ b/products/platform/examples/service-previews/permit-review/web/public/index.html @@ -0,0 +1,61 @@ + + + + + + Apply for a reviewed permit + + + + + +
Registry Stack demonstration
+
Permit review
+
+

Apply for a reviewed permit

+ +

+ + +
+ + diff --git a/products/platform/examples/service-previews/permit-review/web/public/service.css b/products/platform/examples/service-previews/permit-review/web/public/service.css new file mode 100644 index 0000000000..4f0edde4f0 --- /dev/null +++ b/products/platform/examples/service-previews/permit-review/web/public/service.css @@ -0,0 +1,29 @@ +* { box-sizing: border-box; } +body { + margin: 0; + background: #f7f3f3; + color: #2c2c2c; + font: 18px/1.5 system-ui, sans-serif; +} +.skip-link { position: absolute; left: -9999px; } +.skip-link:focus { left: 1rem; top: 1rem; background: white; padding: 0.75rem; } +.official-banner { background: #2c2c2c; color: white; padding: 0.5rem 1.5rem; text-align: center; font-size: 0.8rem; } +header { background: #ffc726; border-bottom: 3px solid #2c2c2c; padding: 1rem 1.5rem; font-size: 1.35rem; font-weight: 700; } +main { max-width: 46rem; margin: 2rem auto; padding: 0 1.5rem; } +h1 { font-size: 2.25rem; line-height: 1.2; } +.field { margin: 1.75rem 0; } +label { display: block; font-size: 1.15rem; font-weight: 700; } +.hint { display: block; color: #595959; font-size: 1rem; margin-bottom: 0.5rem; } +input { width: 100%; max-width: 32rem; border: 2px solid #2c2c2c; padding: 0.65rem; font: inherit; } +input:focus, button:focus, a:focus { outline: 4px solid #ffc726; outline-offset: 2px; } +button { border: 0; background: #00703c; color: white; padding: 0.75rem 1.5rem; font: inherit; font-weight: 700; cursor: pointer; } +button:disabled { opacity: 0.7; cursor: default; } +.error:not(:empty) { border: 4px solid #b71c1c; padding: 1rem; } +.confirmation { margin-top: 2rem; background: #e8f5e9; border-left: 6px solid #00703c; padding: 1rem 1.25rem; } +.confirmation h2 { margin-top: 0; } +dl { background: white; margin-bottom: 0; } +dl div { display: grid; grid-template-columns: minmax(9rem, 1fr) 2fr; gap: 1rem; border-bottom: 1px solid #ddd; padding: 0.75rem; } +dl div:last-child { border-bottom: 0; } +dt { font-weight: 700; } +dd { margin: 0; overflow-wrap: anywhere; } +[hidden], #error:empty, #status:empty { display: none; } diff --git a/products/platform/examples/service-previews/permit-review/web/src/page.ts b/products/platform/examples/service-previews/permit-review/web/src/page.ts new file mode 100644 index 0000000000..3b495fa6b6 --- /dev/null +++ b/products/platform/examples/service-previews/permit-review/web/src/page.ts @@ -0,0 +1,177 @@ +// One built page serves every actor. Each actor's gateway origin answers +// /_rstack/actor and relays only that actor's paths with that actor's own +// credential, so the page never holds a credential or chooses a profile. + +type Json = Record + +function element(id: string): T { + const node = document.getElementById(id) + if (!node) throw new Error('The page needs #' + id) + return node as T +} + +function text(value: FormDataEntryValue | null, maximumLength: number) { + if (typeof value !== 'string') return undefined + const bounded = value.trim() + return bounded.length > 0 && bounded.length <= maximumLength ? bounded : undefined +} + +function field(value: unknown, ...path: string[]): unknown { + return path.reduce((node, key) => + typeof node === 'object' && node !== null ? (node as Json)[key] : undefined, value) +} + +async function call(path: string, init: { method?: string; body?: unknown; headers?: Record } = {}) { + const response = await fetch(path, { + method: init.method ?? 'GET', + credentials: 'same-origin', + headers: { + Accept: 'application/json', + 'Registry-Client': 'page', + ...(init.body === undefined ? {} : { 'Content-Type': 'application/json' }), + ...init.headers, + }, + body: init.body === undefined ? undefined : JSON.stringify(init.body), + }) + const body: unknown = response.status === 204 ? null : await response.json().catch(() => null) + return { status: response.status, body } +} + +async function digest(value: string) { + const bytes = new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(value))) + return 'sha256:' + Array.from(bytes, byte => byte.toString(16).padStart(2, '0')).join('') +} + +const alert = element('error') +const status = element('status') + +async function applicant() { + element('applicant').hidden = false + const form = element('application') + form.addEventListener('submit', async (event) => { + event.preventDefault() + alert.textContent = '' + const data = new FormData(form) + const activity = text(data.get('activity'), 160) + const site = text(data.get('site'), 160) + if (!activity || !site) { + alert.textContent = 'Enter an activity and a site within the stated limits.' + return + } + element('submit').disabled = true + status.textContent = 'Submitting the application.' + try { + const submitted = await call('/registry/permits/v1/actions/submit-application', { + method: 'POST', headers: { 'Idempotency-Key': crypto.randomUUID() }, + body: { input: { activity, site } }, + }) + const recordId = field(submitted.body, 'results', 'application', 'recordId') + if (submitted.status !== 200 || typeof recordId !== 'string') throw new Error('submit') + const record = await call('/registry/permits/v1/records/permit-applications/' + recordId) + const revisionId = field(record.body, 'data', 'revisionId') + if (record.status !== 200 || typeof revisionId !== 'string') throw new Error('read') + element('application-id').textContent = recordId + + const contract = await call('/registry/permit-flow/v1/workflows/permit-flow') + const workflowRevision = field(contract.body, 'workflowRevision') + if (contract.status !== 200 || typeof workflowRevision !== 'string') throw new Error('workflow') + const started = await call('/registry/permit-flow/v1/runs', { + method: 'POST', headers: { 'Idempotency-Key': crypto.randomUUID() }, + body: { + workflow: 'permit-flow', workflowRevision, + input: { + applicationId: recordId, applicationRevision: revisionId, + applicationDigest: await digest(recordId + ':' + revisionId), activity, site, + }, + }, + }) + const runId = field(started.body, 'runId') + if (started.status !== 200 || typeof runId !== 'string') throw new Error('start') + element('run-id').textContent = runId + element('submitted').hidden = false + form.hidden = true + status.textContent = '' + await follow(runId, recordId) + } catch { + alert.textContent = 'We could not submit the application and start its review.' + status.textContent = '' + element('submit').disabled = false + } + }) + + // The applicant's own attempt to decide: Casework, not the page, refuses it. + const attempt = element('decision-attempt') + attempt.addEventListener('submit', async (event) => { + event.preventDefault() + const taskId = text(new FormData(attempt).get('taskId'), 64) + if (!taskId) return + const decided = await call('/registry/casework/v1/review-tasks/' + taskId + '/decisions', { + method: 'POST', headers: { 'If-Match': '"1"', 'Idempotency-Key': crypto.randomUUID() }, + body: { decision: { type: 'approve', outcome: 'approved' } }, + }) + element('decision-attempt-result').textContent = decided.status === 403 + ? 'Casework refused the decision (403).' + : 'Casework answered ' + decided.status + '.' + }) +} + +async function follow(runId: string, recordId: string) { + for (;;) { + const run = await call('/registry/permit-flow/v1/runs/' + runId) + const state = field(run.body, 'state') + element('run-step').textContent = String(field(run.body, 'step') ?? '') + element('run-state').textContent = String(state ?? '') + if (state === 'finished' || state === 'failed' || state === 'cancelled') { + element('run-outcome').textContent = String(field(run.body, 'outcome') ?? '') + element('run-assessment').textContent = String(field(run.body, 'output', 'assessment') ?? '') + const record = await call('/registry/permits/v1/records/permit-applications/' + recordId) + element('application-status').textContent = String(field(record.body, 'data', 'domainData', 'status') ?? '') + return + } + await new Promise(resolve => setTimeout(resolve, 1000)) + } +} + +async function officer() { + element('officer').hidden = false + const list = element('tasks') + element('refresh').addEventListener('click', async () => { + const tasks = await call('/registry/casework/v1/review-tasks?queue=permit-officers') + const items = field(tasks.body, 'items') + list.replaceChildren() + for (const task of Array.isArray(items) ? items : []) { + const taskId = field(task, 'taskId') + const revision = field(task, 'revision') + if (typeof taskId !== 'string') continue + const item = document.createElement('li') + item.dataset.taskId = taskId + const label = document.createElement('span') + label.className = 'task-id' + label.textContent = taskId + const approve = document.createElement('button') + approve.textContent = 'Claim and approve' + approve.addEventListener('click', async () => { + approve.disabled = true + const claimed = await call('/registry/casework/v1/review-tasks/' + taskId + '/claim', { + method: 'POST', headers: { 'If-Match': '"' + String(revision) + '"', 'Idempotency-Key': crypto.randomUUID() }, + }) + const claimRevision = field(claimed.body, 'revision') + const decided = await call('/registry/casework/v1/review-tasks/' + taskId + '/decisions', { + method: 'POST', headers: { 'If-Match': '"' + String(claimRevision) + '"', 'Idempotency-Key': crypto.randomUUID() }, + body: { decision: { type: 'approve', outcome: 'approved' } }, + }) + item.dataset.decided = String(decided.status) + approve.textContent = decided.status === 204 ? 'Approved' : 'Casework answered ' + decided.status + }) + item.append(label, ' ', approve) + list.append(item) + } + }) +} + +const whoami = await call('/_rstack/actor') +const actor = field(whoami.body, 'actor') +element('actor').textContent = String(actor ?? '') +if (actor === 'applicant') await applicant() +else if (actor === 'officer') await officer() +else alert.textContent = 'This page does not know the signed-in actor.' diff --git a/products/platform/examples/service-previews/permit-review/web/tsconfig.json b/products/platform/examples/service-previews/permit-review/web/tsconfig.json new file mode 100644 index 0000000000..9d2bcc4a8a --- /dev/null +++ b/products/platform/examples/service-previews/permit-review/web/tsconfig.json @@ -0,0 +1,11 @@ +{ + "compilerOptions": { + "lib": ["DOM", "ES2023"], + "module": "NodeNext", + "moduleResolution": "NodeNext", + "noEmit": true, + "strict": true, + "target": "ES2023" + }, + "include": ["src/**/*.ts"] +} diff --git a/products/platform/scripts/prepare-service-preview-locks.mjs b/products/platform/scripts/prepare-service-preview-locks.mjs index 482a22c651..a857930729 100644 --- a/products/platform/scripts/prepare-service-preview-locks.mjs +++ b/products/platform/scripts/prepare-service-preview-locks.mjs @@ -59,7 +59,7 @@ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) assert.ok(archive && directory && extra.length === 0 && [archive, directory].every(isAbsolute), 'Usage: node prepare-service-preview-locks.mjs /absolute/client.tgz /absolute/service-previews') const client = await previewClientArchive(archive) - for (const name of ['medical-renewal', 'business-registration']) { + for (const name of ['medical-renewal', 'business-registration', 'permit-review']) { await stagePreviewClient(join(directory, name), client, { pin: true }) } } From 814a7d5ea3f53e4b7a4b9827f6898ba2dd5bbbe6 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 23:43:36 +0000 Subject: [PATCH 145/183] fix(coordinator): compare function host keys as bytes 26c030cb0 compared a service function's key with every other key in the runtime through resolve_reference, which refuses NUL bytes as text. Key files hold random bytes, so a deployment, state, admission or completion key with a NUL stopped every start with adapter.configuration. About half of permit-review preview starts failed this way. The comparison only hashes the bytes or reads a JWK, so it now resolves binary references, and a test starts a function host beside a completion key holding a NUL. Signed-off-by: Jeremi Joslin --- crates/registry-coordinator/src/adapters.rs | 3 +- .../tests/service_function.rs | 39 +++++++++++++++++++ 2 files changed, 41 insertions(+), 1 deletion(-) diff --git a/crates/registry-coordinator/src/adapters.rs b/crates/registry-coordinator/src/adapters.rs index 8f214e6e8b..067b6f0169 100644 --- a/crates/registry-coordinator/src/adapters.rs +++ b/crates/registry-coordinator/src/adapters.rs @@ -474,9 +474,10 @@ fn distinct_function_keys( secrets: ®istry_platform_config::SecretResolver, ) -> Result<()> { use sha2::Digest as _; + // Key files may hold binary material with NUL bytes, so compare bytes. let identity = |reference: ®istry_platform_config::SecretReference| -> Result { let secret = secrets - .resolve_reference(reference) + .resolve_binary_reference(reference) .map_err(|_| config_error())?; let bytes = secret.expose_secret(); let jwk = std::str::from_utf8(bytes) diff --git a/crates/registry-coordinator/tests/service_function.rs b/crates/registry-coordinator/tests/service_function.rs index d512776a92..797a31deaa 100644 --- a/crates/registry-coordinator/tests/service_function.rs +++ b/crates/registry-coordinator/tests/service_function.rs @@ -907,6 +907,45 @@ fn rotating_the_host_key_keeps_the_binding_and_changing_the_credential_kind_does ); } +#[test] +fn a_binary_key_elsewhere_in_the_runtime_does_not_stop_a_function_host_from_starting() { + // Binary key files hold random bytes, NUL included. Comparing the + // function host key with them must read them as bytes, not as text. + let mut document = host_key_document("http://127.0.0.1:9020/"); + document["connections"] + .as_object_mut() + .unwrap() + .remove("registry"); + document["connections"]["review"] = json!({ + "type":"casework-review-producer", "baseUrl":"http://127.0.0.1:9022", + "profile":"coordinator-producer", "producer":"coordinator", + "authorization":{ + "tokenEndpoint":"http://127.0.0.1:9999/token", + "clientAssertionAudience":"http://127.0.0.1:9999", + "clientId":"coordinator-producer", + "signingKeyRef":"secret:file/review-client-key", + "resource":"urn:example:review", + "scopes":["casework:review"] + }, + "completion":{ + "recipientBinding":"coordinator-v1", + "hmacSha256KeyRef":"secret:file/review-completion-key" + } + }); + let (_root, config) = with_secrets( + &document, + &[ + ("function-host-key", "synthetic-function-host-key-canary"), + ("review-client-key", KEY), + ( + "review-completion-key", + "binary\0completion-key-0123456789abcdef", + ), + ], + ); + registry_coordinator::adapters::HttpAdapters::new(&config).unwrap(); +} + #[test] fn the_same_host_key_or_jwk_under_another_form_is_refused_at_startup() { const HOST_KEY: &str = "synthetic-function-host-key-canary"; From 27741d01baed635ff8b428665ac8a7634e1916b0 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 23:43:49 +0000 Subject: [PATCH 146/183] fix(dev): review and decide only the permit application the Coordinator reads The permit-review run took its review subject, snapshot, digest and assessment input from the applicant's page, then decided the named application under the Coordinator's own BReg authority. An applicant could show the reviewer one content and have another record decided. - The run input is only applicationId. The first step reads the application under the Coordinator's permit-coordinator profile, and a run whose application is no longer submitted stops. - The Casework subject, snapshot and assessment input come from that read. Coordinator Functions cannot hash, so a credential-free digest-application service function hashes the read content for the Casework subject digest, through a second service-function connection. - approve-application and refuse-application take the activity and site the Coordinator read and guard them with equalsFromInput, with status submitted, in the same write. BReg target-condition tokens are opaque and only BReg issues them, so the Coordinator cannot pin the read revision; no profile can change activity or site, so the content guard binds the decision to the reviewed content. - The applicant's BReg profile reads no application. The officer page shows the Casework task context before claiming, claims and approves in separate steps, and reads applications from the register. - A neighbour applicant, submitted by the startup journey, gives the preview a second application and an origin that cannot read another applicant's run (Coordinator status is owner-scoped). - The BReg project gains the tests/journeys.yaml a real start requires: a decision refused for other content, accepted for the content read, and refused once decided. They run as a separate register-tester person, so the Coordinator's BReg identity stays dedicated. - The page starts from one async call, as the preview bundle is a classic script, and stops following a run in any state but running or cancel-requested. - The docs describe GET /_rstack/actor. Signed-off-by: Jeremi Joslin --- .../run-a-project-with-rstack-dev.mdx | 4 + .../service-previews/permit-review/README.md | 69 +++++++--- .../permit-review/coordinator/README.md | 8 +- .../already-decided-is-not-reviewed.yaml | 28 ++++ .../approved-assessed-and-recorded.yaml | 38 ++++-- .../rejected-recorded-without-assessment.yaml | 37 +++-- .../permit-review/coordinator/functions.rhai | 53 ++++--- .../generated/permits.contract.json | 2 +- .../permit-review/coordinator/runtime.yaml | 12 +- .../permit-review/coordinator/workflow.yaml | 129 +++++++++++++++--- .../permit-review/dev-journeys.yaml | 11 ++ .../service-previews/permit-review/dev.yaml | 27 +++- .../functions/assess-permit/index.ts | 7 +- .../functions/digest-application/digest.ts | 33 +++++ .../functions/digest-application/index.ts | 7 + .../permit-review/project/registry.yaml | 28 ++-- .../permit-review/project/tests/journeys.yaml | 115 ++++++++++++++++ .../permit-review/service.yaml | 2 +- .../permit-review/web/public/index.html | 14 +- .../permit-review/web/src/page.ts | 105 +++++++++----- 20 files changed, 588 insertions(+), 141 deletions(-) create mode 100644 products/platform/examples/service-previews/permit-review/coordinator/fixtures/already-decided-is-not-reviewed.yaml create mode 100644 products/platform/examples/service-previews/permit-review/functions/digest-application/digest.ts create mode 100644 products/platform/examples/service-previews/permit-review/functions/digest-application/index.ts create mode 100644 products/platform/examples/service-previews/permit-review/project/tests/journeys.yaml diff --git a/docs/site/src/content/docs/configure/run-a-project-with-rstack-dev.mdx b/docs/site/src/content/docs/configure/run-a-project-with-rstack-dev.mdx index 51782f6e2c..297d45bc62 100644 --- a/docs/site/src/content/docs/configure/run-a-project-with-rstack-dev.mdx +++ b/docs/site/src/content/docs/configure/run-a-project-with-rstack-dev.mdx @@ -82,6 +82,10 @@ under `/registry/`, and the Coordinator path takes no query. An actors preview r Casework project and one Coordinator project at most. Every actor has a BReg grant, so every preview function is callable from every actor's origin, and runs under that actor's own BReg credential. +One built page serves every actor, so it asks its own origin which actor it serves: +`GET /_rstack/actor` answers `{"actor": NAME}`. It carries no credential and selects nothing, +and it answers only the page: a request without `Registry-Client: page`, or with a foreign +`Origin` or a cross-site `Sec-Fetch-Site`, gets 403. The generated client names no Proposal author in an actors preview, because each actor's origin pins its own BReg profile. A register with Proposals therefore needs the single-actor form, and the build refuses it in an actors preview. diff --git a/products/platform/examples/service-previews/permit-review/README.md b/products/platform/examples/service-previews/permit-review/README.md index 96b0318006..05c54e72a3 100644 --- a/products/platform/examples/service-previews/permit-review/README.md +++ b/products/platform/examples/service-previews/permit-review/README.md @@ -1,18 +1,23 @@ # Apply for a reviewed permit This preview runs one permit application through four products. The applicant -submits it to BReg and starts a Coordinator run. The run asks Casework for a -review and waits. An officer approves it in Casework. The run then records an -assessment from the `assess-permit` service function and records the decision -in BReg under the Coordinator's own BReg profile. +submits it to BReg and starts a Coordinator run that names only the +application. The Coordinator reads the application under its own BReg +profile, asks Casework to review the content it read, and waits. An officer +reads that content in Casework, claims the task and approves it. The run then +asks the `assess-permit` service function for an assessment and records the +decision in BReg. Start it using the [preview instructions](../README.md). It also needs `casework`, `caseworkctl`, `coordinator` and `coordinatorctl` from the same release. `rstack dev start` prints one URL per actor. Every URL serves the same built page, and each origin acts for one synthetic person: -- the applicant's origin submits an application, starts the run and follows it; -- the officer's origin lists the queue, claims a task and approves it. +- the applicant's origin submits an application, starts the run and follows it. +- the officer's origin lists the queue with the content under review, claims a + task, approves it, and reads an application from the register. +- the neighbour's origin is a second applicant, whose application the startup + journey submits. It cannot follow the applicant's run. From the applicant's origin, enter a task ID in **Decide a review task**. Casework refuses that decision with 403, because the applicant's Casework @@ -21,22 +26,54 @@ profile may ask for a review but never decide one. Serving each actor from its own origin is a development substitution for a real sign-in. A deployment serves one origin and signs each person in. -- [service.yaml](service.yaml) names the products, the page, the function and - each role's access profiles. +## What the applicant controls + +The applicant chooses which application a run names, and nothing else. The +Coordinator reads that application itself. The review subject, the content the +officer sees, the assessment input and the decision all come from that read. +A run that names another applicant's application reviews and decides that +application as stored, never content the applicant supplied. A deployment's +starting service also checks that the applicant owns the application it names +before it starts the run. This preview leaves that check out. + +The decision Actions take the activity and site the Coordinator read and guard +them, with the submitted status, in the same write. A BReg target-condition +token would pin the exact revision, but the token is opaque and only BReg can +issue it, so the Coordinator cannot derive one from its read. The content guard +binds the decision to the reviewed content instead: no profile can change an +application's activity or site, and a decided application is no longer +submitted. + +Casework requires a sha256 digest of the review subject, and Coordinator +Transforms cannot hash. The `digest-application` service function hashes the +content the Coordinator read, and the Coordinator calls it before it asks for +the review. + +## Files + +- [service.yaml](service.yaml) names the products, the page, the two functions + and each role's access profiles. - [The BReg project](project/registry.yaml) defines the application Record, the applicant's submission Action and the two decision Actions that only the - Coordinator's profile may invoke. + Coordinator's profile may invoke. The applicant reads no application. Its + [native journeys](project/tests/journeys.yaml) show a decision refused for + other content and refused once decided. - [The Casework project](casework/casework.yaml) defines the review policy, - the officers' queue and the Coordinator as its one trusted producer. -- [The Coordinator project](coordinator/workflow.yaml) asks for the review, - waits for its result, records the assessment and then the decision. Its - [fixtures](coordinator/fixtures) cover the approved and refused paths. -- [The assessment function](functions/assess-permit/index.ts) returns advice - from the application's activity and site. It holds no registry credential. + the officers' queue and the Coordinator as its one trusted producer. Casework + requires a profile that acts as supervisor, so `permit-supervisor` exists + although no person in this preview holds it. +- [The Coordinator project](coordinator/workflow.yaml) reads the application, + digests it, asks for the review, waits for its result, assesses the approved + content and records the decision. Its [fixtures](coordinator/fixtures) cover + the approved and refused paths and an application already decided. +- [The assessment function](functions/assess-permit/index.ts) and [the digest + function](functions/digest-application/index.ts) hold no registry + credential. Each answers only from the content the Coordinator sends. - [dev.yaml](dev.yaml) declares the synthetic people, binds the Coordinator's Casework and BReg connections to run-local machine identities and lists each actor's preview routes. -- [The startup journey](dev-journeys.yaml) staffs the officers' queue. +- [The startup journeys](dev-journeys.yaml) staff the officers' queue and submit + the neighbour's application. - [The page code](web/src/page.ts) asks its origin which actor it serves and shows that actor's controls. diff --git a/products/platform/examples/service-previews/permit-review/coordinator/README.md b/products/platform/examples/service-previews/permit-review/coordinator/README.md index c59a444ea0..31870da2d3 100644 --- a/products/platform/examples/service-previews/permit-review/coordinator/README.md +++ b/products/platform/examples/service-previews/permit-review/coordinator/README.md @@ -14,4 +14,10 @@ cp /tmp/permits-actions/generated/action-contracts.json \ The runtime template names HTTPS reference endpoints and secret references. Under `rstack dev`, the bindings in `dev.yaml` replace the review and permits -connections, and the preview function host replaces the assessor's. +connections, and the preview function host replaces the digester's and the +assessor's. + +The run input is only the application ID. Every later step uses the +Coordinator's own read of the application, and the decision Actions guard the +read content, as [the preview README](../README.md#what-the-applicant-controls) +explains. diff --git a/products/platform/examples/service-previews/permit-review/coordinator/fixtures/already-decided-is-not-reviewed.yaml b/products/platform/examples/service-previews/permit-review/coordinator/fixtures/already-decided-is-not-reviewed.yaml new file mode 100644 index 0000000000..af66282339 --- /dev/null +++ b/products/platform/examples/service-previews/permit-review/coordinator/fixtures/already-decided-is-not-reviewed.yaml @@ -0,0 +1,28 @@ +# yaml-language-server: $schema=https://id.registrystack.org/schemas/coordinator/fixture/fixture.v1alpha1.schema.json +apiVersion: id.registrystack.org/formats/coordinator/fixture/v1alpha1 +kind: CoordinatorFixture +id: already-decided-is-not-reviewed +admittedAt: '2026-12-01T09:00:00Z' +input: + applicationId: 00000000-0000-4000-8000-000000000001 +replies: + read-application: + - type: success + value: + '@context': https://id.registrystack.org/contexts/registry-record/v1 + data: + recordId: 00000000-0000-4000-8000-000000000001 + revisionId: '1' + domainData: + activity: Night resurfacing + site: North road + office: central + status: approved + meta: + registryId: permit-register + datasetId: applications + recordTypeId: permit-application +expect: + path: [read-application, check-submitted, not-submitted] + state: completed + outcome: {type: named, value: not-submitted} diff --git a/products/platform/examples/service-previews/permit-review/coordinator/fixtures/approved-assessed-and-recorded.yaml b/products/platform/examples/service-previews/permit-review/coordinator/fixtures/approved-assessed-and-recorded.yaml index 55870f8d49..deb180b442 100644 --- a/products/platform/examples/service-previews/permit-review/coordinator/fixtures/approved-assessed-and-recorded.yaml +++ b/products/platform/examples/service-previews/permit-review/coordinator/fixtures/approved-assessed-and-recorded.yaml @@ -5,11 +5,29 @@ id: approved-assessed-and-recorded admittedAt: '2026-12-01T09:00:00Z' input: applicationId: 00000000-0000-4000-8000-000000000001 - applicationRevision: '1' - applicationDigest: sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa - activity: Night resurfacing - site: North road replies: + read-application: + - type: success + value: + '@context': https://id.registrystack.org/contexts/registry-record/v1 + data: + recordId: 00000000-0000-4000-8000-000000000001 + revisionId: '1' + domainData: + activity: Night resurfacing + site: North road + office: central + status: submitted + meta: + registryId: permit-register + datasetId: applications + recordTypeId: permit-application + digest: + - type: response + value: + status: 200 + body: + digest: sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa request-review: - type: success value: @@ -63,17 +81,9 @@ waits: completedAt: '2026-12-02T09:00:00Z' availableUntil: '2027-01-02T09:00:00Z' expect: - path: - - request-review - - await-review - - decide - - assess - - approve - - approved + path: [read-application, check-submitted, digest, request-review, await-review, decide, assess, approve, approved] state: completed - outcome: - type: named - value: approved + outcome: {type: named, value: approved} output: assessment: conditions resultId: 00000000-0000-4000-8000-000000000011 diff --git a/products/platform/examples/service-previews/permit-review/coordinator/fixtures/rejected-recorded-without-assessment.yaml b/products/platform/examples/service-previews/permit-review/coordinator/fixtures/rejected-recorded-without-assessment.yaml index 824fb9ccd2..a98c48b465 100644 --- a/products/platform/examples/service-previews/permit-review/coordinator/fixtures/rejected-recorded-without-assessment.yaml +++ b/products/platform/examples/service-previews/permit-review/coordinator/fixtures/rejected-recorded-without-assessment.yaml @@ -5,11 +5,29 @@ id: rejected-recorded-without-assessment admittedAt: '2026-12-01T09:00:00Z' input: applicationId: 00000000-0000-4000-8000-000000000001 - applicationRevision: '1' - applicationDigest: sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa - activity: Night resurfacing - site: North road replies: + read-application: + - type: success + value: + '@context': https://id.registrystack.org/contexts/registry-record/v1 + data: + recordId: 00000000-0000-4000-8000-000000000001 + revisionId: '1' + domainData: + activity: Night resurfacing + site: North road + office: central + status: submitted + meta: + registryId: permit-register + datasetId: applications + recordTypeId: permit-application + digest: + - type: response + value: + status: 200 + body: + digest: sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa request-review: - type: success value: @@ -57,15 +75,8 @@ waits: completedAt: '2026-12-02T09:00:00Z' availableUntil: '2027-01-02T09:00:00Z' expect: - path: - - request-review - - await-review - - decide - - refuse - - refused + path: [read-application, check-submitted, digest, request-review, await-review, decide, refuse, refused] state: completed - outcome: - type: named - value: refused + outcome: {type: named, value: refused} output: resultId: 00000000-0000-4000-8000-000000000011 diff --git a/products/platform/examples/service-previews/permit-review/coordinator/functions.rhai b/products/platform/examples/service-previews/permit-review/coordinator/functions.rhai index b346e9b294..6c5ead56bd 100644 --- a/products/platform/examples/service-previews/permit-review/coordinator/functions.rhai +++ b/products/platform/examples/service-previews/permit-review/coordinator/functions.rhai @@ -1,38 +1,59 @@ // Pure Function ABI: one typed object of named inputs, one typed output. +// Every value below comes from the Coordinator's own read of the +// application, never from the starter's input. + +fn submitted_route(args) { + if args.record.data.domainData.status == "submitted" { "submitted" } else { "not-submitted" } +} + +fn digest_request(args) { + let data = args.record.data; + #{ + applicationId: data.recordId, + revisionId: data.revisionId, + activity: data.domainData.activity, + site: data.domainData.site + } +} + +// Only a well-formed digest settles the call. Anything else is uncertain, +// so the run holds for same-command recovery instead of guessing. +fn digest_outcome(args) { + let response = args.response; + if response.status == 200 && "digest" in response.body { + return #{state: "accepted", result: #{digest: response.body.digest}}; + } + #{state: "uncertain"} +} -// The page that starts the run supplies the application's revision and an -// opaque digest of it. Casework keeps them as the subject's version. fn review_request(args) { - let input = args["input"]; + let data = args.record.data; #{ policy: #{id: "permit-review"}, subject: #{ source: "permits", type: "permit-application", - id: input.applicationId, - version: input.applicationRevision, - digest: input.applicationDigest + id: data.recordId, + version: data.revisionId, + digest: args.digest.digest }, - requesterReference: input.applicationId, + requesterReference: data.recordId, context: #{ mode: "submitted", - snapshot: #{activity: input.activity, site: input.site} + snapshot: #{activity: data.domainData.activity, site: data.domainData.site} } } } fn assess_request(args) { - let input = args["input"]; - #{applicationId: input.applicationId, activity: input.activity, site: input.site} + let data = args.record.data; + #{applicationId: data.recordId, activity: data.domainData.activity, site: data.domainData.site} } -// Only a recognised answer settles the call. Anything else is uncertain, so -// the run holds for same-command recovery instead of guessing. fn assess_outcome(args) { - let status = args.response.status; - let body = args.response.body; - if status == 200 && "assessment" in body { - return #{state: "accepted", result: #{assessment: body.assessment}}; + let response = args.response; + if response.status == 200 && "assessment" in response.body { + return #{state: "accepted", result: #{assessment: response.body.assessment}}; } #{state: "uncertain"} } diff --git a/products/platform/examples/service-previews/permit-review/coordinator/generated/permits.contract.json b/products/platform/examples/service-previews/permit-review/coordinator/generated/permits.contract.json index 0816d3623c..ff00577e62 100644 --- a/products/platform/examples/service-previews/permit-review/coordinator/generated/permits.contract.json +++ b/products/platform/examples/service-previews/permit-review/coordinator/generated/permits.contract.json @@ -1 +1 @@ -{"actions":[{"display":{"description":"Record an approved review decision on one submitted application.","label":"Approve application"},"id":"approve-application","input":{"$id":"urn:breg:action:approve-application:invoke-input","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"input":{"additionalProperties":false,"properties":{"applicationId":{"format":"uuid","type":"string"}},"required":["applicationId"],"type":"object"},"preconditions":{"additionalProperties":false,"properties":{},"required":[],"type":"object"}},"required":["input"],"type":"object","x-registry-action":"approve-application","x-registry-requiredConditionKeys":[]},"mode":"immediate","output":{"$id":"urn:breg:action:approve-application:invoke-response","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"action":{"const":"approve-application"},"applicationId":{"format":"uuid","type":"string"},"results":{"additionalProperties":false,"properties":{"decided-application":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"const":"permit-application"},"revision":{"format":"int64","minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"}},"required":["decided-application"],"type":"object"}},"required":["action","applicationId","results"],"type":"object"},"revision":"sha256:002f25130195be270d98480a05336cab550e7ebca562263dbed5071d6659160a"},{"display":{"description":"Record a refused review decision on one submitted application.","label":"Refuse application"},"id":"refuse-application","input":{"$id":"urn:breg:action:refuse-application:invoke-input","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"input":{"additionalProperties":false,"properties":{"applicationId":{"format":"uuid","type":"string"}},"required":["applicationId"],"type":"object"},"preconditions":{"additionalProperties":false,"properties":{},"required":[],"type":"object"}},"required":["input"],"type":"object","x-registry-action":"refuse-application","x-registry-requiredConditionKeys":[]},"mode":"immediate","output":{"$id":"urn:breg:action:refuse-application:invoke-response","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"action":{"const":"refuse-application"},"applicationId":{"format":"uuid","type":"string"},"results":{"additionalProperties":false,"properties":{"decided-application":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"const":"permit-application"},"revision":{"format":"int64","minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"}},"required":["decided-application"],"type":"object"}},"required":["action","applicationId","results"],"type":"object"},"revision":"sha256:345ab8daadc77f82e59ff3923b39bcf036e7d86a3b6ad0899fe13f9e4b5ce3dc"},{"display":{"description":"Create a submitted permit application from bounded applicant input.","label":"Submit application"},"id":"submit-application","input":{"$id":"urn:breg:action:submit-application:invoke-input","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"input":{"additionalProperties":false,"properties":{"activity":{"maxLength":160,"minLength":1,"type":"string"},"site":{"maxLength":160,"minLength":1,"type":"string"}},"required":["activity","site"],"type":"object"},"preconditions":{"additionalProperties":false,"properties":{},"required":[],"type":"object"}},"required":["input"],"type":"object","x-registry-action":"submit-application","x-registry-requiredConditionKeys":[]},"mode":"immediate","output":{"$id":"urn:breg:action:submit-application:invoke-response","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"action":{"const":"submit-application"},"applicationId":{"format":"uuid","type":"string"},"results":{"additionalProperties":false,"properties":{"application":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"const":"permit-application"},"revision":{"format":"int64","minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"}},"required":["application"],"type":"object"}},"required":["action","applicationId","results"],"type":"object"},"revision":"sha256:cc7a9aa7902efd4871eb5f1b391d153b4194d57634157307cbafcdc5d4c306ce"}],"apiVersion":"id.registrystack.org/formats/breg/action-contracts/v1","kind":"BRegActionContracts"} \ No newline at end of file +{"actions":[{"display":{"description":"Record an approved review decision on one submitted application.","label":"Approve application"},"id":"approve-application","input":{"$id":"urn:breg:action:approve-application:invoke-input","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"input":{"additionalProperties":false,"properties":{"activity":{"maxLength":160,"minLength":1,"type":"string"},"applicationId":{"format":"uuid","type":"string"},"site":{"maxLength":160,"minLength":1,"type":"string"}},"required":["applicationId","activity","site"],"type":"object"},"preconditions":{"additionalProperties":false,"properties":{"applicationId":{"additionalProperties":false,"properties":{"ifMatch":{"maxLength":256,"minLength":3,"pattern":"^\\\"[\\x21\\x23-\\x7E]+\\\"$","type":"string"}},"required":["ifMatch"],"type":"object"}},"required":["applicationId"],"type":"object"}},"required":["input","preconditions"],"type":"object","x-registry-action":"approve-application","x-registry-requiredConditionKeys":["applicationId"]},"mode":"immediate","output":{"$id":"urn:breg:action:approve-application:invoke-response","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"action":{"const":"approve-application"},"applicationId":{"format":"uuid","type":"string"},"results":{"additionalProperties":false,"properties":{"decided-application":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"const":"permit-application"},"revision":{"format":"int64","minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"}},"required":["decided-application"],"type":"object"}},"required":["action","applicationId","results"],"type":"object"},"revision":"sha256:12b02ec4592deda7491b223ae8863241ad3523f244db25f890c300ef74c1eb54"},{"display":{"description":"Record a refused review decision on one submitted application.","label":"Refuse application"},"id":"refuse-application","input":{"$id":"urn:breg:action:refuse-application:invoke-input","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"input":{"additionalProperties":false,"properties":{"activity":{"maxLength":160,"minLength":1,"type":"string"},"applicationId":{"format":"uuid","type":"string"},"site":{"maxLength":160,"minLength":1,"type":"string"}},"required":["applicationId","activity","site"],"type":"object"},"preconditions":{"additionalProperties":false,"properties":{"applicationId":{"additionalProperties":false,"properties":{"ifMatch":{"maxLength":256,"minLength":3,"pattern":"^\\\"[\\x21\\x23-\\x7E]+\\\"$","type":"string"}},"required":["ifMatch"],"type":"object"}},"required":["applicationId"],"type":"object"}},"required":["input","preconditions"],"type":"object","x-registry-action":"refuse-application","x-registry-requiredConditionKeys":["applicationId"]},"mode":"immediate","output":{"$id":"urn:breg:action:refuse-application:invoke-response","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"action":{"const":"refuse-application"},"applicationId":{"format":"uuid","type":"string"},"results":{"additionalProperties":false,"properties":{"decided-application":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"const":"permit-application"},"revision":{"format":"int64","minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"}},"required":["decided-application"],"type":"object"}},"required":["action","applicationId","results"],"type":"object"},"revision":"sha256:4acdc3bb77437045b615a2db97b63b31cc75369d72a7603de7f4cfebbdb9d72b"},{"display":{"description":"Create a submitted permit application from bounded applicant input.","label":"Submit application"},"id":"submit-application","input":{"$id":"urn:breg:action:submit-application:invoke-input","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"input":{"additionalProperties":false,"properties":{"activity":{"maxLength":160,"minLength":1,"type":"string"},"site":{"maxLength":160,"minLength":1,"type":"string"}},"required":["activity","site"],"type":"object"},"preconditions":{"additionalProperties":false,"properties":{},"required":[],"type":"object"}},"required":["input"],"type":"object","x-registry-action":"submit-application","x-registry-requiredConditionKeys":[]},"mode":"immediate","output":{"$id":"urn:breg:action:submit-application:invoke-response","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"action":{"const":"submit-application"},"applicationId":{"format":"uuid","type":"string"},"results":{"additionalProperties":false,"properties":{"application":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"const":"permit-application"},"revision":{"format":"int64","minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"}},"required":["application"],"type":"object"}},"required":["action","applicationId","results"],"type":"object"},"revision":"sha256:cc7a9aa7902efd4871eb5f1b391d153b4194d57634157307cbafcdc5d4c306ce"}],"apiVersion":"id.registrystack.org/formats/breg/action-contracts/v1","kind":"BRegActionContracts"} \ No newline at end of file diff --git a/products/platform/examples/service-previews/permit-review/coordinator/runtime.yaml b/products/platform/examples/service-previews/permit-review/coordinator/runtime.yaml index 5f79dc1ef9..83ded97e6a 100644 --- a/products/platform/examples/service-previews/permit-review/coordinator/runtime.yaml +++ b/products/platform/examples/service-previews/permit-review/coordinator/runtime.yaml @@ -3,7 +3,7 @@ apiVersion: id.registrystack.org/formats/coordinator/runtime/v1alpha1 kind: CoordinatorRuntimeConfig # Deployment references. Under `rstack dev` the bindings in dev.yaml replace # each connection's address and credential with run-local ones, and the -# preview function host replaces the assessor's. +# preview function host replaces each service function's. secretProviders: environment: {} file: @@ -39,11 +39,17 @@ connections: signingKeyRef: secret:file/permits-client-key resource: urn:example:permits scopes: [registry:permit:decide] + digester: + type: service-function + baseUrl: https://functions.example.org/ + function: digest-application + hostKeyRef: secret:file/function-host-key + responseSchema: {type: object} assessor: type: service-function baseUrl: https://functions.example.org/ function: assess-permit - hostKeyRef: secret:file/assessor-host-key + hostKeyRef: secret:file/function-host-key responseSchema: {type: object} deployment: databaseId: permit-flow @@ -63,7 +69,7 @@ deployment: accessProfiles: permit-starter: requesterClients: [permit-applicant] - subjects: [applicant] + subjects: [applicant, neighbour] requiredScopes: [coordinator:permit:start] workflows: [permit-flow] actions: [status, start] diff --git a/products/platform/examples/service-previews/permit-review/coordinator/workflow.yaml b/products/platform/examples/service-previews/permit-review/coordinator/workflow.yaml index a5e07434bd..7fb5b2b46d 100644 --- a/products/platform/examples/service-previews/permit-review/coordinator/workflow.yaml +++ b/products/platform/examples/service-previews/permit-review/coordinator/workflow.yaml @@ -1,7 +1,9 @@ # yaml-language-server: $schema=https://id.registrystack.org/schemas/coordinator/project/project.v1alpha1.schema.json -# One permit application: Casework decides, the assess-permit service function -# records an assessment, and BReg records the decision under the Coordinator's -# own BReg profile. The Coordinator owns none of those decisions. +# One permit application. The starter names only the application; the +# Coordinator reads it under its own BReg profile, and everything it asks +# Casework to review, assesses and decides comes from that read. Casework +# decides, the assess-permit function advises, and BReg records the decision +# only while the stored application still holds the content that was read. apiVersion: id.registrystack.org/formats/coordinator/project/v1alpha1 kind: CoordinatorProject project: @@ -15,30 +17,41 @@ types: workflow-input: type: object additionalProperties: false - required: [applicationId, applicationRevision, applicationDigest, activity, site] + required: [applicationId] properties: applicationId: {type: string, format: uuid} - applicationRevision: {type: string, minLength: 1, maxLength: 64} - applicationDigest: {type: string, pattern: '^sha256:[0-9a-f]{64}$'} - activity: {type: string, minLength: 1, maxLength: 160} - site: {type: string, minLength: 1, maxLength: 160} - assess-response: + function-response: type: object additionalProperties: false required: [status, body] properties: status: {type: integer, minimum: 200, maximum: 499} - body: - type: object - additionalProperties: false - properties: - assessment: {type: string, enum: [standard, conditions]} + body: {type: object} + digest: + type: object + additionalProperties: false + required: [digest] + properties: + digest: {type: string, pattern: '^sha256:[0-9a-f]{64}$'} assessment: type: object additionalProperties: false required: [assessment] properties: assessment: {type: string, enum: [standard, conditions]} + digest-outcome: + oneOf: + - type: object + additionalProperties: false + required: [state, result] + properties: + state: {type: string, const: accepted} + result: {typeRef: digest} + - type: object + additionalProperties: false + required: [state] + properties: + state: {type: string, const: uncertain} assess-outcome: oneOf: - type: object @@ -53,19 +66,42 @@ types: properties: state: {type: string, const: uncertain} transforms: + submitted-route: + runtime: rhai + source: functions.rhai + entrypoint: submitted_route + inputs: + record: {operationOutput: read-application} + output: {type: string, enum: [submitted, not-submitted]} + digest-request: + runtime: rhai + source: functions.rhai + entrypoint: digest_request + inputs: + record: {operationOutput: read-application} + output: {operationInput: digest-application} + digest-outcome: + runtime: rhai + source: functions.rhai + entrypoint: digest_outcome + inputs: + command: {operationInput: digest-application} + response: {operationOutput: digest-application} + output: {typeRef: digest-outcome} review-request: runtime: rhai source: functions.rhai entrypoint: review_request inputs: - input: {typeRef: workflow-input} + record: {operationOutput: read-application} + digest: {typeRef: digest} output: {operationInput: request-review} assess-request: runtime: rhai source: functions.rhai entrypoint: assess_request inputs: - input: {typeRef: workflow-input} + record: {operationOutput: read-application} output: {operationInput: assess-permit} assess-outcome: runtime: rhai @@ -76,6 +112,15 @@ transforms: response: {operationOutput: assess-permit} output: {typeRef: assess-outcome} operations: + read-application: + uses: breg.read-record/v1 + connection: permits + digest-application: + uses: service.invoke-function/v1 + connection: digester + serviceFunction: digest-application + responseSchema: {typeRef: function-response} + interpret: digest-outcome request-review: uses: casework.submit-review-request/v1 connection: review @@ -83,7 +128,7 @@ operations: uses: service.invoke-function/v1 connection: assessor serviceFunction: assess-permit - responseSchema: {typeRef: assess-response} + responseSchema: {typeRef: function-response} interpret: assess-outcome approve-application: uses: breg.invoke-action/v1 @@ -96,8 +141,38 @@ operations: workflow: input: {typeRef: workflow-input} deadlineSeconds: 2592000 - start: request-review + start: read-application steps: + read-application: + label: Read the application under the Coordinator's profile + type: call + operation: read-application + input: + type: fields + fields: + collection: {type: literal, value: permit-applications} + recordId: {type: input, path: /applicationId} + next: check-submitted + check-submitted: + type: choose + choose: + type: transform + transform: submitted-route + inputs: + record: {type: step, step: read-application} + cases: + submitted: digest + not-submitted: not-submitted + digest: + label: Digest the content read + type: call + operation: digest-application + input: + type: transform + transform: digest-request + inputs: + record: {type: step, step: read-application} + next: request-review request-review: label: Ask Casework for a review type: call @@ -106,7 +181,8 @@ workflow: type: transform transform: review-request inputs: - input: {type: input} + record: {type: step, step: read-application} + digest: {type: step, step: digest} next: await-review await-review: label: Wait for the officer's decision @@ -133,7 +209,7 @@ workflow: type: transform transform: assess-request inputs: - input: {type: input} + record: {type: step, step: read-application} next: approve approve: label: Record the approval in the register @@ -145,7 +221,9 @@ workflow: input: type: fields fields: - applicationId: {type: input, path: /applicationId} + applicationId: {type: step, step: read-application, path: /data/recordId} + activity: {type: step, step: read-application, path: /data/domainData/activity} + site: {type: step, step: read-application, path: /data/domainData/site} next: approved refuse: label: Record the refusal in the register @@ -157,7 +235,9 @@ workflow: input: type: fields fields: - applicationId: {type: input, path: /applicationId} + applicationId: {type: step, step: read-application, path: /data/recordId} + activity: {type: step, step: read-application, path: /data/domainData/activity} + site: {type: step, step: read-application, path: /data/domainData/site} next: refused approved: type: finish @@ -174,6 +254,9 @@ workflow: type: fields fields: resultId: {type: step, step: await-review, path: /resultId} + not-submitted: + type: finish + outcome: not-submitted not-decided: type: finish outcome: not-decided @@ -198,6 +281,8 @@ workflow: required: [resultId] properties: resultId: {type: string, format: uuid} + not-submitted: + type: 'null' not-decided: type: object additionalProperties: false diff --git a/products/platform/examples/service-previews/permit-review/dev-journeys.yaml b/products/platform/examples/service-previews/permit-review/dev-journeys.yaml index ed25eb8c2c..a176eeae9d 100644 --- a/products/platform/examples/service-previews/permit-review/dev-journeys.yaml +++ b/products/platform/examples/service-previews/permit-review/dev-journeys.yaml @@ -18,3 +18,14 @@ journeys: supervisors: [] queueId: permit-officers expect: {status: 200} + - id: neighbour-application + steps: + # Another applicant's application, so the preview has a second record. + - id: neighbour-submits + product: breg + as: neighbour + method: POST + path: /v1/actions/submit-application + headers: {Idempotency-Key: neighbour-application} + body: {input: {activity: Daytime survey, site: Market square}} + expect: {status: 200} diff --git a/products/platform/examples/service-previews/permit-review/dev.yaml b/products/platform/examples/service-previews/permit-review/dev.yaml index a55cd0e405..d1d3ea4203 100644 --- a/products/platform/examples/service-previews/permit-review/dev.yaml +++ b/products/platform/examples/service-previews/permit-review/dev.yaml @@ -27,12 +27,26 @@ people: subject: coordinator-producer client: coordinator-producer roles: [coordinator-producer] + neighbour: + subject: neighbour + client: permit-applicant + roles: [applicant] + claims: + breg: {registry_office: central} coordinator-service: subject: coordinator-service client: permit-coordinator roles: [coordinator-service] claims: breg: {registry_office: central} + # The BReg schema tests decide as this person, so the Coordinator's own + # BReg identity stays dedicated to the Coordinator. + register-tester: + subject: register-tester + client: permit-coordinator + roles: [coordinator-service] + claims: + breg: {registry_office: central} journeyFile: dev-journeys.yaml bindings: coordinatorReviewProducer: @@ -50,20 +64,25 @@ bindings: identity: coordinator-service preview: page: / - functions: [assess-permit] + functions: [assess-permit, digest-application] actors: + # The applicant submits and follows its own run. It reads no + # application from BReg, and Casework refuses its decisions. applicant: breg: - get: ["/v1/records/permit-applications/{recordId}"] post: [/v1/actions/submit-application] casework: post: ["/v1/review-tasks/{taskId}/decisions"] coordinator: get: [/v1/workflows/permit-flow, "/v1/runs/{runId}"] post: [/v1/runs] + # A second applicant, to show one applicant cannot follow another's run. + neighbour: + coordinator: + get: ["/v1/runs/{runId}"] officer: breg: - get: ["/v1/records/permit-applications/{recordId}"] + get: [/v1/records/permit-applications, "/v1/records/permit-applications/{recordId}"] casework: - get: [/v1/review-tasks] + get: [/v1/review-tasks, "/v1/review-tasks/{taskId}/context"] post: ["/v1/review-tasks/{taskId}/claim", "/v1/review-tasks/{taskId}/decisions"] diff --git a/products/platform/examples/service-previews/permit-review/functions/assess-permit/index.ts b/products/platform/examples/service-previews/permit-review/functions/assess-permit/index.ts index 2d53a8c07a..69bcc49cf5 100644 --- a/products/platform/examples/service-previews/permit-review/functions/assess-permit/index.ts +++ b/products/platform/examples/service-previews/permit-review/functions/assess-permit/index.ts @@ -1,7 +1,8 @@ import { defineFunction } from '../../generated/server.js' import { handleAssessment } from './assess.js' -// The Coordinator calls this function with its run host key, which the -// function host replaces with a placeholder. The function uses no registry -// client: it returns an assessment and records nothing itself. +// The Coordinator calls this function with the run host key, which the +// function host replaces with a placeholder. It holds no registry credential: +// it returns an assessment of the content the Coordinator read and records +// nothing itself. export default defineFunction(async (request) => handleAssessment(request)) diff --git a/products/platform/examples/service-previews/permit-review/functions/digest-application/digest.ts b/products/platform/examples/service-previews/permit-review/functions/digest-application/digest.ts new file mode 100644 index 0000000000..82024cc1cc --- /dev/null +++ b/products/platform/examples/service-previews/permit-review/functions/digest-application/digest.ts @@ -0,0 +1,33 @@ +function bounded(value: unknown, maximumLength: number) { + return typeof value === 'string' && value.length > 0 && value.length <= maximumLength ? value : undefined +} + +function answer(body: object, status: number) { + return Response.json(body, { status, headers: { 'Cache-Control': 'no-store' } }) +} + +// The digest of the exact application content the Coordinator read, as one +// JSON array, so Casework's review subject names that content. +export async function digestApplication(applicationId: string, revisionId: string, activity: string, site: string) { + const canonical = new TextEncoder().encode(JSON.stringify([applicationId, revisionId, activity, site])) + const bytes = new Uint8Array(await crypto.subtle.digest('SHA-256', canonical)) + return 'sha256:' + Array.from(bytes, byte => byte.toString(16).padStart(2, '0')).join('') +} + +export async function handleDigest(request: Request) { + if (request.method !== 'POST') return answer({ message: 'Send a POST request.' }, 405) + let submitted: Record | null + try { + submitted = await request.json() + } catch { + return answer({ message: 'Send the application content as JSON.' }, 400) + } + const applicationId = bounded(submitted?.applicationId, 64) + const revisionId = bounded(submitted?.revisionId, 64) + const activity = bounded(submitted?.activity, 160) + const site = bounded(submitted?.site, 160) + if (!applicationId || !revisionId || !activity || !site) { + return answer({ message: 'Send the application ID, revision, activity and site.' }, 400) + } + return answer({ digest: await digestApplication(applicationId, revisionId, activity, site) }, 200) +} diff --git a/products/platform/examples/service-previews/permit-review/functions/digest-application/index.ts b/products/platform/examples/service-previews/permit-review/functions/digest-application/index.ts new file mode 100644 index 0000000000..e227053bba --- /dev/null +++ b/products/platform/examples/service-previews/permit-review/functions/digest-application/index.ts @@ -0,0 +1,7 @@ +import { defineFunction } from '../../generated/server.js' +import { handleDigest } from './digest.js' + +// The Coordinator calls this function with the run host key, which the +// function host replaces with a placeholder. It holds no registry credential: +// it hashes the content the Coordinator read and returns the digest. +export default defineFunction(async (request) => handleDigest(request)) diff --git a/products/platform/examples/service-previews/permit-review/project/registry.yaml b/products/platform/examples/service-previews/permit-review/project/registry.yaml index c293fe752a..24feccc6dd 100644 --- a/products/platform/examples/service-previews/permit-review/project/registry.yaml +++ b/products/platform/examples/service-previews/permit-review/project/registry.yaml @@ -60,12 +60,19 @@ actions: display: label: Approve application description: Record an approved review decision on one submitted application. - execution: {mode: immediate, concurrency: current-revision} + execution: {mode: immediate} inputs: - {id: application, apiName: applicationId, type: reference, target: permit-application, required: true, classification: internal} + - {id: activity, type: string, required: true, minimumLength: 1, maximumLength: 160, classification: internal} + - {id: site, type: string, required: true, minimumLength: 1, maximumLength: 160, classification: internal} + # The caller names the content it read and had reviewed. The write + # applies only while the stored application still holds exactly that + # content and has not been decided. commitGuards: targets: - {input: application, field: status, equals: submitted, reason: not-submitted} + - {input: application, field: activity, equalsFromInput: activity, reason: content-changed} + - {input: application, field: site, equalsFromInput: site, reason: content-changed} plan: type: fixed effects: @@ -78,12 +85,19 @@ actions: display: label: Refuse application description: Record a refused review decision on one submitted application. - execution: {mode: immediate, concurrency: current-revision} + execution: {mode: immediate} inputs: - {id: application, apiName: applicationId, type: reference, target: permit-application, required: true, classification: internal} + - {id: activity, type: string, required: true, minimumLength: 1, maximumLength: 160, classification: internal} + - {id: site, type: string, required: true, minimumLength: 1, maximumLength: 160, classification: internal} + # The caller names the content it read and had reviewed. The write + # applies only while the stored application still holds exactly that + # content and has not been decided. commitGuards: targets: - {input: application, field: status, equals: submitted, reason: not-submitted} + - {input: application, field: activity, equalsFromInput: activity, reason: content-changed} + - {input: application, field: site, equalsFromInput: site, reason: content-changed} plan: type: fixed effects: @@ -99,16 +113,10 @@ accessProfiles: requesterClients: [permit-applicant] display: label: Permit applicant - description: Submits permit applications and reads applications in the office. + description: Submits permit applications. Reads none; the applicant follows its review run. principalClaim: sub requiredScopes: ["registry:permit:apply"] permissions: - records: - - recordType: permit-application - operations: [get] - readableFields: [activity, site, office, status] - rowBoundaries: - - {field: office, claim: registry_office, operator: equals} actions: - action: submit-application operations: [invoke] @@ -128,7 +136,7 @@ accessProfiles: permissions: records: - recordType: permit-application - operations: [get] + operations: [get, list] readableFields: [activity, site, office, status] rowBoundaries: - {field: office, claim: registry_office, operator: equals} diff --git a/products/platform/examples/service-previews/permit-review/project/tests/journeys.yaml b/products/platform/examples/service-previews/permit-review/project/tests/journeys.yaml new file mode 100644 index 0000000000..5129098a66 --- /dev/null +++ b/products/platform/examples/service-previews/permit-review/project/tests/journeys.yaml @@ -0,0 +1,115 @@ +# yaml-language-server: $schema=https://id.registrystack.org/schemas/breg/journeys/journeys.v1.schema.json +apiVersion: id.registrystack.org/formats/breg/journeys/v1 +kind: BRegJourneys +journeys: + - id: permit-decision + steps: + - id: applicant-submits + actor: applicant + action: submit-application + accessProfile: permit-applicant + claims: + principal: applicant + scopes: [registry:permit:apply] + actorKind: human + requesterClient: permit-applicant + directClaims: {registry_office: central} + request: + type: invoke + idempotencyKey: native-permit-application-2026-001 + input: {activity: Night resurfacing, site: North road} + expect: {outcome: success, status: 200} + captureResults: {application: application} + - id: coordinator-reads-approval-conditions + actor: register-tester + action: approve-application + accessProfile: permit-coordinator + claims: + principal: register-tester + scopes: [registry:permit:decide] + actorKind: service + requesterClient: permit-coordinator + directClaims: {registry_office: central} + request: + type: target-conditions + input: {applicationId: {recordCapture: application}} + expect: {outcome: success, status: 200} + capture: approval-condition + - id: coordinator-refused-for-other-content + actor: register-tester + action: approve-application + accessProfile: permit-coordinator + claims: + principal: register-tester + scopes: [registry:permit:decide] + actorKind: service + requesterClient: permit-coordinator + directClaims: {registry_office: central} + request: + type: invoke + idempotencyKey: native-permit-approve-other-content + input: {applicationId: {recordCapture: application}, activity: Daytime survey, site: North road} + preconditions: + applicationId: {conditionCapture: approval-condition} + expect: {outcome: refusal, status: 412, problemCode: action.guard-failed} + - id: coordinator-approves-the-content-read + actor: register-tester + action: approve-application + accessProfile: permit-coordinator + claims: + principal: register-tester + scopes: [registry:permit:decide] + actorKind: service + requesterClient: permit-coordinator + directClaims: {registry_office: central} + request: + type: invoke + idempotencyKey: native-permit-approve + input: {applicationId: {recordCapture: application}, activity: Night resurfacing, site: North road} + preconditions: + applicationId: {conditionCapture: approval-condition} + expect: {outcome: success, status: 200} + - id: coordinator-reads-refusal-conditions + actor: register-tester + action: refuse-application + accessProfile: permit-coordinator + claims: + principal: register-tester + scopes: [registry:permit:decide] + actorKind: service + requesterClient: permit-coordinator + directClaims: {registry_office: central} + request: + type: target-conditions + input: {applicationId: {recordCapture: application}} + expect: {outcome: success, status: 200} + capture: refusal-condition + - id: coordinator-cannot-decide-twice + actor: register-tester + action: refuse-application + accessProfile: permit-coordinator + claims: + principal: register-tester + scopes: [registry:permit:decide] + actorKind: service + requesterClient: permit-coordinator + directClaims: {registry_office: central} + request: + type: invoke + idempotencyKey: native-permit-refuse-after-approval + input: {applicationId: {recordCapture: application}, activity: Night resurfacing, site: North road} + preconditions: + applicationId: {conditionCapture: refusal-condition} + expect: {outcome: refusal, status: 412, problemCode: action.guard-failed} + - id: coordinator-reads-the-decision + actor: register-tester + recordType: permit-application + accessProfile: permit-coordinator + claims: + principal: register-tester + scopes: [registry:permit:decide] + actorKind: service + requesterClient: permit-coordinator + directClaims: {registry_office: central} + request: {type: get, recordCapture: application} + expect: {outcome: success, status: 200, fields: {status: approved, activity: Night resurfacing}} diff --git a/products/platform/examples/service-previews/permit-review/service.yaml b/products/platform/examples/service-previews/permit-review/service.yaml index 5755e57c86..9e363a44b2 100644 --- a/products/platform/examples/service-previews/permit-review/service.yaml +++ b/products/platform/examples/service-previews/permit-review/service.yaml @@ -10,7 +10,7 @@ products: projects: permit-flow: {path: coordinator} ui: {project: web, output: dist} -functions: [assess-permit] +functions: [assess-permit, digest-application] roles: applicant: actorKind: human diff --git a/products/platform/examples/service-previews/permit-review/web/public/index.html b/products/platform/examples/service-previews/permit-review/web/public/index.html index 9e7d97d3a4..b1f0960431 100644 --- a/products/platform/examples/service-previews/permit-review/web/public/index.html +++ b/products/platform/examples/service-previews/permit-review/web/public/index.html @@ -38,7 +38,6 @@

Application under review

State
Outcome
Assessment
-
Register status
@@ -55,6 +54,19 @@

Decide a review task

Permit applications awaiting review

    + +

    Read an application

    +
    + + +
    + +
    +
    Activity
    +
    Site
    +
    Register status
    +
    +
    diff --git a/products/platform/examples/service-previews/permit-review/web/src/page.ts b/products/platform/examples/service-previews/permit-review/web/src/page.ts index 3b495fa6b6..69647d6e17 100644 --- a/products/platform/examples/service-previews/permit-review/web/src/page.ts +++ b/products/platform/examples/service-previews/permit-review/web/src/page.ts @@ -37,11 +37,6 @@ async function call(path: string, init: { method?: string; body?: unknown; heade return { status: response.status, body } } -async function digest(value: string) { - const bytes = new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(value))) - return 'sha256:' + Array.from(bytes, byte => byte.toString(16).padStart(2, '0')).join('') -} - const alert = element('error') const status = element('status') @@ -67,23 +62,16 @@ async function applicant() { }) const recordId = field(submitted.body, 'results', 'application', 'recordId') if (submitted.status !== 200 || typeof recordId !== 'string') throw new Error('submit') - const record = await call('/registry/permits/v1/records/permit-applications/' + recordId) - const revisionId = field(record.body, 'data', 'revisionId') - if (record.status !== 200 || typeof revisionId !== 'string') throw new Error('read') element('application-id').textContent = recordId const contract = await call('/registry/permit-flow/v1/workflows/permit-flow') const workflowRevision = field(contract.body, 'workflowRevision') if (contract.status !== 200 || typeof workflowRevision !== 'string') throw new Error('workflow') + // The run names only the application. The Coordinator reads it under + // its own profile and reviews and decides only what it read. const started = await call('/registry/permit-flow/v1/runs', { method: 'POST', headers: { 'Idempotency-Key': crypto.randomUUID() }, - body: { - workflow: 'permit-flow', workflowRevision, - input: { - applicationId: recordId, applicationRevision: revisionId, - applicationDigest: await digest(recordId + ':' + revisionId), activity, site, - }, - }, + body: { workflow: 'permit-flow', workflowRevision, input: { applicationId: recordId } }, }) const runId = field(started.body, 'runId') if (started.status !== 200 || typeof runId !== 'string') throw new Error('start') @@ -91,7 +79,7 @@ async function applicant() { element('submitted').hidden = false form.hidden = true status.textContent = '' - await follow(runId, recordId) + await follow(runId) } catch { alert.textContent = 'We could not submit the application and start its review.' status.textContent = '' @@ -115,23 +103,34 @@ async function applicant() { }) } -async function follow(runId: string, recordId: string) { +async function follow(runId: string) { for (;;) { const run = await call('/registry/permit-flow/v1/runs/' + runId) const state = field(run.body, 'state') element('run-step').textContent = String(field(run.body, 'step') ?? '') element('run-state').textContent = String(state ?? '') - if (state === 'finished' || state === 'failed' || state === 'cancelled') { + // Every state but these two is terminal or needs an operator. + if (typeof state === 'string' && state !== 'running' && state !== 'cancel-requested') { element('run-outcome').textContent = String(field(run.body, 'outcome') ?? '') element('run-assessment').textContent = String(field(run.body, 'output', 'assessment') ?? '') - const record = await call('/registry/permits/v1/records/permit-applications/' + recordId) - element('application-status').textContent = String(field(record.body, 'data', 'domainData', 'status') ?? '') return } await new Promise(resolve => setTimeout(resolve, 1000)) } } +function line(label: string, value: unknown) { + const item = document.createElement('div') + const term = document.createElement('dt') + term.textContent = label + const detail = document.createElement('dd') + detail.textContent = String(value ?? '') + item.append(term, detail) + return item +} + +// The officer sees the content under review before claiming, and claims and +// approves in two separate steps. async function officer() { element('officer').hidden = false const list = element('tasks') @@ -141,37 +140,71 @@ async function officer() { list.replaceChildren() for (const task of Array.isArray(items) ? items : []) { const taskId = field(task, 'taskId') - const revision = field(task, 'revision') if (typeof taskId !== 'string') continue + const context = await call('/registry/casework/v1/review-tasks/' + taskId + '/context') + const snapshot = field(context.body, 'context', 'snapshot') const item = document.createElement('li') item.dataset.taskId = taskId - const label = document.createElement('span') - label.className = 'task-id' - label.textContent = taskId + item.dataset.applicationId = String(field(context.body, 'subject', 'id') ?? '') + const details = document.createElement('dl') + details.append( + line('Activity', field(snapshot, 'activity')), + line('Site', field(snapshot, 'site')), + line('Application', field(context.body, 'subject', 'id')), + ) + let revision = field(task, 'revision') + const claim = document.createElement('button') + claim.textContent = 'Claim' const approve = document.createElement('button') - approve.textContent = 'Claim and approve' - approve.addEventListener('click', async () => { - approve.disabled = true + approve.textContent = 'Approve' + approve.disabled = true + claim.addEventListener('click', async () => { + claim.disabled = true const claimed = await call('/registry/casework/v1/review-tasks/' + taskId + '/claim', { method: 'POST', headers: { 'If-Match': '"' + String(revision) + '"', 'Idempotency-Key': crypto.randomUUID() }, }) - const claimRevision = field(claimed.body, 'revision') + revision = field(claimed.body, 'revision') + item.dataset.claimed = String(claimed.status) + claim.textContent = claimed.status === 200 ? 'Claimed' : 'Casework answered ' + claimed.status + approve.disabled = claimed.status !== 200 + }) + approve.addEventListener('click', async () => { + approve.disabled = true const decided = await call('/registry/casework/v1/review-tasks/' + taskId + '/decisions', { - method: 'POST', headers: { 'If-Match': '"' + String(claimRevision) + '"', 'Idempotency-Key': crypto.randomUUID() }, + method: 'POST', headers: { 'If-Match': '"' + String(revision) + '"', 'Idempotency-Key': crypto.randomUUID() }, body: { decision: { type: 'approve', outcome: 'approved' } }, }) item.dataset.decided = String(decided.status) approve.textContent = decided.status === 204 ? 'Approved' : 'Casework answered ' + decided.status }) - item.append(label, ' ', approve) + item.append(details, claim, ' ', approve) list.append(item) } }) + + const lookup = element('application-lookup') + lookup.addEventListener('submit', async (event) => { + event.preventDefault() + const recordId = text(new FormData(lookup).get('applicationId'), 64) + if (!recordId) return + const record = await call('/registry/permits/v1/records/permit-applications/' + recordId) + const data = field(record.body, 'data', 'domainData') + element('register-activity').textContent = String(field(data, 'activity') ?? '') + element('register-site').textContent = String(field(data, 'site') ?? '') + element('register-status').textContent = String(field(data, 'status') ?? record.status) + }) +} + +// The page bundles as a classic script, so it starts from one async call. +async function start() { + const whoami = await call('/_rstack/actor') + const actor = field(whoami.body, 'actor') + element('actor').textContent = String(actor ?? '') + if (actor === 'applicant') await applicant() + else if (actor === 'officer') await officer() + else alert.textContent = 'This page has no controls for this person.' } -const whoami = await call('/_rstack/actor') -const actor = field(whoami.body, 'actor') -element('actor').textContent = String(actor ?? '') -if (actor === 'applicant') await applicant() -else if (actor === 'officer') await officer() -else alert.textContent = 'This page does not know the signed-in actor.' +start().catch(() => { + alert.textContent = 'This page could not start.' +}) From cb337d0c215ad17c69381ab2632ab0f404bbe46a Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Wed, 2 Dec 2026 00:01:27 +0000 Subject: [PATCH 147/183] docs(dev): state the permit-review decision guard invariant and test identities Fold the review's notes on 3d0e40947. The decision guards bind the decision to the review only while every snapshot field is guarded and no Action edits a guarded field; registry.yaml now says so beside the guards. dev.yaml says register-tester holds the Coordinator's decide authority in development and its decisions bypass review, the BReg journey steps are named register-tester-* to match the person they act as, and casework.yaml says the applicant's profile exists so Casework, not the page, refuses the applicant's decision. Signed-off-by: Jeremi Joslin --- .../permit-review/casework/casework.yaml | 3 +++ .../examples/service-previews/permit-review/dev.yaml | 4 +++- .../permit-review/project/registry.yaml | 10 ++++++++-- .../permit-review/project/tests/journeys.yaml | 12 ++++++------ 4 files changed, 20 insertions(+), 9 deletions(-) diff --git a/products/platform/examples/service-previews/permit-review/casework/casework.yaml b/products/platform/examples/service-previews/permit-review/casework/casework.yaml index f2e7e6df63..7440ab9026 100644 --- a/products/platform/examples/service-previews/permit-review/casework/casework.yaml +++ b/products/platform/examples/service-previews/permit-review/casework/casework.yaml @@ -20,6 +20,9 @@ accessProfiles: principalClaim: sub requiredScopes: [casework:permit:admin] actsAs: administrator + # The applicant may ask for a review but never decide one. The preview keeps + # this profile so the applicant's decision attempt reaches Casework and is + # refused there with 403. permit-applicant: principalClaim: sub requiredScopes: [casework:permit:apply] diff --git a/products/platform/examples/service-previews/permit-review/dev.yaml b/products/platform/examples/service-previews/permit-review/dev.yaml index d1d3ea4203..b8f5e43b3d 100644 --- a/products/platform/examples/service-previews/permit-review/dev.yaml +++ b/products/platform/examples/service-previews/permit-review/dev.yaml @@ -40,7 +40,9 @@ people: claims: breg: {registry_office: central} # The BReg schema tests decide as this person, so the Coordinator's own - # BReg identity stays dedicated to the Coordinator. + # BReg identity stays dedicated to the Coordinator. In development it holds + # the Coordinator's decide authority for those journeys, and a decision it + # makes bypasses review. register-tester: subject: register-tester client: permit-coordinator diff --git a/products/platform/examples/service-previews/permit-review/project/registry.yaml b/products/platform/examples/service-previews/permit-review/project/registry.yaml index 24feccc6dd..a53055da3d 100644 --- a/products/platform/examples/service-previews/permit-review/project/registry.yaml +++ b/products/platform/examples/service-previews/permit-review/project/registry.yaml @@ -67,7 +67,10 @@ actions: - {id: site, type: string, required: true, minimumLength: 1, maximumLength: 160, classification: internal} # The caller names the content it read and had reviewed. The write # applies only while the stored application still holds exactly that - # content and has not been decided. + # content and has not been decided. This binds the decision to the review + # only while every field in the review snapshot is guarded here and no + # Action can change a guarded field: add a guard with any new snapshot + # field, and add no Action that edits activity or site. commitGuards: targets: - {input: application, field: status, equals: submitted, reason: not-submitted} @@ -92,7 +95,10 @@ actions: - {id: site, type: string, required: true, minimumLength: 1, maximumLength: 160, classification: internal} # The caller names the content it read and had reviewed. The write # applies only while the stored application still holds exactly that - # content and has not been decided. + # content and has not been decided. This binds the decision to the review + # only while every field in the review snapshot is guarded here and no + # Action can change a guarded field: add a guard with any new snapshot + # field, and add no Action that edits activity or site. commitGuards: targets: - {input: application, field: status, equals: submitted, reason: not-submitted} diff --git a/products/platform/examples/service-previews/permit-review/project/tests/journeys.yaml b/products/platform/examples/service-previews/permit-review/project/tests/journeys.yaml index 5129098a66..9af2db4729 100644 --- a/products/platform/examples/service-previews/permit-review/project/tests/journeys.yaml +++ b/products/platform/examples/service-previews/permit-review/project/tests/journeys.yaml @@ -20,7 +20,7 @@ journeys: input: {activity: Night resurfacing, site: North road} expect: {outcome: success, status: 200} captureResults: {application: application} - - id: coordinator-reads-approval-conditions + - id: register-tester-reads-approval-conditions actor: register-tester action: approve-application accessProfile: permit-coordinator @@ -35,7 +35,7 @@ journeys: input: {applicationId: {recordCapture: application}} expect: {outcome: success, status: 200} capture: approval-condition - - id: coordinator-refused-for-other-content + - id: register-tester-refused-for-other-content actor: register-tester action: approve-application accessProfile: permit-coordinator @@ -52,7 +52,7 @@ journeys: preconditions: applicationId: {conditionCapture: approval-condition} expect: {outcome: refusal, status: 412, problemCode: action.guard-failed} - - id: coordinator-approves-the-content-read + - id: register-tester-approves-the-content-read actor: register-tester action: approve-application accessProfile: permit-coordinator @@ -69,7 +69,7 @@ journeys: preconditions: applicationId: {conditionCapture: approval-condition} expect: {outcome: success, status: 200} - - id: coordinator-reads-refusal-conditions + - id: register-tester-reads-refusal-conditions actor: register-tester action: refuse-application accessProfile: permit-coordinator @@ -84,7 +84,7 @@ journeys: input: {applicationId: {recordCapture: application}} expect: {outcome: success, status: 200} capture: refusal-condition - - id: coordinator-cannot-decide-twice + - id: register-tester-cannot-decide-twice actor: register-tester action: refuse-application accessProfile: permit-coordinator @@ -101,7 +101,7 @@ journeys: preconditions: applicationId: {conditionCapture: refusal-condition} expect: {outcome: refusal, status: 412, problemCode: action.guard-failed} - - id: coordinator-reads-the-decision + - id: register-tester-reads-the-decision actor: register-tester recordType: permit-application accessProfile: permit-coordinator From 0ea36894b35c894ea2eecb5fa2b7e9629a90e7b0 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Wed, 2 Dec 2026 00:01:27 +0000 Subject: [PATCH 148/183] fix(coordinator): compare a function host key without its trailing newlines A host key is sent as a bearer after its trailing newlines are trimmed, but the startup comparison hashed the untrimmed bytes, so a host key file "K\n" and another key file "K" held the same secret yet compared as distinct. Byte keys now compare without trailing newlines, with a test. Signed-off-by: Jeremi Joslin --- crates/registry-coordinator/src/adapters.rs | 8 +++++++- .../tests/service_function.rs | 16 ++++++++++++++++ 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/crates/registry-coordinator/src/adapters.rs b/crates/registry-coordinator/src/adapters.rs index 067b6f0169..ae7a1901c8 100644 --- a/crates/registry-coordinator/src/adapters.rs +++ b/crates/registry-coordinator/src/adapters.rs @@ -484,9 +484,15 @@ fn distinct_function_keys( .ok() .and_then(|text| PrivateJwk::parse(text).ok()) .and_then(|key| key.public().jkt().ok()); + // A host key is sent without its trailing newlines, so bytes compare + // in that form: a file differing only by them holds the same key. + let trimmed = bytes + .iter() + .rposition(|byte| *byte != b'\n') + .map_or(&bytes[..0], |last| &bytes[..=last]); Ok(match jwk { Some(thumbprint) => format!("jwk:{thumbprint}"), - None => format!("bytes:{}", hex::encode(sha2::Sha256::digest(bytes))), + None => format!("bytes:{}", hex::encode(sha2::Sha256::digest(trimmed))), }) }; let mut functions = Vec::new(); diff --git a/crates/registry-coordinator/tests/service_function.rs b/crates/registry-coordinator/tests/service_function.rs index 797a31deaa..4b7b2ad10b 100644 --- a/crates/registry-coordinator/tests/service_function.rs +++ b/crates/registry-coordinator/tests/service_function.rs @@ -964,6 +964,22 @@ fn the_same_host_key_or_jwk_under_another_form_is_refused_at_startup() { .expect("one host key behind two references is refused"); assert!(error.message.contains("decide"), "{error:?}"); + // The host key is sent without its trailing newline, so a file that + // differs only by that newline holds the same key. + let host_key_line = format!("{HOST_KEY}\n"); + let (_root, config) = with_secrets( + &document, + &[ + ("function-host-key", &host_key_line), + ("decision-token", HOST_KEY), + ("registry-client-key", KEY), + ], + ); + let error = registry_coordinator::adapters::HttpAdapters::new(&config) + .err() + .expect("a host key and the same key without its newline are refused"); + assert!(error.message.contains("decide"), "{error:?}"); + // The same JWK written again with its members in another order and // spacing is the same key. let parsed: serde_json::Map = serde_json::from_str(KEY).unwrap(); From 66e13546a546a839e899acacbfe8d0eccdd55f05 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Wed, 2 Dec 2026 00:01:33 +0000 Subject: [PATCH 149/183] test(dev): drive the permit-review preview in two browser contexts test-service-previews.mjs runs permit-review after the two existing previews. The applicant and the officer use separate browser contexts on their own actor origins, which serve identical page bytes, and the run reports the per-actor gateway origin substitution. The journey proves: - the applicant submits and starts a run that waits on Casework; - a well-formed completion for the configured recipient binding, signed with a key Casework does not hold, gets 401 authentication.refused and the run keeps waiting (a mutant that skips signature verification answers 204 and fails); - the applicant reads its own run, and the neighbour's origin gets the Coordinator's 404 run.not-visible; - a start whose input carries content is refused; - the officer sees the content the Coordinator read, Casework refuses the applicant's own decision with 403, and the officer claims and approves; - the run records assessment conditions and BReg holds the approval; - a start the browser rewrites to name the neighbour's application reviews and decides only that stored application and leaves the applicant's own application submitted; - the browser sends no Authorization header, and a clean stop closes every actor origin and removes the managed database. A managed candidate skips permit-review only when RSTACK_PREVIEW_SKIP_PERMIT_REVIEW=no-coordinator-in-release is set; otherwise missing Casework or Coordinator components fail the run. The docs name the forged-completion refusal. Signed-off-by: Jeremi Joslin --- .../run-a-project-with-rstack-dev.mdx | 5 +- .../examples/service-previews/README.md | 39 ++- .../scripts/test-service-previews.mjs | 230 +++++++++++++++++- 3 files changed, 260 insertions(+), 14 deletions(-) diff --git a/docs/site/src/content/docs/configure/run-a-project-with-rstack-dev.mdx b/docs/site/src/content/docs/configure/run-a-project-with-rstack-dev.mdx index 297d45bc62..ed1a8ec237 100644 --- a/docs/site/src/content/docs/configure/run-a-project-with-rstack-dev.mdx +++ b/docs/site/src/content/docs/configure/run-a-project-with-rstack-dev.mdx @@ -1108,7 +1108,10 @@ project, as the BReg binding does. It gives the Coordinator connection the Casew the identity's Casework profile and a machine client on the run-local token endpoint, so its token carries the identity's subject and Casework audience. It binds Casework's completion destination to the Coordinator's review completion route. Both sides use one owner-only key -of random bytes written for the run, so Casework wakes the waiting run. +of random bytes written for the run, so Casework wakes the waiting run. The permit-review service +preview's browser journey runs this binding with the real Casework and Coordinator: the +Coordinator refuses, with 401, a completion that the run key did not sign, and the run keeps +waiting until Casework sends the officer's decision. A live Coordinator run binds the connection's address, and the Casework origin changes with each start. Let a waiting Coordinator run finish, or start with `--clean`, before you start again. diff --git a/products/platform/examples/service-previews/README.md b/products/platform/examples/service-previews/README.md index 76c8f02840..03fb2d3ba9 100644 --- a/products/platform/examples/service-previews/README.md +++ b/products/platform/examples/service-previews/README.md @@ -1,9 +1,12 @@ # Local service previews -These two synthetic services run independently. Each uses a real BReg and a -managed development PostgreSQL database. +These three synthetic services run independently. Each uses a real BReg and a +managed development PostgreSQL database. The permit-review service also runs +a real Casework and Coordinator. Install `rstack`, `breg`, and `bregctl` from the same Registry Stack release. +The permit-review service also needs `casework`, `caseworkctl`, `coordinator` +and `coordinatorctl` from that release. Use Node 24 and a local Docker engine. Each starter has an exact npm lock. Place the matching release's `@registrystack/client` tarball beside that starter's lockfile as `registry-preview-client.tgz`, then install: @@ -11,19 +14,21 @@ starter's lockfile as `registry-preview-client.tgz`, then install: ```sh npm ci --prefix ./medical-renewal npm ci --prefix ./business-registration +npm ci --prefix ./permit-review ``` The lock matches the tarball by version and SHA-512. The client package supplies -the preview helper and build tools for both examples. +the preview helper and build tools for every example. -From a directory containing clean copies of the examples, start either preview. +From a directory containing clean copies of the examples, start any preview. ```sh rstack dev start ./medical-renewal rstack dev start ./business-registration +rstack dev start ./permit-review ``` -Open the URL each command prints. Use its run ID to check or stop the preview. +Open the URL each command prints. The permit-review start prints one `Actor` URL per synthetic person. Use its run ID to check or stop the preview. ```sh rstack dev status RUN_ID @@ -33,11 +38,13 @@ rstack dev stop RUN_ID --clean A clean stop removes the run's managed data. After editing a function or page, start the example again to build from the updated source. -Both services declare `ui.project: web` and `ui.output: dist`. Preview start +Every service declares `ui.project: web` and `ui.output: dist`. Preview start bundles `web/src/page.ts` into `app.js` and copies `web/public` into the run's owned output. It generates `generated/service.ts`, `generated/routes.ts` and the server binding inside the run's copy. The page imports the generated browser client and same-origin function paths. The gateway authorizes browser-origin requests for one synthetic actor. +The permit-review service runs one gateway per actor, each on its own origin over +the same built page, as a development substitution for one origin with sign-in. It keeps that actor's credential on the server. Use a trusted workstation or an isolated runner, trusted project code, and synthetic data. The numeric loopback listeners are local to the host and reachable by @@ -62,7 +69,25 @@ absolute examples directory. Set `RSTACK_PREVIEW_INSTALL_ROOT` and `RSTACK_PREVIEW_BIN_DIR` to the managed candidate installation's absolute roots. The driver uses those roots and checks that `npm ci` preserves the delivered files. Both modes check the browser reads and mutations and managed -database cleanup. +database cleanup. For permit-review, the driver opens the applicant and officer +origins in two browser contexts and checks that every actor origin serves the +same page bytes. It also checks that: + +- Casework refuses the applicant's decision with 403. +- the Coordinator refuses a completion Casework did not sign with 401. +- the neighbour's origin cannot read the applicant's run. +- the officer's approval finishes the run with the decision recorded in BReg. +- a start the browser rewrites to name the neighbour's application reviews and + decides only that stored application. It leaves the applicant's own + application submitted. + +The driver takes the Casework and Coordinator binaries from `RSTACK_CASEWORK_BIN`, +`RSTACK_CASEWORKCTL_BIN`, `RSTACK_COORDINATOR_BIN` and `RSTACK_COORDINATORCTL_BIN`, +or from the managed installation. A managed candidate whose release ships no +Coordinator sets `RSTACK_PREVIEW_SKIP_PERMIT_REVIEW=no-coordinator-in-release`. +The driver then reports permit-review as skipped. Any other run fails when +those components are missing. - [Renew a medical licence](medical-renewal/README.md) - [Register a business](business-registration/README.md) +- [Apply for a reviewed permit](permit-review/README.md) diff --git a/products/platform/scripts/test-service-previews.mjs b/products/platform/scripts/test-service-previews.mjs index d940014ffe..9d4e2ce9ae 100644 --- a/products/platform/scripts/test-service-previews.mjs +++ b/products/platform/scripts/test-service-previews.mjs @@ -1,6 +1,6 @@ import assert from 'node:assert/strict' import { execFile } from 'node:child_process' -import { createHash } from 'node:crypto' +import { createHash, createHmac, randomBytes, randomUUID } from 'node:crypto' import { constants } from 'node:fs' import { cp, mkdtemp, mkdir, open, readdir, readFile, rm, stat, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' @@ -200,6 +200,208 @@ async function business(page, url, expectedName = 'Harbour Bicycle Cooperative') return { matchingRecords: records.length, revision: Number(record.revisionId) } } +// Same-origin gateway call as that actor's page would make it. +async function actorCall(origin, path, init = {}) { + const response = await fetch(new URL(path, origin), { + ...init, + headers: { Accept: 'application/json', 'Registry-Client': 'page', Origin: origin.origin, ...init.headers }, + signal: AbortSignal.timeout(8_000), + redirect: 'error', + }) + return { status: response.status, body: await response.json().catch(() => null) } +} + +// The applicant and the officer on two browser contexts, each on its own +// actor origin over the same built page. The applicant starts a Coordinator +// run that names only its application; the Coordinator reads it, Casework +// refuses the applicant's own decision, a forged completion cannot wake the +// run, another applicant cannot follow it, and the officer's approval lets +// the run record the assessment and the decision in BReg. A second run whose +// start the browser tampers with reviews and decides only the record the +// Coordinator read. +async function permitReview(browser, url, report) { + const actors = report.previewActors + assert.deepEqual(Object.keys(actors ?? {}), ['applicant', 'neighbour', 'officer']) + const [applicantUrl, neighbourUrl, officerUrl] = ['applicant', 'neighbour', 'officer'].map(name => loopback(actors[name])) + assert.equal(applicantUrl.href, url.href) + assert.equal(new Set([applicantUrl.origin, neighbourUrl.origin, officerUrl.origin]).size, 3) + assert.ok(report.substitutions.includes('per-actor gateway origin (development)')) + for (const path of ['/', '/app.js', '/service.css']) { + const bodies = await Promise.all([applicantUrl, neighbourUrl, officerUrl].map(async origin => { + const response = await fetch(new URL(path, origin), { signal: AbortSignal.timeout(8_000), redirect: 'error' }) + assert.equal(response.status, 200, path) + return Buffer.from(await response.arrayBuffer()) + })) + assert.ok(bodies.every(body => body.equals(bodies[0])), `The actor origins served different bytes for ${path}.`) + } + // The neighbour's application, seeded by the startup journey. + const listed = await actorCall(officerUrl, '/registry/permits/v1/records/permit-applications') + assert.equal(listed.status, 200) + const neighbourApplication = listed.body.items.find(record => record.domainData.activity === 'Daytime survey') + assert.equal(neighbourApplication?.domainData.status, 'submitted') + + const errors = [] + const requests = [] + const open = async () => { + const context = await browser.newContext({ viewport: { width: 390, height: 900 } }) + const page = await context.newPage() + page.setDefaultTimeout(8_000) + page.on('pageerror', () => errors.push('uncaught page error')) + page.on('request', request => { + const path = new URL(request.url()).pathname + if (path.startsWith('/registry/') || path.startsWith('/_rstack/actor')) requests.push(request) + }) + return { context, page } + } + const applicant = await open() + const officer = await open() + const submit = async (activity, site) => { + const page = applicant.page + await page.goto(applicantUrl.href) + await page.locator('#actor').getByText('applicant', { exact: true }).waitFor() + await page.getByLabel('Activity').fill(activity) + await page.getByLabel('Site').fill(site) + await page.getByRole('button', { name: 'Submit application' }).click() + await page.getByRole('heading', { name: 'Application under review' }).waitFor() + const applicationId = (await page.locator('#application-id').textContent())?.trim() + const runId = (await page.locator('#run-id').textContent())?.trim() + assert.match(applicationId ?? '', uuid) + assert.match(runId ?? '', uuid) + await page.locator('#run-step').getByText('await-review', { exact: true }).waitFor({ timeout: 60_000 }) + return { applicationId, runId } + } + // The officer's task for one application, with the content under review. + const task = async applicationId => { + await officer.page.getByRole('button', { name: 'Show tasks' }).click() + const item = officer.page.locator(`#tasks li[data-application-id="${applicationId}"]`) + await item.waitFor() + return item + } + const approve = async item => { + await item.getByRole('button', { name: 'Claim', exact: true }).click() + await item.getByRole('button', { name: 'Claimed' }).waitFor() + assert.equal(await item.getAttribute('data-claimed'), '200') + await item.getByRole('button', { name: 'Approve', exact: true }).click() + await item.getByRole('button', { name: 'Approved' }).waitFor() + assert.equal(await item.getAttribute('data-decided'), '204') + } + const registered = async applicationId => { + const read = await actorCall(officerUrl, '/registry/permits/v1/records/permit-applications/' + applicationId) + assert.equal(read.status, 200) + return read.body.data.domainData + } + try { + const page = applicant.page + const first = await submit('Night resurfacing', 'North road') + + // A well-formed completion for the configured recipient binding, signed + // with a key Casework does not hold, cannot wake the waiting run: only + // the signature check refuses it. + const coordinator = loopback(report.products.coordinator) + const eventId = randomUUID() + const timestamp = String(Math.floor(Date.now() / 1000)) + const event = JSON.stringify({ + type: 'review.completed', eventId, requestId: randomUUID(), resultId: randomUUID(), + completedAt: new Date().toISOString(), + }) + const forgedSignature = createHmac('sha256', randomBytes(32)).update(`${eventId}.${timestamp}.${event}`).digest('base64') + const forged = await fetch(new URL('/v1/review-completions', coordinator), { + method: 'POST', + headers: { + 'content-type': 'application/json', + 'registry-recipient-binding': 'coordinator-v1', + 'webhook-id': eventId, + 'webhook-timestamp': timestamp, + 'webhook-signature': 'v1,' + forgedSignature, + }, + body: event, + signal: AbortSignal.timeout(8_000), + redirect: 'error', + }) + assert.equal(forged.status, 401, 'The Coordinator accepted a completion Casework did not sign.') + assert.equal((await forged.json()).code, 'authentication.refused') + + // The applicant follows its own run, and another applicant cannot: the + // Coordinator itself answers that the run is not visible. + assert.equal((await actorCall(applicantUrl, '/registry/permit-flow/v1/runs/' + first.runId)).status, 200) + const foreign = await actorCall(neighbourUrl, '/registry/permit-flow/v1/runs/' + first.runId) + assert.equal(foreign.status, 404, 'Another applicant could read the run.') + assert.equal(foreign.body?.code, 'run.not-visible') + + // The run input names only the application, so content is refused. + const workflow = await actorCall(applicantUrl, '/registry/permit-flow/v1/workflows/permit-flow') + const withContent = await actorCall(applicantUrl, '/registry/permit-flow/v1/runs', { + method: 'POST', + headers: { 'Content-Type': 'application/json', 'Idempotency-Key': randomUUID() }, + body: JSON.stringify({ + workflow: 'permit-flow', workflowRevision: workflow.body.workflowRevision, + input: { applicationId: first.applicationId, activity: 'Harmless survey' }, + }), + }) + assert.equal(withContent.status, 400, `A start carrying content answered ${withContent.status}.`) + assert.equal(withContent.body?.code, 'input.invalid') + + await officer.page.goto(officerUrl.href) + await officer.page.locator('#actor').getByText('officer', { exact: true }).waitFor() + const firstTask = await task(first.applicationId) + await firstTask.getByText('Night resurfacing', { exact: true }).waitFor() + await firstTask.getByText('North road', { exact: true }).waitFor() + const taskId = await firstTask.getAttribute('data-task-id') + assert.match(taskId ?? '', uuid) + + // The applicant's own decision reaches Casework, which refuses it. + await page.getByLabel('Task', { exact: true }).fill(taskId) + await page.getByRole('button', { name: 'Approve', exact: true }).click() + await page.getByText('Casework refused the decision (403).').waitFor() + assert.equal(await page.locator('#run-step').textContent(), 'await-review') + assert.equal((await actorCall(applicantUrl, '/registry/permit-flow/v1/runs/' + first.runId)).body.step, 'await-review') + + await approve(firstTask) + await page.locator('#run-outcome').getByText('approved', { exact: true }).waitFor({ timeout: 90_000 }) + assert.equal(await page.locator('#run-state').textContent(), 'finished') + assert.equal(await page.locator('#run-assessment').textContent(), 'conditions') + assert.equal((await registered(first.applicationId)).status, 'approved') + + // The browser rewrites its start to name the neighbour's application. + await page.route('**/registry/permit-flow/v1/runs', async route => { + const body = route.request().postDataJSON() + body.input.applicationId = neighbourApplication.recordId + await route.continue({ postData: JSON.stringify(body) }) + }) + const tampered = await submit('Night works', 'Harbour road') + await page.unroute('**/registry/permit-flow/v1/runs') + const tamperedTask = await task(neighbourApplication.recordId) + await tamperedTask.getByText('Daytime survey', { exact: true }).waitFor() + await tamperedTask.getByText('Market square', { exact: true }).waitFor() + assert.equal(await officer.page.locator(`#tasks li[data-application-id="${tampered.applicationId}"]`).count(), 0) + await approve(tamperedTask) + await page.locator('#run-outcome').getByText('approved', { exact: true }).waitFor({ timeout: 90_000 }) + assert.equal(await page.locator('#run-assessment').textContent(), 'standard') + const decided = await registered(neighbourApplication.recordId) + assert.deepEqual([decided.activity, decided.site, decided.status], ['Daytime survey', 'Market square', 'approved']) + const untouched = await registered(tampered.applicationId) + assert.deepEqual([untouched.activity, untouched.status], ['Night works', 'submitted']) + + assert.deepEqual(errors, []) + assert.ok(requests.some(request => new URL(request.url()).pathname.startsWith('/registry/casework/'))) + assert.ok(requests.some(request => new URL(request.url()).pathname.startsWith('/registry/permit-flow/'))) + for (const request of requests) { + const headers = await request.allHeaders() + assert.equal(Boolean(headers.authorization), false, 'The browser sent an Authorization header.') + assert.equal(headers['registry-client'], 'page') + } + return { + actors: 3, identicalPages: true, applicantDecisionStatus: 403, forgedCompletionStatus: 401, + foreignRunStatus: 404, contentStartRefused: true, outcome: 'approved', assessment: 'conditions', registerStatus: 'approved', + tamperedStart: { reviewed: 'neighbour application', assessment: 'standard', ownApplication: 'submitted' }, + browserBearer: false, + } + } finally { + await applicant.context.close() + await officer.context.close() + } +} + async function exercise(browser, url, journey) { const page = await browser.newPage({ viewport: { width: 390, height: 900 } }) page.setDefaultTimeout(8_000) @@ -253,8 +455,9 @@ async function main() { delete env.RSTACK_DEV_DATABASE_URL delete env.RSTACK_DEV_DATABASE_CA if (managed) { - delete env.RSTACK_BREG_BIN - delete env.RSTACK_BREGCTL_BIN + for (const name of ['BREG', 'BREGCTL', 'CASEWORK', 'CASEWORKCTL', 'COORDINATOR', 'COORDINATORCTL']) { + delete env[`RSTACK_${name}_BIN`] + } } const devArgs = (...args) => [...globalFlags, 'dev', ...args, '--format', 'json'] const dev = async (...args) => JSON.parse(await command(rstack, devArgs(...args), env)) @@ -268,7 +471,7 @@ async function main() { assert.equal(await treeDigest(project), before, 'npm ci modified the delivered example.') return project } - async function runProject(project, functionName, journey, onReady) { + async function runProject(project, functionName, journey, onReady, drive = exercise) { const before = await treeDigest(project) // Keep recovery state if startup times out and the driver never sees a run ID. keepScratch = true @@ -302,7 +505,7 @@ async function main() { }) assert.equal(wrongOrigin.status, 403, 'The preview gateway allowed a different browser origin.') await wrongOrigin.body?.cancel() - result = await exercise(browser, url, journey) + result = await drive(browser, url, journey, report) } finally { const stopped = await dev('stop', report.run_id, '--clean') assert.equal(stopped.cleaned, true) @@ -312,7 +515,8 @@ async function main() { assert.equal(containers.trim(), '', 'The managed PostgreSQL container survived clean stop.') keepScratch = false } - for (const address of [url, privateOrigin]) { + const actorOrigins = Object.values(report.previewActors ?? {}).map(loopback) + for (const address of [url, privateOrigin, ...actorOrigins]) { await assert.rejects(fetch(address, { signal: AbortSignal.timeout(2_000) }), { name: 'TypeError' }) } assert.equal(await treeDigest(project), before, 'Preview modified the authored project.') @@ -326,10 +530,24 @@ async function main() { const medical = await runProject(medicalProject, 'renew', renewal) const registered = await runProject(businessProject, 'register-business', business) assert.notEqual(medical.volume, registered.volume) + // Every run proves permit-review, unless a managed candidate whose release + // ships no Coordinator says so explicitly; a missing install then fails. + const skipPermit = process.env.RSTACK_PREVIEW_SKIP_PERMIT_REVIEW === 'no-coordinator-in-release' + assert.ok(!skipPermit || managed, 'Only a managed candidate may skip permit-review.') + let permit + if (!skipPermit) { + const permitProject = await installProject('permit-review') + permit = await runProject(permitProject, 'assess-permit', null, undefined, + (browser, url, _journey, report) => permitReview(browser, url, report)) + assert.equal(new Set([medical.volume, registered.volume, permit.volume]).size, 3) + } const results = [ { name: 'medical-renewal', ...medical.result, directAnonymousStatus: 401, wrongOriginStatus: 403 }, { name: 'business-registration', ...registered.result, directAnonymousStatus: 401, wrongOriginStatus: 403 }, + permit + ? { name: 'permit-review', ...permit.result, directAnonymousStatus: 401, wrongOriginStatus: 403 } + : { name: 'permit-review', skipped: 'This release ships no Coordinator.' }, ] if (!managed) { From 5b60b88019a76740ab2e094e6aa71ad03747896a Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Wed, 2 Dec 2026 00:02:07 +0000 Subject: [PATCH 150/183] ci: build and run Casework and the Coordinator for the service previews The permit-review preview starts Casework and the Coordinator. CI now routes the browser previews on changes to those crates, builds their binaries beside BReg, and passes their paths to the driver, with five more minutes for the third preview. The release-candidate install smoke installs Casework and the Coordinator whenever the roster ships the Coordinator binaries, so such a candidate must pass permit-review; only a release without them sets RSTACK_PREVIEW_SKIP_PERMIT_REVIEW. The routing test pins both roster gates. Signed-off-by: Jeremi Joslin --- .github/scripts/ci_changes.py | 11 ++++++++- .github/scripts/test_ci_changes.py | 30 +++++++++++++++++++++++++ .github/workflows/ci.yml | 13 ++++++++--- .github/workflows/release-candidate.yml | 28 +++++++++++++++++++++-- 4 files changed, 76 insertions(+), 6 deletions(-) diff --git a/.github/scripts/ci_changes.py b/.github/scripts/ci_changes.py index 870a0ef228..9632af453a 100644 --- a/.github/scripts/ci_changes.py +++ b/.github/scripts/ci_changes.py @@ -169,6 +169,15 @@ # The BReg harnesses and the Adapter GovStack journey start their services with # `rstack dev`, so a change to it runs them. RSTACK_DEV_HARNESS_PACKAGES = frozenset({"registry-rstack", "registry-rstack-dev"}) +# The service previews start these products: BReg in every example, and +# Casework and the Coordinator in permit-review. +SERVICE_PREVIEW_PRODUCT_PACKAGES = frozenset({ + "registry-breg", + "registry-bregctl", + "registry-casework", + "registry-caseworkctl", + "registry-coordinator", +}) # The shared dependency gate owns the list of development runner hosts. _dev_runner_gate = runpy.run_path(str( Path(__file__).resolve().parents[2] / "products/platform/scripts/check_dev_runner_reach.py" @@ -1817,7 +1826,7 @@ def classify( service_previews = ( complete - or bool(affected & (RSTACK_DEV_HARNESS_PACKAGES | {"registry-breg", "registry-bregctl"})) + or bool(affected & (RSTACK_DEV_HARNESS_PACKAGES | SERVICE_PREVIEW_PRODUCT_PACKAGES)) or any(matches(path, *SERVICE_PREVIEW_INPUTS) for path in paths) ) diff --git a/.github/scripts/test_ci_changes.py b/.github/scripts/test_ci_changes.py index e6b2b3fba3..730aa73765 100644 --- a/.github/scripts/test_ci_changes.py +++ b/.github/scripts/test_ci_changes.py @@ -3882,6 +3882,10 @@ def test_service_preview_inputs_select_installed_browser_proof(self) -> None: "clients/typescript/preview/host.mjs", "products/platform/examples/service-previews/medical-renewal/dev.yaml", "products/platform/scripts/test-service-previews.mjs", + # permit-review starts Casework and the Coordinator. + "crates/registry-casework/src/lib.rs", + "crates/registry-caseworkctl/src/main.rs", + "crates/registry-coordinator/src/lib.rs", ): with self.subTest(path=path): outputs = classify(self.workspace, (path,)) @@ -3892,6 +3896,32 @@ def test_service_preview_inputs_select_installed_browser_proof(self) -> None: browser = next(step for step in steps if step.get("name") == "Run installed service previews in Chromium") self.assertIn("needs.changes.outputs.service_previews", browser["if"]) self.assertIn("test-service-previews.mjs", browser["run"]) + build = next(step for step in steps if step.get("name") == "Build the preview launcher and product tools") + for package in ("registry-casework", "registry-caseworkctl", "registry-coordinator"): + self.assertIn(f"-p {package}", build["run"]) + for name in ("CASEWORK", "CASEWORKCTL", "COORDINATOR", "COORDINATORCTL"): + self.assertIn(f"RSTACK_{name}_BIN", browser["env"]) + # A candidate whose release ships the Coordinator installs it and must + # pass permit-review; only one without it may skip, through the roster. + candidate = yaml.safe_load(Path(".github/workflows/release-candidate.yml").read_text()) + runs = [ + step.get("run", "") + for job in candidate["jobs"].values() + for step in job.get("steps", []) + ] + install = next(run for run in runs if "rstack-${tag}-install.sh" in run) + self.assertIn("coordinator-binaries-in-release", install) + self.assertIn("components+=(casework coordinator)", install) + smoke = next(run for run in runs if "test-service-previews.mjs" in run) + self.assertIn("coordinator-binaries-in-release", smoke) + self.assertIn("RSTACK_PREVIEW_SKIP_PERMIT_REVIEW=no-coordinator-in-release", smoke) + # A roster failure fails the step: its output is assigned first, never + # read inside [[ ]], where set -e does not stop a failed substitution. + for run in (install, smoke): + self.assertIn('coordinator_in_release="$(python3 release/scripts/release_roster.py', run) + self.assertNotRegex(run, r'\$\(python3 release/scripts/release_roster\.py\s*\\?\s*coordinator-binaries-in-release[^)]*\)"\s*[!=]=') + self.assertIn('for component in casework coordinator; do', install) + self.assertIn('"${component}ctl ${version}"', install) def test_development_schema_drift_runs_in_the_conformance_job(self) -> None: for path in ( diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index cb87dc32dc..f50f173ccf 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -4159,9 +4159,12 @@ jobs: - name: Build run: npm --prefix clients/typescript run build - - name: Build the preview launcher and BReg tools + - name: Build the preview launcher and product tools if: needs.changes.outputs.service_previews == 'true' - run: cargo build --locked --bins --features registry-breg/runtime -p registry-rstack -p registry-breg -p registry-bregctl + run: >- + cargo build --locked --bins --features registry-breg/runtime + -p registry-rstack -p registry-breg -p registry-bregctl + -p registry-casework -p registry-caseworkctl -p registry-coordinator - name: Install Chromium for previews if: needs.changes.outputs.service_previews == 'true' @@ -4169,10 +4172,14 @@ jobs: - name: Run installed service previews in Chromium if: needs.changes.outputs.service_previews == 'true' - timeout-minutes: 15 + timeout-minutes: 20 env: RSTACK_BREG_BIN: ${{ github.workspace }}/target/debug/breg RSTACK_BREGCTL_BIN: ${{ github.workspace }}/target/debug/bregctl + RSTACK_CASEWORK_BIN: ${{ github.workspace }}/target/debug/casework + RSTACK_CASEWORKCTL_BIN: ${{ github.workspace }}/target/debug/caseworkctl + RSTACK_COORDINATOR_BIN: ${{ github.workspace }}/target/debug/coordinator + RSTACK_COORDINATORCTL_BIN: ${{ github.workspace }}/target/debug/coordinatorctl run: | set -euo pipefail client_dir="${GITHUB_WORKSPACE}/clients/typescript" diff --git a/.github/workflows/release-candidate.yml b/.github/workflows/release-candidate.yml index 1969730087..9a630d4226 100644 --- a/.github/workflows/release-candidate.yml +++ b/.github/workflows/release-candidate.yml @@ -2559,11 +2559,21 @@ jobs: sha256sum -- * > SHA256SUMS ) destination="${RUNNER_TEMP}/rstack-install-smoke" + components=(breg evidence) + # The permit-review preview also needs Casework and the Coordinator. + # A release that ships them must install and pass it; the preview + # smoke skips it only for a release without the Coordinator. The + # assignment fails the step when the roster itself fails. + coordinator_in_release="$(python3 release/scripts/release_roster.py \ + coordinator-binaries-in-release "${version}")" + if [[ "${coordinator_in_release}" == true ]]; then + components+=(casework coordinator) + fi bash "${assets}/rstack-${tag}-install.sh" \ --asset-dir "${assets}" \ --bin-dir "${destination}/bin" \ --install-root "${destination}/lib" \ - breg evidence + "${components[@]}" test -L "${destination}/bin/rstack" test "$(find "${destination}/bin" -mindepth 1 -maxdepth 1 | wc -l)" -eq 1 rstack=("${destination}/bin/rstack" @@ -2578,6 +2588,15 @@ jobs: >/dev/null test "$("${rstack[@]}" breg --version)" = "bregctl ${version}" test "$("${rstack[@]}" evidence --version)" = "evidencectl ${version}" + if [[ "${coordinator_in_release}" == true ]]; then + for component in casework coordinator; do + "${rstack[@]}" components list --format json \ + | jq -e --arg name "${component}" \ + '.components | any(.name == $name and .installed == true)' \ + >/dev/null + test "$("${rstack[@]}" "${component}" --version)" = "${component}ctl ${version}" + done + fi - name: Install Node for the installed service preview smoke if: needs.validate.outputs.unit == 'stack' @@ -2585,7 +2604,7 @@ jobs: with: node-version: 24.11.0 - - name: Smoke both role-backed previews with installed candidate artifacts + - name: Smoke the role-backed previews with installed candidate artifacts if: needs.validate.outputs.unit == 'stack' shell: bash env: @@ -2603,6 +2622,11 @@ jobs: export RSTACK_PREVIEW_INSTALL_ROOT="${destination}/lib" export RSTACK_PREVIEW_BIN_DIR="${destination}/bin" export RSTACK_PREVIEW_EXAMPLES_DIR="${RUNNER_TEMP}/candidate-service-previews" + coordinator_in_release="$(python3 release/scripts/release_roster.py \ + coordinator-binaries-in-release "${CANDIDATE_PREVIEW_VERSION}")" + if [[ "${coordinator_in_release}" != true ]]; then + export RSTACK_PREVIEW_SKIP_PERMIT_REVIEW=no-coordinator-in-release + fi cp -R products/platform/examples/service-previews "${RSTACK_PREVIEW_EXAMPLES_DIR}" node "${GITHUB_WORKSPACE}/products/platform/scripts/prepare-service-preview-locks.mjs" \ "${assets}/${web_package}" "${RSTACK_PREVIEW_EXAMPLES_DIR}" From 93f65bc8d9d213e55e5af9220197085080f6c0dc Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Wed, 2 Dec 2026 00:32:34 +0000 Subject: [PATCH 151/183] ci: run the Evidence store provisioning journey and fail on roster errors The Evidence store provisioning test reads the shared provisioning environment, so the TLS PostgreSQL lane now runs it and checks its own journey line, because those stores provision and serve nothing. Release candidate steps assign each roster answer before testing it, so a roster error fails the step instead of reading as not in release. Signed-off-by: Jeremi Joslin --- .github/scripts/ci_changes.py | 12 ++++++-- .github/scripts/test_ci_changes.py | 40 +++++++++++++++++++++++-- .github/workflows/ci.yml | 14 +++++++-- .github/workflows/release-candidate.yml | 19 +++++++----- 4 files changed, 70 insertions(+), 15 deletions(-) diff --git a/.github/scripts/ci_changes.py b/.github/scripts/ci_changes.py index 9632af453a..b127f88f4a 100644 --- a/.github/scripts/ci_changes.py +++ b/.github/scripts/ci_changes.py @@ -667,17 +667,25 @@ "registry-caseworkctl", "registry-coordinator", "registry-documentsctl", + "registry-evidencectl", "registry-messagingctl", "registry-schedulingctl", ) PROVISION_JOURNEY_INPUTS = ( - *(f"crates/{package}/src/provision.rs" for package in PROVISION_JOURNEY_PACKAGES), + *( + f"crates/{package}/src/provision.rs" + for package in PROVISION_JOURNEY_PACKAGES + if package != "registry-evidencectl" + ), # 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" + if package not in ("registry-caseworkctl", "registry-evidencectl") ), + # Evidence provisions its held stores and serves nothing. + "crates/registry-evidencectl/src/store_provision.rs", + "crates/registry-evidencectl/tests/store_provision.rs", "crates/registry-adapterctl/src/job_provision.rs", "crates/registry-adapterctl/tests/job_provision_postgres.rs", "crates/registry-adapter-job/src/main.rs", diff --git a/.github/scripts/test_ci_changes.py b/.github/scripts/test_ci_changes.py index 730aa73765..fe8304327c 100644 --- a/.github/scripts/test_ci_changes.py +++ b/.github/scripts/test_ci_changes.py @@ -4766,7 +4766,13 @@ def test_product_provisioning_changes_select_the_tls_postgres_lane(self) -> None 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), + # A journey test target names its source: `provision_postgres.rs` + # and `provision.rs` test `provision.rs`, `store_provision.rs` + # tests `store_provision.rs`. + *( + f"crates/{package}/src/{target.removesuffix('_postgres')}.rs" + for package, (target, _) in journeys.items() + ), *(f"crates/{package}/tests/{target}.rs" for package, (target, _) in journeys.items()), "crates/registry-adapterctl/src/job_provision.rs", "crates/registry-adapterctl/tests/job_provision_postgres.rs", @@ -4878,11 +4884,39 @@ def test_contracts_journeys_lane_runs_each_product_provisioning_journey( '"${log}"', command, ) + # Each log needs its journey's own line. A journey that serves + # matches the shared serve pattern, and one that only provisions, + # such as the Evidence stores, names its exact test. + serve = re.compile(r"provision_then_(apply_then_)?serve_with_[a-z_]+") self.assertIn( - "grep -Eq '^test ([a-z_]+::)?provision_then_(apply_then_)?serve_with_[a-z_]+ " - "\\.\\.\\. ok$' \"${log}\"", + "*) journey='^test ([a-z_]+::)?provision_then_(apply_then_)?serve_with_[a-z_]+ " + "\\.\\.\\. ok$' ;;", command, ) + for package, (_, tests) in journeys.items(): + if any(serve.fullmatch(test) for test in tests): + continue + with self.subTest(package=package): + self.assertEqual(1, len(tests), "a provision-only journey names one test") + self.assertIn( + f"{package}) journey='^test {tests[0]} \\.\\.\\. ok$' ;;", + command, + ) + self.assertIn('grep -Eq "${journey}" "${log}"', command) + + def test_no_workflow_reads_a_roster_answer_inside_a_conditional(self) -> None: + # Inside [[ ]], set -e does not stop a failed command substitution, so + # a roster error would read as "not in release". Assign the answer to + # a variable first, so the failure stops the step. + inline = re.compile( + r'\[\[[^\]]*?"\$\(python3 release/scripts/release_roster\.py', re.S + ) + 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", []): + with self.subTest(workflow=workflow.name, job=job_name, step=step.get("name")): + self.assertIsNone(inline.search(step.get("run", ""))) def test_other_postgres_steps_leave_the_provisioning_journeys_to_the_tls_lane( self, diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index f50f173ccf..46842d48f5 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -2145,6 +2145,8 @@ jobs: | 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-evidencectl --features postgres-test --test store_provision \ + | tee "${RUNNER_TEMP}/provision-journey-registry-evidencectl.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 \ @@ -2157,11 +2159,17 @@ jobs: grep -Eq '^test result: ok\. 1 passed; 0 failed; 0 ignored' "${job_log}" || { echo "::error::expected one passing Adapter job provisioning journey"; exit 1; } grep -Fxq 'test provision_then_initialize_and_run_with_split_roles ... ok' "${job_log}" || { echo "::error::expected the Adapter job provisioning journey to run and pass"; exit 1; } # 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 + # pass count, no ignored test, and the journey's own line. The + # Evidence stores provision and serve nothing, so their journey + # names its exact test. + for package in registry-adapterctl registry-bregctl registry-caseworkctl registry-coordinator registry-documentsctl registry-evidencectl 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; } + case "${package}" in + registry-evidencectl) journey='^test both_stores_provision_idempotently_without_migrating \.\.\. ok$' ;; + *) journey='^test ([a-z_]+::)?provision_then_(apply_then_)?serve_with_[a-z_]+ \.\.\. ok$' ;; + esac + grep -Eq "${journey}" "${log}" || { echo "::error::expected the ${package} provisioning journey to run and pass"; exit 1; } done - name: Stop PostgreSQL 16 for the provisioning floor test diff --git a/.github/workflows/release-candidate.yml b/.github/workflows/release-candidate.yml index 9a630d4226..f065943eab 100644 --- a/.github/workflows/release-candidate.yml +++ b/.github/workflows/release-candidate.yml @@ -546,7 +546,9 @@ jobs: "coordinator ${{ needs.validate.outputs.version }}" test "$("dist/bin/coordinatorctl-${{ needs.validate.outputs.tag }}-linux-amd64" --version)" = \ "coordinatorctl ${{ needs.validate.outputs.version }}" - if [[ "$(python3 release/scripts/release_roster.py coordinator-in-release "${{ needs.validate.outputs.version }}")" == true ]]; then + coordinator_image_in_release="$(python3 release/scripts/release_roster.py \ + coordinator-in-release "${{ needs.validate.outputs.version }}")" + if [[ "${coordinator_image_in_release}" == true ]]; then test "$(dist/image-bin/coordinator --version)" = \ "coordinator ${{ needs.validate.outputs.version }}" test "$(dist/image-bin/coordinatorctl --version)" = \ @@ -2314,8 +2316,9 @@ jobs: "${binary} ${{ needs.validate.outputs.version }}" done rm candidate/bundle-root/SHA256SUMS - if [[ "$(python3 release/scripts/release_roster.py \ - rstack-in-release "${version}")" == true ]]; then + rstack_in_release="$(python3 release/scripts/release_roster.py \ + rstack-in-release "${version}")" + if [[ "${rstack_in_release}" == true ]]; then rstack_installer="rstack-${{ needs.validate.outputs.tag }}-install.sh" awk -v version="${{ needs.validate.outputs.tag }}" ' $0 == "default_version=\"\"" { @@ -2428,9 +2431,10 @@ jobs: done | jq -s . )" rstack_components=null + rstack_in_release="$(python3 release/scripts/release_roster.py \ + rstack-in-release "${version}")" if [[ "${{ needs.validate.outputs.unit }}" == stack && - "$(python3 release/scripts/release_roster.py \ - rstack-in-release "${version}")" == true ]]; then + "${rstack_in_release}" == true ]]; then rstack_components="$(printf '%s' "${payloads}" \ | python3 release/scripts/rstack_components.py --version "${version}")" fi @@ -2546,8 +2550,9 @@ jobs: run: | set -euo pipefail version="${{ needs.validate.outputs.version }}" - if [[ "$(python3 release/scripts/release_roster.py \ - rstack-in-release "${version}")" != true ]]; then + rstack_in_release="$(python3 release/scripts/release_roster.py \ + rstack-in-release "${version}")" + if [[ "${rstack_in_release}" != true ]]; then exit 0 fi tag="${{ needs.validate.outputs.tag }}" From d63842a24ef58a013648a6de00baa462338e6271 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Wed, 2 Dec 2026 00:32:05 +0000 Subject: [PATCH 152/183] test(dev): pin every preview route parameter and the generator diagnostic order Fold the rebase review. The docs and the route error name {record_id} and {revision} beside {recordId}, {taskId} and {runId}. Tests refuse a route that mixes {record_id} with {taskId}, match {revision} on a Coordinator route only for a bounded revision number, and assert that a refused actors build shows the generator's diagnostic before the preview's hint. Signed-off-by: Jeremi Joslin --- clients/typescript/preview/gateway.mjs | 2 +- clients/typescript/preview/tests/preview.test.mjs | 13 +++++++++++-- crates/registry-rstack-dev/src/plan.rs | 8 +++++++- .../configure/run-a-project-with-rstack-dev.mdx | 5 +++-- 4 files changed, 22 insertions(+), 6 deletions(-) diff --git a/clients/typescript/preview/gateway.mjs b/clients/typescript/preview/gateway.mjs index 51a40ebeda..068fe6f799 100644 --- a/clients/typescript/preview/gateway.mjs +++ b/clients/typescript/preview/gateway.mjs @@ -41,7 +41,7 @@ function compilePaths(paths = []) { if (parts.length < 2 || parts.filter(part => placeholders.has(part)).length > 1 || parts.filter(part => part === '{revision}').length > 1 || !parts.every(part => segment.test(part) || placeholders.has(part) || part === '{revision}')) { - throw new Error('Expected an exact /v1/ preview route with at most one {recordId}, {taskId} or {runId} and at most one {revision}.') + throw new Error('Expected an exact /v1/ preview route with at most one {recordId}, {record_id}, {taskId} or {runId} and at most one {revision}.') } return parts }) diff --git a/clients/typescript/preview/tests/preview.test.mjs b/clients/typescript/preview/tests/preview.test.mjs index 31bdb81919..b8463d59ce 100644 --- a/clients/typescript/preview/tests/preview.test.mjs +++ b/clients/typescript/preview/tests/preview.test.mjs @@ -309,10 +309,17 @@ test('an actors policy compiles per-product routes and is exclusive with the sin { page: '/', functions: [], actors: { Applicant: {} } }, { page: '/', functions: [], actors: { applicant: { messaging: {} } } }, { page: '/', functions: [], actors: { applicant: { coordinator: { get: ['/v1/runs/{runId}/{taskId}'] } } } }, + { page: '/', functions: [], actors: { officer: { casework: { get: ['/v1/review-tasks/{record_id}/{taskId}'] } } } }, + { page: '/', functions: [], actors: { officer: { casework: { get: ['/v1/review-tasks/{taskId}/{revision}/{revision}'] } } } }, ]) { assert.throws(() => previewPolicy(invalid), JSON.stringify(invalid)) } assert.equal(compileRoutes({ get: ['/v1/review-tasks/{taskId}'] })('GET', '/v1/review-tasks/' + run), true) + // {revision} matches one bounded revision number on any product's route. + const revisions = compileRoutes({ get: ['/v1/runs/{runId}/revisions/{revision}'] }) + assert.equal(revisions('GET', '/v1/runs/' + run + '/revisions/7'), true) + assert.equal(revisions('GET', '/v1/runs/' + run + '/revisions/0'), false) + assert.equal(revisions('GET', '/v1/runs/' + run + '/revisions/9223372036854775808'), false) }) test('a gateway relays each product with its own credential, profile and routes', async (t) => { @@ -574,8 +581,10 @@ test('an actors preview names no Proposal author and refuses a register with Pro ['--author-profile', 'permits=permit-applicant']) const actors = generatorArguments({ product, preview: { functions: ['assess-permit'], actors: { applicant: {} } } }, '/staged') assert.equal(actors.includes('--author-profile'), false) - assert.match(generationError('The register permits has Proposals, so the service description needs authorProfiles.', true).message, - /actors preview cannot start Proposals/u) + const proposals = generationError('The register permits has Proposals, so the service description needs authorProfiles.', true).message + // The generator's own diagnostic comes first, then the preview's hint. + assert.ok(proposals.startsWith('The register permits has Proposals'), proposals) + assert.match(proposals, /\nAn actors preview cannot start Proposals/u) assert.match(generationError('The authorProfile "x" cannot start Proposals in permits.', false).message, /Select a preview actor whose BReg profile can start Proposals/u) assert.equal(generationError('generator diagnostic', true).message, 'generator diagnostic') diff --git a/crates/registry-rstack-dev/src/plan.rs b/crates/registry-rstack-dev/src/plan.rs index 665f3c3d19..405f3052e3 100644 --- a/crates/registry-rstack-dev/src/plan.rs +++ b/crates/registry-rstack-dev/src/plan.rs @@ -4036,10 +4036,14 @@ mod preview_tests { "/v1/records/licences/{recordId}", true )); - for id in ["{recordId}", "{record_id}"] { + for id in ["{recordId}", "{record_id}", "{taskId}", "{runId}"] { let path = format!("/v1/records/applications/{id}/revisions/{{revision}}"); assert!(super::super::preview::valid_path(&path, true), "{path}"); } + assert!(super::super::preview::valid_path( + "/v1/runs/{runId}/revisions/{revision}", + true + )); assert!(super::super::preview::valid_path("/check.html", false)); for path in [ "//elsewhere", @@ -4050,6 +4054,8 @@ mod preview_tests { "/v1/records/{anything}", "/v1/records/{recordId}/{recordId}", "/v1/records/{recordId}/{record_id}", + "/v1/review-tasks/{record_id}/{taskId}", + "/v1/runs/{runId}/{revision}/{revision}", "/v1/records/{recordId}/revisions/{revision}/{revision}", "/v1/records/#fragment", ] { diff --git a/docs/site/src/content/docs/configure/run-a-project-with-rstack-dev.mdx b/docs/site/src/content/docs/configure/run-a-project-with-rstack-dev.mdx index ed1a8ec237..10e0691a2e 100644 --- a/docs/site/src/content/docs/configure/run-a-project-with-rstack-dev.mdx +++ b/docs/site/src/content/docs/configure/run-a-project-with-rstack-dev.mdx @@ -89,8 +89,9 @@ and it answers only the page: a request without `Registry-Client: page`, or with The generated client names no Proposal author in an actors preview, because each actor's origin pins its own BReg profile. A register with Proposals therefore needs the single-actor form, and the build refuses it in an actors preview. -A path may hold one `{recordId}`, `{taskId}` or `{runId}` segment, each matching only a UUID, -for any product. The name documents the path and does not restrict where it may appear. +A path may hold one `{recordId}`, `{record_id}`, `{taskId}` or `{runId}` segment, each +matching only a UUID, and one `{revision}` segment, matching only a Record revision number, for +any product. The name documents the path and does not restrict where it may appear. ```yaml preview: From bee5c4e65eeff46f5f55ad6bd062f48b808e2756 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 23:46:04 +0000 Subject: [PATCH 153/183] test(coordinator): pin the external, decision and token transport rules Characterization before the outbound transport moves to the shared selector: the destinations each connection admits, metadata refused before credentials in its IPv4-mapped form too, and an unresolvable destination answered as unavailable. Refs #2817. Signed-off-by: Jeremi Joslin --- crates/registry-coordinator/src/adapters.rs | 10 ++ .../tests/decision_runtime.rs | 102 ++++++++++++++++++ .../tests/external_http.rs | 53 +++++++++ 3 files changed, 165 insertions(+) diff --git a/crates/registry-coordinator/src/adapters.rs b/crates/registry-coordinator/src/adapters.rs index ae7a1901c8..31afd5949f 100644 --- a/crates/registry-coordinator/src/adapters.rs +++ b/crates/registry-coordinator/src/adapters.rs @@ -2132,5 +2132,15 @@ mod tests { assert!(configured_endpoint_policy(&cleartext) .validate_dns_pinned_for_immediate_fetch(&cleartext) .is_err()); + for loopback in ["http://127.0.0.1:9999/token", "http://[::1]:9999/token"] { + let loopback: Url = loopback.parse().unwrap(); + assert!(configured_endpoint_policy(&loopback) + .validate_dns_pinned_for_immediate_fetch(&loopback) + .is_ok()); + } + let mapped: Url = "https://[::ffff:169.254.169.254]/token".parse().unwrap(); + assert!(configured_endpoint_policy(&mapped) + .validate_dns_pinned_for_immediate_fetch(&mapped) + .is_err()); } } diff --git a/crates/registry-coordinator/tests/decision_runtime.rs b/crates/registry-coordinator/tests/decision_runtime.rs index 4deebb2b74..d29ba52444 100644 --- a/crates/registry-coordinator/tests/decision_runtime.rs +++ b/crates/registry-coordinator/tests/decision_runtime.rs @@ -301,3 +301,105 @@ fn decision_runtime_preserves_unknown_key_positions_and_defers_environment_value .all(|finding| finding.severity != registry_platform_yaml::Severity::Error)); assert!(checked.defers("/connections/assessor/baseUrl")); } + +// Transport selection. These pin the decision destinations a deployment +// admits and how a refused or unreachable one is answered, whatever selects +// the transport. + +fn with_base(base: &str, authorization: Value) -> Value { + let mut d = document(); + d["connections"]["assessor"]["baseUrl"] = json!(base); + d["connections"]["assessor"]["authorization"] = authorization; + d +} + +fn bearer() -> Value { + json!({"bearer":{"tokenRef":"secret:env/UNRESOLVED_DECISION_TEST_TOKEN","principal":"fixture-account"}}) +} + +#[test] +fn decision_destinations_admit_https_and_numeric_loopback_http_only() { + for base in [ + "https://decision.example.test/tenant", + "https://10.0.0.8/tenant", + "http://127.0.0.1:8080/tenant", + "http://127.1.2.3/tenant", + "http://[::1]:8080/tenant", + "http://[::ffff:127.0.0.1]:8080/tenant", + ] { + load(&with_base(base, bearer())).unwrap_or_else(|_| panic!("{base} is admitted")); + } + for base in [ + "http://localhost:8080/tenant", + "http://decision.example.test/tenant", + "http://10.0.0.1/tenant", + "http://user@127.0.0.1/tenant", + "ftp://decision.example.test/tenant", + ] { + assert!( + load(&with_base(base, bearer())).is_err(), + "{base} is refused" + ); + } +} + +#[test] +fn local_decision_authorization_stays_on_numeric_loopback() { + load(&with_base( + "http://127.0.0.1:8080/tenant", + json!({"local":{}}), + )) + .unwrap(); + load(&with_base("http://[::1]:8080/tenant", json!({"local":{}}))).unwrap(); + for base in [ + "https://decision.example.test/tenant", + "https://localhost/tenant", + "http://localhost:8080/tenant", + ] { + assert!( + load(&with_base(base, json!({"local":{}}))).is_err(), + "local authorization is refused at {base}" + ); + } +} + +/// Evaluate once against `base` with a bearer credential that never resolves, +/// so a destination checked before credentials answers its own outcome. +async fn evaluate_unresolved_credential(base: &str) -> CallOutcome { + let adapters = HttpAdapters::new(&load(&with_base(base, bearer())).unwrap()).unwrap(); + let request = CallRequest { + operation_contract: None, + connection: "assessor".into(), + operation: Operation::EvaluateDecision, + input: json!({"state":{"summary":"synthetic"},"questions":{"ready":{"type":"predicate","instructions":"Ready?"}}}), + idempotency_key: None, + }; + let Ok(Some(prepared)) = adapters.prepare(&request).await else { + panic!("inert preparation must succeed") + }; + adapters.call_prepared(&request, Some(&prepared)).await +} + +#[tokio::test] +async fn a_metadata_decision_destination_is_refused_before_acquiring_credentials() { + for base in [ + "https://169.254.169.254/tenant", + "https://[::ffff:169.254.169.254]/tenant", + ] { + let outcome = evaluate_unresolved_credential(base).await; + assert!( + matches!(&outcome, CallOutcome::Refused { code } if code == "decision-invalid-command"), + "{base} is refused before credentials" + ); + } +} + +#[tokio::test] +async fn an_unresolvable_decision_destination_is_unavailable_before_credentials() { + let outcome = + evaluate_unresolved_credential("https://coordinator-transport.invalid/tenant").await; + assert!( + matches!(&outcome, CallOutcome::Retryable { code, .. } if code == "decision-unavailable"), + "an unresolvable destination is unavailable" + ); +} diff --git a/crates/registry-coordinator/tests/external_http.rs b/crates/registry-coordinator/tests/external_http.rs index 5108fef85a..f6671d8131 100644 --- a/crates/registry-coordinator/tests/external_http.rs +++ b/crates/registry-coordinator/tests/external_http.rs @@ -518,3 +518,56 @@ fn offline_contract_refuses_unsafe_urls_paths_and_external_schema_fetches() { .to_string() .contains("sensitive-invalid-resource-canary")); } + +// Transport selection. These pin the destinations a reviewed external +// connection admits and how a refused or unreachable one is answered, whatever +// selects the transport. + +#[test] +fn external_destinations_admit_https_and_numeric_loopback_http_only() { + for base in [ + "https://directory.example.test/", + "https://10.0.0.8/", + "https://[fd00::8]/", + "http://127.0.0.1:8080/", + "http://127.1.2.3/", + "http://[::1]:8080/", + "http://[::ffff:127.0.0.1]:8080/", + ] { + config(base) + .validate() + .unwrap_or_else(|_| panic!("{base} is admitted")); + } + for base in [ + "http://localhost:8080/", + "http://directory.example.test/", + "http://10.0.0.1/", + "http://192.168.1.4/", + "http://user@127.0.0.1/", + "ftp://directory.example.test/", + ] { + let mut admitted = config("https://directory.example.test/"); + admitted.base_url = base.parse().unwrap(); + assert!(admitted.validate().is_err(), "{base} is refused"); + } +} + +#[tokio::test] +async fn a_mapped_metadata_address_is_refused_before_acquiring_credentials() { + let mut config = config("https://[::ffff:169.254.169.254]"); + config.authorization = Some(authorization()); + let connection = ExternalHttpConnection::new(&config, Some(Arc::new(SlowTokens))).unwrap(); + assert!( + matches!(connection.get(&json!({"path":"offices"}), false).await, + CallOutcome::Refused { code } if code == "external-destination-refused") + ); +} + +#[tokio::test] +async fn an_unresolvable_destination_is_unavailable_not_refused() { + let connection = connection(&config("https://coordinator-transport.invalid")); + assert!(matches!( + connection.get(&json!({"path":"offices"}), false).await, + CallOutcome::Retryable { code, .. } if code == "external-unavailable" + )); +} From a4f1c7e1834145b74c454b80fb1e2a91bf380e38 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 23:50:43 +0000 Subject: [PATCH 154/183] refactor(coordinator): select outbound transport through the shared selector External reads and commands, decision calls and token endpoints chose their DNS-pinned policy by reading the URL scheme, in three copies. One helper now selects each endpoint through the shared credential selector, keeps plain HTTP to numeric loopback addresses, and maps the selected transport to the policy. Admitted destinations, the refusal-before-credentials order and the unavailable and refused outcomes are unchanged. The request-time layer now also refuses the name localhost before DNS, as configuration validation already did, so no deployed configuration changes. Refs #2817. Signed-off-by: Jeremi Joslin --- crates/registry-coordinator/src/adapters.rs | 33 +++--- crates/registry-coordinator/src/decision.rs | 33 ++---- .../registry-coordinator/src/external_http.rs | 30 +---- crates/registry-coordinator/src/lib.rs | 1 + crates/registry-coordinator/src/outbound.rs | 112 ++++++++++++++++++ crates/registry-coordinator/src/runtime.rs | 21 +--- 6 files changed, 148 insertions(+), 82 deletions(-) create mode 100644 crates/registry-coordinator/src/outbound.rs diff --git a/crates/registry-coordinator/src/adapters.rs b/crates/registry-coordinator/src/adapters.rs index 31afd5949f..b49efd6559 100644 --- a/crates/registry-coordinator/src/adapters.rs +++ b/crates/registry-coordinator/src/adapters.rs @@ -111,20 +111,13 @@ fn config_error() -> CoordinatorError { // Destinations are explicit, reviewed deployment bindings. Institutional peers // may use private HTTPS networks; all token requests remain DNS-pinned and -// reject metadata addresses. Cleartext remains numeric loopback only. +// reject metadata addresses. Cleartext remains numeric loopback only. An +// endpoint the Coordinator would not admit gets the strict policy, which +// refuses it again at request time. fn configured_endpoint_policy(endpoint: &Url) -> FetchUrlPolicy { - if endpoint.scheme() == "http" { - FetchUrlPolicy::https_or_loopback() - } else { - FetchUrlPolicy { - allowed_schemes: vec!["https".into()], - allow_localhost: true, - allow_http_private_network: false, - allow_http_non_loopback: false, - deny_private_ranges: false, - deny_cloud_metadata: true, - } - } + crate::outbound::select_endpoint(endpoint).map_or_else(FetchUrlPolicy::strict, |selected| { + crate::outbound::fetch_policy(&selected) + }) } fn tokens( @@ -2138,9 +2131,15 @@ mod tests { .validate_dns_pinned_for_immediate_fetch(&loopback) .is_ok()); } - let mapped: Url = "https://[::ffff:169.254.169.254]/token".parse().unwrap(); - assert!(configured_endpoint_policy(&mapped) - .validate_dns_pinned_for_immediate_fetch(&mapped) - .is_err()); + for refused in [ + "https://[::ffff:169.254.169.254]/token", + "https://169.254.1.1/token", + "http://localhost:9999/token", + ] { + let refused: Url = refused.parse().unwrap(); + assert!(configured_endpoint_policy(&refused) + .validate_dns_pinned_for_immediate_fetch(&refused) + .is_err()); + } } } diff --git a/crates/registry-coordinator/src/decision.rs b/crates/registry-coordinator/src/decision.rs index b097f20325..6295d850a2 100644 --- a/crates/registry-coordinator/src/decision.rs +++ b/crates/registry-coordinator/src/decision.rs @@ -10,12 +10,12 @@ use std::{collections::BTreeMap, sync::Arc, time::Duration}; use registry_platform_canonical_json::{canonicalize_json, parse_json_strict}; use registry_platform_config::{SecretReference, SecretResolver}; use registry_platform_httputil::{ - client::BearerToken, read_bounded, FetchUrlError, FetchUrlPolicy, ServiceBaseUrl, + client::BearerToken, read_bounded, FetchUrlError, ServiceBaseUrl, }; use registry_platform_yaml::{BoundedU64, ExternalId, LocalId}; use serde::{Deserialize, Deserializer, Serialize}; use serde_json::{json, Value}; -use url::{Host, Url}; +use url::Url; use crate::{protocol::CallOutcome, CoordinatorError, Result}; @@ -91,15 +91,7 @@ impl DecisionConfig { } pub fn findings(&self, prefix: &str) -> Vec { - let loopback = match self.base_url.host() { - 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 loopback = crate::outbound::numeric_loopback(&self.base_url); let mut errors = Vec::new(); let mut refuse = |field: &str, repair: &str| { let field = if prefix.is_empty() { @@ -117,8 +109,7 @@ impl DecisionConfig { ); }; if ServiceBaseUrl::new(self.base_url.clone()).is_err() - || !matches!(self.base_url.scheme(), "https" | "http") - || (self.base_url.scheme() == "http" && !loopback) + || crate::outbound::select_endpoint(&self.base_url).is_none() { refuse("baseUrl", "Use HTTPS or explicit numeric loopback HTTP, without credentials, query, fragment or empty interior path segments."); } @@ -314,19 +305,9 @@ impl DecisionConnection { &self, timeout: Duration, ) -> std::result::Result { - let policy = if self.endpoint.scheme() == "http" { - FetchUrlPolicy::https_or_loopback() - } else { - FetchUrlPolicy { - allowed_schemes: vec!["https".into()], - allow_localhost: true, - allow_http_private_network: false, - allow_http_non_loopback: false, - deny_private_ranges: false, - deny_cloud_metadata: true, - } - }; - let validated = policy + let selected = crate::outbound::select_endpoint(&self.endpoint) + .ok_or_else(|| refused("decision-invalid-command"))?; + let validated = crate::outbound::fetch_policy(&selected) .validate_dns_pinned_for_immediate_fetch_with_timeout(&self.endpoint, timeout) .await .map_err(|error| match error { diff --git a/crates/registry-coordinator/src/external_http.rs b/crates/registry-coordinator/src/external_http.rs index b4dc1d4339..b9a9305be1 100644 --- a/crates/registry-coordinator/src/external_http.rs +++ b/crates/registry-coordinator/src/external_http.rs @@ -11,12 +11,12 @@ use jsonschema::JSONSchema; use registry_platform_canonical_json::parse_json_strict; use registry_platform_httputil::{ client::{RetryAfter, TokenProvider}, - read_bounded, BoundedReadError, FetchUrlError, FetchUrlPolicy, ServiceBaseUrl, + read_bounded, BoundedReadError, FetchUrlError, ServiceBaseUrl, }; use registry_platform_yaml::{BoundedU64, ExternalId, ForeignValue, LocalId, UniqueList}; use serde::{Deserialize, Deserializer, Serialize}; use serde_json::Value; -use url::{Host, Url}; +use url::Url; use crate::{protocol::CallOutcome, runtime::AuthorizationConfig, CoordinatorError, Result}; use registry_platform_config::SecretReference; @@ -182,16 +182,7 @@ impl ExternalHttpConfig { ); }; let base = ServiceBaseUrl::new(self.base_url.clone()); - let numeric_loopback = match self.base_url.host() { - 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) { + if base.is_err() || crate::outbound::select_endpoint(&self.base_url).is_none() { refuse("baseUrl", "Use HTTPS or explicit numeric loopback HTTP, without credentials, query, fragment or empty interior path segments."); } if self.paths.is_empty() @@ -515,19 +506,10 @@ impl ExternalHttpConnection { // The destination was reviewed by the operator. Institutional HTTPS // 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::https_or_loopback() - } else { - FetchUrlPolicy { - allowed_schemes: vec!["https".into()], - allow_localhost: true, - allow_http_private_network: false, - allow_http_non_loopback: false, - deny_private_ranges: false, - deny_cloud_metadata: true, - } + let Some(selected) = crate::outbound::select_endpoint(&url) else { + return Err(refused("external-destination-refused")); }; - let validated = match policy + let validated = match crate::outbound::fetch_policy(&selected) .validate_dns_pinned_for_immediate_fetch_with_timeout(&url, timeout) .await { diff --git a/crates/registry-coordinator/src/lib.rs b/crates/registry-coordinator/src/lib.rs index c71da85b3c..db2452333c 100644 --- a/crates/registry-coordinator/src/lib.rs +++ b/crates/registry-coordinator/src/lib.rs @@ -18,6 +18,7 @@ mod follow_check; mod functions; mod mapping_check; pub mod operations; +mod outbound; pub mod problem; pub mod project; mod project_check; diff --git a/crates/registry-coordinator/src/outbound.rs b/crates/registry-coordinator/src/outbound.rs new file mode 100644 index 0000000000..0b3ddad2ed --- /dev/null +++ b/crates/registry-coordinator/src/outbound.rs @@ -0,0 +1,112 @@ +// SPDX-License-Identifier: Apache-2.0 +//! The transport of every configured outbound destination: external reads and +//! commands, decision services and product token endpoints. +//! +//! Each carries a credential, so the shared credential selector decides the +//! transport. The Coordinator narrows it once more: plain HTTP reaches only a +//! numeric loopback address, never the name `localhost`. The DNS-pinned fetch +//! policy then follows the selected transport, never the URL's scheme. + +use registry_platform_httputil::{ + loopback::loopback_address, + select::{select_credential_destination, SelectedDestination, TransportClass}, + FetchUrlPolicy, +}; +use url::{Host, Url}; + +/// `url` selected as a credential-bearing destination the Coordinator admits: +/// https, or plain HTTP to a numeric loopback address. +pub(crate) fn select_endpoint(url: &Url) -> Option { + let selected = select_credential_destination(url, None, &[]).ok()?; + (selected.transport() == TransportClass::VerifiedTls || numeric_loopback(url)) + .then_some(selected) +} + +/// Whether `url`'s host is a loopback address literal, mapped forms included. +pub(crate) fn numeric_loopback(url: &Url) -> bool { + match url.host() { + Some(Host::Ipv4(ip)) => loopback_address(ip.into()), + Some(Host::Ipv6(ip)) => loopback_address(ip.into()), + _ => false, + } +} + +/// The DNS-pinned policy a request to `selected` validates against. The +/// destinations are reviewed deployment bindings, so an institutional https +/// peer may be private; cloud metadata stays denied, and plain HTTP stays on +/// loopback. +pub(crate) fn fetch_policy(selected: &SelectedDestination) -> FetchUrlPolicy { + match selected.transport() { + TransportClass::VerifiedTls => FetchUrlPolicy { + allowed_schemes: vec!["https".into()], + allow_localhost: true, + allow_http_private_network: false, + allow_http_non_loopback: false, + deny_private_ranges: false, + deny_cloud_metadata: true, + }, + // `select_endpoint` never selects private plain text; both plain-text + // classes get the loopback-only policy. + TransportClass::LoopbackPlaintext | TransportClass::PrivateNetworkPlaintext => { + FetchUrlPolicy::https_or_loopback() + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn endpoints_are_https_or_numeric_loopback_http() { + for admitted in [ + "https://directory.example.test/", + "https://10.0.0.8/", + "https://localhost/", + "HTTPS://DIRECTORY.EXAMPLE.TEST/", + // Link-local https is selected; the request-time policy refuses it. + "https://169.254.1.1/", + "http://127.0.0.1:8080/", + "http://[::1]:8080/", + "http://[::ffff:127.0.0.1]:8080/", + ] { + assert!( + select_endpoint(&admitted.parse().unwrap()).is_some(), + "{admitted}" + ); + } + for refused in [ + "http://localhost:8080/", + "http://LOCALHOST:8080/", + "http://x.localhost/", + "http://localhost./", + "http://10.0.0.1/", + "http://directory.example.test/", + "https://user@directory.example.test/", + "ftp://directory.example.test/", + ] { + assert!( + select_endpoint(&refused.parse().unwrap()).is_none(), + "{refused}" + ); + } + } + + #[test] + fn the_policy_follows_the_selected_transport() { + let https = select_endpoint(&"https://10.0.0.8/".parse().unwrap()).unwrap(); + assert_eq!( + fetch_policy(&https), + FetchUrlPolicy { + allowed_schemes: vec!["https".into()], + allow_localhost: true, + allow_http_private_network: false, + allow_http_non_loopback: false, + deny_private_ranges: false, + deny_cloud_metadata: true, + } + ); + let loopback = select_endpoint(&"http://127.0.0.1:8080/".parse().unwrap()).unwrap(); + assert_eq!(fetch_policy(&loopback), FetchUrlPolicy::https_or_loopback()); + } +} diff --git a/crates/registry-coordinator/src/runtime.rs b/crates/registry-coordinator/src/runtime.rs index b0dff6dff4..d633c8616f 100644 --- a/crates/registry-coordinator/src/runtime.rs +++ b/crates/registry-coordinator/src/runtime.rs @@ -14,7 +14,7 @@ use registry_platform_httputil::{ use serde::{Deserialize, Deserializer, Serialize}; use serde_json::json; use std::{collections::BTreeMap, path::Path}; -use url::{Host, Url}; +use url::Url; use zeroize::Zeroizing; pub const API_VERSION: &str = "id.registrystack.org/formats/coordinator/runtime/v1alpha1"; @@ -1624,17 +1624,8 @@ fn config_error(field: &str, action: &str) -> CoordinatorError { .at("runtime.yaml", pointer(field)) .suggest(action) } -fn is_loopback(url: &Url) -> bool { - match url.host() { - 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, - } -} - fn check_endpoint(url: &Url) -> Result<()> { - let loopback = is_loopback(url); - if !(url.scheme() == "https" || (loopback && url.scheme() == "http")) + if crate::outbound::select_endpoint(url).is_none() || !url.username().is_empty() || url.password().is_some() || url.query().is_some() @@ -1780,7 +1771,7 @@ fn request_link<'de, D: Deserializer<'de>>(d: D) -> std::result::Result Date: Wed, 2 Dec 2026 00:40:17 +0000 Subject: [PATCH 155/183] ci: pin the provisioning journey arms and every roster call as an assignment The journey check refuses a case arm that would override a serving journey, and every workflow roster call must assign its answer to a variable, whatever test construct or script spelling it sits in. The provisioning step's comment states that the Evidence stores only provision. Signed-off-by: Jeremi Joslin --- .github/scripts/test_ci_changes.py | 35 +++++++++++++++++++++++------- .github/workflows/ci.yml | 5 +++-- 2 files changed, 30 insertions(+), 10 deletions(-) diff --git a/.github/scripts/test_ci_changes.py b/.github/scripts/test_ci_changes.py index fe8304327c..b5ac222fa9 100644 --- a/.github/scripts/test_ci_changes.py +++ b/.github/scripts/test_ci_changes.py @@ -4903,20 +4903,39 @@ def test_contracts_journeys_lane_runs_each_product_provisioning_journey( command, ) self.assertIn('grep -Eq "${journey}" "${log}"', command) + # The case holds exactly one arm per provision-only journey and the + # shared default, so no arm can override a serving journey's check. + case = re.search(r'case "\$\{package\}" in (.*?) esac', command) + self.assertIsNotNone(case) + arms = re.findall(r"(?:^|;;)\s*([^\s;)]+)\) journey=", case.group(1)) + provision_only = { + package + for package, (_, tests) in journeys.items() + if not any(serve.fullmatch(test) for test in tests) + } + self.assertEqual(sorted(provision_only | {"*"}), sorted(arms)) - def test_no_workflow_reads_a_roster_answer_inside_a_conditional(self) -> None: - # Inside [[ ]], set -e does not stop a failed command substitution, so - # a roster error would read as "not in release". Assign the answer to - # a variable first, so the failure stops the step. - inline = re.compile( - r'\[\[[^\]]*?"\$\(python3 release/scripts/release_roster\.py', re.S + def test_every_workflow_roster_call_is_a_plain_assignment(self) -> None: + # Inside [[ ]], [ ] or test, set -e does not stop a failed command + # substitution, so a roster error would read as "not in release". + # Every roster call assigns its answer to a variable first, so the + # failure stops the step. + assignment = re.compile( + r'^\s*[A-Za-z_][A-Za-z0-9_]*="\$\((?:python3 )?\S*release_roster\.py [^()]*\)"\s*$' ) + checked = 0 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", []): - with self.subTest(workflow=workflow.name, job=job_name, step=step.get("name")): - self.assertIsNone(inline.search(step.get("run", ""))) + logical = re.sub(r"\\\n\s*", " ", step.get("run", "")) + for line in logical.splitlines(): + if not re.search(r"(? Date: Wed, 2 Dec 2026 00:41:02 +0000 Subject: [PATCH 156/183] fix(platform): refuse a CA bundle that is not text at provision Reading database.caBundleRef as a public document dropped the UTF-8 check the Coordinator's provision made, so a binary bundle printed a plan and failed later at the TLS connection. DatabaseMember::CaBundle now refuses bytes that are not UTF-8, and the Coordinator and caseworkctl read the bundle through it, so every ctl provision tool applies one rule. Refs #2882. Signed-off-by: Jeremi Joslin --- crates/registry-caseworkctl/src/provision.rs | 4 +-- crates/registry-coordinator/src/provision.rs | 4 +-- .../tests/provision_cli.rs | 20 ++++++++++++++ crates/registry-platform-config/src/blocks.rs | 16 ++++++++--- .../src/blocks_tests.rs | 27 +++++++++++++++++++ products/platform/CHANGELOG.md | 3 +++ 6 files changed, 67 insertions(+), 7 deletions(-) diff --git a/crates/registry-caseworkctl/src/provision.rs b/crates/registry-caseworkctl/src/provision.rs index bf8b0e0f88..24618415c0 100644 --- a/crates/registry-caseworkctl/src/provision.rs +++ b/crates/registry-caseworkctl/src/provision.rs @@ -78,8 +78,8 @@ fn load(path: &Path, declared: DeclaredPosture) -> Result Result Some( - resolver - .resolve_public_document(reference) + registry_platform_config::DatabaseMember::CaBundle + .read(&resolver, reference) .map_err(|_| { vec![*refusal( "/database/caBundleRef", diff --git a/crates/registry-messagingctl/tests/provision_cli.rs b/crates/registry-messagingctl/tests/provision_cli.rs index 31e6a1aeab..eaa1865ceb 100644 --- a/crates/registry-messagingctl/tests/provision_cli.rs +++ b/crates/registry-messagingctl/tests/provision_cli.rs @@ -359,6 +359,26 @@ fn a_missing_runtime_url_secret_is_refused_at_its_member() { assert_eq!(diagnostic["path"], "/database/runtimeUrlRef", "{report:#}"); } +#[test] +fn a_ca_bundle_that_is_not_text_is_refused_at_its_member() { + let directory = scratch(); + let runtime = write_runtime(directory.path()); + let ca = directory.path().join("secrets").join("database-ca.pem"); + std::fs::write(&ca, [0xff, 0xfe, 0xfd]).unwrap(); + let text = std::fs::read_to_string(&runtime).unwrap(); + let stated = text.replace( + " migrationUrlRef: secret:file/migration-database-url\n", + " migrationUrlRef: secret:file/migration-database-url\n caBundleRef: secret:file/database-ca.pem\n", + ); + assert_eq!(stated.matches("caBundleRef").count(), 1, "{stated}"); + std::fs::write(&runtime, stated).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/caBundleRef", "{report:#}"); +} + #[test] fn a_migration_url_secret_that_is_not_text_is_refused_at_its_member() { let directory = scratch(); diff --git a/crates/registry-platform-config/src/blocks.rs b/crates/registry-platform-config/src/blocks.rs index 5b1081935b..56798bb65f 100644 --- a/crates/registry-platform-config/src/blocks.rs +++ b/crates/registry-platform-config/src/blocks.rs @@ -456,14 +456,17 @@ impl DatabaseMember { } } - /// Read the member's reference with the rule the member takes. + /// Read the member's reference with the rule the member takes. A CA + /// bundle is a public document holding PEM text, so bytes that are not + /// UTF-8 are [`SecretError::InvalidValue`] here rather than a failure at + /// the TLS connection. pub fn read( self, resolver: &SecretResolver, reference: &str, ) -> Result { match self { - Self::CaBundle => resolver.resolve_public_document(reference), + Self::CaBundle => pem_text(resolver.resolve_public_document(reference)?), Self::RuntimeUrl | Self::MigrationUrl => resolver.resolve(reference), } } @@ -475,12 +478,19 @@ impl DatabaseMember { reference: &SecretReference, ) -> Result { match self { - Self::CaBundle => resolver.resolve_public_document_reference(reference), + Self::CaBundle => pem_text(resolver.resolve_public_document_reference(reference)?), Self::RuntimeUrl | Self::MigrationUrl => resolver.resolve_reference(reference), } } } +fn pem_text(document: ProtectedSecret) -> Result { + if std::str::from_utf8(document.expose_secret()).is_err() { + return Err(SecretError::InvalidValue); + } + Ok(document) +} + impl fmt::Display for DatabaseMember { fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter.write_str(self.key()) diff --git a/crates/registry-platform-config/src/blocks_tests.rs b/crates/registry-platform-config/src/blocks_tests.rs index bc28f71074..de39da29c5 100644 --- a/crates/registry-platform-config/src/blocks_tests.rs +++ b/crates/registry-platform-config/src/blocks_tests.rs @@ -116,6 +116,33 @@ fn a_database_ca_bundle_reads_as_a_public_document_and_a_url_as_a_secret() { } } +#[cfg(unix)] +#[test] +fn a_database_ca_bundle_that_is_not_text_is_an_invalid_value() { + let root = tempfile::tempdir().expect("tempdir"); + let canonical = std::fs::canonicalize(root.path()).expect("canonical root"); + std::fs::write(canonical.join("binary"), [0xff, 0xfe, 0xfd]).expect("write file"); + let resolver = SecretProvidersConfig { + file: Some(FileSecretProviderConfig::new(canonical)), + environment: None, + } + .resolver(None) + .expect("production resolver"); + let reference = SecretReference::parse("secret:file/binary").unwrap(); + assert_eq!( + DatabaseMember::CaBundle + .read(&resolver, "secret:file/binary") + .unwrap_err(), + SecretError::InvalidValue + ); + assert_eq!( + DatabaseMember::CaBundle + .read_reference(&resolver, &reference) + .unwrap_err(), + SecretError::InvalidValue + ); +} + #[cfg(unix)] #[test] fn secret_providers_resolver_relaxes_secret_file_permissions_only_with_a_development_witness() { diff --git a/products/platform/CHANGELOG.md b/products/platform/CHANGELOG.md index 2bde922007..fa3dc6c69f 100644 --- a/products/platform/CHANGELOG.md +++ b/products/platform/CHANGELOG.md @@ -26,6 +26,9 @@ owner-only. Migration: if `caBundleRef` named a combined certificate and key file, split the key into its own secret file and point `caBundleRef` at the certificates alone. +- Every `*ctl provision` tool now refuses a binary CA bundle at + `/database/caBundleRef` when it reads the runtime file, instead of failing + later at the TLS connection: the bundle must be PEM text. - The shared runtime blocks document publishes `StrictSecretProvidersConfig` and `StrictFileSecretProviderConfig`, the secret providers without `mountPolicy`. The Evidence OID4VCI and OID4VP runtime schemas embed them, From cf4b9e064b11e702697598d76a2433ce76c999db Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Wed, 2 Dec 2026 00:50:36 +0000 Subject: [PATCH 157/183] chore(client): regenerate the Coordinator client for service.invoke-function/v1 Signed-off-by: Jeremi Joslin --- clients/typescript/generated/coordinator.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/clients/typescript/generated/coordinator.ts b/clients/typescript/generated/coordinator.ts index 56e5c25f4e..09874f473c 100644 --- a/clients/typescript/generated/coordinator.ts +++ b/clients/typescript/generated/coordinator.ts @@ -1,5 +1,5 @@ // Generated for Stack version 0.50.0, client version 0.50.0. -// Source SHA-256 bfc1de8b64985751de37a6f66efbca724d2878101aa47b15cb40a4192e76ffc2 +// Source SHA-256 2e480154f09b6a6df9cba0be8e049690f37e69003b55000c30295540fc7eba28 // Unconstrained JSON /components/schemas/HookEnvelope/properties/data // Unconstrained JSON /components/schemas/RunStatus/properties/output // Unconstrained JSON /components/schemas/Start/properties/input @@ -20,7 +20,7 @@ export type Schema_HeldRun = ({ "advice": (string); "findingCode": (string); "re export type Schema_HeldRuns = (Array) export type Schema_Hold = ({ "restoreHold": (boolean) }) export type Schema_HookEnvelope = ({ "causation": ({ "hop": (number); "parent"?: (string); "root": (string) }); "data": JsonValue; "dataschema": (string); "id": (string); "source": (string); "subject": (({ "recordReference": (string); "recordRevision": (number) }) | ({ "proposalReference": (string); "proposalRevision": (number) })); "time": (string); "type": (string) }) -export type Schema_OperationIdentity = ({ "effect": ("read" | "mutation" | "evaluation") & (string); "id": ("breg.read-record/v1" | "messaging.submit-message/v1" | "scheduling.read-service/v1" | "scheduling.read-availability/v1" | "scheduling.create-appointment/v1" | "scheduling.read-appointment/v1" | "scheduling.create-hold/v1" | "scheduling.release-hold/v1" | "scheduling.confirm-hold/v1" | "scheduling.reschedule-appointment/v1" | "scheduling.cancel-appointment/v1" | "breg.invoke-action/v1" | "external.get/v1" | "evaluation.evaluate/v1" | "casework.submit-review-request/v1" | "casework.cancel-review-request/v1" | "scheduling.preview-availability/v1" | "external.command/v1" | "breg.read-in-force/v1" | "breg.read-proposal/v1" | "breg.start-proposal/v1" | "breg.submit-proposal/v1" | "breg.cancel-proposal/v1" | "breg.lookup-record/v1" | "breg.read-record/v2" | "payments.request-collection/v1" | "payments.read-collection/v1" | "payments.record-receipt/v1" | "payments.request-disbursement/v1" | "payments.read-disbursement/v1" | "payments.record-provider-confirmation/v1") & (string); "keyRequirement": ("none" | "required") & (string); "product": (string); "readReceipt": (boolean); "recovery": ("read-again" | "same-command-and-receipt" | "same-command" | "hold-after-dispatch") & (string); "requiresPreparation": (boolean); "version": (number) }) +export type Schema_OperationIdentity = ({ "effect": ("read" | "mutation" | "evaluation") & (string); "id": ("breg.read-record/v1" | "messaging.submit-message/v1" | "scheduling.read-service/v1" | "scheduling.read-availability/v1" | "scheduling.create-appointment/v1" | "scheduling.read-appointment/v1" | "scheduling.create-hold/v1" | "scheduling.release-hold/v1" | "scheduling.confirm-hold/v1" | "scheduling.reschedule-appointment/v1" | "scheduling.cancel-appointment/v1" | "breg.invoke-action/v1" | "external.get/v1" | "evaluation.evaluate/v1" | "casework.submit-review-request/v1" | "casework.cancel-review-request/v1" | "scheduling.preview-availability/v1" | "external.command/v1" | "breg.read-in-force/v1" | "breg.read-proposal/v1" | "breg.start-proposal/v1" | "breg.submit-proposal/v1" | "breg.cancel-proposal/v1" | "breg.lookup-record/v1" | "breg.read-record/v2" | "payments.request-collection/v1" | "payments.read-collection/v1" | "payments.record-receipt/v1" | "payments.request-disbursement/v1" | "payments.read-disbursement/v1" | "payments.record-provider-confirmation/v1" | "service.invoke-function/v1") & (string); "keyRequirement": ("none" | "required") & (string); "product": (string); "readReceipt": (boolean); "recovery": ("read-again" | "same-command-and-receipt" | "same-command" | "hold-after-dispatch") & (string); "requiresPreparation": (boolean); "version": (number) }) export type Schema_Problem = ({ "code": ("admission.held" | "admission.recovery-only" | "audit.response-unavailable" | "authentication.refused" | "binding.conflict" | "binding.live-conflict" | "check.not-waiting" | "definition.refused" | "deployment.activation-changed" | "deployment.refused" | "evaluation.uncertain" | "event.invalid" | "event.too-large" | "event.unauthenticated" | "execution.held" | "idempotency.key-invalid" | "idempotency.key-reused" | "input.invalid" | "mutation.uncertain" | "operation.not-authorized" | "receipt.expired" | "reconcile.raced" | "reconcile.refused" | "reconcile.unsupported" | "request.body-too-large" | "request.invalid" | "request.limit-out-of-range" | "request.method-not-allowed" | "request.not-found" | "request.reason-invalid" | "request.retention-invalid" | "request.unprocessable" | "request.unsupported-media-type" | "restore.hold-required" | "restore.lease-incompatible" | "restore.review-required" | "restore.unresolved" | "retry.refused" | "run.definition-incompatible" | "run.not-visible" | "run.payload-erased" | "runtime.failure" | "service.unavailable" | "workflow.not-served" | "workflow.revision-mismatch") & (string); "detail": (string); "pointer"?: (string); "status": (number); "title": (string); "traceId": (string); "type": ("https://id.registrystack.org/problems/registry-coordinator/admission/held" | "https://id.registrystack.org/problems/registry-coordinator/admission/recovery-only" | "https://id.registrystack.org/problems/registry-coordinator/audit/response-unavailable" | "https://id.registrystack.org/problems/registry-coordinator/authentication/refused" | "https://id.registrystack.org/problems/registry-coordinator/binding/conflict" | "https://id.registrystack.org/problems/registry-coordinator/binding/live-conflict" | "https://id.registrystack.org/problems/registry-coordinator/check/not-waiting" | "https://id.registrystack.org/problems/registry-coordinator/definition/refused" | "https://id.registrystack.org/problems/registry-coordinator/deployment/activation-changed" | "https://id.registrystack.org/problems/registry-coordinator/deployment/refused" | "https://id.registrystack.org/problems/registry-coordinator/evaluation/uncertain" | "https://id.registrystack.org/problems/registry-coordinator/event/invalid" | "https://id.registrystack.org/problems/registry-coordinator/event/too-large" | "https://id.registrystack.org/problems/registry-coordinator/event/unauthenticated" | "https://id.registrystack.org/problems/registry-coordinator/execution/held" | "https://id.registrystack.org/problems/registry-coordinator/idempotency/key-invalid" | "https://id.registrystack.org/problems/registry-coordinator/idempotency/key-reused" | "https://id.registrystack.org/problems/registry-coordinator/input/invalid" | "https://id.registrystack.org/problems/registry-coordinator/mutation/uncertain" | "https://id.registrystack.org/problems/registry-coordinator/operation/not-authorized" | "https://id.registrystack.org/problems/registry-coordinator/receipt/expired" | "https://id.registrystack.org/problems/registry-coordinator/reconcile/raced" | "https://id.registrystack.org/problems/registry-coordinator/reconcile/refused" | "https://id.registrystack.org/problems/registry-coordinator/reconcile/unsupported" | "https://id.registrystack.org/problems/registry-coordinator/request/body-too-large" | "https://id.registrystack.org/problems/registry-coordinator/request/invalid" | "https://id.registrystack.org/problems/registry-coordinator/request/limit-out-of-range" | "https://id.registrystack.org/problems/registry-coordinator/request/method-not-allowed" | "https://id.registrystack.org/problems/registry-coordinator/request/not-found" | "https://id.registrystack.org/problems/registry-coordinator/request/reason-invalid" | "https://id.registrystack.org/problems/registry-coordinator/request/retention-invalid" | "https://id.registrystack.org/problems/registry-coordinator/request/unprocessable" | "https://id.registrystack.org/problems/registry-coordinator/request/unsupported-media-type" | "https://id.registrystack.org/problems/registry-coordinator/restore/hold-required" | "https://id.registrystack.org/problems/registry-coordinator/restore/lease-incompatible" | "https://id.registrystack.org/problems/registry-coordinator/restore/review-required" | "https://id.registrystack.org/problems/registry-coordinator/restore/unresolved" | "https://id.registrystack.org/problems/registry-coordinator/retry/refused" | "https://id.registrystack.org/problems/registry-coordinator/run/definition-incompatible" | "https://id.registrystack.org/problems/registry-coordinator/run/not-visible" | "https://id.registrystack.org/problems/registry-coordinator/run/payload-erased" | "https://id.registrystack.org/problems/registry-coordinator/runtime/failure" | "https://id.registrystack.org/problems/registry-coordinator/service/unavailable" | "https://id.registrystack.org/problems/registry-coordinator/workflow/not-served" | "https://id.registrystack.org/problems/registry-coordinator/workflow/revision-mismatch") & (string) }) export type Schema_ProposalWaitsByTurn = ({ "nobody": (number); "official": (number); "party": (number); "unobserved": (number) }) export type Schema_Reason = ({ "reason": (string) }) @@ -73,7 +73,7 @@ const rules: Record = Object.fromEntries([ ["/components/schemas/HookEnvelope", JSON.parse("{\"additionalProperties\":false,\"properties\":{\"causation\":{\"$ref\":\"/components/schemas/HookEnvelope/$defs/Causation\"},\"data\":true,\"dataschema\":{\"type\":\"string\"},\"id\":{\"type\":\"string\"},\"source\":{\"type\":\"string\"},\"subject\":{\"$ref\":\"/components/schemas/HookEnvelope/$defs/EventSubject\"},\"time\":{\"type\":\"string\"},\"type\":{\"type\":\"string\"}},\"required\":[\"id\",\"type\",\"source\",\"time\",\"subject\",\"dataschema\",\"data\",\"causation\"],\"type\":\"object\"}")], ["/components/schemas/HookEnvelope/$defs/Causation", JSON.parse("{\"additionalProperties\":false,\"properties\":{\"hop\":{\"maximum\":8,\"minimum\":0,\"type\":\"integer\"},\"parent\":{\"type\":\"string\"},\"root\":{\"type\":\"string\"}},\"required\":[\"root\",\"hop\"],\"type\":\"object\"}")], ["/components/schemas/HookEnvelope/$defs/EventSubject", JSON.parse("{\"anyOf\":[{\"additionalProperties\":false,\"properties\":{\"recordReference\":{\"type\":\"string\"},\"recordRevision\":{\"maximum\":9007199254740991,\"minimum\":1,\"type\":\"integer\"}},\"required\":[\"recordReference\",\"recordRevision\"],\"type\":\"object\"},{\"additionalProperties\":false,\"properties\":{\"proposalReference\":{\"type\":\"string\"},\"proposalRevision\":{\"maximum\":9007199254740991,\"minimum\":1,\"type\":\"integer\"}},\"required\":[\"proposalReference\",\"proposalRevision\"],\"type\":\"object\"}]}")], - ["/components/schemas/OperationIdentity", JSON.parse("{\"additionalProperties\":false,\"properties\":{\"effect\":{\"enum\":[\"read\",\"mutation\",\"evaluation\"],\"type\":\"string\"},\"id\":{\"enum\":[\"breg.read-record/v1\",\"messaging.submit-message/v1\",\"scheduling.read-service/v1\",\"scheduling.read-availability/v1\",\"scheduling.create-appointment/v1\",\"scheduling.read-appointment/v1\",\"scheduling.create-hold/v1\",\"scheduling.release-hold/v1\",\"scheduling.confirm-hold/v1\",\"scheduling.reschedule-appointment/v1\",\"scheduling.cancel-appointment/v1\",\"breg.invoke-action/v1\",\"external.get/v1\",\"evaluation.evaluate/v1\",\"casework.submit-review-request/v1\",\"casework.cancel-review-request/v1\",\"scheduling.preview-availability/v1\",\"external.command/v1\",\"breg.read-in-force/v1\",\"breg.read-proposal/v1\",\"breg.start-proposal/v1\",\"breg.submit-proposal/v1\",\"breg.cancel-proposal/v1\",\"breg.lookup-record/v1\",\"breg.read-record/v2\",\"payments.request-collection/v1\",\"payments.read-collection/v1\",\"payments.record-receipt/v1\",\"payments.request-disbursement/v1\",\"payments.read-disbursement/v1\",\"payments.record-provider-confirmation/v1\"],\"type\":\"string\"},\"keyRequirement\":{\"enum\":[\"none\",\"required\"],\"type\":\"string\"},\"product\":{\"type\":\"string\"},\"readReceipt\":{\"type\":\"boolean\"},\"recovery\":{\"enum\":[\"read-again\",\"same-command-and-receipt\",\"same-command\",\"hold-after-dispatch\"],\"type\":\"string\"},\"requiresPreparation\":{\"type\":\"boolean\"},\"version\":{\"minimum\":1,\"type\":\"integer\"}},\"required\":[\"id\",\"version\",\"product\",\"effect\",\"keyRequirement\",\"requiresPreparation\",\"recovery\",\"readReceipt\"],\"type\":\"object\"}")], + ["/components/schemas/OperationIdentity", JSON.parse("{\"additionalProperties\":false,\"properties\":{\"effect\":{\"enum\":[\"read\",\"mutation\",\"evaluation\"],\"type\":\"string\"},\"id\":{\"enum\":[\"breg.read-record/v1\",\"messaging.submit-message/v1\",\"scheduling.read-service/v1\",\"scheduling.read-availability/v1\",\"scheduling.create-appointment/v1\",\"scheduling.read-appointment/v1\",\"scheduling.create-hold/v1\",\"scheduling.release-hold/v1\",\"scheduling.confirm-hold/v1\",\"scheduling.reschedule-appointment/v1\",\"scheduling.cancel-appointment/v1\",\"breg.invoke-action/v1\",\"external.get/v1\",\"evaluation.evaluate/v1\",\"casework.submit-review-request/v1\",\"casework.cancel-review-request/v1\",\"scheduling.preview-availability/v1\",\"external.command/v1\",\"breg.read-in-force/v1\",\"breg.read-proposal/v1\",\"breg.start-proposal/v1\",\"breg.submit-proposal/v1\",\"breg.cancel-proposal/v1\",\"breg.lookup-record/v1\",\"breg.read-record/v2\",\"payments.request-collection/v1\",\"payments.read-collection/v1\",\"payments.record-receipt/v1\",\"payments.request-disbursement/v1\",\"payments.read-disbursement/v1\",\"payments.record-provider-confirmation/v1\",\"service.invoke-function/v1\"],\"type\":\"string\"},\"keyRequirement\":{\"enum\":[\"none\",\"required\"],\"type\":\"string\"},\"product\":{\"type\":\"string\"},\"readReceipt\":{\"type\":\"boolean\"},\"recovery\":{\"enum\":[\"read-again\",\"same-command-and-receipt\",\"same-command\",\"hold-after-dispatch\"],\"type\":\"string\"},\"requiresPreparation\":{\"type\":\"boolean\"},\"version\":{\"minimum\":1,\"type\":\"integer\"}},\"required\":[\"id\",\"version\",\"product\",\"effect\",\"keyRequirement\",\"requiresPreparation\",\"recovery\",\"readReceipt\"],\"type\":\"object\"}")], ["/components/schemas/Problem", JSON.parse("{\"additionalProperties\":false,\"properties\":{\"code\":{\"enum\":[\"admission.held\",\"admission.recovery-only\",\"audit.response-unavailable\",\"authentication.refused\",\"binding.conflict\",\"binding.live-conflict\",\"check.not-waiting\",\"definition.refused\",\"deployment.activation-changed\",\"deployment.refused\",\"evaluation.uncertain\",\"event.invalid\",\"event.too-large\",\"event.unauthenticated\",\"execution.held\",\"idempotency.key-invalid\",\"idempotency.key-reused\",\"input.invalid\",\"mutation.uncertain\",\"operation.not-authorized\",\"receipt.expired\",\"reconcile.raced\",\"reconcile.refused\",\"reconcile.unsupported\",\"request.body-too-large\",\"request.invalid\",\"request.limit-out-of-range\",\"request.method-not-allowed\",\"request.not-found\",\"request.reason-invalid\",\"request.retention-invalid\",\"request.unprocessable\",\"request.unsupported-media-type\",\"restore.hold-required\",\"restore.lease-incompatible\",\"restore.review-required\",\"restore.unresolved\",\"retry.refused\",\"run.definition-incompatible\",\"run.not-visible\",\"run.payload-erased\",\"runtime.failure\",\"service.unavailable\",\"workflow.not-served\",\"workflow.revision-mismatch\"],\"type\":\"string\"},\"detail\":{\"type\":\"string\"},\"pointer\":{\"type\":\"string\"},\"status\":{\"type\":\"integer\"},\"title\":{\"type\":\"string\"},\"traceId\":{\"type\":\"string\"},\"type\":{\"enum\":[\"https://id.registrystack.org/problems/registry-coordinator/admission/held\",\"https://id.registrystack.org/problems/registry-coordinator/admission/recovery-only\",\"https://id.registrystack.org/problems/registry-coordinator/audit/response-unavailable\",\"https://id.registrystack.org/problems/registry-coordinator/authentication/refused\",\"https://id.registrystack.org/problems/registry-coordinator/binding/conflict\",\"https://id.registrystack.org/problems/registry-coordinator/binding/live-conflict\",\"https://id.registrystack.org/problems/registry-coordinator/check/not-waiting\",\"https://id.registrystack.org/problems/registry-coordinator/definition/refused\",\"https://id.registrystack.org/problems/registry-coordinator/deployment/activation-changed\",\"https://id.registrystack.org/problems/registry-coordinator/deployment/refused\",\"https://id.registrystack.org/problems/registry-coordinator/evaluation/uncertain\",\"https://id.registrystack.org/problems/registry-coordinator/event/invalid\",\"https://id.registrystack.org/problems/registry-coordinator/event/too-large\",\"https://id.registrystack.org/problems/registry-coordinator/event/unauthenticated\",\"https://id.registrystack.org/problems/registry-coordinator/execution/held\",\"https://id.registrystack.org/problems/registry-coordinator/idempotency/key-invalid\",\"https://id.registrystack.org/problems/registry-coordinator/idempotency/key-reused\",\"https://id.registrystack.org/problems/registry-coordinator/input/invalid\",\"https://id.registrystack.org/problems/registry-coordinator/mutation/uncertain\",\"https://id.registrystack.org/problems/registry-coordinator/operation/not-authorized\",\"https://id.registrystack.org/problems/registry-coordinator/receipt/expired\",\"https://id.registrystack.org/problems/registry-coordinator/reconcile/raced\",\"https://id.registrystack.org/problems/registry-coordinator/reconcile/refused\",\"https://id.registrystack.org/problems/registry-coordinator/reconcile/unsupported\",\"https://id.registrystack.org/problems/registry-coordinator/request/body-too-large\",\"https://id.registrystack.org/problems/registry-coordinator/request/invalid\",\"https://id.registrystack.org/problems/registry-coordinator/request/limit-out-of-range\",\"https://id.registrystack.org/problems/registry-coordinator/request/method-not-allowed\",\"https://id.registrystack.org/problems/registry-coordinator/request/not-found\",\"https://id.registrystack.org/problems/registry-coordinator/request/reason-invalid\",\"https://id.registrystack.org/problems/registry-coordinator/request/retention-invalid\",\"https://id.registrystack.org/problems/registry-coordinator/request/unprocessable\",\"https://id.registrystack.org/problems/registry-coordinator/request/unsupported-media-type\",\"https://id.registrystack.org/problems/registry-coordinator/restore/hold-required\",\"https://id.registrystack.org/problems/registry-coordinator/restore/lease-incompatible\",\"https://id.registrystack.org/problems/registry-coordinator/restore/review-required\",\"https://id.registrystack.org/problems/registry-coordinator/restore/unresolved\",\"https://id.registrystack.org/problems/registry-coordinator/retry/refused\",\"https://id.registrystack.org/problems/registry-coordinator/run/definition-incompatible\",\"https://id.registrystack.org/problems/registry-coordinator/run/not-visible\",\"https://id.registrystack.org/problems/registry-coordinator/run/payload-erased\",\"https://id.registrystack.org/problems/registry-coordinator/runtime/failure\",\"https://id.registrystack.org/problems/registry-coordinator/service/unavailable\",\"https://id.registrystack.org/problems/registry-coordinator/workflow/not-served\",\"https://id.registrystack.org/problems/registry-coordinator/workflow/revision-mismatch\"],\"type\":\"string\"}},\"required\":[\"type\",\"title\",\"status\",\"detail\",\"code\",\"traceId\"],\"type\":\"object\"}")], ["/components/schemas/ProposalWaitsByTurn", JSON.parse("{\"additionalProperties\":false,\"properties\":{\"nobody\":{\"minimum\":0,\"type\":\"integer\"},\"official\":{\"minimum\":0,\"type\":\"integer\"},\"party\":{\"minimum\":0,\"type\":\"integer\"},\"unobserved\":{\"minimum\":0,\"type\":\"integer\"}},\"required\":[\"party\",\"official\",\"nobody\",\"unobserved\"],\"type\":\"object\"}")], ["/components/schemas/Reason", JSON.parse("{\"additionalProperties\":false,\"properties\":{\"reason\":{\"maxLength\":256,\"minLength\":1,\"type\":\"string\"}},\"required\":[\"reason\"],\"type\":\"object\"}")], From cb50fbeafda80bae9e4ac0ea366d32a3291c3677 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Wed, 2 Dec 2026 00:49:03 +0000 Subject: [PATCH 158/183] fix(platform): build every explicit-setting notice in one place, as a sentence Ten commands printed the notice with their own format string, and a summary that starts lowercase read '... at . admits ...'. One function in registry-platform-config now builds the line and capitalises the summary's first letter; FoundExplicitSetting and ExplicitSettingLine expose it as notice(). JSON summaries stay as authored. The docs examples show the line the tools now print. Refs #2882. Signed-off-by: Jeremi Joslin --- crates/registry-breg-review/src/check.rs | 8 +---- crates/registry-bregctl/src/check.rs | 10 +++--- crates/registry-coordinator/src/cli.rs | 7 +--- .../tests/caller_contract.rs | 2 +- crates/registry-evidence-oid4vci/src/main.rs | 8 +---- crates/registry-evidence-oid4vp/src/main.rs | 8 +---- .../tests/check_command.rs | 2 +- crates/registry-evidence/src/main.rs | 7 +--- crates/registry-evidencectl/src/check.rs | 8 +---- crates/registry-messagingctl/src/lib.rs | 8 +---- crates/registry-platform-config/src/lib.rs | 11 ++++--- .../registry-platform-config/src/posture.rs | 32 ++++++++++++++++--- .../src/posture_tests.rs | 19 +++++++++++ crates/registry-render/src/check.rs | 10 +++--- crates/registry-schedulingctl/src/lib.rs | 3 +- .../docs/configure/enable-sd-jwt-vc.mdx | 2 +- .../build-and-deploy-evidence-project.mdx | 4 +-- .../tutorials/connect-a-sqlite-extract.mdx | 4 +-- .../connect-an-institution-source.mdx | 2 +- .../tutorials/first-evidence-assertion.mdx | 2 +- 20 files changed, 83 insertions(+), 74 deletions(-) diff --git a/crates/registry-breg-review/src/check.rs b/crates/registry-breg-review/src/check.rs index 25d27363bb..ec5f2fa56f 100644 --- a/crates/registry-breg-review/src/check.rs +++ b/crates/registry-breg-review/src/check.rs @@ -154,13 +154,7 @@ fn write_explicit_settings( settings: &[registry_platform_config::FoundExplicitSetting], ) -> std::io::Result<()> { for found in settings { - writeln!( - output, - "Explicit production setting {} at {}. {}.", - found.setting.code, - found.pointer.as_deref().unwrap_or_default(), - found.setting.summary - )?; + writeln!(output, "{}", found.notice())?; } Ok(()) } diff --git a/crates/registry-bregctl/src/check.rs b/crates/registry-bregctl/src/check.rs index b7802f0f00..4de44caf4d 100644 --- a/crates/registry-bregctl/src/check.rs +++ b/crates/registry-bregctl/src/check.rs @@ -1302,10 +1302,12 @@ fn explicit_setting_notes(settings: Option<&[registry_cli_report::ExplicitSettin location.push(' '); } format!( - "Explicit production setting {} at {location}{}. {}.\n", - setting.code, - setting.pointer.as_deref().unwrap_or(""), - setting.summary.trim_end_matches('.') + "{}\n", + registry_platform_config::explicit_setting_notice( + &setting.code, + &format!("{location}{}", setting.pointer.as_deref().unwrap_or("")), + setting.summary.trim_end_matches('.'), + ) ) }) .collect() diff --git a/crates/registry-coordinator/src/cli.rs b/crates/registry-coordinator/src/cli.rs index accdfc4ccb..865c1d55a0 100644 --- a/crates/registry-coordinator/src/cli.rs +++ b/crates/registry-coordinator/src/cli.rs @@ -1877,12 +1877,7 @@ fn with_posture(mut value: Value, declared: DeclaredPosture) -> Value { fn print_explicit_settings(settings: &[registry_cli_report::ExplicitSettingLine]) { for setting in settings { - println!( - "Explicit production setting {} at {}. {}.", - setting.code, - setting.pointer.as_deref().unwrap_or_default(), - setting.summary - ); + println!("{}", setting.notice()); } } diff --git a/crates/registry-coordinator/tests/caller_contract.rs b/crates/registry-coordinator/tests/caller_contract.rs index ed8fe5e54f..ab1e632305 100644 --- a/crates/registry-coordinator/tests/caller_contract.rs +++ b/crates/registry-coordinator/tests/caller_contract.rs @@ -651,7 +651,7 @@ fn human_check_prints_the_explicit_setting_with_its_pointer() { assert!(output.status.success()); let stdout = String::from_utf8(output.stdout).unwrap(); assert!(stdout.lines().any(|line| line == format!( - "Explicit production setting platform.posture.jwt-access-token at {ISSUERS}/main/accessTokenType. admits access tokens typed JWT. ID tokens stay refused." + "Explicit production setting platform.posture.jwt-access-token at {ISSUERS}/main/accessTokenType. Admits access tokens typed JWT. ID tokens stay refused." )), "{stdout}"); } diff --git a/crates/registry-evidence-oid4vci/src/main.rs b/crates/registry-evidence-oid4vci/src/main.rs index 5601e618da..23af19a3da 100644 --- a/crates/registry-evidence-oid4vci/src/main.rs +++ b/crates/registry-evidence-oid4vci/src/main.rs @@ -329,13 +329,7 @@ fn check( OutputFormat::Human => { let mut output = std::io::stderr().lock(); for found in &explicit_settings { - writeln!( - output, - "Explicit production setting {} at {}. {}.", - found.code, - found.pointer.as_deref().unwrap_or_default(), - found.summary - )?; + writeln!(output, "{}", found.notice())?; } write!(output, "{}", report.render_human())?; } diff --git a/crates/registry-evidence-oid4vp/src/main.rs b/crates/registry-evidence-oid4vp/src/main.rs index 0f576013ce..8bae4229bf 100644 --- a/crates/registry-evidence-oid4vp/src/main.rs +++ b/crates/registry-evidence-oid4vp/src/main.rs @@ -293,13 +293,7 @@ fn check( OutputFormat::Human => { let mut output = std::io::stderr().lock(); for found in &explicit_settings { - writeln!( - output, - "Explicit production setting {} at {}. {}.", - found.code, - found.pointer.as_deref().unwrap_or_default(), - found.summary - )?; + writeln!(output, "{}", found.notice())?; } write!(output, "{}", report.render_human())?; } diff --git a/crates/registry-evidence-oid4vp/tests/check_command.rs b/crates/registry-evidence-oid4vp/tests/check_command.rs index b956f5960c..33dbbeadaf 100644 --- a/crates/registry-evidence-oid4vp/tests/check_command.rs +++ b/crates/registry-evidence-oid4vp/tests/check_command.rs @@ -85,7 +85,7 @@ fn the_committed_example_passes_in_both_formats() { assert!(output.stdout.is_empty()); assert_eq!( String::from_utf8(output.stderr).unwrap(), - "Explicit production setting platform.posture.unrestricted-clients at /applicantTokens/issuers/primary/allowedClients. admits a token from every client this issuer signs for.\n0 errors, 0 warnings in 1 file\n" + "Explicit production setting platform.posture.unrestricted-clients at /applicantTokens/issuers/primary/allowedClients. Admits a token from every client this issuer signs for.\n0 errors, 0 warnings in 1 file\n" ); } diff --git a/crates/registry-evidence/src/main.rs b/crates/registry-evidence/src/main.rs index b990c00060..1c8c0ad079 100644 --- a/crates/registry-evidence/src/main.rs +++ b/crates/registry-evidence/src/main.rs @@ -1133,12 +1133,7 @@ async fn run_check(request: CheckRequest) -> ExitCode { } if !check.is_unavailable() { for found in check.explicit_settings() { - eprintln!( - "Explicit production setting {} at {}. {}.", - found.code, - found.pointer.as_deref().unwrap_or_default(), - found.summary - ); + eprintln!("{}", found.notice()); } } eprint!("{}", report.render_human()); diff --git a/crates/registry-evidencectl/src/check.rs b/crates/registry-evidencectl/src/check.rs index 0b86b42eef..3343f72b6e 100644 --- a/crates/registry-evidencectl/src/check.rs +++ b/crates/registry-evidencectl/src/check.rs @@ -562,13 +562,7 @@ pub(crate) fn render_human_with_settings( } } for found in explicit_settings { - writeln!( - out, - "Explicit production setting {} at {}. {}.", - found.code, - found.pointer.as_deref().unwrap_or_default(), - found.summary - )?; + writeln!(out, "{}", found.notice())?; } write!(out, "{}", diagnostics.render_human()) } diff --git a/crates/registry-messagingctl/src/lib.rs b/crates/registry-messagingctl/src/lib.rs index 64bcd67ab0..6d243afba5 100644 --- a/crates/registry-messagingctl/src/lib.rs +++ b/crates/registry-messagingctl/src/lib.rs @@ -2476,13 +2476,7 @@ fn render_check( )?; } for setting in settings { - writeln!( - stdout, - "Explicit production setting {} at {}. {}.", - setting.code, - setting.pointer.as_deref().unwrap_or_default(), - setting.summary - )?; + writeln!(stdout, "{}", setting.notice())?; } Ok(()) } diff --git a/crates/registry-platform-config/src/lib.rs b/crates/registry-platform-config/src/lib.rs index dd91290fd8..a2704968ff 100644 --- a/crates/registry-platform-config/src/lib.rs +++ b/crates/registry-platform-config/src/lib.rs @@ -83,11 +83,12 @@ pub use package::{ }; pub use posture::{ collect_development_settings, collect_posture_settings, declared, declared_from, - declared_from_with_production_alias, declared_with_production_alias, has_denied_warnings, - CollectedSettings, DeclaredPosture, DevelopmentClass, DevelopmentOnlyRefused, - DevelopmentSetting, DevelopmentWitness, ExplicitClass, ExplicitProductionSetting, - ExplicitSettingLine, FoundExplicitSetting, FoundSetting, Gated, Posture, PostureError, - PostureReport, PostureSource, SettingOrigin, Stated, DEVELOPMENT, POSTURE_ENV, + declared_from_with_production_alias, declared_with_production_alias, explicit_setting_notice, + has_denied_warnings, CollectedSettings, DeclaredPosture, DevelopmentClass, + DevelopmentOnlyRefused, DevelopmentSetting, DevelopmentWitness, ExplicitClass, + ExplicitProductionSetting, ExplicitSettingLine, FoundExplicitSetting, FoundSetting, Gated, + Posture, PostureError, PostureReport, PostureSource, SettingOrigin, Stated, DEVELOPMENT, + POSTURE_ENV, }; pub use secrets::{ validate_secret_root, ProtectedSecret, SecretError, SecretFileCheck, SecretProvider, diff --git a/crates/registry-platform-config/src/posture.rs b/crates/registry-platform-config/src/posture.rs index d6af2beaf2..9b5ab0dcd3 100644 --- a/crates/registry-platform-config/src/posture.rs +++ b/crates/registry-platform-config/src/posture.rs @@ -475,6 +475,17 @@ impl ExplicitSettingLine { summary: found.setting.summary.to_owned(), } } + + /// The one line a command prints for this setting: see + /// [`explicit_setting_notice`]. + #[must_use] + pub fn notice(&self) -> String { + explicit_setting_notice( + &self.code, + self.pointer.as_deref().unwrap_or_default(), + &self.summary, + ) + } } impl Serialize for ExplicitSettingLine { @@ -500,6 +511,20 @@ impl Serialize for ExplicitSettingLine { } } +/// The one line every command prints for an explicit production setting: +/// the code, where it is stated and what it relaxes. The summary starts a +/// sentence here, so its first letter is capitalised whatever its authored +/// case. +#[must_use] +pub fn explicit_setting_notice(code: &str, location: &str, summary: &str) -> String { + let mut rest = summary.chars(); + let summary: String = rest + .next() + .map(|first| first.to_uppercase().chain(rest).collect()) + .unwrap_or_default(); + format!("Explicit production setting {code} at {location}. {summary}.") +} + /// An [`ExplicitProductionSetting`] found in a process's configuration. #[derive(Clone, Debug)] pub struct FoundExplicitSetting { @@ -511,14 +536,13 @@ pub struct FoundExplicitSetting { impl FoundExplicitSetting { /// The one line a command prints for this setting, as the check commands - /// print it: the code, the member and what the setting relaxes. + /// print it: see [`explicit_setting_notice`]. #[must_use] pub fn notice(&self) -> String { - format!( - "Explicit production setting {} at {}. {}.", + explicit_setting_notice( self.setting.code, self.pointer.as_deref().unwrap_or_default(), - self.setting.summary + self.setting.summary, ) } } diff --git a/crates/registry-platform-config/src/posture_tests.rs b/crates/registry-platform-config/src/posture_tests.rs index 8f9e097012..61139e852e 100644 --- a/crates/registry-platform-config/src/posture_tests.rs +++ b/crates/registry-platform-config/src/posture_tests.rs @@ -790,3 +790,22 @@ fn deny_warnings_refuses_only_unaccepted_warnings_outside_posture() { assert!(!has_denied_warnings(&[platform, product, accepted])); assert!(has_denied_warnings(&[ordinary])); } + +#[test] +fn a_notice_starts_its_summary_as_a_sentence() { + static LOWERCASE: ExplicitProductionSetting = ExplicitProductionSetting { + code: "platform.posture.example", + key: "example", + summary: "admits an example. Other values stay refused", + }; + let found = FoundExplicitSetting { + setting: &LOWERCASE, + pointer: Some("/example".to_owned()), + position: None, + origin: SettingOrigin::RuntimeFile, + }; + assert_eq!( + found.notice(), + "Explicit production setting platform.posture.example at /example. Admits an example. Other values stay refused." + ); +} diff --git a/crates/registry-render/src/check.rs b/crates/registry-render/src/check.rs index e8dfdf83ff..9f575b6808 100644 --- a/crates/registry-render/src/check.rs +++ b/crates/registry-render/src/check.rs @@ -295,10 +295,12 @@ pub fn run(request: &CheckRequest<'_>, stdout: &mut dyn Write, stderr: &mut dyn .iter() .map(|setting| { format!( - "Explicit production setting {} at {}. {}.\n", - setting.code, - setting.pointer.as_deref().unwrap_or(""), - setting.summary + "{}\n", + registry_platform_config::explicit_setting_notice( + setting.code, + setting.pointer.as_deref().unwrap_or(""), + setting.summary, + ) ) }) .collect::() diff --git a/crates/registry-schedulingctl/src/lib.rs b/crates/registry-schedulingctl/src/lib.rs index ae7ec5e094..d45787e680 100644 --- a/crates/registry-schedulingctl/src/lib.rs +++ b/crates/registry-schedulingctl/src/lib.rs @@ -973,7 +973,8 @@ fn write_explicit_setting( ) -> io::Result<()> { writeln!( out, - "Explicit production setting {code} at {pointer}. {summary}." + "{}", + registry_platform_config::explicit_setting_notice(code, pointer, summary) ) } diff --git a/docs/site/src/content/docs/configure/enable-sd-jwt-vc.mdx b/docs/site/src/content/docs/configure/enable-sd-jwt-vc.mdx index 2d8a448e88..8f760f3734 100644 --- a/docs/site/src/content/docs/configure/enable-sd-jwt-vc.mdx +++ b/docs/site/src/content/docs/configure/enable-sd-jwt-vc.mdx @@ -130,7 +130,7 @@ Project: . Target: local-target.yaml Explicit production setting platform.posture.issuer-loopback-plaintext at /authentication/oidc/issuers/primary/issuer. An issuer endpoint uses plain HTTP on loopback. Explicit production setting platform.posture.issuer-loopback-plaintext at /authentication/oidc/issuers/primary/jwksSource/uri. An issuer endpoint uses plain HTTP on loopback. -Explicit production setting platform.posture.unrestricted-clients at /authentication/oidc/issuers/primary/allowedClients. admits a token from every client this issuer signs for. +Explicit production setting platform.posture.unrestricted-clients at /authentication/oidc/issuers/primary/allowedClients. Admits a token from every client this issuer signs for. warning[evidence.posture.local-assurance] local-target.yaml:1:1 /assuranceProfile local assurance permits locally held signing keys; production refuses it next: Build a production or evidence-grade package with a Transit signer. diff --git a/docs/site/src/content/docs/tutorials/build-and-deploy-evidence-project.mdx b/docs/site/src/content/docs/tutorials/build-and-deploy-evidence-project.mdx index e3e8cbe096..cd739f3656 100644 --- a/docs/site/src/content/docs/tutorials/build-and-deploy-evidence-project.mdx +++ b/docs/site/src/content/docs/tutorials/build-and-deploy-evidence-project.mdx @@ -166,7 +166,7 @@ Project: adult-status Target: deploy-target/target.yaml Explicit production setting platform.posture.issuer-loopback-plaintext at /authentication/oidc/issuers/primary/issuer. An issuer endpoint uses plain HTTP on loopback. Explicit production setting platform.posture.issuer-loopback-plaintext at /authentication/oidc/issuers/primary/jwksSource/uri. An issuer endpoint uses plain HTTP on loopback. -Explicit production setting platform.posture.unrestricted-clients at /authentication/oidc/issuers/primary/allowedClients. admits a token from every client this issuer signs for. +Explicit production setting platform.posture.unrestricted-clients at /authentication/oidc/issuers/primary/allowedClients. Admits a token from every client this issuer signs for. error[evidence.target.production-assurance-required] deploy-target/target.yaml:/assuranceProfile --production requires production or evidence-grade target assurance next: Correct the selected project or target artifact and rerun check. @@ -266,7 +266,7 @@ rstack evidence runtime check --runtime-config candidate/runtime.yaml Evidence package sha256: passed check (4 requirements) Explicit production setting platform.posture.issuer-loopback-plaintext at /authentication/oidc/issuers/primary/issuer. An issuer endpoint uses plain HTTP on loopback. Explicit production setting platform.posture.issuer-loopback-plaintext at /authentication/oidc/issuers/primary/jwksSource/uri. An issuer endpoint uses plain HTTP on loopback. -Explicit production setting platform.posture.unrestricted-clients at /authentication/oidc/issuers/primary/allowedClients. admits a token from every client this issuer signs for. +Explicit production setting platform.posture.unrestricted-clients at /authentication/oidc/issuers/primary/allowedClients. Admits a token from every client this issuer signs for. warning[evidence.posture.local-assurance] /assuranceProfile local assurance permits locally held signing keys; production refuses it next: Build a production or evidence-grade package with a Transit signer. diff --git a/docs/site/src/content/docs/tutorials/connect-a-sqlite-extract.mdx b/docs/site/src/content/docs/tutorials/connect-a-sqlite-extract.mdx index 9cc5c75d62..1bc4d47e44 100644 --- a/docs/site/src/content/docs/tutorials/connect-a-sqlite-extract.mdx +++ b/docs/site/src/content/docs/tutorials/connect-a-sqlite-extract.mdx @@ -149,7 +149,7 @@ Project: . Target: local-target.yaml Explicit production setting platform.posture.issuer-loopback-plaintext at /authentication/oidc/issuers/primary/issuer. An issuer endpoint uses plain HTTP on loopback. Explicit production setting platform.posture.issuer-loopback-plaintext at /authentication/oidc/issuers/primary/jwksSource/uri. An issuer endpoint uses plain HTTP on loopback. -Explicit production setting platform.posture.unrestricted-clients at /authentication/oidc/issuers/primary/allowedClients. admits a token from every client this issuer signs for. +Explicit production setting platform.posture.unrestricted-clients at /authentication/oidc/issuers/primary/allowedClients. Admits a token from every client this issuer signs for. warning[evidence.posture.local-assurance] local-target.yaml:1:1 /assuranceProfile local assurance permits locally held signing keys; production refuses it next: Build a production or evidence-grade package with a Transit signer. @@ -206,7 +206,7 @@ Project: . Target: local-target.yaml Explicit production setting platform.posture.issuer-loopback-plaintext at /authentication/oidc/issuers/primary/issuer. An issuer endpoint uses plain HTTP on loopback. Explicit production setting platform.posture.issuer-loopback-plaintext at /authentication/oidc/issuers/primary/jwksSource/uri. An issuer endpoint uses plain HTTP on loopback. -Explicit production setting platform.posture.unrestricted-clients at /authentication/oidc/issuers/primary/allowedClients. admits a token from every client this issuer signs for. +Explicit production setting platform.posture.unrestricted-clients at /authentication/oidc/issuers/primary/allowedClients. Admits a token from every client this issuer signs for. warning[evidence.posture.local-assurance] local-target.yaml:1:1 /assuranceProfile local assurance permits locally held signing keys; production refuses it next: Build a production or evidence-grade package with a Transit signer. diff --git a/docs/site/src/content/docs/tutorials/connect-an-institution-source.mdx b/docs/site/src/content/docs/tutorials/connect-an-institution-source.mdx index 1ae3afe88c..c7f54aa775 100644 --- a/docs/site/src/content/docs/tutorials/connect-an-institution-source.mdx +++ b/docs/site/src/content/docs/tutorials/connect-an-institution-source.mdx @@ -93,7 +93,7 @@ Target: local-target.yaml Deployment inputs missing: signer.publicJwkFile; the compiled-target bundle check was skipped. Supply them and rerun check to prove the target. Explicit production setting platform.posture.issuer-loopback-plaintext at /authentication/oidc/issuers/primary/issuer. An issuer endpoint uses plain HTTP on loopback. Explicit production setting platform.posture.issuer-loopback-plaintext at /authentication/oidc/issuers/primary/jwksSource/uri. An issuer endpoint uses plain HTTP on loopback. -Explicit production setting platform.posture.unrestricted-clients at /authentication/oidc/issuers/primary/allowedClients. admits a token from every client this issuer signs for. +Explicit production setting platform.posture.unrestricted-clients at /authentication/oidc/issuers/primary/allowedClients. Admits a token from every client this issuer signs for. warning[evidence.posture.local-assurance] local-target.yaml /assuranceProfile local assurance permits locally held signing keys; production refuses it next: Build a production or evidence-grade package with a Transit signer. diff --git a/docs/site/src/content/docs/tutorials/first-evidence-assertion.mdx b/docs/site/src/content/docs/tutorials/first-evidence-assertion.mdx index c15732928f..301f13da4a 100644 --- a/docs/site/src/content/docs/tutorials/first-evidence-assertion.mdx +++ b/docs/site/src/content/docs/tutorials/first-evidence-assertion.mdx @@ -87,7 +87,7 @@ Target: local-target.yaml Deployment inputs missing: signer.publicJwkFile; the compiled-target bundle check was skipped. Supply them and rerun check to prove the target. Explicit production setting platform.posture.issuer-loopback-plaintext at /authentication/oidc/issuers/primary/issuer. An issuer endpoint uses plain HTTP on loopback. Explicit production setting platform.posture.issuer-loopback-plaintext at /authentication/oidc/issuers/primary/jwksSource/uri. An issuer endpoint uses plain HTTP on loopback. -Explicit production setting platform.posture.unrestricted-clients at /authentication/oidc/issuers/primary/allowedClients. admits a token from every client this issuer signs for. +Explicit production setting platform.posture.unrestricted-clients at /authentication/oidc/issuers/primary/allowedClients. Admits a token from every client this issuer signs for. warning[evidence.posture.local-assurance] local-target.yaml /assuranceProfile local assurance permits locally held signing keys; production refuses it next: Build a production or evidence-grade package with a Transit signer. From 9d067fe5b16a2733fbbeb25d5b3fbba0bbeffe09 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Wed, 2 Dec 2026 00:51:47 +0000 Subject: [PATCH 159/183] test(bregctl): expect the explicit-setting notice provision prints The test runtime states accessTokenType: JWT, so provision reports that explicit production setting on stderr. Two print-mode tests still expected empty stderr; they now require exactly that notice line. Refs #2882. Signed-off-by: Jeremi Joslin --- crates/registry-bregctl/tests/provision_cli.rs | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/crates/registry-bregctl/tests/provision_cli.rs b/crates/registry-bregctl/tests/provision_cli.rs index 1e6b5d67aa..2ae650c75d 100644 --- a/crates/registry-bregctl/tests/provision_cli.rs +++ b/crates/registry-bregctl/tests/provision_cli.rs @@ -11,6 +11,15 @@ use std::process::{Command, Output}; const MIGRATION_PASSWORD: &str = "migration-password-for-print-mode"; const RUNTIME_PASSWORD: &str = "runtime-password-for-print-mode"; +/// The runtime file states `accessTokenType: JWT`, an explicit production +/// setting, so `provision` reports it on stderr and nothing else. +fn assert_only_the_jwt_notice(stderr: &str) { + assert_eq!( + stderr, + "Explicit production setting platform.posture.jwt-access-token at /authentication/oidc/issuers/primary/accessTokenType. Admits access tokens typed JWT. ID tokens stay refused.\n" + ); +} + /// 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 { @@ -117,7 +126,7 @@ fn print_sql_writes_the_script_and_no_password() { 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}"); + assert_only_the_jwt_notice(&stderr); for name in [ "breg_migration", "breg_runtime", @@ -151,7 +160,7 @@ fn print_sql_succeeds_before_the_package_root_exists() { 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}"); + assert_only_the_jwt_notice(&stderr); assert!(stdout.contains("CREATE ROLE"), "{stdout}"); } From 7653233a01308ddf3cdc7c8e509d045a503f6905 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Wed, 2 Dec 2026 01:00:24 +0000 Subject: [PATCH 160/183] fix(platform): name a CA bundle that is not text in every provision refusal The text rule refused a binary CA bundle with the generic invalid-value error, which named no reason and, in several tools, a fix that did not apply. SecretError gains PublicDocumentNotText, and every provision tool now words a secret or public-document refusal with its reason and the fix the error names, at the member pointer. The CHANGELOG states the real gap (--print-sql printed a plan) and the real rule (UTF-8 text). Refs #2882. Signed-off-by: Jeremi Joslin --- crates/registry-adapter-engine/src/load.rs | 4 +- .../registry-adapter-job/src/hook_ingress.rs | 4 +- crates/registry-adapterctl/src/provision.rs | 2 +- crates/registry-bregctl/src/provision.rs | 10 ++- crates/registry-caseworkctl/src/provision.rs | 2 +- .../registry-caseworkctl/tests/provision.rs | 24 +++++++ crates/registry-coordinator/src/provision.rs | 10 ++- .../tests/provision_cli.rs | 3 + crates/registry-documentsctl/src/provision.rs | 2 +- crates/registry-messagingctl/src/provision.rs | 2 +- .../tests/provision_cli.rs | 8 +++ crates/registry-platform-config/README.md | 3 +- crates/registry-platform-config/src/blocks.rs | 18 +++-- .../src/blocks_tests.rs | 69 +++++++++++++++++-- .../registry-platform-config/src/secrets.rs | 7 ++ .../registry-schedulingctl/src/provision.rs | 2 +- products/platform/CHANGELOG.md | 16 +++-- 17 files changed, 154 insertions(+), 32 deletions(-) diff --git a/crates/registry-adapter-engine/src/load.rs b/crates/registry-adapter-engine/src/load.rs index cb725c69b6..1cee780125 100644 --- a/crates/registry-adapter-engine/src/load.rs +++ b/crates/registry-adapter-engine/src/load.rs @@ -518,7 +518,9 @@ fn secret_refusal_fix(error: &SecretError) -> &'static str { } SecretError::UnsafeFile(check) => check.suggested_action(), SecretError::UnsafePublicDocument(check) => check.public_suggested_action(), - SecretError::PrivateKeyInPublicDocument => error.suggested_action(), + SecretError::PrivateKeyInPublicDocument | SecretError::PublicDocumentNotText => { + error.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" diff --git a/crates/registry-adapter-job/src/hook_ingress.rs b/crates/registry-adapter-job/src/hook_ingress.rs index 22b6849e76..009394178a 100644 --- a/crates/registry-adapter-job/src/hook_ingress.rs +++ b/crates/registry-adapter-job/src/hook_ingress.rs @@ -437,7 +437,9 @@ fn resolve_member( SecretError::Unavailable => "the secret file is missing", SecretError::UnsafeFile(check) => check.suggested_action(), SecretError::UnsafePublicDocument(check) => check.public_suggested_action(), - SecretError::PrivateKeyInPublicDocument => error.suggested_action(), + SecretError::PrivateKeyInPublicDocument | SecretError::PublicDocumentNotText => { + error.suggested_action() + } SecretError::Read => "the secret file could not be read", SecretError::InvalidValue => "the secret is empty or contains a NUL byte", SecretError::ProviderDisabled => { diff --git a/crates/registry-adapterctl/src/provision.rs b/crates/registry-adapterctl/src/provision.rs index 449dc3b821..3ba29612c9 100644 --- a/crates/registry-adapterctl/src/provision.rs +++ b/crates/registry-adapterctl/src/provision.rs @@ -85,7 +85,7 @@ pub(crate) fn load( "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.", + error.suggested_action(), ) }) }; diff --git a/crates/registry-bregctl/src/provision.rs b/crates/registry-bregctl/src/provision.rs index 03f4e1c559..a92bdb44e5 100644 --- a/crates/registry-bregctl/src/provision.rs +++ b/crates/registry-bregctl/src/provision.rs @@ -95,12 +95,16 @@ pub(crate) fn load( .map_err(|error| runtime_file_refused(&absolute, &error))?; let resolve = |member: DatabaseMember, reference| { let read = member.read_reference(&secrets, reference); - read.map_err(|_| { + read.map_err(|error| { 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.", + registry_platform_config::describe_secret_failure( + &format!("database.{member}"), + reference.as_str(), + &error, + ), + error.suggested_action(), ) }) }; diff --git a/crates/registry-caseworkctl/src/provision.rs b/crates/registry-caseworkctl/src/provision.rs index 24618415c0..d73cef84b7 100644 --- a/crates/registry-caseworkctl/src/provision.rs +++ b/crates/registry-caseworkctl/src/provision.rs @@ -136,6 +136,6 @@ fn secret_diagnostic( "casework.runtime.secret-unavailable", format!("runtime.yaml:{pointer}"), describe_secret_failure(field, reference, error), - SECRET_ACTION, + error.suggested_action(), )) } diff --git a/crates/registry-caseworkctl/tests/provision.rs b/crates/registry-caseworkctl/tests/provision.rs index 8aff6db91e..bf5e7cbed9 100644 --- a/crates/registry-caseworkctl/tests/provision.rs +++ b/crates/registry-caseworkctl/tests/provision.rs @@ -311,6 +311,30 @@ fn a_runtime_url_secret_that_is_not_text_is_refused() { ); } +#[test] +fn a_ca_bundle_that_is_not_text_is_refused_with_its_reason() { + let (migration, runtime) = offline_urls(); + let ca = tempfile::NamedTempFile::new().unwrap(); + fs::write(ca.path(), "replaced below").unwrap(); + let deployment = deployment(&DatabaseUrls { + migration: &migration, + runtime: &runtime, + ca_pem: Some(ca.path()), + plaintext: false, + bind: "127.0.0.1:8100", + }); + let bundle = deployment.root.join("secrets/ca"); + fs::write(&bundle, [0xff, 0xfe, 0xfd]).unwrap(); + fs::set_permissions(&bundle, fs::Permissions::from_mode(0o644)).unwrap(); + let refused = refused_print(&deployment.runtime); + assert_loader_refusal( + &refused, + "casework.runtime.secret-unavailable", + "/database/caBundleRef", + ); + assert!(refused.2.contains("not UTF-8 text"), "{}", refused.2); +} + #[test] fn a_missing_ca_bundle_secret_is_refused() { let (migration, runtime) = offline_urls(); diff --git a/crates/registry-coordinator/src/provision.rs b/crates/registry-coordinator/src/provision.rs index 9605a57bd4..9f6f53f617 100644 --- a/crates/registry-coordinator/src/provision.rs +++ b/crates/registry-coordinator/src/provision.rs @@ -96,11 +96,15 @@ fn load(path: &Path, declared: DeclaredPosture) -> Result Some( registry_platform_config::DatabaseMember::CaBundle .read(&resolver, reference) - .map_err(|_| { + .map_err(|error| { vec![*refusal( "/database/caBundleRef", - "the referenced CA bundle could not be read", - "Make the CA bundle the runtime file names available to this command.", + ®istry_platform_config::describe_secret_failure( + "database.caBundleRef", + reference, + &error, + ), + error.suggested_action(), )] })? .expose_secret() diff --git a/crates/registry-coordinator/tests/provision_cli.rs b/crates/registry-coordinator/tests/provision_cli.rs index f2637fa03d..a76ef1688a 100644 --- a/crates/registry-coordinator/tests/provision_cli.rs +++ b/crates/registry-coordinator/tests/provision_cli.rs @@ -384,12 +384,15 @@ fn a_certificate_authority_file_that_is_not_text_is_refused() { let runtime = runtime_file(directory.path()); let root_pem = directory.path().join("secrets/postgres-root.pem"); fs::write(&root_pem, [0xff, 0xfe, 0xfd]).unwrap(); + fs::set_permissions(&root_pem, fs::Permissions::from_mode(0o600)).unwrap(); let output = provision(&runtime, &["--print-sql"]); assert_refused( &output, "coordinator.runtime-config.refused", "/database/caBundleRef", ); + let stderr = String::from_utf8_lossy(&output.stderr); + assert!(stderr.contains("not UTF-8 text"), "{stderr}"); } #[test] diff --git a/crates/registry-documentsctl/src/provision.rs b/crates/registry-documentsctl/src/provision.rs index 3b6312dfad..c95751348d 100644 --- a/crates/registry-documentsctl/src/provision.rs +++ b/crates/registry-documentsctl/src/provision.rs @@ -77,7 +77,7 @@ pub(crate) fn load( "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.", + error.suggested_action(), ) }) }; diff --git a/crates/registry-messagingctl/src/provision.rs b/crates/registry-messagingctl/src/provision.rs index 157fe168f8..a488c5867d 100644 --- a/crates/registry-messagingctl/src/provision.rs +++ b/crates/registry-messagingctl/src/provision.rs @@ -81,7 +81,7 @@ pub(crate) fn load( "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.", + error.suggested_action(), ) }) }; diff --git a/crates/registry-messagingctl/tests/provision_cli.rs b/crates/registry-messagingctl/tests/provision_cli.rs index eaa1865ceb..df6f80f1af 100644 --- a/crates/registry-messagingctl/tests/provision_cli.rs +++ b/crates/registry-messagingctl/tests/provision_cli.rs @@ -365,6 +365,7 @@ fn a_ca_bundle_that_is_not_text_is_refused_at_its_member() { let runtime = write_runtime(directory.path()); let ca = directory.path().join("secrets").join("database-ca.pem"); std::fs::write(&ca, [0xff, 0xfe, 0xfd]).unwrap(); + std::fs::set_permissions(&ca, std::fs::Permissions::from_mode(0o644)).unwrap(); let text = std::fs::read_to_string(&runtime).unwrap(); let stated = text.replace( " migrationUrlRef: secret:file/migration-database-url\n", @@ -377,6 +378,13 @@ fn a_ca_bundle_that_is_not_text_is_refused_at_its_member() { let diagnostic = first_diagnostic(&report); assert_eq!(diagnostic["code"], "config.refused", "{report:#}"); assert_eq!(diagnostic["path"], "/database/caBundleRef", "{report:#}"); + assert!( + diagnostic["message"] + .as_str() + .unwrap() + .contains("not UTF-8 text"), + "{report:#}" + ); } #[test] diff --git a/crates/registry-platform-config/README.md b/crates/registry-platform-config/README.md index 900eb4f813..d7bdb252a5 100644 --- a/crates/registry-platform-config/README.md +++ b/crates/registry-platform-config/README.md @@ -131,7 +131,8 @@ accepted reference through the explicitly enabled environment or file provider. connections and task connections. - `DatabaseConfig`: `runtimeUrlRef`, `migrationUrlRef`, and an optional `caBundleRef`. `DatabaseMember` names each of them and reads it with the - rule it takes: the CA bundle as a public document, each URL as a secret. + rule it takes: the CA bundle as a public document that must be UTF-8 text, + each URL as a secret. - `DestinationTransport`: `verified-tls`, `loopback-plaintext` or `private-network-plaintext`. Only the last is an explicit production setting. - `PrivateRanges`: the `allowedPrivateCidrs` list of `PrivateRange` values from diff --git a/crates/registry-platform-config/src/blocks.rs b/crates/registry-platform-config/src/blocks.rs index 56798bb65f..9444678671 100644 --- a/crates/registry-platform-config/src/blocks.rs +++ b/crates/registry-platform-config/src/blocks.rs @@ -397,6 +397,10 @@ pub fn describe_secret_failure(field: &str, _reference: &str, error: &SecretErro "the public document holds a PEM private key block. {}", error.suggested_action() ), + SecretError::PublicDocumentNotText => format!( + "the public document is not UTF-8 text. {}", + error.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 \ @@ -457,16 +461,16 @@ impl DatabaseMember { } /// Read the member's reference with the rule the member takes. A CA - /// bundle is a public document holding PEM text, so bytes that are not - /// UTF-8 are [`SecretError::InvalidValue`] here rather than a failure at - /// the TLS connection. + /// bundle is a public document read as text, so bytes that are not UTF-8 + /// are [`SecretError::PublicDocumentNotText`]. Its certificates are + /// parsed where the connection is configured, not here. pub fn read( self, resolver: &SecretResolver, reference: &str, ) -> Result { match self { - Self::CaBundle => pem_text(resolver.resolve_public_document(reference)?), + Self::CaBundle => utf8_text(resolver.resolve_public_document(reference)?), Self::RuntimeUrl | Self::MigrationUrl => resolver.resolve(reference), } } @@ -478,15 +482,15 @@ impl DatabaseMember { reference: &SecretReference, ) -> Result { match self { - Self::CaBundle => pem_text(resolver.resolve_public_document_reference(reference)?), + Self::CaBundle => utf8_text(resolver.resolve_public_document_reference(reference)?), Self::RuntimeUrl | Self::MigrationUrl => resolver.resolve_reference(reference), } } } -fn pem_text(document: ProtectedSecret) -> Result { +fn utf8_text(document: ProtectedSecret) -> Result { if std::str::from_utf8(document.expose_secret()).is_err() { - return Err(SecretError::InvalidValue); + return Err(SecretError::PublicDocumentNotText); } Ok(document) } diff --git a/crates/registry-platform-config/src/blocks_tests.rs b/crates/registry-platform-config/src/blocks_tests.rs index de39da29c5..472d72c968 100644 --- a/crates/registry-platform-config/src/blocks_tests.rs +++ b/crates/registry-platform-config/src/blocks_tests.rs @@ -116,30 +116,89 @@ fn a_database_ca_bundle_reads_as_a_public_document_and_a_url_as_a_secret() { } } +/// A resolver over a fresh root holding each `(name, bytes)` as a 0644 file, +/// the mode a public document may have whatever the process umask. #[cfg(unix)] -#[test] -fn a_database_ca_bundle_that_is_not_text_is_an_invalid_value() { +fn public_documents(files: &[(&str, &[u8])]) -> (tempfile::TempDir, SecretResolver) { + use std::os::unix::fs::PermissionsExt as _; + let root = tempfile::tempdir().expect("tempdir"); let canonical = std::fs::canonicalize(root.path()).expect("canonical root"); - std::fs::write(canonical.join("binary"), [0xff, 0xfe, 0xfd]).expect("write file"); + for (name, bytes) in files { + let path = canonical.join(name); + std::fs::write(&path, bytes).expect("write file"); + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o644)).expect("0644"); + } let resolver = SecretProvidersConfig { file: Some(FileSecretProviderConfig::new(canonical)), environment: None, } .resolver(None) .expect("production resolver"); + (root, resolver) +} + +#[cfg(unix)] +#[test] +fn a_database_ca_bundle_that_is_not_text_is_refused_as_not_text() { + let (_root, resolver) = public_documents(&[("binary", &[0xff, 0xfe, 0xfd])]); let reference = SecretReference::parse("secret:file/binary").unwrap(); assert_eq!( DatabaseMember::CaBundle .read(&resolver, "secret:file/binary") .unwrap_err(), - SecretError::InvalidValue + SecretError::PublicDocumentNotText ); assert_eq!( DatabaseMember::CaBundle .read_reference(&resolver, &reference) .unwrap_err(), - SecretError::InvalidValue + SecretError::PublicDocumentNotText + ); + let described = describe_secret_failure( + "database.caBundleRef", + "secret:file/binary", + &SecretError::PublicDocumentNotText, + ); + assert!(described.contains("not UTF-8 text"), "{described}"); +} + +#[cfg(unix)] +#[test] +fn a_database_ca_bundle_accepts_every_text_shape_of_pem() { + let certificate = "-----BEGIN CERTIFICATE-----\nMIIB\n-----END CERTIFICATE-----\n"; + let bom = [b"\xEF\xBB\xBF".as_slice(), certificate.as_bytes()].concat(); + let crlf = certificate.replace('\n', "\r\n"); + let several = format!("issuer comment\n{certificate}{certificate} \n"); + let (_root, resolver) = public_documents(&[ + ("bom", &bom), + ("crlf", crlf.as_bytes()), + ("several", several.as_bytes()), + ]); + for name in ["bom", "crlf", "several"] { + assert!( + DatabaseMember::CaBundle + .read(&resolver, &format!("secret:file/{name}")) + .is_ok(), + "{name}" + ); + } +} + +#[cfg(unix)] +#[test] +fn a_private_key_is_refused_before_the_text_rule() { + let key = [ + &[0xff, 0xfe][..], + b"\n-----BEGIN PRIVATE KEY-----\nMII\n-----END PRIVATE KEY-----\n", + ] + .concat(); + let (_root, resolver) = public_documents(&[("key", &key)]); + assert_eq!( + DatabaseMember::CaBundle + .read(&resolver, "secret:file/key") + .unwrap_err(), + SecretError::PrivateKeyInPublicDocument ); } diff --git a/crates/registry-platform-config/src/secrets.rs b/crates/registry-platform-config/src/secrets.rs index 8a8c09ec5a..08a3475e4d 100644 --- a/crates/registry-platform-config/src/secrets.rs +++ b/crates/registry-platform-config/src/secrets.rs @@ -200,6 +200,10 @@ pub enum SecretError { /// A public document holds a PEM private key block. #[error("the referenced public document holds a private key")] PrivateKeyInPublicDocument, + /// A public document read as text, such as a CA bundle of PEM + /// certificates, holds bytes that are not UTF-8. + #[error("the referenced public document is not UTF-8 text")] + PublicDocumentNotText, #[error("the referenced secret could not be read")] Read, #[error("the referenced secret value is invalid")] @@ -229,6 +233,9 @@ impl SecretError { Self::PrivateKeyInPublicDocument => { "Put only certificates or public keys in the document, and keep the private key in its own secret file." } + Self::PublicDocumentNotText => { + "Store the document as UTF-8 text, such as PEM certificates." + } 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." diff --git a/crates/registry-schedulingctl/src/provision.rs b/crates/registry-schedulingctl/src/provision.rs index d123514d9d..7190cef0ab 100644 --- a/crates/registry-schedulingctl/src/provision.rs +++ b/crates/registry-schedulingctl/src/provision.rs @@ -81,7 +81,7 @@ pub(crate) fn load( "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.", + error.suggested_action(), ) }) }; diff --git a/products/platform/CHANGELOG.md b/products/platform/CHANGELOG.md index fa3dc6c69f..05b18d47be 100644 --- a/products/platform/CHANGELOG.md +++ b/products/platform/CHANGELOG.md @@ -26,17 +26,21 @@ owner-only. Migration: if `caBundleRef` named a combined certificate and key file, split the key into its own secret file and point `caBundleRef` at the certificates alone. -- Every `*ctl provision` tool now refuses a binary CA bundle at - `/database/caBundleRef` when it reads the runtime file, instead of failing - later at the TLS connection: the bundle must be PEM text. +- Every provision tool refuses a CA bundle that is not UTF-8 text at its + `caBundleRef` member (`/database/caBundleRef`, or `/store/caBundleRef` for + `adapterctl job-provision`) when it reads the runtime file, so + `--print-sql` no longer prints a plan for a binary bundle. Apply still + parses the PEM and refuses a bundle without a certificate. Every provision + tool now words a secret or public-document refusal with its reason and the + fix the error names. - The shared runtime blocks document publishes `StrictSecretProvidersConfig` and `StrictFileSecretProviderConfig`, the secret providers without `mountPolicy`. The Evidence OID4VCI and OID4VP runtime schemas embed them, so the published contract does not offer a member those runtimes refuse. - BREAKING for Rust callers of `registry-platform-config`: `SecretError` gains - `UnsafePublicDocument` and `PrivateKeyInPublicDocument`, and - `ProvisionInput` gains `explicit_settings`. Migration: add arms for the two - variants to exhaustive matches (`SecretFileCheck::public_message` and + `UnsafePublicDocument`, `PrivateKeyInPublicDocument` and + `PublicDocumentNotText`, and `ProvisionInput` gains `explicit_settings`. + Migration: add arms for the three variants to exhaustive matches (`SecretFileCheck::public_message` and `public_suggested_action` give their text), and fill `explicit_settings` from `PostureReport::explicit_setting_notices`. - Numbered releases ship `registry-session` for Linux amd64, Linux arm64 and From 2f0fefe120929f147fdae6891fd0ac33003f7130 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Wed, 2 Dec 2026 01:01:21 +0000 Subject: [PATCH 161/183] test(evidence): expect the store provisioning option in check help evidencectl check also accepts --store-provision-config without a project, and its help says so. Signed-off-by: Jeremi Joslin --- crates/registry-evidencectl/tests/file_check.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/registry-evidencectl/tests/file_check.rs b/crates/registry-evidencectl/tests/file_check.rs index 7d9f6bfc71..46165a0c79 100644 --- a/crates/registry-evidencectl/tests/file_check.rs +++ b/crates/registry-evidencectl/tests/file_check.rs @@ -393,7 +393,7 @@ fn check_help_says_the_project_is_required_unless_a_file_is_given() { .expect("run evidencectl"); let help = String::from_utf8_lossy(&output.stdout); assert!( - help.contains("Required unless --file is given"), + help.contains("Required unless --file or --store-provision-config is given"), "check --help must say when PROJECT is required: {help}" ); } From fbc2b2a4da8cb62fa464fcce44ed4c044444052f Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Wed, 2 Dec 2026 01:31:41 +0000 Subject: [PATCH 162/183] chore(identifiers): regenerate the catalogue for the #2882 follow-up schemas Signed-off-by: Jeremi Joslin --- .../identifiers/generated/catalog.v1.json | 22 +++++++++---------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/products/identifiers/generated/catalog.v1.json b/products/identifiers/generated/catalog.v1.json index d7c6db2fb1..e7ff14123c 100644 --- a/products/identifiers/generated/catalog.v1.json +++ b/products/identifiers/generated/catalog.v1.json @@ -5965,7 +5965,7 @@ "description": "Registry Coordinator deterministic fixture authoring JSON Schema.", "source": { "path": "crates/registry-coordinator/src/scenarios.rs", - "sha256": "8ef5c37541be5c83c60fa82c20d615b79287df941b33c34b8d6a12ed83d562d9" + "sha256": "fb76ce54849cf3beff2614c77dc222d541de45c0d1137339eeacc214ab1729b7" }, "artifact": { "path": "products/coordinator/generated/fixture/fixture.schema.json", @@ -5983,11 +5983,11 @@ "description": "Registry Coordinator portable project authoring JSON Schema.", "source": { "path": "crates/registry-coordinator/src/authoring.rs", - "sha256": "5a69b78d0bd226766a8acaa1d25620309f3294b05aeef34250ea2cea6c6db267" + "sha256": "7861faa7e6967c1780fea4fc224578c9410f58d5ba9038ee38d8fc2e9dc51355" }, "artifact": { "path": "products/coordinator/generated/project/project.schema.json", - "sha256": "4e6aec4ae96ea5a85738802f64e30cb7a4af439ec43fdf0c5b9d8cbe6d96e7ad", + "sha256": "de2670ab3661e52afdb9bfb9be0c491ebb60cf9cc2725c15428f225cd10d9b70", "mediaType": "application/schema+json" } }, @@ -6001,11 +6001,11 @@ "description": "Registry Coordinator runtime configuration JSON Schema.", "source": { "path": "crates/registry-coordinator/src/runtime.rs", - "sha256": "c0d0267ec81eac40b0f73dcc331f174d526ae32658a2be1609682f1d136e30cf" + "sha256": "083365a7bbb3eeb12293cd7c665e52d5bef7444d54e4a5eca9e2ea378c5884c3" }, "artifact": { "path": "products/coordinator/generated/runtime/runtime.schema.json", - "sha256": "e13ad43e7b12338611fc69a0e2c9c0def7dbe42ff7655cdb7180f0c4d719d3c5", + "sha256": "874e8f61db468dc1bcbed3d5ca363f8f4c2cac8eef31a2038a4cb7248610e0d3", "mediaType": "application/schema+json" } }, @@ -6329,7 +6329,7 @@ }, "artifact": { "path": "products/evidence/generated/oid4vci-runtime/oid4vci-runtime.schema.json", - "sha256": "026c2168ecd30d5333c4d8e4fbea7831c6ea65ead80f5d95846634ee88c2a076", + "sha256": "9648aced227106dbfddecbc2acf7fc43d538948f4a9c002b72840cf284f33b43", "mediaType": "application/schema+json" } }, @@ -6347,7 +6347,7 @@ }, "artifact": { "path": "products/evidence/generated/oid4vp-runtime/oid4vp-runtime.schema.json", - "sha256": "4a8784546a9c990eece05f794e1cfd9d87691c310c39d637a1aae9e3bddebf02", + "sha256": "bdb0e2b0ab0b4a23b7df12d643da1d7269049076c01986b317639f92b8be78eb", "mediaType": "application/schema+json" } }, @@ -6419,7 +6419,7 @@ }, "artifact": { "path": "crates/registry-evidencectl/schemas/authoring/store-provision.schema.json", - "sha256": "6421b53f8cbe33174ed88cb0daa83951754a4fc7f98385274d8782a1b960741c", + "sha256": "961639d976875967842004e6e98a0b3e41a7ebd4612f4f7b55aed602ba2a4fe7", "mediaType": "application/schema+json" } }, @@ -6653,7 +6653,7 @@ }, "artifact": { "path": "crates/registry-cli-api/schema/connections.schema.json", - "sha256": "46eedf1ea8f63a1b6397244234ea690f0ebce68d45527cb28d216db9470c819c", + "sha256": "35c0369ec35cf11b3cab6a861b60eb59cff838e328098497f47f627aaadd22cc", "mediaType": "application/schema+json" } }, @@ -6797,7 +6797,7 @@ }, "artifact": { "path": "products/platform/schemas/task-connection.schema.json", - "sha256": "0d65d121798aadf8f321d2ccac71ccdd05808d269de79be5157277a56c191b25", + "sha256": "cc596239277be2a97b9027e6cd3b4501c8e6e2759a67cd34dad4931c0d2997d0", "mediaType": "application/schema+json" } }, @@ -6887,7 +6887,7 @@ }, "artifact": { "path": "products/platform/generated/dev/dev.v1alpha1.schema.json", - "sha256": "f4d72b0fbb16c1f1205cca3f80ae81a6bb46da44962ec74a5872a37589c50761", + "sha256": "a7d8da1e475b8e5ef80e4879a4144bb5b247912ec5315d475d80c3b726953114", "mediaType": "application/schema+json" } }, From 2cf38ee7210e21a8984e21a3360c2a3005f0567a Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Wed, 2 Dec 2026 01:31:41 +0000 Subject: [PATCH 163/183] docs(coordinator): cite the shared numeric loopback check for request links Signed-off-by: Jeremi Joslin --- docs/site/src/content/docs/security/coordinator.mdx | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/site/src/content/docs/security/coordinator.mdx b/docs/site/src/content/docs/security/coordinator.mdx index 07c4ac4ee2..f2bd83f3c3 100644 --- a/docs/site/src/content/docs/security/coordinator.mdx +++ b/docs/site/src/content/docs/security/coordinator.mdx @@ -461,7 +461,8 @@ start or submit on retry; settlement from an event. doctor_counts_proposal_waits_by_their_last_turn_without_reading_breg; crates/registry-coordinator/tests/runtime_config.rs breg_proposal_follow_settings_are_bounded_and_outside_the_binding_digest; - crates/registry-coordinator/src/runtime.rs request_link, is_loopback. */} + crates/registry-coordinator/src/runtime.rs request_link; + crates/registry-coordinator/src/outbound.rs numeric_loopback. */} ### COORDINATOR-INV-08: BReg control metadata has its own response ceiling From f54240702a0c3b0758a428bf522186d1149b8ec3 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Wed, 2 Dec 2026 01:06:10 +0000 Subject: [PATCH 164/183] fix(coordinator): word unreadable database URL secrets with the shared reason Coordinator provision discarded the secret error for its two URL members and suggested a PEM file for a URL. It now gives the shared reason and the fix the error names, as every other provision tool does. Refs #2882. Signed-off-by: Jeremi Joslin --- crates/registry-coordinator/src/provision.rs | 12 ++++++++---- .../registry-coordinator/tests/provision_cli.rs | 16 ++++++++++++++++ 2 files changed, 24 insertions(+), 4 deletions(-) diff --git a/crates/registry-coordinator/src/provision.rs b/crates/registry-coordinator/src/provision.rs index 9f6f53f617..43124f7285 100644 --- a/crates/registry-coordinator/src/provision.rs +++ b/crates/registry-coordinator/src/provision.rs @@ -168,18 +168,22 @@ fn secret_text( reference: &str, pointer: &str, ) -> Result, Box> { - let secret = resolver.resolve(reference).map_err(|_| { + let secret = resolver.resolve(reference).map_err(|error| { refusal( pointer, - "the referenced secret could not be read", - "Make the secret the runtime file names available to this command.", + ®istry_platform_config::describe_secret_failure( + &pointer.trim_start_matches('/').replace('/', "."), + reference, + &error, + ), + error.suggested_action(), ) })?; 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.", + "Supply a UTF-8 PostgreSQL URL.", ) })?; Ok(Zeroizing::new(text.to_owned())) diff --git a/crates/registry-coordinator/tests/provision_cli.rs b/crates/registry-coordinator/tests/provision_cli.rs index a76ef1688a..a19b55ff2a 100644 --- a/crates/registry-coordinator/tests/provision_cli.rs +++ b/crates/registry-coordinator/tests/provision_cli.rs @@ -344,6 +344,20 @@ fn the_runtime_file_may_be_given_before_the_verb() { ); } +/// An unset URL secret is refused with the shared reason and the fix the +/// secret error names, as every provision tool words it. +fn assert_unavailable_reason_and_fix(output: &std::process::Output) { + let stderr = String::from_utf8_lossy(&output.stderr); + assert!( + stderr.contains("no readable secret of that name exists under the configured provider"), + "{stderr}" + ); + assert!( + stderr.contains("Create the secret under the configured provider, or correct the name."), + "{stderr}" + ); +} + #[test] fn an_unreadable_runtime_url_secret_is_refused_without_a_password() { let directory = tempfile::tempdir().unwrap(); @@ -359,6 +373,7 @@ fn an_unreadable_runtime_url_secret_is_refused_without_a_password() { "coordinator.runtime-config.refused", "/database/runtimeUrlRef", ); + assert_unavailable_reason_and_fix(&output); } #[test] @@ -376,6 +391,7 @@ fn an_unreadable_migration_url_secret_is_refused_without_a_password() { "coordinator.runtime-config.refused", "/database/migrationUrlRef", ); + assert_unavailable_reason_and_fix(&output); } #[test] From ce25f53df3a373b09d6ae68bda8c35b453d00d91 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 16:59:53 +0000 Subject: [PATCH 165/183] feat(rstack): bind holder preparation to one BReg action Signed-off-by: Jeremi Joslin --- clients/typescript/holder-function.ts | 132 +++++++++ .../typescript/tests/holder-function.test.ts | 279 ++++++++++++++++++ 2 files changed, 411 insertions(+) create mode 100644 clients/typescript/holder-function.ts create mode 100644 clients/typescript/tests/holder-function.test.ts diff --git a/clients/typescript/holder-function.ts b/clients/typescript/holder-function.ts new file mode 100644 index 0000000000..eb69f84a5a --- /dev/null +++ b/clients/typescript/holder-function.ts @@ -0,0 +1,132 @@ +import { RegistryError } from './core.ts' + +const uuid = /^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/u +const strongTag = /^"[\x21\x23-\x7e]{1,254}"$/u +const maximumRequestBytes = 32_768 +const bodyTooLarge = Symbol('body too large') + +interface HolderSubmission { + recordId: string + ifMatch: string + preparation: Preparation +} + +interface HolderCommand { + recordId: string + ifMatch: string + idempotencyKey: string + input: Input + signal: AbortSignal +} + +/** Host-owned parsing and invocation for one generated BReg Action and its fixed access profile. */ +interface HolderActionBinding { + path: string + parseSubmission: (body: unknown) => HolderSubmission | undefined + parsePreparation: (body: unknown) => Input | undefined + invoke: (credential: string, command: HolderCommand) => Promise<{ recordId: string }> +} + +function reply(body: object, status: number): Response { + return Response.json(body, { status, headers: { 'Cache-Control': 'no-store' } }) +} + +function parseJson(source: string): unknown { + const value: unknown = JSON.parse(source, (_key, member: unknown) => { + if (typeof member === 'number' && + (!Number.isFinite(member) || Number.isInteger(member) && !Number.isSafeInteger(member))) { + throw new SyntaxError('Unsupported JSON number.') + } + return member + }) + // On valid JSON, a quoted token followed by a colon is an object key. + // Decode the key before comparing so Unicode escapes cannot hide duplicates. + const objects: Set[] = [] + for (const [token, quoted, colon] of source.matchAll(/("(?:[^"\\]|\\.)*")(\s*:)?|[{}]/gu)) { + if (token === '{') objects.push(new Set()) + if (token === '}') objects.pop() + if (quoted && colon) { + const keys = objects.at(-1)! + const key: string = JSON.parse(quoted) + if (keys.has(key)) throw new SyntaxError('Duplicate JSON member.') + keys.add(key) + } + } + return value +} + +async function readSubmission(request: Request): Promise { + if (!request.body) return undefined + const reader = request.body.getReader() + const decoder = new TextDecoder('utf-8', { fatal: true }) + let bytes = 0 + let body = '' + try { + for (let chunk = await reader.read(); !chunk.done; chunk = await reader.read()) { + bytes += chunk.value.byteLength + if (bytes > maximumRequestBytes) { + await reader.cancel() + return bodyTooLarge + } + body += decoder.decode(chunk.value, { stream: true }) + } + return parseJson(body + decoder.decode()) + } finally { + reader.releaseLock() + } +} + +/** Use on the trusted invoker's gateway-only listener. Preparation must reproduce the same input on retry. */ +export function createHolderActionHandler( + { path, parseSubmission, parsePreparation, invoke }: HolderActionBinding, + prepare: (input: Preparation) => unknown | Promise, +): (request: Request) => Promise { + if (!/^\/api\/functions\/[a-z][a-z0-9_-]{0,63}$/u.test(path)) throw new TypeError('Expected a declared function path.') + + return async request => { + const url = new URL(request.url) + if (request.method !== 'POST' || url.pathname !== path || url.search || url.hash) { + return reply({ message: 'Unknown function route.' }, 404) + } + const credential = /^Bearer ([A-Za-z0-9._-]+)$/u.exec(request.headers.get('authorization') ?? '')?.[1] + if (!credential) return reply({ message: 'Sign in to continue.' }, 401) + + const idempotencyKey = request.headers.get('idempotency-key') + const mediaType = request.headers.get('content-type')?.split(';', 1)[0]?.trim().toLowerCase() + if (!idempotencyKey || !uuid.test(idempotencyKey.toLowerCase()) || mediaType !== 'application/json') { + return reply({ message: 'Send a JSON request with its attempt key.' }, 400) + } + let submission: HolderSubmission | undefined + try { + const body = await readSubmission(request) + if (body === bodyTooLarge) return reply({ message: 'The request is too large.' }, 413) + if (body !== undefined) submission = parseSubmission(body) + } catch { + return reply({ message: 'Send a valid JSON request.' }, 400) + } + if (!submission || !uuid.test(submission.recordId) || !strongTag.test(submission.ifMatch)) { + return reply({ message: 'Send a record and its reviewed condition.' }, 400) + } + const { recordId, ifMatch, preparation } = submission + + let input: Input | undefined + try { + request.signal.throwIfAborted() + input = parsePreparation(await prepare(preparation)) + } catch { + return reply({ message: 'The function could not prepare the request.' }, 502) + } + if (!input || request.signal.aborted) return reply({ message: 'The function could not prepare the request.' }, 502) + + try { + const result = await invoke(credential, { recordId, ifMatch, idempotencyKey, input, signal: request.signal }) + if (result.recordId === recordId) return reply({ recordId }, 200) + } catch (error) { + if (error instanceof RegistryError && error.kind === 'refused' && !error.outcomeUnknown && + error.status !== undefined && error.status >= 400 && error.status < 500) { + return reply({ message: 'BReg refused the request.' }, error.status) + } + } + return reply({ message: 'The Action outcome is unavailable. Retry the same attempt.' }, 502) + } +} diff --git a/clients/typescript/tests/holder-function.test.ts b/clients/typescript/tests/holder-function.test.ts new file mode 100644 index 0000000000..86abc8e5f4 --- /dev/null +++ b/clients/typescript/tests/holder-function.test.ts @@ -0,0 +1,279 @@ +import assert from 'node:assert/strict' +import test from 'node:test' +import { Transport, type Operation } from '../core.ts' +import { createHolderActionHandler } from '../holder-function.ts' + +const route = '/api/functions/renew' +const licenceId = 'c137aa49-8a74-4d63-9f38-47fde38b2949' +const otherLicenceId = 'a4d5b3fe-eaf4-456e-ae33-9ef6b85fa4b2' +const reviewedExpiresOn = '2027-06-30' +const newExpiresOn = '2028-06-30' +const ifMatch = '"reviewed-revision"' +const otherIfMatch = '"other-reviewed-revision"' +const idempotencyKey = '08114403-75d2-48d3-961a-5d4fb8b19687' +const holderAuthorization = 'Bearer synthetic-holder' +const submission = { licenceId, reviewedExpiresOn, preconditions: { licenceId: { ifMatch } } } +const holder = { subject: 'person-a', holderRef: 'holder-a', actor: 'human', client: 'licence-holder', + profile: 'licence-holder', audience: 'licences' } +const identities = new Map([ + [holderAuthorization, holder], + ['Bearer synthetic-other-subject', { ...holder, subject: 'person-b', holderRef: 'holder-b' }], + ['Bearer synthetic-agent', { ...holder, actor: 'agent' }], + ['Bearer synthetic-officer', { ...holder, profile: 'licence-officer' }], + ['Bearer synthetic-other-client', { ...holder, client: 'other' }], + ['Bearer synthetic-other-audience', { ...holder, audience: 'other' }], +]) +const records = new Map([[licenceId, { holderRef: 'holder-a', ifMatch }], + [otherLicenceId, { holderRef: 'holder-b', ifMatch: otherIfMatch }]]) +const otherSubmission = { ...submission, licenceId: otherLicenceId, preconditions: { licenceId: { ifMatch: otherIfMatch } } } + +const renewal: Operation = { + method: 'POST', path: '/v1/actions/renew', product: 'breg', + accessProfileParameter: true, accessProfileRequired: true, + keyed: true, mutating: true, requestMediaType: 'application/json', + problemValidators: { default: value => exactObject(value, ['code', 'detail', 'status']) }, + responses: { 200: [{ mode: 'json', mediaType: 'application/json' }] }, +} + +function exactObject(value: unknown, keys: readonly string[]): value is Record { + return value !== null && typeof value === 'object' && !Array.isArray(value) + && Object.keys(value).length === keys.length && keys.every(key => Object.hasOwn(value, key)) +} + +function parseSubmission(value: unknown) { + if (!exactObject(value, ['licenceId', 'reviewedExpiresOn', 'preconditions']) || + typeof value.licenceId !== 'string' || typeof value.reviewedExpiresOn !== 'string' || + !exactObject(value.preconditions, ['licenceId']) || !exactObject(value.preconditions.licenceId, ['ifMatch']) || + typeof value.preconditions.licenceId.ifMatch !== 'string') return undefined + return { + recordId: value.licenceId, ifMatch: value.preconditions.licenceId.ifMatch, + preparation: { reviewedExpiresOn: value.reviewedExpiresOn }, + } +} + +function parsePreparation(value: unknown) { + if (!exactObject(value, ['newExpiresOn']) || typeof value.newExpiresOn !== 'string') return undefined + return { newExpiresOn: value.newExpiresOn } +} + +function request(options: { path?: string; authorization?: string | null; body?: unknown; key?: string } = {}) { + const { path = route, authorization = holderAuthorization, body = submission, key = idempotencyKey } = options + const headers = new Headers({ + 'Content-Type': 'application/json', 'Idempotency-Key': key, + 'Registry-Client': 'page', Cookie: 'synthetic-cookie', 'X-Actor': 'synthetic-spoofed-actor', + }) + if (authorization !== null) headers.set('Authorization', authorization) + return new Request('https://service.test' + path, { method: 'POST', headers, body: JSON.stringify(body) }) +} + +function prepareRenewal({ reviewedExpiresOn }: { reviewedExpiresOn: string }) { + const year = Number(reviewedExpiresOn.slice(0, 4)) + return { newExpiresOn: String(year + 1) + reviewedExpiresOn.slice(4) } +} + +function setup(prepare: (input: { reviewedExpiresOn: string }) => unknown = prepareRenewal, + { loseFirstReceipt = false, parse = parseSubmission, receiptRecordId = '' } = {}, +) { + const preparations: unknown[][] = [] + const calls: { url: string; method: string | undefined; headers: Record; body: unknown }[] = [] + const writes: string[] = [] + const committed = new Map() + + const fetchProduct: typeof fetch = async (target, options) => { + const url = new URL(String(target)) + const headers = new Headers(options?.headers) + const body = JSON.parse(String(options?.body)) + calls.push({ url: url.href, method: options?.method, headers: Object.fromEntries(headers), body }) + if (url.pathname !== renewal.path || options?.method !== 'POST' || url.searchParams.get('accessProfile') !== 'licence-holder') { + throw new Error('The caller changed the checked Action contract.') + } + const refuse = (status: number, code = 'synthetic.refusal') => Response.json({ status, code, detail: 'product-only detail' }, + { status, headers: { 'Content-Type': 'application/problem+json' } }) + const identity = identities.get(headers.get('authorization') ?? '') + if (!identity || identity.audience !== 'licences') return refuse(401) + if (identity.actor !== 'human' || identity.client !== 'licence-holder' || identity.profile !== 'licence-holder') return refuse(403) + const record = records.get(body.input.licenceId) + if (record?.holderRef !== identity.holderRef || body.preconditions.licenceId.ifMatch !== record.ifMatch) return refuse(412) + if (body.input.newExpiresOn !== newExpiresOn) return refuse(412, 'synthetic.guard') + const receiptKey = identity.subject + ':' + headers.get('idempotency-key') + const command = JSON.stringify(body) + if (committed.has(receiptKey)) { + if (committed.get(receiptKey) !== command) return refuse(409) + return Response.json({ recordId: body.input.licenceId }) + } + committed.set(receiptKey, command) + writes.push(body.input.licenceId) + if (loseFirstReceipt && writes.length === 1) throw new Error('Simulated lost product receipt') + return Response.json({ recordId: receiptRecordId || body.input.licenceId, detail: 'product-only detail' }) + } + + const handle = createHolderActionHandler({ + path: route, + parseSubmission: parse, + parsePreparation, + async invoke(credential, command) { + const { recordId, ifMatch, input, idempotencyKey, signal } = command + const client = new Transport({ baseUrl: 'https://licences.test', token: () => credential, fetch: fetchProduct }) + const { data } = await client.call<{ recordId: string }>(renewal, { + query: { accessProfile: 'licence-holder' }, + body: { input: { licenceId: recordId, newExpiresOn: input.newExpiresOn }, preconditions: { licenceId: { ifMatch } } }, + idempotencyKey, + signal, + }) + return data + }, + }, (...args) => { + preparations.push(args) + return prepare(...args) + }) + return { handle, preparations, calls, writes } +} + +test('preparation receives one projected value and the checked Action receives the holder command', async () => { + const { handle, preparations, calls, writes } = setup() + const result = await handle(request()) + assert.equal(result.status, 200) + assert.deepEqual(await result.json(), { recordId: licenceId }) + assert.deepEqual(preparations, [[{ reviewedExpiresOn }]]) + assert.equal(calls.length, 1) + const call = calls[0]! + assert.equal(call.url, 'https://licences.test/v1/actions/renew?accessProfile=licence-holder') + assert.equal(call.method, 'POST') + assert.equal(call.headers.authorization, holderAuthorization) + assert.equal(call.headers['idempotency-key'], idempotencyKey) + for (const header of ['cookie', 'registry-client', 'x-actor']) assert.equal(call.headers[header], undefined) + assert.deepEqual(call.body, { input: { licenceId, newExpiresOn }, preconditions: { licenceId: { ifMatch } } }) + assert.deepEqual(writes, [licenceId]) +}) + +test('a missing caller or request outside the declared binding never reaches preparation or BReg', async () => { + const { handle, preparations, calls } = setup() + const cases = [ + [request({ authorization: null }), 401], + [request({ path: route + '/other' }), 404], + [request({ path: route + '?accessProfile=licence-officer' }), 404], + [request({ path: '/api/functions/issue' }), 404], + [request({ body: { ...submission, action: 'issue' } }), 400], + [request({ body: { ...submission, product: 'other' } }), 400], + [request({ body: { ...submission, accessProfile: 'licence-officer' } }), 400], + [request({ body: { ...submission, subject: 'other' } }), 400], + [request({ body: { ...submission, licenceId: licenceId.toUpperCase() } }), 400], + [request({ key: 'wrong' }), 400], + ] as const + for (const [incoming, expected] of cases) assert.equal((await handle(incoming)).status, expected) + assert.deepEqual(preparations, []) + assert.deepEqual(calls, []) +}) + +test('a preparation result outside its projection cannot substitute the target or invoke BReg', async () => { + const { handle, preparations, calls } = setup(() => ({ newExpiresOn, licenceId: otherLicenceId })) + assert.equal((await handle(request())).status, 502) + assert.deepEqual(preparations, [[{ reviewedExpiresOn }]]) + assert.deepEqual(calls, []) +}) + +test('a throwing submission parser returns a fixed refusal before preparation or BReg', async () => { + const { handle, preparations, calls } = setup(prepareRenewal, { + parse() { throw new Error('submitted values excluded from the reply') }, + }) + const response = await handle(request()) + assert.equal(response.status, 400) + assert.doesNotMatch(await response.text(), /submitted values/u) + assert.deepEqual(preparations, []) + assert.deepEqual(calls, []) +}) + +test('absent and oversized bodies are refused before the submission parser', async () => { + let parsed = 0 + const { handle, preparations, calls } = setup(prepareRenewal, { + parse() { parsed++; return parseSubmission(submission) }, + }) + const { url, headers, method } = request() + assert.equal((await handle(new Request(url, { headers, method }))).status, 400) + assert.equal((await handle(request({ body: 'x'.repeat(32_768) }))).status, 413) + assert.equal(parsed, 0) + assert.deepEqual(preparations, []) + assert.deepEqual(calls, []) +}) + +test('ambiguous request JSON is refused before the submission parser', async () => { + let parsed = 0 + const { handle, preparations, calls } = setup(prepareRenewal, { + parse() { parsed++; return parseSubmission(submission) }, + }) + const { url, headers, method } = request() + const cases = [ + '{"preconditions":{"licenceId":{"ifMatch":"a","ifM\\u0061tch":"b"}}}', + '{"input":9007199254740993}', + ] + for (const body of cases) assert.equal((await handle(new Request(url, { headers, method, body }))).status, 400) + assert.equal(parsed, 0) + assert.deepEqual(preparations, []) + assert.deepEqual(calls, []) +}) + +test('the owning product refuses a wrong subject, actor, role, client, audience, target, or condition', async () => { + const { handle, calls, writes } = setup() + const refusals = [ + [request({ authorization: 'Bearer synthetic-other-subject' }), 412], + [request({ authorization: 'Bearer synthetic-agent' }), 403], + [request({ authorization: 'Bearer synthetic-officer' }), 403], + [request({ authorization: 'Bearer synthetic-other-client' }), 403], + [request({ authorization: 'Bearer synthetic-other-audience' }), 401], + [request({ body: otherSubmission }), 412], + [request({ authorization: 'Bearer synthetic-other-subject', body: { ...submission, licenceId: otherLicenceId } }), 412], + [request({ body: { ...submission, preconditions: { licenceId: { ifMatch: '"stale-revision"' } } } }), 412], + ] as const + for (const [incoming, expected] of refusals) { + const response = await handle(incoming) + assert.equal(response.status, expected) + assert.doesNotMatch(await response.text(), /product-only detail|synthetic/u) + } + assert.equal(calls.length, refusals.length) + assert.deepEqual(writes, []) +}) + +test('overlapping requests keep each captured holder and exact target together', async () => { + const { handle, calls, writes } = setup() + const [first, second] = await Promise.all([ + handle(request()), + handle(request({ authorization: 'Bearer synthetic-other-subject', body: otherSubmission })), + ]) + assert.deepEqual([first.status, second.status], [200, 200]) + assert.deepEqual(await first.json(), { recordId: licenceId }) + assert.deepEqual(await second.json(), { recordId: otherLicenceId }) + assert.deepEqual(calls.map(call => call.headers.authorization).sort(), + [holderAuthorization, 'Bearer synthetic-other-subject'].sort()) + assert.deepEqual(writes.sort(), [licenceId, otherLicenceId].sort()) +}) + +test('a product refusal of the prepared value stays a refusal', async () => { + const { handle, calls, writes } = setup(() => ({ newExpiresOn: '2031-07-01' })) + const response = await handle(request()) + assert.equal(response.status, 412) + assert.deepEqual(await response.json(), { message: 'BReg refused the request.' }) + assert.equal(calls.length, 1) + assert.deepEqual(writes, []) +}) + +test('a product receipt for a different record leaves the original attempt unconfirmed', async () => { + const { handle, calls } = setup(prepareRenewal, { receiptRecordId: otherLicenceId }) + const response = await handle(request()) + assert.equal(response.status, 502) + assert.doesNotMatch(await response.text(), new RegExp(otherLicenceId, 'u')) + assert.equal(calls.length, 1) +}) + +test('after a lost product receipt the same renewal prepares the same command and reads back one effect', async () => { + const { handle, calls, preparations, writes } = setup(prepareRenewal, { loseFirstReceipt: true }) + const first = await handle(request()) + assert.equal(first.status, 502) + assert.doesNotMatch(await first.text(), /Simulated/u) + const retry = await handle(request()) + assert.equal(retry.status, 200) + assert.deepEqual(await retry.json(), { recordId: licenceId }) + assert.equal(calls.length, 2) + assert.deepEqual(calls[0], calls[1]) + assert.deepEqual(preparations, [[{ reviewedExpiresOn }], [{ reviewedExpiresOn }]]) + assert.deepEqual(writes, [licenceId]) +}) From d7a981d3c16e96fce49d1b78c02405562935c19b Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 18:05:00 +0000 Subject: [PATCH 166/183] fix(rstack): bound holder preparation and preserve unresolved attempts Signed-off-by: Jeremi Joslin --- clients/typescript/holder-function.ts | 46 ++++- .../typescript/tests/holder-function.test.ts | 190 +++++++++++++++--- 2 files changed, 200 insertions(+), 36 deletions(-) diff --git a/clients/typescript/holder-function.ts b/clients/typescript/holder-function.ts index eb69f84a5a..d50ac23477 100644 --- a/clients/typescript/holder-function.ts +++ b/clients/typescript/holder-function.ts @@ -22,6 +22,7 @@ interface HolderCommand { /** Host-owned parsing and invocation for one generated BReg Action and its fixed access profile. */ interface HolderActionBinding { path: string + preparationTimeoutMs: number parseSubmission: (body: unknown) => HolderSubmission | undefined parsePreparation: (body: unknown) => Input | undefined invoke: (credential: string, command: HolderCommand) => Promise<{ recordId: string }> @@ -31,6 +32,13 @@ function reply(body: object, status: number): Response { return Response.json(body, { status, headers: { 'Cache-Control': 'no-store' } }) } +function unresolvedOutcome(status = 502): Response { + return reply({ + code: 'holder-action.outcome-unresolved', + message: 'The Action outcome is unconfirmed. Keep the original attempt.', + }, status) +} + function parseJson(source: string): unknown { const value: unknown = JSON.parse(source, (_key, member: unknown) => { if (typeof member === 'number' && @@ -76,12 +84,38 @@ async function readSubmission(request: Request): Promise { } } +async function prepareInTime(run: () => unknown, signal: AbortSignal, timeoutMs: number): Promise { + signal.throwIfAborted() + const deadlineAt = performance.now() + timeoutMs + const expired = new Error('The preparation deadline expired.') + let stop!: (reason: unknown) => void + const stopped = new Promise((_resolve, reject) => { stop = reject }) + const abort = () => stop(signal.reason) + signal.addEventListener('abort', abort, { once: true }) + const timer = setTimeout(() => stop(expired), timeoutMs) + try { + const result = await Promise.race([stopped, Promise.resolve().then(() => { + signal.throwIfAborted() + return run() + })]) + signal.throwIfAborted() + if (performance.now() >= deadlineAt) throw expired + return result + } finally { + clearTimeout(timer) + signal.removeEventListener('abort', abort) + } +} + /** Use on the trusted invoker's gateway-only listener. Preparation must reproduce the same input on retry. */ export function createHolderActionHandler( - { path, parseSubmission, parsePreparation, invoke }: HolderActionBinding, + { path, preparationTimeoutMs, parseSubmission, parsePreparation, invoke }: HolderActionBinding, prepare: (input: Preparation) => unknown | Promise, ): (request: Request) => Promise { if (!/^\/api\/functions\/[a-z][a-z0-9_-]{0,63}$/u.test(path)) throw new TypeError('Expected a declared function path.') + if (!Number.isSafeInteger(preparationTimeoutMs) || preparationTimeoutMs < 1 || preparationTimeoutMs > 2_147_483_647) { + throw new TypeError('Expected a bounded preparation deadline.') + } return async request => { const url = new URL(request.url) @@ -104,15 +138,15 @@ export function createHolderActionHandler prepare(preparation), request.signal, preparationTimeoutMs)) } catch { return reply({ message: 'The function could not prepare the request.' }, 502) } @@ -124,9 +158,11 @@ export function createHolderActionHandler= 400 && error.status < 500) { + if (error.status === 409 && error.code === 'idempotency.key-reused' || + error.status === 410 && error.code === 'idempotency.expired') return unresolvedOutcome(error.status) return reply({ message: 'BReg refused the request.' }, error.status) } } - return reply({ message: 'The Action outcome is unavailable. Retry the same attempt.' }, 502) + return unresolvedOutcome() } } diff --git a/clients/typescript/tests/holder-function.test.ts b/clients/typescript/tests/holder-function.test.ts index 86abc8e5f4..e92ee89eb3 100644 --- a/clients/typescript/tests/holder-function.test.ts +++ b/clients/typescript/tests/holder-function.test.ts @@ -1,6 +1,11 @@ import assert from 'node:assert/strict' -import test from 'node:test' -import { Transport, type Operation } from '../core.ts' +import { mkdtempSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import test, { after } from 'node:test' +import { pathToFileURL } from 'node:url' +import { Transport, type CallOptions, type Operation } from '../core.ts' +import { generateFile } from '../generate.ts' import { createHolderActionHandler } from '../holder-function.ts' const route = '/api/functions/renew' @@ -12,11 +17,14 @@ const ifMatch = '"reviewed-revision"' const otherIfMatch = '"other-reviewed-revision"' const idempotencyKey = '08114403-75d2-48d3-961a-5d4fb8b19687' const holderAuthorization = 'Bearer synthetic-holder' +const traceId = '11111111111111111111111111111111' +const traceparent = `00-${traceId}-2222222222222222-01` const submission = { licenceId, reviewedExpiresOn, preconditions: { licenceId: { ifMatch } } } const holder = { subject: 'person-a', holderRef: 'holder-a', actor: 'human', client: 'licence-holder', profile: 'licence-holder', audience: 'licences' } const identities = new Map([ [holderAuthorization, holder], + ['Bearer synthetic-holder-renewed', holder], ['Bearer synthetic-other-subject', { ...holder, subject: 'person-b', holderRef: 'holder-b' }], ['Bearer synthetic-agent', { ...holder, actor: 'agent' }], ['Bearer synthetic-officer', { ...holder, profile: 'licence-officer' }], @@ -31,10 +39,35 @@ const renewal: Operation = { method: 'POST', path: '/v1/actions/renew', product: 'breg', accessProfileParameter: true, accessProfileRequired: true, keyed: true, mutating: true, requestMediaType: 'application/json', - problemValidators: { default: value => exactObject(value, ['code', 'detail', 'status']) }, + problemValidators: { default: value => exactObject(value, ['code', 'detail', 'status', 'title', 'traceId', 'type']) }, responses: { 200: [{ mode: 'json', mediaType: 'application/json' }] }, } +type RenewalInput = { licenceId: string; newExpiresOn: string } +type RenewalOptions = CallOptions & { accessProfile: 'licence-holder'; preconditions: { licenceId: { ifMatch: string } } } +type RenewalReceipt = { results: { licence?: { recordId: string } } } +type RenewalClient = { + invoke(action: 'renew', input: RenewalInput, options: RenewalOptions): Promise<{ data: RenewalReceipt }> +} + +let renewalClient = (transport: Transport): RenewalClient => ({ + invoke(_action, input, { accessProfile, preconditions, ...options }) { + return transport.call(renewal, { ...options, query: { accessProfile }, body: { input, preconditions } }) + }, +}) + +// Re-run the same synthetic transport cases using a client generated from the medical project's OpenAPI. +const medicalOpenApi = process.env.REGISTRY_HOLDER_TEST_OPENAPI +if (medicalOpenApi) { + const scratch = mkdtempSync(join(tmpdir(), 'registry-holder-openapi-')) + after(() => rmSync(scratch, { recursive: true })) + writeFileSync(join(scratch, 'package.json'), '{"type":"module"}\n') + const output = join(scratch, 'medical-renewal.ts') + generateFile(medicalOpenApi, output, false, true, [], true) + const { Client } = await import(pathToFileURL(output).href) as { Client: new (transport: Transport) => RenewalClient } + renewalClient = transport => new Client(transport) +} + function exactObject(value: unknown, keys: readonly string[]): value is Record { return value !== null && typeof value === 'object' && !Array.isArray(value) && Object.keys(value).length === keys.length && keys.every(key => Object.hasOwn(value, key)) @@ -56,14 +89,14 @@ function parsePreparation(value: unknown) { return { newExpiresOn: value.newExpiresOn } } -function request(options: { path?: string; authorization?: string | null; body?: unknown; key?: string } = {}) { - const { path = route, authorization = holderAuthorization, body = submission, key = idempotencyKey } = options +function request(options: { path?: string; authorization?: string | null; body?: unknown; key?: string; signal?: AbortSignal } = {}) { + const { path = route, authorization = holderAuthorization, body = submission, key = idempotencyKey, signal } = options const headers = new Headers({ 'Content-Type': 'application/json', 'Idempotency-Key': key, 'Registry-Client': 'page', Cookie: 'synthetic-cookie', 'X-Actor': 'synthetic-spoofed-actor', }) if (authorization !== null) headers.set('Authorization', authorization) - return new Request('https://service.test' + path, { method: 'POST', headers, body: JSON.stringify(body) }) + return new Request('https://service.test' + path, { method: 'POST', headers, body: JSON.stringify(body), signal }) } function prepareRenewal({ reviewedExpiresOn }: { reviewedExpiresOn: string }) { @@ -72,7 +105,10 @@ function prepareRenewal({ reviewedExpiresOn }: { reviewedExpiresOn: string }) { } function setup(prepare: (input: { reviewedExpiresOn: string }) => unknown = prepareRenewal, - { loseFirstReceipt = false, parse = parseSubmission, receiptRecordId = '' } = {}, + { loseFirstReceipt = false, parse = parseSubmission, receiptRecordId = '', preparationTimeoutMs = 1000, + replayProblem, omitReceiptRevision = false }: { loseFirstReceipt?: boolean; parse?: typeof parseSubmission; + receiptRecordId?: string | null; preparationTimeoutMs?: number; omitReceiptRevision?: boolean; + replayProblem?: 'idempotency.key-reused' | 'idempotency.expired' | 'mutation.conflict' } = {}, ) { const preparations: unknown[][] = [] const calls: { url: string; method: string | undefined; headers: Record; body: unknown }[] = [] @@ -87,40 +123,53 @@ function setup(prepare: (input: { reviewedExpiresOn: string }) => unknown = prep if (url.pathname !== renewal.path || options?.method !== 'POST' || url.searchParams.get('accessProfile') !== 'licence-holder') { throw new Error('The caller changed the checked Action contract.') } - const refuse = (status: number, code = 'synthetic.refusal') => Response.json({ status, code, detail: 'product-only detail' }, - { status, headers: { 'Content-Type': 'application/problem+json' } }) + const refuse = (status: number, code: string) => Response.json({ + status, code, detail: 'product-only detail', title: 'BReg refused the request.', traceId, + type: 'https://id.registrystack.org/problems/registry-breg/' + code.replaceAll('.', '/'), + }, { status, headers: { 'Content-Type': 'application/problem+json', 'Cache-Control': 'no-store', traceparent } }) + const receipt = () => Response.json({ action: 'renew', applicationId: idempotencyKey, + results: receiptRecordId === null ? {} : { licence: { recordId: receiptRecordId || body.input.licenceId, + recordType: 'licence', revision: omitReceiptRevision ? undefined : 2 } }, + }, { headers: { 'Cache-Control': 'no-store', traceparent } }) const identity = identities.get(headers.get('authorization') ?? '') - if (!identity || identity.audience !== 'licences') return refuse(401) - if (identity.actor !== 'human' || identity.client !== 'licence-holder' || identity.profile !== 'licence-holder') return refuse(403) + if (!identity || identity.audience !== 'licences') return refuse(401, 'authentication.refused') + if (identity.actor !== 'human' || identity.client !== 'licence-holder' || identity.profile !== 'licence-holder') { + return refuse(403, 'profile.not-authorized') + } const record = records.get(body.input.licenceId) - if (record?.holderRef !== identity.holderRef || body.preconditions.licenceId.ifMatch !== record.ifMatch) return refuse(412) - if (body.input.newExpiresOn !== newExpiresOn) return refuse(412, 'synthetic.guard') + if (record?.holderRef !== identity.holderRef || body.preconditions.licenceId.ifMatch !== record.ifMatch) { + return refuse(412, 'precondition.failed') + } + if (body.input.newExpiresOn !== newExpiresOn) return refuse(412, 'action.guard-failed') const receiptKey = identity.subject + ':' + headers.get('idempotency-key') const command = JSON.stringify(body) if (committed.has(receiptKey)) { - if (committed.get(receiptKey) !== command) return refuse(409) - return Response.json({ recordId: body.input.licenceId }) + if (replayProblem) return refuse(replayProblem === 'idempotency.expired' ? 410 : 409, replayProblem) + if (committed.get(receiptKey) !== command) return refuse(409, 'idempotency.key-reused') + return receipt() } committed.set(receiptKey, command) writes.push(body.input.licenceId) if (loseFirstReceipt && writes.length === 1) throw new Error('Simulated lost product receipt') - return Response.json({ recordId: receiptRecordId || body.input.licenceId, detail: 'product-only detail' }) + return receipt() } const handle = createHolderActionHandler({ path: route, + preparationTimeoutMs, parseSubmission: parse, parsePreparation, async invoke(credential, command) { const { recordId, ifMatch, input, idempotencyKey, signal } = command - const client = new Transport({ baseUrl: 'https://licences.test', token: () => credential, fetch: fetchProduct }) - const { data } = await client.call<{ recordId: string }>(renewal, { - query: { accessProfile: 'licence-holder' }, - body: { input: { licenceId: recordId, newExpiresOn: input.newExpiresOn }, preconditions: { licenceId: { ifMatch } } }, + const client = renewalClient(new Transport({ baseUrl: 'https://licences.test', token: () => credential, fetch: fetchProduct })) + const { data } = await client.invoke('renew', { licenceId: recordId, newExpiresOn: input.newExpiresOn }, { + accessProfile: 'licence-holder', preconditions: { licenceId: { ifMatch } }, idempotencyKey, signal, }) - return data + const receivedRecordId = data.results.licence?.recordId + if (!receivedRecordId) throw new Error('BReg returned no licence receipt.') + return { recordId: receivedRecordId } }, }, (...args) => { preparations.push(args) @@ -172,6 +221,41 @@ test('a preparation result outside its projection cannot substitute the target o assert.deepEqual(calls, []) }) +test('cancellation before preparation admits no preparation or Action dispatch', async () => { + const { handle, preparations, calls } = setup() + const response = await handle(request({ signal: AbortSignal.abort() })) + assert.equal(response.status, 502) + assert.deepEqual(preparations, []) + assert.deepEqual(calls, []) +}) + +test('cancellation during preparation returns without waiting for the result or dispatching an Action', { timeout: 3000 }, async t => { + const caller = new AbortController() + let finish: ((result: unknown) => void) | undefined + t.after(() => finish?.({ newExpiresOn })) + const { handle, preparations, calls } = setup(() => new Promise(resolve => { + finish = resolve + caller.abort() + }), { preparationTimeoutMs: 10_000 }) + assert.equal((await handle(request({ signal: caller.signal }))).status, 502) + assert.deepEqual(preparations, [[{ reviewedExpiresOn }]]) + finish?.({ newExpiresOn }) + await new Promise(resolve => setImmediate(resolve)) + assert.deepEqual(calls, []) +}) + +test('a late preparation result cannot dispatch an Action after the deadline', { timeout: 3000 }, async () => { + let finish: ((result: unknown) => void) | undefined + const { handle, preparations, calls } = setup(() => new Promise(resolve => { finish = resolve }), { + preparationTimeoutMs: 20, + }) + assert.equal((await handle(request())).status, 502) + assert.deepEqual(preparations, [[{ reviewedExpiresOn }]]) + finish?.({ newExpiresOn }) + await new Promise(resolve => setImmediate(resolve)) + assert.deepEqual(calls, []) +}) + test('a throwing submission parser returns a fixed refusal before preparation or BReg', async () => { const { handle, preparations, calls } = setup(prepareRenewal, { parse() { throw new Error('submitted values excluded from the reply') }, @@ -212,7 +296,7 @@ test('ambiguous request JSON is refused before the submission parser', async () assert.deepEqual(calls, []) }) -test('the owning product refuses a wrong subject, actor, role, client, audience, target, or condition', async () => { +test('synthetic product refusals for subject, actor, role, client, audience, target, or condition stay refusals', async () => { const { handle, calls, writes } = setup() const refusals = [ [request({ authorization: 'Bearer synthetic-other-subject' }), 412], @@ -256,24 +340,68 @@ test('a product refusal of the prepared value stays a refusal', async () => { assert.deepEqual(writes, []) }) -test('a product receipt for a different record leaves the original attempt unconfirmed', async () => { - const { handle, calls } = setup(prepareRenewal, { receiptRecordId: otherLicenceId }) - const response = await handle(request()) - assert.equal(response.status, 502) - assert.doesNotMatch(await response.text(), new RegExp(otherLicenceId, 'u')) - assert.equal(calls.length, 1) +test('a product receipt missing the exact record leaves the original attempt unresolved', async () => { + for (const receiptRecordId of [otherLicenceId, null]) { + const { handle, calls } = setup(prepareRenewal, { receiptRecordId }) + const response = await handle(request()) + assert.equal(response.status, 502) + assert.deepEqual(await response.json(), { + code: 'holder-action.outcome-unresolved', message: 'The Action outcome is unconfirmed. Keep the original attempt.', + }) + assert.equal(calls.length, 1) + assert.equal(calls[0]?.headers['idempotency-key'], idempotencyKey) + } }) -test('after a lost product receipt the same renewal prepares the same command and reads back one effect', async () => { +if (medicalOpenApi) { + test('the generated client refuses a receipt that names the exact record without the required revision', async () => { + const { handle, calls } = setup(prepareRenewal, { omitReceiptRevision: true }) + const response = await handle(request()) + assert.equal(response.status, 502) + assert.deepEqual(await response.json(), { + code: 'holder-action.outcome-unresolved', message: 'The Action outcome is unconfirmed. Keep the original attempt.', + }) + assert.equal(calls.length, 1) + }) +} + +test('after a lost product receipt the renewed holder credential reuses the same command and reads back one effect', async () => { const { handle, calls, preparations, writes } = setup(prepareRenewal, { loseFirstReceipt: true }) const first = await handle(request()) assert.equal(first.status, 502) assert.doesNotMatch(await first.text(), /Simulated/u) - const retry = await handle(request()) + const retry = await handle(request({ authorization: 'Bearer synthetic-holder-renewed' })) assert.equal(retry.status, 200) assert.deepEqual(await retry.json(), { recordId: licenceId }) assert.equal(calls.length, 2) - assert.deepEqual(calls[0], calls[1]) + const [firstCall, secondCall] = calls + assert.ok(firstCall && secondCall) + assert.equal(firstCall.headers.authorization, holderAuthorization) + assert.deepEqual(secondCall, { ...firstCall, headers: { ...firstCall.headers, authorization: 'Bearer synthetic-holder-renewed' } }) assert.deepEqual(preparations, [[{ reviewedExpiresOn }], [{ reviewedExpiresOn }]]) assert.deepEqual(writes, [licenceId]) }) + +test('a spent key leaves the original attempt unresolved without dispatching with a new key', async () => { + for (const [status, replayProblem] of [[409, 'idempotency.key-reused'], [410, 'idempotency.expired']] as const) { + const { handle, calls, writes } = setup(prepareRenewal, { loseFirstReceipt: true, replayProblem }) + const first = await handle(request()) + assert.equal(first.status, 502) + const retry = await handle(request({ authorization: 'Bearer synthetic-holder-renewed' })) + assert.equal(retry.status, status) + assert.deepEqual(await retry.json(), { + code: 'holder-action.outcome-unresolved', message: 'The Action outcome is unconfirmed. Keep the original attempt.', + }) + assert.deepEqual(calls.map(call => call.headers['idempotency-key']), [idempotencyKey, idempotencyKey]) + assert.deepEqual(writes, [licenceId]) + } +}) + +test('an ordinary product conflict keeps its refusal response', async () => { + const { handle, writes } = setup(prepareRenewal, { replayProblem: 'mutation.conflict' }) + assert.equal((await handle(request())).status, 200) + const conflict = await handle(request()) + assert.equal(conflict.status, 409) + assert.deepEqual(await conflict.json(), { message: 'BReg refused the request.' }) + assert.deepEqual(writes, [licenceId]) +}) From a27660dd12001f0cf9a0d61be2eaa71f6097931d Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 19:56:48 +0000 Subject: [PATCH 167/183] test(rstack): gate hard-coded holder applicant identity Signed-off-by: Jeremi Joslin --- .../typescript/tests/holder-function.test.ts | 24 ++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/clients/typescript/tests/holder-function.test.ts b/clients/typescript/tests/holder-function.test.ts index e92ee89eb3..dcf6b2d270 100644 --- a/clients/typescript/tests/holder-function.test.ts +++ b/clients/typescript/tests/holder-function.test.ts @@ -113,6 +113,7 @@ function setup(prepare: (input: { reviewedExpiresOn: string }) => unknown = prep const preparations: unknown[][] = [] const calls: { url: string; method: string | undefined; headers: Record; body: unknown }[] = [] const writes: string[] = [] + const verifiedApplicantIds: string[] = [] const committed = new Map() const fetchProduct: typeof fetch = async (target, options) => { @@ -150,6 +151,7 @@ function setup(prepare: (input: { reviewedExpiresOn: string }) => unknown = prep } committed.set(receiptKey, command) writes.push(body.input.licenceId) + verifiedApplicantIds.push(identity.holderRef) if (loseFirstReceipt && writes.length === 1) throw new Error('Simulated lost product receipt') return receipt() } @@ -175,7 +177,7 @@ function setup(prepare: (input: { reviewedExpiresOn: string }) => unknown = prep preparations.push(args) return prepare(...args) }) - return { handle, preparations, calls, writes } + return { handle, preparations, calls, writes, verifiedApplicantIds } } test('preparation receives one projected value and the checked Action receives the holder command', async () => { @@ -206,6 +208,7 @@ test('a missing caller or request outside the declared binding never reaches pre [request({ body: { ...submission, product: 'other' } }), 400], [request({ body: { ...submission, accessProfile: 'licence-officer' } }), 400], [request({ body: { ...submission, subject: 'other' } }), 400], + [request({ body: { ...submission, applicantId: 'holder-b' } }), 400], [request({ body: { ...submission, licenceId: licenceId.toUpperCase() } }), 400], [request({ key: 'wrong' }), 400], ] as const @@ -221,6 +224,25 @@ test('a preparation result outside its projection cannot substitute the target o assert.deepEqual(calls, []) }) +test('verified caller context replaces an applicant ID hard-coded by the preview function', { + todo: process.env.REGISTRY_HOLDER_REQUIRE_CALLER_CONTEXT !== '1' + && 'Awaiting the trusted Session caller-context binding. The local strict projection currently refuses this result.', +}, async () => { + const hardCodedApplicantId = 'holder-b' + const { handle, preparations, calls, writes, verifiedApplicantIds } = + setup(() => ({ newExpiresOn, applicantId: hardCodedApplicantId })) + + const result = await handle(request()) + assert.equal(result.status, 200) + assert.deepEqual(await result.json(), { recordId: licenceId }) + assert.deepEqual(preparations, [[{ reviewedExpiresOn }]]) + assert.equal(calls.length, 1) + assert.equal(calls[0]!.headers.authorization, holderAuthorization) + assert.deepEqual(calls[0]!.body, { input: { licenceId, newExpiresOn }, preconditions: { licenceId: { ifMatch } } }) + assert.deepEqual(verifiedApplicantIds, [holder.holderRef]) + assert.deepEqual(writes, [licenceId]) +}) + test('cancellation before preparation admits no preparation or Action dispatch', async () => { const { handle, preparations, calls } = setup() const response = await handle(request({ signal: AbortSignal.abort() })) From 79098d9fd4bab2d6940a956589f483e777f60930 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Wed, 2 Dec 2026 00:38:38 +0000 Subject: [PATCH 168/183] feat(rstack): bind holder preparation to one BReg create Action A holder binding now names its kind. A target binding keeps the reviewed shape: one existing Record, its reviewed condition, and a refusal when either is missing. A create binding is for an Action that makes one new Record, such as register-business: the submission names no target and no condition, and the command carries only the attempt key and the prepared input. The new Record's owner comes only from the verified caller. A page that names an owner is refused by the host's parser, and a function that hard-codes an owner or a record ID fails the strict preparation projection with no Action call. Only one new Record answers: the receipt must name a Record at its first revision, so an existing Record's revision or a missing receipt leaves the attempt unresolved, and a same-key retry returns the same Record. Cancellation, deadlines, product refusals and spent keys behave as for a target binding. The tests ran red against the target-only handler first. Signed-off-by: Jeremi Joslin --- clients/typescript/holder-function.ts | 99 +++++- .../tests/holder-function-create.test.ts | 288 ++++++++++++++++++ .../typescript/tests/holder-function.test.ts | 1 + 3 files changed, 375 insertions(+), 13 deletions(-) create mode 100644 clients/typescript/tests/holder-function-create.test.ts diff --git a/clients/typescript/holder-function.ts b/clients/typescript/holder-function.ts index d50ac23477..00d2872877 100644 --- a/clients/typescript/holder-function.ts +++ b/clients/typescript/holder-function.ts @@ -19,8 +19,9 @@ interface HolderCommand { signal: AbortSignal } -/** Host-owned parsing and invocation for one generated BReg Action and its fixed access profile. */ -interface HolderActionBinding { +/** Host-owned parsing and invocation for one generated BReg Action on one existing Record and its fixed access profile. */ +interface HolderTargetBinding { + kind: 'target' path: string preparationTimeoutMs: number parseSubmission: (body: unknown) => HolderSubmission | undefined @@ -28,6 +29,34 @@ interface HolderActionBinding invoke: (credential: string, command: HolderCommand) => Promise<{ recordId: string }> } +interface HolderCreateSubmission { + preparation: Preparation +} + +interface HolderCreateCommand { + idempotencyKey: string + input: Input + signal: AbortSignal +} + +/** + * Host-owned parsing and invocation for one generated BReg Action that creates one new Record. + * The submission names no target and no condition; the new Record's owner comes only from the + * verified caller, so neither the page nor the function can supply one. + */ +interface HolderCreateBinding { + kind: 'create' + path: string + preparationTimeoutMs: number + parseSubmission: (body: unknown) => HolderCreateSubmission | undefined + parsePreparation: (body: unknown) => Input | undefined + /** Returns the created Record and its revision from the generated receipt. */ + invoke: (credential: string, command: HolderCreateCommand) => Promise<{ recordId: string; revision: number }> +} + +type HolderActionBinding = + HolderTargetBinding | HolderCreateBinding + function reply(body: object, status: number): Response { return Response.json(body, { status, headers: { 'Cache-Control': 'no-store' } }) } @@ -107,11 +136,24 @@ async function prepareInTime(run: () => unknown, signal: AbortSignal, timeoutMs: } } +/** A product's own refusal, or an unresolved answer for a spent key; undefined for anything else. */ +function productRefusal(error: unknown): Response | undefined { + if (error instanceof RegistryError && error.kind === 'refused' && !error.outcomeUnknown && + error.status !== undefined && error.status >= 400 && error.status < 500) { + if (error.status === 409 && error.code === 'idempotency.key-reused' || + error.status === 410 && error.code === 'idempotency.expired') return unresolvedOutcome(error.status) + return reply({ message: 'BReg refused the request.' }, error.status) + } + return undefined +} + /** Use on the trusted invoker's gateway-only listener. Preparation must reproduce the same input on retry. */ export function createHolderActionHandler( - { path, preparationTimeoutMs, parseSubmission, parsePreparation, invoke }: HolderActionBinding, + binding: HolderActionBinding, prepare: (input: Preparation) => unknown | Promise, ): (request: Request) => Promise { + const { kind, path, preparationTimeoutMs, parsePreparation } = binding + if (kind !== 'target' && kind !== 'create') throw new TypeError('Expected a target or create holder binding.') if (!/^\/api\/functions\/[a-z][a-z0-9_-]{0,63}$/u.test(path)) throw new TypeError('Expected a declared function path.') if (!Number.isSafeInteger(preparationTimeoutMs) || preparationTimeoutMs < 1 || preparationTimeoutMs > 2_147_483_647) { throw new TypeError('Expected a bounded preparation deadline.') @@ -130,11 +172,46 @@ export function createHolderActionHandler | undefined + try { + if (body !== undefined) created = binding.parseSubmission(body) + } catch { + return reply({ message: 'Send a valid JSON request.' }, 400) + } + if (!created) return reply({ message: 'Send the declared request.' }, 400) + let input: Input | undefined + try { + input = parsePreparation(await prepareInTime(() => prepare(created.preparation), request.signal, preparationTimeoutMs)) + } catch { + return reply({ message: 'The function could not prepare the request.' }, 502) + } + if (!input || request.signal.aborted) return reply({ message: 'The function could not prepare the request.' }, 502) + try { + const result = await binding.invoke(credential, { idempotencyKey, input, signal: request.signal }) + // Only one new Record answers: a create's first revision. A same-key replay returns + // the same receipt, so the page keeps one attempt and one Record. + if (typeof result.recordId === 'string' && uuid.test(result.recordId) && result.revision === 1) { + return reply({ recordId: result.recordId }, 200) + } + } catch (error) { + const refusal = productRefusal(error) + if (refusal) return refusal + } + return unresolvedOutcome() + } + let submission: HolderSubmission | undefined try { - const body = await readSubmission(request) - if (body === bodyTooLarge) return reply({ message: 'The request is too large.' }, 413) - if (body !== undefined) submission = parseSubmission(body) + if (body !== undefined) submission = binding.parseSubmission(body) } catch { return reply({ message: 'Send a valid JSON request.' }, 400) } @@ -153,15 +230,11 @@ export function createHolderActionHandler= 400 && error.status < 500) { - if (error.status === 409 && error.code === 'idempotency.key-reused' || - error.status === 410 && error.code === 'idempotency.expired') return unresolvedOutcome(error.status) - return reply({ message: 'BReg refused the request.' }, error.status) - } + const refusal = productRefusal(error) + if (refusal) return refusal } return unresolvedOutcome() } diff --git a/clients/typescript/tests/holder-function-create.test.ts b/clients/typescript/tests/holder-function-create.test.ts new file mode 100644 index 0000000000..465116d272 --- /dev/null +++ b/clients/typescript/tests/holder-function-create.test.ts @@ -0,0 +1,288 @@ +import assert from 'node:assert/strict' +import test from 'node:test' +import { Transport, type CallOptions, type Operation } from '../core.ts' +import { createHolderActionHandler } from '../holder-function.ts' + +// A create-shaped holder binding: the Action makes one new Record, so the +// submission names no target and no condition. The owner of the new Record +// comes only from the verified caller, never from the page or the function. +const route = '/api/functions/register-business' +const idempotencyKey = '6c0e4c3d-1d0b-4c55-9d43-4ad2a3b3a1f7' +const registrarAuthorization = 'Bearer synthetic-registrar' +const traceId = '33333333333333333333333333333333' +const traceparent = `00-${traceId}-4444444444444444-01` +const submission = { legalName: ' Harbour Bicycle Cooperative ', registrationNumber: 'br-2026-001' } +const prepared = { legalName: 'Harbour Bicycle Cooperative', registrationNumber: 'BR-2026-001' } +const registrar = { subject: 'registrar-a', office: 'central', actor: 'human', client: 'business-registrar', + profile: 'business-registrar', audience: 'businesses' } +const identities = new Map([ + [registrarAuthorization, registrar], + ['Bearer synthetic-registrar-renewed', registrar], + ['Bearer synthetic-reader', { ...registrar, profile: 'business-status' }], + ['Bearer synthetic-other-audience', { ...registrar, audience: 'other' }], +]) + +const registration: Operation = { + method: 'POST', path: '/v1/actions/register-business', product: 'breg', + accessProfileParameter: true, accessProfileRequired: true, + keyed: true, mutating: true, requestMediaType: 'application/json', + problemValidators: { default: value => exactObject(value, ['code', 'detail', 'status', 'title', 'traceId', 'type']) }, + responses: { 200: [{ mode: 'json', mediaType: 'application/json' }] }, +} + +type RegistrationInput = { legalName: string; registrationNumber: string } +type RegistrationReceipt = { results: { business?: { recordId: string; revision: number } } } + +function exactObject(value: unknown, keys: readonly string[]): value is Record { + return value !== null && typeof value === 'object' && !Array.isArray(value) + && Object.keys(value).length === keys.length && keys.every(key => Object.hasOwn(value, key)) +} + +// Host-owned: the page sends only the two business fields. +function parseSubmission(value: unknown) { + if (!exactObject(value, ['legalName', 'registrationNumber']) || + typeof value.legalName !== 'string' || typeof value.registrationNumber !== 'string') return undefined + return { preparation: { legalName: value.legalName, registrationNumber: value.registrationNumber } } +} + +// Host-owned: the function may return only the Action's two inputs. +function parsePreparation(value: unknown) { + if (!exactObject(value, ['legalName', 'registrationNumber']) || + typeof value.legalName !== 'string' || typeof value.registrationNumber !== 'string') return undefined + return { legalName: value.legalName, registrationNumber: value.registrationNumber } +} + +// The declared function: a pure normalisation of what the page submitted. +function prepareRegistration({ legalName, registrationNumber }: RegistrationInput) { + return { legalName: legalName.trim(), registrationNumber: registrationNumber.trim().toUpperCase() } +} + +function request(options: { path?: string; method?: string; authorization?: string | null; body?: unknown; key?: string; signal?: AbortSignal } = {}) { + const { path = route, method = 'POST', authorization = registrarAuthorization, body = submission, key = idempotencyKey, signal } = options + const headers = new Headers({ + 'Content-Type': 'application/json', 'Idempotency-Key': key, + 'Registry-Client': 'page', Cookie: 'synthetic-cookie', 'X-Actor': 'synthetic-spoofed-actor', + }) + if (authorization !== null) headers.set('Authorization', authorization) + return new Request('https://service.test' + path, { + method, headers, body: method === 'GET' ? undefined : JSON.stringify(body), signal, + }) +} + +function setup(prepare: (input: RegistrationInput) => unknown = prepareRegistration, + { loseFirstReceipt = false, receiptRevision = 1, omitReceipt = false, replayProblem, preparationTimeoutMs = 1000 }: { + loseFirstReceipt?: boolean; receiptRevision?: number; omitReceipt?: boolean; preparationTimeoutMs?: number + replayProblem?: 'idempotency.key-reused' | 'idempotency.expired' + } = {}, +) { + const preparations: unknown[][] = [] + const calls: { url: string; headers: Record; body: unknown }[] = [] + // Each new Record and the owner BReg derived for it from the verified caller. + const records = new Map() + const committed = new Map() + let next = 0 + + const fetchProduct: typeof fetch = async (target, options) => { + const url = new URL(String(target)) + const headers = new Headers(options?.headers) + const body = JSON.parse(String(options?.body)) + calls.push({ url: url.href, headers: Object.fromEntries(headers), body }) + if (url.pathname !== registration.path || options?.method !== 'POST' || + url.searchParams.get('accessProfile') !== 'business-registrar') { + throw new Error('The caller changed the checked Action contract.') + } + const refuse = (status: number, code: string) => Response.json({ + status, code, detail: 'product-only detail', title: 'BReg refused the request.', traceId, + type: 'https://id.registrystack.org/problems/registry-breg/' + code.replaceAll('.', '/'), + }, { status, headers: { 'Content-Type': 'application/problem+json', 'Cache-Control': 'no-store', traceparent } }) + const receipt = (recordId: string) => Response.json({ action: 'register-business', applicationId: idempotencyKey, + results: omitReceipt ? {} : { business: { recordId, recordType: 'business', revision: receiptRevision } }, + }, { headers: { 'Cache-Control': 'no-store', traceparent } }) + const identity = identities.get(headers.get('authorization') ?? '') + if (!identity || identity.audience !== 'businesses') return refuse(401, 'authentication.refused') + if (identity.profile !== 'business-registrar') return refuse(403, 'profile.not-authorized') + if (!exactObject(body, ['input']) || !exactObject(body.input, ['legalName', 'registrationNumber'])) { + return refuse(400, 'request.invalid') + } + const receiptKey = identity.subject + ':' + headers.get('idempotency-key') + const command = JSON.stringify(body) + const earlier = committed.get(receiptKey) + if (earlier) { + if (replayProblem) return refuse(replayProblem === 'idempotency.expired' ? 410 : 409, replayProblem) + if (earlier.command !== command) return refuse(409, 'idempotency.key-reused') + return receipt(earlier.recordId) + } + const recordId = `00000000-0000-4000-8000-${String(++next).padStart(12, '0')}` + committed.set(receiptKey, { command, recordId }) + // BReg derives the owner from the verified credential, never from input. + records.set(recordId, { + owner: identity.office, + input: { legalName: String(body.input.legalName), registrationNumber: String(body.input.registrationNumber) }, + }) + if (loseFirstReceipt && calls.length === 1) { + throw new Error('Simulated lost product receipt') + } + return receipt(recordId) + } + + const handle = createHolderActionHandler({ + kind: 'create', + path: route, + preparationTimeoutMs, + parseSubmission, + parsePreparation, + async invoke(credential, { input, idempotencyKey, signal }) { + const transport = new Transport({ baseUrl: 'https://businesses.test', token: () => credential, fetch: fetchProduct }) + const { data } = await transport.call(registration, { + idempotencyKey, signal, query: { accessProfile: 'business-registrar' }, body: { input }, + } as CallOptions & { query: Record; body: unknown }) + const business = data.results.business + if (!business) throw new Error('BReg returned no business receipt.') + return { recordId: business.recordId, revision: business.revision } + }, + }, (...args) => { + preparations.push(args) + return prepare(...args) + }) + return { handle, preparations, calls, records } +} + +test('a create binding prepares the projected value and invokes the Action with no target or condition', async () => { + const { handle, preparations, calls, records } = setup() + const result = await handle(request()) + assert.equal(result.status, 200) + const { recordId } = await result.json() as { recordId: string } + assert.deepEqual(preparations, [[submission]]) + assert.equal(calls.length, 1) + const call = calls[0]! + assert.equal(call.url, 'https://businesses.test/v1/actions/register-business?accessProfile=business-registrar') + assert.equal(call.headers.authorization, registrarAuthorization) + assert.equal(call.headers['idempotency-key'], idempotencyKey) + for (const header of ['cookie', 'registry-client', 'x-actor']) assert.equal(call.headers[header], undefined) + assert.deepEqual(call.body, { input: prepared }) + assert.deepEqual([...records], [[recordId, { owner: 'central', input: prepared }]]) +}) + +test('a create binding owner comes only from the verified caller', async () => { + // A page that names an owner is refused before preparation. + const named = setup() + const refused = await named.handle(request({ body: { ...submission, registeringOffice: 'north' } })) + assert.equal(refused.status, 400) + assert.equal(named.preparations.length, 0) + assert.equal(named.calls.length, 0) + + // A function that hard-codes an owner or a record ID cannot reach BReg. + for (const extra of [{ registeringOffice: 'north' }, { recordId: '00000000-0000-4000-8000-000000000999' }]) { + const hardCoded = setup(input => ({ ...prepareRegistration(input), ...extra })) + const answer = await hardCoded.handle(request()) + assert.equal(answer.status, 502, JSON.stringify(extra)) + assert.equal(hardCoded.calls.length, 0, JSON.stringify(extra)) + assert.equal(hardCoded.records.size, 0, JSON.stringify(extra)) + } +}) + +test('a create binding refuses a request outside the declared binding before preparation or BReg', async () => { + for (const options of [ + { path: '/api/functions/other' }, { path: route + '?accessProfile=admin' }, { method: 'PUT' }, + { authorization: null }, { authorization: 'Basic synthetic' }, { key: 'not-a-key' }, + { body: { legalName: 'Only a name' } }, { body: [submission] }, + ]) { + const { handle, preparations, calls } = setup() + const answer = await handle(request(options)) + assert.ok(answer.status >= 400 && answer.status < 500, `${JSON.stringify(options)}: ${answer.status}`) + assert.equal(preparations.length, 0, JSON.stringify(options)) + assert.equal(calls.length, 0, JSON.stringify(options)) + } +}) + +test('a create binding answers only for one new Record', async () => { + // An existing Record's revision, or no Record, leaves the attempt unresolved. + for (const options of [{ receiptRevision: 2 }, { omitReceipt: true }]) { + const { handle } = setup(prepareRegistration, options) + const answer = await handle(request()) + assert.equal(answer.status, 502, JSON.stringify(options)) + assert.equal((await answer.json() as { code: string }).code, 'holder-action.outcome-unresolved') + } +}) + +test('a create binding retry after a lost receipt returns the same new Record once', async () => { + const { handle, calls, records } = setup(prepareRegistration, { loseFirstReceipt: true }) + const first = await handle(request()) + assert.equal(first.status, 502) + assert.equal((await first.json() as { code: string }).code, 'holder-action.outcome-unresolved') + const retried = await handle(request({ authorization: 'Bearer synthetic-registrar-renewed' })) + assert.equal(retried.status, 200) + const { recordId } = await retried.json() as { recordId: string } + assert.deepEqual([...records.keys()], [recordId]) + assert.equal(calls.length, 2) + assert.deepEqual(calls[1]!.body, calls[0]!.body) + assert.equal(calls[1]!.headers['idempotency-key'], calls[0]!.headers['idempotency-key']) +}) + +test('a create binding keeps a spent key unresolved', async () => { + for (const replayProblem of ['idempotency.key-reused', 'idempotency.expired'] as const) { + const { handle, records } = setup(prepareRegistration, { replayProblem }) + assert.equal((await handle(request())).status, 200) + const replay = await handle(request()) + assert.equal(replay.status, replayProblem === 'idempotency.expired' ? 410 : 409) + assert.equal((await replay.json() as { code: string }).code, 'holder-action.outcome-unresolved') + assert.equal(records.size, 1) + } +}) + +test('a create binding product refusal stays a refusal', async () => { + for (const [authorization, status] of [['Bearer synthetic-reader', 403], ['Bearer synthetic-other-audience', 401]] as const) { + const { handle, records } = setup() + const answer = await handle(request({ authorization })) + assert.equal(answer.status, status) + assert.equal(records.size, 0) + } +}) + +test('cancellation before or during a create preparation makes no Action call', { timeout: 3000 }, async () => { + const early = setup() + const aborted = new AbortController() + aborted.abort() + assert.equal((await early.handle(request({ signal: aborted.signal }))).status, 502) + assert.equal(early.preparations.length, 0) + assert.equal(early.calls.length, 0) + + let release!: (value: unknown) => void + const pending = setup(() => new Promise(resolve => { release = resolve })) + const during = new AbortController() + const answer = pending.handle(request({ signal: during.signal })) + while (pending.preparations.length === 0) await new Promise(resolve => setImmediate(resolve)) + during.abort() + assert.equal((await answer).status, 502) + release(prepared) + await new Promise(resolve => setImmediate(resolve)) + assert.equal(pending.calls.length, 0) + assert.equal(pending.records.size, 0) +}) + +test('a binding names its kind, and a target binding still needs its target and condition', () => { + const common = { + path: route, preparationTimeoutMs: 1000, parseSubmission, parsePreparation, + async invoke() { return { recordId: '00000000-0000-4000-8000-000000000001', revision: 1 } }, + } + for (const kind of [undefined, 'update', 'Create']) { + assert.throws(() => createHolderActionHandler({ ...common, kind } as never, prepareRegistration), + /Expected a target or create holder binding/u, String(kind)) + } +}) + +test('a target binding refuses a submission without its target and condition', async () => { + let invoked = 0 + const handle = createHolderActionHandler({ + kind: 'target', path: route, preparationTimeoutMs: 1000, parsePreparation, + // A target parser that drops the target: the handler must still refuse. + parseSubmission: value => parseSubmission(value) as never, + async invoke() { + invoked += 1 + return { recordId: '00000000-0000-4000-8000-000000000001' } + }, + }, prepareRegistration) + const answer = await handle(request()) + assert.equal(answer.status, 400) + assert.equal(invoked, 0) +}) diff --git a/clients/typescript/tests/holder-function.test.ts b/clients/typescript/tests/holder-function.test.ts index dcf6b2d270..cd578b224c 100644 --- a/clients/typescript/tests/holder-function.test.ts +++ b/clients/typescript/tests/holder-function.test.ts @@ -157,6 +157,7 @@ function setup(prepare: (input: { reviewedExpiresOn: string }) => unknown = prep } const handle = createHolderActionHandler({ + kind: 'target', path: route, preparationTimeoutMs, parseSubmission: parse, From 93721524fc37ee64eae3da906d06d9a280746a7e Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Wed, 2 Dec 2026 00:41:14 +0000 Subject: [PATCH 169/183] test(rstack): model register-business's planned office in the create binding proof Fold Lane 1's review of 1c7231d5c. The register-business plan fixes the new business's registering office, and BReg's Action target row boundary refuses a registrar from another office. The synthetic product now does the same: it plans the office and refuses a north registrar with no Record, which a new case covers. The earlier wording that BReg derives the owner from the caller's credential overclaimed. Neither the page nor the function can name the owner; the Action decides it. The receipt comment now says what revision 1 proves: the Record has not changed since it was created. BReg's idempotency per subject and key gives the single effect. Signed-off-by: Jeremi Joslin --- clients/typescript/holder-function.ts | 9 ++++---- .../tests/holder-function-create.test.ts | 22 ++++++++++++++----- 2 files changed, 21 insertions(+), 10 deletions(-) diff --git a/clients/typescript/holder-function.ts b/clients/typescript/holder-function.ts index 00d2872877..df03ec7d48 100644 --- a/clients/typescript/holder-function.ts +++ b/clients/typescript/holder-function.ts @@ -41,8 +41,8 @@ interface HolderCreateCommand { /** * Host-owned parsing and invocation for one generated BReg Action that creates one new Record. - * The submission names no target and no condition; the new Record's owner comes only from the - * verified caller, so neither the page nor the function can supply one. + * The submission names no target and no condition, and neither the page nor the function can + * name the new Record's owner: the Action's own plan and row boundaries decide it. */ interface HolderCreateBinding { kind: 'create' @@ -197,8 +197,9 @@ export function createHolderActionHandler unknown = prepareRegistrat if (earlier.command !== command) return refuse(409, 'idempotency.key-reused') return receipt(earlier.recordId) } + // The plan fixes the office; the row boundary refuses a caller from another office. + if (identity.office !== plannedOffice) return refuse(403, 'action.target-not-authorized') const recordId = `00000000-0000-4000-8000-${String(++next).padStart(12, '0')}` committed.set(receiptKey, { command, recordId }) - // BReg derives the owner from the verified credential, never from input. records.set(recordId, { - owner: identity.office, + owner: plannedOffice, input: { legalName: String(body.input.legalName), registrationNumber: String(body.input.registrationNumber) }, }) if (loseFirstReceipt && calls.length === 1) { @@ -163,7 +169,7 @@ test('a create binding prepares the projected value and invokes the Action with assert.deepEqual([...records], [[recordId, { owner: 'central', input: prepared }]]) }) -test('a create binding owner comes only from the verified caller', async () => { +test('neither the page nor the function can name the owner of a created Record', async () => { // A page that names an owner is refused before preparation. const named = setup() const refused = await named.handle(request({ body: { ...submission, registeringOffice: 'north' } })) @@ -231,7 +237,11 @@ test('a create binding keeps a spent key unresolved', async () => { }) test('a create binding product refusal stays a refusal', async () => { - for (const [authorization, status] of [['Bearer synthetic-reader', 403], ['Bearer synthetic-other-audience', 401]] as const) { + for (const [authorization, status] of [ + ['Bearer synthetic-reader', 403], ['Bearer synthetic-other-audience', 401], + // A registrar outside the planned office: the Action target's row boundary refuses it. + ['Bearer synthetic-north-registrar', 403], + ] as const) { const { handle, records } = setup() const answer = await handle(request({ authorization })) assert.equal(answer.status, status) From 832192119125e8ecbd35594008c029e015da1956 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Wed, 2 Dec 2026 00:43:47 +0000 Subject: [PATCH 170/183] test(rstack): answer a north create with the native 412 precondition.failed Lane 1's native witness on the business-registration project shows the row policy's check on the Action target's row boundary refusing a north registrar's register-business create with 412 precondition.failed, not 403. The synthetic product now answers the same. Signed-off-by: Jeremi Joslin --- clients/typescript/tests/holder-function-create.test.ts | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/clients/typescript/tests/holder-function-create.test.ts b/clients/typescript/tests/holder-function-create.test.ts index 42dc889b28..95a1c50209 100644 --- a/clients/typescript/tests/holder-function-create.test.ts +++ b/clients/typescript/tests/holder-function-create.test.ts @@ -117,8 +117,9 @@ function setup(prepare: (input: RegistrationInput) => unknown = prepareRegistrat if (earlier.command !== command) return refuse(409, 'idempotency.key-reused') return receipt(earlier.recordId) } - // The plan fixes the office; the row boundary refuses a caller from another office. - if (identity.office !== plannedOffice) return refuse(403, 'action.target-not-authorized') + // The plan fixes the office. Natively, the row policy's check on the Action target's row + // boundary refuses the insert for a caller from another office with 412 precondition.failed. + if (identity.office !== plannedOffice) return refuse(412, 'precondition.failed') const recordId = `00000000-0000-4000-8000-${String(++next).padStart(12, '0')}` committed.set(receiptKey, { command, recordId }) records.set(recordId, { @@ -240,7 +241,7 @@ test('a create binding product refusal stays a refusal', async () => { for (const [authorization, status] of [ ['Bearer synthetic-reader', 403], ['Bearer synthetic-other-audience', 401], // A registrar outside the planned office: the Action target's row boundary refuses it. - ['Bearer synthetic-north-registrar', 403], + ['Bearer synthetic-north-registrar', 412], ] as const) { const { handle, records } = setup() const answer = await handle(request({ authorization })) From 20139729a75b9cd4a5e14fe3757ffe7317e92e72 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Wed, 2 Dec 2026 00:48:46 +0000 Subject: [PATCH 171/183] fix(rstack): fold the holder binding high review The high review of 771cfe211..1c7231d5c found no P1. This folds its P2s and P3s, tests first. - P2-1: the doc comment says what the binding gives. It minimises the arguments prepare receives, but prepare runs in the invoker's process and can reach what that process can, including the next caller's request. Use it only for trusted, reviewed function code, and run unreviewed functions outside the invoker's process. - P2-2: the handler is stateless, so a refused same-key retry after an unresolved attempt reads as an ordinary refusal. The doc comment states the keep-the-key rule, and a test shows that a page keeping the key through an expired-sign-in refusal ends with one Record. - P2-3: the hard-coded applicant TODO is now a test that pins the refusal: 502 and no Action call. - P3: prepare receives a signal that follows the caller and the deadline. The binding's kind, parsers and invoke are read once at construction. Attempt keys are lowercased before forwarding. New tests cover a create receipt naming a non-UUID record, a synchronous deadline overrun, timer and listener cleanup, prepare receiving the host projection rather than the raw body, and the caller signal reaching invoke and prepare. Tests written after the existing code were proven by mutation: keeping the abort listener, forwarding the key unlowercased, and reading the kind late each fail their test. Signed-off-by: Jeremi Joslin --- clients/typescript/holder-function.ts | 47 +++++-- .../tests/holder-function-create.test.ts | 118 ++++++++++++++++-- .../typescript/tests/holder-function.test.ts | 32 ++--- 3 files changed, 157 insertions(+), 40 deletions(-) diff --git a/clients/typescript/holder-function.ts b/clients/typescript/holder-function.ts index df03ec7d48..3fd6691c04 100644 --- a/clients/typescript/holder-function.ts +++ b/clients/typescript/holder-function.ts @@ -113,7 +113,7 @@ async function readSubmission(request: Request): Promise { } } -async function prepareInTime(run: () => unknown, signal: AbortSignal, timeoutMs: number): Promise { +async function prepareInTime(run: (signal: AbortSignal) => unknown, signal: AbortSignal, timeoutMs: number): Promise { signal.throwIfAborted() const deadlineAt = performance.now() + timeoutMs const expired = new Error('The preparation deadline expired.') @@ -123,9 +123,12 @@ async function prepareInTime(run: () => unknown, signal: AbortSignal, timeoutMs: signal.addEventListener('abort', abort, { once: true }) const timer = setTimeout(() => stop(expired), timeoutMs) try { + // The preparation's own signal follows the caller and the deadline, so cooperative code + // can stop early; the race below does not depend on it. + const preparationSignal = AbortSignal.any([signal, AbortSignal.timeout(timeoutMs)]) const result = await Promise.race([stopped, Promise.resolve().then(() => { signal.throwIfAborted() - return run() + return run(preparationSignal) })]) signal.throwIfAborted() if (performance.now() >= deadlineAt) throw expired @@ -147,13 +150,29 @@ function productRefusal(error: unknown): Response | undefined { return undefined } -/** Use on the trusted invoker's gateway-only listener. Preparation must reproduce the same input on retry. */ +/** + * Use on the trusted invoker's gateway-only listener. Preparation must reproduce the same input on retry. + * + * The binding minimises the arguments `prepare` receives: one projected value and a signal, never the + * Request, a header, the caller's credential or a product client. It does not isolate `prepare`. The + * callback runs in the invoker's process, so code there can reach whatever that process can, including + * the next caller's request. Use it only for trusted, reviewed function code, and run unreviewed + * functions outside the invoker's process. + * + * An unresolved answer (`holder-action.outcome-unresolved`) means the product may have acted. The page + * must keep the original attempt key and body until a matching receipt arrives, even through an + * ordinary refusal of a retry such as an expired sign-in: the handler is stateless and cannot tell + * such a refusal apart from one on a fresh attempt, and a new key can create a second Record. + */ export function createHolderActionHandler( binding: HolderActionBinding, - prepare: (input: Preparation) => unknown | Promise, + prepare: (input: Preparation, options: { signal: AbortSignal }) => unknown | Promise, ): (request: Request) => Promise { + // Read the binding once: later changes to the object it came from have no effect. const { kind, path, preparationTimeoutMs, parsePreparation } = binding if (kind !== 'target' && kind !== 'create') throw new TypeError('Expected a target or create holder binding.') + const target = kind === 'target' ? { parseSubmission: binding.parseSubmission, invoke: binding.invoke } : undefined + const create = binding.kind === 'create' ? { parseSubmission: binding.parseSubmission, invoke: binding.invoke } : undefined if (!/^\/api\/functions\/[a-z][a-z0-9_-]{0,63}$/u.test(path)) throw new TypeError('Expected a declared function path.') if (!Number.isSafeInteger(preparationTimeoutMs) || preparationTimeoutMs < 1 || preparationTimeoutMs > 2_147_483_647) { throw new TypeError('Expected a bounded preparation deadline.') @@ -167,9 +186,9 @@ export function createHolderActionHandler | undefined try { - if (body !== undefined) created = binding.parseSubmission(body) + if (body !== undefined) created = create.parseSubmission(body) } catch { return reply({ message: 'Send a valid JSON request.' }, 400) } if (!created) return reply({ message: 'Send the declared request.' }, 400) let input: Input | undefined try { - input = parsePreparation(await prepareInTime(() => prepare(created.preparation), request.signal, preparationTimeoutMs)) + input = parsePreparation(await prepareInTime( + signal => prepare(created.preparation, { signal }), request.signal, preparationTimeoutMs)) } catch { return reply({ message: 'The function could not prepare the request.' }, 502) } if (!input || request.signal.aborted) return reply({ message: 'The function could not prepare the request.' }, 502) try { - const result = await binding.invoke(credential, { idempotencyKey, input, signal: request.signal }) + const result = await create.invoke(credential, { idempotencyKey, input, signal: request.signal }) // A Record at its first revision answers. Revision 1 shows the Record has not changed // since it was created, not that this attempt created it: BReg's idempotency per subject // and key gives the single effect, and a same-key replay returns the same receipt. @@ -212,7 +232,7 @@ export function createHolderActionHandler | undefined try { - if (body !== undefined) submission = binding.parseSubmission(body) + if (body !== undefined) submission = target!.parseSubmission(body) } catch { return reply({ message: 'Send a valid JSON request.' }, 400) } @@ -224,14 +244,15 @@ export function createHolderActionHandler prepare(preparation), request.signal, preparationTimeoutMs)) + input = parsePreparation(await prepareInTime( + signal => prepare(preparation, { signal }), request.signal, preparationTimeoutMs)) } catch { return reply({ message: 'The function could not prepare the request.' }, 502) } if (!input || request.signal.aborted) return reply({ message: 'The function could not prepare the request.' }, 502) try { - const result = await binding.invoke(credential, { recordId, ifMatch, idempotencyKey, input, signal: request.signal }) + const result = await target!.invoke(credential, { recordId, ifMatch, idempotencyKey, input, signal: request.signal }) if (result.recordId === recordId) return reply({ recordId }, 200) } catch (error) { const refusal = productRefusal(error) diff --git a/clients/typescript/tests/holder-function-create.test.ts b/clients/typescript/tests/holder-function-create.test.ts index 95a1c50209..a120113a35 100644 --- a/clients/typescript/tests/holder-function-create.test.ts +++ b/clients/typescript/tests/holder-function-create.test.ts @@ -75,12 +75,16 @@ function request(options: { path?: string; method?: string; authorization?: stri } function setup(prepare: (input: RegistrationInput) => unknown = prepareRegistration, - { loseFirstReceipt = false, receiptRevision = 1, omitReceipt = false, replayProblem, preparationTimeoutMs = 1000 }: { + { loseFirstReceipt = false, receiptRevision = 1, omitReceipt = false, replayProblem, preparationTimeoutMs = 1000, + receiptRecordId, parse = parseSubmission }: { loseFirstReceipt?: boolean; receiptRevision?: number; omitReceipt?: boolean; preparationTimeoutMs?: number - replayProblem?: 'idempotency.key-reused' | 'idempotency.expired' + replayProblem?: 'idempotency.key-reused' | 'idempotency.expired'; receiptRecordId?: string + parse?: (value: unknown) => { preparation: RegistrationInput } | undefined } = {}, ) { const preparations: unknown[][] = [] + const preparationSignals: AbortSignal[] = [] + const invokeSignals: AbortSignal[] = [] const calls: { url: string; headers: Record; body: unknown }[] = [] // Each new Record and the owner BReg derived for it from the verified caller. const records = new Map() @@ -101,7 +105,7 @@ function setup(prepare: (input: RegistrationInput) => unknown = prepareRegistrat type: 'https://id.registrystack.org/problems/registry-breg/' + code.replaceAll('.', '/'), }, { status, headers: { 'Content-Type': 'application/problem+json', 'Cache-Control': 'no-store', traceparent } }) const receipt = (recordId: string) => Response.json({ action: 'register-business', applicationId: idempotencyKey, - results: omitReceipt ? {} : { business: { recordId, recordType: 'business', revision: receiptRevision } }, + results: omitReceipt ? {} : { business: { recordId: receiptRecordId ?? recordId, recordType: 'business', revision: receiptRevision } }, }, { headers: { 'Cache-Control': 'no-store', traceparent } }) const identity = identities.get(headers.get('authorization') ?? '') if (!identity || identity.audience !== 'businesses') return refuse(401, 'authentication.refused') @@ -136,9 +140,10 @@ function setup(prepare: (input: RegistrationInput) => unknown = prepareRegistrat kind: 'create', path: route, preparationTimeoutMs, - parseSubmission, + parseSubmission: parse, parsePreparation, async invoke(credential, { input, idempotencyKey, signal }) { + invokeSignals.push(signal) const transport = new Transport({ baseUrl: 'https://businesses.test', token: () => credential, fetch: fetchProduct }) const { data } = await transport.call(registration, { idempotencyKey, signal, query: { accessProfile: 'business-registrar' }, body: { input }, @@ -147,11 +152,12 @@ function setup(prepare: (input: RegistrationInput) => unknown = prepareRegistrat if (!business) throw new Error('BReg returned no business receipt.') return { recordId: business.recordId, revision: business.revision } }, - }, (...args) => { - preparations.push(args) - return prepare(...args) + }, (value, options) => { + preparations.push([value]) + preparationSignals.push(options.signal) + return prepare(value) }) - return { handle, preparations, calls, records } + return { handle, preparations, preparationSignals, invokeSignals, calls, records } } test('a create binding prepares the projected value and invokes the Action with no target or condition', async () => { @@ -297,3 +303,99 @@ test('a target binding refuses a submission without its target and condition', a assert.equal(answer.status, 400) assert.equal(invoked, 0) }) + +test('keeping the attempt key through a refused retry leaves one Record', async () => { + // A lost receipt leaves the attempt unresolved. A retry with an expired credential is an + // ordinary refusal, which the handler cannot tell apart statelessly. A page that keeps the + // original key and body, as the binding documents, still ends with one Record. + const { handle, records } = setup(prepareRegistration, { loseFirstReceipt: true }) + assert.equal((await handle(request())).status, 502) + assert.equal((await handle(request({ authorization: 'Bearer synthetic-expired' }))).status, 401) + const retried = await handle(request({ authorization: 'Bearer synthetic-registrar-renewed' })) + assert.equal(retried.status, 200) + assert.deepEqual([...records.keys()], [(await retried.json() as { recordId: string }).recordId]) +}) + +test('a create receipt naming a record that is not a UUID leaves the attempt unresolved', async () => { + const { handle } = setup(prepareRegistration, { receiptRecordId: 'not-a-record' }) + const answer = await handle(request()) + assert.equal(answer.status, 502) + assert.equal((await answer.json() as { code: string }).code, 'holder-action.outcome-unresolved') +}) + +test('a synchronous preparation that overruns its deadline makes no Action call', async () => { + const { handle, calls } = setup(input => { + const until = performance.now() + 40 + while (performance.now() < until) { /* busy */ } + return prepareRegistration(input) + }, { preparationTimeoutMs: 10 }) + assert.equal((await handle(request())).status, 502) + assert.equal(calls.length, 0) +}) + +test('the preparation deadline removes its timer and abort listener', async () => { + const controller = new AbortController() + const signal = controller.signal + let added = 0 + let removed = 0 + const addEventListener = signal.addEventListener.bind(signal) + const removeEventListener = signal.removeEventListener.bind(signal) + signal.addEventListener = ((...args: Parameters) => { + if (args[0] === 'abort') added += 1 + return addEventListener(...args) + }) as typeof signal.addEventListener + signal.removeEventListener = ((...args: Parameters) => { + if (args[0] === 'abort') removed += 1 + return removeEventListener(...args) + }) as typeof signal.removeEventListener + // A long deadline: a timer left behind would keep the test process alive. + const { handle } = setup(prepareRegistration, { preparationTimeoutMs: 600_000 }) + // The handler reads the caller's signal from the Request; hand it the spied one. + class SpiedRequest extends Request { + override get signal() { return signal } + } + const answer = await handle(new SpiedRequest(request())) + assert.equal(answer.status, 200) + assert.ok(added >= 1) + assert.equal(removed, added) +}) + +test('a create preparation receives the host projection, not the raw body', async () => { + // A host parser that admits a note the function does not need, and drops it. + const parse = (value: unknown) => { + if (!exactObject(value, ['legalName', 'registrationNumber', 'note']) || + typeof value.legalName !== 'string' || typeof value.registrationNumber !== 'string') return undefined + return { preparation: { legalName: value.legalName, registrationNumber: value.registrationNumber } } + } + const { handle, preparations } = setup(prepareRegistration, { parse }) + assert.equal((await handle(request({ body: { ...submission, note: 'not for the function' } }))).status, 200) + assert.deepEqual(preparations, [[submission]]) +}) + +test('the caller signal reaches the Action call and the preparation', async () => { + const controller = new AbortController() + const { handle, invokeSignals, preparationSignals } = setup() + assert.equal((await handle(request({ signal: controller.signal }))).status, 200) + assert.equal(invokeSignals.length, 1) + assert.equal(preparationSignals.length, 1) + controller.abort() + assert.equal(invokeSignals[0]!.aborted, true) + assert.equal(preparationSignals[0]!.aborted, true) +}) + +test('the attempt key is forwarded in lower case', async () => { + const { handle, calls } = setup() + assert.equal((await handle(request({ key: idempotencyKey.toUpperCase() }))).status, 200) + assert.equal(calls[0]!.headers['idempotency-key'], idempotencyKey) +}) + +test('a binding kind changed after construction has no effect', async () => { + const binding = { + kind: 'create' as 'create' | 'target', path: route, preparationTimeoutMs: 1000, parseSubmission, parsePreparation, + async invoke() { return { recordId: '00000000-0000-4000-8000-000000000001', revision: 1 } }, + } + const handle = createHolderActionHandler(binding as never, prepareRegistration) + binding.kind = 'target' + const answer = await handle(request()) + assert.equal(answer.status, 200) +}) diff --git a/clients/typescript/tests/holder-function.test.ts b/clients/typescript/tests/holder-function.test.ts index cd578b224c..086b778b28 100644 --- a/clients/typescript/tests/holder-function.test.ts +++ b/clients/typescript/tests/holder-function.test.ts @@ -111,6 +111,7 @@ function setup(prepare: (input: { reviewedExpiresOn: string }) => unknown = prep replayProblem?: 'idempotency.key-reused' | 'idempotency.expired' | 'mutation.conflict' } = {}, ) { const preparations: unknown[][] = [] + const preparationSignals: AbortSignal[] = [] const calls: { url: string; method: string | undefined; headers: Record; body: unknown }[] = [] const writes: string[] = [] const verifiedApplicantIds: string[] = [] @@ -174,11 +175,12 @@ function setup(prepare: (input: { reviewedExpiresOn: string }) => unknown = prep if (!receivedRecordId) throw new Error('BReg returned no licence receipt.') return { recordId: receivedRecordId } }, - }, (...args) => { - preparations.push(args) - return prepare(...args) + }, (value, options) => { + preparations.push([value]) + preparationSignals.push(options.signal) + return prepare(value) }) - return { handle, preparations, calls, writes, verifiedApplicantIds } + return { handle, preparations, preparationSignals, calls, writes, verifiedApplicantIds } } test('preparation receives one projected value and the checked Action receives the holder command', async () => { @@ -225,23 +227,15 @@ test('a preparation result outside its projection cannot substitute the target o assert.deepEqual(calls, []) }) -test('verified caller context replaces an applicant ID hard-coded by the preview function', { - todo: process.env.REGISTRY_HOLDER_REQUIRE_CALLER_CONTEXT !== '1' - && 'Awaiting the trusted Session caller-context binding. The local strict projection currently refuses this result.', -}, async () => { - const hardCodedApplicantId = 'holder-b' - const { handle, preparations, calls, writes, verifiedApplicantIds } = - setup(() => ({ newExpiresOn, applicantId: hardCodedApplicantId })) - +test('a preparation result naming an applicant is refused before BReg', async () => { + // The function cannot choose the person: an applicant ID it hard-codes fails the + // strict projection, so no Action is dispatched and BReg keeps the holder's authority. + const { handle, preparations, calls, writes } = setup(() => ({ newExpiresOn, applicantId: 'holder-b' })) const result = await handle(request()) - assert.equal(result.status, 200) - assert.deepEqual(await result.json(), { recordId: licenceId }) + assert.equal(result.status, 502) assert.deepEqual(preparations, [[{ reviewedExpiresOn }]]) - assert.equal(calls.length, 1) - assert.equal(calls[0]!.headers.authorization, holderAuthorization) - assert.deepEqual(calls[0]!.body, { input: { licenceId, newExpiresOn }, preconditions: { licenceId: { ifMatch } } }) - assert.deepEqual(verifiedApplicantIds, [holder.holderRef]) - assert.deepEqual(writes, [licenceId]) + assert.deepEqual(calls, []) + assert.deepEqual(writes, []) }) test('cancellation before preparation admits no preparation or Action dispatch', async () => { From 6db4ad05b81b032547f84fe8bbe6267d1a66269a Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Wed, 2 Dec 2026 00:49:44 +0000 Subject: [PATCH 172/183] feat(client): export the holder binding for trusted hosts Add one subpath export, @registrystack/client/holder-function, to the existing @registrystack/client package. It adds no new npm package name. A trusted host uses createHolderActionHandler to invoke one generated BReg Action for a signed-in person, with a declared function that only prepares the input. The export is pre-1.0. The README states its limits: the binding minimises the function's arguments but does not isolate it, so it suits trusted, reviewed function code only. A created Record's owner comes from the host's parser and the BReg Action, and an unresolved answer must keep the original attempt key and body. The package test pins the export and imports the built module. Signed-off-by: Jeremi Joslin --- clients/typescript/README.md | 30 ++++++++++++++++++++++++ clients/typescript/package.json | 4 ++++ clients/typescript/tests/package.test.ts | 9 +++++++ clients/typescript/tsconfig.browser.json | 2 +- products/platform/CHANGELOG.md | 1 + 5 files changed, 45 insertions(+), 1 deletion(-) diff --git a/clients/typescript/README.md b/clients/typescript/README.md index 50d531777a..69355304b8 100644 --- a/clients/typescript/README.md +++ b/clients/typescript/README.md @@ -344,6 +344,36 @@ with the service before trying it again. The client provides explicit JSON calls for initialization, listing and invocation. Streaming, server-initiated requests, automatic retries and running tool sequences are outside this API. +## Invoke a holder-authorized Action from a trusted host + +Use `@registrystack/client/holder-function` on a trusted host that receives a +signed-in person's bearer on one private, gateway-only route. This entry point +is pre-1.0 and may change. + +`createHolderActionHandler(binding, prepare)` returns a Fetch handler for one +declared function path. The host owns the binding: its `kind`, the exact path, +a preparation deadline, the submission and preparation parsers, and `invoke`, +which calls one generated BReg Action with one fixed access profile and the +caller's bearer. A `target` binding acts on one existing Record and needs its +reviewed condition. A `create` binding makes one new Record and takes no +target. `prepare` is the declared function. It receives only the projected +value the submission parser returns and a signal, never the Request, a +header, the bearer or a product client. Its result passes the preparation +parser, so it cannot select another product, Action, access profile, target, +owner or attempt key. + +The binding minimises arguments. It does not isolate the function: `prepare` +runs in the host's process and can reach whatever that process can, including +the next caller's request. Use it only for trusted, reviewed function code, +and run unreviewed functions outside the host's process. Who owns a created +Record comes from the host's submission parser and the BReg Action's own plan +and row boundaries, not from this handler. + +An answer with code `holder-action.outcome-unresolved` means BReg may have +acted. Keep the original attempt key and body until a matching receipt +arrives, including through an ordinary refusal of a retry such as an expired +sign-in. A new key can create a second Record. + ## Generate a service Install the package in your application with Node 24. diff --git a/clients/typescript/package.json b/clients/typescript/package.json index 377f2ef535..c0b61fb3b7 100644 --- a/clients/typescript/package.json +++ b/clients/typescript/package.json @@ -34,6 +34,10 @@ "types": "./dist/mcp.d.ts", "default": "./dist/mcp.js" }, + "./holder-function": { + "types": "./dist/holder-function.d.ts", + "default": "./dist/holder-function.js" + }, "./products/*": { "types": "./dist/generated/*.d.ts", "default": "./dist/generated/*.js" diff --git a/clients/typescript/tests/package.test.ts b/clients/typescript/tests/package.test.ts index 390c4aa195..5c64c711bc 100644 --- a/clients/typescript/tests/package.test.ts +++ b/clients/typescript/tests/package.test.ts @@ -14,6 +14,9 @@ test('the browser package is publishable at the unified client release version', assert.equal(manifest.exports['.'].types, './dist/browser.d.ts') assert.equal(manifest.exports['.'].default, './dist/browser.js') assert.deepEqual(manifest.exports['./mcp'], { types: './dist/mcp.d.ts', default: './dist/mcp.js' }) + // A trusted host invokes a holder-authorized Action through this binding. + assert.deepEqual(manifest.exports['./holder-function'], + { types: './dist/holder-function.d.ts', default: './dist/holder-function.js' }) assert.equal(manifest.license, 'Apache-2.0') const binaries = { 'registry-generate': './registry-generate.js', 'registry-preview': './preview/cli.mjs' } assert.deepEqual(manifest.bin, binaries) @@ -28,3 +31,9 @@ test('the browser package is publishable at the unified client release version', } assert.deepEqual(manifest.files, ['dist', 'registry-generate.js', 'preview/*.mjs', 'LICENSE']) }) + +test('the built holder binding is the one the package exports', async () => { + const built = new URL('../dist/holder-function.js', import.meta.url) + const { createHolderActionHandler } = await import(built.href) as typeof import('../holder-function.ts') + assert.equal(typeof createHolderActionHandler, 'function') +}) diff --git a/clients/typescript/tsconfig.browser.json b/clients/typescript/tsconfig.browser.json index 2d68615e35..d858b90af0 100644 --- a/clients/typescript/tsconfig.browser.json +++ b/clients/typescript/tsconfig.browser.json @@ -8,5 +8,5 @@ "outDir": "dist", "declaration": true }, - "include": ["browser.ts", "core.ts", "mcp.ts", "webhook.ts", "schema.ts", "generated/**/*.ts"] + "include": ["browser.ts", "core.ts", "holder-function.ts", "mcp.ts", "webhook.ts", "schema.ts", "generated/**/*.ts"] } diff --git a/products/platform/CHANGELOG.md b/products/platform/CHANGELOG.md index 05b18d47be..f6c8890d9e 100644 --- a/products/platform/CHANGELOG.md +++ b/products/platform/CHANGELOG.md @@ -2,6 +2,7 @@ ## Unreleased +- Add `@registrystack/client/holder-function`, a pre-1.0 subpath export of the existing `@registrystack/client` package with no new package name. A trusted host uses `createHolderActionHandler` to invoke one generated BReg Action for a signed-in person, with a declared function that only prepares the input. The function receives one projected value and a signal, never the Request, the bearer or a product client, and runs in the host's process, so the binding minimises arguments for trusted, reviewed code and does not isolate it. - BREAKING: `dev.yaml` declares its products with the same mapping as `service.yaml`, and `rstack dev` refuses the list form with `rstack.dev.products-list`. Migration: replace each `- {product: KIND, project: PATH, audience: AUDIENCE}` entry with `products.KIND.projects.KIND.path: PATH` for `breg`, `coordinator` and `evidence`, or `products.KIND.path: PATH` for the other products, and move the audience to `audiences.KIND: AUDIENCE`. A directory has one inventory: when its `service.yaml` declares `products`, keep only `audiences` in `dev.yaml`. `service.yaml` also accepts `adapter`, `discovery`, `documents`, `render` and `scheduling` projects. - The file secret provider accepts `mountPolicy: compose-native`, an explicit production setting that also admits a root-owned, single-link regular file From ad1f07e8f3fb7c30bb033d4fd6c4cf34bb11bb27 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Wed, 2 Dec 2026 00:59:29 +0000 Subject: [PATCH 173/183] fix(client): fold the holder binding re-review - P1-1: CI runs the package tests before the build, so the export test now checks that the build includes holder-function.ts and imports the source module, not dist. It passes with dist moved aside. - R1: the README credits the owner guarantee to the host's preparation parser, which admits only the Action's inputs, and to the BReg Action. - R2: BReg scopes attempt keys per issuer, subject and key, and a create binding's invoke returns the Record the Action created. - R4: one deadline timer ends the race and aborts the preparation's own signal, so no AbortSignal.timeout timer is left running. A new test shows the preparation signal aborted at the deadline. The cleanup test counts the deadline timers it starts and clears, and clears a leak itself, so removing clearTimeout fails the test instead of hanging it. Both were proven by mutation. - R5: the binding, submission and command types a host implements are exported. Signed-off-by: Jeremi Joslin --- clients/typescript/README.md | 5 ++- clients/typescript/holder-function.ts | 29 +++++++------ .../tests/holder-function-create.test.ts | 43 ++++++++++++++++++- clients/typescript/tests/package.test.ts | 8 ++-- 4 files changed, 66 insertions(+), 19 deletions(-) diff --git a/clients/typescript/README.md b/clients/typescript/README.md index 69355304b8..d7596ae117 100644 --- a/clients/typescript/README.md +++ b/clients/typescript/README.md @@ -366,8 +366,9 @@ The binding minimises arguments. It does not isolate the function: `prepare` runs in the host's process and can reach whatever that process can, including the next caller's request. Use it only for trusted, reviewed function code, and run unreviewed functions outside the host's process. Who owns a created -Record comes from the host's submission parser and the BReg Action's own plan -and row boundaries, not from this handler. +Record comes from the host's preparation parser, which admits only the +Action's inputs, and the BReg Action's own plan and row boundaries, not from +this handler. BReg scopes attempt keys per issuer, subject and key. An answer with code `holder-action.outcome-unresolved` means BReg may have acted. Keep the original attempt key and body until a matching receipt diff --git a/clients/typescript/holder-function.ts b/clients/typescript/holder-function.ts index 3fd6691c04..f74b00214b 100644 --- a/clients/typescript/holder-function.ts +++ b/clients/typescript/holder-function.ts @@ -5,13 +5,13 @@ const strongTag = /^"[\x21\x23-\x7e]{1,254}"$/u const maximumRequestBytes = 32_768 const bodyTooLarge = Symbol('body too large') -interface HolderSubmission { +export interface HolderSubmission { recordId: string ifMatch: string preparation: Preparation } -interface HolderCommand { +export interface HolderCommand { recordId: string ifMatch: string idempotencyKey: string @@ -20,7 +20,7 @@ interface HolderCommand { } /** Host-owned parsing and invocation for one generated BReg Action on one existing Record and its fixed access profile. */ -interface HolderTargetBinding { +export interface HolderTargetBinding { kind: 'target' path: string preparationTimeoutMs: number @@ -29,11 +29,11 @@ interface HolderTargetBinding invoke: (credential: string, command: HolderCommand) => Promise<{ recordId: string }> } -interface HolderCreateSubmission { +export interface HolderCreateSubmission { preparation: Preparation } -interface HolderCreateCommand { +export interface HolderCreateCommand { idempotencyKey: string input: Input signal: AbortSignal @@ -44,17 +44,17 @@ interface HolderCreateCommand { * The submission names no target and no condition, and neither the page nor the function can * name the new Record's owner: the Action's own plan and row boundaries decide it. */ -interface HolderCreateBinding { +export interface HolderCreateBinding { kind: 'create' path: string preparationTimeoutMs: number parseSubmission: (body: unknown) => HolderCreateSubmission | undefined parsePreparation: (body: unknown) => Input | undefined - /** Returns the created Record and its revision from the generated receipt. */ + /** Returns the Record the Action created and its revision, from the generated receipt. */ invoke: (credential: string, command: HolderCreateCommand) => Promise<{ recordId: string; revision: number }> } -type HolderActionBinding = +export type HolderActionBinding = HolderTargetBinding | HolderCreateBinding function reply(body: object, status: number): Response { @@ -121,11 +121,16 @@ async function prepareInTime(run: (signal: AbortSignal) => unknown, signal: Abor const stopped = new Promise((_resolve, reject) => { stop = reject }) const abort = () => stop(signal.reason) signal.addEventListener('abort', abort, { once: true }) - const timer = setTimeout(() => stop(expired), timeoutMs) + // One timer ends the race and aborts the preparation's own signal together. + const deadline = new AbortController() + const timer = setTimeout(() => { + deadline.abort(expired) + stop(expired) + }, timeoutMs) try { // The preparation's own signal follows the caller and the deadline, so cooperative code // can stop early; the race below does not depend on it. - const preparationSignal = AbortSignal.any([signal, AbortSignal.timeout(timeoutMs)]) + const preparationSignal = AbortSignal.any([signal, deadline.signal]) const result = await Promise.race([stopped, Promise.resolve().then(() => { signal.throwIfAborted() return run(preparationSignal) @@ -218,8 +223,8 @@ export function createHolderActionHandler { + let observed: AbortSignal | undefined + const { handle, calls } = setup(prepareRegistration, { preparationTimeoutMs: 20 }) + const slow = createHolderActionHandler({ + kind: 'create', path: route, preparationTimeoutMs: 20, parseSubmission, parsePreparation, + async invoke() { throw new Error('No Action may be called.') }, + }, async (value, { signal }) => { + observed = signal + await new Promise(resolve => setTimeout(resolve, 80)) + return prepareRegistration(value) + }) + assert.equal((await slow(request())).status, 502) + assert.equal(observed?.aborted, true) + assert.equal(calls.length, 0) + void handle +}) + test('the preparation deadline removes its timer and abort listener', async () => { const controller = new AbortController() const signal = controller.signal @@ -348,16 +365,38 @@ test('the preparation deadline removes its timer and abort listener', async () = if (args[0] === 'abort') removed += 1 return removeEventListener(...args) }) as typeof signal.removeEventListener - // A long deadline: a timer left behind would keep the test process alive. const { handle } = setup(prepareRegistration, { preparationTimeoutMs: 600_000 }) + // Count the timers the handler starts and clears, so a leaked timer fails here. + const started = new Set() + const realSetTimeout = globalThis.setTimeout + const realClearTimeout = globalThis.clearTimeout + globalThis.setTimeout = ((...args: Parameters) => { + const timer = realSetTimeout(...args) + if (args[1] === 600_000) started.add(timer) + return timer + }) as typeof setTimeout + globalThis.clearTimeout = ((timer?: Parameters[0]) => { + started.delete(timer) + return realClearTimeout(timer) + }) as typeof clearTimeout // The handler reads the caller's signal from the Request; hand it the spied one. class SpiedRequest extends Request { override get signal() { return signal } } - const answer = await handle(new SpiedRequest(request())) + let answer: Response + try { + answer = await handle(new SpiedRequest(request())) + } finally { + globalThis.setTimeout = realSetTimeout + globalThis.clearTimeout = realClearTimeout + } + // Clear any leaked timer before asserting, so a leak fails the test instead of hanging it. + const leaked = started.size + for (const timer of started) realClearTimeout(timer as Parameters[0]) assert.equal(answer.status, 200) assert.ok(added >= 1) assert.equal(removed, added) + assert.equal(leaked, 0, 'a deadline timer was left running') }) test('a create preparation receives the host projection, not the raw body', async () => { diff --git a/clients/typescript/tests/package.test.ts b/clients/typescript/tests/package.test.ts index 5c64c711bc..ed01c8d0e1 100644 --- a/clients/typescript/tests/package.test.ts +++ b/clients/typescript/tests/package.test.ts @@ -32,8 +32,10 @@ test('the browser package is publishable at the unified client release version', assert.deepEqual(manifest.files, ['dist', 'registry-generate.js', 'preview/*.mjs', 'LICENSE']) }) -test('the built holder binding is the one the package exports', async () => { - const built = new URL('../dist/holder-function.js', import.meta.url) - const { createHolderActionHandler } = await import(built.href) as typeof import('../holder-function.ts') +test('the package builds and exports the holder binding source', async () => { + // CI runs the tests before the build, so check the source the export is built from. + const build = JSON.parse(readFileSync(new URL('../tsconfig.browser.json', import.meta.url), 'utf8')) + assert.ok(build.include.includes('holder-function.ts')) + const { createHolderActionHandler } = await import('../holder-function.ts') assert.equal(typeof createHolderActionHandler, 'function') }) From c7a0c625b59b0f9dade68a7b85cc185521e52d66 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Wed, 2 Dec 2026 01:03:39 +0000 Subject: [PATCH 174/183] docs(client): state the holder owner rule's parser condition Fold the final high review's two nits. The create binding's doc comment says the owner guarantee holds while the host's preparation parser admits only the Action's inputs. The deadline test now wires a counting invoke into the handler under test and asserts it was never called. Signed-off-by: Jeremi Joslin --- clients/typescript/holder-function.ts | 5 +++-- .../typescript/tests/holder-function-create.test.ts | 10 ++++++---- 2 files changed, 9 insertions(+), 6 deletions(-) diff --git a/clients/typescript/holder-function.ts b/clients/typescript/holder-function.ts index f74b00214b..6f4e504012 100644 --- a/clients/typescript/holder-function.ts +++ b/clients/typescript/holder-function.ts @@ -41,8 +41,9 @@ export interface HolderCreateCommand { /** * Host-owned parsing and invocation for one generated BReg Action that creates one new Record. - * The submission names no target and no condition, and neither the page nor the function can - * name the new Record's owner: the Action's own plan and row boundaries decide it. + * The submission names no target and no condition. Neither the page nor the function can name + * the new Record's owner, as long as the host's preparation parser admits only the Action's + * inputs: the Action's own plan and row boundaries then decide it. */ export interface HolderCreateBinding { kind: 'create' diff --git a/clients/typescript/tests/holder-function-create.test.ts b/clients/typescript/tests/holder-function-create.test.ts index c035ce54ca..b891d69d43 100644 --- a/clients/typescript/tests/holder-function-create.test.ts +++ b/clients/typescript/tests/holder-function-create.test.ts @@ -335,10 +335,13 @@ test('a synchronous preparation that overruns its deadline makes no Action call' test('the preparation signal aborts at the deadline', { timeout: 3000 }, async () => { let observed: AbortSignal | undefined - const { handle, calls } = setup(prepareRegistration, { preparationTimeoutMs: 20 }) + let invoked = 0 const slow = createHolderActionHandler({ kind: 'create', path: route, preparationTimeoutMs: 20, parseSubmission, parsePreparation, - async invoke() { throw new Error('No Action may be called.') }, + async invoke() { + invoked += 1 + return { recordId: '00000000-0000-4000-8000-000000000001', revision: 1 } + }, }, async (value, { signal }) => { observed = signal await new Promise(resolve => setTimeout(resolve, 80)) @@ -346,8 +349,7 @@ test('the preparation signal aborts at the deadline', { timeout: 3000 }, async ( }) assert.equal((await slow(request())).status, 502) assert.equal(observed?.aborted, true) - assert.equal(calls.length, 0) - void handle + assert.equal(invoked, 0) }) test('the preparation deadline removes its timer and abort listener', async () => { From e4666eabe18e1572bb4af21c25636f1f7a7646db Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Wed, 2 Dec 2026 01:12:19 +0000 Subject: [PATCH 175/183] test(client): name holder test attempt keys attemptId gitleaks' generic-api-key rule flags a UUID literal assigned to a variable named idempotencyKey. Rename the test constant to attemptId in both holder binding test files, as Lane 1 did, with no allowlist change. gitleaks finds no leak in either file; the previous create test file is flagged. Signed-off-by: Jeremi Joslin --- .../typescript/tests/holder-function-create.test.ts | 12 ++++++------ clients/typescript/tests/holder-function.test.ts | 12 ++++++------ 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/clients/typescript/tests/holder-function-create.test.ts b/clients/typescript/tests/holder-function-create.test.ts index b891d69d43..3b76c975d0 100644 --- a/clients/typescript/tests/holder-function-create.test.ts +++ b/clients/typescript/tests/holder-function-create.test.ts @@ -9,7 +9,7 @@ import { createHolderActionHandler } from '../holder-function.ts' // plan, BReg plans the owning office itself and refuses a create outside the // caller's office through the Action target's row boundary. const route = '/api/functions/register-business' -const idempotencyKey = '6c0e4c3d-1d0b-4c55-9d43-4ad2a3b3a1f7' +const attemptId = '6c0e4c3d-1d0b-4c55-9d43-4ad2a3b3a1f7' const registrarAuthorization = 'Bearer synthetic-registrar' const traceId = '33333333333333333333333333333333' const traceparent = `00-${traceId}-4444444444444444-01` @@ -63,7 +63,7 @@ function prepareRegistration({ legalName, registrationNumber }: RegistrationInpu } function request(options: { path?: string; method?: string; authorization?: string | null; body?: unknown; key?: string; signal?: AbortSignal } = {}) { - const { path = route, method = 'POST', authorization = registrarAuthorization, body = submission, key = idempotencyKey, signal } = options + const { path = route, method = 'POST', authorization = registrarAuthorization, body = submission, key = attemptId, signal } = options const headers = new Headers({ 'Content-Type': 'application/json', 'Idempotency-Key': key, 'Registry-Client': 'page', Cookie: 'synthetic-cookie', 'X-Actor': 'synthetic-spoofed-actor', @@ -104,7 +104,7 @@ function setup(prepare: (input: RegistrationInput) => unknown = prepareRegistrat status, code, detail: 'product-only detail', title: 'BReg refused the request.', traceId, type: 'https://id.registrystack.org/problems/registry-breg/' + code.replaceAll('.', '/'), }, { status, headers: { 'Content-Type': 'application/problem+json', 'Cache-Control': 'no-store', traceparent } }) - const receipt = (recordId: string) => Response.json({ action: 'register-business', applicationId: idempotencyKey, + const receipt = (recordId: string) => Response.json({ action: 'register-business', applicationId: attemptId, results: omitReceipt ? {} : { business: { recordId: receiptRecordId ?? recordId, recordType: 'business', revision: receiptRevision } }, }, { headers: { 'Cache-Control': 'no-store', traceparent } }) const identity = identities.get(headers.get('authorization') ?? '') @@ -170,7 +170,7 @@ test('a create binding prepares the projected value and invokes the Action with const call = calls[0]! assert.equal(call.url, 'https://businesses.test/v1/actions/register-business?accessProfile=business-registrar') assert.equal(call.headers.authorization, registrarAuthorization) - assert.equal(call.headers['idempotency-key'], idempotencyKey) + assert.equal(call.headers['idempotency-key'], attemptId) for (const header of ['cookie', 'registry-client', 'x-actor']) assert.equal(call.headers[header], undefined) assert.deepEqual(call.body, { input: prepared }) assert.deepEqual([...records], [[recordId, { owner: 'central', input: prepared }]]) @@ -426,8 +426,8 @@ test('the caller signal reaches the Action call and the preparation', async () = test('the attempt key is forwarded in lower case', async () => { const { handle, calls } = setup() - assert.equal((await handle(request({ key: idempotencyKey.toUpperCase() }))).status, 200) - assert.equal(calls[0]!.headers['idempotency-key'], idempotencyKey) + assert.equal((await handle(request({ key: attemptId.toUpperCase() }))).status, 200) + assert.equal(calls[0]!.headers['idempotency-key'], attemptId) }) test('a binding kind changed after construction has no effect', async () => { diff --git a/clients/typescript/tests/holder-function.test.ts b/clients/typescript/tests/holder-function.test.ts index 086b778b28..591b54ab0e 100644 --- a/clients/typescript/tests/holder-function.test.ts +++ b/clients/typescript/tests/holder-function.test.ts @@ -15,7 +15,7 @@ const reviewedExpiresOn = '2027-06-30' const newExpiresOn = '2028-06-30' const ifMatch = '"reviewed-revision"' const otherIfMatch = '"other-reviewed-revision"' -const idempotencyKey = '08114403-75d2-48d3-961a-5d4fb8b19687' +const attemptId = '08114403-75d2-48d3-961a-5d4fb8b19687' const holderAuthorization = 'Bearer synthetic-holder' const traceId = '11111111111111111111111111111111' const traceparent = `00-${traceId}-2222222222222222-01` @@ -90,7 +90,7 @@ function parsePreparation(value: unknown) { } function request(options: { path?: string; authorization?: string | null; body?: unknown; key?: string; signal?: AbortSignal } = {}) { - const { path = route, authorization = holderAuthorization, body = submission, key = idempotencyKey, signal } = options + const { path = route, authorization = holderAuthorization, body = submission, key = attemptId, signal } = options const headers = new Headers({ 'Content-Type': 'application/json', 'Idempotency-Key': key, 'Registry-Client': 'page', Cookie: 'synthetic-cookie', 'X-Actor': 'synthetic-spoofed-actor', @@ -129,7 +129,7 @@ function setup(prepare: (input: { reviewedExpiresOn: string }) => unknown = prep status, code, detail: 'product-only detail', title: 'BReg refused the request.', traceId, type: 'https://id.registrystack.org/problems/registry-breg/' + code.replaceAll('.', '/'), }, { status, headers: { 'Content-Type': 'application/problem+json', 'Cache-Control': 'no-store', traceparent } }) - const receipt = () => Response.json({ action: 'renew', applicationId: idempotencyKey, + const receipt = () => Response.json({ action: 'renew', applicationId: attemptId, results: receiptRecordId === null ? {} : { licence: { recordId: receiptRecordId || body.input.licenceId, recordType: 'licence', revision: omitReceiptRevision ? undefined : 2 } }, }, { headers: { 'Cache-Control': 'no-store', traceparent } }) @@ -194,7 +194,7 @@ test('preparation receives one projected value and the checked Action receives t assert.equal(call.url, 'https://licences.test/v1/actions/renew?accessProfile=licence-holder') assert.equal(call.method, 'POST') assert.equal(call.headers.authorization, holderAuthorization) - assert.equal(call.headers['idempotency-key'], idempotencyKey) + assert.equal(call.headers['idempotency-key'], attemptId) for (const header of ['cookie', 'registry-client', 'x-actor']) assert.equal(call.headers[header], undefined) assert.deepEqual(call.body, { input: { licenceId, newExpiresOn }, preconditions: { licenceId: { ifMatch } } }) assert.deepEqual(writes, [licenceId]) @@ -366,7 +366,7 @@ test('a product receipt missing the exact record leaves the original attempt unr code: 'holder-action.outcome-unresolved', message: 'The Action outcome is unconfirmed. Keep the original attempt.', }) assert.equal(calls.length, 1) - assert.equal(calls[0]?.headers['idempotency-key'], idempotencyKey) + assert.equal(calls[0]?.headers['idempotency-key'], attemptId) } }) @@ -409,7 +409,7 @@ test('a spent key leaves the original attempt unresolved without dispatching wit assert.deepEqual(await retry.json(), { code: 'holder-action.outcome-unresolved', message: 'The Action outcome is unconfirmed. Keep the original attempt.', }) - assert.deepEqual(calls.map(call => call.headers['idempotency-key']), [idempotencyKey, idempotencyKey]) + assert.deepEqual(calls.map(call => call.headers['idempotency-key']), [attemptId, attemptId]) assert.deepEqual(writes, [licenceId]) } }) From 54ee713da348b00853bfbcd06a8843deb41eb971 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Wed, 2 Dec 2026 01:15:30 +0000 Subject: [PATCH 176/183] test(client): pin the holder outcome guard and fold the binding review Fold the binding review's open findings. - P2-3: unconditional tests show that a 5xx answer, an unreadable 2xx, a 4xx without a problem body and a caller abort after dispatch each give 502 holder-action.outcome-unresolved. Host invoke errors that fail one condition each (refused, settled, 4xx) make every condition of the refusal guard load-bearing. - P3-4: tests for the content type a cross-site form can send, the strong-tag and type checks on a target submission, and no-store on every answer. - P3-6: the revision comment says a revision 1 receipt names a Record the attempt key inserted, and that a replay returns it unchanged. - P3-7: create binds only to an Action that inserts a Record. - P3-8: the handler checks only the bearer's shape, so it must sit behind the Session gateway, and its path is the browser-facing one. - The create branch no longer reads binding.kind a second time. These tests come after the code, so each was proven by mutation: the four refusal-guard mutants, content type, strong tag, both type checks, no-store, the deadline abort and the timer clear all fail the suite. Signed-off-by: Jeremi Joslin --- clients/typescript/README.md | 10 ++- clients/typescript/holder-function.ts | 17 ++-- .../tests/holder-function-create.test.ts | 81 ++++++++++++++++++- .../typescript/tests/holder-function.test.ts | 20 +++++ 4 files changed, 120 insertions(+), 8 deletions(-) diff --git a/clients/typescript/README.md b/clients/typescript/README.md index d7596ae117..da4031a730 100644 --- a/clients/typescript/README.md +++ b/clients/typescript/README.md @@ -368,7 +368,15 @@ the next caller's request. Use it only for trusted, reviewed function code, and run unreviewed functions outside the host's process. Who owns a created Record comes from the host's preparation parser, which admits only the Action's inputs, and the BReg Action's own plan and row boundaries, not from -this handler. BReg scopes attempt keys per issuer, subject and key. +this handler. BReg scopes attempt keys per issuer, subject and key. Bind +`create` only to an Action that inserts a Record. Bound to one that patches, the +patch commits with no condition and every answer is unresolved. + +The handler checks only the bearer's shape. BReg verifies the bearer when the +Action is called, after `prepare` has run, so serve the handler only behind the +Session gateway, on a listener nothing else can reach. The binding's path is +the browser-facing `/api/functions/`. If your gateway relays to +`/functions/`, hand the handler a request with the browser-facing path. An answer with code `holder-action.outcome-unresolved` means BReg may have acted. Keep the original attempt key and body until a matching receipt diff --git a/clients/typescript/holder-function.ts b/clients/typescript/holder-function.ts index 6f4e504012..0c4428ba4c 100644 --- a/clients/typescript/holder-function.ts +++ b/clients/typescript/holder-function.ts @@ -43,7 +43,9 @@ export interface HolderCreateCommand { * Host-owned parsing and invocation for one generated BReg Action that creates one new Record. * The submission names no target and no condition. Neither the page nor the function can name * the new Record's owner, as long as the host's preparation parser admits only the Action's - * inputs: the Action's own plan and row boundaries then decide it. + * inputs: the Action's own plan and row boundaries then decide it. Bind it only to an Action that + * inserts a Record: bound to one that patches, the patch commits with no condition and every + * answer is unresolved. */ export interface HolderCreateBinding { kind: 'create' @@ -159,6 +161,11 @@ function productRefusal(error: unknown): Response | undefined { /** * Use on the trusted invoker's gateway-only listener. Preparation must reproduce the same input on retry. * + * The handler checks only the bearer's shape. BReg verifies it at dispatch, after `prepare` has run, so + * serve the handler only behind the Session gateway, on a listener nothing else can reach. The binding's + * path is the browser-facing `/api/functions/`: a gateway that relays to `/functions/` + * needs the host to hand the handler a request with the browser-facing path. + * * The binding minimises the arguments `prepare` receives: one projected value and a signal, never the * Request, a header, the caller's credential or a product client. It does not isolate `prepare`. The * callback runs in the invoker's process, so code there can reach whatever that process can, including @@ -178,7 +185,7 @@ export function createHolderActionHandler 2_147_483_647) { throw new TypeError('Expected a bounded preparation deadline.') @@ -223,9 +230,9 @@ export function createHolderActionHandler unknown = prepareRegistration, { loseFirstReceipt = false, receiptRevision = 1, omitReceipt = false, replayProblem, preparationTimeoutMs = 1000, - receiptRecordId, parse = parseSubmission }: { + receiptRecordId, parse = parseSubmission, answer }: { + answer?: (signal: AbortSignal | null | undefined) => Response | Promise loseFirstReceipt?: boolean; receiptRevision?: number; omitReceipt?: boolean; preparationTimeoutMs?: number replayProblem?: 'idempotency.key-reused' | 'idempotency.expired'; receiptRecordId?: string parse?: (value: unknown) => { preparation: RegistrationInput } | undefined @@ -96,6 +97,7 @@ function setup(prepare: (input: RegistrationInput) => unknown = prepareRegistrat const headers = new Headers(options?.headers) const body = JSON.parse(String(options?.body)) calls.push({ url: url.href, headers: Object.fromEntries(headers), body }) + if (answer) return answer(options?.signal) if (url.pathname !== registration.path || options?.method !== 'POST' || url.searchParams.get('accessProfile') !== 'business-registrar') { throw new Error('The caller changed the checked Action contract.') @@ -440,3 +442,78 @@ test('a binding kind changed after construction has no effect', async () => { const answer = await handle(request()) assert.equal(answer.status, 200) }) + +test('an answer that is not a product refusal leaves the attempt unresolved', async () => { + // A 5xx may follow a commit, and a 2xx the client cannot read may carry one: neither is a refusal. + for (const [name, answer] of [ + ['5xx problem', () => Response.json({ status: 503, code: 'service.unavailable', detail: 'd', title: 't', traceId, + type: 'https://id.registrystack.org/problems/registry-breg/service/unavailable' }, + { status: 503, headers: { 'Content-Type': 'application/problem+json', traceparent } })], + ['unreadable 2xx', () => new Response('not json', { status: 200, headers: { 'Content-Type': 'application/json' } })], + // A 4xx with no problem body may come from a proxy, not from BReg's decision. + ['4xx without a problem', () => new Response('denied', { status: 403, headers: { 'Content-Type': 'text/plain' } })], + ] as const) { + const { handle, calls } = setup(prepareRegistration, { answer }) + const result = await handle(request()) + assert.equal(result.status, 502, name) + assert.equal((await result.json() as { code: string }).code, 'holder-action.outcome-unresolved', name) + assert.equal(calls.length, 1, name) + } +}) + +test('a caller abort after dispatch leaves the attempt unresolved', { timeout: 3000 }, async () => { + const controller = new AbortController() + const { handle, calls } = setup(prepareRegistration, { + answer: signal => new Promise((_resolve, reject) => { + signal?.addEventListener('abort', () => reject(signal.reason), { once: true }) + controller.abort() + }), + }) + const result = await handle(request({ signal: controller.signal })) + assert.equal(result.status, 502) + assert.equal((await result.json() as { code: string }).code, 'holder-action.outcome-unresolved') + assert.equal(calls.length, 1) +}) + +test('a create request that is not JSON is refused before preparation', async () => { + // A cross-site form cannot send application/json without a preflight. + for (const type of ['text/plain', 'application/x-www-form-urlencoded', 'multipart/form-data']) { + const { handle, preparations, calls } = setup() + const forged = new Request('https://service.test' + route, { + method: 'POST', body: JSON.stringify(submission), + headers: { 'Content-Type': type, 'Idempotency-Key': attemptId, Authorization: registrarAuthorization }, + }) + assert.equal((await handle(forged)).status, 400, type) + assert.deepEqual([preparations.length, calls.length], [0, 0], type) + } +}) + +test('every handler answer is marked no-store', async () => { + const { handle } = setup() + for (const answer of [await handle(request()), await handle(request({ authorization: null })), + await handle(request({ path: '/api/functions/other' }))]) { + assert.equal(answer.headers.get('cache-control'), 'no-store') + } +}) + +test('a host invoke error is a refusal only when refused, settled and 4xx', async () => { + // Each error fails exactly one of the three conditions, so each condition is needed on its own. + const refusal = (kind: 'refused' | 'unexpected', status: number, outcomeUnknown: boolean) => + new RegistryError({ kind, reason: 'status', status, outcomeUnknown }) + for (const [name, error, expected] of [ + ['settled 4xx refusal', refusal('refused', 403, false), 403], + ['4xx refusal with an unknown outcome', refusal('refused', 403, true), 502], + ['5xx marked refused', refusal('refused', 503, false), 502], + ['unexpected 4xx', refusal('unexpected', 403, false), 502], + ] as const) { + const handle = createHolderActionHandler({ + kind: 'create', path: route, preparationTimeoutMs: 1000, parseSubmission, parsePreparation, + async invoke() { throw error }, + }, prepareRegistration) + const result = await handle(request()) + assert.equal(result.status, expected, name) + if (expected === 502) { + assert.equal((await result.json() as { code: string }).code, 'holder-action.outcome-unresolved', name) + } + } +}) diff --git a/clients/typescript/tests/holder-function.test.ts b/clients/typescript/tests/holder-function.test.ts index 591b54ab0e..64badc47a2 100644 --- a/clients/typescript/tests/holder-function.test.ts +++ b/clients/typescript/tests/holder-function.test.ts @@ -422,3 +422,23 @@ test('an ordinary product conflict keeps its refusal response', async () => { assert.deepEqual(await conflict.json(), { message: 'BReg refused the request.' }) assert.deepEqual(writes, [licenceId]) }) + +test('a target submission needs a string UUID record and a strong condition', async () => { + for (const [name, parse] of [ + ['weak condition', (value: unknown) => ({ ...parseSubmission(value)!, ifMatch: 'W/"reviewed-revision"' })], + ['unquoted condition', (value: unknown) => ({ ...parseSubmission(value)!, ifMatch: 'reviewed-revision' })], + // A one-element array stringifies to a valid value, so only the type check refuses it. + ['array record', (value: unknown) => { + const parsed = parseSubmission(value)! + return { ...parsed, recordId: [parsed.recordId] as unknown as string } + }], + ['array condition', (value: unknown) => { + const parsed = parseSubmission(value)! + return { ...parsed, ifMatch: [parsed.ifMatch] as unknown as string } + }], + ] as const) { + const { handle, preparations, calls } = setup(prepareRenewal, { parse }) + assert.equal((await handle(request())).status, 400, name) + assert.deepEqual([preparations.length, calls.length], [0, 0], name) + } +}) From 913b6540afc9352e61406409deca237996d79527 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Wed, 2 Dec 2026 01:18:02 +0000 Subject: [PATCH 177/183] docs(client): say how BReg answers a create bound to a patch The recheck noted that an unconditioned patch commits only under current-revision concurrency. Under the default condition-required, BReg refuses it and the handler relays the refusal. Signed-off-by: Jeremi Joslin --- clients/typescript/README.md | 4 +++- clients/typescript/holder-function.ts | 5 +++-- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/clients/typescript/README.md b/clients/typescript/README.md index da4031a730..9bae833896 100644 --- a/clients/typescript/README.md +++ b/clients/typescript/README.md @@ -369,7 +369,9 @@ and run unreviewed functions outside the host's process. Who owns a created Record comes from the host's preparation parser, which admits only the Action's inputs, and the BReg Action's own plan and row boundaries, not from this handler. BReg scopes attempt keys per issuer, subject and key. Bind -`create` only to an Action that inserts a Record. Bound to one that patches, the +`create` only to an Action that inserts a Record. Bound to one that patches, +BReg refuses the unconditioned patch under the default `condition-required` +concurrency, and the handler relays that refusal. Under `current-revision` the patch commits with no condition and every answer is unresolved. The handler checks only the bearer's shape. BReg verifies the bearer when the diff --git a/clients/typescript/holder-function.ts b/clients/typescript/holder-function.ts index 0c4428ba4c..b7ed745014 100644 --- a/clients/typescript/holder-function.ts +++ b/clients/typescript/holder-function.ts @@ -44,8 +44,9 @@ export interface HolderCreateCommand { * The submission names no target and no condition. Neither the page nor the function can name * the new Record's owner, as long as the host's preparation parser admits only the Action's * inputs: the Action's own plan and row boundaries then decide it. Bind it only to an Action that - * inserts a Record: bound to one that patches, the patch commits with no condition and every - * answer is unresolved. + * inserts a Record. Bound to one that patches, BReg refuses the unconditioned patch under the + * default `condition-required` concurrency, and the handler relays that refusal. Under + * `current-revision` the patch commits with no condition and every answer is unresolved. */ export interface HolderCreateBinding { kind: 'create' From 652f1c1d705d7fa178411e015ddef87da27ec4db Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Wed, 2 Dec 2026 01:51:20 +0000 Subject: [PATCH 178/183] test(journeys): parenthesize the Documents sink headers for jq 1.7 jq 1.7, on the hosted runners, refuses an object value written as a sum without parentheses. jq 1.8 accepts it, so the Documents hook sink fixture passed locally and failed in CI. Signed-off-by: Jeremi Joslin --- products/platform/journeys/test_journey_tables.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/products/platform/journeys/test_journey_tables.py b/products/platform/journeys/test_journey_tables.py index dcbb284427..205ed2ad4c 100644 --- a/products/platform/journeys/test_journey_tables.py +++ b/products/platform/journeys/test_journey_tables.py @@ -1294,11 +1294,11 @@ def walk(self, product, delivered): type: "document-version-ready", data: {documentId: "retained-id", versionId: (if $mode == "other-version" then "other" else "version-id" end), versionDigest: $digest, policyId: "institutional-custody", policyVersion: "1"}} as $event | - [{body: ($event | tojson), headers: [ + [{body: ($event | tojson), headers: ([ {name: "webhook-id", value: "evt-1"}, {name: "webhook-timestamp", value: "1"}, {name: "webhook-signature", value: "v1,fixture"} - ] + (if $mode == "forwarded-auth" then [{name: "authorization", value: "fixture"}] else [] end)}]' + ] + (if $mode == "forwarded-auth" then [{name: "authorization", value: "fixture"}] else [] end))}]' return fi case "$delivered" in From 4255f709140414fa015a55cb5f4fc29d96595f52 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Wed, 2 Dec 2026 03:16:25 +0000 Subject: [PATCH 179/183] test(bregctl): hold the explain report example to current output The ctl-report registration's example is the completed identity facts report, which shares the explain report's apiVersion and kind. Read the explain example directly and keep the registration check for apiVersion and kind. Signed-off-by: Jeremi Joslin (cherry picked from commit 66e7aace4b0aaa31b527c32c92391a8ef2275cb2) --- crates/registry-bregctl/tests/explain_contract.rs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/crates/registry-bregctl/tests/explain_contract.rs b/crates/registry-bregctl/tests/explain_contract.rs index cfb95544c1..cf323b2aa7 100644 --- a/crates/registry-bregctl/tests/explain_contract.rs +++ b/crates/registry-bregctl/tests/explain_contract.rs @@ -1321,7 +1321,7 @@ fn authored_display_examples_pin_every_presentation_surface() { } #[test] -fn registered_ctl_report_example_matches_current_actions_report() { +fn ctl_report_explain_example_matches_current_actions_report() { let root = repo_root(); let registry = format_registry(&root); let registration = registry["formats"] @@ -1330,7 +1330,9 @@ fn registered_ctl_report_example_matches_current_actions_report() { .iter() .find(|format| format["id"] == "breg/ctl-report") .expect("ctl report is registered"); - let path = root.join(registration["example"].as_str().unwrap()); + // The registration's example and schema are the completed identity facts report. + // This explain report shares its apiVersion and kind and is held to current output here. + let path = root.join("products/breg/examples/formats/ctl-report.json"); let bytes = std::fs::read(&path).unwrap(); let example: Value = serde_json::from_slice(&bytes).expect("registered report parses"); assert_eq!(example["apiVersion"], registration["current"]["apiVersion"]); From 3e4b2313281682aa84286ab6e7bd7996d457afcc Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Wed, 2 Dec 2026 03:23:32 +0000 Subject: [PATCH 180/183] test(adapter): give signed-event fixtures a bare origin The job check now applies the signed-event origin policy that activation always applied, and that policy refuses a base URL with a path. Signed-off-by: Jeremi Joslin --- crates/registry-adapter-job/tests/job_file_host.rs | 2 +- crates/registry-adapter-job/tests/postgres_source_host.rs | 2 +- crates/registry-adapter-job/tests/posture.rs | 2 +- crates/registry-adapter-job/tests/sftp_cli_host.rs | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/crates/registry-adapter-job/tests/job_file_host.rs b/crates/registry-adapter-job/tests/job_file_host.rs index 468abcef49..3e0e3d29e2 100644 --- a/crates/registry-adapter-job/tests/job_file_host.rs +++ b/crates/registry-adapter-job/tests/job_file_host.rs @@ -200,7 +200,7 @@ fn runtime_json(source: &Path, component: &str) -> String { }, "destinations": {"coordinator-test": { "type": "signed-coordinator-event", - "baseUrl": "http://127.0.0.1:9/events", + "baseUrl": "http://127.0.0.1:9", "hmacSha256KeyRef": "secret:env/JOB_TEST_SIGNING_KEY", "attemptTimeoutMilliseconds": 1000 }} diff --git a/crates/registry-adapter-job/tests/postgres_source_host.rs b/crates/registry-adapter-job/tests/postgres_source_host.rs index a400ea2a54..6730098745 100644 --- a/crates/registry-adapter-job/tests/postgres_source_host.rs +++ b/crates/registry-adapter-job/tests/postgres_source_host.rs @@ -828,7 +828,7 @@ fn runtime_yaml(binding: &DatabaseBinding, query_kind: SourceQuery) -> String { "destinations": { "coordinator-test": { "type": "signed-coordinator-event", - "baseUrl": "http://127.0.0.1:9/events", + "baseUrl": "http://127.0.0.1:9", "hmacSha256KeyRef": "secret:env/JOB_TEST_SIGNING_KEY", "attemptTimeoutMilliseconds": 1000 } diff --git a/crates/registry-adapter-job/tests/posture.rs b/crates/registry-adapter-job/tests/posture.rs index 0e93d2a3d5..56cbfc8bf2 100644 --- a/crates/registry-adapter-job/tests/posture.rs +++ b/crates/registry-adapter-job/tests/posture.rs @@ -130,7 +130,7 @@ fn job_check_enforces_and_lists_the_posture() { .unwrap() .join("runtime.yaml"); let yaml = std::fs::read_to_string(base.join("job-runtime.yaml")).unwrap(); - let destination = "\ndestinations:\n coordinator-test:\n type: signed-coordinator-event\n baseUrl: http://127.0.0.1:9/events\n hmacSha256KeyRef: secret:env/JOB_EVENT_KEY\n attemptTimeoutMilliseconds: 1000\n"; + let destination = "\ndestinations:\n coordinator-test:\n type: signed-coordinator-event\n baseUrl: http://127.0.0.1:9\n hmacSha256KeyRef: secret:env/JOB_EVENT_KEY\n attemptTimeoutMilliseconds: 1000\n"; let run = |flag: Option<&str>, environment: Option<&str>| { let mut command = Command::new(env!("CARGO_BIN_EXE_adapter-job")); command diff --git a/crates/registry-adapter-job/tests/sftp_cli_host.rs b/crates/registry-adapter-job/tests/sftp_cli_host.rs index 35605401cd..4bb1bc04eb 100644 --- a/crates/registry-adapter-job/tests/sftp_cli_host.rs +++ b/crates/registry-adapter-job/tests/sftp_cli_host.rs @@ -189,7 +189,7 @@ fn runtime_json(server: &SftpSourceServer) -> Vec { }, "destinations": {"coordinator-test": { "type": "signed-coordinator-event", - "baseUrl": "http://127.0.0.1:9/events", + "baseUrl": "http://127.0.0.1:9", "hmacSha256KeyRef": "secret:env/JOB_TEST_SIGNING_KEY", "attemptTimeoutMilliseconds": 1000 }} From cfb142f1a691ea03d60d6abd0a28f6c276ef243a Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Wed, 2 Dec 2026 03:23:32 +0000 Subject: [PATCH 181/183] test(platform): hold CA bundles to the public-document read A CA bundle is a public document, so a group- or world-readable one is read rather than refused by the secret mode rule. Signed-off-by: Jeremi Joslin --- .../tests/job_provision_postgres.rs | 5 ++++- crates/registry-casework/tests/secret_diagnostics.rs | 10 ++++++---- 2 files changed, 10 insertions(+), 5 deletions(-) diff --git a/crates/registry-adapterctl/tests/job_provision_postgres.rs b/crates/registry-adapterctl/tests/job_provision_postgres.rs index 6fb0afa58d..732fb08edc 100644 --- a/crates/registry-adapterctl/tests/job_provision_postgres.rs +++ b/crates/registry-adapterctl/tests/job_provision_postgres.rs @@ -160,7 +160,6 @@ async fn provision_then_initialize_and_run_with_split_roles() { for (member, name) in [ ("runtimeUrlRef", "runtime-url"), ("migrationUrlRef", "migration-url"), - ("caBundleRef", "ca.pem"), ] { let secret = secrets.join(name); std::fs::set_permissions(&secret, std::fs::Permissions::from_mode(0o644)).unwrap(); @@ -207,8 +206,12 @@ async fn provision_then_initialize_and_run_with_split_roles() { "the failed initialization committed part of the schema" ); + // A CA bundle is a public document: a world-readable one is read. + let ca_file = secrets.join("ca.pem"); + std::fs::set_permissions(&ca_file, std::fs::Permissions::from_mode(0o644)).unwrap(); let (first, second) = tokio::join!(run(job.clone(), init_args()), run(job.clone(), init_args())); + std::fs::set_permissions(&ca_file, std::fs::Permissions::from_mode(0o600)).unwrap(); assert_eq!(first["ok"], true); assert_eq!(second["ok"], true); diff --git a/crates/registry-casework/tests/secret_diagnostics.rs b/crates/registry-casework/tests/secret_diagnostics.rs index b349505db4..1f75d4e080 100644 --- a/crates/registry-casework/tests/secret_diagnostics.rs +++ b/crates/registry-casework/tests/secret_diagnostics.rs @@ -110,7 +110,7 @@ mod unix { } #[test] - fn a_group_readable_trusted_root_reference_is_refused_without_the_reference() { + fn a_group_readable_trusted_root_is_read_as_a_public_document() { let root = tempfile::tempdir().expect("temporary secret root"); write_secret(root.path(), "casework-database-url", DATABASE_URL, 0o600); write_secret( @@ -124,16 +124,18 @@ mod unix { config.ca_bundle_ref = Some("secret:file/database-root.pem".to_owned()); let error = PostgresStore::connect_runtime(&config, &secrets, None) - .expect_err("a group-readable certificate file is refused"); + .expect_err("the truncated certificate holds no trusted root"); + // A CA bundle is public: the mode rule does not apply, and the + // refusal comes from the certificate content instead. let message = error.to_string(); assert!( !message.contains("secret:file/database-root.pem"), "the failure repeats the certificate reference: {message}" ); assert!( - message.contains("0400 or 0600"), - "the failure does not name the mode rule: {message}" + !message.contains("0400 or 0600"), + "a public CA bundle was held to the secret mode rule: {message}" ); } } From 9769ef491cf8dca55d95339a3867a7d61f56a1e1 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Wed, 2 Dec 2026 03:23:32 +0000 Subject: [PATCH 182/183] test(casework): bind the backup proof to the current starter issuer Signed-off-by: Jeremi Joslin --- products/casework/scripts/test-backup-restore.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/products/casework/scripts/test-backup-restore.sh b/products/casework/scripts/test-backup-restore.sh index edc73baf25..1483269933 100755 --- a/products/casework/scripts/test-backup-restore.sh +++ b/products/casework/scripts/test-backup-restore.sh @@ -204,7 +204,7 @@ from pathlib import Path import sys path = Path(sys.argv[1]) text = path.read_text() -for before, after in (("issuer: http://127.0.0.1:8093", f"issuer: {sys.argv[2]}"), +for before, after in (("issuer: https://identity.casework.example.test", f"issuer: {sys.argv[2]}"), ("subject: b75315b2-5854-70f3-8867-511dd771a6da", "subject: requester")): assert text.count(before) == 1, before text = text.replace(before, after) From 8212de67bcaf54a329c4371f28e584af082289fe Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Wed, 2 Dec 2026 04:01:35 +0000 Subject: [PATCH 183/183] test(adapter): drop the loopback range from the Postgres source fixture The signed-event origin policy, now applied at check as at activation, refuses loopback as a private range. The loopback PostgreSQL source does not need it. Signed-off-by: Jeremi Joslin --- crates/registry-adapter-job/tests/postgres_source_host.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/registry-adapter-job/tests/postgres_source_host.rs b/crates/registry-adapter-job/tests/postgres_source_host.rs index 6730098745..d2b672cf27 100644 --- a/crates/registry-adapter-job/tests/postgres_source_host.rs +++ b/crates/registry-adapter-job/tests/postgres_source_host.rs @@ -820,7 +820,7 @@ fn runtime_yaml(binding: &DatabaseBinding, query_kind: SourceQuery) -> String { "id": "ledger-job-test", "endpoints": [], "sources": {"postgres": postgres_sources}, - "allowedPrivateCidrs": ["127.0.0.0/8"], + "allowedPrivateCidrs": [], "store": { "runtimeUrlRef": "secret:env/JOB_TEST_DB", "transport": "loopback-plaintext"