: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 snyk import source (#71197)
Tom Owerse46c198ab127
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 175fb08724d0..43529acaa96a 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -461,6 +461,7 @@ the row lists both.| snapchat_ads | HTTP | requests + `rest_source.RESTClient` | ✅ || snowflake | DB protocol | snowflake-connector-python | ➖ || snowplow | HTTP | requests | ✅ |+| snyk | HTTP | requests | ✅ || solarwinds_service_desk | HTTP | requests | ✅ || sonarqube | HTTP | requests | ✅ || spacelift | HTTP (GraphQL) | requests | ✅ |@@ -915,7 +916,6 @@ doesn't conflict with concurrent PRs.- smaily- smartengage- smartwaiver-- snyk- solarwinds_service_desk- sonar_cloud- sonatype_nexusdiff --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 eca85df6896c..b21074be9970 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@@ -4013,7 +4013,9 @@ class SnowplowSourceConfig(config.Config):@config.configclass SnykSourceConfig(config.Config):- pass+ api_token: str+ region: Literal["us", "eu", "au"] = config.value(default="us")+ organization_id: str | None = None@config.configdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/snyk/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/snyk/canonical_descriptions.pynew file mode 100644index 000000000000..a8cb5428e1f1--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/snyk/canonical_descriptions.py@@ -0,0 +1,75 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++# Descriptions sourced from the Snyk REST API reference (https://apidocs.snyk.io/). Rows are the+# JSON:API record with its `attributes` flattened to the root; fan-out tables additionally carry+# the injected `organization_id`.+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "organizations": {+ "description": "A Snyk organization the API token can access. Organizations group projects, targets, and issues, and carry their own settings and membership.",+ "docs_url": "https://apidocs.snyk.io/#get-/orgs",+ "columns": {+ "id": "Unique identifier (UUID) of the organization.",+ "type": "JSON:API resource type (org).",+ "name": "Display name of the organization.",+ "slug": "URL-friendly unique name of the organization.",+ "group_id": "Identifier of the Snyk group the organization belongs to, if any.",+ "is_personal": "Whether the organization is a personal organization rather than a shared one.",+ "created_at": "When the organization was created.",+ "updated_at": "When the organization was last updated.",+ },+ },+ "projects": {+ "description": "A project scanned by Snyk within an organization — one entry per manifest, container image, or IaC configuration monitored for vulnerabilities.",+ "docs_url": "https://apidocs.snyk.io/#get-/orgs/-org_id-/projects",+ "columns": {+ "id": "Unique identifier (UUID) of the project.",+ "type": "JSON:API resource type (project).",+ "organization_id": "Identifier of the organization the project belongs to.",+ "name": "Name of the project, typically the repository plus the manifest path.",+ "origin": "Integration the project was imported from (e.g. github, cli, docker-hub).",+ "target_file": "Path of the scanned manifest or configuration file.",+ "target_reference": "Reference within the target, such as a branch name or image tag.",+ "created": "When the project was created in Snyk.",+ "status": "Whether the project is actively monitored (active) or deactivated (inactive).",+ "business_criticality": "User-assigned business criticality attributes for the project.",+ "environment": "User-assigned environment attributes for the project.",+ "lifecycle": "User-assigned lifecycle stage attributes for the project.",+ "tags": "User-assigned key/value tags on the project.",+ },+ },+ "targets": {+ "description": "A target is the scanned entity a project comes from — a code repository, container image, or other importable asset within an organization.",+ "docs_url": "https://apidocs.snyk.io/#get-/orgs/-org_id-/targets",+ "columns": {+ "id": "Unique identifier (UUID) of the target.",+ "type": "JSON:API resource type (target).",+ "organization_id": "Identifier of the organization the target belongs to.",+ "display_name": "Human-readable name of the target, such as owner/repository.",+ "url": "URL of the target, e.g. the repository or registry location.",+ "is_private": "Whether the target is private in its source system.",+ "created_at": "When the target was created in Snyk.",+ },+ },+ "issues": {+ "description": "A vulnerability, license, or configuration issue found by Snyk in an organization's projects — the core findings table for tracking security backlog, severity mix, and remediation over time.",+ "docs_url": "https://apidocs.snyk.io/#get-/orgs/-org_id-/issues",+ "columns": {+ "id": "Unique identifier (UUID) of the issue.",+ "type": "JSON:API resource type (issue).",+ "organization_id": "Identifier of the organization the issue belongs to.",+ "key": "Stable key identifying the issue across scans.",+ "title": "Human-readable title of the issue.",+ "effective_severity_level": "Effective severity of the issue (low, medium, high, critical) after any user overrides.",+ "status": "Current status of the issue (open or resolved).",+ "ignored": "Whether the issue has been ignored.",+ "problems": "The underlying problems (vulnerabilities or license conditions) that cause the issue.",+ "coordinates": "Where the issue was found, including the affected package or resource and remediation availability.",+ "classes": "Weakness classes for the issue, such as CWE identifiers.",+ "risk": "Risk information for the issue, including the Snyk risk score when available.",+ "created_at": "When the issue was first created.",+ "updated_at": "When the issue was last updated.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/snyk/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/snyk/settings.pynew file mode 100644index 000000000000..c31892abcd48--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/snyk/settings.py@@ -0,0 +1,106 @@+from dataclasses import dataclass, field+from enum import Enum+from typing import Optional++from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType+++class SnykScope(Enum):+ """Where an endpoint lives in Snyk's resource hierarchy.++ Every Snyk REST resource except the org inventory itself is scoped under an+ organization, so fetching those tables means walking ``orgs -> <endpoint>``.+ """++ # Top-level collection reachable directly from the token (GET /rest/orgs).+ ORGANIZATION = "organization"+ # Fan out over every organization the token can see (GET /rest/orgs/{org_id}/...).+ PER_ORG = "per_org"+++@dataclass+class SnykEndpointConfig:+ name: str+ scope: SnykScope+ # Path template relative to the ``/rest`` prefix. PER_ORG paths contain ``{org_id}``.+ path: str+ # Primary key columns used for merge dedup. Snyk ids are UUIDs, but the REST API only+ # documents uniqueness within a parent org, so fan-out children include the injected+ # ``organization_id`` in their key — a redundant-but-safe composite never seeds duplicates.+ primary_keys: list[str]+ # Stable, creation-time datetime column to partition by. Never ``updated_at`` — that moves+ # and would rewrite partitions every sync. None disables partitioning.+ partition_key: Optional[str] = None+ # The menu of incremental cursor candidates advertised to the user. Empty = full refresh only.+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ # Maps an incremental field to the server-side filter query param that bounds it+ # (e.g. ``updated_at`` -> ``updated_after``). Only populated when the API genuinely+ # filters server-side — an empty mapping keeps the endpoint full-refresh only.+ incremental_param_by_field: dict[str, str] = field(default_factory=dict)+ default_incremental_field: Optional[str] = None+ # Snyk's documented ``limit`` maximum is 100 for these endpoints (default is 10).+ page_size: int = 100++ @property+ def supports_incremental(self) -> bool:+ return bool(self.incremental_param_by_field)+++def _timestamp_incremental_field(field_name: str) -> IncrementalField:+ return {+ "label": field_name,+ "type": IncrementalFieldType.DateTime,+ "field": field_name,+ "field_type": IncrementalFieldType.DateTime,+ }+++# Endpoint catalog. Coverage mirrors the canonical Snyk streams (org inventory, projects,+# targets, and the high-value issues/findings table).+#+# Incremental vs full refresh: only the issues endpoint documents genuine server-side+# timestamp filters (``updated_after`` / ``created_after``), so only issues is marked+# incremental. Orgs/projects/targets have no reliable server-side time filter, so they ship+# full refresh and dedupe on their primary key.+SNYK_ENDPOINTS: dict[str, SnykEndpointConfig] = {+ "organizations": SnykEndpointConfig(+ name="organizations",+ scope=SnykScope.ORGANIZATION,+ path="/orgs",+ primary_keys=["id"],+ ),+ "projects": SnykEndpointConfig(+ name="projects",+ scope=SnykScope.PER_ORG,+ path="/orgs/{org_id}/projects",+ primary_keys=["id", "organization_id"],+ ),+ "targets": SnykEndpointConfig(+ name="targets",+ scope=SnykScope.PER_ORG,+ path="/orgs/{org_id}/targets",+ primary_keys=["id", "organization_id"],+ ),+ "issues": SnykEndpointConfig(+ name="issues",+ scope=SnykScope.PER_ORG,+ path="/orgs/{org_id}/issues",+ primary_keys=["id", "organization_id"],+ partition_key="created_at",+ incremental_fields=[+ _timestamp_incremental_field("updated_at"),+ _timestamp_incremental_field("created_at"),+ ],+ incremental_param_by_field={+ "updated_at": "updated_after",+ "created_at": "created_after",+ },+ default_incremental_field="updated_at",+ ),+}++ENDPOINTS = tuple(SNYK_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in SNYK_ENDPOINTS.items()+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/snyk/snyk.py b/products/warehouse_sources/backend/temporal/data_imports/sources/snyk/snyk.pynew file mode 100644index 000000000000..4b01f043d9cd--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/snyk/snyk.py@@ -0,0 +1,390 @@+import re+import dataclasses+from collections.abc import Iterator+from datetime import UTC, date, datetime+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 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.snyk.settings import (+ SNYK_ENDPOINTS,+ SnykEndpointConfig,+ SnykScope,+)++# Snyk regional stacks are independent and don't share data; the region selects which API host+# the token is sent to. The set is a fixed allow-list, so the host can't be retargeted.+SNYK_REGION_HOSTS = {+ "us": "https://api.snyk.io",+ "eu": "https://api.eu.snyk.io",+ "au": "https://api.au.snyk.io",+}+DEFAULT_REGION = "us"++# Every Snyk REST call requires a dated ``version`` query param; omitting it is an error.+# This is a GA version that includes the issues endpoint's ``updated_after``/``created_after``+# filters. Snyk keeps GA versions available through a long deprecation window.+SNYK_REST_VERSION = "2024-10-15"++REQUEST_TIMEOUT_SECONDS = 60++# Snyk org ids are UUIDs. The configured org id is interpolated into a URL path, so reject+# anything that could alter the path shape before it gets near a request.+_ORG_ID_RE = re.compile(r"^[a-zA-Z0-9-]+$")+++class SnykRetryableError(Exception):+ pass+++class SnykResumeConfig:+ # Next page URL (from the JSON:API ``links.next``) to fetch on resume.+ next_url: str+ # The fan-out org currently being processed. A stable id rather than a positional index so+ # orgs added/removed between a crash and the retry can't resume into the wrong one. None for+ # the top-level organizations endpoint.+ org_id: str | None = None+++def base_url(region: Optional[str]) -> str:+ return SNYK_REGION_HOSTS.get(region or DEFAULT_REGION, SNYK_REGION_HOSTS[DEFAULT_REGION])+++def _get_headers(api_token: str) -> dict[str, str]:+ return {+ "Authorization": f"token {api_token}",+ "Accept": "application/vnd.api+json",+ }+++def _build_url(host: str, path: str, params: dict[str, Any]) -> str:+ return f"{host}/rest{path}?{urlencode(params)}"+++def _format_datetime(value: Any) -> str:+ """Format an incremental cursor value as RFC 3339 with a ``Z`` suffix for Snyk filters."""+ if isinstance(value, datetime):+ dt = value+ elif isinstance(value, date):+ dt = datetime.combine(value, datetime.min.time())+ else:+ return str(value)+ dt = dt.replace(tzinfo=UTC) if dt.tzinfo is None else dt.astimezone(UTC)+ return dt.strftime("%Y-%m-%dT%H:%M:%SZ")+++def _is_same_host(url: str, host: str) -> bool:+ parsed = urlparse(url)+ return parsed.scheme == "https" and parsed.netloc == urlparse(host).netloc+++def _next_page_url(host: str, payload: Any) -> str | None:+ """Resolve the JSON:API ``links.next`` value into an absolute URL on the resolved host.++ Snyk returns ``links.next`` either as a string or a ``{"href": ...}`` object, and as a+ relative path that may or may not carry the ``/rest`` prefix depending on API version. Only+ same-host absolute URLs are followed, so a tampered response can't point our authenticated+ request at another server (SSRF) and leak the token header.+ """+ links = payload.get("links") if isinstance(payload, dict) else None+ next_link = links.get("next") if isinstance(links, dict) else None+ if isinstance(next_link, dict):+ next_link = next_link.get("href")+ if not isinstance(next_link, str) or not next_link:+ return None+ if next_link.startswith("http"):+ return next_link if _is_same_host(next_link, host) else None+ if not next_link.startswith("/"):+ next_link = f"/{next_link}"+ if not next_link.startswith("/rest/"):+ next_link = f"/rest{next_link}"+ return f"{host}{next_link}"+++def _flatten_item(item: dict[str, Any]) -> dict[str, Any]:+ """Lift a JSON:API record's ``attributes`` object to the root, keeping ``id``/``type``."""+ attributes = item.get("attributes")+ if isinstance(attributes, dict):+ item.pop("attributes")+ for key, value in attributes.items():+ item.setdefault(key, value)+ return item+++@retry(+ retry=retry_if_exception_type((SnykRetryableError, requests.ReadTimeout, requests.ConnectionError)),+ stop=stop_after_attempt(5),+ wait=wait_exponential_jitter(initial=1, max=60),+ reraise=True,+)+def _fetch_page(session: requests.Session, url: str, logger: FilteringBoundLogger) -> Any:+ response = session.get(url, timeout=REQUEST_TIMEOUT_SECONDS)++ # Snyk rate limits per token and returns 429 (with Retry-After) on exceed; retry those plus+ # transient 5xx with exponential backoff.+ if response.status_code == 429 or response.status_code >= 500:+ raise SnykRetryableError(f"Snyk API error (retryable): status={response.status_code}, url={url}")++ if not response.ok:+ logger.error(f"Snyk API error: status={response.status_code}, body={response.text}, url={url}")+ response.raise_for_status()++ return response.json()+++def _fetch_list_page(+ session: requests.Session, url: str, host: str, logger: FilteringBoundLogger+) -> tuple[list[dict[str, Any]], str | None]:+ """Fetch one page of a Snyk REST list endpoint, returning (items, next_page_url)."""+ payload = _fetch_page(session, url, logger)+ items = payload.get("data") if isinstance(payload, dict) else None+ if not isinstance(items, list):+ return [], None+ return items, _next_page_url(host, payload)+++def _validated_org_id(organization_id: str) -> str:+ org_id = organization_id.strip()+ if not _ORG_ID_RE.match(org_id):+ raise ValueError(f"Invalid Snyk organization id: {organization_id!r}")+ return org_id+++def _resolve_org_ids(+ session: requests.Session, host: str, organization_id: Optional[str], logger: FilteringBoundLogger+) -> list[str]:+ """The org ids to fan out over: the configured single org, or every org the token can see.++ The multi-org list is sorted so the fan-out order is deterministic across runs. ``/orgs`` takes+ no sort param and JSON:API doesn't guarantee response ordering, so without this the positional+ resume in ``_iter_fan_out`` could skip an org if the API returned the list in a different order+ after a crash.+ """+ if organization_id and organization_id.strip():+ return [_validated_org_id(organization_id)]++ org_ids: list[str] = []+ url: str | None = _build_url(host, "/orgs", {"version": SNYK_REST_VERSION, "limit": 100})+ while url:+ items, url = _fetch_list_page(session, url, host, logger)+ org_ids.extend(item["id"] for item in items)+ return sorted(org_ids)+++def _initial_params(+ config: SnykEndpointConfig,+ incremental_field: Optional[str],+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+) -> dict[str, Any]:+ params: dict[str, Any] = {"version": SNYK_REST_VERSION, "limit": config.page_size}++ # ``links.next`` carries all query params forward, so applying the watermark filter to the+ # first page keeps every subsequent page bounded too.+ if should_use_incremental_field and db_incremental_field_last_value is not None:+ field = incremental_field or config.default_incremental_field+ filter_param = config.incremental_param_by_field.get(field) if field else None+ if filter_param:+ params[filter_param] = _format_datetime(db_incremental_field_last_value)++ return params+++def _iter_single_org(+ session: requests.Session,+ host: str,+ organization_id: str,+ logger: FilteringBoundLogger,+) -> Iterator[list[dict[str, Any]]]:+ """Emit only the configured organization instead of every org the token can reach.++ ``GET /rest/orgs/{org_id}`` returns that one org as a single JSON:API object. Honoring the+ configured id here keeps a single-org connection scoped to that org, so a member can't+ enumerate every organization the token can see via the organizations table.+ """+ org_id = _validated_org_id(organization_id)+ url = _build_url(host, f"/orgs/{org_id}", {"version": SNYK_REST_VERSION})+ payload = _fetch_page(session, url, logger)+ item = payload.get("data") if isinstance(payload, dict) else None+ if isinstance(item, dict):+ yield [_flatten_item(item)]+++def _iter_top_level(+ session: requests.Session,+ host: str,+ config: SnykEndpointConfig,+ params: dict[str, Any],+ logger: FilteringBoundLogger,+ manager: ResumableSourceManager[SnykResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ """Paginate a top-level collection (organizations) with resume support."""+ resume = manager.load_state() if manager.can_resume() else None+ if resume is not None and resume.next_url:+ if not _is_same_host(resume.next_url, host):+ raise ValueError(f"Snyk resume state contains an unexpected URL: {resume.next_url!r}")+ url = resume.next_url+ logger.debug(f"Snyk: resuming {config.name} from URL: {url}")+ else:+ url = _build_url(host, config.path, params)++ while True:+ items, next_url = _fetch_list_page(session, url, host, logger)+ if items:+ yield [_flatten_item(item) for item in items]+ if not next_url:+ break+ # Save AFTER yielding the batch — a crash before the save re-yields this page (merge+ # dedupes on primary key) instead of skipping it.+ manager.save_state(SnykResumeConfig(next_url=next_url))+ url = next_url+++def _iter_fan_out(+ session: requests.Session,+ host: str,+ config: SnykEndpointConfig,+ params: dict[str, Any],+ organization_id: Optional[str],+ logger: FilteringBoundLogger,+ manager: ResumableSourceManager[SnykResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ """Walk every org and emit each org's rows, injecting ``organization_id`` into each row."""+ org_ids = _resolve_org_ids(session, host, organization_id, logger)++ # Resolve the saved org bookmark to the slice of orgs still to process. ``_resolve_org_ids``+ # returns a sorted list, so this positional slice is stable even if the API reordered the orgs+ # between the crash and the retry. If the bookmarked org no longer exists (removed between runs),+ # start over — merge dedupes the re-pulled rows.+ resume = manager.load_state() if manager.can_resume() else None+ start_index = 0+ resume_url: str | None = None+ if resume is not None and resume.org_id is not None and resume.org_id in org_ids:+ if not _is_same_host(resume.next_url, host):+ raise ValueError(f"Snyk resume state contains an unexpected URL: {resume.next_url!r}")+ start_index = org_ids.index(resume.org_id)+ resume_url = resume.next_url+ logger.debug(f"Snyk: resuming {config.name} fan-out from org={resume.org_id}, url={resume_url}")++ for index in range(start_index, len(org_ids)):+ org_id = org_ids[index]+ url = resume_url or _build_url(host, config.path.format(org_id=org_id), params)+ resume_url = None # only the resumed-into org uses the saved URL; the rest start fresh++ while True:+ items, next_url = _fetch_list_page(session, url, host, logger)+ if items:+ yield [{**_flatten_item(item), "organization_id": org_id} for item in items]+ if not next_url:+ break+ manager.save_state(SnykResumeConfig(next_url=next_url, org_id=org_id))+ url = next_url+++def get_rows(+ region: Optional[str],+ api_token: str,+ organization_id: Optional[str],+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[SnykResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+ incremental_field: Optional[str] = None,+) -> Iterator[list[dict[str, Any]]]:+ config = SNYK_ENDPOINTS[endpoint]+ host = base_url(region)+ # One tracked session reused across every page (and every fan-out org) so urllib3 keeps the+ # connection alive. Redact the token: it rides in the ``Authorization: token …`` header under+ # Snyk's custom scheme, which the tracked transport's built-in scrubber doesn't recognise.+ session = make_tracked_session(headers=_get_headers(api_token), redact_values=(api_token,))++ params = _initial_params(config, incremental_field, should_use_incremental_field, db_incremental_field_last_value)++ if config.scope == SnykScope.ORGANIZATION:+ if organization_id and organization_id.strip():+ yield from _iter_single_org(session, host, organization_id, logger)+ else:+ yield from _iter_top_level(session, host, config, params, logger, resumable_source_manager)+ else:+ yield from _iter_fan_out(session, host, config, params, organization_id, logger, resumable_source_manager)+++def snyk_source(+ region: Optional[str],+ api_token: str,+ organization_id: Optional[str],+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[SnykResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+ incremental_field: Optional[str] = None,+) -> SourceResponse:+ endpoint_config = SNYK_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ region=region,+ api_token=api_token,+ organization_id=organization_id,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=db_incremental_field_last_value,+ incremental_field=incremental_field,+ ),+ primary_keys=endpoint_config.primary_keys,+ # Snyk documents no sort param on these endpoints and the response order is undefined —+ # and the multi-org fan-out breaks any global ordering anyway. "desc" defers the watermark+ # write to sync completion (max value seen), which is the safe semantic for unordered data;+ # "asc" would checkpoint a max-so-far watermark mid-sync and could skip rows on retry.+ sort_mode="desc",+ partition_count=1,+ partition_size=1,+ partition_mode="datetime" if endpoint_config.partition_key else None,+ partition_format="month" if endpoint_config.partition_key else None,+ partition_keys=[endpoint_config.partition_key] if endpoint_config.partition_key else None,+ )+++def validate_credentials(+ region: Optional[str], api_token: str, organization_id: Optional[str] = None+) -> tuple[bool, str | None]:+ """Confirm the token is genuine with a single cheap probe.++ ``/rest/self`` validates the token alone; when a single org is configured, probing that org+ also confirms the token can reach it on the selected region.+ """+ host = base_url(region)+ if organization_id and organization_id.strip():+ try:+ org_id = _validated_org_id(organization_id)+ except ValueError:+ return False, "Snyk organization ID is invalid — copy it from your organization settings."+ url = _build_url(host, f"/orgs/{org_id}", {"version": SNYK_REST_VERSION})+ else:+ url = _build_url(host, "/self", {"version": SNYK_REST_VERSION})++ try:+ session = make_tracked_session(redact_values=(api_token,))+ response = session.get(url, headers=_get_headers(api_token), timeout=10)+ except requests.exceptions.RequestException as e:+ return False, str(e)++ if response.status_code == 200:+ return True, None+ if response.status_code == 401:+ return False, "Invalid Snyk API token. Check the token and the selected region, then try again."+ if response.status_code in (403, 404):+ return False, "Your Snyk token can't access this organization. Check the organization ID and region."+ return False, f"Snyk API error: {response.status_code}"diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/snyk/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/snyk/source.pyindex 45811e8d8571..2f077b55877a 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/snyk/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/snyk/source.py@@ -1,30 +1,166 @@-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.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 SnykSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.snyk.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+ SNYK_ENDPOINTS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.snyk.snyk import (+ SnykResumeConfig,+ snyk_source,+ validate_credentials as validate_snyk_credentials,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class SnykSource(SimpleSource[SnykSourceConfig]):+class SnykSource(ResumableSource[SnykSourceConfig, SnykResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.SNYK+ @property+ def connection_host_fields(self) -> list[str]:+ # The API token is sent to the host derived from `region`, so changing the region must+ # re-require the secret rather than reusing it against a different host. `organization_id`+ # selects which Snyk tenant the token reads, so retargeting it must also force re-entry —+ # otherwise an editor could point the preserved token at another organization it can access.+ return ["region", "organization_id"]+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.SNYK,category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,label="Snyk",+ releaseStatus=ReleaseStatus.ALPHA,+ caption="""Connect your Snyk account to sync organizations, projects, targets, and vulnerability issues into the PostHog Data warehouse.++Generate an API token from your [Snyk account settings](https://app.snyk.io/account) (or use a service account token from your organization or group settings). The token is sent as `Authorization: token <token>` and can read every organization it has access to.++Pick the region your Snyk account is hosted on — Snyk's regional stacks are independent and a token only works on its own region.""",iconPath="/static/services/snyk.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/snyk",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_token",+ label="API token",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="Snyk API token",+ secret=True,+ ),+ SourceFieldSelectConfig(+ name="region",+ label="Region",+ required=True,+ defaultValue="us",+ options=[+ SourceFieldSelectConfigOption(label="US (api.snyk.io)", value="us"),+ SourceFieldSelectConfigOption(label="EU (api.eu.snyk.io)", value="eu"),+ SourceFieldSelectConfigOption(label="AU (api.au.snyk.io)", value="au"),+ ],+ ),+ SourceFieldInputConfig(+ name="organization_id",+ label="Organization ID (optional)",+ type=SourceFieldInputConfigType.TEXT,+ required=False,+ placeholder="Leave blank to sync every organization the token can access",+ secret=False,+ ),+ ],+ ),+ )++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ # 401/403 surface as a requests HTTPError when `_fetch_page` calls `raise_for_status()`.+ # No amount of retrying fixes a bad or under-permissioned token, so stop the sync.+ return {+ "401 Client Error: Unauthorized for url": "Your Snyk API token is invalid or has been revoked. Generate a new token in your Snyk account settings, then reconnect.",+ "403 Client Error: Forbidden for url": "Your Snyk API token does not have access to this data. Check the token's role and organization access, then reconnect.",+ }++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.snyk.canonical_descriptions import ( # noqa: PLC0415+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_schemas(+ self,+ config: SnykSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ schemas = [+ SourceSchema(+ name=endpoint,+ supports_incremental=SNYK_ENDPOINTS[endpoint].supports_incremental,+ supports_append=SNYK_ENDPOINTS[endpoint].supports_incremental,+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),+ )+ for endpoint in list(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: SnykSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ return validate_snyk_credentials(config.region, config.api_token, config.organization_id)++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[SnykResumeConfig]:+ return ResumableSourceManager[SnykResumeConfig](inputs, SnykResumeConfig)++ def source_for_pipeline(+ self,+ config: SnykSourceConfig,+ resumable_source_manager: ResumableSourceManager[SnykResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return snyk_source(+ region=config.region,+ api_token=config.api_token,+ organization_id=config.organization_id,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=inputs.should_use_incremental_field,+ db_incremental_field_last_value=inputs.db_incremental_field_last_value+ if inputs.should_use_incremental_field+ else None,+ incremental_field=inputs.incremental_field,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/snyk/tests/test_snyk.py b/products/warehouse_sources/backend/temporal/data_imports/sources/snyk/tests/test_snyk.pynew file mode 100644index 000000000000..86b81f3d8cdb--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/snyk/tests/test_snyk.py@@ -0,0 +1,445 @@+import json+from collections.abc import Mapping+from datetime import UTC, datetime+from typing import Any++import pytest+from unittest.mock import MagicMock++import requests+from parameterized import parameterized+from tenacity import stop_after_attempt, wait_none++from products.warehouse_sources.backend.temporal.data_imports.sources.snyk import snyk+from products.warehouse_sources.backend.temporal.data_imports.sources.snyk.snyk import (+ SNYK_REST_VERSION,+ SnykResumeConfig,+ SnykRetryableError,+ _flatten_item,+ _next_page_url,+ get_rows,+ validate_credentials,+)++HOST = "https://api.snyk.io"+++class _FakeResumableManager:+ def __init__(self, state: SnykResumeConfig | None = None) -> None:+ self._state = state+ self.saved: list[SnykResumeConfig] = []++ def can_resume(self) -> bool:+ return self._state is not None++ def load_state(self) -> SnykResumeConfig | None:+ return self._state++ def save_state(self, data: SnykResumeConfig) -> None:+ self.saved.append(data)+++def _make_response(status_code: int, body: Any = None) -> requests.Response:+ response = requests.Response()+ response.status_code = status_code+ if body is not None:+ response._content = json.dumps(body).encode()+ return response+++class _FakeSession:+ """Returns queued responses in order, recording the URLs requested."""++ def __init__(self, responses: list[requests.Response]) -> None:+ self._responses = list(responses)+ self.requested_urls: list[str] = []++ def get(self, url: str, headers: dict[str, str] | None = None, timeout: int | None = None) -> requests.Response:+ self.requested_urls.append(url)+ return self._responses.pop(0)+++def _collect(+ endpoint: str,+ pages: Mapping[str, tuple[list[dict], str | None]],+ manager: _FakeResumableManager,+ monkeypatch: Any,+ organization_id: str | None = None,+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+ incremental_field: str | None = None,+) -> list[dict]:+ monkeypatch.setattr(snyk, "make_tracked_session", lambda *args, **kwargs: MagicMock())++ def fake_fetch_list_page(session: Any, url: str, host: str, logger: Any) -> tuple[list[dict], str | None]:+ if url not in pages:+ raise AssertionError(f"unexpected URL requested: {url}")+ return pages[url]++ monkeypatch.setattr(snyk, "_fetch_list_page", fake_fetch_list_page)++ rows: list[dict] = []+ for batch in get_rows(+ region="us",+ api_token="tok",+ organization_id=organization_id,+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=manager, # type: ignore[arg-type]+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=db_incremental_field_last_value,+ incremental_field=incremental_field,+ ):+ rows.extend(batch)+ return rows+++ORGS_URL = f"{HOST}/rest/orgs?version={SNYK_REST_VERSION}&limit=100"+++def _issues_url(org_id: str, extra: str = "") -> str:+ return f"{HOST}/rest/orgs/{org_id}/issues?version={SNYK_REST_VERSION}&limit=100{extra}"+++class TestNextPageUrl:+ @parameterized.expand(+ [+ (+ "absolute_same_host",+ {"links": {"next": f"{HOST}/rest/orgs?starting_after=abc"}},+ f"{HOST}/rest/orgs?starting_after=abc",+ ),+ ("absolute_other_host_rejected", {"links": {"next": "https://evil.example.com/rest/orgs"}}, None),+ ("http_scheme_rejected", {"links": {"next": "http://api.snyk.io/rest/orgs?x=1"}}, None),+ (+ "relative_with_rest_prefix",+ {"links": {"next": "/rest/orgs?starting_after=abc"}},+ f"{HOST}/rest/orgs?starting_after=abc",+ ),+ (+ "relative_without_rest_prefix",+ {"links": {"next": "/orgs/o1/issues?starting_after=abc"}},+ f"{HOST}/rest/orgs/o1/issues?starting_after=abc",+ ),+ (+ "relative_without_leading_slash",+ {"links": {"next": "orgs?starting_after=abc"}},+ f"{HOST}/rest/orgs?starting_after=abc",+ ),+ (+ "href_object_form",+ {"links": {"next": {"href": "/rest/orgs?starting_after=abc"}}},+ f"{HOST}/rest/orgs?starting_after=abc",+ ),+ ("no_next", {"links": {"prev": "/rest/orgs"}}, None),+ ("empty_next", {"links": {"next": ""}}, None),+ ("no_links", {"data": []}, None),+ ("non_dict_payload", [], None),+ ]+ )+ def test_next_page_url(self, _name: str, payload: Any, expected: str | None) -> None:+ assert _next_page_url(HOST, payload) == expected+++class TestFlattenItem:+ def test_lifts_attributes_keeping_id_and_type(self) -> None:+ item = {+ "id": "i1",+ "type": "issue",+ "attributes": {"title": "XSS", "created_at": "2025-01-01T00:00:00Z"},+ "relationships": {"organization": {"data": {"id": "o1"}}},+ }+ flattened = _flatten_item(item)+ assert flattened["id"] == "i1"+ assert flattened["type"] == "issue"+ assert flattened["title"] == "XSS"+ assert flattened["created_at"] == "2025-01-01T00:00:00Z"+ assert "attributes" not in flattened+ assert flattened["relationships"] == {"organization": {"data": {"id": "o1"}}}++ def test_root_keys_win_over_attribute_collisions(self) -> None:+ # `id`/`type` at the root are the JSON:API identifiers; an attribute with the same name+ # must not clobber them or merge primary keys break.+ item = {"id": "i1", "attributes": {"id": "other", "title": "t"}}+ assert _flatten_item(item)["id"] == "i1"+++class TestFetchPage:+ @parameterized.expand([("rate_limited", 429), ("server_error", 500), ("bad_gateway", 503)])+ def test_retryable_statuses_raise_retryable_error(self, _name: str, status_code: int) -> None:+ session = _FakeSession([_make_response(status_code) for _ in range(5)])+ fast_fetch = snyk._fetch_page.retry_with(wait=wait_none(), stop=stop_after_attempt(3)) # type: ignore[attr-defined]+ with pytest.raises(SnykRetryableError):+ fast_fetch(session, f"{HOST}/rest/orgs", MagicMock())++ def test_client_error_raises_http_error_without_retry(self) -> None:+ session = _FakeSession([_make_response(401, body={"errors": [{"status": "401"}]})])+ with pytest.raises(requests.HTTPError):+ snyk._fetch_page(session, f"{HOST}/rest/orgs", MagicMock()) # type: ignore[arg-type]+ assert len(session.requested_urls) == 1+++class TestTopLevelOrganizations:+ def test_paginates_and_flattens(self, monkeypatch: Any) -> None:+ page2 = f"{HOST}/rest/orgs?version={SNYK_REST_VERSION}&limit=100&starting_after=cursor"+ pages = {+ ORGS_URL: ([{"id": "o1", "type": "org", "attributes": {"name": "Org 1"}}], page2),+ page2: ([{"id": "o2", "type": "org", "attributes": {"name": "Org 2"}}], None),+ }+ rows = _collect("organizations", pages, _FakeResumableManager(), monkeypatch)+ assert rows == [+ {"id": "o1", "type": "org", "name": "Org 1"},+ {"id": "o2", "type": "org", "name": "Org 2"},+ ]++ def test_saves_state_after_yield_and_resumes_from_it(self, monkeypatch: Any) -> None:+ page2 = f"{HOST}/rest/orgs?version={SNYK_REST_VERSION}&limit=100&starting_after=cursor"+ pages = {+ ORGS_URL: ([{"id": "o1"}], page2),+ page2: ([{"id": "o2"}], None),+ }+ manager = _FakeResumableManager()+ _collect("organizations", pages, manager, monkeypatch)+ assert [s.next_url for s in manager.saved] == [page2]++ resumed = _FakeResumableManager(SnykResumeConfig(next_url=page2))+ rows = _collect("organizations", {page2: ([{"id": "o2"}], None)}, resumed, monkeypatch)+ assert rows == [{"id": "o2"}]++ def test_resume_state_on_wrong_host_is_rejected(self, monkeypatch: Any) -> None:+ # The resume URL is fetched with the auth header attached, so tampered Redis state must+ # not be able to redirect the request off the Snyk host.+ manager = _FakeResumableManager(SnykResumeConfig(next_url="https://evil.example.com/rest/orgs"))+ with pytest.raises(ValueError):+ _collect("organizations", {}, manager, monkeypatch)++ def test_configured_org_fetches_single_org_directly(self, monkeypatch: Any) -> None:+ # A single-org connection must not enumerate every org the token can reach: it fetches+ # /orgs/{org_id} directly and emits only that org. Hitting the /orgs list would raise.+ monkeypatch.setattr(snyk, "make_tracked_session", lambda *args, **kwargs: MagicMock())+ monkeypatch.setattr(+ snyk,+ "_fetch_list_page",+ lambda *a, **k: (_ for _ in ()).throw(AssertionError("must not enumerate orgs")),+ )+ requested: list[str] = []++ def fake_fetch_page(session: Any, url: str, logger: Any) -> Any:+ requested.append(url)+ return {"data": {"id": "o9", "type": "org", "attributes": {"name": "Org 9"}}}++ monkeypatch.setattr(snyk, "_fetch_page", fake_fetch_page)++ rows: list[dict] = []+ for batch in get_rows(+ region="us",+ api_token="tok",+ organization_id="o9",+ endpoint="organizations",+ logger=MagicMock(),+ resumable_source_manager=_FakeResumableManager(), # type: ignore[arg-type]+ ):+ rows.extend(batch)++ assert rows == [{"id": "o9", "type": "org", "name": "Org 9"}]+ assert requested == [f"{HOST}/rest/orgs/o9?version={SNYK_REST_VERSION}"]++ def test_configured_org_id_is_validated_before_the_request(self, monkeypatch: Any) -> None:+ # The org id is interpolated into the URL path, so a path-altering value must be rejected+ # before any request is made — even on the single-org organizations path.+ monkeypatch.setattr(snyk, "make_tracked_session", lambda *args, **kwargs: MagicMock())+ with pytest.raises(ValueError):+ _collect("organizations", {}, _FakeResumableManager(), monkeypatch, organization_id="../self")+++class TestPerOrgFanOut:+ def _two_org_pages(self) -> dict[str, tuple[list[dict], str | None]]:+ return {+ ORGS_URL: ([{"id": "o1"}, {"id": "o2"}], None),+ _issues_url("o1"): ([{"id": "i1", "attributes": {"title": "a"}}], None),+ _issues_url("o2"): ([{"id": "i2", "attributes": {"title": "b"}}], None),+ }++ def test_walks_every_org_and_injects_organization_id(self, monkeypatch: Any) -> None:+ rows = _collect("issues", self._two_org_pages(), _FakeResumableManager(), monkeypatch)+ assert rows == [+ {"id": "i1", "title": "a", "organization_id": "o1"},+ {"id": "i2", "title": "b", "organization_id": "o2"},+ ]++ def test_configured_org_skips_enumeration(self, monkeypatch: Any) -> None:+ # Only the single org's issues URL is served; hitting /orgs would raise in the fake.+ pages = {_issues_url("o9"): ([{"id": "i9"}], None)}+ rows = _collect("issues", pages, _FakeResumableManager(), monkeypatch, organization_id="o9")+ assert rows == [{"id": "i9", "organization_id": "o9"}]++ def test_invalid_configured_org_id_is_rejected(self, monkeypatch: Any) -> None:+ with pytest.raises(ValueError):+ _collect("issues", {}, _FakeResumableManager(), monkeypatch, organization_id="../self")++ def test_saves_org_bookmark_with_next_url(self, monkeypatch: Any) -> None:+ o1_page2 = f"{HOST}/rest/orgs/o1/issues?version={SNYK_REST_VERSION}&starting_after=cursor"+ pages = {+ ORGS_URL: ([{"id": "o1"}], None),+ _issues_url("o1"): ([{"id": "i1"}], o1_page2),+ o1_page2: ([{"id": "i1b"}], None),+ }+ manager = _FakeResumableManager()+ _collect("issues", pages, manager, monkeypatch)+ assert [(s.org_id, s.next_url) for s in manager.saved] == [("o1", o1_page2)]++ def test_resume_skips_already_processed_orgs(self, monkeypatch: Any) -> None:+ # Bookmarked mid-o2: o1 must not be re-fetched (its URL is absent from `pages`, so a fetch+ # would raise); o2 continues from the saved page.+ o2_page2 = f"{HOST}/rest/orgs/o2/issues?version={SNYK_REST_VERSION}&starting_after=cursor"+ pages = {+ ORGS_URL: ([{"id": "o1"}, {"id": "o2"}], None),+ o2_page2: ([{"id": "i2b"}], None),+ }+ manager = _FakeResumableManager(SnykResumeConfig(next_url=o2_page2, org_id="o2"))+ rows = _collect("issues", pages, manager, monkeypatch)+ assert rows == [{"id": "i2b", "organization_id": "o2"}]++ def test_resume_from_removed_org_restarts_from_first(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager(SnykResumeConfig(next_url=_issues_url("GONE"), org_id="GONE"))+ rows = _collect("issues", self._two_org_pages(), manager, monkeypatch)+ assert [row["id"] for row in rows] == ["i1", "i2"]++ def test_resume_survives_reordered_org_list(self, monkeypatch: Any) -> None:+ # /orgs has no sort param, so the API may return orgs in a different order after a crash.+ # Sorting keeps the positional resume stable: o3 (not yet processed) must not be skipped+ # just because the raw response now lists it before the bookmarked o2, and the already-done+ # o1 must not be re-fetched (its URL is absent, so a fetch would raise).+ o2_page2 = f"{HOST}/rest/orgs/o2/issues?version={SNYK_REST_VERSION}&starting_after=cursor"+ pages = {+ ORGS_URL: ([{"id": "o3"}, {"id": "o2"}, {"id": "o1"}], None),+ o2_page2: ([{"id": "i2b"}], None),+ _issues_url("o3"): ([{"id": "i3"}], None),+ }+ manager = _FakeResumableManager(SnykResumeConfig(next_url=o2_page2, org_id="o2"))+ rows = _collect("issues", pages, manager, monkeypatch)+ assert rows == [+ {"id": "i2b", "organization_id": "o2"},+ {"id": "i3", "organization_id": "o3"},+ ]+++class TestIncrementalFilters:+ @parameterized.expand(+ [+ ("default_field", None, "updated_after"),+ ("explicit_updated_at", "updated_at", "updated_after"),+ ("created_at_maps_to_created_after", "created_at", "created_after"),+ ]+ )+ def test_watermark_becomes_server_side_filter(self, _name: str, incremental_field: str | None, param: str) -> None:+ url = _issues_url("o1", extra=f"&{param}=2026-01-01T00%3A00%3A00Z")+ pages = {url: ([{"id": "i1"}], None)}+ with pytest.MonkeyPatch.context() as mp:+ rows = _collect(+ "issues",+ pages,+ _FakeResumableManager(),+ mp,+ organization_id="o1",+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 1, 1, tzinfo=UTC),+ incremental_field=incremental_field,+ )+ assert rows == [{"id": "i1", "organization_id": "o1"}]++ def test_first_sync_has_no_filter(self, monkeypatch: Any) -> None:+ pages = {_issues_url("o1"): ([{"id": "i1"}], None)}+ rows = _collect(+ "issues",+ pages,+ _FakeResumableManager(),+ monkeypatch,+ organization_id="o1",+ should_use_incremental_field=True,+ db_incremental_field_last_value=None,+ )+ assert rows == [{"id": "i1", "organization_id": "o1"}]+++class TestValidateCredentials:+ @parameterized.expand(+ [+ ("ok", 200, True),+ ("unauthorized", 401, False),+ ("forbidden", 403, False),+ ("server_error", 500, False),+ ]+ )+ def test_status_mapping(self, _name: str, status_code: int, expected_ok: bool) -> None:+ session = _FakeSession([_make_response(status_code, body={})])+ with pytest.MonkeyPatch.context() as mp:+ mp.setattr(snyk, "make_tracked_session", lambda *args, **kwargs: session)+ ok, _error = validate_credentials("us", "tok")+ assert ok is expected_ok+ # The probe must carry the mandatory dated version param or Snyk rejects the call.+ assert session.requested_urls == [f"{HOST}/rest/self?version={SNYK_REST_VERSION}"]++ def test_configured_org_is_probed_on_the_selected_region(self) -> None:+ session = _FakeSession([_make_response(200, body={})])+ with pytest.MonkeyPatch.context() as mp:+ mp.setattr(snyk, "make_tracked_session", lambda *args, **kwargs: session)+ ok, _error = validate_credentials("eu", "tok", "org-uuid-1")+ assert ok is True+ assert session.requested_urls == [f"https://api.eu.snyk.io/rest/orgs/org-uuid-1?version={SNYK_REST_VERSION}"]++ def test_invalid_org_id_fails_without_a_request(self) -> None:+ with pytest.MonkeyPatch.context() as mp:+ mp.setattr(snyk, "make_tracked_session", lambda *args, **kwargs: _FakeSession([]))+ ok, error = validate_credentials("us", "tok", "../../self")+ assert ok is False+ assert error is not None++ def test_request_exception_is_failure(self) -> None:+ class _BoomSession:+ def get(self, *args: Any, **kwargs: Any) -> requests.Response:+ raise requests.exceptions.ConnectionError("boom")++ with pytest.MonkeyPatch.context() as mp:+ mp.setattr(snyk, "make_tracked_session", lambda *args, **kwargs: _BoomSession())+ ok, error = validate_credentials("us", "tok")+ assert ok is False+ assert error is not None+++class TestTokenRedaction:+ """The token rides in a custom `Authorization: token …` scheme the tracked transport's+ scrubber doesn't recognise, so every session it builds must redact the token by value."""++ def test_validate_credentials_redacts_token(self) -> None:+ captured: dict[str, Any] = {}++ def fake_make_session(*args: Any, **kwargs: Any) -> Any:+ captured.update(kwargs)+ return _FakeSession([_make_response(200, body={})])++ with pytest.MonkeyPatch.context() as mp:+ mp.setattr(snyk, "make_tracked_session", fake_make_session)+ validate_credentials("us", "super-secret-token")+ assert captured.get("redact_values") == ("super-secret-token",)++ def test_get_rows_redacts_token(self, monkeypatch: Any) -> None:+ captured: dict[str, Any] = {}++ def fake_make_session(*args: Any, **kwargs: Any) -> Any:+ captured.update(kwargs)+ return MagicMock()++ monkeypatch.setattr(snyk, "make_tracked_session", fake_make_session)+ monkeypatch.setattr(snyk, "_fetch_list_page", lambda *args, **kwargs: ([], None))+ list(+ get_rows(+ region="us",+ api_token="super-secret-token",+ organization_id=None,+ endpoint="organizations",+ logger=MagicMock(),+ resumable_source_manager=_FakeResumableManager(), # type: ignore[arg-type]+ )+ )+ assert captured.get("redact_values") == ("super-secret-token",)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/snyk/tests/test_snyk_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/snyk/tests/test_snyk_source.pynew file mode 100644index 000000000000..22bdd9776e93--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/snyk/tests/test_snyk_source.py@@ -0,0 +1,237 @@+from typing import Any, Optional++from unittest import mock+from unittest.mock import MagicMock++from parameterized import parameterized++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldSelectConfig++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 SnykSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.snyk.settings import (+ ENDPOINTS,+ SNYK_ENDPOINTS,+ SnykScope,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.snyk.snyk import SnykResumeConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.snyk.source import SnykSource+from products.warehouse_sources.backend.types import ExternalDataSourceType+++def _source_inputs(+ schema_name: str = "issues",+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+ incremental_field: Optional[str] = None,+) -> SourceInputs:+ return SourceInputs(+ schema_name=schema_name,+ schema_id="schema-1",+ source_id="source-1",+ team_id=1,+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=db_incremental_field_last_value,+ db_incremental_field_earliest_value=None,+ incremental_field=incremental_field,+ incremental_field_type=None,+ job_id="job-1",+ logger=MagicMock(),+ reset_pipeline=False,+ )+++class TestSnykSource:+ def setup_method(self) -> None:+ self.source = SnykSource()+ self.team_id = 1++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.SNYK++ def test_credential_retargeting_fields_force_token_reentry(self) -> None:+ # `region` picks the host the token is sent to and `organization_id` picks the tenant it+ # reads; dropping either from this list would let an editor retarget the preserved token+ # without re-entering it.+ assert self.source.connection_host_fields == ["region", "organization_id"]++ def test_source_config_basics(self) -> None:+ config = self.source.get_source_config+ assert config.label == "Snyk"+ assert config.unreleasedSource is None+ assert config.releaseStatus == ReleaseStatus.ALPHA+ field_names = [f.name for f in config.fields]+ assert field_names == ["api_token", "region", "organization_id"]++ token_field = config.fields[0]+ assert isinstance(token_field, SourceFieldInputConfig)+ assert token_field.required is True+ assert token_field.secret is True++ region_field = config.fields[1]+ assert isinstance(region_field, SourceFieldSelectConfig)+ assert region_field.defaultValue == "us"+ assert [o.value for o in region_field.options] == ["us", "eu", "au"]++ org_field = config.fields[2]+ assert isinstance(org_field, SourceFieldInputConfig)+ assert org_field.required is False++ def test_generated_config_parses_fields(self) -> None:+ # Guards the generated-config round trip: form fields must map to config attributes.+ config = SnykSourceConfig.from_dict({"api_token": "tok_123"})+ assert config.api_token == "tok_123"+ assert config.region == "us"+ assert config.organization_id is None++ def test_get_schemas_lists_every_endpoint(self) -> None:+ schemas = self.source.get_schemas(MagicMock(), team_id=self.team_id)+ assert {s.name for s in schemas} == set(ENDPOINTS)++ @parameterized.expand(+ [+ ("organizations", False),+ ("projects", False),+ ("targets", False),+ ("issues", True),+ ]+ )+ def test_only_issues_advertises_incremental(self, endpoint: str, expected: bool) -> None:+ # Issues is the only endpoint with a documented server-side timestamp filter+ # (updated_after / created_after); the others must stay full refresh.+ schemas = {s.name: s for s in self.source.get_schemas(MagicMock(), team_id=self.team_id)}+ assert schemas[endpoint].supports_incremental is expected+ assert schemas[endpoint].supports_append is expected++ def test_get_schemas_filters_by_names(self) -> None:+ schemas = self.source.get_schemas(MagicMock(), team_id=self.team_id, names=["issues", "projects"])+ assert {s.name for s in schemas} == {"issues", "projects"}++ def test_publishes_table_catalog_for_public_docs(self) -> None:+ # `lists_tables_without_credentials` gates whether the static endpoint catalog reaches the+ # posthog.com "Supported tables" section; dropping it would silently empty that section.+ tables = self.source.get_documented_tables()+ names = {t["name"] for t in tables}+ assert set(ENDPOINTS).issubset(names)+ issues = next(t for t in tables if t["name"] == "issues")+ assert "Incremental" in issues["sync_methods"]+ assert issues["description"]++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.snyk.source.validate_snyk_credentials"+ )+ def test_validate_credentials_plumbs_config(self, mock_validate: MagicMock) -> None:+ mock_validate.return_value = (True, None)+ config = SnykSourceConfig.from_dict({"api_token": "tok", "region": "eu", "organization_id": "org-1"})+ ok, error = self.source.validate_credentials(config, self.team_id)+ assert ok is True+ assert error is None+ mock_validate.assert_called_once_with("eu", "tok", "org-1")++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.snyk.source.validate_snyk_credentials"+ )+ def test_validate_credentials_failure(self, mock_validate: MagicMock) -> None:+ mock_validate.return_value = (False, "Invalid Snyk API token")+ ok, error = self.source.validate_credentials(SnykSourceConfig.from_dict({"api_token": "bad"}), self.team_id)+ assert ok is False+ assert error == "Invalid Snyk API token"++ def test_get_resumable_source_manager_binds_resume_config(self) -> None:+ manager = self.source.get_resumable_source_manager(_source_inputs())+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is SnykResumeConfig++ @parameterized.expand(+ [+ ("organizations", ["id"]),+ ("projects", ["id", "organization_id"]),+ ("targets", ["id", "organization_id"]),+ ("issues", ["id", "organization_id"]),+ ]+ )+ def test_source_response_primary_keys(self, endpoint: str, expected_keys: list[str]) -> None:+ manager = self.source.get_resumable_source_manager(_source_inputs(endpoint))+ response = self.source.source_for_pipeline(+ SnykSourceConfig.from_dict({"api_token": "tok"}), manager, _source_inputs(endpoint)+ )+ assert response.name == endpoint+ assert response.primary_keys == expected_keys++ def test_source_response_defers_watermark_to_completion(self) -> None:+ # Snyk offers no sort param and fan-out breaks global ordering, so the watermark must only+ # advance at sync completion ("desc" semantics) — "asc" would checkpoint mid-sync and skip+ # rows on retry.+ manager = self.source.get_resumable_source_manager(_source_inputs("issues"))+ response = self.source.source_for_pipeline(+ SnykSourceConfig.from_dict({"api_token": "tok"}), manager, _source_inputs("issues")+ )+ assert response.sort_mode == "desc"++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.snyk.source.snyk_source")+ def test_incremental_value_only_passed_when_enabled(self, mock_snyk_source: MagicMock) -> None:+ config = SnykSourceConfig.from_dict({"api_token": "tok"})+ manager = MagicMock()+ inputs = _source_inputs(+ "issues",+ should_use_incremental_field=False,+ db_incremental_field_last_value="2026-01-01",+ incremental_field="updated_at",+ )+ self.source.source_for_pipeline(config, manager, inputs)+ disabled_kwargs = mock_snyk_source.call_args.kwargs+ assert disabled_kwargs["db_incremental_field_last_value"] is None++ inputs = _source_inputs(+ "issues",+ should_use_incremental_field=True,+ db_incremental_field_last_value="2026-01-01",+ incremental_field="updated_at",+ )+ self.source.source_for_pipeline(config, manager, inputs)+ enabled_kwargs = mock_snyk_source.call_args.kwargs+ assert enabled_kwargs["db_incremental_field_last_value"] == "2026-01-01"+ assert enabled_kwargs["incremental_field"] == "updated_at"++ def test_fan_out_children_carry_organization_id_in_primary_key(self) -> None:+ # Fan-out children aggregate rows from every org, so the injected org id must be part of+ # the primary key — otherwise per-org id collisions would seed duplicate rows that slow+ # every subsequent merge.+ for config in SNYK_ENDPOINTS.values():+ if config.scope is SnykScope.PER_ORG:+ assert "organization_id" in config.primary_keys, config.name++ @parameterized.expand(+ [+ (+ "unauthorized",+ "401 Client Error: Unauthorized for url: https://api.snyk.io/rest/orgs?version=2024-10-15",+ ),+ (+ "forbidden",+ "403 Client Error: Forbidden for url: https://api.eu.snyk.io/rest/orgs/o1/issues?version=2024-10-15",+ ),+ ]+ )+ def test_credential_errors_are_non_retryable(self, _name: str, observed_error: str) -> None:+ non_retryable = self.source.get_non_retryable_errors()+ assert any(key in observed_error for key in non_retryable)++ @parameterized.expand(+ [+ ("rate_limited", "429 Client Error: Too Many Requests for url: https://api.snyk.io/rest/orgs"),+ ("server_error", "500 Server Error: Internal Server Error for url: https://api.snyk.io/rest/orgs"),+ ("read_timeout", "HTTPSConnectionPool(host='api.snyk.io', port=443): Read timed out."),+ ]+ )+ def test_transient_errors_remain_retryable(self, _name: str, other_error: str) -> None:+ non_retryable = self.source.get_non_retryable_errors()+ assert not any(key in other_error for key in non_retryable)++ def test_canonical_description_keys_are_real_endpoints(self) -> None:+ # Canonical descriptions are keyed by schema name; a typo'd key would silently never apply.+ descriptions: dict[str, Any] = self.source.get_canonical_descriptions()+ assert set(descriptions) == set(ENDPOINTS)+ for entry in descriptions.values():+ assert entry["description"]