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(warehouse-sources): add dockerhub org and audit log tables (#105919)

Tom Owers30ec856468c9
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
index cd4398264490..4d8bd567acb2 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
@@ -2559,18 +2559,18 @@ Note: Conversations are synced via /conversation_export rather than the paged co
## Dockerhub — gaps
-Today (2): `repositories`, `tags`
+Today (6): `repositories`, `tags`, `org_members`, `org_groups`, `audit_logs`, `audit_log_actions`
Diffed against: <https://docs.docker.com/reference/api/hub/latest.yaml>
-- [ ] `GET /v2/orgs/{org_name}/members` — org membership roster — the lookup that resolves the creator/last_updater usernames already present on repositories (high)
-- [ ] `GET /v2/auditlogs/{account}` — audit log event stream (pushes, permission changes, deletions); the only event-shaped table in the Hub API (high)
+- [x] `GET /v2/orgs/{org_name}/members` — org membership roster — the lookup that resolves the creator/last_updater usernames already present on repositories (high)
+- [x] `GET /v2/auditlogs/{account}` — audit log event stream (pushes, permission changes, deletions); the only event-shaped table in the Hub API (high)
- [ ] `GET /v2/orgs/{org_name}/groups/{group_name}/members` — team↔user membership junction for access analysis (medium)
-- [ ] `GET /v2/orgs/{org_name}/groups` — team lookup that group membership rows point at (medium)
-- [ ] `GET /v2/auditlogs/{account}/actions` — lookup enumerating audit action types for categorizing log rows (medium)
+- [x] `GET /v2/orgs/{org_name}/groups` — team lookup that group membership rows point at (medium)
+- [x] `GET /v2/auditlogs/{account}/actions` — lookup enumerating audit action types for categorizing log rows (medium)
- [ ] `GET /v2/namespaces/{namespace}/pulls (DVP Data API)` — per-repo pull counts over time — the headline usage metric, but only available to Docker Verified Publishers (low)
-Note: The Hub source is namespace-scoped (namespace + repositories fan-out to tags), so the two tables are proportionate for that scope; the gaps are org-scoped endpoints in the same spec. Pull analytics live in a separate spec (https://docs.docker.com/reference/api/dvp/latest.yaml) gated behind Verified Publisher status. Access-token, SCIM schema, and org-settings endpoints were excluded as plumbing.
+Note: The org-scoped endpoints are now covered; they only return data when the configured namespace is an organization and the token belongs to an owner, so `get_endpoint_permissions` reports them as unavailable on a personal namespace. The remaining group-membership junction needs a second fan-out level over `org_groups`. Pull analytics live in a separate spec (https://docs.docker.com/reference/api/dvp/latest.yaml) gated behind Verified Publisher status. Access-token, SCIM schema, and org-settings endpoints were excluded as plumbing.
## Docuseal — adequate
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
index 8617e244023d..84f431b2ed46 100644
--- 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
@@ -50,4 +50,66 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"digest": "Content digest of the tag's manifest.",
},
},
+ "org_members": {
+ "description": "A member of the configured Docker Hub organization, including pending invitees.",
+ "docs_url": "https://docs.docker.com/reference/api/hub/latest/#tag/orgs/operation/getV2OrgsByOrgNameMembers",
+ "columns": {
+ "id": "Identifier of the user account, the trimmed form of its UUID.",
+ "username": "Docker Hub username of the member.",
+ "full_name": "Full name on the member's Docker Hub profile.",
+ "email": "Email address of the member.",
+ "role": "The member's role in the organization: Owner, Editor, Member, or Invitee for a pending invite.",
+ "groups": "Names of the groups (teams) the member belongs to.",
+ "is_guest": "Whether the member's email address is outside the organization's verified domains.",
+ "type": "Type of the account, either User or Org.",
+ "company": "Company on the member's Docker Hub profile.",
+ "location": "Location on the member's Docker Hub profile.",
+ "date_joined": "Timestamp when the account joined Docker Hub.",
+ "profile_url": "URL of the member's Docker Hub profile.",
+ "gravatar_email": "Email address the member's avatar is resolved from.",
+ "gravatar_url": "URL of the member's avatar image.",
+ "primary_email": "The member's primary email address. Deprecated by Docker Hub in favor of email.",
+ "last_logged_in_at": "Timestamp of the member's last login. Only returned to organizations with insights enabled.",
+ "last_seen_at": "Timestamp the member was last seen. Only returned to organizations with insights enabled.",
+ "last_desktop_version": "Last Docker Desktop version the member used. Only returned to organizations with insights enabled.",
+ },
+ },
+ "org_groups": {
+ "description": "A group (team) in the configured Docker Hub organization.",
+ "docs_url": "https://docs.docker.com/reference/api/hub/latest/#tag/groups/operation/getV2OrgsByOrgNameGroups",
+ "columns": {
+ "id": "Numeric identifier of the group.",
+ "uuid": "UUID of the group.",
+ "name": "Name of the group, unique within its organization.",
+ "description": "Free-text description of the group.",
+ "member_count": "Number of members in the group.",
+ "role": "Role assigned to the group: a core role (owner, editor, member) or the name of a custom role.",
+ },
+ },
+ "audit_logs": {
+ "description": "An audit log event for the configured Docker Hub organization, such as an image push, a permission change, or a deletion.",
+ "docs_url": "https://docs.docker.com/reference/api/hub/latest/#tag/audit-logs/operation/AuditLogs_ListAuditLogs",
+ "columns": {
+ "id": "A synthetic identifier PostHog derives from the event's fields, since Docker Hub returns no event id.",
+ "account": "Namespace the event belongs to.",
+ "action": "Action that was performed, e.g. repo.tag.push. Joins to audit_log_actions.qualified_name.",
+ "action_description": "Human-readable sentence describing what happened.",
+ "actor": "Username of the person who triggered the event.",
+ "name": "Subject of the event: the repository name, the organization name, or the username, depending on the action.",
+ "data": "Action-specific details, such as the pushed tag and its digest.",
+ "timestamp": "Timestamp when the event happened.",
+ },
+ },
+ "audit_log_actions": {
+ "description": "The catalog of audit log action types, used to categorize and filter audit log events.",
+ "docs_url": "https://docs.docker.com/reference/api/hub/latest/#tag/audit-logs/operation/AuditLogs_ListAuditActions",
+ "columns": {
+ "action_group": "Group the action belongs to, e.g. repo or org. Added by PostHog from the response's action map key.",
+ "action_group_label": "Human-readable name of the action group, e.g. Repository. Added by PostHog to every row.",
+ "name": "Name of the action within its group, e.g. tag.push.",
+ "qualified_name": "The group and name joined with a dot, e.g. repo.tag.push. Added by PostHog, and the form audit_logs.action uses.",
+ "label": "Human-readable name of the action, e.g. Tag Pushed.",
+ "description": "Explanation of when the action is recorded.",
+ },
+ },
}
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
index c25cc45745ca..c9b71a48464a 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/dockerhub/dockerhub.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/dockerhub/dockerhub.py
@@ -1,16 +1,23 @@
-import dataclasses
-from collections.abc import Iterator
+import hashlib
+import datetime
+from collections.abc import Callable, Iterator
from typing import Any, Optional
from urllib.parse import quote, urlencode, urlsplit
+import orjson
import requests
from structlog.types import FilteringBoundLogger
from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+from posthog.dataclasses import frozen
+
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.common.typings import SourceResponse
-from products.warehouse_sources.backend.temporal.data_imports.sources.dockerhub.settings import DOCKERHUB_ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.dockerhub.settings import (
+ DOCKERHUB_ENDPOINTS,
+ ORG_SCOPED_ENDPOINTS,
+)
# Management API host (hub.docker.com), distinct from the OCI registry API (registry.hub.docker.com).
DOCKERHUB_BASE_URL = "https://hub.docker.com"
@@ -43,7 +50,7 @@ class DockerhubAuthExpiredError(Exception):
pass
+@frozen
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.
@@ -51,6 +58,9 @@ class DockerhubResumeConfig:
# 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
+ # Audit logs only: the next page number to fetch. That endpoint returns no `next` link, so its
+ # cursor is the page number we would ask for next.
+ page: int | None = None
def _repositories_url(namespace: str) -> str:
@@ -60,6 +70,31 @@ def _repositories_url(namespace: str) -> str:
return f"{DOCKERHUB_BASE_URL}/v2/namespaces/{quote(namespace)}/repositories?{query}"
+def _org_members_url(namespace: str, page_size: int = PAGE_SIZE) -> str:
+ # The org endpoints take no ordering parameter. Both are full refresh, so only page-boundary
+ # stability matters and we cannot improve on the server's own order.
+ query = urlencode({"page_size": page_size})
+ return f"{DOCKERHUB_BASE_URL}/v2/orgs/{quote(namespace)}/members?{query}"
+
+
+def _org_groups_url(namespace: str, page_size: int = PAGE_SIZE) -> str:
+ query = urlencode({"page_size": page_size})
+ return f"{DOCKERHUB_BASE_URL}/v2/orgs/{quote(namespace)}/groups?{query}"
+
+
+def _audit_logs_url(namespace: str, page: int, since: Optional[str], page_size: int = PAGE_SIZE) -> str:
+ params: dict[str, Any] = {"page_size": page_size, "page": page}
+ if since:
+ # `from` is the endpoint's server-side lower bound on `timestamp`, which is what makes an
+ # incremental sync cheaper than a full one.
+ params["from"] = since
+ return f"{DOCKERHUB_BASE_URL}/v2/auditlogs/{quote(namespace)}?{urlencode(params)}"
+
+
+def _audit_log_actions_url(namespace: str) -> str:
+ return f"{DOCKERHUB_BASE_URL}/v2/auditlogs/{quote(namespace)}/actions"
+
+
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.
@@ -101,18 +136,12 @@ def _fetch_jwt(
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(
+def _request_json(
session: requests.Session,
url: str,
logger: FilteringBoundLogger,
- allow_reauth: bool = True,
-) -> tuple[list[dict[str, Any]], Optional[str]]:
+ allow_reauth: bool,
+) -> Any:
# `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.
@@ -130,7 +159,22 @@ def _fetch_page(
logger.error(f"Docker Hub API error: status={response.status_code}, body={response.text}, url={url}")
response.raise_for_status()
- data = response.json()
+ return response.json()
+
+
+@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]]:
+ data = _request_json(session, url, logger, allow_reauth)
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__}")
@@ -142,6 +186,28 @@ def _fetch_page(
return data["results"], None
+@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_object(
+ session: requests.Session,
+ url: str,
+ logger: FilteringBoundLogger,
+ allow_reauth: bool = True,
+) -> dict[str, Any]:
+ """Fetch an endpoint that answers with a bare object instead of the `results`/`next` envelope.
+
+ The audit log endpoints are the two that do: events come back under `logs` with no next link,
+ and the action catalog comes back under `actions` as a map."""
+ data = _request_json(session, url, logger, allow_reauth)
+ if not isinstance(data, dict):
+ raise DockerhubRetryableError(f"Docker Hub returned an unexpected payload for {url}: {type(data).__name__}")
+ return data
+
+
class DockerHubClient:
def __init__(self, username: str, personal_access_token: str, logger: FilteringBoundLogger) -> None:
self._username = username
@@ -166,26 +232,38 @@ class DockerHubClient:
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]]:
+ def _with_reauth(self, fetch: Callable[[bool], Any]) -> Any:
try:
- return _fetch_page(self._session, url, self._logger)
+ return fetch(True)
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)
+ return fetch(False)
+
+ def get_page(self, url: str) -> tuple[list[dict[str, Any]], Optional[str]]:
+ return self._with_reauth(
+ lambda allow_reauth: _fetch_page(self._session, url, self._logger, allow_reauth=allow_reauth)
+ )
+
+ def get_object(self, url: str) -> dict[str, Any]:
+ return self._with_reauth(
+ lambda allow_reauth: _fetch_object(self._session, url, self._logger, allow_reauth=allow_reauth)
+ )
-def _repository_pages(
+def _cursor_pages(
client: DockerHubClient,
- namespace: str,
+ initial_url: str,
+ resource: str,
logger: FilteringBoundLogger,
resumable_source_manager: ResumableSourceManager[DockerhubResumeConfig],
) -> Iterator[list[dict[str, Any]]]:
+ """Walk a `results`/`next` list endpoint, saving the next link so a crash can resume on it."""
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)
+ url: Optional[str] = resume.next_url if (resume and resume.next_url) else initial_url
if resume and resume.next_url:
- logger.debug(f"Docker Hub: resuming repositories from {url}")
+ logger.debug(f"Docker Hub: resuming {resource} from {url}")
while url:
items, next_url = client.get_page(url)
@@ -260,6 +338,97 @@ def _tag_pages(
resumable_source_manager.save_state(DockerhubResumeConfig(next_url=None, repository=repository))
+def _audit_log_row(row: dict[str, Any]) -> dict[str, Any]:
+ # Audit events carry no identifier of their own, so key them by a hash of their own contents.
+ # A row re-read at the incremental window boundary then merges onto itself instead of landing
+ # as a second row. Two indistinguishable events collapse into one, which is the cost of having
+ # a stable key at all.
+ body = {key: value for key, value in row.items() if key != "id"}
+ row_id = hashlib.sha256(orjson.dumps(body, option=orjson.OPT_SORT_KEYS, default=str)).hexdigest()
+ return {**body, "id": row_id}
+
+
+def _audit_log_pages(
+ client: DockerHubClient,
+ namespace: str,
+ since: Optional[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
+ page = resume.page if (resume and resume.page) else 1
+ if page > 1:
+ logger.debug(f"Docker Hub: resuming audit logs from page {page}")
+
+ while True:
+ data = client.get_object(_audit_logs_url(namespace, page, since))
+ logs = data.get("logs")
+ if logs is None:
+ logs = []
+ if not isinstance(logs, list):
+ raise DockerhubRetryableError(
+ f"Docker Hub returned an unexpected audit log payload on page {page}: {type(logs).__name__}"
+ )
+
+ if logs:
+ yield [_audit_log_row(row) for row in logs]
+
+ # The endpoint returns neither a next link nor a total count, so a short page is the only
+ # end-of-collection signal it gives us.
+ if len(logs) < PAGE_SIZE:
+ break
+
+ page += 1
+ # Save AFTER yielding so a crash re-fetches from the next page (already-yielded pages are
+ # persisted); merge dedupes any re-pulled page on the primary key.
+ resumable_source_manager.save_state(DockerhubResumeConfig(page=page))
+
+
+def _audit_log_action_rows(client: DockerHubClient, namespace: str) -> Iterator[list[dict[str, Any]]]:
+ # The action catalog answers in one unpaginated response, as a map of group name to that
+ # group's label and actions. Flatten it so each action becomes a row.
+ data = client.get_object(_audit_log_actions_url(namespace))
+ groups = data.get("actions")
+ if not isinstance(groups, dict):
+ raise DockerhubRetryableError(
+ f"Docker Hub returned an unexpected audit action payload: {type(groups).__name__}"
+ )
+
+ rows: list[dict[str, Any]] = []
+ for group, body in groups.items():
+ if not isinstance(body, dict):
+ continue
+ for action in body.get("actions") or []:
+ name = action.get("name")
+ rows.append(
+ {
+ "action_group": group,
+ "action_group_label": body.get("label"),
+ "name": name,
+ # An audit log event names its action as "<group>.<name>" (the `repo` group's
+ # `tag.push` is logged as `repo.tag.push`), so the catalog needs the joined
+ # form to be usable as a lookup on the event stream.
+ "qualified_name": f"{group}.{name}" if name else None,
+ "label": action.get("label"),
+ "description": action.get("description"),
+ }
+ )
+
+ if rows:
+ yield rows
+
+
+def format_incremental_start(value: Any) -> Optional[str]:
+ """Render the stored watermark as the RFC 3339 instant the audit log `from` parameter takes."""
+ if value is None:
+ return None
+ if isinstance(value, datetime.datetime):
+ moment = value if value.tzinfo else value.replace(tzinfo=datetime.UTC)
+ return moment.astimezone(datetime.UTC).strftime("%Y-%m-%dT%H:%M:%SZ")
+ text = str(value).strip()
+ return text or None
+
+
def get_rows(
username: str,
personal_access_token: str,
@@ -267,6 +436,7 @@ def get_rows(
endpoint: str,
logger: FilteringBoundLogger,
resumable_source_manager: ResumableSourceManager[DockerhubResumeConfig],
+ incremental_start: Optional[str] = None,
) -> Iterator[list[dict[str, Any]]]:
if endpoint not in DOCKERHUB_ENDPOINTS:
raise ValueError(f"Unknown Docker Hub endpoint '{endpoint}'")
@@ -275,7 +445,15 @@ def get_rows(
client.login()
if endpoint == "repositories":
- yield from _repository_pages(client, namespace, logger, resumable_source_manager)
+ yield from _cursor_pages(client, _repositories_url(namespace), "repositories", logger, resumable_source_manager)
+ elif endpoint == "org_members":
+ yield from _cursor_pages(client, _org_members_url(namespace), "org members", logger, resumable_source_manager)
+ elif endpoint == "org_groups":
+ yield from _cursor_pages(client, _org_groups_url(namespace), "org groups", logger, resumable_source_manager)
+ elif endpoint == "audit_logs":
+ yield from _audit_log_pages(client, namespace, incremental_start, logger, resumable_source_manager)
+ elif endpoint == "audit_log_actions":
+ yield from _audit_log_action_rows(client, namespace)
else:
yield from _tag_pages(client, namespace, logger, resumable_source_manager)
@@ -287,6 +465,7 @@ def dockerhub_source(
endpoint: str,
logger: FilteringBoundLogger,
resumable_source_manager: ResumableSourceManager[DockerhubResumeConfig],
+ incremental_start: Optional[str] = None,
) -> SourceResponse:
config = DOCKERHUB_ENDPOINTS[endpoint]
@@ -299,10 +478,15 @@ def dockerhub_source(
endpoint=endpoint,
logger=logger,
resumable_source_manager=resumable_source_manager,
+ incremental_start=incremental_start,
),
primary_keys=config.primary_keys,
- partition_count=1,
- partition_size=1,
+ sort_mode=config.sort_mode,
+ partition_mode="datetime" if config.partition_key else None,
+ partition_format="month" if config.partition_key else None,
+ partition_keys=[config.partition_key] if config.partition_key else None,
+ partition_count=None if config.partition_key else 1,
+ partition_size=None if config.partition_key else 1,
)
@@ -324,26 +508,41 @@ def _unexpected_status_message(status_code: int) -> str:
)
+@frozen
+class ProbeSessions:
+ """The two tracked sessions a credential probe uses.
+
+ Credentials are exchanged on `login`, which has sample capture disabled, because the login
+ response body carries a JWT under the generic `token` key that the name-based sample scrubbers
+ don't redact. The JWT then rides in the Authorization header, redacted by name, on `data`."""
+
+ login: requests.Session
+ data: requests.Session
+
+
+def _build_probe_sessions(personal_access_token: str) -> ProbeSessions:
+ return ProbeSessions(
+ login=make_tracked_session(
+ headers={"Accept": "application/json"},
+ redact_values=(personal_access_token,),
+ capture=False,
+ ),
+ data=make_tracked_session(
+ headers={"Accept": "application/json"},
+ redact_values=(personal_access_token,),
+ ),
+ )
+
+
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,),
- )
+ sessions = _build_probe_sessions(personal_access_token)
try:
- response = login_session.post(
+ response = sessions.login.post(
f"{DOCKERHUB_BASE_URL}{LOGIN_PATH}",
json={"username": username, "password": personal_access_token},
timeout=15,
@@ -364,7 +563,7 @@ def check_access(username: str, personal_access_token: str, namespace: str) -> t
# Probe the configured namespace so a typo'd org name fails at connect time, not sync time.
try:
- probe = session.get(
+ probe = sessions.data.get(
f"{DOCKERHUB_BASE_URL}/v2/namespaces/{quote(namespace)}/repositories?{urlencode({'page_size': 1})}",
headers={"Authorization": f"Bearer {token}"},
timeout=15,
@@ -394,3 +593,76 @@ def validate_credentials(username: str, personal_access_token: str, namespace: s
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"
+
+
+def _permission_probe_url(endpoint: str, namespace: str) -> str:
+ if endpoint == "org_members":
+ return _org_members_url(namespace, page_size=1)
+ if endpoint == "org_groups":
+ return _org_groups_url(namespace, page_size=1)
+ if endpoint == "audit_log_actions":
+ return _audit_log_actions_url(namespace)
+ return _audit_logs_url(namespace, page=1, since=None, page_size=1)
+
+
+def _org_scope_reason(namespace: str, status_code: int) -> str:
+ if status_code == 404:
+ return (
+ f"Docker Hub returned no organization named '{namespace}'. This table needs the namespace "
+ "to be an organization that your personal access token can read."
+ )
+ return (
+ f"Your personal access token cannot read organization data for '{namespace}'. "
+ "Docker Hub returns it only to a token belonging to an owner of that organization."
+ )
+
+
+def check_endpoint_access(
+ username: str, personal_access_token: str, namespace: str, endpoints: list[str]
+) -> dict[str, str | None]:
+ """Report which endpoints the configured namespace and token can read. ``None`` = reachable.
+
+ The org and audit log endpoints answer only for an organization namespace, and only for a
+ token that belongs to an owner of it. A source pointed at a personal namespace can still sync
+ repositories and tags, so saying which tables are unavailable lets the user deselect them
+ instead of finding out through a failed sync.
+ """
+ permissions: dict[str, str | None] = dict.fromkeys(endpoints)
+ probes = [endpoint for endpoint in endpoints if endpoint in ORG_SCOPED_ENDPOINTS]
+ if not probes:
+ return permissions
+
+ sessions = _build_probe_sessions(personal_access_token)
+ token: Any = None
+ try:
+ response = sessions.login.post(
+ f"{DOCKERHUB_BASE_URL}{LOGIN_PATH}",
+ json={"username": username, "password": personal_access_token},
+ timeout=15,
+ )
+ if response.ok:
+ body = response.json()
+ token = body.get("token") if isinstance(body, dict) else None
+ except Exception:
+ token = None
+
+ # A rejected credential or an unreachable API is not a missing permission, and this check must
+ # never block the schema picker. `validate_credentials` is what reports those.
+ if not isinstance(token, str) or not token:
+ return permissions
+
+ for endpoint in probes:
+ try:
+ probe = sessions.data.get(
+ _permission_probe_url(endpoint, namespace),
+ headers={"Authorization": f"Bearer {token}"},
+ timeout=15,
+ )
+ except Exception:
+ # A throttle, a 5xx or a network blip is transient, so leave the endpoint reported as
+ # reachable rather than telling the user to change a setting that is already right.
+ continue
+ if probe.status_code in (403, 404):
+ permissions[endpoint] = _org_scope_reason(namespace, probe.status_code)
+
+ return permissions
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
index 46ade97bf907..e2d23a1e07d1 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/dockerhub/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/dockerhub/settings.py
@@ -1,23 +1,63 @@
-from dataclasses import dataclass, field
+from dataclasses import field
+from typing import Optional
+from posthog.dataclasses import frozen
-@dataclass
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import incremental_field
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SortMode
+from products.warehouse_sources.backend.types import IncrementalField
+
+
+@frozen
class DockerhubEndpointConfig:
name: str
primary_keys: list[str] = field(default_factory=lambda: ["id"])
+ incremental_fields: list[IncrementalField] = field(default_factory=list)
+ sort_mode: SortMode = "asc"
+ partition_key: Optional[str] = None
+ """A STABLE field to partition on. Never an updated_at-style field, which would rewrite
+ partitions on every sync."""
+ org_scoped: bool = False
+ """Reads from /v2/orgs or /v2/auditlogs, which only answer for an organization namespace."""
# 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.
+# Only the audit log carries a server-side time filter (`from`/`to`); the repository, tag, member
+# and group endpoints expose no updated_after/since parameter, so they are full refresh only.
+# 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, because 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"]),
+ "org_members": DockerhubEndpointConfig(name="org_members", primary_keys=["id"], org_scoped=True),
+ "org_groups": DockerhubEndpointConfig(name="org_groups", primary_keys=["id"], org_scoped=True),
+ "audit_logs": DockerhubEndpointConfig(
+ name="audit_logs",
+ # Audit events carry no id of their own, so the transport hashes each row's contents into
+ # one. See `_audit_log_row`.
+ primary_keys=["id"],
+ incremental_fields=[incremental_field("timestamp")],
+ # The audit log endpoint documents no ordering and takes no sort parameter, so we cannot
+ # claim rows arrive oldest-first. "desc" is the safe reading of an unknown order, because
+ # the pipeline then commits the watermark once at the end of the run from the highest
+ # timestamp it saw, instead of checkpointing each batch as if the stream were ascending.
+ sort_mode="desc",
+ partition_key="timestamp",
+ org_scoped=True,
+ ),
+ "audit_log_actions": DockerhubEndpointConfig(
+ name="audit_log_actions",
+ # Action names are unique within their group, not across the whole catalog.
+ primary_keys=["action_group", "name"],
+ org_scoped=True,
+ ),
}
ENDPOINTS = tuple(DOCKERHUB_ENDPOINTS.keys())
-INCREMENTAL_FIELDS: dict[str, list[dict[str, str]]] = {}
+ORG_SCOPED_ENDPOINTS = tuple(name for name, config in DOCKERHUB_ENDPOINTS.items() if config.org_scoped)
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in DOCKERHUB_ENDPOINTS.items() if config.incremental_fields
+}
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 50b56901f1c1..042660201356 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
@@ -13,16 +13,22 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.can
)
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.common.schema import (
+ SourceSchema,
+ build_endpoint_schemas,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponse
from products.warehouse_sources.backend.temporal.data_imports.sources.dockerhub.dockerhub import (
DockerhubResumeConfig,
+ check_endpoint_access,
dockerhub_source,
+ format_incremental_start,
validate_credentials,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.dockerhub.settings import (
DOCKERHUB_ENDPOINTS,
ENDPOINTS,
+ INCREMENTAL_FIELDS,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.dockerhub import (
DockerhubSourceConfig,
@@ -62,9 +68,11 @@ class DockerhubSource(ResumableSource[DockerhubSourceConfig, DockerhubResumeConf
category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,
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.
+ caption="""Enter your Docker Hub username and a personal access token to pull your container repositories, tags and organization activity 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.
+
+The member, group and audit log tables read organization data, so they need the namespace to be an organization and the token to belong to one of its owners.
""",
iconPath="/static/services/dockerhub.png",
docsUrl="https://posthog.com/docs/cdp/sources/dockerhub",
@@ -122,21 +130,21 @@ You can create a personal access token with **Read** access under **Account sett
force_refresh: bool = False,
api_version: str | None = None,
) -> 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
+ # Only the audit log takes a server-side time filter, so it is the one endpoint with an
+ # incremental cursor. Merge only: append would duplicate the boundary rows that each
+ # incremental window re-reads.
+ return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names, merge_only=("audit_logs",))
+
+ def get_endpoint_permissions(
+ self,
+ config: DockerhubSourceConfig,
+ team_id: int,
+ endpoints: list[str],
+ api_version: str | None = None,
+ ) -> dict[str, str | None]:
+ return check_endpoint_access(
+ config.username, config.personal_access_token, _namespace_for_config(config), endpoints
+ )
def validate_credentials(
self,
@@ -145,8 +153,9 @@ You can create a personal access token with **Read** access under **Account sett
schema_name: Optional[str] = None,
api_version: str | None = 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.
+ # Source creation only has to prove the token is genuine and the namespace exists. Per-table
+ # access is reported by `get_endpoint_permissions`, so one missing org scope does not block
+ # a source that only wants repositories and tags.
return validate_credentials(config.username, config.personal_access_token, _namespace_for_config(config))
def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[DockerhubResumeConfig]:
@@ -168,4 +177,7 @@ You can create a personal access token with **Read** access under **Account sett
endpoint=inputs.schema_name,
logger=inputs.logger,
resumable_source_manager=resumable_source_manager,
+ incremental_start=format_incremental_start(inputs.db_incremental_field_last_value)
+ if inputs.should_use_incremental_field
+ else None,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/dockerhub/tests/test_dockerhub.py b/products/warehouse_sources/backend/temporal/data_imports/sources/dockerhub/tests/test_dockerhub.py
index b76a7670ad96..deab32fe9dec 100644
--- 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
@@ -1,4 +1,5 @@
from collections.abc import Mapping
+from datetime import UTC, datetime, timedelta, timezone
from typing import Any, Optional
import pytest
@@ -10,29 +11,51 @@ 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,
+ PAGE_SIZE,
DockerhubAuthExpiredError,
DockerHubClient,
DockerhubResumeConfig,
DockerhubRetryableError,
+ _audit_logs_url,
+ _org_groups_url,
+ _org_members_url,
_repositories_url,
_tags_url,
check_access,
+ check_endpoint_access,
dockerhub_source,
+ format_incremental_start,
get_rows,
validate_credentials,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.dockerhub.settings import (
DOCKERHUB_ENDPOINTS,
ENDPOINTS,
+ ORG_SCOPED_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]
+_fetch_object_unwrapped = dockerhub._fetch_object.__wrapped__ # type: ignore[attr-defined]
REPOS_URL = _repositories_url("acme")
ALPHA_TAGS_URL = _tags_url("acme", "alpha")
BETA_TAGS_URL = _tags_url("acme", "beta")
+MEMBERS_URL = _org_members_url("acme")
+GROUPS_URL = _org_groups_url("acme")
+ACTIONS_URL = f"{DOCKERHUB_BASE_URL}/v2/auditlogs/acme/actions"
+
+
+def _audit_page(page: int, since: str | None = None) -> str:
+ return _audit_logs_url("acme", page, since)
+
+
+def _audit_events(count: int, *, action: str = "repo.tag.push") -> list[dict[str, Any]]:
+ return [
+ {"account": "acme", "action": action, "actor": "tom", "timestamp": f"2026-01-01T00:{i:02d}:00Z"}
+ for i in range(count)
+ ]
class _FakeResumableManager:
@@ -51,8 +74,13 @@ class _FakeResumableManager:
class _FakeClient:
- def __init__(self, pages: Mapping[str, tuple[list[dict[str, Any]], Optional[str]]]) -> None:
+ def __init__(
+ self,
+ pages: Mapping[str, tuple[list[dict[str, Any]], Optional[str]]],
+ objects: Mapping[str, dict[str, Any]] | None = None,
+ ) -> None:
self._pages = pages
+ self._objects = objects or {}
self.fetched: list[str] = []
self.login_calls = 0
@@ -63,6 +91,10 @@ class _FakeClient:
self.fetched.append(url)
return self._pages[url]
+ def get_object(self, url: str) -> dict[str, Any]:
+ self.fetched.append(url)
+ return self._objects[url]
+
class TestGetRows:
@staticmethod
@@ -71,8 +103,10 @@ class TestGetRows:
monkeypatch: Any,
pages: Mapping[str, tuple[list[dict[str, Any]], Optional[str]]],
endpoint: str,
+ objects: Mapping[str, dict[str, Any]] | None = None,
+ incremental_start: str | None = None,
) -> tuple[list[dict[str, Any]], _FakeClient]:
- client = _FakeClient(pages)
+ client = _FakeClient(pages, objects)
monkeypatch.setattr(dockerhub, "DockerHubClient", lambda *args, **kwargs: client)
rows: list[dict[str, Any]] = []
@@ -83,6 +117,7 @@ class TestGetRows:
endpoint=endpoint,
logger=MagicMock(),
resumable_source_manager=manager, # type: ignore[arg-type]
+ incremental_start=incremental_start,
):
rows.extend(batch)
return rows, client
@@ -100,33 +135,51 @@ class TestGetRows:
)
)
- def test_repositories_single_page_yields_and_stops(self, monkeypatch: Any) -> None:
+ # pytest.mark.parametrize, not parameterized.expand: these cases take the monkeypatch fixture.
+ @pytest.mark.parametrize(
+ ("endpoint", "initial_url"),
+ [("repositories", REPOS_URL), ("org_members", MEMBERS_URL), ("org_groups", GROUPS_URL)],
+ )
+ def test_cursor_endpoint_single_page_yields_and_stops(
+ self, endpoint: str, initial_url: str, 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"}]
+ pages = {initial_url: ([{"id": "1", "namespace": "acme", "name": "alpha"}], None)}
+ rows, client = self._collect(manager, monkeypatch, pages, endpoint)
+ assert rows == [{"id": "1", "namespace": "acme", "name": "alpha"}]
+ assert client.fetched == [initial_url]
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:
+ @pytest.mark.parametrize(
+ ("endpoint", "initial_url"),
+ [("repositories", REPOS_URL), ("org_members", MEMBERS_URL), ("org_groups", GROUPS_URL)],
+ )
+ def test_cursor_endpoint_follows_next_url_until_null(
+ self, endpoint: str, initial_url: str, monkeypatch: Any
+ ) -> None:
manager = _FakeResumableManager()
- second = f"{DOCKERHUB_BASE_URL}/v2/namespaces/acme/repositories?ordering=name&page=2&page_size=100"
+ second = f"{initial_url}&page=2"
pages = {
- REPOS_URL: ([{"name": "alpha"}], second),
+ initial_url: ([{"name": "alpha"}], second),
second: ([{"name": "beta"}], None),
}
- rows, _ = self._collect(manager, monkeypatch, pages, "repositories")
+ rows, _ = self._collect(manager, monkeypatch, pages, endpoint)
assert rows == [{"name": "alpha"}, {"name": "beta"}]
- # State is saved once — after the first page, pointing at the next cursor — then we stop.
+ # State is saved once, after the first page and 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"
+ @pytest.mark.parametrize(
+ ("endpoint", "initial_url"),
+ [("repositories", REPOS_URL), ("org_members", MEMBERS_URL), ("org_groups", GROUPS_URL)],
+ )
+ def test_cursor_endpoint_resumes_from_saved_cursor(self, endpoint: str, initial_url: str, monkeypatch: Any) -> None:
+ second = f"{initial_url}&page=2"
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")
+ rows, client = self._collect(manager, monkeypatch, pages, endpoint)
assert rows == [{"name": "beta"}]
assert client.fetched == [second]
@@ -485,10 +538,17 @@ class TestDockerhubSourceResponse:
logger=MagicMock(),
resumable_source_manager=MagicMock(),
)
+ config = DOCKERHUB_ENDPOINTS[endpoint]
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
+ assert response.primary_keys == config.primary_keys
+ assert response.sort_mode == config.sort_mode
+ # Only the audit log has an immutable event timestamp to partition on. Repositories, tags,
+ # members and groups carry mutable last_updated fields, which would rewrite partitions on
+ # every sync.
+ if config.partition_key:
+ assert (response.partition_mode, response.partition_keys) == ("datetime", [config.partition_key])
+ else:
+ 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
@@ -497,3 +557,260 @@ class TestDockerhubSourceResponse:
def test_repositories_primary_key_is_namespace_scoped(self) -> None:
assert DOCKERHUB_ENDPOINTS["repositories"].primary_keys == ["namespace", "name"]
+
+
+class TestAuditLogs:
+ def test_short_page_ends_the_walk(self, monkeypatch: Any) -> None:
+ # The endpoint returns no next link and no total count, so a page shorter than page_size is
+ # the only end-of-collection signal. Missing it loops forever on an empty page.
+ manager = _FakeResumableManager()
+ objects = {_audit_page(1): {"logs": _audit_events(2)}}
+ rows, client = TestGetRows._collect(manager, monkeypatch, {}, "audit_logs", objects=objects)
+ assert len(rows) == 2
+ assert client.fetched == [_audit_page(1)]
+ assert manager.saved == []
+
+ def test_full_page_advances_and_saves_the_page_cursor(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager()
+ objects = {
+ _audit_page(1): {"logs": _audit_events(PAGE_SIZE)},
+ _audit_page(2): {"logs": _audit_events(1)},
+ }
+ rows, client = TestGetRows._collect(manager, monkeypatch, {}, "audit_logs", objects=objects)
+ assert len(rows) == PAGE_SIZE + 1
+ assert client.fetched == [_audit_page(1), _audit_page(2)]
+ assert [state.page for state in manager.saved] == [2]
+
+ def test_resumes_from_the_saved_page(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager(DockerhubResumeConfig(page=3))
+ objects = {_audit_page(3): {"logs": _audit_events(1)}}
+ _, client = TestGetRows._collect(manager, monkeypatch, {}, "audit_logs", objects=objects)
+ assert client.fetched == [_audit_page(3)]
+
+ def test_null_logs_ends_the_walk(self, monkeypatch: Any) -> None:
+ # Docker Hub serializes an empty event list as null rather than [].
+ manager = _FakeResumableManager()
+ objects: dict[str, Any] = {_audit_page(1): {"logs": None}}
+ rows, _ = TestGetRows._collect(manager, monkeypatch, {}, "audit_logs", objects=objects)
+ assert rows == []
+
+ def test_non_list_logs_is_retryable(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager()
+ objects: dict[str, Any] = {_audit_page(1): {"logs": {"unexpected": True}}}
+ with pytest.raises(DockerhubRetryableError):
+ TestGetRows._collect(manager, monkeypatch, {}, "audit_logs", objects=objects)
+
+ def test_incremental_run_sends_the_watermark_as_from(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager()
+ since = "2026-01-01T00:00:00Z"
+ objects = {_audit_page(1, since): {"logs": _audit_events(1)}}
+ _, client = TestGetRows._collect(
+ manager, monkeypatch, {}, "audit_logs", objects=objects, incremental_start=since
+ )
+ assert "from=2026-01-01T00%3A00%3A00Z" in client.fetched[0]
+
+ def test_full_refresh_run_omits_from(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager()
+ objects = {_audit_page(1): {"logs": _audit_events(1)}}
+ _, client = TestGetRows._collect(manager, monkeypatch, {}, "audit_logs", objects=objects)
+ assert "from=" not in client.fetched[0]
+
+ def test_synthetic_id_is_stable_for_identical_events(self, monkeypatch: Any) -> None:
+ # The endpoint returns no event id. An id that is not a pure function of the row's content
+ # would make every incremental run re-insert the boundary rows instead of merging onto them.
+ event = _audit_events(1)[0]
+ first, _ = TestGetRows._collect(
+ _FakeResumableManager(), monkeypatch, {}, "audit_logs", objects={_audit_page(1): {"logs": [event]}}
+ )
+ second, _ = TestGetRows._collect(
+ _FakeResumableManager(), monkeypatch, {}, "audit_logs", objects={_audit_page(1): {"logs": [dict(event)]}}
+ )
+ assert first[0]["id"] == second[0]["id"]
+
+ def test_synthetic_id_changes_with_the_event(self, monkeypatch: Any) -> None:
+ rows, _ = TestGetRows._collect(
+ _FakeResumableManager(),
+ monkeypatch,
+ {},
+ "audit_logs",
+ objects={_audit_page(1): {"logs": _audit_events(2)}},
+ )
+ assert rows[0]["id"] != rows[1]["id"]
+
+ def test_synthetic_id_ignores_an_id_the_api_starts_returning(self, monkeypatch: Any) -> None:
+ # If Docker Hub ever adds its own `id`, hashing it in would change every key at once and
+ # re-insert the whole table. The hash covers the event body only.
+ event = _audit_events(1)[0]
+ plain, _ = TestGetRows._collect(
+ _FakeResumableManager(), monkeypatch, {}, "audit_logs", objects={_audit_page(1): {"logs": [event]}}
+ )
+ with_id, _ = TestGetRows._collect(
+ _FakeResumableManager(),
+ monkeypatch,
+ {},
+ "audit_logs",
+ objects={_audit_page(1): {"logs": [{**event, "id": "hub-side-id"}]}},
+ )
+ assert plain[0]["id"] == with_id[0]["id"]
+
+
+class TestAuditLogActions:
+ def test_action_map_is_flattened_into_joinable_rows(self, monkeypatch: Any) -> None:
+ # An audit event names its action as "<group>.<name>", so the catalog is only usable as a
+ # lookup once the joined form is on the row.
+ objects = {
+ ACTIONS_URL: {
+ "actions": {
+ "repo": {
+ "label": "Repository",
+ "actions": [{"name": "tag.push", "label": "Tag Pushed", "description": "Tags pushed"}],
+ },
+ "org": {"label": "Organization", "actions": [{"name": "member.add", "label": "Member Added"}]},
+ }
+ }
+ }
+ rows, _ = TestGetRows._collect(_FakeResumableManager(), monkeypatch, {}, "audit_log_actions", objects=objects)
+ assert rows == [
+ {
+ "action_group": "repo",
+ "action_group_label": "Repository",
+ "name": "tag.push",
+ "qualified_name": "repo.tag.push",
+ "label": "Tag Pushed",
+ "description": "Tags pushed",
+ },
+ {
+ "action_group": "org",
+ "action_group_label": "Organization",
+ "name": "member.add",
+ "qualified_name": "org.member.add",
+ "label": "Member Added",
+ "description": None,
+ },
+ ]
+
+ @pytest.mark.parametrize("body", [{}, {"actions": []}])
+ def test_unexpected_payload_is_retryable(self, body: Any, monkeypatch: Any) -> None:
+ with pytest.raises(DockerhubRetryableError):
+ TestGetRows._collect(
+ _FakeResumableManager(), monkeypatch, {}, "audit_log_actions", objects={ACTIONS_URL: body}
+ )
+
+ def test_group_without_actions_yields_nothing(self, monkeypatch: Any) -> None:
+ objects: dict[str, Any] = {ACTIONS_URL: {"actions": {"repo": {"label": "Repository"}}}}
+ rows, _ = TestGetRows._collect(_FakeResumableManager(), monkeypatch, {}, "audit_log_actions", objects=objects)
+ assert rows == []
+
+
+class TestFormatIncrementalStart:
+ @parameterized.expand(
+ [
+ ("none", None, None),
+ ("aware_datetime", datetime(2026, 1, 2, 3, 4, 5, tzinfo=UTC), "2026-01-02T03:04:05Z"),
+ # A naive watermark is UTC; reading it as local time would shift the window by hours and
+ # either skip events or re-pull a day of them.
+ ("naive_datetime", datetime(2026, 1, 2, 3, 4, 5), "2026-01-02T03:04:05Z"),
+ (
+ "other_zone_datetime",
+ datetime(2026, 1, 2, 3, 4, 5, tzinfo=timezone(timedelta(hours=2))),
+ "2026-01-02T01:04:05Z",
+ ),
+ ("string_passthrough", "2026-01-02T03:04:05Z", "2026-01-02T03:04:05Z"),
+ ("blank_string", " ", None),
+ ]
+ )
+ def test_watermark_is_rendered_as_an_rfc_3339_instant(self, _name: str, value: Any, expected: Any) -> None:
+ assert format_incremental_start(value) == expected
+
+
+class TestCheckEndpointAccess:
+ def _sessions(self, login_status: int = 200, probe: Any = None) -> MagicMock:
+ session = MagicMock()
+ login = MagicMock()
+ login.ok = login_status < 400
+ login.json.return_value = {"token": "jwt-1"}
+ session.post.return_value = login
+ if isinstance(probe, Exception):
+ session.get.side_effect = probe
+ elif probe is not None:
+ response = MagicMock()
+ response.status_code = probe
+ session.get.return_value = response
+ return session
+
+ def _check(self, session: MagicMock, endpoints: list[str] | None = None) -> dict[str, str | None]:
+ with patch.object(dockerhub, "make_tracked_session", return_value=session):
+ return check_endpoint_access("tom", "token", "acme", endpoints or list(ENDPOINTS))
+
+ def test_repositories_and_tags_are_never_probed(self) -> None:
+ # Both read the namespace endpoints that `validate_credentials` already covered, so probing
+ # them again would spend requests to report what the source-level check reports.
+ session = self._sessions()
+ assert self._check(session, ["repositories", "tags"]) == {"repositories": None, "tags": None}
+ session.post.assert_not_called()
+
+ @parameterized.expand(
+ [
+ ("personal_namespace", 404, "returned no organization named"),
+ ("missing_org_scope", 403, "cannot read organization data"),
+ ]
+ )
+ def test_unreachable_org_endpoints_report_what_to_change(
+ self, _name: str, status: int, expected_substr: str
+ ) -> None:
+ permissions = self._check(self._sessions(probe=status))
+ assert permissions["repositories"] is None
+ for endpoint in ORG_SCOPED_ENDPOINTS:
+ reason = permissions[endpoint]
+ assert reason is not None and expected_substr in reason
+
+ def test_reachable_org_endpoints_report_no_reason(self) -> None:
+ assert self._check(self._sessions(probe=200)) == dict.fromkeys(ENDPOINTS)
+
+ @parameterized.expand(
+ [
+ ("rejected_login", 401, None),
+ ("probe_connection_error", 200, requests.ConnectionError("boom")),
+ ]
+ )
+ def test_transient_and_credential_failures_do_not_block_the_picker(
+ self, _name: str, login_status: int, probe: Any
+ ) -> None:
+ # A bad credential is reported by validate_credentials, and a network blip is not a missing
+ # permission. Either one marking every org table unavailable would be a false alarm.
+ assert self._check(self._sessions(login_status=login_status, probe=probe)) == dict.fromkeys(ENDPOINTS)
+
+
+class TestFetchObject:
+ def test_non_object_payload_is_retryable(self) -> None:
+ response = MagicMock()
+ response.status_code = 200
+ response.ok = True
+ response.json.return_value = [{"name": "alpha"}]
+ session = MagicMock()
+ session.get.return_value = response
+ with pytest.raises(DockerhubRetryableError):
+ _fetch_object_unwrapped(session, ACTIONS_URL, MagicMock())
+
+ def test_expired_jwt_triggers_a_relogin_and_retry(self) -> None:
+ # The audit log endpoints go through get_object, so they need the same mid-sync JWT refresh
+ # the list endpoints get. Without it a long audit log walk dies at token expiry.
+ session = MagicMock()
+ session.headers = {}
+ login = MagicMock()
+ login.status_code = 200
+ login.ok = True
+ login.json.return_value = {"token": "jwt-2"}
+ session.post.return_value = login
+
+ expired = MagicMock(status_code=401, ok=False, text="")
+ expired.raise_for_status.side_effect = requests.HTTPError("401 error", response=expired)
+ fresh = MagicMock(status_code=200, ok=True, text="")
+ fresh.json.return_value = {"actions": {}}
+ session.get.side_effect = [expired, fresh]
+
+ with patch.object(dockerhub, "make_tracked_session", return_value=session):
+ client = DockerHubClient("tom", "dckr_pat_token", MagicMock())
+
+ assert client.get_object(ACTIONS_URL) == {"actions": {}}
+ assert session.headers["Authorization"] == "Bearer jwt-2"
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
index f68fc6d6fc4a..7a586ba5db01 100644
--- 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
@@ -24,12 +24,26 @@ class TestDockerhubSource:
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_only_the_audit_log_is_incremental(self) -> None:
+ # The audit log endpoint is the only one taking a server-side time filter (`from`). Marking
+ # any other endpoint incremental would make each sync request a window the API ignores, so
+ # every row outside the first page would silently stop arriving.
+ schemas = {s.name: s for s in self.source.get_schemas(self.config, self.team_id)}
+ assert set(schemas) == set(ENDPOINTS)
+ assert [name for name, s in schemas.items() if s.supports_incremental] == ["audit_logs"]
+ assert [f["field"] for f in schemas["audit_logs"].incremental_fields] == ["timestamp"]
+ # Append would duplicate the boundary rows every incremental window re-reads.
+ assert all(s.supports_append is False for s in schemas.values())
+
+ def test_org_scoped_endpoints_report_why_they_are_unavailable(self) -> None:
+ with mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.dockerhub.source.check_endpoint_access",
+ return_value=dict.fromkeys(ENDPOINTS),
+ ) as probe:
+ self.source.get_endpoint_permissions(self.config, self.team_id, list(ENDPOINTS))
+
+ # A blank namespace means the user's own, so the probe must run against the username.
+ assert probe.call_args.args == ("tom", "dckr_pat_token", "tom", list(ENDPOINTS))
def test_get_schemas_filtered_by_names(self) -> None:
schemas = self.source.get_schemas(self.config, self.team_id, names=["tags"])