diff --git a/.gitleaksignore b/.gitleaksignore index 767366646f..ca227d40d2 100644 --- a/.gitleaksignore +++ b/.gitleaksignore @@ -214,6 +214,9 @@ e4ebb9330cf3fcbf3de89a76d912cf3609163b22:packages/flow/tests/test_choice_widgets # PR #2299: the literal GitLab-shaped string is explicitly SYNTHETIC-CREDENTIAL # in the auth-reference refusal matrix. This exact historical test finding only. cc5fba3e0b69646430c7e11ae0c181aaaad82d7f:packages/flow/tests/test_sanitized_artifact.py:gitlab-pat:1891 +# PR #2300: ZQX-CANARY-SECRET is a synthetic leak canary the connector pilot +# tests search for in every egress body, never a credential. This exact finding only. +f92237889163b242800c6aecd7c334c174ce4428:packages/flow/tests/test_connector_pilot.py:generic-api-key:56 # #2293 squash merge: the same tx/lens.py:885 type annotation that is already ignored at 7571d9c8 (no secret). 5e37bf177d46afddb4e48ea7b1bf87499964e276:packages/flow/openadapt_flow/tx/lens.py:generic-api-key:885 # PR #2411: benchmark/hooks_live/runs/*/report.json from one live hooks run. Each match is diff --git a/CAPABILITIES.md b/CAPABILITIES.md index 97189b5c5b..f8d0c5c82e 100644 --- a/CAPABILITIES.md +++ b/CAPABILITIES.md @@ -486,7 +486,7 @@ A test fails when a command has no file or this list is out of date. - `approve-sanitized` - `connect` -- `connector` +- `connector`: Run an outbound connector with local secrets, pinned admission keys, signed requests, token rotation, heartbeats and cancellation. - `login` - `materialize-approved` - `push` diff --git a/llms-full.txt b/llms-full.txt index b4d0e00959..d38082deca 100644 --- a/llms-full.txt +++ b/llms-full.txt @@ -946,7 +946,7 @@ A test fails when a command has no file or this list is out of date. - `approve-sanitized` - `connect` -- `connector` +- `connector`: Run an outbound connector with local secrets, pinned admission keys, signed requests, token rotation, heartbeats and cancellation. - `login` - `materialize-approved` - `push` diff --git a/packages/flow/deploy/connector/.gitignore b/packages/flow/deploy/connector/.gitignore new file mode 100644 index 0000000000..ad5f6bfcc5 --- /dev/null +++ b/packages/flow/deploy/connector/.gitignore @@ -0,0 +1 @@ +wheels/ diff --git a/packages/flow/deploy/connector/Dockerfile b/packages/flow/deploy/connector/Dockerfile new file mode 100644 index 0000000000..91f72d8680 --- /dev/null +++ b/packages/flow/deploy/connector/Dockerfile @@ -0,0 +1,43 @@ +# OpenAdapt connector (customer-run runner) for Linux hosts. +# +# The container makes outbound HTTPS requests only and listens on no port. +# Build it from a pinned, signed Flow release wheel placed in ./wheels: +# +# mkdir -p wheels && cp openadapt_flow--py3-none-any.whl wheels/ +# docker build -t openadapt-connector: . +# +# Run it with three mounts (see docker-compose.yml): /etc/openadapt holds +# connector.toml (0600, the connector token) and the local secret store; +# /srv/openadapt is the encrypted customer storage volume (programs in, reports +# out); nothing else is written outside the container's tmpfs. +ARG BASE_IMAGE=python:3.12-slim-bookworm +FROM ${BASE_IMAGE} + +ENV PIP_DISABLE_PIP_VERSION_CHECK=1 \ + PYTHONDONTWRITEBYTECODE=1 \ + OPENADAPT_HOME=/etc/openadapt \ + PLAYWRIGHT_BROWSERS_PATH=/opt/playwright + +RUN apt-get update \ + && apt-get install -y --no-install-recommends ca-certificates libnss3-tools libatomic1 tini + +COPY wheels /tmp/wheels +RUN set -eu; \ + python -m venv /opt/openadapt; \ + wheel="$(ls /tmp/wheels/openadapt_flow-*.whl | head -1)"; \ + /opt/openadapt/bin/pip install --no-cache-dir --find-links /tmp/wheels "${wheel}[browser,vision]"; \ + apt-get update; /opt/openadapt/bin/python -m playwright install --with-deps chromium; \ + /opt/openadapt/bin/pip check; \ + rm -rf /tmp/wheels /var/lib/apt/lists/* + +RUN useradd --system --create-home --uid 10001 openadapt \ + && mkdir -p /etc/openadapt /srv/openadapt \ + && chown openadapt:openadapt /srv/openadapt +COPY entrypoint.sh /usr/local/bin/openadapt-connector-entrypoint +RUN chmod 0755 /usr/local/bin/openadapt-connector-entrypoint + +USER openadapt +ENV PATH="/opt/openadapt/bin:${PATH}" +WORKDIR /srv/openadapt +ENTRYPOINT ["/usr/bin/tini", "--", "/usr/local/bin/openadapt-connector-entrypoint"] +CMD ["openadapt-flow", "connector", "run"] diff --git a/packages/flow/deploy/connector/e2e/Dockerfile.publisher b/packages/flow/deploy/connector/e2e/Dockerfile.publisher new file mode 100644 index 0000000000..a868cf6c2c --- /dev/null +++ b/packages/flow/deploy/connector/e2e/Dockerfile.publisher @@ -0,0 +1,16 @@ +# The author's workstation for the end-to-end check: Flow at the cloud's pinned +# compiler version, used once to teach, admit and publish the synthetic program +# against the private app. Not part of the runner. +FROM python:3.12-slim-bookworm +ARG FLOW_VERSION=3.1.0 +ENV PLAYWRIGHT_BROWSERS_PATH=/opt/playwright PIP_DISABLE_PIP_VERSION_CHECK=1 +RUN apt-get update && apt-get install -y --no-install-recommends ca-certificates libnss3-tools libatomic1 tesseract-ocr \ + && python -m venv /opt/flow \ + && /opt/flow/bin/pip install --no-cache-dir "openadapt-flow[browser,vision,privacy]==${FLOW_VERSION}" \ + && /opt/flow/bin/python -m spacy download en_core_web_sm \ + && /opt/flow/bin/python -m playwright install --with-deps chromium \ + && rm -rf /var/lib/apt/lists/* +ENV PATH="/opt/flow/bin:${PATH}" +COPY entrypoint.sh /usr/local/bin/ca-entrypoint +RUN chmod 0755 /usr/local/bin/ca-entrypoint +ENTRYPOINT ["/usr/local/bin/ca-entrypoint"] diff --git a/packages/flow/deploy/connector/e2e/egress_log.py b/packages/flow/deploy/connector/e2e/egress_log.py new file mode 100644 index 0000000000..c05391c0c7 --- /dev/null +++ b/packages/flow/deploy/connector/e2e/egress_log.py @@ -0,0 +1,49 @@ +"""mitmproxy addon: the runner's only way out. + +Every request the runner (or anything on the private network) sends toward the +internet passes here. The addon writes each one, in full (method, URL, headers +with credentials masked, body), to a JSONL file, and refuses any host that is +not on the allow-list. The end-to-end check then searches that file for the +canary values that exist only inside the private network. +""" + +import base64 +import json +import os +import time + +from mitmproxy import http + +ALLOWED = { + h.strip() + for h in os.environ.get("EGRESS_ALLOWED_HOSTS", "").split(",") + if h.strip() +} +LOG = os.environ.get("EGRESS_LOG", "/log/egress.jsonl") +MASK = {"authorization", "x-run-token", "cookie", "x-api-key"} + + +def request(flow: http.HTTPFlow) -> None: + host = flow.request.pretty_host + allowed = host in ALLOWED + body = flow.request.get_content() or b"" + entry = { + "at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), + "allowed": allowed, + "method": flow.request.method, + "host": host, + "port": flow.request.port, + "path": flow.request.path, + "headers": { + k: ("" if k.lower() in MASK else v) + for k, v in flow.request.headers.items() + }, + "body_b64": base64.b64encode(body).decode(), + "body_bytes": len(body), + } + with open(LOG, "a", encoding="utf-8") as fh: + fh.write(json.dumps(entry) + "\n") + if not allowed: + flow.response = http.Response.make( + 403, b"egress refused by pilot proxy", {"content-type": "text/plain"} + ) diff --git a/packages/flow/deploy/connector/e2e/entrypoint.sh b/packages/flow/deploy/connector/e2e/entrypoint.sh new file mode 100755 index 0000000000..c1a4a1e0fe --- /dev/null +++ b/packages/flow/deploy/connector/e2e/entrypoint.sh @@ -0,0 +1,16 @@ +#!/bin/sh +# Trust any extra CA certificates the operator mounts (an internal CA for the +# target application, or a TLS-inspecting egress proxy), for Python and for +# the headless browser, then start the connector. +set -eu +if [ -d /etc/openadapt/ca ] && ls /etc/openadapt/ca/*.crt >/dev/null 2>&1; then + bundle="$HOME/ca-bundle.crt" + cat /etc/ssl/certs/ca-certificates.crt /etc/openadapt/ca/*.crt > "$bundle" + export SSL_CERT_FILE="$bundle" REQUESTS_CA_BUNDLE="$bundle" + mkdir -p "$HOME/.pki/nssdb" + [ -f "$HOME/.pki/nssdb/cert9.db" ] || certutil -d "sql:$HOME/.pki/nssdb" -N --empty-password + for crt in /etc/openadapt/ca/*.crt; do + certutil -d "sql:$HOME/.pki/nssdb" -A -t "C,," -n "$(basename "$crt")" -i "$crt" + done +fi +exec "$@" diff --git a/packages/flow/deploy/connector/e2e/gen_certs.sh b/packages/flow/deploy/connector/e2e/gen_certs.sh new file mode 100755 index 0000000000..a22772a2ec --- /dev/null +++ b/packages/flow/deploy/connector/e2e/gen_certs.sh @@ -0,0 +1,12 @@ +#!/bin/sh +# A throwaway local CA and a server certificate for the private app's name. +set -eu +out="$1"; name="$2" +mkdir -p "$out" +openssl req -x509 -newkey rsa:2048 -nodes -days 7 -subj "/CN=byoc-pilot-local-ca" \ + -keyout "$out/ca.key" -out "$out/ca.crt" 2>/dev/null +openssl req -newkey rsa:2048 -nodes -subj "/CN=$name" -keyout "$out/notes.key" -out "$out/notes.csr" 2>/dev/null +printf 'subjectAltName=DNS:%s\nextendedKeyUsage=serverAuth\n' "$name" > "$out/ext.cnf" +openssl x509 -req -in "$out/notes.csr" -CA "$out/ca.crt" -CAkey "$out/ca.key" -CAcreateserial \ + -days 7 -extfile "$out/ext.cnf" -out "$out/notes.crt" 2>/dev/null +rm -f "$out/notes.csr" "$out/ext.cnf" "$out/ca.srl" diff --git a/packages/flow/deploy/connector/e2e/notes_app.py b/packages/flow/deploy/connector/e2e/notes_app.py new file mode 100644 index 0000000000..dc636d056b --- /dev/null +++ b/packages/flow/deploy/connector/e2e/notes_app.py @@ -0,0 +1,126 @@ +"""Synthetic notes app for the customer-run runner end-to-end check. + +It stands in for an internal application: it is reachable only on the private +Docker network, under a DNS name that does not resolve on the public internet, +over HTTPS signed by a local CA. It holds made-up records that include canary +strings; the check then searches everything the runner sent for them. + +* ``GET /`` the notes form (what the program types into) +* ``POST /save`` saves a note +* ``GET /api/notes`` the records, for the program's independent read-back; + requires ``X-Api-Key`` (the runner's local secret) + +Synthetic data only. +""" + +from __future__ import annotations + +import html +import json +import os +import ssl +import threading +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from pathlib import Path +from urllib.parse import parse_qs + +API_KEY = os.environ["NOTES_READER_KEY"] +STORE = Path(os.environ.get("NOTES_STORE", "/data/notes.json")) +CANARY = os.environ.get("NOTES_CANARY", "ZQX-CANARY-RECORD") +LOCK = threading.Lock() + +PAGE = """Notes + +

Notes

Notes + + +
Notes: clinic notebook, list demo
Notes: clinic notebook, list demo
{msg}
    {items}
