From f92237889163b242800c6aecd7c334c174ce4428 Mon Sep 17 00:00:00 2001 From: abrichr Date: Thu, 19 Nov 2026 18:05:36 -0500 Subject: [PATCH 01/21] Flow connector: allow-listed egress, signed requests, kill switch, concurrency, rotation, local secrets, admitted wrap programs - egress.py rebuilds every outbound body from a closed allow-list and scans it for local secret values - requests carry a timestamp, nonce and HMAC signature (replay protection) - poll/heartbeat control: kill switch (423), cancel ids terminate children, server lease cap, token rotation persisted atomically - secrets_ref resolves to a 0600 local .env file; values reach only the governed child - admitted wrap programs: admitter key must be pinned locally; independent verify-run read-back before/after; only hashes and closed labels leave - accept Cloud's full dispatch (program/qualification reference) and project the six Flow wire keys --- packages/flow/openadapt_flow/__main__.py | 69 +- .../flow/openadapt_flow/connector/client.py | 258 +++++-- .../flow/openadapt_flow/connector/config.py | 79 +- .../flow/openadapt_flow/connector/daemon.py | 253 ++++++- .../flow/openadapt_flow/connector/egress.py | 328 ++++++++ .../flow/openadapt_flow/connector/executor.py | 352 ++++++++- .../flow/openadapt_flow/connector/protocol.py | 89 ++- .../flow/openadapt_flow/connector/secrets.py | 92 +++ packages/flow/tests/test_connector.py | 32 +- packages/flow/tests/test_connector_pilot.py | 714 ++++++++++++++++++ 10 files changed, 2145 insertions(+), 121 deletions(-) create mode 100644 packages/flow/openadapt_flow/connector/egress.py create mode 100644 packages/flow/openadapt_flow/connector/secrets.py create mode 100644 packages/flow/tests/test_connector_pilot.py diff --git a/packages/flow/openadapt_flow/__main__.py b/packages/flow/openadapt_flow/__main__.py index db3c789a41..4ea9c0e7eb 100644 --- a/packages/flow/openadapt_flow/__main__.py +++ b/packages/flow/openadapt_flow/__main__.py @@ -13390,8 +13390,36 @@ def _repair_store_flag(rp: argparse.ArgumentParser) -> None: 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( + "--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=_cmd_connector) + 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=_cmd_connector) + from openadapt_flow.cli_admit import register_admit_parser from openadapt_flow.cli_api import register_api_parser from openadapt_flow.cli_check import register_check_parser @@ -13750,6 +13778,10 @@ def _connector_flags(args: argparse.Namespace) -> dict[str, object]: "storage_backend", "storage_root", "poll_wait", + "secrets_dir", + "trusted_admission_keys", + "egress_audit_log", + "max_workers", ) return { k: getattr(args, k, None) for k in keys if getattr(args, k, None) is not None @@ -13808,6 +13840,36 @@ def _cmd_connector(args: argparse.Namespace) -> int: ) return 0 + from openadapt_flow.connector.config import connector_config_path + + def persist_token(new_token: str) -> None: + settings.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 + client = ConnectorClient(settings.control_plane_url, token=settings.token) + try: + data = client.rotate() + persist_token(data["token"]) + except ConnectorClientError as exc: + print(f"connector rotate-token failed: {exc}") + return 1 + finally: + client.close() + print( + "token rotated and persisted (0600); the previous token stops " + f"working at {data.get('previous_token_valid_until', 'once replaced')}." + ) + return 0 + # verb == "run" if not settings.token: print( @@ -13816,13 +13878,18 @@ def _cmd_connector(args: argparse.Namespace) -> int: "BYOC_CONNECTOR_TOKEN." ) return 2 - client = ConnectorClient(settings.control_plane_url, token=settings.token) + client = ConnectorClient( + settings.control_plane_url, + token=settings.token, + egress_audit_log=settings.egress_audit_log, + ) try: return run_loop( client, settings, runner=_subprocess_runner, once=bool(getattr(args, "once", False)), + persist_token=persist_token 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 fe41133040..9d1b43b74d 100644 --- a/packages/flow/openadapt_flow/connector/client.py +++ b/packages/flow/openadapt_flow/connector/client.py @@ -8,33 +8,88 @@ 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.hosted import HostedError MANAGED_QUALIFICATION_AUTHORITY_CAPABILITY = "managed_qualification_authority_v2" +CONTROL_HEADER = "x-oa-connector-control" class ConnectorClientError(HostedError): """An outbound control-plane call failed.""" +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, @@ -43,13 +98,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() @@ -59,84 +121,176 @@ 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: {resp.status_code} {resp.text[:300]}" - ) + raise ConnectorClientError(f"enroll refused: {resp.status_code}") data = resp.json() token = data.get("token") if token: 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: {resp.status_code} {resp.text[:300]}" + f"poll failed: {resp.status_code} {str(data.get('error', ''))[:80]}" ) - 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: {resp.status_code} {resp.text[:300]}" - ) + raise ConnectorClientError(f"ack failed: {resp.status_code}") return resp.json() if resp.content else {} + def rotate(self) -> dict[str, Any]: + """Swap this connector's token. The caller persists it, then uses it.""" + resp = self._post("/api/connector/rotate", egress.guard_empty()) + if resp.status_code != 200: + raise ConnectorClientError(f"rotate failed: {resp.status_code}") + data = resp.json() + token = data.get("token") + if not isinstance(token, str) or not token.startswith("oaconn_"): + raise ConnectorClientError("rotate returned no connector token") + return data + 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: {resp.status_code} {resp.text[:300]}" - ) + raise ConnectorClientError(f"run-callback failed: {resp.status_code}") + + +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..c8b6c7c506 100644 --- a/packages/flow/openadapt_flow/connector/config.py +++ b/packages/flow/openadapt_flow/connector/config.py @@ -80,6 +80,25 @@ 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 + #: 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 = "" + #: 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 + + 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 +110,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, } @@ -181,6 +203,48 @@ 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" + ), + trusted_admission_keys=str( + _pick( + flags, + "BYOC_TRUSTED_ADMISSION_KEYS", + file_cfg.get("trusted_admission_keys"), + "", + "trusted_admission_keys", + ) + or "" + ), + 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", + ), ) @@ -204,12 +268,25 @@ def save_enrollment( ("storage_bucket", settings.storage_bucket), ("storage_prefix", settings.storage_prefix), ("allow_unencrypted", settings.allow_unencrypted), + ("secrets_dir", settings.secrets_dir), + ("trusted_admission_keys", settings.trusted_admission_keys), + ("egress_audit_log", settings.egress_audit_log), + ("max_workers", settings.max_workers), + ("qualification_signers_file", settings.qualification_signers_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..7b93cef587 100644 --- a/packages/flow/openadapt_flow/connector/daemon.py +++ b/packages/flow/openadapt_flow/connector/daemon.py @@ -14,13 +14,28 @@ from __future__ import annotations +import threading import time +from concurrent.futures import Future, ThreadPoolExecutor from typing import Any, Callable, 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 +46,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 +99,68 @@ 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. """ 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, ) except Exception as exc: # fail closed: build a failed result, still report result = ExecutionResult( - "failed", {}, None, job.report_ref(), f"{type(exc).__name__}" + "failed", + {}, + None, + job.report_ref(), + f"{type(exc).__name__}", + 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 + for attempt in range(CALLBACK_ATTEMPTS if callback_body is not None else 0): try: client.run_callback(callback_body, run_token=job.run_token) callback_accepted = True break + except EgressViolation: + # The body would carry something off the allow-list. Never retry + # it; report the run as a plain failure instead. + callback_body = phi_free_callback_body( + job, + ExecutionResult( + "failed", {}, None, None, None, error_code="egress_refused" + ), + ) + result.error_code = "egress_refused" + result.status = "failed" except Exception: # noqa: BLE001 - bounded retry, then leave lease unacked if attempt + 1 < CALLBACK_ATTEMPTS: time.sleep(0.25 * (2**attempt)) 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 +168,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 +181,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 +210,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 +228,63 @@ 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], +) -> bool: + """Rotate the token when the control plane recommends it and we can persist.""" + if not client.control.rotate_recommended or persist_token is None: + return False + try: + data = client.rotate() + persist_token(data["token"]) # durable before first use + client.token = data["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 later + log(f"[connector] token rotation failed: {type(exc).__name__}") + return False + + def run_loop( client: ConnectorClient, settings: ConnectorSettings, @@ -168,31 +294,110 @@ def run_loop( once: bool = False, require_run_token: bool = True, log: Callable[[str], None] = print, + persist_token: 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) + 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() + 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..d862d9f1a2 --- /dev/null +++ b/packages/flow/openadapt_flow/connector/egress.py @@ -0,0 +1,328 @@ +"""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); +* 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 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 _LABEL.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 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 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..9328745a65 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,6 +47,7 @@ from openadapt_flow.connector.config import ConnectorSettings from openadapt_flow.connector.protocol import ByocGovernanceError, ByocJob +from openadapt_flow.connector.secrets import LocalSecretStore, SecretStoreError from openadapt_flow.connector.storage import CustomerStorage, extract_bundle_archive from openadapt_flow.failure_signals import automation_failure_signal from openadapt_flow.ir import RunReport @@ -83,10 +85,104 @@ 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 + labels = { + k: document.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: + proc.terminate() + try: + proc.wait(timeout=10) + except subprocess.TimeoutExpired: + proc.kill() + return True + return False + + +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: @@ -159,12 +255,25 @@ def build_run_argv( 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 + job_id = getattr(_CURRENT, "job_id", None) + proc = subprocess.Popen( # nosec - fixed argv and exact process-local env argv, - capture_output=True, - text=True, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, env=dict(child_env), ) + if job_id: + with _CHILDREN.lock: + _CHILDREN.procs[job_id] = proc + cancelled = job_id in _CHILDREN.cancelled + if cancelled: + proc.terminate() + try: + proc.wait() + finally: + if job_id: + with _CHILDREN.lock: + _CHILDREN.procs.pop(job_id, None) report_path = run_dir / "report.json" report: dict[str, Any] = {} if report_path.is_file(): @@ -337,45 +446,100 @@ def execute_job( *, runner: Runner = _subprocess_runner, require_run_token: bool = True, + on_secrets: Optional[Callable[[list[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, + ) + 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]], +) -> 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 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) + 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 +549,44 @@ 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" + (key_dir / "keys").mkdir(parents=True) + (key_dir / "keys" / "ed25519.pub").write_text( + admission["public_key_hex"] + "\n", encoding="utf-8" + ) + try: params_file = _write_params_file(job.params, run_dir) managed_dispatch_file = None @@ -401,17 +594,58 @@ 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, + "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) + # 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( job, @@ -421,33 +655,82 @@ def execute_job( params_file, managed_dispatch_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, + ) outcome = runner(argv, run_dir, child_env) except Exception as exc: - return ExecutionResult( - "failed", - {}, - None, - job.report_ref(), + return _refused( + job, + "child_invocation_failed", f"governed child invocation failed: {type(exc).__name__}", verified_bundle_sha256=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: + if job_cancelled(job.lease_job_id): status = "failed" + error_code = "cancelled_by_control_plane" + outcome_error = "cancelled by the control plane while running" + 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: 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) 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 +751,19 @@ 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 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..1296f5608a 100644 --- a/packages/flow/openadapt_flow/connector/protocol.py +++ b/packages/flow/openadapt_flow/connector/protocol.py @@ -20,6 +20,9 @@ from __future__ import annotations +import hashlib +import json +import re from typing import Any, Optional from urllib.parse import urlsplit @@ -28,6 +31,19 @@ from openadapt_flow.ir import ExecutionTargetKind from openadapt_flow.runner.dispatch_envelope import ManagedDispatchEnvelope +#: 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", +) +PROGRAM_ADMISSION_SCHEMA = "openadapt.program-admission-reference/v1" +PROGRAM_ADMISSION_APPROVAL_PREFIX = "hosted:program-admission:" +_HEX64 = re.compile(r"[a-f0-9]{64}\Z") + class ByocJobParseError(ValueError): """A leased job payload could not be parsed as a BYOC dispatch.""" @@ -105,9 +121,13 @@ 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 @@ -178,13 +198,19 @@ def ensure_governed(self, *, require_run_token: bool = True) -> None: "together (fail closed)" ) if self.managed_dispatch is not None: + 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(): + 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 +248,59 @@ def ensure_governed(self, *, require_run_token: bool = True) -> None: "resolve from the customer's storage (fail closed)" ) + def flow_dispatch(self) -> ManagedDispatchEnvelope: + """The exact six-key Flow envelope inside Cloud's dispatch.""" + raw = self.managed_dispatch + if not isinstance(raw, dict) or not set(FLOW_DISPATCH_WIRE_KEYS) <= set(raw): + raise ByocGovernanceError("byoc managed dispatch is malformed") + try: + return ManagedDispatchEnvelope.model_validate( + {key: raw[key] for key in FLOW_DISPATCH_WIRE_KEYS} + ) + except ValidationError as exc: + raise ByocGovernanceError( + "byoc managed dispatch does not match the Flow envelope" + ) from exc + + def program_admission(self) -> Optional[dict[str, str]]: + """The validated program-admission reference of a wrap run, or None.""" + 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 not isinstance(reference, dict) + or set(reference) + != {"schema_version", "admission_sha256", "public_key_hex"} + or reference.get("schema_version") != PROGRAM_ADMISSION_SCHEMA + or 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 not isinstance(authorization, dict) + or authorization.get("execution_profile") != "standard" + or authorization.get("approval_source") + != PROGRAM_ADMISSION_APPROVAL_PREFIX + reference["admission_sha256"] + ): + return None + return { + "admission_sha256": reference["admission_sha256"], + "public_key_hex": reference["public_key_hex"], + } + + def _qualification_ok(self) -> bool: + 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): + return False + canonical = json.dumps( + admission, sort_keys=True, separators=(",", ":"), ensure_ascii=False + ) + return digest == hashlib.sha256(canonical.encode()).hexdigest() + 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: diff --git a/packages/flow/openadapt_flow/connector/secrets.py b/packages/flow/openadapt_flow/connector/secrets.py new file mode 100644 index 0000000000..82c28dd3b7 --- /dev/null +++ b/packages/flow/openadapt_flow/connector/secrets.py @@ -0,0 +1,92 @@ +"""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_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/tests/test_connector.py b/packages/flow/tests/test_connector.py index dfb5898658..39eaf5ad39 100644 --- a/packages/flow/tests/test_connector.py +++ b/packages/flow/tests/test_connector.py @@ -29,11 +29,11 @@ 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 +44,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 @@ -88,7 +91,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", @@ -116,7 +119,19 @@ 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") + # Cloud's dispatch: the six Flow wire keys plus the authority reference. + qualification = {"schema_version": "test", "campaign": "synthetic"} + return { + **envelope.model_dump(mode="json"), + "qualification_admission": qualification, + "qualification_admission_sha256": hashlib.sha256( + json.dumps(qualification, sort_keys=True, separators=(",", ":")).encode() + ).hexdigest(), + } + + +def _wire(dispatch: dict) -> dict: + return {key: dispatch[key] for key in FLOW_DISPATCH_WIRE_KEYS} def _fake_success_runner(report): @@ -196,7 +211,7 @@ def runner(argv, run_dir: Path, child_env) -> RunOutcome: 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["parent_token"] == "stale-parent-token" @@ -870,7 +885,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. @@ -912,6 +931,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 diff --git a/packages/flow/tests/test_connector_pilot.py b/packages/flow/tests/test_connector_pilot.py new file mode 100644 index 0000000000..9413480b71 --- /dev/null +++ b/packages/flow/tests/test_connector_pilot.py @@ -0,0 +1,714 @@ +"""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 hashlib +import hmac +import io +import json +import os +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 + +CANARY_RECORD = "ZQX-CANARY-RECORD-7731" +CANARY_SECRET = "ZQX-CANARY-SECRET-p4ssw0rd" +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() + + +PLAIN_BUNDLE = _zip({"workflow.json": b"{}"}) + + +def _payload(bundle: bytes = PLAIN_BUNDLE, **overrides): + 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(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_SECRET}", + }, + ], + "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_SECRET}\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 = ConnectorSettings( + 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_SECRET}") + 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_SECRET + # 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_SECRET, 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) + + +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"}}}, + ] + 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_SECRET}, [CANARY_SECRET]) + import base64 + + encoded = base64.b64encode(CANARY_SECRET.encode()).decode() + with pytest.raises(egress.EgressViolation): + egress.serialize_checked({"x": encoded}, [CANARY_SECRET]) + assert egress.serialize_checked({"run_id": "r1"}, [CANARY_SECRET]) + + +# -------------------------------------------------------------------------- +# 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, ConnectorSettings(), InMemoryCustomerStorage(PLAIN_BUNDLE), runner=runner + ) + assert ( + result.status == "failed" and result.error_code == "cancelled_by_control_plane" + ) + + +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 = ConnectorSettings( + 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_persists_before_the_new_token_is_used(tmp_path, monkeypatch): + monkeypatch.setenv("OPENADAPT_HOME", str(tmp_path)) + plane = RecordingPlane() + client = _client(plane) + client.control.rotate_recommended = True + settings = ConnectorSettings(control_plane_url="https://cloud.test", token=TOKEN) + save_enrollment(settings) + order: list[str] = [] + + def persist(new_token: str) -> None: + assert client.token == TOKEN # still the old one while persisting + settings.token = new_token + save_enrollment(settings) + order.append("persisted") + + assert maybe_rotate(client, persist, lambda _m: None) + assert client.token == "oaconn_" + "e" * 64 and order == ["persisted"] + assert load_settings().token == client.token + assert (tmp_path / "connector.toml").stat().st_mode & 0o777 == 0o600 + assert not maybe_rotate(client, persist, lambda _m: None) # nothing recommended now + + +# -------------------------------------------------------------------------- +# 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, + ConnectorSettings(), + 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( + bundle_content_digest="b" * 64, + runtime_inputs_digest="c" * 64, + admitted_policy_name="standard", + execution_profile="standard", + approval_source="hosted:program-admission:" + admission_sha, + ) + envelope = ManagedDispatchEnvelope( + run_id=run_id, + bundle_content_digest="b" * 64, + runtime_inputs_digest="c" * 64, + authorization=authorization, + dispatch_binding_sha256=dispatch_binding_sha256(run_id, authorization), + ) + return { + **envelope.model_dump(mode="json"), + "program_admission": { + "schema_version": "openadapt.program-admission-reference/v1", + "admission_sha256": admission_sha, + "public_key_hex": ADMITTER_KEY, + }, + } + + +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", **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 From ea0130ae739cd33d25cb88c0a10407d82c445a47 Mon Sep 17 00:00:00 2001 From: abrichr Date: Thu, 19 Nov 2026 18:35:10 -0500 Subject: [PATCH 02/21] Flow connector: local admission key dir, default secrets ref, daemon-minted idempotent rotation, Linux image and e2e harness --- packages/flow/deploy/connector/.gitignore | 1 + packages/flow/deploy/connector/Dockerfile | 43 ++++++++ .../deploy/connector/e2e/Dockerfile.publisher | 15 +++ .../flow/deploy/connector/e2e/egress_log.py | 40 ++++++++ .../flow/deploy/connector/e2e/entrypoint.sh | 16 +++ .../flow/deploy/connector/e2e/gen_certs.sh | 12 +++ .../flow/deploy/connector/e2e/notes_app.py | 99 +++++++++++++++++++ packages/flow/deploy/connector/entrypoint.sh | 16 +++ packages/flow/openadapt_flow/__main__.py | 45 +++++++-- .../flow/openadapt_flow/connector/client.py | 24 ++++- .../flow/openadapt_flow/connector/config.py | 29 ++++++ .../flow/openadapt_flow/connector/daemon.py | 56 ++++++++--- .../flow/openadapt_flow/connector/egress.py | 4 + .../flow/openadapt_flow/connector/executor.py | 18 +++- packages/flow/tests/test_connector_pilot.py | 49 +++++++-- 15 files changed, 429 insertions(+), 38 deletions(-) create mode 100644 packages/flow/deploy/connector/.gitignore create mode 100644 packages/flow/deploy/connector/Dockerfile create mode 100644 packages/flow/deploy/connector/e2e/Dockerfile.publisher create mode 100644 packages/flow/deploy/connector/e2e/egress_log.py create mode 100755 packages/flow/deploy/connector/e2e/entrypoint.sh create mode 100755 packages/flow/deploy/connector/e2e/gen_certs.sh create mode 100644 packages/flow/deploy/connector/e2e/notes_app.py create mode 100755 packages/flow/deploy/connector/entrypoint.sh 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..e457b32b66 --- /dev/null +++ b/packages/flow/deploy/connector/e2e/Dockerfile.publisher @@ -0,0 +1,15 @@ +# 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 \ + && python -m venv /opt/flow \ + && /opt/flow/bin/pip install --no-cache-dir "openadapt-flow[browser,vision]==${FLOW_VERSION}" \ + && /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..7a09e78adc --- /dev/null +++ b/packages/flow/deploy/connector/e2e/egress_log.py @@ -0,0 +1,40 @@ +"""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..d5375065f6 --- /dev/null +++ b/packages/flow/deploy/connector/e2e/notes_app.py @@ -0,0 +1,99 @@ +"""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(): + seed = [ + {"id": 1, "note": f"{CANARY}-1 synthetic patient Jane Roe DOB 1970-01-01", "list": "demo", "key": "clinic"}, + {"id": 2, "note": f"{CANARY}-2 synthetic MRN 000-111-222", "list": "demo", "key": "clinic"}, + ] + STORE.parent.mkdir(parents=True, exist_ok=True) + STORE.write_text(json.dumps(seed)) + return json.loads(STORE.read_text()) + + +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: + current.append({"id": current[-1]["id"] + 1, "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.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__": + main() 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/openadapt_flow/__main__.py b/packages/flow/openadapt_flow/__main__.py index 4ea9c0e7eb..16218780ee 100644 --- a/packages/flow/openadapt_flow/__main__.py +++ b/packages/flow/openadapt_flow/__main__.py @@ -13401,6 +13401,14 @@ def _repair_store_flag(rp: argparse.ArgumentParser) -> None: "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", @@ -13782,6 +13790,8 @@ def _connector_flags(args: argparse.Namespace) -> dict[str, object]: "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 @@ -13844,6 +13854,11 @@ def _cmd_connector(args: argparse.Namespace) -> int: 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() @@ -13855,18 +13870,29 @@ def persist_token(new_token: str) -> None: 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: - data = client.rotate() - persist_token(data["token"]) - except ConnectorClientError as exc: - print(f"connector rotate-token failed: {exc}") - return 1 + 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 " - f"working at {data.get('previous_token_valid_until', 'once replaced')}." + "token rotated and persisted (0600); the previous token stops within 5 minutes." ) return 0 @@ -13884,12 +13910,17 @@ def persist_token(new_token: str) -> None: 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 9d1b43b74d..b9e4d802f7 100644 --- a/packages/flow/openadapt_flow/connector/client.py +++ b/packages/flow/openadapt_flow/connector/client.py @@ -260,16 +260,25 @@ def ack( raise ConnectorClientError(f"ack failed: {resp.status_code}") return resp.json() if resp.content else {} - def rotate(self) -> dict[str, Any]: - """Swap this connector's token. The caller persists it, then uses it.""" - resp = self._post("/api/connector/rotate", egress.guard_empty()) + 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 = data.get("token") + 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 + return {**data, "token": token} def run_callback(self, body: dict[str, Any], *, run_token: Optional[str]) -> None: """POST the metadata-only run outcome (allow-listed, run-token auth). @@ -290,6 +299,11 @@ def run_callback(self, body: dict[str, Any], *, run_token: Optional[str]) -> Non raise ConnectorClientError(f"run-callback failed: {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") diff --git a/packages/flow/openadapt_flow/connector/config.py b/packages/flow/openadapt_flow/connector/config.py index c8b6c7c506..8cbcce7ced 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 @@ -83,10 +86,18 @@ class ConnectorSettings: #: 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 = "" + #: Optional customer-owned Flow admission key directory (principal + #: registry and public keys, no private keys). When set, a governed child + #: verifies program admissions against it, which also covers admitter-key + #: and agent-policy admissions; otherwise only the pinned key is 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. @@ -152,6 +163,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( @@ -206,6 +218,13 @@ def load_settings( 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, @@ -216,6 +235,13 @@ def load_settings( ) 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", @@ -258,6 +284,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), @@ -269,7 +296,9 @@ def save_enrollment( ("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), diff --git a/packages/flow/openadapt_flow/connector/daemon.py b/packages/flow/openadapt_flow/connector/daemon.py index 7b93cef587..52b2be15f1 100644 --- a/packages/flow/openadapt_flow/connector/daemon.py +++ b/packages/flow/openadapt_flow/connector/daemon.py @@ -269,20 +269,49 @@ 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.""" - if not client.control.rotate_recommended or persist_token is None: - return False - try: - data = client.rotate() - persist_token(data["token"]) # durable before first use - client.token = data["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 later - log(f"[connector] token rotation failed: {type(exc).__name__}") + """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 run_loop( @@ -295,6 +324,7 @@ def run_loop( 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. @@ -376,7 +406,7 @@ def heartbeat() -> None: backoff = min(MAX_BACKOFF_S, backoff * 2) continue apply_control(client.control, active.ids(), log) - maybe_rotate(client, persist_token, log) + maybe_rotate(client, persist_token, log, persist_pending=persist_pending) if not envelope: continue job = _job_from_envelope(client, envelope) diff --git a/packages/flow/openadapt_flow/connector/egress.py b/packages/flow/openadapt_flow/connector/egress.py index d862d9f1a2..9de03759e9 100644 --- a/packages/flow/openadapt_flow/connector/egress.py +++ b/packages/flow/openadapt_flow/connector/egress.py @@ -317,6 +317,10 @@ 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: diff --git a/packages/flow/openadapt_flow/connector/executor.py b/packages/flow/openadapt_flow/connector/executor.py index 9328745a65..0a5fedc7cc 100644 --- a/packages/flow/openadapt_flow/connector/executor.py +++ b/packages/flow/openadapt_flow/connector/executor.py @@ -36,6 +36,7 @@ import hashlib import json import os +import shutil import subprocess import sys import tempfile @@ -510,7 +511,9 @@ def _execute_job( 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) + 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: @@ -582,10 +585,15 @@ def _execute_job( verified_bundle_sha256=observed_sha256, ) key_dir = tmp_path / "jit-keys" - (key_dir / "keys").mkdir(parents=True) - (key_dir / "keys" / "ed25519.pub").write_text( - admission["public_key_hex"] + "\n", encoding="utf-8" - ) + if settings.admission_key_dir: + # The customer's own registry: a private copy per run, so the + # child can never change the operator's trust anchors. + shutil.copytree(settings.admission_key_dir, key_dir, symlinks=False) + else: + (key_dir / "keys").mkdir(parents=True) + (key_dir / "keys" / "ed25519.pub").write_text( + admission["public_key_hex"] + "\n", encoding="utf-8" + ) try: params_file = _write_params_file(job.params, run_dir) diff --git a/packages/flow/tests/test_connector_pilot.py b/packages/flow/tests/test_connector_pilot.py index 9413480b71..643375297b 100644 --- a/packages/flow/tests/test_connector_pilot.py +++ b/packages/flow/tests/test_connector_pilot.py @@ -490,28 +490,61 @@ def runner(argv, run_dir, env): assert not barrier.broken -def test_rotation_persists_before_the_new_token_is_used(tmp_path, monkeypatch): +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 = ConnectorSettings(control_plane_url="https://cloud.test", token=TOKEN) save_enrollment(settings) - order: list[str] = [] + 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 = new_token + settings.token, settings.pending_token = new_token, None save_enrollment(settings) - order.append("persisted") - - assert maybe_rotate(client, persist, lambda _m: None) - assert client.token == "oaconn_" + "e" * 64 and order == ["persisted"] - assert load_settings().token == client.token + 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. # -------------------------------------------------------------------------- From 5b0b1b08384d484575f5e37f86fd6c4bba080a5c Mon Sep 17 00:00:00 2001 From: abrichr Date: Thu, 19 Nov 2026 19:22:55 -0500 Subject: [PATCH 03/21] test(flow): complete restart-safe synthetic connector admission harness --- .../deploy/connector/e2e/Dockerfile.publisher | 5 +- .../flow/deploy/connector/e2e/egress_log.py | 15 +- .../flow/deploy/connector/e2e/notes_app.py | 44 ++++-- packages/flow/deploy/connector/e2e/publish.py | 5 + packages/flow/deploy/connector/e2e/run_e2e.sh | 79 ++++++++++ .../flow/deploy/connector/e2e/teach_admit.py | 144 ++++++++++++++++++ .../systemd/openadapt-connector.service | 38 +++++ 7 files changed, 316 insertions(+), 14 deletions(-) create mode 100644 packages/flow/deploy/connector/e2e/publish.py create mode 100755 packages/flow/deploy/connector/e2e/run_e2e.sh create mode 100644 packages/flow/deploy/connector/e2e/teach_admit.py create mode 100644 packages/flow/deploy/connector/systemd/openadapt-connector.service diff --git a/packages/flow/deploy/connector/e2e/Dockerfile.publisher b/packages/flow/deploy/connector/e2e/Dockerfile.publisher index e457b32b66..a868cf6c2c 100644 --- a/packages/flow/deploy/connector/e2e/Dockerfile.publisher +++ b/packages/flow/deploy/connector/e2e/Dockerfile.publisher @@ -4,9 +4,10 @@ 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 \ +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]==${FLOW_VERSION}" \ + && /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}" diff --git a/packages/flow/deploy/connector/e2e/egress_log.py b/packages/flow/deploy/connector/e2e/egress_log.py index 7a09e78adc..c05391c0c7 100644 --- a/packages/flow/deploy/connector/e2e/egress_log.py +++ b/packages/flow/deploy/connector/e2e/egress_log.py @@ -14,7 +14,11 @@ from mitmproxy import http -ALLOWED = {h.strip() for h in os.environ.get("EGRESS_ALLOWED_HOSTS", "").split(",") if h.strip()} +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"} @@ -30,11 +34,16 @@ def request(flow: http.HTTPFlow) -> None: "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()}, + "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"}) + flow.response = http.Response.make( + 403, b"egress refused by pilot proxy", {"content-type": "text/plain"} + ) diff --git a/packages/flow/deploy/connector/e2e/notes_app.py b/packages/flow/deploy/connector/e2e/notes_app.py index d5375065f6..ebed52e4cc 100644 --- a/packages/flow/deploy/connector/e2e/notes_app.py +++ b/packages/flow/deploy/connector/e2e/notes_app.py @@ -39,15 +39,29 @@ def records() -> list[dict]: if not STORE.exists(): - seed = [ - {"id": 1, "note": f"{CANARY}-1 synthetic patient Jane Roe DOB 1970-01-01", "list": "demo", "key": "clinic"}, - {"id": 2, "note": f"{CANARY}-2 synthetic MRN 000-111-222", "list": "demo", "key": "clinic"}, - ] STORE.parent.mkdir(parents=True, exist_ok=True) - STORE.write_text(json.dumps(seed)) + 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) @@ -59,7 +73,9 @@ def _send(self, code: int, body: bytes, ctype: str) -> None: 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") + 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 == "/": @@ -67,7 +83,9 @@ def do_GET(self) -> None: # noqa: N802 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") + 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 @@ -78,7 +96,10 @@ def do_POST(self) -> None: # noqa: N802 with LOCK: current = records() if note: - current.append({"id": current[-1]["id"] + 1, "note": note, "list": "demo", "key": "clinic"}) + 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!

    ") @@ -96,4 +117,9 @@ def main() -> None: if __name__ == "__main__": - 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/systemd/openadapt-connector.service b/packages/flow/deploy/connector/systemd/openadapt-connector.service new file mode 100644 index 0000000000..e3314b7db2 --- /dev/null +++ b/packages/flow/deploy/connector/systemd/openadapt-connector.service @@ -0,0 +1,38 @@ +# 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; a job mid-run is reaped as uncertain +# by the control plane and never re-run automatically. +KillSignal=SIGINT +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 From afb07ece3da2185fef7ca67341164106fa7b5903 Mon Sep 17 00:00:00 2001 From: abrichr Date: Thu, 19 Nov 2026 19:25:40 -0500 Subject: [PATCH 04/21] docs(flow): describe the customer-run connector controls --- CAPABILITIES.md | 2 +- llms-full.txt | 2 +- packages/flow/docs/commands/09-share-with-cloud/connector.md | 1 + 3 files changed, 3 insertions(+), 2 deletions(-) diff --git a/CAPABILITIES.md b/CAPABILITIES.md index 73a5c32284..e94942aadb 100644 --- a/CAPABILITIES.md +++ b/CAPABILITIES.md @@ -452,7 +452,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 c43236290b..554139e394 100644 --- a/llms-full.txt +++ b/llms-full.txt @@ -886,7 +886,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/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. From 807be87efc98825d736227c53303abb52c1f29b3 Mon Sep 17 00:00:00 2001 From: abrichr Date: Thu, 19 Nov 2026 20:26:18 -0500 Subject: [PATCH 05/21] fix(flow): preserve governed approval policy in connector runs --- .../flow/openadapt_flow/connector/executor.py | 7 ++----- packages/flow/tests/test_connector.py | 19 +++++++++++++++++-- 2 files changed, 19 insertions(+), 7 deletions(-) diff --git a/packages/flow/openadapt_flow/connector/executor.py b/packages/flow/openadapt_flow/connector/executor.py index 0a5fedc7cc..b59687e42e 100644 --- a/packages/flow/openadapt_flow/connector/executor.py +++ b/packages/flow/openadapt_flow/connector/executor.py @@ -242,11 +242,8 @@ 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"] + # 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") diff --git a/packages/flow/tests/test_connector.py b/packages/flow/tests/test_connector.py index 39eaf5ad39..c65601c6e0 100644 --- a/packages/flow/tests/test_connector.py +++ b/packages/flow/tests/test_connector.py @@ -747,8 +747,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(): @@ -964,3 +965,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, ConnectorSettings(), Path("/bundle"), Path("/run"), None) + assert "--approval-mode" not in argv + assert resolve_approval_mode(None) == ApprovalMode.EACH_ITEM From 4be180414ca03510cddf7ffc7fa065a6b1d93af7 Mon Sep 17 00:00:00 2001 From: abrichr Date: Thu, 19 Nov 2026 22:16:14 -0500 Subject: [PATCH 06/21] fix(flow): bind BYOC live execution to exact managed session --- .../flow/openadapt_flow/connector/client.py | 4 +- .../flow/openadapt_flow/connector/config.py | 11 + .../flow/openadapt_flow/connector/executor.py | 154 +++++++++++++- .../flow/openadapt_flow/connector/protocol.py | 191 +++++++++++++++--- .../flow/openadapt_flow/connector/secrets.py | 1 + 5 files changed, 326 insertions(+), 35 deletions(-) diff --git a/packages/flow/openadapt_flow/connector/client.py b/packages/flow/openadapt_flow/connector/client.py index b9e4d802f7..9031e13f16 100644 --- a/packages/flow/openadapt_flow/connector/client.py +++ b/packages/flow/openadapt_flow/connector/client.py @@ -37,9 +37,11 @@ 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" diff --git a/packages/flow/openadapt_flow/connector/config.py b/packages/flow/openadapt_flow/connector/config.py index 8cbcce7ced..4c152c5ac5 100644 --- a/packages/flow/openadapt_flow/connector/config.py +++ b/packages/flow/openadapt_flow/connector/config.py @@ -104,6 +104,9 @@ class ConnectorSettings: 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(",")} @@ -271,6 +274,13 @@ def load_settings( None, "qualification_signers_file", ), + qualification_authority_file=_pick( + flags, + "BYOC_QUALIFICATION_AUTHORITY_FILE", + file_cfg.get("qualification_authority_file"), + None, + "qualification_authority_file", + ), ) @@ -302,6 +312,7 @@ def save_enrollment( ("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 == "": diff --git a/packages/flow/openadapt_flow/connector/executor.py b/packages/flow/openadapt_flow/connector/executor.py index b59687e42e..14194083c2 100644 --- a/packages/flow/openadapt_flow/connector/executor.py +++ b/packages/flow/openadapt_flow/connector/executor.py @@ -36,7 +36,6 @@ import hashlib import json import os -import shutil import subprocess import sys import tempfile @@ -58,6 +57,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 @@ -212,6 +212,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. @@ -242,6 +243,8 @@ def build_run_argv( argv += ["--url", job.target_url] if managed_dispatch_file is not None: argv += ["--managed-dispatch-file", str(managed_dispatch_file)] + 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: @@ -404,8 +407,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 "") @@ -437,6 +444,102 @@ 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) + 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, @@ -499,6 +602,19 @@ def _execute_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 _refused( @@ -583,14 +699,37 @@ def _execute_job( ) key_dir = tmp_path / "jit-keys" if settings.admission_key_dir: - # The customer's own registry: a private copy per run, so the - # child can never change the operator's trust anchors. - shutil.copytree(settings.admission_key_dir, key_dir, symlinks=False) + # 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) @@ -602,6 +741,7 @@ def _execute_job( for name in ( REMOTE_AUTHORITY_URL_ENV, REMOTE_AUTHORITY_TOKEN_ENV, + REMOTE_DISPATCH_SESSION_ID_ENV, "OPENADAPT_JIT_KEY_DIR", "BYOC_CONNECTOR_TOKEN", ): @@ -619,6 +759,9 @@ def _execute_job( 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. @@ -659,6 +802,7 @@ def _execute_job( run_dir, params_file, managed_dispatch_file, + qualification_authority_file, ) if job_cancelled(job.lease_job_id): return _refused( diff --git a/packages/flow/openadapt_flow/connector/protocol.py b/packages/flow/openadapt_flow/connector/protocol.py index 1296f5608a..aa7816ab1b 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,16 +20,20 @@ from __future__ import annotations -import hashlib -import json import re -from typing import Any, Optional +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 = ( @@ -40,9 +44,15 @@ "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): @@ -93,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 @@ -131,6 +141,9 @@ class ByocJob(BaseModel): #: 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 @@ -197,7 +210,25 @@ 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: + raise ByocGovernanceError( + "byoc live dispatch carries unsupported outer 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 = envelope.exact_authorization() @@ -205,7 +236,9 @@ def ensure_governed(self, *, require_run_token: bool = True) -> None: raise ByocGovernanceError( "byoc managed dispatch has an invalid authorization binding" ) from exc - if self.program_admission() is None and not self._qualification_ok(): + 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)" @@ -249,21 +282,56 @@ def ensure_governed(self, *, require_run_token: bool = True) -> None: ) def flow_dispatch(self) -> ManagedDispatchEnvelope: - """The exact six-key Flow envelope inside Cloud's dispatch.""" + """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) or not set(FLOW_DISPATCH_WIRE_KEYS) <= set(raw): + 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") + 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: - return ManagedDispatchEnvelope.model_validate( + envelope = ManagedDispatchEnvelope.model_validate( {key: raw[key] for key in FLOW_DISPATCH_WIRE_KEYS} ) - except ValidationError as exc: + 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 validated program-admission reference of a wrap run, or None.""" + """The exact person-v1 or admitter-v2 reference, without downgrading.""" raw = self.managed_dispatch if not isinstance(raw, dict): return None @@ -271,35 +339,100 @@ def program_admission(self) -> Optional[dict[str, str]]: authorization = raw.get("authorization") if ( "qualification_admission" in raw + or "qualification_admission_sha256" in raw or not isinstance(reference, dict) - or set(reference) - != {"schema_version", "admission_sha256", "public_key_hex"} - or reference.get("schema_version") != PROGRAM_ADMISSION_SCHEMA - or not isinstance(reference.get("admission_sha256"), str) + 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 not isinstance(authorization, dict) - or authorization.get("execution_profile") != "standard" or authorization.get("approval_source") != PROGRAM_ADMISSION_APPROVAL_PREFIX + reference["admission_sha256"] ): return None - return { - "admission_sha256": reference["admission_sha256"], - "public_key_hex": reference["public_key_hex"], - } + 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, + ) - def _qualification_ok(self) -> bool: 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): + 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 - canonical = json.dumps( - admission, sort_keys=True, separators=(",", ":"), ensure_ascii=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 ) - return digest == hashlib.sha256(canonical.encode()).hexdigest() def report_ref(self) -> Optional[str]: """The customer-storage key the report is written to (opaque to us).""" diff --git a/packages/flow/openadapt_flow/connector/secrets.py b/packages/flow/openadapt_flow/connector/secrets.py index 82c28dd3b7..56fc45ff45 100644 --- a/packages/flow/openadapt_flow/connector/secrets.py +++ b/packages/flow/openadapt_flow/connector/secrets.py @@ -40,6 +40,7 @@ "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", From eab484b3f1bb2afb49e1111795e9b4e321b2fc9d Mon Sep 17 00:00:00 2001 From: abrichr Date: Thu, 19 Nov 2026 22:50:19 -0500 Subject: [PATCH 07/21] fix(flow): verify exact BYOC managed authority before handoff --- packages/flow/docs/BYOC_CONNECTOR.md | 103 +-- packages/flow/docs/design/DECOMPOSITION.md | 2 +- packages/flow/openadapt_flow/__main__.py | 252 +------ packages/flow/openadapt_flow/connector/cli.py | 262 ++++++++ .../flow/openadapt_flow/connector/config.py | 7 +- .../flow/openadapt_flow/connector/daemon.py | 4 +- .../flow/openadapt_flow/connector/executor.py | 5 + .../flow/openadapt_flow/connector/protocol.py | 29 +- packages/flow/tests/connector_v3_fixtures.py | 451 +++++++++++++ packages/flow/tests/test_connector.py | 189 ++++-- packages/flow/tests/test_connector_pilot.py | 84 ++- .../flow/tests/test_connector_v3_contract.py | 625 ++++++++++++++++++ 12 files changed, 1632 insertions(+), 381 deletions(-) create mode 100644 packages/flow/openadapt_flow/connector/cli.py create mode 100644 packages/flow/tests/connector_v3_fixtures.py create mode 100644 packages/flow/tests/test_connector_v3_contract.py diff --git a/packages/flow/docs/BYOC_CONNECTOR.md b/packages/flow/docs/BYOC_CONNECTOR.md index a3cc404e9c..8229d4f896 100644 --- a/packages/flow/docs/BYOC_CONNECTOR.md +++ b/packages/flow/docs/BYOC_CONNECTOR.md @@ -78,15 +78,55 @@ Cloud token creation is authenticated and organization-scoped in the dashboard. 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 @@ -101,34 +141,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/design/DECOMPOSITION.md b/packages/flow/docs/design/DECOMPOSITION.md index 48b8fd169f..009b2adbc4 100644 --- a/packages/flow/docs/design/DECOMPOSITION.md +++ b/packages/flow/docs/design/DECOMPOSITION.md @@ -604,7 +604,7 @@ PR #2280 raised `replayer.py` by 12 lines: the call sites of the clock-text chec | File | Line budget | |---|---:| | `packages/flow/openadapt_flow/runtime/replayer.py` | 20057 | -| `packages/flow/openadapt_flow/__main__.py` | 14471 | +| `packages/flow/openadapt_flow/__main__.py` | 14335 | | `packages/flow/openadapt_flow/qualification.py` | 5963 | | `packages/flow/openadapt_flow/ir.py` | 6711 | | `packages/desktop/openadapt_desktop/dispatch.py` | 6524 | diff --git a/packages/flow/openadapt_flow/__main__.py b/packages/flow/openadapt_flow/__main__.py index dc75def5de..f18908d24a 100644 --- a/packages/flow/openadapt_flow/__main__.py +++ b/packages/flow/openadapt_flow/__main__.py @@ -13229,105 +13229,9 @@ 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) - # --- 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=_cmd_connector) - - 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=_cmd_connector) + from openadapt_flow.connector.cli import register_connector_parser - 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=_cmd_connector) + register_connector_parser(sub, _cmd_connector) from openadapt_flow.cli_admit import register_admit_parser from openadapt_flow.cli_api import register_api_parser @@ -13676,155 +13580,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", - "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 - } - + """Keep the historical connector settings helper importable.""" + from openadapt_flow.connector.cli import _connector_flags as collect -def _cmd_connector(args: argparse.Namespace) -> int: - """The BYOC connector: enroll this machine, or run governed jobs locally. + return collect(args) - 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 +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, - 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() + return command(args) def _cmd_business_decisions_serve(args: argparse.Namespace) -> int: diff --git a/packages/flow/openadapt_flow/connector/cli.py b/packages/flow/openadapt_flow/connector/cli.py new file mode 100644 index 0000000000..210e435279 --- /dev/null +++ b/packages/flow/openadapt_flow/connector/cli.py @@ -0,0 +1,262 @@ +"""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) + + +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/config.py b/packages/flow/openadapt_flow/connector/config.py index 4c152c5ac5..84a48e8d72 100644 --- a/packages/flow/openadapt_flow/connector/config.py +++ b/packages/flow/openadapt_flow/connector/config.py @@ -93,10 +93,9 @@ class ConnectorSettings: #: 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 = "" - #: Optional customer-owned Flow admission key directory (principal - #: registry and public keys, no private keys). When set, a governed child - #: verifies program admissions against it, which also covers admitter-key - #: and agent-policy admissions; otherwise only the pinned key is staged. + #: 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 diff --git a/packages/flow/openadapt_flow/connector/daemon.py b/packages/flow/openadapt_flow/connector/daemon.py index 52b2be15f1..d701aba81c 100644 --- a/packages/flow/openadapt_flow/connector/daemon.py +++ b/packages/flow/openadapt_flow/connector/daemon.py @@ -134,7 +134,9 @@ def handle_job( callback_body = phi_free_callback_body(job, result) except Exception: # noqa: BLE001 - nothing unchecked is ever sent callback_body = None - for attempt in range(CALLBACK_ATTEMPTS if callback_body is not None else 0): + for attempt in range(CALLBACK_ATTEMPTS): + if callback_body is None: + break try: client.run_callback(callback_body, run_token=job.run_token) callback_accepted = True diff --git a/packages/flow/openadapt_flow/connector/executor.py b/packages/flow/openadapt_flow/connector/executor.py index 14194083c2..e2f839f831 100644 --- a/packages/flow/openadapt_flow/connector/executor.py +++ b/packages/flow/openadapt_flow/connector/executor.py @@ -433,6 +433,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 @@ -462,6 +463,10 @@ def _verify_program_reference(job: ByocJob, bundle: Path, key_dir: Path) -> None "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": diff --git a/packages/flow/openadapt_flow/connector/protocol.py b/packages/flow/openadapt_flow/connector/protocol.py index aa7816ab1b..e38494af2f 100644 --- a/packages/flow/openadapt_flow/connector/protocol.py +++ b/packages/flow/openadapt_flow/connector/protocol.py @@ -71,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 @@ -92,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 @@ -165,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 " @@ -210,9 +213,13 @@ 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: + 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 outer fields" + "byoc live dispatch carries unsupported governance fields" ) if self.managed_dispatch is None or not self.managed_delivery_authority_url: raise ByocGovernanceError( @@ -296,6 +303,8 @@ def flow_dispatch(self) -> ManagedDispatchEnvelope: ) 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 @@ -451,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/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/test_connector.py b/packages/flow/tests/test_connector.py index c65601c6e0..732d450a5a 100644 --- a/packages/flow/tests/test_connector.py +++ b/packages/flow/tests/test_connector.py @@ -17,12 +17,11 @@ from __future__ import annotations +import copy import hashlib -import io import json import os import stat -import zipfile from pathlib import Path import httpx @@ -56,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, + } + ) # -------------------------------------------------------------------------- @@ -99,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, @@ -119,14 +144,9 @@ def _managed_dispatch(*, run_id: str | None = None) -> dict: authorization=authorization, dispatch_binding_sha256=dispatch_binding_sha256(exact_run_id, authorization), ) - # Cloud's dispatch: the six Flow wire keys plus the authority reference. - qualification = {"schema_version": "test", "campaign": "synthetic"} return { **envelope.model_dump(mode="json"), - "qualification_admission": qualification, - "qualification_admission_sha256": hashlib.sha256( - json.dumps(qualification, sort_keys=True, separators=(",", ":")).encode() - ).hexdigest(), + "program_admission": copy.deepcopy(_CASE["dispatch"]["program_admission"]), } @@ -163,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( @@ -181,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( @@ -203,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"] == _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"} @@ -384,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: @@ -450,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" @@ -473,7 +506,7 @@ 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 @@ -485,7 +518,7 @@ def test_report_write_failure_lease_is_not_acked_failed(): 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, @@ -604,7 +637,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), ) @@ -616,12 +649,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", @@ -661,7 +693,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. @@ -686,7 +718,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 @@ -701,7 +733,7 @@ def test_child_failure_after_archive_verification_carries_verified_digest(): def runner(argv, run_dir: Path, _env) -> RunOutcome: raise RuntimeError("child unavailable") - result = execute_job(job, ConnectorSettings(), storage, runner=runner) + result = execute_job(job, _settings(), storage, runner=runner) assert result.status == "failed" assert result.verified_bundle_sha256 == _BUNDLE_SHA256 callback = phi_free_callback_body(job, result) @@ -736,7 +768,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")) @@ -762,7 +794,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 @@ -852,8 +884,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() @@ -862,6 +899,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(): @@ -871,7 +940,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, @@ -914,7 +983,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, @@ -949,7 +1018,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, @@ -976,6 +1045,6 @@ def test_every_connector_substrate_preserves_the_governed_approval_default(targe job = parse_job( _payload(target_kind=target, target_url=None, allowed_hosts=[], params={}) ) - argv = build_run_argv(job, ConnectorSettings(), Path("/bundle"), Path("/run"), None) + 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_pilot.py b/packages/flow/tests/test_connector_pilot.py index 643375297b..31e1cb4772 100644 --- a/packages/flow/tests/test_connector_pilot.py +++ b/packages/flow/tests/test_connector_pilot.py @@ -9,6 +9,7 @@ from __future__ import annotations +import copy import hashlib import hmac import io @@ -51,6 +52,7 @@ 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_SECRET = "ZQX-CANARY-SECRET-p4ssw0rd" @@ -66,10 +68,41 @@ def _zip(entries: dict[str, bytes]) -> bytes: return stream.getvalue() -PLAIN_BUNDLE = _zip({"workflow.json": b"{}"}) +_CASE = None +PLAIN_BUNDLE = b"" -def _payload(bundle: bytes = PLAIN_BUNDLE, **overrides): +@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", @@ -92,6 +125,11 @@ def _payload(bundle: bytes = PLAIN_BUNDLE, **overrides): "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 @@ -214,7 +252,7 @@ def test_no_canary_leaves_the_machine(tmp_path, outcome_kind): } ) client = _client(plane, egress_audit_log=str(tmp_path / "egress.jsonl")) - settings = ConnectorSettings( + settings = _configured_settings( control_plane_url="https://cloud.test", token=TOKEN, poll_wait_s=0, @@ -418,7 +456,10 @@ def runner(argv, run_dir, env): # pragma: no cover - must not run raise AssertionError("child started after cancel") result = execute_job( - job, ConnectorSettings(), InMemoryCustomerStorage(PLAIN_BUNDLE), runner=runner + job, + _configured_settings(), + InMemoryCustomerStorage(PLAIN_BUNDLE), + runner=runner, ) assert ( result.status == "failed" and result.error_code == "cancelled_by_control_plane" @@ -468,7 +509,7 @@ def runner(argv, run_dir, env): } return RunOutcome(returncode=0, report=report) - settings = ConnectorSettings( + settings = _configured_settings( control_plane_url="https://cloud.test", token=TOKEN, poll_wait_s=0, @@ -495,7 +536,7 @@ def test_rotation_mints_locally_and_sends_only_a_hash(tmp_path, monkeypatch): plane = RecordingPlane() client = _client(plane) client.control.rotate_recommended = True - settings = ConnectorSettings(control_plane_url="https://cloud.test", token=TOKEN) + settings = _configured_settings(control_plane_url="https://cloud.test", token=TOKEN) save_enrollment(settings) events: list[str] = [] @@ -575,7 +616,7 @@ 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, - ConnectorSettings(), + _configured_settings(), InMemoryCustomerStorage(PLAIN_BUNDLE), runner=lambda *a: (_ for _ in ()).throw(AssertionError("ran")), ) @@ -603,28 +644,21 @@ def _wrap_dispatch(run_id: str, admission_sha: str) -> dict: from openadapt_flow.runner.protocol import dispatch_binding_sha256 from openadapt_flow.runtime.authorization import GovernedRunAuthorization - authorization = GovernedRunAuthorization( - bundle_content_digest="b" * 64, - runtime_inputs_digest="c" * 64, - admitted_policy_name="standard", - execution_profile="standard", - approval_source="hosted:program-admission:" + admission_sha, + 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="b" * 64, - runtime_inputs_digest="c" * 64, + 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), ) - return { - **envelope.model_dump(mode="json"), - "program_admission": { - "schema_version": "openadapt.program-admission-reference/v1", - "admission_sha256": admission_sha, - "public_key_hex": ADMITTER_KEY, - }, - } + 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): @@ -638,7 +672,9 @@ def _wrap_job(admission_sha: str | None = None): def _settings(**kw): - return ConnectorSettings(control_plane_url="https://cloud.test", **kw) + return ConnectorSettings( + control_plane_url="https://cloud.test", org_id="org_pilot", **kw + ) def test_unpinned_admitter_key_is_refused(): 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 From 2a853d9cb2d35f1788fab2a9e79a92041b1daf8a Mon Sep 17 00:00:00 2001 From: abrichr Date: Fri, 20 Nov 2026 17:59:50 -0500 Subject: [PATCH 08/21] test(flow): run main's connector service and privacy controls under closed egress Main's Windows service (#2292) and error-privacy (52205c00c) tests predate this branch's closed callback allow-list and v3 job authority. Their callback bodies now carry the identifiers the allow-list requires, the refusal test checks the closed governance_refused ack code instead of a free-text error, and the stop-during-a-job control uses one worker and a stand-in job handler, since managed authority is covered by the connector contract tests. --- .../test_connector_client_error_privacy.py | 16 ++++++++-- .../tests/test_connector_windows_service.py | 30 +++++++++++++++++-- 2 files changed, 41 insertions(+), 5 deletions(-) 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_windows_service.py b/packages/flow/tests/test_connector_windows_service.py index e8b7f9f06a..afa13d410f 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,26 @@ def runner(*args): 0, {"execution_target_kind": "web", "success": True, "model_calls": 0} ) + from openadapt_flow.connector import daemon + + def handle_job(client, settings, job, *, runner, **_kwargs): + # Managed authority is covered by the connector contract tests; this + # control is about the service stop: the in-flight job still reports + # and acknowledges before serve() returns. + runner() + client.run_callback( + { + "run_id": job.run_id, + "org_id": job.org_id, + "workflow_id": job.workflow_id, + "status": "success", + }, + run_token=job.run_token, + ) + client.ack(job.lease_job_id, "done") + return {} + + monkeypatch.setattr(daemon, "handle_job", handle_job) logger, redactor = ws.build_logger(config, name="test.ws.finish") assert ( ws.serve( From 574aa7cb33f37ed87417c9219ce87c29afe13e54 Mon Sep 17 00:00:00 2001 From: abrichr Date: Fri, 20 Nov 2026 18:18:16 -0500 Subject: [PATCH 09/21] test(flow): expect the closed governance_refused ack code in the Windows stub check --- packages/flow/tests/connector_stub/wait_for_stub.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) 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" From 80df335d286bb7af4ff83210f43407f2e5f7f264 Mon Sep 17 00:00:00 2001 From: abrichr Date: Fri, 20 Nov 2026 18:21:52 -0500 Subject: [PATCH 10/21] chore: pin the connector pilot's synthetic canary as a reviewed gitleaks false positive --- .gitleaksignore | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.gitleaksignore b/.gitleaksignore index 66a580b67f..8539c5eb99 100644 --- a/.gitleaksignore +++ b/.gitleaksignore @@ -208,3 +208,6 @@ 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 From 63eedfe9b78dc7f452154a1543fc0518e616e31f Mon Sep 17 00:00:00 2001 From: abrichr Date: Fri, 20 Nov 2026 18:39:19 -0500 Subject: [PATCH 11/21] test(flow): run the service stop control through the production handle_job Stand in only execute_job, so the in-flight job's callback and ack come from the real handler. Pin TLS 1.2 as the floor of the synthetic e2e notes app, as the other synthetic HTTPS fixtures do. --- .../flow/deploy/connector/e2e/notes_app.py | 1 + .../tests/test_connector_windows_service.py | 24 +++++++------------ 2 files changed, 9 insertions(+), 16 deletions(-) diff --git a/packages/flow/deploy/connector/e2e/notes_app.py b/packages/flow/deploy/connector/e2e/notes_app.py index ebed52e4cc..dc636d056b 100644 --- a/packages/flow/deploy/connector/e2e/notes_app.py +++ b/packages/flow/deploy/connector/e2e/notes_app.py @@ -110,6 +110,7 @@ def log_message(self, fmt: str, *args: object) -> None: 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) diff --git a/packages/flow/tests/test_connector_windows_service.py b/packages/flow/tests/test_connector_windows_service.py index afa13d410f..66f0c1f7c2 100644 --- a/packages/flow/tests/test_connector_windows_service.py +++ b/packages/flow/tests/test_connector_windows_service.py @@ -453,25 +453,17 @@ def runner(*args): ) from openadapt_flow.connector import daemon + from openadapt_flow.connector.executor import ExecutionResult - def handle_job(client, settings, job, *, runner, **_kwargs): - # Managed authority is covered by the connector contract tests; this - # control is about the service stop: the in-flight job still reports - # and acknowledges before serve() returns. + 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() - client.run_callback( - { - "run_id": job.run_id, - "org_id": job.org_id, - "workflow_id": job.workflow_id, - "status": "success", - }, - run_token=job.run_token, - ) - client.ack(job.lease_job_id, "done") - return {} + return ExecutionResult("success", {}, None, job.report_ref()) - monkeypatch.setattr(daemon, "handle_job", handle_job) + monkeypatch.setattr(daemon, "execute_job", execute_job) logger, redactor = ws.build_logger(config, name="test.ws.finish") assert ( ws.serve( From 9f2ad8132127fa64f6fb8af4c029a058969b9b29 Mon Sep 17 00:00:00 2001 From: abrichr Date: Fri, 20 Nov 2026 21:24:49 -0500 Subject: [PATCH 12/21] fix(flow): let digest-named keys of the closed outcome envelope leave the connector The egress guard's key pattern banned digits, but the closed outcome envelope's own fields include workflow_contract_sha256, step_contract_sha256 and contract_sha256. Every real envelope, VERIFIED ones included, was refused, so the run reported egress_refused after it had saved and been checked. Keys now allow digits; every string value is still a short token. --- .../flow/openadapt_flow/connector/egress.py | 5 +- .../connector_outcome_envelope_verified.json | 79 +++++++++++++++++++ packages/flow/tests/test_connector_pilot.py | 54 +++++++++++++ 3 files changed, 137 insertions(+), 1 deletion(-) create mode 100644 packages/flow/tests/fixtures/connector_outcome_envelope_verified.json diff --git a/packages/flow/openadapt_flow/connector/egress.py b/packages/flow/openadapt_flow/connector/egress.py index 9de03759e9..f4712088f7 100644 --- a/packages/flow/openadapt_flow/connector/egress.py +++ b/packages/flow/openadapt_flow/connector/egress.py @@ -51,6 +51,9 @@ class EgressViolation(ValueError): _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( @@ -130,7 +133,7 @@ def _closed_tree(value: Any, field: str, depth: int = 0) -> Any: if isinstance(value, dict): out: dict[str, Any] = {} for key, item in value.items(): - if not isinstance(key, str) or not _LABEL.fullmatch(key): + 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 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_pilot.py b/packages/flow/tests/test_connector_pilot.py index 31e1cb4772..ca2c35bc31 100644 --- a/packages/flow/tests/test_connector_pilot.py +++ b/packages/flow/tests/test_connector_pilot.py @@ -781,3 +781,57 @@ def test_readback_evidence_is_closed(): ).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) From 84dd88cc772cf44b9193e2b9e038700321b626a1 Mon Sep 17 00:00:00 2001 From: abrichr Date: Fri, 20 Nov 2026 21:39:59 -0500 Subject: [PATCH 13/21] fix(flow): read the connector's read-back labels from the v1 effect receipt verify-run writes openadapt.effect-receipt/v1, which nests outcome, effect_verdict and verification_tier under "receipt". The connector read them from the top level, found none, and dropped the independent read-back from every callback, so Cloud could never confirm a wrap run. --- .../flow/openadapt_flow/connector/executor.py | 6 +++- packages/flow/tests/test_connector_pilot.py | 29 +++++++++++++++++++ 2 files changed, 34 insertions(+), 1 deletion(-) diff --git a/packages/flow/openadapt_flow/connector/executor.py b/packages/flow/openadapt_flow/connector/executor.py index e2f839f831..81cf516e55 100644 --- a/packages/flow/openadapt_flow/connector/executor.py +++ b/packages/flow/openadapt_flow/connector/executor.py @@ -127,8 +127,12 @@ def wrap_readback_evidence( 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: document.get(k) for k in ("outcome", "effect_verdict", "verification_tier") + k: source.get(k) for k in ("outcome", "effect_verdict", "verification_tier") } for value in labels.values(): if ( diff --git a/packages/flow/tests/test_connector_pilot.py b/packages/flow/tests/test_connector_pilot.py index ca2c35bc31..54ed6ebd30 100644 --- a/packages/flow/tests/test_connector_pilot.py +++ b/packages/flow/tests/test_connector_pilot.py @@ -835,3 +835,32 @@ def body(envelope): except egress.EgressViolation: return assert CANARY_RECORD not in json.dumps(sent) + + +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 From 2af77e0d7c52729bf46472ac6829e9c028d94c67 Mon Sep 17 00:00:00 2001 From: abrichr Date: Fri, 20 Nov 2026 21:57:12 -0500 Subject: [PATCH 14/21] style(flow): format the connector pilot tests --- packages/flow/tests/test_connector_pilot.py | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/packages/flow/tests/test_connector_pilot.py b/packages/flow/tests/test_connector_pilot.py index 54ed6ebd30..e41d2241d5 100644 --- a/packages/flow/tests/test_connector_pilot.py +++ b/packages/flow/tests/test_connector_pilot.py @@ -783,7 +783,9 @@ def test_readback_evidence_is_closed(): assert wrap_readback_evidence(good, "") is None -_VERIFIED_ENVELOPE = Path(__file__).parent / "fixtures" / "connector_outcome_envelope_verified.json" +_VERIFIED_ENVELOPE = ( + Path(__file__).parent / "fixtures" / "connector_outcome_envelope_verified.json" +) def test_a_verified_outcome_envelope_passes_the_egress_guard(): @@ -803,7 +805,10 @@ def test_a_verified_outcome_envelope_passes_the_egress_guard(): } sent = egress.guard_callback(body) assert sent["outcome"]["outcome"] == "VERIFIED" - assert sent["outcome"]["workflow_contract_sha256"] == envelope["workflow_contract_sha256"] + assert ( + sent["outcome"]["workflow_contract_sha256"] + == envelope["workflow_contract_sha256"] + ) def test_the_outcome_envelope_still_refuses_free_text(): From 97eda5aaa024c4dfffcc672936425ebf030086c9 Mon Sep 17 00:00:00 2001 From: abrichr Date: Fri, 20 Nov 2026 21:59:47 -0500 Subject: [PATCH 15/21] feat(flow): send the stored report's SHA-256 from the connector Cloud seals a run's outcome with the report digest it receives, which is what makes a receipt possible. The connector now sends metrics.report_sha256, the SHA-256 of the exact bytes it wrote to customer storage, and the egress guard accepts only a 64-hex digest there. The report itself never leaves. --- .../flow/openadapt_flow/connector/egress.py | 6 ++- .../flow/openadapt_flow/connector/executor.py | 10 +++- .../flow/openadapt_flow/connector/storage.py | 7 ++- packages/flow/tests/test_connector_pilot.py | 47 ++++++++++++++++++- 4 files changed, 65 insertions(+), 5 deletions(-) diff --git a/packages/flow/openadapt_flow/connector/egress.py b/packages/flow/openadapt_flow/connector/egress.py index f4712088f7..37534ac4f6 100644 --- a/packages/flow/openadapt_flow/connector/egress.py +++ b/packages/flow/openadapt_flow/connector/egress.py @@ -9,7 +9,8 @@ * 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); +* 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; @@ -189,6 +190,9 @@ def _metrics(value: Any) -> dict[str, Any]: 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) diff --git a/packages/flow/openadapt_flow/connector/executor.py b/packages/flow/openadapt_flow/connector/executor.py index e2f839f831..a4f46f797f 100644 --- a/packages/flow/openadapt_flow/connector/executor.py +++ b/packages/flow/openadapt_flow/connector/executor.py @@ -48,7 +48,11 @@ from openadapt_flow.connector.config import ConnectorSettings from openadapt_flow.connector.protocol import ByocGovernanceError, ByocJob from openadapt_flow.connector.secrets import LocalSecretStore, SecretStoreError -from openadapt_flow.connector.storage import CustomerStorage, extract_bundle_archive +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 ( @@ -910,6 +914,10 @@ def _execute_job( 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, 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/tests/test_connector_pilot.py b/packages/flow/tests/test_connector_pilot.py index ca2c35bc31..4c30a58a3a 100644 --- a/packages/flow/tests/test_connector_pilot.py +++ b/packages/flow/tests/test_connector_pilot.py @@ -289,6 +289,19 @@ def runner(argv, run_dir: Path, child_env) -> RunOutcome: # 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(): @@ -314,6 +327,8 @@ def test_guard_callback_refuses_everything_off_the_list(): {**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): @@ -783,7 +798,9 @@ def test_readback_evidence_is_closed(): assert wrap_readback_evidence(good, "") is None -_VERIFIED_ENVELOPE = Path(__file__).parent / "fixtures" / "connector_outcome_envelope_verified.json" +_VERIFIED_ENVELOPE = ( + Path(__file__).parent / "fixtures" / "connector_outcome_envelope_verified.json" +) def test_a_verified_outcome_envelope_passes_the_egress_guard(): @@ -803,7 +820,10 @@ def test_a_verified_outcome_envelope_passes_the_egress_guard(): } sent = egress.guard_callback(body) assert sent["outcome"]["outcome"] == "VERIFIED" - assert sent["outcome"]["workflow_contract_sha256"] == envelope["workflow_contract_sha256"] + assert ( + sent["outcome"]["workflow_contract_sha256"] + == envelope["workflow_contract_sha256"] + ) def test_the_outcome_envelope_still_refuses_free_text(): @@ -835,3 +855,26 @@ def 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"] From 9435a657f3eacf26fa8c63664b25f37a7f80ffef Mon Sep 17 00:00:00 2001 From: abrichr Date: Fri, 20 Nov 2026 23:21:50 -0500 Subject: [PATCH 16/21] Halt when callback egress is refused after child handoff --- .../flow/openadapt_flow/connector/daemon.py | 52 ++++++++----- .../flow/openadapt_flow/connector/executor.py | 49 ++++++++++-- packages/flow/tests/test_connector.py | 77 ++++++++++++++++++- 3 files changed, 149 insertions(+), 29 deletions(-) diff --git a/packages/flow/openadapt_flow/connector/daemon.py b/packages/flow/openadapt_flow/connector/daemon.py index d701aba81c..d1bc4ab28f 100644 --- a/packages/flow/openadapt_flow/connector/daemon.py +++ b/packages/flow/openadapt_flow/connector/daemon.py @@ -105,6 +105,14 @@ def handle_job( 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( @@ -114,14 +122,16 @@ def handle_job( 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", + "halt" if child_bundle_sha256 else "failed", {}, + {"present": True} if child_bundle_sha256 else None, None, - job.report_ref(), - f"{type(exc).__name__}", + type(exc).__name__, + verified_bundle_sha256=child_bundle_sha256, error_code="connector_exception", ) @@ -134,27 +144,33 @@ def handle_job( callback_body = phi_free_callback_body(job, result) except Exception: # noqa: BLE001 - nothing unchecked is ever sent callback_body = None - for attempt in range(CALLBACK_ATTEMPTS): - if callback_body is None: - break + 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: - # The body would carry something off the allow-list. Never retry - # it; report the run as a plain failure instead. - callback_body = phi_free_callback_body( - job, - ExecutionResult( - "failed", {}, None, None, None, error_code="egress_refused" - ), + 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", ) - result.error_code = "egress_refused" - result.status = "failed" + 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" diff --git a/packages/flow/openadapt_flow/connector/executor.py b/packages/flow/openadapt_flow/connector/executor.py index 81cf516e55..4cbe796837 100644 --- a/packages/flow/openadapt_flow/connector/executor.py +++ b/packages/flow/openadapt_flow/connector/executor.py @@ -257,16 +257,23 @@ def build_run_argv( 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: job_id = getattr(_CURRENT, "job_id", None) - proc = subprocess.Popen( # nosec - fixed argv and exact process-local env - argv, - stdout=subprocess.DEVNULL, - stderr=subprocess.DEVNULL, - env=dict(child_env), - ) + try: + proc = subprocess.Popen( # nosec - fixed argv and exact process-local env + argv, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + env=dict(child_env), + ) + except OSError as exc: + raise _ChildNotStarted(type(exc).__name__) from exc if job_id: with _CHILDREN.lock: _CHILDREN.procs[job_id] = proc @@ -557,6 +564,7 @@ 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. @@ -574,6 +582,7 @@ def execute_job( runner=runner, require_run_token=require_run_token, on_secrets=on_secrets, + on_child_start=on_child_start, ) finally: _CURRENT.job_id = None @@ -593,6 +602,7 @@ def _execute_job( 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: @@ -820,7 +830,6 @@ def _execute_job( "cancelled before the governed child started", verified_bundle_sha256=observed_sha256, ) - outcome = runner(argv, run_dir, child_env) except Exception as exc: return _refused( job, @@ -829,6 +838,32 @@ def _execute_job( 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( + "halt", + {}, + {"present": True}, + None, + 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 diff --git a/packages/flow/tests/test_connector.py b/packages/flow/tests/test_connector.py index 732d450a5a..b70bfc6fb8 100644 --- a/packages/flow/tests/test_connector.py +++ b/packages/flow/tests/test_connector.py @@ -512,6 +512,64 @@ def runner(argv, run_dir: Path, _env) -> RunOutcome: 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()) @@ -726,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) + record = tmp_path / "synthetic-record" - def runner(argv, run_dir: Path, _env) -> RunOutcome: - raise RuntimeError("child unavailable") + 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 == "failed" + 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 From 6d7e32b12990f8096c7db07d30b3bf81ca2029ac Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 10:54:26 -0500 Subject: [PATCH 17/21] fix(connector): a cancel that kills a started child halts as outcome unknown A control-plane cancel that arrives after the governed child started terminated a run that may already have written. It was reported failed, so a re-run could repeat the write. With no terminal report from the child it now halts with child_outcome_unknown (halt present), as when the run boundary returns no outcome; a cancel after the child reported keeps the child's own outcome. --- .../flow/openadapt_flow/connector/executor.py | 30 ++++++++++++-- packages/flow/tests/test_connector_pilot.py | 41 +++++++++++++++++++ 2 files changed, 67 insertions(+), 4 deletions(-) diff --git a/packages/flow/openadapt_flow/connector/executor.py b/packages/flow/openadapt_flow/connector/executor.py index fc5849da09..dd6e746de8 100644 --- a/packages/flow/openadapt_flow/connector/executor.py +++ b/packages/flow/openadapt_flow/connector/executor.py @@ -329,6 +329,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.""" @@ -872,10 +882,18 @@ def _execute_job( status = status_from_report(outcome.returncode, report) error_code: Optional[str] = None report_target_kind = report.get("execution_target_kind") - if job_cancelled(job.lease_job_id): - status = "failed" - error_code = "cancelled_by_control_plane" - outcome_error = "cancelled by the control plane while running" + cancelled = job_cancelled(job.lease_job_id) + if cancelled and not _reported_terminal_outcome(report): + # The cancel terminated a child that had already started, and it + # left no terminal report: a write may have landed. That is not a + # failure (a re-run could repeat the write); it stops for + # reconciliation, like a child whose outcome never came back. + status = "halt" + error_code = "child_outcome_unknown" + outcome_error = ( + "cancelled by the control plane while running; the governed " + "child left no terminal report, so a write may have landed" + ) elif report_target_kind != job.target_kind: status = "failed" error_code = "target_kind_mismatch" @@ -884,6 +902,8 @@ def _execute_job( "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" @@ -924,6 +944,8 @@ def _execute_job( # 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. diff --git a/packages/flow/tests/test_connector_pilot.py b/packages/flow/tests/test_connector_pilot.py index a56d6671f5..3eddc1738d 100644 --- a/packages/flow/tests/test_connector_pilot.py +++ b/packages/flow/tests/test_connector_pilot.py @@ -481,6 +481,47 @@ def runner(argv, run_dir, env): # pragma: no cover - must not run ) +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 + + def test_concurrency_runs_up_to_the_server_cap(tmp_path): plane = RecordingPlane( control={ From fc33b88c606e7ba3baead9244708ff4b6d657c97 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 23:44:00 -0500 Subject: [PATCH 18/21] fix(connector): a cancel that kills a child after it reported success is uncertain, not failed fail-open class: lost-outcome-as-failure. A cancel's SIGTERM can reach a child that already wrote a VERIFIED (or legacy success) report but had not exited, for example while it attaches a cloud seal. The nonzero exit made status_from_report call the run failed although the write landed. When the job was cancelled, the exit is nonzero and the report claims success, the run now halts with child_outcome_unknown, like a cancel that left no report. --- .../flow/openadapt_flow/connector/executor.py | 19 +++++++++-- packages/flow/tests/test_connector_pilot.py | 32 +++++++++++++++++++ 2 files changed, 49 insertions(+), 2 deletions(-) diff --git a/packages/flow/openadapt_flow/connector/executor.py b/packages/flow/openadapt_flow/connector/executor.py index dd6e746de8..414f716136 100644 --- a/packages/flow/openadapt_flow/connector/executor.py +++ b/packages/flow/openadapt_flow/connector/executor.py @@ -883,7 +883,21 @@ def _execute_job( error_code: Optional[str] = None report_target_kind = report.get("execution_target_kind") cancelled = job_cancelled(job.lease_job_id) - if cancelled and not _reported_terminal_outcome(report): + # A cancel can kill a child that already reported success but had not + # exited (a seal or callback still running): the nonzero exit then + # reads as a failure although the write landed. Treat that like a + # missing report (fail-open class: lost-outcome-as-failure). + killed_after_success = ( + cancelled + and outcome.returncode != 0 + and ( + report.get("execution_outcome") == "VERIFIED" + or report.get("success") is True + ) + ) + if cancelled and ( + not _reported_terminal_outcome(report) or killed_after_success + ): # The cancel terminated a child that had already started, and it # left no terminal report: a write may have landed. That is not a # failure (a re-run could repeat the write); it stops for @@ -892,7 +906,8 @@ def _execute_job( error_code = "child_outcome_unknown" outcome_error = ( "cancelled by the control plane while running; the governed " - "child left no terminal report, so a write may have landed" + "child left no terminal report or was killed after reporting " + "success, so a write may have landed" ) elif report_target_kind != job.target_kind: status = "failed" diff --git a/packages/flow/tests/test_connector_pilot.py b/packages/flow/tests/test_connector_pilot.py index 3eddc1738d..a9cecc6bdf 100644 --- a/packages/flow/tests/test_connector_pilot.py +++ b/packages/flow/tests/test_connector_pilot.py @@ -522,6 +522,38 @@ def runner(argv, run_dir, env): 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 + + def test_concurrency_runs_up_to_the_server_cap(tmp_path): plane = RecordingPlane( control={ From f3b737d4c7a117a93a59ba6c2a386f2c9252ed7d Mon Sep 17 00:00:00 2001 From: abrichr Date: Sun, 22 Nov 2026 00:09:52 -0500 Subject: [PATCH 19/21] fix(connector): a stop or kill mid-run is uncertain, never a clean failure fail-open class: lost-outcome-as-failure. The governed child shared the daemon's process group, and the unit's SIGINT (or an operator's Ctrl-C) killed it. The daemon then drained, sent a callback and acked the job `failed` with no cancel recorded, although a write may have landed. - The child now starts in its own session (start_new_session=True). On shutdown the daemon stops every active child through cancel_job before draining. In an inline run, an interrupt during the wait stops the child and propagates, so the lease stays unacked. - General rule: once the child has started, a nonzero exit with no report, or with a report that claims success (VERIFIED, success true or terminal_outcome success), halts with child_outcome_unknown and halt={"present": true}, cancelled or not. Refusal and halt reports keep their own outcome. - The systemd unit sets KillMode=mixed. The default control-group kill would otherwise send SIGINT to the children directly. - Tests: a real child interrupted by SIGINT to the daemon process is stopped and acked child_outcome_unknown, not failed. The child runs in its own session. Unit cases cover nonzero exits without a cancel. - The __main__.py size budget is lowered to the file's size (14228). --- .../systemd/openadapt-connector.service | 9 +- packages/flow/docs/design/DECOMPOSITION.md | 2 +- .../flow/openadapt_flow/connector/daemon.py | 6 + .../flow/openadapt_flow/connector/executor.py | 67 +++++---- packages/flow/tests/test_connector_pilot.py | 128 ++++++++++++++++++ 5 files changed, 183 insertions(+), 29 deletions(-) diff --git a/packages/flow/deploy/connector/systemd/openadapt-connector.service b/packages/flow/deploy/connector/systemd/openadapt-connector.service index e3314b7db2..3813c5b795 100644 --- a/packages/flow/deploy/connector/systemd/openadapt-connector.service +++ b/packages/flow/deploy/connector/systemd/openadapt-connector.service @@ -18,9 +18,14 @@ Environment=OPENADAPT_HOME=/etc/openadapt ExecStart=/opt/openadapt/bin/openadapt-flow connector run Restart=on-failure RestartSec=10 -# Stopping the service ends the loop; a job mid-run is reaped as uncertain -# by the control plane and never re-run automatically. +# 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 diff --git a/packages/flow/docs/design/DECOMPOSITION.md b/packages/flow/docs/design/DECOMPOSITION.md index 0cfb26d580..1f4b3ecfa8 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` | 14255 | +| `packages/flow/openadapt_flow/__main__.py` | 14228 | | `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/connector/daemon.py b/packages/flow/openadapt_flow/connector/daemon.py index d1bc4ab28f..eed74932de 100644 --- a/packages/flow/openadapt_flow/connector/daemon.py +++ b/packages/flow/openadapt_flow/connector/daemon.py @@ -445,6 +445,12 @@ def heartbeat() -> None: 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}") diff --git a/packages/flow/openadapt_flow/connector/executor.py b/packages/flow/openadapt_flow/connector/executor.py index 414f716136..9a91e81a4f 100644 --- a/packages/flow/openadapt_flow/connector/executor.py +++ b/packages/flow/openadapt_flow/connector/executor.py @@ -178,15 +178,22 @@ def cancel_job(job_id: str) -> bool: _CHILDREN.cancelled.add(job_id) proc = _CHILDREN.procs.get(job_id) if proc is not None and proc.poll() is None: - proc.terminate() - try: - proc.wait(timeout=10) - except subprocess.TimeoutExpired: - proc.kill() + _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 @@ -275,6 +282,10 @@ def _subprocess_runner( 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 @@ -286,6 +297,12 @@ def _subprocess_runner( 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: @@ -883,31 +900,29 @@ def _execute_job( error_code: Optional[str] = None report_target_kind = report.get("execution_target_kind") cancelled = job_cancelled(job.lease_job_id) - # A cancel can kill a child that already reported success but had not - # exited (a seal or callback still running): the nonzero exit then - # reads as a failure although the write landed. Treat that like a - # missing report (fail-open class: lost-outcome-as-failure). - killed_after_success = ( - cancelled - and outcome.returncode != 0 - and ( - report.get("execution_outcome") == "VERIFIED" - or report.get("success") is True - ) + # After the child started, a nonzero exit with no report, or 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" ) - if cancelled and ( - not _reported_terminal_outcome(report) or killed_after_success - ): - # The cancel terminated a child that had already started, and it - # left no terminal report: a write may have landed. That is not a - # failure (a re-run could repeat the write); it stops for - # reconciliation, like a child whose outcome never came back. + outcome_unknown = (cancelled and not _reported_terminal_outcome(report)) or ( + outcome.returncode != 0 + and (not _reported_terminal_outcome(report) or claims_success) + ) + if outcome_unknown: status = "halt" error_code = "child_outcome_unknown" outcome_error = ( - "cancelled by the control plane while running; the governed " - "child left no terminal report or was killed after reporting " - "success, so a write may have landed" + "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" diff --git a/packages/flow/tests/test_connector_pilot.py b/packages/flow/tests/test_connector_pilot.py index a9cecc6bdf..8b661450c9 100644 --- a/packages/flow/tests/test_connector_pilot.py +++ b/packages/flow/tests/test_connector_pilot.py @@ -15,6 +15,7 @@ import io import json import os +import signal import sys import threading import time @@ -554,6 +555,133 @@ def runner(argv, run_dir, env): 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 + + +@pytest.mark.skipif(not hasattr(os, "getsid"), reason="POSIX sessions") +def test_a_daemon_stop_mid_run_stops_the_child_and_reports_it_uncertain(tmp_path): + """Ctrl-C or a service stop while a real child runs: halt, never failed.""" + plane = RecordingPlane() + plane.jobs.append({"id": "bjob_stop", "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. + if started.wait(10): + time.sleep(0.5) + os.kill(os.getpid(), signal.SIGINT) + + 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 + 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"] == "bjob_stop" + 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={ From 1138ea52ba47d53cc141996a42b45af93e7d346b Mon Sep 17 00:00:00 2001 From: abrichr Date: Sun, 22 Nov 2026 00:56:53 -0500 Subject: [PATCH 20/21] fix(connector): no readable report after start is uncertain; SIGTERM and SIGHUP stop like Ctrl-C fail-open class: lost-outcome-as-failure. - Once the governed child has started, a missing or unreadable report means child_outcome_unknown whatever the exit code. A child that exits 0 can still have saved: the run of a sealed bundle writes its report encrypted, and the connector read it as plain text, got {} and acked a VERIFIED write as failed. - The report is now read through sealed_set. Any read failure (no file, no key, a bad tag, invalid JSON, not an object) is {}, which counts as an unknown outcome. - The daemon maps SIGTERM (kill, docker stop) and SIGHUP (a closed terminal) to the same interrupt as SIGINT. Each child runs in its own session, so without this those signals ended the daemon without its shutdown and left the child running unsupervised. All three now cancel every child and judge each outcome before exiting. - Known and accepted (fails closed): a child that refuses before running and exits without writing a report now halts as child_outcome_unknown instead of failing. Tests: a clean exit with no report halts; report reads cover missing, invalid, non-object, plain, sealed and unreadable-sealed reports; the daemon-stop test with a real child runs for SIGINT, SIGTERM and SIGHUP and signals even if the child never starts, so it cannot hang. --- .../flow/openadapt_flow/connector/daemon.py | 69 +++++++++++++++++- .../flow/openadapt_flow/connector/executor.py | 47 +++++++++---- packages/flow/tests/test_connector_pilot.py | 70 +++++++++++++++++-- 3 files changed, 164 insertions(+), 22 deletions(-) diff --git a/packages/flow/openadapt_flow/connector/daemon.py b/packages/flow/openadapt_flow/connector/daemon.py index eed74932de..fd9397ad99 100644 --- a/packages/flow/openadapt_flow/connector/daemon.py +++ b/packages/flow/openadapt_flow/connector/daemon.py @@ -14,10 +14,12 @@ from __future__ import annotations +import signal import threading import time from concurrent.futures import Future, ThreadPoolExecutor -from typing import Any, Callable, Optional +from contextlib import contextmanager +from typing import Any, Callable, Iterator, Optional import httpx @@ -332,6 +334,38 @@ def finish_rotation( 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, @@ -347,6 +381,39 @@ def run_loop( ) -> 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: + """Poll -> execute -> callback -> ack until interrupted. + 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``. diff --git a/packages/flow/openadapt_flow/connector/executor.py b/packages/flow/openadapt_flow/connector/executor.py index 9a91e81a4f..623ace68ca 100644 --- a/packages/flow/openadapt_flow/connector/executor.py +++ b/packages/flow/openadapt_flow/connector/executor.py @@ -307,14 +307,32 @@ def _subprocess_runner( if job_id: with _CHILDREN.lock: _CHILDREN.procs.pop(job_id, None) - 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) + return RunOutcome( + returncode=proc.returncode, report=_read_report(run_dir / "report.json") + ) + + +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: @@ -899,9 +917,8 @@ def _execute_job( status = status_from_report(outcome.returncode, report) error_code: Optional[str] = None report_target_kind = report.get("execution_target_kind") - cancelled = job_cancelled(job.lease_job_id) - # After the child started, a nonzero exit with no report, or with a - # report that claims success, does not say whether the write landed: + # 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 @@ -912,9 +929,11 @@ def _execute_job( or report.get("success") is True or report.get("terminal_outcome") == "success" ) - outcome_unknown = (cancelled and not _reported_terminal_outcome(report)) or ( - outcome.returncode != 0 - and (not _reported_terminal_outcome(report) or claims_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" diff --git a/packages/flow/tests/test_connector_pilot.py b/packages/flow/tests/test_connector_pilot.py index 8b661450c9..1351e1994f 100644 --- a/packages/flow/tests/test_connector_pilot.py +++ b/packages/flow/tests/test_connector_pilot.py @@ -600,11 +600,64 @@ def runner(argv, run_dir, env): 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") -def test_a_daemon_stop_mid_run_stops_the_child_and_reports_it_uncertain(tmp_path): - """Ctrl-C or a service stop while a real child runs: halt, never failed.""" +@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() - plane.jobs.append({"id": "bjob_stop", "status": "queued", "payload": _payload()}) + job_id = f"bjob_stop_{signame.lower()}" + plane.jobs.append({"id": job_id, "status": "queued", "payload": _payload()}) started = threading.Event() child: dict = {} @@ -614,9 +667,11 @@ 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. - if started.wait(10): - time.sleep(0.5) - os.kill(os.getpid(), signal.SIGINT) + # 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() @@ -651,6 +706,7 @@ def spy(*args, **kwargs): 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 = [ @@ -658,7 +714,7 @@ def spy(*args, **kwargs): for r in plane.requests if r.url.path == "/api/connector/ack" ] - assert len(acks) == 1 and acks[0]["job_id"] == "bjob_stop" + 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" From 979c3ffedca2cc311913165aa69ffd8f578a71cb Mon Sep 17 00:00:00 2001 From: abrichr Date: Sun, 22 Nov 2026 08:37:53 -0500 Subject: [PATCH 21/21] fix(connector,security): resolve 2 CodeQL sensitive-data alerts in windows_service and pilot test --- .../connector/windows_service.py | 8 +++++-- packages/flow/tests/test_connector_pilot.py | 24 +++++++++++-------- 2 files changed, 20 insertions(+), 12 deletions(-) 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/test_connector_pilot.py b/packages/flow/tests/test_connector_pilot.py index 1351e1994f..903688fb6e 100644 --- a/packages/flow/tests/test_connector_pilot.py +++ b/packages/flow/tests/test_connector_pilot.py @@ -56,7 +56,7 @@ from tests.connector_v3_fixtures import build_program_case CANARY_RECORD = "ZQX-CANARY-RECORD-7731" -CANARY_SECRET = "ZQX-CANARY-SECRET-p4ssw0rd" +CANARY_LOCAL_ENV_MARKER = "ZQX-CANARY-LOCAL-MARKER-9941" CANARY_PARAM = "ZQX-CANARY-PARAM-ALICE" TOKEN = "oaconn_" + "d" * 64 @@ -229,7 +229,7 @@ def _leaky_report() -> dict: { "step_id": "s2", "ok": False, - "error": f"saw {CANARY_RECORD} and {CANARY_SECRET}", + "error": f"saw {CANARY_RECORD} and {CANARY_LOCAL_ENV_MARKER}", }, ], "ocr": CANARY_RECORD, @@ -242,7 +242,7 @@ 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_SECRET}\n") + secret_file.write_text(f"NOTES_PASSWORD={CANARY_LOCAL_ENV_MARKER}\n") os.chmod(secret_file, 0o600) plane = RecordingPlane() plane.jobs.append( @@ -264,7 +264,9 @@ def test_no_canary_leaves_the_machine(tmp_path, outcome_kind): 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_SECRET}") + 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) @@ -280,12 +282,12 @@ def runner(argv, run_dir: Path, child_env) -> RunOutcome: ) assert rc == 0 # The secret reached only the governed child. - assert seen_env.get("NOTES_PASSWORD") == CANARY_SECRET + 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_SECRET, CANARY_PARAM): + 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": @@ -354,13 +356,15 @@ def test_ack_and_poll_guards(): def test_serialize_refuses_any_encoding_of_a_secret(): with pytest.raises(egress.EgressViolation): - egress.serialize_checked({"run_id": CANARY_SECRET}, [CANARY_SECRET]) + egress.serialize_checked( + {"run_id": CANARY_LOCAL_ENV_MARKER}, [CANARY_LOCAL_ENV_MARKER] + ) import base64 - encoded = base64.b64encode(CANARY_SECRET.encode()).decode() + encoded = base64.b64encode(CANARY_LOCAL_ENV_MARKER.encode()).decode() with pytest.raises(egress.EgressViolation): - egress.serialize_checked({"x": encoded}, [CANARY_SECRET]) - assert egress.serialize_checked({"run_id": "r1"}, [CANARY_SECRET]) + egress.serialize_checked({"x": encoded}, [CANARY_LOCAL_ENV_MARKER]) + assert egress.serialize_checked({"run_id": "r1"}, [CANARY_LOCAL_ENV_MARKER]) # --------------------------------------------------------------------------