Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 5 additions & 2 deletions .github/workflows/connector-windows-service.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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: |
Expand Down Expand Up @@ -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"
Expand Down
11 changes: 6 additions & 5 deletions packages/flow/deploy/connector/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,15 @@
# mkdir -p wheels && cp openadapt_flow-<version>-py3-none-any.whl wheels/
# docker build -t openadapt-connector:<version> .
#
# 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
Expand All @@ -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
Expand Down
1 change: 1 addition & 0 deletions packages/flow/deploy/connector/e2e/run_e2e.sh
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
33 changes: 33 additions & 0 deletions packages/flow/docs/BYOC_CONNECTOR.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
`<report-filename>.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
Expand Down
8 changes: 5 additions & 3 deletions packages/flow/openadapt_flow/at_rest.py
Original file line number Diff line number Diff line change
Expand Up @@ -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='<reason>'`` does the same with a reason.
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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]:
Expand Down Expand Up @@ -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

Expand Down
5 changes: 5 additions & 0 deletions packages/flow/openadapt_flow/connector/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
30 changes: 30 additions & 0 deletions packages/flow/openadapt_flow/connector/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
6 changes: 5 additions & 1 deletion packages/flow/openadapt_flow/connector/daemon.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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:
Expand Down
144 changes: 144 additions & 0 deletions packages/flow/openadapt_flow/connector/diagnostics.py
Original file line number Diff line number Diff line change
@@ -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",
)
Loading
Loading