""" + + +def records() -> list[dict]: + if not STORE.exists(): + STORE.parent.mkdir(parents=True, exist_ok=True) + STORE.write_text("[]") + return json.loads(STORE.read_text()) + + +def seed_canaries() -> None: + """Add made-up records that hold canary strings. Run after the program is + published, as real records would exist only at run time.""" + with LOCK: + current = records() + next_id = (current[-1]["id"] + 1) if current else 1 + for n, text in enumerate( + ( + f"{CANARY}-1 synthetic patient Jane Roe DOB 1970-01-01", + f"{CANARY}-2 synthetic MRN 000-111-222", + ) + ): + current.append( + {"id": next_id + n, "note": text, "list": "demo", "key": "clinic"} + ) + STORE.write_text(json.dumps(current)) + + +class Handler(BaseHTTPRequestHandler): + def _send(self, code: int, body: bytes, ctype: str) -> None: + self.send_response(code) + self.send_header("content-type", ctype) + self.send_header("cache-control", "no-store") + self.send_header("content-length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def _page(self, msg: str = "") -> None: + items = "".join(f"
  • {html.escape(r['note'])}
  • " for r in records()) + self._send( + 200, PAGE.format(msg=msg, items=items).encode(), "text/html; charset=utf-8" + ) + + def do_GET(self) -> None: # noqa: N802 + if self.path == "/": + return self._page() + if self.path == "/api/notes": + if self.headers.get("x-api-key") != API_KEY: + return self._send(401, b'{"error":"unauthorized"}', "application/json") + return self._send( + 200, json.dumps({"records": records()}).encode(), "application/json" + ) + self._send(404, b"not found", "text/plain") + + def do_POST(self) -> None: # noqa: N802 + if self.path != "/save": + return self._send(404, b"not found", "text/plain") + length = min(int(self.headers.get("content-length") or 0), 2000) + note = (parse_qs(self.rfile.read(length).decode()).get("note") or [""])[0][:200] + with LOCK: + current = records() + if note: + next_id = (current[-1]["id"] + 1) if current else 1 + current.append( + {"id": next_id, "note": note, "list": "demo", "key": "clinic"} + ) + STORE.write_text(json.dumps(current[-500:])) + self._page("

    Saved!

    ") + + def log_message(self, fmt: str, *args: object) -> None: + print("notes:", self.command, self.path, flush=True) + + +def main() -> None: + server = ThreadingHTTPServer(("0.0.0.0", 443), Handler) + ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) + ctx.minimum_version = ssl.TLSVersion.TLSv1_2 + ctx.load_cert_chain(os.environ["NOTES_CERT"], os.environ["NOTES_KEY"]) + server.socket = ctx.wrap_socket(server.socket, server_side=True) + print("notes app listening on 443", flush=True) + server.serve_forever() + + +if __name__ == "__main__": + import sys + + if sys.argv[1:] == ["seed-canaries"]: + seed_canaries() + else: + main() diff --git a/packages/flow/deploy/connector/e2e/publish.py b/packages/flow/deploy/connector/e2e/publish.py new file mode 100644 index 0000000000..30d2aae4d4 --- /dev/null +++ b/packages/flow/deploy/connector/e2e/publish.py @@ -0,0 +1,5 @@ +import sys + +from openadapt_flow.wrap import publish + +sys.exit(publish.main(sys.argv[1:])) diff --git a/packages/flow/deploy/connector/e2e/run_e2e.sh b/packages/flow/deploy/connector/e2e/run_e2e.sh new file mode 100755 index 0000000000..611a25b3b5 --- /dev/null +++ b/packages/flow/deploy/connector/e2e/run_e2e.sh @@ -0,0 +1,79 @@ +#!/bin/sh +# End-to-end check of the customer-run runner against a staging control plane. +# +# run_e2e.sh up private network, synthetic app, egress proxy +# run_e2e.sh publish teach, admit and publish the program (author side) +# run_e2e.sh runner start the connector (needs $STATE/connector.toml) +# run_e2e.sh down remove everything +# +# Topology: the app and the runner sit on an --internal network with no route +# out. The only way out is the egress proxy, which logs every request in full +# and refuses any host not on EGRESS_ALLOWED_HOSTS. The app's name resolves +# only inside the private network. Synthetic data only. +set -eu +CTR="${CTR:-docker}" +HERE="$(cd "$(dirname "$0")" && pwd)" +STATE="${STATE:?set STATE to a durable directory}" +APP_HOST="${APP_HOST:-notes.byoc-pilot.openadapt.ai}" +CLOUD_HOST="${CLOUD_HOST:-openadapt-cloud-staging.netlify.app}" +RUNNER_IMAGE="${RUNNER_IMAGE:-openadapt-connector:pilot-dev}" +PUBLISHER_IMAGE="${PUBLISHER_IMAGE:-byoc-publisher:3.1.0}" +PROXY_IMAGE="${PROXY_IMAGE:-mitmproxy/mitmproxy:11.1.3}" +PROXY="http://egress-proxy:8080" + +up() { + mkdir -p "$STATE/certs" "$STATE/mitm" "$STATE/log" "$STATE/notes-data" "$STATE/ca" + [ -f "$STATE/certs/ca.crt" ] || "$HERE/gen_certs.sh" "$STATE/certs" "$APP_HOST" + [ -f "$STATE/secrets/notes-reader.env" ] || { + mkdir -p "$STATE/secrets" + printf 'NOTES_READER_KEY=ZQX-CANARY-SECRET-%s\n' "$(openssl rand -hex 8)" > "$STATE/secrets/notes-reader.env" + chmod 600 "$STATE/secrets/notes-reader.env" + } + $CTR network inspect byoc-private >/dev/null 2>&1 || $CTR network create --internal byoc-private >/dev/null + $CTR network inspect byoc-egress >/dev/null 2>&1 || $CTR network create byoc-egress >/dev/null + $CTR rm -f byoc-notes byoc-egress-proxy >/dev/null 2>&1 || true + $CTR run -d --name byoc-notes --network byoc-private --network-alias "$APP_HOST" \ + --env-file "$STATE/secrets/notes-reader.env" \ + -e NOTES_CERT=/certs/notes.crt -e NOTES_KEY=/certs/notes.key -e NOTES_STORE=/data/notes.json \ + -v "$STATE/certs:/certs:ro" -v "$STATE/notes-data:/data" -v "$HERE/notes_app.py:/app/notes_app.py:ro" \ + python:3.12-slim-bookworm python /app/notes_app.py >/dev/null + $CTR run -d --name byoc-egress-proxy --network byoc-egress \ + -e EGRESS_ALLOWED_HOSTS="$CLOUD_HOST" -e EGRESS_LOG=/log/egress.jsonl \ + -v "$STATE/mitm:/home/mitmproxy/.mitmproxy" -v "$STATE/log:/log" -v "$HERE/egress_log.py:/addon/egress_log.py:ro" \ + "$PROXY_IMAGE" mitmdump --listen-port 8080 -s /addon/egress_log.py --set block_global=false >/dev/null + $CTR network connect --alias egress-proxy byoc-private byoc-egress-proxy + i=0; until [ -f "$STATE/mitm/mitmproxy-ca-cert.pem" ] || [ $i -gt 30 ]; do i=$((i+1)); sleep 1; done + cp "$STATE/certs/ca.crt" "$STATE/ca/app-ca.crt" + cp "$STATE/mitm/mitmproxy-ca-cert.pem" "$STATE/ca/egress-proxy-ca.crt" + echo "up: app at https://$APP_HOST (private only), egress via $PROXY" +} + +publish() { + mkdir -p "$STATE/work" + cp "$HERE/teach_admit.py" "$STATE/work/teach_admit.py" + $CTR run --rm --name byoc-publisher --network byoc-private \ + -e HTTPS_PROXY="$PROXY" -e HTTP_PROXY="$PROXY" -e NO_PROXY="$APP_HOST" \ + -e NOTES_ORIGIN="https://$APP_HOST" \ + --env-file "$STATE/secrets/notes-reader.env" \ + --env-file "$STATE/publisher.env" \ + -v "$STATE/ca:/etc/openadapt/ca:ro" -v "$STATE/work:/work" -w /work \ + "$PUBLISHER_IMAGE" sh -c "${PUBLISH_CMD:?set PUBLISH_CMD}" +} + +runner() { + $CTR rm -f byoc-runner >/dev/null 2>&1 || true + $CTR run -d --name byoc-runner --network byoc-private \ + --read-only --tmpfs /tmp --tmpfs /home/openadapt \ + -e HTTPS_PROXY="$PROXY" -e HTTP_PROXY="$PROXY" -e NO_PROXY="$APP_HOST" \ + -e OPENADAPT_HOME=/etc/openadapt \ + -v "$STATE/runner-etc:/etc/openadapt" -v "$STATE/runner-storage:/srv/openadapt" \ + "$RUNNER_IMAGE" ${RUNNER_CMD:-openadapt-flow connector run} >/dev/null + echo "runner started; logs: $CTR logs -f byoc-runner" +} + +down() { + $CTR rm -f byoc-runner byoc-publisher byoc-notes byoc-egress-proxy >/dev/null 2>&1 || true + $CTR network rm byoc-private byoc-egress >/dev/null 2>&1 || true +} + +"${1:?up|publish|runner|down}" diff --git a/packages/flow/deploy/connector/e2e/teach_admit.py b/packages/flow/deploy/connector/e2e/teach_admit.py new file mode 100644 index 0000000000..54de014dcc --- /dev/null +++ b/packages/flow/deploy/connector/e2e/teach_admit.py @@ -0,0 +1,144 @@ +"""End-to-end check, author side: run `openadapt wrap`'s first run offline: the wrap CLI's own task loader and +WrappedTask, with a scripted FrameworkAgent instead of a model provider. + +No model is called. The scripted agent reads the structural listing and acts +the way a model would. A throwaway admitter key admits the program after the +canary, as `--admit-key` does; the checks are confirmed by a named reviewer, as +`--person` does at a terminal. +""" + +import json +import os +import re +import sys +import time +from pathlib import Path + +from openadapt_flow.approval_mode.approver_roster import ROOT_ENV +from openadapt_flow.integrations.agents.recording import load_task +from openadapt_flow.integrations.agents.skills import FrameworkAgent +from openadapt_flow.jit import authority +from openadapt_flow.jit.keys import CustomerModelKey +from openadapt_flow.teach_authorization_fixture import LocalAuthorizer +from openadapt_flow.wrap import WrappedTask + +R = Path(sys.argv[1]) +request_id, note = sys.argv[2], sys.argv[3] +os.environ.setdefault(authority.KEY_PASSPHRASE_ENV, "byoc-pilot-synthetic-passphrase") +key_dir = R / "keys" +pem = R / ("keys" + "-files") / "ci.pem" +if not pem.is_file(): + pem.parent.mkdir(parents=True, exist_ok=True) + authority.register_principal( + key_dir, + role="admitter_key", + principal_id="ci:byoc-pilot-admitter", + public_key_hex=authority.generate_encrypted_key(pem), + ) +admitter = authority.principal_from_key(authority.load_encrypted_key(pem), key_dir) + + +def ref(listing: str, name: str) -> str: + for line in listing.splitlines(): + m = re.search(r"\[(e\d+)\] \S+ \"" + re.escape(name) + '"', line) + if m: + return m.group(1) + raise AssertionError(f"no {name!r} in listing:\n{listing}") + + +def run(task: str, tools): + value = task.split("text ", 1)[1] + listing = tools.observe() + listing = tools.type_text(value, ref(listing, "Note")) + listing = tools.click(ref(listing, "Save")) + tools.finish("saved") + return { + "calls": [ + { + "input_tokens": 0, + "output_tokens": 0, + "total_tokens": 0, + "cache_creation_input_tokens": 0, + "cache_read_input_tokens": 0, + } + ] + } + + +setup = load_task( + R / "task.json", + offer=lambda proposal: "ci:byoc-pilot-reviewer", + admitter=admitter, + key_dir=key_dir, + model_key=CustomerModelKey("anthropic", "env:TEST_ONLY", "not-a-real-key"), +) +# A person's signed teach authorization for this task (what the exploring +# agent may do), as `--teach-authorization` passes. Throwaway roster keys. + +task_id = setup.cache.task_id(setup.instruction, {"note": note}) +folder = R / ("keys" + "-teach") / task_id +root_pin = R / "keys-root.ok" +root = ( + LocalAuthorizer(key_dir, "ci:byoc-pilot-roster-admin") + if not root_pin.exists() + else None +) +if root is not None: + root_pin.write_text(root.root) +pinned_root = root_pin.read_text().strip() +if not re.fullmatch(r"[0-9a-f]{64}", pinned_root): + raise ValueError("test approver root pin is invalid; use a fresh work directory") +os.environ[ROOT_ENV] = pinned_root +lead = ( + LocalAuthorizer(key_dir, "ci:byoc-pilot-teach-lead", added_by=root) + if root is not None + else None +) +if lead is not None: + os.environ[ROOT_ENV] = lead.root + statement = lead.issue( + folder, + { + "task": { + "task_id": task_id, + "summary": "Add a note to the clinic notebook", + }, + "purposes": ["teach", "repair"], + "origins": [os.environ["NOTES_ORIGIN"]], + "inputs": {"note": {"value": note}}, + "constants": [{"value": "Notes"}], + "writes": { + "record_kind": "note", + "identity": {"list": {"value": "demo"}}, + "fields": {"note": {"value": note}}, + }, + }, + ) + setup.cache.common["teach_authorization"] = lead.authority(statement) +agent = FrameworkAgent(run, principal_id="agent:scripted-byoc-pilot", model="scripted") +task = WrappedTask( + cache=setup.cache, + agent=agent, + instruction=setup.instruction, + parameters=setup.parameters, + runs_dir=R / "runs", +) +s = time.perf_counter() +if os.environ.get("REHEARSAL_DEBUG"): + run = setup.cache.run(setup.instruction, {"note": note}, agent) + print( + json.dumps( + {"status": run.status, "detail": run.detail, "compile": run.compile}, + default=str, + )[:4000] + ) + raise SystemExit(0 if run.status == "admitted" else 1) +result = task.call(request_id, {"note": note}) +print( + json.dumps( + {"seconds": round(time.perf_counter() - s, 2), "result": result}, default=str + )[:3000] +) + +if result.get("status") != "admitted": + raise SystemExit(1) diff --git a/packages/flow/deploy/connector/entrypoint.sh b/packages/flow/deploy/connector/entrypoint.sh new file mode 100755 index 0000000000..c1a4a1e0fe --- /dev/null +++ b/packages/flow/deploy/connector/entrypoint.sh @@ -0,0 +1,16 @@ +#!/bin/sh +# Trust any extra CA certificates the operator mounts (an internal CA for the +# target application, or a TLS-inspecting egress proxy), for Python and for +# the headless browser, then start the connector. +set -eu +if [ -d /etc/openadapt/ca ] && ls /etc/openadapt/ca/*.crt >/dev/null 2>&1; then + bundle="$HOME/ca-bundle.crt" + cat /etc/ssl/certs/ca-certificates.crt /etc/openadapt/ca/*.crt > "$bundle" + export SSL_CERT_FILE="$bundle" REQUESTS_CA_BUNDLE="$bundle" + mkdir -p "$HOME/.pki/nssdb" + [ -f "$HOME/.pki/nssdb/cert9.db" ] || certutil -d "sql:$HOME/.pki/nssdb" -N --empty-password + for crt in /etc/openadapt/ca/*.crt; do + certutil -d "sql:$HOME/.pki/nssdb" -A -t "C,," -n "$(basename "$crt")" -i "$crt" + done +fi +exec "$@" diff --git a/packages/flow/deploy/connector/systemd/openadapt-connector.service b/packages/flow/deploy/connector/systemd/openadapt-connector.service new file mode 100644 index 0000000000..3813c5b795 --- /dev/null +++ b/packages/flow/deploy/connector/systemd/openadapt-connector.service @@ -0,0 +1,43 @@ +# OpenAdapt connector (customer-run runner). Outbound HTTPS only; listens on +# no port. Install the pinned Flow release into /opt/openadapt first, put +# connector.toml (mode 0600) in /etc/openadapt, then: +# useradd --system --home /var/lib/openadapt openadapt +# systemctl enable --now openadapt-connector +[Unit] +Description=OpenAdapt connector (customer-run runner) +After=network-online.target +Wants=network-online.target + +[Service] +Type=simple +User=openadapt +Group=openadapt +Environment=OPENADAPT_HOME=/etc/openadapt +# Uncomment to route the only outbound connection through your proxy. +# Environment=HTTPS_PROXY=http://proxy.internal:3128 +ExecStart=/opt/openadapt/bin/openadapt-flow connector run +Restart=on-failure +RestartSec=10 +# Stopping the service ends the loop. The connector stops each governed run +# itself and reports one that was mid-run as uncertain (child_outcome_unknown, +# held for a person, never re-run automatically). KillMode=mixed sends SIGINT +# to the connector only, so the default control-group kill does not signal +# the governed children first; anything still left at TimeoutStopSec is +# killed. +KillSignal=SIGINT +KillMode=mixed +TimeoutStopSec=60 + +# Hardening +NoNewPrivileges=true +PrivateTmp=true +ProtectSystem=strict +ProtectHome=true +ReadWritePaths=/srv/openadapt /etc/openadapt +StateDirectory=openadapt +CapabilityBoundingSet= +RestrictAddressFamilies=AF_INET AF_INET6 AF_UNIX +LockPersonality=true + +[Install] +WantedBy=multi-user.target diff --git a/packages/flow/docs/BYOC_CONNECTOR.md b/packages/flow/docs/BYOC_CONNECTOR.md index adfd589f29..0c95344f7a 100644 --- a/packages/flow/docs/BYOC_CONNECTOR.md +++ b/packages/flow/docs/BYOC_CONNECTOR.md @@ -152,15 +152,55 @@ with code 2; run `connector run` under systemd or launchd instead. only the verified copy. A pre-verification failure never echoes the unverified digest claim in its callback. -**Fail-closed everywhere.** A dispatch is refused (reported `failed`, no GUI -touched) when it is missing the governed safety policy, missing the run-scoped -callback token, exact archive digest, or execution substrate; carries an -our-owned signed URL; points at archive bytes that do not match the signed -digest; conflicts with the substrate compatibility hint; or enables a grounding -rung whose API key env is not set on this machine. The governed `run` itself -refuses any bundle that is not certified, identity-armed, effect-verified, and -encrypted — those engine gates are unchanged, so identity checks, effect -verification, and halt-don't-guess all remain intact. +A live job requires the exact retained `managed_dispatch_session_id`, a +run-scoped callback capability, a closed managed authority and its bundle +binding. The connector advertises `managed_delivery_authority_v3`; older +qualification-v2 capability alone cannot lease these jobs. Parsing an older +payload does not authorize execution or let it inherit a daemon's session. +The per-run session enters the child environment and must match the signed +v3 delivery response. Each live input needs a fresh signed input-start deadline. + +Authority has two declared forms. A qualified workflow carries the signed +admission v2 artifact and its digest. A program carries either the closed +person reference v1 or registered-admitter reference v2. Unknown or mixed +fields, a different run or organization, conflicting digests, an unpinned key, +and an admitter-to-person downgrade are refused before input. Only after these +extensions are consumed does the connector write the exact six-field Flow +envelope to an owner-only local file. + +Programs use operator-pinned public admission keys. An admitter reference also +requires the current local principal registry, matching principal/key fields +and the exact signed admission. Configure `admission_key_dir` as a public-only, +read-only directory; keep signing material elsewhere. The shared runtime reads +that live registry again at input edges. A person key staged without that +directory is a snapshot and does not provide live local principal revocation. +Remote v3 permit checks remain mandatory for both forms. + +Qualified jobs additionally require an independent operator-owned +`ProductionQualificationAuthority` file. Its wrapper v1 contains the actual +signed admission v2, known expected runtime/deployment contracts and trusted +signer registry. The connector matches its proof and tenant, workflow, version, +validation, archive, content and substrate bindings, then the existing Flow +qualification guard verifies it against the sealed bundle. It never constructs +expected contracts from the remote proof itself. Set the path in +`connector.toml` or `BYOC_QUALIFICATION_AUTHORITY_FILE`: + +```toml +[connector] +qualification_authority_file = "/etc/openadapt/qualification-authority.json" +``` + +That file is owner-only and must match each qualified job exactly. Absent, +changed or unrelated local context refuses the job. Its verified canonical +wrapper is handed to the child through the existing +`--qualification-authority-file` channel; the runtime-local qualification field +stays null on the Cloud wire. The operator's deployment profile and default +per-save approval gate remain authoritative. + +A dispatch also refuses a missing safety policy, archive digest or substrate, +an our-owned bundle URL, conflicting substrate hints and a required grounding +key absent from this machine. The governed child rechecks its normal admission, +identity, effect and storage requirements before execution. The callback is retried a bounded three times. The Connector ACKs a job only after the control plane accepts its outcome. If delivery still fails, the lease @@ -175,34 +215,17 @@ The lane is off by default. An operator enables it with (`RUNNER_SHARED_SECRET`), then sets the organization's `deployment_kind` to `byoc`. See openadapt-cloud `src/lib/byocLane.ts`. -## What works today vs. what remains for production - -**Works end to end (this release):** - -* enrollment -> per-connector token -> outbound poll/lease; -* governed local execution via `openadapt-flow run` (fail-closed admission + - Replayer) against the customer's own `local` storage; -* PHI-free status/halt/metrics callback with the run-scoped token + bundle - binding the control plane verifies; -* cross-org isolation (a Connector only ever leases its own org's jobs); -* the resolved safety + grounding policy delivered and applied fail-closed. - -**Remaining for production:** - -* **Private transport options.** Connector tokens are organization-scoped, - revocable, and stored only as hashes in Cloud. Deployments that require - mTLS/private-link add that transport at the customer network boundary. -* **Full policy materialization.** The delivered safety block governs *dispatch* - and the two fail-closed gates above; materializing every safety key into the - engine's runtime config (so e.g. the delivered grounding endpoint is the one - the Replayer dials) is the same cross-runner "runner-side consumption" half the - Modal and Windows runners have not finished either. The operator's local - `deployment.yaml` (`--config`) is authoritative for the engine posture today. -* **S3 / Azure Blob customer storage.** Only `local` is built into the engine - Connector; the operator-reference agent (openadapt-cloud `connector/agent.py`) - carries S3/Azure backends that need a customer cloud to exercise. -* **Autoscaling / HA.** One Connector process, one lease at a time; production - wants supervised restart, multiple Connectors per org, and a server-side lease - reaper for a Connector that dies mid-run. -* **Customer-facing install/packaging.** A signed installer / container image and - an operator runbook (partly in openadapt-cloud `deploy/byoc/`). +## Qualification and operating scope + +The source tests exercise an in-process control plane, actual program and +qualification signatures, exact file parsing, session binding, egress refusal, +rotation, cancellation and uncertain lease handling. These are synthetic source +controls. A complete managed BYOC run on a real system of record has not yet +been established by this change. + +The engine connector currently reads exact archives and writes reports through +its `local` customer-storage backend. The local deployment profile governs the +engine posture: the delivered safety block does not materialize every runtime +setting, including grounding endpoints. Operators must qualify that profile and +the installed runtime together. Container/service supervision and separate +customer network controls remain part of the deployment. diff --git a/packages/flow/docs/commands/09-share-with-cloud/connector.md b/packages/flow/docs/commands/09-share-with-cloud/connector.md index e69de29bb2..81c8be20c1 100644 --- a/packages/flow/docs/commands/09-share-with-cloud/connector.md +++ b/packages/flow/docs/commands/09-share-with-cloud/connector.md @@ -0,0 +1 @@ +Run an outbound connector with local secrets, pinned admission keys, signed requests, token rotation, heartbeats and cancellation. diff --git a/packages/flow/docs/design/DECOMPOSITION.md b/packages/flow/docs/design/DECOMPOSITION.md index aa0e4991a6..cc6361e755 100644 --- a/packages/flow/docs/design/DECOMPOSITION.md +++ b/packages/flow/docs/design/DECOMPOSITION.md @@ -608,7 +608,7 @@ PR #2295 raised `replayer.py`, `ir.py`, `interactive_recorder.py` and `playwrigh | File | Line budget | |---|---:| | `packages/flow/openadapt_flow/runtime/replayer.py` | 19229 | -| `packages/flow/openadapt_flow/__main__.py` | 14331 | +| `packages/flow/openadapt_flow/__main__.py` | 14237 | | `packages/flow/openadapt_flow/qualification/__init__.py` | 4891 | | `packages/flow/openadapt_flow/ir.py` | 6830 | | `packages/desktop/openadapt_desktop/dispatch.py` | 6524 | diff --git a/packages/flow/openadapt_flow/__main__.py b/packages/flow/openadapt_flow/__main__.py index 195b1b4bc7..49b0fe6825 100644 --- a/packages/flow/openadapt_flow/__main__.py +++ b/packages/flow/openadapt_flow/__main__.py @@ -13151,7 +13151,7 @@ def _repair_store_flag(rp: argparse.ArgumentParser) -> None: ps.add_argument("--once", action="store_true", help="Run one relay cycle and exit") ps.set_defaults(func=_cmd_business_decisions_serve) - from openadapt_flow.cli_connector import register_connector_parser + from openadapt_flow.connector.cli import register_connector_parser register_connector_parser(sub, _cmd_connector) @@ -13483,93 +13483,17 @@ def _cmd_serve_reward(args: argparse.Namespace) -> int: def _connector_flags(args: argparse.Namespace) -> dict[str, object]: - """Collect the connector CLI flags into the settings-resolution dict.""" - keys = ( - "control_plane_url", - "token", - "org_id", - "name", - "profile", - "policy", - "storage_backend", - "storage_root", - "poll_wait", - ) - return { - k: getattr(args, k, None) for k in keys if getattr(args, k, None) is not None - } - - -def _cmd_connector(args: argparse.Namespace) -> int: - """The BYOC connector: enroll this machine, or run governed jobs locally. - - Both sub-verbs are thin wrappers over :mod:`openadapt_flow.connector`. The - engine ships the connector so a dispatched run is the SAME fail-closed - ``openadapt-flow run`` admission gate + governed Replayer the local CLI uses, - executed inside the customer perimeter against the customer's own storage. - """ - import os + """Keep the historical connector settings helper importable.""" + from openadapt_flow.connector.cli import _connector_flags as collect - from openadapt_flow.connector import ( - ConnectorClient, - ConnectorClientError, - load_settings, - run_loop, - save_enrollment, - ) - from openadapt_flow.connector.config import ConnectorConfigError - from openadapt_flow.connector.executor import _subprocess_runner + return collect(args) - verb = getattr(args, "connector_cmd", None) - try: - settings = load_settings(_connector_flags(args)) - except ConnectorConfigError as exc: - print(f"connector: {exc}") - return 2 - if verb == "enroll": - enrollment_secret = getattr(args, "enrollment_secret", None) or os.environ.get( - "BYOC_ENROLLMENT_SECRET" - ) - client = ConnectorClient(settings.control_plane_url) - try: - data = client.enroll( - enrollment_secret=enrollment_secret, - org_id=settings.org_id, - name=settings.name, - ) - except ConnectorClientError as exc: - print(f"connector enroll failed: {exc}") - return 1 - finally: - client.close() - settings.token = data.get("token") or settings.token - settings.org_id = data.get("org_id") or settings.org_id - path = save_enrollment(settings) - print( - f"enrolled connector {data.get('connector_id', '?')} for org " - f"{settings.org_id}; token persisted to {path} (0600)." - ) - return 0 +def _cmd_connector(args: argparse.Namespace) -> int: + """Dispatch connector commands through the focused CLI helper.""" + from openadapt_flow.connector.cli import _cmd_connector as command - # verb == "run" - if not settings.token: - print( - "connector run: no token. Create an organization connector in " - "OpenAdapt Cloud → Settings, then pass --token or set " - "BYOC_CONNECTOR_TOKEN." - ) - return 2 - client = ConnectorClient(settings.control_plane_url, token=settings.token) - try: - return run_loop( - client, - settings, - runner=_subprocess_runner, - once=bool(getattr(args, "once", False)), - ) - finally: - client.close() + return command(args) def _cmd_business_decisions_serve(args: argparse.Namespace) -> int: diff --git a/packages/flow/openadapt_flow/cli_connector.py b/packages/flow/openadapt_flow/cli_connector.py deleted file mode 100644 index 7bdc3a82f4..0000000000 --- a/packages/flow/openadapt_flow/cli_connector.py +++ /dev/null @@ -1,79 +0,0 @@ -"""Register the connector command family outside the main CLI entrypoint.""" - -from __future__ import annotations - -import argparse -from typing import Callable - - -def register_connector_parser( - sub: argparse._SubParsersAction, - dispatch: Callable[[argparse.Namespace], int], -) -> None: - # --- connector: the BYOC (bring-your-own-cloud) outbound-pull daemon ------- - p = sub.add_parser( - "connector", - help=( - "BYOC connector: enroll this machine with OpenAdapt Cloud and run " - "governed jobs LOCALLY (customer owns the data boundary; PHI stays " - "on this side)" - ), - allow_abbrev=False, - ) - csub = p.add_subparsers(dest="connector_cmd", required=True) - - pe = csub.add_parser( - "enroll", - help="Enroll against a mock/development control plane and persist its token", - allow_abbrev=False, - ) - pe.add_argument( - "--control-plane-url", help="Control plane base URL (or CONTROL_PLANE_URL)" - ) - pe.add_argument( - "--enrollment-secret", help="Org enrollment secret (or BYOC_ENROLLMENT_SECRET)" - ) - pe.add_argument("--org-id", help="Org id to enroll under (or BYOC_ORG_ID)") - pe.add_argument("--name", help="Connector name (or BYOC_CONNECTOR_NAME)") - pe.add_argument( - "--profile", help="Path to the deployment.yaml governed runs use as --config" - ) - pe.add_argument( - "--policy", help="Pinned admitted policy name (else the deployment config's)" - ) - pe.add_argument("--storage-backend", help="Customer storage backend (local)") - pe.add_argument( - "--storage-root", - help="Customer storage root dir (a full-disk-encrypted volume)", - ) - pe.set_defaults(func=dispatch) - - pr = csub.add_parser( - "run", - help="Poll the control plane and run governed jobs until interrupted", - allow_abbrev=False, - ) - pr.add_argument( - "--control-plane-url", help="Control plane base URL (or CONTROL_PLANE_URL)" - ) - pr.add_argument("--token", help="Per-connector token (or BYOC_CONNECTOR_TOKEN)") - pr.add_argument("--org-id", help="Org id (or BYOC_ORG_ID)") - pr.add_argument( - "--profile", help="Path to the deployment.yaml governed runs use as --config" - ) - pr.add_argument( - "--policy", help="Pinned admitted policy name (else the deployment config's)" - ) - pr.add_argument("--storage-backend", help="Customer storage backend (local)") - pr.add_argument("--storage-root", help="Customer storage root dir") - pr.add_argument( - "--poll-wait", type=int, help="Long-poll wait seconds (or BYOC_POLL_WAIT_S)" - ) - pr.add_argument( - "--once", action="store_true", help="Poll once then exit (cron-style)" - ) - pr.set_defaults(func=dispatch) - - from openadapt_flow.connector.windows_service import register_service_parser - - register_service_parser(csub) diff --git a/packages/flow/openadapt_flow/connector/cli.py b/packages/flow/openadapt_flow/connector/cli.py new file mode 100644 index 0000000000..7036e0b5be --- /dev/null +++ b/packages/flow/openadapt_flow/connector/cli.py @@ -0,0 +1,266 @@ +"""Connector CLI registration and handlers; governed execution stays shared.""" + +from __future__ import annotations + +import argparse +from typing import Callable + + +def register_connector_parser( + sub: argparse._SubParsersAction, command: Callable[[argparse.Namespace], int] +) -> None: + """Register the existing connector commands with the caller's callback.""" + p = sub.add_parser( + "connector", + help=( + "BYOC connector: enroll this machine with OpenAdapt Cloud and run " + "governed jobs LOCALLY (customer owns the data boundary; PHI stays " + "on this side)" + ), + allow_abbrev=False, + ) + csub = p.add_subparsers(dest="connector_cmd", required=True) + + pe = csub.add_parser( + "enroll", + help="Enroll against a mock/development control plane and persist its token", + allow_abbrev=False, + ) + pe.add_argument( + "--control-plane-url", help="Control plane base URL (or CONTROL_PLANE_URL)" + ) + pe.add_argument( + "--enrollment-secret", help="Org enrollment secret (or BYOC_ENROLLMENT_SECRET)" + ) + pe.add_argument("--org-id", help="Org id to enroll under (or BYOC_ORG_ID)") + pe.add_argument("--name", help="Connector name (or BYOC_CONNECTOR_NAME)") + pe.add_argument( + "--profile", help="Path to the deployment.yaml governed runs use as --config" + ) + pe.add_argument( + "--policy", help="Pinned admitted policy name (else the deployment config's)" + ) + pe.add_argument("--storage-backend", help="Customer storage backend (local)") + pe.add_argument( + "--storage-root", + help="Customer storage root dir (a full-disk-encrypted volume)", + ) + pe.set_defaults(func=command) + + pr = csub.add_parser( + "run", + help="Poll the control plane and run governed jobs until interrupted", + allow_abbrev=False, + ) + pr.add_argument( + "--control-plane-url", help="Control plane base URL (or CONTROL_PLANE_URL)" + ) + pr.add_argument("--token", help="Per-connector token (or BYOC_CONNECTOR_TOKEN)") + pr.add_argument("--org-id", help="Org id (or BYOC_ORG_ID)") + pr.add_argument( + "--profile", help="Path to the deployment.yaml governed runs use as --config" + ) + pr.add_argument( + "--policy", help="Pinned admitted policy name (else the deployment config's)" + ) + pr.add_argument("--storage-backend", help="Customer storage backend (local)") + pr.add_argument("--storage-root", help="Customer storage root dir") + pr.add_argument( + "--poll-wait", type=int, help="Long-poll wait seconds (or BYOC_POLL_WAIT_S)" + ) + pr.add_argument( + "--once", action="store_true", help="Poll once then exit (cron-style)" + ) + pr.add_argument( + "--secrets-dir", + help="Local secret store: /.env, mode 0600 (or BYOC_SECRETS_DIR)", + ) + pr.add_argument( + "--trusted-admission-keys", + help=( + "Comma-separated Ed25519 public keys of the program admitters this " + "runner trusts (or BYOC_TRUSTED_ADMISSION_KEYS)" + ), + ) + pr.add_argument( + "--default-secrets-ref", + help="Local secret reference used when a job names none", + ) + pr.add_argument( + "--admission-key-dir", + help="Customer-owned Flow admission key directory (public keys only)", + ) + pr.add_argument( + "--egress-audit-log", + help="Append every request body sent to this local JSONL file", + ) + pr.add_argument( + "--max-workers", type=int, help="Local ceiling on parallel jobs (1-16)" + ) + pr.set_defaults(func=command) + + pt = csub.add_parser( + "rotate-token", + help="Swap this connector's token now and persist the new one (0600)", + allow_abbrev=False, + ) + pt.add_argument( + "--control-plane-url", help="Control plane base URL (or CONTROL_PLANE_URL)" + ) + pt.set_defaults(func=command) + + from openadapt_flow.connector.windows_service import register_service_parser + + register_service_parser(csub) + + +def _connector_flags(args: argparse.Namespace) -> dict[str, object]: + """Collect the connector CLI flags into the settings-resolution dict.""" + keys = ( + "control_plane_url", + "token", + "org_id", + "name", + "profile", + "policy", + "storage_backend", + "storage_root", + "poll_wait", + "secrets_dir", + "trusted_admission_keys", + "egress_audit_log", + "max_workers", + "admission_key_dir", + "default_secrets_ref", + ) + return { + k: getattr(args, k, None) for k in keys if getattr(args, k, None) is not None + } + + +def _cmd_connector(args: argparse.Namespace) -> int: + """The BYOC connector: enroll this machine, or run governed jobs locally. + + Both sub-verbs are thin wrappers over :mod:`openadapt_flow.connector`. The + engine ships the connector so a dispatched run is the SAME fail-closed + ``openadapt-flow run`` admission gate + governed Replayer the local CLI uses, + executed inside the customer perimeter against the customer's own storage. + """ + import os + + from openadapt_flow.connector import ( + ConnectorClient, + ConnectorClientError, + load_settings, + run_loop, + save_enrollment, + ) + from openadapt_flow.connector.config import ConnectorConfigError + from openadapt_flow.connector.executor import _subprocess_runner + + verb = getattr(args, "connector_cmd", None) + try: + settings = load_settings(_connector_flags(args)) + except ConnectorConfigError as exc: + print(f"connector: {exc}") + return 2 + + if verb == "enroll": + enrollment_secret = getattr(args, "enrollment_secret", None) or os.environ.get( + "BYOC_ENROLLMENT_SECRET" + ) + client = ConnectorClient(settings.control_plane_url) + try: + data = client.enroll( + enrollment_secret=enrollment_secret, + org_id=settings.org_id, + name=settings.name, + ) + except ConnectorClientError as exc: + print(f"connector enroll failed: {exc}") + return 1 + finally: + client.close() + settings.token = data.get("token") or settings.token + settings.org_id = data.get("org_id") or settings.org_id + path = save_enrollment(settings) + print( + f"enrolled connector {data.get('connector_id', '?')} for org " + f"{settings.org_id}; token persisted to {path} (0600)." + ) + return 0 + + from openadapt_flow.connector.config import connector_config_path + + def persist_token(new_token: str) -> None: + settings.token = new_token + settings.pending_token = None + save_enrollment(settings) + + def persist_pending(new_token: str) -> None: + settings.pending_token = new_token + save_enrollment(settings) + + can_persist = connector_config_path().is_file() + + if verb == "rotate-token": + if not settings.token or not can_persist: + print( + "connector rotate-token: needs an enrolled connector.toml " + f"({connector_config_path()}) holding the current token." + ) + return 2 + from openadapt_flow.connector.daemon import finish_rotation, maybe_rotate + + client = ConnectorClient(settings.control_plane_url, token=settings.token) + try: + if settings.pending_token: + ok = finish_rotation( + client, settings.pending_token, persist_token, print + ) + else: + ok = maybe_rotate( + client, + persist_token, + print, + persist_pending=persist_pending, + force=True, + ) + finally: + client.close() + if not ok: + print("connector rotate-token failed; the current token still works.") + return 1 + print( + "token rotated and persisted (0600); the previous token stops within 5 minutes." + ) + return 0 + + # verb == "run" + if not settings.token: + print( + "connector run: no token. Create an organization connector in " + "OpenAdapt Cloud → Settings, then pass --token or set " + "BYOC_CONNECTOR_TOKEN." + ) + return 2 + client = ConnectorClient( + settings.control_plane_url, + token=settings.token, + egress_audit_log=settings.egress_audit_log, + ) + try: + if settings.pending_token and can_persist: + from openadapt_flow.connector.daemon import finish_rotation + + finish_rotation(client, settings.pending_token, persist_token, print) + return run_loop( + client, + settings, + runner=_subprocess_runner, + once=bool(getattr(args, "once", False)), + persist_token=persist_token if can_persist else None, + persist_pending=persist_pending if can_persist else None, + ) + finally: + client.close() diff --git a/packages/flow/openadapt_flow/connector/client.py b/packages/flow/openadapt_flow/connector/client.py index f091a182d5..2fd94fd52e 100644 --- a/packages/flow/openadapt_flow/connector/client.py +++ b/packages/flow/openadapt_flow/connector/client.py @@ -8,27 +8,41 @@ Endpoints (all outbound): * ``POST /api/connector/register`` mock/dev enrollment compatibility * ``POST /api/connector/poll`` long-poll -> lease the next job + * ``POST /api/connector/heartbeat`` liveness + control while jobs run * ``POST /api/connector/ack`` release the lease (done|failed) - * ``POST /api/internal/run-callback`` PHI-free status/metrics (existing boundary) + * ``POST /api/connector/rotate`` swap this connector's token + * ``POST /api/internal/run-callback`` metadata-only status and receipt -Auth: the organization-scoped per-connector token as ``Authorization: Bearer`` -on poll/ack and the run-scoped ``x-run-token`` on the callback. Live Cloud -mints the connector token through its authenticated settings API; the legacy -enrollment secret is used only by mock/development control planes. +Every body is built by :mod:`openadapt_flow.connector.egress` (a closed +allow-list) and scanned for local secret values before it is sent. Every +connector request is signed (timestamp, nonce, HMAC over method, path and body +digest) so a captured request cannot be replayed or altered. A custom ``transport`` (an :class:`httpx.BaseTransport`) may be injected so tests -drive the whole enroll -> poll -> callback -> ack loop with ZERO network. +drive the whole loop with ZERO network. """ from __future__ import annotations -from typing import Any, Optional +import hashlib +import hmac +import json +import os +import secrets as _secrets +import threading +import time +from dataclasses import dataclass, field +from typing import Any, Iterable, Optional import httpx +from openadapt_flow.connector import egress +from openadapt_flow.connector.protocol import MANAGED_DELIVERY_AUTHORITY_CAPABILITY from openadapt_flow.hosted import HostedError -MANAGED_QUALIFICATION_AUTHORITY_CAPABILITY = "managed_qualification_authority_v2" +# Retain the import name for callers; only the qualified v3 wire is advertised. +MANAGED_QUALIFICATION_AUTHORITY_CAPABILITY = MANAGED_DELIVERY_AUTHORITY_CAPABILITY +CONTROL_HEADER = "x-oa-connector-control" class ConnectorClientError(HostedError): @@ -39,6 +53,49 @@ class ConnectorClientError(HostedError): """ +class RunsStopped(ConnectorClientError): + """The organization's kill switch is on: lease nothing, stop what runs.""" + + +@dataclass +class ConnectorControl: + """Server-side control state delivered on every poll and heartbeat.""" + + max_concurrent_leases: int = 1 + runs_stopped: bool = False + cancel_job_ids: frozenset[str] = field(default_factory=frozenset) + rotate_recommended: bool = False + token_expires_at: Optional[str] = None + + @classmethod + def parse(cls, raw: Any) -> Optional["ConnectorControl"]: + if not isinstance(raw, dict): + return None + cap = raw.get("max_concurrent_leases", 1) + if isinstance(cap, bool) or not isinstance(cap, int): + cap = 1 + cancel = raw.get("cancel_job_ids") or [] + expires = raw.get("token_expires_at") + return cls( + max_concurrent_leases=max(1, min(16, cap)), + runs_stopped=raw.get("runs_stopped") is True, + cancel_job_ids=frozenset(str(i) for i in cancel if isinstance(i, str)), + rotate_recommended=raw.get("rotate_recommended") is True, + token_expires_at=expires if isinstance(expires, str) else None, + ) + + +def sign_request( + token: str, method: str, path: str, body: bytes, *, ts: int, nonce: str +) -> str: + """The v1 request signature (see the BYOC connector protocol).""" + key = hashlib.sha256(token.encode("utf-8")).hexdigest().encode("utf-8") + message = "\n".join( + ["v1", str(ts), nonce, method.upper(), path, hashlib.sha256(body).hexdigest()] + ).encode("utf-8") + return hmac.new(key, message, hashlib.sha256).hexdigest() + + class ConnectorClient: def __init__( self, @@ -47,13 +104,20 @@ def __init__( token: Optional[str] = None, timeout: float = 60.0, transport: Optional[httpx.BaseTransport] = None, + egress_audit_log: Optional[str] = None, ) -> None: self.base = control_plane_url.rstrip("/") self.token = token + self.control = ConnectorControl() + self.egress_audit_log = egress_audit_log + self._secret_values: set[str] = set() + self._lock = threading.Lock() self._client = httpx.Client( base_url=self.base, timeout=timeout, transport=transport ) + # -- lifecycle ----------------------------------------------------------- + def close(self) -> None: self._client.close() @@ -63,23 +127,87 @@ def __enter__(self) -> "ConnectorClient": def __exit__(self, *exc: object) -> None: self.close() - def _bearer(self) -> dict[str, str]: - if not self.token: - raise ConnectorClientError("connector is not enrolled (no token)") - return {"authorization": f"Bearer {self.token}"} + def add_secret_values(self, values: Iterable[str]) -> None: + """Register local secret values the egress scan must never let out.""" + with self._lock: + self._secret_values.update(v for v in values if v) + + # -- transport ----------------------------------------------------------- + + def _audit(self, path: str, raw: bytes) -> None: + if not self.egress_audit_log: + return + entry = { + "at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), + "path": path, + "body_sha256": hashlib.sha256(raw).hexdigest(), + "body": json.loads(raw.decode("utf-8")) if raw else None, + } + with self._lock: + with open(self.egress_audit_log, "a", encoding="utf-8") as fh: + fh.write(json.dumps(entry, sort_keys=True) + "\n") + + def _post( + self, + path: str, + body: dict[str, Any], + *, + signed: bool = True, + extra_headers: Optional[dict[str, str]] = None, + ) -> httpx.Response: + with self._lock: + secret_values = tuple(self._secret_values) + raw = egress.serialize_checked(body, secret_values) + headers = {"content-type": "application/json"} + if signed: + if not self.token: + raise ConnectorClientError("connector is not enrolled (no token)") + ts = int(time.time()) + nonce = _secrets.token_hex(16) + headers.update( + { + "authorization": f"Bearer {self.token}", + "x-oa-connector-ts": str(ts), + "x-oa-connector-nonce": nonce, + "x-oa-connector-signature": sign_request( + self.token, "POST", path, raw, ts=ts, nonce=nonce + ), + } + ) + if extra_headers: + headers.update(extra_headers) + self._audit(path, raw) + return self._client.post(path, content=raw, headers=headers) + + def _absorb_control(self, resp: httpx.Response, data: Any = None) -> None: + control = None + if isinstance(data, dict): + control = ConnectorControl.parse(data.get("connector")) + if control is None: + header = resp.headers.get(CONTROL_HEADER) + if header: + try: + control = ConnectorControl.parse(json.loads(header)) + except ValueError: + control = None + if control is not None: + self.control = control + + # -- endpoints ----------------------------------------------------------- def enroll( self, *, enrollment_secret: Optional[str], org_id: Optional[str], name: str ) -> dict[str, Any]: - """Enroll this machine as a Connector; returns the register response - (including the per-connector ``token``, shown exactly once).""" + """Mock/development enrollment (live Cloud mints tokens in Settings).""" headers: dict[str, str] = {} - body: dict[str, Any] = {"name": name} + body: dict[str, Any] = {"name": str(name)[:100]} if enrollment_secret: headers["x-byoc-enrollment-secret"] = enrollment_secret if org_id: - body["org_id"] = org_id - resp = self._client.post("/api/connector/register", json=body, headers=headers) + body["org_id"] = egress._ident(org_id, "org_id") + resp = self._post( + "/api/connector/register", body, signed=False, extra_headers=headers + ) if resp.status_code != 200: raise ConnectorClientError(f"enroll refused: HTTP {resp.status_code}") data = resp.json() @@ -88,51 +216,99 @@ def enroll( self.token = token return data - def poll(self, wait_s: int) -> Optional[dict[str, Any]]: - """Long-poll for the next leased job. Returns the poll envelope - ``{"job": {...}}`` or None on a 204 (no work in the wait window).""" - resp = self._client.post( - "/api/connector/poll", - json={ - "wait": wait_s, - "capabilities": [MANAGED_QUALIFICATION_AUTHORITY_CAPABILITY], - }, - headers=self._bearer(), + def poll( + self, wait_s: int, *, active_job_ids: Iterable[str] = () + ) -> Optional[dict[str, Any]]: + """Long-poll for the next leased job. Returns the job envelope + ``{"id", "payload", ...}`` or None (no work, or at the lease cap). + + Raises :class:`RunsStopped` while the organization's kill switch is on. + """ + body = egress.guard_poll( + int(wait_s), + [MANAGED_QUALIFICATION_AUTHORITY_CAPABILITY], + list(active_job_ids), ) + resp = self._post("/api/connector/poll", body) if resp.status_code == 204: + self._absorb_control(resp) return None + data = resp.json() if resp.content else {} + if resp.status_code == 423: + self._absorb_control(resp, data) + self.control.runs_stopped = True + raise RunsStopped("organization runs are stopped by an administrator") if resp.status_code != 200: raise ConnectorClientError(f"poll failed: HTTP {resp.status_code}") - data = resp.json() + self._absorb_control(resp, data) return data.get("job") + def heartbeat(self, active_job_ids: Iterable[str]) -> ConnectorControl: + resp = self._post( + "/api/connector/heartbeat", egress.guard_heartbeat(list(active_job_ids)) + ) + if resp.status_code != 200: + raise ConnectorClientError(f"heartbeat failed: {resp.status_code}") + self._absorb_control(resp, resp.json()) + return self.control + def ack( - self, job_id: str, status: str, error: Optional[str] = None + self, job_id: str, status: str, error_code: Optional[str] = None ) -> dict[str, Any]: - """Release a leased job (``done`` | ``failed``).""" - resp = self._client.post( - "/api/connector/ack", - json={"job_id": job_id, "status": status, "error": error}, - headers=self._bearer(), + """Release a leased job (``done`` | ``failed``) with a closed code.""" + resp = self._post( + "/api/connector/ack", egress.guard_ack(job_id, status, error_code) ) - # 409 = the lease was already released/re-offered; not fatal, move on. + # 409 = the lease was already released or reaped; not fatal, move on. if resp.status_code not in (200, 409): raise ConnectorClientError(f"ack failed: HTTP {resp.status_code}") return resp.json() if resp.content else {} + def rotate(self, new_token: Optional[str] = None) -> dict[str, Any]: + """Swap this connector's token. + + With ``new_token`` (minted locally by :func:`mint_token`) only its + SHA-256 crosses the network, and a retry after a lost response is + answered ``already_rotated``. Without it the server mints the token + (legacy). Returns the response with ``token`` set to the new token. + """ + body: dict[str, Any] = egress.guard_empty() + if new_token is not None: + body = egress.guard_rotate(hashlib.sha256(new_token.encode()).hexdigest()) + resp = self._post("/api/connector/rotate", body) + if resp.status_code != 200: + raise ConnectorClientError(f"rotate failed: {resp.status_code}") + data = resp.json() + token = new_token if new_token is not None else data.get("token") + if not isinstance(token, str) or not token.startswith("oaconn_"): + raise ConnectorClientError("rotate returned no connector token") + return {**data, "token": token} + def run_callback(self, body: dict[str, Any], *, run_token: Optional[str]) -> None: - """POST PHI-free run status/metrics via the existing callback boundary. + """POST the metadata-only run outcome (allow-listed, run-token auth). - Authenticated by the run-scoped ``x-run-token`` delivered in the job - (proves this run; forbids forging another's status). Every non-2xx - response propagates: the caller must not ACK a lease whose authoritative - run outcome the control plane rejected or did not receive. + Every non-2xx response propagates: the caller must not ACK a lease whose + authoritative run outcome the control plane rejected or did not receive. """ - headers = {"content-type": "application/json"} + headers = {} if run_token: headers["x-run-token"] = run_token - resp = self._client.post( - "/api/internal/run-callback", json=body, headers=headers + resp = self._post( + "/api/internal/run-callback", + egress.guard_callback(body), + signed=False, + extra_headers=headers, ) if not 200 <= resp.status_code < 300: raise ConnectorClientError(f"run-callback failed: HTTP {resp.status_code}") + + +def mint_token() -> str: + """A new connector token, minted on this machine (never sent in clear).""" + return "oaconn_" + _secrets.token_hex(32) + + +def default_audit_path(home: Optional[str] = None) -> Optional[str]: + """``$OPENADAPT_HOME/connector-egress.jsonl`` when OPENADAPT_HOME is set.""" + root = home or os.environ.get("OPENADAPT_HOME") + return os.path.join(root, "connector-egress.jsonl") if root else None diff --git a/packages/flow/openadapt_flow/connector/config.py b/packages/flow/openadapt_flow/connector/config.py index 7994cb8af0..84a48e8d72 100644 --- a/packages/flow/openadapt_flow/connector/config.py +++ b/packages/flow/openadapt_flow/connector/config.py @@ -66,6 +66,9 @@ class ConnectorSettings: control_plane_url: str = "https://app.openadapt.ai" token: Optional[str] = None + #: A locally minted replacement token whose rotation has not been + #: confirmed yet (finished on the next start). + pending_token: Optional[str] = None org_id: Optional[str] = None name: str = "openadapt-connector" poll_wait_s: int = 25 @@ -80,6 +83,35 @@ class ConnectorSettings: storage_prefix: str = "" #: Mirror the governed ``run`` escape hatch; default OFF (fail closed). allow_unencrypted: bool = False + #: Local secret store: ``/.env`` (mode 0600). + #: Only the ``secrets_ref`` name ever crosses the network. + secrets_dir: Optional[str] = None + #: Local secret reference used when a dispatch names none (the workflow + #: then needs no secret name in the cloud at all). + default_secrets_ref: Optional[str] = None + #: Comma-separated Ed25519 public keys (64 hex) of the program admitters + #: this runner trusts. A dispatch whose admission key is not pinned here is + #: refused: the control plane cannot widen what this machine will run. + trusted_admission_keys: str = "" + #: Operator-owned public, read-only Flow trust directory. The child + #: rechecks its current registry at input edges. Required for admitter-v2; + #: without it only a pinned person-v1 key snapshot can be staged. + admission_key_dir: Optional[str] = None + #: Local, append-only JSONL log of every request body this connector sent. + egress_audit_log: Optional[str] = None + #: Local ceiling on parallel jobs; the server's cap applies under it. + max_workers: int = 4 + #: Path to the qualification signer registry JSON (production admission). + qualification_signers_file: Optional[str] = None + #: Independent operator-owned ProductionQualificationAuthority wrapper. + #: Qualified jobs must match it exactly; never built from a remote proof. + qualification_authority_file: Optional[str] = None + + def pinned_admission_keys(self) -> frozenset[str]: + keys = {k.strip().lower() for k in self.trusted_admission_keys.split(",")} + return frozenset( + k for k in keys if len(k) == 64 and all(c in "0123456789abcdef" for c in k) + ) def redacted(self) -> dict[str, Any]: """A log-safe view (token elided).""" @@ -91,6 +123,9 @@ def redacted(self) -> dict[str, Any]: "profile": self.profile, "policy": self.policy, "storage_backend": self.storage_backend, + "secrets_dir": self.secrets_dir, + "trusted_admission_keys": sorted(self.pinned_admission_keys()), + "max_workers": self.max_workers, "token": "" if self.token else None, } @@ -130,6 +165,7 @@ def load_settings( token=_pick( flags, "BYOC_CONNECTOR_TOKEN", file_cfg.get("token"), None, "token" ), + pending_token=file_cfg.get("pending_token"), org_id=_pick(flags, "BYOC_ORG_ID", file_cfg.get("org_id"), None, "org_id"), name=str( _pick( @@ -181,6 +217,69 @@ def load_settings( or "" ), allow_unencrypted=bool(file_cfg.get("allow_unencrypted", False)), + secrets_dir=_pick( + flags, "BYOC_SECRETS_DIR", file_cfg.get("secrets_dir"), None, "secrets_dir" + ), + default_secrets_ref=_pick( + flags, + "BYOC_DEFAULT_SECRETS_REF", + file_cfg.get("default_secrets_ref"), + None, + "default_secrets_ref", + ), + trusted_admission_keys=str( + _pick( + flags, + "BYOC_TRUSTED_ADMISSION_KEYS", + file_cfg.get("trusted_admission_keys"), + "", + "trusted_admission_keys", + ) + or "" + ), + admission_key_dir=_pick( + flags, + "BYOC_ADMISSION_KEY_DIR", + file_cfg.get("admission_key_dir"), + None, + "admission_key_dir", + ), + egress_audit_log=_pick( + flags, + "BYOC_EGRESS_AUDIT_LOG", + file_cfg.get("egress_audit_log"), + None, + "egress_audit_log", + ), + max_workers=max( + 1, + min( + 16, + int( + _pick( + flags, + "BYOC_MAX_WORKERS", + file_cfg.get("max_workers"), + 4, + "max_workers", + ) + ), + ), + ), + qualification_signers_file=_pick( + flags, + "BYOC_QUALIFICATION_SIGNERS_FILE", + file_cfg.get("qualification_signers_file"), + None, + "qualification_signers_file", + ), + qualification_authority_file=_pick( + flags, + "BYOC_QUALIFICATION_AUTHORITY_FILE", + file_cfg.get("qualification_authority_file"), + None, + "qualification_authority_file", + ), ) @@ -194,6 +293,7 @@ def save_enrollment( fields: list[tuple[str, Any]] = [ ("control_plane_url", settings.control_plane_url), ("token", settings.token), + ("pending_token", settings.pending_token), ("org_id", settings.org_id), ("name", settings.name), ("poll_wait_s", settings.poll_wait_s), @@ -204,12 +304,28 @@ def save_enrollment( ("storage_bucket", settings.storage_bucket), ("storage_prefix", settings.storage_prefix), ("allow_unencrypted", settings.allow_unencrypted), + ("secrets_dir", settings.secrets_dir), + ("default_secrets_ref", settings.default_secrets_ref), + ("trusted_admission_keys", settings.trusted_admission_keys), + ("admission_key_dir", settings.admission_key_dir), + ("egress_audit_log", settings.egress_audit_log), + ("max_workers", settings.max_workers), + ("qualification_signers_file", settings.qualification_signers_file), + ("qualification_authority_file", settings.qualification_authority_file), ] for key, value in fields: if value is None or value == "": continue lines.append(f"{key} = {_toml_scalar(value)}") - cfg_path.write_text("\n".join(lines) + "\n", encoding="utf-8") + # Atomic: a crash mid-write (for example during token rotation) leaves + # either the old file or the new one, never a truncated token. + tmp = cfg_path.with_name(cfg_path.name + ".tmp") + fd = os.open(str(tmp), os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600) + with os.fdopen(fd, "w", encoding="utf-8") as fh: + fh.write("\n".join(lines) + "\n") + fh.flush() + os.fsync(fh.fileno()) + os.replace(tmp, cfg_path) try: os.chmod(cfg_path, 0o600) # holds the per-connector token except OSError: # pragma: no cover - platform without chmod semantics diff --git a/packages/flow/openadapt_flow/connector/daemon.py b/packages/flow/openadapt_flow/connector/daemon.py index 034c828036..fd9397ad99 100644 --- a/packages/flow/openadapt_flow/connector/daemon.py +++ b/packages/flow/openadapt_flow/connector/daemon.py @@ -14,13 +14,30 @@ from __future__ import annotations +import signal +import threading import time -from typing import Any, Callable, Optional +from concurrent.futures import Future, ThreadPoolExecutor +from contextlib import contextmanager +from typing import Any, Callable, Iterator, Optional -from openadapt_flow.connector.client import ConnectorClient +import httpx + +from openadapt_flow.connector.client import ( + ConnectorClient, + ConnectorClientError, + ConnectorControl, + RunsStopped, +) from openadapt_flow.connector.config import ConnectorSettings -from openadapt_flow.connector.executor import ExecutionResult, Runner, execute_job -from openadapt_flow.connector.protocol import ByocJob, parse_job +from openadapt_flow.connector.egress import EgressViolation +from openadapt_flow.connector.executor import ( + ExecutionResult, + Runner, + cancel_job, + execute_job, +) +from openadapt_flow.connector.protocol import ByocJob, ByocJobParseError, parse_job from openadapt_flow.connector.storage import CustomerStorage, build_storage from openadapt_flow.failure_signals import ( automation_failure_signal, @@ -31,6 +48,11 @@ #: from settings + the job's backend hint. StorageFactory = Callable[[ByocJob], CustomerStorage] CALLBACK_ATTEMPTS = 3 +HEARTBEAT_S = 15.0 +STOPPED_BACKOFF_S = 15.0 +MAX_BACKOFF_S = 60.0 +#: persist_token(new_token) writes the rotated token durably before use. +TokenPersister = Callable[[str], None] def phi_free_callback_body(job: ByocJob, result: ExecutionResult) -> dict[str, Any]: @@ -79,42 +101,86 @@ def handle_job( storage_factory: StorageFactory, require_run_token: bool, ) -> dict[str, Any]: - """Run one leased job end to end: execute -> PHI-free callback -> ack. + """Run one leased job end to end: execute -> metadata-only callback -> ack. - Never raises: an execution failure still reports PHI-free and is ACKed only - after Cloud accepts that outcome. A callback/ACK delivery failure leaves the + Never raises: an execution failure still reports and is ACKed only after + Cloud accepts that outcome. A callback/ACK delivery failure leaves the lease to expire as terminal ``lease_expired_uncertain`` without re-offer. """ + # The executor supplies its observed archive digest once the child could + # have written to the system of record. + child_bundle_sha256: Optional[str] = None + + def child_start(verified_sha256: str) -> None: + nonlocal child_bundle_sha256 + child_bundle_sha256 = verified_sha256 + try: storage = storage_factory(job) result = execute_job( - job, settings, storage, runner=runner, require_run_token=require_run_token + job, + settings, + storage, + runner=runner, + require_run_token=require_run_token, + on_secrets=client.add_secret_values, + on_child_start=child_start, ) - except Exception as exc: # fail closed: build a failed result, still report + except Exception as exc: # The outcome may be unknown after child handoff. result = ExecutionResult( - "failed", {}, None, job.report_ref(), f"{type(exc).__name__}" + "halt" if child_bundle_sha256 else "failed", + {}, + {"present": True} if child_bundle_sha256 else None, + None, + type(exc).__name__, + verified_bundle_sha256=child_bundle_sha256, + error_code="connector_exception", ) # The callback is the authoritative run outcome. Retry briefly for a # transient transport failure, but NEVER ACK the lease unless Cloud accepted # it. An unacked lease expires to `lease_expired_uncertain` and is not - # automatically re-offered, preventing blind duplicate actuation after a - # crash or partition. + # automatically re-offered, preventing blind duplicate actuation. callback_accepted = False - callback_body = phi_free_callback_body(job, result) - for attempt in range(CALLBACK_ATTEMPTS): + try: + callback_body = phi_free_callback_body(job, result) + except Exception: # noqa: BLE001 - nothing unchecked is ever sent + callback_body = None + transport_failures = 0 + while callback_body is not None and transport_failures < CALLBACK_ATTEMPTS: try: client.run_callback(callback_body, run_token=job.run_token) callback_accepted = True break + except EgressViolation: + if result.error_code == "egress_refused": + break # Even the minimal binding was refused. Leave the lease unacked. + # Discard every report-derived field. Cloud requires the observed + # archive digest for a halt, and runner_failure for a pre-hash failure. + result = ExecutionResult( + "halt" if child_bundle_sha256 else "failed", + {}, + {"present": True} if child_bundle_sha256 else None, + None, + verified_bundle_sha256=child_bundle_sha256, + error_code="egress_refused", + ) + callback_body = phi_free_callback_body(job, result) + callback_body.pop("failure_signal", None) + if child_bundle_sha256: + callback_body["error_code"] = "egress_refused" except Exception: # noqa: BLE001 - bounded retry, then leave lease unacked - if attempt + 1 < CALLBACK_ATTEMPTS: - time.sleep(0.25 * (2**attempt)) + transport_failures += 1 + if transport_failures < CALLBACK_ATTEMPTS: + time.sleep(0.25 * (2 ** (transport_failures - 1))) if job.lease_job_id and callback_accepted: ack_status = "failed" if result.status == "failed" else "done" + code = result.error_code or ( + "governed_run_failed" if ack_status == "failed" else None + ) try: - client.ack(job.lease_job_id, ack_status, result.error) + client.ack(job.lease_job_id, ack_status, code) except Exception: # noqa: BLE001 - terminal uncertainty, never re-offered pass @@ -122,6 +188,7 @@ def handle_job( "job_id": job.lease_job_id, "run_id": job.run_id, "status": result.status, + "error_code": result.error_code, "callback_accepted": callback_accepted, } @@ -134,6 +201,23 @@ def factory(job: ByocJob) -> CustomerStorage: return factory +def _job_from_envelope( + client: ConnectorClient, envelope: dict[str, Any] +) -> Optional[ByocJob]: + """Parse a leased envelope; refuse (ack failed) a payload we cannot parse.""" + payload = dict(envelope.get("payload") or {}) + lease_id = envelope.get("id") + try: + return parse_job(payload, lease_job_id=lease_id) + except ByocJobParseError: + if isinstance(lease_id, str): + try: + client.ack(lease_id, "failed", "job_parse_failed") + except Exception: # noqa: BLE001 + pass + return None + + def run_once( client: ConnectorClient, settings: ConnectorSettings, @@ -146,8 +230,13 @@ def run_once( envelope = client.poll(settings.poll_wait_s) if not envelope: return None - payload = dict(envelope.get("payload") or {}) - job = parse_job(payload, lease_job_id=envelope.get("id")) + job = _job_from_envelope(client, envelope) + if job is None: + return { + "job_id": envelope.get("id"), + "status": "failed", + "error_code": "job_parse_failed", + } factory = storage_factory or _default_storage_factory(settings) return handle_job( client, @@ -159,6 +248,124 @@ def run_once( ) +class _ActiveJobs: + def __init__(self) -> None: + self.lock = threading.Lock() + self.futures: dict[str, Future[dict[str, Any]]] = {} + + def ids(self) -> list[str]: + with self.lock: + return list(self.futures) + + def reap(self, log: Callable[[str], None]) -> int: + done = 0 + with self.lock: + for job_id, fut in list(self.futures.items()): + if fut.done(): + self.futures.pop(job_id) + done += 1 + try: + log(f"[connector] job done: {fut.result()}") + except Exception as exc: # noqa: BLE001 + log(f"[connector] job crashed: {type(exc).__name__}") + return done + + +def apply_control( + control: ConnectorControl, active: list[str], log: Callable[[str], None] +) -> None: + """Terminate children the control plane cancelled, or all on a kill switch.""" + targets = ( + set(active) + if control.runs_stopped + else set(active) & set(control.cancel_job_ids) + ) + for job_id in sorted(targets): + if cancel_job(job_id): + log(f"[connector] stopped job {job_id} on control-plane request") + + +def maybe_rotate( + client: ConnectorClient, + persist_token: Optional[TokenPersister], + log: Callable[[str], None], + *, + persist_pending: Optional[TokenPersister] = None, + force: bool = False, + attempts: int = 3, +) -> bool: + """Rotate the token when the control plane recommends it and we can persist. + + The new token is minted here and only its hash is sent. It is written to + ``pending_token`` first, so a crash or a lost response can be finished on + the next start by repeating the same request (the server answers + ``already_rotated``) instead of stranding the connector. + """ + if (not force and not client.control.rotate_recommended) or persist_token is None: + return False + from openadapt_flow.connector.client import mint_token + + new_token = mint_token() + if persist_pending is not None: + persist_pending(new_token) + return finish_rotation(client, new_token, persist_token, log, attempts=attempts) + + +def finish_rotation( + client: ConnectorClient, + new_token: str, + persist_token: TokenPersister, + log: Callable[[str], None], + *, + attempts: int = 3, +) -> bool: + for attempt in range(attempts): + try: + client.rotate(new_token) + persist_token(new_token) # durable before first use + client.token = new_token + client.control.rotate_recommended = False + log("[connector] token rotated and persisted") + return True + except Exception as exc: # noqa: BLE001 - keep the old token; retry + log(f"[connector] token rotation attempt failed: {type(exc).__name__}") + if attempt + 1 < attempts: + time.sleep(0.5 * (2**attempt)) + return False + + +def _raise_interrupt(signum: int, _frame: Any) -> None: + raise KeyboardInterrupt(f"signal {signum}") + + +@contextmanager +def _stop_signals_interrupt() -> Iterator[None]: + """SIGTERM and SIGHUP stop the loop the way Ctrl-C (SIGINT) does. + + Each governed child runs in its own session, so a signal to the daemon + never reaches it. Without this, SIGTERM (``kill``, ``docker stop``) or + SIGHUP (a closed terminal) would end the daemon without its shutdown and + leave the child running unsupervised. Mapped to KeyboardInterrupt, both + take the same path: cancel every child, judge each outcome, then exit. + Signal handlers can only be set from the main thread; elsewhere the + process's existing handling is kept. + """ + if threading.current_thread() is not threading.main_thread(): + yield + return + names = ("SIGTERM", "SIGHUP") + previous = {} + for name in names: + number = getattr(signal, name, None) + if number is not None: + previous[number] = signal.signal(number, _raise_interrupt) + try: + yield + finally: + for number, handler in previous.items(): + signal.signal(number, handler) + + def run_loop( client: ConnectorClient, settings: ConnectorSettings, @@ -168,31 +375,150 @@ def run_loop( once: bool = False, require_run_token: bool = True, log: Callable[[str], None] = print, + persist_token: Optional[TokenPersister] = None, + persist_pending: Optional[TokenPersister] = None, + heartbeat_s: float = HEARTBEAT_S, +) -> int: + """Poll -> execute -> callback -> ack until interrupted. + + SIGINT, SIGTERM and SIGHUP all interrupt it the same way (see + :func:`_stop_signals_interrupt`). The rest is :func:`_run_loop`. + """ + with _stop_signals_interrupt(): + return _run_loop( + client, + settings, + runner=runner, + storage_factory=storage_factory, + once=once, + require_run_token=require_run_token, + log=log, + persist_token=persist_token, + persist_pending=persist_pending, + heartbeat_s=heartbeat_s, + ) + + +def _run_loop( + client: ConnectorClient, + settings: ConnectorSettings, + *, + runner: Runner, + storage_factory: Optional[StorageFactory] = None, + once: bool = False, + require_run_token: bool = True, + log: Callable[[str], None] = print, + persist_token: Optional[TokenPersister] = None, + persist_pending: Optional[TokenPersister] = None, + heartbeat_s: float = HEARTBEAT_S, ) -> int: - """Enroll (if needed) then poll->execute->callback->ack until interrupted. + """Poll -> execute -> callback -> ack until interrupted. - ``once`` runs a single poll cycle (cron-style). Returns a process exit code. + Up to ``min(settings.max_workers, server max_concurrent_leases)`` jobs run + at once. While jobs run a heartbeat thread fetches control state, so a + kill switch or cancel stops the governed children within ``heartbeat_s``. + ``once`` runs a single poll cycle (cron-style). Returns an exit code. """ if not client.token: return 1 factory = storage_factory or _default_storage_factory(settings) log(f"[connector] polling {settings.control_plane_url} (org {settings.org_id})") + + if once: + try: + result = run_once( + client, + settings, + runner=runner, + storage_factory=factory, + require_run_token=require_run_token, + ) + except RunsStopped: + log("[connector] organization runs are stopped; nothing leased") + return 0 + except KeyboardInterrupt: # pragma: no cover + return 0 + if result is not None: + log(f"[connector] job done: {result}") + log( + "[connector] loop exiting; jobs handled this session: " + f"{1 if result is not None else 0}" + ) + return 0 + + active = _ActiveJobs() + stop = threading.Event() + pool = ThreadPoolExecutor( + max_workers=settings.max_workers, thread_name_prefix="oa-job" + ) + + def heartbeat() -> None: + while not stop.wait(heartbeat_s): + ids = active.ids() + if not ids: + continue + try: + apply_control(client.heartbeat(ids), ids, log) + except Exception as exc: # noqa: BLE001 - next beat retries + log(f"[connector] heartbeat failed: {type(exc).__name__}") + + beat = threading.Thread(target=heartbeat, name="oa-heartbeat", daemon=True) + beat.start() handled = 0 + backoff = 1.0 try: while True: - result = run_once( + handled += active.reap(log) + cap = min(settings.max_workers, client.control.max_concurrent_leases) + if len(active.ids()) >= cap: + time.sleep(0.5) + continue + try: + envelope = client.poll( + settings.poll_wait_s, active_job_ids=active.ids() + ) + backoff = 1.0 + except RunsStopped: + apply_control(client.control, active.ids(), log) + log("[connector] organization runs are stopped; holding") + time.sleep(STOPPED_BACKOFF_S) + continue + except (ConnectorClientError, httpx.TransportError, ValueError) as exc: + log( + f"[connector] poll failed ({type(exc).__name__}); retrying in {backoff:.0f}s" + ) + time.sleep(backoff) + backoff = min(MAX_BACKOFF_S, backoff * 2) + continue + apply_control(client.control, active.ids(), log) + maybe_rotate(client, persist_token, log, persist_pending=persist_pending) + if not envelope: + continue + job = _job_from_envelope(client, envelope) + if job is None or not job.lease_job_id: + continue + fut = pool.submit( + handle_job, client, settings, + job, runner=runner, storage_factory=factory, require_run_token=require_run_token, ) - if result is not None: - handled += 1 - log(f"[connector] job done: {result}") - if once: - break - except KeyboardInterrupt: # pragma: no cover - operator Ctrl-C + with active.lock: + active.futures[job.lease_job_id] = fut + except KeyboardInterrupt: # operator Ctrl-C or service stop log("[connector] interrupted; exiting") + finally: + stop.set() + # Stop every governed child before draining. Each now runs in its own + # session, so a service stop or Ctrl-C reaches only this daemon; a + # stopped child is judged by the executor (a write may have landed: + # halt, child_outcome_unknown), never acked as a clean failure. + for job_id in active.ids(): + cancel_job(job_id) + pool.shutdown(wait=True) + handled += active.reap(log) log(f"[connector] loop exiting; jobs handled this session: {handled}") return 0 diff --git a/packages/flow/openadapt_flow/connector/egress.py b/packages/flow/openadapt_flow/connector/egress.py new file mode 100644 index 0000000000..37534ac4f6 --- /dev/null +++ b/packages/flow/openadapt_flow/connector/egress.py @@ -0,0 +1,339 @@ +"""The connector's egress allow-list: the only bytes that may leave the machine. + +Every request body the connector sends to the control plane is built here, from +a closed set of fields with closed value shapes. Anything not on the list is +refused before a socket opens. This is the code that enforces the runner's data +boundary; the docstrings elsewhere describe it, this module makes it true. + +What may leave (and nothing else): + +* identifiers the control plane issued (run, org, workflow, bundle version, + runtime validation, lease job ids); +* SHA-256 digests (bundle archive, read-back spec, effect receipt, the stored + report); +* closed labels (status, outcome, error code, effect verdict); +* structural counts (steps, halts, heals, model calls, cost); +* the opaque report key the control plane itself assigned; +* the closed outcome envelope and failure signal Flow already defines as + PHI-free (re-validated here, with every string leaf restricted to a short + token that cannot hold free text). + +Record values, screenshots, OCR text, typed values, halt reasons, exception +text, file paths and secrets have no field to travel in. As a second wall, every +serialized body is scanned for every encoding of every secret value the local +secret store resolved; a hit refuses the send. +""" + +from __future__ import annotations + +import json +import re +from typing import Any, Iterable, Mapping, Optional + +from openadapt_flow.wire_check import carries_secret + +__all__ = [ + "EgressViolation", + "ERROR_CODE", + "guard_ack", + "guard_callback", + "guard_heartbeat", + "guard_poll", + "guard_empty", + "serialize_checked", +] + + +class EgressViolation(ValueError): + """A body would carry something outside the allow-list. Never sent.""" + + +_ID = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$") +_HEX64 = re.compile(r"^[a-f0-9]{64}$") +ERROR_CODE = re.compile(r"^[a-z][a-z0-9_]{0,63}$") +_LABEL = re.compile(r"^[A-Za-z_]{1,40}$") +#: A key inside a closed envelope: a field name, which may carry digits +#: (``workflow_contract_sha256``). Values are still restricted to short tokens. +_KEY = re.compile(r"^[A-Za-z_][A-Za-z0-9_]{0,63}$") +#: A string leaf inside the closed envelopes: a short token, no whitespace. +_TOKEN = re.compile(r"^[A-Za-z0-9_.:/+-]{0,128}$") +_REPORT_KEY = re.compile( + r"^[A-Za-z0-9_-][A-Za-z0-9_.-]{0,127}(/[A-Za-z0-9_-][A-Za-z0-9_.-]{0,127}){0,7}$" +) +_CAPABILITY = re.compile(r"^[a-z][a-z0-9_]{0,63}$") + +_STATUSES = {"running", "success", "halt", "failed"} +_ACK_STATUSES = {"done", "failed"} +_MODES = {"replay", "teach"} +_METRIC_KEYS = {"steps", "steps_ok", "halts", "heals", "model_calls", "cost_usd"} +_READBACK_KEYS = { + "readback_sha256", + "outcome", + "effect_verdict", + "verification_tier", + "receipt_sha256", +} +_FAILURE_SIGNAL_KEYS = { + "schema", + "failure_kind", + "substrate", + "action_kind", + "risk_class", + "resolution_rung", + "identity_state", + "effect_tier", + "delivery_state", + "execution_profile", + "outcome", + "runtime_version", + "model_calls", + "external_network_calls", + "occurred_at", +} +MAX_ACTIVE_JOBS = 64 + + +def _ident(value: Any, field: str, *, optional: bool = False) -> Optional[str]: + if value is None and optional: + return None + if not isinstance(value, str) or not _ID.fullmatch(value): + raise EgressViolation(f"{field} is not a control-plane identifier") + return value + + +def _hex64(value: Any, field: str) -> str: + if not isinstance(value, str) or not _HEX64.fullmatch(value): + raise EgressViolation(f"{field} is not a SHA-256 digest") + return value + + +def _number(value: Any, field: str) -> float | int: + if isinstance(value, bool) or not isinstance(value, (int, float)): + raise EgressViolation(f"metric {field} is not a number") + if value != value or value in (float("inf"), float("-inf")) or value < 0: + raise EgressViolation(f"metric {field} is not a finite count") + return value + + +def _closed_tree(value: Any, field: str, depth: int = 0) -> Any: + """Re-walk a closed envelope: dicts, lists, bools, numbers, short tokens.""" + if depth > 6: + raise EgressViolation(f"{field} nests too deeply") + if value is None or isinstance(value, bool): + return value + if isinstance(value, (int, float)): + return _number(value, field) + if isinstance(value, str): + if not _TOKEN.fullmatch(value): + raise EgressViolation(f"{field} carries a string that is not a short token") + return value + if isinstance(value, list): + if len(value) > 256: + raise EgressViolation(f"{field} is too long") + return [_closed_tree(item, field, depth + 1) for item in value] + if isinstance(value, dict): + out: dict[str, Any] = {} + for key, item in value.items(): + if not isinstance(key, str) or not _KEY.fullmatch(key): + raise EgressViolation(f"{field} has a key that is not a label") + out[key] = _closed_tree(item, f"{field}.{key}", depth + 1) + return out + raise EgressViolation(f"{field} has an unsupported value type") + + +def _outcome_envelope(value: Any) -> dict[str, Any]: + from openadapt_flow.ir import ExecutionOutcomeEnvelope + + try: + model = ExecutionOutcomeEnvelope.model_validate(value) + except (TypeError, ValueError) as exc: + raise EgressViolation("outcome is not a valid closed outcome envelope") from exc + dumped = model.model_dump(mode="json") + return _closed_tree(dumped, "outcome") + + +def _failure_signal(value: Any) -> dict[str, Any]: + if not isinstance(value, dict) or set(value) != _FAILURE_SIGNAL_KEYS: + raise EgressViolation("failure_signal is not the closed v1 envelope") + if value.get("schema") != "openadapt.automation-failure-signal/v1": + raise EgressViolation("failure_signal has an unknown schema") + return _closed_tree(value, "failure_signal") + + +def _wrap_readback(value: Any) -> dict[str, str]: + if not isinstance(value, dict) or set(value) != _READBACK_KEYS: + raise EgressViolation("wrap_readback is not the closed read-back record") + out = { + "readback_sha256": _hex64( + value["readback_sha256"], "wrap_readback.readback_sha256" + ), + "receipt_sha256": _hex64( + value["receipt_sha256"], "wrap_readback.receipt_sha256" + ), + } + for key in ("outcome", "effect_verdict", "verification_tier"): + label = value[key] + if not isinstance(label, str) or not _LABEL.fullmatch(label): + raise EgressViolation(f"wrap_readback.{key} is not a label") + out[key] = label + return out + + +def _metrics(value: Any) -> dict[str, Any]: + if value is None: + return {} + if not isinstance(value, dict): + raise EgressViolation("metrics is not an object") + out: dict[str, Any] = {} + for key, item in value.items(): + if key == "wrap_readback": + if item is not None: + out[key] = _wrap_readback(item) + continue + if key == "report_sha256": + out[key] = _hex64(item, "metrics.report_sha256") + continue + if key not in _METRIC_KEYS: + raise EgressViolation(f"metric {key!r} is not on the allow-list") + out[key] = _number(item, key) + return out + + +def guard_callback(body: Mapping[str, Any]) -> dict[str, Any]: + """Rebuild a run-callback body from allow-listed fields, or refuse.""" + allowed = { + "run_id", + "org_id", + "workflow_id", + "bundle_version_id", + "runtime_validation_id", + "mode", + "status", + "report_path", + "metrics", + "error_code", + "bundle_sha256", + "halt", + "outcome", + "failure_signal", + } + extra = set(body) - allowed + if extra: + raise EgressViolation( + f"callback field(s) not on the allow-list: {sorted(extra)}" + ) + out: dict[str, Any] = { + "run_id": _ident(body.get("run_id"), "run_id"), + "org_id": _ident(body.get("org_id"), "org_id"), + "workflow_id": _ident(body.get("workflow_id"), "workflow_id"), + "bundle_version_id": _ident( + body.get("bundle_version_id"), "bundle_version_id", optional=True + ), + "runtime_validation_id": _ident( + body.get("runtime_validation_id"), "runtime_validation_id", optional=True + ), + } + mode = body.get("mode", "replay") + if mode not in _MODES: + raise EgressViolation("mode is not replay or teach") + out["mode"] = mode + status = body.get("status") + if status not in _STATUSES: + raise EgressViolation("status is not a lifecycle status") + out["status"] = status + report_path = body.get("report_path") + if report_path is not None: + if ( + not isinstance(report_path, str) + or not _REPORT_KEY.fullmatch(report_path) + or ".." in report_path.split("/") + ): + raise EgressViolation("report_path is not an opaque relative storage key") + out["report_path"] = report_path + out["metrics"] = _metrics(body.get("metrics")) + error_code = body.get("error_code") + if error_code is not None and ( + not isinstance(error_code, str) or not ERROR_CODE.fullmatch(error_code) + ): + raise EgressViolation("error_code is not a closed code") + out["error_code"] = error_code + if "bundle_sha256" in body: + out["bundle_sha256"] = _hex64(body["bundle_sha256"], "bundle_sha256") + if "halt" in body: + if body["halt"] != {"present": True}: + raise EgressViolation("halt may only say that a halt is present") + out["halt"] = {"present": True} + if "outcome" in body and body["outcome"] is not None: + out["outcome"] = _outcome_envelope(body["outcome"]) + if "failure_signal" in body and body["failure_signal"] is not None: + out["failure_signal"] = _failure_signal(body["failure_signal"]) + return out + + +def guard_ack(job_id: Any, status: Any, error_code: Any = None) -> dict[str, Any]: + if status not in _ACK_STATUSES: + raise EgressViolation("ack status is not done or failed") + if error_code is not None and ( + not isinstance(error_code, str) or not ERROR_CODE.fullmatch(error_code) + ): + raise EgressViolation("ack error_code is not a closed code") + return { + "job_id": _ident(job_id, "job_id"), + "status": status, + "error_code": error_code, + } + + +def _active_ids(active_job_ids: Iterable[Any]) -> list[str]: + ids = [_ident(item, "active_job_ids[]") for item in active_job_ids] + if len(ids) > MAX_ACTIVE_JOBS: + raise EgressViolation("too many active job ids") + return [item for item in ids if item is not None] + + +def guard_poll( + wait_s: Any, + capabilities: Iterable[Any], + active_job_ids: Iterable[Any] = (), + lease_seconds: Any = None, +) -> dict[str, Any]: + if isinstance(wait_s, bool) or not isinstance(wait_s, int) or not 0 <= wait_s <= 50: + raise EgressViolation("poll wait is not 0..50 seconds") + caps = [] + for cap in capabilities: + if not isinstance(cap, str) or not _CAPABILITY.fullmatch(cap): + raise EgressViolation("capability is not a closed token") + caps.append(cap) + body: dict[str, Any] = { + "wait": wait_s, + "capabilities": caps, + "active_job_ids": _active_ids(active_job_ids), + } + if lease_seconds is not None: + if isinstance(lease_seconds, bool) or not isinstance(lease_seconds, int): + raise EgressViolation("lease_seconds is not an integer") + body["lease_seconds"] = lease_seconds + return body + + +def guard_heartbeat(active_job_ids: Iterable[Any]) -> dict[str, Any]: + return {"active_job_ids": _active_ids(active_job_ids)} + + +def guard_empty() -> dict[str, Any]: + return {} + + +def guard_rotate(new_token_sha256: Any) -> dict[str, Any]: + return {"new_token_sha256": _hex64(new_token_sha256, "new_token_sha256")} + + +def serialize_checked( + body: Mapping[str, Any], secret_values: Iterable[str] = () +) -> bytes: + """Serialize an allow-listed body and refuse it if any secret shows up.""" + raw = json.dumps(body, separators=(",", ":"), sort_keys=True) + secrets = [value for value in secret_values if value and len(value) >= 4] + if secrets and carries_secret(raw, secrets): + raise EgressViolation("a local secret value would leave the machine; refused") + return raw.encode("utf-8") diff --git a/packages/flow/openadapt_flow/connector/executor.py b/packages/flow/openadapt_flow/connector/executor.py index 960342a4ca..623ace68ca 100644 --- a/packages/flow/openadapt_flow/connector/executor.py +++ b/packages/flow/openadapt_flow/connector/executor.py @@ -39,6 +39,7 @@ import subprocess import sys import tempfile +import threading from dataclasses import dataclass, field from pathlib import Path from typing import Any, Callable, Mapping, Optional @@ -46,7 +47,12 @@ from openadapt_flow.connector.config import ConnectorSettings from openadapt_flow.connector.protocol import ByocGovernanceError, ByocJob -from openadapt_flow.connector.storage import CustomerStorage, extract_bundle_archive +from openadapt_flow.connector.secrets import LocalSecretStore, SecretStoreError +from openadapt_flow.connector.storage import ( + CustomerStorage, + extract_bundle_archive, + report_bytes, +) from openadapt_flow.failure_signals import automation_failure_signal from openadapt_flow.ir import RunReport from openadapt_flow.runner.dispatch_envelope import ( @@ -55,6 +61,7 @@ from openadapt_flow.runtime.durable.authority import ( REMOTE_AUTHORITY_TOKEN_ENV, REMOTE_AUTHORITY_URL_ENV, + REMOTE_DISPATCH_SESSION_ID_ENV, ) #: A run-gate refusal (fail-closed admission denied) exits 2 before the replay @@ -83,10 +90,115 @@ class ExecutionResult: metrics: dict[str, Any] halt: Optional[dict[str, Any]] report_ref: Optional[str] + #: Local, operator-facing detail. NEVER sent: it can name paths or values. error: Optional[str] = None verified_bundle_sha256: Optional[str] = None failure_signal: Optional[dict[str, Any]] = None outcome: Optional[dict[str, Any]] = None + #: Closed code that may leave the machine (ack ``error_code``). + error_code: Optional[str] = None + + +# --- Wrap programs: admission and independent read-back ----------------------- +WRAP_MANIFEST_NAME = "openadapt-wrap-publish.json" +WRAP_READBACK_RELPATH = "readback/verify.yaml" +WRAP_ADMISSION_NAME = "admission.json" +_WRAP_LABEL_CHARS = frozenset("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_") +_WRAP_RECEIPT_MAX = 256 * 1024 + + +def wrap_readback_sha256(bundle_dir: Path) -> Optional[str]: + """SHA-256 of a wrap bundle's verify.yaml, "" for a wrap bundle without one, + None for any other bundle (same rule as the managed runner).""" + manifest = bundle_dir / WRAP_MANIFEST_NAME + readback = bundle_dir / WRAP_READBACK_RELPATH + if not manifest.is_file() and not readback.is_file(): + return None + if readback.is_symlink() or not readback.is_file(): + return "" + return hashlib.sha256(readback.read_bytes()).hexdigest() + + +def wrap_readback_evidence( + receipt: bytes, readback_sha256: Optional[str] +) -> Optional[dict[str, str]]: + """The closed callback fields from Flow's effect receipt, or None.""" + if not readback_sha256 or not receipt or len(receipt) > _WRAP_RECEIPT_MAX: + return None + try: + document = json.loads(receipt.decode("utf-8")) + except (UnicodeDecodeError, ValueError): + return None + if not isinstance(document, dict): + return None + # verify-run writes openadapt.effect-receipt/v1: the labels sit under + # "receipt". Older flat receipts carry them at the top level. + nested = document.get("receipt") + source = nested if isinstance(nested, dict) else document + labels = { + k: source.get(k) for k in ("outcome", "effect_verdict", "verification_tier") + } + for value in labels.values(): + if ( + not isinstance(value, str) + or not 1 <= len(value) <= 40 + or not set(value) <= _WRAP_LABEL_CHARS + ): + return None + return { + "readback_sha256": readback_sha256, + **labels, # type: ignore[dict-item] + "receipt_sha256": hashlib.sha256(receipt).hexdigest(), + } + + +def _run_flow_tool(argv: list[str], child_env: Mapping[str, str]) -> int: + """Run one read-only Flow helper (``verify-run``); output stays local.""" + proc = subprocess.run( # nosec - fixed argv and exact process-local env + argv, capture_output=True, text=True, env=dict(child_env), timeout=300 + ) + return proc.returncode + + +# --- Cancellation (kill switch, control-plane cancel) --------------------------- +class _Children: + def __init__(self) -> None: + self.lock = threading.Lock() + self.procs: dict[str, subprocess.Popen[Any]] = {} + self.cancelled: set[str] = set() + + +_CHILDREN = _Children() +_CURRENT = threading.local() + + +def cancel_job(job_id: str) -> bool: + """Mark a job cancelled and terminate its governed child if one runs.""" + with _CHILDREN.lock: + _CHILDREN.cancelled.add(job_id) + proc = _CHILDREN.procs.get(job_id) + if proc is not None and proc.poll() is None: + _stop(proc) + return True + return False + + +def _stop(proc: "subprocess.Popen[Any]") -> None: + if proc.poll() is not None: + return + proc.terminate() + try: + proc.wait(timeout=10) + except subprocess.TimeoutExpired: + proc.kill() + proc.wait() + + +def job_cancelled(job_id: Optional[str]) -> bool: + if not job_id: + return False + with _CHILDREN.lock: + return job_id in _CHILDREN.cancelled def _grounding_env_available(job: ByocJob) -> bool: @@ -115,6 +227,7 @@ def build_run_argv( run_dir: Path, params_file: Optional[Path], managed_dispatch_file: Optional[Path] = None, + qualification_authority_file: Optional[Path] = None, ) -> list[str]: """The exact governed CLI invocation for a verified BYOC dispatch. @@ -145,34 +258,81 @@ def build_run_argv( argv += ["--url", job.target_url] if managed_dispatch_file is not None: argv += ["--managed-dispatch-file", str(managed_dispatch_file)] - # Cloud-dispatched items have no per-item pause until the founder decides - # otherwise (approval-mode design section 11). Say so explicitly, so the - # run report records "not_gated" instead of waiting for a person nobody - # is asked to be. - argv += ["--approval-mode", "not_gated"] + if qualification_authority_file is not None: + argv += ["--qualification-authority-file", str(qualification_authority_file)] + # Preserve the governed run's approval policy and gated default. Transport + # selection is not authority to disable a person's per-save decision. if settings.allow_unencrypted: # Local escape hatch, mirroring the governed run CLI; default OFF. argv.append("--allow-unencrypted") return argv +class _ChildNotStarted(RuntimeError): + """The operating system refused to start the governed process.""" + + def _subprocess_runner( argv: list[str], run_dir: Path, child_env: Mapping[str, str] ) -> RunOutcome: - proc = subprocess.run( # nosec - fixed argv and exact process-local env - argv, - capture_output=True, - text=True, - env=dict(child_env), + job_id = getattr(_CURRENT, "job_id", None) + try: + proc = subprocess.Popen( # nosec - fixed argv and exact process-local env + argv, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + env=dict(child_env), + # Its own session: an operator Ctrl-C or a service stop signals + # the daemon's process group, not the governed child. The daemon + # stops children itself (cancel_job), so each outcome is judged. + start_new_session=True, + ) + except OSError as exc: + raise _ChildNotStarted(type(exc).__name__) from exc + if job_id: + with _CHILDREN.lock: + _CHILDREN.procs[job_id] = proc + cancelled = job_id in _CHILDREN.cancelled + if cancelled: + proc.terminate() + try: + proc.wait() + except BaseException: + # Interrupted while waiting (an inline run's Ctrl-C): never leave the + # child running in its own session. The interrupt still propagates, + # so the lease is not acked and the plane reaps it as uncertain. + _stop(proc) + raise + finally: + if job_id: + with _CHILDREN.lock: + _CHILDREN.procs.pop(job_id, None) + return RunOutcome( + returncode=proc.returncode, report=_read_report(run_dir / "report.json") ) - report_path = run_dir / "report.json" - report: dict[str, Any] = {} - if report_path.is_file(): - try: - report = json.loads(report_path.read_text(encoding="utf-8")) - except (OSError, ValueError): - report = {} - return RunOutcome(returncode=proc.returncode, report=report) + + +def _read_report(report_path: Path) -> dict[str, Any]: + """The child's report, or ``{}`` when it is missing or cannot be read. + + The run of a sealed bundle writes its report encrypted + (:mod:`openadapt_flow.sealed_set`), so it is read through the sealed set. + Any failure (no file, no key, a bad tag, invalid JSON) is ``{}``, which + the executor treats as an unknown outcome, never as a clean failure. + """ + from openadapt_flow import sealed_set as _sealed + + try: + if _sealed.is_sealed_path(report_path): + text = _sealed.read_text(report_path) + elif report_path.is_file(): + text = report_path.read_text(encoding="utf-8") + else: + return {} + report = json.loads(text) + except Exception: # noqa: BLE001 - unreadable is an unknown outcome + return {} + return report if isinstance(report, dict) else {} def status_from_report(returncode: int, report: dict[str, Any]) -> str: @@ -204,6 +364,16 @@ def status_from_report(returncode: int, report: dict[str, Any]) -> str: return "failed" +def _reported_terminal_outcome(report: dict[str, Any]) -> bool: + """True when the child's report records how its run ended.""" + return bool(report) and ( + report.get("execution_outcome") is not None + or report.get("terminal_outcome") is not None + or report.get("halt") is not None + or isinstance(report.get("success"), bool) + ) + + def precise_outcome_from_report(report: dict[str, Any]) -> Optional[dict[str, Any]]: """Project a valid local report onto its closed PHI-free outcome envelope.""" @@ -297,8 +467,12 @@ def _assert_managed_authority_is_pinned( ) -> None: """Keep the run capability on the enrolled control-plane origin.""" + if not settings.org_id or settings.org_id != job.org_id: + raise ByocGovernanceError( + "byoc job is not bound to this connector's configured organization" + ) if job.managed_dispatch is None: - return + raise ByocGovernanceError("byoc live execution requires managed authority") try: configured = urlsplit(settings.control_plane_url) delivered = urlsplit(job.managed_delivery_authority_url or "") @@ -319,6 +493,7 @@ def _assert_managed_authority_is_pinned( or configured.password is not None or bool(configured.query) or bool(configured.fragment) + or configured.path not in {"", "/"} or delivered.scheme != "https" or delivered.hostname != configured.hostname or delivered_port != configured_port @@ -330,6 +505,106 @@ def _assert_managed_authority_is_pinned( ) +def _verify_program_reference(job: ByocJob, bundle: Path, key_dir: Path) -> None: + """Rebind both reference forms to the exact signed local admission.""" + from openadapt_flow.jit.authority import PrincipalRegistry + from openadapt_flow.jit.lifecycle import verify_admission + + reference = job.program_admission() + if reference is None: + raise ByocGovernanceError("byoc program admission reference is absent") + public_file = key_dir / "keys" / "ed25519.pub" + if ( + public_file.is_symlink() + or bytes.fromhex(public_file.read_text(encoding="utf-8").strip()).hex() + != reference["public_key_hex"] + ): + raise ByocGovernanceError( + "byoc program reference names another public trust key" + ) + manifest = verify_admission(bundle, key_dir=key_dir) + if manifest.get("digest") != job.flow_dispatch().bundle_content_digest: + raise ByocGovernanceError( + "byoc program content digest differs from its dispatch" + ) + mode = manifest.get("admission_mode", "person") + if reference["schema_version"] == "openadapt.program-admission-reference/v1": + if mode != "person": + raise ByocGovernanceError( + "an admitter admission cannot use a person reference" + ) + return + if ( + mode != "admitter_key" + or manifest.get("admitted_by_principal_id") + != reference["admitted_by_principal_id"] + or manifest.get("admitter_public_key") != reference["admitter_public_key_hex"] + or PrincipalRegistry.load(key_dir).lookup(reference["admitter_public_key_hex"]) + != ("admitter_key", reference["admitted_by_principal_id"]) + ): + raise ByocGovernanceError( + "byoc admitter reference does not match current local trust" + ) + + +def _stage_qualification_authority( + job: ByocJob, settings: ConnectorSettings, bundle: Path, run_dir: Path +) -> Path: + """Use independent local authority context; never self-assert expectations.""" + from openadapt_flow.ir import Workflow + from openadapt_flow.production_qualification import ( + ProductionQualificationAuthority, + ProductionQualificationGuard, + load_production_qualification_authority, + ) + + if not settings.qualification_authority_file: + raise ByocGovernanceError( + "qualified byoc jobs require independent local authority" + ) + source = Path(settings.qualification_authority_file) + authority = load_production_qualification_authority(source) + proof = job.qualification_admission() + expected = getattr(authority, "expected", None) + if ( + not isinstance(authority, ProductionQualificationAuthority) + or authority.qualification_admission != proof + or authority.qualification_admission_sha256 != proof.artifact_sha256() + or expected is None + or expected.tenant_id != job.org_id + or expected.workflow_id != job.workflow_id + or expected.workflow_version_id != job.bundle_version_id + or expected.bundle_version_id != job.bundle_version_id + or expected.runtime_validation_id != job.runtime_validation_id + or expected.bundle_artifact_sha256 != job.bundle_sha256 + or expected.bundle_content_digest != job.flow_dispatch().bundle_content_digest + or expected.runtime_build_identity.substrate != job.target_kind + ): + raise ByocGovernanceError( + "local qualification context does not match the exact job" + ) + workflow = Workflow.load(bundle) + ProductionQualificationGuard(source, remote_permit_revalidation=True).verify( + workflow, for_actuation=False + ) + if load_production_qualification_authority(source) != authority: + raise ByocGovernanceError( + "local qualification context changed during verification" + ) + destination = run_dir / "qualification-authority.json" + flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_NOFOLLOW", 0) + descriptor = os.open(destination, flags, 0o600) + with os.fdopen(descriptor, "w", encoding="utf-8") as stream: + stream.write(authority.model_dump_json()) + stream.flush() + os.fsync(stream.fileno()) + # Re-open with the existing owner/ACL/canonical/signature/workflow checks. + ProductionQualificationGuard(destination, remote_permit_revalidation=True).verify( + workflow, for_actuation=False + ) + return destination + + def execute_job( job: ByocJob, settings: ConnectorSettings, @@ -337,45 +612,118 @@ def execute_job( *, runner: Runner = _subprocess_runner, require_run_token: bool = True, + on_secrets: Optional[Callable[[list[str]], None]] = None, + on_child_start: Optional[Callable[[str], None]] = None, ) -> ExecutionResult: """Run one governed BYOC job end to end, inside the customer perimeter. Fail-closed on every governance requirement. Never raises for a job-level - refusal — returns a ``failed`` :class:`ExecutionResult` with a PHI-free - reason so the caller can report + ack it and move on. + refusal: returns a ``failed`` :class:`ExecutionResult` with a closed + ``error_code`` (which may leave the machine) and a local ``error`` detail + (which never does). """ + _CURRENT.job_id = job.lease_job_id + try: + return _execute_job( + job, + settings, + storage, + runner=runner, + require_run_token=require_run_token, + on_secrets=on_secrets, + on_child_start=on_child_start, + ) + finally: + _CURRENT.job_id = None + + +def _refused(job: ByocJob, code: str, detail: str, **extra: Any) -> ExecutionResult: + return ExecutionResult( + "failed", {}, None, job.report_ref(), detail, error_code=code, **extra + ) + + +def _execute_job( + job: ByocJob, + settings: ConnectorSettings, + storage: CustomerStorage, + *, + runner: Runner, + require_run_token: bool, + on_secrets: Optional[Callable[[list[str]], None]], + on_child_start: Optional[Callable[[str], None]], +) -> ExecutionResult: # 1. Governance gates (fail closed BEFORE any bundle is fetched or run). try: job.ensure_governed(require_run_token=require_run_token) _assert_managed_authority_is_pinned(job, settings) except ByocGovernanceError as exc: - return ExecutionResult("failed", {}, None, job.report_ref(), str(exc)) + return _refused(job, "governance_refused", str(exc)) + admission = job.program_admission() + if admission is not None and ( + admission["public_key_hex"] not in settings.pinned_admission_keys() + ): + # The control plane can name an admission key, but only this machine's + # own configuration decides which admitters it trusts. + return _refused( + job, + "admission_key_not_pinned", + "the program's admission key is not pinned in trusted_admission_keys", + ) + if admission is not None and admission.get("admission_mode") == "admitter_key": + if not settings.admission_key_dir: + return _refused( + job, + "admission_registry_required", + "admitter jobs require current local public trust", + ) + if admission is None and not settings.qualification_authority_file: + return _refused( + job, + "qualification_authority_unavailable", + "qualified jobs need independent local context", + ) if not _grounding_env_available(job): gm = job.grounding_model - return ExecutionResult( - "failed", - {}, - None, - job.report_ref(), + return _refused( + job, + "grounding_unavailable", f"org requires grounding model {gm.model or gm.provider!r} but its " - f"api key env {gm.api_key_env!r} is not set on this connector " - "(fail closed; halting rather than running without the governed rung)", + f"api key env {gm.api_key_env!r} is not set on this connector", + ) + try: + secret_env = LocalSecretStore(settings.secrets_dir).resolve( + job.secrets_ref or settings.default_secrets_ref ) + except SecretStoreError as exc: + return _refused(job, "secrets_unavailable", str(exc)) + if on_secrets is not None and secret_env: + on_secrets(list(secret_env.values())) + signers_json: Optional[str] = None + if settings.qualification_signers_file: + try: + signers_json = Path(settings.qualification_signers_file).read_text( + encoding="utf-8" + ) + except OSError: + return _refused( + job, "signers_unavailable", "qualification signer registry unreadable" + ) with tempfile.TemporaryDirectory(prefix="oa-byoc-") as tmp: tmp_path = Path(tmp) bundle_archive = tmp_path / "approved-bundle.zip" bundle_scratch = tmp_path / "bundle" run_dir = tmp_path / "run" + readback_dir = tmp_path / "readback" bundle_scratch.mkdir(parents=True, exist_ok=True) run_dir.mkdir(parents=True, exist_ok=True) + readback_dir.mkdir(parents=True, exist_ok=True) _write_policy_audit(job, run_dir) # 2. Copy and verify the EXACT approved archive bytes from the customer's - # storage before extraction. The content digest inside workflow.json is - # a separate semantic binding; neither can substitute for this signed - # archive-byte identity. + # storage before extraction. try: fetched_archive = storage.fetch_bundle_archive( job.storage.bundle_ref if job.storage else None, bundle_archive @@ -385,15 +733,72 @@ def execute_job( raise RuntimeError("bundle archive SHA-256 does not match dispatch") extract_bundle_archive(fetched_archive, bundle_scratch) bundle_dir = bundle_scratch - except Exception as exc: # storage failure — fail closed, PHI-free msg - return ExecutionResult( - "failed", - {}, - None, - job.report_ref(), + except Exception as exc: # storage failure: fail closed + return _refused( + job, + "bundle_fetch_failed", f"customer-storage bundle fetch failed: {type(exc).__name__}", ) + readback_sha256 = wrap_readback_sha256(bundle_dir) + key_dir: Optional[Path] = None + if admission is not None: + admission_file = bundle_dir / WRAP_ADMISSION_NAME + if ( + not admission_file.is_file() + or admission_file.is_symlink() + or not readback_sha256 + ): + return _refused( + job, + "program_admission_refused", + "the archive is not an admitted program with a read-back check", + verified_bundle_sha256=observed_sha256, + ) + if ( + hashlib.sha256(admission_file.read_bytes()).hexdigest() + != admission["admission_sha256"] + ): + return _refused( + job, + "program_admission_refused", + "the archive's admission is not the dispatched one", + verified_bundle_sha256=observed_sha256, + ) + key_dir = tmp_path / "jit-keys" + if settings.admission_key_dir: + # The operator's public-only, read-only trust directory stays + # live: the shared guard can observe subsequent revocation. + # Signing/private material belongs outside this directory. + key_dir = Path(settings.admission_key_dir) + else: + (key_dir / "keys").mkdir(parents=True) + (key_dir / "keys" / "ed25519.pub").write_text( + admission["public_key_hex"] + "\n", encoding="utf-8" + ) + try: + _verify_program_reference(job, bundle_dir, key_dir) + except Exception: + return _refused( + job, + "program_admission_refused", + "signed program or current local principal refused", + verified_bundle_sha256=observed_sha256, + ) + qualification_authority_file: Optional[Path] = None + if admission is None: + try: + qualification_authority_file = _stage_qualification_authority( + job, settings, bundle_dir, run_dir + ) + except Exception: + return _refused( + job, + "qualification_authority_refused", + "local qualification context refused", + verified_bundle_sha256=observed_sha256, + ) + try: params_file = _write_params_file(job.params, run_dir) managed_dispatch_file = None @@ -401,16 +806,61 @@ def execute_job( # Never let a long-running Connector inherit stale authority from # its service environment. Add the exact run capability only for # the child that also receives the matching dispatch envelope. - child_env.pop(REMOTE_AUTHORITY_URL_ENV, None) - child_env.pop(REMOTE_AUTHORITY_TOKEN_ENV, None) + for name in ( + REMOTE_AUTHORITY_URL_ENV, + REMOTE_AUTHORITY_TOKEN_ENV, + REMOTE_DISPATCH_SESSION_ID_ENV, + "OPENADAPT_JIT_KEY_DIR", + "BYOC_CONNECTOR_TOKEN", + ): + child_env.pop(name, None) + child_env.update(secret_env) + if signers_json is not None: + child_env["OPENADAPT_QUALIFICATION_SIGNERS_JSON"] = signers_json + if key_dir is not None: + child_env["OPENADAPT_JIT_KEY_DIR"] = str(key_dir) if job.managed_dispatch is not None: managed_dispatch_file = write_managed_dispatch_envelope_value( - run_dir / "managed-dispatch.json", job.managed_dispatch + run_dir / "managed-dispatch.json", job.flow_dispatch() ) child_env[REMOTE_AUTHORITY_URL_ENV] = str( job.managed_delivery_authority_url ) child_env[REMOTE_AUTHORITY_TOKEN_ENV] = str(job.run_token) + child_env[REMOTE_DISPATCH_SESSION_ID_ENV] = str( + job.managed_dispatch_session_id + ) + + # Independent read-back, before: a private baseline of the system + # of record. It holds raw records and never leaves this directory. + baseline = readback_dir / "baseline.json" + readback_params = run_dir / "readback-params.json" + if readback_sha256: + readback_params.write_text( + json.dumps( + {k: v for k, v in job.params.items() if k != "target_kind"} + ), + encoding="utf-8", + ) + os.chmod(readback_params, 0o600) + verify = str(bundle_dir / WRAP_READBACK_RELPATH) + rc = _run_flow_tool( + [ + sys.executable, + "-m", + "openadapt_flow", + "verify-run", + "--verify", + verify, + "--params", + str(readback_params), + "--capture-baseline", + str(baseline), + ], + child_env, + ) + if rc != 0: + baseline.unlink(missing_ok=True) # 3. The governed, fail-closed child invocation. argv = build_run_argv( @@ -420,34 +870,135 @@ def execute_job( run_dir, params_file, managed_dispatch_file, + qualification_authority_file, + ) + if job_cancelled(job.lease_job_id): + return _refused( + job, + "cancelled_by_control_plane", + "cancelled before the governed child started", + verified_bundle_sha256=observed_sha256, + ) + except Exception as exc: + return _refused( + job, + "child_invocation_failed", + f"governed child invocation failed: {type(exc).__name__}", + verified_bundle_sha256=observed_sha256, ) + + try: outcome = runner(argv, run_dir, child_env) + except _ChildNotStarted as exc: + return _refused( + job, + "child_invocation_failed", + f"governed child did not start: {exc}", + verified_bundle_sha256=observed_sha256, + ) except Exception as exc: + # A missing return from the run boundary cannot establish that the + # child did nothing. Preserve its verified binding for reconciliation. + if on_child_start is not None: + on_child_start(observed_sha256) return ExecutionResult( - "failed", + "halt", {}, + {"present": True}, None, - job.report_ref(), - f"governed child invocation failed: {type(exc).__name__}", + f"governed child outcome unavailable: {type(exc).__name__}", verified_bundle_sha256=observed_sha256, + error_code="child_outcome_unknown", ) + if on_child_start is not None: + on_child_start(observed_sha256) report = outcome.report or {} status = status_from_report(outcome.returncode, report) + error_code: Optional[str] = None report_target_kind = report.get("execution_target_kind") - if report_target_kind != job.target_kind: + # After the child started, no readable report, or a nonzero exit with + # a report that claims success, does not say whether the write landed: + # a cancel, a service stop, an OOM kill or a crash can end a child + # that already saved (or reported success and was still sealing). + # That is never a clean failure (a re-run could repeat the write); it + # stops for reconciliation (fail-open class: lost-outcome-as-failure). + # A report that records a refusal or a halt keeps its own outcome. + claims_success = ( + report.get("execution_outcome") == "VERIFIED" + or report.get("success") is True + or report.get("terminal_outcome") == "success" + ) + # A missing or unreadable report says nothing either, whatever the + # exit code: a child that exits 0 may still have saved (a sealed run + # whose report could not be read, a report that never got written). + outcome_unknown = not _reported_terminal_outcome(report) or ( + outcome.returncode != 0 and claims_success + ) + if outcome_unknown: + status = "halt" + error_code = "child_outcome_unknown" + outcome_error = ( + "the governed child ended without a report it could stand by " + "(cancelled, stopped or killed while running, or killed after " + "reporting success), so a write may have landed" + ) + elif report_target_kind != job.target_kind: status = "failed" + error_code = "target_kind_mismatch" outcome_error = ( "governed child report execution_target_kind does not match " "the signed dispatch target_kind (fail closed)" ) else: + # A cancel that arrived after the child reported does not change + # what the child did: its own outcome stands. outcome_error = None + if status == "failed": + error_code = "governed_run_failed" + + # Independent read-back, after: rule on the run with the same + # verify.yaml. Only hashes and closed labels of the receipt leave. + readback_evidence: Optional[dict[str, str]] = None + if readback_sha256 and baseline.is_file() and error_code is None: + run_record = readback_dir / "run-record.json" + run_record.write_text('{"executor_kind":"flow_replay"}', encoding="utf-8") + receipt_path = readback_dir / "effect-receipt.json" + rc = _run_flow_tool( + [ + sys.executable, + "-m", + "openadapt_flow", + "verify-run", + "--verify", + str(bundle_dir / WRAP_READBACK_RELPATH), + "--params", + str(readback_params), + "--run-record", + str(run_record), + "--baseline", + str(baseline), + "--authorization-ref", + job.run_id, + "--out", + str(readback_dir), + ], + child_env, + ) + if rc == 0 and receipt_path.is_file(): + readback_evidence = wrap_readback_evidence( + receipt_path.read_bytes(), readback_sha256 + ) # 4. The PHI-bearing report body goes to the CUSTOMER'S store, never ours. report_ref: Optional[str] = job.report_ref() halt = halt_object(report) + if error_code == "child_outcome_unknown" and halt is None: + halt = {"present": True} outcome_envelope = precise_outcome_from_report(report) + if error_code is not None and outcome_envelope is not None: + # A cancelled or mismatched run never reports a success envelope. + outcome_envelope = None try: storage.write_report(report_ref, report) except Exception as exc: @@ -468,14 +1019,23 @@ def execute_job( status = "halt" outcome_envelope = None halt = halt or {"outcome": "halt"} + error_code = error_code or "report_write_failed" + metrics = metrics_from_report(report) + if readback_evidence is not None: + metrics["wrap_readback"] = readback_evidence + if report_ref is not None: + # Only the SHA-256 of the stored report leaves; Cloud seals it with + # the outcome so a receipt can bind this exact report. + metrics["report_sha256"] = hashlib.sha256(report_bytes(report)).hexdigest() return ExecutionResult( status=status, - metrics=metrics_from_report(report), + metrics=metrics, halt=halt, report_ref=report_ref, error=outcome_error, verified_bundle_sha256=observed_sha256, failure_signal=automation_failure_signal(report, status, job.target_kind), outcome=outcome_envelope, + error_code=error_code, ) diff --git a/packages/flow/openadapt_flow/connector/protocol.py b/packages/flow/openadapt_flow/connector/protocol.py index 5126d9eccf..e38494af2f 100644 --- a/packages/flow/openadapt_flow/connector/protocol.py +++ b/packages/flow/openadapt_flow/connector/protocol.py @@ -10,9 +10,9 @@ storage it is configured with. The control plane holds no URL to those bytes and signs no access to them. -The model is intentionally ``extra="ignore"`` (the control plane may add PHI-free -fields; a Connector must not brittle-fail on an additive change). The governance -posture is instead enforced EXPLICITLY by :meth:`ByocJob.ensure_governed`, which +Legacy payloads can still be parsed for inspection. Unknown outer fields are +retained, never silently dropped; live execution rejects them. The governance +posture is enforced by :meth:`ByocJob.ensure_governed`, which fail-closes when the dispatch is missing the governed policy, the run-scoped callback capability, or the immutable bundle binding — or when it carries an our-owned signed URL that has no place on the byoc path. @@ -20,13 +20,39 @@ from __future__ import annotations -from typing import Any, Optional +import re +from typing import TYPE_CHECKING, Any, Optional from urllib.parse import urlsplit from pydantic import BaseModel, ConfigDict, Field, ValidationError from openadapt_flow.ir import ExecutionTargetKind from openadapt_flow.runner.dispatch_envelope import ManagedDispatchEnvelope +from openadapt_flow.runner.protocol import DISPATCH_BINDING_LOCAL_FIELDS + +if TYPE_CHECKING: + from openadapt_flow.qualification_admission_v2 import ( + QualificationAdmissionEnvelope as QualificationAdmissionEnvelopeV2, + ) + +#: The exact keys Flow's ManagedDispatchEnvelope reads (Cloud adds others). +FLOW_DISPATCH_WIRE_KEYS = ( + "schema_version", + "run_id", + "bundle_content_digest", + "runtime_inputs_digest", + "authorization", + "dispatch_binding_sha256", +) +MANAGED_DELIVERY_AUTHORITY_CAPABILITY = "managed_delivery_authority_v3" +PROGRAM_ADMISSION_SCHEMA = "openadapt.program-admission-reference/v1" +PROGRAM_ADMISSION_ADMITTER_SCHEMA = "openadapt.program-admission-reference/v2" +PROGRAM_ADMISSION_APPROVAL_PREFIX = "hosted:program-admission:" +_HEX64 = re.compile(r"[a-f0-9]{64}\Z") +_UUID = re.compile( + r"[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}\Z" +) +_PRINCIPAL = re.compile(r"[A-Za-z0-9][A-Za-z0-9._:@-]{0,127}\Z") class ByocJobParseError(ValueError): @@ -45,7 +71,7 @@ class ByocGovernanceError(ValueError): class ByocStorage(BaseModel): """Customer-owned storage reference (opaque relative keys).""" - model_config = ConfigDict(extra="ignore") + model_config = ConfigDict(extra="allow") #: Hint only; the Connector's own config is authoritative. backend: Optional[str] = None @@ -66,7 +92,7 @@ class GroundingModel(BaseModel): environment, inside the customer perimeter. """ - model_config = ConfigDict(extra="ignore") + model_config = ConfigDict(extra="allow") enabled: bool = False provider: Optional[str] = None @@ -77,9 +103,9 @@ class GroundingModel(BaseModel): class ByocJob(BaseModel): - """One PHI-free BYOC dispatch descriptor.""" + """One BYOC descriptor; parsing alone never authorizes live execution.""" - model_config = ConfigDict(extra="ignore") + model_config = ConfigDict(extra="allow") mode: str = "replay" run_id: str @@ -105,12 +131,19 @@ class ByocJob(BaseModel): #: Run-scoped bearer capability presented as ``x-run-token`` on the PHI-free #: callback. It proves this run and must remain private. run_token: Optional[str] = None - #: Exact Cloud-issued, one-run authority. It stays PHI-free and is written - #: to a private local file before the governed child starts. - managed_dispatch: Optional[ManagedDispatchEnvelope] = None + #: Exact Cloud-issued, one-run authority, as Cloud sends it: the six Flow + #: wire keys plus the authority reference (``program_admission`` for an + #: admitted wrap program, or ``qualification_admission`` and its digest). + #: Kept raw here; :meth:`flow_dispatch` projects the exact Flow envelope + #: that is written to a private local file before the governed child + #: starts, and :meth:`program_admission` validates the reference. + managed_dispatch: Optional[dict[str, Any]] = None #: HTTPS endpoint that issues monotonic per-action delivery permits for the #: exact managed dispatch. The run-scoped ``run_token`` authenticates it. managed_delivery_authority_url: Optional[str] = None + #: Retained Cloud session, required by live execution and bound again by + #: the signed v3 permit. Never inferred from an untrusted response. + managed_dispatch_session_id: Optional[str] = None bundle_version_id: Optional[str] = None runtime_validation_id: Optional[str] = None #: SHA-256 of the exact approved sanitized derivative ZIP bytes staged at @@ -132,14 +165,17 @@ def ensure_governed(self, *, require_run_token: bool = True) -> None: """Fail closed unless every governance requirement is present. Args: - require_run_token: when True (the live default) a dispatch without a - run-scoped callback token is refused — we would be unable to - report its outcome, so we must not run it. Set False only for a - mock/dev control plane that bypasses callback auth. + require_run_token: retained for legacy callers. Live managed + execution always requires its callback token and session; + False cannot authorize an older/mock payload. Raises: ByocGovernanceError: on the first missing requirement. """ + if self.mode != "replay": + raise ByocGovernanceError( + "byoc live connector only supports governed replay jobs" + ) if self.bundle_download_url: raise ByocGovernanceError( "byoc dispatch carries an our-owned bundle URL; the bundle must " @@ -177,14 +213,44 @@ def ensure_governed(self, *, require_run_token: bool = True) -> None: "byoc managed dispatch and delivery authority must be supplied " "together (fail closed)" ) + if ( + self.model_extra + or (self.storage is not None and self.storage.model_extra) + or self.grounding_model.model_extra + ): + raise ByocGovernanceError( + "byoc live dispatch carries unsupported governance fields" + ) + if self.managed_dispatch is None or not self.managed_delivery_authority_url: + raise ByocGovernanceError( + "byoc live execution requires exact managed delivery authority" + ) + if not isinstance(self.managed_dispatch_session_id, str) or not _UUID.fullmatch( + self.managed_dispatch_session_id + ): + raise ByocGovernanceError( + "byoc live execution requires a canonical managed dispatch session" + ) if self.managed_dispatch is not None: + if not self.run_token: + raise ByocGovernanceError( + "byoc managed dispatch requires its run-scoped callback token" + ) + envelope = self.flow_dispatch() try: - authorization = self.managed_dispatch.exact_authorization() + authorization = envelope.exact_authorization() except ValueError as exc: raise ByocGovernanceError( "byoc managed dispatch has an invalid authorization binding" ) from exc - if self.managed_dispatch.run_id != self.run_id: + if self.program_admission() is None and not self._qualification_ok( + envelope + ): + raise ByocGovernanceError( + "byoc managed dispatch carries neither a program admission " + "nor an exact qualification admission (fail closed)" + ) + if envelope.run_id != self.run_id: raise ByocGovernanceError( "byoc managed dispatch belongs to a different run (fail closed)" ) @@ -222,6 +288,161 @@ def ensure_governed(self, *, require_run_token: bool = True) -> None: "resolve from the customer's storage (fail closed)" ) + def flow_dispatch(self) -> ManagedDispatchEnvelope: + """Consume the closed authority union before writing its six Flow keys.""" + from openadapt_flow.runtime.authorization import GovernedRunAuthorization + + raw = self.managed_dispatch + if not isinstance(raw, dict): + raise ByocGovernanceError("byoc managed dispatch is malformed") + program = "program_admission" in raw + extension = ( + {"program_admission"} + if program + else {"qualification_admission", "qualification_admission_sha256"} + ) + if set(raw) != set(FLOW_DISPATCH_WIRE_KEYS) | extension: + raise ByocGovernanceError("byoc managed authority union is not closed") + if type(raw.get("schema_version")) is not int or raw["schema_version"] != 1: + raise ByocGovernanceError("byoc managed dispatch version is not canonical") + authorization = raw.get("authorization") + if not isinstance(authorization, dict) or set(authorization) - set( + GovernedRunAuthorization.model_fields + ): + raise ByocGovernanceError( + "byoc managed authorization has unsupported fields" + ) + if any( + authorization.get(key) is not None for key in DISPATCH_BINDING_LOCAL_FIELDS + ): + raise ByocGovernanceError( + "byoc remote dispatch cannot supply runner-local authority" + ) + try: + envelope = ManagedDispatchEnvelope.model_validate( + {key: raw[key] for key in FLOW_DISPATCH_WIRE_KEYS} + ) + except (ValidationError, ValueError) as exc: + raise ByocGovernanceError( + "byoc managed dispatch does not match the Flow envelope" + ) from exc + if program: + if ( + self.program_admission() is None + or envelope.authorization.qualification_admission is not None + or envelope.authorization.qualification_admission_sha256 is not None + ): + raise ByocGovernanceError("byoc program admission reference is invalid") + elif not self._qualification_ok(envelope): + raise ByocGovernanceError( + "byoc qualification admission does not bind this job" + ) + return envelope + + def program_admission(self) -> Optional[dict[str, str]]: + """The exact person-v1 or admitter-v2 reference, without downgrading.""" + raw = self.managed_dispatch + if not isinstance(raw, dict): + return None + reference = raw.get("program_admission") + authorization = raw.get("authorization") + if ( + "qualification_admission" in raw + or "qualification_admission_sha256" in raw + or not isinstance(reference, dict) + or not isinstance(authorization, dict) + or authorization.get("execution_profile") != "standard" + ): + return None + common = {"schema_version", "admission_sha256", "public_key_hex"} + version = reference.get("schema_version") + if version == PROGRAM_ADMISSION_SCHEMA: + if set(reference) != common: + return None + elif version == PROGRAM_ADMISSION_ADMITTER_SCHEMA: + if ( + set(reference) + != common + | { + "admission_mode", + "admitted_by_principal_id", + "admitter_public_key_hex", + } + or reference.get("admission_mode") != "admitter_key" + or not isinstance(reference.get("admitted_by_principal_id"), str) + or not _PRINCIPAL.fullmatch(reference["admitted_by_principal_id"]) + or not isinstance(reference.get("admitter_public_key_hex"), str) + or not _HEX64.fullmatch(reference["admitter_public_key_hex"]) + ): + return None + else: + return None + if ( + not isinstance(reference.get("admission_sha256"), str) + or not _HEX64.fullmatch(reference["admission_sha256"]) + or not isinstance(reference.get("public_key_hex"), str) + or not _HEX64.fullmatch(reference["public_key_hex"]) + or authorization.get("approval_source") + != PROGRAM_ADMISSION_APPROVAL_PREFIX + reference["admission_sha256"] + ): + return None + return dict(reference) + + def qualification_admission(self) -> QualificationAdmissionEnvelopeV2: + """Parse the actual outer signed v2 proof; parsing is not authority.""" + from openadapt_flow.qualification_admission_v2 import ( + QualificationAdmissionEnvelope, + ) + + raw = self.managed_dispatch or {} + admission = raw.get("qualification_admission") + digest = raw.get("qualification_admission_sha256") + if ( + "program_admission" in raw + or not isinstance(admission, dict) + or set(admission) != {"payload", "algorithm", "signature"} + or not isinstance(digest, str) + or not _HEX64.fullmatch(digest) + ): + raise ByocGovernanceError( + "byoc signed qualification reference is malformed" + ) + try: + parsed = QualificationAdmissionEnvelope.model_validate(admission) + except (ValidationError, ValueError) as exc: + raise ByocGovernanceError( + "byoc qualification proof is not admission v2" + ) from exc + if ( + parsed.model_dump(mode="json") != admission + or parsed.artifact_sha256() != digest + ): + raise ByocGovernanceError("byoc qualification proof digest does not match") + return parsed + + def _qualification_ok(self, envelope: ManagedDispatchEnvelope) -> bool: + # The outer v2 artifact is distinct from the runtime-local v1 field, + # which Cloud cannot populate. The executor must verify the artifact + # against independent operator context through the authority-file path. + if ( + envelope.authorization.qualification_admission is not None + or envelope.authorization.qualification_admission_sha256 is not None + ): + return False + try: + payload = self.qualification_admission().payload + except ByocGovernanceError: + return False + return ( + payload.tenant_id == self.org_id + and payload.workflow_id == self.workflow_id + and payload.workflow_version_id == self.bundle_version_id + and payload.bundle_version_id == self.bundle_version_id + and payload.runtime_validation_id == self.runtime_validation_id + and payload.bundle_artifact_sha256 == self.bundle_sha256 + and payload.bundle_content_digest == envelope.bundle_content_digest + ) + def report_ref(self) -> Optional[str]: """The customer-storage key the report is written to (opaque to us).""" if self.storage and self.storage.report_ref: @@ -239,6 +460,10 @@ def parse_job( required identifiers). The caller reports the refusal; it never runs a job it could not parse. """ + if "lease_job_id" in payload: + raise ByocJobParseError( + "byoc payload cannot replace its authenticated lease id" + ) try: job = ByocJob.model_validate(payload) except ValidationError as exc: diff --git a/packages/flow/openadapt_flow/connector/secrets.py b/packages/flow/openadapt_flow/connector/secrets.py new file mode 100644 index 0000000000..56fc45ff45 --- /dev/null +++ b/packages/flow/openadapt_flow/connector/secrets.py @@ -0,0 +1,93 @@ +"""Local secret store for the connector: only the reference crosses the network. + +A dispatch carries ``secrets_ref`` (a short name such as ``emr-reader``). The +connector resolves it here, on this machine, to ``/.env``: a +file of ``NAME=value`` lines the customer's administrator writes and protects. +The values go only into the environment of the one governed child process that +runs that job (where a deployment's ``effects.secret_env`` slots read them), +and into the egress guard's scan list, so a value that somehow reached a +request body is refused before it is sent. They are never logged, written to +the run directory, or returned to the control plane. + +On POSIX the file must not be readable by group or others (mode 0600 or +stricter); on Windows the service installer restricts the config directory +ACL to SYSTEM, Administrators and the service account. +""" + +from __future__ import annotations + +import os +import re +import stat +from pathlib import Path +from typing import Optional + +__all__ = ["SecretStoreError", "LocalSecretStore"] + +_REF = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$") +_ENV_NAME = re.compile(r"^[A-Z_][A-Z0-9_]{0,127}$") +#: Names a secret file may not set: they would redirect the child itself. +_RESERVED = frozenset( + { + "PATH", + "PYTHONPATH", + "PYTHONHOME", + "LD_PRELOAD", + "LD_LIBRARY_PATH", + "DYLD_INSERT_LIBRARIES", + "HTTP_PROXY", + "HTTPS_PROXY", + "NO_PROXY", + "OPENADAPT_DURABLE_AUTHORITY_URL", + "OPENADAPT_RUNNER_TOKEN", + "OPENADAPT_DURABLE_DISPATCH_SESSION_ID", + "OPENADAPT_JIT_KEY_DIR", + "OPENADAPT_QUALIFICATION_SIGNERS_JSON", + "BYOC_CONNECTOR_TOKEN", + } +) + + +class SecretStoreError(RuntimeError): + """A secret reference cannot be resolved safely. The job is refused.""" + + +class LocalSecretStore: + def __init__(self, root: Optional[str]) -> None: + self.root = Path(root) if root else None + + def resolve(self, ref: Optional[str]) -> dict[str, str]: + """Return the NAME=value pairs for ``ref`` (empty when ref is None).""" + if ref is None or ref == "": + return {} + if not isinstance(ref, str) or not _REF.fullmatch(ref): + raise SecretStoreError("secrets_ref is not a valid local reference") + if self.root is None: + raise SecretStoreError( + "the job names a secrets_ref but this connector has no secrets_dir" + ) + path = self.root / f"{ref}.env" + try: + info = path.stat() + except OSError as exc: + raise SecretStoreError( + "secrets_ref is not present in the local store" + ) from exc + if not stat.S_ISREG(info.st_mode): + raise SecretStoreError("secrets_ref does not name a regular file") + if os.name == "posix" and info.st_mode & 0o077: + raise SecretStoreError( + "local secret file is readable by group or others; chmod 600 it" + ) + values: dict[str, str] = {} + for number, line in enumerate(path.read_text(encoding="utf-8").splitlines(), 1): + stripped = line.strip() + if not stripped or stripped.startswith("#"): + continue + name, sep, value = stripped.partition("=") + name = name.strip() + if not sep or not _ENV_NAME.fullmatch(name) or name in _RESERVED: + # Say which line, never what it holds. + raise SecretStoreError(f"local secret file line {number} is invalid") + values[name] = value.strip() + return values diff --git a/packages/flow/openadapt_flow/connector/storage.py b/packages/flow/openadapt_flow/connector/storage.py index 67c066336a..deb410243c 100644 --- a/packages/flow/openadapt_flow/connector/storage.py +++ b/packages/flow/openadapt_flow/connector/storage.py @@ -44,6 +44,11 @@ def write_report(self, ref: Optional[str], report: dict[str, Any]) -> Optional[s ... +def report_bytes(report: dict[str, Any]) -> bytes: + """The exact bytes a report is stored as (its digest may leave; it may not).""" + return json.dumps(report, indent=2).encode("utf-8") + + def _customer_path(root: Path, ref: str, *, kind: str) -> Path: """Resolve one relative customer-storage key without crossing its root.""" if Path(ref).is_absolute() or "\\" in ref: @@ -94,7 +99,7 @@ def write_report(self, ref: Optional[str], report: dict[str, Any]) -> Optional[s return None dest = _customer_path(self.root, ref, kind="report") dest.parent.mkdir(parents=True, exist_ok=True) - dest.write_text(json.dumps(report, indent=2), encoding="utf-8") + dest.write_bytes(report_bytes(report)) try: os.chmod(dest, 0o600) # PHI-bearing — restrict at rest except OSError: # pragma: no cover diff --git a/packages/flow/openadapt_flow/connector/windows_service.py b/packages/flow/openadapt_flow/connector/windows_service.py index 9d7ce132e1..e3521c6678 100644 --- a/packages/flow/openadapt_flow/connector/windows_service.py +++ b/packages/flow/openadapt_flow/connector/windows_service.py @@ -236,9 +236,13 @@ def serve( ) return 2 logger.info( - "service starting: config %s, settings %s", + "service starting: config %s, control_plane_url=%s, org_id=%s, name=%s, poll_wait_s=%s, max_workers=%s", config_file(config_dir), - settings.redacted(), + settings.control_plane_url, + settings.org_id, + settings.name, + settings.poll_wait_s, + settings.max_workers, ) delay = _RETRY_START_S diff --git a/packages/flow/tests/connector_stub/wait_for_stub.py b/packages/flow/tests/connector_stub/wait_for_stub.py index 9d87f8927a..caf0f483fe 100644 --- a/packages/flow/tests/connector_stub/wait_for_stub.py +++ b/packages/flow/tests/connector_stub/wait_for_stub.py @@ -43,8 +43,9 @@ def check(records: list[dict[str, Any]]) -> tuple[bool, str]: raise SystemExit("callback carried no x-run-token header") if ack_body.get("job_id") != JOB_ID or ack_body.get("status") != "failed": raise SystemExit(f"unexpected ack: {ack_body}") - if "safety" not in (ack_body.get("error") or ""): - raise SystemExit(f"ack error does not name the safety refusal: {ack_body}") + # The ack carries a closed code, never free text. + if ack_body.get("error_code") != "governance_refused" or "error" in ack_body: + raise SystemExit(f"ack does not carry the governance refusal code: {ack_body}") return True, f"poll -> failed callback -> ack after {len(records)} requests" diff --git a/packages/flow/tests/connector_v3_fixtures.py b/packages/flow/tests/connector_v3_fixtures.py new file mode 100644 index 0000000000..2e22baa1b4 --- /dev/null +++ b/packages/flow/tests/connector_v3_fixtures.py @@ -0,0 +1,451 @@ +"""Public synthetic BYOC contracts with real signatures and no external service. + +Signing keys are generated only in test-local author storage. The exposed +customer trust directory contains public keys/registrations, never a signer. +""" + +from __future__ import annotations + +import hashlib +import io +import json +import shutil +import zipfile +from pathlib import Path +from typing import Any + +from cryptography.hazmat.primitives import serialization +from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey + +from openadapt_flow.execute.keys import fingerprint_of, load_or_create_private_key +from openadapt_flow.ir import ( + ActionKind, + Anchor, + Postcondition, + PostconditionKind, + Step, + Workflow, +) +from openadapt_flow.jit import authority, hosted_authority, lifecycle +from openadapt_flow.runner.dispatch_envelope import ManagedDispatchEnvelope +from openadapt_flow.runner.protocol import dispatch_binding_sha256 +from openadapt_flow.runtime.authorization import ( + GovernedRunAuthorization, + runtime_inputs_digest, +) +from openadapt_flow.runtime.effects.effect import Effect, EffectKind + +ORG_ID = "ac100000-0000-4000-8000-000000000001" +WORKFLOW_ID = "ac100000-0000-4000-8000-000000000002" +RUN_ID = "ac100000-0000-4000-8000-000000000003" +BUNDLE_VERSION_ID = "ac100000-0000-4000-8000-000000000004" +VALIDATION_ID = "ac100000-0000-4000-8000-000000000005" +SESSION_ID = "ac100000-0000-4000-8000-000000000006" +CONTROL_PLANE = "https://control.example.test" +PERMIT_URL = CONTROL_PLANE + "/api/internal/managed-delivery-permit" +ADMITTER_ID = "ci:contract-test-admitter" +CHECKS = ( + "schema_version: openadapt.verify/v1\n" + "verifier:\n kind: rest\n base_url: https://record.example.test\n" + " records_path: /records\n" + "effects:\n - kind: record_written\n" + " match: {type: synthetic-record}\n field: value\n" +) + + +def archive_tree(root: Path) -> bytes: + """Return deterministic bytes for this test's immutable bundle inventory.""" + stream = io.BytesIO() + with zipfile.ZipFile(stream, "w", zipfile.ZIP_DEFLATED) as archive: + for path in sorted(root.rglob("*")): + if path.is_file(): + member = zipfile.ZipInfo(path.relative_to(root).as_posix()) + archive.writestr(member, path.read_bytes()) + return stream.getvalue() + + +def build_program_case(root: Path, mode: str = "person") -> dict[str, Any]: + """Build a real signed person/admitter case for receiver boundary tests.""" + if mode not in {"person", "admitter_key"}: + raise ValueError("the fixture models only the two declared program forms") + root.mkdir(parents=True, exist_ok=True) + bundle = root / "bundle" + signing_dir = root / "author-signing" + trust_dir = root / "customer-public-trust" + author_key = load_or_create_private_key(signing_dir) + public = author_key.public_key() + public_hex = public.public_bytes( + serialization.Encoding.Raw, serialization.PublicFormat.Raw + ).hex() + workflow = Workflow( + name="synthetic-contract", + steps=[ + Step( + id="step_000", + intent="enter value", + action=ActionKind.TYPE, + text="fixture", + ), + Step( + id="step_001", + intent="save record", + action=ActionKind.CLICK, + risk="irreversible", + identity_armed=True, + anchor=Anchor( + template="templates/save.png", + region=(0, 0, 10, 10), + click_point=(5, 5), + ocr_text="Save", + context_text="Synthetic record", + ), + expect=[ + Postcondition(kind=PostconditionKind.TEXT_PRESENT, text="Saved") + ], + effects=[ + Effect( + kind=EffectKind.RECORD_WRITTEN, + match={"type": "synthetic-record"}, + field="value", + idempotency_key="synthetic-contract-write", + risk="irreversible", + ) + ], + ), + ], + ) + from tests.test_replayer import make_png + + (bundle / "templates").mkdir(parents=True, exist_ok=True) + (bundle / "templates/save.png").write_bytes(make_png((10, 10))) + workflow.save(bundle) + readback = bundle / hosted_authority.READBACK_PATH + readback.parent.mkdir(parents=True, exist_ok=True) + readback.write_text(CHECKS, encoding="utf-8") + workflow = Workflow.load(bundle) + assert workflow.manifest is not None + body: dict[str, Any] = { + "schema": lifecycle.ADMISSION_SCHEMA, + "signing_key": fingerprint_of(public), + "admitted_by_principal_id": "Example Operator", + "admission_mode": mode, + "state": lifecycle.BundleState.ADMITTED.value, + "digest": workflow.manifest.content_digest, + } + registry = authority.PrincipalRegistry() + admitter_hex = None + if mode == "admitter_key": + admitter = Ed25519PrivateKey.generate() + admitter_hex = ( + admitter.public_key() + .public_bytes(serialization.Encoding.Raw, serialization.PublicFormat.Raw) + .hex() + ) + body.update( + admitted_by_principal_id=ADMITTER_ID, + admitter_public_key=admitter_hex, + ) + body["admitter_signature"] = authority._sign( + admitter, authority.ADMITTER_DOMAIN, body + ) + registry = authority.PrincipalRegistry( + admitter_keys={ADMITTER_ID: admitter_hex} + ) + registry.save(signing_dir) + original = {**body, "signature": lifecycle._sign_record(body, signing_dir)} + hosted = hosted_authority.hosted_admission( + original, + key_dir=signing_dir, + readback_digest=hosted_authority.readback_sha256(bundle), + ) + (bundle / lifecycle.ADMISSION_FILE).write_text(json.dumps(hosted), encoding="utf-8") + (trust_dir / "keys").mkdir(parents=True, exist_ok=True) + shutil.copyfile(signing_dir / "keys/ed25519.pub", trust_dir / "keys/ed25519.pub") + registry.save(trust_dir) + # This is deliberately a public projection. The signing PEM stays above. + assert sorted( + p.relative_to(trust_dir).as_posix() for p in trust_dir.rglob("*") if p.is_file() + ) == ["keys/ed25519.pub", "principals.json"] + lifecycle.verify_admission(bundle, key_dir=trust_dir) + shape = hosted_authority.run_shape(bundle, workflow, policy_source="clinical-write") + authorization = GovernedRunAuthorization( + bundle_content_digest=shape["bundle_content_digest"], + runtime_inputs_digest=runtime_inputs_digest( + workflow, {}, None, interstitials=[] + ), + admitted_policy_name=shape["admitted_policy_name"], + admitted_policy_contract_sha256=shape["admitted_policy_contract_sha256"], + execution_profile="standard", + minimum_effect_tier=shape["minimum_effect_tier"], + qualified_effect_requirements=shape["qualified_effect_requirements"], + required_identity_step_ids=shape["required_identity_step_ids"], + approval_source=hosted_authority.approval_source(shape["admission_sha256"]), + ) + envelope = ManagedDispatchEnvelope( + run_id=RUN_ID, + bundle_content_digest=authorization.bundle_content_digest, + runtime_inputs_digest=authorization.runtime_inputs_digest, + authorization=authorization, + dispatch_binding_sha256=dispatch_binding_sha256(RUN_ID, authorization), + ) + reference = { + "schema_version": "openadapt.program-admission-reference/v1", + "admission_sha256": shape["admission_sha256"], + "public_key_hex": public_hex, + } + if mode == "admitter_key": + reference.update( + schema_version="openadapt.program-admission-reference/v2", + admission_mode="admitter_key", + admitted_by_principal_id=ADMITTER_ID, + admitter_public_key_hex=admitter_hex, + ) + dispatch = {**envelope.model_dump(mode="json"), "program_admission": reference} + archive = archive_tree(bundle) + payload = { + "mode": "replay", + "run_id": RUN_ID, + "org_id": ORG_ID, + "workflow_id": WORKFLOW_ID, + "target_kind": "web", + "storage": { + "backend": "local", + "bundle_ref": "bundles/program.zip", + "report_ref": "reports/run.json", + }, + "target_url": "https://record.example.test/", + "allowed_hosts": ["record.example.test"], + "params": {"target_kind": "web"}, + "run_token": "synthetic-run-capability", + "bundle_version_id": BUNDLE_VERSION_ID, + "runtime_validation_id": VALIDATION_ID, + "bundle_sha256": hashlib.sha256(archive).hexdigest(), + "safety": {"effects.verify": True}, + "grounding_model": {"enabled": False}, + "managed_dispatch": dispatch, + "managed_delivery_authority_url": PERMIT_URL, + "managed_dispatch_session_id": SESSION_ID, + } + return { + "bundle": bundle, + "bundle_dir": bundle, + "bundle_bytes": archive, + "archive": archive, + "key_dir": trust_dir, + "public_key_hex": public_hex, + "admission_sha256": shape["admission_sha256"], + "admission": hosted, + "workflow": workflow, + "shape": shape, + "dispatch": dispatch, + "payload": payload, + "settings_kwargs": { + "control_plane_url": CONTROL_PLANE, + "org_id": ORG_ID, + "trusted_admission_keys": public_hex, + "admission_key_dir": str(trust_dir), + }, + } + + +def build_qualification_case(root: Path) -> dict[str, Any]: + """Sign a v2 proof for public synthetic certification/model evidence. + + The operator context is assembled from known fixture state before signing. + This is cryptographic source-contract evidence, not live qualification. + """ + from base64 import b64encode + from datetime import datetime, timedelta, timezone + + from openadapt_flow.policy import load_policy + from openadapt_flow.production_qualification import ( + ProductionQualificationAuthority, + ProductionQualificationGuard, + ) + from openadapt_flow.qualification import certify_project, save_qualified_workflow + from openadapt_flow.qualification_admission_v2 import ( + QualificationAdmissionExpected, + QualificationAdmissionPayload, + QualificationSignerRegistry, + contract_sha256, + qualification_signer_key_id, + sign_qualification_admission, + ) + from openadapt_flow.verification import VerificationTier + from tests.test_qualification_admission_v2 import ( + _payload, + _registry, + _runtime_build, + ) + from tests.test_qualification_project import ( + _configure, + _qualification_visual_fixture, + _record_passing_campaign, + _workflow, + ) + + root.mkdir(parents=True, exist_ok=True) + bundle = root / "bundle" + (bundle / "templates").mkdir(parents=True) + (bundle / "templates/save.png").write_bytes(_qualification_visual_fixture()[1]) + workflow = _workflow() + workflow.save(bundle) + workflow = Workflow.load(bundle) + _configure(workflow, tier=VerificationTier.INDEPENDENT_SYSTEM) + evidence_root = root / "synthetic-evidence" + _record_passing_campaign(workflow, evidence_root) + certification = certify_project( + workflow, policy=load_policy("clinical-write"), evidence_root=evidence_root + ) + assert certification.passed, certification.render() + save_qualified_workflow(workflow, bundle) + workflow = Workflow.load(bundle) + assert workflow.manifest is not None and workflow.qualification is not None + template = workflow.manifest.provenance.governed_authorization_template + assert template is not None + archive = archive_tree(bundle) + archive_digest = hashlib.sha256(archive).hexdigest() + now = datetime.now(timezone.utc).replace(microsecond=0) + + def utc(moment): + return moment.strftime("%Y-%m-%dT%H:%M:%SZ") + + signer = Ed25519PrivateKey.generate() + public = signer.public_key().public_bytes( + serialization.Encoding.Raw, serialization.PublicFormat.Raw + ) + registry_data = _registry().model_dump(mode="json") + registry_data.update( + generated_at=utc(now - timedelta(minutes=1)), + expires_at=utc(now + timedelta(hours=1)), + ) + registry_data["signers"][0].update( + key_id=qualification_signer_key_id(public), + public_key=b64encode(public).decode("ascii"), + ) + registry = QualificationSignerRegistry.model_validate(registry_data) + runtime = _runtime_build().model_dump(mode="json") + known = { + "tenant_id": ORG_ID, + "workflow_id": WORKFLOW_ID, + "workflow_version_id": BUNDLE_VERSION_ID, + "bundle_version_id": BUNDLE_VERSION_ID, + "runtime_validation_id": VALIDATION_ID, + "bundle_artifact_sha256": archive_digest, + "bundle_content_digest": workflow.manifest.content_digest, + "environment_digest": workflow.qualification.environment.environment_digest, + "governed_authorization_template_sha256": template.template_sha256, + "application_contract_sha256": "a" * 64, + "substrate_contract_sha256": "a" * 64, + "environment_contract_sha256": template.qualification_environment_contract_sha256, + "runtime_environment_sha256": "c" * 64, + "runtime_contract_sha256": "a" * 64, + "input_policy_sha256": template.parameter_contract_sha256, + "action_policy_sha256": template.qualification_project_contract_sha256, + "network_policy_sha256": "a" * 64, + "identity_contract_sha256": template.identity_contract_sha256, + "effect_contract_sha256": contract_sha256( + [ + item.model_dump(mode="json") + for item in template.qualified_effect_requirements + ] + ), + "operator_contract_sha256": "a" * 64, + "runtime_build_identity": runtime, + "evidence_runner_signer_sha256": "b" * 64, + "deployment_manifest_sha256": "d" * 64, + } + expected = QualificationAdmissionExpected.model_validate(known) + raw = _payload(registry).model_dump(mode="json") + raw.update({k: v for k, v in known.items() if k in raw}) + raw.update( + issued_at=utc(now - timedelta(seconds=1)), + not_before=utc(now - timedelta(seconds=1)), + expires_at=utc(now + timedelta(minutes=30)), + ) + raw["issuer"]["key_id"] = qualification_signer_key_id(public) + raw["evidence_identity"].update( + {k: v for k, v in known.items() if k in raw["evidence_identity"]} + ) + raw["evidence_identity"]["workflow_digest"] = workflow.manifest.content_digest + proof = sign_qualification_admission( + QualificationAdmissionPayload.model_validate(raw), signer + ) + authority_file = root / "operator-authority.json" + operator = ProductionQualificationAuthority( + qualification_admission=proof, + qualification_admission_sha256=proof.artifact_sha256(), + expected=expected, + qualification_signer_registry=registry, + qualification_signer_registry_sha256=registry.artifact_sha256(), + ) + authority_file.write_text(operator.model_dump_json(), encoding="utf-8") + authority_file.chmod(0o600) + ProductionQualificationGuard( + authority_file, remote_permit_revalidation=True + ).verify(workflow, for_actuation=False) + authorization = GovernedRunAuthorization( + bundle_content_digest=workflow.manifest.content_digest, + runtime_inputs_digest=runtime_inputs_digest( + workflow, {}, None, interstitials=[] + ), + admitted_policy_name=template.policy_name, + admitted_policy_contract_sha256=template.policy_contract_sha256, + execution_profile="standard", + minimum_effect_tier=template.minimum_effect_tier, + qualified_effect_requirements=template.qualified_effect_requirements, + required_identity_step_ids=template.required_identity_step_ids, + approval_source="hosted:execute-api", + ) + envelope = ManagedDispatchEnvelope( + run_id=RUN_ID, + bundle_content_digest=authorization.bundle_content_digest, + runtime_inputs_digest=authorization.runtime_inputs_digest, + authorization=authorization, + dispatch_binding_sha256=dispatch_binding_sha256(RUN_ID, authorization), + ) + dispatch = { + **envelope.model_dump(mode="json"), + "qualification_admission": proof.model_dump(mode="json"), + "qualification_admission_sha256": proof.artifact_sha256(), + } + payload = { + "mode": "replay", + "run_id": RUN_ID, + "org_id": ORG_ID, + "workflow_id": WORKFLOW_ID, + "target_kind": "web", + "storage": { + "backend": "local", + "bundle_ref": "bundles/qualified.zip", + "report_ref": "reports/run.json", + }, + "target_url": "https://record.example.test/", + "allowed_hosts": ["record.example.test"], + "params": {"target_kind": "web"}, + "run_token": "synthetic-run-capability", + "bundle_version_id": BUNDLE_VERSION_ID, + "runtime_validation_id": VALIDATION_ID, + "bundle_sha256": archive_digest, + "safety": {"effects.verify": True}, + "grounding_model": {"enabled": False}, + "managed_dispatch": dispatch, + "managed_delivery_authority_url": PERMIT_URL, + "managed_dispatch_session_id": SESSION_ID, + } + return { + "bundle": bundle, + "bundle_dir": bundle, + "bundle_bytes": archive, + "archive": archive, + "payload": payload, + "dispatch": dispatch, + "operator": operator, + "authority_file": authority_file, + "workflow": workflow, + "settings_kwargs": { + "control_plane_url": CONTROL_PLANE, + "org_id": ORG_ID, + "qualification_authority_file": str(authority_file), + }, + } diff --git a/packages/flow/tests/fixtures/connector_outcome_envelope_verified.json b/packages/flow/tests/fixtures/connector_outcome_envelope_verified.json new file mode 100644 index 0000000000..a090982dce --- /dev/null +++ b/packages/flow/tests/fixtures/connector_outcome_envelope_verified.json @@ -0,0 +1,79 @@ +{ + "compensation_actions": 0, + "evidence_classes": [ + "authorization", + "effect_tier_1", + "identity", + "postcondition" + ], + "execution_completed": true, + "external_network_calls": "observed", + "model_calls": 0, + "outcome": "VERIFIED", + "passed_contracts": { + "authorization": 1, + "effect": 2, + "identity": 2, + "postcondition": 4 + }, + "postcondition_evidence": [ + { + "action_kind": "click", + "actuation_path": "gui", + "contract_index": 0, + "contract_kind": "explicit_predicate", + "contract_sha256": "d750488f78772be76ebd73cd59d0f86fc3dfdbb489f2df21c17a17272fcc08a2", + "result_index": 0, + "step_contract_sha256": "d36ec7bb6a6fa08e1fb9c774009cfa031b5d4110a748c53884e487abcc0b0931", + "step_index": 0, + "verdict": "passed", + "workflow_contract_sha256": "dae8ae6ed64c61d73f8f9e4c2d395c0158b2288fc084a6ebf34acac63ccb02f9" + }, + { + "action_kind": "type", + "actuation_path": "gui", + "contract_index": 0, + "contract_kind": "intrinsic_input_readback", + "contract_sha256": "9ec4d9a765695df30a2a0004cb83142d34f9364fe85fe26804d034337e0888be", + "result_index": 1, + "step_contract_sha256": "f1b9a9687e449f73e8ae1d1fd5c8e064d138c28d6f79bb7581e2025e034af7f8", + "step_index": 1, + "verdict": "passed", + "workflow_contract_sha256": "dae8ae6ed64c61d73f8f9e4c2d395c0158b2288fc084a6ebf34acac63ccb02f9" + }, + { + "action_kind": "click", + "actuation_path": "gui", + "contract_index": 0, + "contract_kind": "explicit_predicate", + "contract_sha256": "b95dcc1092a0382ceb9617ec8454346fca5b60efd3db208cb034eea5f3d05ed4", + "result_index": 2, + "step_contract_sha256": "7b85a93d484530d98da535f683fae1e53ce232af57d1627ffb4920ad18b0e30b", + "step_index": 2, + "verdict": "passed", + "workflow_contract_sha256": "dae8ae6ed64c61d73f8f9e4c2d395c0158b2288fc084a6ebf34acac63ccb02f9" + }, + { + "action_kind": "click", + "actuation_path": "gui", + "contract_index": 1, + "contract_kind": "explicit_predicate", + "contract_sha256": "c56c32d7cc387b50bf5709c35cbf4856208c224685da70bb0837ad5f54383356", + "result_index": 2, + "step_contract_sha256": "7b85a93d484530d98da535f683fae1e53ce232af57d1627ffb4920ad18b0e30b", + "step_index": 2, + "verdict": "passed", + "workflow_contract_sha256": "dae8ae6ed64c61d73f8f9e4c2d395c0158b2288fc084a6ebf34acac63ccb02f9" + } + ], + "production_eligible": true, + "profile": "standard", + "required_contracts": { + "authorization": 1, + "effect": 2, + "identity": 2, + "postcondition": 4 + }, + "version": "openadapt.execution-outcome/v1", + "workflow_contract_sha256": "dae8ae6ed64c61d73f8f9e4c2d395c0158b2288fc084a6ebf34acac63ccb02f9" +} \ No newline at end of file diff --git a/packages/flow/tests/test_connector.py b/packages/flow/tests/test_connector.py index dfb5898658..b70bfc6fb8 100644 --- a/packages/flow/tests/test_connector.py +++ b/packages/flow/tests/test_connector.py @@ -17,23 +17,22 @@ from __future__ import annotations +import copy import hashlib -import io import json import os import stat -import zipfile from pathlib import Path import httpx import pytest from openadapt_flow.connector import ( + MANAGED_QUALIFICATION_AUTHORITY_CAPABILITY, ConnectorClient, ConnectorSettings, ExecutionResult, InMemoryCustomerStorage, - MANAGED_QUALIFICATION_AUTHORITY_CAPABILITY, build_run_argv, execute_job, load_settings, @@ -44,7 +43,10 @@ status_from_report, ) from openadapt_flow.connector.executor import RunOutcome, precise_outcome_from_report -from openadapt_flow.connector.protocol import ByocGovernanceError +from openadapt_flow.connector.protocol import ( + FLOW_DISPATCH_WIRE_KEYS, + ByocGovernanceError, +) from openadapt_flow.connector.storage import LocalCustomerStorage from openadapt_flow.failure_signals import automation_failure_signal from openadapt_flow.runner.dispatch_envelope import ManagedDispatchEnvelope @@ -53,19 +55,44 @@ from openadapt_flow.runtime.durable.authority import ( REMOTE_AUTHORITY_TOKEN_ENV, REMOTE_AUTHORITY_URL_ENV, + REMOTE_DISPATCH_SESSION_ID_ENV, ) +from tests.connector_v3_fixtures import build_program_case +_CASE = None +_BUNDLE_BYTES = b"" +_BUNDLE_SHA256 = "" -def _bundle_archive_bytes() -> bytes: - stream = io.BytesIO() - info = zipfile.ZipInfo("workflow.json", date_time=(2026, 1, 1, 0, 0, 0)) - with zipfile.ZipFile(stream, "w", compression=zipfile.ZIP_DEFLATED) as archive: - archive.writestr(info, "{}") - return stream.getvalue() +@pytest.fixture(scope="module", autouse=True) +def _signed_transport_program(module_durable_authority, tmp_path_factory): + # Transport tests still fake the governed child. Their bundle now carries + # real signatures instead of inheriting live authority from a legacy mock. + global _CASE, _BUNDLE_BYTES, _BUNDLE_SHA256 + _CASE = build_program_case(tmp_path_factory.mktemp("connector-program")) + _BUNDLE_BYTES = _CASE["bundle_bytes"] + _BUNDLE_SHA256 = hashlib.sha256(_BUNDLE_BYTES).hexdigest() -_BUNDLE_BYTES = _bundle_archive_bytes() -_BUNDLE_SHA256 = hashlib.sha256(_BUNDLE_BYTES).hexdigest() + +@pytest.fixture(autouse=True) +def _transport_has_no_external_readback(monkeypatch): + # The old transport fixture had no readback file. Keep these wire/report + # tests offline while leaving signature, registry and envelope gates real. + monkeypatch.setattr( + "openadapt_flow.connector.executor._run_flow_tool", lambda *_: 1 + ) + + +def _settings(**overrides): + return ConnectorSettings( + **{ + "control_plane_url": "https://app.test", + "org_id": "org_demo", + "trusted_admission_keys": _CASE["public_key_hex"], + "admission_key_dir": str(_CASE["key_dir"]), + **overrides, + } + ) # -------------------------------------------------------------------------- @@ -88,7 +115,7 @@ def _payload(**overrides): "target_url": "https://emr.internal/app", "allowed_hosts": ["cdn.internal"], "params": {"vendor": "ACME", "target_kind": "web"}, - "secrets_ref": "emr-secrets", + "secrets_ref": None, "run_token": "a" * 64, "bundle_version_id": "bv_1", "runtime_validation_id": "rv_1", @@ -96,18 +123,19 @@ def _payload(**overrides): "safety": {"halt.on_ambiguous": True, "effects.verify": True}, "grounding_model": {"enabled": False, "api_key_env": ""}, } + payload.update( + managed_dispatch=_managed_dispatch(), + managed_delivery_authority_url="https://app.test/api/internal/managed-delivery-permit", + managed_dispatch_session_id=_CASE["payload"]["managed_dispatch_session_id"], + ) payload.update(overrides) return payload def _managed_dispatch(*, run_id: str | None = None) -> dict: - exact_run_id = run_id or _payload()["run_id"] - authorization = GovernedRunAuthorization( - bundle_content_digest="b" * 64, - runtime_inputs_digest="c" * 64, - admitted_policy_name="standard", - execution_profile="standard", - approval_source="hosted:execute-api", + exact_run_id = run_id or "00000000-0000-4000-8000-000000000005" + authorization = GovernedRunAuthorization.model_validate( + _CASE["dispatch"]["authorization"] ) envelope = ManagedDispatchEnvelope( run_id=exact_run_id, @@ -116,7 +144,14 @@ def _managed_dispatch(*, run_id: str | None = None) -> dict: authorization=authorization, dispatch_binding_sha256=dispatch_binding_sha256(exact_run_id, authorization), ) - return envelope.model_dump(mode="json") + return { + **envelope.model_dump(mode="json"), + "program_admission": copy.deepcopy(_CASE["dispatch"]["program_admission"]), + } + + +def _wire(dispatch: dict) -> dict: + return {key: dispatch[key] for key in FLOW_DISPATCH_WIRE_KEYS} def _fake_success_runner(report): @@ -148,7 +183,7 @@ def runner(argv, run_dir: Path, _env) -> RunOutcome: # -------------------------------------------------------------------------- def test_execute_job_success_writes_report_to_customer_storage_only(): job = parse_job(_payload(), lease_job_id="bjob_1") - settings = ConnectorSettings(profile=None) + settings = _settings(profile=None) storage = InMemoryCustomerStorage(bundle_bytes=_BUNDLE_BYTES) result = execute_job( @@ -166,9 +201,10 @@ def test_execute_job_success_writes_report_to_customer_storage_only(): def test_execute_job_consumes_exact_managed_dispatch_through_private_child_boundary( monkeypatch, ): - authority_url = "https://app.openadapt.ai/api/internal/managed-delivery-permit" + authority_url = "https://app.test/api/internal/managed-delivery-permit" token = "a" * 64 managed_dispatch = _managed_dispatch() + monkeypatch.setenv(REMOTE_DISPATCH_SESSION_ID_ENV, "stale-parent-session") monkeypatch.setenv(REMOTE_AUTHORITY_URL_ENV, "https://stale.invalid/permit") monkeypatch.setenv(REMOTE_AUTHORITY_TOKEN_ENV, "stale-parent-token") job = parse_job( @@ -188,46 +224,60 @@ def runner(argv, run_dir: Path, child_env) -> RunOutcome: observed["envelope"] = json.loads(envelope_path.read_text()) observed["authority_url"] = child_env[REMOTE_AUTHORITY_URL_ENV] observed["authority_token"] = child_env[REMOTE_AUTHORITY_TOKEN_ENV] + observed["session_id"] = child_env[REMOTE_DISPATCH_SESSION_ID_ENV] observed["parent_token"] = os.environ.get(REMOTE_AUTHORITY_TOKEN_ENV) (run_dir / "report.json").write_text(json.dumps(SUCCESS_REPORT)) return RunOutcome(returncode=0, report=SUCCESS_REPORT) - result = execute_job(job, ConnectorSettings(), storage, runner=runner) + result = execute_job(job, _settings(), storage, runner=runner) assert result.status == "success" assert observed["mode"] == 0o600 - assert observed["envelope"] == managed_dispatch + assert observed["envelope"] == _wire(managed_dispatch) assert observed["authority_url"] == authority_url assert observed["authority_token"] == token + assert observed["session_id"] == job.managed_dispatch_session_id assert observed["parent_token"] == "stale-parent-token" assert token not in json.dumps(observed["argv"]) assert token not in json.dumps(observed["envelope"]) -def test_connector_drops_inherited_authority_from_a_job_without_an_envelope( - monkeypatch, -): +@pytest.mark.parametrize("require_run_token", [True, False]) +def test_legacy_payload_cannot_inherit_live_authority(monkeypatch, require_run_token): monkeypatch.setenv(REMOTE_AUTHORITY_URL_ENV, "https://stale.invalid/permit") monkeypatch.setenv(REMOTE_AUTHORITY_TOKEN_ENV, "stale-parent-token") - job = parse_job(_payload(), lease_job_id="bjob_1") + monkeypatch.setenv(REMOTE_DISPATCH_SESSION_ID_ENV, "stale-parent-session") + job = parse_job( + _payload( + managed_dispatch=None, + managed_delivery_authority_url=None, + managed_dispatch_session_id=None, + ), + lease_job_id="bjob_1", + ) storage = InMemoryCustomerStorage(bundle_bytes=_BUNDLE_BYTES) + calls = [] - def runner(argv, run_dir: Path, child_env) -> RunOutcome: - assert REMOTE_AUTHORITY_URL_ENV not in child_env - assert REMOTE_AUTHORITY_TOKEN_ENV not in child_env - assert "--managed-dispatch-file" not in argv - (run_dir / "report.json").write_text(json.dumps(SUCCESS_REPORT)) - return RunOutcome(returncode=0, report=SUCCESS_REPORT) + def fetch(*_): + calls.append("fetch") + raise AssertionError("legacy payload must not fetch live bytes") - assert ( - execute_job(job, ConnectorSettings(), storage, runner=runner).status - == "success" + monkeypatch.setattr(storage, "fetch_bundle_archive", fetch) + result = execute_job( + job, + _settings(), + storage, + runner=lambda *_: calls.append("run"), + require_run_token=require_run_token, ) + assert result.status == "failed" + assert result.error_code == "governance_refused" + assert calls == [] def test_execute_job_refuses_child_report_for_different_substrate(): job = parse_job(_payload(), lease_job_id="bjob_1") - settings = ConnectorSettings(profile=None) + settings = _settings(profile=None) storage = InMemoryCustomerStorage(bundle_bytes=_BUNDLE_BYTES) mismatched = {**SUCCESS_REPORT, "execution_target_kind": "citrix"} @@ -369,7 +419,7 @@ def test_halt_maps_to_halt_status_and_present_flag(): "halt": {"outcome": "halt", "reason": "identity ambiguous for patient row"}, } job = parse_job(_payload(), lease_job_id="bjob_1") - settings = ConnectorSettings() + settings = _settings() storage = InMemoryCustomerStorage(bundle_bytes=_BUNDLE_BYTES) def runner(argv, run_dir: Path, _env) -> RunOutcome: @@ -435,9 +485,7 @@ def test_report_write_failure_does_not_report_completed_run_as_runner_failure( job = parse_job(_payload(), lease_job_id="bjob_1") storage = _FailingReportStorage(bundle_bytes=_BUNDLE_BYTES) - result = execute_job( - job, ConnectorSettings(), storage, runner=_fake_success_runner(report) - ) + result = execute_job(job, _settings(), storage, runner=_fake_success_runner(report)) body = phi_free_callback_body(job, result) assert body["status"] == "halt" @@ -458,19 +506,77 @@ def test_report_write_failure_keeps_child_failure_as_failed(): def runner(argv, run_dir: Path, _env) -> RunOutcome: return RunOutcome(returncode=1, report=failed_report) - result = execute_job(job, ConnectorSettings(), storage, runner=runner) + result = execute_job(job, _settings(), storage, runner=runner) body = phi_free_callback_body(job, result) assert body["status"] == "failed" assert body["report_path"] is None +@pytest.mark.parametrize("phase", ["before_child", "verified", "failed_after_write"]) +def test_egress_refusal_reports_whether_the_child_could_have_written(tmp_path, phase): + cp = StubControlPlane() + payload = _payload() + # An unsafe report reference makes the guard refuse both failure cases. + # For the verified case the refused value occurs only in the outcome. + if phase != "verified": + payload["storage"]["report_ref"] = "synthetic private report" + if phase == "before_child": + payload["safety"] = {} + cp.enqueue("org_demo", payload) + client = ConnectorClient( + "https://app.test", transport=httpx.MockTransport(cp.handler) + ) + client.enroll(enrollment_secret="s", org_id="org_demo", name="n") + client.add_secret_values(["effect_tier_1"]) + record = tmp_path / "synthetic-record.txt" + + def runner(argv, run_dir, env): + with record.open("a") as stream: + stream.write("saved\n") + report = ( + VERIFIED_REPORT + if phase == "verified" + else {**SUCCESS_REPORT, "success": False} + ) + return RunOutcome(0 if phase == "verified" else 1, report) + + result = run_once( + client, + _settings(), + runner=runner, + storage_factory=lambda job: InMemoryCustomerStorage(bundle_bytes=_BUNDLE_BYTES), + ) + + assert result["error_code"] == "egress_refused" + assert result["callback_accepted"] + assert len(cp.callbacks) == len(cp.acks) == 1 + callback = cp.callbacks[0]["body"] + assert callback["report_path"] is None and callback["metrics"] == {} + assert "outcome" not in callback and "failure_signal" not in callback + assert cp.acks[0]["error_code"] == "egress_refused" + if phase == "before_child": + assert not record.exists() + assert ( + result["status"] == callback["status"] == cp.acks[0]["status"] == "failed" + ) + assert callback["error_code"] == "runner_failure" + assert "bundle_sha256" not in callback and "halt" not in callback + else: + assert record.read_text().splitlines() == ["saved"] + assert result["status"] == callback["status"] == "halt" + assert callback["halt"] == {"present": True} + assert callback["bundle_sha256"] == _BUNDLE_SHA256 + assert callback["error_code"] == "egress_refused" + assert cp.acks[0]["status"] == "done" + + def test_report_write_failure_lease_is_not_acked_failed(): cp = StubControlPlane() cp.enqueue("org_demo", _payload()) transport = httpx.MockTransport(cp.handler) client = ConnectorClient("https://app.test", token=None, transport=transport) client.enroll(enrollment_secret="s", org_id="org_demo", name="n") - settings = ConnectorSettings( + settings = _settings( control_plane_url="https://app.test", org_id="org_demo", token=client.token, @@ -589,7 +695,7 @@ def test_execute_refuses_managed_authority_on_a_different_https_origin(): ) result = execute_job( job, - ConnectorSettings(control_plane_url="https://app.openadapt.ai"), + _settings(control_plane_url="https://app.openadapt.ai"), InMemoryCustomerStorage(bundle_bytes=_BUNDLE_BYTES), runner=_fake_success_runner(SUCCESS_REPORT), ) @@ -601,12 +707,11 @@ def test_execute_refuses_managed_authority_on_a_different_https_origin(): "overrides, match", [ ( - {"managed_dispatch": _managed_dispatch()}, + {"managed_delivery_authority_url": None}, "must be supplied together", ), ( { - "managed_dispatch": _managed_dispatch(), "managed_delivery_authority_url": "http://localhost/permit", }, "credential-free HTTPS endpoint", @@ -646,7 +751,7 @@ def test_execute_refuses_when_required_grounding_key_is_absent(monkeypatch): ), lease_job_id="bjob_1", ) - settings = ConnectorSettings() + settings = _settings() storage = InMemoryCustomerStorage(bundle_bytes=_BUNDLE_BYTES) # A runner that would "succeed" — the governance gate must refuse BEFORE it. @@ -671,7 +776,7 @@ def runner(argv, run_dir: Path, _env) -> RunOutcome: called["ran"] = True return RunOutcome(returncode=0, report=SUCCESS_REPORT) - result = execute_job(job, ConnectorSettings(), storage, runner=runner) + result = execute_job(job, _settings(), storage, runner=runner) assert result.status == "failed" assert "storage bundle fetch failed" in (result.error or "") assert called["ran"] is False @@ -679,15 +784,26 @@ def runner(argv, run_dir: Path, _env) -> RunOutcome: assert "bundle_sha256" not in phi_free_callback_body(job, result) -def test_child_failure_after_archive_verification_carries_verified_digest(): +@pytest.mark.parametrize("spawned", [False, True]) +def test_child_exception_keeps_verified_binding_and_stage(tmp_path, spawned): + from openadapt_flow.connector.executor import _subprocess_runner + job = parse_job(_payload(), lease_job_id="bjob_1") storage = InMemoryCustomerStorage(bundle_bytes=_BUNDLE_BYTES) - - def runner(argv, run_dir: Path, _env) -> RunOutcome: - raise RuntimeError("child unavailable") - - result = execute_job(job, ConnectorSettings(), storage, runner=runner) - assert result.status == "failed" + record = tmp_path / "synthetic-record" + + def runner(argv, run_dir: Path, env) -> RunOutcome: + if not spawned: + return _subprocess_runner([str(tmp_path / "missing-program")], run_dir, env) + record.write_text("saved") + raise RuntimeError("synthetic result unavailable") + + result = execute_job(job, _settings(), storage, runner=runner) + assert result.status == ("halt" if spawned else "failed") + assert result.error_code == ( + "child_outcome_unknown" if spawned else "child_invocation_failed" + ) + assert record.exists() == spawned assert result.verified_bundle_sha256 == _BUNDLE_SHA256 callback = phi_free_callback_body(job, result) assert callback["bundle_sha256"] == _BUNDLE_SHA256 @@ -721,7 +837,7 @@ def test_local_storage_refuses_report_ref_outside_root(tmp_path): def test_governed_run_argv_uses_the_fail_closed_run_verb(): job = parse_job(_payload(), lease_job_id="bjob_1") - settings = ConnectorSettings( + settings = _settings( profile="/opt/openadapt/deployment.yaml", policy="clinical-write" ) argv = build_run_argv(job, settings, Path("/b"), Path("/r"), Path("/r/params.json")) @@ -732,8 +848,9 @@ def test_governed_run_argv_uses_the_fail_closed_run_verb(): assert "--params-file" in argv assert argv[argv.index("--backend") + 1] == "web" assert "replay" not in argv - # Cloud-dispatched items have no per-item pause, and the run says so. - assert argv[argv.index("--approval-mode") + 1] == "not_gated" + # A dispatch transport cannot turn off the governed run's approval gate. + assert "--approval-mode" not in argv + assert "not_gated" not in argv def test_native_dispatch_routes_exact_first_class_target_kind(): @@ -746,7 +863,7 @@ def test_native_dispatch_routes_exact_first_class_target_kind(): ), lease_job_id="bjob_1", ) - argv = build_run_argv(job, ConnectorSettings(), Path("/b"), Path("/r"), None) + argv = build_run_argv(job, _settings(), Path("/b"), Path("/r"), None) assert argv[argv.index("--backend") + 1] == "citrix" assert "--url" not in argv @@ -836,8 +953,13 @@ def test_enroll_persists_token_0600(tmp_path, monkeypatch): ) assert data["token"].startswith("oaconn_") - settings = ConnectorSettings( - control_plane_url="https://app.test", token=data["token"], org_id="org_demo" + monkeypatch.delenv("BYOC_QUALIFICATION_AUTHORITY_FILE", raising=False) + authority_file = str(tmp_path / "operator-authority.json") + settings = _settings( + control_plane_url="https://app.test", + token=data["token"], + org_id="org_demo", + qualification_authority_file=authority_file, ) path = save_enrollment(settings) assert path.exists() @@ -846,6 +968,38 @@ def test_enroll_persists_token_0600(tmp_path, monkeypatch): reloaded = load_settings() assert reloaded.token == data["token"] assert reloaded.org_id == "org_demo" + assert reloaded.qualification_authority_file == authority_file + monkeypatch.setenv("BYOC_QUALIFICATION_AUTHORITY_FILE", "operator-env.json") + assert load_settings().qualification_authority_file == "operator-env.json" + assert ( + load_settings( + {"qualification_authority_file": "operator-flag.json"} + ).qualification_authority_file + == "operator-flag.json" + ) + + +@pytest.mark.parametrize("verb", ["enroll", "run", "rotate-token"]) +def test_connector_cli_retains_callbacks_and_refuses_unenrolled_run( + verb, tmp_path, monkeypatch +): + from openadapt_flow.__main__ import _cmd_connector, _connector_flags, build_parser + + monkeypatch.setenv("OPENADAPT_HOME", str(tmp_path)) + monkeypatch.delenv("BYOC_CONNECTOR_TOKEN", raising=False) + options = ["connector", verb, "--control-plane-url", "https://app.test"] + if verb == "run": + options += ["--secrets-dir", str(tmp_path / "secrets"), "--max-workers", "2"] + args = build_parser().parse_args(options) + assert args.func is _cmd_connector + flags = _connector_flags(args) + assert flags["control_plane_url"] == "https://app.test" + if verb == "run": + assert flags["max_workers"] == 2 + assert flags["secrets_dir"] == str(tmp_path / "secrets") + if verb != "enroll": + # The actual moved handler must refuse before opening a connection. + assert args.func(args) == 2 def test_full_loop_dispatch_execute_callback_ack(): @@ -855,7 +1009,7 @@ def test_full_loop_dispatch_execute_callback_ack(): client = ConnectorClient("https://app.test", token=None, transport=transport) client.enroll(enrollment_secret="s", org_id="org_demo", name="n") - settings = ConnectorSettings( + settings = _settings( control_plane_url="https://app.test", org_id="org_demo", token=client.token, @@ -870,7 +1024,11 @@ def test_full_loop_dispatch_execute_callback_ack(): ) assert result["status"] == "success" assert cp.poll_bodies == [ - {"wait": 0, "capabilities": [MANAGED_QUALIFICATION_AUTHORITY_CAPABILITY]} + { + "wait": 0, + "capabilities": [MANAGED_QUALIFICATION_AUTHORITY_CAPABILITY], + "active_job_ids": [], + } ] # A PHI-free callback carrying the run-scoped token was posted. @@ -894,7 +1052,7 @@ def test_callback_rejection_is_retried_but_never_acked(callback_status, monkeypa transport = httpx.MockTransport(cp.handler) client = ConnectorClient("https://app.test", transport=transport) client.enroll(enrollment_secret="s", org_id="org_demo", name="n") - settings = ConnectorSettings( + settings = _settings( control_plane_url="https://app.test", org_id="org_demo", token=client.token, @@ -912,6 +1070,7 @@ def test_callback_rejection_is_retried_but_never_acked(callback_status, monkeypa "job_id": "bjob_1", "run_id": _payload()["run_id"], "status": "success", + "error_code": None, "callback_accepted": False, } assert cp.callback_attempts == 3 @@ -928,7 +1087,7 @@ def test_cross_org_isolation_connector_never_sees_another_orgs_job(): # A connector enrolled for org_A. client = ConnectorClient("https://app.test", transport=transport) client.enroll(enrollment_secret="s", org_id="org_A", name="a") - settings = ConnectorSettings( + settings = _settings( control_plane_url="https://app.test", org_id="org_A", token=client.token, @@ -944,3 +1103,17 @@ def test_cross_org_isolation_connector_never_sees_another_orgs_job(): assert result is None # org_A connector sees no work; org_B's job stays queued assert cp.jobs[0]["status"] == "queued" assert cp.callbacks == [] + + +@pytest.mark.parametrize( + "target", ["web", "windows", "macos", "linux", "rdp", "citrix"] +) +def test_every_connector_substrate_preserves_the_governed_approval_default(target): + from openadapt_flow.approval_mode.model import ApprovalMode, resolve_approval_mode + + job = parse_job( + _payload(target_kind=target, target_url=None, allowed_hosts=[], params={}) + ) + argv = build_run_argv(job, _settings(), Path("/bundle"), Path("/run"), None) + assert "--approval-mode" not in argv + assert resolve_approval_mode(None) == ApprovalMode.EACH_ITEM diff --git a/packages/flow/tests/test_connector_client_error_privacy.py b/packages/flow/tests/test_connector_client_error_privacy.py index add46aedb1..3c4dfdb6a5 100644 --- a/packages/flow/tests/test_connector_client_error_privacy.py +++ b/packages/flow/tests/test_connector_client_error_privacy.py @@ -10,6 +10,16 @@ from openadapt_flow.connector.config import ConnectorSettings +def _callback(status): + # The smallest body the closed callback allow-list accepts. + return { + "run_id": "own-run", + "org_id": "own-org", + "workflow_id": "own-wf", + "status": status, + } + + class BodyMustNotBeRendered(httpx.Response): @property def text(self): @@ -58,7 +68,7 @@ def response(_request): client.ack("own-job", "failed") else: client.run_callback( - {"status": "failed"}, run_token=secret + _callback("failed"), run_token=secret ) message = str(failure.exception) self.assertEqual(message, f"{label}: HTTP {status}") @@ -96,7 +106,9 @@ def response(request): self.assertIsNone(client.poll(1)) self.assertEqual(client.poll(1), {"id": "own-job"}) self.assertEqual(client.ack("own-job", "done"), {"already_released": True}) - self.assertIsNone(client.run_callback({"status": "done"}, run_token=secret)) + self.assertIsNone( + client.run_callback(_callback("success"), run_token=secret) + ) self.assertEqual( requests, [ diff --git a/packages/flow/tests/test_connector_pilot.py b/packages/flow/tests/test_connector_pilot.py new file mode 100644 index 0000000000..903688fb6e --- /dev/null +++ b/packages/flow/tests/test_connector_pilot.py @@ -0,0 +1,1170 @@ +"""Pilot hardening of the BYOC connector: the egress allow-list, request +signing, the kill switch, cancellation, concurrency, token rotation, the local +secret store, and admitted wrap programs with an independent read-back. + +The central test plants canary values everywhere a record value or secret +could hide (report text, halt reason, exception text, run parameters, the local +secret file) and asserts none of them appears in any byte the connector sent. +""" + +from __future__ import annotations + +import copy +import hashlib +import hmac +import io +import json +import os +import signal +import sys +import threading +import time +import zipfile +from pathlib import Path + +import httpx +import pytest + +from openadapt_flow.connector import egress +from openadapt_flow.connector import executor as executor_mod +from openadapt_flow.connector.client import ( + ConnectorClient, + ConnectorControl, + RunsStopped, + sign_request, +) +from openadapt_flow.connector.config import ( + ConnectorSettings, + load_settings, + save_enrollment, +) +from openadapt_flow.connector.daemon import ( + apply_control, + maybe_rotate, + run_loop, +) +from openadapt_flow.connector.executor import ( + RunOutcome, + _subprocess_runner, + cancel_job, + execute_job, + wrap_readback_evidence, +) +from openadapt_flow.connector.protocol import parse_job +from openadapt_flow.connector.secrets import LocalSecretStore, SecretStoreError +from openadapt_flow.connector.storage import InMemoryCustomerStorage +from tests.connector_v3_fixtures import build_program_case + +CANARY_RECORD = "ZQX-CANARY-RECORD-7731" +CANARY_LOCAL_ENV_MARKER = "ZQX-CANARY-LOCAL-MARKER-9941" +CANARY_PARAM = "ZQX-CANARY-PARAM-ALICE" +TOKEN = "oaconn_" + "d" * 64 + + +def _zip(entries: dict[str, bytes]) -> bytes: + stream = io.BytesIO() + with zipfile.ZipFile(stream, "w") as archive: + for name, data in entries.items(): + archive.writestr(zipfile.ZipInfo(name, (2026, 1, 1, 0, 0, 0)), data) + return stream.getvalue() + + +_CASE = None +PLAIN_BUNDLE = b"" + + +@pytest.fixture(scope="module", autouse=True) +def _signed_transport_program(module_durable_authority, tmp_path_factory): + global _CASE, PLAIN_BUNDLE, WRAP_BUNDLE, ADMISSION, ADMITTER_KEY, VERIFY_YAML + _CASE = build_program_case(tmp_path_factory.mktemp("connector-pilot-program")) + PLAIN_BUNDLE = WRAP_BUNDLE = _CASE["bundle_bytes"] + ADMISSION = (_CASE["bundle_dir"] / "admission.json").read_bytes() + ADMITTER_KEY = _CASE["public_key_hex"] + VERIFY_YAML = (_CASE["bundle_dir"] / "readback/verify.yaml").read_bytes() + + +@pytest.fixture(autouse=True) +def _transport_has_no_external_readback(monkeypatch): + # Keep wire/secret/lease tests offline. Dedicated v3 tests retain the + # actual authority/crypto/Flow-parser controls; these tests fake the child. + monkeypatch.setattr(executor_mod, "_run_flow_tool", lambda *_: 1) + + +def _configured_settings(**overrides): + return ConnectorSettings( + **{ + "control_plane_url": "https://cloud.test", + "org_id": "org_pilot", + "trusted_admission_keys": _CASE["public_key_hex"], + "admission_key_dir": str(_CASE["key_dir"]), + **overrides, + } + ) + + +def _payload(bundle: bytes | None = None, **overrides): + bundle = PLAIN_BUNDLE if bundle is None else bundle + payload = { + "mode": "replay", + "run_id": "00000000-0000-4000-8000-000000000009", + "org_id": "org_pilot", + "workflow_id": "wf_pilot", + "target_kind": "web", + "storage": { + "backend": "local", + "bundle_ref": "bundles/wf_pilot/bundle.zip", + "report_ref": "org_pilot/run_9/report.json", + }, + "target_url": "https://notes.byoc-pilot.example.org/", + "allowed_hosts": ["notes.byoc-pilot.example.org"], + "params": {"note": CANARY_PARAM, "target_kind": "web"}, + "secrets_ref": None, + "run_token": "a" * 64, + "bundle_version_id": "bv_9", + "runtime_validation_id": "rv_9", + "bundle_sha256": hashlib.sha256(bundle).hexdigest(), + "safety": {"halt.on_ambiguous": True}, + "grounding_model": {"enabled": False}, + } + payload.update( + managed_dispatch=_wrap_dispatch(payload["run_id"], _CASE["admission_sha256"]), + managed_delivery_authority_url="https://cloud.test/api/internal/managed-delivery-permit", + managed_dispatch_session_id=_CASE["payload"]["managed_dispatch_session_id"], + ) + payload.update(overrides) + return payload + + +class RecordingPlane: + """A stub control plane that records every raw request byte.""" + + def __init__(self, control=None, poll_status=None): + self.raw: list[bytes] = [] + self.requests: list[httpx.Request] = [] + self.jobs: list[dict] = [] + self.control = control or { + "max_concurrent_leases": 1, + "runs_stopped": False, + "cancel_job_ids": [], + "rotate_recommended": False, + "token_expires_at": None, + } + self.poll_status = poll_status + self.lock = threading.Lock() + + def handler(self, request: httpx.Request) -> httpx.Response: + with self.lock: + self.requests.append(request) + self.raw.append( + request.method.encode() + + b" " + + str(request.url).encode() + + b"\n" + + b"\n".join(f"{k}: {v}".encode() for k, v in request.headers.items()) + + b"\n\n" + + (request.content or b"") + ) + path = request.url.path + if path == "/api/connector/poll": + if self.poll_status == 423: + return httpx.Response( + 423, + json={ + "error": "org_runs_stopped", + "connector": {**self.control, "runs_stopped": True}, + }, + ) + with self.lock: + for job in self.jobs: + if job["status"] == "queued": + job["status"] = "leased" + return httpx.Response( + 200, + json={ + "job": {"id": job["id"], "payload": job["payload"]}, + "connector": self.control, + }, + ) + return httpx.Response( + 204, headers={"x-oa-connector-control": json.dumps(self.control)} + ) + if path == "/api/connector/heartbeat": + return httpx.Response(200, json={"connector": self.control}) + if path == "/api/connector/rotate": + return httpx.Response( + 200, + json={ + "token": "oaconn_" + "e" * 64, + "token_expires_at": None, + "previous_token_valid_until": None, + }, + ) + return httpx.Response(200, json={"ok": True}) + + def all_bytes(self) -> bytes: + return b"\n".join(self.raw) + + +def _client(plane: RecordingPlane, **kwargs) -> ConnectorClient: + return ConnectorClient( + "https://cloud.test", + token=TOKEN, + transport=httpx.MockTransport(plane.handler), + **kwargs, + ) + + +# -------------------------------------------------------------------------- +# The metadata-only boundary, end to end. +# -------------------------------------------------------------------------- +def _leaky_report() -> dict: + """A report that holds record values and a secret in every free-text slot.""" + return { + "execution_target_kind": "web", + "success": False, + "terminal_outcome": "halt", + "halt": {"reason": f"field showed {CANARY_RECORD}", "typed": CANARY_PARAM}, + "results": [ + {"step_id": "s1", "ok": True, "intent": f"type {CANARY_PARAM}"}, + { + "step_id": "s2", + "ok": False, + "error": f"saw {CANARY_RECORD} and {CANARY_LOCAL_ENV_MARKER}", + }, + ], + "ocr": CANARY_RECORD, + "model_calls": 0, + } + + +@pytest.mark.parametrize("outcome_kind", ["halt_report", "child_crash"]) +def test_no_canary_leaves_the_machine(tmp_path, outcome_kind): + secrets_dir = tmp_path / "secrets" + secrets_dir.mkdir() + secret_file = secrets_dir / "notes-reader.env" + secret_file.write_text(f"NOTES_PASSWORD={CANARY_LOCAL_ENV_MARKER}\n") + os.chmod(secret_file, 0o600) + plane = RecordingPlane() + plane.jobs.append( + { + "id": "bjob_9", + "status": "queued", + "payload": _payload(secrets_ref="notes-reader"), + } + ) + client = _client(plane, egress_audit_log=str(tmp_path / "egress.jsonl")) + settings = _configured_settings( + control_plane_url="https://cloud.test", + token=TOKEN, + poll_wait_s=0, + secrets_dir=str(secrets_dir), + ) + seen_env: dict[str, str] = {} + + def runner(argv, run_dir: Path, child_env) -> RunOutcome: + seen_env.update(child_env) + if outcome_kind == "child_crash": + raise RuntimeError( + f"crashed holding {CANARY_RECORD} {CANARY_LOCAL_ENV_MARKER}" + ) + report = _leaky_report() + (run_dir / "report.json").write_text(json.dumps(report)) + return RunOutcome(returncode=1, report=report) + + storage = InMemoryCustomerStorage(bundle_bytes=PLAIN_BUNDLE) + rc = run_loop( + client, + settings, + runner=runner, + storage_factory=lambda job: storage, + once=True, + log=lambda _m: None, + ) + assert rc == 0 + # The secret reached only the governed child. + assert seen_env.get("NOTES_PASSWORD") == CANARY_LOCAL_ENV_MARKER + # The run reported and acked. + paths = [r.url.path for r in plane.requests] + assert "/api/internal/run-callback" in paths and "/api/connector/ack" in paths + sent = plane.all_bytes() + (tmp_path / "egress.jsonl").read_bytes() + for canary in (CANARY_RECORD, CANARY_LOCAL_ENV_MARKER, CANARY_PARAM): + assert canary.encode() not in sent, canary + # The PHI-bearing report stayed in customer storage. + if outcome_kind == "halt_report": + assert CANARY_RECORD in json.dumps(storage.written) + # Only the stored report's digest left, so Cloud can bind it. + from openadapt_flow.connector.storage import report_bytes + + callback = next( + json.loads(r.content) + for r in plane.requests + if r.url.path == "/api/internal/run-callback" + ) + (stored,) = storage.written.values() + assert ( + callback["metrics"]["report_sha256"] + == hashlib.sha256(report_bytes(stored)).hexdigest() + ) + + +def test_guard_callback_refuses_everything_off_the_list(): + base = { + "run_id": "r1", + "org_id": "o1", + "workflow_id": "w1", + "mode": "replay", + "status": "failed", + "report_path": "o1/r1/report.json", + "metrics": {"steps": 1}, + "error_code": "runner_failure", + } + assert egress.guard_callback(base)["status"] == "failed" + bad = [ + {**base, "error": "free text"}, + {**base, "error_code": "Saw Alice Smith"}, + {**base, "metrics": {"steps": "Alice"}}, + {**base, "metrics": {"patient_name": 1}}, + {**base, "halt": {"present": True, "reason": "x"}}, + {**base, "report_path": "/etc/passwd"}, + {**base, "report_path": "a/../b"}, + {**base, "status": "VERIFIED by Alice"}, + {**base, "outcome": {"outcome": "VERIFIED", "note": "Alice"}}, + {**base, "metrics": {"wrap_readback": {"readback_sha256": "x"}}}, + {**base, "metrics": {"report_sha256": f"report of {CANARY_RECORD}"}}, + {**base, "metrics": {"report_sha256": "A" * 64}}, + ] + for body in bad: + with pytest.raises(egress.EgressViolation): + egress.guard_callback(body) + + +def test_ack_and_poll_guards(): + assert ( + egress.guard_ack("bjob_1", "failed", "governance_refused")["error_code"] + == "governance_refused" + ) + for code in ("Bad Code", "x" * 80, "has space"): + with pytest.raises(egress.EgressViolation): + egress.guard_ack("bjob_1", "failed", code) + with pytest.raises(egress.EgressViolation): + egress.guard_ack("bjob 1", "done") + with pytest.raises(egress.EgressViolation): + egress.guard_poll(10, ["Not A Token"]) + with pytest.raises(egress.EgressViolation): + egress.guard_poll(10, [], ["id"] * (egress.MAX_ACTIVE_JOBS + 1)) + + +def test_serialize_refuses_any_encoding_of_a_secret(): + with pytest.raises(egress.EgressViolation): + egress.serialize_checked( + {"run_id": CANARY_LOCAL_ENV_MARKER}, [CANARY_LOCAL_ENV_MARKER] + ) + import base64 + + encoded = base64.b64encode(CANARY_LOCAL_ENV_MARKER.encode()).decode() + with pytest.raises(egress.EgressViolation): + egress.serialize_checked({"x": encoded}, [CANARY_LOCAL_ENV_MARKER]) + assert egress.serialize_checked({"run_id": "r1"}, [CANARY_LOCAL_ENV_MARKER]) + + +# -------------------------------------------------------------------------- +# Request signing and replay protection. +# -------------------------------------------------------------------------- +def test_requests_are_signed_with_fresh_nonces(): + plane = RecordingPlane() + client = _client(plane) + client.poll(0) + client.poll(0) + nonces = set() + for request in plane.requests: + ts = request.headers["x-oa-connector-ts"] + nonce = request.headers["x-oa-connector-nonce"] + assert len(nonce) == 32 and abs(int(ts) - time.time()) < 5 + expected = sign_request( + TOKEN, "POST", request.url.path, request.content, ts=int(ts), nonce=nonce + ) + assert hmac.compare_digest( + expected, request.headers["x-oa-connector-signature"] + ) + nonces.add(nonce) + assert len(nonces) == 2 + # The callback uses the run token, not the connector token. + tampered = sign_request( + TOKEN, "POST", "/api/connector/poll", b"{}", ts=1, nonce="0" * 32 + ) + assert tampered != sign_request( + TOKEN, "POST", "/api/connector/ack", b"{}", ts=1, nonce="0" * 32 + ) + + +def test_signature_key_is_the_stored_token_hash(): + key = hashlib.sha256(TOKEN.encode()).hexdigest().encode() + msg = "\n".join( + ["v1", "100", "a" * 32, "POST", "/p", hashlib.sha256(b"").hexdigest()] + ).encode() + assert ( + sign_request(TOKEN, "post", "/p", b"", ts=100, nonce="a" * 32) + == hmac.new(key, msg, hashlib.sha256).hexdigest() + ) + + +# -------------------------------------------------------------------------- +# Kill switch, cancellation, concurrency, rotation. +# -------------------------------------------------------------------------- +def test_poll_423_raises_runs_stopped_and_cancels_everything(monkeypatch): + plane = RecordingPlane(poll_status=423) + client = _client(plane) + with pytest.raises(RunsStopped): + client.poll(0) + assert client.control.runs_stopped + cancelled: list[str] = [] + monkeypatch.setattr( + "openadapt_flow.connector.daemon.cancel_job", + lambda j: cancelled.append(j) or True, + ) + apply_control(client.control, ["bjob_1", "bjob_2"], lambda _m: None) + assert sorted(cancelled) == ["bjob_1", "bjob_2"] + + +def test_cancel_ids_stop_only_listed_jobs(monkeypatch): + cancelled: list[str] = [] + monkeypatch.setattr( + "openadapt_flow.connector.daemon.cancel_job", + lambda j: cancelled.append(j) or True, + ) + apply_control( + ConnectorControl(cancel_job_ids=frozenset({"bjob_2"})), + ["bjob_1", "bjob_2"], + lambda _m: None, + ) + assert cancelled == ["bjob_2"] + + +def test_cancel_job_terminates_the_governed_child(tmp_path): + started = threading.Event() + outcome: dict = {} + + def run(): + executor_mod._CURRENT.job_id = "bjob_kill" + started.set() + outcome["r"] = _subprocess_runner( + [sys.executable, "-c", "import time; time.sleep(60)"], + tmp_path, + dict(os.environ), + ) + + thread = threading.Thread(target=run) + began = time.monotonic() + thread.start() + started.wait(5) + for _ in range(50): + with executor_mod._CHILDREN.lock: + if "bjob_kill" in executor_mod._CHILDREN.procs: + break + time.sleep(0.05) + assert cancel_job("bjob_kill") is True + thread.join(15) + assert not thread.is_alive() and time.monotonic() - began < 15 + assert outcome["r"].returncode != 0 + + +def test_cancelled_job_reports_failed_with_closed_code(tmp_path): + job = parse_job(_payload(), lease_job_id="bjob_c") + cancel_job("bjob_c") + + def runner(argv, run_dir, env): # pragma: no cover - must not run + raise AssertionError("child started after cancel") + + result = execute_job( + job, + _configured_settings(), + InMemoryCustomerStorage(PLAIN_BUNDLE), + runner=runner, + ) + assert ( + result.status == "failed" and result.error_code == "cancelled_by_control_plane" + ) + + +def test_cancel_that_kills_a_started_child_is_uncertain_not_failed(tmp_path): + """A cancel after the child started may follow a landed write.""" + job = parse_job(_payload(), lease_job_id="bjob_mid") + + def runner(argv, run_dir, env): + cancel_job("bjob_mid") # arrives while the child runs; it is killed + return RunOutcome(returncode=-15, report={}) + + result = execute_job( + job, + _configured_settings(), + InMemoryCustomerStorage(PLAIN_BUNDLE), + runner=runner, + ) + assert result.status == "halt" + assert result.error_code == "child_outcome_unknown" + assert result.halt == {"present": True} and result.outcome is None + + +def test_cancel_after_the_child_reported_keeps_its_real_outcome(tmp_path): + job = parse_job(_payload(), lease_job_id="bjob_late") + + def runner(argv, run_dir, env): + cancel_job("bjob_late") # too late: the child already finished + report = { + "execution_target_kind": "web", + "success": True, + "execution_outcome": "VERIFIED", + "results": [{"ok": True}], + } + return RunOutcome(returncode=0, report=report) + + result = execute_job( + job, + _configured_settings(), + InMemoryCustomerStorage(PLAIN_BUNDLE), + runner=runner, + ) + assert result.status == "success" and result.error_code is None + + +@pytest.mark.parametrize( + "report", + [ + {"success": True, "execution_outcome": "VERIFIED", "results": [{"ok": True}]}, + {"success": True, "results": [{"ok": True}]}, + ], + ids=["verified", "legacy"], +) +def test_cancel_that_kills_a_child_after_it_reported_success_is_uncertain( + tmp_path, report +): + """Killed after writing success (a seal still running): the write landed.""" + lease = f"bjob_post_{len(report)}" + job = parse_job(_payload(), lease_job_id=lease) + + def runner(argv, run_dir, env): + cancel_job(lease) + return RunOutcome( + returncode=-15, report={"execution_target_kind": "web", **report} + ) + + result = execute_job( + job, + _configured_settings(), + InMemoryCustomerStorage(PLAIN_BUNDLE), + runner=runner, + ) + assert result.status == "halt" + assert result.error_code == "child_outcome_unknown" + assert result.halt == {"present": True} and result.outcome is None + + +@pytest.mark.parametrize( + "returncode,report,status,error_code", + [ + # No cancel: a stop, an OOM kill or a crash after the child started. + (-2, {}, "halt", "child_outcome_unknown"), + ( + -9, + {"execution_outcome": "VERIFIED", "success": True}, + "halt", + "child_outcome_unknown", + ), + (1, {"success": True}, "halt", "child_outcome_unknown"), + (-15, {"terminal_outcome": "success"}, "halt", "child_outcome_unknown"), + # A report that records a refusal or a halt keeps its own outcome. + ( + 1, + {"execution_outcome": "FAILED", "success": False}, + "failed", + "governed_run_failed", + ), + (1, {"execution_outcome": "HALTED", "success": False}, "halt", None), + ], + ids=["no-report", "verified", "legacy", "terminal-success", "refused", "halted"], +) +def test_a_nonzero_exit_after_start_is_judged_without_a_cancel( + tmp_path, returncode, report, status, error_code +): + job = parse_job(_payload(), lease_job_id=f"bjob_exit_{returncode}_{len(report)}") + + def runner(argv, run_dir, env): + body = {"execution_target_kind": "web", **report} if report else {} + return RunOutcome(returncode=returncode, report=body) + + result = execute_job( + job, + _configured_settings(), + InMemoryCustomerStorage(PLAIN_BUNDLE), + runner=runner, + ) + assert result.status == status + assert result.error_code == error_code + if error_code == "child_outcome_unknown": + assert result.halt == {"present": True} and result.outcome is None + + +def test_a_clean_exit_with_no_readable_report_is_uncertain_not_failed(tmp_path): + """Exit 0 but no report the connector can read (a sealed run's report it + could not decrypt, or none written): a write may have landed.""" + job = parse_job(_payload(), lease_job_id="bjob_exit0_noreport") + + def runner(argv, run_dir, env): + return RunOutcome(returncode=0, report={}) + + result = execute_job( + job, + _configured_settings(), + InMemoryCustomerStorage(PLAIN_BUNDLE), + runner=runner, + ) + assert result.status == "halt" + assert result.error_code == "child_outcome_unknown" + assert result.halt == {"present": True} and result.outcome is None + + +def test_the_report_is_read_through_the_sealed_set(tmp_path, monkeypatch): + from openadapt_flow import sealed_set + + report = tmp_path / "report.json" + assert executor_mod._read_report(report) == {} # missing + report.write_text("{not json", encoding="utf-8") + assert executor_mod._read_report(report) == {} # unreadable + report.write_text('["a list"]', encoding="utf-8") + assert executor_mod._read_report(report) == {} # not an object + report.write_text('{"success": true}', encoding="utf-8") + assert executor_mod._read_report(report) == {"success": True} + + # A sealed run's report is decrypted by the sealed set, and a sealed + # report that can't be read (no key, a bad tag) is unknown, not plaintext. + monkeypatch.setattr(sealed_set, "is_sealed_path", lambda path: True) + monkeypatch.setattr( + sealed_set, "read_text", lambda path, encoding="utf-8": '{"halt": {}}' + ) + assert executor_mod._read_report(report) == {"halt": {}} + + def refuse(path, encoding="utf-8"): + raise ValueError("no key for this sealed set") + + monkeypatch.setattr(sealed_set, "read_text", refuse) + assert executor_mod._read_report(report) == {} + + +@pytest.mark.skipif(not hasattr(os, "getsid"), reason="POSIX sessions") +@pytest.mark.parametrize("signame", ["SIGINT", "SIGTERM", "SIGHUP"]) +def test_a_daemon_stop_mid_run_stops_the_child_and_reports_it_uncertain( + tmp_path, signame +): + """Ctrl-C, a service stop, kill or a closed terminal while a real child + runs: the daemon stops the child and reports halt, never failed.""" + if not hasattr(signal, signame): + pytest.skip(f"no {signame} here") + plane = RecordingPlane() + job_id = f"bjob_stop_{signame.lower()}" + plane.jobs.append({"id": job_id, "status": "queued", "payload": _payload()}) + started = threading.Event() + child: dict = {} + + client = _client(plane) + + def interrupt() -> None: + # The operator's Ctrl-C (or the unit's SIGINT) reaches this process + # while the child runs. Only this process: the test runner's own + # process group is left alone. + # Signal even if the child never started, so a regression fails the + # assertions below instead of leaving the loop polling forever. + started.wait(10) + time.sleep(0.5) + os.kill(os.getpid(), getattr(signal, signame)) + + threading.Thread(target=interrupt, daemon=True).start() + + def runner(argv, run_dir, env): + real = [sys.executable, "-c", "import time; time.sleep(30)"] + original = executor_mod.subprocess.Popen + + def spy(*args, **kwargs): + proc = original(*args, **kwargs) + child["proc"] = proc + started.set() + return proc + + executor_mod.subprocess.Popen = spy + try: + return _subprocess_runner(real, run_dir, {"PATH": os.environ["PATH"]}) + finally: + executor_mod.subprocess.Popen = original + + settings = _configured_settings( + control_plane_url="https://cloud.test", + token=TOKEN, + poll_wait_s=0, + max_workers=2, + ) + began = time.monotonic() + run_loop( + client, + settings, + runner=runner, + storage_factory=lambda job: InMemoryCustomerStorage(PLAIN_BUNDLE), + log=lambda _m: None, + ) + assert time.monotonic() - began < 20 # stopped, not waited out + assert "proc" in child, "the governed child never started" + proc = child["proc"] + assert proc.poll() is not None # the daemon stopped its child + acks = [ + json.loads(r.content) + for r in plane.requests + if r.url.path == "/api/connector/ack" + ] + assert len(acks) == 1 and acks[0]["job_id"] == job_id + assert acks[0]["status"] != "failed" + assert acks[0].get("error_code") == "child_outcome_unknown" + + +@pytest.mark.skipif(not hasattr(os, "getsid"), reason="POSIX sessions") +def test_the_governed_child_runs_in_its_own_session(tmp_path): + """A signal to the daemon's process group does not reach the child.""" + seen: dict = {} + original = executor_mod.subprocess.Popen + + def spy(*args, **kwargs): + proc = original(*args, **kwargs) + seen["sid"] = os.getsid(proc.pid) + return proc + + executor_mod.subprocess.Popen = spy + try: + _subprocess_runner([sys.executable, "-c", "pass"], tmp_path, dict(os.environ)) + finally: + executor_mod.subprocess.Popen = original + assert seen["sid"] != os.getsid(0) + + +def test_concurrency_runs_up_to_the_server_cap(tmp_path): + plane = RecordingPlane( + control={ + "max_concurrent_leases": 2, + "runs_stopped": False, + "cancel_job_ids": [], + "rotate_recommended": False, + "token_expires_at": None, + } + ) + for n in (1, 2): + plane.jobs.append( + { + "id": f"bjob_{n}", + "status": "queued", + "payload": _payload(run_id=f"00000000-0000-4000-8000-00000000000{n}"), + } + ) + barrier = threading.Barrier(2, timeout=10) + polls = {"n": 0} + + class StoppingClient(ConnectorClient): + def poll(self, wait_s, *, active_job_ids=()): + polls["n"] += 1 + if polls["n"] > 6: + raise KeyboardInterrupt + return super().poll(0, active_job_ids=active_job_ids) + + client = StoppingClient( + "https://cloud.test", token=TOKEN, transport=httpx.MockTransport(plane.handler) + ) + client.control = ConnectorControl(max_concurrent_leases=2) + + def runner(argv, run_dir, env): + barrier.wait() # both jobs must be running at the same time + report = { + "execution_target_kind": "web", + "success": True, + "terminal_outcome": "success", + "results": [], + } + return RunOutcome(returncode=0, report=report) + + settings = _configured_settings( + control_plane_url="https://cloud.test", + token=TOKEN, + poll_wait_s=0, + max_workers=4, + ) + run_loop( + client, + settings, + runner=runner, + storage_factory=lambda job: InMemoryCustomerStorage(PLAIN_BUNDLE), + log=lambda _m: None, + ) + acks = [ + json.loads(r.content) + for r in plane.requests + if r.url.path == "/api/connector/ack" + ] + assert sorted(a["job_id"] for a in acks) == ["bjob_1", "bjob_2"] + assert not barrier.broken + + +def test_rotation_mints_locally_and_sends_only_a_hash(tmp_path, monkeypatch): + monkeypatch.setenv("OPENADAPT_HOME", str(tmp_path)) + plane = RecordingPlane() + client = _client(plane) + client.control.rotate_recommended = True + settings = _configured_settings(control_plane_url="https://cloud.test", token=TOKEN) + save_enrollment(settings) + events: list[str] = [] + + def pending(new_token: str) -> None: + settings.pending_token = new_token + save_enrollment(settings) + events.append("pending") + + def persist(new_token: str) -> None: + assert client.token == TOKEN # still the old one while persisting + settings.token, settings.pending_token = new_token, None + save_enrollment(settings) + events.append("persisted") + + assert maybe_rotate(client, persist, lambda _m: None, persist_pending=pending) + assert events == ["pending", "persisted"] + new = client.token + assert new != TOKEN and new.startswith("oaconn_") + rotate = [r for r in plane.requests if r.url.path == "/api/connector/rotate"][0] + assert json.loads(rotate.content) == { + "new_token_sha256": hashlib.sha256(new.encode()).hexdigest() + } + assert new.encode() not in plane.all_bytes() # the token itself never crossed + reloaded = load_settings() + assert reloaded.token == new and reloaded.pending_token is None + assert (tmp_path / "connector.toml").stat().st_mode & 0o777 == 0o600 + assert not maybe_rotate(client, persist, lambda _m: None) # nothing recommended now + + +def test_lost_rotate_response_is_finished_by_retrying(monkeypatch): + from openadapt_flow.connector.daemon import finish_rotation + + monkeypatch.setattr("openadapt_flow.connector.daemon.time.sleep", lambda _s: None) + calls = {"n": 0} + + def handler(request): + calls["n"] += 1 + if calls["n"] == 1: + raise httpx.ReadTimeout("lost", request=request) + return httpx.Response(200, json={"token": None, "already_rotated": True}) + + client = ConnectorClient( + "https://cloud.test", token=TOKEN, transport=httpx.MockTransport(handler) + ) + saved: list[str] = [] + assert finish_rotation(client, "oaconn_" + "9" * 64, saved.append, lambda _m: None) + assert saved == ["oaconn_" + "9" * 64] and client.token == saved[0] + + +# -------------------------------------------------------------------------- +# Local secret store. +# -------------------------------------------------------------------------- +def test_secret_store_rules(tmp_path): + store = LocalSecretStore(str(tmp_path)) + assert store.resolve(None) == {} + f = tmp_path / "app.env" + f.write_text("# comment\nAPP_PASSWORD=hunter22\n") + os.chmod(f, 0o644) + with pytest.raises(SecretStoreError, match="group or others"): + store.resolve("app") + os.chmod(f, 0o600) + assert store.resolve("app") == {"APP_PASSWORD": "hunter22"} + for bad in ("../app", "a b", ""): + if bad: + with pytest.raises(SecretStoreError): + store.resolve(bad) + g = tmp_path / "evil.env" + g.write_text("LD_PRELOAD=/tmp/x.so\n") + os.chmod(g, 0o600) + with pytest.raises(SecretStoreError, match="line 1"): + store.resolve("evil") + with pytest.raises(SecretStoreError): + LocalSecretStore(None).resolve("app") + + +def test_job_naming_unknown_secret_is_refused_before_any_run(): + job = parse_job(_payload(secrets_ref="missing"), lease_job_id="bjob_s") + result = execute_job( + job, + _configured_settings(), + InMemoryCustomerStorage(PLAIN_BUNDLE), + runner=lambda *a: (_ for _ in ()).throw(AssertionError("ran")), + ) + assert result.error_code == "secrets_unavailable" + + +# -------------------------------------------------------------------------- +# Admitted wrap programs: pinned admitter keys and the independent read-back. +# -------------------------------------------------------------------------- +ADMISSION = b'{"admission": "signed"}' +VERIFY_YAML = b"verifier: {kind: rest}\n" +WRAP_BUNDLE = _zip( + { + "workflow.json": b"{}", + "admission.json": ADMISSION, + "readback/verify.yaml": VERIFY_YAML, + "openadapt-wrap-publish.json": b"{}", + } +) +ADMITTER_KEY = "f" * 64 + + +def _wrap_dispatch(run_id: str, admission_sha: str) -> dict: + from openadapt_flow.runner.dispatch_envelope import ManagedDispatchEnvelope + from openadapt_flow.runner.protocol import dispatch_binding_sha256 + from openadapt_flow.runtime.authorization import GovernedRunAuthorization + + authorization = GovernedRunAuthorization.model_validate( + _CASE["dispatch"]["authorization"] + ).model_copy( + update={"approval_source": "hosted:program-admission:" + admission_sha} + ) + envelope = ManagedDispatchEnvelope( + run_id=run_id, + bundle_content_digest=authorization.bundle_content_digest, + runtime_inputs_digest=authorization.runtime_inputs_digest, + authorization=authorization, + dispatch_binding_sha256=dispatch_binding_sha256(run_id, authorization), + ) + reference = copy.deepcopy(_CASE["dispatch"]["program_admission"]) + reference["admission_sha256"] = admission_sha + return {**envelope.model_dump(mode="json"), "program_admission": reference} + + +def _wrap_job(admission_sha: str | None = None): + payload = _payload(bundle=WRAP_BUNDLE) + sha = admission_sha or hashlib.sha256(ADMISSION).hexdigest() + payload["managed_dispatch"] = _wrap_dispatch(payload["run_id"], sha) + payload["managed_delivery_authority_url"] = ( + "https://cloud.test/api/internal/managed-delivery-permit" + ) + return parse_job(payload, lease_job_id="bjob_w") + + +def _settings(**kw): + return ConnectorSettings( + control_plane_url="https://cloud.test", org_id="org_pilot", **kw + ) + + +def test_unpinned_admitter_key_is_refused(): + result = execute_job( + _wrap_job(), + _settings(), + InMemoryCustomerStorage(WRAP_BUNDLE), + runner=lambda *a: (_ for _ in ()).throw(AssertionError("ran")), + ) + assert result.error_code == "admission_key_not_pinned" + + +def test_dispatched_admission_must_match_the_archive(): + result = execute_job( + _wrap_job("0" * 64), + _settings(trusted_admission_keys=ADMITTER_KEY), + InMemoryCustomerStorage(WRAP_BUNDLE), + runner=lambda *a: (_ for _ in ()).throw(AssertionError("ran")), + ) + assert result.error_code == "program_admission_refused" + + +def test_admitted_wrap_run_stages_key_and_reports_readback(monkeypatch): + calls: list[list[str]] = [] + + def fake_tool(argv, env): + calls.append(argv) + if "--capture-baseline" in argv: + Path(argv[argv.index("--capture-baseline") + 1]).write_text( + json.dumps({"records": [CANARY_RECORD]}) + ) + else: + out = Path(argv[argv.index("--out") + 1]) + (out / "effect-receipt.json").write_text( + json.dumps( + { + "outcome": "verified", + "effect_verdict": "CONFIRMED", + "verification_tier": "independent_readback", + "records": [CANARY_RECORD], + } + ) + ) + return 0 + + monkeypatch.setattr(executor_mod, "_run_flow_tool", fake_tool) + seen: dict = {} + + def runner(argv, run_dir, env): + key_dir = Path(env["OPENADAPT_JIT_KEY_DIR"]) + seen["key"] = (key_dir / "keys" / "ed25519.pub").read_text().strip() + seen["dispatch"] = json.loads( + Path(argv[argv.index("--managed-dispatch-file") + 1]).read_text() + ) + report = { + "execution_target_kind": "web", + "success": True, + "execution_outcome": "VERIFIED", + "results": [{"ok": True}], + } + return RunOutcome(returncode=0, report=report) + + job = _wrap_job() + result = execute_job( + job, + _settings(trusted_admission_keys=ADMITTER_KEY), + InMemoryCustomerStorage(WRAP_BUNDLE), + runner=runner, + ) + assert seen["key"] == ADMITTER_KEY + assert "program_admission" not in seen["dispatch"] # only the six Flow keys + assert len(calls) == 2 and "--authorization-ref" in calls[1] + readback = result.metrics["wrap_readback"] + assert readback["readback_sha256"] == hashlib.sha256(VERIFY_YAML).hexdigest() + assert readback["effect_verdict"] == "CONFIRMED" + body = egress.guard_callback( + { + "run_id": job.run_id, + "org_id": job.org_id, + "workflow_id": job.workflow_id, + "status": result.status, + "metrics": result.metrics, + "report_path": result.report_ref, + } + ) + assert CANARY_RECORD not in json.dumps(body) + + +def test_readback_evidence_is_closed(): + good = json.dumps( + { + "outcome": "verified", + "effect_verdict": "CONFIRMED", + "verification_tier": "independent_readback", + } + ).encode() + assert wrap_readback_evidence(good, "a" * 64)["outcome"] == "verified" + bad = json.dumps( + { + "outcome": "verified by Alice", + "effect_verdict": "CONFIRMED", + "verification_tier": "x", + } + ).encode() + assert wrap_readback_evidence(bad, "a" * 64) is None + assert wrap_readback_evidence(good, "") is None + + +_VERIFIED_ENVELOPE = ( + Path(__file__).parent / "fixtures" / "connector_outcome_envelope_verified.json" +) + + +def test_a_verified_outcome_envelope_passes_the_egress_guard(): + """A real VERIFIED envelope (staging, synthetic) carries digest-named keys.""" + from openadapt_flow.connector import egress + + envelope = json.loads(_VERIFIED_ENVELOPE.read_text()) + body = { + "run_id": "run_1", + "org_id": "org_1", + "workflow_id": "wf_1", + "status": "success", + "report_path": "org_1/run_1/report.json", + "metrics": {"steps": 3}, + "mode": "replay", + "outcome": envelope, + } + sent = egress.guard_callback(body) + assert sent["outcome"]["outcome"] == "VERIFIED" + assert ( + sent["outcome"]["workflow_contract_sha256"] + == envelope["workflow_contract_sha256"] + ) + + +def test_the_outcome_envelope_still_refuses_free_text(): + from openadapt_flow.connector import egress + + def body(envelope): + return { + "run_id": "run_1", + "org_id": "org_1", + "workflow_id": "wf_1", + "status": "success", + "report_path": "org_1/run_1/report.json", + "metrics": {"steps": 3}, + "mode": "replay", + "outcome": envelope, + } + + # A record value in a string leaf is refused. + envelope = json.loads(_VERIFIED_ENVELOPE.read_text()) + envelope["postcondition_evidence"][0]["action_kind"] = f"type {CANARY_RECORD}" + with pytest.raises(egress.EgressViolation): + egress.guard_callback(body(envelope)) + + # An unknown key is refused or dropped by the closed model; it never leaves. + envelope = json.loads(_VERIFIED_ENVELOPE.read_text()) + envelope["required_contracts"][f"note {CANARY_RECORD}"] = 1 + try: + sent = egress.guard_callback(body(envelope)) + except egress.EgressViolation: + return + assert CANARY_RECORD not in json.dumps(sent) + + +def test_local_report_digest_matches_the_stored_bytes(tmp_path): + from openadapt_flow.connector.storage import LocalCustomerStorage, report_bytes + + report = {"success": True, "note": CANARY_RECORD} + storage = LocalCustomerStorage(str(tmp_path)) + written = storage.write_report("org_1/run_1/report.json", report) + assert Path(written).read_bytes() == report_bytes(report) + assert egress.guard_callback( + { + "run_id": "run_1", + "org_id": "org_1", + "workflow_id": "wf_1", + "status": "success", + "report_path": "org_1/run_1/report.json", + "metrics": { + "steps": 1, + "report_sha256": hashlib.sha256(report_bytes(report)).hexdigest(), + }, + "mode": "replay", + } + )["metrics"]["report_sha256"] + + +def test_wrap_readback_evidence_reads_the_v1_effect_receipt(): + """verify-run nests the closed labels under "receipt" (effect-receipt/v1).""" + from openadapt_flow.connector.executor import wrap_readback_evidence + + receipt = json.dumps( + { + "schema_version": "openadapt.effect-receipt/v1", + "receipt": { + "outcome": "verified", + "effect_verdict": "CONFIRMED", + "verification_tier": "system_of_record", + }, + "evidence": {"checked": {"frame": "confirmed"}}, + } + ).encode() + evidence = wrap_readback_evidence(receipt, "a" * 64) + assert evidence == { + "readback_sha256": "a" * 64, + "outcome": "verified", + "effect_verdict": "CONFIRMED", + "verification_tier": "system_of_record", + "receipt_sha256": hashlib.sha256(receipt).hexdigest(), + } + # A free-text label is still refused. + bad = json.loads(receipt) + bad["receipt"]["outcome"] = f"saw {CANARY_RECORD}" + assert wrap_readback_evidence(json.dumps(bad).encode(), "a" * 64) is None diff --git a/packages/flow/tests/test_connector_v3_contract.py b/packages/flow/tests/test_connector_v3_contract.py new file mode 100644 index 0000000000..16d2d14f77 --- /dev/null +++ b/packages/flow/tests/test_connector_v3_contract.py @@ -0,0 +1,625 @@ +"""BYOC live authority crosses every process boundary without gaining scope. + +All fixtures are public synthetic contracts with real throwaway signatures. +No production account, external service, GUI or live qualification is used. +""" + +from __future__ import annotations + +import copy +import hashlib +import json +import os +import stat +from base64 import b64encode +from datetime import datetime, timedelta, timezone +from pathlib import Path +from types import SimpleNamespace + +import httpx +import pytest + +from openadapt_flow.connector import executor +from openadapt_flow.connector.client import ConnectorClient +from openadapt_flow.connector.config import ConnectorSettings +from openadapt_flow.connector.protocol import ( + MANAGED_DELIVERY_AUTHORITY_CAPABILITY, + ByocGovernanceError, + parse_job, +) +from openadapt_flow.connector.storage import InMemoryCustomerStorage +from openadapt_flow.ir import Workflow +from openadapt_flow.jit.authority import PrincipalRegistry +from openadapt_flow.production_qualification import ( + ProductionQualificationGuard, + load_production_qualification_authority, +) +from openadapt_flow.runner.dispatch_envelope import read_managed_dispatch_envelope +from openadapt_flow.runner.protocol import dispatch_binding_sha256 +from openadapt_flow.runtime.authorization import GovernedRunAuthorization +from openadapt_flow.runtime.durable.authority import ( + REMOTE_AUTHORITY_TOKEN_ENV, + REMOTE_AUTHORITY_URL_ENV, + REMOTE_DISPATCH_SESSION_ID_ENV, + DurableAuthority, + DurableAuthorityBusy, +) +from tests.connector_v3_fixtures import ( + ADMITTER_ID, + CONTROL_PLANE, + RUN_ID, + SESSION_ID, + archive_tree, + build_program_case, + build_qualification_case, +) + +OTHER_ID = "ac200000-0000-4000-8000-000000000001" + + +class CountingStorage(InMemoryCustomerStorage): + def __init__(self, data: bytes): + super().__init__(data) + self.fetches = 0 + + def fetch_bundle_archive(self, ref, destination): + self.fetches += 1 + return super().fetch_bundle_archive(ref, destination) + + +def _settings(case, **overrides): + return ConnectorSettings(**{**case["settings_kwargs"], **overrides}) + + +def _run(case, monkeypatch, *, payload=None, settings=None, runner=None): + # Only the record system is outside this source-contract test. This read + # helper would perform external I/O; no admission/authority check is stubbed. + monkeypatch.setattr(executor, "_run_flow_tool", lambda *_args: 1) + storage = CountingStorage(case["bundle_bytes"]) + seen = [] + failures = [] + + def capture(argv, run_dir, env): + __tracebackhide__ = True + # Keep unrelated inherited process configuration out of test tracebacks. + env = { + key: env[key] + for key in ( + REMOTE_AUTHORITY_URL_ENV, + REMOTE_AUTHORITY_TOKEN_ENV, + REMOTE_DISPATCH_SESSION_ID_ENV, + "OPENADAPT_JIT_KEY_DIR", + "OPENADAPT_QUALIFICATION_SIGNERS_JSON", + ) + if key in env + } + seen.append((argv, env)) + if runner is not None: + try: + runner(argv, run_dir, env) + except Exception as exc: + failures.append(exc) + raise + return executor.RunOutcome( + 0, + { + "execution_target_kind": "web", + "success": True, + "execution_outcome": "VERIFIED", + "results": [], + }, + ) + + result = executor.execute_job( + parse_job(payload or case["payload"], lease_job_id="synthetic-lease"), + settings or _settings(case), + storage, + runner=capture, + ) + if failures: + raise failures[0] + return result, storage, seen + + +def _assert_handoff(case, argv, _run_dir, env): + assert "--approval-mode" not in argv + assert "synthetic-run-capability" not in " ".join(argv) + assert ( + env[REMOTE_AUTHORITY_URL_ENV] + == case["payload"]["managed_delivery_authority_url"] + ) + assert env[REMOTE_AUTHORITY_TOKEN_ENV] == "synthetic-run-capability" + assert env[REMOTE_DISPATCH_SESSION_ID_ENV] == SESSION_ID + path = Path(argv[argv.index("--managed-dispatch-file") + 1]) + if os.name != "nt": + assert stat.S_IMODE(path.stat().st_mode) == 0o600 + binding = read_managed_dispatch_envelope(path) + assert binding.run_id == RUN_ID + assert ( + binding.authorization.bundle_content_digest + == case["dispatch"]["bundle_content_digest"] + ) + assert binding.binding_sha256 == case["dispatch"]["dispatch_binding_sha256"] + # The consumed extension cannot masquerade as an inner v1 approval. + assert binding.authorization.qualification_admission is None + return binding + + +@pytest.mark.parametrize("mode", ["person", "admitter_key"]) +def test_real_program_forms_cross_poll_payload_private_file_and_flow_parse( + tmp_path, monkeypatch, mode +): + case = build_program_case(tmp_path, mode) + requests = [] + + def control(request): + requests.append(json.loads(request.content)) + return httpx.Response( + 200, json={"job": {"id": "synthetic-lease", "payload": case["payload"]}} + ) + + with ConnectorClient( + CONTROL_PLANE, + token="synthetic-connector-capability", + transport=httpx.MockTransport(control), + ) as client: + leased = client.poll(1) + assert requests[0]["capabilities"] == [MANAGED_DELIVERY_AUTHORITY_CAPABILITY] + assert MANAGED_DELIVERY_AUTHORITY_CAPABILITY == "managed_delivery_authority_v3" + assert leased["payload"] == case["payload"] + monkeypatch.setenv(REMOTE_AUTHORITY_TOKEN_ENV, "stale-inherited-token") + monkeypatch.setenv(REMOTE_DISPATCH_SESSION_ID_ENV, OTHER_ID) + result, storage, seen = _run( + case, + monkeypatch, + payload=leased["payload"], + runner=lambda *args: _assert_handoff(case, *args), + ) + assert result.error_code is None + assert storage.fetches == 1 and len(seen) == 1 + assert list(case["key_dir"].rglob("*.pem")) == [] + + +@pytest.mark.parametrize( + "fault", + [ + "missing_session", + "unsupported_teach_mode", + "unsupported_unknown_mode", + "noncanonical_session", + "missing_authority", + "wrong_run", + "wrong_org", + "foreign_origin", + "wrong_path", + "unknown_outer", + "unknown_extension", + "unknown_authorization", + "unknown_nested_authorization", + "remote_save_override", + "mixed_basis", + ], +) +def test_live_scope_faults_refuse_before_fetch_or_child(tmp_path, monkeypatch, fault): + case = ( + build_qualification_case(tmp_path) + if fault == "unknown_nested_authorization" + else build_program_case(tmp_path) + ) + raw = copy.deepcopy(case["payload"]) + if fault == "missing_session": + raw.pop("managed_dispatch_session_id") + elif fault in {"unsupported_teach_mode", "unsupported_unknown_mode"}: + raw["mode"] = "teach" if fault == "unsupported_teach_mode" else "future-mode" + elif fault == "noncanonical_session": + raw["managed_dispatch_session_id"] = SESSION_ID.upper() + elif fault == "missing_authority": + raw["managed_dispatch"] = None + raw["managed_delivery_authority_url"] = None + elif fault == "wrong_run": + raw["run_id"] = OTHER_ID + elif fault == "wrong_org": + raw["org_id"] = OTHER_ID + elif fault == "foreign_origin": + raw["managed_delivery_authority_url"] = ( + "https://other.example.test/api/internal/managed-delivery-permit" + ) + elif fault == "wrong_path": + raw["managed_delivery_authority_url"] = CONTROL_PLANE + "/other" + elif fault == "unknown_outer": + raw["stronger_authority"] = True + elif fault == "unknown_extension": + raw["managed_dispatch"]["stronger_authority"] = True + elif fault == "unknown_authorization": + raw["managed_dispatch"]["authorization"]["unbound_approval"] = True + elif fault == "unknown_nested_authorization": + requirements = raw["managed_dispatch"]["authorization"][ + "qualified_effect_requirements" + ] + assert requirements + requirements[0]["unbound_requirement"] = True + elif fault == "remote_save_override": + raw["managed_dispatch"]["authorization"]["approval_mode"] = "not_gated" + elif fault == "mixed_basis": + raw["managed_dispatch"]["qualification_admission"] = {} + result, storage, seen = _run(case, monkeypatch, payload=raw) + assert result.status == "failed" and result.error_code == "governance_refused" + assert storage.fetches == 0 and seen == [] + + +def test_legacy_parse_never_inherits_live_authority_from_environment( + tmp_path, monkeypatch +): + case = build_program_case(tmp_path) + legacy = copy.deepcopy(case["payload"]) + for key in ( + "managed_dispatch", + "managed_delivery_authority_url", + "managed_dispatch_session_id", + ): + legacy.pop(key) + monkeypatch.setenv( + REMOTE_AUTHORITY_URL_ENV, case["payload"]["managed_delivery_authority_url"] + ) + monkeypatch.setenv(REMOTE_AUTHORITY_TOKEN_ENV, "stale-inherited-token") + monkeypatch.setenv(REMOTE_DISPATCH_SESSION_ID_ENV, SESSION_ID) + parsed = parse_job(legacy) + with pytest.raises(ByocGovernanceError): + parsed.ensure_governed(require_run_token=False) + result, storage, seen = _run(case, monkeypatch, payload=legacy) + assert ( + result.error_code == "governance_refused" and storage.fetches == 0 and not seen + ) + + +@pytest.mark.parametrize( + "fault", + [ + "principal", + "admitter_key", + "registry_removed", + "registry_role", + "downgrade", + "primary_key", + "admission_digest", + ], +) +def test_admitter_reference_cannot_change_principal_key_role_or_form( + tmp_path, monkeypatch, fault +): + case = build_program_case(tmp_path, "admitter_key") + raw = copy.deepcopy(case["payload"]) + reference = raw["managed_dispatch"]["program_admission"] + if fault == "principal": + reference["admitted_by_principal_id"] = "ci:other-admitter" + elif fault == "admitter_key": + reference["admitter_public_key_hex"] = "e" * 64 + elif fault == "registry_removed": + PrincipalRegistry().save(case["key_dir"]) + elif fault == "registry_role": + PrincipalRegistry( + agents={ADMITTER_ID: reference["admitter_public_key_hex"]} + ).save(case["key_dir"]) + elif fault == "downgrade": + raw["managed_dispatch"]["program_admission"] = { + k: reference[k] + for k in ("schema_version", "admission_sha256", "public_key_hex") + } + raw["managed_dispatch"]["program_admission"]["schema_version"] = ( + "openadapt.program-admission-reference/v1" + ) + elif fault == "primary_key": + reference["public_key_hex"] = "e" * 64 + elif fault == "admission_digest": + reference["admission_sha256"] = "e" * 64 + authorization = raw["managed_dispatch"]["authorization"] + authorization["approval_source"] = "hosted:program-admission:" + "e" * 64 + raw["managed_dispatch"]["dispatch_binding_sha256"] = dispatch_binding_sha256( + RUN_ID, GovernedRunAuthorization.model_validate(authorization) + ) + settings = _settings(case, trusted_admission_keys=reference["public_key_hex"]) + result, _storage, seen = _run(case, monkeypatch, payload=raw, settings=settings) + assert result.status == "failed" and not seen + assert result.error_code == "program_admission_refused" + + +def test_outer_metadata_cannot_rescue_a_tampered_program_signature( + tmp_path, monkeypatch +): + case = build_program_case(tmp_path) + admission_path = case["bundle"] / "admission.json" + tampered = json.loads(admission_path.read_text()) + tampered["admitted_by_principal_id"] = "Another Operator" + admission_path.write_text(json.dumps(tampered)) + case["bundle_bytes"] = archive_tree(case["bundle"]) + raw = copy.deepcopy(case["payload"]) + raw["bundle_sha256"] = hashlib.sha256(case["bundle_bytes"]).hexdigest() + digest = hashlib.sha256(admission_path.read_bytes()).hexdigest() + raw["managed_dispatch"]["program_admission"]["admission_sha256"] = digest + raw["managed_dispatch"]["authorization"]["approval_source"] = ( + "hosted:program-admission:" + digest + ) + raw["managed_dispatch"]["dispatch_binding_sha256"] = dispatch_binding_sha256( + RUN_ID, + GovernedRunAuthorization.model_validate( + raw["managed_dispatch"]["authorization"] + ), + ) + result, storage, seen = _run(case, monkeypatch, payload=raw) + assert storage.fetches == 1 and not seen + assert result.error_code == "program_admission_refused" + + +def test_qualification_v2_uses_independent_private_wrapper_and_real_guard( + tmp_path, monkeypatch +): + case = build_qualification_case(tmp_path) + parsed = parse_job(case["payload"]) + parsed.ensure_governed() + assert ( + parsed.qualification_admission().payload.schema_version + == "openadapt.qualification-admission/v2" + ) + + def inspect(argv, run_dir, env): + _assert_handoff(case, argv, run_dir, env) + path = Path(argv[argv.index("--qualification-authority-file") + 1]) + assert path != case["authority_file"] + copied = load_production_qualification_authority(path) + assert copied == case["operator"] + ProductionQualificationGuard(path, remote_permit_revalidation=True).verify( + Workflow.load(argv[argv.index("run") + 1]), for_actuation=False + ) + + result, storage, seen = _run(case, monkeypatch, runner=inspect) + assert result.error_code is None and storage.fetches == 1 and len(seen) == 1 + + +@pytest.mark.parametrize( + "fault", + [ + "missing_context", + "different_tenant", + "bad_signature", + pytest.param( + "context_public", + marks=pytest.mark.skipif( + os.name == "nt", + reason="POSIX mode refusal; Windows uses the descriptor ACL guard", + ), + ), + ], +) +def test_qualification_cannot_self_assert_or_replace_operator_context( + tmp_path, monkeypatch, fault +): + case = build_qualification_case(tmp_path) + settings = _settings(case) + raw = copy.deepcopy(case["payload"]) + if fault == "missing_context": + settings.qualification_authority_file = None + else: + operator = json.loads(case["authority_file"].read_text()) + if fault == "different_tenant": + operator["expected"]["tenant_id"] = OTHER_ID + elif fault == "bad_signature": + operator["qualification_admission"]["signature"] = "A" * 86 + "==" + from openadapt_flow.qualification_admission_v2 import ( + QualificationAdmissionEnvelope, + ) + + proof = QualificationAdmissionEnvelope.model_validate( + operator["qualification_admission"] + ) + operator["qualification_admission_sha256"] = proof.artifact_sha256() + raw["managed_dispatch"]["qualification_admission"] = proof.model_dump( + mode="json" + ) + raw["managed_dispatch"]["qualification_admission_sha256"] = ( + proof.artifact_sha256() + ) + case["authority_file"].write_text(json.dumps(operator)) + case["authority_file"].chmod( + 0o644 if fault == "context_public" and os.name != "nt" else 0o600 + ) + result, _storage, seen = _run(case, monkeypatch, payload=raw, settings=settings) + assert result.status == "failed" and not seen + assert result.error_code in { + "qualification_authority_unavailable", + "qualification_authority_refused", + } + + +@pytest.mark.parametrize("fault", ["none", "different_session", "other_run", "v2"]) +def test_source_v3_permission_is_bound_to_handoff_session_before_input( + tmp_path, monkeypatch, fault +): + from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey + + from openadapt_flow.terminal_verification_v2 import ( + sign_production_delivery_permit_v3, + ) + from tests.test_delivery_permit_receiver_freshness import _response + + case = build_program_case(tmp_path) + issuer_key = Ed25519PrivateKey.generate() + inputs = [] + + def guarded_input(argv, run_dir, env): + binding = _assert_handoff(case, argv, run_dir, env) + authority = object.__new__(DurableAuthority) + + def issue(_url, _headers, body): + request = json.loads(body) + issued = datetime.now(timezone.utc).replace(microsecond=0) + if fault == "other_run": + request["run_id"] = OTHER_ID + response, retained = _response( + request, + checked=issued, + issued=issued, + expires=issued + timedelta(seconds=120), + ) + artifact = sign_production_delivery_permit_v3( + retained.permit_artifact.payload, issuer_key + ).canonical_bytes() + response["permit_artifact_bytes_base64"] = b64encode(artifact).decode() + response["permit_artifact_sha256"] = hashlib.sha256(artifact).hexdigest() + response["dispatch_session_id"] = ( + OTHER_ID if fault == "different_session" else SESSION_ID + ) + if fault == "v2": + response["schema_version"] = ( + "openadapt.production-delivery-permit-issue/v2" + ) + return json.dumps(response).encode() + + authority._remote_transport = issue + manifest = SimpleNamespace( + governed_authorization=binding.authorization, + delivery_authority_kind="cloud_runner", + remote_delivery_run_id=binding.run_id, + namespace_id="a" * 32, + managed_dispatch_binding_sha256=binding.binding_sha256, + ) + record = SimpleNamespace( + path_key="c" * 64, + progress_digest="sha256:" + "d" * 64, + operation="initial", + delivery_sequence=0, + ) + with monkeypatch.context() as context: + for name in ( + REMOTE_AUTHORITY_URL_ENV, + REMOTE_AUTHORITY_TOKEN_ENV, + REMOTE_DISPATCH_SESSION_ID_ENV, + ): + context.setenv(name, env[name]) + if fault == "none": + permit = authority._require_remote_delivery_permit( + manifest, + record, + remote_authority_id=None, + remote_delivery_sequence=0, + permit_cursor=None, + ) + authority.require_remote_delivery_fresh(permit) + inputs.append("synthetic-counted-input") + else: + with pytest.raises(DurableAuthorityBusy): + authority._require_remote_delivery_permit( + manifest, + record, + remote_authority_id=None, + remote_delivery_sequence=0, + permit_cursor=None, + ) + + result, _storage, seen = _run(case, monkeypatch, runner=guarded_input) + assert result.error_code is None and len(seen) == 1 + assert len(inputs) == (1 if fault == "none" else 0) + + +def test_local_secret_store_cannot_override_managed_session(tmp_path): + from openadapt_flow.connector.secrets import LocalSecretStore, SecretStoreError + + local = tmp_path / "input.env" + local.write_text("OPENADAPT_DURABLE_DISPATCH_SESSION_ID=" + OTHER_ID + "\n") + local.chmod(0o600) + with pytest.raises(SecretStoreError, match="invalid"): + LocalSecretStore(str(tmp_path)).resolve("input") + + +@pytest.mark.parametrize( + "field", + [ + "org_id", + "workflow_id", + "bundle_version_id", + "runtime_validation_id", + "bundle_sha256", + ], +) +def test_qualification_proof_binds_the_authenticated_job_tuple( + tmp_path, monkeypatch, field +): + case = build_qualification_case(tmp_path) + raw = copy.deepcopy(case["payload"]) + raw[field] = "e" * 64 if field == "bundle_sha256" else OTHER_ID + result, storage, seen = _run(case, monkeypatch, payload=raw) + assert result.error_code == "governance_refused" + assert storage.fetches == 0 and not seen + + +@pytest.mark.parametrize("mode", ["person", "admitter_key"]) +def test_snapshot_key_fallback_does_not_replace_an_admitter_registry( + tmp_path, monkeypatch, mode +): + case = build_program_case(tmp_path, mode) + + def inspect(argv, _run_dir, env): + trust = Path(env["OPENADAPT_JIT_KEY_DIR"]) + assert trust != case["key_dir"] + assert sorted( + p.relative_to(trust).as_posix() for p in trust.rglob("*") if p.is_file() + ) == ["keys/ed25519.pub"] + assert (trust / "keys/ed25519.pub").read_text().strip() == case[ + "public_key_hex" + ] + + result, storage, seen = _run( + case, + monkeypatch, + settings=_settings(case, admission_key_dir=None), + runner=inspect, + ) + if mode == "person": + assert result.error_code is None and len(seen) == 1 and storage.fetches == 1 + else: + assert result.error_code == "admission_registry_required" + assert not seen and storage.fetches == 0 + + +@pytest.mark.parametrize( + "damage", ["principal_removed", "primary_key_removed", "primary_key_changed"] +) +def test_child_uses_live_public_trust_for_current_dispatch_revalidation( + tmp_path, monkeypatch, damage +): + from openadapt_flow.jit.dispatch_authority import verify_program_dispatch + from tests.test_execution_profiles import _TieredVerifier + + case = build_program_case(tmp_path, "admitter_key") + + def inspect(argv, run_dir, env): + binding = _assert_handoff(case, argv, run_dir, env) + trust = Path(env["OPENADAPT_JIT_KEY_DIR"]) + assert trust == case["key_dir"] + bundle = Path(argv[argv.index("run") + 1]) + workflow = Workflow.load(bundle) + with monkeypatch.context() as child: + for key in (REMOTE_AUTHORITY_URL_ENV, REMOTE_DISPATCH_SESSION_ID_ENV): + child.setenv(key, env[key]) + verified = verify_program_dispatch( + binding, + bundle_dir=bundle, + workflow=workflow, + params={}, + worklists={}, + policy_source="clinical-write", + effect_verifier=_TieredVerifier(), + key_dir=trust, + ) + capability = verified.program_admission_authority + assert capability is not None + assert capability.refusal(workflow, verified) is None + if damage == "principal_removed": + PrincipalRegistry().save(trust) + elif damage == "primary_key_removed": + (trust / "keys/ed25519.pub").unlink() + else: + (trust / "keys/ed25519.pub").write_text("e" * 64) + assert capability.refusal(workflow, verified) is not None + + result, storage, seen = _run(case, monkeypatch, runner=inspect) + assert result.error_code is None and len(seen) == 1 and storage.fetches == 1 diff --git a/packages/flow/tests/test_connector_windows_service.py b/packages/flow/tests/test_connector_windows_service.py index e8b7f9f06a..66f0c1f7c2 100644 --- a/packages/flow/tests/test_connector_windows_service.py +++ b/packages/flow/tests/test_connector_windows_service.py @@ -287,7 +287,8 @@ def test_serve_refuses_the_stub_job_then_stops_on_the_event(tmp_path: Path) -> N ack = next(r for r in records if r["path"] == "/api/connector/ack") assert ack["body"]["job_id"] == stub.JOB_ID assert ack["body"]["status"] == "failed" - assert "safety" in (ack["body"]["error"] or "") + assert ack["body"]["error_code"] == "governance_refused" + assert "error" not in ack["body"] assert TOKEN not in log.read_text("utf-8") text = ws.log_path(config_dir).read_text("utf-8") assert TOKEN not in text and "service stopped" in text @@ -411,14 +412,17 @@ def handler(request): assert "ConnectorClientError" in text -def test_stop_during_an_existing_job_reports_and_acks_before_exit(tmp_path): +def test_stop_during_an_existing_job_reports_and_acks_before_exit( + tmp_path, monkeypatch +): import hashlib import zipfile from openadapt_flow.connector.executor import RunOutcome config = tmp_path / "connector" - _write_config(config, "https://cp.example") + # One worker: the service must not lease a second job while the first runs. + _write_config(config, "https://cp.example", max_workers=1) bundle = config / "storage/bundles/wf_stub/bundle.zip" bundle.parent.mkdir(parents=True) with zipfile.ZipFile(bundle, "w") as archive: @@ -448,6 +452,18 @@ def runner(*args): 0, {"execution_target_kind": "web", "success": True, "model_calls": 0} ) + from openadapt_flow.connector import daemon + from openadapt_flow.connector.executor import ExecutionResult + + def execute_job(job, settings, storage, *, runner, **_kwargs): + # Managed authority is covered by the connector contract tests. Only + # execution is stood in here: the production handle_job still builds + # the callback and ack, so the stop control runs through real + # report/ack code while a job is in flight. + runner() + return ExecutionResult("success", {}, None, job.report_ref()) + + monkeypatch.setattr(daemon, "execute_job", execute_job) logger, redactor = ws.build_logger(config, name="test.ws.finish") assert ( ws.serve(