diff --git a/packages/flow/openadapt_flow/connector/daemon.py b/packages/flow/openadapt_flow/connector/daemon.py index fd9397ad99..a4746d4a96 100644 --- a/packages/flow/openadapt_flow/connector/daemon.py +++ b/packages/flow/openadapt_flow/connector/daemon.py @@ -252,10 +252,14 @@ class _ActiveJobs: def __init__(self) -> None: self.lock = threading.Lock() self.futures: dict[str, Future[dict[str, Any]]] = {} + #: Jobs about to be submitted: listed before ``pool.submit`` so a stop + #: signal between the submit and the future's registration still + #: reaches the job through shutdown's ``cancel_job``. + self.pending: set[str] = set() def ids(self) -> list[str]: with self.lock: - return list(self.futures) + return list(self.futures) + sorted(self.pending - set(self.futures)) def reap(self, log: Callable[[str], None]) -> int: done = 0 @@ -497,6 +501,8 @@ def heartbeat() -> None: job = _job_from_envelope(client, envelope) if job is None or not job.lease_job_id: continue + with active.lock: + active.pending.add(job.lease_job_id) fut = pool.submit( handle_job, client, @@ -508,6 +514,7 @@ def heartbeat() -> None: ) with active.lock: active.futures[job.lease_job_id] = fut + active.pending.discard(job.lease_job_id) except KeyboardInterrupt: # operator Ctrl-C or service stop log("[connector] interrupted; exiting") finally: diff --git a/packages/flow/openadapt_flow/connector/executor.py b/packages/flow/openadapt_flow/connector/executor.py index 623ace68ca..99c4eb00c8 100644 --- a/packages/flow/openadapt_flow/connector/executor.py +++ b/packages/flow/openadapt_flow/connector/executor.py @@ -17,8 +17,9 @@ ``api_key_env`` is NOT set in the Connector's own environment, the job is refused — the org required a governed control this machine cannot honor, so we halt rather than silently run without it; -* the resolved policy is written to ``/governed_policy.json`` for the - operator's local audit trail. +* the resolved policy is written to ``governed_policy.json`` in the job's + private staging directory (beside the run directory, never in it) for the + operator's local audit trail while the job runs. The PHI-bearing report.json is written to the CUSTOMER'S storage and stays local; only PHI-free status/metrics are returned for the callback. @@ -308,22 +309,41 @@ def _subprocess_runner( with _CHILDREN.lock: _CHILDREN.procs.pop(job_id, None) return RunOutcome( - returncode=proc.returncode, report=_read_report(run_dir / "report.json") + returncode=proc.returncode, + report=_read_report(run_dir / "report.json", key=_run_key(child_env)), ) -def _read_report(report_path: Path) -> dict[str, Any]: +def _run_key(child_env: Mapping[str, str]) -> Optional[str]: + """The key the child seals its run with, from the child's own environment. + + A key delivered only through the job's ``secrets_ref`` reaches the child + but not this process, so the report is opened with the same value. It is + held in memory for the read only, never logged or written. + """ + from openadapt_flow import crypto + from openadapt_flow import sealed_set as _sealed + + return child_env.get(crypto.ENV_KEY) or child_env.get(_sealed.RECORDING_ENV_KEY) + + +def _read_report(report_path: Path, key: Optional[str] = None) -> 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. + (:mod:`openadapt_flow.sealed_set`), so it is read through the sealed set, + with ``key`` when given (the child's key) and otherwise this process's. 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): + root = _sealed.sealed_root(report_path) + if root is not None and key: + rel = report_path.resolve().relative_to(root.resolve()).as_posix() + text = _sealed.open_set(root, key).read_bytes(rel).decode("utf-8") + elif _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") @@ -425,7 +445,7 @@ def halt_object(report: dict[str, Any]) -> Optional[dict[str, Any]]: return None -def _write_params_file(params: dict[str, Any], run_dir: Path) -> Optional[Path]: +def _write_params_file(params: dict[str, Any], staging: Path) -> Optional[Path]: """Write runtime params to a 0600 file so values stay OFF the process table. Drops the internal ``target_kind`` routing hint (not a workflow param). @@ -433,7 +453,7 @@ def _write_params_file(params: dict[str, Any], run_dir: Path) -> Optional[Path]: clean = {k: v for k, v in params.items() if k != "target_kind"} if not clean: return None - pf = run_dir / "params.json" + pf = staging / "params.json" pf.write_text(json.dumps(clean), encoding="utf-8") try: os.chmod(pf, 0o600) @@ -442,10 +462,10 @@ def _write_params_file(params: dict[str, Any], run_dir: Path) -> Optional[Path]: return pf -def _write_policy_audit(job: ByocJob, run_dir: Path) -> None: +def _write_policy_audit(job: ByocJob, staging: Path) -> None: """Record the delivered governed policy locally for the operator audit.""" try: - (run_dir / "governed_policy.json").write_text( + (staging / "governed_policy.json").write_text( json.dumps( { "run_id": job.run_id, @@ -548,7 +568,7 @@ def _verify_program_reference(job: ByocJob, bundle: Path, key_dir: Path) -> None def _stage_qualification_authority( - job: ByocJob, settings: ConnectorSettings, bundle: Path, run_dir: Path + job: ByocJob, settings: ConnectorSettings, bundle: Path, staging: Path ) -> Path: """Use independent local authority context; never self-assert expectations.""" from openadapt_flow.ir import Workflow @@ -591,7 +611,7 @@ def _stage_qualification_authority( raise ByocGovernanceError( "local qualification context changed during verification" ) - destination = run_dir / "qualification-authority.json" + destination = staging / "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: @@ -716,11 +736,20 @@ def _execute_job( bundle_scratch = tmp_path / "bundle" run_dir = tmp_path / "run" readback_dir = tmp_path / "readback" + # The connector's own plaintext inputs (policy audit, params, dispatch + # envelope, qualification context) live beside the run, never in it: + # a sealed bundle's run directory is a sealed set that refuses any + # plaintext file at finalize, which would halt every sealed job. + # tmp_path is a 0700 directory removed when the job ends, however it + # ends; staging is 0700 too. + staging = tmp_path / "staging" bundle_scratch.mkdir(parents=True, exist_ok=True) run_dir.mkdir(parents=True, exist_ok=True) readback_dir.mkdir(parents=True, exist_ok=True) + staging.mkdir(mode=0o700) + os.chmod(staging, 0o700) - _write_policy_audit(job, run_dir) + _write_policy_audit(job, staging) # 2. Copy and verify the EXACT approved archive bytes from the customer's # storage before extraction. @@ -789,7 +818,7 @@ def _execute_job( if admission is None: try: qualification_authority_file = _stage_qualification_authority( - job, settings, bundle_dir, run_dir + job, settings, bundle_dir, staging ) except Exception: return _refused( @@ -800,7 +829,7 @@ def _execute_job( ) try: - params_file = _write_params_file(job.params, run_dir) + params_file = _write_params_file(job.params, staging) managed_dispatch_file = None child_env = os.environ.copy() # Never let a long-running Connector inherit stale authority from @@ -821,7 +850,7 @@ def _execute_job( 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.flow_dispatch() + staging / "managed-dispatch.json", job.flow_dispatch() ) child_env[REMOTE_AUTHORITY_URL_ENV] = str( job.managed_delivery_authority_url @@ -834,7 +863,7 @@ def _execute_job( # 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" + readback_params = staging / "readback-params.json" if readback_sha256: readback_params.write_text( json.dumps( diff --git a/packages/flow/tests/test_connector_sealed_staging.py b/packages/flow/tests/test_connector_sealed_staging.py new file mode 100644 index 0000000000..b68d44aa59 --- /dev/null +++ b/packages/flow/tests/test_connector_sealed_staging.py @@ -0,0 +1,189 @@ +"""A sealed bundle's BYOC job finishes cleanly: the connector's own plaintext +inputs never land in the run directory, the run's sealed report is read with +the key the child got, and a stop signal never misses a job being submitted. +Synthetic data only; no browser.""" + +from __future__ import annotations + +import os +import stat +import sys +import textwrap +from pathlib import Path + +from openadapt_flow import crypto, sealed_set +from openadapt_flow.connector import daemon as daemon_mod +from openadapt_flow.connector import executor as executor_mod +from openadapt_flow.connector.executor import ( + RunOutcome, + _subprocess_runner, + execute_job, +) +from openadapt_flow.connector.protocol import parse_job +from openadapt_flow.connector.storage import InMemoryCustomerStorage +from tests import test_connector_pilot as pilot + +KEY = "synthetic-sealed-byoc-key-0123456789" + +# Exactly what the governed child does for a sealed bundle +# (runtime/durable/first_local_runtime.py): open the run directory as a sealed +# writer, write the report through it, then finalize with adopt_external=True, +# which refuses any plaintext file found in the run directory. +SEALED_CHILD = textwrap.dedent( + """ + import json, os, sys + from pathlib import Path + from openadapt_flow import sealed_set + + run = Path(sys.argv[1]) + key = os.environ["OPENADAPT_BUNDLE_KEY"] + writer = sealed_set.SealedSetWriter( + run, "run", key, resume=sealed_set.is_sealed(run) + ) + sealed_set.register_writer(writer) + try: + sealed_set.write_bytes(run / "report.json", json.dumps({ + "execution_target_kind": "web", + "execution_outcome": "VERIFIED", + "success": True, + "terminal_outcome": "success", + "results": [], + }).encode("utf-8")) + finally: + sealed_set.unregister_writer(writer) + writer.finalize(adopt_external=True) + """ +) + + +# The pilot module's signed program case and offline read-back, reused as is +# (pytest registers fixtures found in a test module's namespace). +from tests.test_connector_pilot import ( # noqa: E402,F401 + _signed_transport_program, + _transport_has_no_external_readback, +) + + +def _flag_values(argv: list[str], flag: str) -> list[str]: + return [argv[i + 1] for i, a in enumerate(argv) if a == flag] + + +def test_a_sealed_job_finishes_cleanly_with_its_key_only_in_secrets_ref( + tmp_path, monkeypatch +): + # The daemon itself holds no bundle key: only the job's secrets_ref does. + monkeypatch.delenv(crypto.ENV_KEY, raising=False) + monkeypatch.delenv(sealed_set.RECORDING_ENV_KEY, raising=False) + secrets_dir = tmp_path / "secrets" + secrets_dir.mkdir() + secret_file = secrets_dir / "sealed-run.env" + secret_file.write_text(f"{crypto.ENV_KEY}={KEY}\n", encoding="utf-8") + os.chmod(secret_file, 0o600) + job = parse_job( + pilot._payload(secrets_ref="sealed-run"), lease_job_id="bjob_sealed" + ) + seen: dict = {} + + def runner(argv, run_dir: Path, child_env) -> RunOutcome: + staged = [ + Path(p) + for flag in ("--params-file", "--managed-dispatch-file") + for p in _flag_values(argv, flag) + ] + seen.update( + run_dir=run_dir, + staged=staged, + before=sorted(p.name for p in run_dir.iterdir()), + staging_mode=stat.S_IMODE(staged[0].parent.stat().st_mode), + ) + # The real _subprocess_runner and a real child process that seals the + # run exactly as the governed child does. + outcome = _subprocess_runner( + [sys.executable, "-c", SEALED_CHILD, str(run_dir)], run_dir, child_env + ) + seen["after"] = sorted(p.name for p in run_dir.iterdir()) + seen["sealed"] = sealed_set.is_sealed(run_dir) + return outcome + + result = execute_job( + job, + pilot._configured_settings(secrets_dir=str(secrets_dir)), + InMemoryCustomerStorage(pilot.PLAIN_BUNDLE), + runner=runner, + ) + + assert result.status == "success", (result.status, result.error_code) + assert result.error_code is None and result.halt is None + # Nothing the connector wrote was in the run directory, before or after. + assert seen["before"] == [] + assert seen["sealed"] is True + assert "report.json" not in seen["after"] or seen["sealed"] + assert seen["staged"], "the params and dispatch files were staged" + for path in seen["staged"]: + assert seen["run_dir"] not in path.parents + assert seen["staging_mode"] == 0o700 + # The whole per-job directory, staging included, is gone afterwards. + assert not seen["run_dir"].exists() + for path in seen["staged"]: + assert not path.exists() and not path.parent.exists() + + +def test_a_sealed_report_without_the_childs_key_is_unknown(tmp_path, monkeypatch): + monkeypatch.delenv(crypto.ENV_KEY, raising=False) + monkeypatch.delenv(sealed_set.RECORDING_ENV_KEY, raising=False) + run = tmp_path / "run" + run.mkdir() + env = {**os.environ, crypto.ENV_KEY: KEY} + outcome = _subprocess_runner( + [sys.executable, "-c", SEALED_CHILD, str(run)], run, env + ) + assert outcome.returncode == 0 + assert outcome.report["execution_outcome"] == "VERIFIED" + # Read with no key, or the wrong one: never a report, so never a verdict. + report = run / "report.json" + assert executor_mod._read_report(report, key="not the key") == {} + assert executor_mod._read_report(report, key=None) == {} + + +def test_plaintext_in_a_sealed_run_directory_is_refused(tmp_path): + """Why staging moved: the sealed run refuses a plaintext file beside it.""" + run = tmp_path / "run" + run.mkdir() + (run / "params.json").write_text("{}", encoding="utf-8") + env = {**os.environ, crypto.ENV_KEY: KEY} + outcome = _subprocess_runner( + [sys.executable, "-c", SEALED_CHILD, str(run)], run, env + ) + assert outcome.returncode != 0 + + +def test_a_stop_between_submit_and_register_still_cancels_the_job(monkeypatch): + plane = pilot.RecordingPlane() + plane.jobs.append( + {"id": "bjob_gap", "status": "queued", "payload": pilot._payload()} + ) + client = pilot._client(plane) + cancelled: list[str] = [] + monkeypatch.setattr( + daemon_mod, "cancel_job", lambda job_id: cancelled.append(job_id) or True + ) + real_submit = daemon_mod.ThreadPoolExecutor.submit + + def submit_then_stop(self, *args, **kwargs): + real_submit(self, *args, **kwargs) + raise KeyboardInterrupt # the stop lands before the future is listed + + monkeypatch.setattr(daemon_mod.ThreadPoolExecutor, "submit", submit_then_stop) + settings = pilot._configured_settings( + control_plane_url="https://cloud.test", + token=pilot.TOKEN, + poll_wait_s=0, + ) + daemon_mod.run_loop( + client, + settings, + runner=lambda argv, run_dir, env: RunOutcome(returncode=0, report={}), + storage_factory=lambda job: InMemoryCustomerStorage(pilot.PLAIN_BUNDLE), + log=lambda _m: None, + ) + assert "bjob_gap" in cancelled