Skip to content

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

feat(data-warehouse): implement argocd import source (#71226)

Tom Owers560961c8dae2
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
index 145661cc5d3e..91acf4c97456 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -65,6 +65,7 @@ the row lists both.
| appfollow | HTTP | requests | ✅ |
| appsflyer | HTTP (CSV reports) | requests | ✅ |
| appsignal | HTTP (REST + GraphQL) | requests | ✅ |
+| argocd | HTTP | requests | ✅ |
| asana | HTTP | requests | ✅ |
| ashby | HTTP | requests | ✅ |
| asknicely | HTTP | requests | ✅ |
@@ -602,7 +603,6 @@ doesn't conflict with concurrent PRs.
- appstack
- apptivo
- appwrite
-- argocd
- asknicely
- auth0
- automox
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/argocd/argocd.py b/products/warehouse_sources/backend/temporal/data_imports/sources/argocd/argocd.py
new file mode 100644
index 000000000000..ba0c61c8ede8
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/argocd/argocd.py
@@ -0,0 +1,433 @@
+import re
+import json
+import time
+from collections.abc import Iterator
+from typing import Any, Optional
+from urllib.parse import urlencode, urlparse
+
+import requests
+from structlog.types import FilteringBoundLogger
+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+from urllib3.util.retry import Retry
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.argocd.settings import ARGOCD_ENDPOINTS
+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.mixins import _is_host_safe
+
+REQUEST_TIMEOUT_SECONDS = 120
+MAX_RETRIES = 5
+
+HOST_NOT_ALLOWED_ERROR = "Argo CD host is not allowed"
+HTTPS_REQUIRED_ERROR = "Argo CD host must use HTTPS"
+RESPONSE_TOO_LARGE_ERROR = "Argo CD API response exceeded the size limit"
+RESPONSE_TIMEOUT_ERROR = "Argo CD API response exceeded the download time limit"
+
+# The host is customer-controlled, so responses are streamed and read under a byte cap —
+# an arbitrarily large (or endless) 200 body must fail the sync instead of exhausting
+# worker memory. The cap applies to decoded bytes, so a gzip bomb can't slip past it.
+MAX_RESPONSE_BYTES = 512 * 1024 * 1024
+_READ_CHUNK_BYTES = 1024 * 1024
+
+# The per-read timeout only bounds the gap between chunks, so a server can trickle one byte
+# just before each read timeout and keep a worker occupied until the activity's 24h timeout.
+# A monotonic total-transfer deadline caps how long a single body read may take end to end,
+# independent of how the bytes are paced, so this slow-drip path fails the sync instead.
+MAX_RESPONSE_SECONDS = 600
+# Bytes read from an error body for a diagnostic message. Error bodies are never needed in
+# full, so only a short bounded snippet is ever pulled into memory.
+_ERROR_SNIPPET_BYTES = 2048
+
+# The applications list is fetched in one response, so batch the yielded rows to keep
+# downstream Arrow conversion working on bounded slices.
+_ROWS_PER_BATCH = 1000
+
+# Repository objects' credential fields are write-only in the Argo CD API, but drop them
+# defensively in case a server version ever echoes one back.
+_REPOSITORY_SECRET_FIELDS = (
+ "password",
+ "bearerToken",
+ "sshPrivateKey",
+ "tlsClientCertData",
+ "tlsClientCertKey",
+ "githubAppPrivateKey",
+ "gcpServiceAccountKey",
+)
+
+
+class ArgocdRetryableError(Exception):
+ pass
+
+
+class ArgocdHostNotAllowedError(Exception):
+ pass
+
+
+class ArgocdResponseTooLargeError(Exception):
+ pass
+
+
+class ArgocdResponseTimeoutError(Exception):
+ pass
+
+
+def _read_bounded(response: requests.Response, max_bytes: int, max_seconds: float = MAX_RESPONSE_SECONDS) -> bytes:
+ """Read a streamed response body under both a byte cap and a total-transfer deadline.
+
+ The deadline covers time spent waiting for each chunk, so a slow-drip body that stays
+ under the per-read timeout but never finishes is aborted instead of holding the worker.
+ """
+ total = 0
+ chunks: list[bytes] = []
+ deadline = time.monotonic() + max_seconds
+ for chunk in response.iter_content(chunk_size=_READ_CHUNK_BYTES):
+ total += len(chunk)
+ if total > max_bytes:
+ raise ArgocdResponseTooLargeError(f"{RESPONSE_TOO_LARGE_ERROR} ({max_bytes} bytes)")
+ if time.monotonic() > deadline:
+ raise ArgocdResponseTimeoutError(f"{RESPONSE_TIMEOUT_ERROR} ({max_seconds:g}s)")
+ chunks.append(chunk)
+ return b"".join(chunks)
+
+
+def _error_snippet(response: requests.Response) -> str:
+ try:
+ chunk = next(response.iter_content(chunk_size=_ERROR_SNIPPET_BYTES), b"")
+ return chunk[:_ERROR_SNIPPET_BYTES].decode("utf-8", errors="replace")
+ except Exception:
+ return ""
+
+
+def normalize_host(host: str | None) -> str:
+ """Turn whatever the user typed into an Argo CD base URL.
+
+ Accepts ``argocd.example.com``, ``https://argocd.example.com/``, or
+ ``https://argocd.example.com/api/v1`` and returns ``https://argocd.example.com``.
+ A path prefix is preserved (Argo CD can be served under a sub-path via ``--rootpath``).
+ """
+ host = (host or "").strip()
+ if not host:
+ return ""
+ if not re.match(r"^https?://", host, flags=re.IGNORECASE):
+ host = f"https://{host}"
+ host = host.rstrip("/")
+ host = re.sub(r"/api/v1$", "", host, flags=re.IGNORECASE)
+ return host.rstrip("/")
+
+
+def _host_only(host: str | None) -> str:
+ return (urlparse(normalize_host(host)).hostname or "").lower()
+
+
+def _has_ambiguous_authority(host: str | None) -> bool:
+ """True if ``urlparse`` and the HTTP client could disagree on the real host.
+
+ A backslash (raw or percent-encoded) or userinfo (``@``) in the authority lets the SSRF
+ check validate one host while the request reaches another: ``urlparse`` reads the host
+ after the ``@`` as the hostname, but a client that folds ``\\`` into ``/`` treats the part
+ before it as the host. A real Argo CD URL contains neither, so refuse both.
+ """
+ raw = host or ""
+ if "\\" in raw or "%5c" in raw.lower():
+ return True
+ return "@" in urlparse(normalize_host(host)).netloc
+
+
+def _is_https(host: str | None) -> bool:
+ # The API token rides in the Authorization header, so refuse plaintext HTTP to keep an
+ # on-path attacker from capturing it.
+ return urlparse(normalize_host(host)).scheme == "https"
+
+
+def _get_headers(api_token: str) -> dict[str, str]:
+ return {
+ "Authorization": f"Bearer {api_token}",
+ "Accept": "application/json",
+ }
+
+
+def _build_url(host: str | None, path: str, params: Optional[dict[str, Any]] = None) -> str:
+ url = f"{normalize_host(host)}{path}"
+ if params:
+ url = f"{url}?{urlencode(params)}"
+ return url
+
+
+def _list_params(endpoint: str, project: str | None) -> dict[str, Any]:
+ if endpoint not in ("applications", "deployment_history") or not project:
+ return {}
+ # The query param scoping the applications list is `projects` on current servers and
+ # `project` on older ones; grpc-gateway ignores whichever it doesn't know, so send both.
+ return {"project": project, "projects": project}
+
+
+def _items(data: Any) -> list[dict[str, Any]]:
+ # Kubernetes-style List: an empty collection marshals as `"items": null`, not `[]`.
+ if not isinstance(data, dict):
+ return []
+ items = data.get("items")
+ return items if isinstance(items, list) else []
+
+
+def _normalize_application(app: dict[str, Any]) -> dict[str, Any]:
+ metadata = app.get("metadata") or {}
+ spec = app.get("spec") or {}
+ status = app.get("status") or {}
+ # Lift identity, timing, and the two headline statuses to the top level so primary
+ # keys, partitioning, and common queries resolve against real columns.
+ return {
+ "name": metadata.get("name"),
+ "namespace": metadata.get("namespace"),
+ "uid": metadata.get("uid"),
+ "created_at": metadata.get("creationTimestamp"),
+ "project": spec.get("project"),
+ "sync_status": (status.get("sync") or {}).get("status"),
+ "health_status": (status.get("health") or {}).get("status"),
+ "metadata": metadata,
+ "spec": spec,
+ "status": status,
+ "operation": app.get("operation"),
+ }
+
+
+def _history_rows(app: dict[str, Any]) -> list[dict[str, Any]]:
+ metadata = app.get("metadata") or {}
+ spec = app.get("spec") or {}
+ status = app.get("status") or {}
+ return [
+ {
+ "application_name": metadata.get("name"),
+ "application_namespace": metadata.get("namespace"),
+ "application_uid": metadata.get("uid"),
+ "project": spec.get("project"),
+ "id": entry.get("id"),
+ "revision": entry.get("revision"),
+ "revisions": entry.get("revisions"),
+ "deployed_at": entry.get("deployedAt"),
+ "deploy_started_at": entry.get("deployStartedAt"),
+ "source": entry.get("source"),
+ "sources": entry.get("sources"),
+ "initiated_by": entry.get("initiatedBy"),
+ }
+ for entry in status.get("history") or []
+ if isinstance(entry, dict)
+ ]
+
+
+def _normalize_project(item: dict[str, Any]) -> dict[str, Any]:
+ metadata = item.get("metadata") or {}
+ return {
+ "name": metadata.get("name"),
+ "uid": metadata.get("uid"),
+ "created_at": metadata.get("creationTimestamp"),
+ "metadata": metadata,
+ "spec": item.get("spec"),
+ "status": item.get("status"),
+ }
+
+
+def _normalize_repository(item: dict[str, Any]) -> dict[str, Any]:
+ return {k: v for k, v in item.items() if k not in _REPOSITORY_SECRET_FIELDS}
+
+
+def _normalize_cluster(item: dict[str, Any]) -> dict[str, Any]:
+ # `config` holds the cluster connection credentials (bearer token, TLS client key);
+ # never persist it into the warehouse.
+ return {k: v for k, v in item.items() if k != "config"}
+
+
+@retry(
+ retry=retry_if_exception_type((ArgocdRetryableError, requests.ReadTimeout, requests.ConnectionError)),
+ stop=stop_after_attempt(MAX_RETRIES),
+ wait=wait_exponential_jitter(initial=1, max=30),
+ reraise=True,
+)
+def _fetch(session: requests.Session, url: str, headers: dict[str, str], logger: FilteringBoundLogger) -> Any:
+ # Don't follow redirects: the customer-controlled host could 3xx to an internal address,
+ # bypassing the host validation done before the request (SSRF). `stream=True` so bodies
+ # are only read through `_read_bounded` / `_error_snippet` under a byte cap.
+ with session.get(
+ url, headers=headers, timeout=REQUEST_TIMEOUT_SECONDS, allow_redirects=False, stream=True
+ ) as response:
+ if response.status_code == 429 or response.status_code >= 500:
+ raise ArgocdRetryableError(f"Argo CD API error (retryable): status={response.status_code}, url={url}")
+
+ if response.is_redirect or response.is_permanent_redirect:
+ raise ArgocdHostNotAllowedError(
+ f"Argo CD API returned an unexpected redirect (status={response.status_code}); refusing to follow it"
+ )
+
+ if not response.ok:
+ logger.error(
+ f"Argo CD API error: status={response.status_code}, body={_error_snippet(response)}, url={url}"
+ )
+ response.raise_for_status()
+
+ return json.loads(_read_bounded(response, MAX_RESPONSE_BYTES))
+
+
+def get_rows(
+ host: str,
+ api_token: str,
+ endpoint: str,
+ team_id: int,
+ logger: FilteringBoundLogger,
+ project: str | None = None,
+) -> Iterator[list[dict[str, Any]]]:
+ config = ARGOCD_ENDPOINTS[endpoint]
+
+ if _has_ambiguous_authority(host):
+ raise ArgocdHostNotAllowedError(HOST_NOT_ALLOWED_ERROR)
+
+ if not _is_https(host):
+ raise ArgocdHostNotAllowedError(HTTPS_REQUIRED_ERROR)
+
+ # Re-check at run time (not just at source-create) in case the host was edited or now
+ # resolves to an internal address (SSRF / DNS rebinding). Only enforced on cloud.
+ host_ok, host_err = _is_host_safe(_host_only(host), team_id)
+ if not host_ok:
+ raise ArgocdHostNotAllowedError(host_err or HOST_NOT_ALLOWED_ERROR)
+
+ # `capture=False`: raw cluster/repository responses carry credential fields the name-based
+ # sample scrubbers can't recognise (camelCase `bearerToken`, `sshPrivateKey`, ...) — they are
+ # stripped at row level, but must never reach HTTP sample capture either.
+ # `retry=Retry(total=0)`: `_fetch` owns the retry budget via tenacity; leaving the adapter's
+ # default retries on would nest under it, so a host that stalls each read could occupy a
+ # worker for adapter_attempts × tenacity_attempts × timeout.
+ session = make_tracked_session(redact_values=(api_token,), capture=False, retry=Retry(total=0))
+ url = _build_url(host, config.path, _list_params(endpoint, project))
+ data = _fetch(session, url, _get_headers(api_token), logger)
+ items = _items(data)
+
+ rows: list[dict[str, Any]]
+ if endpoint == "applications":
+ rows = [_normalize_application(item) for item in items]
+ elif endpoint == "deployment_history":
+ rows = [row for item in items for row in _history_rows(item)]
+ elif endpoint == "projects":
+ rows = [_normalize_project(item) for item in items]
+ elif endpoint == "repositories":
+ rows = [_normalize_repository(item) for item in items]
+ else:
+ rows = [_normalize_cluster(item) for item in items]
+
+ for i in range(0, len(rows), _ROWS_PER_BATCH):
+ yield rows[i : i + _ROWS_PER_BATCH]
+
+
+def validate_credentials(
+ host: str,
+ api_token: str,
+ schema_name: Optional[str] = None,
+ team_id: Optional[int] = None,
+ project: str | None = None,
+) -> tuple[bool, str | None]:
+ """Probe the API to confirm the token is genuine.
+
+ At source-create (``schema_name is None``) a 403 is accepted: the token is valid but its
+ RBAC may only grant the resources the user intends to sync. A scoped probe treats 403 as
+ a hard failure.
+ """
+ normalized = normalize_host(host)
+ hostname = (urlparse(normalized).hostname or "").lower()
+ if not normalized or not hostname:
+ return False, "Invalid Argo CD host"
+
+ if _has_ambiguous_authority(host):
+ return False, "Invalid Argo CD host"
+
+ if urlparse(normalized).scheme != "https":
+ return False, HTTPS_REQUIRED_ERROR
+
+ # The host is fully customer-controlled, so block hosts that resolve to private/internal
+ # addresses (SSRF). Only enforced on cloud — see _is_host_safe.
+ if team_id is not None:
+ host_ok, host_err = _is_host_safe(hostname, team_id)
+ if not host_ok:
+ return False, host_err or HOST_NOT_ALLOWED_ERROR
+
+ endpoint = schema_name if schema_name in ARGOCD_ENDPOINTS else "applications"
+ params = _list_params(endpoint, project)
+ if endpoint in ("applications", "deployment_history"):
+ # Filtering by a name that can't exist keeps the probe response tiny; servers that
+ # don't support the filter just return the full list, which is still a valid probe.
+ params = {**params, "name": "posthog-connectivity-probe"}
+
+ try:
+ # `capture=False` for the same reason as in `get_rows`: probe responses can carry
+ # credential fields the name-based sample scrubbers can't recognise. `stream=True`
+ # because the probe runs inline on the API thread and only ever needs the status —
+ # the body is never ingested beyond a short error snippet, so a huge response
+ # (e.g. an old server ignoring the name filter) can't buffer into memory.
+ # `retry=Retry(total=0)`: the probe runs inline on an API worker, so it takes a single
+ # attempt — the adapter's default retries would let a stalling host hold the worker for
+ # several timeouts instead of one.
+ response = make_tracked_session(redact_values=(api_token,), capture=False, retry=Retry(total=0)).get(
+ _build_url(normalized, ARGOCD_ENDPOINTS[endpoint].path, params),
+ headers=_get_headers(api_token),
+ timeout=30,
+ allow_redirects=False,
+ stream=True,
+ )
+ except requests.exceptions.SSLError:
+ return (
+ False,
+ "Could not verify the Argo CD server's TLS certificate. The server must present a publicly trusted certificate.",
+ )
+ except requests.exceptions.RequestException as e:
+ return False, f"Could not connect to the Argo CD server: {e}"
+
+ with response:
+ if response.is_redirect or response.is_permanent_redirect:
+ return False, HOST_NOT_ALLOWED_ERROR
+
+ if response.status_code == 200:
+ return True, None
+
+ if response.status_code == 401:
+ return False, "Invalid Argo CD API token"
+
+ if response.status_code == 403:
+ if schema_name is None:
+ # Valid token, missing RBAC for this probe — let source creation through.
+ return True, None
+ return False, f"Your Argo CD API token lacks the RBAC permissions required to sync '{schema_name}'"
+
+ if response.status_code == 429 or response.status_code >= 500:
+ return False, "The Argo CD server is temporarily unavailable. Please try again in a moment."
+
+ snippet = _error_snippet(response)
+ try:
+ body = json.loads(snippet)
+ return False, body.get("message") or body.get("error") or snippet
+ except Exception:
+ return False, snippet
+
+
+def argocd_source(
+ host: str,
+ api_token: str,
+ endpoint: str,
+ team_id: int,
+ logger: FilteringBoundLogger,
+ project: str | None = None,
+) -> SourceResponse:
+ config = ARGOCD_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ host=host,
+ api_token=api_token,
+ endpoint=endpoint,
+ team_id=team_id,
+ logger=logger,
+ project=project,
+ ),
+ 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,
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/argocd/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/argocd/canonical_descriptions.py
new file mode 100644
index 000000000000..90125b0d8524
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/argocd/canonical_descriptions.py
@@ -0,0 +1,76 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "applications": {
+ "description": "Argo CD applications with their sync state, health, and full desired/live specification.",
+ "docs_url": "https://argo-cd.readthedocs.io/en/stable/operator-manual/declarative-setup/#applications",
+ "columns": {
+ "name": "Name of the application.",
+ "namespace": "Kubernetes namespace the Application resource lives in (usually the Argo CD control-plane namespace).",
+ "uid": "Kubernetes UID of the Application resource; changes if the application is deleted and recreated.",
+ "created_at": "Timestamp the Application resource was created.",
+ "project": "Argo CD project the application belongs to.",
+ "sync_status": "Whether the live state matches the desired Git state (Synced, OutOfSync, or Unknown).",
+ "health_status": "Aggregated health of the application's resources (Healthy, Progressing, Degraded, Suspended, Missing, or Unknown).",
+ "metadata": "Full Kubernetes object metadata (labels, annotations, finalizers).",
+ "spec": "Desired application state: source repository, target revision, destination cluster/namespace, and sync policy.",
+ "status": "Observed application state: resources, conditions, sync/health details, and deployment history.",
+ "operation": "Currently requested sync operation, if one is in flight.",
+ },
+ },
+ "deployment_history": {
+ "description": "One row per recorded deployment, flattened from each application's status.history. Useful for DORA metrics such as deployment frequency.",
+ "docs_url": "https://argo-cd.readthedocs.io/en/stable/user-guide/commands/argocd_app_history/",
+ "columns": {
+ "application_name": "Name of the application that was deployed.",
+ "application_namespace": "Namespace of the Application resource.",
+ "application_uid": "Kubernetes UID of the Application resource.",
+ "project": "Argo CD project the application belongs to.",
+ "id": "History entry id, incremented per application on each deployment.",
+ "revision": "Git revision (commit SHA) that was deployed.",
+ "revisions": "Git revisions deployed, for applications with multiple sources.",
+ "deployed_at": "Timestamp the deployment finished.",
+ "deploy_started_at": "Timestamp the deployment started.",
+ "source": "Application source (repository URL, path, target revision) at deployment time.",
+ "sources": "Application sources at deployment time, for applications with multiple sources.",
+ "initiated_by": "Who or what triggered the deployment (user or automated sync).",
+ },
+ },
+ "projects": {
+ "description": "Argo CD projects (AppProject resources), which group applications and restrict their sources and destinations.",
+ "docs_url": "https://argo-cd.readthedocs.io/en/stable/user-guide/projects/",
+ "columns": {
+ "name": "Name of the project.",
+ "uid": "Kubernetes UID of the AppProject resource.",
+ "created_at": "Timestamp the project was created.",
+ "metadata": "Full Kubernetes object metadata (labels, annotations).",
+ "spec": "Project configuration: allowed source repositories, destinations, cluster resource whitelists, and roles.",
+ "status": "Observed project state, e.g. jwt token metadata per role.",
+ },
+ },
+ "repositories": {
+ "description": "Git and Helm repositories connected to Argo CD. Credential fields are never synced.",
+ "docs_url": "https://argo-cd.readthedocs.io/en/stable/user-guide/private-repositories/",
+ "columns": {
+ "repo": "Repository URL.",
+ "name": "Display name of the repository.",
+ "project": "Argo CD project the repository is scoped to, if any.",
+ "type": "Repository type (git or helm).",
+ "connectionState": "Result of Argo CD's most recent connectivity check for the repository.",
+ },
+ },
+ "clusters": {
+ "description": "Kubernetes clusters Argo CD deploys to. Connection credentials are never synced.",
+ "docs_url": "https://argo-cd.readthedocs.io/en/stable/operator-manual/declarative-setup/#clusters",
+ "columns": {
+ "server": "Kubernetes API server URL of the cluster.",
+ "name": "Display name of the cluster.",
+ "namespaces": "Namespaces Argo CD is allowed to manage in the cluster.",
+ "connectionState": "Result of Argo CD's most recent connectivity check for the cluster.",
+ "serverVersion": "Kubernetes version of the cluster.",
+ "info": "Cluster statistics such as application count and cache state.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/argocd/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/argocd/settings.py
new file mode 100644
index 000000000000..e9048ac03606
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/argocd/settings.py
@@ -0,0 +1,58 @@
+from dataclasses import dataclass
+
+from products.warehouse_sources.backend.types import IncrementalField
+
+
+@dataclass
+class ArgocdEndpointConfig:
+ name: str
+ path: str
+ primary_keys: list[str]
+ # Stable, immutable field to partition by (creation/deployment timestamps only).
+ partition_key: str | None = None
+
+
+# Argo CD's list APIs return the whole collection in one Kubernetes-style List response
+# (`{"items": [...]}`). There is no reliable pagination and no server-side timestamp
+# filter on any of them, so every endpoint is full refresh.
+ARGOCD_ENDPOINTS: dict[str, ArgocdEndpointConfig] = {
+ "applications": ArgocdEndpointConfig(
+ name="applications",
+ path="/api/v1/applications",
+ # With apps-in-any-namespace enabled, application names are only unique per namespace.
+ primary_keys=["namespace", "name"],
+ partition_key="created_at",
+ ),
+ "deployment_history": ArgocdEndpointConfig(
+ name="deployment_history",
+ # Flattened from each application's `status.history` — Argo CD has no standalone
+ # deployment-history API.
+ path="/api/v1/applications",
+ # History ids increment per application, so the key needs the parent identity.
+ primary_keys=["application_namespace", "application_name", "id"],
+ partition_key="deployed_at",
+ ),
+ "projects": ArgocdEndpointConfig(
+ name="projects",
+ path="/api/v1/projects",
+ # AppProjects are cluster-scoped in Argo CD, so the name is unique.
+ primary_keys=["name"],
+ partition_key="created_at",
+ ),
+ "repositories": ArgocdEndpointConfig(
+ name="repositories",
+ path="/api/v1/repositories",
+ primary_keys=["repo"],
+ ),
+ "clusters": ArgocdEndpointConfig(
+ name="clusters",
+ path="/api/v1/clusters",
+ primary_keys=["server"],
+ ),
+}
+
+ENDPOINTS = tuple(ARGOCD_ENDPOINTS.keys())
+
+# No endpoint exposes a server-side timestamp filter (the applications list has no
+# updated-since/created-since param), so nothing is advertised as incremental.
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {name: [] for name in ARGOCD_ENDPOINTS}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/argocd/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/argocd/source.py
index 3543b291435f..88adbb59a369 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/argocd/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/argocd/source.py
@@ -1,19 +1,44 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
DataWarehouseSourceCategory,
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
)
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (
+ SourceInputs,
+ SourceResponse,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.argocd.argocd import (
+ HOST_NOT_ALLOWED_ERROR,
+ HTTPS_REQUIRED_ERROR,
+ RESPONSE_TIMEOUT_ERROR,
+ RESPONSE_TOO_LARGE_ERROR,
+ argocd_source,
+ validate_credentials as validate_argocd_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.argocd.settings import (
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+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.schema import SourceSchema
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import ArgocdSourceConfig
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
class ArgocdSource(SimpleSource[ArgocdSourceConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.ARGOCD
@@ -23,8 +48,101 @@ class ArgocdSource(SimpleSource[ArgocdSourceConfig]):
return SourceConfig(
name=SchemaExternalDataSourceType.ARGOCD,
category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,
- label="Argo CD (Argo Project / CNCF)",
+ label="Argo CD",
+ keywords=["argo", "gitops", "kubernetes", "deployments"],
+ releaseStatus=ReleaseStatus.ALPHA,
+ caption="""Sync applications, deployment history, projects, repositories, and clusters from your Argo CD server, e.g. to track deployment frequency and rollback rates.
+
+Generate an API token with `argocd account generate-token`. The account needs the `apiKey` capability enabled and read access to the resources you want to sync, for example:
+- `applications, get`
+- `projects, get`
+- `repositories, get`
+- `clusters, get`
+
+Your Argo CD API server must be reachable from PostHog over HTTPS with a publicly trusted certificate — servers on a private network can't be synced.""",
iconPath="/static/services/argocd.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/argocd",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="host",
+ label="Argo CD server URL",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="https://argocd.example.com",
+ secret=False,
+ ),
+ SourceFieldInputConfig(
+ name="api_token",
+ label="API token",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ SourceFieldInputConfig(
+ name="project",
+ label="Project (optional)",
+ type=SourceFieldInputConfigType.TEXT,
+ required=False,
+ placeholder="Limit synced applications to one Argo CD project",
+ secret=False,
+ ),
+ ],
+ ),
+ )
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error": "Your Argo CD API token is invalid or expired. Please generate a new token and reconnect.",
+ "403 Client Error": "Your Argo CD API token lacks the required RBAC permissions. Please check the account's RBAC policy and try again.",
+ HOST_NOT_ALLOWED_ERROR: "The Argo CD host is not allowed. Please use your own Argo CD server's public URL.",
+ HTTPS_REQUIRED_ERROR: "The Argo CD server URL must use HTTPS.",
+ RESPONSE_TOO_LARGE_ERROR: "The Argo CD API response was too large to sync. Use the project field to limit which applications are synced.",
+ RESPONSE_TIMEOUT_ERROR: "The Argo CD API took too long to send its response. Check the server's health, or use the project field to limit which applications are synced.",
+ }
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.argocd.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_schemas(
+ self,
+ config: ArgocdSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ schemas = [
+ SourceSchema(
+ name=endpoint,
+ supports_incremental=False,
+ supports_append=False,
+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),
+ )
+ for endpoint in ENDPOINTS
+ ]
+ if names is not None:
+ names_set = set(names)
+ schemas = [s for s in schemas if s.name in names_set]
+ return schemas
+
+ def validate_credentials(
+ self, config: ArgocdSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ return validate_argocd_credentials(config.host, config.api_token, schema_name, team_id, config.project)
+
+ def source_for_pipeline(self, config: ArgocdSourceConfig, inputs: SourceInputs) -> SourceResponse:
+ return argocd_source(
+ host=config.host,
+ api_token=config.api_token,
+ endpoint=inputs.schema_name,
+ team_id=inputs.team_id,
+ logger=inputs.logger,
+ project=config.project,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/argocd/tests/test_argocd.py b/products/warehouse_sources/backend/temporal/data_imports/sources/argocd/tests/test_argocd.py
new file mode 100644
index 000000000000..8d9e57e54740
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/argocd/tests/test_argocd.py
@@ -0,0 +1,490 @@
+import json
+from typing import Any, Optional
+
+import pytest
+from unittest import mock
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.argocd import argocd as argocd_module
+from products.warehouse_sources.backend.temporal.data_imports.sources.argocd.argocd import (
+ HOST_NOT_ALLOWED_ERROR,
+ HTTPS_REQUIRED_ERROR,
+ ArgocdHostNotAllowedError,
+ ArgocdResponseTimeoutError,
+ ArgocdResponseTooLargeError,
+ _has_ambiguous_authority,
+ _history_rows,
+ _items,
+ _list_params,
+ _normalize_application,
+ _normalize_cluster,
+ _normalize_repository,
+ argocd_source,
+ get_rows,
+ normalize_host,
+ validate_credentials,
+)
+
+APPLICATION = {
+ "metadata": {
+ "name": "guestbook",
+ "namespace": "argocd",
+ "uid": "uid-1",
+ "creationTimestamp": "2025-01-01T00:00:00Z",
+ },
+ "spec": {"project": "default", "source": {"repoURL": "https://github.com/org/repo"}},
+ "status": {
+ "sync": {"status": "Synced"},
+ "health": {"status": "Healthy"},
+ "history": [
+ {"id": 1, "revision": "abc", "deployedAt": "2025-01-02T00:00:00Z", "deployStartedAt": None},
+ {"id": 2, "revision": "def", "deployedAt": "2025-01-03T00:00:00Z", "initiatedBy": {"username": "jane"}},
+ ],
+ },
+}
+
+
+def _response(*, status_code: int = 200, json_data: Any = None, text: str = "") -> mock.MagicMock:
+ response = mock.MagicMock()
+ response.status_code = status_code
+ response.ok = 200 <= status_code < 400
+ response.is_redirect = status_code in (302, 303, 307)
+ response.is_permanent_redirect = status_code in (301, 308)
+ response.headers = {}
+ # Bodies are streamed and read through iter_content, never .text / .json().
+ body = json.dumps(json_data).encode() if json_data is not None else text.encode()
+ response.iter_content = mock.Mock(side_effect=lambda chunk_size: iter([body] if body else []))
+ response.__enter__ = mock.Mock(return_value=response)
+ response.__exit__ = mock.Mock(return_value=False)
+ return response
+
+
+def _patch_session(response: Optional[mock.MagicMock] = None, raises: Optional[Exception] = None):
+ session = mock.MagicMock()
+ if raises is not None:
+ session.get.side_effect = raises
+ else:
+ session.get.return_value = response
+ return mock.patch.object(argocd_module, "make_tracked_session", return_value=session)
+
+
+class TestNormalizeHost:
+ @pytest.mark.parametrize(
+ "raw, expected",
+ [
+ ("argocd.example.com", "https://argocd.example.com"),
+ ("https://argocd.example.com/", "https://argocd.example.com"),
+ (" https://argocd.example.com ", "https://argocd.example.com"),
+ ("https://argocd.example.com/api/v1", "https://argocd.example.com"),
+ # A sub-path deployment (server --rootpath) must be preserved.
+ ("https://example.com/argocd", "https://example.com/argocd"),
+ ("http://argocd.internal", "http://argocd.internal"),
+ ("", ""),
+ (None, ""),
+ ],
+ )
+ def test_normalize_host(self, raw, expected):
+ assert normalize_host(raw) == expected
+
+
+class TestAmbiguousAuthority:
+ @pytest.mark.parametrize(
+ "host, ambiguous",
+ [
+ ("https://argocd.example.com", False),
+ ("https://argocd.example.com/api/v1", False),
+ # Backslash + userinfo: urlparse says public.example, a `\`→`/` client says internal.
+ ("https://internal.example\\@public.example", True),
+ # Percent-encoded backslash hides the same trick from urlparse.
+ ("https://internal.example%[email protected]", True),
+ # Plain userinfo is never valid for an Argo CD URL and muddies the authority.
+ ("https://[email protected]", True),
+ ],
+ )
+ def test_flags_parser_mismatches(self, host, ambiguous):
+ assert _has_ambiguous_authority(host) is ambiguous
+
+
+class TestListParams:
+ @pytest.mark.parametrize("endpoint", ["applications", "deployment_history"])
+ def test_project_scoping_sends_both_param_spellings(self, endpoint):
+ params = _list_params(endpoint, "team-a")
+ assert params == {"project": "team-a", "projects": "team-a"}
+
+ @pytest.mark.parametrize("endpoint", ["projects", "repositories", "clusters"])
+ def test_project_scoping_not_applied_to_other_endpoints(self, endpoint):
+ assert _list_params(endpoint, "team-a") == {}
+
+ @pytest.mark.parametrize("project", [None, ""])
+ def test_no_project_no_params(self, project):
+ assert _list_params("applications", project) == {}
+
+
+class TestItems:
+ @pytest.mark.parametrize(
+ "data, expected",
+ [
+ ({"items": [{"a": 1}]}, [{"a": 1}]),
+ # Kubernetes-style lists marshal an empty collection as null, not [].
+ ({"items": None}, []),
+ ({}, []),
+ (None, []),
+ ([], []),
+ ],
+ )
+ def test_items(self, data, expected):
+ assert _items(data) == expected
+
+
+class TestNormalization:
+ def test_application_lifts_identity_and_status_columns(self):
+ row = _normalize_application(APPLICATION)
+ assert row["name"] == "guestbook"
+ assert row["namespace"] == "argocd"
+ assert row["uid"] == "uid-1"
+ assert row["created_at"] == "2025-01-01T00:00:00Z"
+ assert row["project"] == "default"
+ assert row["sync_status"] == "Synced"
+ assert row["health_status"] == "Healthy"
+ assert row["spec"] == APPLICATION["spec"]
+
+ def test_application_with_missing_status_does_not_raise(self):
+ row = _normalize_application({"metadata": {"name": "bare"}})
+ assert row["name"] == "bare"
+ assert row["sync_status"] is None
+ assert row["health_status"] is None
+
+ def test_history_rows_carry_parent_identity(self):
+ rows = _history_rows(APPLICATION)
+ assert len(rows) == 2
+ for row in rows:
+ assert row["application_name"] == "guestbook"
+ assert row["application_namespace"] == "argocd"
+ assert row["project"] == "default"
+ assert rows[0]["id"] == 1
+ assert rows[0]["revision"] == "abc"
+ assert rows[0]["deployed_at"] == "2025-01-02T00:00:00Z"
+ assert rows[1]["initiated_by"] == {"username": "jane"}
+
+ def test_history_rows_empty_when_no_history(self):
+ assert _history_rows({"metadata": {"name": "new-app"}, "status": {}}) == []
+
+ def test_cluster_config_is_dropped(self):
+ # `config` carries the cluster's connection credentials and must never reach the warehouse.
+ row = _normalize_cluster({"server": "https://k8s.example.com", "name": "prod", "config": {"bearerToken": "s"}})
+ assert "config" not in row
+ assert row["server"] == "https://k8s.example.com"
+
+ def test_repository_secret_fields_are_dropped(self):
+ # gcpServiceAccountKey carries a GCS service-account JSON — it must be stripped like the
+ # other write-only credential fields in case a server version echoes it back.
+ row = _normalize_repository(
+ {
+ "repo": "https://github.com/org/repo",
+ "password": "x",
+ "sshPrivateKey": "y",
+ "gcpServiceAccountKey": "z",
+ }
+ )
+ assert row == {"repo": "https://github.com/org/repo"}
+
+
+class TestGetRows:
+ def _run(self, endpoint: str, response: mock.MagicMock, host: str = "https://argocd.example.com", **kwargs: Any):
+ with _patch_session(response) as patched:
+ rows: list[dict[str, Any]] = []
+ for batch in get_rows(
+ host=host, api_token="tok", endpoint=endpoint, team_id=1, logger=mock.MagicMock(), **kwargs
+ ):
+ rows.extend(batch)
+ return rows, patched.return_value
+
+ def test_applications_yields_normalized_rows(self):
+ rows, session = self._run("applications", _response(json_data={"items": [APPLICATION]}))
+
+ assert [r["name"] for r in rows] == ["guestbook"]
+ url = session.get.call_args.args[0]
+ assert url == "https://argocd.example.com/api/v1/applications"
+ assert session.get.call_args.kwargs["headers"]["Authorization"] == "Bearer tok"
+ assert session.get.call_args.kwargs["allow_redirects"] is False
+
+ def test_project_scope_is_passed_as_query_params(self):
+ _rows, session = self._run("applications", _response(json_data={"items": []}), project="team-a")
+ url = session.get.call_args.args[0]
+ assert "project=team-a" in url
+ assert "projects=team-a" in url
+
+ def test_deployment_history_flattens_from_applications_endpoint(self):
+ rows, session = self._run("deployment_history", _response(json_data={"items": [APPLICATION]}))
+
+ assert [r["id"] for r in rows] == [1, 2]
+ assert session.get.call_args.args[0] == "https://argocd.example.com/api/v1/applications"
+
+ def test_null_items_yields_nothing(self):
+ rows, _session = self._run("applications", _response(json_data={"items": None}))
+ assert rows == []
+
+ def test_rows_are_batched_without_loss(self):
+ apps = [
+ {"metadata": {"name": f"app-{i}", "namespace": "argocd", "uid": f"u{i}"}, "spec": {}, "status": {}}
+ for i in range(5)
+ ]
+ with (
+ mock.patch.object(argocd_module, "_ROWS_PER_BATCH", 2),
+ _patch_session(_response(json_data={"items": apps})),
+ ):
+ batches = list(
+ get_rows(
+ host="https://argocd.example.com",
+ api_token="tok",
+ endpoint="applications",
+ team_id=1,
+ logger=mock.MagicMock(),
+ )
+ )
+ assert [len(b) for b in batches] == [2, 2, 1]
+ assert [r["name"] for b in batches for r in b] == [f"app-{i}" for i in range(5)]
+
+ def test_http_host_is_rejected_before_any_request(self):
+ with _patch_session(_response(json_data={"items": []})) as patched:
+ with pytest.raises(ArgocdHostNotAllowedError, match=HTTPS_REQUIRED_ERROR):
+ list(
+ get_rows(
+ host="http://argocd.internal",
+ api_token="tok",
+ endpoint="applications",
+ team_id=1,
+ logger=mock.MagicMock(),
+ )
+ )
+ patched.return_value.get.assert_not_called()
+
+ def test_authority_parser_mismatch_is_rejected_before_any_request(self):
+ # `urlparse` reads the host after `@` (public.example) while an HTTP client that folds
+ # `\` into `/` reaches internal.example. The SSRF check must not be handed the wrong
+ # host — the request must never be attempted.
+ with _patch_session(_response(json_data={"items": []})) as patched:
+ with pytest.raises(ArgocdHostNotAllowedError):
+ list(
+ get_rows(
+ host="https://internal.example\\@public.example",
+ api_token="tok",
+ endpoint="applications",
+ team_id=1,
+ logger=mock.MagicMock(),
+ )
+ )
+ patched.return_value.get.assert_not_called()
+
+ def test_unsafe_host_is_rejected_before_any_request(self):
+ with (
+ mock.patch.object(argocd_module, "_is_host_safe", return_value=(False, "internal address")),
+ _patch_session(_response(json_data={"items": []})) as patched,
+ ):
+ with pytest.raises(ArgocdHostNotAllowedError, match="internal address"):
+ list(
+ get_rows(
+ host="https://10.0.0.1",
+ api_token="tok",
+ endpoint="applications",
+ team_id=1,
+ logger=mock.MagicMock(),
+ )
+ )
+ patched.return_value.get.assert_not_called()
+
+ def test_redirect_response_is_not_followed(self):
+ # A redirect could point at an internal address; it must raise, not be parsed or followed.
+ with pytest.raises(ArgocdHostNotAllowedError, match="redirect"):
+ self._run("applications", _response(status_code=302))
+
+ def test_session_opts_out_of_sample_capture_and_redacts_token(self):
+ # Raw cluster/repository responses carry credential fields the name-based sample
+ # scrubbers can't recognise, so the session must be excluded from HTTP sample capture.
+ with _patch_session(_response(json_data={"items": None})) as patched:
+ list(
+ get_rows(
+ host="https://argocd.example.com",
+ api_token="tok",
+ endpoint="clusters",
+ team_id=1,
+ logger=mock.MagicMock(),
+ )
+ )
+ assert patched.call_args.kwargs["capture"] is False
+ assert "tok" in patched.call_args.kwargs["redact_values"]
+ # `_fetch` owns the retry budget via tenacity; the adapter must not retry underneath it,
+ # or a stalling host could hold a worker for adapter × tenacity × timeout.
+ assert patched.call_args.kwargs["retry"].total == 0
+
+ def test_oversized_response_aborts_instead_of_buffering(self):
+ # The host is customer-controlled: a response bigger than the byte cap must fail the
+ # sync rather than being buffered into worker memory.
+ big = _response()
+ big.iter_content = mock.Mock(return_value=iter([b"x" * 10, b"x" * 10]))
+ with (
+ mock.patch.object(argocd_module, "MAX_RESPONSE_BYTES", 15),
+ _patch_session(big),
+ pytest.raises(ArgocdResponseTooLargeError),
+ ):
+ list(
+ get_rows(
+ host="https://argocd.example.com",
+ api_token="tok",
+ endpoint="applications",
+ team_id=1,
+ logger=mock.MagicMock(),
+ )
+ )
+
+ def test_slow_drip_response_aborts_on_total_deadline(self):
+ # A body that stays under the byte cap and never trips the per-read timeout but keeps
+ # dripping past the total transfer budget must fail the sync, not hold the worker.
+ slow = mock.MagicMock()
+ slow.iter_content = mock.Mock(return_value=iter([b"x", b"x", b"x"]))
+ # First call sets the deadline; the next read is already past it. Patched on the
+ # module's time reference so real elapsed time doesn't make the test flaky.
+ monotonic = mock.Mock(side_effect=[0.0, 601.0])
+ with (
+ mock.patch.object(argocd_module.time, "monotonic", monotonic),
+ pytest.raises(ArgocdResponseTimeoutError),
+ ):
+ argocd_module._read_bounded(slow, max_bytes=1_000, max_seconds=600)
+
+
+class TestValidateCredentials:
+ def test_success_without_reading_the_body(self):
+ # The probe runs inline on the API thread; on success it must decide from the status
+ # alone — ingesting the body would let a huge response buffer into memory.
+ ok = _response(json_data={"items": None})
+ with _patch_session(ok):
+ assert validate_credentials("https://argocd.example.com", "tok") == (True, None)
+ ok.iter_content.assert_not_called()
+
+ def test_probe_url_uses_name_filter_for_applications(self):
+ with _patch_session(_response(json_data={"items": None})) as patched:
+ validate_credentials("https://argocd.example.com", "tok", schema_name="applications")
+ url = patched.return_value.get.call_args.args[0]
+ assert url.startswith("https://argocd.example.com/api/v1/applications?")
+ assert "name=posthog-connectivity-probe" in url
+
+ def test_probe_url_for_projects_hits_projects_path(self):
+ with _patch_session(_response(json_data={"items": None})) as patched:
+ validate_credentials("https://argocd.example.com", "tok", schema_name="projects")
+ url = patched.return_value.get.call_args.args[0]
+ assert url == "https://argocd.example.com/api/v1/projects"
+
+ def test_authority_parser_mismatch_is_rejected_without_probing(self):
+ # The probe must not be sent to a host the SSRF check never validated.
+ with _patch_session(_response(json_data={"items": None})) as patched:
+ valid, _msg = validate_credentials("https://internal.example\\@public.example", "tok", team_id=1)
+ assert valid is False
+ patched.return_value.get.assert_not_called()
+
+ def test_invalid_token(self):
+ with _patch_session(_response(status_code=401)):
+ assert validate_credentials("https://argocd.example.com", "tok") == (False, "Invalid Argo CD API token")
+
+ def test_403_at_source_create_is_accepted(self):
+ with _patch_session(_response(status_code=403)):
+ assert validate_credentials("https://argocd.example.com", "tok", schema_name=None) == (True, None)
+
+ def test_403_for_scoped_probe_fails(self):
+ with _patch_session(_response(status_code=403)):
+ valid, msg = validate_credentials("https://argocd.example.com", "tok", schema_name="clusters")
+ assert valid is False
+ assert "clusters" in (msg or "")
+
+ @pytest.mark.parametrize("status_code", [429, 500, 503])
+ def test_transient_errors_are_not_reported_as_bad_credentials(self, status_code):
+ with _patch_session(_response(status_code=status_code)):
+ valid, msg = validate_credentials("https://argocd.example.com", "tok")
+ assert valid is False
+ assert "temporarily unavailable" in (msg or "")
+
+ def test_unexpected_status_surfaces_api_message(self):
+ with _patch_session(_response(status_code=400, json_data={"message": "bad request", "error": "bad"})):
+ valid, msg = validate_credentials("https://argocd.example.com", "tok")
+ assert valid is False
+ assert msg == "bad request"
+
+ @pytest.mark.parametrize("bad_host", ["", " ", "https://"])
+ def test_invalid_host_short_circuits(self, bad_host):
+ valid, msg = validate_credentials(bad_host, "tok")
+ assert valid is False
+ assert msg == "Invalid Argo CD host"
+
+ def test_http_host_is_rejected(self):
+ valid, msg = validate_credentials("http://argocd.internal", "tok")
+ assert valid is False
+ assert msg == HTTPS_REQUIRED_ERROR
+
+ def test_blocks_unsafe_host_before_any_request(self):
+ with (
+ mock.patch.object(argocd_module, "_is_host_safe", return_value=(False, "internal address")),
+ _patch_session(_response(status_code=200)) as patched,
+ ):
+ valid, msg = validate_credentials("https://10.0.0.1", "tok", team_id=99)
+ assert valid is False
+ assert msg == "internal address"
+ patched.return_value.get.assert_not_called()
+
+ def test_rejects_redirect_response(self):
+ with _patch_session(_response(status_code=302)) as patched:
+ valid, msg = validate_credentials("https://argocd.example.com", "tok")
+ assert valid is False
+ assert msg == HOST_NOT_ALLOWED_ERROR
+ assert patched.return_value.get.call_args.kwargs["allow_redirects"] is False
+
+ def test_ssl_error_gets_actionable_message(self):
+ import requests
+
+ with _patch_session(raises=requests.exceptions.SSLError("self signed certificate")):
+ valid, msg = validate_credentials("https://argocd.example.com", "tok")
+ assert valid is False
+ assert "certificate" in (msg or "")
+
+ def test_connection_error_returns_failure(self):
+ import requests
+
+ with _patch_session(raises=requests.exceptions.ConnectionError("boom")):
+ valid, msg = validate_credentials("https://argocd.example.com", "tok")
+ assert valid is False
+ assert "boom" in (msg or "")
+
+ def test_session_opts_out_of_sample_capture_and_redacts_token(self):
+ with _patch_session(_response(json_data={"items": None})) as patched:
+ validate_credentials("https://argocd.example.com", "tok")
+ assert patched.call_args.kwargs["capture"] is False
+ assert "tok" in patched.call_args.kwargs["redact_values"]
+ # The probe runs inline on an API worker and takes a single attempt — adapter retries
+ # would let a stalling host hold the worker across several timeouts.
+ assert patched.call_args.kwargs["retry"].total == 0
+
+
+class TestArgocdSourceResponse:
+ @pytest.mark.parametrize(
+ "endpoint, primary_keys, partition_key",
+ [
+ ("applications", ["namespace", "name"], "created_at"),
+ ("deployment_history", ["application_namespace", "application_name", "id"], "deployed_at"),
+ ("projects", ["name"], "created_at"),
+ ("repositories", ["repo"], None),
+ ("clusters", ["server"], None),
+ ],
+ )
+ def test_response_shape(self, endpoint, primary_keys, partition_key):
+ response = argocd_source(
+ host="https://argocd.example.com",
+ api_token="tok",
+ endpoint=endpoint,
+ team_id=1,
+ logger=mock.MagicMock(),
+ )
+ assert response.name == endpoint
+ assert response.primary_keys == primary_keys
+ if partition_key:
+ assert response.partition_keys == [partition_key]
+ assert response.partition_mode == "datetime"
+ else:
+ assert response.partition_keys is None
+ assert response.partition_mode is None
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/argocd/tests/test_argocd_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/argocd/tests/test_argocd_source.py
new file mode 100644
index 000000000000..17426e56e5c0
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/argocd/tests/test_argocd_source.py
@@ -0,0 +1,106 @@
+import pytest
+from unittest import mock
+
+from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.argocd.settings import ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.argocd.source import ArgocdSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import ArgocdSourceConfig
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+class TestArgocdSource:
+ def setup_method(self):
+ self.source = ArgocdSource()
+ self.team_id = 123
+ self.config = ArgocdSourceConfig(host="https://argocd.example.com", api_token="tok", project=None)
+
+ def test_source_type(self):
+ assert self.source.source_type == ExternalDataSourceType.ARGOCD
+
+ def test_get_source_config(self):
+ config = self.source.get_source_config
+
+ assert config.name.value == "Argocd"
+ assert config.label == "Argo CD"
+ assert config.unreleasedSource is None
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.iconPath == "/static/services/argocd.png"
+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/argocd"
+
+ field_names = [f.name for f in config.fields]
+ assert field_names == ["host", "api_token", "project"]
+
+ host_field, token_field, project_field = config.fields
+ assert isinstance(host_field, SourceFieldInputConfig)
+ assert host_field.type == SourceFieldInputConfigType.TEXT
+ assert host_field.required is True
+ assert host_field.secret is False
+
+ assert isinstance(token_field, SourceFieldInputConfig)
+ assert token_field.type == SourceFieldInputConfigType.PASSWORD
+ assert token_field.required is True
+ assert token_field.secret is True
+
+ assert isinstance(project_field, SourceFieldInputConfig)
+ assert project_field.required is False
+
+ @pytest.mark.parametrize(
+ "expected_key",
+ [
+ "401 Client Error",
+ "403 Client Error",
+ "Argo CD host is not allowed",
+ "Argo CD host must use HTTPS",
+ "Argo CD API response exceeded the size limit",
+ "Argo CD API response exceeded the download time limit",
+ ],
+ )
+ def test_non_retryable_errors(self, expected_key):
+ assert expected_key in self.source.get_non_retryable_errors()
+
+ def test_get_schemas_returns_all_endpoints_full_refresh_only(self):
+ schemas = self.source.get_schemas(self.config, self.team_id)
+ assert {s.name for s in schemas} == set(ENDPOINTS)
+ # No Argo CD endpoint has a server-side timestamp filter, so nothing may advertise
+ # incremental or append sync.
+ for schema in schemas:
+ assert schema.supports_incremental is False
+ assert schema.supports_append is False
+ assert schema.incremental_fields == []
+
+ def test_get_schemas_filtered_by_names(self):
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["applications"])
+ assert [s.name for s in schemas] == ["applications"]
+
+ def test_get_schemas_unknown_name_returns_empty(self):
+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []
+
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.argocd.source.validate_argocd_credentials"
+ )
+ def test_validate_credentials_plumbs_arguments(self, mock_validate):
+ mock_validate.return_value = (True, None)
+
+ result = self.source.validate_credentials(self.config, self.team_id, schema_name="applications")
+
+ assert result == (True, None)
+ mock_validate.assert_called_once_with(
+ self.config.host, self.config.api_token, "applications", self.team_id, self.config.project
+ )
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.argocd.source.argocd_source")
+ def test_source_for_pipeline_plumbs_arguments(self, mock_argocd_source):
+ config = ArgocdSourceConfig(host="https://argocd.example.com", api_token="tok", project="default")
+ inputs = mock.MagicMock()
+ inputs.schema_name = "applications"
+ inputs.team_id = 42
+
+ self.source.source_for_pipeline(config, inputs)
+
+ kwargs = mock_argocd_source.call_args.kwargs
+ assert kwargs["host"] == "https://argocd.example.com"
+ assert kwargs["api_token"] == "tok"
+ assert kwargs["endpoint"] == "applications"
+ assert kwargs["team_id"] == 42
+ assert kwargs["project"] == "default"
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
index 0e58f5c64bf6..659375438622 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
@@ -404,7 +404,9 @@ class AppwriteSourceConfig(config.Config):
@config.config
class ArgocdSourceConfig(config.Config):
- pass
+ host: str
+ api_token: str
+ project: str | None = None
@config.config