: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): implement checkmarx import source (#71180)
Tom Owersc9c09aa91c1f
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 6c0dd9885c2c..215363c117c3 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -107,6 +107,7 @@ the row lists both.| chargedesk | HTTP | requests | ✅ || chargify | HTTP | requests + `rest_source.RESTClient` | ✅ || charthop | HTTP | requests | ✅ |+| checkmarx | HTTP | requests | ✅ || checkout_com | HTTP | requests | ✅ || churnkey | HTTP | requests | ✅ || coassemble | HTTP | requests | ✅ |@@ -589,7 +590,6 @@ doesn't conflict with concurrent PRs.- cart_com- castor_edc- chatwoot-- checkmarx- chift- chorus- cin7diff --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.pynew file mode 100644index 000000000000..42b1c12a5dd2--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/checkmarx/canonical_descriptions.py@@ -0,0 +1,99 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "projects": {+ "description": "A Checkmarx One project, the unit that groups scans of a single code repository or component.",+ "docs_url": "https://checkmarx.com/resource/documents/en/34965-91104-projects-api.html",+ "columns": {+ "id": "Unique identifier (UUID) of the project.",+ "name": "Display name of the project.",+ "applicationIds": "Identifiers of the applications this project is assigned to.",+ "groups": "Identifiers of the user groups that have access to the project.",+ "repoUrl": "URL of the source code repository the project scans.",+ "mainBranch": "The repository branch designated as the project's primary branch.",+ "origin": "Where the project was created from (e.g. the web UI, CLI, or an SCM integration).",+ "tags": "Key/value tags assigned to the project.",+ "criticality": "Business criticality level assigned to the project (1-5).",+ "privatePackage": "Whether the project's packages are marked as private for SCA.",+ "createdAt": "Timestamp when the project was created.",+ "updatedAt": "Timestamp when the project was last updated.",+ },+ },+ "applications": {+ "description": "A Checkmarx One application, a business-level grouping of related projects.",+ "docs_url": "https://checkmarx.com/resource/documents/en/34965-91099-applications-api.html",+ "columns": {+ "id": "Unique identifier (UUID) of the application.",+ "name": "Display name of the application.",+ "description": "Free-text description of the application.",+ "criticality": "Business criticality level assigned to the application (1-5).",+ "rules": "Rules that automatically assign projects to this application.",+ "projectIds": "Identifiers of the projects assigned to the application.",+ "tags": "Key/value tags assigned to the application.",+ "createdAt": "Timestamp when the application was created.",+ "updatedAt": "Timestamp when the application was last updated.",+ },+ },+ "scans": {+ "description": "A scan run in Checkmarx One, including its status and the engines (SAST, SCA, KICS, etc.) it executed.",+ "docs_url": "https://checkmarx.com/resource/documents/en/34965-90786-scans-api.html",+ "columns": {+ "id": "Unique identifier (UUID) of the scan.",+ "projectId": "Identifier of the project the scan belongs to.",+ "projectName": "Name of the project the scan belongs to.",+ "branch": "Repository branch that was scanned.",+ "status": "Overall execution status of the scan (e.g. Queued, Running, Completed, Failed, Partial, Canceled).",+ "statusDetails": "Per-engine execution status for the scan.",+ "engines": "Analysis engines that ran in this scan (e.g. sast, sca, kics).",+ "sourceType": "Type of source the scan ran against (e.g. github, upload).",+ "sourceOrigin": "Origin that initiated the scan (e.g. the web UI, CLI, or a CI integration).",+ "initiator": "User or integration that started the scan.",+ "tags": "Key/value tags assigned to the scan.",+ "metadata": "Scan configuration metadata, including the engine configurations requested.",+ "createdAt": "Timestamp when the scan was created.",+ "updatedAt": "Timestamp when the scan was last updated.",+ },+ },+ "scan_results": {+ "description": "An individual finding (vulnerability, misconfiguration, or risk) reported by a scan, across all engines.",+ "docs_url": "https://checkmarx.com/resource/documents/en/34965-90822-results-api.html",+ "columns": {+ "result_id": "Finding identifier scoped to its scan, derived from the engine type plus the result's id (falling back to its similarity id). Added by PostHog.",+ "scan_id": "Identifier of the scan that produced this finding. Added by PostHog.",+ "scan_created_at": "Creation timestamp of the scan that produced this finding. Added by PostHog.",+ "type": "Engine that reported the finding (e.g. sast, sca, kics).",+ "id": "Engine-assigned identifier of the finding within the scan.",+ "similarityId": "Stable identifier used to correlate the same finding across scans.",+ "status": "Comparison status of the finding relative to the previous scan (e.g. NEW, RECURRENT, FIXED).",+ "state": "Triage state of the finding (e.g. TO_VERIFY, CONFIRMED, NOT_EXPLOITABLE).",+ "severity": "Severity of the finding (e.g. CRITICAL, HIGH, MEDIUM, LOW, INFO).",+ "confidenceLevel": "Confidence level assigned to the finding.",+ "created": "Timestamp when the finding was created.",+ "firstFoundAt": "Timestamp when this finding was first detected in the project.",+ "foundAt": "Timestamp when this finding was detected in this scan.",+ "firstScanId": "Identifier of the scan in which this finding was first detected.",+ "description": "Human-readable description of the finding.",+ "data": "Engine-specific finding details (e.g. file, line, and attack vector for SAST).",+ "vulnerabilityDetails": "Vulnerability metadata such as CWE id, CVSS scores, and compliance mappings.",+ "comments": "Comments attached to the finding.",+ },+ },+ "scan_results_summary": {+ "description": "Aggregated result counters for a scan, broken down by severity, state, and status per engine.",+ "docs_url": "https://checkmarx.com/resource/documents/en/34965-90823-scan-summary-api.html",+ "columns": {+ "scan_id": "Identifier of the scan the summary belongs to. Added by PostHog.",+ "scan_created_at": "Creation timestamp of the scan the summary belongs to. Added by PostHog.",+ "scanId": "Identifier of the scan the summary belongs to, as reported by Checkmarx One.",+ "tenantId": "Identifier of the Checkmarx One tenant.",+ "sastCounters": "Aggregated SAST finding counters grouped by severity, state, status, and language.",+ "scaCounters": "Aggregated SCA finding counters grouped by severity, state, and status.",+ "kicsCounters": "Aggregated IaC (KICS) finding counters grouped by severity, state, status, and platform.",+ "scaContainersCounters": "Aggregated SCA container image finding counters.",+ "apiSecCounters": "Aggregated API security finding counters.",+ "microEnginesCounters": "Aggregated micro-engine (e.g. secrets) finding counters.",+ },+ },+}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.pynew file mode 100644index 000000000000..daa4bfe1d681--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/checkmarx/checkmarx.py@@ -0,0 +1,432 @@+import json+import time+import hashlib+import dataclasses+from collections.abc import Iterator+from datetime import UTC, date, datetime+from typing import Any, Optional+from urllib.parse import quote++import requests+from structlog.types import FilteringBoundLogger+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.checkmarx.settings import (+ CHECKMARX_ENDPOINTS,+ CHECKMARX_REGION_HOSTS,+ CheckmarxEndpointConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager++REQUEST_TIMEOUT = 60+TOKEN_REQUEST_TIMEOUT = 30+# Re-exchange the API key this many seconds before the current access token expires, so a request+# never goes out with a token that dies mid-flight. Checkmarx One access tokens are short-lived+# (~30 minutes) and syncs can run much longer.+TOKEN_REFRESH_LEEWAY = 120+# The OAuth client id Checkmarx One assigns to API-key (refresh token) exchanges.+TOKEN_CLIENT_ID = "ast-app"++AUTH_ERROR_PREFIX = "Checkmarx One authentication failed"+++class CheckmarxRetryableError(Exception):+ pass+++class CheckmarxAuthError(Exception):+ pass+++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+++def _make_session(api_key: str) -> requests.Session:+ """Tracked session hardened for this source's traffic.++ Sample capture is disabled: responses carry customer vulnerability findings, repository URLs,+ and attack-vector details that the name-based scrubbers can't sanitise, so they must never+ reach the HTTP sample bucket. The API key is registered for value-based redaction, and+ redirects are refused so the token POST body (which carries the key) can never be re-sent to+ a redirect target — no Checkmarx One endpoint we call legitimately redirects.+ """+ return make_tracked_session(redact_values=(api_key,), allow_redirects=False, capture=False)+++def get_region_hosts(region: str) -> tuple[str, str]:+ """Return (api_base_url, iam_base_url) for a Checkmarx One region."""+ hosts = CHECKMARX_REGION_HOSTS.get(region)+ if hosts is None:+ raise ValueError(f"Unknown Checkmarx One region: {region}")+ return hosts+++def _format_datetime(value: Any) -> str:+ if isinstance(value, datetime):+ utc_value = value.replace(tzinfo=UTC) if value.tzinfo is None else value.astimezone(UTC)+ return utc_value.strftime("%Y-%m-%dT%H:%M:%SZ")+ if isinstance(value, date):+ return datetime.combine(value, datetime.min.time(), tzinfo=UTC).strftime("%Y-%m-%dT%H:%M:%SZ")+ return str(value)+++class CheckmarxAuth:+ """Exchanges a Checkmarx One API key (an IAM refresh token) for a short-lived JWT bearer token,+ re-exchanging automatically as the token approaches expiry."""++ def __init__(self, session: requests.Session, iam_base_url: str, tenant_name: str, api_key: str) -> None:+ self._session = session+ self._token_url = (+ f"{iam_base_url}/auth/realms/{quote(tenant_name.strip(), safe='')}/protocol/openid-connect/token"+ )+ self._api_key = api_key+ self._token: str | None = None+ self._expires_at: float = 0.0++ def get_token(self) -> str:+ now = time.monotonic()+ if self._token is not None and now < self._expires_at - TOKEN_REFRESH_LEEWAY:+ return self._token++ response = self._session.post(+ self._token_url,+ data={+ "grant_type": "refresh_token",+ "client_id": TOKEN_CLIENT_ID,+ "refresh_token": self._api_key,+ },+ timeout=TOKEN_REQUEST_TIMEOUT,+ )++ if response.status_code == 429 or response.status_code >= 500:+ raise CheckmarxRetryableError(+ f"Checkmarx One IAM error (retryable): status={response.status_code}, url={self._token_url}"+ )+ if not response.ok:+ # Keycloak reports bad credentials as 400/401 with an error/error_description body+ # (e.g. invalid_grant for a revoked API key, "Realm does not exist" for a bad tenant).+ detail = ""+ try:+ payload = response.json()+ detail = payload.get("error_description") or payload.get("error") or ""+ except Exception:+ pass+ raise CheckmarxAuthError(+ f"{AUTH_ERROR_PREFIX}: status={response.status_code}"+ + (f", {detail}" if detail else "")+ + ". Check your tenant name, region, and API key."+ )++ payload = response.json()+ self._token = payload["access_token"]+ self._expires_at = time.monotonic() + float(payload.get("expires_in", 1800))+ return self._token+++@retry(+ retry=retry_if_exception_type(+ (+ CheckmarxRetryableError,+ requests.ReadTimeout,+ requests.ConnectionError,+ requests.exceptions.ChunkedEncodingError,+ )+ ),+ stop=stop_after_attempt(5),+ wait=wait_exponential_jitter(initial=1, max=30),+ reraise=True,+)+def _fetch_json(+ session: requests.Session,+ auth: CheckmarxAuth,+ url: str,+ params: dict[str, Any],+ logger: FilteringBoundLogger,+) -> dict[str, Any]:+ # The token is fetched inside the retried function so a transient IAM failure is retried too.+ headers = {+ "Authorization": f"Bearer {auth.get_token()}",+ # Checkmarx One versions its REST endpoints through the Accept header.+ "Accept": "application/json; version=1.0",+ }+ response = session.get(url, params=params, headers=headers, timeout=REQUEST_TIMEOUT)++ if response.status_code == 429 or response.status_code >= 500:+ raise CheckmarxRetryableError(f"Checkmarx One API error (retryable): status={response.status_code}, url={url}")++ if not response.ok:+ logger.error(f"Checkmarx One API error: status={response.status_code}, body={response.text}, url={url}")+ response.raise_for_status()++ return response.json()+++def _iter_pages(+ session: requests.Session,+ auth: CheckmarxAuth,+ url: str,+ params: dict[str, Any],+ data_key: str,+ page_size: int,+ 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.++ 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.+ """+ offset = start_offset+ while True:+ data = _fetch_json(session, auth, url, {**params, "offset": offset, "limit": page_size}, logger)+ items = data.get(data_key) or []+ if not items:+ break++ next_offset: int | None = offset + len(items) if len(items) >= page_size else None+ yield items, next_offset++ if next_offset is None:+ break+ offset = next_offset+++def _build_incremental_value(+ config: CheckmarxEndpointConfig,+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+) -> str | None:+ if not should_use_incremental_field or db_incremental_field_last_value is None:+ return None++ value = db_incremental_field_last_value+ if config.incremental_lookback is not None:+ if isinstance(value, date) and not isinstance(value, datetime):+ value = datetime.combine(value, datetime.min.time(), tzinfo=UTC)+ if isinstance(value, datetime):+ value = value - config.incremental_lookback++ return _format_datetime(value)+++def _result_id(item: dict[str, Any]) -> str:+ """A per-scan-unique identifier for a finding.++ The unified results API documents an `id` per result; `similarityId` is the fallback for+ engines that omit it, and a content hash guards against rows with neither (unverified against+ a live tenant, hence the defensive chain). Prefixed with the engine type since ids are only+ documented unique within their engine.+ """+ raw = item.get("id") or item.get("similarityId")+ if raw is None:+ raw = hashlib.sha256(json.dumps(item, sort_keys=True, default=str).encode()).hexdigest()+ 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]:+ 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+ return row+++def _enumerate_scans(+ session: requests.Session,+ auth: CheckmarxAuth,+ api_base_url: str,+ 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++ scans: list[tuple[str, Any]] = []+ for items, _next_offset in _iter_pages(+ session, auth, f"{api_base_url}/api/scans", params, "scans", page_size, logger+ ):+ scans.extend((item["id"], item.get("createdAt")) for item in items)+ return scans+++def _get_fan_out_rows(+ session: requests.Session,+ auth: CheckmarxAuth,+ api_base_url: str,+ endpoint: str,+ config: CheckmarxEndpointConfig,+ resumable_source_manager: ResumableSourceManager[CheckmarxResumeConfig],+ 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.++ 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.+ """+ scans = _enumerate_scans(session, auth, api_base_url, from_date, config.page_size, 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.+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ remaining = scans+ 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) :]+ resume_offset = resume.offset+ logger.debug(f"Checkmarx: resuming {endpoint} from scan_id={resume.scan_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):+ start_offset = resume_offset+ resume_offset = 0 # only the resumed-into scan starts mid-way; the rest start fresh++ for items, next_offset in _iter_pages(+ session,+ auth,+ url,+ {config.scan_id_param: scan_id},+ config.data_key,+ config.page_size,+ logger,+ start_offset=start_offset,+ ):+ yield [_shape_fan_out_row(item, scan_id, scan_created_at, endpoint) 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))++ # Advance the bookmark to the next scan so a crash between scans 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))+++def get_rows(+ tenant_name: str,+ region: str,+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[CheckmarxResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+) -> Iterator[list[dict[str, Any]]]:+ config = CHECKMARX_ENDPOINTS[endpoint]+ api_base_url, iam_base_url = get_region_hosts(region)+ # One session reused across every page (and, for fan-out, every scan) so urllib3 keeps the+ # connection alive instead of re-handshaking per request.+ session = _make_session(api_key)+ auth = CheckmarxAuth(session, iam_base_url, tenant_name, api_key)++ from_date = _build_incremental_value(config, should_use_incremental_field, db_incremental_field_last_value)++ if config.fan_out_over_scans:+ yield from _get_fan_out_rows(+ session, auth, api_base_url, endpoint, config, resumable_source_manager, from_date, logger+ )+ return++ params: dict[str, Any] = {}+ if from_date:+ params["from-date"] = 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+ if start_offset:+ logger.debug(f"Checkmarx: resuming {endpoint} from offset={start_offset}")++ for items, next_offset in _iter_pages(+ session,+ auth,+ f"{api_base_url}{config.path}",+ params,+ config.data_key,+ config.page_size,+ logger,+ start_offset=start_offset,+ ):+ yield items+ if next_offset is not None:+ resumable_source_manager.save_state(CheckmarxResumeConfig(offset=next_offset))+++def validate_credentials(tenant_name: str, region: str, api_key: str) -> tuple[bool, str | None]:+ try:+ api_base_url, iam_base_url = get_region_hosts(region)+ except ValueError as e:+ return False, str(e)++ session = _make_session(api_key)+ auth = CheckmarxAuth(session, iam_base_url, tenant_name, api_key)++ try:+ token = auth.get_token()+ response = session.get(+ f"{api_base_url}/api/projects",+ params={"offset": 0, "limit": 1},+ headers={"Authorization": f"Bearer {token}", "Accept": "application/json; version=1.0"},+ timeout=TOKEN_REQUEST_TIMEOUT,+ )+ if response.ok:+ return True, None+ return False, f"Checkmarx One API returned status {response.status_code} when listing projects"+ except CheckmarxAuthError as e:+ return False, str(e)+ except Exception:+ return False, "Could not connect to Checkmarx One. Check your tenant name, region, and API key."+++def checkmarx_source(+ tenant_name: str,+ region: str,+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[CheckmarxResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+) -> SourceResponse:+ config = CHECKMARX_ENDPOINTS[endpoint]+ has_incremental = len(config.incremental_fields) > 0++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ tenant_name=tenant_name,+ region=region,+ api_key=api_key,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=db_incremental_field_last_value,+ ),+ primary_keys=config.primary_keys,+ # The scans list returns newest-first by default and the fan-outs follow its order, so the+ # incremental watermark is finalized at successful job end rather than checkpointed per batch.+ sort_mode="desc" if has_incremental else "asc",+ partition_count=1,+ partition_size=1,+ partition_mode="datetime" if config.partition_key else None,+ partition_format="month" if config.partition_key else None,+ partition_keys=[config.partition_key] if config.partition_key else None,+ )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.pynew file mode 100644index 000000000000..0e93f90a5e45--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/checkmarx/settings.py@@ -0,0 +1,115 @@+from dataclasses import dataclass, field+from datetime import timedelta+from typing import Optional++from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType++# Checkmarx One is deployed per region; both the API host and the IAM (auth) host vary with it.+# Region values match the documented multi-tenant deployments (https://checkmarx.com/resource/documents/en/34965-68630-checkmarx-one-regions.html).+CHECKMARX_REGION_HOSTS: dict[str, tuple[str, str]] = {+ "us": ("https://ast.checkmarx.net", "https://iam.checkmarx.net"),+ "us2": ("https://us.ast.checkmarx.net", "https://us.iam.checkmarx.net"),+ "eu": ("https://eu.ast.checkmarx.net", "https://eu.iam.checkmarx.net"),+ "eu2": ("https://eu-2.ast.checkmarx.net", "https://eu-2.iam.checkmarx.net"),+ "deu": ("https://deu.ast.checkmarx.net", "https://deu.iam.checkmarx.net"),+ "anz": ("https://anz.ast.checkmarx.net", "https://anz.iam.checkmarx.net"),+ "ind": ("https://ind.ast.checkmarx.net", "https://ind.iam.checkmarx.net"),+ "sng": ("https://sng.ast.checkmarx.net", "https://sng.iam.checkmarx.net"),+ "mea": ("https://mea.ast.checkmarx.net", "https://mea.iam.checkmarx.net"),+}++_SCAN_CREATED_AT_INCREMENTAL_FIELD: IncrementalField = {+ "label": "scan_created_at",+ "type": IncrementalFieldType.DateTime,+ "field": "scan_created_at",+ "field_type": IncrementalFieldType.DateTime,+}+++@dataclass+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+ 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+ # 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+ # recent triage/state changes); merge dedupes the re-pulled rows on the primary key.+ incremental_lookback: Optional[timedelta] = None+ should_sync_default: bool = True+++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.+ "projects": CheckmarxEndpointConfig(+ name="projects",+ path="/api/projects",+ data_key="projects",+ partition_key="createdAt",+ ),+ "applications": CheckmarxEndpointConfig(+ name="applications",+ path="/api/applications",+ data_key="applications",+ partition_key="createdAt",+ ),+ # The scans list accepts a `from-date` (ISO-8601) filter on scan creation time, which is the+ # server-side cursor for incremental sync.+ "scans": CheckmarxEndpointConfig(+ name="scans",+ path="/api/scans",+ data_key="scans",+ partition_key="createdAt",+ incremental_fields=[+ {+ "label": "createdAt",+ "type": IncrementalFieldType.DateTime,+ "field": "createdAt",+ "field_type": IncrementalFieldType.DateTime,+ },+ ],+ ),+ # Findings are keyed by scan, so incremental sync fetches scans created since the watermark and+ # pulls each scan's results. Rows carry injected `scan_id` / `scan_created_at` / `result_id`+ # columns (see checkmarx.py).+ "scan_results": CheckmarxEndpointConfig(+ name="scan_results",+ path="/api/results",+ data_key="results",+ 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",+ incremental_lookback=timedelta(days=7),+ ),+ # Aggregated severity/status counters per scan, one row per scan.+ "scan_results_summary": CheckmarxEndpointConfig(+ name="scan_results_summary",+ path="/api/scan-summary",+ data_key="scansSummaries",+ 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",+ incremental_lookback=timedelta(days=7),+ ),+}++ENDPOINTS = tuple(CHECKMARX_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in CHECKMARX_ENDPOINTS.items()+}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.pyindex 439364c78842..337cda1f88b3 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@@ -1,19 +1,45 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,+ SourceFieldSelectConfig,+ SourceFieldSelectConfigOption,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (+ SourceInputs,+ SourceResponse,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.checkmarx.checkmarx import (+ AUTH_ERROR_PREFIX,+ CheckmarxResumeConfig,+ checkmarx_source,+ validate_credentials as validate_checkmarx_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.checkmarx.settings import (+ CHECKMARX_ENDPOINTS,+ ENDPOINTS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchemafrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import CheckmarxSourceConfigfrom products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class CheckmarxSource(SimpleSource[CheckmarxSourceConfig]):+class CheckmarxSource(ResumableSource[CheckmarxSourceConfig, CheckmarxResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.CHECKMARX@@ -24,7 +50,128 @@ class CheckmarxSource(SimpleSource[CheckmarxSourceConfig]):name=SchemaExternalDataSourceType.CHECKMARX,category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,label="Checkmarx (Checkmarx One)",+ releaseStatus=ReleaseStatus.ALPHA,+ keywords=["checkmarx one", "sast", "sca", "appsec"],+ caption="""Enter your Checkmarx One credentials to automatically pull your application security data into the PostHog Data warehouse.++You can generate an API key in Checkmarx One under **Settings** → **Identity and Access Management** → **API Keys**. The tenant name and region are shown in your Checkmarx One URL (for example, a tenant on `https://eu.ast.checkmarx.net` is in the EU region).+""",iconPath="/static/services/checkmarx.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/checkmarx",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="tenant_name",+ label="Tenant name",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="your-tenant",+ secret=False,+ ),+ SourceFieldSelectConfig(+ name="region",+ label="Region",+ required=True,+ defaultValue="us",+ options=[+ SourceFieldSelectConfigOption(label="US (ast.checkmarx.net)", value="us"),+ SourceFieldSelectConfigOption(label="US2 (us.ast.checkmarx.net)", value="us2"),+ SourceFieldSelectConfigOption(label="EU (eu.ast.checkmarx.net)", value="eu"),+ SourceFieldSelectConfigOption(label="EU2 (eu-2.ast.checkmarx.net)", value="eu2"),+ SourceFieldSelectConfigOption(label="Germany (deu.ast.checkmarx.net)", value="deu"),+ SourceFieldSelectConfigOption(label="ANZ (anz.ast.checkmarx.net)", value="anz"),+ SourceFieldSelectConfigOption(label="India (ind.ast.checkmarx.net)", value="ind"),+ SourceFieldSelectConfigOption(label="Singapore (sng.ast.checkmarx.net)", value="sng"),+ SourceFieldSelectConfigOption(label="UAE (mea.ast.checkmarx.net)", value="mea"),+ ],+ ),+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.checkmarx.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ # Raised by CheckmarxAuth when the IAM token exchange rejects the API key / tenant.+ AUTH_ERROR_PREFIX: "Your Checkmarx One tenant name, region, or API key is incorrect, or the API key has been revoked. Generate a new API key in Checkmarx One and reconnect.",+ "401 Client Error: Unauthorized for url": "Your Checkmarx One API key is invalid or has been revoked. Generate a new API key in Checkmarx One and reconnect.",+ "403 Client Error: Forbidden for url": "Your Checkmarx One API key does not have permission to read this data. Assign the key a role with view permissions for projects, applications, scans, and results, then reconnect.",+ }++ def get_schemas(+ self,+ config: CheckmarxSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ def _description(endpoint: str) -> str | None:+ if CHECKMARX_ENDPOINTS[endpoint].fan_out_over_scans:+ 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++ def _build_schema(endpoint: str) -> SourceSchema:+ endpoint_config = CHECKMARX_ENDPOINTS[endpoint]+ has_incremental = len(endpoint_config.incremental_fields) > 0+ return SourceSchema(+ name=endpoint,+ 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,+ incremental_fields=endpoint_config.incremental_fields,+ should_sync_default=endpoint_config.should_sync_default,+ description=_description(endpoint),+ )++ schemas = [_build_schema(endpoint) for endpoint in ENDPOINTS]+ if names is not None:+ names_set = set(names)+ schemas = [s for s in schemas if s.name in names_set]+ return schemas++ def validate_credentials(+ self, config: CheckmarxSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ return validate_checkmarx_credentials(config.tenant_name, config.region, config.api_key)++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[CheckmarxResumeConfig]:+ return ResumableSourceManager[CheckmarxResumeConfig](inputs, CheckmarxResumeConfig)++ def source_for_pipeline(+ self,+ config: CheckmarxSourceConfig,+ resumable_source_manager: ResumableSourceManager[CheckmarxResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return checkmarx_source(+ tenant_name=config.tenant_name,+ region=config.region,+ api_key=config.api_key,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=inputs.should_use_incremental_field,+ db_incremental_field_last_value=inputs.db_incremental_field_last_value+ if inputs.should_use_incremental_field+ else None,)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.pynew file mode 100644index 000000000000..5163432b0f1c--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/checkmarx/tests/test_checkmarx.py@@ -0,0 +1,561 @@+from collections.abc import Callable+from datetime import UTC, date, datetime+from typing import Any++import pytest+from unittest.mock import MagicMock, patch++from requests import HTTPError++from products.warehouse_sources.backend.temporal.data_imports.sources.checkmarx.checkmarx import (+ AUTH_ERROR_PREFIX,+ CheckmarxAuth,+ CheckmarxAuthError,+ CheckmarxResumeConfig,+ CheckmarxRetryableError,+ _build_incremental_value,+ _result_id,+ checkmarx_source,+ get_region_hosts,+ get_rows,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.checkmarx.settings import (+ CHECKMARX_ENDPOINTS,+ ENDPOINTS,+)++TOKEN_PAYLOAD = {"access_token": "jwt-token", "expires_in": 1800}+++def _response(status: int = 200, payload: Any = None, text: str = "") -> MagicMock:+ response = MagicMock()+ response.status_code = status+ response.ok = status < 400+ response.json.return_value = payload if payload is not None else {}+ response.text = text+ if status >= 400:+ response.raise_for_status.side_effect = HTTPError(+ f"{status} Client Error: Unauthorized for url: https://ast.checkmarx.net", response=response+ )+ else:+ response.raise_for_status.return_value = None+ return response+++class FakeSession:+ """Routes POSTs to the token endpoint and GETs through a per-test handler."""++ def __init__(+ self,+ get_handler: Callable[[str, dict[str, Any]], MagicMock],+ token_response: MagicMock | None = None,+ ) -> None:+ self._get_handler = get_handler+ self._token_response = token_response or _response(payload=TOKEN_PAYLOAD)+ self.post_calls: list[tuple[str, dict[str, Any]]] = []+ self.get_calls: list[tuple[str, dict[str, Any], dict[str, str]]] = []++ def post(self, url: str, data: dict[str, Any] | None = None, timeout: Any = None) -> MagicMock:+ self.post_calls.append((url, data or {}))+ return self._token_response++ def get(+ self, url: str, params: dict[str, Any] | None = None, headers: dict[str, str] | None = None, timeout: Any = None+ ) -> MagicMock:+ self.get_calls.append((url, params or {}, headers or {}))+ return self._get_handler(url, params or {})+++def _make_manager(resume: CheckmarxResumeConfig | None = None) -> MagicMock:+ manager = MagicMock()+ manager.can_resume.return_value = resume is not None+ manager.load_state.return_value = resume+ return manager+++def _make_logger() -> MagicMock:+ return MagicMock()+++class TestCheckmarx:+ # ---- auth ----++ def test_auth_exchanges_api_key_and_caches_token(self) -> None:+ session = FakeSession(lambda url, params: _response())+ auth = CheckmarxAuth(session, "https://iam.checkmarx.net", "my-tenant", "refresh-token") # type: ignore[arg-type]++ assert auth.get_token() == "jwt-token"+ assert auth.get_token() == "jwt-token"++ assert len(session.post_calls) == 1+ url, data = session.post_calls[0]+ assert url == "https://iam.checkmarx.net/auth/realms/my-tenant/protocol/openid-connect/token"+ assert data == {"grant_type": "refresh_token", "client_id": "ast-app", "refresh_token": "refresh-token"}++ def test_auth_refreshes_expired_token(self) -> None:+ session = FakeSession(lambda url, params: _response())+ auth = CheckmarxAuth(session, "https://iam.checkmarx.net", "my-tenant", "refresh-token") # type: ignore[arg-type]++ auth.get_token()+ auth._expires_at = 0.0 # simulate expiry+ auth.get_token()++ assert len(session.post_calls) == 2++ def test_auth_quotes_tenant_name_in_realm_url(self) -> None:+ session = FakeSession(lambda url, params: _response())+ auth = CheckmarxAuth(session, "https://iam.checkmarx.net", " my/tenant ", "key") # type: ignore[arg-type]++ auth.get_token()++ url, _data = session.post_calls[0]+ assert url == "https://iam.checkmarx.net/auth/realms/my%2Ftenant/protocol/openid-connect/token"++ @pytest.mark.parametrize("status", [400, 401, 403, 404])+ def test_auth_error_statuses_raise_auth_error(self, status: int) -> None:+ token_response = _response(+ status=status, payload={"error": "invalid_grant", "error_description": "Token is not active"}+ )+ session = FakeSession(lambda url, params: _response(), token_response=token_response)+ auth = CheckmarxAuth(session, "https://iam.checkmarx.net", "my-tenant", "bad-key") # type: ignore[arg-type]++ with pytest.raises(CheckmarxAuthError) as exc_info:+ auth.get_token()++ assert AUTH_ERROR_PREFIX in str(exc_info.value)+ assert "Token is not active" in str(exc_info.value)++ @pytest.mark.parametrize("status", [429, 500, 503])+ def test_auth_transient_statuses_raise_retryable_error(self, status: int) -> None:+ session = FakeSession(lambda url, params: _response(), token_response=_response(status=status))+ auth = CheckmarxAuth(session, "https://iam.checkmarx.net", "my-tenant", "key") # type: ignore[arg-type]++ with pytest.raises(CheckmarxRetryableError):+ auth.get_token()++ # ---- region hosts ----++ @pytest.mark.parametrize(+ ("region", "api_host", "iam_host"),+ [+ ("us", "https://ast.checkmarx.net", "https://iam.checkmarx.net"),+ ("eu", "https://eu.ast.checkmarx.net", "https://eu.iam.checkmarx.net"),+ ("sng", "https://sng.ast.checkmarx.net", "https://sng.iam.checkmarx.net"),+ ],+ )+ def test_get_region_hosts(self, region: str, api_host: str, iam_host: str) -> None:+ assert get_region_hosts(region) == (api_host, iam_host)++ def test_get_region_hosts_unknown_region(self) -> None:+ with pytest.raises(ValueError):+ get_region_hosts("mars")++ # ---- incremental value ----++ @pytest.mark.parametrize(+ ("endpoint", "value", "expected"),+ [+ ("scans", datetime(2026, 1, 15, 12, 30, tzinfo=UTC), "2026-01-15T12:30:00Z"),+ ("scans", date(2026, 1, 15), "2026-01-15T00:00:00Z"),+ # Fan-out endpoints subtract their 7-day safety lookback from the watermark.+ ("scan_results", datetime(2026, 1, 15, 12, 30, tzinfo=UTC), "2026-01-08T12:30:00Z"),+ ("scan_results_summary", date(2026, 1, 15), "2026-01-08T00:00:00Z"),+ ],+ )+ def test_build_incremental_value(self, endpoint: str, value: Any, expected: str) -> None:+ assert _build_incremental_value(CHECKMARX_ENDPOINTS[endpoint], True, value) == expected++ @pytest.mark.parametrize(+ ("should_use", "value"),+ [(False, datetime(2026, 1, 15, tzinfo=UTC)), (True, None), (False, None)],+ )+ def test_build_incremental_value_disabled(self, should_use: bool, value: Any) -> None:+ assert _build_incremental_value(CHECKMARX_ENDPOINTS["scans"], should_use, value) is None++ # ---- result id ----++ @pytest.mark.parametrize(+ ("item", "expected"),+ [+ ({"type": "sast", "id": "abc", "similarityId": "sim"}, "sast:abc"),+ ({"type": "sca", "similarityId": "sim-1"}, "sca:sim-1"),+ ],+ )+ def test_result_id_prefers_id_then_similarity_id(self, item: dict[str, Any], expected: str) -> None:+ assert _result_id(item) == expected++ def test_result_id_hashes_rows_without_identifiers(self) -> None:+ item = {"type": "kics", "severity": "HIGH"}+ first = _result_id(item)+ second = _result_id(dict(item))++ assert first.startswith("kics:")+ assert first == second+ assert _result_id({"type": "kics", "severity": "LOW"}) != first++ # ---- top-level pagination ----++ def test_get_rows_paginates_until_short_page(self) -> None:+ page_size = CHECKMARX_ENDPOINTS["projects"].page_size+ full_page = [{"id": f"p{i}"} for i in range(page_size)]+ short_page = [{"id": "last"}]++ def handler(url: str, params: dict[str, Any]) -> MagicMock:+ assert url == "https://ast.checkmarx.net/api/projects"+ if params["offset"] == 0:+ return _response(payload={"projects": full_page, "totalCount": page_size + 1})+ return _response(payload={"projects": short_page, "totalCount": page_size + 1})++ 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="projects",+ logger=_make_logger(),+ resumable_source_manager=manager,+ )+ )++ assert [len(batch) for batch in batches] == [page_size, 1]+ assert [call[1]["offset"] for call in session.get_calls] == [0, page_size]+ # 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}))++ 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="applications",+ logger=_make_logger(),+ resumable_source_manager=_make_manager(),+ )+ )++ assert batches == []++ @pytest.mark.parametrize(+ ("should_use_incremental_field", "expects_from_date"),+ [(True, True), (False, False)],+ )+ def test_get_rows_scans_incremental_filter(+ self, should_use_incremental_field: bool, expects_from_date: bool+ ) -> None:+ def handler(url: str, params: dict[str, Any]) -> MagicMock:+ return _response(payload={"scans": [{"id": "s1", "createdAt": "2026-02-01T00:00:00Z"}], "totalCount": 1})++ session = FakeSession(handler)++ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.checkmarx.checkmarx.make_tracked_session",+ return_value=session,+ ):+ list(+ get_rows(+ tenant_name="my-tenant",+ region="us",+ api_key="key",+ endpoint="scans",+ logger=_make_logger(),+ resumable_source_manager=_make_manager(),+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=datetime(2026, 1, 15, tzinfo=UTC)+ if should_use_incremental_field+ else None,+ )+ )++ _url, params, _headers = session.get_calls[0]+ if expects_from_date:+ assert params["from-date"] == "2026-01-15T00:00:00Z"+ else:+ assert "from-date" not in params++ def test_get_rows_resumes_from_saved_offset(self) -> None:+ def handler(url: str, params: dict[str, Any]) -> MagicMock:+ return _response(payload={"projects": [{"id": "p1"}], "totalCount": 201})++ session = FakeSession(handler)+ manager = _make_manager(CheckmarxResumeConfig(offset=200))++ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.checkmarx.checkmarx.make_tracked_session",+ return_value=session,+ ):+ list(+ get_rows(+ tenant_name="my-tenant",+ region="us",+ api_key="key",+ endpoint="projects",+ logger=_make_logger(),+ resumable_source_manager=manager,+ )+ )++ assert session.get_calls[0][1]["offset"] == 200++ def test_get_rows_sends_bearer_and_versioned_accept_headers(self) -> None:+ session = FakeSession(lambda url, params: _response(payload={"projects": []}))++ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.checkmarx.checkmarx.make_tracked_session",+ return_value=session,+ ) as mock_session_factory:+ list(+ get_rows(+ tenant_name="my-tenant",+ region="us",+ api_key="key",+ endpoint="projects",+ logger=_make_logger(),+ resumable_source_manager=_make_manager(),+ )+ )++ _url, _params, headers = session.get_calls[0]+ assert headers["Authorization"] == "Bearer jwt-token"+ assert headers["Accept"] == "application/json; version=1.0"+ # Responses carry customer vulnerability data and the token POST body carries the API key:+ # the session must stay excluded from sample capture, redact the key, and refuse redirects.+ mock_session_factory.assert_called_once_with(redact_values=("key",), allow_redirects=False, capture=False)++ # ---- fan-out over scans ----++ def _fan_out_handler(+ self, results_by_scan: dict[str, list[dict[str, Any]]]+ ) -> Callable[[str, dict[str, Any]], MagicMock]:+ scans = [+ {"id": scan_id, "createdAt": f"2026-02-0{i + 1}T00:00:00Z"}+ for i, scan_id in enumerate(results_by_scan.keys())+ ]++ def handler(url: str, params: dict[str, Any]) -> MagicMock:+ if url.endswith("/api/scans"):+ return _response(payload={"scans": scans, "totalCount": len(scans)})+ if url.endswith("/api/results"):+ return _response(payload={"results": results_by_scan[params["scan-id"]], "totalCount": 1})+ if url.endswith("/api/scan-summary"):+ return _response(payload={"scansSummaries": [{"scanId": params["scan-ids"]}], "totalCount": 1})+ raise AssertionError(f"Unexpected URL: {url}")++ return handler++ def test_scan_results_rows_carry_scan_context_and_result_id(self) -> None:+ handler = self._fan_out_handler(+ {+ "s1": [{"type": "sast", "id": "r1", "severity": "HIGH"}],+ "s2": [{"type": "sca", "similarityId": "sim-9", "severity": "LOW"}],+ }+ )+ 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="scan_results",+ logger=_make_logger(),+ resumable_source_manager=manager,+ )+ )++ rows = [row for batch in batches for row in batch]+ assert [row["scan_id"] for row in rows] == ["s1", "s2"]+ assert [row["result_id"] for row in rows] == ["sast:r1", "sca:sim-9"]+ 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"))++ def test_scan_results_incremental_applies_lookback_to_scan_enumeration(self) -> None:+ handler = self._fan_out_handler({"s1": [{"type": "sast", "id": "r1"}]})+ session = FakeSession(handler)++ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.checkmarx.checkmarx.make_tracked_session",+ return_value=session,+ ):+ list(+ get_rows(+ tenant_name="my-tenant",+ region="us",+ api_key="key",+ endpoint="scan_results",+ logger=_make_logger(),+ resumable_source_manager=_make_manager(),+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 1, 15, tzinfo=UTC),+ )+ )++ 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:+ handler = self._fan_out_handler(+ {+ "s1": [{"type": "sast", "id": "r1"}],+ "s2": [{"type": "sast", "id": "r2"}],+ }+ )+ session = FakeSession(handler)+ manager = _make_manager(CheckmarxResumeConfig(offset=0, scan_id="s2"))++ 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="scan_results",+ logger=_make_logger(),+ resumable_source_manager=manager,+ )+ )++ rows = [row for batch in batches for row in batch]+ assert [row["scan_id"] for row in rows] == ["s2"]+ requested_scan_ids = [+ params["scan-id"] for url, params, _headers in session.get_calls if url.endswith("/api/results")+ ]+ assert requested_scan_ids == ["s2"]++ def test_scan_results_restarts_when_bookmarked_scan_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"))++ 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="scan_results",+ logger=_make_logger(),+ resumable_source_manager=manager,+ )+ )++ rows = [row for batch in batches for row in batch]+ assert [row["scan_id"] for row in rows] == ["s1"]+ # The stale offset must not leak into the restarted scan.+ results_offsets = [+ params["offset"] for url, params, _headers in session.get_calls if url.endswith("/api/results")+ ]+ assert results_offsets == [0]++ def test_scan_results_summary_requests_one_scan_per_call(self) -> None:+ handler = self._fan_out_handler({"s1": [], "s2": []})+ 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="scan_results_summary",+ logger=_make_logger(),+ resumable_source_manager=_make_manager(),+ )+ )++ rows = [row for batch in batches for row in batch]+ assert [row["scan_id"] for row in rows] == ["s1", "s2"]+ 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"]++ # ---- validate_credentials ----++ @pytest.mark.parametrize(+ ("projects_status", "expected_valid"),+ [(200, True), (403, False)],+ )+ def test_validate_credentials_probes_projects(self, projects_status: int, expected_valid: bool) -> None:+ session = FakeSession(lambda url, params: _response(status=projects_status, payload={"projects": []}))++ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.checkmarx.checkmarx.make_tracked_session",+ return_value=session,+ ):+ valid, error = validate_credentials("my-tenant", "us", "key")++ assert valid is expected_valid+ if expected_valid:+ assert error is None+ else:+ assert error is not None++ def test_validate_credentials_bad_api_key(self) -> None:+ token_response = _response(status=401, payload={"error": "invalid_grant"})+ session = FakeSession(lambda url, params: _response(), token_response=token_response)++ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.checkmarx.checkmarx.make_tracked_session",+ return_value=session,+ ):+ valid, error = validate_credentials("my-tenant", "us", "bad-key")++ assert valid is False+ assert error is not None+ assert AUTH_ERROR_PREFIX in error++ def test_validate_credentials_unknown_region(self) -> None:+ valid, error = validate_credentials("my-tenant", "mars", "key")++ assert valid is False+ assert error is not None+ assert "region" in error.lower()++ # ---- SourceResponse assembly ----++ @pytest.mark.parametrize("endpoint", ENDPOINTS)+ def test_checkmarx_source_response_shape(self, endpoint: str) -> None:+ config = CHECKMARX_ENDPOINTS[endpoint]+ response = checkmarx_source(+ tenant_name="my-tenant",+ region="us",+ api_key="key",+ endpoint=endpoint,+ logger=_make_logger(),+ resumable_source_manager=_make_manager(),+ )++ 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"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.pynew file mode 100644index 000000000000..12fe5adb3c7f--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/checkmarx/tests/test_checkmarx_source.py@@ -0,0 +1,119 @@+from typing import Any++import pytest+from unittest.mock import MagicMock, patch++from posthog.schema import DataWarehouseSourceCategory, ReleaseStatus, SourceFieldInputConfig, SourceFieldSelectConfig++from products.warehouse_sources.backend.temporal.data_imports.sources.checkmarx.checkmarx import CheckmarxResumeConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.checkmarx.source import CheckmarxSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import CheckmarxSourceConfig+from products.warehouse_sources.backend.types import ExternalDataSourceType+++def _make_config(**overrides: Any) -> CheckmarxSourceConfig:+ payload: dict[str, Any] = {"tenant_name": "my-tenant", "region": "eu", "api_key": "secret-key", **overrides}+ return CheckmarxSourceConfig(**payload)+++class TestCheckmarxSource:+ def setup_method(self) -> None:+ self.source = CheckmarxSource()++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.CHECKMARX++ def test_get_source_config(self) -> None:+ config = self.source.get_source_config++ assert config.category == DataWarehouseSourceCategory.ENGINEERING___MONITORING+ assert config.label == "Checkmarx (Checkmarx One)"+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert not config.unreleasedSource+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/checkmarx"+ assert [field.name for field in config.fields] == ["tenant_name", "region", "api_key"]++ def test_api_key_field_is_secret(self) -> None:+ api_key_field = next(field for field in self.source.get_source_config.fields if field.name == "api_key")+ assert isinstance(api_key_field, SourceFieldInputConfig)+ assert api_key_field.secret is True++ def test_region_field_covers_all_configured_hosts(self) -> None:+ from products.warehouse_sources.backend.temporal.data_imports.sources.checkmarx.settings import (+ CHECKMARX_REGION_HOSTS,+ )++ region_field = next(field for field in self.source.get_source_config.fields if field.name == "region")+ assert isinstance(region_field, SourceFieldSelectConfig)+ assert {option.value for option in region_field.options} == set(CHECKMARX_REGION_HOSTS.keys())++ @pytest.mark.parametrize(+ ("endpoint", "supports_incremental", "supports_append"),+ [+ ("projects", False, False),+ ("applications", False, False),+ ("scans", True, True),+ ("scan_results", True, False),+ ("scan_results_summary", True, False),+ ],+ )+ def test_get_schemas_sync_modes(self, endpoint: str, supports_incremental: bool, supports_append: bool) -> None:+ schemas = {schema.name: schema for schema in self.source.get_schemas(_make_config(), team_id=1)}++ assert schemas[endpoint].supports_incremental == supports_incremental+ assert schemas[endpoint].supports_append == supports_append++ 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"}++ @pytest.mark.parametrize(("valid", "error"), [(True, None), (False, "Checkmarx One authentication failed: nope")])+ def test_validate_credentials_delegates_to_transport(self, valid: bool, error: str | None) -> None:+ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.checkmarx.source.validate_checkmarx_credentials",+ return_value=(valid, error),+ ) as mock_validate:+ result = self.source.validate_credentials(_make_config(), team_id=1)++ assert result == (valid, error)+ mock_validate.assert_called_once_with("my-tenant", "eu", "secret-key")++ def test_get_resumable_source_manager_binds_resume_config(self) -> None:+ inputs = MagicMock()+ manager = self.source.get_resumable_source_manager(inputs)++ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is CheckmarxResumeConfig++ @pytest.mark.parametrize("should_use_incremental_field", [True, False])+ def test_source_for_pipeline_plumbs_inputs(self, should_use_incremental_field: bool) -> None:+ inputs = MagicMock()+ inputs.schema_name = "scans"+ inputs.should_use_incremental_field = should_use_incremental_field+ inputs.db_incremental_field_last_value = "2026-01-01T00:00:00Z"+ manager = MagicMock()++ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.checkmarx.source.checkmarx_source"+ ) as mock_source:+ self.source.source_for_pipeline(_make_config(), manager, inputs)++ mock_source.assert_called_once_with(+ tenant_name="my-tenant",+ region="eu",+ api_key="secret-key",+ endpoint="scans",+ logger=inputs.logger,+ resumable_source_manager=manager,+ should_use_incremental_field=should_use_incremental_field,+ # The stored watermark must not leak into a full-refresh run.+ db_incremental_field_last_value="2026-01-01T00:00:00Z" if should_use_incremental_field else None,+ )++ def test_get_non_retryable_errors_covers_auth_failures(self) -> None:+ errors = self.source.get_non_retryable_errors()++ assert "Checkmarx One authentication failed" in errors+ assert "401 Client Error: Unauthorized for url" in errors+ assert "403 Client Error: Forbidden for url" in errorsdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.pyindex cf72df835642..09c4b95828d0 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py@@ -763,7 +763,9 @@ class ChatwootSourceConfig(config.Config):@config.configclass CheckmarxSourceConfig(config.Config):- pass+ tenant_name: str+ api_key: str+ region: Literal["us", "us2", "eu", "eu2", "deu", "anz", "ind", "sng", "mea"] = config.value(default="us")@config.config