Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(data-warehouse): implement veracode import source (#71201)

Tom Owerse6c3c8c3a72f
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
index 63bf622243f2..94ab80be4244 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -492,6 +492,7 @@ the row lists both.
| vantage | HTTP | requests | ✅ |
| vapi | HTTP | requests | ✅ |
| vellum | HTTP | requests | ✅ |
+| veracode | HTTP | requests (custom HMAC signing) | ✅ |
| vercel | HTTP | requests | ✅ |
| vitally | HTTP | requests + `rest_source.RESTClient` | ✅ |
| vultr | HTTP | requests + `rest_source.RESTClient` | ✅ |
@@ -964,7 +965,6 @@ doesn't conflict with concurrent PRs.
- usersnap
- uservoice
- veeqo
-- veracode
- vespa
- visma_economic
- vwo
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
index bf4805d7c9ea..0df24be28c2a 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
@@ -4509,7 +4509,9 @@ class VellumSourceConfig(config.Config):
@config.config
class VeracodeSourceConfig(config.Config):
- pass
+ api_id: str
+ api_secret: str
+ region: Literal["com", "eu", "us"] = config.value(default="com")
@config.config
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/veracode/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/veracode/canonical_descriptions.py
new file mode 100644
index 000000000000..9992f2ff5010
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/veracode/canonical_descriptions.py
@@ -0,0 +1,68 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "applications": {
+ "description": "An application profile in the Veracode portfolio, including its policy-compliance state and scan history.",
+ "docs_url": "https://docs.veracode.com/r/c_apps_intro",
+ "columns": {
+ "guid": "Globally unique identifier for the application profile.",
+ "id": "Numeric identifier for the application profile.",
+ "oid": "Organization-scoped numeric identifier for the application.",
+ "profile": "Application profile details: name, business unit, tags, teams, and custom fields.",
+ "scans": "Most recent scan per scan type, each with status and last-modified date.",
+ "created": "When the application profile was created.",
+ "modified": "When the application profile was last modified.",
+ "last_completed_scan_date": "When the most recent scan of any type completed.",
+ "app_profile_url": "Deep link to the application profile in the Veracode Platform.",
+ "results_url": "Deep link to the application's results in the Veracode Platform.",
+ },
+ },
+ "sandboxes": {
+ "description": "A development sandbox belonging to an application, used to scan code before it is promoted to a policy scan.",
+ "docs_url": "https://docs.veracode.com/r/c_apps_intro",
+ "columns": {
+ "guid": "Globally unique identifier for the sandbox.",
+ "application_guid": "GUID of the application this sandbox belongs to.",
+ "id": "Numeric identifier for the sandbox.",
+ "name": "Display name of the sandbox.",
+ "owner": "User who created the sandbox.",
+ "auto_recreate": "Whether the sandbox is automatically recreated after expiry.",
+ "custom_fields": "Custom name/value metadata attached to the sandbox.",
+ "created": "When the sandbox was created.",
+ "modified": "When the sandbox was last modified.",
+ },
+ },
+ "findings": {
+ "description": "Static, dynamic, and manual security findings for an application, with severity, CWE, and remediation status.",
+ "docs_url": "https://docs.veracode.com/r/c_findings_v2_intro",
+ "columns": {
+ "issue_id": "Identifier for the finding, unique within its application.",
+ "application_guid": "GUID of the application this finding belongs to.",
+ "scan_type": "Scan type that produced the finding (STATIC, DYNAMIC, or MANUAL).",
+ "description": "Human-readable description of the finding.",
+ "count": "Number of occurrences of this finding.",
+ "context_type": "Whether the finding is from the application policy scan or a sandbox.",
+ "context_guid": "GUID of the sandbox context, when the finding is a sandbox finding.",
+ "violates_policy": "Whether the finding violates the application's assigned policy.",
+ "severity": "Severity of the finding on Veracode's 0-5 scale.",
+ "finding_status": "Current status of the finding: new/open/closed, resolution, first/last found dates.",
+ "finding_details": "Finding specifics such as CWE, file path, line number, and affected component.",
+ },
+ },
+ "sca_findings": {
+ "description": "Software Composition Analysis findings for an application: vulnerabilities in open-source and third-party components.",
+ "docs_url": "https://docs.veracode.com/r/c_findings_v2_intro",
+ "columns": {
+ "issue_id": "Identifier for the finding, unique within its application.",
+ "application_guid": "GUID of the application this finding belongs to.",
+ "scan_type": "Scan type that produced the finding (SCA).",
+ "description": "Human-readable description of the finding.",
+ "violates_policy": "Whether the finding violates the application's assigned policy.",
+ "severity": "Severity of the finding on Veracode's 0-5 scale.",
+ "finding_status": "Current status of the finding: new/open/closed, resolution, first/last found dates.",
+ "finding_details": "Finding specifics such as the affected component, version, CVE, and CVSS score.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/veracode/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/veracode/settings.py
new file mode 100644
index 000000000000..d1aeb8ee2f76
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/veracode/settings.py
@@ -0,0 +1,87 @@
+from dataclasses import dataclass, field
+from typing import Optional
+
+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+
+
+@dataclass
+class VeracodeEndpointConfig:
+ name: str
+ # Path to the resource. Fan-out endpoints carry a `{application_guid}` placeholder that is filled
+ # per parent application while iterating.
+ path: str
+ # Key under `_embedded` that holds the list of rows for this endpoint (Spring HAL envelope).
+ embedded_key: str
+ incremental_fields: list[IncrementalField]
+ # Field to partition by. Must be a STABLE creation timestamp so partitions never rewrite.
+ partition_key: Optional[str] = None
+ primary_keys: list[str] = field(default_factory=lambda: ["guid"])
+ should_sync_default: bool = True
+ # Extra query params merged into every request (e.g. the findings `scan_type` selector).
+ extra_params: dict[str, str] = field(default_factory=dict)
+ # Iterate every application and query this endpoint once per application GUID.
+ fan_out_over_applications: bool = False
+
+
+# Max page size. Veracode's appsec endpoints document up to 500 on some resources, but 100 is the
+# safe, universally-accepted value, so we page in 100s until per-endpoint caps are curl-verified.
+PAGE_SIZE = 100
+
+VERACODE_ENDPOINTS: dict[str, VeracodeEndpointConfig] = {
+ # Application portfolio. The only endpoint with a genuine server-side timestamp filter
+ # (`modified_after`), so it drives the incremental sync; the fan-out endpoints below re-pull per
+ # application.
+ "applications": VeracodeEndpointConfig(
+ name="applications",
+ path="/appsec/v1/applications",
+ embedded_key="applications",
+ partition_key="created",
+ incremental_fields=[
+ {
+ "label": "modified",
+ "type": IncrementalFieldType.DateTime,
+ "field": "modified",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+ ],
+ ),
+ # Development sandboxes per application. No server-side timestamp filter, so full refresh only.
+ "sandboxes": VeracodeEndpointConfig(
+ name="sandboxes",
+ path="/appsec/v1/applications/{application_guid}/sandboxes",
+ embedded_key="sandboxes",
+ partition_key="created",
+ incremental_fields=[],
+ primary_keys=["application_guid", "guid"],
+ fan_out_over_applications=True,
+ ),
+ # Static, dynamic and manual findings per application. SCA findings must be requested on their
+ # own (`scan_type=SCA` cannot be combined with other scan types), so they live in a separate
+ # endpoint below. `issue_id` is unique only within an application, so the parent GUID is part of
+ # the primary key.
+ "findings": VeracodeEndpointConfig(
+ name="findings",
+ path="/appsec/v2/applications/{application_guid}/findings",
+ embedded_key="findings",
+ incremental_fields=[],
+ primary_keys=["application_guid", "issue_id"],
+ extra_params={"scan_type": "STATIC,DYNAMIC,MANUAL"},
+ fan_out_over_applications=True,
+ ),
+ "sca_findings": VeracodeEndpointConfig(
+ name="sca_findings",
+ path="/appsec/v2/applications/{application_guid}/findings",
+ embedded_key="findings",
+ incremental_fields=[],
+ primary_keys=["application_guid", "issue_id"],
+ should_sync_default=False,
+ extra_params={"scan_type": "SCA"},
+ fan_out_over_applications=True,
+ ),
+}
+
+ENDPOINTS = tuple(VERACODE_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in VERACODE_ENDPOINTS.items()
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/veracode/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/veracode/source.py
index 00ff815d3a08..e26d414d7d27 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/veracode/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/veracode/source.py
@@ -1,19 +1,45 @@
-from typing import cast
+from typing import Optional, cast
from 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.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 SourceSchema
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import VeracodeSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.veracode.settings import (
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+ VERACODE_ENDPOINTS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.veracode.veracode import (
+ VeracodeResumeConfig,
+ validate_credentials as validate_veracode_credentials,
+ veracode_source,
+)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class VeracodeSource(SimpleSource[VeracodeSourceConfig]):
+class VeracodeSource(ResumableSource[VeracodeSourceConfig, VeracodeResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.VERACODE
@@ -24,7 +50,134 @@ class VeracodeSource(SimpleSource[VeracodeSourceConfig]):
name=SchemaExternalDataSourceType.VERACODE,
category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,
label="Veracode",
+ caption=(
+ "Connect Veracode with an API service account's **API ID** and **secret key**, generated under "
+ "**Account settings → API credentials** in the Veracode Platform. Requests are signed with "
+ "Veracode's HMAC scheme.\n\n"
+ "The service account needs the **Results API** and **Applications API** roles to read the "
+ "application portfolio and findings. Pick the region your Veracode account lives in — data is "
+ "isolated per region."
+ ),
+ docsUrl="https://posthog.com/docs/cdp/sources/veracode",
iconPath="/static/services/veracode.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_id",
+ label="API ID",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ SourceFieldInputConfig(
+ name="api_secret",
+ label="API secret key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ SourceFieldSelectConfig(
+ name="region",
+ label="Region",
+ required=True,
+ defaultValue="com",
+ options=[
+ SourceFieldSelectConfigOption(label="US commercial (api.veracode.com)", value="com"),
+ SourceFieldSelectConfigOption(label="European (api.veracode.eu)", value="eu"),
+ SourceFieldSelectConfigOption(label="US federal (api.veracode.us)", value="us"),
+ ],
+ ),
+ ],
+ ),
+ releaseStatus=ReleaseStatus.ALPHA,
+ )
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.veracode.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error: Unauthorized": (
+ "Veracode rejected the credentials. Generate a fresh API ID and secret key for the service "
+ "account in the Veracode Platform (Account settings → API credentials) and reconnect."
+ ),
+ "403 Client Error: Forbidden": (
+ "The Veracode service account is missing the roles needed to sync this data. Grant the Results "
+ "API and Applications API roles to the account, then reconnect."
+ ),
+ }
+
+ def get_schemas(
+ self,
+ config: VeracodeSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ schemas = [
+ SourceSchema(
+ name=name,
+ supports_incremental=bool(INCREMENTAL_FIELDS.get(name)),
+ supports_append=bool(INCREMENTAL_FIELDS.get(name)),
+ incremental_fields=INCREMENTAL_FIELDS.get(name, []),
+ should_sync_default=endpoint.should_sync_default,
+ )
+ for name, endpoint in VERACODE_ENDPOINTS.items()
+ ]
+
+ 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: VeracodeSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ ok, status_code = validate_veracode_credentials(config.api_id, config.api_secret, config.region)
+ if ok:
+ return True, None
+
+ # A 403 means the token is genuine but the service account lacks a role. Accept it at
+ # source-create (the user may only have granted roles for the tables they want) and only
+ # surface it when validating a specific schema.
+ if status_code == 403 and schema_name is None:
+ return True, None
+
+ if status_code in (401, 403):
+ return False, "Veracode rejected the credentials. Check the API ID, secret key, region, and account roles."
+
+ return False, "Could not reach Veracode with the provided credentials."
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[VeracodeResumeConfig]:
+ return ResumableSourceManager[VeracodeResumeConfig](inputs, VeracodeResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: VeracodeSourceConfig,
+ resumable_source_manager: ResumableSourceManager[VeracodeResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ if inputs.schema_name not in ENDPOINTS:
+ raise ValueError(f"Unknown Veracode endpoint: {inputs.schema_name}")
+
+ return veracode_source(
+ api_id=config.api_id,
+ api_secret=config.api_secret,
+ region=config.region,
+ 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/veracode/tests/test_veracode.py b/products/warehouse_sources/backend/temporal/data_imports/sources/veracode/tests/test_veracode.py
new file mode 100644
index 000000000000..9ff38d7d89a7
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/veracode/tests/test_veracode.py
@@ -0,0 +1,348 @@
+from datetime import UTC, date, datetime
+from typing import Any
+
+from unittest.mock import MagicMock
+
+import requests
+from parameterized import parameterized
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http.transport import TrackedHTTPAdapter
+from products.warehouse_sources.backend.temporal.data_imports.sources.veracode.settings import (
+ PAGE_SIZE,
+ VERACODE_ENDPOINTS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.veracode.veracode import (
+ VeracodeHMACAuth,
+ VeracodeResumeConfig,
+ VeracodeRetryableError,
+ _calculate_signature,
+ _fetch_page_once,
+ _make_session,
+ _modified_after,
+ _strip_region_prefix,
+ get_rows,
+ resolve_host,
+ validate_credentials,
+ veracode_source,
+)
+
+
+def _mock_response(status_code: int, body: Any = None) -> MagicMock:
+ response = MagicMock(spec=requests.Response)
+ response.status_code = status_code
+ response.ok = status_code < 400
+ response.json.return_value = body if body is not None else {}
+ response.text = ""
+
+ def raise_for_status() -> None:
+ if not response.ok:
+ error = requests.HTTPError(f"{status_code} Client Error", response=response)
+ raise error
+
+ response.raise_for_status.side_effect = raise_for_status
+ return response
+
+
+def _page(rows: list[dict], embedded_key: str, total_pages: int) -> dict:
+ return {"_embedded": {embedded_key: rows}, "page": {"total_pages": total_pages}}
+
+
+class TestHMACSigning:
+ def test_signature_pins_documented_key_chain(self) -> None:
+ # Golden vector guards the documented four-step HMAC-SHA-256 derivation. If someone reorders
+ # or alters the chain (or the version string), every real request would 401 — this catches it.
+ sig = _calculate_signature(
+ "abcdef0123456789",
+ "id=abcdef0123456789&host=api.veracode.com&url=/appsec/v1/applications?size=1&method=GET",
+ 1700000000000,
+ "00112233445566778899aabbccddeeff",
+ )
+ assert sig == "b191e323ec5f869605337d1aa9fcc689ed35ececbb28cdb67436448712e89259"
+
+ def test_signature_is_lowercase_hex_256_bits(self) -> None:
+ sig = _calculate_signature("abcdef", "id=abcdef&host=h&url=/x&method=GET", 1, "abcd")
+ assert len(sig) == 64
+ assert all(c in "0123456789abcdef" for c in sig)
+
+ @parameterized.expand(
+ [
+ ("prefixed", "vera01ei-abcdef0123456789", "abcdef0123456789"),
+ ("unprefixed", "abcdef0123456789", "abcdef0123456789"),
+ ]
+ )
+ def test_strip_region_prefix(self, _name: str, credential: str, expected: str) -> None:
+ assert _strip_region_prefix(credential) == expected
+
+ def test_auth_header_format_and_signed_url_includes_query(self) -> None:
+ auth = VeracodeHMACAuth("abcdef0123456789", "abcdef0123456789")
+ request = requests.Request("GET", "https://api.veracode.com/appsec/v1/applications?size=100&page=2").prepare()
+
+ auth(request)
+
+ header = request.headers["Authorization"]
+ assert header.startswith("VERACODE-HMAC-SHA-256 ")
+ parts = dict(kv.split("=", 1) for kv in header.removeprefix("VERACODE-HMAC-SHA-256 ").split(","))
+ assert set(parts) == {"id", "ts", "nonce", "sig"}
+ assert parts["id"] == "abcdef0123456789"
+ assert len(parts["sig"]) == 64
+
+ def test_prefix_stripped_from_header_id(self) -> None:
+ auth = VeracodeHMACAuth("vera01ei-abcdef0123456789", "vera01ei-abcdef0123456789")
+ request = requests.Request("GET", "https://api.veracode.com/appsec/v1/applications").prepare()
+
+ auth(request)
+
+ header = request.headers["Authorization"]
+ assert "id=abcdef0123456789," in header
+
+ def test_each_call_produces_fresh_signature(self) -> None:
+ auth = VeracodeHMACAuth("abcdef0123456789", "abcdef0123456789")
+ r1 = requests.Request("GET", "https://api.veracode.com/x").prepare()
+ r2 = requests.Request("GET", "https://api.veracode.com/x").prepare()
+
+ auth(r1)
+ auth(r2)
+
+ # Nonce + timestamp are regenerated per call, so signatures differ even for the same URL.
+ assert r1.headers["Authorization"] != r2.headers["Authorization"]
+
+
+class TestResolveHost:
+ @parameterized.expand(
+ [
+ ("commercial", "com", "api.veracode.com"),
+ ("europe", "eu", "api.veracode.eu"),
+ ("federal", "us", "api.veracode.us"),
+ ("default_when_none", None, "api.veracode.com"),
+ ("default_when_unknown", "bogus", "api.veracode.com"),
+ ]
+ )
+ def test_resolve_host(self, _name: str, region: str | None, expected: str) -> None:
+ assert resolve_host(region) == expected
+
+
+class TestSessionSecurity:
+ def test_session_disables_sample_capture_and_redacts_credentials(self) -> None:
+ # Veracode response bodies carry customers' vulnerability inventory, so both the credential
+ # probe and the sync must stay out of HTTP sample capture. Re-enabling capture here would
+ # leak that data to anyone with sample access, outside the warehouse table's access path.
+ session = _make_session("00vc-api-id", "ff-api-secret")
+ adapter = session.get_adapter("https://api.veracode.com")
+ assert isinstance(adapter, TrackedHTTPAdapter)
+ assert adapter._capture is False
+ assert "00vc-api-id" in adapter._redact_values
+ assert "ff-api-secret" in adapter._redact_values
+
+
+class TestModifiedAfter:
+ @parameterized.expand(
+ [
+ ("datetime_utc", datetime(2026, 3, 4, 12, 0, tzinfo=UTC), "2026-03-03"),
+ ("naive_datetime", datetime(2026, 3, 4, 12, 0), "2026-03-03"),
+ ("date", date(2026, 3, 4), "2026-03-03"),
+ ("non_temporal", "not-a-date", None),
+ ]
+ )
+ def test_modified_after_applies_day_lookback(self, _name: str, value: Any, expected: str | None) -> None:
+ # Day-granular filter with a 1-day lookback so nothing is dropped at the day boundary.
+ assert _modified_after(value) == expected
+
+
+class TestFetchPage:
+ # Call the single-attempt function so retry backoff isn't incurred. This guards the
+ # retryable-vs-permanent status classification.
+ _fetch_once = staticmethod(_fetch_page_once)
+
+ @parameterized.expand([("rate_limited", 429), ("server_error", 500), ("bad_gateway", 502)])
+ def test_retryable_statuses_raise_retryable_error(self, _name: str, status_code: int) -> None:
+ session = MagicMock()
+ session.get.return_value = _mock_response(status_code)
+ try:
+ self._fetch_once(session, "https://api.veracode.com/x", MagicMock())
+ except VeracodeRetryableError:
+ pass
+ else:
+ raise AssertionError("expected VeracodeRetryableError")
+
+ def test_client_error_raises_http_error(self) -> None:
+ session = MagicMock()
+ session.get.return_value = _mock_response(401)
+ try:
+ self._fetch_once(session, "https://api.veracode.com/x", MagicMock())
+ except requests.HTTPError:
+ pass
+ else:
+ raise AssertionError("expected HTTPError")
+
+ def test_ok_returns_json_body(self) -> None:
+ session = MagicMock()
+ session.get.return_value = _mock_response(200, {"_embedded": {"applications": []}})
+ assert self._fetch_once(session, "https://api.veracode.com/x", MagicMock()) == {
+ "_embedded": {"applications": []}
+ }
+
+
+class TestGetRowsTopLevel:
+ def test_pages_through_all_hal_pages_and_saves_resume_state(self) -> None:
+ session = MagicMock()
+ session.get.side_effect = [
+ _mock_response(200, _page([{"guid": "a"}], "applications", total_pages=2)),
+ _mock_response(200, _page([{"guid": "b"}], "applications", total_pages=2)),
+ ]
+ manager = MagicMock()
+ manager.can_resume.return_value = False
+
+ with _patched_session(session):
+ batches = list(
+ get_rows(
+ "id", "secret", "com", "applications", MagicMock(), manager, should_use_incremental_field=False
+ )
+ )
+
+ assert [row["guid"] for batch in batches for row in batch] == ["a", "b"]
+ # State saved after the first page (more remained), so a crash re-yields page 2, not skips it.
+ manager.save_state.assert_called_once_with(VeracodeResumeConfig(page=1))
+
+ def test_resumes_from_saved_page(self) -> None:
+ session = MagicMock()
+ session.get.return_value = _mock_response(200, _page([{"guid": "b"}], "applications", total_pages=2))
+ manager = MagicMock()
+ manager.can_resume.return_value = True
+ manager.load_state.return_value = VeracodeResumeConfig(page=1)
+
+ with _patched_session(session):
+ list(get_rows("id", "secret", "com", "applications", MagicMock(), manager))
+
+ # Resumed straight at page=1 rather than refetching page 0.
+ assert "page=1" in session.get.call_args_list[0].args[0]
+
+ def test_incremental_adds_modified_after_filter(self) -> None:
+ session = MagicMock()
+ session.get.return_value = _mock_response(200, _page([], "applications", total_pages=1))
+ manager = MagicMock()
+ manager.can_resume.return_value = False
+
+ with _patched_session(session):
+ list(
+ get_rows(
+ "id",
+ "secret",
+ "com",
+ "applications",
+ MagicMock(),
+ manager,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2026, 3, 4, tzinfo=UTC),
+ )
+ )
+
+ assert "modified_after=2026-03-03" in session.get.call_args_list[0].args[0]
+
+
+class TestGetRowsFanOut:
+ def test_stamps_application_guid_on_child_rows(self) -> None:
+ session = MagicMock()
+ session.get.side_effect = [
+ # application enumeration
+ _mock_response(200, _page([{"guid": "app-1"}], "applications", total_pages=1)),
+ # findings for app-1
+ _mock_response(200, _page([{"issue_id": 7}], "findings", total_pages=1)),
+ ]
+ manager = MagicMock()
+ manager.can_resume.return_value = False
+
+ with _patched_session(session):
+ batches = list(get_rows("id", "secret", "com", "findings", MagicMock(), manager))
+
+ rows = [row for batch in batches for row in batch]
+ assert rows == [{"issue_id": 7, "application_guid": "app-1"}]
+
+ def test_deleted_application_404_is_skipped(self) -> None:
+ session = MagicMock()
+ session.get.side_effect = [
+ _mock_response(200, _page([{"guid": "app-gone"}, {"guid": "app-ok"}], "applications", total_pages=1)),
+ _mock_response(404), # app-gone deleted between enumeration and fetch
+ _mock_response(200, _page([{"issue_id": 1}], "findings", total_pages=1)), # app-ok
+ ]
+ manager = MagicMock()
+ manager.can_resume.return_value = False
+
+ with _patched_session(session):
+ batches = list(get_rows("id", "secret", "com", "findings", MagicMock(), manager))
+
+ rows = [row for batch in batches for row in batch]
+ assert rows == [{"issue_id": 1, "application_guid": "app-ok"}]
+
+ def test_sca_findings_requests_scan_type_sca(self) -> None:
+ session = MagicMock()
+ session.get.side_effect = [
+ _mock_response(200, _page([{"guid": "app-1"}], "applications", total_pages=1)),
+ _mock_response(200, _page([], "findings", total_pages=1)),
+ ]
+ manager = MagicMock()
+ manager.can_resume.return_value = False
+
+ with _patched_session(session):
+ list(get_rows("id", "secret", "com", "sca_findings", MagicMock(), manager))
+
+ findings_url = session.get.call_args_list[1].args[0]
+ assert "scan_type=SCA" in findings_url
+ # Fan-out child requests must carry the configured page size too, not fall back to the API
+ # default — the top-level path and application enumeration both set it.
+ assert f"size={PAGE_SIZE}" in findings_url
+
+
+class TestVeracodeSourceResponse:
+ @parameterized.expand(list(VERACODE_ENDPOINTS.keys()))
+ def test_source_response_matches_endpoint_config(self, endpoint: str) -> None:
+ config = VERACODE_ENDPOINTS[endpoint]
+ response = veracode_source("id", "secret", "com", endpoint, MagicMock(), MagicMock())
+
+ assert response.name == endpoint
+ assert response.primary_keys == config.primary_keys
+ assert response.sort_mode == "asc"
+ if config.partition_key:
+ assert response.partition_keys == [config.partition_key]
+ assert response.partition_mode == "datetime"
+ else:
+ assert response.partition_keys is None
+
+
+class TestValidateCredentials:
+ @parameterized.expand([("ok", 200, True), ("unauthorized", 401, False), ("forbidden", 403, False)])
+ def test_status_maps_to_ok_flag(self, _name: str, status_code: int, expected_ok: bool) -> None:
+ session = MagicMock()
+ session.get.return_value = _mock_response(status_code)
+ with _patched_session(session):
+ ok, returned_status = validate_credentials("id", "secret", "com")
+ assert ok is expected_ok
+ assert returned_status == status_code
+
+ def test_network_error_returns_false_none(self) -> None:
+ session = MagicMock()
+ session.get.side_effect = requests.ConnectionError()
+ with _patched_session(session):
+ ok, status = validate_credentials("id", "secret", "com")
+ assert ok is False
+ assert status is None
+
+
+class _patched_session:
+ """Context manager patching `_make_session` so tests inject a mock requests session."""
+
+ def __init__(self, session: MagicMock):
+ self._session = session
+ self._patcher: Any = None
+
+ def __enter__(self) -> MagicMock:
+ from unittest.mock import patch
+
+ self._patcher = patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.veracode.veracode._make_session",
+ return_value=self._session,
+ )
+ self._patcher.start()
+ return self._session
+
+ def __exit__(self, *args: Any) -> None:
+ self._patcher.stop()
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/veracode/tests/test_veracode_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/veracode/tests/test_veracode_source.py
new file mode 100644
index 000000000000..d1eed1df4ddb
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/veracode/tests/test_veracode_source.py
@@ -0,0 +1,119 @@
+from typing import Optional
+
+from unittest.mock import MagicMock, patch
+
+from parameterized import parameterized
+
+from posthog.schema import ReleaseStatus
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceInputs
+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 VeracodeSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.veracode.source import VeracodeSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.veracode.veracode import VeracodeResumeConfig
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+def _config() -> VeracodeSourceConfig:
+ return VeracodeSourceConfig(api_id="the-id", api_secret="the-secret", region="com")
+
+
+def _inputs(schema_name: str) -> SourceInputs:
+ return SourceInputs(
+ schema_name=schema_name,
+ schema_id="schema-id",
+ source_id="source-id",
+ team_id=1,
+ should_use_incremental_field=False,
+ db_incremental_field_last_value=None,
+ db_incremental_field_earliest_value=None,
+ incremental_field=None,
+ incremental_field_type=None,
+ job_id="job-id",
+ logger=MagicMock(),
+ reset_pipeline=False,
+ )
+
+
+class TestVeracodeSourceConfig:
+ def test_source_type(self) -> None:
+ assert VeracodeSource().source_type == ExternalDataSourceType.VERACODE
+
+ def test_config_is_visible_and_alpha(self) -> None:
+ config = VeracodeSource().get_source_config
+ # A finished source must never keep unreleasedSource (that hides it from every user).
+ assert config.unreleasedSource is None
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+
+ def test_config_fields(self) -> None:
+ config = VeracodeSource().get_source_config
+ assert [f.name for f in config.fields] == ["api_id", "api_secret", "region"]
+
+ def test_lists_tables_without_credentials(self) -> None:
+ # Static endpoint catalog with no I/O — required for the public docs table list to render.
+ assert VeracodeSource().lists_tables_without_credentials is True
+ assert len(VeracodeSource().get_documented_tables()) == 4
+
+
+class TestGetSchemas:
+ def test_only_applications_supports_incremental(self) -> None:
+ schemas = {s.name: s for s in VeracodeSource().get_schemas(_config(), team_id=1)}
+ assert set(schemas) == {"applications", "sandboxes", "findings", "sca_findings"}
+ assert schemas["applications"].supports_incremental is True
+ assert [f["field"] for f in schemas["applications"].incremental_fields] == ["modified"]
+ for full_refresh in ("sandboxes", "findings", "sca_findings"):
+ assert schemas[full_refresh].supports_incremental is False
+
+ def test_names_filter(self) -> None:
+ schemas = VeracodeSource().get_schemas(_config(), team_id=1, names=["findings"])
+ assert [s.name for s in schemas] == ["findings"]
+
+
+class TestValidateCredentials:
+ @parameterized.expand(
+ [
+ ("valid", (True, 200), None, True),
+ ("forbidden_at_create_is_accepted", (False, 403), None, True),
+ ("forbidden_for_schema_is_rejected", (False, 403), "findings", False),
+ ("unauthorized_is_rejected", (False, 401), None, False),
+ ("unreachable_is_rejected", (False, None), None, False),
+ ]
+ )
+ def test_validate_credentials(
+ self, _name: str, probe_result: tuple[bool, Optional[int]], schema_name: Optional[str], expected_ok: bool
+ ) -> None:
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.veracode.source.validate_veracode_credentials",
+ return_value=probe_result,
+ ):
+ ok, error = VeracodeSource().validate_credentials(_config(), team_id=1, schema_name=schema_name)
+ assert ok is expected_ok
+ assert (error is None) is expected_ok
+
+
+class TestResumableWiring:
+ def test_resumable_manager_bound_to_resume_config(self) -> None:
+ manager = VeracodeSource().get_resumable_source_manager(_inputs("applications"))
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is VeracodeResumeConfig
+
+ def test_source_for_pipeline_returns_named_response(self) -> None:
+ manager = MagicMock()
+ response = VeracodeSource().source_for_pipeline(_config(), manager, _inputs("findings"))
+ assert response.name == "findings"
+ assert response.primary_keys == ["application_guid", "issue_id"]
+
+ def test_source_for_pipeline_rejects_unknown_endpoint(self) -> None:
+ try:
+ VeracodeSource().source_for_pipeline(_config(), MagicMock(), _inputs("not_an_endpoint"))
+ except ValueError:
+ pass
+ else:
+ raise AssertionError("expected ValueError for unknown endpoint")
+
+
+class TestNonRetryableErrors:
+ def test_auth_errors_are_non_retryable(self) -> None:
+ errors = VeracodeSource().get_non_retryable_errors()
+ assert "401 Client Error: Unauthorized" in errors
+ assert "403 Client Error: Forbidden" in errors
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/veracode/veracode.py b/products/warehouse_sources/backend/temporal/data_imports/sources/veracode/veracode.py
new file mode 100644
index 000000000000..551947d7e724
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/veracode/veracode.py
@@ -0,0 +1,362 @@
+import os
+import hmac
+import time
+import hashlib
+import dataclasses
+from collections.abc import Iterator
+from datetime import UTC, date, datetime, timedelta
+from typing import Any, Optional
+from urllib.parse import urlencode, urlparse
+
+import requests
+from structlog.types import FilteringBoundLogger
+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+from urllib3.util.retry import Retry
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.veracode.settings import (
+ PAGE_SIZE,
+ VERACODE_ENDPOINTS,
+ VeracodeEndpointConfig,
+)
+
+# Region -> REST API host. Veracode isolates data per region, and the signing host must match the
+# host the request is actually sent to, so the region choice picks both.
+REGION_HOSTS: dict[str, str] = {
+ "com": "api.veracode.com", # US commercial (default)
+ "eu": "api.veracode.eu", # European region
+ "us": "api.veracode.us", # US federal (FedRAMP)
+}
+DEFAULT_REGION = "com"
+
+_HMAC_VERSION = b"vcode_request_version_1"
+_AUTH_SCHEME = "VERACODE-HMAC-SHA-256"
+
+# Applications API modified_after filter is day-granular; re-pull the whole day around the watermark
+# and let merge dedupe on the primary key so nothing is missed at the day boundary.
+MODIFIED_AFTER_LOOKBACK_DAYS = 1
+
+REQUEST_TIMEOUT_SECONDS = 60
+
+
+class VeracodeRetryableError(Exception):
+ pass
+
+
+class VeracodeResumeConfig:
+ # Next zero-based HAL page to fetch. For fan-out endpoints this is the page within `app_guid`.
+ page: int = 0
+ # Fan-out only: the application GUID currently being processed. None for top-level endpoints.
+ app_guid: str | None = None
+
+
+def _strip_region_prefix(credential: str) -> str:
+ """Strip the region prefix from a Veracode credential.
+
+ Newer credentials are issued as `<prefix>-<hex>` (e.g. `vera01ei-abc123...`); the prefix is not
+ part of the signing material and must be removed from both the id and the secret before use.
+ Legacy credentials have no `-` and pass through unchanged.
+ """
+ return credential.rsplit("-", 1)[-1]
+
+
+def _calculate_signature(api_secret: str, signing_data: str, timestamp_ms: int, nonce_hex: str) -> str:
+ """Compute the Veracode HMAC-SHA-256 request signature via the documented key-derivation chain."""
+ key = bytes.fromhex(_strip_region_prefix(api_secret))
+ nonce = bytes.fromhex(nonce_hex)
+ key_nonce = hmac.new(key, nonce, hashlib.sha256).digest()
+ key_date = hmac.new(key_nonce, str(timestamp_ms).encode(), hashlib.sha256).digest()
+ signature_key = hmac.new(key_date, _HMAC_VERSION, hashlib.sha256).digest()
+ return hmac.new(signature_key, signing_data.encode(), hashlib.sha256).hexdigest()
+
+
+class VeracodeHMACAuth(requests.auth.AuthBase):
+ """Signs each request with a per-request `VERACODE-HMAC-SHA-256` Authorization header.
+
+ Applied at the session level so every attempt re-signs with a fresh timestamp and nonce — the
+ signed timestamp expires, so retries must not reuse a stale signature.
+ """
+
+ def __init__(self, api_id: str, api_secret: str):
+ self._api_id = _strip_region_prefix(api_id)
+ self._api_secret = api_secret
+
+ def __call__(self, request: requests.PreparedRequest) -> requests.PreparedRequest:
+ parsed = urlparse(request.url or "")
+ host = (parsed.hostname or "").lower()
+ url = parsed.path or "/"
+ if parsed.query:
+ url = f"{url}?{parsed.query}"
+ timestamp_ms = int(round(time.time() * 1000))
+ nonce = os.urandom(16).hex()
+ signing_data = f"id={self._api_id.lower()}&host={host}&url={url}&method={(request.method or 'GET').upper()}"
+ signature = _calculate_signature(self._api_secret, signing_data, timestamp_ms, nonce)
+ request.headers["Authorization"] = (
+ f"{_AUTH_SCHEME} id={self._api_id},ts={timestamp_ms},nonce={nonce},sig={signature}"
+ )
+ return request
+
+
+def resolve_host(region: str | None) -> str:
+ return REGION_HOSTS.get(region or DEFAULT_REGION, REGION_HOSTS[DEFAULT_REGION])
+
+
+def _base_url(region: str | None) -> str:
+ return f"https://{resolve_host(region)}"
+
+
+def _make_session(api_id: str, api_secret: str) -> requests.Session:
+ # Disable urllib3-level retries so tenacity owns retry (it re-signs each attempt); a urllib3 retry
+ # would resend the same prepared request with an expired signature.
+ # capture=False: Veracode response bodies carry customers' vulnerability inventory (finding
+ # locations, components, procedure names). The generic scrubber can't recognise those, so keep
+ # them out of HTTP sample capture entirely rather than leak them outside the warehouse table.
+ session = make_tracked_session(retry=Retry(total=0), redact_values=(api_id, api_secret), capture=False)
+ session.auth = VeracodeHMACAuth(api_id, api_secret)
+ session.headers.update({"Accept": "application/json"})
+ return session
+
+
+def validate_credentials(api_id: str, api_secret: str, region: str | None) -> tuple[bool, int | None]:
+ """Probe the token with one cheap request. Returns (ok, status_code)."""
+ url = f"{_base_url(region)}/appsec/v1/applications?size=1"
+ try:
+ response = _make_session(api_id, api_secret).get(url, timeout=REQUEST_TIMEOUT_SECONDS)
+ except Exception:
+ return False, None
+ return response.status_code == 200, response.status_code
+
+
+def _fetch_page_once(session: requests.Session, url: str, logger: FilteringBoundLogger) -> dict:
+ response = session.get(url, timeout=REQUEST_TIMEOUT_SECONDS)
+
+ if response.status_code == 429 or response.status_code >= 500:
+ raise VeracodeRetryableError(f"Veracode API error (retryable): status={response.status_code}, url={url}")
+
+ if not response.ok:
+ log = logger.warning if response.status_code == 404 else logger.error
+ log(f"Veracode API error: status={response.status_code}, body={response.text}, url={url}")
+ response.raise_for_status()
+
+ return response.json()
+
+
+@retry(
+ retry=retry_if_exception_type(
+ (
+ VeracodeRetryableError,
+ requests.ReadTimeout,
+ requests.ConnectionError,
+ requests.exceptions.ChunkedEncodingError,
+ )
+ ),
+ stop=stop_after_attempt(5),
+ wait=wait_exponential_jitter(initial=1, max=30),
+ reraise=True,
+)
+def _fetch_page(session: requests.Session, url: str, logger: FilteringBoundLogger) -> dict:
+ return _fetch_page_once(session, url, logger)
+
+
+def _total_pages(data: dict) -> int:
+ return int(data.get("page", {}).get("total_pages", 0) or 0)
+
+
+def _build_url(region: str | None, path: str, params: dict[str, Any]) -> str:
+ query = urlencode({k: v for k, v in params.items() if v is not None})
+ return f"{_base_url(region)}{path}?{query}"
+
+
+def _modified_after(db_incremental_field_last_value: Any) -> str | None:
+ """Format the incremental watermark as a `modified_after` date, minus the day-granular lookback."""
+ value = db_incremental_field_last_value
+ if isinstance(value, datetime):
+ as_date = value.astimezone(UTC).date() if value.tzinfo else value.date()
+ elif isinstance(value, date):
+ as_date = value
+ else:
+ return None
+ return (as_date - timedelta(days=MODIFIED_AFTER_LOOKBACK_DAYS)).isoformat()
+
+
+def _application_params(
+ config: VeracodeEndpointConfig,
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Any,
+) -> dict[str, Any]:
+ params: dict[str, Any] = {"size": PAGE_SIZE, **config.extra_params}
+ if should_use_incremental_field and db_incremental_field_last_value is not None:
+ modified_after = _modified_after(db_incremental_field_last_value)
+ if modified_after:
+ params["modified_after"] = modified_after
+ return params
+
+
+def _iter_application_guids(
+ session: requests.Session, region: str | None, logger: FilteringBoundLogger
+) -> Iterator[str]:
+ """Page through /applications and yield each application GUID (drives fan-out endpoints)."""
+ page = 0
+ while True:
+ url = _build_url(region, VERACODE_ENDPOINTS["applications"].path, {"size": PAGE_SIZE, "page": page})
+ data = _fetch_page(session, url, logger)
+ for item in data.get("_embedded", {}).get("applications", []):
+ guid = item.get("guid")
+ if guid:
+ yield guid
+ page += 1
+ if page >= _total_pages(data):
+ break
+
+
+def _iter_top_level_rows(
+ session: requests.Session,
+ region: str | None,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[VeracodeResumeConfig],
+ config: VeracodeEndpointConfig,
+ params: dict[str, Any],
+) -> Iterator[list[dict[str, Any]]]:
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ page = resume.page if resume is not None and resume.app_guid is None else 0
+
+ while True:
+ url = _build_url(region, config.path, {**params, "page": page})
+ data = _fetch_page(session, url, logger)
+ rows = data.get("_embedded", {}).get(config.embedded_key, [])
+
+ page += 1
+ has_more = page < _total_pages(data)
+
+ if rows:
+ yield rows
+ # Save AFTER yielding so a crash re-yields the last page rather than skipping it — merge
+ # dedupes on the primary key.
+ if has_more:
+ resumable_source_manager.save_state(VeracodeResumeConfig(page=page))
+
+ if not has_more:
+ break
+
+
+def _iter_fan_out_rows(
+ session: requests.Session,
+ region: str | None,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[VeracodeResumeConfig],
+ config: VeracodeEndpointConfig,
+ params: dict[str, Any],
+) -> Iterator[list[dict[str, Any]]]:
+ """Iterate every application and page through the per-application child endpoint.
+
+ Each child row is stamped with `application_guid` so the composite primary key is unique across
+ the whole table (child ids are only unique within their parent application).
+ """
+ app_guids = list(_iter_application_guids(session, region, logger))
+
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ remaining = app_guids
+ resume_page = 0
+ if resume is not None and resume.app_guid is not None and resume.app_guid in app_guids:
+ remaining = app_guids[app_guids.index(resume.app_guid) :]
+ resume_page = resume.page
+ logger.debug(f"Veracode: resuming {config.name} from app_guid={resume.app_guid}, page={resume_page}")
+
+ for index, app_guid in enumerate(remaining):
+ path = config.path.format(application_guid=app_guid)
+ page = resume_page
+ resume_page = 0 # only the resumed-into application uses the saved page
+
+ try:
+ while True:
+ url = _build_url(region, path, {**params, "page": page})
+ data = _fetch_page(session, url, logger)
+ rows = [
+ {**row, "application_guid": app_guid}
+ for row in data.get("_embedded", {}).get(config.embedded_key, [])
+ ]
+
+ page += 1
+ has_more = page < _total_pages(data)
+
+ if rows:
+ yield rows
+ if has_more:
+ resumable_source_manager.save_state(VeracodeResumeConfig(page=page, app_guid=app_guid))
+
+ if not has_more:
+ break
+ except requests.HTTPError as exc:
+ # An application deleted between enumeration and this fetch 404s. Skip it rather than
+ # failing the whole sync. Any other HTTP error is re-raised.
+ if exc.response is not None and exc.response.status_code == 404:
+ logger.warning(f"Veracode: application {app_guid} not found while fetching {config.name}, skipping")
+ else:
+ raise
+
+ # Advance the bookmark to the next application so a crash between apps resumes correctly.
+ if index + 1 < len(remaining):
+ resumable_source_manager.save_state(VeracodeResumeConfig(page=0, app_guid=remaining[index + 1]))
+
+
+def get_rows(
+ api_id: str,
+ api_secret: str,
+ region: str | None,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[VeracodeResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+) -> Iterator[list[dict[str, Any]]]:
+ config = VERACODE_ENDPOINTS[endpoint]
+ session = _make_session(api_id, api_secret)
+
+ if config.fan_out_over_applications:
+ yield from _iter_fan_out_rows(
+ session, region, logger, resumable_source_manager, config, {"size": PAGE_SIZE, **config.extra_params}
+ )
+ return
+
+ params = _application_params(config, should_use_incremental_field, db_incremental_field_last_value)
+ yield from _iter_top_level_rows(session, region, logger, resumable_source_manager, config, params)
+
+
+def veracode_source(
+ api_id: str,
+ api_secret: str,
+ region: str | None,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[VeracodeResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+) -> SourceResponse:
+ config = VERACODE_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ api_id=api_id,
+ api_secret=api_secret,
+ region=region,
+ 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,
+ # HAL pagination is deterministic and resumed by page number, so ordering doesn't gate resume;
+ # ascending is the safe default for the day-granular applications watermark (paired with the
+ # lookback above). Fan-out endpoints are full refresh.
+ sort_mode="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,
+ )