Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(data-warehouse): implement octopus_deploy import source (#71190)

Tom Owers369368252f8f
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
index 89f84fec744e..a3332232ba24 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -361,6 +361,7 @@ the row lists both.
| northpass_lms | HTTP | requests | ✅ |
| notion | HTTP | requests | ✅ |
| omnisend | HTTP | requests | ✅ |
+| octopus_deploy | HTTP | requests | ✅ |
| oncehub | HTTP | requests | ✅ |
| onepagecrm | HTTP | requests | ✅ |
| onepassword | HTTP (cursor pagination) | requests | ✅ |
@@ -817,7 +818,6 @@ doesn't conflict with concurrent PRs.
- nutshell
- nylas
- octolens
-- octopus_deploy
- onedrive
- onehundredms
- onesignal
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
index 555da3c044fc..fceccdd41872 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
@@ -2966,7 +2966,8 @@ class OctolensSourceConfig(config.Config):
@config.config
class OctopusDeploySourceConfig(config.Config):
- pass
+ host: str
+ api_key: str
@config.config
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/octopus_deploy/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/octopus_deploy/canonical_descriptions.py
new file mode 100644
index 000000000000..7fa122eb5fc1
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/octopus_deploy/canonical_descriptions.py
@@ -0,0 +1,160 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "spaces": {
+ "description": "Spaces partition an Octopus Deploy instance; every other resource belongs to exactly one space.",
+ "docs_url": "https://octopus.com/docs/administration/spaces",
+ "columns": {
+ "Id": "Unique identifier for the space.",
+ "Name": "Display name of the space.",
+ "Slug": "URL-friendly identifier for the space.",
+ "Description": "Description of the space.",
+ "IsDefault": "Whether this is the instance's default space.",
+ "IsPrivate": "Whether the space is a private user space.",
+ "TaskQueueStopped": "Whether the space's task queue has been stopped.",
+ "LastModifiedOn": "When the space was last modified.",
+ },
+ },
+ "projects": {
+ "description": "A project is a deployable application or component, holding its deployment process, variables, and releases.",
+ "docs_url": "https://octopus.com/docs/projects",
+ "columns": {
+ "Id": "Unique identifier for the project.",
+ "SpaceId": "Identifier of the space the project belongs to.",
+ "Name": "Display name of the project.",
+ "Slug": "URL-friendly identifier for the project.",
+ "Description": "Description of the project.",
+ "ProjectGroupId": "Identifier of the project group the project belongs to.",
+ "LifecycleId": "Identifier of the lifecycle that governs the project's promotion through environments.",
+ "IsDisabled": "Whether the project is disabled.",
+ "IsVersionControlled": "Whether the project's deployment process is stored in version control.",
+ "TenantedDeploymentMode": "Whether deployments are untenanted, tenanted, or both.",
+ },
+ },
+ "project_groups": {
+ "description": "Project groups organize related projects within a space.",
+ "docs_url": "https://octopus.com/docs/projects#project-group",
+ "columns": {
+ "Id": "Unique identifier for the project group.",
+ "SpaceId": "Identifier of the space the project group belongs to.",
+ "Name": "Display name of the project group.",
+ "Description": "Description of the project group.",
+ },
+ },
+ "environments": {
+ "description": "Environments are the stages deployments are promoted through, such as Development, Test, and Production.",
+ "docs_url": "https://octopus.com/docs/infrastructure/environments",
+ "columns": {
+ "Id": "Unique identifier for the environment.",
+ "SpaceId": "Identifier of the space the environment belongs to.",
+ "Name": "Display name of the environment.",
+ "Description": "Description of the environment.",
+ "SortOrder": "Relative order of the environment in the promotion lifecycle.",
+ "UseGuidedFailure": "Whether guided failure mode is enabled by default for the environment.",
+ },
+ },
+ "channels": {
+ "description": "Channels let a project run multiple release cadences (for example default and hotfix) with their own version rules and lifecycles.",
+ "docs_url": "https://octopus.com/docs/releases/channels",
+ "columns": {
+ "Id": "Unique identifier for the channel.",
+ "SpaceId": "Identifier of the space the channel belongs to.",
+ "ProjectId": "Identifier of the project the channel belongs to.",
+ "Name": "Display name of the channel.",
+ "Description": "Description of the channel.",
+ "LifecycleId": "Identifier of the lifecycle used by releases in this channel; empty means the project default.",
+ "IsDefault": "Whether this is the project's default channel.",
+ },
+ },
+ "tenants": {
+ "description": "Tenants model per-customer or per-region deployments of the same project (multi-tenancy).",
+ "docs_url": "https://octopus.com/docs/tenants",
+ "columns": {
+ "Id": "Unique identifier for the tenant.",
+ "SpaceId": "Identifier of the space the tenant belongs to.",
+ "Name": "Display name of the tenant.",
+ "TenantTags": "Tenant tags applied to the tenant.",
+ "ProjectEnvironments": "Mapping of project ids to the environments the tenant is connected to.",
+ },
+ },
+ "machines": {
+ "description": "Machines are deployment targets (VMs, Kubernetes clusters, cloud targets) that deployments run against.",
+ "docs_url": "https://octopus.com/docs/infrastructure/deployment-targets",
+ "columns": {
+ "Id": "Unique identifier for the deployment target.",
+ "SpaceId": "Identifier of the space the deployment target belongs to.",
+ "Name": "Display name of the deployment target.",
+ "Roles": "Target tags (roles) that deployment steps use to select this target.",
+ "EnvironmentIds": "Identifiers of the environments the target is assigned to.",
+ "HealthStatus": "Latest health check status of the target.",
+ "IsDisabled": "Whether the target is disabled.",
+ "OperatingSystem": "Operating system reported by the target.",
+ },
+ },
+ "releases": {
+ "description": "A release is a versioned snapshot of a project's deployment process, variables, and packages, ready to be deployed.",
+ "docs_url": "https://octopus.com/docs/releases",
+ "columns": {
+ "Id": "Unique identifier for the release.",
+ "SpaceId": "Identifier of the space the release belongs to.",
+ "ProjectId": "Identifier of the project the release belongs to.",
+ "ChannelId": "Identifier of the channel the release was created in.",
+ "Version": "Version number of the release.",
+ "Assembled": "When the release was created.",
+ "ReleaseNotes": "Release notes attached to the release.",
+ },
+ },
+ "deployments": {
+ "description": "A deployment is one execution of a release into an environment (optionally for a tenant) — the core record for deployment frequency and DORA metrics.",
+ "docs_url": "https://octopus.com/docs/deployments",
+ "columns": {
+ "Id": "Unique identifier for the deployment.",
+ "SpaceId": "Identifier of the space the deployment belongs to.",
+ "ReleaseId": "Identifier of the release that was deployed.",
+ "ProjectId": "Identifier of the project that was deployed.",
+ "EnvironmentId": "Identifier of the environment deployed to.",
+ "TenantId": "Identifier of the tenant deployed for, when tenanted.",
+ "ChannelId": "Identifier of the channel of the deployed release.",
+ "TaskId": "Identifier of the server task that executed the deployment; join to tasks for state and duration.",
+ "Name": "Display name of the deployment.",
+ "Created": "When the deployment was created.",
+ "DeployedBy": "User or trigger that started the deployment.",
+ },
+ },
+ "tasks": {
+ "description": "Server tasks are queued units of work (deployments, runbook runs, health checks) with state and timing — the source of deployment outcomes and durations.",
+ "docs_url": "https://octopus.com/docs/tasks",
+ "columns": {
+ "Id": "Unique identifier for the task.",
+ "SpaceId": "Identifier of the space the task belongs to.",
+ "Name": "Task type, such as Deploy or Health.",
+ "Description": "Human-readable description of the task.",
+ "State": "Current state of the task, such as Queued, Executing, Success, Failed, or Canceled.",
+ "QueueTime": "When the task was queued.",
+ "StartTime": "When the task started executing.",
+ "CompletedTime": "When the task completed.",
+ "Duration": "Human-readable duration of the task.",
+ "FinishedSuccessfully": "Whether the task finished successfully.",
+ "HasWarningsOrErrors": "Whether the task log contains warnings or errors.",
+ "ErrorMessage": "Error message for failed tasks.",
+ "ProjectId": "Identifier of the project the task relates to, when applicable.",
+ },
+ },
+ "events": {
+ "description": "Audit events record every significant action on the instance (deployments queued, releases created, settings changed).",
+ "docs_url": "https://octopus.com/docs/security/users-and-teams/auditing",
+ "columns": {
+ "Id": "Unique identifier for the audit event.",
+ "SpaceId": "Identifier of the space the event belongs to.",
+ "Occurred": "When the event occurred.",
+ "Category": "Event category, such as Created, Modified, Deleted, or DeploymentQueued.",
+ "Message": "Human-readable description of the event.",
+ "Username": "Username of the user who performed the action.",
+ "UserId": "Identifier of the user who performed the action.",
+ "IpAddress": "IP address the action was performed from.",
+ "RelatedDocumentIds": "Identifiers of the documents the event relates to.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/octopus_deploy/octopus_deploy.py b/products/warehouse_sources/backend/temporal/data_imports/sources/octopus_deploy/octopus_deploy.py
new file mode 100644
index 000000000000..8598544a70e0
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/octopus_deploy/octopus_deploy.py
@@ -0,0 +1,503 @@
+import re
+import json
+import time
+import dataclasses
+from collections.abc import Iterator
+from datetime import UTC, date, datetime
+from typing import Any, Optional
+from urllib.parse import urlencode
+
+import requests
+from structlog.types import FilteringBoundLogger
+from tenacity import RetryCallState, retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+from urllib3.util.retry import Retry
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.mixins import _is_host_safe
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.octopus_deploy.settings import (
+ OCTOPUS_DEPLOY_ENDPOINTS,
+ OctopusDeployEndpointConfig,
+)
+
+REQUEST_TIMEOUT_SECONDS = 60
+MAX_RETRIES = 5
+MAX_RETRY_AFTER_SECONDS = 60
+SPACES_PAGE_SIZE = 100
+
+# The host is customer-controlled, so a malicious or misconfigured server could stream an
+# unbounded body and exhaust a shared worker (requests buffers the whole body into memory by
+# default, and the read timeout only guards idle gaps, not a steady large transfer). Cap what we
+# read into memory — far larger than any real listing page, anything past it is refused.
+MAX_RESPONSE_BYTES = 256 * 1024 * 1024
+RESPONSE_CHUNK_BYTES = 256 * 1024
+# Error bodies are customer-controlled and capped only by MAX_RESPONSE_BYTES, so never interpolate a
+# whole body into a log event — a large-but-under-cap 4xx would balloon the log line and hammer the
+# logging pipeline. Log a small fixed-size preview plus the true byte count instead.
+LOG_BODY_PREVIEW_BYTES = 8 * 1024
+# Wall-clock budget for downloading one page's body. requests' timeout only bounds each individual
+# socket read, so a host that dribbles the body slowly could hold the connection (and a shared
+# worker) open far longer than any read timeout while staying under MAX_RESPONSE_BYTES. This caps
+# total transfer time — 256 MiB in 300s is a ~0.85 MiB/s floor, far below any real API response and
+# far above a slow-drip stall.
+MAX_DOWNLOAD_SECONDS = 300
+
+# A customer-controlled host could return `Page.Next` forever (or a `skip` that never advances past
+# the data), keeping a shared worker paginating indefinitely while `_get_space_ids` accumulates IDs
+# in memory. Cap how many pages any single listing loop will walk — set far above any real Octopus
+# listing (100k pages is 10M+ rows even at the smallest page size) so only a misbehaving or
+# malicious server trips it. Non-retryable: the same host returns the same runaway response.
+MAX_PAGES_PER_LISTING = 100_000
+
+# The page ceiling bounds memory, not time: each page may legitimately take up to MAX_DOWNLOAD_SECONDS,
+# so a host that returns nonempty pages advertising `Page.Next` (or stalls before each fetch) could
+# keep a shared worker paginating far longer than any real sync while never tripping the page ceiling.
+# Cap the cumulative wall-clock a single listing loop may spend — generous for real syncs (fast pages
+# walk enormous volumes well within it) yet far below the import activity's one-week timeout, so a slow
+# or malicious host is cut off. Non-retryable, like the page ceiling: the same host reproduces it.
+MAX_LISTING_SECONDS = 6 * 60 * 60
+
+HOST_NOT_ALLOWED_ERROR = "Octopus Deploy host is not allowed"
+RESPONSE_TOO_LARGE_ERROR = "Octopus Deploy response body was too large"
+RESPONSE_TOO_SLOW_ERROR = "Octopus Deploy response download was too slow"
+PAGINATION_LIMIT_ERROR = "Octopus Deploy pagination exceeded the maximum budget"
+
+
+class OctopusDeployRetryableError(Exception):
+ def __init__(self, message: str, retry_after: float | None = None) -> None:
+ super().__init__(message)
+ self.retry_after = retry_after
+
+
+class OctopusDeployHostNotAllowedError(Exception):
+ pass
+
+
+class OctopusDeployResponseTooLargeError(Exception):
+ pass
+
+
+class OctopusDeployResponseTooSlowError(Exception):
+ pass
+
+
+class OctopusDeployPaginationLimitError(Exception):
+ pass
+
+
+def _read_capped_body(response: requests.Response) -> bytes:
+ """Stream the body into memory, aborting past MAX_RESPONSE_BYTES or MAX_DOWNLOAD_SECONDS.
+
+ The host is customer-controlled, so a body must never be buffered unbounded (size cap) nor be
+ allowed to hold the connection open indefinitely by dribbling under the per-read timeout (time
+ cap). Both are non-retryable: re-fetching the same page yields the same oversized/slow body.
+ """
+ chunks: list[bytes] = []
+ total = 0
+ deadline = time.monotonic() + MAX_DOWNLOAD_SECONDS
+ try:
+ for chunk in response.iter_content(chunk_size=RESPONSE_CHUNK_BYTES):
+ if time.monotonic() > deadline:
+ raise OctopusDeployResponseTooSlowError(
+ f"{RESPONSE_TOO_SLOW_ERROR}: exceeded {MAX_DOWNLOAD_SECONDS}s download budget"
+ )
+ if not chunk:
+ continue
+ total += len(chunk)
+ if total > MAX_RESPONSE_BYTES:
+ raise OctopusDeployResponseTooLargeError(
+ f"{RESPONSE_TOO_LARGE_ERROR}: exceeded {MAX_RESPONSE_BYTES} bytes"
+ )
+ chunks.append(chunk)
+ finally:
+ response.close()
+ return b"".join(chunks)
+
+
+class OctopusDeployResumeConfig:
+ # Offset (`skip`) of the next unfetched page within the current listing.
+ skip: int = 0
+ # The space currently being processed. A stable space-ID bookmark (not a positional index)
+ # so spaces added/removed between a crash and the retry can't resume us into the wrong
+ # space. None for instance-level endpoints (spaces).
+ space_id: str | None = None
+
+
+def normalize_host(host: str) -> str:
+ """Turn whatever the user typed into a bare Octopus server host.
+
+ Accepts values like ``my-org.octopus.app``, ``https://my-org.octopus.app/``, or
+ ``https://octopus.example.com/app#/Spaces-1`` and returns the bare hostname.
+ """
+ host = host.strip()
+ host = re.sub(r"^https?://", "", host, flags=re.IGNORECASE)
+ host = host.split("/")[0]
+ return host.strip().rstrip("/")
+
+
+def _base_url(host: str) -> str:
+ return f"https://{normalize_host(host)}"
+
+
+def _get_headers(api_key: str) -> dict[str, str]:
+ return {
+ "X-Octopus-ApiKey": api_key,
+ "Accept": "application/json",
+ }
+
+
+def _format_incremental_value(value: Any) -> str:
+ if isinstance(value, datetime):
+ utc_dt = value.replace(tzinfo=UTC) if value.tzinfo is None else value.astimezone(UTC)
+ return utc_dt.isoformat()
+ if isinstance(value, date):
+ return datetime.combine(value, datetime.min.time(), tzinfo=UTC).isoformat()
+ return str(value)
+
+
+def _build_params(
+ config: OctopusDeployEndpointConfig,
+ skip: int,
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Any,
+) -> dict[str, Any]:
+ params: dict[str, Any] = {"skip": skip, "take": config.page_size}
+
+ if config.incremental_param and should_use_incremental_field and db_incremental_field_last_value:
+ params[config.incremental_param] = _format_incremental_value(db_incremental_field_last_value)
+
+ return params
+
+
+def _endpoint_url(host: str, config: OctopusDeployEndpointConfig, space_id: str | None) -> str:
+ if config.space_scoped:
+ return f"{_base_url(host)}/api/{space_id}{config.path}"
+ return f"{_base_url(host)}{config.path}"
+
+
+def _parse_retry_after(response: requests.Response) -> float | None:
+ """Octopus sends ``Retry-After`` in whole seconds on 429. Ignore HTTP-date forms."""
+ raw = response.headers.get("Retry-After")
+ if raw and raw.strip().isdigit():
+ return min(float(raw.strip()), MAX_RETRY_AFTER_SECONDS)
+ return None
+
+
+def _retry_wait(retry_state: RetryCallState) -> float:
+ """Honor a server-provided Retry-After when present, else exponential backoff."""
+ exc = retry_state.outcome.exception() if retry_state.outcome else None
+ if isinstance(exc, OctopusDeployRetryableError) and exc.retry_after is not None:
+ return exc.retry_after
+ return wait_exponential_jitter(initial=1, max=30)(retry_state)
+
+
+@retry(
+ retry=retry_if_exception_type((OctopusDeployRetryableError, requests.ReadTimeout, requests.ConnectionError)),
+ stop=stop_after_attempt(MAX_RETRIES),
+ wait=_retry_wait,
+ reraise=True,
+)
+def _fetch_page(
+ session: requests.Session, url: str, headers: dict[str, str], logger: FilteringBoundLogger
+) -> dict[str, Any]:
+ # Don't follow redirects: the customer-controlled host could 3xx to an internal address,
+ # bypassing the host validation done before the request (SSRF).
+ # stream=True so the body isn't buffered until we cap it — see _read_capped_body.
+ response = session.get(url, headers=headers, timeout=REQUEST_TIMEOUT_SECONDS, allow_redirects=False, stream=True)
+
+ if response.status_code == 429 or response.status_code >= 500:
+ response.close()
+ retry_after = _parse_retry_after(response) if response.status_code == 429 else None
+ raise OctopusDeployRetryableError(
+ f"Octopus Deploy API error (retryable): status={response.status_code}, url={url}",
+ retry_after=retry_after,
+ )
+
+ # A 3xx isn't an error status (`response.ok` is True), so reject it explicitly rather than
+ # silently parsing the redirect body as data.
+ if response.is_redirect or response.is_permanent_redirect:
+ response.close()
+ raise OctopusDeployHostNotAllowedError(
+ f"Octopus Deploy API returned an unexpected redirect (status={response.status_code}); refusing to follow it"
+ )
+
+ body = _read_capped_body(response)
+
+ if not response.ok:
+ preview = body[:LOG_BODY_PREVIEW_BYTES].decode(errors="replace")
+ logger.error(
+ f"Octopus Deploy API error: status={response.status_code}, body_bytes={len(body)}, body_preview={preview}, url={url}"
+ )
+ response.raise_for_status()
+
+ return json.loads(body or b"null")
+
+
+def _get_space_ids(
+ session: requests.Session, host: str, headers: dict[str, str], logger: FilteringBoundLogger
+) -> list[str]:
+ """Enumerate every space the API key can see, sorted by id for a deterministic fan-out order."""
+ space_ids: list[str] = []
+ skip = 0
+ deadline = time.monotonic() + MAX_LISTING_SECONDS
+ for _ in range(MAX_PAGES_PER_LISTING):
+ url = f"{_base_url(host)}/api/spaces?{urlencode({'skip': skip, 'take': SPACES_PAGE_SIZE})}"
+ data = _fetch_page(session, url, headers, logger)
+ items = data.get("Items") or []
+ if not items:
+ break
+ space_ids.extend(item["Id"] for item in items)
+ if "Page.Next" not in (data.get("Links") or {}):
+ break
+ if time.monotonic() > deadline:
+ raise OctopusDeployPaginationLimitError(
+ f"{PAGINATION_LIMIT_ERROR}: spaces listing exceeded {MAX_LISTING_SECONDS}s time budget"
+ )
+ skip += len(items)
+ else:
+ raise OctopusDeployPaginationLimitError(
+ f"{PAGINATION_LIMIT_ERROR}: spaces listing exceeded {MAX_PAGES_PER_LISTING} pages"
+ )
+ return sorted(space_ids)
+
+
+def _paginate(
+ session: requests.Session,
+ url: str,
+ config: OctopusDeployEndpointConfig,
+ headers: dict[str, str],
+ logger: FilteringBoundLogger,
+ space_id: str | None,
+ initial_skip: int,
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Any,
+ resumable_source_manager: ResumableSourceManager[OctopusDeployResumeConfig],
+) -> Iterator[list[dict[str, Any]]]:
+ """Walk one listing with skip/take offset pagination, yielding a batch per page.
+
+ Octopus returns newest-first, so rows created mid-sync push already-seen rows to higher
+ offsets — worst case we re-fetch a row (merge dedupes on the primary key), never skip one.
+ """
+ skip = initial_skip
+ deadline = time.monotonic() + MAX_LISTING_SECONDS
+ for _ in range(MAX_PAGES_PER_LISTING):
+ params = _build_params(config, skip, should_use_incremental_field, db_incremental_field_last_value)
+ data = _fetch_page(session, f"{url}?{urlencode(params)}", headers, logger)
+
+ items = data.get("Items") or []
+ if not items:
+ break
+
+ if config.space_scoped and space_id is not None:
+ for item in items:
+ item.setdefault("SpaceId", space_id)
+
+ has_next = "Page.Next" in (data.get("Links") or {})
+ skip += len(items)
+
+ yield items
+
+ if not has_next:
+ break
+
+ if time.monotonic() > deadline:
+ raise OctopusDeployPaginationLimitError(
+ f"{PAGINATION_LIMIT_ERROR}: {url} exceeded {MAX_LISTING_SECONDS}s time budget"
+ )
+
+ # Save AFTER yielding so a crash re-yields the last page rather than skipping it — merge
+ # dedupes on the primary key.
+ resumable_source_manager.save_state(OctopusDeployResumeConfig(skip=skip, space_id=space_id))
+ else:
+ raise OctopusDeployPaginationLimitError(
+ f"{PAGINATION_LIMIT_ERROR}: {url} exceeded {MAX_PAGES_PER_LISTING} pages"
+ )
+
+
+def get_rows(
+ host: str,
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[OctopusDeployResumeConfig],
+ team_id: int,
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+) -> Iterator[list[dict[str, Any]]]:
+ config = OCTOPUS_DEPLOY_ENDPOINTS[endpoint]
+ headers = _get_headers(api_key)
+
+ # Re-check at run time (not just at source-create) in case the host was edited or now
+ # resolves to an internal address (SSRF / DNS rebinding). Only enforced on cloud.
+ host_ok, host_err = _is_host_safe(normalize_host(host), team_id)
+ if not host_ok:
+ raise OctopusDeployHostNotAllowedError(host_err or HOST_NOT_ALLOWED_ERROR)
+
+ # One session reused across every page (and space) so urllib3 keeps the connection alive
+ # instead of re-handshaking per request. `redact_values` masks the API key from logged
+ # URLs and captured HTTP samples (the X-Octopus-ApiKey header isn't in the sampler's
+ # generic denylist). `retry=Retry(total=0)` disables the adapter's default retries so
+ # `_fetch_page`'s tenacity policy is the only retry budget — otherwise the two nest and a
+ # stalling host could hold a worker for far longer than either policy alone intends.
+ session = make_tracked_session(retry=Retry(total=0), redact_values=(api_key,))
+
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+
+ if not config.space_scoped:
+ initial_skip = resume.skip if resume is not None else 0
+ url = _endpoint_url(host, config, None)
+ yield from _paginate(
+ session,
+ url,
+ config,
+ headers,
+ logger,
+ space_id=None,
+ initial_skip=initial_skip,
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ resumable_source_manager=resumable_source_manager,
+ )
+ return
+
+ space_ids = _get_space_ids(session, host, headers, logger)
+
+ # Resolve the saved space-ID bookmark to the slice of spaces still to process. If the
+ # bookmarked space no longer exists (deleted between runs), start over from the first space —
+ # merge dedupes the re-pulled rows on the primary key.
+ remaining = space_ids
+ resume_skip = 0
+ if resume is not None and resume.space_id is not None and resume.space_id in space_ids:
+ remaining = space_ids[space_ids.index(resume.space_id) :]
+ resume_skip = resume.skip
+ logger.debug(f"Octopus Deploy: resuming {endpoint} from space_id={resume.space_id}, skip={resume_skip}")
+
+ for index, space_id in enumerate(remaining):
+ url = _endpoint_url(host, config, space_id)
+ yield from _paginate(
+ session,
+ url,
+ config,
+ headers,
+ logger,
+ space_id=space_id,
+ initial_skip=resume_skip,
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ resumable_source_manager=resumable_source_manager,
+ )
+ resume_skip = 0 # only the resumed-into space starts at the saved offset
+
+ # Advance the bookmark to the next space so a crash between spaces resumes correctly.
+ if index + 1 < len(remaining):
+ resumable_source_manager.save_state(OctopusDeployResumeConfig(skip=0, space_id=remaining[index + 1]))
+
+
+def validate_credentials(
+ host: str, api_key: str, schema_name: Optional[str] = None, team_id: Optional[int] = None
+) -> tuple[bool, str | None]:
+ """Probe the spaces listing to confirm the API key is genuine.
+
+ At source-create (``schema_name is None``) a 403 is accepted: the key is valid but may be
+ scoped to specific spaces/permissions. A scoped probe (``schema_name`` set) treats 403 as a
+ hard failure.
+ """
+ try:
+ normalized = normalize_host(host)
+ except Exception:
+ return False, "Invalid Octopus Deploy host"
+
+ if not normalized or not re.match(r"^[A-Za-z0-9.\-]+$", normalized):
+ return False, "Invalid Octopus Deploy host"
+
+ # The host is fully customer-controlled (cloud `*.octopus.app` or self-hosted), so block
+ # hosts that resolve to private/internal addresses (SSRF). Only enforced on cloud.
+ if team_id is not None:
+ host_ok, host_err = _is_host_safe(normalized, team_id)
+ if not host_ok:
+ return False, host_err or HOST_NOT_ALLOWED_ERROR
+
+ url = f"https://{normalized}/api/spaces?take=1"
+ try:
+ # Don't follow redirects: the validated host could 3xx to an internal address, defeating
+ # the host check above (SSRF). stream=True so a customer-controlled host can't force us to
+ # buffer an unbounded probe body — see _read_capped_body. retry=Retry(total=0) keeps a
+ # stalling host from being retried three times behind this single validation probe.
+ response = make_tracked_session(retry=Retry(total=0), redact_values=(api_key,)).get(
+ url, headers=_get_headers(api_key), timeout=10, allow_redirects=False, stream=True
+ )
+ except requests.exceptions.RequestException as e:
+ return False, str(e)
+
+ try:
+ if response.is_redirect or response.is_permanent_redirect:
+ return False, HOST_NOT_ALLOWED_ERROR
+
+ if response.status_code == 200:
+ return True, None
+
+ if response.status_code == 401:
+ return False, "Invalid Octopus Deploy API key"
+
+ if response.status_code == 403:
+ if schema_name is None:
+ # Valid key, missing permission for this probe — let source creation through.
+ return True, None
+ return False, "Your Octopus Deploy API key lacks the required permissions for this endpoint"
+
+ try:
+ body = _read_capped_body(response)
+ except (OctopusDeployResponseTooLargeError, OctopusDeployResponseTooSlowError) as e:
+ return False, str(e)
+
+ text = body.decode(errors="replace")
+ try:
+ parsed = json.loads(body or b"null")
+ except ValueError:
+ return False, text
+ if isinstance(parsed, dict):
+ return False, parsed.get("ErrorMessage", text)
+ return False, text
+ finally:
+ response.close()
+
+
+def octopus_deploy_source(
+ host: str,
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[OctopusDeployResumeConfig],
+ team_id: int,
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+) -> SourceResponse:
+ endpoint_config = OCTOPUS_DEPLOY_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ host=host,
+ api_key=api_key,
+ endpoint=endpoint,
+ logger=logger,
+ resumable_source_manager=resumable_source_manager,
+ team_id=team_id,
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ ),
+ # Octopus document ids look instance-unique, but that isn't documented — and space-scoped
+ # listings fan out over every space, so the space id goes in the key to be safe.
+ primary_keys=["SpaceId", "Id"] if endpoint_config.space_scoped else ["Id"],
+ # Octopus listings return newest-first with no ascending option (verified against a live
+ # server), and space fan-out means a partial run's max says nothing about spaces it never
+ # reached — so the incremental watermark must only persist at successful job end.
+ sort_mode="desc",
+ partition_count=1,
+ partition_size=1,
+ partition_mode="datetime" if endpoint_config.partition_key else None,
+ partition_format="week" if endpoint_config.partition_key else None,
+ partition_keys=[endpoint_config.partition_key] if endpoint_config.partition_key else None,
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/octopus_deploy/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/octopus_deploy/settings.py
new file mode 100644
index 000000000000..d4bf1a220a11
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/octopus_deploy/settings.py
@@ -0,0 +1,102 @@
+from dataclasses import dataclass, field
+from typing import Optional
+
+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+
+
+def _datetime_incremental_field(name: str) -> IncrementalField:
+ return {
+ "label": name,
+ "type": IncrementalFieldType.DateTime,
+ "field": name,
+ "field_type": IncrementalFieldType.DateTime,
+ }
+
+
+@dataclass
+class OctopusDeployEndpointConfig:
+ name: str
+ # For space-scoped endpoints, relative to `/api/{space_id}`; for instance-level endpoints,
+ # the full path under the host (e.g. `/api/spaces`).
+ path: str
+ # Almost every Octopus resource lives under `/api/Spaces-{n}/...`; the source fans out over
+ # every space the API key can see and stamps `SpaceId` onto each row.
+ space_scoped: bool = True
+ incremental_fields: list[IncrementalField] = field(default_factory=list)
+ # Query param carrying the server-side date filter (`fromCompletedDate` on tasks, `from` on
+ # events). Endpoints without one are full-refresh only.
+ incremental_param: Optional[str] = None
+ # Stable, immutable field to partition by. Never a last-modified style field (it mutates).
+ partition_key: Optional[str] = None
+ page_size: int = 100
+
+
+OCTOPUS_DEPLOY_ENDPOINTS: dict[str, OctopusDeployEndpointConfig] = {
+ "spaces": OctopusDeployEndpointConfig(
+ name="spaces",
+ path="/api/spaces",
+ space_scoped=False,
+ ),
+ "projects": OctopusDeployEndpointConfig(
+ name="projects",
+ path="/projects",
+ ),
+ "project_groups": OctopusDeployEndpointConfig(
+ name="project_groups",
+ path="/projectgroups",
+ ),
+ "environments": OctopusDeployEndpointConfig(
+ name="environments",
+ path="/environments",
+ ),
+ "channels": OctopusDeployEndpointConfig(
+ name="channels",
+ path="/channels",
+ ),
+ "tenants": OctopusDeployEndpointConfig(
+ name="tenants",
+ path="/tenants",
+ ),
+ "machines": OctopusDeployEndpointConfig(
+ name="machines",
+ path="/machines",
+ ),
+ # Releases and deployments expose no server-side date filter (only project/environment
+ # filters), so they are full-refresh only. Their creation timestamps are immutable and make
+ # stable partition keys.
+ "releases": OctopusDeployEndpointConfig(
+ name="releases",
+ path="/releases",
+ partition_key="Assembled",
+ ),
+ "deployments": OctopusDeployEndpointConfig(
+ name="deployments",
+ path="/deployments",
+ partition_key="Created",
+ ),
+ # Tasks accept `fromCompletedDate`, a genuine server-side filter on CompletedTime (verified:
+ # a future cutoff returns zero rows). QueueTime is set once at creation and never mutates,
+ # unlike CompletedTime which flips from null when the task finishes.
+ "tasks": OctopusDeployEndpointConfig(
+ name="tasks",
+ path="/tasks",
+ incremental_fields=[_datetime_incremental_field("CompletedTime")],
+ incremental_param="fromCompletedDate",
+ partition_key="QueueTime",
+ ),
+ # Audit events accept `from`, a server-side filter on Occurred. Events are immutable.
+ "events": OctopusDeployEndpointConfig(
+ name="events",
+ path="/events",
+ incremental_fields=[_datetime_incremental_field("Occurred")],
+ incremental_param="from",
+ partition_key="Occurred",
+ page_size=200,
+ ),
+}
+
+ENDPOINTS = tuple(OCTOPUS_DEPLOY_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in OCTOPUS_DEPLOY_ENDPOINTS.items()
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/octopus_deploy/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/octopus_deploy/source.py
index 741089d68548..3565d5d1cdbd 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/octopus_deploy/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/octopus_deploy/source.py
@@ -1,19 +1,43 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
DataWarehouseSourceCategory,
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (
+ SourceInputs,
+ SourceResponse,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchema
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import OctopusDeploySourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.octopus_deploy.octopus_deploy import (
+ HOST_NOT_ALLOWED_ERROR,
+ OctopusDeployResumeConfig,
+ octopus_deploy_source,
+ validate_credentials as validate_octopus_deploy_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.octopus_deploy.settings import (
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class OctopusDeploySource(SimpleSource[OctopusDeploySourceConfig]):
+class OctopusDeploySource(ResumableSource[OctopusDeploySourceConfig, OctopusDeployResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.OCTOPUSDEPLOY
@@ -24,7 +48,108 @@ class OctopusDeploySource(SimpleSource[OctopusDeploySourceConfig]):
name=SchemaExternalDataSourceType.OCTOPUS_DEPLOY,
category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,
label="Octopus Deploy",
+ releaseStatus=ReleaseStatus.ALPHA,
+ caption="""Enter your Octopus Deploy server URL and an API key to pull your deployment data into the PostHog Data warehouse.
+
+Use your Octopus Cloud URL (like `https://your-org.octopus.app`) or your self-hosted server's public URL.
+
+You can create an API key in the Octopus web portal under **your profile > My API Keys**. The key inherits your user's permissions, so it needs read access to the spaces you want to sync.""",
iconPath="/static/services/octopus_deploy.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/octopus-deploy",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="host",
+ label="Octopus Deploy URL",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="https://your-org.octopus.app",
+ secret=False,
+ ),
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="API-XXXXXXXXXXXXXXXXXXXXXXXXXX",
+ secret=True,
+ ),
+ ],
+ ),
+ )
+
+ @property
+ def connection_host_fields(self) -> list[str]:
+ # The API key is sent to whatever host `host` points at, so retargeting it must
+ # re-require the key (prevents exfiltrating the stored key to a server the editor controls).
+ return ["host"]
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error": "Invalid Octopus Deploy API key. Please generate a new key and reconnect.",
+ "403 Client Error": "Your Octopus Deploy API key lacks the required permissions. Please check the key's user permissions and try again.",
+ HOST_NOT_ALLOWED_ERROR: "The Octopus Deploy host is not allowed. Please use your Octopus Cloud or self-hosted server URL.",
+ }
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.octopus_deploy.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_schemas(
+ self,
+ config: OctopusDeploySourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ def _description(endpoint: str) -> str | None:
+ if endpoint == "tasks":
+ return "Incremental syncs filter on completion date, so tasks only appear once they finish"
+ return None
+
+ schemas = [
+ SourceSchema(
+ name=endpoint,
+ supports_incremental=bool(INCREMENTAL_FIELDS.get(endpoint)),
+ supports_append=bool(INCREMENTAL_FIELDS.get(endpoint)),
+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),
+ description=_description(endpoint),
+ )
+ for endpoint in ENDPOINTS
+ ]
+ if names is not None:
+ names_set = set(names)
+ schemas = [s for s in schemas if s.name in names_set]
+ return schemas
+
+ def validate_credentials(
+ self, config: OctopusDeploySourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ return validate_octopus_deploy_credentials(config.host, config.api_key, schema_name, team_id)
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[OctopusDeployResumeConfig]:
+ return ResumableSourceManager[OctopusDeployResumeConfig](inputs, OctopusDeployResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: OctopusDeploySourceConfig,
+ resumable_source_manager: ResumableSourceManager[OctopusDeployResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return octopus_deploy_source(
+ host=config.host,
+ api_key=config.api_key,
+ endpoint=inputs.schema_name,
+ logger=inputs.logger,
+ resumable_source_manager=resumable_source_manager,
+ team_id=inputs.team_id,
+ should_use_incremental_field=inputs.should_use_incremental_field,
+ db_incremental_field_last_value=inputs.db_incremental_field_last_value
+ if inputs.should_use_incremental_field
+ else None,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/octopus_deploy/tests/test_octopus_deploy.py b/products/warehouse_sources/backend/temporal/data_imports/sources/octopus_deploy/tests/test_octopus_deploy.py
new file mode 100644
index 000000000000..bc067c5144b2
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/octopus_deploy/tests/test_octopus_deploy.py
@@ -0,0 +1,499 @@
+import json
+from datetime import UTC, date, datetime
+from typing import Any, Optional
+from urllib.parse import parse_qs, urlparse
+
+import pytest
+from unittest import mock
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.octopus_deploy import (
+ octopus_deploy as octopus_deploy_module,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.octopus_deploy.octopus_deploy import (
+ OctopusDeployResumeConfig,
+ _build_params,
+ _format_incremental_value,
+ _parse_retry_after,
+ get_rows,
+ normalize_host,
+ octopus_deploy_source,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.octopus_deploy.settings import (
+ OCTOPUS_DEPLOY_ENDPOINTS,
+)
+
+
+def _response(*, status_code: int = 200, json_data: Any = None, text: str = "") -> mock.MagicMock:
+ response = mock.MagicMock()
+ response.status_code = status_code
+ response.ok = 200 <= status_code < 400
+ response.is_redirect = status_code in (302, 303, 307)
+ response.is_permanent_redirect = status_code in (301, 308)
+ response.text = text
+ response.json.return_value = json_data
+ response.headers = {}
+ # The body is streamed and read via iter_content (stream=True), not response.json().
+ if json_data is not None:
+ body = json.dumps(json_data).encode()
+ else:
+ body = text.encode()
+ response.iter_content.return_value = [body] if body else []
+ return response
+
+
+def _page(items: list[dict[str, Any]], has_next: bool) -> mock.MagicMock:
+ links = {"Self": "/api/x"}
+ if has_next:
+ links["Page.Next"] = "/api/x?skip=next"
+ return _response(json_data={"Items": items, "Links": links})
+
+
+class TestNormalizeHost:
+ @pytest.mark.parametrize(
+ "raw, expected",
+ [
+ ("my-org.octopus.app", "my-org.octopus.app"),
+ ("https://my-org.octopus.app", "my-org.octopus.app"),
+ ("http://octopus.example.com/", "octopus.example.com"),
+ (" my-org.octopus.app ", "my-org.octopus.app"),
+ ("https://my-org.octopus.app/app#/Spaces-1", "my-org.octopus.app"),
+ ],
+ )
+ def test_normalize_host(self, raw, expected):
+ assert normalize_host(raw) == expected
+
+
+class TestFormatIncrementalValue:
+ @pytest.mark.parametrize(
+ "value, expected",
+ [
+ (datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC), "2026-03-04T02:58:14+00:00"),
+ (datetime(2026, 3, 4, 2, 58, 14), "2026-03-04T02:58:14+00:00"),
+ (date(2026, 3, 4), "2026-03-04T00:00:00+00:00"),
+ ("already-a-cursor", "already-a-cursor"),
+ ],
+ )
+ def test_format(self, value, expected):
+ assert _format_incremental_value(value) == expected
+
+
+class TestBuildParams:
+ def test_tasks_incremental_sends_from_completed_date(self):
+ params = _build_params(
+ OCTOPUS_DEPLOY_ENDPOINTS["tasks"],
+ skip=0,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2024, 1, 1, tzinfo=UTC),
+ )
+ assert params["fromCompletedDate"] == "2024-01-01T00:00:00+00:00"
+ assert params["skip"] == 0
+ assert params["take"] == 100
+
+ def test_events_incremental_sends_from(self):
+ params = _build_params(
+ OCTOPUS_DEPLOY_ENDPOINTS["events"],
+ skip=200,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2024, 1, 1, tzinfo=UTC),
+ )
+ assert params["from"] == "2024-01-01T00:00:00+00:00"
+ assert params["skip"] == 200
+
+ def test_no_watermark_sends_no_filter(self):
+ params = _build_params(
+ OCTOPUS_DEPLOY_ENDPOINTS["tasks"],
+ skip=0,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=None,
+ )
+ assert "fromCompletedDate" not in params
+
+ def test_full_refresh_ignores_stray_watermark(self):
+ params = _build_params(
+ OCTOPUS_DEPLOY_ENDPOINTS["tasks"],
+ skip=0,
+ should_use_incremental_field=False,
+ db_incremental_field_last_value=datetime(2024, 1, 1, tzinfo=UTC),
+ )
+ assert "fromCompletedDate" not in params
+
+ def test_non_incremental_endpoint_never_sends_filter(self):
+ # Deployments expose no server-side date filter; an incremental run must not invent one.
+ params = _build_params(
+ OCTOPUS_DEPLOY_ENDPOINTS["deployments"],
+ skip=0,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2024, 1, 1, tzinfo=UTC),
+ )
+ assert params == {"skip": 0, "take": 100}
+
+
+class TestValidateCredentials:
+ def _patch_session(self, response=None, raises=None):
+ session = mock.MagicMock()
+ if raises is not None:
+ session.get.side_effect = raises
+ else:
+ session.get.return_value = response
+ return mock.patch.object(octopus_deploy_module, "make_tracked_session", return_value=session)
+
+ def test_success(self):
+ with self._patch_session(_response(status_code=200, json_data={"Items": []})):
+ assert validate_credentials("my-org.octopus.app", "API-KEY") == (True, None)
+
+ def test_invalid_key(self):
+ with self._patch_session(_response(status_code=401)):
+ valid, msg = validate_credentials("my-org.octopus.app", "API-KEY")
+ assert valid is False
+ assert msg == "Invalid Octopus Deploy API key"
+
+ def test_403_at_source_create_is_accepted(self):
+ with self._patch_session(_response(status_code=403)):
+ assert validate_credentials("my-org.octopus.app", "API-KEY", schema_name=None) == (True, None)
+
+ def test_403_for_scoped_probe_fails(self):
+ with self._patch_session(_response(status_code=403)):
+ valid, msg = validate_credentials("my-org.octopus.app", "API-KEY", schema_name="deployments")
+ assert valid is False
+ assert msg is not None
+
+ def test_error_body_message_is_surfaced(self):
+ with self._patch_session(_response(status_code=400, json_data={"ErrorMessage": "Something broke"})):
+ valid, msg = validate_credentials("my-org.octopus.app", "API-KEY")
+ assert valid is False
+ assert msg == "Something broke"
+
+ @pytest.mark.parametrize("bad_host", ["", "not a host!", "https://"])
+ def test_invalid_host_short_circuits(self, bad_host):
+ valid, msg = validate_credentials(bad_host, "API-KEY")
+ assert valid is False
+ assert msg == "Invalid Octopus Deploy host"
+
+ def test_request_exception_returns_failure(self):
+ import requests
+
+ with self._patch_session(raises=requests.exceptions.ConnectionError("boom")):
+ valid, msg = validate_credentials("my-org.octopus.app", "API-KEY")
+ assert valid is False
+ assert "boom" in (msg or "")
+
+ def test_rejects_redirect_response(self):
+ # A validated host that 3xx-redirects (potentially to an internal address) must be
+ # rejected, not followed (SSRF).
+ with self._patch_session(_response(status_code=302)) as patched:
+ valid, msg = validate_credentials("my-org.octopus.app", "API-KEY")
+ assert valid is False
+ assert msg == octopus_deploy_module.HOST_NOT_ALLOWED_ERROR
+ assert patched.return_value.get.call_args.kwargs["allow_redirects"] is False
+
+ def test_blocks_unsafe_host(self):
+ # When a team_id is supplied, a host resolving to an internal address is rejected before
+ # any HTTP request is made (SSRF guard).
+ with (
+ mock.patch.object(octopus_deploy_module, "_is_host_safe", return_value=(False, "internal address")),
+ self._patch_session(_response(status_code=200)) as patched,
+ ):
+ valid, msg = validate_credentials("10.0.0.1", "API-KEY", team_id=99)
+ assert valid is False
+ assert msg == "internal address"
+ patched.return_value.get.assert_not_called()
+
+
+class TestOctopusDeploySourceResponse:
+ @pytest.mark.parametrize(
+ "endpoint, primary_keys, partition_key",
+ [
+ ("spaces", ["Id"], None),
+ ("projects", ["SpaceId", "Id"], None),
+ ("releases", ["SpaceId", "Id"], "Assembled"),
+ ("deployments", ["SpaceId", "Id"], "Created"),
+ ("tasks", ["SpaceId", "Id"], "QueueTime"),
+ ("events", ["SpaceId", "Id"], "Occurred"),
+ ],
+ )
+ def test_response_shape(self, endpoint, primary_keys, partition_key):
+ response = octopus_deploy_source(
+ host="my-org.octopus.app",
+ api_key="API-KEY",
+ endpoint=endpoint,
+ logger=mock.MagicMock(),
+ resumable_source_manager=mock.MagicMock(),
+ team_id=1,
+ )
+ assert response.name == endpoint
+ assert response.primary_keys == primary_keys
+ assert response.sort_mode == "desc"
+ if partition_key:
+ assert response.partition_keys == [partition_key]
+ assert response.partition_mode == "datetime"
+ else:
+ assert response.partition_keys is None
+ assert response.partition_mode is None
+
+
+class TestGetRows:
+ def _run(
+ self,
+ manager,
+ responses,
+ endpoint: str = "projects",
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+ ):
+ session = mock.MagicMock()
+ session.get.side_effect = responses
+ with mock.patch.object(octopus_deploy_module, "make_tracked_session", return_value=session):
+ rows: list[dict[str, Any]] = []
+ for batch in get_rows(
+ host="my-org.octopus.app",
+ api_key="API-KEY",
+ endpoint=endpoint,
+ logger=mock.MagicMock(),
+ resumable_source_manager=manager,
+ team_id=1,
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ ):
+ rows.extend(batch)
+ return rows, session
+
+ def _manager(self, resume: Optional[OctopusDeployResumeConfig] = None):
+ manager = mock.MagicMock()
+ manager.can_resume.return_value = resume is not None
+ manager.load_state.return_value = resume
+ return manager
+
+ def _requested_urls(self, session):
+ return [call.args[0] for call in session.get.call_args_list]
+
+ def test_fans_out_over_spaces_and_stamps_space_id(self):
+ manager = self._manager()
+ responses = [
+ # Spaces enumeration returns unsorted ids; fan-out must be deterministic (sorted).
+ _page([{"Id": "Spaces-2"}, {"Id": "Spaces-1"}], has_next=False),
+ _page([{"Id": "Projects-1"}], has_next=False), # Spaces-1
+ _page([{"Id": "Projects-1"}], has_next=False), # Spaces-2
+ ]
+ rows, session = self._run(manager, responses)
+
+ assert [(r["SpaceId"], r["Id"]) for r in rows] == [("Spaces-1", "Projects-1"), ("Spaces-2", "Projects-1")]
+ urls = self._requested_urls(session)
+ assert "/api/spaces" in urls[0]
+ assert "/api/Spaces-1/projects" in urls[1]
+ assert "/api/Spaces-2/projects" in urls[2]
+
+ def test_paginates_with_skip_until_no_next_page(self):
+ manager = self._manager()
+ responses = [
+ _page([{"Id": "Spaces-1"}], has_next=False),
+ _page([{"Id": "Projects-1"}, {"Id": "Projects-2"}], has_next=True),
+ _page([{"Id": "Projects-3"}], has_next=False),
+ ]
+ rows, session = self._run(manager, responses)
+
+ assert [r["Id"] for r in rows] == ["Projects-1", "Projects-2", "Projects-3"]
+ second_page_qs = parse_qs(urlparse(self._requested_urls(session)[2]).query)
+ assert second_page_qs["skip"] == ["2"]
+
+ def test_empty_page_terminates(self):
+ manager = self._manager()
+ responses = [
+ _page([{"Id": "Spaces-1"}], has_next=False),
+ _page([], has_next=False),
+ ]
+ rows, session = self._run(manager, responses)
+ assert rows == []
+ assert session.get.call_count == 2
+
+ # "spaces" exercises the instance-level `_paginate` loop; "projects" (space-scoped) first
+ # exercises the `_get_space_ids` enumeration loop. Both must refuse a host that advertises
+ # `Page.Next` forever rather than looping indefinitely.
+ @pytest.mark.parametrize("endpoint", ["spaces", "projects"])
+ def test_pagination_budget_aborts_runaway_listing(self, endpoint):
+ manager = self._manager()
+ responses = [_page([{"Id": "Spaces-1"}], has_next=True) for _ in range(3)]
+ with mock.patch.object(octopus_deploy_module, "MAX_PAGES_PER_LISTING", 3):
+ with pytest.raises(octopus_deploy_module.OctopusDeployPaginationLimitError):
+ self._run(manager, responses, endpoint=endpoint)
+
+ # The page ceiling only catches a host returning pages *fast*; one that keeps advertising
+ # `Page.Next` while each page burns wall-clock (slow drip / stall before headers) would hold a
+ # worker indefinitely without the time budget. Same two loops as the page-ceiling test.
+ @pytest.mark.parametrize("endpoint", ["spaces", "projects"])
+ def test_pagination_time_budget_aborts_slow_listing(self, endpoint):
+ manager = self._manager()
+ responses = [_page([{"Id": "Spaces-1"}], has_next=True)]
+ with mock.patch.object(octopus_deploy_module, "MAX_LISTING_SECONDS", -1):
+ with pytest.raises(octopus_deploy_module.OctopusDeployPaginationLimitError):
+ self._run(manager, responses, endpoint=endpoint)
+
+ def test_saves_state_after_page_and_between_spaces(self):
+ manager = self._manager()
+ responses = [
+ _page([{"Id": "Spaces-1"}, {"Id": "Spaces-2"}], has_next=False),
+ _page([{"Id": "P-1"}], has_next=True), # Spaces-1 page 1
+ _page([{"Id": "P-2"}], has_next=False), # Spaces-1 page 2
+ _page([{"Id": "P-3"}], has_next=False), # Spaces-2
+ ]
+ self._run(manager, responses)
+
+ saved = [call.args[0] for call in manager.save_state.call_args_list]
+ assert OctopusDeployResumeConfig(skip=1, space_id="Spaces-1") in saved
+ assert OctopusDeployResumeConfig(skip=0, space_id="Spaces-2") in saved
+
+ def test_resumes_from_saved_space_and_skip(self):
+ manager = self._manager(OctopusDeployResumeConfig(skip=200, space_id="Spaces-2"))
+ responses = [
+ _page([{"Id": "Spaces-1"}, {"Id": "Spaces-2"}, {"Id": "Spaces-3"}], has_next=False),
+ _page([{"Id": "P-1"}], has_next=False), # Spaces-2, resumed at skip=200
+ _page([{"Id": "P-2"}], has_next=False), # Spaces-3, fresh at skip=0
+ ]
+ rows, session = self._run(manager, responses)
+
+ urls = self._requested_urls(session)
+ assert "/api/Spaces-2/projects" in urls[1]
+ assert parse_qs(urlparse(urls[1]).query)["skip"] == ["200"]
+ assert "/api/Spaces-3/projects" in urls[2]
+ assert parse_qs(urlparse(urls[2]).query)["skip"] == ["0"]
+ # Spaces-1 was already completed before the crash — not re-fetched.
+ assert not any("/api/Spaces-1/projects" in url for url in urls)
+
+ def test_resume_bookmark_for_deleted_space_starts_over(self):
+ manager = self._manager(OctopusDeployResumeConfig(skip=100, space_id="Spaces-gone"))
+ responses = [
+ _page([{"Id": "Spaces-1"}], has_next=False),
+ _page([{"Id": "P-1"}], has_next=False),
+ ]
+ rows, session = self._run(manager, responses)
+
+ urls = self._requested_urls(session)
+ assert "/api/Spaces-1/projects" in urls[1]
+ assert parse_qs(urlparse(urls[1]).query)["skip"] == ["0"]
+ assert [r["Id"] for r in rows] == ["P-1"]
+
+ def test_instance_level_endpoint_skips_space_fan_out(self):
+ manager = self._manager()
+ responses = [_page([{"Id": "Spaces-1"}, {"Id": "Spaces-2"}], has_next=False)]
+ rows, session = self._run(manager, responses, endpoint="spaces")
+
+ assert session.get.call_count == 1
+ assert [r["Id"] for r in rows] == ["Spaces-1", "Spaces-2"]
+
+ def test_incremental_filter_applied_to_every_page(self):
+ manager = self._manager()
+ responses = [
+ _page([{"Id": "Spaces-1"}], has_next=False),
+ _page([{"Id": "T-1"}], has_next=True),
+ _page([{"Id": "T-2"}], has_next=False),
+ ]
+ _rows, session = self._run(
+ manager,
+ responses,
+ endpoint="tasks",
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2024, 1, 1, tzinfo=UTC),
+ )
+
+ for url in self._requested_urls(session)[1:]:
+ assert parse_qs(urlparse(url).query)["fromCompletedDate"] == ["2024-01-01T00:00:00+00:00"]
+
+ def test_redirect_response_raises(self):
+ # Requests are made with allow_redirects=False, and a redirect response is rejected rather
+ # than followed to a (potentially internal) Location (SSRF).
+ manager = self._manager()
+ with pytest.raises(octopus_deploy_module.OctopusDeployHostNotAllowedError):
+ self._run(manager, [_response(status_code=302)])
+
+ def test_unsafe_host_raises_before_any_request(self):
+ manager = self._manager()
+ session = mock.MagicMock()
+ with (
+ mock.patch.object(octopus_deploy_module, "_is_host_safe", return_value=(False, "internal address")),
+ mock.patch.object(octopus_deploy_module, "make_tracked_session", return_value=session),
+ ):
+ with pytest.raises(octopus_deploy_module.OctopusDeployHostNotAllowedError):
+ list(
+ get_rows(
+ host="10.0.0.1",
+ api_key="API-KEY",
+ endpoint="projects",
+ logger=mock.MagicMock(),
+ resumable_source_manager=manager,
+ team_id=1,
+ )
+ )
+ session.get.assert_not_called()
+
+
+class TestReadCappedBody:
+ def _streamed(self, chunks: list[bytes]) -> mock.MagicMock:
+ response = mock.MagicMock()
+ response.iter_content.return_value = chunks
+ return response
+
+ def test_reads_full_body_and_closes(self):
+ response = self._streamed([b'{"ok"', b": true}"])
+ assert octopus_deploy_module._read_capped_body(response) == b'{"ok": true}'
+ response.close.assert_called_once()
+
+ def test_rejects_oversized_body(self):
+ # A customer-controlled host that streams past the cap must be refused before it exhausts
+ # the worker's memory, not buffered whole.
+ response = self._streamed([b"x" * 10, b"x" * 10])
+ with mock.patch.object(octopus_deploy_module, "MAX_RESPONSE_BYTES", 15):
+ with pytest.raises(octopus_deploy_module.OctopusDeployResponseTooLargeError):
+ octopus_deploy_module._read_capped_body(response)
+ response.close.assert_called_once()
+
+ def test_rejects_slow_download(self):
+ # A host dribbling the body under the per-read timeout must hit the wall-clock deadline
+ # rather than holding the connection (and worker) open indefinitely.
+ response = self._streamed([b"x"])
+ with mock.patch.object(octopus_deploy_module, "MAX_DOWNLOAD_SECONDS", -1):
+ with pytest.raises(octopus_deploy_module.OctopusDeployResponseTooSlowError):
+ octopus_deploy_module._read_capped_body(response)
+ response.close.assert_called_once()
+
+
+class TestFetchPageErrorLogging:
+ def test_error_body_is_truncated_in_log(self):
+ # A customer-controlled host can return a large-but-under-cap 4xx body; the log line must
+ # carry only a bounded preview plus the byte count, never the whole body.
+ import requests
+
+ body = b"x" * (octopus_deploy_module.LOG_BODY_PREVIEW_BYTES * 4)
+ response = mock.MagicMock()
+ response.status_code = 400
+ response.ok = False
+ response.is_redirect = False
+ response.is_permanent_redirect = False
+ response.iter_content.return_value = [body]
+ response.raise_for_status.side_effect = requests.HTTPError("bad request", response=response)
+
+ session = mock.MagicMock()
+ session.get.return_value = response
+ logger = mock.MagicMock()
+
+ with pytest.raises(requests.HTTPError):
+ octopus_deploy_module._fetch_page(session, "https://my-org.octopus.app/api/spaces", {}, logger)
+
+ logged = logger.error.call_args.args[0]
+ assert f"body_bytes={len(body)}" in logged
+ assert logged.count("x") <= octopus_deploy_module.LOG_BODY_PREVIEW_BYTES
+
+
+class TestRetryAfter:
+ @pytest.mark.parametrize(
+ "headers, expected",
+ [
+ ({"Retry-After": "5"}, 5.0),
+ ({"Retry-After": "100000"}, 60.0), # capped
+ ({"Retry-After": "Wed, 21 Oct 2026 07:28:00 GMT"}, None), # HTTP-date ignored
+ ({}, None),
+ ],
+ )
+ def test_parse_retry_after(self, headers, expected):
+ response = mock.MagicMock()
+ response.headers = headers
+ assert _parse_retry_after(response) == expected
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/octopus_deploy/tests/test_octopus_deploy_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/octopus_deploy/tests/test_octopus_deploy_source.py
new file mode 100644
index 000000000000..9d10988e2aed
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/octopus_deploy/tests/test_octopus_deploy_source.py
@@ -0,0 +1,142 @@
+import pytest
+from unittest import mock
+
+from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import OctopusDeploySourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.octopus_deploy.octopus_deploy import (
+ OctopusDeployResumeConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.octopus_deploy.settings import ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.octopus_deploy.source import OctopusDeploySource
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+class TestOctopusDeploySource:
+ def setup_method(self):
+ self.source = OctopusDeploySource()
+ self.team_id = 123
+ self.config = OctopusDeploySourceConfig(host="https://my-org.octopus.app", api_key="API-KEY")
+
+ def test_source_type(self):
+ assert self.source.source_type == ExternalDataSourceType.OCTOPUSDEPLOY
+
+ def test_get_source_config(self):
+ config = self.source.get_source_config
+
+ assert config.name.value == "OctopusDeploy"
+ assert config.label == "Octopus Deploy"
+ assert config.unreleasedSource is None
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.iconPath == "/static/services/octopus_deploy.png"
+
+ field_names = [f.name for f in config.fields]
+ assert field_names == ["host", "api_key"]
+
+ host_field, key_field = config.fields
+ assert isinstance(host_field, SourceFieldInputConfig)
+ assert host_field.type == SourceFieldInputConfigType.TEXT
+ assert host_field.secret is False
+
+ assert isinstance(key_field, SourceFieldInputConfig)
+ assert key_field.type == SourceFieldInputConfigType.PASSWORD
+ assert key_field.secret is True
+ assert key_field.required is True
+
+ def test_connection_host_fields_force_key_reentry_on_host_change(self):
+ # Changing host retargets the stored API key, so it must count as a host field and force
+ # the editor to re-enter the key rather than silently redirecting it to a new server.
+ assert self.source.connection_host_fields == ["host"]
+
+ @pytest.mark.parametrize("expected_key", ["401 Client Error", "403 Client Error"])
+ def test_non_retryable_errors(self, expected_key):
+ assert expected_key in self.source.get_non_retryable_errors()
+
+ def test_get_schemas_returns_all_endpoints(self):
+ schemas = self.source.get_schemas(self.config, self.team_id)
+ assert {s.name for s in schemas} == set(ENDPOINTS)
+
+ @pytest.mark.parametrize(
+ "endpoint, incremental",
+ [
+ ("spaces", False),
+ ("projects", False),
+ ("releases", False),
+ ("deployments", False),
+ ("tasks", True),
+ ("events", True),
+ ],
+ )
+ def test_schema_incremental_support(self, endpoint, incremental):
+ schemas = {s.name: s for s in self.source.get_schemas(self.config, self.team_id)}
+ assert schemas[endpoint].supports_incremental is incremental
+ assert schemas[endpoint].supports_append is incremental
+
+ def test_get_schemas_filtered_by_names(self):
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["deployments"])
+ assert len(schemas) == 1
+ assert schemas[0].name == "deployments"
+
+ def test_get_schemas_unknown_name_returns_empty(self):
+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []
+
+ @pytest.mark.parametrize(
+ "mock_return",
+ [
+ (True, None),
+ (False, "Invalid Octopus Deploy API key"),
+ ],
+ )
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.octopus_deploy.source.validate_octopus_deploy_credentials"
+ )
+ def test_validate_credentials(self, mock_validate, mock_return):
+ mock_validate.return_value = mock_return
+
+ result = self.source.validate_credentials(self.config, self.team_id, schema_name="deployments")
+
+ assert result == mock_return
+ mock_validate.assert_called_once_with(self.config.host, self.config.api_key, "deployments", self.team_id)
+
+ def test_get_resumable_source_manager(self):
+ inputs = mock.MagicMock()
+ manager = self.source.get_resumable_source_manager(inputs)
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is OctopusDeployResumeConfig
+
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.octopus_deploy.source.octopus_deploy_source"
+ )
+ def test_source_for_pipeline_plumbs_arguments(self, mock_source):
+ inputs = mock.MagicMock()
+ inputs.schema_name = "tasks"
+ inputs.team_id = 42
+ inputs.should_use_incremental_field = True
+ inputs.db_incremental_field_last_value = "2024-01-01T00:00:00+00:00"
+ manager = mock.MagicMock()
+
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ mock_source.assert_called_once()
+ kwargs = mock_source.call_args.kwargs
+ assert kwargs["host"] == "https://my-org.octopus.app"
+ assert kwargs["api_key"] == "API-KEY"
+ assert kwargs["endpoint"] == "tasks"
+ assert kwargs["resumable_source_manager"] is manager
+ assert kwargs["team_id"] == 42
+ assert kwargs["should_use_incremental_field"] is True
+ assert kwargs["db_incremental_field_last_value"] == "2024-01-01T00:00:00+00:00"
+
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.octopus_deploy.source.octopus_deploy_source"
+ )
+ def test_source_for_pipeline_omits_last_value_when_not_incremental(self, mock_source):
+ inputs = mock.MagicMock()
+ inputs.schema_name = "deployments"
+ inputs.should_use_incremental_field = False
+ inputs.db_incremental_field_last_value = "ignored"
+
+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)
+
+ assert mock_source.call_args.kwargs["db_incremental_field_last_value"] is None