diff --git a/.github/workflows/connector-windows-service.yml b/.github/workflows/connector-windows-service.yml index 0fafd80b94..4a1ab1ab0a 100644 --- a/.github/workflows/connector-windows-service.yml +++ b/.github/workflows/connector-windows-service.yml @@ -31,7 +31,7 @@ jobs: env: CONNECTOR_DIR: C:\ProgramData\OpenAdapt\connector EVIDENCE_DIR: ${{ github.workspace }}\connector-evidence - # A fixed test value; the stub accepts any bearer token. + # Synthetic bootstrap token; the rotation probe requires a new bearer. CI_CONNECTOR_TOKEN: ci-connector-service-test-token-7f3a9c steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 @@ -93,7 +93,9 @@ jobs: 'storage_backend = "local"', "storage_root = '$storage'" ) -join "`n" - [IO.File]::WriteAllText((Join-Path $env:CONNECTOR_DIR 'connector.toml'), "$toml`n") + $configPath = Join-Path $env:CONNECTOR_DIR 'connector.toml' + [IO.File]::WriteAllText($configPath, "$toml`n") + "BOOTSTRAP_CONFIG_HASH=$((Get-FileHash $configPath).Hash)" >> $env:GITHUB_ENV # Plant explicit broad grants. Installation must replace them, # not merely remove inheritance or update its own named entries. icacls $env:CONNECTOR_DIR /grant '*S-1-1-0:(OI)(CI)R' '*S-1-5-32-545:(OI)(CI)R' @@ -122,9 +124,17 @@ jobs: $failure if ($failure -notmatch 'RESTART') { throw 'no restart recovery action' } $allowed = @('NT AUTHORITY\SYSTEM', 'BUILTIN\Administrators', 'NT SERVICE\OpenAdaptConnector') + $serviceWriteRights = [Security.AccessControl.FileSystemRights]'Write,Delete,DeleteSubdirectoriesAndFiles,ChangePermissions,TakeOwnership' foreach ($path in @($env:CONNECTOR_DIR, (Join-Path $env:CONNECTOR_DIR 'connector.toml'))) { icacls $path - $ids = (Get-Acl $path).Access | ForEach-Object { $_.IdentityReference.Value } + $acl = Get-Acl $path + if ($acl.GetOwner([Security.Principal.SecurityIdentifier]).Value -ne 'S-1-5-32-544') { throw "Administrators do not own $path" } + $serviceWrites = $acl.Access | Where-Object { + $_.IdentityReference.Value -eq 'NT SERVICE\OpenAdaptConnector' -and + $_.AccessControlType -eq 'Allow' -and ($_.FileSystemRights -band $serviceWriteRights) + } + if ($serviceWrites) { throw "service has write access on $path" } + $ids = $acl.Access | ForEach-Object { $_.IdentityReference.Value } $extra = $ids | Where-Object { $allowed -notcontains $_ } if ($extra) { throw "unexpected ACL entries on ${path}: $($extra -join ', ')" } if ($ids -notcontains 'NT SERVICE\OpenAdaptConnector') { throw "service account missing on $path" } @@ -147,31 +157,39 @@ jobs: --log "$env:EVIDENCE_DIR\stub-requests.json" --timeout 120 --token-env CI_CONNECTOR_TOKEN - - name: Recover after process death during an empty poll + - name: Rotate the service token and recover it after process death during an empty poll run: | $ErrorActionPreference = 'Stop' - $stateUrl = "http://127.0.0.1:$env:STUB_PORT/test/state" + $testUrl = "http://127.0.0.1:$env:STUB_PORT/test" + $stateUrl = "$testUrl/state" + $configPath = Join-Path $env:CONNECTOR_DIR 'connector.toml' + $configAcl = (Get-Acl $configPath).Sddl + Invoke-RestMethod "$testUrl/request-rotation" | Out-Null $active = $false for ($i = 0; $i -lt 100; $i++) { $before = Invoke-RestMethod $stateUrl - if ($before.active_empty_polls -gt 0) { $active = $true; break } + if ($before.rotated_polls -gt 0 -and $before.active_empty_polls -gt 0) { $active = $true; break } Start-Sleep -Milliseconds 100 } - if (-not $active) { throw 'no active empty poll before the crash probe' } + if (-not $active) { throw 'service never polled with the rotated token before the crash probe' } $oldPid = [int](Get-CimInstance Win32_Service -Filter "Name='OpenAdaptConnector'").ProcessId if ($oldPid -le 0) { throw 'service was not running before the crash probe' } Stop-Process -Id $oldPid -Force + $afterStop = Invoke-RestMethod $stateUrl $recovered = $false for ($i = 0; $i -lt 120; $i++) { $svc = Get-CimInstance Win32_Service -Filter "Name='OpenAdaptConnector'" $after = Invoke-RestMethod $stateUrl - if ($svc.State -eq 'Running' -and [int]$svc.ProcessId -gt 0 -and [int]$svc.ProcessId -ne $oldPid -and $after.polls -gt $before.polls) { + if ($svc.State -eq 'Running' -and [int]$svc.ProcessId -gt 0 -and [int]$svc.ProcessId -ne $oldPid -and $after.rotated_polls -gt $afterStop.rotated_polls) { $recovered = $true; break } Start-Sleep -Milliseconds 500 } - if (-not $recovered) { throw 'SCM did not restart the service and resume polling' } - @{ old_pid = $oldPid; restarted_pid = [int]$svc.ProcessId; polls_before = $before.polls; polls_after = $after.polls; restarted_during_empty_poll = $true } | + if (-not $recovered) { throw 'SCM did not restart the service and resume polling with the rotated bearer' } + if ((Get-FileHash $configPath).Hash -ne $env:BOOTSTRAP_CONFIG_HASH -or (Get-Acl $configPath).Sddl -ne $configAcl) { + throw 'rotation changed the admin-owned connector config or ACL' + } + @{ old_pid = $oldPid; restarted_pid = [int]$svc.ProcessId; polls_before = $before.polls; polls_after = $after.polls; restarted_during_empty_poll = $true; rotated_polls_after_restart = $after.rotated_polls - $afterStop.rotated_polls } | ConvertTo-Json | Set-Content (Join-Path $env:EVIDENCE_DIR 'service-lifecycle.json') - name: Refuse a revoked token without logging it or reporting a job @@ -258,9 +276,10 @@ jobs: if (Test-Path $logs) { Copy-Item "$logs\*" $env:EVIDENCE_DIR -ErrorAction SilentlyContinue } if ($env:STUB_PID) { taskkill /T /F /PID $env:STUB_PID 2>&1 | Out-Null } Get-ChildItem $env:EVIDENCE_DIR | Format-Table Name, Length + $tokenPatterns = @([regex]::Escape($env:CI_CONNECTOR_TOKEN), 'oaconn_[0-9a-f]{64}') + $hits = Get-ChildItem $env:EVIDENCE_DIR -File | Select-String -Pattern $tokenPatterns + if ($hits) { $hits | ForEach-Object { $_.Path }; throw 'a connector token appears in the evidence' } Get-Content (Join-Path $env:EVIDENCE_DIR 'connector.log') -ErrorAction SilentlyContinue - $hits = Get-ChildItem $env:EVIDENCE_DIR -File | Select-String -SimpleMatch $env:CI_CONNECTOR_TOKEN - if ($hits) { $hits | ForEach-Object { $_.Path }; throw 'the connector token appears in the evidence' } exit 0 - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 diff --git a/packages/flow/docs/BYOC_CONNECTOR.md b/packages/flow/docs/BYOC_CONNECTOR.md index 0c95344f7a..860ea52c94 100644 --- a/packages/flow/docs/BYOC_CONNECTOR.md +++ b/packages/flow/docs/BYOC_CONNECTOR.md @@ -110,11 +110,15 @@ service runs that installation's `python.exe`, and `install` refuses a venv. - **Stop.** A job already running finishes and reports. A lease returned while the service is stopping never starts; it is left unacknowledged for the control plane to reconcile, rather than reported as completed. -- **Token replacement.** The service account reads its configuration and can - write only to its log directory. Replace the enrollment token as an - administrator while the service is stopped, then start it again. Automatic - token persistence needs a separate writable-state contract; the wrapper's - authorization-refusal check does not prove token rotation. +- **Token rotation.** For a file-enrolled connector, the service stores the + active and pending rotation in its virtual account's Windows Credential + Manager. The entry is local to the machine. The service retries the pending + candidate after restart before polling. Clearing an old pending field in + the enrollment file preserves the committed rotation. The service waits + between failed confirmations. If Cloud can no longer confirm the candidate, + replace the enrollment token as an administrator and restart the service. + An environment override for the token, control-plane URL or organization + leaves rotation with the operator. Update by stopping the service, installing the pinned version, and starting it again: @@ -125,9 +129,11 @@ pip install "openadapt-flow[vision,connector-windows]==" openadapt-flow connector service start ``` -Uninstall with `openadapt-flow connector service remove`. The config -directory, with the token, is kept; delete it to remove the enrollment, and -revoke the token in Cloud settings. +Uninstall with `openadapt-flow connector service remove`. Removal preserves +the enrollment and its local rotation state for reinstallation. To +decommission the connector, revoke it in Cloud and remove its config directory. +The service requires that enrollment before it can use the stored rotation +state. Starting with a replacement enrollment discards the old credential. On other operating systems, `connector service` prints a message and exits with code 2; run `connector run` under systemd or launchd instead. diff --git a/packages/flow/openadapt_flow/connector/cli.py b/packages/flow/openadapt_flow/connector/cli.py index 7036e0b5be..ad201ef303 100644 --- a/packages/flow/openadapt_flow/connector/cli.py +++ b/packages/flow/openadapt_flow/connector/cli.py @@ -3,6 +3,7 @@ from __future__ import annotations import argparse +from dataclasses import replace from typing import Callable @@ -193,13 +194,13 @@ def _cmd_connector(args: argparse.Namespace) -> int: from openadapt_flow.connector.config import connector_config_path def persist_token(new_token: str) -> None: + save_enrollment(replace(settings, token=new_token, pending_token=None)) settings.token = new_token settings.pending_token = None - save_enrollment(settings) def persist_pending(new_token: str) -> None: + save_enrollment(replace(settings, pending_token=new_token)) settings.pending_token = new_token - save_enrollment(settings) can_persist = connector_config_path().is_file() @@ -250,10 +251,6 @@ def persist_pending(new_token: str) -> None: egress_audit_log=settings.egress_audit_log, ) try: - if settings.pending_token and can_persist: - from openadapt_flow.connector.daemon import finish_rotation - - finish_rotation(client, settings.pending_token, persist_token, print) return run_loop( client, settings, diff --git a/packages/flow/openadapt_flow/connector/daemon.py b/packages/flow/openadapt_flow/connector/daemon.py index d701aba81c..cc21e65b91 100644 --- a/packages/flow/openadapt_flow/connector/daemon.py +++ b/packages/flow/openadapt_flow/connector/daemon.py @@ -328,6 +328,7 @@ def run_loop( persist_token: Optional[TokenPersister] = None, persist_pending: Optional[TokenPersister] = None, heartbeat_s: float = HEARTBEAT_S, + stop_requested: Optional[threading.Event] = None, ) -> int: """Poll -> execute -> callback -> ack until interrupted. @@ -342,6 +343,9 @@ def run_loop( log(f"[connector] polling {settings.control_plane_url} (org {settings.org_id})") if once: + if settings.pending_token and persist_token is not None: + if not finish_rotation(client, settings.pending_token, persist_token, log): + return 1 try: result = run_once( client, @@ -365,6 +369,7 @@ def run_loop( active = _ActiveJobs() stop = threading.Event() + retry_stop = stop_requested if stop_requested is not None else stop pool = ThreadPoolExecutor( max_workers=settings.max_workers, thread_name_prefix="oa-job" ) @@ -384,7 +389,16 @@ def heartbeat() -> None: handled = 0 backoff = 1.0 try: - while True: + while not retry_stop.is_set(): + # A lost rotate response or failed local commit leaves one durable + # candidate. Confirm it before polling or minting another token. + if settings.pending_token and persist_token is not None: + if not finish_rotation( + client, settings.pending_token, persist_token, log, attempts=1 + ): + retry_stop.wait(backoff) + backoff = min(MAX_BACKOFF_S, backoff * 2) + continue handled += active.reap(log) cap = min(settings.max_workers, client.control.max_concurrent_leases) if len(active.ids()) >= cap: diff --git a/packages/flow/openadapt_flow/connector/windows_service.py b/packages/flow/openadapt_flow/connector/windows_service.py index 9d7ce132e1..a8773e7a22 100644 --- a/packages/flow/openadapt_flow/connector/windows_service.py +++ b/packages/flow/openadapt_flow/connector/windows_service.py @@ -204,6 +204,7 @@ def serve( redactor: Optional[TokenRedactingFilter] = None, runner: Optional[Callable[..., Any]] = None, client_kwargs: Optional[dict[str, Any]] = None, + credential_api: Any = None, ) -> int: """Run the connector loop until ``stop_event`` is set. Returns an exit code. @@ -215,6 +216,7 @@ def serve( from openadapt_flow.connector.config import ConnectorConfigError, load_settings from openadapt_flow.connector.daemon import run_loop + from openadapt_flow.connector.windows_tokens import ServiceTokenRotation if runner is None: from openadapt_flow.connector.executor import _subprocess_runner @@ -228,6 +230,7 @@ def serve( return 2 if redactor is not None: redactor.add(settings.token) + redactor.add(settings.pending_token) if not settings.token: logger.error( 'no connector token: put token = "..." in %s or set ' @@ -235,6 +238,23 @@ def serve( config_file(config_dir), ) return 2 + rotation = None + # The administrator owns the bootstrap and destination. Explicit + # environment credentials or destinations keep their operator-managed + # lifecycle. Only the real service host supplies its OS credential API. + if credential_api is not None and not any( + key in os.environ + for key in ("BYOC_CONNECTOR_TOKEN", "CONTROL_PLANE_URL", "BYOC_ORG_ID") + ): + assert redactor is not None # installed by the service host + rotation = ServiceTokenRotation( + credential_api, config_dir, settings, redactor.add + ) + try: + rotation.restore() + except Exception as exc: + logger.error("service rotation state unavailable (%s)", type(exc).__name__) + return 2 logger.info( "service starting: config %s, settings %s", config_file(config_dir), @@ -251,7 +271,15 @@ def serve( **(client_kwargs or {}), ) try: - code = run_loop(client, settings, runner=runner, log=logger.info) + code = run_loop( + client, + settings, + runner=runner, + log=logger.info, + persist_token=rotation.persist_token if rotation else None, + persist_pending=rotation.persist_pending if rotation else None, + stop_requested=stop_event, + ) if stop_event.is_set(): break if code != 0: @@ -483,10 +511,16 @@ def SvcStop(self) -> None: # noqa: N802 - pywin32 API self.stop_event.set() def SvcDoRun(self) -> None: # noqa: N802 - pywin32 API + import win32cred + logger, redactor = build_logger(self.config_dir) try: code = serve( - self.config_dir, self.stop_event, logger, redactor=redactor + self.config_dir, + self.stop_event, + logger, + redactor=redactor, + credential_api=win32cred, ) except Exception: logger.exception("service crashed") @@ -657,7 +691,7 @@ def _act(action: str, config_dir: Path, timeout_s: float) -> int: # pragma: no win32serviceutil.RemoveService(SERVICE_NAME) print( f"removed {SERVICE_NAME}; {config_dir} (with the token) was kept, " - "delete it to remove the enrollment" + "revoke the connector in Cloud and remove the directory to decommission" ) return 0 # status diff --git a/packages/flow/openadapt_flow/connector/windows_tokens.py b/packages/flow/openadapt_flow/connector/windows_tokens.py new file mode 100644 index 0000000000..7db4f2fc1c --- /dev/null +++ b/packages/flow/openadapt_flow/connector/windows_tokens.py @@ -0,0 +1,110 @@ +"""Windows service token rotation in the virtual account's Credential Manager.""" + +from __future__ import annotations + +import hashlib +import json +import os +import re +from pathlib import Path +from typing import Any, Callable, Optional + +from openadapt_flow.connector.config import ConnectorSettings + +# Windows gives each logon identity its own credential set. There is only one +# OpenAdaptConnector service on the machine. The username binds its one entry +# to the administrator's enrollment, including the destination for its tokens. +_TARGET = "OpenAdapt/connector/service-rotation/v1" + + +class ServiceTokenRotation: + def __init__( + self, + api: Any, + config_dir: Path, + settings: ConnectorSettings, + redact: Callable[[Optional[str]], None], + ): + self.api = api + self.settings = settings + self.redact = redact + self.bootstrap = settings.token + enrollment = [ + os.path.normcase(str(config_dir.resolve())), + settings.control_plane_url, + settings.org_id, + settings.token, + ] + self.binding = ( + "v2:" + hashlib.sha256(json.dumps(enrollment).encode()).hexdigest() + ) + # The first format also included a mutable field from connector.toml. + # An exact match is enough to migrate. A mismatch is ambiguous. + self._legacy_binding = hashlib.sha256( + json.dumps([*enrollment, settings.pending_token]).encode() + ).hexdigest() + + def restore(self) -> None: + try: + cred = self.api.CredRead(_TARGET, self.api.CRED_TYPE_GENERIC) + except Exception as exc: + if getattr(exc, "winerror", None) == 1168: # ERROR_NOT_FOUND + return + raise RuntimeError("service credential store unavailable") from None + identity = cred.get("UserName") + legacy = identity == self._legacy_binding + if not legacy and ( + not isinstance(identity, str) + or not re.fullmatch(r"v2:[0-9a-f]{64}", identity) + ): + raise RuntimeError("unrecognized service enrollment binding") + if not legacy and identity != self.binding: + # An administrator changed the enrollment. Its credentials take + # precedence over any token saved for the previous destination. + self.api.CredDelete(_TARGET, self.api.CRED_TYPE_GENERIC) + return + try: + # pywin32 takes a Unicode blob on write and returns UTF-16 bytes. + state = json.loads(cred["CredentialBlob"].decode("utf-16-le")) + if not isinstance(state, list) or len(state) != 2: + raise ValueError + active, pending = state + if any( + token is not None and not re.fullmatch(r"oaconn_[0-9a-f]{64}", token) + for token in (active, pending) + ) or (active is None and pending is None): + raise ValueError + except (KeyError, TypeError, ValueError, AttributeError): + raise RuntimeError("invalid service rotation state") from None + self.redact(active) + self.redact(pending) + if legacy: + self._save(active or self.bootstrap, pending) + return + self.settings.token = active or self.bootstrap + self.settings.pending_token = pending + + def _save(self, active: Optional[str], pending: Optional[str]) -> None: + # Persist both fields in one credential write before changing memory. + # The administrator's original token stays in the enrollment file. + self.api.CredWrite( + { + "Type": self.api.CRED_TYPE_GENERIC, + "TargetName": _TARGET, + "UserName": self.binding, + "Persist": self.api.CRED_PERSIST_LOCAL_MACHINE, + "CredentialBlob": json.dumps( + [None if active == self.bootstrap else active, pending] + ), + } + ) + self.settings.token = active + self.settings.pending_token = pending + + def persist_pending(self, candidate: str) -> None: + self.redact(candidate) + self._save(self.settings.token, candidate) + + def persist_token(self, candidate: str) -> None: + self.redact(candidate) + self._save(candidate, None) diff --git a/packages/flow/tests/connector_stub/stub_server.py b/packages/flow/tests/connector_stub/stub_server.py index 3f48ca75ec..9e27fe8a0c 100644 --- a/packages/flow/tests/connector_stub/stub_server.py +++ b/packages/flow/tests/connector_stub/stub_server.py @@ -1,6 +1,6 @@ """A stub BYOC control plane for the connector service tests. -It listens on 127.0.0.1 only and answers the three outbound endpoints the +It listens on 127.0.0.1 only and answers the outbound endpoints the connector calls: * ``POST /api/connector/poll``: 204 for the first ``--empty-polls`` polls @@ -10,6 +10,8 @@ fetches a bundle or touches any GUI. * ``POST /api/internal/run-callback``: 200. * ``POST /api/connector/ack``: 200. +* ``POST /api/connector/rotate``: following a test rotation request, accept + the new token digest and require its matching bearer on subsequent polls. Every request is appended to a JSON file (method, path, sorted header names, parsed body). Header values are never recorded, so the bearer token never @@ -21,7 +23,9 @@ from __future__ import annotations import argparse +import hashlib import json +import re import threading import time from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer @@ -67,6 +71,9 @@ def __init__(self, log_path: Path, empty_polls: int, empty_sleep: float): self.active_empty_polls = 0 self.auth_denials = 0 self.deny_auth = False + self.rotate_requested = False + self.rotated_digest: Optional[str] = None + self.rotated_polls = 0 self.lock = threading.Lock() def record(self, entry: dict[str, Any]) -> None: @@ -92,9 +99,19 @@ class Handler(BaseHTTPRequestHandler): def log_message(self, format: str, *args: Any) -> None: # noqa: A002 return - def _reply(self, status: int, body: Optional[dict[str, Any]]) -> None: + def _reply( + self, + status: int, + body: Optional[dict[str, Any]], + *, + recommend_rotation: bool = False, + ) -> None: data = json.dumps(body).encode("utf-8") if body is not None else b"" self.send_response(status) + if recommend_rotation: + self.send_header( + "x-oa-connector-control", '{"rotate_recommended":true}' + ) if data: self.send_header("content-type", "application/json") self.send_header("content-length", str(len(data))) @@ -110,6 +127,9 @@ def do_GET(self) -> None: # noqa: N802 elif self.path == "/test/allow-auth": with state.lock: state.deny_auth = False + elif self.path == "/test/request-rotation": + with state.lock: + state.rotate_requested = True elif self.path != "/test/state": return self._reply(404, {"error": "not_found"}) with state.lock: @@ -117,6 +137,7 @@ def do_GET(self) -> None: # noqa: N802 "polls": state.polls, "active_empty_polls": state.active_empty_polls, "auth_denials": state.auth_denials, + "rotated_polls": state.rotated_polls, } self._reply(200, snapshot) @@ -137,11 +158,41 @@ def do_POST(self) -> None: # noqa: N802 "t": time.time(), } ) + auth = self.headers.get("authorization", "") + token_digest = ( + hashlib.sha256(auth[7:].encode()).hexdigest() + if auth.startswith("Bearer ") + else None + ) + if path == "/api/connector/rotate": + candidate = ( + body.get("new_token_sha256") if isinstance(body, dict) else None + ) + if not isinstance(candidate, str) or not re.fullmatch( + r"[0-9a-f]{64}", candidate + ): + return self._reply(400, {"error": "invalid_candidate"}) + with state.lock: + accepted = ( + state.rotate_requested + and token_digest is not None + and candidate != token_digest + ) + if accepted: + state.rotated_digest = candidate + state.rotate_requested = False + return self._reply(200 if accepted else 409, {"ok": accepted}) if path == "/api/connector/poll": with state.lock: - deny_auth = state.deny_auth + deny_auth = state.deny_auth or ( + state.rotated_digest is not None + and token_digest != state.rotated_digest + ) + recommend_rotation = state.rotate_requested if deny_auth: state.auth_denials += 1 + elif state.rotated_digest is not None: + state.rotated_polls += 1 if deny_auth: # Deliberately hostile response: the service log must # remove its token even when a server echoes it back. @@ -154,7 +205,7 @@ def do_POST(self) -> None: # noqa: N802 state.active_empty_polls += 1 try: time.sleep(state.empty_sleep) - self._reply(204, None) + self._reply(204, None, recommend_rotation=recommend_rotation) finally: with state.lock: state.active_empty_polls -= 1 diff --git a/packages/flow/tests/test_connector_service_rotation.py b/packages/flow/tests/test_connector_service_rotation.py new file mode 100644 index 0000000000..2fce2fd2bf --- /dev/null +++ b/packages/flow/tests/test_connector_service_rotation.py @@ -0,0 +1,310 @@ +"""Service rotation with synthetic credentials and a process-local WinCred model.""" + +import hashlib +import json +import os +import threading + +import httpx +import pytest + +from openadapt_flow.connector import windows_service as ws +from openadapt_flow.connector.config import ConnectorSettings +from openadapt_flow.connector.windows_tokens import ServiceTokenRotation + +BOOTSTRAP = "service-test-bootstrap" +CANDIDATE = "oaconn_" + "a" * 64 + + +class CredentialNotFound(Exception): + winerror = 1168 + + +class CredentialSet: + CRED_TYPE_GENERIC = 1 + CRED_PERSIST_LOCAL_MACHINE = 2 + + def __init__(self): + self.entry = None + + def CredRead(self, target, kind): + if self.entry is None: + raise CredentialNotFound() + assert self.entry["TargetName"] == target and self.entry["Type"] == kind + return self.entry + + def CredWrite(self, record): + assert record["Persist"] == self.CRED_PERSIST_LOCAL_MACHINE + self.entry = { + **record, + "CredentialBlob": record["CredentialBlob"].encode("utf-16-le"), + } + + def CredDelete(self, target, kind): + self.CredRead(target, kind) + self.entry = None + + +@pytest.fixture(autouse=True) +def service_environment(monkeypatch, tmp_path): + monkeypatch.setenv("OPENADAPT_HOME", str(tmp_path)) + for name in ("BYOC_CONNECTOR_TOKEN", "BYOC_ORG_ID", "CONTROL_PLANE_URL"): + monkeypatch.delenv(name, raising=False) + + +def test_service_recovers_same_candidate_before_polling(tmp_path, monkeypatch): + class SimulatedCrash(BaseException): + pass + + config = tmp_path / "connector.toml" + original = ( + f'[connector]\ncontrol_plane_url = "https://cloud.example"\ntoken = "{BOOTSTRAP}"\n' + ).encode() + config.write_bytes(original) + monkeypatch.setattr("openadapt_flow.connector.client.mint_token", lambda: CANDIDATE) + store = CredentialSet() + logger, redactor = ws.build_logger(tmp_path, name="test.service-rotation") + stop = threading.Event() + paths = [] + digests = [] + + def transport(request): + path = request.url.path + paths.append(path) + if path.endswith("/rotate"): + assert request.headers["Authorization"] == "Bearer " + BOOTSTRAP + digests.append(json.loads(request.content)["new_token_sha256"]) + assert json.loads(store.entry["CredentialBlob"].decode("utf-16-le")) == [ + None, + CANDIDATE, + ] + if len(digests) == 1: + raise SimulatedCrash + return httpx.Response(200, json={"already_rotated": True}) + if len(paths) == 1: + return httpx.Response(200, json={"connector": {"rotate_recommended": True}}) + assert request.headers["Authorization"] == "Bearer " + CANDIDATE + stop.set() + return httpx.Response(204) + + def run(): + return ws.serve( + tmp_path, + stop, + logger, + redactor=redactor, + credential_api=store, + client_kwargs={"transport": httpx.MockTransport(transport)}, + ) + + with pytest.raises(SimulatedCrash): + run() + assert paths == ["/api/connector/poll", "/api/connector/rotate"] + assert run() == 0 + assert paths[2:] == ["/api/connector/rotate", "/api/connector/poll"] + assert digests == [hashlib.sha256(CANDIDATE.encode()).hexdigest()] * 2 + assert json.loads(store.entry["CredentialBlob"].decode("utf-16-le")) == [ + CANDIDATE, + None, + ] + assert config.read_bytes() == original + logger.warning("%s %s", BOOTSTRAP, CANDIDATE) + log = ws.log_path(tmp_path).read_text() + assert BOOTSTRAP not in log and CANDIDATE not in log + + +@pytest.mark.parametrize( + "field,value", + [ + ("control_plane_url", "https://another.example"), + ("org_id", "another-org"), + ("token", "another-bootstrap"), + ], +) +def test_changed_enrollment_discards_previous_rotation(tmp_path, field, value): + store = CredentialSet() + settings = ConnectorSettings(token=BOOTSTRAP, org_id="old-org") + ServiceTokenRotation(store, tmp_path, settings, lambda _: None).persist_token( + CANDIDATE + ) + settings = ConnectorSettings(token=BOOTSTRAP, org_id="old-org") + setattr(settings, field, value) + ServiceTokenRotation(store, tmp_path, settings, lambda _: None).restore() + assert store.entry is None + assert settings.token == (value if field == "token" else BOOTSTRAP) + + +def test_store_write_failure_retains_durable_pending(tmp_path, monkeypatch): + settings = ConnectorSettings(token=BOOTSTRAP) + store = CredentialSet() + rotation = ServiceTokenRotation(store, tmp_path, settings, lambda _: None) + rotation.persist_pending(CANDIDATE) + + def fail(record): + raise OSError("store offline") + + monkeypatch.setattr(store, "CredWrite", fail) + with pytest.raises(OSError): + rotation.persist_token(CANDIDATE) + assert settings.token == BOOTSTRAP and settings.pending_token == CANDIDATE + restarted = ConnectorSettings(token=BOOTSTRAP) + ServiceTokenRotation(store, tmp_path, restarted, lambda _: None).restore() + assert restarted.token == BOOTSTRAP and restarted.pending_token == CANDIDATE + + +def test_clearing_file_pending_keeps_rotated_credential(tmp_path): + stale = "oaconn_" + "b" * 64 + store = CredentialSet() + enrollment = ConnectorSettings(token=BOOTSTRAP, pending_token=stale) + journal = ServiceTokenRotation(store, tmp_path, enrollment, lambda _: None) + journal.persist_token(stale) + journal.persist_pending(CANDIDATE) + journal.persist_token(CANDIDATE) + + # The administrator removes only the stale pending field from the file. + restarted = ConnectorSettings(token=BOOTSTRAP) + ServiceTokenRotation(store, tmp_path, restarted, lambda _: None).restore() + assert restarted.token == CANDIDATE and restarted.pending_token is None + assert store.entry is not None + + +def test_confirmation_retries_same_candidate_until_success(tmp_path, monkeypatch): + config = tmp_path / "connector.toml" + config.write_text( + f'[connector]\ncontrol_plane_url = "https://cloud.example"\ntoken = "{BOOTSTRAP}"\n' + f'pending_token = "{CANDIDATE}"\n' + ) + # A transient outage lasts longer than the original three-attempt limit. + monkeypatch.setattr("openadapt_flow.connector.daemon.time.sleep", lambda _: None) + monkeypatch.setattr("openadapt_flow.connector.daemon.MAX_BACKOFF_S", 0.01) + stop = threading.Event() + paths = [] + digests = [] + + def handler(request): + paths.append(request.url.path) + if request.url.path.endswith("/rotate"): + digests.append(json.loads(request.content)["new_token_sha256"]) + assert request.headers["Authorization"] == "Bearer " + BOOTSTRAP + return httpx.Response(503 if len(digests) <= 3 else 200, json={}) + assert request.headers["Authorization"] == "Bearer " + CANDIDATE + stop.set() + return httpx.Response(204) + + logger, redactor = ws.build_logger(tmp_path, name="test.service-rotation-retry") + assert ( + ws.serve( + tmp_path, + stop, + logger, + redactor=redactor, + credential_api=CredentialSet(), + client_kwargs={"transport": httpx.MockTransport(handler)}, + ) + == 0 + ) + assert digests == [hashlib.sha256(CANDIDATE.encode()).hexdigest()] * 4 + assert paths == ["/api/connector/rotate"] * 4 + ["/api/connector/poll"] + + +@pytest.mark.parametrize("same_enrollment", [True, False]) +def test_legacy_record_requires_its_original_binding(tmp_path, same_enrollment): + old_file_pending = "oaconn_" + "b" * 64 + original = ConnectorSettings(token=BOOTSTRAP, pending_token=old_file_pending) + store = CredentialSet() + journal = ServiceTokenRotation(store, tmp_path, original, lambda _: None) + journal.persist_token(CANDIDATE) + v1_fields = [ + os.path.normcase(str(tmp_path.resolve())), + original.control_plane_url, + original.org_id, + BOOTSTRAP, + old_file_pending, + ] + store.entry["UserName"] = hashlib.sha256(json.dumps(v1_fields).encode()).hexdigest() + entry = store.entry.copy() + restarted = ConnectorSettings( + token=BOOTSTRAP, pending_token=old_file_pending if same_enrollment else None + ) + journal = ServiceTokenRotation(store, tmp_path, restarted, lambda _: None) + if same_enrollment: + journal.restore() + assert restarted.token == CANDIDATE and restarted.pending_token is None + assert store.entry["UserName"] == journal.binding + else: + with pytest.raises(RuntimeError, match="enrollment binding"): + journal.restore() + assert restarted.token == BOOTSTRAP and store.entry == entry + + +def test_operator_stop_interrupts_confirmation_backoff(tmp_path): + (tmp_path / "connector.toml").write_text( + f'[connector]\ncontrol_plane_url = "https://cloud.example"\ntoken = "{BOOTSTRAP}"\n' + f'pending_token = "{CANDIDATE}"\n' + ) + stop = threading.Event() + paths = [] + + def handler(request): + paths.append(request.url.path) + stop.set() + return httpx.Response(503) + + logger, redactor = ws.build_logger(tmp_path, name="test.service-rotation-stop") + assert ( + ws.serve( + tmp_path, + stop, + logger, + redactor=redactor, + credential_api=CredentialSet(), + client_kwargs={"transport": httpx.MockTransport(handler)}, + ) + == 0 + ) + assert paths == ["/api/connector/rotate"] + + +def test_environment_token_keeps_its_external_lifecycle(tmp_path, monkeypatch): + monkeypatch.setenv("BYOC_CONNECTOR_TOKEN", BOOTSTRAP) + stop = threading.Event() + paths = [] + + def handler(request): + paths.append(request.url.path) + assert request.headers["Authorization"] == "Bearer " + BOOTSTRAP + if len(paths) == 2: + stop.set() + return httpx.Response(200, json={"connector": {"rotate_recommended": True}}) + + logger, redactor = ws.build_logger(tmp_path, name="test.service-rotation-env") + assert ( + ws.serve( + tmp_path, + stop, + logger, + redactor=redactor, + credential_api=object(), + client_kwargs={"transport": httpx.MockTransport(handler)}, + ) + == 0 + ) + assert paths == ["/api/connector/poll", "/api/connector/poll"] + + +def test_unreadable_store_stops_before_polling(tmp_path, monkeypatch): + (tmp_path / "connector.toml").write_text(f'[connector]\ntoken = "{BOOTSTRAP}"\n') + store = CredentialSet() + + def fail(*_args): + raise OSError(f"store locked {BOOTSTRAP}") + + monkeypatch.setattr(store, "CredRead", fail) + logger, redactor = ws.build_logger(tmp_path, name="test.service-rotation-locked") + assert ( + ws.serve( + tmp_path, threading.Event(), logger, redactor=redactor, credential_api=store + ) + == 2 + ) + assert BOOTSTRAP not in ws.log_path(tmp_path).read_text()