: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 semgrep import source (#71175)
Tom Owers958f583395f7
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 66b48f0bb1dc..7779f8648c4a 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -404,6 +404,7 @@ the row lists both.| scaleway | HTTP | requests | ✅ || secoda | HTTP | requests | ✅ || segment | HTTP | requests | ✅ |+| semgrep | HTTP | requests | ✅ || sendgrid | HTTP | requests | ✅ || sendowl | HTTP | requests | ✅ || sentry | HTTP | requests + `rest_source.RESTClient` | ✅ |@@ -867,7 +868,6 @@ doesn't conflict with concurrent PRs.- search_ads_360- secureframe- semaphore-- semgrep- sendpulse- senseforce- sentinelonediff --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 c944df3a8e36..f82a802dedec 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@@ -3716,7 +3716,7 @@ class SemaphoreSourceConfig(config.Config):@config.configclass SemgrepSourceConfig(config.Config):- pass+ api_token: str@config.configdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/semgrep/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/semgrep/canonical_descriptions.pynew file mode 100644index 000000000000..e3379961147f--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/semgrep/canonical_descriptions.py@@ -0,0 +1,118 @@+# Descriptions sourced from the official Semgrep API reference (https://semgrep.dev/api/v1/docs/)+# and its published OpenAPI spec (https://semgrep.dev/api/v1/public_v1.openapi.yaml).+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++_FAN_OUT_COLUMNS = {+ "deployment_id": "Unique numerical identifier of the Semgrep deployment this row belongs to (added by PostHog).",+ "deployment_slug": "Machine-readable slug of the Semgrep deployment this row belongs to (added by PostHog).",+}++_SHARED_FINDING_COLUMNS = {+ "id": "Unique ID of this finding.",+ "ref": "External reference to the source of this finding (e.g. a branch or pull request ref).",+ "first_seen_scan_id": "Unique ID of the Semgrep scan that first identified this finding.",+ "match_based_id": "ID calculated from the finding's file path, rule identifier and pattern, and index.",+ "syntactic_id": "ID calculated from the finding's file path, rule and matched code content.",+ "created_at": "The timestamp when this finding was created.",+ "relevant_since": "The timestamp when this finding was detected by Semgrep (the first time, or when reintroduced).",+ "rule_name": "Name of the rule that triggered the finding (deprecated in favor of rule.name).",+ "rule_message": "Rule message at the time of finding identification (deprecated in favor of rule.message).",+ "rule": "Details of the rule that triggered this finding (name, message, category, confidence, severity, CWE and OWASP names).",+ "location": "File path, line and column range where the finding was detected.",+ "line_of_code_url": "The source URL including file and line number.",+ "repository": "Repository where the finding was detected (name and URL).",+ "severity": "Severity of the finding, derived from the rule that triggered it: low, medium, high, or critical.",+ "confidence": "Confidence of the finding, derived from the rule that triggered it: low, medium, or high.",+ "categories": "The categories of the finding as classified by the associated rule metadata.",+ "state": "The finding's resolution state, managed only by changes detected at scan time: fixed, muted, or unresolved.",+ "state_updated_at": "When this finding's resolution state was last updated, as distinct from when it was triaged.",+ "status": "The finding's status as exposed in the Semgrep UI, combining `state` and `triage_state`: open, reviewing, fixing, fixed, ignored, or provisionally_ignored.",+ "triage_state": "The finding's triage state, managed by user triage actions: untriaged, reviewing, fixing, ignored, or provisionally_ignored.",+ "triage_reason": "Why the finding was triaged (e.g. acceptable_risk, false_positive, no_time).",+ "triage_comment": "Free-form comment left when the finding was triaged.",+ "triaged_at": "When the finding was last triaged.",+ "external_ticket": "Reference to the external ticket (e.g. Jira) linked to this finding, if any.",+ "review_comments": "External review comment information associated with the finding.",+ **_FAN_OUT_COLUMNS,+}++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "deployments": {+ "description": "The Semgrep deployment (organization) the API token can access, with its identifiers and links to related resources.",+ "docs_url": "https://semgrep.dev/api/v1/docs/#tag/DeploymentsService",+ "columns": {+ "id": "Unique numerical identifier of the deployment.",+ "name": "Human readable name of the deployment.",+ "slug": "Sanitized machine-readable name, used as the primary identifier through the web API.",+ "findings": "Link to the deployment's findings resource on the API.",+ },+ },+ "projects": {+ "description": "Projects (repositories) that have been scanned by or onboarded to Semgrep in the deployment. Archived repositories are not returned.",+ "docs_url": "https://semgrep.dev/api/v1/docs/#tag/ProjectsService",+ "columns": {+ "id": "Unique ID of this project.",+ "name": "Name of the project, e.g. `myorg/myrepo`.",+ "url": "URL of the project, if there is one.",+ "tags": "Tags associated to this project.",+ "created_at": "Time when this project was created.",+ "latest_scan_at": "Time of the latest Semgrep scan, if there is one.",+ "primary_branch": "The primary branch of the project, if known.",+ "default_branch": "The default branch in the source code manager.",+ "managed_scan_config": "Semgrep Managed Scans configuration for the project, if enabled.",+ **_FAN_OUT_COLUMNS,+ },+ },+ "sast_findings": {+ "description": "Code (SAST) findings Semgrep has identified in the deployment, deduplicated across refs/branches to match the counts in the Semgrep UI.",+ "docs_url": "https://semgrep.dev/api/v1/docs/#tag/FindingsService",+ "columns": {+ **_SHARED_FINDING_COLUMNS,+ "assistant": "Semgrep Assistant data (autofix, autotriage, component tags, guidance). Only present if Assistant is enabled.",+ "sourcing_policy": "Reference to the policy that generated this finding, with some basic information.",+ "click_to_fix_prs": "Pull requests created by Semgrep's autofix feature (Click to Fix) for this finding.",+ "click_to_fix_failures": "Failed PR creation attempts by Semgrep's autofix feature (Click to Fix) for this finding.",+ },+ },+ "sca_findings": {+ "description": "Supply chain (SCA) findings Semgrep has identified in the deployment's dependencies, deduplicated across refs/branches to match the counts in the Semgrep UI.",+ "docs_url": "https://semgrep.dev/api/v1/docs/#tag/FindingsService",+ "columns": {+ **_SHARED_FINDING_COLUMNS,+ "vulnerability_identifier": "CVE or GHSA identifier of the vulnerability the finding is based on.",+ "found_dependency": "The dependency (package, version, ecosystem, transitivity, lockfile) in which the finding was identified.",+ "usage": "How the vulnerable code is used, e.g. whether the vulnerable function is reachable from first-party code.",+ "reachability": "Reachability of the vulnerability: reachable, always_reachable, conditionally_reachable, unreachable, or unknown.",+ "reachable_condition": "Condition under which the vulnerability is reachable, if any.",+ "epss_score": "EPSS (Exploit Prediction Scoring System) score and percentile for the vulnerability.",+ "fix_recommendations": "Recommended dependency upgrades that fix the finding.",+ "is_malicious": "Whether the finding comes from a known-malicious dependency.",+ },+ },+ "secrets": {+ "description": "Secrets findings Semgrep has detected in the deployment's repositories, with validation state for supported services. Note: this endpoint returns camelCase field names.",+ "docs_url": "https://semgrep.dev/api/v1/docs/#tag/SecretsService",+ "columns": {+ "id": "ID of the finding.",+ "type": "Service type for the secrets finding (e.g. AWS, GitHub, GitLab).",+ "mode": "The behavior of the finding reporting: MODE_MONITOR, MODE_COMMENT, MODE_BLOCK, or MODE_DISABLED.",+ "status": "Status of the finding: FINDING_STATUS_OPEN, FINDING_STATUS_IGNORED, FINDING_STATUS_FIXED, FINDING_STATUS_REMOVED, or FINDING_STATUS_UNKNOWN.",+ "severity": "Severity of the finding: SEVERITY_LOW, SEVERITY_MEDIUM, SEVERITY_HIGH, or SEVERITY_CRITICAL.",+ "confidence": "Confidence of the finding: CONFIDENCE_LOW, CONFIDENCE_MEDIUM, or CONFIDENCE_HIGH.",+ "validationState": "Whether the secret was validated against its service: confirmed valid, confirmed invalid, validation error, or no validator.",+ "findingPath": "File path where the finding was detected.",+ "findingPathUrl": "URL to the file where the finding was detected.",+ "ref": "Branch where the finding was detected.",+ "refUrl": "URL to the branch where the finding was detected.",+ "repository": "Repository where the finding was detected (name, URL, SCM type, visibility).",+ "ruleHashId": "ID of the rule that triggered the finding.",+ "createdAt": "Creation timestamp.",+ "updatedAt": "Update timestamp.",+ "reviewComments": "External review comment information associated with the finding.",+ "externalTicket": "Reference to the external ticket linked to this finding, if any.",+ **_FAN_OUT_COLUMNS,+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/semgrep/docs/semgrep.mdx b/products/warehouse_sources/backend/temporal/data_imports/sources/semgrep/docs/semgrep.mdxnew file mode 100644index 000000000000..2ad2571616e4--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/semgrep/docs/semgrep.mdx@@ -0,0 +1,76 @@+---+title: Linking Semgrep as a source+sidebar: Docs+showTitle: true+availability: { free: full, selfServe: full, enterprise: full }+sourceId: Semgrep+---++<!--+This is the user-facing posthog.com source doc. It lives here only because no posthog.com+checkout was available when the source was implemented. Move it to+`posthog.com/contents/docs/cdp/sources/semgrep.mdx` and delete this copy, then run+`python manage.py audit_source_docs --docs-dir <posthog.com>/contents/docs/cdp/sources`.+-->++import SourceSetupIntro from '../_snippets/source-setup-intro.mdx'+import SyncModes from '../_snippets/sync-modes.mdx'+import TroubleshootingLink from '../_snippets/dw-troubleshooting-link.mdx'+import AlphaRelease from '../_snippets/alpha-release.mdx'++<AlphaRelease />++[Semgrep](https://semgrep.dev) is a static analysis and application security platform that scans your+repositories for code (SAST) findings, supply chain (SCA) vulnerabilities, and leaked secrets. Linking+it as a source syncs your deployment, projects, and findings history into the PostHog Data warehouse so+you can trend your vulnerability backlog, fix rates, and scan coverage alongside your product data.++## Prerequisites++To connect Semgrep, you need:++- A Semgrep AppSec Platform account on a **Team or Enterprise** plan (the web API isn't available on+ the free tier).+- An API token created under **Settings → Tokens** with the **Web API** scope.++## Adding a data source++<SourceSetupIntro />++1. Open [Semgrep AppSec Platform](https://semgrep.dev) and go to **Settings → Tokens**.+2. Create a new token and make sure the **Web API** scope is selected.+3. Copy the token and paste it into the **API token** field in PostHog.++The token is scoped to a single Semgrep deployment (organization); PostHog syncs the data of the+deployment the token can access.++## Sync modes++<SyncModes />++Semgrep's API has no server-side "updated since" filter (findings' statuses and triage states change+without moving their detection timestamp), so every table syncs as a **full refresh** — each sync+re-reads the resource and merges on the primary key. Findings are deduplicated across refs/branches+(`dedup=true`) so row counts match the Semgrep UI.++## Configuration++<SourceParameters />++## Supported tables++<SourceTables />++Rows in the `projects`, `sast_findings`, `sca_findings`, and `secrets` tables carry an extra+`deployment_id` and `deployment_slug` column added by PostHog so you can join them back to the+`deployments` table.++## Troubleshooting++- **"Invalid Semgrep API token"** when connecting: the token is wrong, has been revoked, or is missing+ the **Web API** scope. Create a new token under **Settings → Tokens** and re-enter it.+- **Sync fails with a 403**: your plan may not include API access to a synced resource (for example,+ the `secrets` table requires the Semgrep Secrets product). Deselect the affected table or upgrade+ your Semgrep plan.++<TroubleshootingLink />diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/semgrep/semgrep.py b/products/warehouse_sources/backend/temporal/data_imports/sources/semgrep/semgrep.pynew file mode 100644index 000000000000..0d23eab57364--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/semgrep/semgrep.py@@ -0,0 +1,240 @@+import dataclasses+from collections.abc import Iterator+from typing import Any+from urllib.parse import urlencode++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.semgrep.settings import (+ SEMGREP_ENDPOINTS,+ SemgrepEndpointConfig,+)++SEMGREP_BASE_URL = "https://semgrep.dev/api/v1"+REQUEST_TIMEOUT_SECONDS = 60+++class SemgrepRetryableError(Exception):+ pass+++class SemgrepResumeConfig:+ # Deployment being processed when the state was saved. Semgrep tokens currently scope to a+ # single deployment, but the fan-out iterates whatever /deployments returns, so the bookmark+ # is a stable deployment id rather than a positional index.+ deployment_id: str | None = None+ # Next zero-indexed page for page-numbered endpoints (projects, findings).+ page: int = 0+ # Next cursor for the cursor-paginated secrets endpoint.+ cursor: str | None = None+++def _get_headers(api_token: str) -> dict[str, str]:+ return {+ "Authorization": f"Bearer {api_token}",+ "Accept": "application/json",+ }+++def _make_session(api_token: str) -> requests.Session:+ # `redact_values` masks the bearer token in logged URLs and captured HTTP samples so a failed+ # or sampled request can never persist the raw Semgrep credential in PostHog's HTTP telemetry.+ # `capture=False` keeps response bodies out of sample capture entirely: findings and secrets+ # payloads carry security-sensitive detail (secret finding locations, free-form triage+ # comments) the name-based scrubbers can't recognise.+ return make_tracked_session(headers=_get_headers(api_token), redact_values=(api_token,), capture=False)+++def _build_url(path: str, params: dict[str, Any]) -> str:+ query = {key: value for key, value in params.items() if value is not None and value != ""}+ if not query:+ return f"{SEMGREP_BASE_URL}{path}"+ return f"{SEMGREP_BASE_URL}{path}?{urlencode(query)}"+++@retry(+ retry=retry_if_exception_type((SemgrepRetryableError, requests.ReadTimeout, requests.ConnectionError)),+ 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[str, Any]:+ response = session.get(url, timeout=REQUEST_TIMEOUT_SECONDS)++ if response.status_code == 429 or response.status_code >= 500:+ raise SemgrepRetryableError(f"Semgrep API error (retryable): status={response.status_code}, url={url}")++ if not response.ok:+ # Don't log the response body: it can echo back request details we'd rather not persist.+ logger.error(f"Semgrep API error: status={response.status_code}, url={url}")+ response.raise_for_status()++ data = response.json()+ # Every endpoint wraps its rows in a JSON object. A non-object 200 is a permanent API-contract+ # violation (proxy HTML, ...), not a transient failure — raise a plain ValueError so it+ # surfaces immediately instead of burning the retry budget on something retries can't fix.+ if not isinstance(data, dict):+ raise ValueError(f"Semgrep API returned a non-object response: url={url}")+ return data+++def validate_credentials(api_token: str) -> bool:+ # One cheap probe of the token itself: /deployments is the root resource every Web API token+ # can read, and it's the same call the sync fans out from.+ try:+ response = _make_session(api_token).get(f"{SEMGREP_BASE_URL}/deployments", timeout=10)+ return response.status_code == 200+ except Exception:+ return False+++def _list_deployments(session: requests.Session, logger: FilteringBoundLogger) -> list[dict[str, Any]]:+ data = _fetch_page(session, f"{SEMGREP_BASE_URL}/deployments", logger)+ return data.get("deployments") or []+++def _with_deployment(rows: list[dict[str, Any]], deployment: dict[str, Any]) -> list[dict[str, Any]]:+ """Inject the parent deployment onto each fan-out row so rows stay unique table-wide."""+ return [{**row, "deployment_id": deployment.get("id"), "deployment_slug": deployment.get("slug")} for row in rows]+++def _iter_paged_rows(+ session: requests.Session,+ path: str,+ config: SemgrepEndpointConfig,+ deployment: dict[str, Any],+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[SemgrepResumeConfig],+ start_page: int,+) -> Iterator[list[dict[str, Any]]]:+ page = start_page+ while True:+ url = _build_url(path, {**config.params, "page": page, "page_size": config.page_size})+ data = _fetch_page(session, url, logger)+ rows = data.get(config.data_key) or []+ if not rows:+ break++ yield _with_deployment(rows, deployment)++ # A short page means we've reached the end of the resource.+ if config.page_size is not None and len(rows) < config.page_size:+ break++ page += 1+ # Save AFTER yielding so a crash re-pulls from the last persisted page rather than+ # skipping ahead; the merge dedupes any re-pulled rows on the primary key.+ resumable_source_manager.save_state(SemgrepResumeConfig(deployment_id=str(deployment["id"]), page=page))+++def _iter_cursor_rows(+ session: requests.Session,+ path: str,+ config: SemgrepEndpointConfig,+ deployment: dict[str, Any],+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[SemgrepResumeConfig],+ start_cursor: str | None,+) -> Iterator[list[dict[str, Any]]]:+ cursor = start_cursor+ while True:+ params: dict[str, Any] = {**config.params, "limit": config.page_size}+ if cursor:+ params["cursor"] = cursor+ data = _fetch_page(session, _build_url(path, params), logger)+ rows = data.get(config.data_key) or []+ if not rows:+ break++ yield _with_deployment(rows, deployment)++ next_cursor = data.get("cursor")+ # The API isn't explicit about the final page's cursor; treat a missing or unchanged+ # cursor as the end so we can't loop on the same page forever.+ if not next_cursor or next_cursor == cursor:+ break+ cursor = next_cursor+ resumable_source_manager.save_state(SemgrepResumeConfig(deployment_id=str(deployment["id"]), cursor=cursor))+++def get_rows(+ api_token: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[SemgrepResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ config = SEMGREP_ENDPOINTS[endpoint]+ # One session reused across every page (and every deployment) so urllib3 keeps the+ # connection alive instead of re-handshaking per request.+ session = _make_session(api_token)++ if config.pagination == "none":+ data = _fetch_page(session, _build_url(config.path, dict(config.params)), logger)+ rows = data.get(config.data_key) or []+ if rows:+ yield rows+ return++ deployments = _list_deployments(session, logger)++ # Resolve the saved deployment bookmark to the slice still to process. If the bookmarked+ # deployment no longer exists, start over from the first one — merge dedupes re-pulled rows.+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ remaining = deployments+ if resume is not None and resume.deployment_id is not None:+ deployment_ids = [str(d.get("id")) for d in deployments]+ if resume.deployment_id in deployment_ids:+ remaining = deployments[deployment_ids.index(resume.deployment_id) :]+ logger.debug(f"Semgrep: resuming {endpoint} from deployment_id={resume.deployment_id}")+ else:+ resume = None++ for index, deployment in enumerate(remaining):+ path = config.path.format(deployment_slug=deployment.get("slug", ""), deployment_id=deployment.get("id", ""))+ # Only the resumed-into deployment starts from the saved page/cursor; the rest start fresh.+ start_page = resume.page if resume is not None else 0+ start_cursor = resume.cursor if resume is not None else None+ resume = None++ if config.pagination == "page":+ yield from _iter_paged_rows(session, path, config, deployment, logger, resumable_source_manager, start_page)+ else:+ yield from _iter_cursor_rows(+ session, path, config, deployment, logger, resumable_source_manager, start_cursor+ )++ # Advance the bookmark so a crash between deployments resumes at the next one.+ if index + 1 < len(remaining):+ resumable_source_manager.save_state(SemgrepResumeConfig(deployment_id=str(remaining[index + 1]["id"])))+++def semgrep_source(+ api_token: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[SemgrepResumeConfig],+) -> SourceResponse:+ config = SEMGREP_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ api_token=api_token,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ ),+ primary_keys=config.primary_keys,+ 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,+ sort_mode=config.sort_mode,+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/semgrep/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/semgrep/settings.pynew file mode 100644index 000000000000..da65a058b5f3--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/semgrep/settings.py@@ -0,0 +1,77 @@+from dataclasses import dataclass, field+from typing import Literal++PaginationStyle = Literal["none", "page", "cursor"]+++@dataclass+class SemgrepEndpointConfig:+ # Path relative to the API base URL; may contain `{deployment_slug}` / `{deployment_id}`+ # placeholders resolved per deployment during the fan-out.+ path: str+ # Response key carrying the row list (Semgrep wraps every list payload in an object).+ data_key: str+ # `page` = zero-indexed `page`/`page_size` params; `cursor` = `cursor`/`limit` params with the+ # next cursor returned in the response body; `none` = single unpaginated request.+ pagination: PaginationStyle = "page"+ page_size: int | None = None+ # Static query params sent on every request (e.g. `issue_type`, `dedup`).+ params: dict[str, str] = field(default_factory=dict)+ # Fan-out rows get `deployment_id`/`deployment_slug` injected, and the composite key guards+ # against id collisions if a token ever spans more than one deployment.+ primary_keys: list[str] = field(default_factory=lambda: ["deployment_id", "id"])+ # Stable creation timestamp for datetime partitioning (never a churning field like updated_at).+ partition_key: str | None = None+ # Findings arrive newest-first (`relevant_since` descending, no sort param). Irrelevant for the+ # full-refresh-only sync these endpoints use, but declared truthfully.+ sort_mode: Literal["asc", "desc"] = "asc"+++# Semgrep AppSec Platform REST API (https://semgrep.dev/api/v1/docs/). Requires an API token with+# the Web API scope (Team/Enterprise tier). Tokens are scoped to a single deployment, so the+# per-deployment fan-out normally iterates exactly one deployment. No endpoint offers a server-side+# updated-since filter (findings' `since` filters on `relevant_since`, which does not advance when+# a finding's status/triage changes), so every table syncs as full refresh (see source.py).+SEMGREP_ENDPOINTS: dict[str, SemgrepEndpointConfig] = {+ "deployments": SemgrepEndpointConfig(+ path="/deployments",+ data_key="deployments",+ pagination="none",+ primary_keys=["id"],+ ),+ "projects": SemgrepEndpointConfig(+ path="/deployments/{deployment_slug}/projects",+ data_key="projects",+ page_size=100,+ ),+ "sast_findings": SemgrepEndpointConfig(+ path="/deployments/{deployment_slug}/findings",+ data_key="findings",+ # Findings allow page_size 100-3000; a bigger page keeps request volume down on large+ # backlogs without inflating per-yield memory beyond the pipeline's buffering thresholds.+ page_size=1000,+ # dedup=true collapses per-branch duplicates so counts match the Semgrep UI.+ params={"issue_type": "sast", "dedup": "true"},+ partition_key="created_at",+ sort_mode="desc",+ ),+ "sca_findings": SemgrepEndpointConfig(+ path="/deployments/{deployment_slug}/findings",+ data_key="findings",+ page_size=1000,+ params={"issue_type": "sca", "dedup": "true"},+ partition_key="created_at",+ sort_mode="desc",+ ),+ "secrets": SemgrepEndpointConfig(+ path="/deployments/{deployment_id}/secrets",+ data_key="findings",+ pagination="cursor",+ page_size=100,+ # The secrets endpoint uses camelCase field names, unlike the findings endpoints.+ partition_key="createdAt",+ sort_mode="desc",+ ),+}++ENDPOINTS = tuple(SEMGREP_ENDPOINTS.keys())diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/semgrep/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/semgrep/source.pyindex 379511e0873a..509715909474 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/semgrep/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/semgrep/source.py@@ -1,19 +1,42 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,)-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 SemgrepSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.semgrep.semgrep import (+ SemgrepResumeConfig,+ semgrep_source,+ validate_credentials as validate_semgrep_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.semgrep.settings import (+ ENDPOINTS,+ SEMGREP_ENDPOINTS,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class SemgrepSource(SimpleSource[SemgrepSourceConfig]):+class SemgrepSource(ResumableSource[SemgrepSourceConfig, SemgrepResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.SEMGREP@@ -23,8 +46,93 @@ class SemgrepSource(SimpleSource[SemgrepSourceConfig]):return SourceConfig(name=SchemaExternalDataSourceType.SEMGREP,category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,- label="Semgrep, Inc.",+ label="Semgrep",+ releaseStatus=ReleaseStatus.ALPHA,+ keywords=["sast", "sca", "appsec"],+ caption="""Enter your Semgrep API token to sync your static analysis data — deployments, projects, code (SAST) and supply chain (SCA) findings, and secrets — into the PostHog Data warehouse.++Create a token in Semgrep AppSec Platform under **Settings → Tokens** and grant it the **Web API** scope. The API requires a Semgrep Team or Enterprise plan.""",iconPath="/static/services/semgrep.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/semgrep",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_token",+ label="API token",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.semgrep.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ # An invalid or revoked API token surfaces as a requests HTTPError when `_fetch_page`+ # calls `raise_for_status()`. Retrying can never satisfy a credential problem, so stop+ # the sync. Match the stable status text and base host, not the per-request path/query.+ "401 Client Error: Unauthorized for url: https://semgrep.dev": "Your Semgrep API token is invalid or has been revoked. Create a new token with the Web API scope under Settings → Tokens in Semgrep, then reconnect.",+ "403 Client Error: Forbidden for url: https://semgrep.dev": "Your Semgrep API token does not have permission to read this data. Grant the token the Web API scope (and make sure your plan includes API access), then reconnect.",+ }++ def get_schemas(+ self,+ config: SemgrepSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ # Semgrep exposes no server-side updated-since filter: the findings `since` param filters+ # on `relevant_since`, which does not advance when a finding's status or triage changes,+ # so an incremental sync would freeze statuses. Every endpoint is full refresh.+ schemas = [+ SourceSchema(+ name=endpoint,+ supports_incremental=False,+ supports_append=False,+ incremental_fields=[],+ detected_primary_keys=SEMGREP_ENDPOINTS[endpoint].primary_keys,+ )+ for endpoint in ENDPOINTS+ ]+ if names is not None:+ names_set = set(names)+ schemas = [s for s in schemas if s.name in names_set]+ return schemas++ def validate_credentials(+ self, config: SemgrepSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ # /deployments is the cheapest probe and the root every synced endpoint fans out from, so+ # it confirms the token for any schema.+ if validate_semgrep_credentials(config.api_token):+ return True, None++ return False, "Invalid Semgrep API token"++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[SemgrepResumeConfig]:+ return ResumableSourceManager[SemgrepResumeConfig](inputs, SemgrepResumeConfig)++ def source_for_pipeline(+ self,+ config: SemgrepSourceConfig,+ resumable_source_manager: ResumableSourceManager[SemgrepResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return semgrep_source(+ api_token=config.api_token,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/semgrep/tests/test_semgrep.py b/products/warehouse_sources/backend/temporal/data_imports/sources/semgrep/tests/test_semgrep.pynew file mode 100644index 000000000000..7cf47654a52d--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/semgrep/tests/test_semgrep.py@@ -0,0 +1,294 @@+from typing import Any++import pytest+from unittest.mock import MagicMock, patch++import requests+from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.sources.semgrep import semgrep+from products.warehouse_sources.backend.temporal.data_imports.sources.semgrep.semgrep import (+ SEMGREP_BASE_URL,+ SemgrepResumeConfig,+ SemgrepRetryableError,+ _build_url,+ get_rows,+ semgrep_source,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.semgrep.settings import (+ ENDPOINTS,+ SEMGREP_ENDPOINTS,+)++DEPLOYMENT = {"id": 123, "slug": "my-org", "name": "My Org"}+OTHER_DEPLOYMENT = {"id": 456, "slug": "other-org", "name": "Other Org"}+++class _FakeResumableManager:+ def __init__(self, state: SemgrepResumeConfig | None = None) -> None:+ self._state = state+ self.saved: list[SemgrepResumeConfig] = []++ def can_resume(self) -> bool:+ return self._state is not None++ def load_state(self) -> SemgrepResumeConfig | None:+ return self._state++ def save_state(self, data: SemgrepResumeConfig) -> None:+ self.saved.append(data)+++def _response_with_status(status_code: int, body: bytes = b"") -> requests.Response:+ response = requests.Response()+ response.status_code = status_code+ response._content = body+ return response+++def _query_param(url: str, name: str) -> str | None:+ if f"{name}=" not in url:+ return None+ return url.split(f"{name}=")[1].split("&")[0]+++class TestBuildUrl:+ def test_page_zero_is_kept(self) -> None:+ # page=0 is the first page; it must not be dropped as a falsy value.+ url = _build_url("/deployments/my-org/projects", {"page": 0, "page_size": 100})+ assert "page=0" in url++ def test_no_params_yields_bare_url(self) -> None:+ assert _build_url("/deployments", {}) == f"{SEMGREP_BASE_URL}/deployments"++ def test_none_values_are_omitted(self) -> None:+ url = _build_url("/deployments/123/secrets", {"limit": 100, "cursor": None})+ assert "cursor" not in url+++class TestFetchPage:+ @parameterized.expand([("rate_limited", 429), ("server_error", 500), ("bad_gateway", 503)])+ def test_retryable_statuses_raise_retryable_error(self, _name: str, status: int) -> None:+ session = MagicMock()+ session.get.return_value = _response_with_status(status)+ # No-op the backoff sleep so the 5 attempts run instantly.+ with patch.object(semgrep._fetch_page.retry, "sleep", lambda *a, **k: None): # type: ignore[attr-defined]+ with pytest.raises(SemgrepRetryableError):+ semgrep._fetch_page(session, f"{SEMGREP_BASE_URL}/deployments", MagicMock())+ assert session.get.call_count == 5++ @parameterized.expand([("unauthorized", 401), ("forbidden", 403), ("not_found", 404)])+ def test_client_errors_raise_http_error(self, _name: str, status: int) -> None:+ session = MagicMock()+ session.get.return_value = _response_with_status(status)+ with pytest.raises(requests.HTTPError):+ semgrep._fetch_page(session, f"{SEMGREP_BASE_URL}/deployments", MagicMock())++ def test_non_object_payload_raises_value_error(self) -> None:+ # A non-object 200 is a permanent contract violation, so it must bypass the retry decorator.+ session = MagicMock()+ session.get.return_value = _response_with_status(200, b'[{"id": 1}]')+ with pytest.raises(ValueError):+ semgrep._fetch_page(session, f"{SEMGREP_BASE_URL}/deployments", MagicMock())+ assert session.get.call_count == 1+++class TestGetRows:+ @staticmethod+ def _collect(+ endpoint: str,+ manager: _FakeResumableManager,+ monkeypatch: Any,+ responses: dict[str, dict[str, Any]],+ deployments: list[dict[str, Any]] | None = None,+ ) -> tuple[list[dict], list[str]]:+ """Drive get_rows with canned responses keyed on (page|cursor) query param per path."""+ fetched_urls: list[str] = []++ def fake_fetch(session: Any, url: str, logger: Any) -> dict[str, Any]:+ fetched_urls.append(url)+ if url == f"{SEMGREP_BASE_URL}/deployments":+ return {"deployments": deployments if deployments is not None else [DEPLOYMENT]}+ key = _query_param(url, "page") or _query_param(url, "cursor") or ""+ path = url.split(SEMGREP_BASE_URL)[1].split("?")[0]+ return responses.get(f"{path}|{key}", {})++ monkeypatch.setattr(semgrep, "_fetch_page", fake_fetch)+ monkeypatch.setattr(semgrep, "make_tracked_session", lambda **kwargs: MagicMock())++ rows: list[dict] = []+ for page in get_rows(+ api_token="token",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=manager, # type: ignore[arg-type]+ ):+ rows.extend(page)+ return rows, fetched_urls++ def test_deployments_is_a_single_unpaginated_request(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ rows, urls = self._collect("deployments", manager, monkeypatch, {})+ assert rows == [DEPLOYMENT]+ assert urls == [f"{SEMGREP_BASE_URL}/deployments"]+ assert manager.saved == []++ def test_paged_endpoint_paginates_until_short_page_and_injects_deployment(self, monkeypatch: Any) -> None:+ page_size = SEMGREP_ENDPOINTS["sast_findings"].page_size+ assert page_size is not None+ full_page = [{"id": i} for i in range(page_size)]+ manager = _FakeResumableManager()+ rows, urls = self._collect(+ "sast_findings",+ manager,+ monkeypatch,+ {+ "/deployments/my-org/findings|0": {"findings": full_page},+ "/deployments/my-org/findings|1": {"findings": [{"id": page_size}]},+ },+ )+ assert len(rows) == page_size + 1+ # Every row carries the parent deployment, keeping the composite primary key unique.+ assert all(row["deployment_id"] == 123 and row["deployment_slug"] == "my-org" for row in rows)+ # State is saved after the full page (pointing at the next page), then we stop on the short one.+ assert manager.saved == [SemgrepResumeConfig(deployment_id="123", page=1)]+ # sast_findings requests must pin issue_type and dedup so counts match the Semgrep UI.+ finding_urls = [url for url in urls if "findings" in url]+ assert all("issue_type=sast" in url and "dedup=true" in url for url in finding_urls)++ def test_sca_findings_requests_sca_issue_type(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ _, urls = self._collect(+ "sca_findings",+ manager,+ monkeypatch,+ {"/deployments/my-org/findings|0": {"findings": [{"id": 1}]}},+ )+ assert any("issue_type=sca" in url for url in urls)++ def test_empty_first_page_yields_nothing(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ rows, _ = self._collect("projects", manager, monkeypatch, {"/deployments/my-org/projects|0": {"projects": []}})+ assert rows == []+ assert manager.saved == []++ def test_resumes_from_saved_page(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager(SemgrepResumeConfig(deployment_id="123", page=2))+ rows, urls = self._collect(+ "projects",+ manager,+ monkeypatch,+ {"/deployments/my-org/projects|2": {"projects": [{"id": 7}]}},+ )+ # Resuming skips pages 0-1; the short page 2 finishes the sync.+ assert [row["id"] for row in rows] == [7]+ project_urls = [url for url in urls if "projects" in url]+ assert len(project_urls) == 1+ assert "page=2" in project_urls[0]++ def test_vanished_bookmarked_deployment_starts_over(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager(SemgrepResumeConfig(deployment_id="999", page=5))+ rows, urls = self._collect(+ "projects",+ manager,+ monkeypatch,+ {"/deployments/my-org/projects|0": {"projects": [{"id": 1}]}},+ )+ assert [row["id"] for row in rows] == [1]+ assert any("page=0" in url for url in urls)++ def test_fans_out_over_every_deployment_and_bookmarks_the_next(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ rows, _ = self._collect(+ "projects",+ manager,+ monkeypatch,+ {+ "/deployments/my-org/projects|0": {"projects": [{"id": 1}]},+ "/deployments/other-org/projects|0": {"projects": [{"id": 2}]},+ },+ deployments=[DEPLOYMENT, OTHER_DEPLOYMENT],+ )+ assert {(row["id"], row["deployment_slug"]) for row in rows} == {(1, "my-org"), (2, "other-org")}+ # A crash between deployments must resume at the second one, not re-run the first.+ assert SemgrepResumeConfig(deployment_id="456") in manager.saved++ def test_cursor_endpoint_follows_cursor_until_absent(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ rows, urls = self._collect(+ "secrets",+ manager,+ monkeypatch,+ {+ "/deployments/123/secrets|": {"findings": [{"id": "1"}], "cursor": "abc"},+ "/deployments/123/secrets|abc": {"findings": [{"id": "2"}]},+ },+ )+ assert [row["id"] for row in rows] == ["1", "2"]+ secrets_urls = [url for url in urls if "secrets" in url]+ assert _query_param(secrets_urls[0], "cursor") is None+ assert _query_param(secrets_urls[1], "cursor") == "abc"+ # State is saved after yielding the first page so a crash re-pulls, never skips, a page.+ assert manager.saved == [SemgrepResumeConfig(deployment_id="123", cursor="abc")]++ def test_cursor_endpoint_terminates_on_repeated_cursor(self, monkeypatch: Any) -> None:+ # If the API keeps echoing the final cursor, the sync must stop instead of looping forever.+ manager = _FakeResumableManager()+ rows, urls = self._collect(+ "secrets",+ manager,+ monkeypatch,+ {+ "/deployments/123/secrets|": {"findings": [{"id": "1"}], "cursor": "abc"},+ "/deployments/123/secrets|abc": {"findings": [{"id": "2"}], "cursor": "abc"},+ },+ )+ assert [row["id"] for row in rows] == ["1", "2"]+ assert len([url for url in urls if "secrets" in url]) == 2++ def test_cursor_endpoint_resumes_from_saved_cursor(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager(SemgrepResumeConfig(deployment_id="123", cursor="abc"))+ rows, urls = self._collect(+ "secrets",+ manager,+ monkeypatch,+ {"/deployments/123/secrets|abc": {"findings": [{"id": "2"}]}},+ )+ assert [row["id"] for row in rows] == ["2"]+ secrets_urls = [url for url in urls if "secrets" in url]+ assert len(secrets_urls) == 1+ assert _query_param(secrets_urls[0], "cursor") == "abc"+++class TestSemgrepSourceResponse:+ @parameterized.expand([(name,) for name in ENDPOINTS])+ def test_source_response_shape(self, name: str) -> None:+ config = SEMGREP_ENDPOINTS[name]+ response = semgrep_source(+ api_token="token",+ endpoint=name,+ logger=MagicMock(),+ resumable_source_manager=MagicMock(),+ )+ assert response.name == name+ assert response.primary_keys == config.primary_keys+ assert response.sort_mode == config.sort_mode+ if config.partition_key:+ assert response.partition_keys == [config.partition_key]+ assert response.partition_mode == "datetime"+ else:+ assert response.partition_keys is None++ def test_fan_out_endpoints_key_on_deployment_and_id(self) -> None:+ # Guards against dropping the parent id from a fan-out child's key, which would seed+ # duplicate rows if a token ever spans multiple deployments.+ for name, config in SEMGREP_ENDPOINTS.items():+ if name == "deployments":+ assert config.primary_keys == ["id"]+ else:+ assert config.primary_keys == ["deployment_id", "id"]++ def test_partition_keys_are_stable_creation_timestamps(self) -> None:+ # Partitioning on a churning field (updated_at) rewrites partitions on every sync.+ partitioned = {name: cfg.partition_key for name, cfg in SEMGREP_ENDPOINTS.items() if cfg.partition_key}+ assert partitioned == {"sast_findings": "created_at", "sca_findings": "created_at", "secrets": "createdAt"}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/semgrep/tests/test_semgrep_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/semgrep/tests/test_semgrep_source.pynew file mode 100644index 000000000000..b0943e41df10--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/semgrep/tests/test_semgrep_source.py@@ -0,0 +1,159 @@+from typing import Any++from unittest.mock import MagicMock, patch++from parameterized import parameterized++from posthog.schema import DataWarehouseSourceCategory, ReleaseStatus, SourceFieldInputConfig++from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.semgrep.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.semgrep.semgrep import SemgrepResumeConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.semgrep.settings import (+ ENDPOINTS,+ SEMGREP_ENDPOINTS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.semgrep.source import SemgrepSource+from products.warehouse_sources.backend.types import ExternalDataSourceType+++def _config(api_token: str = "token") -> Any:+ config = MagicMock()+ config.api_token = api_token+ return config+++class TestSourceConfig:+ def test_source_type(self) -> None:+ assert SemgrepSource().source_type == ExternalDataSourceType.SEMGREP++ def test_config_is_visible_and_alpha(self) -> None:+ config = SemgrepSource().get_source_config+ # A finished source must not be hidden from users.+ assert getattr(config, "unreleasedSource", None) in (None, False)+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.category == DataWarehouseSourceCategory.ENGINEERING___MONITORING+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/semgrep"++ def test_fields(self) -> None:+ fields = {f.name: f for f in SemgrepSource().get_source_config.fields if isinstance(f, SourceFieldInputConfig)}+ assert set(fields) == {"api_token"}+ assert fields["api_token"].required is True+ assert fields["api_token"].secret is True+++class TestGetSchemas:+ def test_lists_every_endpoint_as_full_refresh(self) -> None:+ schemas = SemgrepSource().get_schemas(_config(), team_id=1)+ assert {s.name for s in schemas} == set(ENDPOINTS)+ # Semgrep has no server-side updated-since filter (the findings `since` param doesn't move+ # on status/triage changes), so nothing may be advertised as incremental/append.+ assert all(not s.supports_incremental and not s.supports_append for s in schemas)+ assert all(s.incremental_fields == [] for s in schemas)+ for schema in schemas:+ assert schema.detected_primary_keys == SEMGREP_ENDPOINTS[schema.name].primary_keys++ def test_names_filter(self) -> None:+ schemas = SemgrepSource().get_schemas(_config(), team_id=1, names=["deployments", "secrets"])+ assert {s.name for s in schemas} == {"deployments", "secrets"}++ def test_lists_tables_without_credentials(self) -> None:+ # Static endpoint catalog (no I/O) — public docs render the table list.+ assert SemgrepSource.lists_tables_without_credentials is True+ tables = SemgrepSource().get_documented_tables()+ assert {t["name"] for t in tables} == set(ENDPOINTS)+ findings = next(t for t in tables if t["name"] == "sast_findings")+ assert findings["sync_methods"] == ["Full refresh"]+ assert findings["primary_keys"] == ["deployment_id", "id"]+++class TestValidateCredentials:+ def test_success(self) -> None:+ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.semgrep.source.validate_semgrep_credentials",+ return_value=True,+ ) as mocked:+ ok, error = SemgrepSource().validate_credentials(_config(), team_id=1)+ assert ok is True+ assert error is None+ mocked.assert_called_once_with("token")++ def test_failure(self) -> None:+ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.semgrep.source.validate_semgrep_credentials",+ return_value=False,+ ):+ ok, error = SemgrepSource().validate_credentials(_config(), team_id=1, schema_name="sast_findings")+ assert ok is False+ assert error is not None+++class TestResumableWiring:+ def test_get_resumable_source_manager_binds_data_class(self) -> None:+ inputs = MagicMock()+ inputs.logger = MagicMock()+ manager = SemgrepSource().get_resumable_source_manager(inputs)+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is SemgrepResumeConfig++ def test_source_for_pipeline_plumbs_arguments(self) -> None:+ inputs = MagicMock()+ inputs.schema_name = "sca_findings"+ inputs.logger = MagicMock()+ manager = MagicMock()+ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.semgrep.source.semgrep_source"+ ) as mocked:+ SemgrepSource().source_for_pipeline(_config(), manager, inputs)+ mocked.assert_called_once_with(+ api_token="token",+ endpoint="sca_findings",+ logger=inputs.logger,+ resumable_source_manager=manager,+ )+++class TestNonRetryableErrors:+ @parameterized.expand(+ [+ (+ "unauthorized",+ "401 Client Error: Unauthorized for url: https://semgrep.dev/api/v1/deployments/my-org/findings?issue_type=sast",+ ),+ (+ "forbidden",+ "403 Client Error: Forbidden for url: https://semgrep.dev/api/v1/deployments/123/secrets",+ ),+ ]+ )+ def test_credential_errors_are_non_retryable(self, _name: str, observed_error: str) -> None:+ non_retryable = SemgrepSource().get_non_retryable_errors()+ assert any(key in observed_error for key in non_retryable)++ @parameterized.expand(+ [+ ("read_timeout", "HTTPSConnectionPool(host='semgrep.dev', port=443): Read timed out."),+ (+ "server_error",+ "500 Server Error: Internal Server Error for url: https://semgrep.dev/api/v1/deployments",+ ),+ (+ "rate_limited",+ "429 Client Error: Too Many Requests for url: https://semgrep.dev/api/v1/deployments",+ ),+ ]+ )+ def test_transient_errors_remain_retryable(self, _name: str, other_error: str) -> None:+ non_retryable = SemgrepSource().get_non_retryable_errors()+ assert not any(key in other_error for key in non_retryable)+++class TestCanonicalDescriptions:+ def test_canonical_descriptions_keys_are_known_endpoints(self) -> None:+ # Every documented table must map to a real endpoint, or its descriptions never apply.+ assert set(CANONICAL_DESCRIPTIONS) == set(ENDPOINTS)++ def test_source_exposes_canonical_descriptions(self) -> None:+ assert SemgrepSource().get_canonical_descriptions() is CANONICAL_DESCRIPTIONS