:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): implement terraform_cloud import source (#71173)
Tom Owers5f9dfe9c06f2
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 51c2d60c2c36..66b48f0bb1dc 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -444,6 +444,7 @@ the row lists both.| teamwork | HTTP | requests | ✅ || tempo | HTTP | requests | ✅ || temporalio | gRPC (vendor SDK) | temporalio (`Client`, Rust core via `temporalio.bridge`) | ⚠️ |+| terraform_cloud | HTTP | requests | ✅ || testrail | HTTP | requests | ✅ || thinkific | HTTP | requests | ✅ || tickettailor | HTTP | requests | ✅ |@@ -928,7 +929,6 @@ doesn't conflict with concurrent PRs.- tempo- tenable_vulnerability_management- terra_api-- terraform_cloud- thinkific_courses- thrive_learning- ticketmasterdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.pyindex 8ab36516dda4..c944df3a8e36 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@@ -4223,7 +4223,8 @@ class TerraApiSourceConfig(config.Config):@config.configclass TerraformCloudSourceConfig(config.Config):- pass+ api_token: str+ organization: str@config.configdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/terraform_cloud/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/terraform_cloud/canonical_descriptions.pynew file mode 100644index 000000000000..01ac1cf9ce11--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/terraform_cloud/canonical_descriptions.py@@ -0,0 +1,108 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "organizations": {+ "description": "The configured HCP Terraform organization. An organization is a shared space for teams to collaborate on workspaces.",+ "docs_url": "https://developer.hashicorp.com/terraform/cloud-docs/api-docs/organizations",+ "columns": {+ "id": "Unique identifier of the organization — its name.",+ "name": "Name of the organization.",+ "external_id": "Immutable external identifier of the organization (org-...).",+ "created_at": "When the organization was created.",+ "email": "Admin email address for the organization.",+ "plan_expired": "Whether the organization's paid plan has expired.",+ "plan_expires_at": "When the organization's paid plan expires.",+ "cost_estimation_enabled": "Whether cost estimation is enabled for the organization.",+ "saml_enabled": "Whether SAML single sign-on is enabled.",+ "default_execution_mode": "Default execution mode for new workspaces (remote, local, or agent).",+ },+ },+ "projects": {+ "description": "Projects in the configured organization. Projects group related workspaces and let teams organize permissions at a higher level.",+ "docs_url": "https://developer.hashicorp.com/terraform/cloud-docs/api-docs/projects",+ "columns": {+ "id": "Unique identifier of the project (prj-...).",+ "name": "Name of the project.",+ "description": "Description of the project.",+ "created_at": "When the project was created.",+ "workspace_count": "Number of workspaces in the project.",+ "team_count": "Number of teams with access to the project.",+ "organization_id": "Name of the organization the project belongs to.",+ },+ },+ "teams": {+ "description": "Teams in the configured organization. Teams group users and are granted permissions on workspaces and projects.",+ "docs_url": "https://developer.hashicorp.com/terraform/cloud-docs/api-docs/teams",+ "columns": {+ "id": "Unique identifier of the team (team-...).",+ "name": "Name of the team.",+ "users_count": "Number of users on the team.",+ "visibility": "Team visibility within the organization (secret or organization).",+ "organization_access": "Organization-level permissions granted to the team.",+ "sso_team_id": "SSO team id mapped to this team, when SSO team management is enabled.",+ },+ },+ "workspaces": {+ "description": "Workspaces in the configured organization. A workspace holds a Terraform configuration, its state, and its run history.",+ "docs_url": "https://developer.hashicorp.com/terraform/cloud-docs/api-docs/workspaces",+ "columns": {+ "id": "Unique identifier of the workspace (ws-...).",+ "name": "Name of the workspace.",+ "created_at": "When the workspace was created.",+ "updated_at": "When the workspace was last updated.",+ "auto_apply": "Whether successful plans are automatically applied.",+ "execution_mode": "How runs execute (remote, local, or agent).",+ "terraform_version": "Terraform version the workspace runs.",+ "working_directory": "Relative path Terraform executes in.",+ "locked": "Whether the workspace is currently locked.",+ "resource_count": "Number of resources tracked in the workspace's current state.",+ "latest_change_at": "When the workspace last changed (run, state, or settings).",+ "organization_id": "Name of the organization the workspace belongs to.",+ "project_id": "Identifier of the project the workspace belongs to.",+ "current_run_id": "Identifier of the workspace's current run.",+ },+ },+ "runs": {+ "description": "Runs across every workspace in the organization. A run is one plan/apply cycle performed against a workspace's configuration.",+ "docs_url": "https://developer.hashicorp.com/terraform/cloud-docs/api-docs/run",+ "columns": {+ "id": "Unique identifier of the run (run-...).",+ "status": "Current status of the run (e.g. planned, applied, errored, canceled).",+ "status_timestamps": "Timestamps for each status transition the run has reached.",+ "created_at": "When the run was created.",+ "message": "Message describing why the run was queued.",+ "is_destroy": "Whether the run destroys all managed infrastructure.",+ "source": "What triggered the run (e.g. tfe-ui, tfe-api, tfe-configuration-version).",+ "trigger_reason": "Why the run was triggered.",+ "has_changes": "Whether the plan detected resource changes.",+ "auto_apply": "Whether the run applies automatically after a successful plan.",+ "plan_only": "Whether the run is speculative (plan only, never applied).",+ "terraform_version": "Terraform version used for the run.",+ "workspace_id": "Identifier of the workspace the run belongs to.",+ "workspace_name": "Name of the workspace the run belongs to.",+ "plan_id": "Identifier of the run's plan.",+ "apply_id": "Identifier of the run's apply.",+ "configuration_version_id": "Identifier of the configuration version the run used.",+ },+ },+ "state_versions": {+ "description": "State versions across every workspace in the organization. A state version is one snapshot of a workspace's Terraform state, created by an apply or an upload.",+ "docs_url": "https://developer.hashicorp.com/terraform/cloud-docs/api-docs/state-versions",+ "columns": {+ "id": "Unique identifier of the state version (sv-...).",+ "serial": "Monotonically increasing serial number of the state within its workspace.",+ "created_at": "When the state version was created.",+ "size": "Size of the state file in bytes.",+ "state_version": "Version of the Terraform state file format.",+ "terraform_version": "Terraform version that produced the state.",+ "resources_processed": "Whether HCP Terraform has finished parsing resources out of the state.",+ "modules": "Resource counts grouped by module.",+ "providers": "Resource counts grouped by provider.",+ "workspace_id": "Identifier of the workspace the state version belongs to.",+ "workspace_name": "Name of the workspace the state version belongs to.",+ "run_id": "Identifier of the run that created the state version, when applicable.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/terraform_cloud/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/terraform_cloud/settings.pynew file mode 100644index 000000000000..a08429655a96--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/terraform_cloud/settings.py@@ -0,0 +1,109 @@+from dataclasses import dataclass, field+from datetime import timedelta+from typing import Literal, Optional++from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType++CREATED_AT_INCREMENTAL_FIELDS: list[IncrementalField] = [+ {+ "label": "created_at",+ "type": IncrementalFieldType.DateTime,+ "field": "created_at",+ "field_type": IncrementalFieldType.DateTime,+ },+]+++@dataclass+class TerraformCloudEndpointConfig:+ name: str+ # Path template. `{organization}` is filled from the source config; fan-out endpoints may+ # also use `{workspace_id}` (filled per workspace).+ path: str+ # Extra query param templates, formatted with the same placeholders as `path` plus+ # `{workspace_name}` (state versions are listed by workspace *name*, not id).+ params: dict[str, str] = field(default_factory=dict)+ # Partition on a STABLE creation timestamp so partitions don't rewrite on every sync.+ partition_key: Optional[str] = None+ primary_keys: list[str] = field(default_factory=lambda: ["id"])+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ # The API has no server-side updated-since filter. Runs and state versions are returned+ # newest-first by creation time, so incremental sync pages descending and stops once an+ # entire page predates the watermark (see terraform_cloud.py); "desc" tells the pipeline+ # to persist the watermark only at successful job end.+ sort_mode: Literal["asc", "desc"] = "asc"+ # Fan out one paginated request sequence per workspace in the organization.+ fan_out_over_workspaces: bool = False+ # Safety overlap subtracted from the incremental watermark on every run, re-pulling a+ # window of rows that merge dedupes on the primary key. Used for runs, whose+ # status/timestamps keep mutating until the run reaches a final state.+ incremental_lookback: Optional[timedelta] = None+ # Normalized attribute keys stripped from rows before they're yielded. Keeps signed+ # capability URLs (state-file download/upload) out of the warehouse — anyone who can query+ # the table could otherwise read or write raw Terraform state, including its secrets,+ # without any HCP Terraform authorization.+ drop_fields: tuple[str, ...] = ()+++TERRAFORM_CLOUD_ENDPOINTS: dict[str, TerraformCloudEndpointConfig] = {+ "organizations": TerraformCloudEndpointConfig(+ name="organizations",+ # Scoped to the configured organization only. `/organizations` (no id) returns every+ # organization the token can access, leaking other orgs' names, admin emails, and+ # plan/SSO metadata to anyone who can query this table. The single-resource response is+ # normalized to a one-row list downstream.+ path="/organizations/{organization}",+ ),+ "projects": TerraformCloudEndpointConfig(+ name="projects",+ path="/organizations/{organization}/projects",+ ),+ "teams": TerraformCloudEndpointConfig(+ name="teams",+ path="/organizations/{organization}/teams",+ ),+ "workspaces": TerraformCloudEndpointConfig(+ name="workspaces",+ path="/organizations/{organization}/workspaces",+ ),+ "runs": TerraformCloudEndpointConfig(+ name="runs",+ path="/workspaces/{workspace_id}/runs",+ partition_key="created_at",+ incremental_fields=CREATED_AT_INCREMENTAL_FIELDS,+ sort_mode="desc",+ fan_out_over_workspaces=True,+ # A run's status/status-timestamps mutate after creation until it reaches a final+ # state (applied/errored/canceled). Re-pull a trailing day so recently created runs+ # pick up those transitions; runs that finalize later than that only refresh on a+ # full refresh.+ incremental_lookback=timedelta(hours=24),+ ),+ "state_versions": TerraformCloudEndpointConfig(+ name="state_versions",+ path="/state-versions",+ # The list endpoint takes workspace *name* + organization name filters (there is no+ # per-workspace-id path), so the fan-out fills both from the parent workspace row.+ params={+ "filter[organization][name]": "{organization}",+ "filter[workspace][name]": "{workspace_name}",+ },+ partition_key="created_at",+ incremental_fields=CREATED_AT_INCREMENTAL_FIELDS,+ sort_mode="desc",+ fan_out_over_workspaces=True,+ drop_fields=(+ "hosted_state_download_url",+ "hosted_json_state_download_url",+ "sanitized_state_download_url",+ "hosted_state_upload_url",+ "hosted_json_state_upload_url",+ ),+ ),+}++ENDPOINTS = tuple(TERRAFORM_CLOUD_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in TERRAFORM_CLOUD_ENDPOINTS.items()+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/terraform_cloud/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/terraform_cloud/source.pyindex c736ef0ad994..c82654ab259f 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/terraform_cloud/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/terraform_cloud/source.py@@ -1,21 +1,48 @@-from typing import cast+import re+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (+ SourceInputs,+ SourceResponse,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchemafrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import (TerraformCloudSourceConfig,)+from products.warehouse_sources.backend.temporal.data_imports.sources.terraform_cloud.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.terraform_cloud.terraform_cloud import (+ TerraformCloudResumeConfig,+ terraform_cloud_source,+ validate_credentials as validate_terraform_cloud_credentials,+)from products.warehouse_sources.backend.types import ExternalDataSourceType+# HCP Terraform organization names: letters, digits, hyphens, underscores.+_ORGANIZATION_NAME_REGEX = re.compile(r"^[a-zA-Z0-9][a-zA-Z0-9-_]*$")+@SourceRegistry.register-class TerraformCloudSource(SimpleSource[TerraformCloudSourceConfig]):+class TerraformCloudSource(ResumableSource[TerraformCloudSourceConfig, TerraformCloudResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.TERRAFORMCLOUD@@ -26,7 +53,98 @@ class TerraformCloudSource(SimpleSource[TerraformCloudSourceConfig]):name=SchemaExternalDataSourceType.TERRAFORM_CLOUD,category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,label="HashiCorp (HCP Terraform / Terraform Cloud)",+ releaseStatus=ReleaseStatus.ALPHA,+ keywords=["tfc", "hcp", "infrastructure as code", "iac"],+ caption="""Sync organizations, projects, teams, workspaces, runs, and state versions from HCP Terraform (formerly Terraform Cloud) into the PostHog Data warehouse to analyze infrastructure change frequency, plan/apply durations, and failure rates.++Create an API token in your HCP Terraform organization settings under **API tokens** — an organization token is recommended so every workspace is visible. Team and user tokens also work but only see the workspaces they have access to.++Only the SaaS API at `app.terraform.io` is supported; self-hosted Terraform Enterprise is not currently supported.""",iconPath="/static/services/terraform_cloud.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/terraform-cloud",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_token",+ label="API token",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ SourceFieldInputConfig(+ name="organization",+ label="Organization name",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="my-organization",+ secret=False,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.terraform_cloud.canonical_descriptions import ( # noqa: PLC0415 — lazy import of sibling metadata, per the source architecture contract+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error: Unauthorized for url: https://app.terraform.io": "Your HCP Terraform API token is invalid or has been revoked. Create a new token in your organization settings, then reconnect.",+ "403 Client Error: Forbidden for url: https://app.terraform.io": "Your HCP Terraform API token does not have access to this data. Check the token's permissions, then reconnect.",+ }++ def get_schemas(+ self,+ config: TerraformCloudSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ schemas = [+ SourceSchema(+ name=endpoint,+ supports_incremental=len(INCREMENTAL_FIELDS.get(endpoint, [])) > 0,+ supports_append=len(INCREMENTAL_FIELDS.get(endpoint, [])) > 0,+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),+ )+ for endpoint in ENDPOINTS+ ]+ if names is not None:+ names_set = set(names)+ schemas = [s for s in schemas if s.name in names_set]+ return schemas++ def validate_credentials(+ self, config: TerraformCloudSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ organization = config.organization.strip()+ if not _ORGANIZATION_NAME_REGEX.match(organization):+ return False, "HCP Terraform organization name is invalid"+ return validate_terraform_cloud_credentials(config.api_token, organization)++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[TerraformCloudResumeConfig]:+ return ResumableSourceManager[TerraformCloudResumeConfig](inputs, TerraformCloudResumeConfig)++ def source_for_pipeline(+ self,+ config: TerraformCloudSourceConfig,+ resumable_source_manager: ResumableSourceManager[TerraformCloudResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return terraform_cloud_source(+ api_token=config.api_token,+ organization=config.organization.strip(),+ 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/terraform_cloud/terraform_cloud.py b/products/warehouse_sources/backend/temporal/data_imports/sources/terraform_cloud/terraform_cloud.pynew file mode 100644index 000000000000..a873004753c2--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/terraform_cloud/terraform_cloud.py@@ -0,0 +1,391 @@+import dataclasses+from collections.abc import Iterator+from datetime import UTC, date, datetime, timedelta+from typing import Any, Optional+from urllib.parse import quote, urlencode, urljoin++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.terraform_cloud.settings import (+ TERRAFORM_CLOUD_ENDPOINTS,+ TerraformCloudEndpointConfig,+)++TERRAFORM_CLOUD_HOST = "https://app.terraform.io"+TERRAFORM_CLOUD_BASE_URL = f"{TERRAFORM_CLOUD_HOST}/api/v2"+PAGE_SIZE = 100 # API maximum for page[size]+++class TerraformCloudRetryableError(Exception):+ """Raised for responses that are safe to retry (429 / 5xx)."""+++class TerraformCloudResumeConfig:+ # Next page URL to fetch. None means "start the current list at its first page" — used when+ # the fan-out bookmark advances to a workspace whose first page URL is built when reached.+ next_url: str | None = None+ # The workspace currently being processed during a fan-out. A stable id bookmark (not a+ # positional index) so workspaces added/removed between a crash and the retry can't resume+ # us into the wrong workspace. None for top-level endpoints.+ workspace_id: str | None = None+++def _get_headers(api_token: str) -> dict[str, str]:+ return {+ "Authorization": f"Bearer {api_token}",+ "Accept": "application/vnd.api+json",+ }+++def _make_session(api_token: str) -> requests.Session:+ """Session for all HCP Terraform traffic. The bearer token is set once on the session so its+ redaction policy applies everywhere, redirects are pinned off so a credentialed request can't+ be replayed against another host, and response capture is disabled because state-version rows+ carry signed state-file download URLs (valid ~25h) that must not land in captured samples."""+ return make_tracked_session(+ headers=_get_headers(api_token),+ redact_values=(api_token,),+ allow_redirects=False,+ capture=False,+ )+++@retry(+ retry=retry_if_exception_type(+ (+ TerraformCloudRetryableError,+ requests.ReadTimeout,+ requests.ConnectionError,+ requests.exceptions.ChunkedEncodingError,+ )+ ),+ stop=stop_after_attempt(5),+ wait=wait_exponential_jitter(initial=1, max=30),+ reraise=True,+)+def _fetch_json(session: requests.Session, url: str, logger: FilteringBoundLogger) -> dict[str, Any]:+ # The API throttles at ~30 req/s per token and signals it with a 429.+ response = session.get(url, timeout=60)++ if response.status_code == 429 or response.status_code >= 500:+ raise TerraformCloudRetryableError(+ f"HCP Terraform API error (retryable): status={response.status_code}, url={url}"+ )++ if not response.ok:+ # 404 is expected during the fan-out (a workspace deleted mid-sync) and handled there.+ log = logger.warning if response.status_code == 404 else logger.error+ log(f"HCP Terraform API error: status={response.status_code}, body={response.text}, url={url}")+ response.raise_for_status()++ return response.json()+++def _normalize_key(key: str) -> str:+ return key.replace("-", "_")+++def _normalize_keys(value: Any) -> Any:+ """JSON:API attribute keys are kebab-case ("created-at"); normalize them (recursively) to+ snake_case so warehouse columns are queryable and incremental fields match row keys."""+ if isinstance(value, dict):+ return {_normalize_key(k): _normalize_keys(v) for k, v in value.items()}+ if isinstance(value, list):+ return [_normalize_keys(v) for v in value]+ return value+++def _flatten_item(item: dict[str, Any], drop_fields: tuple[str, ...] = ()) -> dict[str, Any]:+ """Flatten a JSON:API resource object into a row: id + type + normalized attributes, with+ each to-one relationship reduced to a `<name>_id` column (e.g. plan_id, workspace_id).+ `drop_fields` removes attributes that must never be persisted — state versions carry signed+ state-file download/upload URLs that would grant raw state access to anyone who can query+ the warehouse table."""+ row: dict[str, Any] = {"id": item["id"], "type": item.get("type")}+ attributes = item.get("attributes") or {}+ if isinstance(attributes, dict):+ row.update(_normalize_keys(attributes))+ for field in drop_fields:+ row.pop(field, None)+ relationships = item.get("relationships") or {}+ if isinstance(relationships, dict):+ for rel_name, rel in relationships.items():+ data = rel.get("data") if isinstance(rel, dict) else None+ if isinstance(data, dict) and data.get("id"):+ row[f"{_normalize_key(rel_name)}_id"] = data["id"]+ return row+++def _data_items(data: dict[str, Any]) -> list[dict[str, Any]]:+ """JSON:API `data` is a list for collection endpoints but a single resource object for+ individual-resource endpoints (e.g. the configured organization); normalize both to a list."""+ payload = data.get("data")+ if isinstance(payload, dict):+ return [payload]+ return payload or []+++def _next_url(data: dict[str, Any]) -> str | None:+ """Resolve the JSON:API `links.next` pagination URL, tolerating both the absolute URLs the+ API returns today and spec-allowed relative ones."""+ next_link = (data.get("links") or {}).get("next")+ if not next_link:+ return None+ return urljoin(TERRAFORM_CLOUD_HOST, next_link)+++def _build_url(path: str, params: dict[str, Any]) -> str:+ return f"{TERRAFORM_CLOUD_BASE_URL}{path}?{urlencode(params)}"+++def _parse_created_at(row: dict[str, Any]) -> datetime | None:+ value = row.get("created_at")+ if not isinstance(value, str):+ return None+ try:+ parsed = datetime.fromisoformat(value.replace("Z", "+00:00"))+ except ValueError:+ return None+ return parsed if parsed.tzinfo else parsed.replace(tzinfo=UTC)+++def _incremental_cutoff(last_value: Any, lookback: timedelta | None) -> datetime | None:+ """Turn the persisted watermark into the datetime below which pagination stops."""+ if isinstance(last_value, str):+ try:+ last_value = datetime.fromisoformat(last_value.replace("Z", "+00:00"))+ except ValueError:+ return None+ if isinstance(last_value, datetime):+ cutoff = last_value if last_value.tzinfo else last_value.replace(tzinfo=UTC)+ elif isinstance(last_value, date):+ cutoff = datetime.combine(last_value, datetime.min.time(), tzinfo=UTC)+ else:+ return None+ return cutoff - lookback if lookback else cutoff+++def _page_predates_cutoff(rows: list[dict[str, Any]], cutoff: datetime | None) -> bool:+ """True when every parseable created_at on the page is older than the cutoff — the signal to+ stop paginating a newest-first list on an incremental sync. Yielding the boundary page itself+ is harmless: merge dedupes re-pulled rows on the primary key."""+ if cutoff is None:+ return False+ parsed = [ts for ts in (_parse_created_at(row) for row in rows) if ts is not None]+ return bool(parsed) and max(parsed) < cutoff+++def _iter_workspaces(+ session: requests.Session, organization: str, logger: FilteringBoundLogger+) -> Iterator[dict[str, Any]]:+ """Page through the organization's workspaces, yielding raw JSON:API workspace objects."""+ url: str | None = _build_url(f"/organizations/{quote(organization, safe='')}/workspaces", {"page[size]": PAGE_SIZE})+ while url:+ data = _fetch_json(session, url, logger)+ yield from _data_items(data)+ url = _next_url(data)+++def _get_top_level_rows(+ session: requests.Session,+ organization: str,+ config: TerraformCloudEndpointConfig,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[TerraformCloudResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ if resume is not None and resume.next_url:+ url: str | None = resume.next_url+ logger.debug(f"HCP Terraform: resuming {config.name} from URL: {resume.next_url}")+ else:+ path = config.path.format(organization=quote(organization, safe=""))+ url = _build_url(path, {"page[size]": PAGE_SIZE})++ while url:+ data = _fetch_json(session, url, logger)+ rows = [_flatten_item(item, config.drop_fields) for item in _data_items(data)]+ next_url = _next_url(data)+ if rows:+ yield rows+ # Save AFTER yielding (and only when more pages remain) so a crash re-yields the last+ # page rather than skipping it — merge dedupes on the primary key.+ if next_url:+ resumable_source_manager.save_state(TerraformCloudResumeConfig(next_url=next_url))+ url = next_url+++def _first_child_url(+ config: TerraformCloudEndpointConfig, organization: str, workspace_id: str, workspace_name: str+) -> str:+ path = config.path.format(organization=quote(organization, safe=""), workspace_id=quote(workspace_id, safe=""))+ params: dict[str, Any] = {+ key: value.format(organization=organization, workspace_id=workspace_id, workspace_name=workspace_name)+ for key, value in config.params.items()+ }+ params["page[size]"] = PAGE_SIZE+ return _build_url(path, params)+++def _get_fan_out_rows(+ session: requests.Session,+ organization: str,+ config: TerraformCloudEndpointConfig,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[TerraformCloudResumeConfig],+ cutoff: datetime | None,+) -> Iterator[list[dict[str, Any]]]:+ """Fan out over every workspace in the organization and page through the child endpoint.++ Each row is stamped with `workspace_id`/`workspace_name` so child tables join back to their+ parent workspace without unpacking relationships. Run and state-version ids are globally+ unique, so `id` alone stays a valid table-wide primary key.+ """+ workspaces = list(_iter_workspaces(session, organization, logger))++ # Resolve the saved workspace bookmark to the slice still to process. If the bookmarked+ # workspace no longer exists (deleted between attempts), start over from the first one —+ # merge dedupes the re-pulled rows on the primary key. `resume_url` seeds the first+ # workspace only.+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ remaining = workspaces+ resume_url: str | None = None+ if resume is not None and resume.workspace_id is not None:+ workspace_ids = [workspace["id"] for workspace in workspaces]+ if resume.workspace_id in workspace_ids:+ remaining = workspaces[workspace_ids.index(resume.workspace_id) :]+ resume_url = resume.next_url+ logger.debug(+ f"HCP Terraform: resuming {config.name} from workspace_id={resume.workspace_id}, url={resume_url}"+ )++ for index, workspace in enumerate(remaining):+ workspace_id = workspace["id"]+ workspace_name = (workspace.get("attributes") or {}).get("name") or ""++ url: str | None = resume_url or _first_child_url(config, organization, workspace_id, workspace_name)+ resume_url = None # only the resumed-into workspace uses the saved URL++ try:+ while url:+ data = _fetch_json(session, url, logger)+ rows = []+ for item in _data_items(data):+ row = _flatten_item(item, config.drop_fields)+ row["workspace_id"] = workspace_id+ row["workspace_name"] = workspace_name+ rows.append(row)+ next_url = _next_url(data)++ if rows:+ yield rows+ if next_url:+ resumable_source_manager.save_state(+ TerraformCloudResumeConfig(next_url=next_url, workspace_id=workspace_id)+ )++ # Both child lists return newest-first with no server-side time filter, so an+ # incremental sync must terminate at the watermark client-side — otherwise every+ # sync re-walks each workspace's full history.+ if _page_predates_cutoff(rows, cutoff):+ break+ url = next_url+ except requests.HTTPError as exc:+ # A workspace deleted between enumeration and this fetch 404s. Skip it rather than+ # failing the whole sync; any other HTTP error is re-raised.+ if exc.response is not None and exc.response.status_code == 404:+ logger.warning(f"HCP Terraform: workspace {workspace_id} not found while fetching {config.name}")+ else:+ raise++ # Advance the bookmark so a crash between workspaces resumes at the next one.+ if index + 1 < len(remaining):+ resumable_source_manager.save_state(+ TerraformCloudResumeConfig(next_url=None, workspace_id=remaining[index + 1]["id"])+ )+++def get_rows(+ api_token: str,+ organization: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[TerraformCloudResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+) -> Iterator[list[dict[str, Any]]]:+ config = TERRAFORM_CLOUD_ENDPOINTS.get(endpoint)+ if config is None:+ raise ValueError(f"Unknown HCP Terraform endpoint: {endpoint}")++ session = _make_session(api_token)++ if config.fan_out_over_workspaces:+ cutoff = (+ _incremental_cutoff(db_incremental_field_last_value, config.incremental_lookback)+ if should_use_incremental_field+ else None+ )+ yield from _get_fan_out_rows(session, organization, config, logger, resumable_source_manager, cutoff)+ else:+ yield from _get_top_level_rows(session, organization, config, logger, resumable_source_manager)+++def terraform_cloud_source(+ api_token: str,+ organization: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[TerraformCloudResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+) -> SourceResponse:+ endpoint_config = TERRAFORM_CLOUD_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ api_token=api_token,+ organization=organization,+ 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=endpoint_config.primary_keys,+ # Fan-out lists arrive newest-first per workspace; desc mode makes the pipeline persist+ # the incremental watermark only at successful job end, since a partial run's max says+ # nothing about workspaces it never reached.+ sort_mode=endpoint_config.sort_mode,+ partition_count=1,+ partition_size=1,+ partition_mode="datetime" if endpoint_config.partition_key else None,+ partition_format="month" if endpoint_config.partition_key else None,+ partition_keys=[endpoint_config.partition_key] if endpoint_config.partition_key else None,+ )+++def validate_credentials(api_token: str, organization: str) -> tuple[bool, str | None]:+ """Single cheap probe: show the configured organization. Confirms the token is genuine and+ can see the org in one request. The API returns 404 (not 403) for an organization the token+ can't access, so both "wrong name" and "no access" surface as the same message."""+ try:+ response = _make_session(api_token).get(+ f"{TERRAFORM_CLOUD_BASE_URL}/organizations/{quote(organization, safe='')}", timeout=10+ )+ except Exception:+ return False, "Could not connect to HCP Terraform"++ if response.status_code == 200:+ return True, None+ if response.status_code == 401:+ return False, "Invalid HCP Terraform API token"+ if response.status_code == 404:+ return False, f"Organization '{organization}' was not found or your API token cannot access it"+ return False, f"HCP Terraform returned an unexpected status: {response.status_code}"diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/terraform_cloud/tests/test_terraform_cloud.py b/products/warehouse_sources/backend/temporal/data_imports/sources/terraform_cloud/tests/test_terraform_cloud.pynew file mode 100644index 000000000000..167c29ca1ef0--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/terraform_cloud/tests/test_terraform_cloud.py@@ -0,0 +1,412 @@+import json+from datetime import UTC, datetime+from typing import Any++import pytest+from unittest.mock import MagicMock, patch++import requests+from requests import Response++from products.warehouse_sources.backend.temporal.data_imports.sources.terraform_cloud.terraform_cloud import (+ TerraformCloudResumeConfig,+ TerraformCloudRetryableError,+ _fetch_json,+ _flatten_item,+ get_rows,+ terraform_cloud_source,+ validate_credentials,+)++BASE = "https://app.terraform.io/api/v2"+++def _response(body: Any, status: int = 200, url: str = f"{BASE}/organizations") -> Response:+ resp = Response()+ resp.status_code = status+ resp._content = json.dumps(body).encode()+ resp.url = url+ resp.headers["Content-Type"] = "application/vnd.api+json"+ return resp+++def _page(items: list[dict], next_url: str | None = None) -> dict:+ body: dict[str, Any] = {"data": items}+ if next_url:+ body["links"] = {"next": next_url}+ return body+++def _workspace(workspace_id: str, name: str) -> dict:+ return {"id": workspace_id, "type": "workspaces", "attributes": {"name": name}}+++def _run_item(run_id: str, created_at: str) -> dict:+ return {"id": run_id, "type": "runs", "attributes": {"created-at": created_at, "status": "applied"}}+++def _manager(resume: TerraformCloudResumeConfig | None = None) -> MagicMock:+ manager = MagicMock()+ manager.can_resume.return_value = resume is not None+ manager.load_state.return_value = resume+ return manager+++def _run_endpoint(+ endpoint: str,+ responses: list[Response],+ manager: MagicMock | None = None,+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+) -> tuple[list[list[dict]], MagicMock, MagicMock]:+ session = MagicMock()+ session.get.side_effect = responses+ manager = manager if manager is not None else _manager()+ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.terraform_cloud.terraform_cloud.make_tracked_session",+ return_value=session,+ ):+ batches = list(+ get_rows(+ api_token="t",+ organization="acme",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=manager,+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=db_incremental_field_last_value,+ )+ )+ return batches, session, manager+++class TestFlattenItem:+ def test_normalizes_attributes_and_extracts_relationship_ids(self) -> None:+ # created-at must land as created_at, or the declared incremental/partition fields+ # never match any row column and incremental sync silently breaks.+ row = _flatten_item(+ {+ "id": "run-1",+ "type": "runs",+ "attributes": {"created-at": "2026-01-01T00:00:00Z", "status-timestamps": {"applied-at": "x"}},+ "relationships": {+ "workspace": {"data": {"id": "ws-1", "type": "workspaces"}},+ "plan": {"data": {"id": "plan-1", "type": "plans"}},+ "comments": {"data": []},+ "created-by": {"data": None},+ },+ }+ )+ assert row == {+ "id": "run-1",+ "type": "runs",+ "created_at": "2026-01-01T00:00:00Z",+ "status_timestamps": {"applied_at": "x"},+ "workspace_id": "ws-1",+ "plan_id": "plan-1",+ }+++class TestTopLevelEndpoints:+ def test_paginates_via_links_next_and_resolves_relative_urls(self) -> None:+ # The API documents absolute next links, but JSON:API allows relative ones — both must+ # advance pagination, and a missing link must terminate it (not loop on page one).+ responses = [+ _response(+ _page(+ [{"id": "team-a", "type": "teams", "attributes": {"name": "a"}}],+ "/api/v2/organizations/acme/teams?page%5Bnumber%5D=2",+ )+ ),+ _response(_page([{"id": "team-b", "type": "teams", "attributes": {"name": "b"}}])),+ ]+ batches, session, _ = _run_endpoint("teams", responses)+ assert [row["id"] for batch in batches for row in batch] == ["team-a", "team-b"]+ assert session.get.call_count == 2+ assert (+ session.get.call_args_list[1].args[0]+ == "https://app.terraform.io/api/v2/organizations/acme/teams?page%5Bnumber%5D=2"+ )++ def test_organizations_scoped_to_configured_org(self) -> None:+ # `/organizations` (no id) would return every org the token can access, leaking other+ # orgs' names, admin emails, and plan/SSO metadata. The endpoint must target only the+ # configured org and normalize its single-resource response to one row.+ responses = [_response({"data": {"id": "acme", "type": "organizations", "attributes": {"name": "acme"}}})]+ batches, session, _ = _run_endpoint("organizations", responses)+ assert session.get.call_args_list[0].args[0] == f"{BASE}/organizations/acme?page%5Bsize%5D=100"+ assert [row["id"] for batch in batches for row in batch] == ["acme"]++ def test_saves_resume_state_only_while_pages_remain(self) -> None:+ next_url = f"{BASE}/organizations/acme/projects?page%5Bnumber%5D=2"+ responses = [+ _response(_page([{"id": "prj-1", "attributes": {}}], next_url)),+ _response(_page([{"id": "prj-2", "attributes": {}}])),+ ]+ _, _, manager = _run_endpoint("projects", responses)+ # The final page must not be checkpointed — a retry resuming past the end would sync nothing.+ assert [call.args[0] for call in manager.save_state.call_args_list] == [+ TerraformCloudResumeConfig(next_url=next_url)+ ]++ def test_resumes_from_saved_url(self) -> None:+ resume_url = f"{BASE}/organizations/acme/projects?page%5Bnumber%5D=3"+ responses = [_response(_page([{"id": "prj-9", "attributes": {}}]))]+ batches, session, _ = _run_endpoint(+ "projects", responses, manager=_manager(TerraformCloudResumeConfig(next_url=resume_url))+ )+ assert session.get.call_args_list[0].args[0] == resume_url+ assert [row["id"] for batch in batches for row in batch] == ["prj-9"]+++class TestFanOutEndpoints:+ def test_runs_fan_out_stamps_workspace_and_bookmarks_progress(self) -> None:+ responses = [+ _response(_page([_workspace("ws-1", "app"), _workspace("ws-2", "infra")])),+ _response(_page([_run_item("run-1", "2026-01-02T00:00:00Z")])), # ws-1 runs+ _response(_page([_run_item("run-2", "2026-01-01T00:00:00Z")])), # ws-2 runs+ ]+ batches, session, manager = _run_endpoint("runs", responses)++ rows = [row for batch in batches for row in batch]+ # Every child row carries its parent workspace so the table joins back without+ # unpacking JSON:API relationships.+ assert [(row["id"], row["workspace_id"], row["workspace_name"]) for row in rows] == [+ ("run-1", "ws-1", "app"),+ ("run-2", "ws-2", "infra"),+ ]+ assert session.get.call_args_list[1].args[0] == f"{BASE}/workspaces/ws-1/runs?page%5Bsize%5D=100"+ # Crash between workspaces must resume at ws-2, not restart the whole fan-out.+ assert TerraformCloudResumeConfig(next_url=None, workspace_id="ws-2") in [+ call.args[0] for call in manager.save_state.call_args_list+ ]++ def test_state_versions_filter_by_workspace_name_and_org(self) -> None:+ # State versions have no per-workspace path; dropping the name filters would sync the+ # same global list once per workspace.+ responses = [+ _response(_page([_workspace("ws-1", "app")])),+ _response(_page([{"id": "sv-1", "attributes": {"serial": 4, "created-at": "2026-01-01T00:00:00Z"}}])),+ ]+ batches, session, _ = _run_endpoint("state_versions", responses)+ child_url = session.get.call_args_list[1].args[0]+ assert child_url.startswith(f"{BASE}/state-versions?")+ assert "filter%5Borganization%5D%5Bname%5D=acme" in child_url+ assert "filter%5Bworkspace%5D%5Bname%5D=app" in child_url+ assert [row["id"] for batch in batches for row in batch] == ["sv-1"]++ def test_state_versions_strip_signed_capability_urls(self) -> None:+ # State-version payloads carry signed state-file download/upload URLs. Persisting them+ # would let anyone who can query the warehouse table read or write raw Terraform state+ # (including secrets) without any HCP Terraform authorization.+ responses = [+ _response(_page([_workspace("ws-1", "app")])),+ _response(+ _page(+ [+ {+ "id": "sv-1",+ "attributes": {+ "serial": 4,+ "created-at": "2026-01-01T00:00:00Z",+ "hosted-state-download-url": "https://archivist.terraform.io/v1/object/signed",+ "hosted-json-state-download-url": "https://archivist.terraform.io/v1/object/signed-json",+ "sanitized-state-download-url": "https://archivist.terraform.io/v1/object/sanitized",+ "hosted-state-upload-url": "https://archivist.terraform.io/v1/object/upload",+ "hosted-json-state-upload-url": "https://archivist.terraform.io/v1/object/upload-json",+ },+ }+ ]+ )+ ),+ ]+ batches, _, _ = _run_endpoint("state_versions", responses)+ (row,) = [row for batch in batches for row in batch]+ assert not any("download_url" in key or "upload_url" in key for key in row)+ # The non-capability metadata still lands.+ assert row["serial"] == 4+ assert row["created_at"] == "2026-01-01T00:00:00Z"+ assert row["workspace_id"] == "ws-1"++ def test_resumes_into_bookmarked_workspace(self) -> None:+ resume_url = f"{BASE}/workspaces/ws-2/runs?page%5Bnumber%5D=5"+ responses = [+ _response(_page([_workspace("ws-1", "app"), _workspace("ws-2", "infra")])),+ _response(_page([_run_item("run-9", "2026-01-01T00:00:00Z")])),+ ]+ batches, session, _ = _run_endpoint(+ "runs", responses, manager=_manager(TerraformCloudResumeConfig(next_url=resume_url, workspace_id="ws-2"))+ )+ # ws-1 is skipped entirely; the resumed workspace starts at its saved page URL.+ assert session.get.call_count == 2+ assert session.get.call_args_list[1].args[0] == resume_url+ assert [row["id"] for batch in batches for row in batch] == ["run-9"]++ def test_restarts_when_bookmarked_workspace_no_longer_exists(self) -> None:+ responses = [+ _response(_page([_workspace("ws-1", "app")])),+ _response(_page([_run_item("run-1", "2026-01-01T00:00:00Z")])),+ ]+ batches, _, _ = _run_endpoint(+ "runs", responses, manager=_manager(TerraformCloudResumeConfig(next_url="http://x", workspace_id="ws-gone"))+ )+ assert [row["id"] for batch in batches for row in batch] == ["run-1"]++ def test_skips_workspace_deleted_mid_sync(self) -> None:+ responses = [+ _response(_page([_workspace("ws-1", "app"), _workspace("ws-2", "infra")])),+ _response({"errors": [{"status": "404"}]}, status=404),+ _response(_page([_run_item("run-2", "2026-01-01T00:00:00Z")])),+ ]+ batches, _, _ = _run_endpoint("runs", responses)+ # A workspace deleted between enumeration and fetch must not fail the whole sync.+ assert [row["id"] for batch in batches for row in batch] == ["run-2"]+++class TestIncrementalPaginationTermination:+ def test_stops_paging_once_page_predates_watermark(self) -> None:+ # The API has no server-side time filter: without the client-side stop every+ # incremental sync re-walks each workspace's whole run history.+ next_url = f"{BASE}/workspaces/ws-1/runs?page%5Bnumber%5D=2"+ responses = [+ _response(_page([_workspace("ws-1", "app")])),+ # Older than watermark minus the 24h lookback -> stop, page 2 never requested.+ _response(_page([_run_item("run-old", "2026-01-01T00:00:00Z")], next_url)),+ ]+ batches, session, _ = _run_endpoint(+ "runs",+ responses,+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 1, 10, tzinfo=UTC),+ )+ assert session.get.call_count == 2+ # The boundary page is still yielded; merge dedupes it on the primary key.+ assert [row["id"] for batch in batches for row in batch] == ["run-old"]++ def test_lookback_keeps_paging_through_recent_rows(self) -> None:+ # Runs mutate until they reach a final status, so rows inside the 24h lookback window+ # must be re-pulled even though they predate the raw watermark.+ next_url = f"{BASE}/workspaces/ws-1/runs?page%5Bnumber%5D=2"+ responses = [+ _response(_page([_workspace("ws-1", "app")])),+ _response(_page([_run_item("run-recent", "2026-01-09T18:00:00Z")], next_url)),+ _response(_page([_run_item("run-old", "2026-01-01T00:00:00Z")])),+ ]+ batches, session, _ = _run_endpoint(+ "runs",+ responses,+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 1, 10, tzinfo=UTC),+ )+ assert session.get.call_count == 3+ assert [row["id"] for batch in batches for row in batch] == ["run-recent", "run-old"]++ def test_first_sync_without_watermark_walks_all_pages(self) -> None:+ next_url = f"{BASE}/workspaces/ws-1/runs?page%5Bnumber%5D=2"+ responses = [+ _response(_page([_workspace("ws-1", "app")])),+ _response(_page([_run_item("run-1", "2026-01-02T00:00:00Z")], next_url)),+ _response(_page([_run_item("run-2", "2026-01-01T00:00:00Z")])),+ ]+ batches, session, _ = _run_endpoint("runs", responses, should_use_incremental_field=True)+ assert session.get.call_count == 3+ assert [row["id"] for batch in batches for row in batch] == ["run-1", "run-2"]+++class TestGetRowsUnknownEndpoint:+ def test_raises_for_unknown_endpoint(self) -> None:+ with pytest.raises(ValueError, match="Unknown HCP Terraform endpoint"):+ list(+ get_rows(+ api_token="t",+ organization="acme",+ endpoint="nope",+ logger=MagicMock(),+ resumable_source_manager=_manager(),+ )+ )+++class TestFetchJsonStatusHandling:+ @pytest.mark.parametrize("status", [429, 500, 503])+ def test_retryable_statuses_raise_retryable_error(self, status: int) -> None:+ session = MagicMock()+ session.get.return_value = _response({}, status=status)+ # Call the undecorated function so tenacity's backoff doesn't sleep in the test.+ with pytest.raises(TerraformCloudRetryableError):+ _fetch_json.__wrapped__(session, f"{BASE}/organizations", MagicMock()) # type: ignore[attr-defined]++ @pytest.mark.parametrize("status", [400, 401, 403, 404])+ def test_client_errors_propagate_as_httperror(self, status: int) -> None:+ # 4xx must surface as HTTPError so get_non_retryable_errors can match and permanently+ # fail the sync instead of retrying a dead credential forever.+ session = MagicMock()+ session.get.return_value = _response({"errors": []}, status=status)+ with pytest.raises(requests.HTTPError):+ _fetch_json.__wrapped__(session, f"{BASE}/organizations", MagicMock()) # type: ignore[attr-defined]+++class TestValidateCredentials:+ @pytest.mark.parametrize(+ ("status", "valid", "message_fragment"),+ [+ (200, True, None),+ (401, False, "Invalid HCP Terraform API token"),+ (404, False, "not found or your API token cannot access it"),+ (500, False, "unexpected status"),+ ],+ )+ def test_maps_status_to_result(self, status: int, valid: bool, message_fragment: str | None) -> None:+ session = MagicMock()+ session.get.return_value = _response({}, status=status)+ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.terraform_cloud.terraform_cloud.make_tracked_session",+ return_value=session,+ ):+ ok, message = validate_credentials("token", "acme")+ assert ok is valid+ if message_fragment is None:+ assert message is None+ else:+ assert message is not None and message_fragment in message++ def test_network_failure_is_invalid(self) -> None:+ session = MagicMock()+ session.get.side_effect = requests.ConnectionError("boom")+ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.terraform_cloud.terraform_cloud.make_tracked_session",+ return_value=session,+ ):+ ok, message = validate_credentials("token", "acme")+ assert ok is False+ assert message is not None+++class TestSourceResponseShape:+ @pytest.mark.parametrize(+ ("endpoint", "partition_key", "sort_mode"),+ [+ ("organizations", None, "asc"),+ ("projects", None, "asc"),+ ("teams", None, "asc"),+ ("workspaces", None, "asc"),+ ("runs", "created_at", "desc"),+ ("state_versions", "created_at", "desc"),+ ],+ )+ def test_partition_and_sort_config(self, endpoint: str, partition_key: str | None, sort_mode: str) -> None:+ # Newest-first endpoints must declare desc, or the pipeline checkpoints the watermark+ # to ≈now after the first batch and mid-sync shutdowns lose rows. Partitioning is on+ # the STABLE created_at, never a mutating field.+ response = terraform_cloud_source(+ api_token="t",+ organization="acme",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=_manager(),+ )+ assert response.name == endpoint+ assert response.primary_keys == ["id"]+ assert response.sort_mode == sort_mode+ assert response.partition_keys == ([partition_key] if partition_key else None)+ assert response.partition_mode == ("datetime" if partition_key else None)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/terraform_cloud/tests/test_terraform_cloud_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/terraform_cloud/tests/test_terraform_cloud_source.pynew file mode 100644index 000000000000..c023d13e06d9--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/terraform_cloud/tests/test_terraform_cloud_source.py@@ -0,0 +1,145 @@+from typing import Any++from unittest.mock import MagicMock, patch++from parameterized import parameterized++from posthog.schema import DataWarehouseSourceCategory, ReleaseStatus, SourceFieldInputConfig++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceInputs+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import (+ TerraformCloudSourceConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.terraform_cloud.source import TerraformCloudSource+from products.warehouse_sources.backend.temporal.data_imports.sources.terraform_cloud.terraform_cloud import (+ TerraformCloudResumeConfig,+)+from products.warehouse_sources.backend.types import ExternalDataSourceType+++def _config(api_token: str = "test-token", organization: str = "acme") -> TerraformCloudSourceConfig:+ return TerraformCloudSourceConfig.from_dict({"api_token": api_token, "organization": organization})+++def _inputs(schema_name: str, should_use_incremental_field: bool = False) -> SourceInputs:+ return SourceInputs(+ schema_name=schema_name,+ schema_id="schema-1",+ source_id="source-1",+ team_id=1,+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value="2026-01-01T00:00:00Z",+ db_incremental_field_earliest_value=None,+ incremental_field="created_at" if should_use_incremental_field else None,+ incremental_field_type=None,+ job_id="job-1",+ logger=MagicMock(),+ reset_pipeline=False,+ )+++class TestTerraformCloudSource:+ def test_source_type(self) -> None:+ assert TerraformCloudSource().source_type == ExternalDataSourceType.TERRAFORMCLOUD++ def test_source_config_shape(self) -> None:+ config = TerraformCloudSource().get_source_config+ assert config.category == DataWarehouseSourceCategory.ENGINEERING___MONITORING+ assert config.releaseStatus == ReleaseStatus.ALPHA+ # A finished source must be visible — unreleasedSource hides it from every user.+ assert not config.unreleasedSource+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/terraform-cloud"+ field_names = [f.name for f in config.fields]+ assert field_names == ["api_token", "organization"]+ token_field = config.fields[0]+ assert isinstance(token_field, SourceFieldInputConfig)+ assert token_field.secret is True++ def test_get_schemas_incremental_flags(self) -> None:+ # Only the newest-first, created_at-cursorable child endpoints may advertise+ # incremental; the org-level lists have no cursor and must stay full refresh.+ schemas = {s.name: s for s in TerraformCloudSource().get_schemas(_config(), team_id=1)}+ assert set(schemas) == {"organizations", "projects", "teams", "workspaces", "runs", "state_versions"}+ for name in ("runs", "state_versions"):+ assert schemas[name].supports_incremental is True+ assert [f["field"] for f in schemas[name].incremental_fields] == ["created_at"]+ for name in ("organizations", "projects", "teams", "workspaces"):+ assert schemas[name].supports_incremental is False+ assert schemas[name].incremental_fields == []++ def test_get_schemas_filters_by_name(self) -> None:+ schemas = TerraformCloudSource().get_schemas(_config(), team_id=1, names=["runs"])+ assert [s.name for s in schemas] == ["runs"]++ @parameterized.expand(+ [+ ("bad org/../path", False),+ ("has space", False),+ ("", False),+ ]+ )+ def test_validate_credentials_rejects_invalid_org_names_without_network(self, organization: str, _: bool) -> None:+ # The org name lands in a URL path; a malformed value must be rejected before any request.+ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.terraform_cloud.source.validate_terraform_cloud_credentials"+ ) as probe:+ ok, message = TerraformCloudSource().validate_credentials(_config(organization=organization), team_id=1)+ assert ok is False+ assert message is not None+ probe.assert_not_called()++ def test_validate_credentials_delegates_probe(self) -> None:+ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.terraform_cloud.source.validate_terraform_cloud_credentials",+ return_value=(True, None),+ ) as probe:+ assert TerraformCloudSource().validate_credentials(_config(), team_id=1) == (True, None)+ probe.assert_called_once_with("test-token", "acme")++ def test_resumable_source_manager_binds_resume_dataclass(self) -> None:+ manager = TerraformCloudSource().get_resumable_source_manager(_inputs("runs"))+ assert manager._data_class is TerraformCloudResumeConfig++ @parameterized.expand(+ [+ ("401 Client Error: Unauthorized for url: https://app.terraform.io/api/v2/workspaces/ws-1/runs",),+ ("403 Client Error: Forbidden for url: https://app.terraform.io/api/v2/organizations/acme/teams",),+ ]+ )+ def test_non_retryable_errors_match_credential_failures(self, raised_message: str) -> None:+ # A revoked token must permanently fail the sync rather than retry forever; the matcher+ # keys on the stable status text + host, so real HTTPError strings match.+ errors = TerraformCloudSource().get_non_retryable_errors()+ assert any(pattern in raised_message and friendly for pattern, friendly in errors.items())++ @parameterized.expand([(True, "2026-01-01T00:00:00Z"), (False, None)])+ def test_source_for_pipeline_plumbs_arguments(self, should_use_incremental: bool, expected_last_value: Any) -> None:+ sentinel = object()+ manager = MagicMock()+ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.terraform_cloud.source.terraform_cloud_source",+ return_value=sentinel,+ ) as mock_source:+ inputs = _inputs("runs", should_use_incremental_field=should_use_incremental)+ result = TerraformCloudSource().source_for_pipeline(_config(organization=" acme "), manager, inputs)++ assert result is sentinel+ mock_source.assert_called_once_with(+ api_token="test-token",+ organization="acme", # stripped so a pasted name with whitespace doesn't 404 every request+ endpoint="runs",+ logger=inputs.logger,+ resumable_source_manager=manager,+ should_use_incremental_field=should_use_incremental,+ db_incremental_field_last_value=expected_last_value,+ )++ def test_documented_tables_render_without_credentials(self) -> None:+ # lists_tables_without_credentials powers the public docs table catalog; it must resolve+ # from the static endpoint catalog with no network call and merge canonical descriptions.+ tables = TerraformCloudSource().get_documented_tables()+ by_name: dict[str, dict[str, Any]] = {t["name"]: t for t in tables}+ assert set(by_name) == {"organizations", "projects", "teams", "workspaces", "runs", "state_versions"}+ assert by_name["runs"]["sync_methods"] == ["Incremental", "Full refresh"]+ assert by_name["workspaces"]["sync_methods"] == ["Full refresh"]+ assert by_name["runs"]["description"]