From 8812266e4c81e1489ae8955d2ae0b58f608ee837 Mon Sep 17 00:00:00 2001 From: abrichr Date: Fri, 20 Nov 2026 23:24:59 -0500 Subject: [PATCH 1/8] Check connector profiles at startup and isolate the container ledger --- .../workflows/connector-windows-service.yml | 3 + packages/flow/deploy/connector/Dockerfile | 11 +- packages/flow/deploy/connector/e2e/run_e2e.sh | 1 + packages/flow/docs/BYOC_CONNECTOR.md | 33 ++++++ packages/flow/openadapt_flow/at_rest.py | 11 +- packages/flow/openadapt_flow/connector/cli.py | 5 + .../flow/openadapt_flow/connector/config.py | 30 +++++ .../flow/openadapt_flow/connector/secrets.py | 3 + .../connector/windows_service.py | 5 + packages/flow/tests/conftest.py | 1 + .../test_connector_deployment_preflight.py | 109 ++++++++++++++++++ .../tests/test_connector_windows_service.py | 3 + 12 files changed, 206 insertions(+), 9 deletions(-) create mode 100644 packages/flow/tests/test_connector_deployment_preflight.py diff --git a/.github/workflows/connector-windows-service.yml b/.github/workflows/connector-windows-service.yml index 0fafd80b94..e4fe14f89a 100644 --- a/.github/workflows/connector-windows-service.yml +++ b/.github/workflows/connector-windows-service.yml @@ -84,12 +84,15 @@ jobs: New-Item -ItemType Directory -Force -Path $env:CONNECTOR_DIR | Out-Null $storage = Join-Path $env:RUNNER_TEMP 'byoc-storage' New-Item -ItemType Directory -Force -Path $storage | Out-Null + $profilePath = Join-Path $env:CONNECTOR_DIR 'deployment.yaml' + [IO.File]::WriteAllText($profilePath, "runtime: {profile: standard}`n") $toml = @( '[connector]', "control_plane_url = `"http://127.0.0.1:$env:STUB_PORT`"", "token = `"$env:CI_CONNECTOR_TOKEN`"", 'org_id = "org_stub"', 'poll_wait_s = 2', + "profile = '$profilePath'", 'storage_backend = "local"', "storage_root = '$storage'" ) -join "`n" diff --git a/packages/flow/deploy/connector/Dockerfile b/packages/flow/deploy/connector/Dockerfile index 91f72d8680..c2c4aa8e74 100644 --- a/packages/flow/deploy/connector/Dockerfile +++ b/packages/flow/deploy/connector/Dockerfile @@ -6,14 +6,15 @@ # 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. +# Mount operator configuration at /etc/openadapt, encrypted customer storage +# at /srv/openadapt and a separate private ledger directory from the encrypted +# volume at /var/lib/openadapt/ledger. See docs/BYOC_CONNECTOR.md. ARG BASE_IMAGE=python:3.12-slim-bookworm FROM ${BASE_IMAGE} ENV PIP_DISABLE_PIP_VERSION_CHECK=1 \ + PYTHONUNBUFFERED=1 \ + OPENADAPT_FLOW_PLAINTEXT_LEDGER_DIR=/var/lib/openadapt/ledger \ PYTHONDONTWRITEBYTECODE=1 \ OPENADAPT_HOME=/etc/openadapt \ PLAYWRIGHT_BROWSERS_PATH=/opt/playwright @@ -31,7 +32,7 @@ RUN set -eu; \ rm -rf /tmp/wheels /var/lib/apt/lists/* RUN useradd --system --create-home --uid 10001 openadapt \ - && mkdir -p /etc/openadapt /srv/openadapt \ + && mkdir -p /etc/openadapt /srv/openadapt /var/lib/openadapt/ledger \ && chown openadapt:openadapt /srv/openadapt COPY entrypoint.sh /usr/local/bin/openadapt-connector-entrypoint RUN chmod 0755 /usr/local/bin/openadapt-connector-entrypoint diff --git a/packages/flow/deploy/connector/e2e/run_e2e.sh b/packages/flow/deploy/connector/e2e/run_e2e.sh index 611a25b3b5..b065b1fba0 100755 --- a/packages/flow/deploy/connector/e2e/run_e2e.sh +++ b/packages/flow/deploy/connector/e2e/run_e2e.sh @@ -66,6 +66,7 @@ runner() { --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 \ + --mount "type=bind,source=$STATE/runner-ledger,target=/var/lib/openadapt/ledger" \ -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" diff --git a/packages/flow/docs/BYOC_CONNECTOR.md b/packages/flow/docs/BYOC_CONNECTOR.md index 0c95344f7a..cda398a93b 100644 --- a/packages/flow/docs/BYOC_CONNECTOR.md +++ b/packages/flow/docs/BYOC_CONNECTOR.md @@ -58,6 +58,39 @@ Every flag also resolves from an environment variable `connector enroll` remains available for mock/development control planes; live Cloud token creation is authenticated and organization-scoped in the dashboard. +Set `runtime.profile` explicitly in the local deployment file. Use `standard` +for admitted programs. Qualified jobs can use `standard` or `regulated`, +matching their authorization. Startup checks the local profile before polling. +The child checks the exact authorization again for each run. + +```yaml +runtime: + profile: standard +``` + +### Container storage and logs + +Mount a private directory from the customer's encrypted data volume at +`/var/lib/openadapt/ledger`. The connector user (UID 10001) needs write access. +Keep this directory outside the storage root used for job bundles and reports. +For the synthetic container harness, prepare `$STATE/runner-ledger` with mode +0700 for that user. The image sets `OPENADAPT_FLOW_PLAINTEXT_LEDGER_DIR` to +the mount and flushes Python output to `docker logs` without a TTY. + +The plaintext ledger records writes already permitted by the local at-rest +policy. The encryption key keeps its configured location. With read-only +configuration at `/etc/openadapt`, provision any required local key beforehand +or use the operator's existing key configuration. If the service manages token +rotation, its enrollment state also needs its own writable location. + +For a refused run, look beside the expected report in the customer store for +`.connector-diagnostics`, even if the child produced no report. +Read it in the connector's environment with +`python -m openadapt_flow.connector.diagnostics /path/to/report.json.connector-diagnostics`. +It contains the local error and up to the final 32 KiB of combined child output. +That output stays local. If the connector reports `local_diagnostics_unavailable`, +check the customer storage, its access permissions and the configured key. + ## Windows service The `OpenAdaptConnector` wrapper runs the connector loop under the Windows diff --git a/packages/flow/openadapt_flow/at_rest.py b/packages/flow/openadapt_flow/at_rest.py index fcd09f42a3..6a3511cb99 100644 --- a/packages/flow/openadapt_flow/at_rest.py +++ b/packages/flow/openadapt_flow/at_rest.py @@ -18,8 +18,9 @@ * In the default mode, each recording, bundle, run directory or other output written in plaintext goes through :func:`unsealed_write` or :func:`seal_new`: stderr names the path and a ledger line (``plaintext-at-rest.jsonl``) - records it, and Desktop shows the ledger as a notice. Once every consumer - reads encrypted artifacts (#1751), the default encrypts them too + records it, and Desktop shows the ledger as a notice. + ``OPENADAPT_FLOW_PLAINTEXT_LEDGER_DIR`` relocates only this ledger. Once + every consumer reads encrypted artifacts (#1751), the default encrypts them too (:data:`DEFAULT_SEALS_ARTIFACTS`). * ``OPENADAPT_FLOW_PLAINTEXT_AT_REST=''`` turns encryption off for development or de-identified data, with a warning and a ledger line. Strict @@ -132,6 +133,7 @@ def unsealed_write(artifact: str, path: Path | str, *, refuse: bool = True) -> N HOME_ENV: Final[str] = "OPENADAPT_FLOW_AT_REST_HOME" +LEDGER_DIR_ENV: Final[str] = "OPENADAPT_FLOW_PLAINTEXT_LEDGER_DIR" def _home() -> Path: @@ -165,7 +167,8 @@ def recent_plaintext_writes(limit: int = 20) -> list[dict]: def ledger_path() -> Path: """The record of every process that wrote plaintext under the opt-out.""" - return _home() / LEDGER_NAME + directory = os.environ.get(LEDGER_DIR_ENV) + return (Path(directory) if directory else _home()) / LEDGER_NAME def opt_out_reason() -> Optional[str]: @@ -251,7 +254,7 @@ def _record( _warned.discard(purpose) raise AtRestRefused( f"Not writing {purpose}: the plaintext ledger at {ledger_path()} " - f"can't be written ({exc}). Set {HOME_ENV} to a writable private " + f"can't be written ({exc}). Set {LEDGER_DIR_ENV} to a writable private " "directory. Nothing was written." ) from exc diff --git a/packages/flow/openadapt_flow/connector/cli.py b/packages/flow/openadapt_flow/connector/cli.py index 7036e0b5be..14311a2939 100644 --- a/packages/flow/openadapt_flow/connector/cli.py +++ b/packages/flow/openadapt_flow/connector/cli.py @@ -244,6 +244,11 @@ def persist_pending(new_token: str) -> None: "BYOC_CONNECTOR_TOKEN." ) return 2 + try: + settings.validate_run_config() + except ConnectorConfigError as exc: + print(f"connector run: {exc}") + return 2 client = ConnectorClient( settings.control_plane_url, token=settings.token, diff --git a/packages/flow/openadapt_flow/connector/config.py b/packages/flow/openadapt_flow/connector/config.py index 84a48e8d72..8f989b1375 100644 --- a/packages/flow/openadapt_flow/connector/config.py +++ b/packages/flow/openadapt_flow/connector/config.py @@ -107,6 +107,36 @@ class ConnectorSettings: #: Qualified jobs must match it exactly; never built from a remote proof. qualification_authority_file: Optional[str] = None + def validate_run_config(self) -> None: + """Check local startup configuration before connecting or leasing work.""" + from openadapt_flow import at_rest + from openadapt_flow.deployment import load_deployment + + if not self.profile: + raise ConnectorConfigError( + "Set --profile, BYOC_PROFILE or connector.toml profile to a deployment " + "file with runtime.profile set to standard or regulated." + ) + try: + deployment = load_deployment(self.profile) + except (OSError, ValueError) as exc: + # A parser error can quote local config values. Log only our diagnostic. + raise ConnectorConfigError( + "Cannot read a valid deployment profile. Check the local deployment " + "file and set runtime.profile to standard or regulated." + ) from exc + if deployment.runtime.profile not in {"standard", "regulated"}: + raise ConnectorConfigError( + "Managed dispatch requires runtime.profile set to standard or regulated." + ) + if self.storage_root and at_rest.ledger_path().resolve().is_relative_to( + Path(self.storage_root).resolve() + ): + raise ConnectorConfigError( + "The plaintext ledger must be outside the job-addressable storage_root. " + f"Set {at_rest.LEDGER_DIR_ENV} to a separate private directory." + ) + def pinned_admission_keys(self) -> frozenset[str]: keys = {k.strip().lower() for k in self.trusted_admission_keys.split(",")} return frozenset( diff --git a/packages/flow/openadapt_flow/connector/secrets.py b/packages/flow/openadapt_flow/connector/secrets.py index 56fc45ff45..ed10798bef 100644 --- a/packages/flow/openadapt_flow/connector/secrets.py +++ b/packages/flow/openadapt_flow/connector/secrets.py @@ -42,6 +42,9 @@ "OPENADAPT_RUNNER_TOKEN", "OPENADAPT_DURABLE_DISPATCH_SESSION_ID", "OPENADAPT_JIT_KEY_DIR", + "OPENADAPT_HOME", + "OPENADAPT_FLOW_AT_REST_HOME", + "OPENADAPT_FLOW_PLAINTEXT_LEDGER_DIR", "OPENADAPT_QUALIFICATION_SIGNERS_JSON", "BYOC_CONNECTOR_TOKEN", } diff --git a/packages/flow/openadapt_flow/connector/windows_service.py b/packages/flow/openadapt_flow/connector/windows_service.py index 9d7ce132e1..8220c34263 100644 --- a/packages/flow/openadapt_flow/connector/windows_service.py +++ b/packages/flow/openadapt_flow/connector/windows_service.py @@ -235,6 +235,11 @@ def serve( config_file(config_dir), ) return 2 + try: + settings.validate_run_config() + except ConnectorConfigError as exc: + logger.error("connector run: %s", exc) + return 2 logger.info( "service starting: config %s, settings %s", config_file(config_dir), diff --git a/packages/flow/tests/conftest.py b/packages/flow/tests/conftest.py index ba5300693f..0d9bbb1020 100644 --- a/packages/flow/tests/conftest.py +++ b/packages/flow/tests/conftest.py @@ -74,6 +74,7 @@ def _isolation_env(root: Path) -> dict[str, str | None]: # encryption and strict modes are covered by test_at_rest_default.py. "OPENADAPT_FLOW_PLAINTEXT_AT_REST": "test suite: synthetic data", "OPENADAPT_FLOW_AT_REST_HOME": str(root / ".at-rest-home"), + "OPENADAPT_FLOW_PLAINTEXT_LEDGER_DIR": None, "OPENADAPT_FLOW_AT_REST": None, } diff --git a/packages/flow/tests/test_connector_deployment_preflight.py b/packages/flow/tests/test_connector_deployment_preflight.py new file mode 100644 index 0000000000..64182c187a --- /dev/null +++ b/packages/flow/tests/test_connector_deployment_preflight.py @@ -0,0 +1,109 @@ +"""Connector startup, ledger location, and the shipped container configuration.""" + +import argparse +import json +import logging +import os +import threading +from pathlib import Path + +import pytest + +from openadapt_flow import at_rest +from openadapt_flow.connector import cli, windows_service +from openadapt_flow.connector.config import ConnectorConfigError, ConnectorSettings +from openadapt_flow.connector.secrets import LocalSecretStore, SecretStoreError + + +@pytest.mark.parametrize("profile", ["standard", "regulated"]) +def test_managed_profiles_pass_preflight(tmp_path, profile): + path = tmp_path / "deployment.yaml" + path.write_text(f"runtime: {{profile: {profile}}}", encoding="utf-8") + ConnectorSettings(profile=str(path)).validate_run_config() + + +@pytest.mark.parametrize( + "contents", [None, "{}", "runtime: {profile: demo}", "runtime: {profile: invalid}"] +) +def test_run_and_service_refuse_invalid_profile_before_any_request( + tmp_path, monkeypatch, capsys, caplog, contents +): + monkeypatch.setenv("OPENADAPT_HOME", str(tmp_path)) + monkeypatch.setenv("BYOC_CONNECTOR_TOKEN", "synthetic-test-value") + monkeypatch.delenv("BYOC_PROFILE", raising=False) + if contents is not None: + path = tmp_path / "deployment.yaml" + path.write_text(contents, encoding="utf-8") + monkeypatch.setenv("BYOC_PROFILE", str(path)) + + def no_client(*args, **kwargs): + pytest.fail("startup connected before checking its deployment configuration") + + monkeypatch.setattr("openadapt_flow.connector.ConnectorClient", no_client) + monkeypatch.setattr(windows_service, "_stoppable_client", no_client) + assert cli._cmd_connector(argparse.Namespace(connector_cmd="run")) == 2 + assert "runtime.profile" in capsys.readouterr().out + assert ( + windows_service.serve(tmp_path, threading.Event(), logging.getLogger(__name__)) + == 2 + ) + assert "runtime.profile" in caplog.text + assert "synthetic-test-value" not in caplog.text + + +def test_container_uses_private_ledger_outside_read_only_config(tmp_path, monkeypatch): + deploy = Path(__file__).resolve().parents[1] / "deploy" / "connector" + image = (deploy / "Dockerfile").read_text() + harness = (deploy / "e2e" / "run_e2e.sh").read_text() + mount = "/var/lib/openadapt/ledger" + assert "PYTHONUNBUFFERED=1" in image + assert f"{at_rest.LEDGER_DIR_ENV}={mount}" in image + assert f'source=$STATE/runner-ledger,target={mount}"' in harness + + key_home = tmp_path / "config" + ledger_dir = tmp_path / "private-state" + ledger_dir.mkdir(mode=0o700) + monkeypatch.setenv(at_rest.HOME_ENV, str(key_home)) + monkeypatch.setenv(at_rest.LEDGER_DIR_ENV, str(ledger_dir)) + at_rest.unsealed_write("synthetic run", tmp_path / "report") + assert at_rest.ledger_path() == ledger_dir / at_rest.LEDGER_NAME + entry = json.loads(at_rest.ledger_path().read_text()) + assert entry["path"] == str(tmp_path / "report") + assert entry["purpose"].startswith("synthetic run") + assert at_rest.local_key_path() == key_home / "keys" / at_rest.KEY_NAME + assert not key_home.exists() + + monkeypatch.setenv(at_rest.MODE_ENV, "strict") + with pytest.raises(at_rest.AtRestRefused): + at_rest.unsealed_write("synthetic strict run", tmp_path / "other") + + +def test_unwritable_ledger_still_refuses_the_write(tmp_path, monkeypatch): + blocked = tmp_path / "file" + blocked.write_text("existing file", encoding="utf-8") + monkeypatch.setenv(at_rest.LEDGER_DIR_ENV, str(blocked)) + with pytest.raises(at_rest.AtRestRefused, match="plaintext ledger"): + at_rest.unsealed_write("synthetic blocked run", tmp_path / "report") + + +def test_job_storage_cannot_contain_ledger(tmp_path, monkeypatch): + config = tmp_path / "deployment.yaml" + config.write_text("runtime: {profile: standard}", encoding="utf-8") + storage = tmp_path / "store" + monkeypatch.setenv(at_rest.LEDGER_DIR_ENV, str(storage / "ledger")) + with pytest.raises(ConnectorConfigError, match="outside"): + ConnectorSettings( + profile=str(config), storage_root=str(storage) + ).validate_run_config() + + +@pytest.mark.parametrize( + "name", [at_rest.LEDGER_DIR_ENV, at_rest.HOME_ENV, "OPENADAPT_HOME"] +) +def test_secret_reference_cannot_select_ledger(tmp_path, name): + secret_file = tmp_path / "synthetic.env" + secret_file.write_text(f"{name}=/wrong", encoding="utf-8") + if os.name == "posix": + secret_file.chmod(0o600) + with pytest.raises(SecretStoreError, match="invalid"): + LocalSecretStore(str(tmp_path)).resolve("synthetic") diff --git a/packages/flow/tests/test_connector_windows_service.py b/packages/flow/tests/test_connector_windows_service.py index 66f0c1f7c2..6d2d6a1113 100644 --- a/packages/flow/tests/test_connector_windows_service.py +++ b/packages/flow/tests/test_connector_windows_service.py @@ -46,6 +46,9 @@ def _write_config( 'org_id = "org_stub"', "poll_wait_s = 1", ] + profile = config_dir / "deployment.yaml" + profile.write_text("runtime: {profile: standard}\n", encoding="utf-8") + lines.append(f"profile = {json.dumps(str(profile))}") lines.append(f"storage_root = {json.dumps(str(config_dir / 'storage'))}") lines += [f"{k} = {json.dumps(v)}" for k, v in extra.items()] (config_dir / "connector.toml").write_text("\n".join(lines) + "\n", "utf-8") From b293d905e1a112e8712ffe536f103808a432f4ca Mon Sep 17 00:00:00 2001 From: abrichr Date: Fri, 20 Nov 2026 23:33:37 -0500 Subject: [PATCH 2/8] Keep refusal details in the operator's private connector storage --- .../workflows/connector-windows-service.yml | 4 +- .../flow/openadapt_flow/connector/daemon.py | 6 +- .../openadapt_flow/connector/diagnostics.py | 143 ++++++++++++++++ .../flow/openadapt_flow/connector/executor.py | 88 ++++++++-- .../flow/openadapt_flow/connector/storage.py | 10 ++ packages/flow/tests/test_connector.py | 155 ++++++++++++++++++ .../test_connector_diagnostic_process.py | 61 +++++++ 7 files changed, 454 insertions(+), 13 deletions(-) create mode 100644 packages/flow/openadapt_flow/connector/diagnostics.py create mode 100644 packages/flow/tests/test_connector_diagnostic_process.py diff --git a/.github/workflows/connector-windows-service.yml b/.github/workflows/connector-windows-service.yml index e4fe14f89a..ac90567be8 100644 --- a/.github/workflows/connector-windows-service.yml +++ b/.github/workflows/connector-windows-service.yml @@ -51,9 +51,9 @@ jobs: --lock 'packages/flow[connector-windows]' --editable packages/types --editable packages/flow - - name: Unit tests (service wrapper) + - name: Unit tests (service wrapper and child output) working-directory: packages/flow - run: python -m pytest tests/test_connector_windows_service.py -q -p no:cacheprovider + run: python -m pytest tests/test_connector_windows_service.py tests/test_connector_diagnostic_process.py -q -p no:cacheprovider - name: Start the stub control plane on 127.0.0.1 run: | diff --git a/packages/flow/openadapt_flow/connector/daemon.py b/packages/flow/openadapt_flow/connector/daemon.py index d1bc4ab28f..847ad4d78a 100644 --- a/packages/flow/openadapt_flow/connector/daemon.py +++ b/packages/flow/openadapt_flow/connector/daemon.py @@ -140,6 +140,7 @@ def child_start(verified_sha256: str) -> None: # it. An unacked lease expires to `lease_expired_uncertain` and is not # automatically re-offered, preventing blind duplicate actuation. callback_accepted = False + local_diagnostics_unavailable = result.local_diagnostics_unavailable try: callback_body = phi_free_callback_body(job, result) except Exception: # noqa: BLE001 - nothing unchecked is ever sent @@ -182,13 +183,16 @@ def child_start(verified_sha256: str) -> None: except Exception: # noqa: BLE001 - terminal uncertainty, never re-offered pass - return { + summary = { "job_id": job.lease_job_id, "run_id": job.run_id, "status": result.status, "error_code": result.error_code, "callback_accepted": callback_accepted, } + if local_diagnostics_unavailable: + summary["local_diagnostics_unavailable"] = True + return summary def _default_storage_factory(settings: ConnectorSettings) -> StorageFactory: diff --git a/packages/flow/openadapt_flow/connector/diagnostics.py b/packages/flow/openadapt_flow/connector/diagnostics.py new file mode 100644 index 0000000000..4ce8d6a99b --- /dev/null +++ b/packages/flow/openadapt_flow/connector/diagnostics.py @@ -0,0 +1,143 @@ +"""Bounded local diagnostics for the connector. Only the operator opens these files.""" + +from __future__ import annotations + +import argparse +import json +import os +import stat +import subprocess +import sys +import tempfile +import time +from pathlib import Path +from typing import Any + +from openadapt_flow import at_rest, crypto +from openadapt_flow.private_file import open_binary, windows_descriptor_has_private_acl + +MAX_OUTPUT = 32 * 1024 +_AAD = b"openadapt-flow/connector-diagnostics/v1" +_SCHEMA = "openadapt.connector-diagnostics/v1" + + +def _read_available(fd: int) -> bytes: + if sys.platform != "win32": + try: + return os.read(fd, 8192) + except BlockingIOError: + return b"" + # select() accepts only sockets on Windows. Peek without blocking or + # requiring a TTY; this also works on the supported Python 3.10/3.11. + import ctypes + import msvcrt + from ctypes import wintypes + + count = wintypes.DWORD() + handle = wintypes.HANDLE(msvcrt.get_osfhandle(fd)) + kernel = ctypes.WinDLL("kernel32", use_last_error=True) + if not kernel.PeekNamedPipe(handle, None, 0, None, ctypes.byref(count), None): + error = ctypes.get_last_error() + if error in (109, 232): # ERROR_BROKEN_PIPE, ERROR_NO_DATA + return b"" + raise OSError(error, "child output pipe unavailable") + return os.read(fd, min(count.value, 8192)) if count.value else b"" + + +def child_output(proc: subprocess.Popen[bytes]) -> str: + """Drain while the child runs. A descendant retaining stdout cannot hold the lease.""" + assert proc.stdout is not None + tail = bytearray() + deadline = None + with proc.stdout: + fd = proc.stdout.fileno() + if os.name != "nt": + os.set_blocking(fd, False) + while True: + finished = proc.poll() is not None + if finished and deadline is None: + deadline = time.monotonic() + 0.25 + chunk = _read_available(fd) + if chunk: + tail.extend(chunk) + del tail[:-MAX_OUTPUT] + if deadline is not None and time.monotonic() >= deadline: + break + elif finished: + break + else: + try: + proc.wait(timeout=0.05) + except subprocess.TimeoutExpired: + pass + return tail.decode("utf-8", errors="replace") + + +def _check_private(fd: int) -> None: + info = os.fstat(fd) + if not stat.S_ISREG(info.st_mode) or info.st_nlink != 1: + raise ValueError("connector diagnostics require a regular private file") + if os.name == "nt": + private = windows_descriptor_has_private_acl(fd) + else: + private = info.st_uid == os.geteuid() and not info.st_mode & 0o077 + if not private: + raise ValueError("connector diagnostics require owner-only access") + + +def write_diagnostics(path: Path, data: dict[str, Any]) -> None: + """Publish an owner-only sidecar atomically, honoring the operator's key/opt-out.""" + body = json.dumps( + {"schema": _SCHEMA, "diagnostic": data}, ensure_ascii=False + ).encode("utf-8") + key = crypto.resolve_key(None) + if key: + body = crypto.encrypt_bytes(body, key, aad=_AAD) + elif not at_rest.plaintext_allowed("connector diagnostics"): + raise at_rest.AtRestRefused("connector diagnostics require an at-rest key") + path.parent.mkdir(parents=True, exist_ok=True) + fd, tmp = tempfile.mkstemp(dir=path.parent, prefix=".connector-diagnostics-") + try: + with os.fdopen(fd, "wb") as stream: + _check_private(stream.fileno()) + stream.write(body) + stream.flush() + os.fsync(stream.fileno()) + os.replace(tmp, path) + finally: + Path(tmp).unlink(missing_ok=True) + + +def read_diagnostics(path: Path) -> dict[str, Any]: + flags = os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_NONBLOCK", 0) + with os.fdopen(open_binary(path, flags), "rb") as stream: + _check_private(stream.fileno()) + body = stream.read() + if crypto.is_encrypted(body): + body = crypto.decrypt_bytes(body, crypto.resolve_read_key(None), aad=_AAD) + record = json.loads(body) + if ( + not isinstance(record, dict) + or record.get("schema") != _SCHEMA + or not isinstance(record.get("diagnostic"), dict) + ): + raise ValueError("unrecognized connector diagnostic") + return record["diagnostic"] + + +if __name__ == "__main__": + parser = argparse.ArgumentParser( + description="Read a private local connector diagnostic." + ) + parser.add_argument("path", type=Path) + try: + print( + json.dumps( + read_diagnostics(parser.parse_args().path), indent=2, ensure_ascii=False + ) + ) + except (OSError, ValueError, crypto.CryptoError, at_rest.LocalKeyError): + parser.exit( + 1, + "Unable to open the private connector diagnostic. Check its permissions and key.\n", + ) diff --git a/packages/flow/openadapt_flow/connector/executor.py b/packages/flow/openadapt_flow/connector/executor.py index fc5849da09..6db2f2f8d8 100644 --- a/packages/flow/openadapt_flow/connector/executor.py +++ b/packages/flow/openadapt_flow/connector/executor.py @@ -63,6 +63,7 @@ REMOTE_AUTHORITY_URL_ENV, REMOTE_DISPATCH_SESSION_ID_ENV, ) +from openadapt_flow.wire_check import mask_secrets #: A run-gate refusal (fail-closed admission denied) exits 2 before the replay #: creates report.json. @@ -75,6 +76,7 @@ class RunOutcome: returncode: int report: dict[str, Any] = field(default_factory=dict) + output: str = field(default="", repr=False) #: A runner maps argv -> RunOutcome. The default shells the governed ``run`` CLI @@ -91,12 +93,14 @@ class ExecutionResult: 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 + error: Optional[str] = field(default=None, repr=False) 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 + child_output: str = field(default="", repr=False) + local_diagnostics_unavailable: bool = False # --- Wrap programs: admission and independent read-back ----------------------- @@ -268,12 +272,14 @@ class _ChildNotStarted(RuntimeError): def _subprocess_runner( argv: list[str], run_dir: Path, child_env: Mapping[str, str] ) -> RunOutcome: + from openadapt_flow.connector.diagnostics import child_output + job_id = getattr(_CURRENT, "job_id", None) try: proc = subprocess.Popen( # nosec - fixed argv and exact process-local env argv, - stdout=subprocess.DEVNULL, - stderr=subprocess.DEVNULL, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, env=dict(child_env), ) except OSError as exc: @@ -285,8 +291,9 @@ def _subprocess_runner( if cancelled: proc.terminate() try: - proc.wait() + output = child_output(proc) finally: + proc.wait() if job_id: with _CHILDREN.lock: _CHILDREN.procs.pop(job_id, None) @@ -294,10 +301,12 @@ def _subprocess_runner( report: dict[str, Any] = {} if report_path.is_file(): try: - report = json.loads(report_path.read_text(encoding="utf-8")) + document = json.loads(report_path.read_text(encoding="utf-8")) + if isinstance(document, dict): + report = document except (OSError, ValueError): report = {} - return RunOutcome(returncode=proc.returncode, report=report) + return RunOutcome(returncode=proc.returncode, report=report, output=output) def status_from_report(returncode: int, report: dict[str, Any]) -> str: @@ -577,17 +586,57 @@ def execute_job( ``error_code`` (which may leave the machine) and a local ``error`` detail (which never does). """ + from openadapt_flow.crypto import ENV_KEY + + known_secrets = [ + value + for value in ( + job.run_token, + settings.token, + settings.pending_token, + os.environ.get(ENV_KEY), + ) + if value + ] + + def remember_secrets(values: list[str]) -> None: + known_secrets.extend(values) + if on_secrets is not None: + on_secrets(values) + _CURRENT.job_id = job.lease_job_id try: - return _execute_job( + result = _execute_job( job, settings, storage, runner=runner, require_run_token=require_run_token, - on_secrets=on_secrets, + on_secrets=remember_secrets, on_child_start=on_child_start, ) + if result.error or (result.status != "success" and result.child_output): + sink = getattr(storage, "write_diagnostics", None) + if callable(sink): + try: + sink( + job.report_ref(), + { + "run_id": job.run_id, + "error_code": result.error_code, + "detail": mask_secrets(result.error, known_secrets) + if result.error + else None, + "child_output": mask_secrets( + result.child_output, known_secrets + ), + }, + ) + except Exception: + # Losing an optional local diagnostic cannot change the run outcome. + result.local_diagnostics_unavailable = True + result.child_output = "" + return result finally: _CURRENT.job_id = None @@ -876,6 +925,20 @@ def _execute_job( status = "failed" error_code = "cancelled_by_control_plane" outcome_error = "cancelled by the control plane while running" + elif not report or report_target_kind is None: + # Exit status alone cannot establish what happened to the record. + status = "halt" + error_code = ( + "child_no_report" if not report else "child_report_missing_target" + ) + outcome_error = ( + f"governed child exited with code {outcome.returncode} and " + + ( + "no readable report" + if not report + else "no execution_target_kind in its report" + ) + ) elif report_target_kind != job.target_kind: status = "failed" error_code = "target_kind_mismatch" @@ -922,14 +985,18 @@ def _execute_job( ) # 4. The PHI-bearing report body goes to the CUSTOMER'S store, never ours. - report_ref: Optional[str] = job.report_ref() + # An absent or unreadable report has no bytes to bind in a Receipt. + report_ref: Optional[str] = job.report_ref() if report else None halt = halt_object(report) + if status == "halt" and halt is None: + halt = {"present": True} outcome_envelope = precise_outcome_from_report(report) if error_code is not None and outcome_envelope is not None: # A cancelled or mismatched run never reports a success envelope. outcome_envelope = None try: - storage.write_report(report_ref, report) + if report_ref is not None: + storage.write_report(report_ref, report) except Exception as exc: # A storage fault says nothing about what the child did, so it # never becomes a runner failure: a run that actuated would show @@ -967,4 +1034,5 @@ def _execute_job( failure_signal=automation_failure_signal(report, status, job.target_kind), outcome=outcome_envelope, error_code=error_code, + child_output=outcome.output, ) diff --git a/packages/flow/openadapt_flow/connector/storage.py b/packages/flow/openadapt_flow/connector/storage.py index deb410243c..c0b63ec614 100644 --- a/packages/flow/openadapt_flow/connector/storage.py +++ b/packages/flow/openadapt_flow/connector/storage.py @@ -106,6 +106,16 @@ def write_report(self, ref: Optional[str], report: dict[str, Any]) -> Optional[s pass return str(dest) + def write_diagnostics(self, ref: Optional[str], data: dict[str, Any]) -> None: + from openadapt_flow.connector.diagnostics import write_diagnostics + + if not ref: + raise ValueError("connector diagnostics require a local report key") + report = _customer_path(self.root, ref, kind="report") + write_diagnostics( + report.with_name(report.name + ".connector-diagnostics"), data + ) + class InMemoryCustomerStorage: """Tests/dry-run backend: exact bundle bytes + an in-memory report sink. diff --git a/packages/flow/tests/test_connector.py b/packages/flow/tests/test_connector.py index b70bfc6fb8..8d8427267c 100644 --- a/packages/flow/tests/test_connector.py +++ b/packages/flow/tests/test_connector.py @@ -22,6 +22,7 @@ import json import os import stat +import sys from pathlib import Path import httpx @@ -817,6 +818,160 @@ def test_local_storage_refuses_unpacked_directory_bundle(tmp_path): storage.fetch_bundle_archive("bundles/wf", tmp_path / "scratch.zip") +@pytest.mark.parametrize( + "phase", ["before_child", "no_report", "missing_target", "wrong_target"] +) +def test_local_diagnostic_keeps_child_output_and_refusal_off_the_wire( + tmp_path, monkeypatch, capsys, phase +): + from openadapt_flow import at_rest, crypto + from openadapt_flow.connector.diagnostics import MAX_OUTPUT, read_diagnostics + from openadapt_flow.connector.executor import _subprocess_runner + + marker = "synthetic-private-diagnostic-value" + monkeypatch.setenv(crypto.ENV_KEY, "synthetic-local-encryption") + monkeypatch.setenv(at_rest.MODE_ENV, "strict") + payload = _payload() + if phase == "before_child": + payload["safety"] = {} + cp = StubControlPlane() + cp.enqueue("org_demo", payload) + audit = tmp_path / "egress.jsonl" + client = ConnectorClient( + "https://app.test", + transport=httpx.MockTransport(cp.handler), + egress_audit_log=str(audit), + ) + client.enroll(enrollment_secret="s", org_id="org_demo", name="n") + root = tmp_path / "customer" + bundle = root / payload["storage"]["bundle_ref"] + bundle.parent.mkdir(parents=True) + bundle.write_bytes(_BUNDLE_BYTES) + report = root / payload["storage"]["report_ref"] + fake_report = { + "missing_target": {"success": True}, + "wrong_target": {"execution_target_kind": "citrix"}, + }.get(phase) + + def runner(argv, run_dir, env): + assert phase != "before_child" + program = ( + "import pathlib, sys\n" + f"print('old-prefix' + 'x' * {MAX_OUTPUT + 5000}, flush=True)\n" + f"print({payload['run_token']!r}, flush=True)\n" + f"print('gate detail: {marker}', flush=True)\n" + f"print('run REFUSED: {marker}', file=sys.stderr, flush=True)\n" + ) + if fake_report is not None: + program += ( + f"pathlib.Path(sys.argv[1]).write_text({json.dumps(fake_report)!r})\n" + ) + return _subprocess_runner( + [sys.executable, "-c", program, str(run_dir / "report.json")], run_dir, env + ) + + result = run_once(client, _settings(storage_root=str(root)), runner=runner) + expected = { + "before_child": "governance_refused", + "no_report": "child_no_report", + "missing_target": "child_report_missing_target", + "wrong_target": "target_kind_mismatch", + } + assert result["error_code"] == expected[phase] + assert result["callback_accepted"] + assert result["status"] == ( + "halt" if phase in {"no_report", "missing_target"} else "failed" + ) + sidecar = report.with_name(report.name + ".connector-diagnostics") + if phase == "no_report": + assert not report.exists() + callback = cp.callbacks[0]["body"] + assert callback["report_path"] is None + assert "report_sha256" not in callback["metrics"] + assert marker.encode() not in sidecar.read_bytes() + assert crypto.is_encrypted(sidecar.read_bytes()) + if os.name == "posix": + assert stat.S_IMODE(sidecar.stat().st_mode) == 0o600 + diagnostic = read_diagnostics(sidecar) + assert diagnostic["run_id"] == payload["run_id"] + assert diagnostic["error_code"] == expected[phase] + assert diagnostic["detail"] + if phase == "before_child": + assert "policy" in diagnostic["detail"] + assert diagnostic["child_output"] == "" + else: + assert diagnostic["child_output"].splitlines()[-2:] == [ + f"gate detail: {marker}", + f"run REFUSED: {marker}", + ] + assert "old-prefix" not in diagnostic["child_output"] + assert payload["run_token"] not in diagnostic["child_output"] + assert len(diagnostic["child_output"]) <= MAX_OUTPUT + captured = capsys.readouterr() + shared = ( + captured.out + + captured.err + + str(result) + + str(cp.callbacks) + + str(cp.acks) + + audit.read_text() + ) + assert marker not in shared and diagnostic["detail"] not in shared + + +def test_private_diagnostic_plaintext_requires_recorded_optout(tmp_path, monkeypatch): + from openadapt_flow import at_rest, crypto + from openadapt_flow.connector.diagnostics import read_diagnostics, write_diagnostics + + monkeypatch.delenv(crypto.ENV_KEY, raising=False) + monkeypatch.delenv(at_rest.MODE_ENV, raising=False) + monkeypatch.setenv(at_rest.HOME_ENV, str(tmp_path / "state")) + monkeypatch.setenv(at_rest.LEDGER_DIR_ENV, str(tmp_path / "ledger")) + monkeypatch.setenv(at_rest.OPT_OUT_ENV, "synthetic diagnostics fixture") + at_rest._reset_for_tests() + sidecar = tmp_path / "report.json.connector-diagnostics" + content = {"detail": "synthetic refusal detail"} + write_diagnostics(sidecar, content) + assert not crypto.is_encrypted(sidecar.read_bytes()) + assert read_diagnostics(sidecar) == content + assert "connector diagnostics" in at_rest.ledger_path().read_text() + if os.name == "posix": + sidecar.chmod(0o644) + with pytest.raises(ValueError, match="owner-only"): + read_diagnostics(sidecar) + + +def test_unavailable_private_diagnostic_preserves_authoritative_result( + tmp_path, monkeypatch +): + from openadapt_flow.connector.diagnostics import write_diagnostics + + path = tmp_path / "report.json.connector-diagnostics" + monkeypatch.setenv("OPENADAPT_BUNDLE_KEY", "synthetic-key") + + def refuse_descriptor(fd): + raise PermissionError("synthetic private path detail") + + monkeypatch.setattr( + "openadapt_flow.connector.diagnostics._check_private", refuse_descriptor + ) + with pytest.raises(PermissionError): + write_diagnostics(path, {"detail": "private"}) + assert not list(tmp_path.iterdir()) + + cp = StubControlPlane() + cp.enqueue("org_demo", _payload(safety={})) + client = ConnectorClient( + "https://app.test", transport=httpx.MockTransport(cp.handler) + ) + client.enroll(enrollment_secret="s", org_id="org_demo", name="n") + result = run_once(client, _settings(storage_root=str(tmp_path)), runner=pytest.fail) + assert result["callback_accepted"] and result["status"] == "failed" + assert result["error_code"] == "governance_refused" + assert result["local_diagnostics_unavailable"] is True + assert "local_diagnostics_unavailable" not in str(cp.callbacks) + + def test_local_storage_copies_exact_archive_bytes(tmp_path): archive = tmp_path / "bundles" / "wf.zip" archive.parent.mkdir(parents=True) diff --git a/packages/flow/tests/test_connector_diagnostic_process.py b/packages/flow/tests/test_connector_diagnostic_process.py new file mode 100644 index 0000000000..a6095163ed --- /dev/null +++ b/packages/flow/tests/test_connector_diagnostic_process.py @@ -0,0 +1,61 @@ +"""Cross-platform capture through the connector's real subprocess boundary.""" + +import os +import sys +import time + +from openadapt_flow.connector.diagnostics import MAX_OUTPUT +from openadapt_flow.connector.executor import _subprocess_runner + + +def test_refusal_tail_works_with_inherited_stdout(tmp_path): + # The grandchild inherits stdout. The connector must finish the governed + # child and deliver its last diagnostic without waiting for that grandchild. + release = tmp_path / "release" + expired = tmp_path / "expired" + stopped = tmp_path / "stopped" + descendant = ( + "import pathlib, sys, time\n" + "release, expired, stopped = map(pathlib.Path, sys.argv[1:])\n" + "for _ in range(200):\n" + " if release.exists(): break\n" + " time.sleep(0.05)\n" + "else: expired.touch()\n" + "stopped.touch()\n" + ) + parent = ( + "import subprocess, sys\n" + "subprocess.Popen([sys.executable, '-c', *sys.argv[1:]], stdout=sys.stdout, stderr=sys.stderr)\n" + f"print('discarded-start' + 'x' * {MAX_OUTPUT + 1000}, flush=True)\n" + "print('synthetic admission gate', flush=True)\n" + "print('synthetic refusal', file=sys.stderr, flush=True)\n" + "sys.exit(2)\n" + ) + try: + outcome = _subprocess_runner( + [ + sys.executable, + "-c", + parent, + descendant, + str(release), + str(expired), + str(stopped), + ], + tmp_path, + os.environ, + ) + assert outcome.returncode == 2 + assert not expired.exists() + assert "discarded-start" not in outcome.output + assert len(outcome.output) <= MAX_OUTPUT + assert outcome.output.splitlines()[-2:] == [ + "synthetic admission gate", + "synthetic refusal", + ] + finally: + release.touch() + deadline = time.monotonic() + 5 + while not stopped.exists() and time.monotonic() < deadline: + time.sleep(0.02) + assert stopped.exists() From c7a31be4196b727501f07f840d1d324d82ca88b9 Mon Sep 17 00:00:00 2001 From: Richard Abrich Date: Sat, 21 Nov 2026 00:36:38 -0500 Subject: [PATCH 3/8] Reconcile cancellations that may follow a connector write --- .../flow/openadapt_flow/connector/daemon.py | 5 +- .../flow/openadapt_flow/connector/executor.py | 66 +++++++---- packages/flow/tests/test_connector.py | 106 ++++++++++++++++++ 3 files changed, 155 insertions(+), 22 deletions(-) diff --git a/packages/flow/openadapt_flow/connector/daemon.py b/packages/flow/openadapt_flow/connector/daemon.py index d1bc4ab28f..0cd71d9f07 100644 --- a/packages/flow/openadapt_flow/connector/daemon.py +++ b/packages/flow/openadapt_flow/connector/daemon.py @@ -83,7 +83,10 @@ def phi_free_callback_body(job: ByocJob, result: ExecutionResult) -> dict[str, A body["halt"] = {"present": True} if result.outcome is not None: body["outcome"] = result.outcome - if result.status != "success" and failure_signal_sharing_enabled(): + if result.error_code == "cancelled_after_child_start": + # The interrupted report cannot establish a failure kind or final effect. + body["error_code"] = "cancelled_after_child_start" + elif result.status != "success" and failure_signal_sharing_enabled(): body["failure_signal"] = result.failure_signal or automation_failure_signal( None, result.status, job.target_kind ) diff --git a/packages/flow/openadapt_flow/connector/executor.py b/packages/flow/openadapt_flow/connector/executor.py index fc5849da09..82f2ebdb5c 100644 --- a/packages/flow/openadapt_flow/connector/executor.py +++ b/packages/flow/openadapt_flow/connector/executor.py @@ -265,25 +265,30 @@ class _ChildNotStarted(RuntimeError): """The operating system refused to start the governed process.""" +class _CancelledBeforeStart(RuntimeError): + """The control plane stopped the job before its process was created.""" + + def _subprocess_runner( argv: list[str], run_dir: Path, child_env: Mapping[str, str] ) -> RunOutcome: job_id = getattr(_CURRENT, "job_id", None) - try: - proc = subprocess.Popen( # nosec - fixed argv and exact process-local env - argv, - stdout=subprocess.DEVNULL, - stderr=subprocess.DEVNULL, - env=dict(child_env), - ) - except OSError as exc: - raise _ChildNotStarted(type(exc).__name__) from exc - if job_id: - with _CHILDREN.lock: + # Order cancellation and registration at one boundary. A control that + # wins the lock prevents launch; a control that follows can stop the PID. + with _CHILDREN.lock: + if job_id and job_id in _CHILDREN.cancelled: + raise _CancelledBeforeStart() + 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: _CHILDREN.procs[job_id] = proc - cancelled = job_id in _CHILDREN.cancelled - if cancelled: - proc.terminate() try: proc.wait() finally: @@ -844,6 +849,13 @@ def _execute_job( try: outcome = runner(argv, run_dir, child_env) + except _CancelledBeforeStart: + return _refused( + job, + "cancelled_by_control_plane", + "cancelled before the governed child started", + verified_bundle_sha256=observed_sha256, + ) except _ChildNotStarted as exc: return _refused( job, @@ -872,10 +884,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" + outcome_envelope = precise_outcome_from_report(report) + # Cancellation can race with both the write and the child's final report. + # Retain a validated terminal success or halt for this substrate. Otherwise + # the stop cannot establish what happened to the system of record. + if job_cancelled(job.lease_job_id) and ( + report_target_kind != job.target_kind + or outcome_envelope is None + or status == "failed" + ): + status = "halt" + error_code = "cancelled_after_child_start" + outcome_error = "cancelled after child start; reconcile the system of record" elif report_target_kind != job.target_kind: status = "failed" error_code = "target_kind_mismatch" @@ -923,13 +943,17 @@ def _execute_job( # 4. The PHI-bearing report body goes to the CUSTOMER'S store, never ours. report_ref: Optional[str] = job.report_ref() + if error_code == "cancelled_after_child_start" and not report: + report_ref = None halt = halt_object(report) - outcome_envelope = precise_outcome_from_report(report) + if error_code == "cancelled_after_child_start": + halt = {"present": True} if error_code is not None and outcome_envelope is not None: - # A cancelled or mismatched run never reports a success envelope. + # An uncertain or mismatched run never reports a success envelope. outcome_envelope = None try: - storage.write_report(report_ref, report) + if report_ref is not None: + storage.write_report(report_ref, report) except Exception as exc: # A storage fault says nothing about what the child did, so it # never becomes a runner failure: a run that actuated would show diff --git a/packages/flow/tests/test_connector.py b/packages/flow/tests/test_connector.py index b70bfc6fb8..f4510bf046 100644 --- a/packages/flow/tests/test_connector.py +++ b/packages/flow/tests/test_connector.py @@ -22,6 +22,9 @@ import json import os import stat +import sys +import time +from concurrent.futures import ThreadPoolExecutor from pathlib import Path import httpx @@ -570,6 +573,109 @@ def runner(argv, run_dir, env): assert cp.acks[0]["status"] == "done" +@pytest.mark.parametrize( + "phase", + [ + "before_start", + "at_spawn", + "after_write", + "late_verified", + "wrong_target", + "legacy_success", + "conflicting_exit", + ], +) +def test_cancellation_reports_effect_evidence_and_releases_the_lease(tmp_path, phase): + from openadapt_flow.connector.executor import _subprocess_runner, cancel_job + + cp = StubControlPlane() + cp.enqueue("org_demo", _payload()) + job_id = f"bjob_cancel_{phase}" + cp.jobs[0]["id"] = job_id + client = ConnectorClient( + "https://app.test", transport=httpx.MockTransport(cp.handler) + ) + client.enroll(enrollment_secret="s", org_id="org_demo", name="n") + storage = InMemoryCustomerStorage(bundle_bytes=_BUNDLE_BYTES) + record = tmp_path / "synthetic-record" + if phase == "before_start": + cancel_job(job_id) + + def runner(argv, run_dir, env): + # The subprocess writes a real synthetic record. A control delivered + # before the executor consumes its result can still observe either an + # incomplete or an already-finalized report. + assert phase != "before_start" + report = VERIFIED_REPORT + if phase == "legacy_success": + report = SUCCESS_REPORT + elif phase == "wrong_target": + report = {**VERIFIED_REPORT, "execution_target_kind": "citrix"} + child = ( + "import pathlib, sys, time\n" + "with pathlib.Path(sys.argv[1]).open('a') as saved: saved.write('saved\\n')\n" + "if sys.argv[2]: pathlib.Path(sys.argv[2]).write_text(sys.argv[3])\n" + "else: time.sleep(10)\n" + "sys.exit(int(sys.argv[4]))\n" + ) + command = [ + sys.executable, + "-c", + child, + str(record), + "" if phase == "after_write" else str(run_dir / "report.json"), + json.dumps(report), + "1" if phase == "conflicting_exit" else "0", + ] + if phase == "at_spawn": + cancel_job(job_id) + if phase == "after_write": + def stop_after_write(): + deadline = time.monotonic() + 8 + while time.monotonic() < deadline: + if record.exists() and record.read_text() == "saved\n": + return cancel_job(job_id) + time.sleep(0.02) + return False + + with ThreadPoolExecutor(max_workers=1) as pool: + stopped = pool.submit(stop_after_write) + outcome = _subprocess_runner(command, run_dir, env) + assert stopped.result() and outcome.returncode != 0 + return outcome + outcome = _subprocess_runner(command, run_dir, env) + cancel_job(job_id) + return outcome + + result = run_once( + client, _settings(), runner=runner, storage_factory=lambda job: storage + ) + assert result["callback_accepted"] and len(cp.callbacks) == len(cp.acks) == 1 + body, ack = cp.callbacks[0]["body"], cp.acks[0] + assert "synthetic-record" not in json.dumps(body) + if phase in {"before_start", "at_spawn"}: + assert not record.exists() + assert result["status"] == body["status"] == ack["status"] == "failed" + assert ack["error_code"] == "cancelled_by_control_plane" + else: + assert record.read_text().splitlines() == ["saved"] + assert ack["status"] == "done" + assert body["bundle_sha256"] == _BUNDLE_SHA256 + if phase == "late_verified": + assert result["status"] == body["status"] == "success" + assert body["outcome"]["outcome"] == "VERIFIED" + assert ack["error_code"] is None + else: + assert result["status"] == body["status"] == "halt" + assert body["halt"] == {"present": True} and "outcome" not in body + assert ack["error_code"] == body["error_code"] + assert ack["error_code"] == "cancelled_after_child_start" + assert "failure_signal" not in body + if phase == "after_write": + assert body["report_path"] is None + assert "report_sha256" not in body["metrics"] + + def test_report_write_failure_lease_is_not_acked_failed(): cp = StubControlPlane() cp.enqueue("org_demo", _payload()) From ecb591be41b143aace590f4ea15b953b003af34d Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 00:40:44 -0500 Subject: [PATCH 4/8] Omit unwritten report references from connector refusals --- .../flow/openadapt_flow/connector/executor.py | 28 ++++++++----------- packages/flow/tests/test_connector.py | 8 ++++-- 2 files changed, 17 insertions(+), 19 deletions(-) diff --git a/packages/flow/openadapt_flow/connector/executor.py b/packages/flow/openadapt_flow/connector/executor.py index 6db2f2f8d8..c7e52f897d 100644 --- a/packages/flow/openadapt_flow/connector/executor.py +++ b/packages/flow/openadapt_flow/connector/executor.py @@ -641,9 +641,15 @@ def remember_secrets(values: list[str]) -> None: _CURRENT.job_id = None -def _refused(job: ByocJob, code: str, detail: str, **extra: Any) -> ExecutionResult: +def _refused(code: str, detail: str, **extra: Any) -> ExecutionResult: return ExecutionResult( - "failed", {}, None, job.report_ref(), detail, error_code=code, **extra + status="failed", + metrics={}, + halt=None, + report_ref=None, + error=detail, + error_code=code, + **extra, ) @@ -662,7 +668,7 @@ def _execute_job( job.ensure_governed(require_run_token=require_run_token) _assert_managed_authority_is_pinned(job, settings) except ByocGovernanceError as exc: - return _refused(job, "governance_refused", str(exc)) + return _refused("governance_refused", str(exc)) admission = job.program_admission() if admission is not None and ( admission["public_key_hex"] not in settings.pinned_admission_keys() @@ -670,27 +676,23 @@ def _execute_job( # The control plane can name an admission key, but only this machine's # own configuration decides which admitters it trusts. return _refused( - job, "admission_key_not_pinned", "the program's admission key is not pinned in trusted_admission_keys", ) if admission is not None and admission.get("admission_mode") == "admitter_key": if not settings.admission_key_dir: return _refused( - job, "admission_registry_required", "admitter jobs require current local public trust", ) if admission is None and not settings.qualification_authority_file: return _refused( - job, "qualification_authority_unavailable", "qualified jobs need independent local context", ) if not _grounding_env_available(job): gm = job.grounding_model return _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", @@ -700,7 +702,7 @@ def _execute_job( job.secrets_ref or settings.default_secrets_ref ) except SecretStoreError as exc: - return _refused(job, "secrets_unavailable", str(exc)) + return _refused("secrets_unavailable", str(exc)) if on_secrets is not None and secret_env: on_secrets(list(secret_env.values())) signers_json: Optional[str] = None @@ -711,7 +713,7 @@ def _execute_job( ) except OSError: return _refused( - job, "signers_unavailable", "qualification signer registry unreadable" + "signers_unavailable", "qualification signer registry unreadable" ) with tempfile.TemporaryDirectory(prefix="oa-byoc-") as tmp: @@ -739,7 +741,6 @@ def _execute_job( bundle_dir = bundle_scratch except Exception as exc: # storage failure: fail closed return _refused( - job, "bundle_fetch_failed", f"customer-storage bundle fetch failed: {type(exc).__name__}", ) @@ -754,7 +755,6 @@ def _execute_job( 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, @@ -764,7 +764,6 @@ def _execute_job( != admission["admission_sha256"] ): return _refused( - job, "program_admission_refused", "the archive's admission is not the dispatched one", verified_bundle_sha256=observed_sha256, @@ -784,7 +783,6 @@ def _execute_job( _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, @@ -797,7 +795,6 @@ def _execute_job( ) except Exception: return _refused( - job, "qualification_authority_refused", "local qualification context refused", verified_bundle_sha256=observed_sha256, @@ -878,14 +875,12 @@ def _execute_job( ) if job_cancelled(job.lease_job_id): return _refused( - job, "cancelled_by_control_plane", "cancelled before the governed child started", verified_bundle_sha256=observed_sha256, ) except Exception as exc: return _refused( - job, "child_invocation_failed", f"governed child invocation failed: {type(exc).__name__}", verified_bundle_sha256=observed_sha256, @@ -895,7 +890,6 @@ def _execute_job( 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, diff --git a/packages/flow/tests/test_connector.py b/packages/flow/tests/test_connector.py index 8d8427267c..869faf5324 100644 --- a/packages/flow/tests/test_connector.py +++ b/packages/flow/tests/test_connector.py @@ -883,11 +883,15 @@ def runner(argv, run_dir, env): "halt" if phase in {"no_report", "missing_target"} else "failed" ) sidecar = report.with_name(report.name + ".connector-diagnostics") - if phase == "no_report": + callback = cp.callbacks[0]["body"] + if phase in {"before_child", "no_report"}: assert not report.exists() - callback = cp.callbacks[0]["body"] assert callback["report_path"] is None assert "report_sha256" not in callback["metrics"] + else: + assert callback["report_path"] == payload["storage"]["report_ref"] + stored_digest = hashlib.sha256(report.read_bytes()).hexdigest() + assert callback["metrics"]["report_sha256"] == stored_digest assert marker.encode() not in sidecar.read_bytes() assert crypto.is_encrypted(sidecar.read_bytes()) if os.name == "posix": From e7bc2183985efb581eb9191804a64a6b1936c7de Mon Sep 17 00:00:00 2001 From: Richard Abrich Date: Sat, 21 Nov 2026 01:36:46 -0500 Subject: [PATCH 5/8] Apply Ruff to the cancellation outcome and test --- packages/flow/openadapt_flow/connector/executor.py | 4 +++- packages/flow/tests/test_connector.py | 1 + 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/packages/flow/openadapt_flow/connector/executor.py b/packages/flow/openadapt_flow/connector/executor.py index 82f2ebdb5c..99e57df039 100644 --- a/packages/flow/openadapt_flow/connector/executor.py +++ b/packages/flow/openadapt_flow/connector/executor.py @@ -895,7 +895,9 @@ def _execute_job( ): status = "halt" error_code = "cancelled_after_child_start" - outcome_error = "cancelled after child start; reconcile the system of record" + outcome_error = ( + "cancelled after child start; reconcile the system of record" + ) elif report_target_kind != job.target_kind: status = "failed" error_code = "target_kind_mismatch" diff --git a/packages/flow/tests/test_connector.py b/packages/flow/tests/test_connector.py index f4510bf046..0a0b305d13 100644 --- a/packages/flow/tests/test_connector.py +++ b/packages/flow/tests/test_connector.py @@ -630,6 +630,7 @@ def runner(argv, run_dir, env): if phase == "at_spawn": cancel_job(job_id) if phase == "after_write": + def stop_after_write(): deadline = time.monotonic() + 8 while time.monotonic() < deadline: From a9b9a699126e6fd8a16a89cd94e9e7997b76bf01 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 02:27:22 -0500 Subject: [PATCH 6/8] Distinguish pre-launch governance and egress refusals in connector tests --- packages/flow/tests/test_connector.py | 34 +++++++++++++++++++-------- 1 file changed, 24 insertions(+), 10 deletions(-) diff --git a/packages/flow/tests/test_connector.py b/packages/flow/tests/test_connector.py index 869faf5324..1464d946d4 100644 --- a/packages/flow/tests/test_connector.py +++ b/packages/flow/tests/test_connector.py @@ -49,7 +49,10 @@ ByocGovernanceError, ) from openadapt_flow.connector.storage import LocalCustomerStorage -from openadapt_flow.failure_signals import automation_failure_signal +from openadapt_flow.failure_signals import ( + AUTOMATION_FAILURE_SIGNAL_SCHEMA, + automation_failure_signal, +) from openadapt_flow.runner.dispatch_envelope import ManagedDispatchEnvelope from openadapt_flow.runner.protocol import dispatch_binding_sha256 from openadapt_flow.runtime.authorization import GovernedRunAuthorization @@ -513,15 +516,19 @@ 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): +@pytest.mark.parametrize( + "phase", ["before_child", "before_child_egress", "verified", "failed_after_write"] +) +def test_egress_refusal_reports_whether_the_child_could_have_written( + tmp_path, monkeypatch, 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. + # An unsafe planned report key reaches the guard only if the child wrote a report. + before_child = phase in {"before_child", "before_child_egress"} if phase != "verified": payload["storage"]["report_ref"] = "synthetic private report" - if phase == "before_child": + if before_child: payload["safety"] = {} cp.enqueue("org_demo", payload) client = ConnectorClient( @@ -529,6 +536,11 @@ def test_egress_refusal_reports_whether_the_child_could_have_written(tmp_path, p ) client.enroll(enrollment_secret="s", org_id="org_demo", name="n") client.add_secret_values(["effect_tier_1"]) + if phase == "before_child_egress": + # Exercise a real pre-child egress refusal in the optional failure signal. + monkeypatch.delenv("DO_NOT_TRACK", raising=False) + monkeypatch.setenv("OPENADAPT_TELEMETRY", "1") + client.add_secret_values([AUTOMATION_FAILURE_SIGNAL_SCHEMA]) record = tmp_path / "synthetic-record.txt" def runner(argv, run_dir, env): @@ -548,14 +560,16 @@ def runner(argv, run_dir, env): storage_factory=lambda job: InMemoryCustomerStorage(bundle_bytes=_BUNDLE_BYTES), ) - assert result["error_code"] == "egress_refused" + expected_code = "governance_refused" if phase == "before_child" else "egress_refused" assert result["callback_accepted"] assert len(cp.callbacks) == len(cp.acks) == 1 + assert result["error_code"] == cp.acks[0]["error_code"] == expected_code 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 "outcome" not in callback + if expected_code == "egress_refused": + assert "failure_signal" not in callback + if before_child: assert not record.exists() assert ( result["status"] == callback["status"] == cp.acks[0]["status"] == "failed" From 3cd8eaace7bb569537271b0016ca9e29be32d0ad Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 05:46:51 -0500 Subject: [PATCH 7/8] Format the connector refusal expectation with pinned Ruff --- packages/flow/tests/test_connector.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/packages/flow/tests/test_connector.py b/packages/flow/tests/test_connector.py index 9415d68ddc..f8f69fbe7e 100644 --- a/packages/flow/tests/test_connector.py +++ b/packages/flow/tests/test_connector.py @@ -562,7 +562,9 @@ def runner(argv, run_dir, env): storage_factory=lambda job: InMemoryCustomerStorage(bundle_bytes=_BUNDLE_BYTES), ) - expected_code = "governance_refused" if phase == "before_child" else "egress_refused" + expected_code = ( + "governance_refused" if phase == "before_child" else "egress_refused" + ) assert result["callback_accepted"] assert len(cp.callbacks) == len(cp.acks) == 1 assert result["error_code"] == cp.acks[0]["error_code"] == expected_code From d42513eb908e054b296f1314f4bc2ca0d29c1c02 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 07:02:23 -0500 Subject: [PATCH 8/8] Require exact option spellings for the connector diagnostics CLI --- packages/flow/openadapt_flow/connector/diagnostics.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/packages/flow/openadapt_flow/connector/diagnostics.py b/packages/flow/openadapt_flow/connector/diagnostics.py index 4ce8d6a99b..c8b0769731 100644 --- a/packages/flow/openadapt_flow/connector/diagnostics.py +++ b/packages/flow/openadapt_flow/connector/diagnostics.py @@ -127,7 +127,8 @@ def read_diagnostics(path: Path) -> dict[str, Any]: if __name__ == "__main__": parser = argparse.ArgumentParser( - description="Read a private local connector diagnostic." + description="Read a private local connector diagnostic.", + allow_abbrev=False, ) parser.add_argument("path", type=Path) try: