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(checkmarx): add triage history and result lookup tables (#102238)

Tom Owers2b090c67723b
diff --git a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt b/posthog/test/repo_invariants/dataclass_frozen_baseline.txt
index 2dde03949bd8..ee8429efe092 100644
--- a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt
+++ b/posthog/test/repo_invariants/dataclass_frozen_baseline.txt
@@ -384,8 +384,6 @@
1 products/warehouse_sources/backend/temporal/data_imports/sources/chartmogul/settings.py
1 products/warehouse_sources/backend/temporal/data_imports/sources/chatwoot/chatwoot.py
1 products/warehouse_sources/backend/temporal/data_imports/sources/chatwoot/settings.py
-1 products/warehouse_sources/backend/temporal/data_imports/sources/checkmarx/checkmarx.py
-1 products/warehouse_sources/backend/temporal/data_imports/sources/checkmarx/settings.py
1 products/warehouse_sources/backend/temporal/data_imports/sources/checkout_com/checkout_com.py
1 products/warehouse_sources/backend/temporal/data_imports/sources/churnkey/churnkey.py
1 products/warehouse_sources/backend/temporal/data_imports/sources/churnkey/settings.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 04e6da8432ea..f105f8caf22d 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
@@ -1415,14 +1415,14 @@ Note: Vendor's own swagger.json in the chatwoot/chatwoot repo, 90 paths. Coverag
## Checkmarx — gaps
-Today (5): `applications`, `projects`, `scan_results`, `scan_results_summary`, `scans`
+Today (11): `application_rules`, `applications`, `custom_states`, `projects`, `result_severities`, `result_states`, `result_statuses`, `sast_predicates_changelog`, `scan_results`, `scan_results_summary`, `scans`
Diffed against: <https://checkmarx.stoplight.io/docs/checkmarx-one-api-reference-guide>
-- [ ] `sast-results-predicates (Retrieve SAST predicates, Retrieve predicates changelog)` — per-result triage state/severity transition history - the only way to measure remediation and time-to-triage (high)
-- [ ] `Lists API (Retrieve list of states / statuses / severities)` — lookup tables that decode the state, status and severity ids already present on scan_results (high)
-- [ ] `Custom States (Retrieve custom states)` — lookup for tenant-defined triage states; without it custom-state results are unreadable ids (high)
-- [ ] `Applications - Retrieve list of application rules` — lookup resolving which projects roll into which application; today the applications-to-projects edge is missing (high)
+- [x] `sast-results-predicates (Retrieve SAST predicates, Retrieve predicates changelog)` — per-result triage state/severity transition history - the only way to measure remediation and time-to-triage (high)
+- [x] `Lists API (Retrieve list of states / statuses / severities)` — lookup tables that decode the state, status and severity ids already present on scan_results (high)
+- [x] `Custom States (Retrieve custom states)` — lookup for tenant-defined triage states; without it custom-state results are unreadable ids (high)
+- [x] `Applications - Retrieve list of application rules` — lookup resolving which projects roll into which application; today the applications-to-projects edge is missing (high)
- [ ] `Projects - Retrieve list of branches (and Retrieve last scan)` — branch dimension for scans; per-branch vulnerability trend is a core use case (medium)
- [ ] `SAST Metadata (Retrieve scans metadata, Retrieve scan metrics)` — LOC scanned, engine config and scan metrics - the denominators for density metrics (medium)
- [ ] `Policy Management (Retrieve all policies, policy violation details, policy violation summary)` — policy breaches per scan, the compliance-reporting object (medium)
@@ -1432,6 +1432,15 @@ Diffed against: <https://checkmarx.stoplight.io/docs/checkmarx-one-api-reference
- [ ] `API Security Scan Results (Retrieve API Security risks, Get all api scan Metadata)` — API risk findings and the sensitive/undocumented API counts (medium)
- [ ] `Risk Orchestration (Retrieve risks, Retrieve aggregated risks)` — cross-scanner aggregated risk view used for posture reporting (low)
+Note: `sast_predicates_changelog` is ticked against the bulk route
+(`GET /api/sast-results-predicates/changelog?entityType=projectID&history=true`), fanned out over
+projects. That route returns each change as `{change, date, user, origin}` with no similarity id, so
+the table carries the triage trail per project, not per result. Per-result attribution only exists on
+`GET /api/sast-results-predicates/{similarityID}`, which takes one request per finding and so is left
+out on cost. `Applications - Retrieve list of application rules` is ticked for the flat rules table it
+gives; the applications-to-projects edge it was filed for is already synced, as `applications.projectIds`
+and `projects.applicationIds`.
+
Note: docs.checkmarx.com now redirects the API reference to Stoplight; I pulled the full operation tree from https://checkmarx.stoplight.io/api/v1/projects/cHJqOjE5ODM2OQ==/table-of-contents (project 198369) and read every GET operation from it. The gap concentration is in triage state history and the small lookup tables that decode the ids on scan_results.
## CheckoutCom — **thin**
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/checkmarx/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/checkmarx/canonical_descriptions.py
index 42b1c12a5dd2..374514e08c2e 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/checkmarx/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/checkmarx/canonical_descriptions.py
@@ -2,6 +2,8 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.can
CanonicalDescriptions,
)
+_API_REFERENCE = "https://checkmarx.stoplight.io/docs/checkmarx-one-api-reference-guide"
+
CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"projects": {
"description": "A Checkmarx One project, the unit that groups scans of a single code repository or component.",
@@ -96,4 +98,59 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"microEnginesCounters": "Aggregated micro-engine (e.g. secrets) finding counters.",
},
},
+ "application_rules": {
+ "description": "A rule on a Checkmarx One application that assigns projects to it, by project name or project tag.",
+ "docs_url": f"{_API_REFERENCE}/b893e178b7eee-retrieve-list-of-application-rules",
+ "columns": {
+ "id": "Unique identifier (UUID) of the rule.",
+ "application_id": "Identifier of the application the rule belongs to. Added by PostHog.",
+ "application_created_at": "Creation timestamp of the application the rule belongs to. Added by PostHog.",
+ "type": "What the rule matches on (e.g. project.name.contains, project.tag.key-value.exists).",
+ "value": "Value the rule matches against, interpreted according to the rule type. Key/value pairs and id lists are separated by a semicolon.",
+ },
+ },
+ "sast_predicates_changelog": {
+ "description": "A change made while triaging a project's findings: the state, severity, and comment edits applied to results, with who made each one.",
+ "docs_url": f"{_API_REFERENCE}/gmnw4cuhobl2z-retrieve-bulk-predicates",
+ "columns": {
+ "change_id": "Identifier of the change, derived from the change's own fields because Checkmarx One does not return one. Added by PostHog.",
+ "project_id": "Identifier of the project whose findings were triaged. Added by PostHog.",
+ "project_created_at": "Creation timestamp of the project whose findings were triaged. Added by PostHog.",
+ "change": "Description of the change that was made.",
+ "date": "Timestamp when the change was made.",
+ "user": "User who made the change.",
+ "origin": "Where the change was made from (e.g. the web UI or an integration).",
+ },
+ },
+ "result_states": {
+ "description": "The built-in triage states a finding can be assigned, which decode the state column on scan_results.",
+ "docs_url": f"{_API_REFERENCE}/h9ryi6k6wcz24-lists-enum-values-rest-api",
+ "columns": {
+ "value": "The state (e.g. TO_VERIFY, NOT_EXPLOITABLE, PROPOSED_NOT_EXPLOITABLE, CONFIRMED, URGENT).",
+ },
+ },
+ "result_statuses": {
+ "description": "The statuses a finding can carry relative to the previous scan, which decode the status column on scan_results.",
+ "docs_url": f"{_API_REFERENCE}/h9ryi6k6wcz24-lists-enum-values-rest-api",
+ "columns": {
+ "value": "The status (e.g. NEW, RECURRENT, FIXED).",
+ },
+ },
+ "result_severities": {
+ "description": "The severities a finding can carry, which decode the severity column on scan_results.",
+ "docs_url": f"{_API_REFERENCE}/h9ryi6k6wcz24-lists-enum-values-rest-api",
+ "columns": {
+ "value": "The severity (e.g. CRITICAL, HIGH, MEDIUM, LOW, INFO).",
+ },
+ },
+ "custom_states": {
+ "description": "A triage state defined by your tenant, in addition to the built-in states in result_states. Includes states that have since been deleted, so findings left in one still resolve to a name.",
+ "docs_url": "https://checkmarx.com/resource/documents/en/34965-378909-custom-states.html",
+ "columns": {
+ "id": "Unique identifier of the custom state.",
+ "name": "Display name of the custom state.",
+ "type": "Whether the state is a built-in or a custom one.",
+ "isAllowed": "Whether the API key's user has permission to move findings into this state.",
+ },
+ },
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/checkmarx/checkmarx.py b/products/warehouse_sources/backend/temporal/data_imports/sources/checkmarx/checkmarx.py
index 951c7db72438..55559aa55590 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/checkmarx/checkmarx.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/checkmarx/checkmarx.py
@@ -1,7 +1,6 @@
import json
import time
import hashlib
-import dataclasses
from collections.abc import Iterator
from datetime import UTC, date, datetime
from typing import Any, Optional
@@ -11,10 +10,13 @@ import requests
from structlog.types import FilteringBoundLogger
from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+from posthog.dataclasses import frozen
+
from products.warehouse_sources.backend.temporal.data_imports.sources.checkmarx.settings import (
CHECKMARX_ENDPOINTS,
CHECKMARX_REGION_HOSTS,
CheckmarxEndpointConfig,
+ CheckmarxFanOutConfig,
RegionHosts,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
@@ -41,13 +43,13 @@ class CheckmarxAuthError(Exception):
pass
+@frozen
class CheckmarxResumeConfig:
# Row offset to resume the current page loop from.
offset: int = 0
- # For fan-out endpoints: the scan currently being processed. A stable scan-id bookmark (not a
- # positional index) so scans created between a crash and the retry can't shift the resume point.
- scan_id: str | None = None
+ # For fan-out endpoints: the parent row currently being processed. A stable id bookmark (not a
+ # positional index) so parents created between a crash and the retry can't shift the resume point.
+ parent_id: str | None = None
def _make_session(api_key: str) -> requests.Session:
@@ -151,7 +153,7 @@ def _fetch_json(
url: str,
params: dict[str, Any],
logger: FilteringBoundLogger,
-) -> dict[str, Any]:
+) -> Any:
# The token is fetched inside the retried function so a transient IAM failure is retried too.
headers = {
"Authorization": f"Bearer {auth.get_token()}",
@@ -170,30 +172,48 @@ def _fetch_json(
return response.json()
+def _extract_rows(data: Any, config: CheckmarxEndpointConfig) -> list[dict[str, Any]]:
+ """Rows out of a response body, which is either a bare JSON array or wrapped under `data_key`."""
+ if config.data_key is None:
+ items = data if isinstance(data, list) else []
+ else:
+ items = data.get(config.data_key) or []
+
+ if config.scalar_row_field is not None:
+ return [{config.scalar_row_field: item} for item in items]
+ return items
+
+
def _iter_pages(
session: requests.Session,
auth: CheckmarxAuth,
url: str,
params: dict[str, Any],
- data_key: str,
- page_size: int,
+ config: CheckmarxEndpointConfig,
logger: FilteringBoundLogger,
start_offset: int = 0,
) -> Iterator[tuple[list[dict[str, Any]], int | None]]:
- """Walk an offset/limit paginated endpoint, yielding (rows, next_offset) per page.
+ """Walk an endpoint's rows, yielding (rows, next_offset) per page.
next_offset is None on the terminal page. Termination is by short page: Checkmarx One list
responses wrap rows under `data_key` alongside totalCount/filteredTotalCount, and a page with
- fewer than `limit` rows is the last one.
+ fewer than `limit` rows is the last one. The lookup endpoints return their whole collection in
+ one unpaginated response, so they are fetched without offset/limit.
"""
+ if not config.paginated:
+ rows = _extract_rows(_fetch_json(session, auth, url, params, logger), config)
+ if rows:
+ yield rows, None
+ return
+
offset = start_offset
while True:
- data = _fetch_json(session, auth, url, {**params, "offset": offset, "limit": page_size}, logger)
- items = data.get(data_key) or []
+ data = _fetch_json(session, auth, url, {**params, "offset": offset, "limit": config.page_size}, logger)
+ items = _extract_rows(data, config)
if not items:
break
- next_offset: int | None = offset + len(items) if len(items) >= page_size else None
+ next_offset: int | None = offset + len(items) if len(items) >= config.page_size else None
yield items, next_offset
if next_offset is None:
@@ -233,33 +253,50 @@ def _result_id(item: dict[str, Any]) -> str:
return f"{item.get('type', 'unknown')}:{raw}"
-def _shape_fan_out_row(item: dict[str, Any], scan_id: str, scan_created_at: Any, endpoint: str) -> dict[str, Any]:
+def _change_id(item: dict[str, Any]) -> str:
+ """A stable identifier for a predicate change, which the changelog returns without one.
+
+ Hashed from the whole row so every sync merges onto the same key instead of appending a
+ duplicate. Two changes identical in action, timestamp, user and origin collapse into one row.
+ """
+ return hashlib.sha256(json.dumps(item, sort_keys=True, default=str).encode()).hexdigest()
+
+
+def _shape_fan_out_row(
+ item: dict[str, Any],
+ parent_id: str,
+ parent_created_at: Any,
+ endpoint: str,
+ fan_out: CheckmarxFanOutConfig,
+) -> dict[str, Any]:
row = dict(item)
if endpoint == "scan_results":
row["result_id"] = _result_id(item)
- row["scan_id"] = scan_id
- row["scan_created_at"] = scan_created_at
+ elif endpoint == "sast_predicates_changelog":
+ row["change_id"] = _change_id(item)
+ row[fan_out.parent_id_field] = parent_id
+ row[fan_out.parent_created_at_field] = parent_created_at
return row
-def _enumerate_scans(
+def _enumerate_parents(
session: requests.Session,
auth: CheckmarxAuth,
api_base_url: str,
+ parent_config: CheckmarxEndpointConfig,
from_date: str | None,
- page_size: int,
logger: FilteringBoundLogger,
) -> list[tuple[str, Any]]:
- params: dict[str, Any] = {}
- if from_date:
- params["from-date"] = from_date
+ params: dict[str, Any] = dict(parent_config.params)
+ if from_date and parent_config.from_date_param:
+ params[parent_config.from_date_param] = from_date
- scans: list[tuple[str, Any]] = []
+ parents: list[tuple[str, Any]] = []
for items, _next_offset in _iter_pages(
- session, auth, f"{api_base_url}/api/scans", params, "scans", page_size, logger
+ session, auth, f"{api_base_url}{parent_config.path}", params, parent_config, logger
):
- scans.extend((item["id"], item.get("createdAt")) for item in items)
- return scans
+ parents.extend((item["id"], item.get("createdAt")) for item in items)
+ return parents
def _get_fan_out_rows(
@@ -272,53 +309,57 @@ def _get_fan_out_rows(
from_date: str | None,
logger: FilteringBoundLogger,
) -> Iterator[list[dict[str, Any]]]:
- """Fetch `config.path` once per scan, stamping each row with the parent scan's id and creation time.
+ """Fetch `config.path` once per parent row, stamping each row with the parent's id and creation time.
- Each request targets a single scan id — the summary endpoint accepts multiple ids per call, but
- the batching syntax isn't verifiable without a live tenant, so one-id-per-request keeps the
- behavior unambiguous at the cost of extra calls.
+ Each request targets a single parent id — the scan summary endpoint accepts multiple ids per
+ call, but the batching syntax isn't verifiable without a live tenant, so one-id-per-request
+ keeps the behavior unambiguous at the cost of extra calls.
"""
- scans = _enumerate_scans(session, auth, api_base_url, from_date, config.page_size, logger)
+ fan_out = config.fan_out
+ assert fan_out is not None
+ parents = _enumerate_parents(session, auth, api_base_url, CHECKMARX_ENDPOINTS[fan_out.parent], from_date, logger)
- # Resolve the saved scan-id bookmark to the slice of scans still to process. If the bookmarked
- # scan no longer exists (deleted between runs), start over — merge dedupes on the primary key.
+ # Resolve the saved parent-id bookmark to the slice of parents still to process. If the
+ # bookmarked parent no longer exists (deleted between runs), start over — merge dedupes on the
+ # primary key.
resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
- remaining = scans
+ remaining = parents
resume_offset = 0
- if resume is not None and resume.scan_id is not None:
- scan_ids = [scan_id for scan_id, _created_at in scans]
- if resume.scan_id in scan_ids:
- remaining = scans[scan_ids.index(resume.scan_id) :]
+ if resume is not None and resume.parent_id is not None:
+ parent_ids = [parent_id for parent_id, _created_at in parents]
+ if resume.parent_id in parent_ids:
+ remaining = parents[parent_ids.index(resume.parent_id) :]
resume_offset = resume.offset
- logger.debug(f"Checkmarx: resuming {endpoint} from scan_id={resume.scan_id}, offset={resume_offset}")
+ logger.debug(f"Checkmarx: resuming {endpoint} from parent_id={resume.parent_id}, offset={resume_offset}")
- assert config.scan_id_param is not None
- url = f"{api_base_url}{config.path}"
-
- for index, (scan_id, scan_created_at) in enumerate(remaining):
+ for index, (parent_id, parent_created_at) in enumerate(remaining):
start_offset = resume_offset
- resume_offset = 0 # only the resumed-into scan starts mid-way; the rest start fresh
+ resume_offset = 0 # only the resumed-into parent starts mid-way; the rest start fresh
+
+ url = f"{api_base_url}{config.path}".replace("{parent_id}", quote(parent_id, safe=""))
+ params: dict[str, Any] = dict(config.params)
+ if fan_out.id_param is not None:
+ params[fan_out.id_param] = parent_id
for items, next_offset in _iter_pages(
session,
auth,
url,
- {config.scan_id_param: scan_id},
- config.data_key,
- config.page_size,
+ params,
+ config,
logger,
start_offset=start_offset,
):
- yield [_shape_fan_out_row(item, scan_id, scan_created_at, endpoint) for item in items]
+ yield [_shape_fan_out_row(item, parent_id, parent_created_at, endpoint, fan_out) for item in items]
# Save AFTER yielding (and only when more pages remain) so a crash re-yields the last
# page rather than skipping it — merge dedupes on the primary key.
if next_offset is not None:
- resumable_source_manager.save_state(CheckmarxResumeConfig(offset=next_offset, scan_id=scan_id))
+ resumable_source_manager.save_state(CheckmarxResumeConfig(offset=next_offset, parent_id=parent_id))
- # Advance the bookmark to the next scan so a crash between scans resumes correctly.
+ # Advance the bookmark to the next parent so a crash between parents resumes correctly.
if index + 1 < len(remaining):
- next_scan_id = remaining[index + 1][0]
- resumable_source_manager.save_state(CheckmarxResumeConfig(offset=0, scan_id=next_scan_id))
+ next_parent_id = remaining[index + 1][0]
+ resumable_source_manager.save_state(CheckmarxResumeConfig(offset=0, parent_id=next_parent_id))
def get_rows(
@@ -340,15 +381,15 @@ def get_rows(
from_date = _build_incremental_value(config, should_use_incremental_field, db_incremental_field_last_value)
- if config.fan_out_over_scans:
+ if config.fan_out is not None:
yield from _get_fan_out_rows(
session, auth, hosts.api_base_url, endpoint, config, resumable_source_manager, from_date, logger
)
return
- params: dict[str, Any] = {}
- if from_date:
- params["from-date"] = from_date
+ params: dict[str, Any] = dict(config.params)
+ if from_date and config.from_date_param:
+ params[config.from_date_param] = from_date
resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
start_offset = resume.offset if resume is not None else 0
@@ -360,8 +401,7 @@ def get_rows(
auth,
f"{hosts.api_base_url}{config.path}",
params,
- config.data_key,
- config.page_size,
+ config,
logger,
start_offset=start_offset,
):
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/checkmarx/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/checkmarx/settings.py
index 3862216b7362..b58d5a534476 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/checkmarx/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/checkmarx/settings.py
@@ -1,4 +1,4 @@
-from dataclasses import dataclass, field
+from dataclasses import field
from datetime import timedelta
from typing import Optional
@@ -35,21 +35,40 @@ _SCAN_CREATED_AT_INCREMENTAL_FIELD: IncrementalField = {
}
-@dataclass
+@frozen
+class CheckmarxFanOutConfig:
+ # Endpoint whose rows are the parents: the child endpoint is requested once per parent row.
+ parent: str
+ # Columns every child row is stamped with, carrying the parent's id and creation time.
+ parent_id_field: str
+ parent_created_at_field: str
+ # Query param that carries the parent id. None means the id fills the `{parent_id}`
+ # placeholder in the child endpoint's path instead.
+ id_param: Optional[str] = None
+
+
+@frozen
class CheckmarxEndpointConfig:
name: str
path: str
# Key of the list of rows in the wrapped JSON response, e.g. {"projects": [...], "totalCount": n}.
- data_key: str
+ # None when the endpoint returns a bare JSON array.
+ data_key: Optional[str]
incremental_fields: list[IncrementalField] = field(default_factory=list)
primary_keys: list[str] = field(default_factory=lambda: ["id"])
# Stable datetime field used for Delta partitioning (never an updated-at style field).
partition_key: Optional[str] = None
page_size: int = 100
- # Fan out over the scans list, requesting this endpoint once per scan id.
- fan_out_over_scans: bool = False
- # Query param that carries the scan id on fan-out requests.
- scan_id_param: Optional[str] = None
+ # Query params sent on every request to this endpoint.
+ params: dict[str, str] = field(default_factory=dict)
+ # False for endpoints that return their whole collection in one response.
+ paginated: bool = True
+ # Set when the endpoint returns an array of bare strings: each one becomes a row under this column.
+ scalar_row_field: Optional[str] = None
+ # Query param carrying the incremental watermark, on the endpoints that accept one.
+ from_date_param: Optional[str] = None
+ # Set to request this endpoint once per row of a parent endpoint.
+ fan_out: Optional[CheckmarxFanOutConfig] = None
# Safety overlap subtracted from the incremental watermark on every run. Fan-out endpoints key
# their watermark on scan creation time, but a scan's results only exist once the scan finishes —
# re-pulling a window of recent scans picks up results of scans that were still running (and
@@ -58,6 +77,26 @@ class CheckmarxEndpointConfig:
should_sync_default: bool = True
+def _scans_fan_out(id_param: str) -> CheckmarxFanOutConfig:
+ return CheckmarxFanOutConfig(
+ parent="scans",
+ parent_id_field="scan_id",
+ parent_created_at_field="scan_created_at",
+ id_param=id_param,
+ )
+
+
+def _scalar_list(name: str, path: str) -> CheckmarxEndpointConfig:
+ return CheckmarxEndpointConfig(
+ name=name,
+ path=path,
+ data_key=None,
+ paginated=False,
+ scalar_row_field="value",
+ primary_keys=["value"],
+ )
+
+
CHECKMARX_ENDPOINTS: dict[str, CheckmarxEndpointConfig] = {
# Projects and applications have no server-side timestamp filter, so they are full refresh only.
# Both are small (one row per project/application) so a full refresh per run is cheap.
@@ -80,6 +119,7 @@ CHECKMARX_ENDPOINTS: dict[str, CheckmarxEndpointConfig] = {
path="/api/scans",
data_key="scans",
partition_key="createdAt",
+ from_date_param="from-date",
incremental_fields=[
{
"label": "createdAt",
@@ -99,8 +139,7 @@ CHECKMARX_ENDPOINTS: dict[str, CheckmarxEndpointConfig] = {
primary_keys=["scan_id", "result_id"],
partition_key="scan_created_at",
incremental_fields=[_SCAN_CREATED_AT_INCREMENTAL_FIELD],
- fan_out_over_scans=True,
- scan_id_param="scan-id",
+ fan_out=_scans_fan_out("scan-id"),
incremental_lookback=timedelta(days=7),
),
# Aggregated severity/status counters per scan, one row per scan.
@@ -111,10 +150,56 @@ CHECKMARX_ENDPOINTS: dict[str, CheckmarxEndpointConfig] = {
primary_keys=["scan_id"],
partition_key="scan_created_at",
incremental_fields=[_SCAN_CREATED_AT_INCREMENTAL_FIELD],
- fan_out_over_scans=True,
- scan_id_param="scan-ids",
+ fan_out=_scans_fan_out("scan-ids"),
incremental_lookback=timedelta(days=7),
),
+ # One row per rule assigning projects to an application. The applications list already carries
+ # these nested under `rules`; a flat table joins to `applications` without unnesting.
+ "application_rules": CheckmarxEndpointConfig(
+ name="application_rules",
+ path="/api/applications/{parent_id}/project-rules",
+ data_key=None,
+ paginated=False,
+ primary_keys=["application_id", "id"],
+ partition_key="application_created_at",
+ fan_out=CheckmarxFanOutConfig(
+ parent="applications",
+ parent_id_field="application_id",
+ parent_created_at_field="application_created_at",
+ ),
+ ),
+ # Triage history: every state, severity and comment change made to a project's findings, with
+ # the user, timestamp and origin. Keyed on the project rather than the finding — the
+ # per-similarity-id route would need one request per finding.
+ "sast_predicates_changelog": CheckmarxEndpointConfig(
+ name="sast_predicates_changelog",
+ path="/api/sast-results-predicates/changelog",
+ data_key="results",
+ params={"entityType": "projectID", "history": "true"},
+ primary_keys=["project_id", "change_id"],
+ partition_key="project_created_at",
+ fan_out=CheckmarxFanOutConfig(
+ parent="projects",
+ parent_id_field="project_id",
+ parent_created_at_field="project_created_at",
+ id_param="entityId",
+ ),
+ ),
+ # The Lists API returns each enum as a bare array of strings, so every value becomes a row
+ # under a single `value` column. These decode the state, status and severity columns on
+ # scan_results, and are the full set of values a result can carry.
+ "result_states": _scalar_list("result_states", "/api/lists/states"),
+ "result_statuses": _scalar_list("result_statuses", "/api/lists/statuses"),
+ "result_severities": _scalar_list("result_severities", "/api/lists/severities"),
+ # Triage states defined by the tenant, on top of the built-in ones in `result_states`. Deleted
+ # states are requested too, so a finding left in a since-removed state still resolves to a name.
+ "custom_states": CheckmarxEndpointConfig(
+ name="custom_states",
+ path="/api/custom-states",
+ data_key=None,
+ paginated=False,
+ params={"include-deleted": "true"},
+ ),
}
ENDPOINTS = tuple(CHECKMARX_ENDPOINTS.keys())
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/checkmarx/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/checkmarx/source.py
index 53b209368c0d..eb47b98a5bda 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/checkmarx/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/checkmarx/source.py
@@ -120,12 +120,15 @@ You can generate an API key in Checkmarx One under **Settings** → **Identity a
api_version: str | None = None,
) -> list[SourceSchema]:
def _description(endpoint: str) -> str | None:
- if CHECKMARX_ENDPOINTS[endpoint].fan_out_over_scans:
+ endpoint_config = CHECKMARX_ENDPOINTS[endpoint]
+ if endpoint_config.fan_out is None:
+ return None
+ if endpoint_config.incremental_lookback is not None:
return (
"Fetched per scan. Incremental syncs pull data for scans created since the last sync "
"(with a 7-day overlap so late-finishing scans and recent triage changes are picked up)"
)
- return None
+ return f"Fetched once per row in the {endpoint_config.fan_out.parent} table"
def _build_schema(endpoint: str) -> SourceSchema:
endpoint_config = CHECKMARX_ENDPOINTS[endpoint]
@@ -135,7 +138,7 @@ You can generate an API key in Checkmarx One under **Settings** → **Identity a
supports_incremental=has_incremental,
# The fan-outs' incremental lookback intentionally re-pulls a window of rows each run;
# only merge dedupes those on the primary key, append would materialize duplicates.
- supports_append=has_incremental and not endpoint_config.fan_out_over_scans,
+ supports_append=has_incremental and endpoint_config.fan_out is None,
incremental_fields=endpoint_config.incremental_fields,
should_sync_default=endpoint_config.should_sync_default,
description=_description(endpoint),
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/checkmarx/tests/test_checkmarx.py b/products/warehouse_sources/backend/temporal/data_imports/sources/checkmarx/tests/test_checkmarx.py
index 4ff8ad1ca6f2..57059311b52d 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/checkmarx/tests/test_checkmarx.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/checkmarx/tests/test_checkmarx.py
@@ -1,9 +1,10 @@
from collections.abc import Callable
from datetime import UTC, date, datetime
from typing import Any
+from urllib.parse import unquote
import pytest
-from unittest.mock import MagicMock, patch
+from unittest.mock import MagicMock, call, patch
from requests import HTTPError
@@ -14,6 +15,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.checkmarx.
CheckmarxResumeConfig,
CheckmarxRetryableError,
_build_incremental_value,
+ _change_id,
_result_id,
checkmarx_source,
get_region_hosts,
@@ -231,8 +233,16 @@ class TestCheckmarx:
# State saved after the yielded full page, pointing at the next offset.
manager.save_state.assert_called_once_with(CheckmarxResumeConfig(offset=page_size))
- def test_get_rows_empty_first_page_yields_nothing(self) -> None:
- session = FakeSession(lambda url, params: _response(payload={"applications": [], "totalCount": 0}))
+ @pytest.mark.parametrize(
+ ("endpoint", "payload"),
+ [
+ ("applications", {"applications": [], "totalCount": 0}),
+ # A lookup endpoint returns a bare array, so emptiness looks different on the wire.
+ ("custom_states", []),
+ ],
+ )
+ def test_get_rows_empty_first_page_yields_nothing(self, endpoint: str, payload: Any) -> None:
+ session = FakeSession(lambda url, params: _response(payload=payload))
with patch(
"products.warehouse_sources.backend.temporal.data_imports.sources.checkmarx.checkmarx.make_tracked_session",
@@ -243,7 +253,7 @@ class TestCheckmarx:
tenant_name="my-tenant",
region="us",
api_key="key",
- endpoint="applications",
+ endpoint=endpoint,
logger=_make_logger(),
resumable_source_manager=_make_manager(),
)
@@ -389,7 +399,7 @@ class TestCheckmarx:
assert rows[0]["scan_created_at"] == "2026-02-01T00:00:00Z"
assert rows[1]["scan_created_at"] == "2026-02-02T00:00:00Z"
# Bookmark advanced to the second scan after the first one finished.
- manager.save_state.assert_called_once_with(CheckmarxResumeConfig(offset=0, scan_id="s2"))
+ manager.save_state.assert_called_once_with(CheckmarxResumeConfig(offset=0, parent_id="s2"))
def test_scan_results_incremental_applies_lookback_to_scan_enumeration(self) -> None:
handler = self._fan_out_handler({"s1": [{"type": "sast", "id": "r1"}]})
@@ -415,7 +425,7 @@ class TestCheckmarx:
scans_call_params = next(params for url, params, _headers in session.get_calls if url.endswith("/api/scans"))
assert scans_call_params["from-date"] == "2026-01-08T00:00:00Z"
- def test_scan_results_resumes_from_bookmarked_scan(self) -> None:
+ def test_scan_results_resumes_from_bookmarked_parent(self) -> None:
handler = self._fan_out_handler(
{
"s1": [{"type": "sast", "id": "r1"}],
@@ -423,7 +433,7 @@ class TestCheckmarx:
}
)
session = FakeSession(handler)
- manager = _make_manager(CheckmarxResumeConfig(offset=0, scan_id="s2"))
+ manager = _make_manager(CheckmarxResumeConfig(offset=0, parent_id="s2"))
with patch(
"products.warehouse_sources.backend.temporal.data_imports.sources.checkmarx.checkmarx.make_tracked_session",
@@ -447,10 +457,10 @@ class TestCheckmarx:
]
assert requested_scan_ids == ["s2"]
- def test_scan_results_restarts_when_bookmarked_scan_is_gone(self) -> None:
+ def test_scan_results_restarts_when_bookmarked_parent_is_gone(self) -> None:
handler = self._fan_out_handler({"s1": [{"type": "sast", "id": "r1"}]})
session = FakeSession(handler)
- manager = _make_manager(CheckmarxResumeConfig(offset=100, scan_id="deleted-scan"))
+ manager = _make_manager(CheckmarxResumeConfig(offset=100, parent_id="deleted-scan"))
with patch(
"products.warehouse_sources.backend.temporal.data_imports.sources.checkmarx.checkmarx.make_tracked_session",
@@ -499,6 +509,223 @@ class TestCheckmarx:
summary_calls = [params for url, params, _headers in session.get_calls if url.endswith("/api/scan-summary")]
assert [params["scan-ids"] for params in summary_calls] == ["s1", "s2"]
+ # ---- lookup endpoints ----
+
+ @pytest.mark.parametrize(
+ ("endpoint", "path", "values"),
+ [
+ ("result_states", "/api/lists/states", ["TO_VERIFY", "CONFIRMED"]),
+ ("result_statuses", "/api/lists/statuses", ["NEW", "RECURRENT", "FIXED"]),
+ ("result_severities", "/api/lists/severities", ["CRITICAL", "HIGH"]),
+ ],
+ )
+ def test_lists_endpoints_wrap_bare_strings_and_skip_pagination(
+ self, endpoint: str, path: str, values: list[str]
+ ) -> None:
+ def handler(url: str, params: dict[str, Any]) -> MagicMock:
+ assert url == f"https://ast.checkmarx.net{path}"
+ return _response(payload=values)
+
+ session = FakeSession(handler)
+ manager = _make_manager()
+
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.checkmarx.checkmarx.make_tracked_session",
+ return_value=session,
+ ):
+ batches = list(
+ get_rows(
+ tenant_name="my-tenant",
+ region="us",
+ api_key="key",
+ endpoint=endpoint,
+ logger=_make_logger(),
+ resumable_source_manager=manager,
+ )
+ )
+
+ assert batches == [[{"value": value} for value in values]]
+ # A single unpaginated request: sending offset/limit to these endpoints would be meaningless,
+ # and the source must not checkpoint resume state for a collection it read in one go.
+ assert len(session.get_calls) == 1
+ assert session.get_calls[0][1] == {}
+ manager.save_state.assert_not_called()
+
+ def test_custom_states_requests_deleted_states(self) -> None:
+ states = [{"id": 1, "name": "In sprint", "type": "custom", "isAllowed": True}]
+
+ def handler(url: str, params: dict[str, Any]) -> MagicMock:
+ assert url == "https://ast.checkmarx.net/api/custom-states"
+ return _response(payload=states)
+
+ session = FakeSession(handler)
+
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.checkmarx.checkmarx.make_tracked_session",
+ return_value=session,
+ ):
+ batches = list(
+ get_rows(
+ tenant_name="my-tenant",
+ region="us",
+ api_key="key",
+ endpoint="custom_states",
+ logger=_make_logger(),
+ resumable_source_manager=_make_manager(),
+ )
+ )
+
+ assert batches == [states]
+ # Without this a finding triaged into a since-deleted state resolves to nothing.
+ assert session.get_calls[0][1] == {"include-deleted": "true"}
+
+ # ---- fan-out over applications ----
+
+ def test_application_rules_fan_out_puts_the_application_id_in_the_path(self) -> None:
+ applications = [
+ {"id": "app-1", "createdAt": "2026-01-01T00:00:00Z"},
+ {"id": "app 2/x", "createdAt": "2026-01-02T00:00:00Z"},
+ ]
+ rules_by_application = {
+ "app-1": [{"id": "rule-1", "type": "project.name.contains", "value": "demo"}],
+ "app 2/x": [{"id": "rule-2", "type": "project.tag.key.exists", "value": "team"}],
+ }
+
+ def handler(url: str, params: dict[str, Any]) -> MagicMock:
+ if url.endswith("/api/applications"):
+ return _response(payload={"applications": applications, "totalCount": len(applications)})
+ prefix = "https://ast.checkmarx.net/api/applications/"
+ assert url.startswith(prefix) and url.endswith("/project-rules")
+ application_id = unquote(url[len(prefix) : -len("/project-rules")])
+ return _response(payload=rules_by_application[application_id])
+
+ session = FakeSession(handler)
+ manager = _make_manager()
+
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.checkmarx.checkmarx.make_tracked_session",
+ return_value=session,
+ ):
+ batches = list(
+ get_rows(
+ tenant_name="my-tenant",
+ region="us",
+ api_key="key",
+ endpoint="application_rules",
+ logger=_make_logger(),
+ resumable_source_manager=manager,
+ )
+ )
+
+ rows = [row for batch in batches for row in batch]
+ assert [(row["id"], row["application_id"], row["application_created_at"]) for row in rows] == [
+ ("rule-1", "app-1", "2026-01-01T00:00:00Z"),
+ ("rule-2", "app 2/x", "2026-01-02T00:00:00Z"),
+ ]
+ # The id is path-quoted, so an id carrying a slash cannot reshape the request path.
+ assert [url for url, _params, _headers in session.get_calls if "project-rules" in url] == [
+ "https://ast.checkmarx.net/api/applications/app-1/project-rules",
+ "https://ast.checkmarx.net/api/applications/app%202%2Fx/project-rules",
+ ]
+
+ # ---- fan-out over projects ----
+
+ def _changelog_handler(
+ self, changes_by_project: dict[str, list[dict[str, Any]]]
+ ) -> Callable[[str, dict[str, Any]], MagicMock]:
+ projects = [
+ {"id": project_id, "createdAt": f"2026-03-0{i + 1}T00:00:00Z"}
+ for i, project_id in enumerate(changes_by_project)
+ ]
+
+ def handler(url: str, params: dict[str, Any]) -> MagicMock:
+ if url.endswith("/api/projects"):
+ return _response(payload={"projects": projects, "totalCount": len(projects)})
+ if url.endswith("/api/sast-results-predicates/changelog"):
+ changes = changes_by_project[params["entityId"]]
+ offset = params["offset"]
+ page = changes[offset : offset + params["limit"]]
+ return _response(payload={"results": page, "totalSimilarityIds": f"presenting x of {len(changes)}"})
+ raise AssertionError(f"Unexpected URL: {url}")
+
+ return handler
+
+ def test_predicates_changelog_requests_full_history_per_project(self) -> None:
+ change = {
+ "change": "State changed from TO_VERIFY to CONFIRMED",
+ "date": "2026-03-05T09:00:00Z",
+ "user": "[email protected]",
+ "origin": "WebApp",
+ }
+ session = FakeSession(self._changelog_handler({"proj-1": [change]}))
+
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.checkmarx.checkmarx.make_tracked_session",
+ return_value=session,
+ ):
+ batches = list(
+ get_rows(
+ tenant_name="my-tenant",
+ region="us",
+ api_key="key",
+ endpoint="sast_predicates_changelog",
+ logger=_make_logger(),
+ resumable_source_manager=_make_manager(),
+ )
+ )
+
+ rows = [row for batch in batches for row in batch]
+ assert len(rows) == 1
+ assert rows[0]["project_id"] == "proj-1"
+ assert rows[0]["project_created_at"] == "2026-03-01T00:00:00Z"
+ assert rows[0]["change"] == change["change"]
+ assert rows[0]["change_id"] == _change_id(change)
+
+ changelog_params = next(params for url, params, _headers in session.get_calls if url.endswith("/changelog"))
+ # Without entityType the API rejects the call, and without history=true it returns only the
+ # latest state per finding rather than the transitions.
+ assert changelog_params["entityType"] == "projectID"
+ assert changelog_params["history"] == "true"
+ assert changelog_params["entityId"] == "proj-1"
+
+ def test_predicates_changelog_paginates_and_bookmarks_each_project(self) -> None:
+ page_size = CHECKMARX_ENDPOINTS["sast_predicates_changelog"].page_size
+ changes = [{"change": f"change {i}", "date": "2026-03-05T09:00:00Z"} for i in range(page_size + 1)]
+ session = FakeSession(self._changelog_handler({"proj-1": changes, "proj-2": []}))
+ manager = _make_manager()
+
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.checkmarx.checkmarx.make_tracked_session",
+ return_value=session,
+ ):
+ batches = list(
+ get_rows(
+ tenant_name="my-tenant",
+ region="us",
+ api_key="key",
+ endpoint="sast_predicates_changelog",
+ logger=_make_logger(),
+ resumable_source_manager=manager,
+ )
+ )
+
+ assert [len(batch) for batch in batches] == [page_size, 1]
+ assert [params["offset"] for url, params, _headers in session.get_calls if url.endswith("/changelog")] == [
+ 0,
+ page_size,
+ 0,
+ ]
+ assert manager.save_state.call_args_list == [
+ call(CheckmarxResumeConfig(offset=page_size, parent_id="proj-1")),
+ call(CheckmarxResumeConfig(offset=0, parent_id="proj-2")),
+ ]
+
+ def test_change_id_is_stable_and_row_specific(self) -> None:
+ change = {"change": "State changed", "date": "2026-03-05T09:00:00Z", "user": "a", "origin": "WebApp"}
+
+ assert _change_id(change) == _change_id(dict(reversed(list(change.items()))))
+ assert _change_id({**change, "user": "b"}) != _change_id(change)
+
# ---- validate_credentials ----
@pytest.mark.parametrize(
@@ -558,5 +785,10 @@ class TestCheckmarx:
assert response.name == endpoint
assert response.primary_keys == config.primary_keys
assert response.sort_mode == ("desc" if config.incremental_fields else "asc")
- assert response.partition_keys == [config.partition_key]
- assert response.partition_mode == "datetime"
+ if config.partition_key is None:
+ # The lookup tables carry no datetime column, so there is nothing to partition on.
+ assert response.partition_keys is None
+ assert response.partition_mode is None
+ else:
+ assert response.partition_keys == [config.partition_key]
+ assert response.partition_mode == "datetime"
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/checkmarx/tests/test_checkmarx_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/checkmarx/tests/test_checkmarx_source.py
index ae9b9e64445e..e687e2cb8edf 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/checkmarx/tests/test_checkmarx_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/checkmarx/tests/test_checkmarx_source.py
@@ -34,6 +34,28 @@ class TestCheckmarxSource:
assert schemas[endpoint].supports_incremental == supports_incremental
assert schemas[endpoint].supports_append == supports_append
+ @pytest.mark.parametrize(
+ ("endpoint", "expected"),
+ [
+ # The scan fan-outs re-pull a window of recent scans, which the description has to say.
+ ("scan_results", "7-day overlap"),
+ # The other fan-outs have no watermark, so they must not claim incremental behaviour.
+ ("application_rules", "Fetched once per row in the applications table"),
+ ("sast_predicates_changelog", "Fetched once per row in the projects table"),
+ ],
+ )
+ def test_get_schemas_describes_how_fan_out_endpoints_are_fetched(self, endpoint: str, expected: str) -> None:
+ schemas = {schema.name: schema for schema in self.source.get_schemas(_make_config(), team_id=1)}
+
+ description = schemas[endpoint].description
+ assert description is not None
+ assert expected in description
+
+ def test_get_schemas_leaves_plain_endpoints_undescribed(self) -> None:
+ schemas = {schema.name: schema for schema in self.source.get_schemas(_make_config(), team_id=1)}
+
+ assert schemas["result_states"].description is None
+
def test_get_schemas_filters_by_names(self) -> None:
schemas = self.source.get_schemas(_make_config(), team_id=1, names=["scans", "projects"])
assert {schema.name for schema in schemas} == {"scans", "projects"}