diff --git a/.github/workflows/connector-windows-service.yml b/.github/workflows/connector-windows-service.yml index c80e4197cb..a4d2feeac0 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: | @@ -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 89e72b910d..dc2ffcc6a9 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:uid=10001,gid=10001,mode=0700 \ -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 860ea52c94..b81aa215f7 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 14da1c2083..170fdba0bc 100644 --- a/packages/flow/openadapt_flow/at_rest.py +++ b/packages/flow/openadapt_flow/at_rest.py @@ -29,7 +29,7 @@ * In the default mode, each output that still can't be encrypted goes through :func:`unsealed_write`: stderr names the path and a ledger line (``plaintext-at-rest.jsonl``) records it, and Desktop shows the ledger as a - notice. + notice. ``OPENADAPT_FLOW_PLAINTEXT_LEDGER_DIR`` relocates only this ledger. * ``OPENADAPT_ENCRYPT_AT_REST=0`` (or ``record --no-encrypt``, ``compile --no-encrypt``, ``run --no-encrypt``) turns encryption off, and ``OPENADAPT_FLOW_PLAINTEXT_AT_REST=''`` does the same with a reason. @@ -195,6 +195,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: @@ -228,7 +229,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]: @@ -316,7 +318,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 ad201ef303..ad77397a8b 100644 --- a/packages/flow/openadapt_flow/connector/cli.py +++ b/packages/flow/openadapt_flow/connector/cli.py @@ -245,6 +245,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/daemon.py b/packages/flow/openadapt_flow/connector/daemon.py index 2cba94ec78..b7ab148ec6 100644 --- a/packages/flow/openadapt_flow/connector/daemon.py +++ b/packages/flow/openadapt_flow/connector/daemon.py @@ -145,6 +145,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 @@ -187,13 +188,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..c8b0769731 --- /dev/null +++ b/packages/flow/openadapt_flow/connector/diagnostics.py @@ -0,0 +1,144 @@ +"""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.", + allow_abbrev=False, + ) + 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 7f3ff34bb2..2134155c16 100644 --- a/packages/flow/openadapt_flow/connector/executor.py +++ b/packages/flow/openadapt_flow/connector/executor.py @@ -64,6 +64,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. @@ -76,6 +77,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 @@ -92,12 +94,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 ----------------------- @@ -280,6 +284,8 @@ class _CancelledBeforeStart(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) # Order cancellation and registration at one boundary. A control that # wins the lock prevents launch; a control that follows can stop the PID. @@ -289,8 +295,8 @@ def _subprocess_runner( 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), # Its own session: an operator Ctrl-C or a service stop signals # the daemon's process group, not the governed child. The daemon @@ -302,7 +308,7 @@ def _subprocess_runner( if job_id: _CHILDREN.procs[job_id] = proc try: - proc.wait() + output = child_output(proc) except BaseException: # Interrupted while waiting (an inline run's Ctrl-C): never leave the # child running in its own session. The interrupt still propagates, @@ -310,12 +316,14 @@ def _subprocess_runner( _stop(proc) raise finally: + proc.wait() if job_id: with _CHILDREN.lock: _CHILDREN.procs.pop(job_id, None) return RunOutcome( returncode=proc.returncode, report=_read_report(run_dir / "report.json", key=_run_key(child_env)), + output=output, ) @@ -647,24 +655,70 @@ 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 -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, ) @@ -683,7 +737,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() @@ -691,27 +745,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", @@ -721,7 +771,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 @@ -732,7 +782,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: @@ -769,7 +819,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__}", ) @@ -784,7 +833,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, @@ -794,7 +842,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, @@ -814,7 +861,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, @@ -827,7 +873,6 @@ def _execute_job( ) except Exception: return _refused( - job, "qualification_authority_refused", "local qualification context refused", verified_bundle_sha256=observed_sha256, @@ -908,14 +953,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, @@ -925,14 +968,12 @@ def _execute_job( 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, "child_invocation_failed", f"governed child did not start: {exc}", verified_bundle_sha256=observed_sha256, @@ -991,6 +1032,13 @@ def _execute_job( outcome_error = ( "cancelled after child start; reconcile the system of record" ) + elif report_target_kind is not None and 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)" + ) elif outcome_unknown: status = "halt" error_code = "child_outcome_unknown" @@ -999,12 +1047,13 @@ def _execute_job( "(cancelled, stopped or killed while running, or killed after " "reporting success), so a write may have landed" ) - elif report_target_kind != job.target_kind: - status = "failed" - error_code = "target_kind_mismatch" + elif report_target_kind is None: + # Exit status alone cannot establish what happened to the record. + status = "halt" + error_code = "child_report_missing_target" outcome_error = ( - "governed child report execution_target_kind does not match " - "the signed dispatch target_kind (fail closed)" + f"governed child exited with code {outcome.returncode} and " + "no execution_target_kind in its report" ) else: outcome_error = None @@ -1045,14 +1094,13 @@ 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 in ("cancelled_after_child_start", "child_outcome_unknown") - and not report - ): - report_ref = None + # 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 error_code in ("cancelled_after_child_start", "child_outcome_unknown"): + if status == "halt" and ( + halt is None + or error_code in ("cancelled_after_child_start", "child_outcome_unknown") + ): halt = {"present": True} if error_code is not None and outcome_envelope is not None: # An uncertain or mismatched run never reports a success envelope. @@ -1097,4 +1145,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/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/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/openadapt_flow/connector/windows_service.py b/packages/flow/openadapt_flow/connector/windows_service.py index 86aa166c45..a800afa38c 100644 --- a/packages/flow/openadapt_flow/connector/windows_service.py +++ b/packages/flow/openadapt_flow/connector/windows_service.py @@ -238,6 +238,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 rotation = None # The administrator owns the bootstrap and destination. Explicit # environment credentials or destinations keep their operator-managed diff --git a/packages/flow/tests/conftest.py b/packages/flow/tests/conftest.py index 131ab40e96..d782321e92 100644 --- a/packages/flow/tests/conftest.py +++ b/packages/flow/tests/conftest.py @@ -158,6 +158,7 @@ def _isolation_env(root: Path) -> dict[str, str | None]: # never land inside a recording or run directory a test seals. "OPENADAPT_FLOW_AT_REST_HOME": _SESSION_AT_REST_HOME or str(root / ".at-rest-home"), + "OPENADAPT_FLOW_PLAINTEXT_LEDGER_DIR": None, "OPENADAPT_FLOW_AT_REST": None, # The device key goes to a file in the isolated home, never to the # OS keychain (no dialog, no write to the person's login keychain). diff --git a/packages/flow/tests/test_connector.py b/packages/flow/tests/test_connector.py index 0a0b305d13..3e63350d7f 100644 --- a/packages/flow/tests/test_connector.py +++ b/packages/flow/tests/test_connector.py @@ -51,7 +51,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 @@ -515,15 +518,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( @@ -531,6 +538,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): @@ -550,14 +562,18 @@ 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" @@ -655,6 +671,9 @@ def stop_after_write(): 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 storage.written == {} + assert body["report_path"] is None + assert "report_sha256" not in body["metrics"] assert not record.exists() assert result["status"] == body["status"] == ack["status"] == "failed" assert ack["error_code"] == "cancelled_by_control_plane" @@ -673,6 +692,7 @@ def stop_after_write(): assert ack["error_code"] == "cancelled_after_child_start" assert "failure_signal" not in body if phase == "after_write": + assert storage.written == {} assert body["report_path"] is None assert "report_sha256" not in body["metrics"] @@ -924,6 +944,164 @@ 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_outcome_unknown", + "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") + callback = cp.callbacks[0]["body"] + if phase in {"before_child", "no_report"}: + assert not report.exists() + 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": + 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_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_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() diff --git a/packages/flow/tests/test_connector_service_rotation.py b/packages/flow/tests/test_connector_service_rotation.py index 2fce2fd2bf..b7c694c3c3 100644 --- a/packages/flow/tests/test_connector_service_rotation.py +++ b/packages/flow/tests/test_connector_service_rotation.py @@ -48,6 +48,9 @@ def CredDelete(self, target, kind): @pytest.fixture(autouse=True) def service_environment(monkeypatch, tmp_path): monkeypatch.setenv("OPENADAPT_HOME", str(tmp_path)) + profile = tmp_path / "deployment.yaml" + profile.write_text("runtime: {profile: standard}\n", encoding="utf-8") + monkeypatch.setenv("BYOC_PROFILE", str(profile)) for name in ("BYOC_CONNECTOR_TOKEN", "BYOC_ORG_ID", "CONTROL_PLANE_URL"): monkeypatch.delenv(name, raising=False) 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")