"""BHE queue handling for Cloud Collection, the SpecterOps-hosted Enterprise beta.""" import logging import multiprocessing import signal import time from collections.abc import Callable, Iterator from concurrent.futures import CancelledError from contextlib import contextmanager from dataclasses import dataclass, field from datetime import UTC, datetime from functools import partial from multiprocessing.connection import Connection, wait from pathlib import Path from typing import Any, BinaryIO from uuid import UUID import requests from openhound.core.clients.aws_secrets_manager import AWSSecretsManager from openhound.core.clients.bloodhound import BloodHoundHTTPError from openhound.core.clients.bloodhound_enterprise import ( BloodHoundEnterprise, CloudCollectorJobOutcome, CollectorJobRequest, CollectorJobRequestRunner, RequestBody, ) from openhound.core.clients.models.jobs import CollectorJob from openhound.scheduler.configuration import CloudConfigurationError, JobEnvironment from openhound.scheduler.credentials import ( CredentialPreparationError, prepare_job_credentials, ) from openhound.scheduler.status import SchedulerStatus from openhound.scheduler.worker import CollectionWorker, Result logger = logging.getLogger("openhound.scheduler.service") _CLOUD_JOB_DRAIN_TIMEOUT_SECONDS = 60 HEARTBEAT_INTERVAL = 300 # seconds; BHE's default claim TTL is 15 minutes _HEARTBEAT_RETRY_INTERVAL = 30 class CloudRuntimeUnavailableError(RuntimeError): """Cloud Collection scheduling requires a configured collection runtime.""" class CloudJobProcessingError(RuntimeError): """A sanitized Cloud Collection polling failure that can be retried next poll.""" class _CloudClaimLost(CancelledError): """Stop delivery and unwind open resources before discarding the job.""" @dataclass(frozen=True) class PreparedCloudJob: """Validated job and credentials for the Cloud Collection runtime. Keep credentials in the in-memory worker handoff; never persist or log them. """ job: CollectorJob = field(repr=False) credentials: dict[str, Any] = field(repr=False) environment: JobEnvironment = field(default_factory=dict, repr=False) class CloudJobs: """Own claim recovery, worker handoff, and delivery to BHE.""" def __init__( self, client: BloodHoundEnterprise, worker: CollectionWorker, *, stopping: Callable[[], bool], status: SchedulerStatus | None = None, secrets_manager: AWSSecretsManager | None = None, cloud_job_runner: Callable[[PreparedCloudJob], None] | None = None, ) -> None: self.client = client self.worker = worker self._stopping = stopping self.status = status self.secrets_manager = secrets_manager or AWSSecretsManager() self.cloud_job_runner = cloud_job_runner or self._run_prepared_cloud_job self._pending_cloud_claim: str | None = None self._pending_cloud_start: PreparedCloudJob | None = None self._pending_cloud_failure: str | None = None self._pending_cloud_failure_summary = "Credential document is invalid" self._claim_lost = False self._claim_unconfirmed = False self._job_ended = False self._drain_deadline: float | None = None self._upload_failure: str | None = None self.next_heartbeat_at: float | None = None def on_start(self) -> None: """Cloud Collection identities have no client metadata endpoint.""" @property def _has_pending_cloud_job(self) -> bool: return ( self._pending_cloud_claim is not None or self._pending_cloud_start is not None or self._pending_cloud_failure is not None ) def poll(self, interval: int) -> float: if self._poll_started_job(): return self._heartbeat_delay(interval) if not self._stopping() or self._has_pending_cloud_job: self._try_poll_cloud_jobs(interval) return self._heartbeat_delay(interval) def _try_poll_cloud_jobs(self, interval: int) -> None: try: self._poll_cloud_jobs() except CloudRuntimeUnavailableError: logger.error("Cloud Collection runtime is unavailable; retrying next poll.") except CloudJobProcessingError: logger.error( "Cloud Collection scheduler poll failed; retrying next poll in %s seconds.", interval, ) def drain_once(self, interval: int, *, after_poll: bool = False) -> float | None: """Resolve existing reservations and finish started work without discovery.""" if self._has_pending_cloud_job: # Reconcile reservations before draining a worker that they may start. delay = self._reconcile_during_shutdown(interval, after_poll=after_poll) if delay is not None: return delay if self._poll_started_job(shutting_down=True): return self._heartbeat_delay(interval) return None def _reconcile_during_shutdown( self, interval: int, *, after_poll: bool ) -> float | None: now = time.monotonic() if self._drain_deadline is None: self._drain_deadline = now + _CLOUD_JOB_DRAIN_TIMEOUT_SECONDS if after_poll: # A poll that just ran keeps its usual delay before a retry. return min(interval, _CLOUD_JOB_DRAIN_TIMEOUT_SECONDS) if now >= self._drain_deadline: self._discard_unresolved_cloud_job() return None self._try_poll_cloud_jobs(interval) if self._has_pending_cloud_job: return max(0, min(interval, self._drain_deadline - time.monotonic())) return None def check_cloud_collector_jobs(self) -> CollectorJob | None: """Return the first available job from the Cloud Collection queue.""" logger.info("Checking for new Cloud Collection jobs in BloodHound Enterprise.") collector_name = self.worker.collector_name available_jobs = self.client.available_cloud_collector_jobs(collector_name) for job in available_jobs.data.jobs: if job.job_key == collector_name: return job return None def _report_cloud_failure(self, job_id: str) -> None: # Retain the unresolved ID if reporting exhausts its retries. On the next # poll retry end, rather than claiming or retrieving another job. self._pending_cloud_failure = job_id try: self._end_job(job_id, self._pending_cloud_failure_summary) except _CloudClaimLost: # Submission already failed; there is no running worker to abort. pass self._pending_cloud_failure = None self._clear_active_job(job_id) def _load_cloud_credentials( self, job: CollectorJob ) -> tuple[dict[str, Any], JobEnvironment]: """Retrieve and validate credentials, exposing only a safe failure message.""" logger.debug( "Retrieving Cloud Collection credentials.", extra={ "job_id": str(job.id), "provider": "aws.secretsmanager", "secret_count": 1, }, ) try: return prepare_job_credentials(job, self.secrets_manager.get_secret) except CredentialPreparationError: raise except CloudConfigurationError as error: raise CredentialPreparationError(str(error)) from None except Exception as error: # noqa: BLE001 # Unexpected readers can expose payloads. raise CredentialPreparationError( f"Credential secret reader failed ({type(error).__name__})", "Credential secret retrieval failed", ) from None def _validate_cloud_claim(self, job: CollectorJob, job_id: str) -> None: """Check the job identity and lease confirmed by BHE's claim response.""" # The authenticated claim endpoint confirms the holder. Reclaiming does # not renew the lease, so an old response is not enough to permit work. lease_expires_at = job.claim_expires_at if ( str(job.id) != job_id or job.job_key != self.worker.collector_name or job.status != "claimed" or job.claimed_by is None or job.claimed_at is None or lease_expires_at is None or lease_expires_at.utcoffset() is None or lease_expires_at <= datetime.now(UTC) ): logger.error( "Cloud Collection claim response does not confirm a usable claim.", extra={"job_id": job_id}, ) raise CloudJobProcessingError( "Cloud Collection claim could not be reconciled" ) def _claim_and_validate_cloud_job(self, job_id: str) -> PreparedCloudJob | None: """Claim a Cloud Collection job and validate its credentials.""" # A timeout can happen after BHE commits the claim. Keep the ID until we # reconcile it; discovery no longer lists jobs held by this collector. if self.status is not None and self.status.reserve(job_id, "claiming") is None: return None self._pending_cloud_claim = job_id try: job = self.client.claim_cloud_collector_job(job_id) except BloodHoundHTTPError as error: if error.code in (404, 409): # An existing claimed job held by this client would return 200. self._pending_cloud_claim = None if self.status is not None: self.status.release(job_id) if error.code == 409: logger.debug( "Cloud Collection claim conflict.", extra={"job_id": job_id}, ) return None raise self._validate_cloud_claim(job, job_id) if self.status is not None: self.status.transition(job_id, "preparing") context = {"job_id": job_id} logger.info("Job successfully picked up", extra=context) try: credentials, environment = self._load_cloud_credentials(job) except CredentialPreparationError as error: logger.error( "Cannot prepare Cloud Collection job %s: %s. Reporting this job failed.", job_id, str(error).rstrip("."), extra={ **error.context, **context, **( {} if job.job_key == "aws" else {"secret_id": job.secret_key_id} ), }, ) self._pending_cloud_claim = None self._pending_cloud_failure_summary = error.summary self._report_cloud_failure(str(job.id)) return None # Secret retrieval may have consumed the remaining lease time. self._validate_cloud_claim(job, job_id) logger.info("Credential retrieval valid", extra=context) return PreparedCloudJob( job=job, credentials=credentials, environment=environment ) def _clear_pending_cloud_start(self) -> None: """Discard preparation state once start is confirmed or rejected.""" self._pending_cloud_claim = None self._pending_cloud_start = None def _discard_unresolved_cloud_job(self) -> None: """Drop local reconciliation state when the shutdown deadline expires.""" job_id = self._pending_cloud_failure or self._pending_cloud_claim if job_id is None and self._pending_cloud_start is not None: job_id = str(self._pending_cloud_start.job.id) # A request may have committed before its response was lost. BHE owns # the job's outcome and lease-expiry recovery for any remaining claim. logger.warning( "Cloud Collection job %s was unresolved at the shutdown deadline; " "BHE state is unconfirmed.", job_id, extra={"job_id": job_id}, ) self._clear_pending_cloud_start() self._pending_cloud_failure = None if job_id is not None: self._clear_active_job(job_id) def _require_cloud_runtime(self) -> Callable[[PreparedCloudJob], None]: if self.cloud_job_runner is None: raise CloudRuntimeUnavailableError( "Cloud Collection runtime is required for Cloud Collection scheduling" ) return self.cloud_job_runner def _run_prepared_cloud_job(self, prepared: PreparedCloudJob) -> None: self.run_claimed_job( prepared.job.id, prepared.job.params, prepared.credentials, environment=prepared.environment, ) def _poll_cloud_jobs(self) -> None: runner = self._require_cloud_runtime() try: if self._pending_cloud_failure is not None: self._report_cloud_failure(self._pending_cloud_failure) return prepared = self._pending_cloud_start if prepared is None: job_id = self._pending_cloud_claim if job_id is None: if self._stopping(): return available_job = self.check_cloud_collector_jobs() if available_job is None or self._stopping(): return job_id = str(available_job.id) prepared = self._claim_and_validate_cloud_job(job_id) # Keep validated inputs in memory across ambiguous start failures. # Repeating BHE's idempotent start also reconciles a job that is # already running remotely; re-claiming it would return 409. self._pending_cloud_start = prepared if prepared is not None: runner(prepared) self._clear_pending_cloud_start() if self.status is not None and self.worker.job_running is None: job_id = str(prepared.job.id) if self._pending_cloud_failure != job_id: self.status.release(job_id) except Exception: # noqa: BLE001 - redact Cloud Collection runtime errors raise CloudJobProcessingError( "Cloud Collection job processing failed" ) from None def run_claimed_job( self, job_id: str | UUID, params: dict[str, Any], secrets: dict[str, Any], *, environment: JobEnvironment | None = None, ) -> None: """Start a validated Cloud Collection job and submit it to the collection worker.""" self.worker.ensure_idle() if isinstance(job_id, UUID): job_id = str(job_id) logger.info( "Starting job %s with collector '%s'.", job_id, self.worker.collector_name ) if not isinstance(job_id, str): raise TypeError("Cloud Collection job IDs must be strings") attempt = None if self.status is not None: attempt = self.status.reserve(job_id, "starting") if attempt is None: return try: self.client.start_cloud_collector_job(job_id) except BloodHoundHTTPError as error: if error.code in (404, 409): self._clear_pending_cloud_start() if self.status is not None: self.status.release(job_id) raise self._clear_pending_cloud_start() logger.info("Cloud Collection job %s started successfully.", job_id) self.next_heartbeat_at = time.monotonic() + HEARTBEAT_INTERVAL def report_failure(message: str) -> None: self._pending_cloud_failure_summary = message self._report_cloud_failure(job_id) try: self.worker.start( job_id, report_failure=report_failure, params=params, secrets=secrets, cloud_collection=True, environment=environment, attempt=attempt, ) finally: if ( self.worker.job_running is None and self._pending_cloud_failure != job_id ): self._clear_active_job(job_id) def _end_job(self, job_id: str, failure_message: str | None) -> None: if self.status is not None: self.status.transition(job_id, "finalizing") before_attempt = ( partial(self._check_claim_before_request, job_id) if self.next_heartbeat_at is not None else None ) try: self.client.end_cloud_collector_job( job_id, ( CloudCollectorJobOutcome.SUCCEEDED if failure_message is None else CloudCollectorJobOutcome.FAILED ), failure_message=failure_message, before_attempt=before_attempt, ) except BloodHoundHTTPError as error: if error.code != 404: raise logger.info( "Cloud Collection job %s is no longer actionable; discarding local state.", job_id, ) def _poll_started_job(self, *, shutting_down: bool = False) -> bool: """Renew active work or deliver its completed result.""" job_id = self.worker.job_running if job_id is None: return False assert isinstance(job_id, str) try: if self._claim_lost: self._abort_cloud_job(job_id) return False if self.worker.done: self._handle_completed_job(job_id) else: self._renew_claim_if_due(job_id) except _CloudClaimLost: self._abort_cloud_job(job_id) except Exception: # noqa: BLE001 - redact sensitive errors; retain work for retry logger.error( "Error reporting completed Cloud Collection job%s; will retry.", " during shutdown" if shutting_down else "", ) return self.worker.job_running is not None def _handle_completed_job(self, job_id: str) -> None: result, failure = self.worker.completed_result() if result is not None and result.output_path is not None: if not self._deliver_result(job_id, result): return failure = self._upload_failure if not self._job_ended: self._end_job(job_id, failure) self._job_ended = True self.worker.release(result) self._clear_active_job(job_id) def _deliver_result(self, job_id: str, result: Result) -> bool: """Attempt delivery and return whether this job can still be ended.""" if result.job_id != job_id: raise ValueError("Cloud Collection result does not match the running job") if self._upload_failure is not None: return True if self.status is not None and result.uploaded_files < len(result.data_files): self.status.transition(job_id, "uploading") def upload(data: BinaryIO) -> None: self._check_claim_before_request(job_id) self.client.upload_cloud_collector_job_data( job_id, data, run_attempt=self._upload_runner(job_id) ) try: delivered = result.deliver_staged_files(upload) except BloodHoundHTTPError as error: if error.code in (404, 409): self._abort_cloud_job(job_id) return False if error.code not in (400, 401, 403, 415): raise # Retain the failure across polls if reporting it fails. # Response bodies can contain sensitive collected data. self._upload_failure = f"Collector data upload rejected (HTTP {error.code})" else: if not delivered: self._upload_failure = ( "Collector data upload failed: staged file is missing" ) return True def _clear_active_job(self, job_id: str) -> None: self.next_heartbeat_at = None self._upload_failure = None self._claim_lost = False self._claim_unconfirmed = False self._job_ended = False if self.status is not None: self.status.release(job_id) def _heartbeat_delay(self, interval: float) -> float: if self.next_heartbeat_at is None: return interval return max(0, min(interval, self.next_heartbeat_at - time.monotonic())) def _check_claim_before_request(self, job_id: str) -> None: if not self._renew_claim_if_due(job_id): raise requests.ConnectionError("Cloud Collection claim check deferred") def _renew_claim_if_due(self, job_id: str) -> bool: if self._claim_lost: raise _CloudClaimLost now = time.monotonic() if self.next_heartbeat_at is None or now < self.next_heartbeat_at: return not self._claim_unconfirmed try: self.client.heartbeat_cloud_collector_job(job_id) except _CloudClaimLost: raise except Exception as error: # noqa: BLE001 if isinstance(error, BloodHoundHTTPError) and error.code == 404: self._claim_lost = True raise _CloudClaimLost from None self._claim_unconfirmed = True self.next_heartbeat_at = time.monotonic() + _HEARTBEAT_RETRY_INTERVAL logger.info( "Cloud Collection job %s heartbeat request failed.", job_id, extra={ "job_id": job_id, "error_type": type(error).__name__, "status_code": ( error.code if isinstance(error, BloodHoundHTTPError) else None ), }, ) else: self._claim_unconfirmed = False self.next_heartbeat_at = now + HEARTBEAT_INTERVAL logger.info("Cloud Collection job %s heartbeat succeeded.", job_id) return not self._claim_unconfirmed def _upload_runner(self, job_id: str) -> CollectorJobRequestRunner | None: if self.next_heartbeat_at is None: return None return partial(self._run_upload_attempt, job_id) def _run_upload_attempt( self, job_id: str, prepare_attempt: Callable[[], CollectorJobRequest], body: RequestBody, ) -> None: position = ( body.tell() if body is not None and not isinstance(body, bytes) else None ) for attempt in range(2): self._check_claim_before_request(job_id) request = prepare_attempt() try: with _upload_request( request, body, confirm_claim=partial(self._renew_claim_if_due, job_id), ) as finished: while not finished(self._heartbeat_delay(HEARTBEAT_INTERVAL)): self._renew_claim_if_due(job_id) return except BloodHoundHTTPError as error: if error.code != 401 or attempt: raise # A due heartbeat may have already replaced the rejected credentials. self._check_claim_before_request(job_id) credentials = ( self.client.token_key, self.client.token_id, ) if ( request.credentials == credentials and not self.client.refresh_credentials() ): raise if ( body is not None and not isinstance(body, bytes) and position is not None ): body.seek(position) def _abort_cloud_job(self, job_id: str) -> None: """Stop local work without reporting an outcome for a claim we no longer own.""" logger.warning( "Cloud Collection job %s claim lost; discarding local job.", job_id ) self._claim_lost = True try: self.worker.abort() finally: self._clear_active_job(job_id) @contextmanager def _upload_request( send: CollectorJobRequest, body: RequestBody, *, confirm_claim: Callable[[], bool], ) -> Iterator[Callable[[float], bool]]: """Run one upload attempt, joining it before the staged file can close.""" if body is None or isinstance(body, bytes): source, position = body, 0 else: # Reopen the staged file in the child so its offset and lifetime are local. source, position = Path(body.name), body.tell() context = multiprocessing.get_context("spawn") parent, child = context.Pipe() with parent, child: process = context.Process( target=_send_upload, args=(send, source, position, child) ) if hasattr(signal, "pthread_sigmask"): mask = signal.pthread_sigmask(signal.SIG_BLOCK, {signal.SIGINT}) try: process.start() finally: signal.pthread_sigmask(signal.SIG_SETMASK, mask) else: process.start() try: child.close() dispatch_pending = False dispatched = False outcome_received = False outcome = None def finished(timeout: float) -> bool: nonlocal dispatch_pending, dispatched, outcome_received, outcome if dispatch_pending and confirm_claim(): parent.send(None) dispatch_pending = False dispatched = True # A child awaiting authorization cannot send an outcome yet. handles = [process.sentinel] if not dispatch_pending and not dispatched: handles.append(parent) ready = wait(handles, timeout) if parent in ready: message = parent.recv() if message == "ready": dispatch_pending = True return False outcome, outcome_received = message, True return True return process.sentinel in ready yield finished if not outcome_received: try: outcome = parent.recv() except EOFError: raise RuntimeError( "Cloud Collection upload exited without a response" ) from None except BaseException: process.kill() raise finally: process.join() process.close() if outcome is None: return if isinstance(outcome, int): raise BloodHoundHTTPError("Cloud Collection upload rejected", outcome) if outcome == "timeout": raise requests.Timeout("Cloud Collection upload timed out") if outcome == "connection": raise requests.ConnectionError("Cloud Collection upload connection failed") raise RuntimeError("Cloud Collection upload failed") def _send_upload( send: CollectorJobRequest, body: bytes | Path | None, position: int, connection: Connection, ) -> None: signal.signal(signal.SIGINT, signal.SIG_IGN) if hasattr(signal, "pthread_sigmask"): signal.pthread_sigmask(signal.SIG_UNBLOCK, {signal.SIGINT}) # Forward only status or error type, never response content or credentials. with connection: def before_send() -> None: connection.send("ready") connection.recv() try: if isinstance(body, Path): with body.open("rb") as stream: stream.seek(position) send(stream, before_send=before_send) else: send(body, before_send=before_send) except BloodHoundHTTPError as error: connection.send(error.code) except requests.Timeout: connection.send("timeout") except requests.ConnectionError: connection.send("connection") except Exception: # noqa: BLE001 connection.send("failed") else: connection.send(None)