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 codefresh import source (#66733)

Tom Owerseade8d5dd9c3
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 84979146327c..190972253a46 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -89,6 +89,7 @@ the row lists both.
| checkout_com | HTTP | requests | ✅ |
| churnkey | HTTP | requests | ✅ |
| coda | HTTP | requests | ✅ |
+| codefresh | HTTP | requests | ✅ |
| coin_api | HTTP | requests | ✅ |
| coingecko | HTTP | requests | ✅ |
| coinmarketcap | HTTP | requests + `rest_source.RESTClient` | ✅ |
@@ -354,7 +355,6 @@ doesn't conflict with concurrent PRs.
- cloudbeds
- coassemble
- cockroachdb
-- codefresh
- concord
- configcat
- constant_contact
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/codefresh/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/codefresh/canonical_descriptions.py
new file mode 100644
index 000000000000..58caa3c6cd0e
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/codefresh/canonical_descriptions.py
@@ -0,0 +1,84 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+# Descriptions are taken from the Codefresh public API reference (https://g.codefresh.io/api/).
+# Codefresh is a fixed-schema SaaS source, so the table/column meanings are the same for every
+# account and worth documenting once here instead of re-deriving them per team via the LLM.
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "projects": {
+ "description": "A Codefresh project — a logical grouping of pipelines, with shared variables and tags.",
+ "docs_url": "https://g.codefresh.io/api/",
+ "columns": {
+ "id": "Unique identifier of the project.",
+ "projectName": "Human-readable name of the project.",
+ "accountId": "Identifier of the Codefresh account the project belongs to.",
+ "tags": "Free-form tags applied to the project.",
+ "variables": "Project-level shared variables available to its pipelines.",
+ "pipelinesNumber": "Number of pipelines that belong to the project.",
+ "updatedAt": "Timestamp of the last update to the project.",
+ "favorite": "Whether the project is marked as a favorite.",
+ },
+ },
+ "pipelines": {
+ "description": "A Codefresh pipeline definition. The pipeline's `metadata` fields (id, name, project, …) are lifted to the row's top level; the build specification stays under `spec`.",
+ "docs_url": "https://g.codefresh.io/api/",
+ "columns": {
+ "id": "Unique identifier of the pipeline (from metadata).",
+ "name": "Name of the pipeline (from metadata).",
+ "project": "Name of the project the pipeline belongs to.",
+ "projectId": "Identifier of the project the pipeline belongs to.",
+ "spec": "Pipeline specification: triggers, steps, and runtime configuration.",
+ },
+ },
+ "builds": {
+ "description": "A pipeline build (workflow execution), including its status, trigger, and source commit.",
+ "docs_url": "https://g.codefresh.io/api/",
+ "columns": {
+ "id": "Unique identifier of the build.",
+ "created": "Timestamp the build was created.",
+ "finished": "Timestamp the build finished, if it has completed.",
+ "status": "Final or current status of the build (e.g. success, error, running, terminated).",
+ "pipelineName": "Name of the pipeline that produced the build.",
+ "project": "Name of the project the build belongs to.",
+ "trigger": "How the build was triggered (e.g. build, promote).",
+ "triggeredBy": "User or system that triggered the build.",
+ "repoOwner": "Owner of the source repository.",
+ "repoName": "Name of the source repository.",
+ "branchName": "Source branch the build ran against.",
+ "revision": "Commit revision the build ran against.",
+ "commitMessage": "Commit message of the source revision.",
+ },
+ },
+ "images": {
+ "description": "A container image produced and tracked by Codefresh builds.",
+ "docs_url": "https://g.codefresh.io/api/",
+ "columns": {
+ "id": "Unique identifier of the image.",
+ "created": "Timestamp the image was created.",
+ "imageName": "Name of the image.",
+ "tags": "Tags applied to the image.",
+ "branch": "Source branch the image was built from.",
+ "sha": "Image SHA digest.",
+ "commit": "Source commit the image was built from.",
+ "size": "Size of the image.",
+ "internalImageId": "Codefresh-internal identifier of the image.",
+ },
+ },
+ "triggers": {
+ "description": "A Hermes trigger linking a trigger-event to the pipeline it fires.",
+ "docs_url": "https://g.codefresh.io/api/",
+ "columns": {
+ "event": "Identifier of the trigger-event.",
+ "pipeline": "Identifier of the pipeline the event triggers.",
+ "filters": "Filters that further constrain when the trigger fires.",
+ },
+ },
+ "step_types": {
+ "description": "A Codefresh typed step (plugin) available to pipelines, from the public and account step-type catalog.",
+ "docs_url": "https://g.codefresh.io/api/",
+ "columns": {
+ "id": "Unique identifier of the step type.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/codefresh/codefresh.py b/products/warehouse_sources/backend/temporal/data_imports/sources/codefresh/codefresh.py
new file mode 100644
index 000000000000..14b632d117ee
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/codefresh/codefresh.py
@@ -0,0 +1,263 @@
+import dataclasses
+from collections.abc import Iterator
+from typing import Any, Optional
+from urllib.parse import urlencode
+
+import requests
+from structlog.types import FilteringBoundLogger
+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.codefresh.settings import (
+ CODEFRESH_ENDPOINTS,
+ CodefreshEndpointConfig,
+)
+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
+
+# Only the US SaaS host is supported. EU / self-hosted installs use a different host, which we don't
+# let the user retarget yet (it would mean sending the stored API key to an arbitrary host).
+CODEFRESH_BASE_URL = "https://g.codefresh.io/api"
+
+_DEFAULT_TIMEOUT = 60
+
+
+class CodefreshRetryableError(Exception):
+ pass
+
+
+class CodefreshResumeConfig:
+ # Offset pagination position (projects, pipelines, images, step_types).
+ offset: int | None = None
+ # Page pagination position (builds) plus the stable pagination session cursor so resumed pages
+ # read against the same snapshot the first page opened.
+ page: int | None = None
+ session_id: str | None = None
+
+
+def _get_headers(api_key: str) -> dict[str, str]:
+ # Codefresh expects the raw token as the Authorization header value — no "Bearer " prefix.
+ return {"Authorization": api_key, "Accept": "application/json"}
+
+
+def _build_url(path: str, params: Optional[dict[str, Any]] = None) -> str:
+ url = f"{CODEFRESH_BASE_URL}{path}"
+ if params:
+ url = f"{url}?{urlencode(params)}"
+ return url
+
+
+def _extract_items(data: Any, data_key: Optional[list[str]]) -> list[dict[str, Any]]:
+ """Pull the record list out of a response. Codefresh returns either a bare array or an envelope
+ (``{docs: [...]}``, ``{workflows: {docs: [...]}}``), so ``data_key`` is the path to walk."""
+ if data_key is None:
+ return data if isinstance(data, list) else []
+ node: Any = data
+ for key in data_key:
+ if not isinstance(node, dict):
+ return []
+ node = node.get(key)
+ return node if isinstance(node, list) else []
+
+
+def _flatten(item: dict[str, Any], flatten_key: Optional[str]) -> dict[str, Any]:
+ """Lift the fields of a nested object (e.g. a pipeline's ``metadata``) to the row top level so
+ the primary key / partition columns resolve against real top-level fields. Top-level fields win
+ on a name clash."""
+ if flatten_key and isinstance(item.get(flatten_key), dict):
+ item = dict(item)
+ nested = item.pop(flatten_key)
+ return {**nested, **item}
+ return item
+
+
+def _redact_key(row: dict[str, Any], dotted_key: str) -> dict[str, Any]:
+ """Return ``row`` with a possibly-nested field removed. ``"variables"`` drops a top-level field;
+ ``"spec.variables"`` walks into ``spec`` and drops its ``variables``. Only the nodes on the path
+ are copied, so the upstream item is left unmodified; a missing or non-dict node is a no-op."""
+ head, _, rest = dotted_key.partition(".")
+ if head not in row:
+ return row
+ if not rest:
+ return {k: v for k, v in row.items() if k != head}
+ nested = row[head]
+ if not isinstance(nested, dict):
+ return row
+ return {**row, head: _redact_key(nested, rest)}
+
+
+def _transform_row(item: dict[str, Any], config: CodefreshEndpointConfig) -> dict[str, Any]:
+ """Flatten the row, then drop any redacted fields. Redaction runs after flattening so a key that
+ only surfaces once a nested object is lifted (and a top-level key of the same name) are both
+ caught. Redact keys may be dotted paths (e.g. ``spec.variables``) to reach nested fields."""
+ row = _flatten(item, config.flatten_key)
+ for key in config.redact_keys:
+ row = _redact_key(row, key)
+ return row
+
+
+@retry(
+ retry=retry_if_exception_type((CodefreshRetryableError, requests.ReadTimeout, requests.ConnectionError)),
+ stop=stop_after_attempt(5),
+ wait=wait_exponential_jitter(initial=1, max=30),
+ reraise=True,
+)
+def _fetch_page(session: requests.Session, url: str, headers: dict[str, str], logger: FilteringBoundLogger) -> Any:
+ response = session.get(url, headers=headers, timeout=_DEFAULT_TIMEOUT)
+
+ # Codefresh rate-limits per account with a 429; retry those and transient 5xx with backoff.
+ if response.status_code == 429 or response.status_code >= 500:
+ raise CodefreshRetryableError(f"Codefresh API error (retryable): status={response.status_code}, url={url}")
+
+ if not response.ok:
+ logger.error(f"Codefresh API error: status={response.status_code}, body={response.text}, url={url}")
+ response.raise_for_status()
+
+ return response.json()
+
+
+def _iter_offset(
+ session: requests.Session,
+ config: CodefreshEndpointConfig,
+ headers: dict[str, str],
+ logger: FilteringBoundLogger,
+ manager: ResumableSourceManager[CodefreshResumeConfig],
+) -> Iterator[list[dict[str, Any]]]:
+ resume = manager.load_state() if manager.can_resume() else None
+ offset = resume.offset if resume is not None and resume.offset is not None else 0
+
+ while True:
+ url = _build_url(config.path, {"limit": config.page_size, "offset": offset})
+ data = _fetch_page(session, url, headers, logger)
+ items = _extract_items(data, config.data_key)
+ if not items:
+ break
+
+ yield [_transform_row(item, config) for item in items]
+
+ # A short page is the last page. We don't save state on it: there's nothing left to resume to.
+ if len(items) < config.page_size:
+ break
+
+ offset += config.page_size
+ # Save AFTER yielding so a crash re-pulls the page we just emitted rather than skipping it —
+ # merge dedupes the re-pulled rows on the primary key.
+ manager.save_state(CodefreshResumeConfig(offset=offset))
+
+
+def _iter_page(
+ session: requests.Session,
+ config: CodefreshEndpointConfig,
+ headers: dict[str, str],
+ logger: FilteringBoundLogger,
+ manager: ResumableSourceManager[CodefreshResumeConfig],
+) -> Iterator[list[dict[str, Any]]]:
+ resume = manager.load_state() if manager.can_resume() else None
+ page = resume.page if resume is not None and resume.page is not None else 1
+ session_id = resume.session_id if resume is not None else None
+
+ while True:
+ req_headers = dict(headers)
+ if session_id:
+ # Pin every page to the snapshot the first page opened, so builds created mid-sync can't
+ # shift the window underneath us.
+ req_headers["X-Pagination-Session-Id"] = session_id
+
+ url = _build_url(config.path, {"limit": config.page_size, "page": page})
+ data = _fetch_page(session, url, req_headers, logger)
+
+ items = _extract_items(data, config.data_key)
+ pagination = data.get("pagination", {}) if isinstance(data, dict) else {}
+ session_id = pagination.get("sessionId") or session_id
+
+ # An empty page terminates the stream even if the API keeps advertising nextPage. Without
+ # this, a server-side cursor bug that streams empty pages forever would loop indefinitely.
+ if not items:
+ break
+
+ yield [_transform_row(item, config) for item in items]
+
+ if not pagination.get("nextPage"):
+ break
+
+ page += 1
+ manager.save_state(CodefreshResumeConfig(page=page, session_id=session_id))
+
+
+def get_rows(
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[CodefreshResumeConfig],
+) -> Iterator[list[dict[str, Any]]]:
+ config = CODEFRESH_ENDPOINTS[endpoint]
+ headers = _get_headers(api_key)
+ # One session reused across every page so urllib3 keeps the connection alive.
+ session = make_tracked_session()
+
+ if config.pagination == "none":
+ data = _fetch_page(session, _build_url(config.path), headers, logger)
+ items = [_transform_row(item, config) for item in _extract_items(data, config.data_key)]
+ if items:
+ yield items
+ return
+
+ if config.pagination == "offset":
+ yield from _iter_offset(session, config, headers, logger, resumable_source_manager)
+ return
+
+ yield from _iter_page(session, config, headers, logger, resumable_source_manager)
+
+
+def validate_credentials(api_key: str, schema_name: Optional[str] = None) -> tuple[bool, str | None]:
+ """Probe the token. Codefresh keys are scoped per resource, so at source-create (``schema_name``
+ is ``None``) a 403 means the token is genuine but lacks scope for the probed resource — accept it
+ and let the user pick the tables their key can reach. A 401 always means a bad token."""
+ config = CODEFRESH_ENDPOINTS.get(schema_name) if schema_name else None
+ path = config.path if config is not None else "/projects"
+
+ try:
+ response = make_tracked_session().get(_build_url(path, {"limit": 1}), headers=_get_headers(api_key), timeout=10)
+ except Exception:
+ return False, "Could not connect to Codefresh. Please try again."
+
+ if response.status_code == 200:
+ return True, None
+ if response.status_code == 401:
+ return False, "Your Codefresh API key is invalid or has been revoked."
+ if response.status_code == 403:
+ if schema_name:
+ return False, f"Your Codefresh API key is missing the access scope required to sync '{schema_name}'."
+ # Valid token, but it lacks scope for the probe resource — don't block source creation.
+ return True, None
+ if response.status_code == 429 or response.status_code >= 500:
+ # Transient: a rate-limit or server error doesn't mean the key is bad. Surface it as a
+ # retryable failure rather than telling the user their credentials are invalid.
+ return False, "Codefresh is temporarily unavailable. Please try again in a moment."
+ return False, f"Codefresh API returned an unexpected status ({response.status_code})."
+
+
+def codefresh_source(
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[CodefreshResumeConfig],
+) -> SourceResponse:
+ config = CODEFRESH_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ api_key=api_key,
+ endpoint=endpoint,
+ logger=logger,
+ resumable_source_manager=resumable_source_manager,
+ ),
+ primary_keys=config.primary_keys,
+ partition_count=1,
+ partition_size=1,
+ partition_mode="datetime" if config.partition_key else None,
+ partition_format="month" if config.partition_key else None,
+ partition_keys=[config.partition_key] if config.partition_key else None,
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/codefresh/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/codefresh/settings.py
new file mode 100644
index 000000000000..867a96637e75
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/codefresh/settings.py
@@ -0,0 +1,102 @@
+from dataclasses import dataclass, field
+from typing import Literal, Optional
+
+from products.warehouse_sources.backend.types import IncrementalField
+
+# How an endpoint paginates. Codefresh is inconsistent across resources:
+# - "offset": limit/offset query params, terminate when a page is short (projects, pipelines, images, step_types)
+# - "page": 1-indexed `page` param plus a `pagination.nextPage` flag and a stable `sessionId` cursor (builds)
+# - "none": single request, no pagination params (triggers)
+PaginationMode = Literal["offset", "page", "none"]
+
+
+@dataclass
+class CodefreshEndpointConfig:
+ name: str
+ path: str
+ pagination: PaginationMode
+ # Path to the list of records inside the response body. ``None`` means the body is itself a bare
+ # array. Otherwise it's the sequence of keys to walk (e.g. ["docs"] or ["workflows", "docs"]).
+ data_key: Optional[list[str]] = None
+ # Nested object whose fields are lifted to the row's top level (e.g. pipeline `metadata`), so the
+ # primary key / partition columns resolve against real top-level fields.
+ flatten_key: Optional[str] = None
+ primary_keys: list[str] = field(default_factory=lambda: ["id"])
+ # Stable creation-time field to partition by. Never an `updated`/`lastSeen` field — those rewrite
+ # partitions on every sync. ``None`` when the resource exposes no stable creation timestamp.
+ partition_key: Optional[str] = None
+ page_size: int = 100
+ should_sync_default: bool = True
+ incremental_fields: list[IncrementalField] = field(default_factory=list)
+ # Fields to strip from every row before it's emitted, to keep secret-bearing fields (e.g. a
+ # project's `variables` or a pipeline's `spec.variables`, which can hold plaintext config values)
+ # out of the warehouse, where any table reader could see them. Each entry is a dotted path, so
+ # nested fields can be redacted (e.g. `spec.variables`); a bare name targets a top-level field.
+ redact_keys: list[str] = field(default_factory=list)
+
+
+CODEFRESH_ENDPOINTS: dict[str, CodefreshEndpointConfig] = {
+ "projects": CodefreshEndpointConfig(
+ name="projects",
+ path="/projects",
+ pagination="offset",
+ data_key=None, # bare array
+ primary_keys=["id"],
+ # Project variables can hold plaintext secrets — never land them in the warehouse.
+ redact_keys=["variables"],
+ ),
+ "pipelines": CodefreshEndpointConfig(
+ name="pipelines",
+ path="/pipelines",
+ pagination="offset",
+ data_key=["docs"], # envelope: {docs: [...], count}
+ flatten_key="metadata", # lift metadata.{id,name,project,...} to the row top level
+ primary_keys=["id"],
+ # Pipeline spec variables are exported with their plaintext `value` — keep them out of the warehouse.
+ redact_keys=["spec.variables"],
+ ),
+ "builds": CodefreshEndpointConfig(
+ name="builds",
+ path="/workflow",
+ pagination="page",
+ data_key=["workflows", "docs"], # nested envelope: {workflows: {docs: [...]}, pagination: {...}}
+ primary_keys=["id"],
+ partition_key="created",
+ ),
+ "images": CodefreshEndpointConfig(
+ name="images",
+ path="/images",
+ pagination="offset",
+ data_key=None, # bare array
+ primary_keys=["id"],
+ partition_key="created",
+ ),
+ "triggers": CodefreshEndpointConfig(
+ name="triggers",
+ path="/hermes/triggers",
+ pagination="none",
+ data_key=None, # bare array, no pagination params
+ # A trigger row is the link between a trigger-event and a pipeline; neither is unique on its
+ # own across the table, so the pair is the key.
+ primary_keys=["event", "pipeline"],
+ # `event-data.secret` is the webhook signing secret, and `event-data.endpoint` embeds it as a
+ # query parameter — keep both out of the warehouse where any table reader could recover them.
+ redact_keys=["event-data.endpoint", "event-data.secret"],
+ ),
+ "step_types": CodefreshEndpointConfig(
+ name="step_types",
+ path="/step-types",
+ pagination="offset",
+ data_key=None, # bare array
+ primary_keys=["id"],
+ ),
+}
+
+ENDPOINTS = tuple(CODEFRESH_ENDPOINTS.keys())
+
+# Codefresh has no server-side updated-since filter on any list endpoint, so no endpoint is genuinely
+# incremental — every table is full refresh only. Kept as an (empty) per-endpoint map for parity with
+# other sources and so the schema builder has a single place to read advertised fields from.
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in CODEFRESH_ENDPOINTS.items()
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/codefresh/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/codefresh/source.py
index 90bf47ce192f..d4b1094af0a7 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/codefresh/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/codefresh/source.py
@@ -1,19 +1,43 @@
-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.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.codefresh.codefresh import (
+ CodefreshResumeConfig,
+ codefresh_source,
+ validate_credentials as validate_codefresh_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.codefresh.settings import (
+ CODEFRESH_ENDPOINTS,
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchema
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import CodefreshSourceConfig
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class CodefreshSource(SimpleSource[CodefreshSourceConfig]):
+class CodefreshSource(ResumableSource[CodefreshSourceConfig, CodefreshResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.CODEFRESH
@@ -24,7 +48,99 @@ class CodefreshSource(SimpleSource[CodefreshSourceConfig]):
name=SchemaExternalDataSourceType.CODEFRESH,
category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,
label="Codefresh",
- iconPath="/static/services/codefresh.png",
- fields=cast(list[FieldType], []),
+ releaseStatus=ReleaseStatus.ALPHA,
unreleasedSource=True,
+ caption="""Enter your Codefresh API key to automatically pull your Codefresh CI/CD data into the PostHog Data warehouse.
+
+You can create an API key in your [Codefresh user settings](https://g.codefresh.io/user/settings). Codefresh API keys are scoped per resource, so grant read access for the resources you want to sync:
+- **Project** (projects)
+- **Pipeline** (pipelines, triggers)
+- **Build** (builds, images)
+- **Step Type** (step types)
+
+Only the US SaaS host (`g.codefresh.io`) is supported. EU and self-hosted/on-prem installations are not yet supported.
+""",
+ iconPath="/static/services/codefresh.png",
+ docsUrl="https://posthog.com/docs/cdp/sources/codefresh",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
+ )
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.codefresh.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ # An invalid or revoked Codefresh API key surfaces as a requests HTTPError when
+ # `_fetch_page` calls `raise_for_status()`. Retrying can never satisfy a credential
+ # problem, so stop the sync. Match the stable status text and base host, not the
+ # per-request path/query.
+ "401 Client Error: Unauthorized for url: https://g.codefresh.io": "Your Codefresh API key is invalid or has been revoked. Create a new key in your Codefresh user settings, then reconnect.",
+ "403 Client Error: Forbidden for url: https://g.codefresh.io": "Your Codefresh API key is missing the access scope needed to sync this data. Grant the required resource scopes to the key in your Codefresh user settings, then reconnect.",
+ }
+
+ def get_schemas(
+ self,
+ config: CodefreshSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ def _build_schema(endpoint: str) -> SourceSchema:
+ endpoint_config = CODEFRESH_ENDPOINTS[endpoint]
+ return SourceSchema(
+ name=endpoint,
+ # Codefresh exposes no server-side updated-since filter on any list endpoint, so
+ # every table is full refresh only — an "incremental" sync would re-page the whole
+ # resource anyway.
+ supports_incremental=False,
+ supports_append=False,
+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),
+ should_sync_default=endpoint_config.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 validate_credentials(
+ self, config: CodefreshSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ valid, error = validate_codefresh_credentials(config.api_key, schema_name=schema_name)
+ if valid:
+ return True, None
+ return False, error or "Invalid Codefresh API key"
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[CodefreshResumeConfig]:
+ return ResumableSourceManager[CodefreshResumeConfig](inputs, CodefreshResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: CodefreshSourceConfig,
+ resumable_source_manager: ResumableSourceManager[CodefreshResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return codefresh_source(
+ api_key=config.api_key,
+ endpoint=inputs.schema_name,
+ logger=inputs.logger,
+ resumable_source_manager=resumable_source_manager,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/codefresh/tests/test_codefresh.py b/products/warehouse_sources/backend/temporal/data_imports/sources/codefresh/tests/test_codefresh.py
new file mode 100644
index 000000000000..3e01483182d7
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/codefresh/tests/test_codefresh.py
@@ -0,0 +1,394 @@
+from typing import Any
+
+import pytest
+from unittest.mock import MagicMock
+
+from parameterized import parameterized
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.codefresh import codefresh
+from products.warehouse_sources.backend.temporal.data_imports.sources.codefresh.codefresh import (
+ CodefreshResumeConfig,
+ _extract_items,
+ _flatten,
+ _iter_offset,
+ _iter_page,
+ _transform_row,
+ codefresh_source,
+ get_rows,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.codefresh.settings import (
+ CODEFRESH_ENDPOINTS,
+ CodefreshEndpointConfig,
+)
+
+
+class _FakeResumableManager:
+ def __init__(self, state: CodefreshResumeConfig | None = None) -> None:
+ self._state = state
+ self.saved: list[CodefreshResumeConfig] = []
+
+ def can_resume(self) -> bool:
+ return self._state is not None
+
+ def load_state(self) -> CodefreshResumeConfig | None:
+ return self._state
+
+ def save_state(self, data: CodefreshResumeConfig) -> None:
+ self.saved.append(data)
+
+
+def _fetch_stub(pages: dict[str, Any], captured_headers: list[dict[str, str]] | None = None):
+ """Build a `_fetch_page` replacement that returns canned bodies keyed by URL."""
+
+ def fake_fetch(session: Any, url: str, headers: dict[str, str], logger: Any) -> Any:
+ if captured_headers is not None:
+ captured_headers.append(dict(headers))
+ result = pages[url]
+ if isinstance(result, Exception):
+ raise result
+ return result
+
+ return fake_fetch
+
+
+class TestExtractItems:
+ @parameterized.expand(
+ [
+ ("bare_array", [{"id": "1"}, {"id": "2"}], None, [{"id": "1"}, {"id": "2"}]),
+ ("docs_envelope", {"docs": [{"id": "1"}], "count": 1}, ["docs"], [{"id": "1"}]),
+ (
+ "nested_workflows_docs",
+ {"workflows": {"docs": [{"id": "b1"}]}, "pagination": {}},
+ ["workflows", "docs"],
+ [{"id": "b1"}],
+ ),
+ ("missing_key_returns_empty", {"other": []}, ["docs"], []),
+ ("non_list_value_returns_empty", {"docs": {"not": "a list"}}, ["docs"], []),
+ ("bare_array_on_non_list_returns_empty", {"docs": []}, None, []),
+ ]
+ )
+ def test_extract_items(self, _name: str, data: Any, data_key: list[str] | None, expected: list) -> None:
+ assert _extract_items(data, data_key) == expected
+
+
+class TestFlatten:
+ def test_lifts_nested_object_to_top_level(self) -> None:
+ item = {"metadata": {"id": "p1", "name": "build-and-test"}, "spec": {"steps": {}}}
+ result = _flatten(item, "metadata")
+ assert result["id"] == "p1"
+ assert result["name"] == "build-and-test"
+ assert result["spec"] == {"steps": {}}
+ assert "metadata" not in result
+
+ def test_top_level_field_wins_on_clash(self) -> None:
+ item = {"metadata": {"id": "from_metadata"}, "id": "top_level"}
+ assert _flatten(item, "metadata")["id"] == "top_level"
+
+ def test_no_flatten_key_is_passthrough(self) -> None:
+ item = {"id": "1", "created": "2026-01-01"}
+ assert _flatten(item, None) == item
+
+ def test_flatten_key_absent_is_passthrough(self) -> None:
+ item = {"id": "1"}
+ assert _flatten(item, "metadata") == item
+
+
+class TestTransformRow:
+ @parameterized.expand(
+ [
+ (
+ "top_level_key",
+ ["variables"],
+ {"id": "p1", "variables": [{"key": "TOKEN", "value": "secret"}]},
+ {"id": "p1"},
+ ),
+ (
+ "nested_dotted_key",
+ ["spec.variables"],
+ {"id": "p1", "spec": {"steps": {}, "variables": [{"key": "TOKEN", "value": "secret"}]}},
+ {"id": "p1", "spec": {"steps": {}}},
+ ),
+ (
+ "nested_path_absent_is_noop",
+ ["spec.variables"],
+ {"id": "p1", "spec": {"steps": {}}},
+ {"id": "p1", "spec": {"steps": {}}},
+ ),
+ (
+ "nested_parent_not_a_dict_is_noop",
+ ["spec.variables"],
+ {"id": "p1", "spec": None},
+ {"id": "p1", "spec": None},
+ ),
+ ]
+ )
+ def test_redacts_configured_keys(
+ self, _name: str, redact_keys: list[str], item: dict[str, Any], expected: dict[str, Any]
+ ) -> None:
+ config = CodefreshEndpointConfig(
+ name="projects", path="/projects", pagination="offset", redact_keys=redact_keys
+ )
+ assert _transform_row(item, config) == expected
+
+ def test_redaction_does_not_mutate_source_item(self) -> None:
+ config = CodefreshEndpointConfig(
+ name="pipelines", path="/pipelines", pagination="offset", redact_keys=["spec.variables"]
+ )
+ item = {"id": "p1", "spec": {"variables": [{"key": "TOKEN", "value": "secret"}]}}
+ _transform_row(item, config)
+ assert item["spec"] == {"variables": [{"key": "TOKEN", "value": "secret"}]}
+
+ def test_no_redact_keys_is_passthrough(self) -> None:
+ config = CodefreshEndpointConfig(name="builds", path="/workflow", pagination="page")
+ row = _transform_row({"id": "b1", "variables": ["x"]}, config)
+ assert row == {"id": "b1", "variables": ["x"]}
+
+ @parameterized.expand(
+ [
+ ("projects", "variables"),
+ ("pipelines", "spec.variables"),
+ ("triggers", "event-data.endpoint"),
+ ("triggers", "event-data.secret"),
+ ]
+ )
+ def test_endpoint_redacts_secret_bearing_variables(self, endpoint: str, redacted_key: str) -> None:
+ # These endpoints expose plaintext config/CI variables or webhook secrets; the configured
+ # source must strip them.
+ assert redacted_key in CODEFRESH_ENDPOINTS[endpoint].redact_keys
+
+
+def _offset_config(page_size: int = 2) -> CodefreshEndpointConfig:
+ return CodefreshEndpointConfig(
+ name="projects", path="/projects", pagination="offset", data_key=None, page_size=page_size
+ )
+
+
+class TestOffsetPagination:
+ def test_short_first_page_stops_without_saving(self, monkeypatch: Any) -> None:
+ config = _offset_config(page_size=2)
+ pages = {"https://g.codefresh.io/api/projects?limit=2&offset=0": [{"id": "1"}]}
+ monkeypatch.setattr(codefresh, "_fetch_page", _fetch_stub(pages))
+ manager = _FakeResumableManager()
+
+ batches = list(_iter_offset(MagicMock(), config, {}, MagicMock(), manager)) # type: ignore[arg-type]
+
+ assert batches == [[{"id": "1"}]]
+ # A short page is the last page — nothing left to resume to, so no state is saved.
+ assert manager.saved == []
+
+ def test_full_page_then_short_page_paginates_and_saves(self, monkeypatch: Any) -> None:
+ config = _offset_config(page_size=2)
+ pages = {
+ "https://g.codefresh.io/api/projects?limit=2&offset=0": [{"id": "1"}, {"id": "2"}],
+ "https://g.codefresh.io/api/projects?limit=2&offset=2": [{"id": "3"}],
+ }
+ monkeypatch.setattr(codefresh, "_fetch_page", _fetch_stub(pages))
+ manager = _FakeResumableManager()
+
+ batches = list(_iter_offset(MagicMock(), config, {}, MagicMock(), manager)) # type: ignore[arg-type]
+
+ assert batches == [[{"id": "1"}, {"id": "2"}], [{"id": "3"}]]
+ # State saved exactly once, after the first (full) page is yielded, pointing at the next offset.
+ assert manager.saved == [CodefreshResumeConfig(offset=2)]
+
+ def test_resume_starts_from_saved_offset(self, monkeypatch: Any) -> None:
+ config = _offset_config(page_size=2)
+ pages = {"https://g.codefresh.io/api/projects?limit=2&offset=4": [{"id": "5"}]}
+ monkeypatch.setattr(codefresh, "_fetch_page", _fetch_stub(pages))
+ manager = _FakeResumableManager(CodefreshResumeConfig(offset=4))
+
+ batches = list(_iter_offset(MagicMock(), config, {}, MagicMock(), manager)) # type: ignore[arg-type]
+
+ assert batches == [[{"id": "5"}]]
+
+
+def _page_config(page_size: int = 2) -> CodefreshEndpointConfig:
+ return CodefreshEndpointConfig(
+ name="builds",
+ path="/workflow",
+ pagination="page",
+ data_key=["workflows", "docs"],
+ page_size=page_size,
+ )
+
+
+class TestPagePagination:
+ def test_follows_next_page_and_forwards_session_id(self, monkeypatch: Any) -> None:
+ config = _page_config(page_size=2)
+ pages = {
+ "https://g.codefresh.io/api/workflow?limit=2&page=1": {
+ "workflows": {"docs": [{"id": "b1"}, {"id": "b2"}]},
+ "pagination": {"sessionId": "sess-1", "nextPage": True},
+ },
+ "https://g.codefresh.io/api/workflow?limit=2&page=2": {
+ "workflows": {"docs": [{"id": "b3"}]},
+ "pagination": {"sessionId": "sess-1", "nextPage": False},
+ },
+ }
+ captured: list[dict[str, str]] = []
+ monkeypatch.setattr(codefresh, "_fetch_page", _fetch_stub(pages, captured))
+ manager = _FakeResumableManager()
+
+ batches = list(_iter_page(MagicMock(), config, {}, MagicMock(), manager)) # type: ignore[arg-type]
+
+ assert batches == [[{"id": "b1"}, {"id": "b2"}], [{"id": "b3"}]]
+ # The session cursor opened by page 1 must be pinned on page 2 so the snapshot is stable.
+ assert "X-Pagination-Session-Id" not in captured[0]
+ assert captured[1]["X-Pagination-Session-Id"] == "sess-1"
+ assert manager.saved == [CodefreshResumeConfig(page=2, session_id="sess-1")]
+
+ def test_single_page_no_next(self, monkeypatch: Any) -> None:
+ config = _page_config(page_size=2)
+ pages = {
+ "https://g.codefresh.io/api/workflow?limit=2&page=1": {
+ "workflows": {"docs": [{"id": "b1"}]},
+ "pagination": {"nextPage": False},
+ },
+ }
+ monkeypatch.setattr(codefresh, "_fetch_page", _fetch_stub(pages))
+ manager = _FakeResumableManager()
+
+ batches = list(_iter_page(MagicMock(), config, {}, MagicMock(), manager)) # type: ignore[arg-type]
+
+ assert batches == [[{"id": "b1"}]]
+ assert manager.saved == []
+
+ def test_empty_page_stops_even_when_next_page_advertised(self, monkeypatch: Any) -> None:
+ # A misbehaving API that streams empty pages with nextPage=True must not loop forever.
+ config = _page_config(page_size=2)
+ pages = {
+ "https://g.codefresh.io/api/workflow?limit=2&page=1": {
+ "workflows": {"docs": []},
+ "pagination": {"nextPage": True},
+ },
+ }
+ monkeypatch.setattr(codefresh, "_fetch_page", _fetch_stub(pages))
+ manager = _FakeResumableManager()
+
+ batches = list(_iter_page(MagicMock(), config, {}, MagicMock(), manager)) # type: ignore[arg-type]
+
+ assert batches == []
+ assert manager.saved == []
+
+ def test_resume_starts_from_saved_page_and_session(self, monkeypatch: Any) -> None:
+ config = _page_config(page_size=2)
+ pages = {
+ "https://g.codefresh.io/api/workflow?limit=2&page=3": {
+ "workflows": {"docs": [{"id": "b9"}]},
+ "pagination": {"nextPage": False},
+ },
+ }
+ captured: list[dict[str, str]] = []
+ monkeypatch.setattr(codefresh, "_fetch_page", _fetch_stub(pages, captured))
+ manager = _FakeResumableManager(CodefreshResumeConfig(page=3, session_id="sess-resume"))
+
+ batches = list(_iter_page(MagicMock(), config, {}, MagicMock(), manager)) # type: ignore[arg-type]
+
+ assert batches == [[{"id": "b9"}]]
+ assert captured[0]["X-Pagination-Session-Id"] == "sess-resume"
+
+
+class TestUnpaginatedEndpoint:
+ def test_triggers_single_fetch_yields_one_list(self, monkeypatch: Any) -> None:
+ pages = {
+ "https://g.codefresh.io/api/hermes/triggers": [
+ {"event": "e1", "pipeline": "p1"},
+ {"event": "e2", "pipeline": "p1"},
+ ]
+ }
+ monkeypatch.setattr(codefresh, "_fetch_page", _fetch_stub(pages))
+ manager = _FakeResumableManager()
+
+ batches = list(get_rows("token", "triggers", MagicMock(), manager)) # type: ignore[arg-type]
+
+ assert batches == [[{"event": "e1", "pipeline": "p1"}, {"event": "e2", "pipeline": "p1"}]]
+ assert manager.saved == []
+
+ def test_empty_response_yields_nothing(self, monkeypatch: Any) -> None:
+ pages: dict[str, Any] = {"https://g.codefresh.io/api/hermes/triggers": []}
+ monkeypatch.setattr(codefresh, "_fetch_page", _fetch_stub(pages))
+
+ batches = list(get_rows("token", "triggers", MagicMock(), _FakeResumableManager())) # type: ignore[arg-type]
+
+ assert batches == []
+
+
+class TestGetRowsFlattensPipelines:
+ def test_pipeline_metadata_lifted_to_top_level(self, monkeypatch: Any) -> None:
+ pages = {
+ "https://g.codefresh.io/api/pipelines?limit=100&offset=0": {
+ "docs": [{"metadata": {"id": "p1", "name": "deploy"}, "spec": {"steps": {}}}],
+ "count": 1,
+ }
+ }
+ monkeypatch.setattr(codefresh, "_fetch_page", _fetch_stub(pages))
+
+ batches = list(get_rows("token", "pipelines", MagicMock(), _FakeResumableManager())) # type: ignore[arg-type]
+
+ assert batches == [[{"id": "p1", "name": "deploy", "spec": {"steps": {}}}]]
+
+
+class _FakeResponse:
+ def __init__(self, status_code: int) -> None:
+ self.status_code = status_code
+
+
+class TestValidateCredentials:
+ @parameterized.expand(
+ [
+ ("ok", 200, None, True),
+ ("unauthorized", 401, None, False),
+ ("forbidden_at_create_is_accepted", 403, None, True),
+ ("forbidden_for_specific_schema_is_rejected", 403, "projects", False),
+ ("rate_limited", 429, None, False),
+ ("server_error", 500, None, False),
+ ]
+ )
+ def test_status_mapping(self, _name: str, status: int, schema_name: str | None, expected_valid: bool) -> None:
+ session = MagicMock()
+ session.get.return_value = _FakeResponse(status)
+ with pytest.MonkeyPatch().context() as mp:
+ mp.setattr(codefresh, "make_tracked_session", lambda *a, **k: session)
+ valid, _error = validate_credentials("token", schema_name=schema_name)
+ assert valid is expected_valid
+
+ def test_connection_error_is_invalid(self) -> None:
+ session = MagicMock()
+ session.get.side_effect = ConnectionError("boom")
+ with pytest.MonkeyPatch().context() as mp:
+ mp.setattr(codefresh, "make_tracked_session", lambda *a, **k: session)
+ valid, error = validate_credentials("token")
+ assert valid is False
+ assert error is not None
+
+
+class TestCodefreshSourceResponse:
+ @parameterized.expand(
+ [
+ ("projects", ["id"], None),
+ ("pipelines", ["id"], None),
+ ("builds", ["id"], "created"),
+ ("images", ["id"], "created"),
+ ("triggers", ["event", "pipeline"], None),
+ ("step_types", ["id"], None),
+ ]
+ )
+ def test_source_response_primary_keys_and_partition(
+ self, endpoint: str, expected_keys: list[str], partition_key: str | None
+ ) -> None:
+ response = codefresh_source("token", endpoint, MagicMock(), _FakeResumableManager()) # type: ignore[arg-type]
+ assert response.name == endpoint
+ assert response.primary_keys == expected_keys
+ if partition_key is None:
+ assert response.partition_mode is None
+ assert response.partition_keys is None
+ else:
+ assert response.partition_mode == "datetime"
+ assert response.partition_keys == [partition_key]
+
+ def test_every_endpoint_has_a_source_response(self) -> None:
+ # Guards against an endpoint added to settings without transport wiring.
+ for endpoint in CODEFRESH_ENDPOINTS:
+ response = codefresh_source("token", endpoint, MagicMock(), _FakeResumableManager()) # type: ignore[arg-type]
+ assert response.primary_keys
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/codefresh/tests/test_codefresh_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/codefresh/tests/test_codefresh_source.py
new file mode 100644
index 000000000000..acfb1ebd7bff
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/codefresh/tests/test_codefresh_source.py
@@ -0,0 +1,126 @@
+import pytest
+from unittest import mock
+
+from parameterized import parameterized
+
+from posthog.schema import SourceFieldInputConfig
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.codefresh.codefresh import CodefreshResumeConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.codefresh.settings import ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.codefresh.source import CodefreshSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import CodefreshSourceConfig
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+class TestCodefreshSource:
+ def setup_method(self) -> None:
+ self.source = CodefreshSource()
+ self.team_id = 123
+
+ def test_source_type(self) -> None:
+ assert self.source.source_type == ExternalDataSourceType.CODEFRESH
+
+ def test_source_config_has_api_key_password_field(self) -> None:
+ config = self.source.get_source_config
+ assert config.label == "Codefresh"
+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/codefresh"
+ field_names = [f.name for f in config.fields]
+ assert field_names == ["api_key"]
+ api_key_field = config.fields[0]
+ assert isinstance(api_key_field, SourceFieldInputConfig)
+ assert api_key_field.type == "password"
+ assert api_key_field.required is True
+
+ @parameterized.expand(
+ [
+ ("401 Client Error: Unauthorized for url: https://g.codefresh.io/api/projects?limit=100&offset=0",),
+ ("403 Client Error: Forbidden for url: https://g.codefresh.io/api/workflow?limit=100&page=1",),
+ ]
+ )
+ def test_credential_errors_are_non_retryable(self, observed_error: str) -> None:
+ non_retryable = self.source.get_non_retryable_errors()
+ assert any(key in observed_error for key in non_retryable)
+
+ @parameterized.expand(
+ [
+ ("read_timeout", "HTTPSConnectionPool(host='g.codefresh.io', port=443): Read timed out."),
+ ("server_error", "500 Server Error: Internal Server Error for url: https://g.codefresh.io/api/projects"),
+ ("rate_limited", "429 Client Error: Too Many Requests for url: https://g.codefresh.io/api/workflow"),
+ ]
+ )
+ def test_transient_errors_remain_retryable(self, _name: str, other_error: str) -> None:
+ non_retryable = self.source.get_non_retryable_errors()
+ assert not any(key in other_error for key in non_retryable)
+
+ def test_get_schemas_lists_every_endpoint_as_full_refresh(self) -> None:
+ schemas = self.source.get_schemas(CodefreshSourceConfig(api_key="t"), self.team_id)
+ assert {s.name for s in schemas} == set(ENDPOINTS)
+ for schema in schemas:
+ # Codefresh has no server-side updated-since filter, so every table is full refresh only.
+ assert schema.supports_incremental is False
+ assert schema.supports_append is False
+ assert schema.incremental_fields == []
+
+ def test_get_schemas_filters_by_names(self) -> None:
+ schemas = self.source.get_schemas(CodefreshSourceConfig(api_key="t"), self.team_id, names=["builds"])
+ assert [s.name for s in schemas] == ["builds"]
+
+ def test_lists_tables_without_credentials(self) -> None:
+ # get_schemas does no I/O, so the public docs may render the table catalog.
+ assert self.source.lists_tables_without_credentials is True
+ tables = self.source.get_documented_tables()
+ assert {t["name"] for t in tables} == set(ENDPOINTS)
+
+ @parameterized.expand(
+ [
+ ("valid", True, None, True),
+ ("invalid", False, "Your Codefresh API key is invalid or has been revoked.", False),
+ ]
+ )
+ def test_validate_credentials_plumbs_through(
+ self, _name: str, inner_valid: bool, inner_error: str | None, expected_valid: bool
+ ) -> None:
+ with mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.codefresh.source.validate_codefresh_credentials",
+ return_value=(inner_valid, inner_error),
+ ) as mocked:
+ valid, error = self.source.validate_credentials(CodefreshSourceConfig(api_key="t"), self.team_id)
+ mocked.assert_called_once_with("t", schema_name=None)
+ assert valid is expected_valid
+ if not expected_valid:
+ assert error == inner_error
+
+ def test_get_resumable_source_manager_binds_resume_config(self) -> None:
+ inputs = mock.MagicMock()
+ manager = self.source.get_resumable_source_manager(inputs)
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is CodefreshResumeConfig
+
+ def test_source_for_pipeline_passes_schema_name_as_endpoint(self) -> None:
+ config = CodefreshSourceConfig(api_key="secret")
+ inputs = mock.MagicMock()
+ inputs.schema_name = "builds"
+ manager = mock.MagicMock()
+
+ with mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.codefresh.source.codefresh_source"
+ ) as mocked_source:
+ self.source.source_for_pipeline(config, manager, inputs)
+
+ mocked_source.assert_called_once()
+ kwargs = mocked_source.call_args.kwargs
+ assert kwargs["api_key"] == "secret"
+ assert kwargs["endpoint"] == "builds"
+ assert kwargs["resumable_source_manager"] is manager
+
+ def test_canonical_descriptions_cover_endpoints(self) -> None:
+ canonical = self.source.get_canonical_descriptions()
+ # Every documented endpoint must be a real endpoint, and the high-value tables are covered.
+ assert set(canonical).issubset(set(ENDPOINTS))
+ for name in ("projects", "pipelines", "builds", "images"):
+ assert name in canonical
+
+
+if __name__ == "__main__":
+ pytest.main([__file__])
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 5ef523b3f7f0..b9a6b4b53dca 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
@@ -754,7 +754,7 @@ class CodaSourceConfig(config.Config):
@config.config
class CodefreshSourceConfig(config.Config):
- pass
+ api_key: str
@config.config