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 env0 import source (#71188)

Tom Owersf196766433b2
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 95608f1ff63a..183076fd1616 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -197,6 +197,7 @@ the row lists both.
| elasticemail | HTTP | requests | ✅ |
| elasticsearch | HTTP | requests | ✅ |
| emailoctopus | HTTP | requests | ✅ |
+| env0 | HTTP | requests | ✅ |
| eventbrite | HTTP | requests | ✅ |
| eventee | HTTP | requests | ✅ |
| eventzilla | HTTP | requests | ✅ |
@@ -682,7 +683,6 @@ doesn't conflict with concurrent PRs.
- eloqua
- employment_hero
- encharge
-- env0
- expensify
- facebook_pages
- fastbill
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/env0/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/env0/canonical_descriptions.py
new file mode 100644
index 000000000000..48f8790e2403
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/env0/canonical_descriptions.py
@@ -0,0 +1,113 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "organizations": {
+ "description": "An env0 organization the API key can access, including its policies and plan settings.",
+ "docs_url": "https://docs.envzero.com/api-reference/organization/list-organizations",
+ "columns": {
+ "id": "Unique identifier of the organization.",
+ "name": "Display name of the organization.",
+ "description": "Description of the organization.",
+ "createdBy": "Identifier of the user who created the organization.",
+ "createdAt": "Timestamp when the organization was created.",
+ "updatedAt": "Timestamp when the organization was last updated.",
+ "role": "The API key's role in the organization.",
+ "maxTtl": "Maximum time-to-live allowed for environments in the organization.",
+ "defaultTtl": "Default time-to-live applied to new environments.",
+ },
+ },
+ "projects": {
+ "description": "A project groups environments, templates, and team access under an organization.",
+ "docs_url": "https://docs.envzero.com/api-reference/projects/list-projects",
+ "columns": {
+ "id": "Unique identifier of the project.",
+ "name": "Display name of the project.",
+ "description": "Description of the project.",
+ "organizationId": "Identifier of the organization the project belongs to.",
+ "parentProjectId": "Identifier of the parent project when this is a sub-project.",
+ "createdBy": "Identifier of the user who created the project.",
+ "isArchived": "Whether the project is archived.",
+ "hierarchy": "The project's position in the project hierarchy.",
+ },
+ },
+ "teams": {
+ "description": "A team of users used to assign roles and project access within an organization.",
+ "docs_url": "https://docs.envzero.com/api-reference/teams/list-teams",
+ "columns": {
+ "id": "Unique identifier of the team.",
+ "name": "Display name of the team.",
+ "description": "Description of the team.",
+ "organizationId": "Identifier of the organization the team belongs to.",
+ "users": "Users that are members of the team.",
+ },
+ },
+ "templates": {
+ "description": "A template (blueprint) defines a deployable environment type: its IaC repository, revision, and tooling.",
+ "docs_url": "https://docs.envzero.com/api-reference/templates/list-templates",
+ "columns": {
+ "id": "Unique identifier of the template.",
+ "name": "Display name of the template.",
+ "type": "IaC tool the template uses (e.g. terraform, opentofu, terragrunt, pulumi).",
+ "repository": "Git repository the template deploys from.",
+ "revision": "Git revision (branch or tag) the template tracks.",
+ "path": "Path within the repository containing the IaC code.",
+ "organizationId": "Identifier of the organization the template belongs to.",
+ "projectIds": "Identifiers of the projects the template is assigned to.",
+ "createdAt": "Timestamp when the template was created.",
+ "updatedAt": "Timestamp when the template was last updated.",
+ "isDeleted": "Whether the template has been deleted.",
+ },
+ },
+ "environments": {
+ "description": "An environment is a deployment managed by env0 — the live instance of a template within a project.",
+ "docs_url": "https://docs.envzero.com/api-reference/environments/list-environments",
+ "columns": {
+ "id": "Unique identifier of the environment.",
+ "name": "Display name of the environment.",
+ "organizationId": "Identifier of the organization the environment belongs to.",
+ "projectId": "Identifier of the project the environment belongs to.",
+ "userId": "Identifier of the user who owns the environment.",
+ "workspaceName": "Terraform/OpenTofu workspace name backing the environment.",
+ "status": "Current status of the environment (e.g. ACTIVE, INACTIVE, FAILED).",
+ "latestDeploymentLogId": "Identifier of the environment's most recent deployment.",
+ "lifespanEndAt": "Timestamp when the environment's TTL expires.",
+ "isArchived": "Whether the environment is archived.",
+ "driftStatus": "Result of the latest drift detection run.",
+ "createdAt": "Timestamp when the environment was created.",
+ "updatedAt": "Timestamp when the environment was last updated.",
+ },
+ },
+ "deployments": {
+ "description": "A deployment log records one deploy, destroy, plan, or drift-detection run of an environment.",
+ "docs_url": "https://docs.envzero.com/api-reference/environments/list-deployments",
+ "columns": {
+ "id": "Unique identifier of the deployment.",
+ "environmentId": "Identifier of the environment the deployment ran against.",
+ "type": "Type of the deployment (e.g. deploy, destroy, prPlan, driftDetection).",
+ "status": "Current status of the deployment (e.g. SUCCESS, FAILURE, IN_PROGRESS).",
+ "startedBy": "Identifier of the user or trigger that started the deployment.",
+ "queuedAt": "Timestamp when the deployment was queued.",
+ "startedAt": "Timestamp when the deployment started running.",
+ "finishedAt": "Timestamp when the deployment finished.",
+ "blueprintId": "Identifier of the template the deployment used.",
+ "blueprintRepository": "Git repository the deployment pulled IaC code from.",
+ "blueprintRevision": "Git revision the deployment used.",
+ "resourceCount": "Number of resources managed by the deployment.",
+ "error": "Error details when the deployment failed.",
+ "planSummary": "Summary of the plan (resources to add, change, and destroy).",
+ "createdAt": "Timestamp when the deployment log was created.",
+ },
+ },
+ "environment_costs": {
+ "description": "Daily cloud cost records for an environment over the last year. Requires cost monitoring to be configured for the environment.",
+ "docs_url": "https://docs.envzero.com/api-reference/cost/get-costs-for-an-environment",
+ "columns": {
+ "environment_id": "Identifier of the environment the cost record belongs to.",
+ "date": "Date of the cost record.",
+ "total": "Total cost for the period.",
+ "isStale": "Whether the cost record is stale and pending refresh.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/env0/env0.py b/products/warehouse_sources/backend/temporal/data_imports/sources/env0/env0.py
new file mode 100644
index 000000000000..9e2e2db4e797
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/env0/env0.py
@@ -0,0 +1,330 @@
+import base64
+import dataclasses
+from collections.abc import Iterator
+from datetime import UTC, date, datetime
+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.common.http import make_tracked_session
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.env0.settings import (
+ ENV0_ENDPOINTS,
+ Env0EndpointConfig,
+)
+
+ENV0_BASE_URL = "https://api.env0.com"
+# Environments/deployments list endpoints cap pages at 100 items.
+PAGE_SIZE = 100
+REQUEST_TIMEOUT_SECONDS = 60
+# env0 rate-limits at 1,000 requests / 60s per IP+method+URI; exponential backoff on 429 suffices.
+MAX_RETRIES = 5
+
+
+class Env0RetryableError(Exception):
+ pass
+
+
+class Env0ResumeConfig:
+ # Stable parent-id bookmark (organization or environment id, per the endpoint's scope; None
+ # for root endpoints) — not a positional index, so parents added/removed between a crash and
+ # the retry can't resume us into the wrong parent.
+ parent_id: str | None = None
+ # Position within the bookmarked parent's page chain: a numeric offset for limit/offset
+ # endpoints, or the teams endpoint's nextPageKey. None means "start at the first page".
+ offset: str | None = None
+
+
+def _get_headers(api_key_id: str, api_key_secret: str) -> dict[str, str]:
+ basic_token = base64.b64encode(f"{api_key_id}:{api_key_secret}".encode("ascii")).decode("ascii")
+ return {
+ "Authorization": f"Basic {basic_token}",
+ "Accept": "application/json",
+ }
+
+
+def _format_date_window_value(value: Any) -> Optional[str]:
+ """Format an incremental cursor as YYYY-MM-DDTHH:mm:ss.sssZ, the format env0's
+ fromDate/toDate params require."""
+ if isinstance(value, datetime):
+ dt = value.replace(tzinfo=UTC) if value.tzinfo is None else value.astimezone(UTC)
+ elif isinstance(value, date):
+ dt = datetime.combine(value, datetime.min.time(), tzinfo=UTC)
+ else:
+ return None
+ return dt.strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z"
+
+
+def _build_date_window_params(
+ config: Env0EndpointConfig,
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Any,
+) -> dict[str, str]:
+ """Build the fromDate/toDate server-side window for incremental syncs.
+
+ env0 requires both params together, so the window runs from the watermark (minus the
+ endpoint's lookback, letting rows that mutated after first fetch be re-pulled and merged)
+ up to now.
+ """
+ if not config.supports_date_window or not should_use_incremental_field:
+ return {}
+
+ if db_incremental_field_last_value is None:
+ return {}
+
+ from_value = db_incremental_field_last_value
+ if config.incremental_lookback is not None and isinstance(from_value, datetime | date):
+ if isinstance(from_value, datetime):
+ from_value = from_value - config.incremental_lookback
+ else:
+ from_value = datetime.combine(from_value, datetime.min.time(), tzinfo=UTC) - config.incremental_lookback
+
+ from_date = _format_date_window_value(from_value)
+ if from_date is None:
+ return {}
+
+ return {"fromDate": from_date, "toDate": _format_date_window_value(datetime.now(UTC)) or ""}
+
+
+def _build_url(config: Env0EndpointConfig, parent_id: str | None, params: dict[str, Any]) -> str:
+ path = config.path.format(parent_id=parent_id) if parent_id is not None else config.path
+ clean_params = {key: value for key, value in params.items() if value is not None}
+ if not clean_params:
+ return f"{ENV0_BASE_URL}{path}"
+ return f"{ENV0_BASE_URL}{path}?{urlencode(clean_params)}"
+
+
+def _build_params(
+ config: Env0EndpointConfig,
+ parent_id: str | None,
+ offset: str | None,
+ date_window_params: dict[str, str],
+) -> dict[str, Any]:
+ params: dict[str, Any] = dict(config.params)
+ if config.org_id_param and parent_id is not None:
+ params[config.org_id_param] = parent_id
+ if config.paginated:
+ params["limit"] = PAGE_SIZE
+ if offset is not None:
+ params["offset"] = offset
+ params.update(date_window_params)
+ return params
+
+
+def validate_credentials(api_key_id: str, api_key_secret: str) -> bool:
+ """Confirm the API key pair is valid. /organizations is a cheap authenticated probe that
+ works for both organization and personal API keys."""
+ try:
+ response = make_tracked_session().get(
+ f"{ENV0_BASE_URL}/organizations",
+ headers=_get_headers(api_key_id, api_key_secret),
+ timeout=10,
+ )
+ return response.status_code == 200
+ except Exception:
+ return False
+
+
+@retry(
+ retry=retry_if_exception_type((Env0RetryableError, requests.ReadTimeout, requests.ConnectionError)),
+ stop=stop_after_attempt(MAX_RETRIES),
+ wait=wait_exponential_jitter(initial=1, max=60),
+ reraise=True,
+)
+def _fetch_page(session: requests.Session, url: str, headers: dict[str, str], logger: FilteringBoundLogger) -> Any:
+ response = session.get(url, headers=headers, timeout=REQUEST_TIMEOUT_SECONDS)
+
+ if response.status_code == 429 or response.status_code >= 500:
+ raise Env0RetryableError(f"env0 API error (retryable): status={response.status_code}, url={url}")
+
+ if not response.ok:
+ # 404s during the per-environment fan-out (environment deleted mid-sync, or cost
+ # monitoring not configured) are handled by the caller.
+ log = logger.warning if response.status_code == 404 else logger.error
+ log(f"env0 API error: status={response.status_code}, body={response.text}, url={url}")
+ response.raise_for_status()
+
+ return response.json()
+
+
+def _extract_items(
+ data: Any, config: Env0EndpointConfig, offset: str | None
+) -> tuple[list[dict[str, Any]], str | None]:
+ """Pull the item list out of a response and compute the next-page offset (None = done).
+
+ Most env0 list endpoints return a bare JSON array; paginated arrays advance a numeric
+ offset until a short page. Teams returns {"teams": [...], "nextPageKey": ...} where the
+ next request's offset is the returned nextPageKey.
+ """
+ if isinstance(data, dict):
+ items = data.get(config.data_key or "items", []) or []
+ next_page_key = data.get("nextPageKey")
+ return items, str(next_page_key) if next_page_key else None
+
+ items = data or []
+ if config.paginated and len(items) == PAGE_SIZE:
+ return items, str(int(offset or 0) + len(items))
+ return items, None
+
+
+def _normalize_row(item: dict[str, Any], config: Env0EndpointConfig, parent_id: str | None) -> dict[str, Any]:
+ row = {key: value for key, value in item.items() if key not in config.strip_fields}
+ if config.inject_parent_id_field and parent_id is not None:
+ row[config.inject_parent_id_field] = parent_id
+ return row
+
+
+def _list_organization_ids(
+ session: requests.Session, headers: dict[str, str], logger: FilteringBoundLogger
+) -> list[str]:
+ data = _fetch_page(session, f"{ENV0_BASE_URL}/organizations", headers, logger)
+ return [org["id"] for org in data or []]
+
+
+def _list_environment_ids(
+ session: requests.Session, headers: dict[str, str], logger: FilteringBoundLogger
+) -> list[str]:
+ """Enumerate every environment id across all accessible organizations, paging through the
+ environments list. The nested latest deployment is excluded to keep enumeration light."""
+ environment_ids: list[str] = []
+ for organization_id in _list_organization_ids(session, headers, logger):
+ offset = 0
+ while True:
+ query = urlencode(
+ {
+ "organizationId": organization_id,
+ "limit": PAGE_SIZE,
+ "offset": offset,
+ "excludeFields": "latestDeploymentLog",
+ }
+ )
+ data = _fetch_page(session, f"{ENV0_BASE_URL}/environments?{query}", headers, logger)
+ items = data or []
+ environment_ids.extend(item["id"] for item in items)
+ if len(items) < PAGE_SIZE:
+ break
+ offset += len(items)
+ return environment_ids
+
+
+def _list_parents(
+ session: requests.Session, headers: dict[str, str], logger: FilteringBoundLogger, config: Env0EndpointConfig
+) -> list[str | None]:
+ if config.scope == "organization":
+ return list(_list_organization_ids(session, headers, logger))
+ if config.scope == "environment":
+ return list(_list_environment_ids(session, headers, logger))
+ return [None]
+
+
+def get_rows(
+ api_key_id: str,
+ api_key_secret: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[Env0ResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+) -> Iterator[list[dict[str, Any]]]:
+ config = ENV0_ENDPOINTS[endpoint]
+ headers = _get_headers(api_key_id, api_key_secret)
+ # One session reused across every page and fan-out parent so urllib3 keeps the connection
+ # alive instead of re-handshaking per request.
+ #
+ # capture=False: sample capture records raw response bodies before _normalize_row strips
+ # deployment secrets (variable `value`s, injected `oidcToken`/`vcsAccessToken`), and the
+ # name-based scrubbers don't recognise those keys. The environment fan-out also enumerates
+ # /environments through this session, whose rows can carry those same secrets nested under
+ # latestDeploymentLog if the API ignores excludeFields. Requests stay metered and logged.
+ session = make_tracked_session(capture=False)
+
+ date_window_params = _build_date_window_params(
+ config, should_use_incremental_field, db_incremental_field_last_value
+ )
+
+ parents = _list_parents(session, headers, logger, config)
+
+ # Resolve the saved parent bookmark to the slice of parents still to process. If the
+ # bookmarked parent no longer exists (deleted between runs), start over from the first —
+ # merge dedupes the re-pulled rows on the primary key.
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ remaining = parents
+ resume_offset: str | None = None
+ if resume is not None and resume.parent_id in parents:
+ remaining = parents[parents.index(resume.parent_id) :]
+ resume_offset = resume.offset
+ logger.debug(f"env0: resuming {endpoint} from parent_id={resume.parent_id}, offset={resume_offset}")
+
+ for index, parent_id in enumerate(remaining):
+ offset = resume_offset
+ resume_offset = None # only the resumed-into parent uses the saved offset
+
+ try:
+ while True:
+ params = _build_params(config, parent_id, offset, date_window_params)
+ url = _build_url(config, parent_id, params)
+ data = _fetch_page(session, url, headers, logger)
+ items, next_offset = _extract_items(data, config, offset)
+
+ rows = [_normalize_row(item, config, parent_id) for item in items]
+ if rows:
+ yield rows
+
+ if next_offset is None:
+ break
+ # Save AFTER yielding so a crash re-yields the last page rather than skipping
+ # it — merge dedupes on the primary key.
+ resumable_source_manager.save_state(Env0ResumeConfig(parent_id=parent_id, offset=next_offset))
+ offset = next_offset
+ except requests.HTTPError as exc:
+ # During the per-environment fan-out, a 404 means the environment was deleted
+ # mid-sync or (for costs) cost monitoring isn't configured for it. Skip it rather
+ # than failing the whole sync; any other HTTP error is re-raised.
+ if config.scope == "environment" and exc.response is not None and exc.response.status_code == 404:
+ logger.warning(f"env0: {endpoint} returned 404 for environment {parent_id}, skipping")
+ else:
+ raise
+
+ # Advance the bookmark to the next parent so a crash between parents resumes correctly.
+ if index + 1 < len(remaining):
+ resumable_source_manager.save_state(Env0ResumeConfig(parent_id=remaining[index + 1], offset=None))
+
+
+def env0_source(
+ api_key_id: str,
+ api_key_secret: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[Env0ResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+) -> SourceResponse:
+ config = ENV0_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ api_key_id=api_key_id,
+ api_key_secret=api_key_secret,
+ endpoint=endpoint,
+ logger=logger,
+ resumable_source_manager=resumable_source_manager,
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ ),
+ primary_keys=config.primary_keys,
+ # env0 doesn't document list ordering and the deployments endpoint fans out per
+ # environment, so the incremental watermark must only persist at successful job end —
+ # "desc" gives exactly that. Full-refresh endpoints have no watermark to protect.
+ sort_mode="desc" if config.incremental_fields else "asc",
+ partition_count=1,
+ partition_size=1,
+ partition_mode="datetime" if config.partition_key else None,
+ partition_format="week" 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/env0/posthog_com_doc.md b/products/warehouse_sources/backend/temporal/data_imports/sources/env0/posthog_com_doc.md
new file mode 100644
index 000000000000..272decadbd96
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/env0/posthog_com_doc.md
@@ -0,0 +1,57 @@
+---
+title: Linking env0 as a source
+sidebar: Docs
+showTitle: true
+availability: { free: full, selfServe: full, enterprise: full }
+sourceId: Env0
+beta: true
+---
+
+import SourceSetupIntro from "../\_snippets/source-setup-intro.mdx"
+import SyncModes from "../\_snippets/sync-modes.mdx"
+import TroubleshootingLink from "../\_snippets/dw-troubleshooting-link.mdx"
+import AlphaRelease from "../\_snippets/alpha-release.mdx"
+
+<AlphaRelease />
+
+The env0 connector syncs your infrastructure-as-code data — organizations, projects, environments, deployment history, teams, templates, and per-environment cloud cost — into PostHog, so you can attribute cloud spend to teams and projects and analyze deployment activity alongside your product data.
+
+## Prerequisites
+
+You need an env0 API key. Organization administrators can create an organization API key, or you can use a personal API key scoped to your user. The key needs read access to the organizations you want to sync.
+
+Environment cost data additionally requires [cost monitoring](https://docs.envzero.com/docs/cost-monitoring) to be configured in env0 for the environments you want cost records for.
+
+## Adding a data source
+
+<SourceSetupIntro />
+
+To connect env0, you need an API key ID and an API key secret:
+
+1. In env0, go to **Organization Settings** → **API Keys** (or create a [personal API key](https://docs.envzero.com/docs/api-keys) from your user settings).
+2. Create a new API key and copy both the **API Key ID** and the **API Key Secret** — the secret is only shown once.
+3. Paste them into the PostHog source setup form.
+
+## Sync modes
+
+<SyncModes />
+
+The `deployments` table supports incremental sync on `startedAt`. Deployments can change after they first sync (their status and finish time land when the run completes), so incremental syncs re-pull a one-day window behind the last synced deployment to keep recently-synced rows fresh.
+
+The `environment_costs` table always syncs the last year of daily cost records per environment, so full refresh is the right mode for it.
+
+## Configuration
+
+<SourceParameters />
+
+## Supported tables
+
+<SourceTables />
+
+## Troubleshooting
+
+**Missing cost data:** the `environment_costs` table only has rows for environments where env0 cost monitoring is configured. Environments without it are skipped.
+
+**Rate limits:** env0 limits API usage to 1,000 requests per 60 seconds. Deployments and costs are fetched per environment, so accounts with very many environments may sync these tables slowly — the connector backs off and retries automatically.
+
+<TroubleshootingLink />
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/env0/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/env0/settings.py
new file mode 100644
index 000000000000..a2ddc89e7c4a
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/env0/settings.py
@@ -0,0 +1,125 @@
+from dataclasses import dataclass, field
+from datetime import timedelta
+from typing import Literal, Optional
+
+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+
+Env0EndpointScope = Literal["root", "organization", "environment"]
+
+
+@dataclass
+class Env0EndpointConfig:
+ name: str
+ # Path template; `{parent_id}` is replaced with the fan-out parent's id (organization or
+ # environment, per `scope`).
+ path: str
+ # "root" endpoints are called once; "organization"/"environment" endpoints fan out one
+ # request chain per parent resource.
+ scope: Env0EndpointScope = "root"
+ # env0's core list endpoints are mostly unpaginated JSON arrays; only environments,
+ # deployments, and teams document limit/offset pagination.
+ paginated: bool = False
+ # Key the item list is nested under when the endpoint returns an object instead of a bare
+ # array (teams returns {"teams": [...], "nextPageKey": ...} when paginating).
+ data_key: Optional[str] = None
+ # Query param that carries the organization id for org-scoped endpoints whose path
+ # doesn't embed it.
+ org_id_param: Optional[str] = None
+ params: dict[str, str] = field(default_factory=dict)
+ primary_keys: list[str] = field(default_factory=lambda: ["id"])
+ # Stable creation-time field used for datetime partitioning. Never an updatedAt-style
+ # field, which would rewrite partitions on every sync.
+ partition_key: Optional[str] = None
+ incremental_fields: list[IncrementalField] = field(default_factory=list)
+ # Response fields dropped client-side before yielding: huge free-text blobs (raw
+ # Terraform output) and secret-bearing fields (deployment variable values, injected
+ # OIDC/VCS tokens) that must not be persisted to the warehouse.
+ strip_fields: tuple[str, ...] = ()
+ # Endpoint supports env0's server-side fromDate/toDate window (must be passed together).
+ supports_date_window: bool = False
+ # When set, each row gets the fan-out parent's id injected under this column so the
+ # primary key stays unique table-wide.
+ inject_parent_id_field: Optional[str] = None
+ # Safety overlap subtracted from the incremental watermark on every run, re-pulling a
+ # window that merge dedupes on the primary key. Deployments mutate after creation
+ # (status/finishedAt land when the run completes), so re-pulling the last day refreshes
+ # rows first fetched mid-run.
+ incremental_lookback: Optional[timedelta] = None
+
+
+ENV0_ENDPOINTS: dict[str, Env0EndpointConfig] = {
+ "organizations": Env0EndpointConfig(
+ name="organizations",
+ path="/organizations",
+ ),
+ "projects": Env0EndpointConfig(
+ name="projects",
+ path="/projects",
+ scope="organization",
+ org_id_param="organizationId",
+ ),
+ "teams": Env0EndpointConfig(
+ name="teams",
+ path="/teams/organizations/{parent_id}",
+ scope="organization",
+ paginated=True,
+ data_key="teams",
+ ),
+ "templates": Env0EndpointConfig(
+ name="templates",
+ path="/blueprints",
+ scope="organization",
+ org_id_param="organizationId",
+ ),
+ "environments": Env0EndpointConfig(
+ name="environments",
+ path="/environments",
+ scope="organization",
+ org_id_param="organizationId",
+ paginated=True,
+ partition_key="createdAt",
+ # The nested latest deployment carries megabytes of raw Terraform output/plan AND
+ # secret-bearing fields (deployment variables, injected OIDC/VCS tokens). Excluded
+ # server-side and stripped client-side too in case the API ignores the param; the
+ # deployments table covers per-deployment analytics.
+ params={"excludeFields": "latestDeploymentLog"},
+ strip_fields=("latestDeploymentLog",),
+ ),
+ "deployments": Env0EndpointConfig(
+ name="deployments",
+ path="/environments/{parent_id}/deployments",
+ scope="environment",
+ paginated=True,
+ partition_key="createdAt",
+ # output/plan are huge free-text blobs; variables carries raw variable values and
+ # customEnv0EnvironmentVariables carries injected credentials (oidcToken,
+ # vcsAccessToken) — none of these may land in the warehouse.
+ strip_fields=("output", "plan", "variables", "customEnv0EnvironmentVariables"),
+ supports_date_window=True,
+ incremental_lookback=timedelta(hours=24),
+ incremental_fields=[
+ {
+ "label": "startedAt",
+ "type": IncrementalFieldType.DateTime,
+ "field": "startedAt",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+ ],
+ ),
+ "environment_costs": Env0EndpointConfig(
+ name="environment_costs",
+ path="/costs/environments/{parent_id}",
+ scope="environment",
+ # The cost endpoint only takes a relative timespan (DAY..YEAR), not an arbitrary date
+ # range, so the widest window with daily grain is the best full-refresh shape.
+ params={"timespan": "YEAR", "granularity": "DAILY"},
+ primary_keys=["environment_id", "date"],
+ inject_parent_id_field="environment_id",
+ ),
+}
+
+ENDPOINTS = tuple(ENV0_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in ENV0_ENDPOINTS.items() if config.incremental_fields
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/env0/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/env0/source.py
index db9c9b2af8e3..8726e41184a8 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/env0/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/env0/source.py
@@ -1,19 +1,39 @@
-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.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.env0.env0 import (
+ Env0ResumeConfig,
+ env0_source,
+ validate_credentials as validate_env0_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.env0.settings import ENDPOINTS, INCREMENTAL_FIELDS
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import Env0SourceConfig
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class Env0Source(SimpleSource[Env0SourceConfig]):
+class Env0Source(ResumableSource[Env0SourceConfig, Env0ResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.ENV0
@@ -23,8 +43,101 @@ class Env0Source(SimpleSource[Env0SourceConfig]):
return SourceConfig(
name=SchemaExternalDataSourceType.ENV0,
category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,
- label="env0 (env zero)",
+ label="env0",
+ caption="""Enter your env0 API key credentials to pull your env0 data into the PostHog Data warehouse.
+
+You can create an organization API key in your env0 [Organization Settings > API Keys](https://docs.envzero.com/docs/api-keys), or a personal API key from your user settings. The key needs read access to the organizations you want to sync.
+
+Environment cost data is only available for environments with [cost monitoring](https://docs.envzero.com/docs/cost-monitoring) configured.""",
iconPath="/static/services/env0.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/env0",
+ releaseStatus=ReleaseStatus.ALPHA,
+ keywords=["env zero", "iac", "terraform"],
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_key_id",
+ label="API key ID",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="",
+ secret=False,
+ ),
+ SourceFieldInputConfig(
+ name="api_key_secret",
+ label="API key secret",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
+ )
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error: Unauthorized for url: https://api.env0.com": "env0 authentication failed. Please check your API key ID and secret.",
+ "403 Client Error: Forbidden for url: https://api.env0.com": "env0 denied access. Please check that your API key has read access to this organization.",
+ }
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.env0.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_schemas(
+ self,
+ config: Env0SourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ schemas = [
+ SourceSchema(
+ name=endpoint,
+ supports_incremental=INCREMENTAL_FIELDS.get(endpoint, None) is not None,
+ supports_append=INCREMENTAL_FIELDS.get(endpoint, None) is not None,
+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),
+ )
+ for endpoint in list(ENDPOINTS)
+ ]
+
+ if names is not None:
+ names_set = set(names)
+ schemas = [s for s in schemas if s.name in names_set]
+
+ return schemas
+
+ def validate_credentials(
+ self, config: Env0SourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ if validate_env0_credentials(config.api_key_id, config.api_key_secret):
+ return True, None
+
+ return False, "Invalid env0 API key credentials"
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[Env0ResumeConfig]:
+ return ResumableSourceManager[Env0ResumeConfig](inputs, Env0ResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: Env0SourceConfig,
+ resumable_source_manager: ResumableSourceManager[Env0ResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return env0_source(
+ api_key_id=config.api_key_id,
+ api_key_secret=config.api_key_secret,
+ endpoint=inputs.schema_name,
+ logger=inputs.logger,
+ resumable_source_manager=resumable_source_manager,
+ should_use_incremental_field=inputs.should_use_incremental_field,
+ db_incremental_field_last_value=inputs.db_incremental_field_last_value
+ if inputs.should_use_incremental_field
+ else None,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/env0/tests/test_env0.py b/products/warehouse_sources/backend/temporal/data_imports/sources/env0/tests/test_env0.py
new file mode 100644
index 000000000000..c02e9467340e
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/env0/tests/test_env0.py
@@ -0,0 +1,302 @@
+from datetime import UTC, datetime
+from typing import Any
+from urllib.parse import parse_qs, urlparse
+
+import pytest
+from unittest import mock
+
+import requests
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.env0.env0 import (
+ PAGE_SIZE,
+ Env0ResumeConfig,
+ _build_date_window_params,
+ env0_source,
+ get_rows,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.env0.settings import ENDPOINTS, ENV0_ENDPOINTS
+
+MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.env0.env0"
+
+
+def _make_manager(resume_state: Env0ResumeConfig | None = None) -> mock.MagicMock:
+ manager = mock.MagicMock()
+ manager.can_resume.return_value = resume_state is not None
+ manager.load_state.return_value = resume_state
+ return manager
+
+
+def _response(payload: Any, status_code: int = 200) -> mock.MagicMock:
+ resp = mock.MagicMock()
+ resp.status_code = status_code
+ resp.ok = status_code < 400
+ resp.json.return_value = payload
+ if status_code >= 400:
+ resp.raise_for_status.side_effect = requests.HTTPError(f"{status_code} Client Error", response=resp)
+ return resp
+
+
+def _requested_urls(mock_session: mock.MagicMock) -> list[str]:
+ return [call.args[0] for call in mock_session.return_value.get.call_args_list]
+
+
+def _query(url: str) -> dict[str, list[str]]:
+ return parse_qs(urlparse(url).query)
+
+
+class TestBuildDateWindowParams:
+ def test_incremental_deployments_sends_from_and_to_date_together(self):
+ watermark = datetime(2026, 6, 1, 12, 0, 0, tzinfo=UTC)
+ params = _build_date_window_params(ENV0_ENDPOINTS["deployments"], True, watermark)
+
+ # env0 rejects fromDate without toDate, so both must always be present together.
+ assert params["fromDate"] == "2026-05-31T12:00:00.000Z" # watermark minus the 24h lookback
+ assert params["toDate"].endswith("Z")
+
+ @pytest.mark.parametrize(
+ "endpoint, should_use_incremental_field, last_value",
+ [
+ ("deployments", True, None),
+ ("deployments", False, datetime(2026, 6, 1, tzinfo=UTC)),
+ ("environments", True, datetime(2026, 6, 1, tzinfo=UTC)),
+ ],
+ )
+ def test_no_window_without_watermark_or_support(self, endpoint, should_use_incremental_field, last_value):
+ assert _build_date_window_params(ENV0_ENDPOINTS[endpoint], should_use_incremental_field, last_value) == {}
+
+
+class TestValidateCredentials:
+ @pytest.mark.parametrize(
+ "status_code, expected",
+ [
+ (200, True),
+ (401, False),
+ (403, False),
+ (500, False),
+ ],
+ )
+ @mock.patch(f"{MODULE}.make_tracked_session")
+ def test_validate_credentials_status_mapping(self, mock_session, status_code, expected):
+ response = mock.MagicMock()
+ response.status_code = status_code
+ mock_session.return_value.get.return_value = response
+
+ assert validate_credentials("key-id", "key-secret") is expected
+
+ @mock.patch(f"{MODULE}.make_tracked_session")
+ def test_validate_credentials_swallows_exceptions(self, mock_session):
+ mock_session.return_value.get.side_effect = Exception("boom")
+ assert validate_credentials("key-id", "key-secret") is False
+
+
+class TestGetRows:
+ @mock.patch(f"{MODULE}.make_tracked_session")
+ def test_root_endpoint_fetches_once(self, mock_session):
+ mock_session.return_value.get.return_value = _response([{"id": "org-1"}, {"id": "org-2"}])
+
+ manager = _make_manager()
+ batches = list(get_rows("key-id", "key-secret", "organizations", mock.MagicMock(), manager))
+
+ assert [row["id"] for batch in batches for row in batch] == ["org-1", "org-2"]
+ assert mock_session.return_value.get.call_count == 1
+ manager.save_state.assert_not_called()
+
+ @mock.patch(f"{MODULE}.make_tracked_session")
+ def test_org_scoped_endpoint_fans_out_over_organizations(self, mock_session):
+ mock_session.return_value.get.side_effect = [
+ _response([{"id": "org-1"}, {"id": "org-2"}]),
+ _response([{"id": "proj-1"}]),
+ _response([{"id": "proj-2"}]),
+ ]
+
+ manager = _make_manager()
+ batches = list(get_rows("key-id", "key-secret", "projects", mock.MagicMock(), manager))
+
+ assert [row["id"] for batch in batches for row in batch] == ["proj-1", "proj-2"]
+ urls = _requested_urls(mock_session)
+ assert _query(urls[1])["organizationId"] == ["org-1"]
+ assert _query(urls[2])["organizationId"] == ["org-2"]
+ # Bookmark advances to the next organization so a crash between parents resumes there.
+ manager.save_state.assert_called_once_with(Env0ResumeConfig(parent_id="org-2", offset=None))
+
+ @mock.patch(f"{MODULE}.make_tracked_session")
+ def test_offset_pagination_advances_until_short_page(self, mock_session):
+ full_page = [{"id": f"env-{i}"} for i in range(PAGE_SIZE)]
+ mock_session.return_value.get.side_effect = [
+ _response([{"id": "org-1"}]),
+ _response(full_page),
+ # latestDeploymentLog embeds deployment variables and injected tokens; it must be
+ # dropped even when the server ignores the excludeFields param.
+ _response(
+ [{"id": "env-last", "latestDeploymentLog": {"customEnv0EnvironmentVariables": {"oidcToken": "x"}}}]
+ ),
+ ]
+
+ manager = _make_manager()
+ batches = list(get_rows("key-id", "key-secret", "environments", mock.MagicMock(), manager))
+
+ assert sum(len(batch) for batch in batches) == PAGE_SIZE + 1
+ assert batches[-1][-1] == {"id": "env-last"}
+ environments_query = _query(_requested_urls(mock_session)[1])
+ assert environments_query["excludeFields"] == ["latestDeploymentLog"]
+ urls = _requested_urls(mock_session)
+ assert "offset" not in _query(urls[1])
+ assert _query(urls[2])["offset"] == [str(PAGE_SIZE)]
+ # State saved after yielding the full page, pointing at the next offset.
+ manager.save_state.assert_called_once_with(Env0ResumeConfig(parent_id="org-1", offset=str(PAGE_SIZE)))
+
+ @mock.patch(f"{MODULE}.make_tracked_session")
+ def test_teams_pagination_follows_next_page_key(self, mock_session):
+ mock_session.return_value.get.side_effect = [
+ _response([{"id": "org-1"}]),
+ _response({"teams": [{"id": "team-1"}], "nextPageKey": "key-abc"}),
+ _response({"teams": [{"id": "team-2"}]}),
+ ]
+
+ manager = _make_manager()
+ batches = list(get_rows("key-id", "key-secret", "teams", mock.MagicMock(), manager))
+
+ assert [row["id"] for batch in batches for row in batch] == ["team-1", "team-2"]
+ urls = _requested_urls(mock_session)
+ assert _query(urls[2])["offset"] == ["key-abc"]
+
+ @mock.patch(f"{MODULE}.make_tracked_session")
+ def test_deployments_fan_out_strips_heavy_and_secret_fields_and_windows_requests(self, mock_session):
+ mock_session.return_value.get.side_effect = [
+ _response([{"id": "org-1"}]),
+ _response([{"id": "env-1"}]),
+ _response(
+ [
+ {
+ "id": "dep-1",
+ "status": "SUCCESS",
+ "output": "x" * 100,
+ "plan": {"big": True},
+ "variables": [{"name": "DB_PASSWORD", "value": "hunter2", "isSensitive": False}],
+ "customEnv0EnvironmentVariables": {"oidcToken": "eyJ...", "vcsAccessToken": "ghs_..."},
+ }
+ ]
+ ),
+ ]
+
+ manager = _make_manager()
+ watermark = datetime(2026, 6, 1, tzinfo=UTC)
+ batches = list(
+ get_rows(
+ "key-id",
+ "key-secret",
+ "deployments",
+ mock.MagicMock(),
+ manager,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=watermark,
+ )
+ )
+
+ rows = [row for batch in batches for row in batch]
+ assert rows == [{"id": "dep-1", "status": "SUCCESS"}]
+
+ deployments_query = _query(_requested_urls(mock_session)[2])
+ assert deployments_query["fromDate"] == ["2026-05-31T00:00:00.000Z"]
+ assert "toDate" in deployments_query
+
+ @mock.patch(f"{MODULE}.make_tracked_session")
+ def test_costs_inject_environment_id_and_skip_404s(self, mock_session):
+ mock_session.return_value.get.side_effect = [
+ _response([{"id": "org-1"}]),
+ _response([{"id": "env-1"}, {"id": "env-2"}]),
+ # env-1 has no cost monitoring configured.
+ _response({"message": "not found"}, status_code=404),
+ _response([{"date": "2026-06-01", "total": 12.5}]),
+ ]
+
+ manager = _make_manager()
+ batches = list(get_rows("key-id", "key-secret", "environment_costs", mock.MagicMock(), manager))
+
+ rows = [row for batch in batches for row in batch]
+ assert rows == [{"date": "2026-06-01", "total": 12.5, "environment_id": "env-2"}]
+
+ @mock.patch(f"{MODULE}.make_tracked_session")
+ def test_non_404_error_fails_the_sync(self, mock_session):
+ mock_session.return_value.get.side_effect = [
+ _response([{"id": "org-1"}]),
+ _response([{"id": "env-1"}]),
+ _response({"message": "forbidden"}, status_code=403),
+ ]
+
+ with pytest.raises(requests.HTTPError):
+ list(get_rows("key-id", "key-secret", "environment_costs", mock.MagicMock(), _make_manager()))
+
+ @mock.patch(f"{MODULE}.make_tracked_session")
+ def test_resume_skips_already_processed_parents(self, mock_session):
+ mock_session.return_value.get.side_effect = [
+ _response([{"id": "org-1"}, {"id": "org-2"}]),
+ _response([{"id": "proj-2"}]),
+ ]
+
+ manager = _make_manager(Env0ResumeConfig(parent_id="org-2", offset=None))
+ batches = list(get_rows("key-id", "key-secret", "projects", mock.MagicMock(), manager))
+
+ assert [row["id"] for batch in batches for row in batch] == ["proj-2"]
+ urls = _requested_urls(mock_session)
+ assert len(urls) == 2
+ assert _query(urls[1])["organizationId"] == ["org-2"]
+
+ @mock.patch(f"{MODULE}.make_tracked_session")
+ def test_resume_offset_applies_only_to_bookmarked_parent(self, mock_session):
+ mock_session.return_value.get.side_effect = [
+ _response([{"id": "org-1"}, {"id": "org-2"}]),
+ _response([{"id": "env-9"}]),
+ _response([{"id": "env-10"}]),
+ ]
+
+ manager = _make_manager(Env0ResumeConfig(parent_id="org-1", offset="200"))
+ list(get_rows("key-id", "key-secret", "environments", mock.MagicMock(), manager))
+
+ urls = _requested_urls(mock_session)
+ assert _query(urls[1])["offset"] == ["200"]
+ # The next parent starts a fresh page chain.
+ assert "offset" not in _query(urls[2])
+
+ @mock.patch(f"{MODULE}.make_tracked_session")
+ def test_stale_resume_bookmark_starts_over(self, mock_session):
+ mock_session.return_value.get.side_effect = [
+ _response([{"id": "org-1"}]),
+ _response([{"id": "proj-1"}]),
+ ]
+
+ manager = _make_manager(Env0ResumeConfig(parent_id="org-deleted", offset="100"))
+ batches = list(get_rows("key-id", "key-secret", "projects", mock.MagicMock(), manager))
+
+ assert [row["id"] for batch in batches for row in batch] == ["proj-1"]
+ assert "offset" not in _query(_requested_urls(mock_session)[1])
+
+
+class TestEnv0SourceResponse:
+ @pytest.mark.parametrize("endpoint", list(ENDPOINTS))
+ def test_response_metadata_per_endpoint(self, endpoint):
+ config = ENV0_ENDPOINTS[endpoint]
+ response = env0_source("key-id", "key-secret", endpoint, mock.MagicMock(), _make_manager())
+
+ assert response.name == endpoint
+ assert response.primary_keys == config.primary_keys
+ # Unverified API ordering: incremental endpoints must persist their watermark only at
+ # successful job end, which "desc" guarantees.
+ assert response.sort_mode == ("desc" if config.incremental_fields else "asc")
+ if config.partition_key:
+ assert response.partition_mode == "datetime"
+ assert response.partition_keys == [config.partition_key]
+ else:
+ assert response.partition_mode is None
+ assert response.partition_keys is None
+
+ def test_fan_out_child_primary_keys_include_parent_id(self):
+ # Cost rows have no globally-unique id of their own; without the environment id in the
+ # key, rows from different environments on the same date would merge into one.
+ assert ENV0_ENDPOINTS["environment_costs"].primary_keys == ["environment_id", "date"]
+
+ @pytest.mark.parametrize("config", list(ENV0_ENDPOINTS.values()))
+ def test_partition_keys_are_stable_creation_fields(self, config):
+ if config.partition_key:
+ assert config.partition_key == "createdAt"
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/env0/tests/test_env0_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/env0/tests/test_env0_source.py
new file mode 100644
index 000000000000..85f161d81c31
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/env0/tests/test_env0_source.py
@@ -0,0 +1,140 @@
+import pytest
+from unittest import mock
+
+from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.env0.env0 import Env0ResumeConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.env0.settings import ENDPOINTS, INCREMENTAL_FIELDS
+from products.warehouse_sources.backend.temporal.data_imports.sources.env0.source import Env0Source
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import Env0SourceConfig
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+class TestEnv0Source:
+ def setup_method(self):
+ self.source = Env0Source()
+ self.team_id = 123
+ self.config = Env0SourceConfig(api_key_id="key-id", api_key_secret="key-secret")
+
+ def test_source_type(self):
+ assert self.source.source_type == ExternalDataSourceType.ENV0
+
+ def test_get_source_config(self):
+ config = self.source.get_source_config
+
+ assert config.name.value == "Env0"
+ assert config.label == "env0"
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.unreleasedSource is None
+ assert config.iconPath == "/static/services/env0.png"
+
+ field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]
+ assert field_names == ["api_key_id", "api_key_secret"]
+
+ def test_api_key_secret_field_is_secret_password(self):
+ config = self.source.get_source_config
+ secret_field = next(
+ f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "api_key_secret"
+ )
+ assert secret_field.type == SourceFieldInputConfigType.PASSWORD
+ assert secret_field.secret is True
+ assert secret_field.required is True
+
+ @pytest.mark.parametrize(
+ "observed_error",
+ [
+ "401 Client Error: Unauthorized for url: https://api.env0.com/environments?limit=100",
+ "403 Client Error: Forbidden for url: https://api.env0.com/projects?organizationId=org-1",
+ ],
+ )
+ def test_non_retryable_errors_match_auth_failures(self, observed_error):
+ non_retryable_errors = self.source.get_non_retryable_errors()
+ assert any(key in observed_error for key in non_retryable_errors)
+
+ @pytest.mark.parametrize(
+ "other_vendor_error",
+ [
+ "401 Client Error: Unauthorized for url: https://api.stripe.com/v1/customers",
+ "500 Server Error for url: https://api.env0.com/environments",
+ ],
+ )
+ def test_non_retryable_errors_does_not_match_unrelated(self, other_vendor_error):
+ non_retryable_errors = self.source.get_non_retryable_errors()
+ assert not any(key in other_vendor_error for key in non_retryable_errors)
+
+ def test_get_schemas(self):
+ schemas = self.source.get_schemas(self.config, self.team_id)
+
+ assert {schema.name for schema in schemas} == set(ENDPOINTS)
+ incremental = {schema.name for schema in schemas if schema.supports_incremental}
+ # Only deployments expose env0's server-side fromDate/toDate window.
+ assert incremental == {"deployments"}
+
+ def test_incremental_schemas_advertise_their_fields(self):
+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}
+
+ assert schemas["deployments"].incremental_fields == INCREMENTAL_FIELDS["deployments"]
+ assert schemas["environments"].incremental_fields == []
+ assert schemas["environments"].supports_append is False
+
+ def test_get_schemas_filtered_by_names(self):
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["deployments"])
+ assert len(schemas) == 1
+ assert schemas[0].name == "deployments"
+
+ @pytest.mark.parametrize(
+ "mock_return, expected_valid, expected_message",
+ [
+ (True, True, None),
+ (False, False, "Invalid env0 API key credentials"),
+ ],
+ )
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.env0.source.validate_env0_credentials"
+ )
+ def test_validate_credentials(self, mock_validate, mock_return, expected_valid, expected_message):
+ mock_validate.return_value = mock_return
+
+ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id)
+
+ assert is_valid is expected_valid
+ assert error_message == expected_message
+ mock_validate.assert_called_once_with(self.config.api_key_id, self.config.api_key_secret)
+
+ def test_get_resumable_source_manager_binds_resume_config(self):
+ inputs = mock.MagicMock()
+ manager = self.source.get_resumable_source_manager(inputs)
+
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is Env0ResumeConfig
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.env0.source.env0_source")
+ def test_source_for_pipeline_plumbs_arguments(self, mock_env0_source):
+ inputs = mock.MagicMock()
+ inputs.schema_name = "deployments"
+ inputs.should_use_incremental_field = True
+ inputs.db_incremental_field_last_value = "2026-01-01"
+ manager = mock.MagicMock()
+
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ mock_env0_source.assert_called_once()
+ kwargs = mock_env0_source.call_args.kwargs
+ assert kwargs["api_key_id"] == "key-id"
+ assert kwargs["api_key_secret"] == "key-secret"
+ assert kwargs["endpoint"] == "deployments"
+ assert kwargs["resumable_source_manager"] is manager
+ assert kwargs["should_use_incremental_field"] is True
+ assert kwargs["db_incremental_field_last_value"] == "2026-01-01"
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.env0.source.env0_source")
+ def test_source_for_pipeline_omits_last_value_on_full_refresh(self, mock_env0_source):
+ inputs = mock.MagicMock()
+ inputs.schema_name = "environments"
+ inputs.should_use_incremental_field = False
+ inputs.db_incremental_field_last_value = "2026-01-01"
+
+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)
+
+ assert mock_env0_source.call_args.kwargs["db_incremental_field_last_value"] is None
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 755358dca023..736d37565747 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
@@ -1470,7 +1470,8 @@ class EnchargeSourceConfig(config.Config):
@config.config
class Env0SourceConfig(config.Config):
- pass
+ api_key_id: str
+ api_key_secret: str
@config.config