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
43 changes: 31 additions & 12 deletions .github/workflows/connector-windows-service.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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'
Expand Down Expand Up @@ -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" }
Expand All @@ -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
Expand Down Expand Up @@ -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
Expand Down
22 changes: 14 additions & 8 deletions packages/flow/docs/BYOC_CONNECTOR.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -125,9 +129,11 @@ pip install "openadapt-flow[vision,connector-windows]==<new version>"
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.
Expand Down
9 changes: 3 additions & 6 deletions packages/flow/openadapt_flow/connector/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
from __future__ import annotations

import argparse
from dataclasses import replace
from typing import Callable


Expand Down Expand Up @@ -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()

Expand Down Expand Up @@ -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,
Expand Down
16 changes: 15 additions & 1 deletion packages/flow/openadapt_flow/connector/daemon.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand All @@ -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,
Expand All @@ -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"
)
Expand All @@ -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:
Expand Down
40 changes: 37 additions & 3 deletions packages/flow/openadapt_flow/connector/windows_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand All @@ -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
Expand All @@ -228,13 +230,31 @@ 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 '
"BYOC_CONNECTOR_TOKEN for the service",
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),
Expand All @@ -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:
Expand Down Expand Up @@ -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")
Expand Down Expand Up @@ -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
Expand Down
Loading
Loading