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 jfrog_artifactory import source (#71344)

Tom Owers7ee3c12b3a31
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 361ce617be3e..2f79d505e387 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -284,6 +284,7 @@ the row lists both.
| iterable | HTTP | requests | ✅ |
| jamf_pro | HTTP | requests | ✅ |
| jellyfish | HTTP | requests | ✅ |
+| jfrog_artifactory | HTTP | requests | ✅ |
| jira | HTTP | requests | ✅ |
| jobnimbus | HTTP | requests | ✅ |
| jotform | HTTP | requests | ✅ |
@@ -758,7 +759,6 @@ doesn't conflict with concurrent PRs.
- instantly
- interzoid
- jenkins
-- jfrog_artifactory
- jobber
- judgeme_reviews
- justsift
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 a007bfee7c71..6efeffc34db8 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
@@ -2255,7 +2255,8 @@ class JenkinsSourceConfig(config.Config):
@config.config
class JfrogArtifactorySourceConfig(config.Config):
- pass
+ base_url: str
+ access_token: str
@config.config
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/jfrog_artifactory/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/jfrog_artifactory/canonical_descriptions.py
new file mode 100644
index 000000000000..1793bf6e4434
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/jfrog_artifactory/canonical_descriptions.py
@@ -0,0 +1,73 @@
+"""Canonical, documentation-sourced descriptions for JFrog Artifactory endpoints and columns.
+
+Sourced from the official JFrog REST API and AQL references (https://jfrog.com/help/r/jfrog-rest-apis
+and https://docs.jfrog.com/artifactory/docs/artifactory-query-language). Keyed by the endpoint names
+in `settings.py` `JFROG_ARTIFACTORY_ENDPOINTS`, which match the `ExternalDataSchema.name` of a synced
+table. Columns absent here fall back to LLM enrichment.
+"""
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "repositories": {
+ "description": "A repository configured in Artifactory — local, remote, virtual, or federated — that stores or proxies packages.",
+ "docs_url": "https://jfrog.com/help/r/jfrog-rest-apis/get-repositories",
+ "columns": {
+ "key": "Unique repository key (name).",
+ "type": "Repository class: LOCAL, REMOTE, VIRTUAL, or FEDERATED.",
+ "description": "Free-text description of the repository.",
+ "url": "URL of the repository in Artifactory.",
+ "packageType": "Package format the repository serves (e.g. Maven, Docker, npm, PyPI, Generic).",
+ },
+ },
+ "artifacts": {
+ "description": "A file (artifact) stored in an Artifactory repository, with its coordinates, checksums, and timestamps. Queried via AQL over the items domain.",
+ "docs_url": "https://docs.jfrog.com/artifactory/docs/aql-entities-fields-reference",
+ "columns": {
+ "repo": "Key of the repository the artifact lives in.",
+ "path": "Folder path of the artifact within the repository.",
+ "name": "File name of the artifact.",
+ "type": "Item type; artifact rows are files.",
+ "size": "Size of the artifact in bytes.",
+ "created": "Time at which the artifact was first deployed.",
+ "created_by": "User that deployed the artifact.",
+ "modified": "Time at which the artifact was last modified.",
+ "modified_by": "User that last modified the artifact.",
+ "updated": "Time at which the artifact's metadata was last updated.",
+ "sha256": "SHA-256 checksum of the artifact.",
+ "actual_sha1": "SHA-1 checksum of the artifact.",
+ "actual_md5": "MD5 checksum of the artifact.",
+ },
+ },
+ "builds": {
+ "description": "Build-info records published to Artifactory by CI servers, one row per build run. Queried via AQL over the builds domain (requires an admin token).",
+ "docs_url": "https://docs.jfrog.com/artifactory/docs/aql-entities-fields-reference",
+ "columns": {
+ "name": "Name of the build.",
+ "number": "Run number of the build.",
+ "created": "Time at which the build-info was published.",
+ "created_by": "User that published the build-info.",
+ "modified": "Time at which the build-info was last modified.",
+ "modified_by": "User that last modified the build-info.",
+ "url": "URL of the build run on the CI server.",
+ },
+ },
+ "storage_summary": {
+ "description": "Point-in-time storage summary per repository — file counts and used space — from the storageinfo API (requires an admin token).",
+ "docs_url": "https://jfrog.com/help/r/jfrog-rest-apis/get-storage-summary-info",
+ "columns": {
+ "repoKey": "Key of the repository the summary row describes.",
+ "repoType": "Repository class: LOCAL, REMOTE, VIRTUAL, FEDERATED, or NA for totals.",
+ "foldersCount": "Number of folders in the repository.",
+ "filesCount": "Number of files in the repository.",
+ "usedSpace": "Human-readable used storage space.",
+ "usedSpaceInBytes": "Used storage space in bytes.",
+ "itemsCount": "Total number of items (files and folders) in the repository.",
+ "packageType": "Package format the repository serves.",
+ "projectKey": "Key of the JFrog project the repository belongs to, if any.",
+ "percentage": "Share of total instance storage used by the repository.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/jfrog_artifactory/jfrog_artifactory.py b/products/warehouse_sources/backend/temporal/data_imports/sources/jfrog_artifactory/jfrog_artifactory.py
new file mode 100644
index 000000000000..82e6ecada311
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/jfrog_artifactory/jfrog_artifactory.py
@@ -0,0 +1,382 @@
+import json
+import time
+import dataclasses
+from collections.abc import Iterator
+from datetime import UTC, date, datetime
+from typing import Any, Optional
+from urllib.parse import urlparse
+
+import requests
+from structlog.types import FilteringBoundLogger
+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+
+from posthog.cloud_utils import is_cloud
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.jfrog_artifactory.settings import (
+ AQL_PAGE_SIZE,
+ JFROG_ARTIFACTORY_ENDPOINTS,
+ JfrogArtifactoryEndpointConfig,
+)
+
+# Artifactory's REST and AQL APIs live under /artifactory on both SaaS (<company>.jfrog.io)
+# and standard self-hosted installs.
+ARTIFACTORY_API_PATH = "/artifactory/api"
+
+REQUEST_TIMEOUT_SECONDS = 120
+PROBE_TIMEOUT_SECONDS = 30
+MAX_RETRY_ATTEMPTS = 5
+
+# The platform URL is user-supplied, so a hostile host could stream an arbitrarily large (or
+# highly compressed) body and OOM the import worker. Cap how much we buffer before decoding JSON and
+# how long a single transfer may run, on both the sync path and the reachability probe. A legitimate
+# response is one AQL page (AQL_PAGE_SIZE rows of small metadata) or a REST listing
+# (repositories/storageinfo, bounded by repo count), i.e. a few MB at most, so keep the byte cap low.
+# json.loads allocates one Python object per value, so a compact body of many small values amplifies
+# far past its byte size — cap the number of structural tokens too so an amplification bomb (millions
+# of `{}`/`[]`/scalars) is rejected before it is materialized, even while under the byte cap.
+MAX_RESPONSE_BYTES = 8 * 1024 * 1024
+MAX_JSON_TOKENS = 1_000_000
+MAX_TRANSFER_SECONDS = 600
+RESPONSE_CHUNK_BYTES = 256 * 1024
+RESPONSE_LIMIT_ERROR = "JFrog response exceeded a transfer limit"
+
+
+class JfrogArtifactoryRetryableError(Exception):
+ pass
+
+
+class JfrogArtifactoryResponseTooLargeError(Exception):
+ # Non-retryable: a body over the cap won't shrink on retry, and buffering it again wastes the worker.
+ pass
+
+
+def _read_capped_body(response: requests.Response, url: str) -> bytes:
+ """Stream the response body under a byte cap and a wall-clock deadline, then return the raw bytes.
+
+ Called only when the caller opened the request with ``stream=True`` so the body isn't buffered
+ until here. ``iter_content`` decodes any content-encoding, so ``total`` and the cap track the
+ decoded size that actually lands in memory — a compression bomb trips the cap as it inflates.
+ Raises :class:`JfrogArtifactoryResponseTooLargeError` before the JSON is decoded rather than
+ letting a hostile host OOM the worker. The wall-clock deadline bounds a transfer that keeps
+ yielding chunks but drags on; a per-read socket timeout (``REQUEST_TIMEOUT_SECONDS``) bounds a
+ stall with no bytes at all, and a hung sync is ultimately bounded by the Temporal activity timeout.
+ """
+ started = time.monotonic()
+ total = 0
+ chunks: list[bytes] = []
+ for chunk in response.iter_content(chunk_size=RESPONSE_CHUNK_BYTES):
+ if not chunk:
+ continue
+ total += len(chunk)
+ if total > MAX_RESPONSE_BYTES:
+ raise JfrogArtifactoryResponseTooLargeError(
+ f"{RESPONSE_LIMIT_ERROR}: {url} returned more than {MAX_RESPONSE_BYTES} bytes"
+ )
+ if time.monotonic() - started > MAX_TRANSFER_SECONDS:
+ raise JfrogArtifactoryResponseTooLargeError(
+ f"{RESPONSE_LIMIT_ERROR}: {url} transfer exceeded {MAX_TRANSFER_SECONDS}s"
+ )
+ chunks.append(chunk)
+ return b"".join(chunks)
+
+
+def _loads_bounded(body: bytes, url: str) -> Any:
+ """Parse JSON only after bounding how many Python objects it can materialize.
+
+ ``json.loads`` allocates a distinct object per value, so a compact body of many ``{}``/``[]`` or
+ scalars (e.g. ``[0.0, 0.0, ...]``) amplifies far beyond its byte size — enough to OOM the worker
+ while under the byte cap. Structural tokens (``,`` ``{`` ``[``) are an O(n) upper bound on the
+ values the parse would create (over-counting occurrences inside strings only makes the guard more
+ conservative), so we can reject an amplification bomb before materializing it. The bound sits well
+ above a legitimate AQL page or repo/storage listing.
+ """
+ tokens = body.count(b",") + body.count(b"{") + body.count(b"[")
+ if tokens > MAX_JSON_TOKENS:
+ raise JfrogArtifactoryResponseTooLargeError(
+ f"{RESPONSE_LIMIT_ERROR}: {url} returned more than {MAX_JSON_TOKENS} JSON tokens"
+ )
+ return json.loads(body)
+
+
+class JfrogArtifactoryResumeConfig:
+ # Next AQL .offset() to request. None means "start from the first page".
+ next_offset: int | None = None
+ # The formatted timestamp the interrupted run's AQL filter was built with, reused verbatim on
+ # resume. The pipeline checkpoints the incremental watermark per batch (asc sort), so rebuilding
+ # the filter from the advanced DB value would shrink the result set and misalign every offset.
+ incremental_filter_value: str | None = None
+
+
+def normalize_base_url(base_url: str) -> str:
+ """Normalize the JFrog platform URL and reject anything that isn't plain http(s).
+
+ Accepts a bare host (``mycompany.jfrog.io``) or a full URL, with or without a trailing
+ ``/artifactory``, and returns the platform origin (no trailing slash).
+ """
+ base_url = base_url.strip()
+ if not base_url:
+ raise ValueError("JFrog platform URL is required")
+ if "://" not in base_url:
+ base_url = f"https://{base_url}"
+ base_url = base_url.rstrip("/")
+ # Tolerate a pasted Artifactory base URL by trimming a trailing /artifactory.
+ if base_url.endswith("/artifactory"):
+ base_url = base_url[: -len("/artifactory")]
+ parsed = urlparse(base_url)
+ if parsed.scheme not in ("http", "https") or not parsed.hostname:
+ raise ValueError(f"Invalid JFrog platform URL: {base_url}")
+ if parsed.path:
+ # Artifactory serves its API under /artifactory on the platform origin; a leftover path
+ # means the input wasn't a platform URL (or tried to smuggle one past the host checks).
+ raise ValueError(f"Invalid JFrog platform URL (must not contain a path): {base_url}")
+ # The access token rides in the Authorization header on every request, so plaintext http would
+ # leak it to any network observer. On PostHog Cloud the request egresses over the public
+ # internet, so require https. Self-hosted operators control their own network path, so http
+ # stays allowed there — mirroring how host IP safety is only enforced on cloud.
+ if parsed.scheme == "http" and is_cloud():
+ raise ValueError("JFrog platform URL must use https")
+ # SSRF guard: urlparse treats a backslash as part of the path and an "@" as a userinfo
+ # separator, but urllib3/requests treat the backslash as an authority separator, so
+ # `http://127.0.0.1\@example.com` validates as example.com yet connects to 127.0.0.1.
+ # A legitimate platform URL has no userinfo, so reject either construct outright.
+ if "\\" in base_url or "%5c" in base_url.lower() or "@" in parsed.netloc:
+ raise ValueError(f"Invalid JFrog platform URL: {base_url}")
+ return base_url
+
+
+def hostname_of(base_url: str) -> str:
+ return urlparse(normalize_base_url(base_url)).hostname or ""
+
+
+def _api_url(base_url: str, path: str) -> str:
+ return f"{normalize_base_url(base_url)}{ARTIFACTORY_API_PATH}{path}"
+
+
+def _headers(access_token: str) -> dict[str, str]:
+ return {"Authorization": f"Bearer {access_token}", "Accept": "application/json"}
+
+
+def _get_session(access_token: str) -> requests.Session:
+ # `base_url` is user-supplied, so pin redirects off so validation and the outbound request
+ # stay on the same target (SSRF defense-in-depth). Redact the token from logs.
+ return make_tracked_session(redact_values=(access_token,), allow_redirects=False)
+
+
+def _format_aql_datetime(value: Any) -> str:
+ """Format an incremental cursor as the ISO 8601 string AQL date comparisons accept.
+
+ The AQL docs use explicit UTC offsets (e.g. ``2012-07-16T19:20:30.45+01:00``), so emit
+ millisecond precision with a ``+00:00`` offset rather than the ``Z`` suffix.
+ """
+ if isinstance(value, datetime):
+ aware = value if value.tzinfo is not None else value.replace(tzinfo=UTC)
+ return aware.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "+00:00"
+ if isinstance(value, date):
+ return datetime.combine(value, datetime.min.time(), tzinfo=UTC).strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "+00:00"
+ return str(value)
+
+
+def build_aql_query(
+ config: JfrogArtifactoryEndpointConfig,
+ incremental_field: str | None = None,
+ incremental_filter_value: str | None = None,
+ offset: int = 0,
+ limit: int = AQL_PAGE_SIZE,
+) -> str:
+ """Build one AQL page query, e.g. ``items.find({...}).include(...).sort(...).offset(0).limit(1000)``.
+
+ The sort field always matches the filter field (or the endpoint default on full refresh) so
+ rows arrive in ascending cursor order and offset pagination walks a stable ordering.
+ """
+ sort_field = (incremental_field if incremental_filter_value else None) or config.default_incremental_field
+ criteria = json.dumps({sort_field: {"$gt": incremental_filter_value}}) if incremental_filter_value else ""
+ include = ", ".join(f'"{field}"' for field in config.aql_fields)
+ sort = json.dumps({"$asc": [sort_field]})
+ return f"{config.aql_domain}.find({criteria}).include({include}).sort({sort}).offset({offset}).limit({limit})"
+
+
+@retry(
+ retry=retry_if_exception_type(
+ (
+ JfrogArtifactoryRetryableError,
+ requests.ReadTimeout,
+ requests.ConnectionError,
+ requests.exceptions.ChunkedEncodingError,
+ )
+ ),
+ stop=stop_after_attempt(MAX_RETRY_ATTEMPTS),
+ wait=wait_exponential_jitter(initial=1, max=30),
+ reraise=True,
+)
+def _request(
+ session: requests.Session,
+ method: str,
+ url: str,
+ headers: dict[str, str],
+ logger: FilteringBoundLogger,
+ data: str | None = None,
+) -> Any:
+ # stream=True so the (user-supplied) host's body isn't buffered until we read it under a cap.
+ response = session.request(method, url, headers=headers, data=data, timeout=REQUEST_TIMEOUT_SECONDS, stream=True)
+
+ # JFrog Cloud tiers rate limit; transient 5xx are retryable too.
+ if response.status_code == 429 or response.status_code >= 500:
+ raise JfrogArtifactoryRetryableError(f"JFrog API error (retryable): status={response.status_code}, url={url}")
+
+ body = _read_capped_body(response, url)
+
+ if not response.ok:
+ logger.error(f"JFrog API error: status={response.status_code}, body={body[:500]!r}, url={url}")
+ response.raise_for_status()
+
+ return _loads_bounded(body, url)
+
+
+def _get_json(
+ session: requests.Session, base_url: str, access_token: str, path: str, logger: FilteringBoundLogger
+) -> Any:
+ return _request(session, "GET", _api_url(base_url, path), _headers(access_token), logger)
+
+
+def _post_aql(
+ session: requests.Session, base_url: str, access_token: str, query: str, logger: FilteringBoundLogger
+) -> dict[str, Any]:
+ # AQL queries are POSTed as a text/plain body, not JSON.
+ headers = {**_headers(access_token), "Content-Type": "text/plain"}
+ return _request(session, "POST", _api_url(base_url, "/search/aql"), headers, logger, data=query)
+
+
+def _strip_domain_prefix(item: dict[str, Any], domain: str) -> dict[str, Any]:
+ # Builds-domain results have historically been keyed as "build.name"/"build.created" (the
+ # documented legacy output) while items-domain results use bare field names. Normalize to bare
+ # names so the table schema, primary keys, and incremental watermark are stable either way.
+ prefix = f"{domain.rstrip('s')}."
+ return {(key[len(prefix) :] if key.startswith(prefix) else key): value for key, value in item.items()}
+
+
+def get_rows(
+ base_url: str,
+ access_token: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[JfrogArtifactoryResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+ incremental_field: str | None = None,
+) -> Iterator[Any]:
+ config = JFROG_ARTIFACTORY_ENDPOINTS[endpoint]
+ session = _get_session(access_token)
+
+ if config.kind == "rest":
+ data = _get_json(session, base_url, access_token, config.path, logger)
+ rows = (data.get(config.response_key) or []) if config.response_key else data
+ if rows:
+ yield rows
+ return
+
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ if resume is not None and resume.next_offset:
+ offset = resume.next_offset
+ filter_value = resume.incremental_filter_value
+ logger.debug(f"JFrog Artifactory: resuming {endpoint} from offset {offset}")
+ else:
+ offset = 0
+ filter_value = (
+ _format_aql_datetime(db_incremental_field_last_value)
+ if config.supports_incremental and should_use_incremental_field and db_incremental_field_last_value
+ else None
+ )
+
+ while True:
+ query = build_aql_query(config, incremental_field, filter_value, offset)
+ data = _post_aql(session, base_url, access_token, query, logger)
+ results = data.get("results", [])
+ if not results:
+ break
+
+ has_more = len(results) >= AQL_PAGE_SIZE
+ yield [_strip_domain_prefix(item, config.aql_domain) for item in results]
+
+ if not has_more:
+ break
+ offset += len(results)
+ # Save AFTER yielding so a crash re-yields the last page rather than skipping it — merge
+ # dedupes on the primary key.
+ resumable_source_manager.save_state(
+ JfrogArtifactoryResumeConfig(next_offset=offset, incremental_filter_value=filter_value)
+ )
+
+
+def jfrog_artifactory_source(
+ base_url: str,
+ access_token: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[JfrogArtifactoryResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+ incremental_field: str | None = None,
+) -> SourceResponse:
+ config = JFROG_ARTIFACTORY_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ base_url=base_url,
+ access_token=access_token,
+ endpoint=endpoint,
+ logger=logger,
+ resumable_source_manager=resumable_source_manager,
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ incremental_field=incremental_field,
+ ),
+ primary_keys=config.primary_keys,
+ partition_count=1,
+ partition_size=1,
+ 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,
+ )
+
+
+def probe_endpoint(base_url: str, access_token: str, endpoint: str | None = None) -> tuple[bool, int | None]:
+ """Cheap reachability probe for the token (``endpoint=None``) or one specific endpoint.
+
+ Returns ``(ok, status_code)``; ``status_code`` is ``None`` on a transport error. Raises
+ ``ValueError`` when the platform URL is malformed so the caller can surface a precise message.
+ """
+ config = JFROG_ARTIFACTORY_ENDPOINTS[endpoint] if endpoint is not None else None
+ session = _get_session(access_token)
+ # stream=True keeps the (user-supplied) host's body off the wire until we ask for it — the probe
+ # only inspects the status code, so we never read it, and closing the response frees the socket.
+ try:
+ if config is not None and config.kind == "aql":
+ # AQL requires authentication and (for builds) admin/scoped-token access, so a
+ # single-row query is the accurate scope probe for these endpoints.
+ query = build_aql_query(config, limit=1)
+ url = _api_url(base_url, "/search/aql")
+ response = session.post(
+ url,
+ headers={**_headers(access_token), "Content-Type": "text/plain"},
+ data=query,
+ timeout=PROBE_TIMEOUT_SECONDS,
+ stream=True,
+ )
+ else:
+ path = config.path if config is not None else "/repositories"
+ response = session.get(
+ _api_url(base_url, path), headers=_headers(access_token), timeout=PROBE_TIMEOUT_SECONDS, stream=True
+ )
+ except ValueError:
+ raise
+ except Exception:
+ return False, None
+ try:
+ return response.status_code == 200, response.status_code
+ finally:
+ response.close()
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/jfrog_artifactory/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/jfrog_artifactory/settings.py
new file mode 100644
index 000000000000..1e7c9908a362
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/jfrog_artifactory/settings.py
@@ -0,0 +1,113 @@
+from dataclasses import dataclass, field
+from typing import Literal, Optional
+
+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+
+# AQL pages are requested with in-query .offset()/.limit(). 1000 rows keeps response bodies small
+# while limiting round trips; the AQL server-side hard limit is far above this.
+AQL_PAGE_SIZE = 1000
+
+
+def _datetime_incremental_fields(*names: str) -> list[IncrementalField]:
+ return [
+ {
+ "label": name,
+ "type": IncrementalFieldType.DateTime,
+ "field": name,
+ "field_type": IncrementalFieldType.DateTime,
+ }
+ for name in names
+ ]
+
+
+@dataclass
+class JfrogArtifactoryEndpointConfig:
+ name: str
+ # "rest" endpoints are a single unpaginated GET under /artifactory/api; "aql" endpoints POST an
+ # AQL query to /artifactory/api/search/aql with in-body offset/limit pagination.
+ kind: Literal["rest", "aql"]
+ # REST only: path under /artifactory/api, e.g. "/repositories".
+ path: str = ""
+ # REST only: key of the row list in the response JSON; None when the response is a bare array.
+ response_key: Optional[str] = None
+ # AQL only: query domain ("items" or "builds").
+ aql_domain: str = ""
+ # AQL only: fields for .include(). Primary-domain fields only — AQL rejects
+ # .sort()/.offset()/.limit() when .include() pulls fields from other domains.
+ aql_fields: tuple[str, ...] = ()
+ # AQL exposes server-side timestamp filters ({"modified":{"$gt":...}}); the REST list
+ # endpoints here have none, so they stay full refresh.
+ supports_incremental: bool = False
+ # Also the sort/pagination field for full-refresh AQL runs, so page boundaries stay stable.
+ default_incremental_field: str = "modified"
+ incremental_fields: list[IncrementalField] = field(default_factory=list)
+ # Stable creation-time field to partition by. None when the resource has no creation timestamp.
+ partition_key: Optional[str] = None
+ primary_keys: list[str] = field(default_factory=lambda: ["key"])
+ should_sync_default: bool = True
+
+
+JFROG_ARTIFACTORY_ENDPOINTS: dict[str, JfrogArtifactoryEndpointConfig] = {
+ "repositories": JfrogArtifactoryEndpointConfig(
+ name="repositories",
+ kind="rest",
+ path="/repositories",
+ primary_keys=["key"],
+ ),
+ "artifacts": JfrogArtifactoryEndpointConfig(
+ name="artifacts",
+ kind="aql",
+ aql_domain="items",
+ # Non-admin AQL item queries must include repo, path, and name in the output.
+ aql_fields=(
+ "repo",
+ "path",
+ "name",
+ "type",
+ "size",
+ "created",
+ "created_by",
+ "modified",
+ "modified_by",
+ "updated",
+ "sha256",
+ "actual_sha1",
+ "actual_md5",
+ ),
+ supports_incremental=True,
+ default_incremental_field="modified",
+ incremental_fields=_datetime_incremental_fields("modified", "created"),
+ partition_key="created",
+ # An artifact is uniquely addressed by its repository + folder path + file name.
+ primary_keys=["repo", "path", "name"],
+ ),
+ "builds": JfrogArtifactoryEndpointConfig(
+ name="builds",
+ kind="aql",
+ aql_domain="builds",
+ aql_fields=("name", "number", "created", "created_by", "modified", "modified_by", "url"),
+ supports_incremental=True,
+ default_incremental_field="created",
+ incremental_fields=_datetime_incremental_fields("created"),
+ partition_key="created",
+ primary_keys=["name", "number"],
+ # AQL build-domain queries need an admin user (or a token scoped to the builds domain),
+ # so don't select this table by default for tokens that can't reach it.
+ should_sync_default=False,
+ ),
+ "storage_summary": JfrogArtifactoryEndpointConfig(
+ name="storage_summary",
+ kind="rest",
+ path="/storageinfo",
+ response_key="repositoriesSummaryList",
+ primary_keys=["repoKey"],
+ # /api/storageinfo requires admin privileges.
+ should_sync_default=False,
+ ),
+}
+
+ENDPOINTS = tuple(JFROG_ARTIFACTORY_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in JFROG_ARTIFACTORY_ENDPOINTS.items()
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/jfrog_artifactory/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/jfrog_artifactory/source.py
index ac873abe5018..e01b37d28d09 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/jfrog_artifactory/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/jfrog_artifactory/source.py
@@ -1,32 +1,231 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
DataWarehouseSourceCategory,
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (
+ SourceInputs,
+ SourceResponse,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.mixins import ValidateDatabaseHostMixin
from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchema
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import (
JfrogArtifactorySourceConfig,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.jfrog_artifactory.jfrog_artifactory import (
+ JfrogArtifactoryResumeConfig,
+ hostname_of,
+ jfrog_artifactory_source,
+ probe_endpoint,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.jfrog_artifactory.settings import (
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+ JFROG_ARTIFACTORY_ENDPOINTS,
+)
from products.warehouse_sources.backend.types import ExternalDataSourceType
+# Endpoints JFrog restricts to admin users (or access tokens scoped to the relevant domain).
+_ADMIN_ENDPOINTS = {"builds", "storage_summary"}
+
@SourceRegistry.register
-class JfrogArtifactorySource(SimpleSource[JfrogArtifactorySourceConfig]):
+class JfrogArtifactorySource(
+ ResumableSource[JfrogArtifactorySourceConfig, JfrogArtifactoryResumeConfig], ValidateDatabaseHostMixin
+):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.JFROGARTIFACTORY
+ @property
+ def connection_host_fields(self) -> list[str]:
+ # The access token is sent to `base_url`, so retargeting it must re-require the token.
+ return ["base_url"]
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=SchemaExternalDataSourceType.JFROG_ARTIFACTORY,
category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,
label="JFrog (Artifactory / JFrog Platform)",
+ releaseStatus=ReleaseStatus.ALPHA,
+ keywords=["artifactory", "jfrog platform"],
+ caption="""Connect your JFrog Platform instance to pull your Artifactory data into the PostHog Data warehouse.
+
+Enter your platform URL (e.g. `https://mycompany.jfrog.io`, or your own domain for self-hosted installs) and an access token. Generate a token from your JFrog user profile (**Edit Profile → Generate an Identity Token**) or, as an admin, under **Administration → User Management → Access Tokens**.
+
+The `artifacts` and `repositories` tables work with any authenticated token that can read your repositories. The `builds` and `storage_summary` tables require an admin user (or a token scoped to those APIs); deselect them if your token can't access them.""",
iconPath="/static/services/jfrog_artifactory.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/jfrog-artifactory",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="base_url",
+ label="Platform URL",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="https://mycompany.jfrog.io",
+ secret=False,
+ ),
+ SourceFieldInputConfig(
+ name="access_token",
+ label="Access token",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
+ )
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.jfrog_artifactory.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ # 401/403 surface as a requests HTTPError when `_request` calls `raise_for_status()`.
+ # Retrying can never fix a credential/permission problem, so fail the sync. The host is
+ # per-tenant, so match on the stable status text only.
+ "401 Client Error: Unauthorized for url": "Your JFrog access token is invalid, expired, or has been revoked. Generate a new access token, then reconnect.",
+ "403 Client Error: Forbidden for url": "Your JFrog access token is missing the permissions needed to sync this data. The builds and storage_summary tables require an admin token — deselect them or use a token with the required access.",
+ }
+
+ def get_schemas(
+ self,
+ config: JfrogArtifactorySourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ def _description(endpoint: str) -> str | None:
+ if endpoint == "builds":
+ return "Requires an admin user or a token scoped to the builds domain"
+ if endpoint == "storage_summary":
+ return "Point-in-time snapshot of per-repository storage usage. Requires an admin token"
+ return None
+
+ def _build_schema(endpoint: str) -> SourceSchema:
+ endpoint_config = JFROG_ARTIFACTORY_ENDPOINTS[endpoint]
+ return SourceSchema(
+ name=endpoint,
+ supports_incremental=endpoint_config.supports_incremental,
+ supports_append=endpoint_config.supports_incremental,
+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),
+ should_sync_default=endpoint_config.should_sync_default,
+ detected_primary_keys=list(endpoint_config.primary_keys),
+ description=_description(endpoint),
+ )
+
+ schemas = [_build_schema(endpoint) for endpoint in ENDPOINTS]
+ if names is not None:
+ names_set = set(names)
+ schemas = [s for s in schemas if s.name in names_set]
+ return schemas
+
+ def validate_credentials(
+ self, config: JfrogArtifactorySourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ try:
+ host_valid, host_error = self.is_database_host_valid(hostname_of(config.base_url), team_id)
+ except ValueError as e:
+ return False, str(e)
+ if not host_valid:
+ return False, host_error
+
+ try:
+ ok, status_code = probe_endpoint(
+ config.base_url,
+ config.access_token,
+ endpoint=schema_name if schema_name in JFROG_ARTIFACTORY_ENDPOINTS else None,
+ )
+ except ValueError as e:
+ return False, str(e)
+
+ if ok:
+ return True, None
+ if status_code == 401:
+ return False, "Invalid JFrog access token"
+ if status_code == 403:
+ # At source-create a 403 means the token is genuine but not fully scoped — accept it and
+ # surface per-table scope via get_endpoint_permissions instead of blocking the source.
+ if schema_name is None:
+ return True, None
+ if schema_name in _ADMIN_ENDPOINTS:
+ return (
+ False,
+ f"Your JFrog access token cannot access the {schema_name} table — it requires an admin user or a token scoped to that API",
+ )
+ return False, f"Your JFrog access token is missing the permissions needed for the {schema_name} table"
+ return False, "Could not connect to JFrog with the provided platform URL and access token"
+
+ def get_endpoint_permissions(
+ self, config: JfrogArtifactorySourceConfig, team_id: int, endpoints: list[str]
+ ) -> dict[str, str | None]:
+ permissions: dict[str, str | None] = {}
+ for endpoint in endpoints:
+ if endpoint not in JFROG_ARTIFACTORY_ENDPOINTS:
+ permissions[endpoint] = None
+ continue
+ try:
+ ok, status_code = probe_endpoint(config.base_url, config.access_token, endpoint=endpoint)
+ except ValueError:
+ permissions[endpoint] = None
+ continue
+ # Only a definite denial is a missing scope; throttles, 5xx, and network blips must not
+ # mark the table as unreachable.
+ if ok or status_code not in (401, 403):
+ permissions[endpoint] = None
+ elif endpoint in _ADMIN_ENDPOINTS:
+ permissions[endpoint] = "Requires an admin user or a token scoped to this API"
+ else:
+ permissions[endpoint] = "Your access token cannot read this API"
+ return permissions
+
+ def get_resumable_source_manager(
+ self, inputs: SourceInputs
+ ) -> ResumableSourceManager[JfrogArtifactoryResumeConfig]:
+ return ResumableSourceManager[JfrogArtifactoryResumeConfig](inputs, JfrogArtifactoryResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: JfrogArtifactorySourceConfig,
+ resumable_source_manager: ResumableSourceManager[JfrogArtifactoryResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ host_valid, host_error = self.is_database_host_valid(hostname_of(config.base_url), inputs.team_id)
+ if not host_valid:
+ raise ValueError(host_error or "Invalid JFrog platform URL")
+
+ return jfrog_artifactory_source(
+ base_url=config.base_url,
+ access_token=config.access_token,
+ endpoint=inputs.schema_name,
+ logger=inputs.logger,
+ resumable_source_manager=resumable_source_manager,
+ should_use_incremental_field=inputs.should_use_incremental_field,
+ db_incremental_field_last_value=inputs.db_incremental_field_last_value
+ if inputs.should_use_incremental_field
+ else None,
+ incremental_field=inputs.incremental_field,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/jfrog_artifactory/tests/test_jfrog_artifactory.py b/products/warehouse_sources/backend/temporal/data_imports/sources/jfrog_artifactory/tests/test_jfrog_artifactory.py
new file mode 100644
index 000000000000..dfcc77e9f65e
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/jfrog_artifactory/tests/test_jfrog_artifactory.py
@@ -0,0 +1,461 @@
+from datetime import UTC, date, datetime
+from typing import Any
+
+import pytest
+from unittest.mock import MagicMock
+
+from parameterized import parameterized
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.jfrog_artifactory import jfrog_artifactory
+from products.warehouse_sources.backend.temporal.data_imports.sources.jfrog_artifactory.jfrog_artifactory import (
+ RESPONSE_LIMIT_ERROR,
+ JfrogArtifactoryResponseTooLargeError,
+ JfrogArtifactoryResumeConfig,
+ _format_aql_datetime,
+ _request,
+ _strip_domain_prefix,
+ build_aql_query,
+ get_rows,
+ jfrog_artifactory_source,
+ normalize_base_url,
+ probe_endpoint,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.jfrog_artifactory.settings import (
+ AQL_PAGE_SIZE,
+ JFROG_ARTIFACTORY_ENDPOINTS,
+)
+
+
+class TestNormalizeBaseUrl:
+ @parameterized.expand(
+ [
+ ("bare_host", "acme.jfrog.io", "https://acme.jfrog.io"),
+ ("https_url", "https://acme.jfrog.io", "https://acme.jfrog.io"),
+ ("trailing_slash", "https://acme.jfrog.io/", "https://acme.jfrog.io"),
+ ("artifactory_suffix", "https://acme.jfrog.io/artifactory", "https://acme.jfrog.io"),
+ ("artifactory_suffix_slash", "acme.jfrog.io/artifactory/", "https://acme.jfrog.io"),
+ (
+ "self_hosted_with_port",
+ "https://artifactory.internal.example.com:8082",
+ "https://artifactory.internal.example.com:8082",
+ ),
+ ("whitespace", " acme.jfrog.io ", "https://acme.jfrog.io"),
+ ]
+ )
+ def test_valid_urls(self, _name: str, value: str, expected: str) -> None:
+ assert normalize_base_url(value) == expected
+
+ @parameterized.expand(
+ [
+ ("empty", ""),
+ ("path", "https://acme.jfrog.io/some/path"),
+ ("userinfo_injection", "https://[email protected]"),
+ ("backslash_injection", "https://127.0.0.1\\@acme.jfrog.io"),
+ ("encoded_backslash", "https://127.0.0.1%[email protected]"),
+ ("bad_scheme", "ftp://acme.jfrog.io"),
+ ]
+ )
+ def test_invalid_urls_raise(self, _name: str, value: str) -> None:
+ with pytest.raises(ValueError):
+ normalize_base_url(value)
+
+
+class TestFormatAqlDatetime:
+ @parameterized.expand(
+ [
+ ("utc_datetime", datetime(2026, 3, 4, 2, 58, 14, 123000, tzinfo=UTC), "2026-03-04T02:58:14.123+00:00"),
+ ("naive_datetime", datetime(2026, 3, 4, 2, 58, 14), "2026-03-04T02:58:14.000+00:00"),
+ ("date_value", date(2026, 3, 4), "2026-03-04T00:00:00.000+00:00"),
+ ("string_passthrough", "2026-03-04T02:58:14.000+00:00", "2026-03-04T02:58:14.000+00:00"),
+ ]
+ )
+ def test_format(self, _name: str, value: Any, expected: str) -> None:
+ assert _format_aql_datetime(value) == expected
+
+
+class TestBuildAqlQuery:
+ def test_incremental_query_filters_and_sorts_on_cursor_field(self) -> None:
+ query = build_aql_query(
+ JFROG_ARTIFACTORY_ENDPOINTS["artifacts"],
+ incremental_field="modified",
+ incremental_filter_value="2026-03-04T02:58:14.000+00:00",
+ offset=2000,
+ )
+ assert query.startswith('items.find({"modified": {"$gt": "2026-03-04T02:58:14.000+00:00"}})')
+ assert '.sort({"$asc": ["modified"]})' in query
+ assert query.endswith(f".offset(2000).limit({AQL_PAGE_SIZE})")
+
+ def test_full_refresh_query_has_no_criteria_but_stable_sort(self) -> None:
+ query = build_aql_query(JFROG_ARTIFACTORY_ENDPOINTS["artifacts"])
+ assert query.startswith("items.find()")
+ assert '.sort({"$asc": ["modified"]})' in query
+ assert f".offset(0).limit({AQL_PAGE_SIZE})" in query
+
+ def test_user_chosen_cursor_field_drives_filter_and_sort(self) -> None:
+ query = build_aql_query(
+ JFROG_ARTIFACTORY_ENDPOINTS["artifacts"],
+ incremental_field="created",
+ incremental_filter_value="2026-03-04T00:00:00.000+00:00",
+ )
+ assert '"created": {"$gt"' in query
+ assert '.sort({"$asc": ["created"]})' in query
+
+ def test_builds_query_uses_builds_domain(self) -> None:
+ query = build_aql_query(JFROG_ARTIFACTORY_ENDPOINTS["builds"], limit=1)
+ assert query.startswith("builds.find()")
+ assert '"name", "number", "created"' in query
+ assert query.endswith(".offset(0).limit(1)")
+
+ def test_sort_field_always_included_in_output_fields(self) -> None:
+ # AQL rejects .sort() on fields absent from a primary-domain .include() list.
+ for config in JFROG_ARTIFACTORY_ENDPOINTS.values():
+ if config.kind != "aql":
+ continue
+ assert config.default_incremental_field in config.aql_fields
+ for incremental_field in config.incremental_fields:
+ assert incremental_field["field"] in config.aql_fields
+
+
+class TestStripDomainPrefix:
+ @parameterized.expand(
+ [
+ ("prefixed_builds", {"build.name": "b", "build.number": "1"}, "builds", {"name": "b", "number": "1"}),
+ ("bare_builds", {"name": "b", "number": "1"}, "builds", {"name": "b", "number": "1"}),
+ ("bare_items", {"repo": "r", "path": "p", "name": "n"}, "items", {"repo": "r", "path": "p", "name": "n"}),
+ ]
+ )
+ def test_strip(self, _name: str, item: dict, domain: str, expected: dict) -> None:
+ assert _strip_domain_prefix(item, domain) == expected
+
+
+class _FakeResumableManager:
+ def __init__(self, state: JfrogArtifactoryResumeConfig | None = None) -> None:
+ self._state = state
+ self.saved: list[JfrogArtifactoryResumeConfig] = []
+
+ def can_resume(self) -> bool:
+ return self._state is not None
+
+ def load_state(self) -> JfrogArtifactoryResumeConfig | None:
+ return self._state
+
+ def save_state(self, data: JfrogArtifactoryResumeConfig) -> None:
+ self.saved.append(data)
+
+
+def _patch_aql(monkeypatch: Any, pages: dict[str, dict]) -> list[str]:
+ queries: list[str] = []
+
+ def fake_post_aql(session: Any, base_url: str, access_token: str, query: str, logger: Any) -> dict:
+ queries.append(query)
+ return pages[query]
+
+ monkeypatch.setattr(jfrog_artifactory, "_post_aql", fake_post_aql)
+ return queries
+
+
+def _collect(manager: _FakeResumableManager, **kwargs: Any) -> list[dict]:
+ rows: list[dict] = []
+ for batch in get_rows(
+ base_url="https://acme.jfrog.io",
+ access_token="token",
+ logger=MagicMock(),
+ resumable_source_manager=manager, # type: ignore[arg-type]
+ **kwargs,
+ ):
+ rows.extend(batch)
+ return rows
+
+
+def _artifact(name: str) -> dict:
+ return {"repo": "libs", "path": "com/acme", "name": name, "modified": "2026-01-01T00:00:00.000+00:00"}
+
+
+class TestGetRowsAql:
+ def test_paginates_until_short_page(self, monkeypatch: Any) -> None:
+ full_page = [_artifact(f"a{i}.jar") for i in range(AQL_PAGE_SIZE)]
+ config = JFROG_ARTIFACTORY_ENDPOINTS["artifacts"]
+ page_1 = build_aql_query(config, offset=0)
+ page_2 = build_aql_query(config, offset=AQL_PAGE_SIZE)
+ queries = _patch_aql(
+ monkeypatch,
+ {
+ page_1: {"results": full_page, "range": {"start_pos": 0, "end_pos": AQL_PAGE_SIZE}},
+ page_2: {"results": [_artifact("last.jar")], "range": {"start_pos": AQL_PAGE_SIZE}},
+ },
+ )
+
+ rows = _collect(_FakeResumableManager(), endpoint="artifacts")
+
+ assert len(rows) == AQL_PAGE_SIZE + 1
+ assert queries == [page_1, page_2]
+
+ def test_saves_resume_state_after_each_yielded_page(self, monkeypatch: Any) -> None:
+ full_page = [_artifact(f"a{i}.jar") for i in range(AQL_PAGE_SIZE)]
+ config = JFROG_ARTIFACTORY_ENDPOINTS["artifacts"]
+ _patch_aql(
+ monkeypatch,
+ {
+ build_aql_query(config, offset=0): {"results": full_page},
+ build_aql_query(config, offset=AQL_PAGE_SIZE): {"results": [_artifact("last.jar")]},
+ },
+ )
+ manager = _FakeResumableManager()
+
+ _collect(manager, endpoint="artifacts")
+
+ # State is saved only while more pages remain, never on the final short page.
+ assert manager.saved == [JfrogArtifactoryResumeConfig(next_offset=AQL_PAGE_SIZE, incremental_filter_value=None)]
+
+ def test_resumes_from_saved_offset_with_original_filter(self, monkeypatch: Any) -> None:
+ config = JFROG_ARTIFACTORY_ENDPOINTS["artifacts"]
+ saved_filter = "2026-01-01T00:00:00.000+00:00"
+ resume_query = build_aql_query(
+ config, incremental_field="modified", incremental_filter_value=saved_filter, offset=AQL_PAGE_SIZE
+ )
+ queries = _patch_aql(monkeypatch, {resume_query: {"results": [_artifact("resumed.jar")]}})
+
+ rows = _collect(
+ _FakeResumableManager(
+ JfrogArtifactoryResumeConfig(next_offset=AQL_PAGE_SIZE, incremental_filter_value=saved_filter)
+ ),
+ endpoint="artifacts",
+ should_use_incremental_field=True,
+ # The DB watermark has advanced past the saved filter; resuming must reuse the saved
+ # value or the offset would point at a different slice of the result set.
+ db_incremental_field_last_value=datetime(2026, 2, 1, tzinfo=UTC),
+ incremental_field="modified",
+ )
+
+ assert [r["name"] for r in rows] == ["resumed.jar"]
+ assert queries == [resume_query]
+
+ def test_incremental_filter_built_from_db_watermark(self, monkeypatch: Any) -> None:
+ config = JFROG_ARTIFACTORY_ENDPOINTS["artifacts"]
+ query = build_aql_query(
+ config,
+ incremental_field="modified",
+ incremental_filter_value="2026-03-04T02:58:14.000+00:00",
+ offset=0,
+ )
+ queries = _patch_aql(monkeypatch, {query: {"results": [_artifact("new.jar")]}})
+
+ _collect(
+ _FakeResumableManager(),
+ endpoint="artifacts",
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC),
+ incremental_field="modified",
+ )
+
+ assert queries == [query]
+
+ def test_stops_on_empty_first_page(self, monkeypatch: Any) -> None:
+ config = JFROG_ARTIFACTORY_ENDPOINTS["artifacts"]
+ _patch_aql(monkeypatch, {build_aql_query(config, offset=0): {"results": []}})
+
+ assert _collect(_FakeResumableManager(), endpoint="artifacts") == []
+
+ def test_builds_rows_normalized_from_prefixed_keys(self, monkeypatch: Any) -> None:
+ config = JFROG_ARTIFACTORY_ENDPOINTS["builds"]
+ _patch_aql(
+ monkeypatch,
+ {
+ build_aql_query(config, offset=0): {
+ "results": [{"build.name": "app", "build.number": "42", "build.created": "2026-01-01"}]
+ }
+ },
+ )
+
+ rows = _collect(_FakeResumableManager(), endpoint="builds")
+
+ assert rows == [{"name": "app", "number": "42", "created": "2026-01-01"}]
+
+
+class TestGetRowsRest:
+ def test_repositories_returns_bare_array(self, monkeypatch: Any) -> None:
+ monkeypatch.setattr(
+ jfrog_artifactory,
+ "_get_json",
+ lambda session, base_url, access_token, path, logger: [{"key": "libs-release", "type": "LOCAL"}],
+ )
+
+ rows = _collect(_FakeResumableManager(), endpoint="repositories")
+
+ assert rows == [{"key": "libs-release", "type": "LOCAL"}]
+
+ def test_storage_summary_extracts_repositories_summary_list(self, monkeypatch: Any) -> None:
+ monkeypatch.setattr(
+ jfrog_artifactory,
+ "_get_json",
+ lambda session, base_url, access_token, path, logger: {
+ "binariesSummary": {"binariesCount": "100"},
+ "repositoriesSummaryList": [{"repoKey": "libs-release", "filesCount": 10}],
+ },
+ )
+
+ rows = _collect(_FakeResumableManager(), endpoint="storage_summary")
+
+ assert rows == [{"repoKey": "libs-release", "filesCount": 10}]
+
+ def test_storage_summary_missing_key_yields_nothing(self, monkeypatch: Any) -> None:
+ monkeypatch.setattr(
+ jfrog_artifactory,
+ "_get_json",
+ lambda session, base_url, access_token, path, logger: {"binariesSummary": {}},
+ )
+
+ assert _collect(_FakeResumableManager(), endpoint="storage_summary") == []
+
+
+class TestSourceResponse:
+ @parameterized.expand(
+ [
+ ("repositories", ["key"], None),
+ ("artifacts", ["repo", "path", "name"], "created"),
+ ("builds", ["name", "number"], "created"),
+ ("storage_summary", ["repoKey"], None),
+ ]
+ )
+ def test_primary_keys_and_partitioning(
+ self, endpoint: str, primary_keys: list[str], partition_key: str | None
+ ) -> None:
+ response = jfrog_artifactory_source(
+ base_url="https://acme.jfrog.io",
+ access_token="token",
+ endpoint=endpoint,
+ logger=MagicMock(),
+ resumable_source_manager=MagicMock(),
+ )
+ assert response.name == endpoint
+ assert response.primary_keys == primary_keys
+ assert response.sort_mode == "asc"
+ if partition_key is None:
+ assert response.partition_mode is None
+ else:
+ assert response.partition_mode == "datetime"
+ assert response.partition_keys == [partition_key]
+
+
+class _FakeSession:
+ def __init__(self, status_code: int = 200) -> None:
+ self.requests: list[tuple[str, str, str | None]] = []
+ self._status_code = status_code
+
+ def get(self, url: str, headers: dict | None = None, timeout: int | None = None, stream: bool = False) -> MagicMock:
+ self.requests.append(("GET", url, None))
+ return MagicMock(status_code=self._status_code)
+
+ def post(
+ self,
+ url: str,
+ headers: dict | None = None,
+ data: str | None = None,
+ timeout: int | None = None,
+ stream: bool = False,
+ ) -> MagicMock:
+ self.requests.append(("POST", url, data))
+ return MagicMock(status_code=self._status_code)
+
+
+class TestProbeEndpoint:
+ def test_token_probe_gets_repositories(self, monkeypatch: Any) -> None:
+ session = _FakeSession()
+ monkeypatch.setattr(jfrog_artifactory, "_get_session", lambda access_token: session)
+
+ ok, status = probe_endpoint("https://acme.jfrog.io", "token")
+
+ assert (ok, status) == (True, 200)
+ assert session.requests == [("GET", "https://acme.jfrog.io/artifactory/api/repositories", None)]
+
+ def test_aql_endpoint_probe_posts_single_row_query(self, monkeypatch: Any) -> None:
+ session = _FakeSession(status_code=403)
+ monkeypatch.setattr(jfrog_artifactory, "_get_session", lambda access_token: session)
+
+ ok, status = probe_endpoint("https://acme.jfrog.io", "token", endpoint="builds")
+
+ assert (ok, status) == (False, 403)
+ method, url, data = session.requests[0]
+ assert (method, url) == ("POST", "https://acme.jfrog.io/artifactory/api/search/aql")
+ assert data is not None and data.startswith("builds.find()") and data.endswith(".limit(1)")
+
+ def test_transport_error_returns_none_status(self, monkeypatch: Any) -> None:
+ session = MagicMock()
+ session.get.side_effect = ConnectionError("nope")
+ monkeypatch.setattr(jfrog_artifactory, "_get_session", lambda access_token: session)
+
+ assert probe_endpoint("https://acme.jfrog.io", "token") == (False, None)
+
+ def test_malformed_url_raises(self) -> None:
+ with pytest.raises(ValueError):
+ probe_endpoint("https://acme.jfrog.io/evil@path", "token")
+
+
+def _streamed_response(status_code: int = 200, chunks: list[bytes] | None = None) -> MagicMock:
+ response = MagicMock()
+ response.status_code = status_code
+ response.ok = 200 <= status_code < 400
+ response.iter_content.return_value = chunks if chunks is not None else [b"{}"]
+ return response
+
+
+class TestRequestBodyCap:
+ def test_decodes_streamed_body(self) -> None:
+ session = MagicMock()
+ session.request.return_value = _streamed_response(chunks=[b'{"a":', b"1}"])
+
+ result = _request(session, "GET", "https://acme.jfrog.io/api/x", {}, MagicMock())
+
+ assert result == {"a": 1}
+ # stream=True keeps a hostile host's body off the wire until we read it under the cap.
+ assert session.request.call_args.kwargs["stream"] is True
+
+ def test_over_byte_cap_raises_non_retryable(self) -> None:
+ # A hostile/self-hosted host could stream an unbounded (or highly compressed) body and OOM a
+ # shared worker. The read must abort past the byte cap before parsing JSON, with a
+ # non-retryable error (retrying can't shrink the body) — so session.request runs exactly once.
+ session = MagicMock()
+ session.request.return_value = _streamed_response(chunks=[b"aaaa", b"aaaa"])
+
+ with pytest.raises(JfrogArtifactoryResponseTooLargeError) as exc:
+ with pytest.MonkeyPatch.context() as mp:
+ mp.setattr(jfrog_artifactory, "MAX_RESPONSE_BYTES", 4)
+ _request(session, "GET", "https://acme.jfrog.io/api/x", {}, MagicMock())
+
+ assert RESPONSE_LIMIT_ERROR in str(exc.value)
+ assert session.request.call_count == 1
+
+ @parameterized.expand(
+ [
+ # A compact body of many containers or scalars stays under the byte cap but json.loads
+ # allocates one object per value, amplifying far past its size. The token guard counts
+ # `,`/`{`/`[` and must reject either shape before parsing.
+ ("containers", b"[" + b"{}," * 60 + b"{}]"),
+ ("scalars", b'{"results":[' + b"0.0," * 60 + b"0.0]}"),
+ ]
+ )
+ def test_over_token_cap_raises_non_retryable(self, _name: str, body: bytes) -> None:
+ session = MagicMock()
+ session.request.return_value = _streamed_response(chunks=[body])
+
+ with pytest.raises(JfrogArtifactoryResponseTooLargeError) as exc:
+ with pytest.MonkeyPatch.context() as mp:
+ mp.setattr(jfrog_artifactory, "MAX_JSON_TOKENS", 10)
+ _request(session, "GET", "https://acme.jfrog.io/api/x", {}, MagicMock())
+
+ assert RESPONSE_LIMIT_ERROR in str(exc.value)
+ assert session.request.call_count == 1
+
+ def test_transfer_deadline_aborts_slow_stream(self) -> None:
+ # A transfer that keeps yielding chunks but drags past the wall-clock deadline must abort
+ # (before parsing) rather than run indefinitely; the check runs between chunks.
+ session = MagicMock()
+ session.request.return_value = _streamed_response(chunks=[b"a", b"b"])
+
+ with pytest.raises(JfrogArtifactoryResponseTooLargeError) as exc:
+ with pytest.MonkeyPatch.context() as mp:
+ mp.setattr(jfrog_artifactory, "MAX_TRANSFER_SECONDS", -1) # any elapsed time is past it
+ _request(session, "GET", "https://acme.jfrog.io/api/x", {}, MagicMock())
+
+ assert RESPONSE_LIMIT_ERROR in str(exc.value)
+ assert session.request.call_count == 1
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/jfrog_artifactory/tests/test_jfrog_artifactory_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/jfrog_artifactory/tests/test_jfrog_artifactory_source.py
new file mode 100644
index 000000000000..69b76d058b6d
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/jfrog_artifactory/tests/test_jfrog_artifactory_source.py
@@ -0,0 +1,245 @@
+import pytest
+from unittest import mock
+
+from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import (
+ JfrogArtifactorySourceConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.jfrog_artifactory.jfrog_artifactory import (
+ JfrogArtifactoryResumeConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.jfrog_artifactory.settings import (
+ ENDPOINTS,
+ JFROG_ARTIFACTORY_ENDPOINTS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.jfrog_artifactory.source import (
+ JfrogArtifactorySource,
+)
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+# AQL endpoints expose server-side timestamp filters; the REST list endpoints don't.
+_INCREMENTAL_ENDPOINTS = {"artifacts", "builds"}
+_FULL_REFRESH_ENDPOINTS = {"repositories", "storage_summary"}
+
+
+class TestJfrogArtifactorySource:
+ def setup_method(self):
+ self.source = JfrogArtifactorySource()
+ self.team_id = 123
+ self.config = JfrogArtifactorySourceConfig(base_url="https://acme.jfrog.io", access_token="token")
+
+ def test_source_type(self):
+ assert self.source.source_type == ExternalDataSourceType.JFROGARTIFACTORY
+
+ def test_get_source_config(self):
+ config = self.source.get_source_config
+
+ assert config.name.value == "JfrogArtifactory"
+ assert config.label == "JFrog (Artifactory / JFrog Platform)"
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.unreleasedSource is None
+ assert config.iconPath == "/static/services/jfrog_artifactory.png"
+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/jfrog-artifactory"
+
+ field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]
+ assert field_names == ["base_url", "access_token"]
+
+ def test_access_token_field_is_secret_password(self):
+ config = self.source.get_source_config
+ token_field = next(
+ f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "access_token"
+ )
+ assert token_field.type == SourceFieldInputConfigType.PASSWORD
+ assert token_field.secret is True
+ assert token_field.required is True
+
+ def test_base_url_listed_as_connection_host_field(self):
+ # The access token is sent to base_url, so retargeting it must re-require the token.
+ assert self.source.connection_host_fields == ["base_url"]
+
+ @pytest.mark.parametrize(
+ "observed_error",
+ [
+ "401 Client Error: Unauthorized for url: https://acme.jfrog.io/artifactory/api/search/aql",
+ "403 Client Error: Forbidden for url: https://acme.jfrog.io/artifactory/api/storageinfo",
+ ],
+ )
+ def test_non_retryable_errors_match_auth_failures(self, observed_error):
+ non_retryable_errors = self.source.get_non_retryable_errors()
+ assert any(key in observed_error for key in non_retryable_errors)
+
+ @pytest.mark.parametrize(
+ "other_error",
+ [
+ "429 Client Error: Too Many Requests for url: https://acme.jfrog.io/artifactory/api/search/aql",
+ "500 Server Error: Internal Server Error for url: https://acme.jfrog.io/artifactory/api/repositories",
+ "HTTPSConnectionPool(host='acme.jfrog.io', port=443): Read timed out.",
+ ],
+ )
+ def test_non_retryable_errors_do_not_match_transient(self, other_error):
+ non_retryable_errors = self.source.get_non_retryable_errors()
+ assert not any(key in other_error for key in non_retryable_errors)
+
+ def test_get_schemas_match_endpoints_with_correct_sync_modes(self):
+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}
+
+ assert set(schemas) == set(ENDPOINTS)
+ for name in _INCREMENTAL_ENDPOINTS:
+ assert schemas[name].supports_incremental is True
+ assert schemas[name].supports_append is True
+ assert len(schemas[name].incremental_fields) > 0
+ for name in _FULL_REFRESH_ENDPOINTS:
+ assert schemas[name].supports_incremental is False
+ assert schemas[name].supports_append is False
+ assert schemas[name].incremental_fields == []
+
+ def test_get_schemas_admin_endpoints_not_selected_by_default(self):
+ # builds/storage_summary need an admin token; syncing them by default would fail most
+ # non-admin connections.
+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}
+ assert schemas["builds"].should_sync_default is False
+ assert schemas["storage_summary"].should_sync_default is False
+ assert schemas["repositories"].should_sync_default is True
+ assert schemas["artifacts"].should_sync_default is True
+
+ def test_get_schemas_filtered_by_names(self):
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["artifacts"])
+ assert len(schemas) == 1
+ assert schemas[0].name == "artifacts"
+
+ def test_lists_tables_without_credentials_publishes_catalog(self):
+ # Static endpoint catalog (no I/O) — the public docs table list should render.
+ assert self.source.lists_tables_without_credentials is True
+ documented = self.source.get_documented_tables()
+ assert {table["name"] for table in documented} == set(ENDPOINTS)
+
+ def test_canonical_descriptions_cover_every_endpoint(self):
+ canonical = self.source.get_canonical_descriptions()
+ assert set(canonical) == set(JFROG_ARTIFACTORY_ENDPOINTS)
+
+ @pytest.mark.parametrize(
+ "probe_return, schema_name, expected_valid, expected_message_part",
+ [
+ ((True, 200), None, True, None),
+ ((False, 401), None, False, "Invalid JFrog access token"),
+ # A 403 at source-create means the token is genuine but not fully scoped — accept it.
+ ((False, 403), None, True, None),
+ ((False, 403), "builds", False, "admin"),
+ ((False, 403), "artifacts", False, "missing the permissions"),
+ ((False, None), None, False, "Could not connect"),
+ ],
+ )
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.jfrog_artifactory.source.probe_endpoint"
+ )
+ @mock.patch.object(JfrogArtifactorySource, "is_database_host_valid")
+ def test_validate_credentials(
+ self, mock_host_valid, mock_probe, probe_return, schema_name, expected_valid, expected_message_part
+ ):
+ mock_host_valid.return_value = (True, None)
+ mock_probe.return_value = probe_return
+
+ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id, schema_name)
+
+ assert is_valid is expected_valid
+ if expected_message_part is None:
+ assert error_message is None
+ else:
+ assert expected_message_part in (error_message or "")
+
+ @mock.patch.object(JfrogArtifactorySource, "is_database_host_valid")
+ def test_validate_credentials_rejects_unsafe_host(self, mock_host_valid):
+ mock_host_valid.return_value = (False, "Host is not allowed")
+
+ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id)
+
+ assert is_valid is False
+ assert error_message == "Host is not allowed"
+
+ def test_validate_credentials_surfaces_bad_url(self):
+ config = JfrogArtifactorySourceConfig(base_url="https://acme.jfrog.io/evil/path", access_token="token")
+
+ is_valid, error_message = self.source.validate_credentials(config, self.team_id)
+
+ assert is_valid is False
+ assert "Invalid JFrog platform URL" in (error_message or "")
+
+ @pytest.mark.parametrize(
+ "probe_return, endpoint, expected_reason_part",
+ [
+ ((True, 200), "artifacts", None),
+ ((False, 403), "builds", "admin"),
+ ((False, 401), "artifacts", "cannot read"),
+ # A throttle or transient failure is not a missing scope.
+ ((False, 429), "artifacts", None),
+ ((False, None), "builds", None),
+ ],
+ )
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.jfrog_artifactory.source.probe_endpoint"
+ )
+ def test_get_endpoint_permissions(self, mock_probe, probe_return, endpoint, expected_reason_part):
+ mock_probe.return_value = probe_return
+
+ permissions = self.source.get_endpoint_permissions(self.config, self.team_id, [endpoint])
+
+ if expected_reason_part is None:
+ assert permissions[endpoint] is None
+ else:
+ assert expected_reason_part in (permissions[endpoint] or "")
+
+ def test_get_resumable_source_manager_bound_to_resume_config(self):
+ inputs = mock.MagicMock()
+ manager = self.source.get_resumable_source_manager(inputs)
+ assert manager._data_class is JfrogArtifactoryResumeConfig
+
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.jfrog_artifactory.source.jfrog_artifactory_source"
+ )
+ @mock.patch.object(JfrogArtifactorySource, "is_database_host_valid")
+ def test_source_for_pipeline_plumbs_arguments(self, mock_host_valid, mock_source_fn):
+ mock_host_valid.return_value = (True, None)
+ inputs = mock.MagicMock()
+ inputs.schema_name = "artifacts"
+ inputs.team_id = self.team_id
+ inputs.should_use_incremental_field = True
+ inputs.db_incremental_field_last_value = "2026-01-01T00:00:00+00:00"
+ inputs.incremental_field = "modified"
+ manager = mock.MagicMock()
+
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ mock_source_fn.assert_called_once()
+ kwargs = mock_source_fn.call_args.kwargs
+ assert kwargs["base_url"] == "https://acme.jfrog.io"
+ assert kwargs["access_token"] == "token"
+ assert kwargs["endpoint"] == "artifacts"
+ assert kwargs["resumable_source_manager"] is manager
+ assert kwargs["db_incremental_field_last_value"] == "2026-01-01T00:00:00+00:00"
+
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.jfrog_artifactory.source.jfrog_artifactory_source"
+ )
+ @mock.patch.object(JfrogArtifactorySource, "is_database_host_valid")
+ def test_source_for_pipeline_omits_cursor_when_not_incremental(self, mock_host_valid, mock_source_fn):
+ mock_host_valid.return_value = (True, None)
+ inputs = mock.MagicMock()
+ inputs.schema_name = "repositories"
+ inputs.team_id = self.team_id
+ inputs.should_use_incremental_field = False
+ inputs.db_incremental_field_last_value = "2026-01-01T00:00:00+00:00"
+
+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)
+
+ assert mock_source_fn.call_args.kwargs["db_incremental_field_last_value"] is None
+
+ @mock.patch.object(JfrogArtifactorySource, "is_database_host_valid")
+ def test_source_for_pipeline_rejects_unsafe_host(self, mock_host_valid):
+ mock_host_valid.return_value = (False, "Host is not allowed")
+ inputs = mock.MagicMock()
+ inputs.schema_name = "artifacts"
+ inputs.team_id = self.team_id
+
+ with pytest.raises(ValueError, match="Host is not allowed"):
+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)