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 dockerhub import source (#69334)

Tom Owersff8bf5d65b41
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 8500a4f01da8..3bd4e6491353 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -131,6 +131,7 @@ the row lists both.
| devin_ai | HTTP | requests | ✅ |
| ding_connect | HTTP | requests | ✅ |
| dixa | HTTP | requests | ✅ |
+| dockerhub | HTTP | requests | ✅ |
| docuseal | HTTP | requests | ✅ |
| doit | HTTP | requests | ✅ |
| dropbox_sign | HTTP | requests | ✅ |
@@ -491,7 +492,6 @@ doesn't conflict with concurrent PRs.
- deepgram
- deputy
- display_video_360
-- dockerhub
- docusign
- dolibarr
- dremio
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/dockerhub/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/dockerhub/canonical_descriptions.py
new file mode 100644
index 000000000000..8617e244023d
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/dockerhub/canonical_descriptions.py
@@ -0,0 +1,53 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "repositories": {
+ "description": "A container image repository in the configured Docker Hub namespace (user or organization).",
+ "docs_url": "https://docs.docker.com/reference/api/hub/latest/#tag/repositories",
+ "columns": {
+ "name": "Name of the repository, unique within its namespace.",
+ "namespace": "Namespace (user or organization) that owns the repository.",
+ "repository_type": "Type of the repository, e.g. image.",
+ "status": "Numeric status code of the repository (1 = active).",
+ "status_description": "Human-readable repository status, e.g. active or inactive.",
+ "description": "Short free-text description of the repository.",
+ "is_private": "Whether the repository is private (true) or public (false).",
+ "star_count": "Number of users who starred the repository.",
+ "pull_count": "Total number of image pulls from the repository.",
+ "last_updated": "Timestamp of the last image push to the repository.",
+ "last_modified": "Timestamp of the last change to the repository's settings or metadata.",
+ "date_registered": "Timestamp when the repository was created.",
+ "affiliation": "Requesting user's affiliation with the repository, e.g. owner.",
+ "media_types": "Media types stored in the repository, e.g. container image manifests.",
+ "content_types": "Content types stored in the repository, e.g. image.",
+ "categories": "Docker Hub catalog categories assigned to the repository.",
+ "storage_size": "Total storage used by the repository, in bytes.",
+ },
+ },
+ "tags": {
+ "description": "A tag on a repository in the configured Docker Hub namespace, including its per-architecture images.",
+ "docs_url": "https://docs.docker.com/reference/api/hub/latest/#tag/repositories/operation/ListRepositoryTags",
+ "columns": {
+ "id": "Numeric identifier of the tag assigned by Docker Hub.",
+ "name": "Name of the tag, unique within its repository.",
+ "namespace": "Namespace (user or organization) that owns the repository. Added by PostHog to every row.",
+ "repository_name": "Name of the repository the tag belongs to. Added by PostHog to every row.",
+ "repository": "Numeric identifier of the repository the tag belongs to.",
+ "creator": "Numeric identifier of the user who created the tag.",
+ "images": "Per-architecture images the tag points at, including digest, os, architecture, and size.",
+ "full_size": "Compressed size of the tag's image, in bytes.",
+ "last_updated": "Timestamp when the tag was last updated.",
+ "last_updater": "Numeric identifier of the user who last updated the tag.",
+ "last_updater_username": "Username of the user who last updated the tag.",
+ "tag_status": "Status of the tag, e.g. active or inactive.",
+ "tag_last_pulled": "Timestamp when the tag was last pulled.",
+ "tag_last_pushed": "Timestamp when the tag was last pushed.",
+ "v2": "Whether the tag uses a v2 image manifest.",
+ "media_type": "Media type of the tag's manifest.",
+ "content_type": "Content type of the tag, e.g. image.",
+ "digest": "Content digest of the tag's manifest.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/dockerhub/dockerhub.py b/products/warehouse_sources/backend/temporal/data_imports/sources/dockerhub/dockerhub.py
new file mode 100644
index 000000000000..0a2398932a64
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/dockerhub/dockerhub.py
@@ -0,0 +1,378 @@
+import dataclasses
+from collections.abc import Iterator
+from typing import Any, Optional
+from urllib.parse import quote, urlencode, urlsplit
+
+import requests
+from structlog.types import FilteringBoundLogger
+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+
+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.dockerhub.settings import DOCKERHUB_ENDPOINTS
+
+# Management API host (hub.docker.com), distinct from the OCI registry API (registry.hub.docker.com).
+DOCKERHUB_BASE_URL = "https://hub.docker.com"
+# Host the Bearer JWT is scoped to. Every URL we fetch (including verbatim `next` links and resumed
+# cursors) is pinned to this host so a hostile/spoofed response can't redirect the token elsewhere.
+DOCKERHUB_HOST = urlsplit(DOCKERHUB_BASE_URL).netloc
+LOGIN_PATH = "/v2/users/login"
+# Maximum accepted page_size on the v2 list endpoints.
+PAGE_SIZE = 100
+REQUEST_TIMEOUT_SECONDS = 60
+
+
+def _require_dockerhub_url(url: str) -> str:
+ # Pagination follows the API's `next` field verbatim, so a compromised or spoofed response could
+ # point `next` at an attacker host and exfiltrate the Bearer JWT. Pin scheme+host to Docker Hub
+ # before any request carries the token; the pinned initial URLs pass trivially.
+ parts = urlsplit(url)
+ if parts.scheme != "https" or parts.netloc != DOCKERHUB_HOST:
+ raise ValueError(f"Refusing to fetch non-Docker Hub URL: {url}")
+ return url
+
+
+class DockerhubRetryableError(Exception):
+ pass
+
+
+class DockerhubAuthExpiredError(Exception):
+ # Raised on a mid-sync 401: the short-lived JWT (undocumented expiry) has lapsed and the client
+ # should re-login once and retry the same URL.
+ pass
+
+
+class DockerhubResumeConfig:
+ # Full URL of the next page to fetch, taken verbatim from the API's `next` field (it carries the
+ # page/page_size/ordering params). Merge dedupes any re-pulled page on the primary key.
+ next_url: str | None = None
+ # Tags fan-out only: the repository whose tag pages we were walking when state was last saved.
+ # `next_url=None` with a repository set means that repository completed.
+ repository: str | None = None
+
+
+def _repositories_url(namespace: str) -> str:
+ # ordering=name is ascending on the repositories endpoint (verified against the live API). An
+ # explicit sort on an immutable field keeps page boundaries stable while paginating.
+ query = urlencode({"page_size": PAGE_SIZE, "ordering": "name"})
+ return f"{DOCKERHUB_BASE_URL}/v2/namespaces/{quote(namespace)}/repositories?{query}"
+
+
+def _tags_url(namespace: str, repository: str) -> str:
+ # The tags endpoint inverts the ordering sign vs repositories: ordering=-name is ascending name
+ # (verified against the live API). Tag names are immutable, so pagination stays stable.
+ query = urlencode({"page_size": PAGE_SIZE, "ordering": "-name"})
+ return f"{DOCKERHUB_BASE_URL}/v2/namespaces/{quote(namespace)}/repositories/{quote(repository)}/tags?{query}"
+
+
+@retry(
+ retry=retry_if_exception_type((DockerhubRetryableError, requests.ReadTimeout, requests.ConnectionError)),
+ stop=stop_after_attempt(5),
+ wait=wait_exponential_jitter(initial=1, max=30),
+ reraise=True,
+)
+def _fetch_jwt(
+ session: requests.Session,
+ username: str,
+ personal_access_token: str,
+ logger: FilteringBoundLogger,
+) -> str:
+ # The Hub management API only accepts a Bearer JWT, obtained by exchanging the username and PAT
+ # (or password) via POST /v2/users/login.
+ response = session.post(
+ f"{DOCKERHUB_BASE_URL}{LOGIN_PATH}",
+ json={"username": username, "password": personal_access_token},
+ timeout=REQUEST_TIMEOUT_SECONDS,
+ )
+
+ if response.status_code == 429 or response.status_code >= 500:
+ raise DockerhubRetryableError(f"Docker Hub login error (retryable): status={response.status_code}")
+
+ if not response.ok:
+ logger.error(f"Docker Hub login error: status={response.status_code}, body={response.text}")
+ response.raise_for_status()
+
+ data = response.json()
+ token = data.get("token") if isinstance(data, dict) else None
+ if not isinstance(token, str) or not token:
+ raise DockerhubRetryableError("Docker Hub login succeeded but returned no token")
+ return token
+
+
+@retry(
+ retry=retry_if_exception_type((DockerhubRetryableError, requests.ReadTimeout, requests.ConnectionError)),
+ stop=stop_after_attempt(5),
+ wait=wait_exponential_jitter(initial=1, max=30),
+ reraise=True,
+)
+def _fetch_page(
+ session: requests.Session,
+ url: str,
+ logger: FilteringBoundLogger,
+ allow_reauth: bool = True,
+) -> tuple[list[dict[str, Any]], Optional[str]]:
+ # `url` is already absolute — either an initial endpoint URL or a verbatim `next` link, so we
+ # never re-send page params (they're baked into the URL). Pin it to Docker Hub first: this is the
+ # single choke point for initial, resumed, and `next`-followed URLs, so the token never leaves.
+ _require_dockerhub_url(url)
+ response = session.get(url, timeout=REQUEST_TIMEOUT_SECONDS)
+
+ if response.status_code == 429 or response.status_code >= 500:
+ raise DockerhubRetryableError(f"Docker Hub API error (retryable): status={response.status_code}, url={url}")
+
+ if response.status_code == 401 and allow_reauth:
+ # Login succeeded earlier in the sync, so a 401 here means the JWT expired.
+ raise DockerhubAuthExpiredError(f"Docker Hub JWT expired mid-sync for {url}")
+
+ if not response.ok:
+ logger.error(f"Docker Hub API error: status={response.status_code}, body={response.text}, url={url}")
+ response.raise_for_status()
+
+ data = response.json()
+ if not isinstance(data, dict) or not isinstance(data.get("results"), list):
+ raise DockerhubRetryableError(f"Docker Hub returned an unexpected payload for {url}: {type(data).__name__}")
+
+ next_url = data.get("next")
+ if isinstance(next_url, str) and next_url:
+ # Validate before returning so a hostile `next` is rejected here, not persisted to resume
+ # state and re-tried on the next run.
+ return data["results"], _require_dockerhub_url(next_url)
+ return data["results"], None
+
+
+class DockerHubClient:
+ def __init__(self, username: str, personal_access_token: str, logger: FilteringBoundLogger) -> None:
+ self._username = username
+ self._personal_access_token = personal_access_token
+ self._logger = logger
+ self._session = make_tracked_session(
+ headers={"Accept": "application/json"},
+ redact_values=(personal_access_token,),
+ )
+ # The login response body carries a freshly minted JWT under the generic `token` key, which
+ # the name-based sample scrubbers don't redact. Exchange credentials on a capture-disabled
+ # session so that token never lands in a captured HTTP sample; the JWT then rides in the
+ # Authorization header (redacted by name) on the capture-enabled data session.
+ self._login_session = make_tracked_session(
+ headers={"Accept": "application/json"},
+ redact_values=(personal_access_token,),
+ capture=False,
+ )
+
+ def login(self) -> None:
+ self._session.headers.pop("Authorization", None)
+ token = _fetch_jwt(self._login_session, self._username, self._personal_access_token, self._logger)
+ self._session.headers["Authorization"] = f"Bearer {token}"
+
+ def get_page(self, url: str) -> tuple[list[dict[str, Any]], Optional[str]]:
+ try:
+ return _fetch_page(self._session, url, self._logger)
+ except DockerhubAuthExpiredError:
+ self._logger.debug("Docker Hub: JWT expired mid-sync, re-authenticating")
+ self.login()
+ # A second 401 after a fresh login is a genuine auth failure, not expiry.
+ return _fetch_page(self._session, url, self._logger, allow_reauth=False)
+
+
+def _repository_pages(
+ client: DockerHubClient,
+ namespace: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[DockerhubResumeConfig],
+) -> Iterator[list[dict[str, Any]]]:
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ url: Optional[str] = resume.next_url if (resume and resume.next_url) else _repositories_url(namespace)
+ if resume and resume.next_url:
+ logger.debug(f"Docker Hub: resuming repositories from {url}")
+
+ while url:
+ items, next_url = client.get_page(url)
+ if items:
+ yield items
+
+ # A null `next` link means we've reached the end of the collection.
+ if not next_url:
+ break
+
+ url = next_url
+ # Save AFTER yielding so a crash re-fetches from the next page (already-yielded pages are
+ # persisted); merge dedupes the re-pulled page on the primary key.
+ resumable_source_manager.save_state(DockerhubResumeConfig(next_url=next_url))
+
+
+def _list_repository_names(client: DockerHubClient, namespace: str) -> list[str]:
+ names: list[str] = []
+ url: Optional[str] = _repositories_url(namespace)
+ while url:
+ items, url = client.get_page(url)
+ # `name` is the repository primary key and the fan-out key for tags: access it directly so a
+ # malformed row (missing name) fails fast instead of being silently dropped from the sync.
+ names.extend(item["name"] for item in items)
+ return names
+
+
+def _tag_pages(
+ client: DockerHubClient,
+ namespace: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[DockerhubResumeConfig],
+) -> Iterator[list[dict[str, Any]]]:
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ # The repository list is small (names only) and alphabetically ordered, so materializing it keeps
+ # resume deterministic: we slice from the saved repository instead of comparing names.
+ repositories = _list_repository_names(client, namespace)
+
+ start_index = 0
+ resume_next_url: Optional[str] = None
+ if resume and resume.repository:
+ if resume.repository in repositories:
+ start_index = repositories.index(resume.repository)
+ resume_next_url = resume.next_url
+ logger.debug(f"Docker Hub: resuming tags from repository {resume.repository}")
+ else:
+ # The repository was deleted since state was saved; restart from the beginning — merge
+ # dedupes any re-pulled rows on the primary key.
+ logger.debug("Docker Hub: saved resume repository no longer exists, restarting tags sync")
+
+ for index in range(start_index, len(repositories)):
+ repository = repositories[index]
+ url: Optional[str] = (
+ resume_next_url if index == start_index and resume_next_url else _tags_url(namespace, repository)
+ )
+
+ while url:
+ items, next_url = client.get_page(url)
+ if items:
+ # Tag rows only carry a numeric repository id; inject the namespace and repository
+ # name so rows are self-describing and the composite primary key is table-unique.
+ yield [{**row, "namespace": namespace, "repository_name": repository} for row in items]
+
+ if not next_url:
+ break
+
+ url = next_url
+ resumable_source_manager.save_state(DockerhubResumeConfig(next_url=next_url, repository=repository))
+
+ # Pin state to the completed repository so a crash before the next repository's first page
+ # re-syncs at most this one repository.
+ resumable_source_manager.save_state(DockerhubResumeConfig(next_url=None, repository=repository))
+
+
+def get_rows(
+ username: str,
+ personal_access_token: str,
+ namespace: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[DockerhubResumeConfig],
+) -> Iterator[list[dict[str, Any]]]:
+ if endpoint not in DOCKERHUB_ENDPOINTS:
+ raise ValueError(f"Unknown Docker Hub endpoint '{endpoint}'")
+
+ client = DockerHubClient(username, personal_access_token, logger)
+ client.login()
+
+ if endpoint == "repositories":
+ yield from _repository_pages(client, namespace, logger, resumable_source_manager)
+ else:
+ yield from _tag_pages(client, namespace, logger, resumable_source_manager)
+
+
+def dockerhub_source(
+ username: str,
+ personal_access_token: str,
+ namespace: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[DockerhubResumeConfig],
+) -> SourceResponse:
+ config = DOCKERHUB_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ username=username,
+ personal_access_token=personal_access_token,
+ namespace=namespace,
+ endpoint=endpoint,
+ logger=logger,
+ resumable_source_manager=resumable_source_manager,
+ ),
+ primary_keys=config.primary_keys,
+ partition_count=1,
+ partition_size=1,
+ )
+
+
+def check_access(username: str, personal_access_token: str, namespace: str) -> tuple[int, Optional[str]]:
+ """Login with the PAT and probe the configured namespace.
+
+ Returns ``(status, message)``: ``200`` reachable, ``401``/``403`` auth failure, ``0`` for a
+ connection problem, other HTTP status (with a message) otherwise.
+ """
+ # The login response body carries a JWT under the generic `token` key that the name-based
+ # sample scrubbers don't redact, so exchange credentials on a capture-disabled session (still
+ # metered and logged). The namespace probe below runs on the capture-enabled session.
+ login_session = make_tracked_session(
+ headers={"Accept": "application/json"},
+ redact_values=(personal_access_token,),
+ capture=False,
+ )
+ session = make_tracked_session(
+ headers={"Accept": "application/json"},
+ redact_values=(personal_access_token,),
+ )
+ try:
+ response = login_session.post(
+ f"{DOCKERHUB_BASE_URL}{LOGIN_PATH}",
+ json={"username": username, "password": personal_access_token},
+ timeout=15,
+ )
+ except Exception as e:
+ return 0, f"Could not connect to Docker Hub: {e}"
+
+ if response.status_code in (401, 403):
+ return response.status_code, None
+
+ if not response.ok:
+ return response.status_code, f"Docker Hub returned HTTP {response.status_code}"
+
+ data = response.json()
+ token = data.get("token") if isinstance(data, dict) else None
+ if not isinstance(token, str) or not token:
+ return 0, "Docker Hub login did not return a token"
+
+ # Probe the configured namespace so a typo'd org name fails at connect time, not sync time.
+ try:
+ probe = session.get(
+ f"{DOCKERHUB_BASE_URL}/v2/namespaces/{quote(namespace)}/repositories?{urlencode({'page_size': 1})}",
+ headers={"Authorization": f"Bearer {token}"},
+ timeout=15,
+ )
+ except Exception as e:
+ return 0, f"Could not connect to Docker Hub: {e}"
+
+ if probe.status_code == 404:
+ return 404, f"Docker Hub namespace '{namespace}' was not found"
+
+ if probe.status_code == 403:
+ return 403, f"Your personal access token does not have access to the '{namespace}' namespace"
+
+ if probe.status_code == 401:
+ return 401, None
+
+ if not probe.ok:
+ return probe.status_code, f"Docker Hub returned HTTP {probe.status_code}"
+
+ return 200, None
+
+
+def validate_credentials(username: str, personal_access_token: str, namespace: str) -> tuple[bool, str | None]:
+ status, message = check_access(username, personal_access_token, namespace)
+ if status == 200:
+ return True, None
+ if status in (401, 403):
+ return False, message or "Invalid Docker Hub username or personal access token"
+ return False, message or "Could not validate Docker Hub credentials"
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/dockerhub/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/dockerhub/settings.py
new file mode 100644
index 000000000000..46ade97bf907
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/dockerhub/settings.py
@@ -0,0 +1,23 @@
+from dataclasses import dataclass, field
+
+
+@dataclass
+class DockerhubEndpointConfig:
+ name: str
+ primary_keys: list[str] = field(default_factory=lambda: ["id"])
+
+
+# Docker Hub management API v2 list endpoints (https://docs.docker.com/reference/api/hub/latest/).
+# Both are full-refresh only: the Hub API exposes no server-side updated_after/since filter on
+# repositories or tags, so there is no incremental cursor to advance (see the
+# implementing-warehouse-sources skill). Tag rows carry a numeric `repository` id, not the repo
+# name, so we inject `namespace` and `repository_name` into every tag row and key on those plus the
+# tag name — tag names are only unique within their repository.
+DOCKERHUB_ENDPOINTS: dict[str, DockerhubEndpointConfig] = {
+ "repositories": DockerhubEndpointConfig(name="repositories", primary_keys=["namespace", "name"]),
+ "tags": DockerhubEndpointConfig(name="tags", primary_keys=["namespace", "repository_name", "name"]),
+}
+
+ENDPOINTS = tuple(DOCKERHUB_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[dict[str, str]]] = {}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/dockerhub/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/dockerhub/source.py
index e38e855612d3..9bfa06d4437d 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/dockerhub/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/dockerhub/source.py
@@ -1,30 +1,167 @@
-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.dockerhub.dockerhub import (
+ DockerhubResumeConfig,
+ dockerhub_source,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.dockerhub.settings import (
+ DOCKERHUB_ENDPOINTS,
+ ENDPOINTS,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import DockerhubSourceConfig
from products.warehouse_sources.backend.types import ExternalDataSourceType
+def _namespace_for_config(config: DockerhubSourceConfig) -> str:
+ # A blank namespace means "my own repositories": Docker Hub personal repositories live under the
+ # username's namespace.
+ namespace = (config.namespace or "").strip()
+ return namespace or config.username.strip()
+
+
@SourceRegistry.register
-class DockerhubSource(SimpleSource[DockerhubSourceConfig]):
+class DockerhubSource(ResumableSource[DockerhubSourceConfig, DockerhubResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.DOCKERHUB
+ @property
+ def connection_host_fields(self) -> list[str]:
+ # The stored token pulls repositories and tags from whatever `namespace` is configured, so
+ # retargeting the namespace must force re-entry of the token — otherwise an editor could
+ # point the preserved credential at any org the token can read.
+ return ["namespace"]
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=SchemaExternalDataSourceType.DOCKERHUB,
category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,
- label="Dockerhub",
+ label="Docker Hub",
+ releaseStatus=ReleaseStatus.ALPHA,
+ caption="""Enter your Docker Hub username and a personal access token to pull your container repositories and tags into the PostHog Data warehouse.
+
+You can create a personal access token with **Read** access under **Account settings → Personal access tokens** in [Docker Hub](https://app.docker.com/settings/personal-access-tokens). To import an organization's repositories instead of your own, set the namespace field to the organization name.
+""",
iconPath="/static/services/dockerhub.png",
- fields=cast(list[FieldType], []),
+ docsUrl="https://posthog.com/docs/cdp/sources/dockerhub",
+ keywords=["docker"],
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="username",
+ label="Username",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="",
+ secret=False,
+ ),
+ SourceFieldInputConfig(
+ name="personal_access_token",
+ label="Personal access token",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ SourceFieldInputConfig(
+ name="namespace",
+ label="Namespace",
+ type=SourceFieldInputConfigType.TEXT,
+ required=False,
+ placeholder="Defaults to your username",
+ secret=False,
+ ),
+ ],
+ ),
unreleasedSource=True,
)
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.dockerhub.canonical_descriptions import ( # noqa: PLC0415
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error: Unauthorized for url: https://hub.docker.com": "Your Docker Hub username or personal access token is invalid or has been revoked. Generate a new token under Account settings → Personal access tokens, then reconnect.",
+ "403 Client Error: Forbidden for url: https://hub.docker.com": "Your Docker Hub personal access token does not have access to this data. Check the token's access permissions and the configured namespace, then reconnect.",
+ }
+
+ def get_schemas(
+ self,
+ config: DockerhubSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ # Every endpoint is full refresh only — the Hub management API exposes no server-side
+ # updated_after/since filter on repositories or tags, so there is no incremental cursor.
+ schemas = [
+ SourceSchema(
+ name=endpoint,
+ supports_incremental=False,
+ supports_append=False,
+ incremental_fields=[],
+ )
+ 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: DockerhubSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ # Both endpoints read from the same namespace with the same token, so a single login +
+ # namespace probe validates access to every schema.
+ return validate_credentials(config.username, config.personal_access_token, _namespace_for_config(config))
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[DockerhubResumeConfig]:
+ return ResumableSourceManager[DockerhubResumeConfig](inputs, DockerhubResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: DockerhubSourceConfig,
+ resumable_source_manager: ResumableSourceManager[DockerhubResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ if inputs.schema_name not in DOCKERHUB_ENDPOINTS:
+ raise ValueError(f"Unknown Docker Hub schema '{inputs.schema_name}'")
+
+ return dockerhub_source(
+ username=config.username,
+ personal_access_token=config.personal_access_token,
+ namespace=_namespace_for_config(config),
+ endpoint=inputs.schema_name,
+ logger=inputs.logger,
+ resumable_source_manager=resumable_source_manager,
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/dockerhub/tests/test_dockerhub.py b/products/warehouse_sources/backend/temporal/data_imports/sources/dockerhub/tests/test_dockerhub.py
new file mode 100644
index 000000000000..626800ccfccd
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/dockerhub/tests/test_dockerhub.py
@@ -0,0 +1,478 @@
+from collections.abc import Mapping
+from typing import Any, Optional
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+import requests
+from parameterized import parameterized
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.dockerhub import dockerhub
+from products.warehouse_sources.backend.temporal.data_imports.sources.dockerhub.dockerhub import (
+ DOCKERHUB_BASE_URL,
+ DockerhubAuthExpiredError,
+ DockerHubClient,
+ DockerhubResumeConfig,
+ DockerhubRetryableError,
+ _repositories_url,
+ _tags_url,
+ check_access,
+ dockerhub_source,
+ get_rows,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.dockerhub.settings import (
+ DOCKERHUB_ENDPOINTS,
+ ENDPOINTS,
+)
+
+# Call the undecorated functions so the tenacity retry/backoff wrappers don't slow failure-path tests.
+_fetch_page_unwrapped = dockerhub._fetch_page.__wrapped__ # type: ignore[attr-defined]
+_fetch_jwt_unwrapped = dockerhub._fetch_jwt.__wrapped__ # type: ignore[attr-defined]
+
+REPOS_URL = _repositories_url("acme")
+ALPHA_TAGS_URL = _tags_url("acme", "alpha")
+BETA_TAGS_URL = _tags_url("acme", "beta")
+
+
+class _FakeResumableManager:
+ def __init__(self, state: DockerhubResumeConfig | None = None) -> None:
+ self._state = state
+ self.saved: list[DockerhubResumeConfig] = []
+
+ def can_resume(self) -> bool:
+ return self._state is not None
+
+ def load_state(self) -> DockerhubResumeConfig | None:
+ return self._state
+
+ def save_state(self, data: DockerhubResumeConfig) -> None:
+ self.saved.append(data)
+
+
+class _FakeClient:
+ def __init__(self, pages: Mapping[str, tuple[list[dict[str, Any]], Optional[str]]]) -> None:
+ self._pages = pages
+ self.fetched: list[str] = []
+ self.login_calls = 0
+
+ def login(self) -> None:
+ self.login_calls += 1
+
+ def get_page(self, url: str) -> tuple[list[dict[str, Any]], Optional[str]]:
+ self.fetched.append(url)
+ return self._pages[url]
+
+
+class TestGetRows:
+ @staticmethod
+ def _collect(
+ manager: _FakeResumableManager,
+ monkeypatch: Any,
+ pages: Mapping[str, tuple[list[dict[str, Any]], Optional[str]]],
+ endpoint: str,
+ ) -> tuple[list[dict[str, Any]], _FakeClient]:
+ client = _FakeClient(pages)
+ monkeypatch.setattr(dockerhub, "DockerHubClient", lambda *args, **kwargs: client)
+
+ rows: list[dict[str, Any]] = []
+ for batch in get_rows(
+ username="tom",
+ personal_access_token="dckr_pat_token",
+ namespace="acme",
+ endpoint=endpoint,
+ logger=MagicMock(),
+ resumable_source_manager=manager, # type: ignore[arg-type]
+ ):
+ rows.extend(batch)
+ return rows, client
+
+ def test_unknown_endpoint_raises(self, monkeypatch: Any) -> None:
+ with pytest.raises(ValueError, match="Unknown Docker Hub endpoint 'nope'"):
+ list(
+ get_rows(
+ username="tom",
+ personal_access_token="dckr_pat_token",
+ namespace="acme",
+ endpoint="nope",
+ logger=MagicMock(),
+ resumable_source_manager=_FakeResumableManager(), # type: ignore[arg-type]
+ )
+ )
+
+ def test_repositories_single_page_yields_and_stops(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager()
+ pages = {REPOS_URL: ([{"namespace": "acme", "name": "alpha"}], None)}
+ rows, client = self._collect(manager, monkeypatch, pages, "repositories")
+ assert rows == [{"namespace": "acme", "name": "alpha"}]
+ assert client.login_calls == 1
+ # A null next link ends the sync without persisting resume state.
+ assert manager.saved == []
+
+ def test_repositories_follows_next_url_until_null(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager()
+ second = f"{DOCKERHUB_BASE_URL}/v2/namespaces/acme/repositories?ordering=name&page=2&page_size=100"
+ pages = {
+ REPOS_URL: ([{"name": "alpha"}], second),
+ second: ([{"name": "beta"}], None),
+ }
+ rows, _ = self._collect(manager, monkeypatch, pages, "repositories")
+ assert rows == [{"name": "alpha"}, {"name": "beta"}]
+ # State is saved once — after the first page, pointing at the next cursor — then we stop.
+ assert [(s.next_url, s.repository) for s in manager.saved] == [(second, None)]
+
+ def test_repositories_resumes_from_saved_cursor(self, monkeypatch: Any) -> None:
+ second = f"{DOCKERHUB_BASE_URL}/v2/namespaces/acme/repositories?ordering=name&page=2&page_size=100"
+ manager = _FakeResumableManager(DockerhubResumeConfig(next_url=second))
+ # The first page URL must never be fetched on resume.
+ pages = {second: ([{"name": "beta"}], None)}
+ rows, client = self._collect(manager, monkeypatch, pages, "repositories")
+ assert rows == [{"name": "beta"}]
+ assert client.fetched == [second]
+
+ def test_tags_fan_out_injects_namespace_and_repository_name(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager()
+ pages: Mapping[str, tuple[list[dict[str, Any]], Optional[str]]] = {
+ REPOS_URL: ([{"name": "alpha"}, {"name": "beta"}], None),
+ ALPHA_TAGS_URL: ([{"name": "latest", "repository": 42}], None),
+ BETA_TAGS_URL: ([{"name": "v1"}], None),
+ }
+ rows, _ = self._collect(manager, monkeypatch, pages, "tags")
+ assert rows == [
+ {"name": "latest", "repository": 42, "namespace": "acme", "repository_name": "alpha"},
+ {"name": "v1", "namespace": "acme", "repository_name": "beta"},
+ ]
+ # State pins each completed repository so a crash re-syncs at most one repository.
+ assert [(s.repository, s.next_url) for s in manager.saved] == [("alpha", None), ("beta", None)]
+
+ def test_tags_saves_cursor_state_within_a_repository(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager()
+ alpha_page_2 = f"{DOCKERHUB_BASE_URL}/v2/namespaces/acme/repositories/alpha/tags?page=2&page_size=100"
+ pages = {
+ REPOS_URL: ([{"name": "alpha"}], None),
+ ALPHA_TAGS_URL: ([{"name": "v2"}], alpha_page_2),
+ alpha_page_2: ([{"name": "v1"}], None),
+ }
+ rows, _ = self._collect(manager, monkeypatch, pages, "tags")
+ assert [r["name"] for r in rows] == ["v2", "v1"]
+ assert [(s.repository, s.next_url) for s in manager.saved] == [
+ ("alpha", alpha_page_2),
+ ("alpha", None),
+ ]
+
+ def test_tags_resumes_from_saved_repository_and_cursor(self, monkeypatch: Any) -> None:
+ beta_page_2 = f"{DOCKERHUB_BASE_URL}/v2/namespaces/acme/repositories/beta/tags?page=2&page_size=100"
+ manager = _FakeResumableManager(DockerhubResumeConfig(next_url=beta_page_2, repository="beta"))
+ pages = {
+ REPOS_URL: ([{"name": "alpha"}, {"name": "beta"}, {"name": "gamma"}], None),
+ beta_page_2: ([{"name": "v1"}], None),
+ _tags_url("acme", "gamma"): ([{"name": "g1"}], None),
+ }
+ rows, client = self._collect(manager, monkeypatch, pages, "tags")
+ # alpha is skipped entirely; beta resumes mid-pagination; gamma starts fresh.
+ assert [(r["repository_name"], r["name"]) for r in rows] == [("beta", "v1"), ("gamma", "g1")]
+ assert ALPHA_TAGS_URL not in client.fetched
+ assert BETA_TAGS_URL not in client.fetched
+
+ def test_tags_restarts_when_resume_repository_was_deleted(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager(DockerhubResumeConfig(next_url=None, repository="deleted-repo"))
+ pages = {
+ REPOS_URL: ([{"name": "alpha"}], None),
+ ALPHA_TAGS_URL: ([{"name": "latest"}], None),
+ }
+ rows, _ = self._collect(manager, monkeypatch, pages, "tags")
+ assert [(r["repository_name"], r["name"]) for r in rows] == [("alpha", "latest")]
+
+
+class TestOrderingParams:
+ def test_repositories_url_uses_ascending_name_ordering(self) -> None:
+ # ordering=name is ascending on the repositories endpoint (verified live).
+ assert "ordering=name" in REPOS_URL
+ assert "ordering=-name" not in REPOS_URL
+
+ def test_tags_url_uses_inverted_ordering_sign(self) -> None:
+ # The tags endpoint inverts the sign: ordering=-name is ascending name (verified live).
+ assert "ordering=-name" in ALPHA_TAGS_URL
+
+
+class TestFetchPage:
+ def _session_returning(self, status_code: int, body: Any = None) -> MagicMock:
+ response = MagicMock()
+ response.status_code = status_code
+ response.ok = status_code < 400
+ response.json.return_value = body if body is not None else {"results": [], "next": None}
+ response.text = ""
+ response.raise_for_status.side_effect = (
+ requests.HTTPError(f"{status_code} error", response=response) if status_code >= 400 else None
+ )
+ session = MagicMock()
+ session.get.return_value = response
+ return session
+
+ @parameterized.expand([("rate_limited", 429), ("server_error", 500), ("bad_gateway", 503)])
+ def test_retryable_statuses_raise_retryable_error(self, _name: str, status: int) -> None:
+ session = self._session_returning(status)
+ with pytest.raises(DockerhubRetryableError):
+ _fetch_page_unwrapped(session, REPOS_URL, MagicMock())
+
+ @parameterized.expand([("forbidden", 403), ("not_found", 404)])
+ def test_client_errors_raise_for_status(self, _name: str, status: int) -> None:
+ session = self._session_returning(status)
+ with pytest.raises(requests.HTTPError):
+ _fetch_page_unwrapped(session, REPOS_URL, MagicMock())
+
+ def test_unauthorized_raises_auth_expired_when_reauth_allowed(self) -> None:
+ session = self._session_returning(401)
+ with pytest.raises(DockerhubAuthExpiredError):
+ _fetch_page_unwrapped(session, REPOS_URL, MagicMock())
+
+ def test_unauthorized_raises_for_status_when_reauth_disallowed(self) -> None:
+ session = self._session_returning(401)
+ with pytest.raises(requests.HTTPError):
+ _fetch_page_unwrapped(session, REPOS_URL, MagicMock(), allow_reauth=False)
+
+ def test_success_returns_results_and_next(self) -> None:
+ next_url = f"{REPOS_URL}&page=2"
+ body = {"count": 5, "next": next_url, "previous": None, "results": [{"name": "alpha"}]}
+ session = self._session_returning(200, body)
+ rows, returned_next = _fetch_page_unwrapped(session, REPOS_URL, MagicMock())
+ assert rows == [{"name": "alpha"}]
+ assert returned_next == next_url
+
+ def test_null_next_returns_none(self) -> None:
+ body = {"count": 1, "next": None, "previous": None, "results": [{"name": "alpha"}]}
+ session = self._session_returning(200, body)
+ _, returned_next = _fetch_page_unwrapped(session, REPOS_URL, MagicMock())
+ assert returned_next is None
+
+ @parameterized.expand([("bare_list", [{"name": "a"}]), ("missing_results", {"count": 1})])
+ def test_unexpected_payload_is_retryable(self, _name: str, body: Any) -> None:
+ session = self._session_returning(200, body)
+ with pytest.raises(DockerhubRetryableError):
+ _fetch_page_unwrapped(session, REPOS_URL, MagicMock())
+
+ @parameterized.expand(
+ [
+ ("other_host", "https://attacker.example/v2/namespaces/acme/repositories"),
+ ("http_scheme", "http://hub.docker.com/v2/namespaces/acme/repositories"),
+ ]
+ )
+ def test_non_dockerhub_url_is_rejected_before_request(self, _name: str, url: str) -> None:
+ session = self._session_returning(200)
+ with pytest.raises(ValueError):
+ _fetch_page_unwrapped(session, url, MagicMock())
+ session.get.assert_not_called()
+
+ def test_hostile_next_link_is_rejected(self) -> None:
+ body = {"next": "https://attacker.example/v2/steal", "previous": None, "results": [{"name": "alpha"}]}
+ session = self._session_returning(200, body)
+ with pytest.raises(ValueError):
+ _fetch_page_unwrapped(session, REPOS_URL, MagicMock())
+
+
+class TestClientAuth:
+ def _login_response(self, status_code: int = 200, body: Any = None) -> MagicMock:
+ response = MagicMock()
+ response.status_code = status_code
+ response.ok = status_code < 400
+ response.json.return_value = body if body is not None else {"token": "jwt-1"}
+ response.text = ""
+ response.raise_for_status.side_effect = (
+ requests.HTTPError(f"{status_code} error", response=response) if status_code >= 400 else None
+ )
+ return response
+
+ def _page_response(self, status_code: int, body: Any = None) -> MagicMock:
+ response = MagicMock()
+ response.status_code = status_code
+ response.ok = status_code < 400
+ response.json.return_value = body if body is not None else {"results": [{"name": "alpha"}], "next": None}
+ response.text = ""
+ response.raise_for_status.side_effect = (
+ requests.HTTPError(f"{status_code} error", response=response) if status_code >= 400 else None
+ )
+ return response
+
+ def _client_with_session(self, session: MagicMock) -> DockerHubClient:
+ with patch.object(dockerhub, "make_tracked_session", return_value=session):
+ return DockerHubClient("tom", "dckr_pat_token", MagicMock())
+
+ def test_login_sets_bearer_token_from_exchanged_jwt(self) -> None:
+ session = MagicMock()
+ session.headers = {}
+ session.post.return_value = self._login_response()
+ client = self._client_with_session(session)
+ client.login()
+ assert session.headers["Authorization"] == "Bearer jwt-1"
+ args, kwargs = session.post.call_args
+ assert args[0] == f"{DOCKERHUB_BASE_URL}/v2/users/login"
+ assert kwargs["json"] == {"username": "tom", "password": "dckr_pat_token"}
+
+ def test_login_failure_raises_http_error(self) -> None:
+ session = MagicMock()
+ session.headers = {}
+ session.post.return_value = self._login_response(status_code=401)
+ client = self._client_with_session(session)
+ with pytest.raises(requests.HTTPError):
+ client.login()
+
+ def test_login_without_token_in_body_is_retryable(self) -> None:
+ session = MagicMock()
+ session.post.return_value = self._login_response(body={"detail": "weird"})
+ with pytest.raises(DockerhubRetryableError):
+ _fetch_jwt_unwrapped(session, "tom", "dckr_pat_token", MagicMock())
+
+ def test_expired_jwt_triggers_single_relogin_and_retry(self) -> None:
+ session = MagicMock()
+ session.headers = {}
+ session.post.side_effect = [
+ self._login_response(body={"token": "jwt-1"}),
+ self._login_response(body={"token": "jwt-2"}),
+ ]
+ session.get.side_effect = [self._page_response(401), self._page_response(200)]
+ client = self._client_with_session(session)
+ client.login()
+
+ rows, next_url = client.get_page(REPOS_URL)
+
+ assert rows == [{"name": "alpha"}]
+ assert next_url is None
+ assert session.post.call_count == 2
+ assert session.headers["Authorization"] == "Bearer jwt-2"
+
+ def test_second_unauthorized_after_relogin_is_permanent(self) -> None:
+ session = MagicMock()
+ session.headers = {}
+ session.post.side_effect = [
+ self._login_response(body={"token": "jwt-1"}),
+ self._login_response(body={"token": "jwt-2"}),
+ ]
+ session.get.side_effect = [self._page_response(401), self._page_response(401)]
+ client = self._client_with_session(session)
+ client.login()
+
+ with pytest.raises(requests.HTTPError):
+ client.get_page(REPOS_URL)
+
+
+class TestCheckAccess:
+ def _response(self, status_code: int, body: Any = None) -> MagicMock:
+ response = MagicMock()
+ response.status_code = status_code
+ response.ok = status_code < 400
+ response.json.return_value = body if body is not None else {"token": "jwt-1"}
+ return response
+
+ def _session(self, login_response: Any, probe_response: Any = None) -> MagicMock:
+ session = MagicMock()
+ if isinstance(login_response, Exception):
+ session.post.side_effect = login_response
+ else:
+ session.post.return_value = login_response
+ if isinstance(probe_response, Exception):
+ session.get.side_effect = probe_response
+ elif probe_response is not None:
+ session.get.return_value = probe_response
+ return session
+
+ @parameterized.expand(
+ [
+ ("unauthorized", 401),
+ ("forbidden", 403),
+ ]
+ )
+ def test_login_auth_failures(self, _name: str, status: int) -> None:
+ session = self._session(self._response(status))
+ with patch.object(dockerhub, "make_tracked_session", return_value=session):
+ assert check_access("tom", "bad-token", "acme") == (status, None)
+
+ def test_login_server_error_returns_status_and_message(self) -> None:
+ session = self._session(self._response(500))
+ with patch.object(dockerhub, "make_tracked_session", return_value=session):
+ assert check_access("tom", "token", "acme") == (500, "Docker Hub returned HTTP 500")
+
+ def test_login_connection_error_maps_to_zero(self) -> None:
+ session = self._session(requests.ConnectionError("boom"))
+ with patch.object(dockerhub, "make_tracked_session", return_value=session):
+ status, message = check_access("tom", "token", "acme")
+ assert status == 0
+ assert message is not None and "boom" in message
+
+ def test_login_without_token_maps_to_zero(self) -> None:
+ session = self._session(self._response(200, body={"detail": "weird"}))
+ with patch.object(dockerhub, "make_tracked_session", return_value=session):
+ status, message = check_access("tom", "token", "acme")
+ assert status == 0
+ assert message == "Docker Hub login did not return a token"
+
+ @parameterized.expand(
+ [
+ ("reachable", 200, 200, None),
+ ("missing_namespace", 404, 404, "Docker Hub namespace 'acme' was not found"),
+ (
+ "no_namespace_access",
+ 403,
+ 403,
+ "Your personal access token does not have access to the 'acme' namespace",
+ ),
+ ]
+ )
+ def test_namespace_probe_status_mapping(
+ self, _name: str, probe_status: int, expected_status: int, expected_message: str | None
+ ) -> None:
+ session = self._session(self._response(200), self._response(probe_status))
+ with patch.object(dockerhub, "make_tracked_session", return_value=session):
+ assert check_access("tom", "token", "acme") == (expected_status, expected_message)
+
+ @parameterized.expand(
+ [
+ ("ok", 200, None, True, None),
+ ("bad_credentials", 401, None, False, "Invalid Docker Hub username or personal access token"),
+ ("missing_namespace", 200, 404, False, "Docker Hub namespace 'acme' was not found"),
+ (
+ "no_namespace_access",
+ 200,
+ 403,
+ False,
+ "Your personal access token does not have access to the 'acme' namespace",
+ ),
+ ("server_error", 500, None, False, "Docker Hub returned HTTP 500"),
+ ]
+ )
+ def test_validate_credentials(
+ self,
+ _name: str,
+ login_status: int,
+ probe_status: int | None,
+ expected_valid: bool,
+ expected_message: str | None,
+ ) -> None:
+ probe_response = self._response(probe_status) if probe_status is not None else self._response(200)
+ session = self._session(self._response(login_status), probe_response)
+ with patch.object(dockerhub, "make_tracked_session", return_value=session):
+ assert validate_credentials("tom", "token", "acme") == (expected_valid, expected_message)
+
+
+class TestDockerhubSourceResponse:
+ @parameterized.expand([(e,) for e in ENDPOINTS])
+ def test_source_response_shape(self, endpoint: str) -> None:
+ response = dockerhub_source(
+ username="tom",
+ personal_access_token="dckr_pat_token",
+ namespace="acme",
+ endpoint=endpoint,
+ logger=MagicMock(),
+ resumable_source_manager=MagicMock(),
+ )
+ assert response.name == endpoint
+ assert response.primary_keys == DOCKERHUB_ENDPOINTS[endpoint].primary_keys
+ # Repositories and tags carry mutable last_updated timestamps only; we don't partition.
+ assert response.partition_mode is None
+
+ def test_tags_primary_key_includes_parent_identifiers(self) -> None:
+ # Tag names are only unique within a repository; without the injected parent identifiers in
+ # the key, fan-out rows from different repositories would collide and corrupt merges.
+ assert DOCKERHUB_ENDPOINTS["tags"].primary_keys == ["namespace", "repository_name", "name"]
+
+ def test_repositories_primary_key_is_namespace_scoped(self) -> None:
+ assert DOCKERHUB_ENDPOINTS["repositories"].primary_keys == ["namespace", "name"]
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/dockerhub/tests/test_dockerhub_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/dockerhub/tests/test_dockerhub_source.py
new file mode 100644
index 000000000000..fcf28e4b6047
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/dockerhub/tests/test_dockerhub_source.py
@@ -0,0 +1,145 @@
+import pytest
+from unittest import mock
+
+from parameterized import parameterized
+
+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.dockerhub.dockerhub import DockerhubResumeConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.dockerhub.settings import ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.dockerhub.source import DockerhubSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import DockerhubSourceConfig
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+class TestDockerhubSource:
+ def setup_method(self) -> None:
+ self.source = DockerhubSource()
+ self.team_id = 123
+ self.config = DockerhubSourceConfig(username="tom", personal_access_token="dckr_pat_token")
+
+ def test_source_type(self) -> None:
+ assert self.source.source_type == ExternalDataSourceType.DOCKERHUB
+
+ def test_get_source_config(self) -> None:
+ config = self.source.get_source_config
+ assert config.name.value == "Dockerhub"
+ assert config.label == "Docker Hub"
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/dockerhub"
+
+ field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]
+ assert field_names == ["username", "personal_access_token", "namespace"]
+
+ def test_personal_access_token_field_is_secret_password(self) -> None:
+ config = self.source.get_source_config
+ field = next(
+ f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "personal_access_token"
+ )
+ assert field.type == SourceFieldInputConfigType.PASSWORD
+ assert field.secret is True
+ assert field.required is True
+
+ def test_namespace_field_is_optional(self) -> None:
+ config = self.source.get_source_config
+ field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "namespace")
+ assert field.required is False
+ assert field.secret is False
+
+ def test_namespace_is_a_connection_host_field(self) -> None:
+ # The stored token pulls data from whatever namespace is configured, so changing it must force
+ # secret re-entry — otherwise an editor could retarget the preserved token at another org.
+ assert self.source.connection_host_fields == ["namespace"]
+
+ def test_lists_tables_without_credentials(self) -> None:
+ assert self.source.lists_tables_without_credentials is True
+
+ def test_get_schemas_covers_all_endpoints_as_full_refresh(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id)
+ assert {s.name for s in schemas} == set(ENDPOINTS)
+ assert all(s.supports_incremental is False for s in schemas)
+ assert all(s.supports_append is False for s in schemas)
+ assert all(s.incremental_fields == [] for s in schemas)
+
+ def test_get_schemas_filtered_by_names(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["tags"])
+ assert len(schemas) == 1
+ assert schemas[0].name == "tags"
+
+ def test_get_schemas_filtered_unknown_name_returns_empty(self) -> None:
+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []
+
+ def test_documented_tables_render_for_public_docs(self) -> None:
+ tables = self.source.get_documented_tables()
+ assert {t["name"] for t in tables} == set(ENDPOINTS)
+ assert all("Full refresh" in t["sync_methods"] for t in tables)
+
+ @parameterized.expand(
+ [
+ ("401 Client Error: Unauthorized for url: https://hub.docker.com/v2/users/login",),
+ ("403 Client Error: Forbidden for url: https://hub.docker.com/v2/namespaces/tom/repositories",),
+ ]
+ )
+ def test_non_retryable_errors_match_auth_failures(self, observed_error: str) -> None:
+ non_retryable = self.source.get_non_retryable_errors()
+ assert any(key in observed_error for key in non_retryable)
+
+ @parameterized.expand(
+ [
+ ("500 Server Error: Internal Server Error for url: https://hub.docker.com/v2/users/login",),
+ ("429 Client Error: Too Many Requests for url: https://hub.docker.com/v2/namespaces/tom/repositories",),
+ ]
+ )
+ def test_non_retryable_errors_ignore_transient(self, unrelated_error: str) -> None:
+ non_retryable = self.source.get_non_retryable_errors()
+ assert not any(key in unrelated_error for key in non_retryable)
+
+ @parameterized.expand(
+ [
+ ("blank_defaults_to_username", None, "tom"),
+ ("empty_defaults_to_username", "", "tom"),
+ ("whitespace_defaults_to_username", " ", "tom"),
+ ("explicit_namespace_wins", "my-org", "my-org"),
+ ("explicit_namespace_is_trimmed", " my-org ", "my-org"),
+ ]
+ )
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.dockerhub.source.validate_credentials"
+ )
+ def test_validate_credentials_resolves_namespace(
+ self, _name: str, namespace: str | None, expected: str, mock_validate: mock.MagicMock
+ ) -> None:
+ mock_validate.return_value = (True, None)
+ config = DockerhubSourceConfig(username="tom", personal_access_token="dckr_pat_token", namespace=namespace)
+ result = self.source.validate_credentials(config, self.team_id)
+ assert result == (True, None)
+ mock_validate.assert_called_once_with("tom", "dckr_pat_token", expected)
+
+ def test_get_resumable_source_manager_binds_resume_config(self) -> None:
+ manager = self.source.get_resumable_source_manager(mock.MagicMock())
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is DockerhubResumeConfig
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.dockerhub.source.dockerhub_source")
+ def test_source_for_pipeline_plumbs_arguments(self, mock_source: mock.MagicMock) -> None:
+ inputs = mock.MagicMock()
+ inputs.schema_name = "repositories"
+ manager = mock.MagicMock()
+ config = DockerhubSourceConfig(username="tom", personal_access_token="dckr_pat_token", namespace="my-org")
+
+ self.source.source_for_pipeline(config, manager, inputs)
+
+ mock_source.assert_called_once()
+ kwargs = mock_source.call_args.kwargs
+ assert kwargs["username"] == "tom"
+ assert kwargs["personal_access_token"] == "dckr_pat_token"
+ assert kwargs["namespace"] == "my-org"
+ assert kwargs["endpoint"] == "repositories"
+ assert kwargs["resumable_source_manager"] is manager
+
+ def test_source_for_pipeline_rejects_unknown_schema(self) -> None:
+ inputs = mock.MagicMock()
+ inputs.schema_name = "not_a_table"
+ with pytest.raises(ValueError, match="Unknown Docker Hub schema 'not_a_table'"):
+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)
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 16109767bf78..04a6c90dedbe 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
@@ -1038,7 +1038,9 @@ class DoItSourceConfig(config.Config):
@config.config
class DockerhubSourceConfig(config.Config):
- pass
+ username: str
+ personal_access_token: str
+ namespace: str | None = None
@config.config