: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 gitguardian import source (#71193)
Tom Owersa39950af3378
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex a2f37859ce36..6d54397c9073 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -234,6 +234,7 @@ the row lists both.| gitbook | HTTP | requests | ✅ || gitea | HTTP + Webhook | requests + `WebhookSourceManager` | ✅ (pull) / ➖ (webhook) || github | HTTP + Webhook | requests + `WebhookSourceManager` | ✅ (pull) / ➖ (webhook) |+| gitguardian | HTTP | requests | ✅ || giphy | HTTP | requests | ✅ || gitlab | HTTP | requests | ✅ || gladly | HTTP | requests | ✅ |@@ -718,7 +719,6 @@ doesn't conflict with concurrent PRs.- gerrit- getstream- gitea-- gitguardian- glassfrog- gmail- gnewsdiff --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 8b8ea6a47200..5a3a3a8f1e79 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@@ -1777,7 +1777,8 @@ class GiteaSourceConfig(config.Config):@config.configclass GitguardianSourceConfig(config.Config):- pass+ api_key: str+ base_url: str | None = None@config.configdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gitguardian/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gitguardian/canonical_descriptions.pynew file mode 100644index 000000000000..63a273dabcc6--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gitguardian/canonical_descriptions.py@@ -0,0 +1,109 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "secret_incidents": {+ "description": "A secret incident regroups every occurrence of the same secret detected across your monitored perimeter, with its triage status and remediation timeline.",+ "docs_url": "https://api.gitguardian.com/docs#tag/Secret-Incidents",+ "columns": {+ "id": "Unique identifier of the incident.",+ "date": "Date and time the secret was first detected. Immutable.",+ "detector": "Detector that matched the secret (name, family, detector group).",+ "secret_hash": "Hash of the detected secret, used to group occurrences of the same secret.",+ "gitguardian_url": "Link to the incident in the GitGuardian dashboard.",+ "regression": "Whether the incident reappeared after having been resolved.",+ "status": "Triage status of the incident (IGNORED, TRIGGERED, ASSIGNED, RESOLVED).",+ "assignee_id": "Identifier of the workspace member the incident is assigned to.",+ "assignee_email": "Email of the workspace member the incident is assigned to.",+ "occurrences_count": "Number of times the secret occurs across the monitored perimeter.",+ "occurrences": "Up to 20 embedded occurrences of the secret; the full list lives in the secret_occurrences table.",+ "ignore_reason": "Why the incident was ignored (test_credential, false_positive, low_risk).",+ "ignored_at": "Date and time the incident was ignored, if it was.",+ "resolved_at": "Date and time the incident was resolved, if it was.",+ "secret_revoked": "Whether the secret was revoked as part of remediation.",+ "severity": "Severity assigned to the incident (critical, high, medium, low, info, unknown).",+ "validity": "Whether the secret is still valid against its service (valid, invalid, failed_to_check, no_checker, unknown).",+ "tags": "Tags attached to the incident (e.g. PUBLICLY_EXPOSED, SENSITIVE_FILE).",+ },+ },+ "secret_occurrences": {+ "description": "A single place a secret was found: one match of an incident's secret in a specific commit, file, or other monitored location.",+ "docs_url": "https://api.gitguardian.com/docs#tag/Secret-Occurrences",+ "columns": {+ "id": "Unique identifier of the occurrence.",+ "incident_id": "Identifier of the secret incident this occurrence belongs to.",+ "kind": "Kind of occurrence (e.g. realtime, historical).",+ "source": "Monitored source (repository, ...) the occurrence was found in.",+ "author_name": "Name of the commit author who introduced the secret.",+ "author_info": "Email or other contact info of the commit author.",+ "sha": "Commit SHA the secret was found in.",+ "date": "Date and time the occurrence was detected. Immutable.",+ "filepath": "Path of the file containing the secret.",+ "filename": "Name of the file containing the secret.",+ "url": "Link to the occurrence location.",+ "presence": "Whether the secret is still present in the source (present, removed).",+ "matches": "Matched portions of the secret within the file (indices and match kind).",+ },+ },+ "sources": {+ "description": "A monitored source in your GitGuardian perimeter (repository, VCS org, ...), with its scan health and open incident counts.",+ "docs_url": "https://api.gitguardian.com/docs#tag/Sources",+ "columns": {+ "id": "Unique identifier of the source.",+ "url": "URL of the source.",+ "type": "Type of source (github, gitlab, bitbucket, azure_devops, ...).",+ "full_name": "Full name of the source, e.g. the owner/repository slug.",+ "health": "Health of the source based on its open incidents (safe, unknown, at_risk).",+ "default_branch": "Default branch of the repository, when applicable.",+ "open_incidents_count": "Number of open secret incidents detected on this source.",+ "closed_incidents_count": "Number of closed secret incidents detected on this source.",+ "visibility": "Visibility of the source (public, private, internal).",+ "external_id": "Identifier of the source on the external system (e.g. the GitHub repository id).",+ "source_criticality": "Criticality assigned to the source (critical, high, medium, low, unknown).",+ "last_scan": "Status and date of the source's last historical scan.",+ "monitored": "Whether the source is currently monitored.",+ },+ },+ "honeytokens": {+ "description": "A honeytoken (decoy credential) created in your workspace, with its trigger status showing whether it was used.",+ "docs_url": "https://api.gitguardian.com/docs#tag/Honeytokens",+ "columns": {+ "id": "Unique identifier of the honeytoken.",+ "name": "Name given to the honeytoken.",+ "description": "Description of the honeytoken.",+ "type": "Type of honeytoken (e.g. AWS).",+ "status": "Status of the honeytoken (active, triggered, revoked).",+ "created_at": "Date and time the honeytoken was created.",+ "triggered_at": "Date and time the honeytoken was first triggered, if it was.",+ "revoked_at": "Date and time the honeytoken was revoked, if it was.",+ "creator_id": "Identifier of the workspace member who created the honeytoken.",+ "gitguardian_url": "Link to the honeytoken in the GitGuardian dashboard.",+ },+ },+ "members": {+ "description": "A member of your GitGuardian workspace, with their access level and activity.",+ "docs_url": "https://api.gitguardian.com/docs#tag/Members",+ "columns": {+ "id": "Unique identifier of the member.",+ "name": "Name of the member.",+ "email": "Email of the member.",+ "role": "Deprecated in favor of access_level; the member's workspace role.",+ "access_level": "Access level of the member (owner, manager, member, restricted).",+ "created_at": "Date and time the member joined the workspace.",+ "last_login": "Date and time of the member's last login.",+ "active": "Whether the member's account is active.",+ },+ },+ "teams": {+ "description": "A team in your GitGuardian workspace, used to scope incidents and sources to groups of members.",+ "docs_url": "https://api.gitguardian.com/docs#tag/Teams",+ "columns": {+ "id": "Unique identifier of the team.",+ "name": "Name of the team.",+ "description": "Description of the team.",+ "is_global": "Whether this is the built-in All incidents team covering the whole workspace.",+ "gitguardian_url": "Link to the team in the GitGuardian dashboard.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gitguardian/gitguardian.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gitguardian/gitguardian.pynew file mode 100644index 000000000000..578211b73a86--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gitguardian/gitguardian.py@@ -0,0 +1,283 @@+import dataclasses+from collections.abc import Iterator+from datetime import UTC, date, datetime+from typing import Any, Optional+from urllib.parse import urlencode, urljoin, urlsplit++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.gitguardian.settings import (+ GITGUARDIAN_ENDPOINTS,+ GitGuardianEndpointConfig,+)++GITGUARDIAN_DEFAULT_BASE_URL = "https://api.gitguardian.com"+++class GitGuardianRetryableError(Exception):+ pass+++class GitGuardianResumeConfig:+ # The full URL used to FETCH the page we last yielded (the initial params URL or a+ # Link-header cursor URL). We checkpoint the current page's URL (not the next one) so a+ # crash re-fetches and re-yields the last page rather than skipping it; merge dedupes the+ # re-pulled rows on the primary key.+ url: str | None = None+++def resolve_base_url(base_url: str | None) -> str:+ """SaaS US users leave this blank; EU and self-hosted workspaces point it at their instance."""+ resolved = (base_url or "").strip().rstrip("/")+ return resolved or GITGUARDIAN_DEFAULT_BASE_URL+++def validate_base_url(base_url: str) -> str | None:+ """Return an error message if `base_url` is not a safe HTTPS URL, else None.++ Defense-in-depth on top of the Smokescreen egress proxy. The secret API token is sent to+ whatever this points at, so we:+ - require HTTPS, so the token is never sent over plaintext HTTP;+ - reject backslashes, which `urlsplit` folds into the userinfo (host `example.com` for+ `https://169.254.169.254\\@example.com`) while `requests`/`urllib3` treat them as `/` and+ connect to `169.254.169.254`, letting a crafted URL slip past the hostname safety check.+ """+ if "\\" in base_url:+ return "The GitGuardian API URL must not contain backslashes."+ if urlsplit(base_url).scheme.lower() != "https":+ return "The GitGuardian API URL must use HTTPS."+ return None+++def _get_headers(api_key: str) -> dict[str, str]:+ return {+ "Authorization": f"Token {api_key}",+ "Accept": "application/json",+ }+++def _format_incremental_value(value: Any) -> str:+ """Format an incremental cursor value as an ISO 8601 datetime for the date_after filter."""+ if isinstance(value, datetime):+ aware = value if value.tzinfo is not None else value.replace(tzinfo=UTC)+ return aware.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%SZ")+ if isinstance(value, date):+ return datetime.combine(value, datetime.min.time(), tzinfo=UTC).strftime("%Y-%m-%dT%H:%M:%SZ")+ return str(value)+++def _build_url(base_url: str, path: str, params: dict[str, Any]) -> str:+ if not params:+ return f"{base_url}{path}"+ return f"{base_url}{path}?{urlencode(params)}"+++@retry(+ retry=retry_if_exception_type(+ (+ GitGuardianRetryableError,+ requests.ReadTimeout,+ requests.ConnectionError,+ requests.exceptions.ChunkedEncodingError,+ )+ ),+ stop=stop_after_attempt(5),+ wait=wait_exponential_jitter(initial=1, max=30),+ reraise=True,+)+def _fetch_page(+ session: requests.Session, url: str, headers: dict[str, str], logger: FilteringBoundLogger+) -> requests.Response:+ """Fetch one page, returning the raw response (the cursor lives in the Link header)."""+ response = session.get(url, headers=headers, timeout=60)++ # GitGuardian rate-limits per API key (with monthly quotas) and returns 429 on exceed;+ # back off and retry on 429 and transient 5xx.+ if response.status_code == 429 or response.status_code >= 500:+ raise GitGuardianRetryableError(f"GitGuardian API error (retryable): status={response.status_code}, url={url}")++ if not response.ok:+ logger.error(f"GitGuardian API error: status={response.status_code}, body={response.text}, url={url}")+ response.raise_for_status()++ return response+++def _next_page_url(response: requests.Response) -> str | None:+ """GitGuardian paginates via RFC 5988 Link headers; `requests` parses them into `.links`."""+ return response.links.get("next", {}).get("url")+++def _ensure_same_origin(url: str, base_url: str) -> str:+ """Refuse to fetch a URL whose origin differs from the configured API URL.++ Pagination URLs come from response Link headers and resume URLs from persisted state; both+ are fetched with the `Authorization` token attached, so a tampered value must not be able to+ steer the token to another host. Relative URLs are resolved against the base first.+ """+ resolved = urljoin(f"{base_url}/", url)+ base, target = urlsplit(base_url), urlsplit(resolved)+ if (target.scheme, target.netloc) != (base.scheme, base.netloc):+ raise ValueError(f"GitGuardian returned a cross-origin pagination URL; refusing to follow it: {resolved}")+ return resolved+++def validate_credentials(api_key: str, base_url: str) -> tuple[bool, str | None]:+ """Probe the token against the scope-free health endpoint. 200 => valid; 401 => bad token."""+ url = f"{base_url}/v1/health"+ try:+ # allow_redirects=False keeps the token pinned to the validated host: a 30x from a+ # self-hosted instance must not replay `Authorization` to an internal or attacker origin.+ response = make_tracked_session(allow_redirects=False).get(url, headers=_get_headers(api_key), timeout=10)+ except requests.exceptions.RequestException as e:+ return False, str(e)++ if response.status_code == 200:+ return True, None+ if response.status_code in (401, 403):+ return False, "Invalid GitGuardian API token. Create a valid token in your workspace's API settings."+ return False, f"GitGuardian returned an unexpected response: {response.status_code}"+++def _error_detail(response: requests.Response) -> str | None:+ """Extract GitGuardian's own `detail` message (e.g. the scope it wants) from an error body."""+ try:+ detail = response.json().get("detail")+ except (ValueError, AttributeError):+ return None+ return detail if isinstance(detail, str) and detail else None+++def check_endpoint_access(api_key: str, base_url: str, endpoint: str) -> str | None:+ """Probe one endpoint with a minimal page. None when reachable, else a short reason.++ Only a real denial (401/403) counts as a missing scope — throttles, 5xx, and network blips+ stay retryable, so they report the endpoint as reachable rather than blocking the schema.+ """+ config = GITGUARDIAN_ENDPOINTS[endpoint]+ url = _build_url(base_url, config.path, {"per_page": 1})+ try:+ # capture=False keeps GitGuardian security metadata (repo names, file paths, secret hashes)+ # out of the HTTP sample bucket — the name-based scrubbers can't recognise these fields.+ response = make_tracked_session(allow_redirects=False, capture=False).get(+ url, headers=_get_headers(api_key), timeout=10+ )+ except requests.exceptions.RequestException:+ return None++ if response.status_code not in (401, 403):+ return None+ detail = _error_detail(response)+ if detail:+ return detail+ return f"Your API token is missing the `{config.required_scope}` scope required for this table."+++def get_rows(+ api_key: str,+ base_url: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[GitGuardianResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+ incremental_field: str | None = None,+) -> Iterator[list[dict[str, Any]]]:+ config = GITGUARDIAN_ENDPOINTS[endpoint]+ headers = _get_headers(api_key)+ # One session reused across every page for connection keep-alive. allow_redirects=False keeps+ # the token pinned to the validated host. capture=False keeps GitGuardian security metadata+ # (repo names, file paths, secret hashes) out of the HTTP sample bucket.+ session = make_tracked_session(allow_redirects=False, capture=False)++ params: dict[str, Any] = {"per_page": config.page_size}+ if config.ordering:+ params["ordering"] = config.ordering+ if should_use_incremental_field and db_incremental_field_last_value is not None:+ value = db_incremental_field_last_value+ if isinstance(value, datetime | date) and config.incremental_lookback:+ if isinstance(value, date) and not isinstance(value, datetime):+ value = datetime.combine(value, datetime.min.time(), tzinfo=UTC)+ value = value - config.incremental_lookback+ # `date_after` filters on the row's detection date server-side. The Link header's next-page+ # URL carries the original query params alongside the cursor, so the filter (and ordering)+ # holds on every page — verified against the API reference; unverified against a live+ # workspace (no credentials at build time).+ params[f"{incremental_field or config.default_incremental_field}_after"] = _format_incremental_value(value)++ resume = (+ resumable_source_manager.load_state() if config.resumable and resumable_source_manager.can_resume() else None+ )+ url = (+ _ensure_same_origin(resume.url, base_url)+ if resume and resume.url+ else _build_url(base_url, config.path, params)+ )++ while True:+ response = _fetch_page(session, url, headers, logger)+ rows = response.json()+ if not isinstance(rows, list):+ # Every GitGuardian list endpoint returns a plain JSON array; anything else means the+ # URL walked somewhere unexpected. Bail loudly rather than yield garbage rows.+ raise ValueError(f"GitGuardian returned a non-list response for {endpoint}: {type(rows).__name__}")+ next_url = _next_page_url(response)++ if rows:+ if config.excluded_fields:+ rows = [{k: v for k, v in row.items() if k not in config.excluded_fields} for row in rows]+ yield rows+ # Checkpoint the CURRENT page's URL after yielding, so a crash re-fetches this page.+ if config.resumable:+ resumable_source_manager.save_state(GitGuardianResumeConfig(url=url))++ if not next_url:+ break+ url = _ensure_same_origin(next_url, base_url)++ # The walk finished cleanly, so drop the checkpoint. Otherwise a retry that re-runs extract+ # after a completed walk would resume from the final page and skip everything before it.+ if config.resumable:+ resumable_source_manager.clear_state()+++def gitguardian_source(+ api_key: str,+ base_url: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[GitGuardianResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+ incremental_field: str | None = None,+) -> SourceResponse:+ endpoint_config: GitGuardianEndpointConfig = GITGUARDIAN_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ api_key=api_key,+ base_url=base_url,+ 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,+ # Incremental endpoints request `ordering=date` explicitly, so rows arrive oldest-first+ # and the incremental watermark can checkpoint per batch.+ sort_mode="asc",+ 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,+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gitguardian/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gitguardian/settings.pynew file mode 100644index 000000000000..7d2de4b76908--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gitguardian/settings.py@@ -0,0 +1,120 @@+from collections.abc import Set as AbstractSet+from dataclasses import dataclass, field+from datetime import timedelta+from typing import Optional++from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType+++@dataclass+class GitGuardianEndpointConfig:+ name: str+ path: str+ incremental_fields: list[IncrementalField]+ default_incremental_field: Optional[str] = None+ # Field to partition by. Must be a STABLE detection/creation timestamp (never a mutable+ # status timestamp) so partitions aren't rewritten every sync.+ partition_key: Optional[str] = None+ # Explicit `ordering` param so pagination walks a stable monotonic field; must match the+ # endpoint's SourceResponse sort_mode (asc).+ ordering: Optional[str] = None+ page_size: int = 100 # GitGuardian caps per_page at 100+ primary_keys: list[str] = field(default_factory=lambda: ["id"])+ should_sync_default: bool = True+ # Scope named in permission errors when the probe can't extract the API's own detail message.+ required_scope: str = "incidents:read"+ # Safety overlap subtracted from the incremental watermark each run. GitGuardian rows are+ # created immutable but their triage fields keep mutating (incident status / resolved_at,+ # occurrence presence), and there is no updated-since filter — so we re-pull a trailing+ # window of recently detected rows to pick up late transitions. Merge dedupes on the+ # primary key. Older transitions are only recaptured by a full refresh.+ incremental_lookback: Optional[timedelta] = None+ # Only incremental-capable endpoints checkpoint resume state: their sync merges on the+ # primary key, so a resumed job re-yielding the last page dedupes cleanly. The small+ # full-refresh tables just restart from page one on a worker restart.+ resumable: bool = False+ # Fields dropped from every row before it lands in the warehouse. Used to strip bearer links+ # (e.g. `share_url`, which grants secret access without a GitGuardian account) that would+ # otherwise leak the very secrets this data is meant to help remediate.+ excluded_fields: AbstractSet[str] = field(default_factory=frozenset)+++_DATE_INCREMENTAL_FIELD: list[IncrementalField] = [+ {+ "label": "date",+ "type": IncrementalFieldType.DateTime,+ "field": "date",+ "field_type": IncrementalFieldType.DateTime,+ },+]+++GITGUARDIAN_ENDPOINTS: dict[str, GitGuardianEndpointConfig] = {+ # Secret incidents: the core detection history. `date` (first detection) is immutable, and+ # the endpoint accepts a server-side `date_after` filter plus `ordering=date`, so incremental+ # sync watermarks on it. Status/resolved_at/ignored_at mutate after detection with no+ # updated-since filter, hence the trailing lookback window.+ "secret_incidents": GitGuardianEndpointConfig(+ name="secret_incidents",+ path="/v1/incidents/secrets",+ default_incremental_field="date",+ partition_key="date",+ ordering="date",+ required_scope="incidents:read",+ incremental_lookback=timedelta(days=7),+ resumable=True,+ # `share_url` is a no-auth bearer link that can expose the leaked secret itself.+ excluded_fields=frozenset({"share_url"}),+ incremental_fields=_DATE_INCREMENTAL_FIELD,+ ),+ # Secret occurrences: one row per place a secret was found (commit, file, ...). Same+ # `date_after` + `ordering=date` semantics as incidents; `presence` can flip after+ # remediation, hence the lookback.+ "secret_occurrences": GitGuardianEndpointConfig(+ name="secret_occurrences",+ path="/v1/occurrences/secrets",+ default_incremental_field="date",+ partition_key="date",+ ordering="date",+ required_scope="incidents:read",+ incremental_lookback=timedelta(days=7),+ resumable=True,+ incremental_fields=_DATE_INCREMENTAL_FIELD,+ ),+ # Monitored sources (repositories etc.): a mutable perimeter snapshot (health, open incident+ # counts, last scan) with no creation timestamp or server-side time filter, so full refresh.+ "sources": GitGuardianEndpointConfig(+ name="sources",+ path="/v1/sources",+ required_scope="sources:read",+ incremental_fields=[],+ ),+ # Honeytokens: a small config-and-status table (status / triggered_at / revoked_at mutate),+ # so full refresh.+ "honeytokens": GitGuardianEndpointConfig(+ name="honeytokens",+ path="/v1/honeytokens",+ required_scope="honeytokens:read",+ incremental_fields=[],+ ),+ # Workspace members: small mutable directory (role, last_login), full refresh.+ "members": GitGuardianEndpointConfig(+ name="members",+ path="/v1/members",+ required_scope="members:read",+ incremental_fields=[],+ ),+ # Teams: small mutable directory, full refresh.+ "teams": GitGuardianEndpointConfig(+ name="teams",+ path="/v1/teams",+ required_scope="teams:read",+ incremental_fields=[],+ ),+}++ENDPOINTS = tuple(GITGUARDIAN_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in GITGUARDIAN_ENDPOINTS.items()+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gitguardian/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gitguardian/source.pyindex 4a39cee366c3..4c75f1520785 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/gitguardian/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gitguardian/source.py@@ -1,30 +1,201 @@-from typing import cast+from typing import Optional, cast+from urllib.parse import urlsplitfrom 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.mixins import _is_host_safefrom 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 GitguardianSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.gitguardian.gitguardian import (+ GitGuardianResumeConfig,+ check_endpoint_access,+ gitguardian_source,+ resolve_base_url,+ validate_base_url,+ validate_credentials as validate_gitguardian_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.gitguardian.settings import (+ ENDPOINTS,+ GITGUARDIAN_ENDPOINTS,+ INCREMENTAL_FIELDS,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class GitguardianSource(SimpleSource[GitguardianSourceConfig]):+class GitguardianSource(ResumableSource[GitguardianSourceConfig, GitGuardianResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.GITGUARDIAN+ @property+ def connection_host_fields(self) -> list[str]:+ # The API token is sent to whatever `base_url` points at, so retargeting it must re-require+ # the secret — otherwise the preserved token could be exfiltrated to an attacker-controlled host.+ return ["base_url"]+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.GITGUARDIAN,category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,label="GitGuardian",+ releaseStatus=ReleaseStatus.ALPHA,+ caption="""Enter a GitGuardian API token to sync your secret incidents, occurrences, monitored sources, honeytokens, members, and teams into the PostHog Data warehouse.++Create a service account token (recommended for unattended syncs) or a personal access token in your [GitGuardian API settings](https://dashboard.gitguardian.com/api). Grant the read scopes for the tables you want to sync: `incidents:read`, `sources:read`, `honeytokens:read`, `members:read`, and `teams:read`. Reading incidents requires a token with at least the Manager access level.++Workspaces on the EU instance should set the API URL to `https://api.eu1.gitguardian.com`; self-hosted instances should enter their own API URL.+""",iconPath="/static/services/gitguardian.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/gitguardian",+ keywords=["secrets", "secret scanning", "code security", "honeytoken"],+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API token",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="gg_sat_... or gg_pat_...",+ secret=True,+ ),+ SourceFieldInputConfig(+ name="base_url",+ label="API URL (EU or self-hosted only)",+ type=SourceFieldInputConfigType.TEXT,+ required=False,+ placeholder="https://api.gitguardian.com",+ secret=False,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.gitguardian.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ # An invalid or revoked token surfaces as a requests HTTPError when `_fetch_page` calls+ # `raise_for_status()`. Retrying can never satisfy a credential problem, so stop the+ # sync. The base host varies for EU/self-hosted instances, so match the stable status+ # text only.+ "401 Client Error": "Your GitGuardian API token is invalid or has been revoked. Create a new token in your GitGuardian API settings, then reconnect.",+ "403 Client Error": "Your GitGuardian API token is missing a required scope or access level for this data. Grant the required read scopes (and Manager access level for incidents), then reconnect.",+ }++ def get_schemas(+ self,+ config: GitguardianSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ def _build_schema(endpoint: str) -> SourceSchema:+ has_incremental = bool(INCREMENTAL_FIELDS.get(endpoint))+ return SourceSchema(+ name=endpoint,+ supports_incremental=has_incremental,+ supports_append=has_incremental,+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),+ should_sync_default=GITGUARDIAN_ENDPOINTS[endpoint].should_sync_default,+ )++ schemas = [_build_schema(endpoint) for endpoint in ENDPOINTS]+ if names is not None:+ names_set = set(names)+ schemas = [s for s in schemas if s.name in names_set]+ return schemas++ def _check_base_url(self, config: GitguardianSourceConfig, team_id: int) -> tuple[str, str | None]:+ """Resolve and safety-check the base URL. Returns (base_url, error)."""+ base_url = resolve_base_url(config.base_url)+ url_error = validate_base_url(base_url)+ if url_error:+ return base_url, url_error+ host = urlsplit(base_url).hostname or ""+ host_ok, host_error = _is_host_safe(host, team_id)+ if not host_ok:+ return base_url, host_error or "GitGuardian host is not allowed"+ return base_url, None++ def validate_credentials(+ self, config: GitguardianSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ base_url, error = self._check_base_url(config, team_id)+ if error:+ return False, error+ if schema_name is not None and schema_name in GITGUARDIAN_ENDPOINTS:+ # Per-schema check: confirm the token's scopes actually cover this endpoint.+ reason = check_endpoint_access(config.api_key, base_url, schema_name)+ if reason:+ return False, reason+ return True, None+ # Source-create check: one cheap scope-free probe confirming the token is genuine. Missing+ # scopes surface per table via get_endpoint_permissions instead of blocking the source.+ return validate_gitguardian_credentials(config.api_key, base_url)++ def get_endpoint_permissions(+ self, config: GitguardianSourceConfig, team_id: int, endpoints: list[str]+ ) -> dict[str, str | None]:+ base_url, error = self._check_base_url(config, team_id)+ if error:+ return dict.fromkeys(endpoints, error)+ return {+ endpoint: check_endpoint_access(config.api_key, base_url, endpoint)+ if endpoint in GITGUARDIAN_ENDPOINTS+ else None+ for endpoint in endpoints+ }++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[GitGuardianResumeConfig]:+ return ResumableSourceManager[GitGuardianResumeConfig](inputs, GitGuardianResumeConfig)++ def source_for_pipeline(+ self,+ config: GitguardianSourceConfig,+ resumable_source_manager: ResumableSourceManager[GitGuardianResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ base_url, error = self._check_base_url(config, inputs.team_id)+ if error:+ raise ValueError(error)++ return gitguardian_source(+ api_key=config.api_key,+ base_url=base_url,+ 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/gitguardian/tests/test_gitguardian.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gitguardian/tests/test_gitguardian.pynew file mode 100644index 000000000000..037db6a5d6d1--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gitguardian/tests/test_gitguardian.py@@ -0,0 +1,393 @@+from datetime import UTC, date, datetime+from typing import Any+from urllib.parse import parse_qs, urlsplit++import pytest+from unittest.mock import MagicMock, patch++import requests+from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.sources.gitguardian import gitguardian+from products.warehouse_sources.backend.temporal.data_imports.sources.gitguardian.gitguardian import (+ GitGuardianResumeConfig,+ check_endpoint_access,+ get_rows,+ gitguardian_source,+ resolve_base_url,+ validate_base_url,+ validate_credentials,+)++BASE_URL = "https://api.gitguardian.com"+++def _page(rows: Any, next_url: str | None = None) -> MagicMock:+ response = MagicMock()+ response.json.return_value = rows+ response.links = {"next": {"url": next_url}} if next_url else {}+ return response+++class _FakeManager:+ def __init__(self, state: GitGuardianResumeConfig | None = None) -> None:+ self._state = state+ self.saved: list[GitGuardianResumeConfig] = []+ self.cleared = False++ def can_resume(self) -> bool:+ return self._state is not None++ def load_state(self) -> GitGuardianResumeConfig | None:+ return self._state++ def save_state(self, data: GitGuardianResumeConfig) -> None:+ self.saved.append(data)++ def clear_state(self) -> None:+ self.cleared = True+++def _run_get_rows(+ monkeypatch: Any,+ endpoint: str,+ responses: list[MagicMock],+ manager: _FakeManager | None = None,+ **kwargs: Any,+) -> tuple[list[dict], list[str], _FakeManager]:+ fetched: list[str] = []+ resp_iter = iter(responses)++ def fake_fetch(session: Any, url: str, headers: dict[str, str], logger: Any) -> MagicMock:+ fetched.append(url)+ return next(resp_iter)++ monkeypatch.setattr(gitguardian, "_fetch_page", fake_fetch)+ monkeypatch.setattr(gitguardian, "make_tracked_session", lambda *a, **k: MagicMock())++ manager = manager or _FakeManager()+ rows: list[dict] = []+ for page in get_rows(+ api_key="gg_sat_x",+ base_url=BASE_URL,+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=manager, # type: ignore[arg-type]+ **kwargs,+ ):+ rows.extend(page)+ return rows, fetched, manager+++def _query(url: str) -> dict[str, list[str]]:+ return parse_qs(urlsplit(url).query)+++class TestResolveBaseUrl:+ @parameterized.expand(+ [+ ("blank", None, "https://api.gitguardian.com"),+ ("empty", "", "https://api.gitguardian.com"),+ ("trailing_slash", "https://api.eu1.gitguardian.com/", "https://api.eu1.gitguardian.com"),+ (+ "self_hosted_path_prefix",+ "https://gitguardian.acme.internal/exposed",+ "https://gitguardian.acme.internal/exposed",+ ),+ ]+ )+ def test_resolve(self, _name: str, given: str | None, expected: str) -> None:+ assert resolve_base_url(given) == expected+++class TestValidateBaseUrl:+ @parameterized.expand(+ [+ ("default", "https://api.gitguardian.com"),+ ("self_hosted_https", "https://gitguardian.acme.dev"),+ ]+ )+ def test_https_urls_pass(self, _name: str, base_url: str) -> None:+ assert validate_base_url(base_url) is None++ @parameterized.expand(+ [+ # Plaintext would send the secret token in the clear.+ ("http", "http://gitguardian.acme.dev"),+ # `urlsplit` reads the host as example.com, but requests connects to 169.254.169.254.+ ("backslash_authority_confusion", "https://169.254.169.254\\@example.com"),+ ]+ )+ def test_unsafe_urls_are_rejected(self, _name: str, base_url: str) -> None:+ assert validate_base_url(base_url) is not None+++class TestLinkHeaderPagination:+ def test_walks_pages_until_link_header_exhausted(self, monkeypatch: Any) -> None:+ # The next-page cursor lives in the Link header; the walk must follow it and stop when absent.+ next_url = f"{BASE_URL}/v1/incidents/secrets?cursor=abc&per_page=100&ordering=date"+ responses = [+ _page([{"id": 1}, {"id": 2}], next_url=next_url),+ _page([{"id": 3}]),+ ]+ rows, fetched, _ = _run_get_rows(monkeypatch, "secret_incidents", responses)+ assert [r["id"] for r in rows] == [1, 2, 3]+ assert fetched == [f"{BASE_URL}/v1/incidents/secrets?per_page=100&ordering=date", next_url]++ def test_first_sync_sends_ordering_but_no_date_filter(self, monkeypatch: Any) -> None:+ # No watermark => full backfill, but ordering must still be explicit so sort_mode="asc" holds.+ responses = [_page([{"id": 1}])]+ _, fetched, _ = _run_get_rows(+ monkeypatch,+ "secret_incidents",+ responses,+ should_use_incremental_field=True,+ db_incremental_field_last_value=None,+ )+ query = _query(fetched[0])+ assert query["ordering"] == ["date"]+ assert "date_after" not in query++ def test_incremental_sends_date_after_with_lookback(self, monkeypatch: Any) -> None:+ # The watermark must reach the server as date_after (minus the safety lookback), otherwise+ # every "incremental" sync silently re-fetches all history.+ responses = [_page([{"id": 1}])]+ _, fetched, _ = _run_get_rows(+ monkeypatch,+ "secret_incidents",+ responses,+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 1, 10, tzinfo=UTC),+ incremental_field="date",+ )+ assert _query(fetched[0])["date_after"] == ["2026-01-03T00:00:00Z"]++ @parameterized.expand(+ [+ ("naive_datetime", datetime(2026, 1, 10), "2026-01-03T00:00:00Z"),+ ("date_value", date(2026, 1, 10), "2026-01-03T00:00:00Z"),+ ]+ )+ def test_incremental_value_types_are_formatted_utc(self, _name: str, value: Any, expected: str) -> None:+ responses = [_page([{"id": 1}])]+ with pytest.MonkeyPatch.context() as monkeypatch:+ _, fetched, _ = _run_get_rows(+ monkeypatch,+ "secret_incidents",+ responses,+ should_use_incremental_field=True,+ db_incremental_field_last_value=value,+ )+ assert _query(fetched[0])["date_after"] == [expected]++ def test_cross_origin_next_link_is_refused(self, monkeypatch: Any) -> None:+ # Pagination URLs are fetched with the Authorization token attached; a tampered Link+ # header must not be able to steer the token to another host.+ responses = [_page([{"id": 1}], next_url="https://attacker.example/v1/incidents/secrets?cursor=abc")]+ with pytest.raises(ValueError, match="cross-origin"):+ _run_get_rows(monkeypatch, "secret_incidents", responses)++ def test_non_list_response_raises_instead_of_yielding_garbage(self, monkeypatch: Any) -> None:+ responses = [_page({"detail": "Not found."})]+ with pytest.raises(ValueError, match="non-list response"):+ _run_get_rows(monkeypatch, "secret_incidents", responses)++ def test_share_url_bearer_link_is_stripped_before_yield(self, monkeypatch: Any) -> None:+ # share_url is a no-auth bearer link that can expose the leaked secret itself; it must+ # never reach the warehouse. Other fields survive.+ responses = [+ _page([{"id": 1, "share_url": "https://dashboard.gitguardian.com/share/xyz", "date": "2026-01-01"}])+ ]+ rows, _, _ = _run_get_rows(monkeypatch, "secret_incidents", responses)+ assert rows == [{"id": 1, "date": "2026-01-01"}]+++class TestResumeCheckpoints:+ def test_resumes_from_saved_url(self, monkeypatch: Any) -> None:+ saved_url = f"{BASE_URL}/v1/incidents/secrets?cursor=abc&per_page=100"+ manager = _FakeManager(GitGuardianResumeConfig(url=saved_url))+ responses = [_page([{"id": 4}])]+ rows, fetched, _ = _run_get_rows(monkeypatch, "secret_incidents", responses, manager=manager)+ assert [r["id"] for r in rows] == [4]+ assert fetched == [saved_url]++ def test_cross_origin_resume_url_is_refused(self, monkeypatch: Any) -> None:+ # Resume URLs come from persisted state; a tampered value must not receive the token either.+ manager = _FakeManager(GitGuardianResumeConfig(url="https://attacker.example/v1/incidents/secrets?cursor=abc"))+ with pytest.raises(ValueError, match="cross-origin"):+ _run_get_rows(monkeypatch, "secret_incidents", [], manager=manager)++ def test_checkpoints_current_page_url_after_yield_and_clears_on_completion(self, monkeypatch: Any) -> None:+ # Resume must re-fetch the last yielded page (checkpoint the CURRENT URL, not the next one)+ # so a crash can't skip rows, and a finished walk must drop its checkpoint or a retry that+ # re-runs extract would resume from the final page and skip everything before it.+ next_url = f"{BASE_URL}/v1/incidents/secrets?cursor=abc&per_page=100"+ responses = [+ _page([{"id": 1}], next_url=next_url),+ _page([{"id": 2}]),+ ]+ _, fetched, manager = _run_get_rows(monkeypatch, "secret_incidents", responses)+ assert [s.url for s in manager.saved] == fetched+ assert manager.cleared is True++ def test_full_refresh_endpoints_never_checkpoint(self, monkeypatch: Any) -> None:+ # sources/members/teams merge nothing on resume, so a restart re-reads from page one.+ responses = [_page([{"id": 1}])]+ _, _, manager = _run_get_rows(monkeypatch, "sources", responses)+ assert manager.saved == []+ assert manager.cleared is False++ def test_full_refresh_endpoints_ignore_stale_resume_state(self, monkeypatch: Any) -> None:+ manager = _FakeManager(GitGuardianResumeConfig(url=f"{BASE_URL}/v1/sources?cursor=zzz"))+ responses = [_page([{"id": 1}])]+ _, fetched, _ = _run_get_rows(monkeypatch, "sources", responses, manager=manager)+ assert fetched == [f"{BASE_URL}/v1/sources?per_page=100"]+++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_valid: bool) -> None:+ response = MagicMock()+ response.status_code = status_code+ session = MagicMock()+ session.get.return_value = response+ with patch.object(gitguardian, "make_tracked_session", return_value=session):+ valid, error = validate_credentials("gg_sat_x", BASE_URL)+ assert valid is expected_valid+ assert (error is None) is expected_valid++ def test_network_error_is_invalid_not_raised(self) -> None:+ session = MagicMock()+ session.get.side_effect = requests.ConnectionError("boom")+ with patch.object(gitguardian, "make_tracked_session", return_value=session):+ valid, error = validate_credentials("gg_sat_x", BASE_URL)+ assert valid is False+ assert error is not None+++class TestCheckEndpointAccess:+ def _probe(self, response: MagicMock | Exception, endpoint: str = "secret_incidents") -> str | None:+ session = MagicMock()+ if isinstance(response, Exception):+ session.get.side_effect = response+ else:+ session.get.return_value = response+ with patch.object(gitguardian, "make_tracked_session", return_value=session):+ return check_endpoint_access("gg_sat_x", BASE_URL, endpoint)++ def test_reachable_endpoint_reports_no_error(self) -> None:+ response = MagicMock()+ response.status_code = 200+ assert self._probe(response) is None++ def test_denial_surfaces_the_apis_own_detail_message(self) -> None:+ response = MagicMock()+ response.status_code = 403+ response.json.return_value = {"detail": "You do not have the required incidents:read scope."}+ assert self._probe(response) == "You do not have the required incidents:read scope."++ @parameterized.expand(+ [+ ("secret_incidents", "incidents:read"),+ ("sources", "sources:read"),+ ("honeytokens", "honeytokens:read"),+ ]+ )+ def test_denial_without_detail_names_the_required_scope(self, endpoint: str, scope: str) -> None:+ response = MagicMock()+ response.status_code = 403+ response.json.side_effect = ValueError("no json")+ reason = self._probe(response, endpoint=endpoint)+ assert reason is not None and scope in reason++ @parameterized.expand(+ [+ ("throttle", 429),+ ("server_error", 500),+ ]+ )+ def test_non_denial_errors_do_not_block_the_table(self, _name: str, status_code: int) -> None:+ # Only a real 401/403 is a missing scope; a throttle or blip must not mark the table+ # unreachable in the schema picker.+ response = MagicMock()+ response.status_code = status_code+ assert self._probe(response) is None++ def test_network_error_does_not_block_the_table(self) -> None:+ assert self._probe(requests.ConnectionError("boom")) is None+++class TestFetchPageRetries:+ @parameterized.expand(+ [+ ("rate_limited", 429),+ ("server_error", 503),+ ]+ )+ def test_retryable_status_is_retried(self, _name: str, status_code: int) -> None:+ bad = MagicMock()+ bad.status_code = status_code+ good = MagicMock()+ good.status_code = 200+ good.ok = True+ session = MagicMock()+ session.get.side_effect = [bad, good]++ with patch.object(gitguardian._fetch_page.retry, "sleep", lambda *_: None): # type: ignore[attr-defined]+ result = gitguardian._fetch_page(session, f"{BASE_URL}/v1/incidents/secrets", {}, MagicMock())++ assert result is good+ assert session.get.call_count == 2++ def test_unauthorized_raises_and_is_not_retried(self) -> None:+ response = MagicMock()+ response.status_code = 401+ response.ok = False+ response.raise_for_status.side_effect = requests.HTTPError("401 Client Error: Unauthorized", response=response)+ session = MagicMock()+ session.get.return_value = response++ with pytest.raises(requests.HTTPError):+ gitguardian._fetch_page(session, f"{BASE_URL}/v1/incidents/secrets", {}, MagicMock())+ assert session.get.call_count == 1+++class TestSourceResponseShape:+ @parameterized.expand(+ [+ ("secret_incidents", ["date"]),+ ("secret_occurrences", ["date"]),+ ]+ )+ def test_incremental_endpoints_partition_on_stable_detection_date(+ self, endpoint: str, expected_partition: list[str]+ ) -> None:+ response = gitguardian_source(+ api_key="gg_sat_x",+ base_url=BASE_URL,+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=MagicMock(),+ )+ assert response.partition_keys == expected_partition+ assert response.primary_keys == ["id"]+ assert response.sort_mode == "asc"++ @parameterized.expand([("sources",), ("honeytokens",), ("members",), ("teams",)])+ def test_full_refresh_endpoints_are_unpartitioned(self, endpoint: str) -> None:+ response = gitguardian_source(+ api_key="gg_sat_x",+ base_url=BASE_URL,+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=MagicMock(),+ )+ assert response.partition_mode is None+ assert response.partition_keys is Nonediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gitguardian/tests/test_gitguardian_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gitguardian/tests/test_gitguardian_source.pynew file mode 100644index 000000000000..c6a2c5567ae6--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gitguardian/tests/test_gitguardian_source.py@@ -0,0 +1,201 @@+from unittest.mock import MagicMock, patch++from parameterized import parameterized++from posthog.schema import SourceFieldInputConfig++from products.warehouse_sources.backend.temporal.data_imports.sources.gitguardian import source as source_module+from products.warehouse_sources.backend.temporal.data_imports.sources.gitguardian.gitguardian import (+ GitGuardianResumeConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.gitguardian.source import GitguardianSource+from products.warehouse_sources.backend.types import ExternalDataSourceType++ALL_ENDPOINTS = {"secret_incidents", "secret_occurrences", "sources", "honeytokens", "members", "teams"}+++class TestGitguardianSourceConfig:+ def test_source_type(self) -> None:+ assert GitguardianSource().source_type == ExternalDataSourceType.GITGUARDIAN++ def test_fields_require_secret_token_and_optional_base_url(self) -> None:+ fields = {f.name: f for f in GitguardianSource().get_source_config.fields}+ api_key, base_url = fields["api_key"], fields["base_url"]+ assert isinstance(api_key, SourceFieldInputConfig)+ assert isinstance(base_url, SourceFieldInputConfig)+ assert api_key.required is True+ assert api_key.secret is True+ assert base_url.required is False+ assert base_url.secret is False++ def test_base_url_is_a_connection_host_field(self) -> None:+ # Retargeting base_url must re-require the secret, else the preserved token leaks to a new host.+ assert GitguardianSource().connection_host_fields == ["base_url"]++ def test_lists_tables_without_credentials(self) -> None:+ # Static endpoint catalog with no I/O, so public docs can render the table list.+ assert GitguardianSource.lists_tables_without_credentials is True+++class TestGitguardianSchemas:+ def test_incident_endpoints_are_incremental_and_directories_are_full_refresh(self) -> None:+ schemas = {s.name: s for s in GitguardianSource().get_schemas(MagicMock(), team_id=1)}+ assert set(schemas) == ALL_ENDPOINTS+ for name in ("secret_incidents", "secret_occurrences"):+ assert schemas[name].supports_incremental is True+ assert [f["field"] for f in schemas[name].incremental_fields] == ["date"]+ for name in ("sources", "honeytokens", "members", "teams"):+ assert schemas[name].supports_incremental is False++ def test_names_filter(self) -> None:+ schemas = GitguardianSource().get_schemas(MagicMock(), team_id=1, names=["teams"])+ assert [s.name for s in schemas] == ["teams"]+++class TestNonRetryableErrors:+ @parameterized.expand(+ [+ (+ "unauthorized",+ "401 Client Error: Unauthorized for url: https://api.gitguardian.com/v1/incidents/secrets",+ ),+ ("forbidden", "403 Client Error: Forbidden for url: https://gitguardian.acme.dev/v1/sources"),+ ]+ )+ def test_credential_errors_are_non_retryable(self, _name: str, observed: str) -> None:+ errors = GitguardianSource().get_non_retryable_errors()+ assert any(key in observed for key in errors)++ @parameterized.expand(+ [+ ("read_timeout", "HTTPSConnectionPool(host='api.gitguardian.com', port=443): Read timed out."),+ ("server_error", "500 Server Error: Internal Server Error"),+ ("rate_limited", "429 Client Error: Too Many Requests"),+ ]+ )+ def test_transient_errors_remain_retryable(self, _name: str, observed: str) -> None:+ errors = GitguardianSource().get_non_retryable_errors()+ assert not any(key in observed for key in errors)+++class TestValidateCredentials:+ def test_blocks_unsafe_host_before_probing(self) -> None:+ # An internal/private base_url must be rejected without an outbound request being made.+ config = MagicMock(api_key="gg_sat_x", base_url="https://169.254.169.254")+ with (+ patch.object(source_module, "_is_host_safe", return_value=(False, "internal IP blocked")) as host_check,+ patch.object(source_module, "validate_gitguardian_credentials") as probe,+ ):+ valid, error = GitguardianSource().validate_credentials(config, team_id=1)+ assert valid is False+ assert error == "internal IP blocked"+ host_check.assert_called_once()+ probe.assert_not_called()++ def test_rejects_plaintext_base_url_before_probing(self) -> None:+ # A non-HTTPS URL would leak the token; reject it without any outbound request.+ config = MagicMock(api_key="gg_sat_x", base_url="http://gitguardian.acme.dev")+ with patch.object(source_module, "validate_gitguardian_credentials") as probe:+ valid, error = GitguardianSource().validate_credentials(config, team_id=1)+ assert valid is False+ assert error is not None+ probe.assert_not_called()++ def test_source_create_uses_the_scope_free_health_probe(self) -> None:+ config = MagicMock(api_key="gg_sat_x", base_url=None)+ with (+ patch.object(source_module, "_is_host_safe", return_value=(True, None)),+ patch.object(source_module, "validate_gitguardian_credentials", return_value=(True, None)) as probe,+ ):+ valid, error = GitguardianSource().validate_credentials(config, team_id=1)+ assert valid is True+ assert error is None+ # Blank base_url resolves to the hosted API URL before probing.+ probe.assert_called_once_with("gg_sat_x", "https://api.gitguardian.com")++ @parameterized.expand(+ [+ ("reachable", None, True),+ ("missing_scope", "missing the `incidents:read` scope", False),+ ]+ )+ def test_per_schema_check_probes_that_endpoint(self, _name: str, reason: str | None, expected: bool) -> None:+ config = MagicMock(api_key="gg_sat_x", base_url=None)+ with (+ patch.object(source_module, "_is_host_safe", return_value=(True, None)),+ patch.object(source_module, "check_endpoint_access", return_value=reason) as probe,+ ):+ valid, error = GitguardianSource().validate_credentials(config, team_id=1, schema_name="secret_incidents")+ assert valid is expected+ assert error == reason+ probe.assert_called_once_with("gg_sat_x", "https://api.gitguardian.com", "secret_incidents")+++class TestGetEndpointPermissions:+ def test_maps_reachable_and_denied_endpoints(self) -> None:+ config = MagicMock(api_key="gg_sat_x", base_url=None)+ with (+ patch.object(source_module, "_is_host_safe", return_value=(True, None)),+ patch.object(source_module, "check_endpoint_access", side_effect=[None, "missing scope"]),+ ):+ permissions = GitguardianSource().get_endpoint_permissions(+ config, team_id=1, endpoints=["secret_incidents", "honeytokens"]+ )+ assert permissions == {"secret_incidents": None, "honeytokens": "missing scope"}+++class TestSourceForPipeline:+ def test_plumbs_resolved_base_url_and_incremental_inputs(self) -> None:+ config = MagicMock(api_key="gg_sat_x", base_url="https://gitguardian.acme.dev/")+ inputs = MagicMock(+ schema_name="secret_incidents",+ team_id=1,+ should_use_incremental_field=True,+ db_incremental_field_last_value="2026-01-01T00:00:00Z",+ incremental_field="date",+ )+ with (+ patch.object(source_module, "_is_host_safe", return_value=(True, None)),+ patch.object(source_module, "gitguardian_source") as build,+ ):+ result = GitguardianSource().source_for_pipeline(config, MagicMock(), inputs)+ assert result is build.return_value+ kwargs = build.call_args.kwargs+ assert kwargs["base_url"] == "https://gitguardian.acme.dev"+ assert kwargs["endpoint"] == "secret_incidents"+ assert kwargs["should_use_incremental_field"] is True+ assert kwargs["db_incremental_field_last_value"] == "2026-01-01T00:00:00Z"++ def test_does_not_pass_watermark_when_not_incremental(self) -> None:+ config = MagicMock(api_key="gg_sat_x", base_url=None)+ inputs = MagicMock(+ schema_name="sources",+ team_id=1,+ should_use_incremental_field=False,+ db_incremental_field_last_value="2026-01-01T00:00:00Z",+ incremental_field=None,+ )+ with (+ patch.object(source_module, "_is_host_safe", return_value=(True, None)),+ patch.object(source_module, "gitguardian_source") as build,+ ):+ GitguardianSource().source_for_pipeline(config, MagicMock(), inputs)+ assert build.call_args.kwargs["db_incremental_field_last_value"] is None+++class TestResumableSourceManager:+ def test_returns_manager_bound_to_resume_config(self) -> None:+ manager = GitguardianSource().get_resumable_source_manager(MagicMock())+ assert manager._data_class is GitGuardianResumeConfig+++class TestGetDocumentedTables:+ def test_publishes_every_table_with_canonical_descriptions(self) -> None:+ # Guards the canonical_descriptions keys staying aligned with the endpoint names — a drifted+ # key silently drops that table's description from the public docs.+ tables = {t["name"]: t for t in GitguardianSource().get_documented_tables()}+ assert set(tables) == ALL_ENDPOINTS+ for name, table in tables.items():+ assert table["description"], f"{name} lost its canonical description"+ assert "Incremental" in tables["secret_incidents"]["sync_methods"]+ assert tables["sources"]["sync_methods"] == ["Full refresh"]