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): add jfrog artifactory build and xray tables (#112553)

Tom Owers5c138c7a46c5
diff --git a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt b/posthog/test/repo_invariants/dataclass_frozen_baseline.txt
index 7f25c61442f6..865664bd2577 100644
--- a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt
+++ b/posthog/test/repo_invariants/dataclass_frozen_baseline.txt
@@ -712,7 +712,6 @@
1 products/warehouse_sources/backend/temporal/data_imports/sources/jenkins/jenkins.py
1 products/warehouse_sources/backend/temporal/data_imports/sources/jenkins/settings.py
1 products/warehouse_sources/backend/temporal/data_imports/sources/jfrog_artifactory/jfrog_artifactory.py
-1 products/warehouse_sources/backend/temporal/data_imports/sources/jfrog_artifactory/settings.py
1 products/warehouse_sources/backend/temporal/data_imports/sources/jira/jira.py
1 products/warehouse_sources/backend/temporal/data_imports/sources/jira/settings.py
1 products/warehouse_sources/backend/temporal/data_imports/sources/jobnimbus/jobnimbus.py
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 30d73f5798fd..ac358303bd0e 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
@@ -4528,10 +4528,10 @@ Today (4): `artifacts`, `builds`, `repositories`, `storage_summary`
Diffed against: <https://docs.jfrog.com/artifactory/docs/aql-entities-fields-reference.md>
-- [ ] `AQL promotion domain (build promotions)` — build state transition history - when a build moved to which repo, by whom, with what status (high)
-- [ ] `AQL statistic domain (stat.downloads, stat.downloaded, stat.downloaded_by)` — artifact download counts and last-download - the headline consumption metric for a registry (high)
-- [ ] `AQL artifact / module / dependency domains (build artifacts and dependencies)` — line items joining the already-synced builds to the already-synced artifacts, plus the dependency graph (high)
-- [ ] `Xray Get Violations (/xray/api/v1/violations)` — security and license policy violations per artifact/build, the main security-analytics fact table (high)
+- [x] `AQL promotion domain (build promotions)` — build state transition history - when a build moved to which repo, by whom, with what status (high)
+- [x] `AQL statistic domain (stat.downloads, stat.downloaded, stat.downloaded_by)` — artifact download counts and last-download - the headline consumption metric for a registry (high)
+- [x] `AQL artifact / module / dependency domains (build artifacts and dependencies)` — line items joining the already-synced builds to the already-synced artifacts, plus the dependency graph (high)
+- [x] `Xray Get Violations (/xray/api/v1/violations)` — security and license policy violations per artifact/build, the main security-analytics fact table (high)
- [ ] `AQL property domain (artifact properties)` — key/value metadata on artifacts used for promotion and environment labelling (medium)
- [ ] `Xray Artifact Summary / Build Summary (/xray/api/v1/summary/*)` — per-artifact and per-build vulnerability and license rollups (medium)
- [ ] `Release bundles: Get All Bundles / Get All Bundle Versions (AQL release domain)` — release-level grouping of artifacts, the unit teams actually ship (medium)
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
index 1793bf6e4434..74f502bb3821 100644
--- 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
@@ -54,6 +54,81 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"url": "URL of the build run on the CI server.",
},
},
+ "artifact_statistics": {
+ "description": "Download statistics for each artifact that has been downloaded at least once. Queried via AQL over the items domain with the statistic domain fields.",
+ "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.",
+ "created": "Time at which the artifact was first deployed.",
+ "downloads": "Total number of downloads of the artifact.",
+ "downloaded": "Last time the artifact was downloaded.",
+ "downloaded_by": "Name of the last user to download the artifact.",
+ "remote_downloads": "Total number of downloads through a smart remote repository proxying this repository.",
+ "remote_downloaded": "Last time the artifact was downloaded through a smart remote repository proxy.",
+ "remote_downloaded_by": "Name of the last user to download the artifact through a smart remote repository proxy.",
+ },
+ },
+ "build_artifacts": {
+ "description": "Artifacts produced by each build module, one row per artifact in a published build-info. Queried via AQL over the builds domain with module and artifact fields (requires an admin token).",
+ "docs_url": "https://docs.jfrog.com/artifactory/docs/aql-entities-fields-reference",
+ "columns": {
+ "build_name": "Name of the build that produced the artifact.",
+ "build_number": "Run number of the build that produced the artifact.",
+ "build_created": "Time at which the build-info was published.",
+ "module_name": "Name of the build module that produced the artifact.",
+ "name": "Name of the artifact.",
+ "type": "Type of the artifact.",
+ "sha1": "SHA-1 checksum of the artifact.",
+ "md5": "MD5 checksum of the artifact.",
+ },
+ },
+ "build_dependencies": {
+ "description": "Dependencies consumed by each build module, one row per dependency in a published build-info. Queried via AQL over the builds domain with module and dependency fields (requires an admin token).",
+ "docs_url": "https://docs.jfrog.com/artifactory/docs/aql-entities-fields-reference",
+ "columns": {
+ "build_name": "Name of the build that used the dependency.",
+ "build_number": "Run number of the build that used the dependency.",
+ "build_created": "Time at which the build-info was published.",
+ "module_name": "Name of the build module that used the dependency.",
+ "name": "Name of the dependency.",
+ "scope": "Scope of the dependency (e.g. compile, runtime, test).",
+ "type": "Type of the dependency.",
+ "sha1": "SHA-1 checksum of the dependency.",
+ "md5": "MD5 checksum of the dependency.",
+ },
+ },
+ "build_promotions": {
+ "description": "Promotion history of builds: each time a build moved to a repository or changed status. Queried via AQL over the builds domain with promotion fields (requires an admin token).",
+ "docs_url": "https://docs.jfrog.com/artifactory/docs/aql-entities-fields-reference",
+ "columns": {
+ "build_name": "Name of the promoted build.",
+ "build_number": "Run number of the promoted build.",
+ "build_created": "Time at which the build-info was published.",
+ "created": "Time at which the build was promoted.",
+ "created_by": "Artifactory user that promoted the build.",
+ "status": "Status set by the promotion (e.g. staged, released).",
+ "repo": "Repository the build was promoted to.",
+ "comment": "Free-text comment about the promotion.",
+ "user": "CI server user that promoted the build.",
+ },
+ },
+ "xray_violations": {
+ "description": "JFrog Xray security, license, and operational risk policy violations, one row per issue on a component under a watch.",
+ "docs_url": "https://docs.jfrog.com/security/reference/get-violations",
+ "columns": {
+ "description": "Description of the violation.",
+ "severity": "Severity of the violation (Critical, High, Medium, Low, Information, or Unknown).",
+ "type": "Violation type: Security, License, or Operational_Risk.",
+ "infected_components": "Components that triggered the violation.",
+ "created": "Time at which the violation was created.",
+ "watch_name": "Name of the Xray watch that raised the violation.",
+ "issue_id": "Identifier of the Xray issue behind the violation.",
+ "violation_details_url": "Xray API URL with the full details of the violation. Encodes the watch, issue, and component.",
+ "impacted_artifacts": "Artifacts impacted by the violation.",
+ },
+ },
"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",
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
index 215489006c0f..75c3f43a3efa 100644
--- 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
@@ -2,7 +2,7 @@ import json
import time
import dataclasses
from collections.abc import Iterator
-from datetime import UTC, date, datetime
+from datetime import UTC, date, datetime, timedelta
from typing import Any, Optional
from urllib.parse import urlparse
@@ -18,12 +18,22 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.typ
from products.warehouse_sources.backend.temporal.data_imports.sources.jfrog_artifactory.settings import (
AQL_PAGE_SIZE,
JFROG_ARTIFACTORY_ENDPOINTS,
+ XRAY_PAGE_SIZE,
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"
+XRAY_API_PATH = "/xray/api"
+
+# Xray's v1 violations search answers 429 once a query scrolls past 50,000 matching violations, so
+# restart the scroll from the last seen creation time well before that depth.
+XRAY_MAX_SCROLL_ROWS = 10_000
+
+# Artifactory defaults to a 6,000-byte AQL query limit. Related-domain requests use an `$or`
+# clause per parent, so split before sending rather than relying only on the response-size guard.
+AQL_RELATED_QUERY_MAX_BYTES = 6_000
REQUEST_TIMEOUT_SECONDS = 120
PROBE_TIMEOUT_SECONDS = 30
@@ -156,6 +166,10 @@ def _api_url(base_url: str, path: str) -> str:
return f"{normalize_base_url(base_url)}{ARTIFACTORY_API_PATH}{path}"
+def _xray_url(base_url: str, path: str) -> str:
+ return f"{normalize_base_url(base_url)}{XRAY_API_PATH}{path}"
+
+
def _headers(access_token: str) -> dict[str, str]:
return {"Authorization": f"Bearer {access_token}", "Accept": "application/json"}
@@ -193,12 +207,36 @@ def build_aql_query(
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 ""
+ criteria_fields = dict(config.aql_criteria)
+ if incremental_filter_value:
+ criteria_fields[sort_field] = {"$gt": incremental_filter_value}
+ criteria = json.dumps(criteria_fields) if criteria_fields 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})"
+def build_related_aql_query(config: JfrogArtifactoryEndpointConfig, parents: list[dict[str, Any]]) -> str:
+ """Build the unpaginated query that fetches related-domain fields for one chunk of parent rows.
+
+ The chunk bounds the result set, so no .sort()/.offset()/.limit() is needed (AQL would ignore
+ them anyway once .include() names a related domain).
+ """
+ criteria = {"$or": [{key: parent.get(key) for key in config.aql_key_fields} for parent in parents]}
+ include = ", ".join(f'"{field}"' for field in (*config.aql_fields, *config.aql_related_fields))
+ return f"{config.aql_domain}.find({json.dumps(criteria)}).include({include})"
+
+
+def build_xray_violations_request(
+ created_from: str | None = None, page: int = 1, limit: int = XRAY_PAGE_SIZE
+) -> dict[str, Any]:
+ # Xray's `offset` is a 1-based page number, not a row offset.
+ return {
+ "filters": {"created_from": created_from} if created_from else {},
+ "pagination": {"order_by": "created", "direction": "asc", "limit": limit, "offset": page},
+ }
+
+
@retry(
retry=retry_if_exception_type(
(
@@ -250,6 +288,18 @@ def _post_aql(
return _request(session, "POST", _api_url(base_url, "/search/aql"), headers, logger, data=query)
+def _post_xray(
+ session: requests.Session,
+ base_url: str,
+ access_token: str,
+ path: str,
+ body: dict[str, Any],
+ logger: FilteringBoundLogger,
+) -> dict[str, Any]:
+ headers = {**_headers(access_token), "Content-Type": "application/json"}
+ return _request(session, "POST", _xray_url(base_url, path), headers, logger, data=json.dumps(body))
+
+
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
@@ -258,31 +308,92 @@ def _strip_domain_prefix(item: dict[str, Any], domain: str) -> dict[str, Any]:
return {(key[len(prefix) :] if key.startswith(prefix) else key): value for key, value in item.items()}
-def get_rows(
+def _related_children(node: dict[str, Any], plural: str) -> list[dict[str, Any]]:
+ # Related-domain output nests under a plural key, e.g. "modules" or "build.promotions".
+ for key, value in node.items():
+ if isinstance(value, list) and (key == plural or key.endswith(f".{plural}")):
+ return value
+ return []
+
+
+def _walk_related(
+ node: dict[str, Any], levels: tuple[tuple[str, str], ...], row: dict[str, Any]
+) -> Iterator[dict[str, Any]]:
+ plural, domain = levels[0]
+ prefix = f"{domain}."
+ for child in _related_children(node, plural):
+ fields = {
+ key.removeprefix(prefix): value for key, value in child.items() if not isinstance(value, (list, dict))
+ }
+ if len(levels) == 1:
+ yield {**row, **fields}
+ else:
+ yield from _walk_related(child, levels[1:], {**row, **{f"{domain}_{k}": v for k, v in fields.items()}})
+
+
+def flatten_related(config: JfrogArtifactoryEndpointConfig, item: dict[str, Any]) -> Iterator[dict[str, Any]]:
+ """Emit one row per leaf related entry, carrying the parent and intermediate-level fields."""
+ parent = _strip_domain_prefix(item, config.aql_domain)
+ row = {f"{config.parent_field_prefix}{key}": parent.get(key) for key in config.aql_fields}
+ yield from _walk_related(item, config.aql_related_path, row)
+
+
+def _fetch_related(
+ session: requests.Session,
base_url: str,
access_token: str,
- endpoint: str,
+ config: JfrogArtifactoryEndpointConfig,
+ parents: list[dict[str, Any]],
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)
+) -> Iterator[list[dict[str, Any]]]:
+ query = build_related_aql_query(config, parents)
+ if len(query.encode()) > AQL_RELATED_QUERY_MAX_BYTES and len(parents) > 1:
+ middle = len(parents) // 2
+ yield from _fetch_related(session, base_url, access_token, config, parents[:middle], logger)
+ yield from _fetch_related(session, base_url, access_token, config, parents[middle:], logger)
+ return
- 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
+ try:
+ data = _post_aql(session, base_url, access_token, query, logger)
+ except JfrogArtifactoryResponseTooLargeError:
+ # A few very large builds can push one chunk past the response cap; split until it fits.
+ # Each half yields on its own so split responses never pile up in memory.
+ if len(parents) <= 1:
+ raise
+ middle = len(parents) // 2
+ yield from _fetch_related(session, base_url, access_token, config, parents[:middle], logger)
+ yield from _fetch_related(session, base_url, access_token, config, parents[middle:], logger)
return
+ rows: list[dict[str, Any]] = []
+ seen: set[tuple[Any, ...]] = set()
+ for item in data.get("results", []):
+ for row in flatten_related(config, item):
+ key = tuple(row.get(field) for field in config.primary_keys)
+ if key in seen:
+ continue
+ seen.add(key)
+ rows.append(row)
+ if rows:
+ yield rows
+
+
+def _iter_aql_pages(
+ session: requests.Session,
+ base_url: str,
+ access_token: str,
+ config: JfrogArtifactoryEndpointConfig,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[JfrogArtifactoryResumeConfig],
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Any,
+ incremental_field: str | None,
+) -> Iterator[list[dict[str, Any]]]:
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}")
+ logger.debug(f"JFrog Artifactory: resuming {config.name} from offset {offset}")
else:
offset = 0
filter_value = (
@@ -309,6 +420,129 @@ def get_rows(
resumable_source_manager.save_state(
JfrogArtifactoryResumeConfig(next_offset=offset, incremental_filter_value=filter_value)
)
+ resumable_source_manager.safe_point()
+
+
+def _xray_restart_filter(last_created: Any, current_filter: str | None) -> str | None:
+ """Return a `created_from` that restarts the scroll near the last row, or None to keep paging.
+
+ Backs off one second in case `created_from` is exclusive; the overlap re-reads a few rows,
+ which merge dedupes on the primary key. Returns None when the restart wouldn't move forward
+ (e.g. more than a scroll's worth of violations share one timestamp).
+ """
+ if not isinstance(last_created, str):
+ return None
+ try:
+ restart = datetime.fromisoformat(last_created) - timedelta(seconds=1)
+ if current_filter is not None and restart <= datetime.fromisoformat(current_filter):
+ return None
+ except ValueError:
+ return None
+ return _format_aql_datetime(restart)
+
+
+def _iter_xray_violations(
+ session: requests.Session,
+ base_url: str,
+ access_token: str,
+ config: JfrogArtifactoryEndpointConfig,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[JfrogArtifactoryResumeConfig],
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Any,
+) -> Iterator[list[dict[str, Any]]]:
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ if resume is not None and resume.next_offset:
+ page = resume.next_offset
+ filter_value = resume.incremental_filter_value
+ else:
+ page = 1
+ filter_value = (
+ _format_aql_datetime(db_incremental_field_last_value)
+ if should_use_incremental_field and db_incremental_field_last_value
+ else None
+ )
+
+ while True:
+ body = build_xray_violations_request(filter_value, page)
+ data = _post_xray(session, base_url, access_token, config.path, body, logger)
+ violations = data.get("violations") or []
+ if not violations:
+ break
+
+ has_more = len(violations) >= XRAY_PAGE_SIZE
+ yield violations
+
+ if not has_more:
+ break
+ page += 1
+ if (page - 1) * XRAY_PAGE_SIZE >= XRAY_MAX_SCROLL_ROWS:
+ restart_filter = _xray_restart_filter(violations[-1].get("created"), filter_value)
+ if restart_filter is not None:
+ filter_value, page = restart_filter, 1
+ resumable_source_manager.save_state(
+ JfrogArtifactoryResumeConfig(next_offset=page, incremental_filter_value=filter_value)
+ )
+ resumable_source_manager.safe_point()
+
+
+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
+
+ if config.kind == "xray":
+ yield from _iter_xray_violations(
+ session,
+ base_url,
+ access_token,
+ config,
+ logger,
+ resumable_source_manager,
+ should_use_incremental_field,
+ db_incremental_field_last_value,
+ )
+ return
+
+ # Related-domain tables expose parent fields as e.g. `build_created`; the parent query filters
+ # and sorts on the bare primary-domain field.
+ parent_incremental_field = incremental_field.removeprefix(config.parent_field_prefix) if incremental_field else None
+ pages = _iter_aql_pages(
+ session,
+ base_url,
+ access_token,
+ config,
+ logger,
+ resumable_source_manager,
+ should_use_incremental_field,
+ db_incremental_field_last_value,
+ parent_incremental_field,
+ )
+
+ if config.kind == "aql":
+ yield from pages
+ return
+
+ for parents in pages:
+ for start in range(0, len(parents), config.aql_related_chunk_size):
+ yield from _fetch_related(
+ session, base_url, access_token, config, parents[start : start + config.aql_related_chunk_size], logger
+ )
def jfrog_artifactory_source(
@@ -355,7 +589,15 @@ def probe_endpoint(base_url: str, access_token: str, endpoint: str | None = None
# 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":
+ if config is not None and config.kind == "xray":
+ response = session.post(
+ _xray_url(base_url, config.path),
+ headers={**_headers(access_token), "Content-Type": "application/json"},
+ data=json.dumps(build_xray_violations_request(limit=1)),
+ timeout=PROBE_TIMEOUT_SECONDS,
+ stream=True,
+ )
+ elif config is not None and config.kind in ("aql", "aql_related"):
# 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)
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
index 1e7c9908a362..ca6367a22d76 100644
--- 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
@@ -1,5 +1,5 @@
from dataclasses import dataclass, field
-from typing import Literal, Optional
+from typing import Any, Literal, Optional
from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
@@ -7,6 +7,9 @@ from products.warehouse_sources.backend.types import IncrementalField, Increment
# while limiting round trips; the AQL server-side hard limit is far above this.
AQL_PAGE_SIZE = 1000
+# Xray's v1 violations API defaults to 25 rows per page and doesn't document a maximum.
+XRAY_PAGE_SIZE = 100
+
def _datetime_incremental_fields(*names: str) -> list[IncrementalField]:
return [
@@ -20,12 +23,16 @@ def _datetime_incremental_fields(*names: str) -> list[IncrementalField]:
]
-@dataclass
+@dataclass(frozen=True)
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"]
+ # AQL query to /artifactory/api/search/aql with in-body offset/limit pagination. "aql_related"
+ # endpoints page the primary domain the same way, then fetch related-domain fields (stats,
+ # modules, promotions) for each chunk of that page in a second, unpaginated query, because AQL
+ # ignores .sort()/.offset()/.limit() once .include() names a related domain. "xray" is the
+ # Xray v1 violations search.
+ kind: Literal["rest", "aql", "aql_related", "xray"]
# 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.
@@ -35,6 +42,21 @@ class JfrogArtifactoryEndpointConfig:
# 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 only: static criteria merged into the primary-domain .find(). Related-domain criteria are
+ # allowed here; only .include() is limited to the primary domain.
+ aql_criteria: dict[str, Any] = field(default_factory=dict)
+ # aql_related only: primary-domain fields that identify a parent row in the related query.
+ aql_key_fields: tuple[str, ...] = ()
+ # aql_related only: related-domain fields for the second query's .include().
+ aql_related_fields: tuple[str, ...] = ()
+ # aql_related only: nested (list key, domain) levels to walk in the related query's output,
+ # e.g. (("modules", "module"), ("artifacts", "artifact")). One row is emitted per leaf entry.
+ aql_related_path: tuple[tuple[str, str], ...] = ()
+ # aql_related only: prefix for parent fields in emitted rows, e.g. "build_" -> build_name.
+ parent_field_prefix: str = ""
+ # aql_related only: parents per related query. Kept small where one parent fans out to many
+ # rows so a related response stays well under MAX_RESPONSE_BYTES.
+ aql_related_chunk_size: int = 100
# AQL exposes server-side timestamp filters ({"modified":{"$gt":...}}); the REST list
# endpoints here have none, so they stay full refresh.
supports_incremental: bool = False
@@ -95,6 +117,115 @@ JFROG_ARTIFACTORY_ENDPOINTS: dict[str, JfrogArtifactoryEndpointConfig] = {
# so don't select this table by default for tokens that can't reach it.
should_sync_default=False,
),
+ "artifact_statistics": JfrogArtifactoryEndpointConfig(
+ name="artifact_statistics",
+ kind="aql_related",
+ aql_domain="items",
+ aql_fields=("repo", "path", "name", "created"),
+ # Only artifacts that have been downloaded carry download statistics.
+ aql_criteria={"stat.downloads": {"$gt": 0}},
+ aql_key_fields=("repo", "path", "name"),
+ aql_related_fields=(
+ "stat.downloads",
+ "stat.downloaded",
+ "stat.downloaded_by",
+ "stat.remote_downloads",
+ "stat.remote_downloaded",
+ "stat.remote_downloaded_by",
+ ),
+ aql_related_path=(("stats", "stat"),),
+ aql_related_chunk_size=250,
+ # Download stats change on every download and AQL can't sort by a related-domain field,
+ # so there is no ascending cursor to sync incrementally on.
+ default_incremental_field="created",
+ primary_keys=["repo", "path", "name"],
+ ),
+ "build_artifacts": JfrogArtifactoryEndpointConfig(
+ name="build_artifacts",
+ kind="aql_related",
+ aql_domain="builds",
+ aql_fields=("name", "number", "created"),
+ aql_key_fields=("name", "number"),
+ aql_related_fields=(
+ "module.name",
+ "module.artifact.name",
+ "module.artifact.type",
+ "module.artifact.sha1",
+ "module.artifact.md5",
+ ),
+ aql_related_path=(("modules", "module"), ("artifacts", "artifact")),
+ parent_field_prefix="build_",
+ aql_related_chunk_size=10,
+ # Build-info is immutable once published, so a build's artifacts never change after its
+ # creation time.
+ supports_incremental=True,
+ default_incremental_field="created",
+ incremental_fields=_datetime_incremental_fields("build_created"),
+ partition_key="build_created",
+ primary_keys=["build_name", "build_number", "module_name", "name"],
+ should_sync_default=False,
+ ),
+ "build_dependencies": JfrogArtifactoryEndpointConfig(
+ name="build_dependencies",
+ kind="aql_related",
+ aql_domain="builds",
+ aql_fields=("name", "number", "created"),
+ aql_key_fields=("name", "number"),
+ aql_related_fields=(
+ "module.name",
+ "module.dependency.name",
+ "module.dependency.scope",
+ "module.dependency.type",
+ "module.dependency.sha1",
+ "module.dependency.md5",
+ ),
+ aql_related_path=(("modules", "module"), ("dependencies", "dependency")),
+ parent_field_prefix="build_",
+ aql_related_chunk_size=10,
+ supports_incremental=True,
+ default_incremental_field="created",
+ incremental_fields=_datetime_incremental_fields("build_created"),
+ partition_key="build_created",
+ primary_keys=["build_name", "build_number", "module_name", "name"],
+ should_sync_default=False,
+ ),
+ "build_promotions": JfrogArtifactoryEndpointConfig(
+ name="build_promotions",
+ kind="aql_related",
+ aql_domain="builds",
+ aql_fields=("name", "number", "created"),
+ aql_key_fields=("name", "number"),
+ aql_related_fields=(
+ "promotion.created",
+ "promotion.created_by",
+ "promotion.status",
+ "promotion.repo",
+ "promotion.comment",
+ "promotion.user",
+ ),
+ aql_related_path=(("promotions", "promotion"),),
+ parent_field_prefix="build_",
+ # Old builds get promoted long after they're created, so a cursor on the build's creation
+ # time would miss new promotions. Full refresh only.
+ default_incremental_field="created",
+ partition_key="created",
+ primary_keys=["build_name", "build_number", "created", "status"],
+ should_sync_default=False,
+ ),
+ "xray_violations": JfrogArtifactoryEndpointConfig(
+ name="xray_violations",
+ kind="xray",
+ path="/v1/violations",
+ supports_incremental=True,
+ default_incremental_field="created",
+ incremental_fields=_datetime_incremental_fields("created"),
+ partition_key="created",
+ # A violation is one issue on one component under one watch; the details URL encodes all three
+ # (watch_id, issue_id, comp_id) and is the only per-violation identifier the API returns.
+ primary_keys=["violation_details_url"],
+ # Needs JFrog Xray, which not every instance has.
+ should_sync_default=False,
+ ),
"storage_summary": JfrogArtifactoryEndpointConfig(
name="storage_summary",
kind="rest",
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 49a19a120ee5..67a8876d7b06 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
@@ -33,7 +33,9 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.jfrog_arti
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"}
+_ADMIN_ENDPOINTS = {"builds", "build_artifacts", "build_dependencies", "build_promotions", "storage_summary"}
+_XRAY_ENDPOINTS = {"xray_violations"}
+_XRAY_UNAVAILABLE = "Requires JFrog Xray and a token with Xray Read permission"
@SourceRegistry.register
@@ -63,7 +65,7 @@ class JfrogArtifactorySource(
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.""",
+The `artifacts`, `artifact_statistics`, and `repositories` tables work with any authenticated token that can read your repositories. The `builds`, `build_artifacts`, `build_dependencies`, `build_promotions`, and `storage_summary` tables require an admin user (or a token scoped to those APIs). The `xray_violations` table requires JFrog Xray. Deselect any table your token can't access.""",
iconPath="/static/services/jfrog_artifactory.png",
docsUrl="https://posthog.com/docs/cdp/sources/jfrog-artifactory",
fields=cast(
@@ -102,7 +104,7 @@ The `artifacts` and `repositories` tables work with any authenticated token that
# 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.",
+ "403 Client Error: Forbidden for url": "Your JFrog access token is missing the permissions needed to sync this data. The build and storage_summary tables require an admin token, and xray_violations requires JFrog Xray. Deselect them or use a token with the required access.",
}
def get_schemas(
@@ -115,8 +117,12 @@ The `artifacts` and `repositories` tables work with any authenticated token that
api_version: str | None = None,
) -> list[SourceSchema]:
def _description(endpoint: str) -> str | None:
- if endpoint == "builds":
+ if endpoint in ("builds", "build_artifacts", "build_dependencies", "build_promotions"):
return "Requires an admin user or a token scoped to the builds domain"
+ if endpoint == "artifact_statistics":
+ return "Download counts for artifacts that have been downloaded at least once"
+ if endpoint in _XRAY_ENDPOINTS:
+ return _XRAY_UNAVAILABLE
if endpoint == "storage_summary":
return "Point-in-time snapshot of per-repository storage usage. Requires an admin token"
return None
@@ -166,6 +172,9 @@ The `artifacts` and `repositories` tables work with any authenticated token that
return True, None
if status_code == 401:
return False, "Invalid JFrog access token"
+ if schema_name in _XRAY_ENDPOINTS and status_code in (403, 404):
+ # Xray answers 404 when it isn't installed or hides unauthorized resources.
+ return False, f"Your JFrog instance can't serve the {schema_name} table. {_XRAY_UNAVAILABLE}"
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.
@@ -194,8 +203,12 @@ The `artifacts` and `repositories` tables work with any authenticated token that
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):
+ if endpoint in _XRAY_ENDPOINTS and status_code == 404:
+ permissions[endpoint] = _XRAY_UNAVAILABLE
+ elif ok or status_code not in (401, 403):
permissions[endpoint] = None
+ elif endpoint in _XRAY_ENDPOINTS:
+ permissions[endpoint] = _XRAY_UNAVAILABLE
elif endpoint in _ADMIN_ENDPOINTS:
permissions[endpoint] = "Requires an admin user or a token scoped to this API"
else:
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
index dfcc77e9f65e..fc3bb21de667 100644
--- 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
@@ -1,3 +1,5 @@
+import json
+import dataclasses
from datetime import UTC, date, datetime
from typing import Any
@@ -15,6 +17,9 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.jfrog_arti
_request,
_strip_domain_prefix,
build_aql_query,
+ build_related_aql_query,
+ build_xray_violations_request,
+ flatten_related,
get_rows,
jfrog_artifactory_source,
normalize_base_url,
@@ -23,6 +28,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.jfrog_arti
from products.warehouse_sources.backend.temporal.data_imports.sources.jfrog_artifactory.settings import (
AQL_PAGE_SIZE,
JFROG_ARTIFACTORY_ENDPOINTS,
+ XRAY_PAGE_SIZE,
)
@@ -109,11 +115,34 @@ class TestBuildAqlQuery:
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":
+ if config.kind not in ("aql", "aql_related"):
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
+ assert incremental_field["field"].removeprefix(config.parent_field_prefix) in config.aql_fields
+
+ def test_static_criteria_combined_with_incremental_filter(self) -> None:
+ query = build_aql_query(
+ JFROG_ARTIFACTORY_ENDPOINTS["artifact_statistics"],
+ incremental_field="created",
+ incremental_filter_value="2026-03-04T00:00:00.000+00:00",
+ )
+ assert query.startswith(
+ 'items.find({"stat.downloads": {"$gt": 0}, "created": {"$gt": "2026-03-04T00:00:00.000+00:00"}})'
+ )
+ # The parent page include stays primary-domain only, or AQL ignores sort/offset/limit.
+ assert '.include("repo", "path", "name", "created")' in query
+
+ def test_related_query_selects_chunk_without_pagination(self) -> None:
+ query = build_related_aql_query(
+ JFROG_ARTIFACTORY_ENDPOINTS["build_promotions"],
+ [{"name": "app", "number": "1", "created": "x"}, {"name": "app", "number": "2", "created": "y"}],
+ )
+ assert query.startswith(
+ 'builds.find({"$or": [{"name": "app", "number": "1"}, {"name": "app", "number": "2"}]})'
+ )
+ assert '"promotion.created"' in query
+ assert ".sort(" not in query and ".offset(" not in query and ".limit(" not in query
class TestStripDomainPrefix:
@@ -128,6 +157,85 @@ class TestStripDomainPrefix:
assert _strip_domain_prefix(item, domain) == expected
+class TestFlattenRelated:
+ @parameterized.expand(
+ [
+ (
+ "bare_nested_keys",
+ {
+ "build.name": "app",
+ "build.number": "7",
+ "build.created": "2026-01-01",
+ "modules": [
+ {"module.name": "core", "artifacts": [{"artifact.name": "core.jar", "artifact.sha1": "a1"}]},
+ {"module.name": "web", "artifacts": [{"artifact.name": "web.war", "artifact.sha1": "b2"}]},
+ ],
+ },
+ ),
+ (
+ "prefixed_nested_keys",
+ {
+ "name": "app",
+ "number": "7",
+ "created": "2026-01-01",
+ "build.modules": [
+ {"name": "core", "module.artifacts": [{"name": "core.jar", "sha1": "a1"}]},
+ {"name": "web", "module.artifacts": [{"name": "web.war", "sha1": "b2"}]},
+ ],
+ },
+ ),
+ ]
+ )
+ def test_build_artifacts_one_row_per_module_artifact(self, _name: str, item: dict) -> None:
+ rows = list(flatten_related(JFROG_ARTIFACTORY_ENDPOINTS["build_artifacts"], item))
+
+ assert rows == [
+ {
+ "build_name": "app",
+ "build_number": "7",
+ "build_created": "2026-01-01",
+ "module_name": "core",
+ "name": "core.jar",
+ "sha1": "a1",
+ },
+ {
+ "build_name": "app",
+ "build_number": "7",
+ "build_created": "2026-01-01",
+ "module_name": "web",
+ "name": "web.war",
+ "sha1": "b2",
+ },
+ ]
+
+ def test_artifact_statistics_merges_stat_into_item(self) -> None:
+ item = {
+ "repo": "libs",
+ "path": "com/acme",
+ "name": "a.jar",
+ "created": "2026-01-01",
+ "stats": [{"downloads": 12, "downloaded": "2026-02-01", "downloaded_by": "ci"}],
+ }
+
+ rows = list(flatten_related(JFROG_ARTIFACTORY_ENDPOINTS["artifact_statistics"], item))
+
+ assert rows == [
+ {
+ "repo": "libs",
+ "path": "com/acme",
+ "name": "a.jar",
+ "created": "2026-01-01",
+ "downloads": 12,
+ "downloaded": "2026-02-01",
+ "downloaded_by": "ci",
+ }
+ ]
+
+ def test_parent_without_related_entries_emits_nothing(self) -> None:
+ item = {"build.name": "app", "build.number": "7", "build.created": "2026-01-01"}
+ assert list(flatten_related(JFROG_ARTIFACTORY_ENDPOINTS["build_promotions"], item)) == []
+
+
class _FakeResumableManager:
def __init__(self, state: JfrogArtifactoryResumeConfig | None = None) -> None:
self._state = state
@@ -142,6 +250,9 @@ class _FakeResumableManager:
def save_state(self, data: JfrogArtifactoryResumeConfig) -> None:
self.saved.append(data)
+ def safe_point(self) -> None:
+ pass
+
def _patch_aql(monkeypatch: Any, pages: dict[str, dict]) -> list[str]:
queries: list[str] = []
@@ -272,6 +383,232 @@ class TestGetRowsAql:
assert rows == [{"name": "app", "number": "42", "created": "2026-01-01"}]
+def _build(number: int) -> dict:
+ return {"build.name": "app", "build.number": str(number), "build.created": f"2026-01-01T00:00:{number:02d}"}
+
+
+def _promotions_for(query: str) -> dict:
+ criteria = json.loads(query[len("builds.find(") : query.index(").include(")])
+ return {
+ "results": [
+ {
+ "build.name": parent["name"],
+ "build.number": parent["number"],
+ "build.created": "2026-01-01",
+ "promotions": [{"promotion.created": f"2026-02-{parent['number']}", "promotion.status": "released"}],
+ }
+ for parent in criteria["$or"]
+ ]
+ }
+
+
+def _patch_related_aql(monkeypatch: Any, parent_pages: dict[str, dict], related: Any) -> 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)
+ if ".offset(" in query:
+ return parent_pages[query]
+ return related(query)
+
+ monkeypatch.setattr(jfrog_artifactory, "_post_aql", fake_post_aql)
+ return queries
+
+
+class TestGetRowsAqlRelated:
+ def test_fetches_related_rows_per_chunk_and_saves_state_per_parent_page(self, monkeypatch: Any) -> None:
+ config = dataclasses.replace(JFROG_ARTIFACTORY_ENDPOINTS["build_promotions"], aql_related_chunk_size=2)
+ monkeypatch.setitem(JFROG_ARTIFACTORY_ENDPOINTS, "build_promotions", config)
+ full_page = [_build(i) for i in range(AQL_PAGE_SIZE)]
+ page_1 = build_aql_query(config, offset=0)
+ page_2 = build_aql_query(config, offset=AQL_PAGE_SIZE)
+ queries = _patch_related_aql(
+ monkeypatch,
+ {page_1: {"results": full_page}, page_2: {"results": [_build(99)]}},
+ _promotions_for,
+ )
+ manager = _FakeResumableManager()
+
+ rows = _collect(manager, endpoint="build_promotions")
+
+ assert len(rows) == AQL_PAGE_SIZE + 1
+ assert rows[0] == {
+ "build_name": "app",
+ "build_number": "0",
+ "build_created": "2026-01-01",
+ "created": "2026-02-0",
+ "status": "released",
+ }
+ related_queries = [q for q in queries if ".offset(" not in q]
+ assert len(related_queries) == AQL_PAGE_SIZE // 2 + 1
+ assert manager.saved == [JfrogArtifactoryResumeConfig(next_offset=AQL_PAGE_SIZE, incremental_filter_value=None)]
+
+ def test_incremental_cursor_on_build_created_filters_parent_created(self, monkeypatch: Any) -> None:
+ config = JFROG_ARTIFACTORY_ENDPOINTS["build_artifacts"]
+ parent_query = build_aql_query(
+ config, incremental_field="created", incremental_filter_value="2026-03-04T00:00:00.000+00:00"
+ )
+ queries = _patch_related_aql(monkeypatch, {parent_query: {"results": []}}, lambda q: {"results": []})
+
+ _collect(
+ _FakeResumableManager(),
+ endpoint="build_artifacts",
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2026, 3, 4, tzinfo=UTC),
+ incremental_field="build_created",
+ )
+
+ assert queries == [parent_query]
+
+ def test_oversized_related_query_splits_before_request(self, monkeypatch: Any) -> None:
+ config = JFROG_ARTIFACTORY_ENDPOINTS["build_promotions"]
+ parents = [_build(i) for i in range(4)]
+ two_parent_query = build_related_aql_query(config, parents[:2])
+ monkeypatch.setattr(jfrog_artifactory, "AQL_RELATED_QUERY_MAX_BYTES", len(two_parent_query.encode()) - 1)
+ queries = _patch_related_aql(
+ monkeypatch, {build_aql_query(config, offset=0): {"results": parents}}, _promotions_for
+ )
+
+ rows = _collect(_FakeResumableManager(), endpoint="build_promotions")
+
+ assert sorted(r["build_number"] for r in rows) == ["0", "1", "2", "3"]
+ assert all(query.count('{"name"') == 1 for query in queries if ".offset(" not in query)
+
+ def test_oversized_related_response_splits_chunk(self, monkeypatch: Any) -> None:
+ config = JFROG_ARTIFACTORY_ENDPOINTS["build_promotions"]
+ parents = [_build(i) for i in range(4)]
+
+ def related(query: str) -> dict:
+ if query.count('{"name"') > 1:
+ raise JfrogArtifactoryResponseTooLargeError(RESPONSE_LIMIT_ERROR)
+ return _promotions_for(query)
+
+ _patch_related_aql(monkeypatch, {build_aql_query(config, offset=0): {"results": parents}}, related)
+
+ rows = _collect(_FakeResumableManager(), endpoint="build_promotions")
+
+ assert sorted(r["build_number"] for r in rows) == ["0", "1", "2", "3"]
+
+ def test_single_parent_over_cap_still_raises(self, monkeypatch: Any) -> None:
+ config = JFROG_ARTIFACTORY_ENDPOINTS["build_promotions"]
+
+ def related(query: str) -> dict:
+ raise JfrogArtifactoryResponseTooLargeError(RESPONSE_LIMIT_ERROR)
+
+ _patch_related_aql(monkeypatch, {build_aql_query(config, offset=0): {"results": [_build(1)]}}, related)
+
+ with pytest.raises(JfrogArtifactoryResponseTooLargeError):
+ _collect(_FakeResumableManager(), endpoint="build_promotions")
+
+ def test_duplicate_related_entries_are_dropped(self, monkeypatch: Any) -> None:
+ # Duplicate primary keys in one batch would seed duplicate rows that every later merge multi-matches.
+ config = JFROG_ARTIFACTORY_ENDPOINTS["build_dependencies"]
+ dependency = {"dependency.name": "lib", "dependency.scope": "compile"}
+ _patch_related_aql(
+ monkeypatch,
+ {build_aql_query(config, offset=0): {"results": [_build(1)]}},
+ lambda q: {
+ "results": [
+ {
+ "build.name": "app",
+ "build.number": "1",
+ "build.created": "2026-01-01",
+ "modules": [{"module.name": "core", "dependencies": [dependency, dependency]}],
+ }
+ ]
+ },
+ )
+
+ rows = _collect(_FakeResumableManager(), endpoint="build_dependencies")
+
+ assert [(r["module_name"], r["name"]) for r in rows] == [("core", "lib")]
+
+
+def _violation(created: str) -> dict:
+ return {"issue_id": "XRAY-1", "created": created, "violation_details_url": f"https://x/{created}"}
+
+
+def _patch_xray(monkeypatch: Any, responder: Any) -> list[dict]:
+ bodies: list[dict] = []
+
+ def fake_post_xray(session: Any, base_url: str, access_token: str, path: str, body: dict, logger: Any) -> dict:
+ assert path == "/v1/violations"
+ bodies.append(body)
+ return responder(body)
+
+ monkeypatch.setattr(jfrog_artifactory, "_post_xray", fake_post_xray)
+ return bodies
+
+
+class TestGetRowsXray:
+ def test_pages_ascending_from_watermark_until_short_page(self, monkeypatch: Any) -> None:
+ pages = {
+ 1: [_violation("2026-03-05T00:00:00+00:00")] * XRAY_PAGE_SIZE,
+ 2: [_violation("2026-03-06T00:00:00+00:00")],
+ }
+ bodies = _patch_xray(monkeypatch, lambda body: {"violations": pages[body["pagination"]["offset"]]})
+ manager = _FakeResumableManager()
+
+ rows = _collect(
+ manager,
+ endpoint="xray_violations",
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2026, 3, 4, tzinfo=UTC),
+ incremental_field="created",
+ )
+
+ assert len(rows) == XRAY_PAGE_SIZE + 1
+ assert bodies == [
+ build_xray_violations_request("2026-03-04T00:00:00.000+00:00", 1),
+ build_xray_violations_request("2026-03-04T00:00:00.000+00:00", 2),
+ ]
+ assert bodies[0]["pagination"]["order_by"] == "created"
+ assert bodies[0]["pagination"]["direction"] == "asc"
+ assert manager.saved == [
+ JfrogArtifactoryResumeConfig(next_offset=2, incremental_filter_value="2026-03-04T00:00:00.000+00:00")
+ ]
+
+ def test_full_refresh_sends_no_created_from(self, monkeypatch: Any) -> None:
+ bodies = _patch_xray(monkeypatch, lambda body: {"violations": []})
+
+ _collect(_FakeResumableManager(), endpoint="xray_violations")
+
+ assert bodies == [build_xray_violations_request(None, 1)]
+ assert bodies[0]["filters"] == {}
+
+ def test_restarts_scroll_from_last_created_before_depth_cap(self, monkeypatch: Any) -> None:
+ monkeypatch.setattr(jfrog_artifactory, "XRAY_MAX_SCROLL_ROWS", 2 * XRAY_PAGE_SIZE)
+ calls: list[tuple[str | None, int]] = []
+
+ def responder(body: dict) -> dict:
+ calls.append((body["filters"].get("created_from"), body["pagination"]["offset"]))
+ if len(calls) == 1:
+ return {"violations": [_violation("2026-03-05T10:00:00+00:00")] * XRAY_PAGE_SIZE}
+ if len(calls) == 2:
+ return {"violations": [_violation("2026-03-05T12:00:00+02:00")] * XRAY_PAGE_SIZE}
+ return {"violations": []}
+
+ _patch_xray(monkeypatch, responder)
+
+ _collect(_FakeResumableManager(), endpoint="xray_violations")
+
+ # After two pages the scroll restarts one second before the last row's created time (in UTC).
+ assert calls == [(None, 1), (None, 2), ("2026-03-05T09:59:59.000+00:00", 1)]
+
+ def test_resumes_saved_page_and_filter(self, monkeypatch: Any) -> None:
+ bodies = _patch_xray(monkeypatch, lambda body: {"violations": [_violation("2026-03-05T00:00:00+00:00")]})
+
+ rows = _collect(
+ _FakeResumableManager(
+ JfrogArtifactoryResumeConfig(next_offset=3, incremental_filter_value="2026-03-01T00:00:00.000+00:00")
+ ),
+ endpoint="xray_violations",
+ )
+
+ assert len(rows) == 1
+ assert bodies == [build_xray_violations_request("2026-03-01T00:00:00.000+00:00", 3)]
+
+
class TestGetRowsRest:
def test_repositories_returns_bare_array(self, monkeypatch: Any) -> None:
monkeypatch.setattr(
@@ -315,6 +652,11 @@ class TestSourceResponse:
("artifacts", ["repo", "path", "name"], "created"),
("builds", ["name", "number"], "created"),
("storage_summary", ["repoKey"], None),
+ ("artifact_statistics", ["repo", "path", "name"], None),
+ ("build_artifacts", ["build_name", "build_number", "module_name", "name"], "build_created"),
+ ("build_dependencies", ["build_name", "build_number", "module_name", "name"], "build_created"),
+ ("build_promotions", ["build_name", "build_number", "created", "status"], "created"),
+ ("xray_violations", ["violation_details_url"], "created"),
]
)
def test_primary_keys_and_partitioning(
@@ -379,6 +721,17 @@ class TestProbeEndpoint:
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_xray_probe_posts_single_row_violations_search(self, monkeypatch: Any) -> None:
+ session = _FakeSession(status_code=404)
+ monkeypatch.setattr(jfrog_artifactory, "_get_session", lambda access_token: session)
+
+ ok, status = probe_endpoint("https://acme.jfrog.io", "token", endpoint="xray_violations")
+
+ assert (ok, status) == (False, 404)
+ method, url, data = session.requests[0]
+ assert (method, url) == ("POST", "https://acme.jfrog.io/xray/api/v1/violations")
+ assert data is not None and json.loads(data)["pagination"]["limit"] == 1
+
def test_transport_error_returns_none_status(self, monkeypatch: Any) -> None:
session = MagicMock()
session.get.side_effect = ConnectionError("nope")
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
index ecfa769308ce..2c41c2db0955 100644
--- 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
@@ -10,8 +10,8 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.jfrog_arti
)
# AQL endpoints expose server-side timestamp filters; the REST list endpoints don't.
-_INCREMENTAL_ENDPOINTS = {"artifacts", "builds"}
-_FULL_REFRESH_ENDPOINTS = {"repositories", "storage_summary"}
+_INCREMENTAL_ENDPOINTS = {"artifacts", "builds", "build_artifacts", "build_dependencies", "xray_violations"}
+_FULL_REFRESH_ENDPOINTS = {"repositories", "storage_summary", "artifact_statistics", "build_promotions"}
class TestJfrogArtifactorySource:
@@ -64,8 +64,9 @@ class TestJfrogArtifactorySource:
# 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
+ for name in ("builds", "build_artifacts", "build_dependencies", "build_promotions", "storage_summary"):
+ assert schemas[name].should_sync_default is False
+ assert schemas["xray_violations"].should_sync_default is False
assert schemas["repositories"].should_sync_default is True
assert schemas["artifacts"].should_sync_default is True
@@ -89,6 +90,8 @@ class TestJfrogArtifactorySource:
((False, 403), None, True, None),
((False, 403), "builds", False, "admin"),
((False, 403), "artifacts", False, "missing the permissions"),
+ ((False, 403), "build_promotions", False, "admin"),
+ ((False, 404), "xray_violations", False, "Requires JFrog Xray"),
((False, None), None, False, "Could not connect"),
],
)
@@ -133,6 +136,9 @@ class TestJfrogArtifactorySource:
((True, 200), "artifacts", None),
((False, 403), "builds", "admin"),
((False, 401), "artifacts", "cannot read"),
+ ((False, 403), "build_artifacts", "admin"),
+ ((False, 404), "xray_violations", "Requires JFrog Xray"),
+ ((False, 404), "artifacts", None),
# A throttle or transient failure is not a missing scope.
((False, 429), "artifacts", None),
((False, None), "builds", None),