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 sonatype_nexus import source (#71167)

Tom Owers0a1eb8ec99ca
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 2f79d505e387..890dc2603d0b 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -485,6 +485,7 @@ the row lists both.
| solarwinds_service_desk | HTTP | requests | ✅ |
| sonar_cloud | HTTP | requests | ✅ |
| sonarqube | HTTP | requests | ✅ |
+| sonatype_nexus | HTTP | requests | ✅ |
| spacelift | HTTP (GraphQL) | requests | ✅ |
| sparkpost | HTTP | requests | ✅ |
| split_io | HTTP | requests | ✅ |
@@ -925,6 +926,7 @@ doesn't conflict with concurrent PRs.
- smartengage
- smartwaiver
- solarwinds_service_desk
+- sonar_cloud
- sonatype_nexus
- sourcegraph
- spacelift
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 6efeffc34db8..6164f803ad63 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
@@ -4091,7 +4091,9 @@ class SonarqubeSourceConfig(config.Config):
@config.config
class SonatypeNexusSourceConfig(config.Config):
- pass
+ host: str
+ username: str
+ password: str
@config.config
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sonatype_nexus/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sonatype_nexus/canonical_descriptions.py
new file mode 100644
index 000000000000..5d67768d3845
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sonatype_nexus/canonical_descriptions.py
@@ -0,0 +1,64 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "repositories": {
+ "description": "A repository configured on the Nexus instance — hosted, proxy, or group — for a package format such as Maven, npm, Docker, or PyPI.",
+ "docs_url": "https://help.sonatype.com/en/repositories-api.html",
+ "columns": {
+ "name": "Unique name of the repository on the instance.",
+ "format": "Package format the repository serves (e.g. maven2, npm, docker, pypi, nuget).",
+ "type": "Repository type: hosted (stores uploads), proxy (caches a remote), or group (aggregates other repositories).",
+ "url": "Base URL clients use to access the repository's content.",
+ "attributes": "Format- and type-specific settings, such as a proxy repository's remote URL.",
+ },
+ },
+ "components": {
+ "description": "A versioned package (e.g. a Maven artifact, npm package, or Docker image) stored in a hosted or proxy repository. Group repositories are excluded to avoid double-counting their members' components.",
+ "docs_url": "https://help.sonatype.com/en/components-api.html",
+ "columns": {
+ "id": "Opaque identifier of the component within the instance.",
+ "repository": "Name of the repository the component lives in.",
+ "format": "Package format of the component (e.g. maven2, npm, docker, pypi).",
+ "group": "Component namespace, such as a Maven groupId. Null for formats without one.",
+ "name": "Component name, such as a Maven artifactId or npm package name.",
+ "version": "Component version.",
+ "assets": "The component's files, each with path, download URL, checksums, and size.",
+ "tags": "Tags applied to the component (Nexus Repository Pro).",
+ },
+ },
+ "assets": {
+ "description": "An individual file stored in a hosted or proxy repository, such as a .jar, .tgz, or Docker layer, with its checksums, size, and download metadata. Group repositories are excluded to avoid double-counting their members' assets.",
+ "docs_url": "https://help.sonatype.com/en/assets-api.html",
+ "columns": {
+ "id": "Opaque identifier of the asset within the instance.",
+ "repository": "Name of the repository the asset lives in.",
+ "format": "Package format of the asset (e.g. maven2, npm, docker, pypi).",
+ "path": "Path of the asset within the repository.",
+ "downloadUrl": "URL to download the asset's content.",
+ "contentType": "MIME type of the asset's content.",
+ "fileSize": "Size of the asset in bytes.",
+ "checksum": "Checksums of the asset's content (md5, sha1, sha256, sha512 where available).",
+ "blobCreated": "When the asset's blob was created. Can be null for blobs created before the instance recorded it.",
+ "lastModified": "When the asset was last modified.",
+ "lastDownloaded": "When the asset was last downloaded by a client.",
+ "uploader": "Username that uploaded the asset.",
+ "uploaderIp": "IP address the asset was uploaded from.",
+ },
+ },
+ "tasks": {
+ "description": "A scheduled or manually triggered maintenance task on the Nexus instance, such as blob store compaction or repository cleanup, with its schedule and last run state.",
+ "docs_url": "https://help.sonatype.com/en/tasks-api.html",
+ "columns": {
+ "id": "Unique identifier of the task.",
+ "name": "Display name of the task.",
+ "type": "Task type identifier (e.g. blobstore.compact, repository.cleanup).",
+ "message": "Status message from the task's most recent activity.",
+ "currentState": "Current state of the task (e.g. WAITING, RUNNING).",
+ "lastRunResult": "Result of the task's last run (e.g. OK, FAILED).",
+ "nextRun": "When the task is next scheduled to run.",
+ "lastRun": "When the task last ran.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sonatype_nexus/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sonatype_nexus/settings.py
new file mode 100644
index 000000000000..8f73b5cb6384
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sonatype_nexus/settings.py
@@ -0,0 +1,51 @@
+from dataclasses import dataclass, field
+
+# Nexus Repository's REST API is served per-instance under this base path.
+NEXUS_API_PATH = "/service/rest/v1"
+
+
+@dataclass
+class SonatypeNexusEndpointConfig:
+ name: str
+ path: str
+ primary_keys: list[str] = field(default_factory=lambda: ["id"])
+ # Components and assets must be queried one repository at a time
+ # (?repository=<name>), so these endpoints fan out over /repositories.
+ per_repository: bool = False
+ # Whether the endpoint returns the {items, continuationToken} envelope.
+ # /repositories returns a plain JSON array with no pagination.
+ paginated: bool = True
+
+
+# The REST API exposes no server-side timestamp filter, so every table is full
+# refresh only. No datetime partitioning either: repositories, tasks, and
+# components carry no timestamp at all, and assets' `blobCreated` can be null
+# for blobs created before the instance was upgraded to a version that records it.
+SONATYPE_NEXUS_ENDPOINTS: dict[str, SonatypeNexusEndpointConfig] = {
+ "repositories": SonatypeNexusEndpointConfig(
+ name="repositories",
+ path="/repositories",
+ primary_keys=["name"],
+ paginated=False,
+ ),
+ # Component/asset ids are opaque identifiers; uniqueness across repositories
+ # isn't documented, so the repository is part of the key.
+ "components": SonatypeNexusEndpointConfig(
+ name="components",
+ path="/components",
+ primary_keys=["repository", "id"],
+ per_repository=True,
+ ),
+ "assets": SonatypeNexusEndpointConfig(
+ name="assets",
+ path="/assets",
+ primary_keys=["repository", "id"],
+ per_repository=True,
+ ),
+ "tasks": SonatypeNexusEndpointConfig(
+ name="tasks",
+ path="/tasks",
+ ),
+}
+
+ENDPOINTS = tuple(SONATYPE_NEXUS_ENDPOINTS.keys())
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sonatype_nexus/sonatype_nexus.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sonatype_nexus/sonatype_nexus.py
new file mode 100644
index 000000000000..3c199540429c
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sonatype_nexus/sonatype_nexus.py
@@ -0,0 +1,403 @@
+import json
+import time
+import dataclasses
+from collections.abc import Iterator
+from typing import Any, Optional
+from urllib.parse import urlencode, urlparse
+
+import requests
+from structlog.types import FilteringBoundLogger
+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+
+from posthog.cloud_utils import is_cloud
+
+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.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.sonatype_nexus.settings import (
+ NEXUS_API_PATH,
+ SONATYPE_NEXUS_ENDPOINTS,
+)
+
+REQUEST_TIMEOUT_SECONDS = 60
+MAX_RETRY_ATTEMPTS = 5
+
+# The host is customer-controlled, so response bodies are streamed and read under a byte cap —
+# an arbitrarily large (or endless) 200 body must fail the sync instead of exhausting worker
+# memory. The cap applies to decoded bytes, so a gzip bomb can't slip past it.
+MAX_RESPONSE_BYTES = 512 * 1024 * 1024
+_READ_CHUNK_BYTES = 1024 * 1024
+# The per-read timeout only bounds the gap between chunks, so a server can trickle one byte just
+# before each read timeout and keep a worker occupied indefinitely. A monotonic total-transfer
+# deadline caps how long a single body read may take end to end, independent of byte pacing.
+MAX_RESPONSE_SECONDS = 600
+# Bytes read from an error body for a diagnostic message — never needed in full.
+_ERROR_SNIPPET_BYTES = 2048
+# A misbehaving (or malicious) instance can hand out continuation tokens forever, keeping the
+# worker paginating until the activity timeout on every retry. Cap the pages fetched per endpoint
+# (per repository for the fan-out endpoints) so runaway pagination fails the sync loudly instead.
+MAX_PAGES_PER_ENDPOINT = 1_000_000
+# The per-page transfer deadline resets each page, so a host that returns a valid tiny page with a
+# fresh token just before each deadline can still occupy a worker for pages * MAX_RESPONSE_SECONDS
+# — up to the one-week activity timeout. A cumulative wall-clock deadline set once per pagination
+# walk (covering every repository in the fan-out case) bounds total worker occupancy independent of
+# how many small pages the host drips out.
+MAX_PAGINATION_SECONDS = 6 * 60 * 60
+
+RESPONSE_TOO_LARGE_ERROR = "Nexus API response exceeded the size limit"
+RESPONSE_TIMEOUT_ERROR = "Nexus API response exceeded the download time limit"
+
+
+class SonatypeNexusRetryableError(Exception):
+ pass
+
+
+class SonatypeNexusResponseTooLargeError(Exception):
+ pass
+
+
+class SonatypeNexusResponseTimeoutError(Exception):
+ pass
+
+
+class SonatypeNexusPaginationError(Exception):
+ pass
+
+
+def _read_bounded(response: requests.Response, max_bytes: int, max_seconds: float = MAX_RESPONSE_SECONDS) -> bytes:
+ """Read a streamed response body under both a byte cap and a total-transfer deadline.
+
+ The deadline covers time spent waiting for each chunk, so a slow-drip body that stays under
+ the per-read timeout but never finishes is aborted instead of holding the worker.
+ """
+ total = 0
+ chunks: list[bytes] = []
+ deadline = time.monotonic() + max_seconds
+ for chunk in response.iter_content(chunk_size=_READ_CHUNK_BYTES):
+ total += len(chunk)
+ if total > max_bytes:
+ raise SonatypeNexusResponseTooLargeError(f"{RESPONSE_TOO_LARGE_ERROR} ({max_bytes} bytes)")
+ if time.monotonic() > deadline:
+ raise SonatypeNexusResponseTimeoutError(f"{RESPONSE_TIMEOUT_ERROR} ({max_seconds:g}s)")
+ chunks.append(chunk)
+ return b"".join(chunks)
+
+
+def _error_snippet(response: requests.Response) -> str:
+ try:
+ chunk = next(response.iter_content(chunk_size=_ERROR_SNIPPET_BYTES), b"")
+ return chunk[:_ERROR_SNIPPET_BYTES].decode("utf-8", errors="replace")
+ except Exception:
+ return ""
+
+
+class SonatypeNexusResumeConfig:
+ # The `continuationToken` to fetch the next page. None means "start from the
+ # first page" — used both on a fresh sync and when the bookmark advances to a
+ # repository whose first page has no token yet.
+ continuation_token: Optional[str] = None
+ # For per-repository endpoints (components/assets): the repository currently
+ # being processed. A stable name bookmark (not a positional index) so
+ # repositories added/removed between a crash and the retry can't resume us
+ # into the wrong one. None for the top-level endpoints.
+ repository: Optional[str] = None
+
+
+def normalize_host(host: str) -> str:
+ """Normalize the instance URL and reject anything that isn't plain http(s).
+
+ Accepts either a bare host (`nexus.example.com`) or a full URL, with or
+ without the `/service/rest[/v1]` suffix, and returns the instance origin
+ (no trailing slash).
+ """
+ host = host.strip()
+ if not host:
+ raise ValueError("Nexus host is required")
+ if "://" not in host:
+ host = f"https://{host}"
+ host = host.rstrip("/")
+ # Tolerate a pasted API base URL by trimming the REST path suffix.
+ for suffix in (NEXUS_API_PATH, "/service/rest"):
+ if host.endswith(suffix):
+ host = host[: -len(suffix)]
+ break
+ parsed = urlparse(host)
+ if parsed.scheme not in ("http", "https") or not parsed.hostname:
+ raise ValueError(f"Invalid Nexus host: {host}")
+ # Credentials ride in the Authorization header on every request, so plaintext
+ # http would leak them to any network observer. On PostHog Cloud the request
+ # egresses over the public internet, so require https. Self-hosted operators
+ # control their own network path (e.g. an internal Nexus reachable only over
+ # http), so http stays allowed there — mirroring how host IP safety is only
+ # enforced on cloud.
+ if parsed.scheme == "http" and is_cloud():
+ raise ValueError("Nexus instance URL must use https")
+ # SSRF guard: urlparse treats a backslash as userinfo and an "@" as a userinfo
+ # separator, but urllib3/requests treat the backslash as an authority separator, so
+ # `http://127.0.0.1\@example.com` validates as example.com yet connects to 127.0.0.1.
+ # A legitimate instance URL has no userinfo, so reject either construct outright.
+ if "\\" in host or "%5c" in host.lower() or "@" in parsed.netloc:
+ raise ValueError(f"Invalid Nexus host: {host}")
+ return host
+
+
+def hostname_of(host: str) -> str:
+ return urlparse(normalize_host(host)).hostname or ""
+
+
+def _base_url(host: str) -> str:
+ return f"{normalize_host(host)}{NEXUS_API_PATH}"
+
+
+def _get_session(username: str, password: str) -> requests.Session:
+ # `host` is user-supplied, so pin redirects off so validation and the outbound
+ # request stay on the same target (SSRF defense-in-depth). Redact the password
+ # from logs.
+ session = make_tracked_session(redact_values=(password,), allow_redirects=False)
+ session.auth = (username, password)
+ return session
+
+
+def _build_url(base_url: str, params: dict[str, Any]) -> str:
+ if not params:
+ return base_url
+ return f"{base_url}?{urlencode(params)}"
+
+
+@retry(
+ retry=retry_if_exception_type(
+ (
+ SonatypeNexusRetryableError,
+ requests.ReadTimeout,
+ requests.ConnectionError,
+ requests.exceptions.ChunkedEncodingError,
+ )
+ ),
+ stop=stop_after_attempt(MAX_RETRY_ATTEMPTS),
+ wait=wait_exponential_jitter(initial=1, max=30),
+ reraise=True,
+)
+def _fetch_page(session: requests.Session, url: str, logger: FilteringBoundLogger) -> dict[str, Any]:
+ # `stream=True` so the body is only pulled into memory through `_read_bounded` /
+ # `_error_snippet` under a byte cap — a huge or endless 200 body from a customer-controlled
+ # host fails the sync instead of exhausting the worker.
+ with session.get(url, timeout=REQUEST_TIMEOUT_SECONDS, stream=True) as response:
+ if response.status_code == 429 or response.status_code >= 500:
+ raise SonatypeNexusRetryableError(f"Nexus API error (retryable): status={response.status_code}, url={url}")
+
+ if not response.ok:
+ logger.error(f"Nexus API error: status={response.status_code}, body={_error_snippet(response)}, url={url}")
+ response.raise_for_status()
+
+ body = json.loads(_read_bounded(response, MAX_RESPONSE_BYTES))
+ # /repositories returns a plain JSON array; wrap it into the paginated
+ # endpoints' {items, continuationToken} envelope for uniform handling.
+ return body if isinstance(body, dict) else {"items": body}
+
+
+def validate_credentials(host: str, username: str, password: str) -> bool:
+ """Confirm the instance is reachable and the credentials are accepted.
+
+ Probes /repositories — the cheapest endpoint available to any user with
+ read access (it only lists repositories the user can browse).
+ """
+ try:
+ url = f"{_base_url(host)}/repositories"
+ # `stream=True` and a `with` block so only the status code is read and the connection is
+ # closed immediately — the probe never needs the body, so a huge response from a
+ # misbehaving host can't buffer into memory on the inline API worker.
+ with _get_session(username, password).get(url, timeout=15, stream=True) as response:
+ return response.status_code == 200
+ except Exception:
+ return False
+
+
+def _list_content_repositories(session: requests.Session, base_url: str, logger: FilteringBoundLogger) -> list[str]:
+ """Names of the repositories to fan out over, sorted for a deterministic resume walk.
+
+ Group repositories return the union of their members' components/assets
+ (verified against a live instance), which would double-count rows already
+ synced from the member repositories — so only hosted and proxy repositories
+ are included.
+ """
+ data = _fetch_page(session, f"{base_url}/repositories", logger)
+ return sorted(repo["name"] for repo in data["items"] if repo.get("type") != "group")
+
+
+def _get_repository_fanout_rows(
+ session: requests.Session,
+ base_url: str,
+ endpoint_url: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[SonatypeNexusResumeConfig],
+) -> Iterator[list[dict[str, Any]]]:
+ repositories = _list_content_repositories(session, base_url, logger)
+
+ # Cumulative deadline across every repository in this fan-out, so a host with many
+ # repositories can't multiply the budget by returning small pages forever in each.
+ pagination_deadline = time.monotonic() + MAX_PAGINATION_SECONDS
+
+ # Resolve the saved repository bookmark to the slice still to process. If the
+ # bookmarked repository no longer exists (deleted between runs), start over
+ # from the first one — re-yielded rows are harmless on a full refresh.
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ remaining = repositories
+ resume_token: Optional[str] = None
+ if resume is not None and resume.repository is not None and resume.repository in repositories:
+ remaining = repositories[repositories.index(resume.repository) :]
+ resume_token = resume.continuation_token
+ logger.debug(f"Sonatype Nexus: resuming from repository={resume.repository}")
+
+ for index, repository in enumerate(remaining):
+ token = resume_token
+ resume_token = None # only the resumed-into repository uses the saved token
+
+ try:
+ page_count = 0
+ while True:
+ params: dict[str, Any] = {"repository": repository}
+ if token:
+ params["continuationToken"] = token
+
+ data = _fetch_page(session, _build_url(endpoint_url, params), logger)
+ items = data["items"]
+ next_token = data.get("continuationToken")
+ page_count += 1
+
+ # Check the cumulative deadline immediately after every response, before the
+ # terminal-page break — otherwise a host that enumerates many repositories and
+ # slow-drips each one's single terminal page to just under the per-response budget
+ # would bypass the check and hold the worker for repositories × MAX_RESPONSE_SECONDS.
+ if time.monotonic() > pagination_deadline:
+ raise SonatypeNexusPaginationError(
+ f"Nexus pagination exceeded the {MAX_PAGINATION_SECONDS:g}s time budget for repository={repository}"
+ )
+
+ if items:
+ yield items
+
+ # Save AFTER yielding so a crash re-yields the in-flight page rather than
+ # skipping it. Save whenever a token exists, even for an empty page, so a
+ # crash resumes from the page's actual progression instead of an older token.
+ if next_token:
+ resumable_source_manager.save_state(
+ SonatypeNexusResumeConfig(continuation_token=next_token, repository=repository)
+ )
+
+ if not next_token:
+ break
+ # A token that doesn't advance (or a runaway stream of fresh ones) would loop until
+ # the activity timeout on every retry — reject both so it fails the sync instead.
+ if next_token == token:
+ raise SonatypeNexusPaginationError(
+ f"Nexus returned a non-advancing continuation token for repository={repository}"
+ )
+ if page_count >= MAX_PAGES_PER_ENDPOINT:
+ raise SonatypeNexusPaginationError(
+ f"Nexus pagination exceeded {MAX_PAGES_PER_ENDPOINT} pages for repository={repository}"
+ )
+ token = next_token
+ except requests.HTTPError as exc:
+ # A repository deleted between enumeration and this fetch 404s. Skip it
+ # rather than failing the whole sync — its content is genuinely gone.
+ if exc.response is not None and exc.response.status_code == 404:
+ logger.warning(f"Sonatype Nexus: repository {repository} not found while fetching, skipping")
+ else:
+ raise
+
+ # Advance the bookmark to the next repository so a crash between
+ # repositories resumes correctly.
+ if index + 1 < len(remaining):
+ resumable_source_manager.save_state(
+ SonatypeNexusResumeConfig(continuation_token=None, repository=remaining[index + 1])
+ )
+
+
+def get_rows(
+ host: str,
+ username: str,
+ password: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[SonatypeNexusResumeConfig],
+) -> Iterator[list[dict[str, Any]]]:
+ config = SONATYPE_NEXUS_ENDPOINTS[endpoint]
+ session = _get_session(username, password)
+ base_url = _base_url(host)
+ endpoint_url = f"{base_url}{config.path}"
+
+ if config.per_repository:
+ yield from _get_repository_fanout_rows(session, base_url, endpoint_url, logger, resumable_source_manager)
+ return
+
+ if not config.paginated:
+ data = _fetch_page(session, endpoint_url, logger)
+ items = data["items"]
+ if items:
+ yield items
+ return
+
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ token: Optional[str] = resume.continuation_token if resume is not None else None
+ if token:
+ logger.debug(f"Sonatype Nexus: resuming {endpoint} from continuation token")
+
+ page_count = 0
+ pagination_deadline = time.monotonic() + MAX_PAGINATION_SECONDS
+ while True:
+ params: dict[str, Any] = {"continuationToken": token} if token else {}
+ data = _fetch_page(session, _build_url(endpoint_url, params), logger)
+
+ # `items` is the required envelope field; fail fast if a 200 response ever omits it.
+ items = data["items"]
+ next_token = data.get("continuationToken")
+ page_count += 1
+
+ if items:
+ yield items
+
+ if not next_token:
+ break
+
+ # A token that doesn't advance (or a runaway stream of fresh ones) would loop until the
+ # activity timeout on every retry — reject both so it fails the sync instead.
+ if next_token == token:
+ raise SonatypeNexusPaginationError(f"Nexus returned a non-advancing continuation token for {endpoint}")
+ if page_count >= MAX_PAGES_PER_ENDPOINT:
+ raise SonatypeNexusPaginationError(
+ f"Nexus pagination exceeded {MAX_PAGES_PER_ENDPOINT} pages for {endpoint}"
+ )
+ if time.monotonic() > pagination_deadline:
+ raise SonatypeNexusPaginationError(
+ f"Nexus pagination exceeded the {MAX_PAGINATION_SECONDS:g}s time budget for {endpoint}"
+ )
+
+ token = next_token
+ # Save state AFTER yielding so a crash re-yields the in-flight page rather
+ # than skipping it.
+ resumable_source_manager.save_state(SonatypeNexusResumeConfig(continuation_token=token))
+
+
+def sonatype_nexus_source(
+ host: str,
+ username: str,
+ password: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[SonatypeNexusResumeConfig],
+) -> SourceResponse:
+ config = SONATYPE_NEXUS_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ host=host,
+ username=username,
+ password=password,
+ endpoint=endpoint,
+ logger=logger,
+ resumable_source_manager=resumable_source_manager,
+ ),
+ primary_keys=list(config.primary_keys),
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sonatype_nexus/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sonatype_nexus/source.py
index ebc4d27433b5..4525a9065116 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/sonatype_nexus/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sonatype_nexus/source.py
@@ -1,30 +1,177 @@
-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.mixins import ValidateDatabaseHostMixin
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 SonatypeNexusSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.sonatype_nexus.settings import (
+ ENDPOINTS,
+ SONATYPE_NEXUS_ENDPOINTS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.sonatype_nexus.sonatype_nexus import (
+ SonatypeNexusResumeConfig,
+ hostname_of,
+ sonatype_nexus_source,
+ validate_credentials as validate_sonatype_nexus_credentials,
+)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class SonatypeNexusSource(SimpleSource[SonatypeNexusSourceConfig]):
+class SonatypeNexusSource(
+ ResumableSource[SonatypeNexusSourceConfig, SonatypeNexusResumeConfig], ValidateDatabaseHostMixin
+):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.SONATYPENEXUS
+ @property
+ def connection_host_fields(self) -> list[str]:
+ # `host` determines where the stored credentials are sent, so retargeting it
+ # must re-require them.
+ return ["host"]
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=SchemaExternalDataSourceType.SONATYPE_NEXUS,
category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,
label="Sonatype (Nexus Repository)",
+ caption="""Connect your Sonatype Nexus Repository instance to pull your artifact inventory into the PostHog Data warehouse.
+
+Enter your instance URL (e.g. `https://nexus.example.com`) and the username and password of a user with read access to the repositories you want to sync. A [user token](https://help.sonatype.com/en/user-tokens.html) also works: use the token name code as the username and the pass code as the password.
+
+The tasks table additionally requires the `nx-tasks-read` privilege; deselect it if your user doesn't have it.""",
iconPath="/static/services/sonatype_nexus.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/sonatype-nexus",
+ releaseStatus=ReleaseStatus.ALPHA,
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="host",
+ label="Instance URL",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="https://nexus.example.com",
+ secret=False,
+ ),
+ SourceFieldInputConfig(
+ name="username",
+ label="Username",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="",
+ secret=False,
+ ),
+ SourceFieldInputConfig(
+ name="password",
+ label="Password",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
+ )
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.sonatype_nexus.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error: Unauthorized for url": "Your Nexus credentials are invalid or have been revoked. Check the username and password (or user token) and reconnect.",
+ "403 Client Error: Forbidden for url": "Your Nexus user does not have access to this resource. The tasks table requires the nx-tasks-read privilege, and repository content requires browse/read access — deselect the affected tables or use a user with the required privileges.",
+ }
+
+ def get_schemas(
+ self,
+ config: SonatypeNexusSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ # The Nexus REST API exposes no server-side timestamp filter, so every
+ # table is full refresh only.
+ schemas = [
+ SourceSchema(
+ name=endpoint,
+ supports_incremental=False,
+ supports_append=False,
+ incremental_fields=[],
+ detected_primary_keys=list(SONATYPE_NEXUS_ENDPOINTS[endpoint].primary_keys),
+ )
+ 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: SonatypeNexusSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ try:
+ host_valid, host_error = self.is_database_host_valid(hostname_of(config.host), team_id)
+ except ValueError:
+ return False, "Invalid Nexus instance URL"
+ if not host_valid:
+ return False, host_error
+
+ if validate_sonatype_nexus_credentials(config.host, config.username, config.password):
+ return True, None
+
+ return False, "Invalid Nexus credentials. Check the instance URL, username, and password."
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[SonatypeNexusResumeConfig]:
+ return ResumableSourceManager[SonatypeNexusResumeConfig](inputs, SonatypeNexusResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: SonatypeNexusSourceConfig,
+ resumable_source_manager: ResumableSourceManager[SonatypeNexusResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ try:
+ host_valid, host_error = self.is_database_host_valid(hostname_of(config.host), inputs.team_id)
+ except ValueError:
+ raise ValueError("Invalid Nexus instance URL")
+ if not host_valid:
+ raise ValueError(host_error or "Invalid Nexus host")
+
+ return sonatype_nexus_source(
+ host=config.host,
+ username=config.username,
+ password=config.password,
+ endpoint=inputs.schema_name,
+ logger=inputs.logger,
+ resumable_source_manager=resumable_source_manager,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sonatype_nexus/tests/test_sonatype_nexus.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sonatype_nexus/tests/test_sonatype_nexus.py
new file mode 100644
index 000000000000..21acc2f14699
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sonatype_nexus/tests/test_sonatype_nexus.py
@@ -0,0 +1,457 @@
+import json
+from typing import Any
+
+import pytest
+from unittest import mock
+
+import requests
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.sonatype_nexus.settings import (
+ ENDPOINTS,
+ SONATYPE_NEXUS_ENDPOINTS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.sonatype_nexus.sonatype_nexus import (
+ SonatypeNexusPaginationError,
+ SonatypeNexusResponseTimeoutError,
+ SonatypeNexusResponseTooLargeError,
+ SonatypeNexusResumeConfig,
+ SonatypeNexusRetryableError,
+ _build_url,
+ _fetch_page,
+ _read_bounded,
+ get_rows,
+ hostname_of,
+ normalize_host,
+ sonatype_nexus_source,
+ validate_credentials,
+)
+
+_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.sonatype_nexus.sonatype_nexus"
+
+# `_fetch_page` is wrapped by tenacity's @retry; call the underlying function directly so a
+# retryable status raises immediately instead of sleeping through the backoff schedule.
+_fetch_undecorated = _fetch_page.__wrapped__ # type: ignore[attr-defined]
+
+_REPOSITORIES = [
+ {"name": "maven-releases", "format": "maven2", "type": "hosted"},
+ {"name": "maven-public", "format": "maven2", "type": "group"},
+ {"name": "docker-proxy", "format": "docker", "type": "proxy"},
+]
+
+
+def _make_manager(resume_state: SonatypeNexusResumeConfig | None = None) -> mock.MagicMock:
+ manager = mock.MagicMock()
+ manager.can_resume.return_value = resume_state is not None
+ manager.load_state.return_value = resume_state
+ return manager
+
+
+def _response(body: Any, status_code: int = 200) -> mock.MagicMock:
+ resp = mock.MagicMock()
+ resp.status_code = status_code
+ resp.ok = status_code < 400
+ # Bodies are streamed and read through iter_content + json.loads, never .json(), and
+ # `_fetch_page` reads the response inside a `with` block.
+ payload = json.dumps(body).encode()
+ resp.iter_content = mock.Mock(side_effect=lambda chunk_size: iter([payload]))
+ resp.__enter__ = mock.Mock(return_value=resp)
+ resp.__exit__ = mock.Mock(return_value=False)
+ return resp
+
+
+def _streaming_response(chunks: list[bytes], status_code: int = 200) -> mock.MagicMock:
+ resp = mock.MagicMock()
+ resp.status_code = status_code
+ resp.ok = status_code < 400
+ resp.iter_content = mock.Mock(side_effect=lambda chunk_size: iter(chunks))
+ resp.__enter__ = mock.Mock(return_value=resp)
+ resp.__exit__ = mock.Mock(return_value=False)
+ return resp
+
+
+def _not_found_response() -> mock.MagicMock:
+ resp = _response({}, status_code=404)
+ resp.raise_for_status.side_effect = requests.HTTPError("404 Client Error", response=resp)
+ return resp
+
+
+class TestNormalizeHost:
+ @pytest.mark.parametrize(
+ "value, expected",
+ [
+ ("https://nexus.example.com", "https://nexus.example.com"),
+ ("nexus.example.com", "https://nexus.example.com"),
+ ("https://nexus.example.com/", "https://nexus.example.com"),
+ ("http://nexus.internal:8081", "http://nexus.internal:8081"),
+ # A pasted API base URL is tolerated by trimming the REST path suffix.
+ ("https://nexus.example.com/service/rest/v1", "https://nexus.example.com"),
+ ("https://nexus.example.com/service/rest/v1/", "https://nexus.example.com"),
+ ("https://nexus.example.com/service/rest", "https://nexus.example.com"),
+ ],
+ )
+ def test_valid_hosts(self, value, expected):
+ assert normalize_host(value) == expected
+
+ @pytest.mark.parametrize(
+ "value",
+ [
+ "",
+ " ",
+ "ftp://example.com",
+ "https://",
+ # SSRF: urlparse reads the host as example.com but urllib3 connects to
+ # 127.0.0.1 (backslash / userinfo confusion), so these must be rejected.
+ r"http://127.0.0.1\@example.com",
+ r"http://127.0.0.1%[email protected]",
+ "https://[email protected]",
+ ],
+ )
+ def test_invalid_hosts_raise(self, value):
+ with pytest.raises(ValueError):
+ normalize_host(value)
+
+ @pytest.mark.parametrize(
+ "cloud, host, expect_raise",
+ [
+ # On cloud the credentials would egress over the public internet, so
+ # plaintext http is rejected while https is fine.
+ (True, "http://nexus.example.com", True),
+ (True, "https://nexus.example.com", False),
+ # Self-hosted operators control their network path, so http stays allowed.
+ (False, "http://nexus.internal:8081", False),
+ ],
+ )
+ def test_http_requires_https_only_on_cloud(self, cloud, host, expect_raise):
+ with mock.patch(f"{_MODULE}.is_cloud", return_value=cloud):
+ if expect_raise:
+ with pytest.raises(ValueError):
+ normalize_host(host)
+ else:
+ assert normalize_host(host) == host
+
+ def test_hostname_of(self):
+ assert hostname_of("https://nexus.example.com/service/rest/v1") == "nexus.example.com"
+
+
+class TestFetchPage:
+ @pytest.mark.parametrize("status_code", [429, 500, 502, 503])
+ def test_retryable_statuses_raise_retryable_error(self, status_code):
+ session = mock.MagicMock()
+ session.get.return_value = _response({}, status_code=status_code)
+ with pytest.raises(SonatypeNexusRetryableError):
+ _fetch_undecorated(session, "https://x", mock.MagicMock())
+
+ @pytest.mark.parametrize("status_code", [400, 401, 403, 404])
+ def test_client_errors_raise_for_status(self, status_code):
+ session = mock.MagicMock()
+ resp = _response({}, status_code=status_code)
+ resp.raise_for_status.side_effect = requests.HTTPError(f"{status_code} Client Error", response=resp)
+ session.get.return_value = resp
+ with pytest.raises(requests.HTTPError):
+ _fetch_undecorated(session, "https://x", mock.MagicMock())
+
+ def test_list_body_is_wrapped_in_items(self):
+ # /repositories returns a plain JSON array instead of the paginated envelope.
+ session = mock.MagicMock()
+ session.get.return_value = _response([{"name": "maven-releases"}])
+ body = _fetch_undecorated(session, "https://x", mock.MagicMock())
+ assert body == {"items": [{"name": "maven-releases"}]}
+
+
+class TestReadBounded:
+ def test_oversized_body_aborts_instead_of_buffering(self):
+ resp = _streaming_response([b"x" * 10, b"x" * 10])
+ with pytest.raises(SonatypeNexusResponseTooLargeError):
+ _read_bounded(resp, max_bytes=15)
+
+ def test_slow_drip_body_aborts_on_total_deadline(self):
+ # A body that stays under the per-read timeout but never finishes is aborted once the
+ # total-transfer deadline passes, rather than holding the worker indefinitely.
+ resp = _streaming_response([b"x", b"x"])
+ with mock.patch(f"{_MODULE}.time.monotonic", side_effect=[0.0, 601.0]):
+ with pytest.raises(SonatypeNexusResponseTimeoutError):
+ _read_bounded(resp, max_bytes=1_000_000, max_seconds=600)
+
+
+class TestValidateCredentials:
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_valid_credentials(self, mock_session):
+ mock_session.return_value.get.return_value = _response([])
+
+ assert validate_credentials("https://nexus.example.com", "user", "pass") is True
+ assert mock_session.return_value.auth == ("user", "pass")
+ url = mock_session.return_value.get.call_args.args[0]
+ assert url == "https://nexus.example.com/service/rest/v1/repositories"
+
+ @pytest.mark.parametrize("status_code", [401, 403, 500])
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_non_200_fails_validation(self, mock_session, status_code):
+ mock_session.return_value.get.return_value = _response({}, status_code=status_code)
+ assert validate_credentials("https://nexus.example.com", "user", "bad") is False
+
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_network_error_fails_validation(self, mock_session):
+ mock_session.return_value.get.side_effect = requests.ConnectionError("boom")
+ assert validate_credentials("https://nexus.example.com", "user", "pass") is False
+
+
+class TestGetRowsTopLevel:
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_repositories_single_fetch_yields_and_stops(self, mock_session):
+ mock_session.return_value.get.return_value = _response(_REPOSITORIES)
+
+ manager = _make_manager()
+ batches = list(get_rows("https://n.example.com", "u", "p", "repositories", mock.MagicMock(), manager))
+
+ assert batches == [_REPOSITORIES]
+ manager.save_state.assert_not_called()
+ assert mock_session.return_value.get.call_count == 1
+ url = mock_session.return_value.get.call_args.args[0]
+ assert url == "https://n.example.com/service/rest/v1/repositories"
+
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_tasks_paginates_and_saves_token_after_each_page(self, mock_session):
+ mock_session.return_value.get.side_effect = [
+ _response({"items": [{"id": "1"}], "continuationToken": "TOKEN_A"}),
+ _response({"items": [{"id": "2"}], "continuationToken": "TOKEN_B"}),
+ _response({"items": [{"id": "3"}], "continuationToken": None}),
+ ]
+
+ manager = _make_manager()
+ batches = list(get_rows("https://n.example.com", "u", "p", "tasks", mock.MagicMock(), manager))
+
+ assert [row["id"] for batch in batches for row in batch] == ["1", "2", "3"]
+ # State saved once per page that has a following page (not for the last page).
+ saved = [call.args[0].continuation_token for call in manager.save_state.call_args_list]
+ assert saved == ["TOKEN_A", "TOKEN_B"]
+ second_url = mock_session.return_value.get.call_args_list[1].args[0]
+ assert "continuationToken=TOKEN_A" in second_url
+
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_tasks_resumes_from_saved_token(self, mock_session):
+ mock_session.return_value.get.return_value = _response({"items": [{"id": "9"}], "continuationToken": None})
+
+ manager = _make_manager(SonatypeNexusResumeConfig(continuation_token="SAVED"))
+ list(get_rows("https://n.example.com", "u", "p", "tasks", mock.MagicMock(), manager))
+
+ first_url = mock_session.return_value.get.call_args_list[0].args[0]
+ assert "continuationToken=SAVED" in first_url
+
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_tasks_empty_page_still_terminates(self, mock_session):
+ mock_session.return_value.get.return_value = _response({"items": [], "continuationToken": None})
+
+ manager = _make_manager()
+ batches = list(get_rows("https://n.example.com", "u", "p", "tasks", mock.MagicMock(), manager))
+
+ assert batches == []
+ manager.save_state.assert_not_called()
+
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_non_advancing_token_raises(self, mock_session):
+ # A server that keeps returning the same token would loop forever; it must fail instead.
+ mock_session.return_value.get.return_value = _response({"items": [{"id": "1"}], "continuationToken": "STUCK"})
+
+ manager = _make_manager()
+ with pytest.raises(SonatypeNexusPaginationError):
+ list(get_rows("https://n.example.com", "u", "p", "tasks", mock.MagicMock(), manager))
+
+ @mock.patch(f"{_MODULE}.MAX_PAGES_PER_ENDPOINT", 2)
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_page_ceiling_raises(self, mock_session):
+ # A server that hands out fresh tokens forever is bounded by the page ceiling.
+ mock_session.return_value.get.side_effect = [
+ _response({"items": [{"id": "1"}], "continuationToken": "A"}),
+ _response({"items": [{"id": "2"}], "continuationToken": "B"}),
+ _response({"items": [{"id": "3"}], "continuationToken": "C"}),
+ ]
+
+ manager = _make_manager()
+ with pytest.raises(SonatypeNexusPaginationError):
+ list(get_rows("https://n.example.com", "u", "p", "tasks", mock.MagicMock(), manager))
+
+ @mock.patch(f"{_MODULE}.MAX_PAGINATION_SECONDS", -1)
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_pagination_time_budget_raises(self, mock_session):
+ # Individually valid pages with fresh tokens must still fail once the cumulative
+ # wall-clock budget is exhausted, so a slow-drip host can't run until the activity timeout.
+ mock_session.return_value.get.side_effect = [
+ _response({"items": [{"id": "1"}], "continuationToken": "A"}),
+ _response({"items": [{"id": "2"}], "continuationToken": "B"}),
+ ]
+
+ manager = _make_manager()
+ with pytest.raises(SonatypeNexusPaginationError):
+ list(get_rows("https://n.example.com", "u", "p", "tasks", mock.MagicMock(), manager))
+
+
+class TestGetRowsRepositoryFanout:
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_fans_out_over_non_group_repositories(self, mock_session):
+ mock_session.return_value.get.side_effect = [
+ _response(_REPOSITORIES),
+ _response({"items": [{"id": "d1", "repository": "docker-proxy"}], "continuationToken": None}),
+ _response({"items": [{"id": "m1", "repository": "maven-releases"}], "continuationToken": None}),
+ ]
+
+ manager = _make_manager()
+ batches = list(get_rows("https://n.example.com", "u", "p", "components", mock.MagicMock(), manager))
+
+ assert [row["id"] for batch in batches for row in batch] == ["d1", "m1"]
+ urls = [call.args[0] for call in mock_session.return_value.get.call_args_list]
+ # Repositories are walked sorted by name; group repositories are excluded
+ # because they'd double-count their members' components.
+ assert "repository=docker-proxy" in urls[1]
+ assert "repository=maven-releases" in urls[2]
+ assert not any("maven-public" in url for url in urls)
+ # The bookmark advances to the next repository after each one completes.
+ saved = [(c.args[0].repository, c.args[0].continuation_token) for c in manager.save_state.call_args_list]
+ assert saved == [("maven-releases", None)]
+
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_saves_repository_and_token_after_each_page(self, mock_session):
+ mock_session.return_value.get.side_effect = [
+ _response(_REPOSITORIES),
+ _response({"items": [{"id": "d1"}], "continuationToken": "TOKEN_A"}),
+ _response({"items": [{"id": "d2"}], "continuationToken": None}),
+ _response({"items": [{"id": "m1"}], "continuationToken": None}),
+ ]
+
+ manager = _make_manager()
+ batches = list(get_rows("https://n.example.com", "u", "p", "assets", mock.MagicMock(), manager))
+
+ assert [row["id"] for batch in batches for row in batch] == ["d1", "d2", "m1"]
+ third_url = mock_session.return_value.get.call_args_list[2].args[0]
+ assert "repository=docker-proxy" in third_url
+ assert "continuationToken=TOKEN_A" in third_url
+ saved = [(c.args[0].repository, c.args[0].continuation_token) for c in manager.save_state.call_args_list]
+ assert saved == [("docker-proxy", "TOKEN_A"), ("maven-releases", None)]
+
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_empty_page_with_token_still_checkpoints(self, mock_session):
+ # An empty page that still returns a continuation token must save state, so a crash
+ # resumes from the page's real progression rather than an older token.
+ mock_session.return_value.get.side_effect = [
+ _response(_REPOSITORIES),
+ _response({"items": [], "continuationToken": "TOKEN_A"}),
+ _response({"items": [{"id": "d1"}], "continuationToken": None}),
+ _response({"items": [{"id": "m1"}], "continuationToken": None}),
+ ]
+
+ manager = _make_manager()
+ batches = list(get_rows("https://n.example.com", "u", "p", "components", mock.MagicMock(), manager))
+
+ assert [row["id"] for batch in batches for row in batch] == ["d1", "m1"]
+ saved = [(c.args[0].repository, c.args[0].continuation_token) for c in manager.save_state.call_args_list]
+ assert saved == [("docker-proxy", "TOKEN_A"), ("maven-releases", None)]
+
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_resumes_from_bookmarked_repository_and_token(self, mock_session):
+ mock_session.return_value.get.side_effect = [
+ _response(_REPOSITORIES),
+ _response({"items": [{"id": "m1"}], "continuationToken": None}),
+ ]
+
+ manager = _make_manager(SonatypeNexusResumeConfig(continuation_token="SAVED", repository="maven-releases"))
+ batches = list(get_rows("https://n.example.com", "u", "p", "components", mock.MagicMock(), manager))
+
+ assert [row["id"] for batch in batches for row in batch] == ["m1"]
+ # docker-proxy sorts before the bookmark, so it is skipped entirely.
+ urls = [call.args[0] for call in mock_session.return_value.get.call_args_list]
+ assert len(urls) == 2
+ assert "repository=maven-releases" in urls[1]
+ assert "continuationToken=SAVED" in urls[1]
+
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_resume_with_deleted_bookmark_repository_starts_over(self, mock_session):
+ mock_session.return_value.get.side_effect = [
+ _response(_REPOSITORIES),
+ _response({"items": [{"id": "d1"}], "continuationToken": None}),
+ _response({"items": [{"id": "m1"}], "continuationToken": None}),
+ ]
+
+ manager = _make_manager(SonatypeNexusResumeConfig(continuation_token="SAVED", repository="deleted-repo"))
+ batches = list(get_rows("https://n.example.com", "u", "p", "components", mock.MagicMock(), manager))
+
+ assert [row["id"] for batch in batches for row in batch] == ["d1", "m1"]
+ # The saved token belongs to the deleted repository and must not leak into
+ # the fresh walk.
+ urls = [call.args[0] for call in mock_session.return_value.get.call_args_list]
+ assert not any("continuationToken=SAVED" in url for url in urls)
+
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_repository_deleted_mid_sync_is_skipped(self, mock_session):
+ mock_session.return_value.get.side_effect = [
+ _response(_REPOSITORIES),
+ _not_found_response(),
+ _response({"items": [{"id": "m1"}], "continuationToken": None}),
+ ]
+
+ manager = _make_manager()
+ batches = list(get_rows("https://n.example.com", "u", "p", "components", mock.MagicMock(), manager))
+
+ # docker-proxy 404s (deleted between enumeration and fetch) and is skipped;
+ # maven-releases still syncs.
+ assert [row["id"] for batch in batches for row in batch] == ["m1"]
+
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_non_advancing_token_raises(self, mock_session):
+ # A repository whose pages never advance the token must fail rather than loop forever.
+ mock_session.return_value.get.side_effect = [
+ _response(_REPOSITORIES),
+ _response({"items": [{"id": "d1"}], "continuationToken": "STUCK"}),
+ _response({"items": [{"id": "d2"}], "continuationToken": "STUCK"}),
+ ]
+
+ manager = _make_manager()
+ with pytest.raises(SonatypeNexusPaginationError):
+ list(get_rows("https://n.example.com", "u", "p", "components", mock.MagicMock(), manager))
+
+ @mock.patch(f"{_MODULE}.MAX_PAGINATION_SECONDS", -1)
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_pagination_time_budget_raises(self, mock_session):
+ # A per-repository walk of individually valid small pages must fail once the cumulative
+ # wall-clock budget is exhausted, independent of the per-response transfer deadline.
+ mock_session.return_value.get.side_effect = [
+ _response(_REPOSITORIES),
+ _response({"items": [{"id": "d1"}], "continuationToken": "A"}),
+ _response({"items": [{"id": "d2"}], "continuationToken": "B"}),
+ ]
+
+ manager = _make_manager()
+ with pytest.raises(SonatypeNexusPaginationError):
+ list(get_rows("https://n.example.com", "u", "p", "components", mock.MagicMock(), manager))
+
+ @mock.patch(f"{_MODULE}.MAX_PAGINATION_SECONDS", -1)
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_pagination_time_budget_raises_on_terminal_pages(self, mock_session):
+ # A host that slow-drips a single terminal page (no continuation token) per repository
+ # must still trip the cumulative deadline — the check runs after every response, not only
+ # before continuing to a next page, so terminal pages can't bypass it across many repos.
+ mock_session.return_value.get.side_effect = [
+ _response(_REPOSITORIES),
+ _response({"items": [{"id": "d1"}], "continuationToken": None}),
+ _response({"items": [{"id": "m1"}], "continuationToken": None}),
+ ]
+
+ manager = _make_manager()
+ with pytest.raises(SonatypeNexusPaginationError):
+ list(get_rows("https://n.example.com", "u", "p", "components", mock.MagicMock(), manager))
+
+
+class TestSonatypeNexusSource:
+ @pytest.mark.parametrize("endpoint", list(ENDPOINTS))
+ def test_source_response_primary_keys_and_no_partitioning(self, endpoint):
+ config = SONATYPE_NEXUS_ENDPOINTS[endpoint]
+ response = sonatype_nexus_source("https://n.example.com", "u", "p", endpoint, mock.MagicMock(), _make_manager())
+
+ assert response.name == endpoint
+ assert response.primary_keys == config.primary_keys
+ # No Nexus endpoint has a universally-populated stable timestamp, so
+ # nothing is datetime-partitioned.
+ assert response.partition_mode is None
+ assert response.partition_keys is None
+
+ def test_build_url_encodes_params(self):
+ url = _build_url("https://x/service/rest/v1/components", {"repository": "a b", "continuationToken": "t/1"})
+ assert url == "https://x/service/rest/v1/components?repository=a+b&continuationToken=t%2F1"
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sonatype_nexus/tests/test_sonatype_nexus_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sonatype_nexus/tests/test_sonatype_nexus_source.py
new file mode 100644
index 000000000000..ae9e6cb8a7f1
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sonatype_nexus/tests/test_sonatype_nexus_source.py
@@ -0,0 +1,180 @@
+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 SonatypeNexusSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.sonatype_nexus.settings import ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.sonatype_nexus.sonatype_nexus import (
+ SonatypeNexusResumeConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.sonatype_nexus.source import SonatypeNexusSource
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+class TestSonatypeNexusSource:
+ def setup_method(self):
+ self.source = SonatypeNexusSource()
+ self.team_id = 123
+ self.config = SonatypeNexusSourceConfig(host="https://nexus.example.com", username="user", password="pass")
+
+ def test_source_type(self):
+ assert self.source.source_type == ExternalDataSourceType.SONATYPENEXUS
+
+ def test_get_source_config(self):
+ config = self.source.get_source_config
+
+ assert config.name.value == "SonatypeNexus"
+ assert config.label == "Sonatype (Nexus Repository)"
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.unreleasedSource is None
+ assert config.iconPath == "/static/services/sonatype_nexus.png"
+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/sonatype-nexus"
+
+ field_names = [f.name for f in config.fields]
+ assert field_names == ["host", "username", "password"]
+
+ def test_password_field_is_secret_password(self):
+ config = self.source.get_source_config
+ password_field = next(
+ f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "password"
+ )
+ assert password_field.type == SourceFieldInputConfigType.PASSWORD
+ assert password_field.secret is True
+ assert password_field.required is True
+
+ def test_connection_host_fields_cover_host(self):
+ # The instance URL decides where the stored credentials get sent.
+ assert self.source.connection_host_fields == ["host"]
+
+ def test_lists_tables_without_credentials(self):
+ # get_schemas is a static endpoint catalog, so the public docs can render tables.
+ assert self.source.lists_tables_without_credentials is True
+
+ @pytest.mark.parametrize(
+ "observed_error",
+ [
+ "401 Client Error: Unauthorized for url: https://nexus.example.com/service/rest/v1/components",
+ "403 Client Error: Forbidden for url: https://nexus.example.com/service/rest/v1/tasks",
+ ],
+ )
+ def test_non_retryable_errors_match_known_failures(self, observed_error):
+ non_retryable_errors = self.source.get_non_retryable_errors()
+ assert any(key in observed_error for key in non_retryable_errors)
+
+ @pytest.mark.parametrize(
+ "error",
+ [
+ "500 Server Error for url: https://nexus.example.com/service/rest/v1/components",
+ "429 Client Error: Too Many Requests",
+ ],
+ )
+ def test_non_retryable_errors_does_not_match_transient_failures(self, error):
+ non_retryable_errors = self.source.get_non_retryable_errors()
+ assert not any(key in error for key in non_retryable_errors)
+
+ def test_get_schemas_are_all_full_refresh(self):
+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}
+
+ assert set(schemas) == set(ENDPOINTS)
+ # The Nexus REST API exposes no server-side timestamp filter, so nothing is incremental.
+ assert all(not schema.supports_incremental for schema in schemas.values())
+ assert all(not schema.supports_append for schema in schemas.values())
+ assert all(schema.incremental_fields == [] for schema in schemas.values())
+ # Primary keys are surfaced so the public docs' Supported tables section renders them.
+ assert schemas["repositories"].detected_primary_keys == ["name"]
+ assert schemas["components"].detected_primary_keys == ["repository", "id"]
+ assert schemas["assets"].detected_primary_keys == ["repository", "id"]
+ assert schemas["tasks"].detected_primary_keys == ["id"]
+
+ def test_get_schemas_filtered_by_names(self):
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["components"])
+ assert len(schemas) == 1
+ assert schemas[0].name == "components"
+
+ def test_get_schemas_filtered_unknown_name_returns_empty(self):
+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []
+
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.sonatype_nexus.source.validate_sonatype_nexus_credentials"
+ )
+ @mock.patch.object(SonatypeNexusSource, "is_database_host_valid")
+ def test_validate_credentials_happy_path(self, mock_host_valid, mock_validate):
+ mock_host_valid.return_value = (True, None)
+ mock_validate.return_value = True
+
+ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id)
+
+ assert is_valid is True
+ assert error_message is None
+ mock_host_valid.assert_called_once_with("nexus.example.com", self.team_id)
+ mock_validate.assert_called_once_with("https://nexus.example.com", "user", "pass")
+
+ @mock.patch.object(SonatypeNexusSource, "is_database_host_valid")
+ def test_validate_credentials_rejects_unsafe_host(self, mock_host_valid):
+ mock_host_valid.return_value = (False, "Host is not allowed")
+
+ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id)
+
+ assert is_valid is False
+ assert error_message == "Host is not allowed"
+
+ def test_validate_credentials_rejects_invalid_url(self):
+ config = SonatypeNexusSourceConfig(host="ftp://nope", username="user", password="pass")
+
+ is_valid, error_message = self.source.validate_credentials(config, self.team_id)
+
+ assert is_valid is False
+ assert error_message == "Invalid Nexus instance URL"
+
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.sonatype_nexus.source.validate_sonatype_nexus_credentials"
+ )
+ @mock.patch.object(SonatypeNexusSource, "is_database_host_valid")
+ def test_validate_credentials_bad_credentials(self, mock_host_valid, mock_validate):
+ mock_host_valid.return_value = (True, None)
+ mock_validate.return_value = False
+
+ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id)
+
+ assert is_valid is False
+ assert "Invalid Nexus credentials" in (error_message or "")
+
+ def test_get_resumable_source_manager_binds_resume_config(self):
+ inputs = mock.MagicMock()
+ manager = self.source.get_resumable_source_manager(inputs)
+
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is SonatypeNexusResumeConfig
+
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.sonatype_nexus.source.sonatype_nexus_source"
+ )
+ @mock.patch.object(SonatypeNexusSource, "is_database_host_valid")
+ def test_source_for_pipeline_plumbs_arguments(self, mock_host_valid, mock_source):
+ mock_host_valid.return_value = (True, None)
+ inputs = mock.MagicMock()
+ inputs.schema_name = "components"
+ inputs.team_id = self.team_id
+ 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://nexus.example.com"
+ assert kwargs["username"] == "user"
+ assert kwargs["password"] == "pass"
+ assert kwargs["endpoint"] == "components"
+ assert kwargs["resumable_source_manager"] is manager
+
+ @mock.patch.object(SonatypeNexusSource, "is_database_host_valid")
+ def test_source_for_pipeline_rejects_unsafe_host(self, mock_host_valid):
+ mock_host_valid.return_value = (False, "Host is not allowed")
+ inputs = mock.MagicMock()
+ inputs.schema_name = "components"
+ inputs.team_id = self.team_id
+
+ with pytest.raises(ValueError, match="Host is not allowed"):
+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)