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 pulumi_cloud import source (#71203)

Tom Owers6a71b45d8d57
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 7f6dfb136b86..60a242890bd7 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -385,6 +385,7 @@ the row lists both.
| pretix | HTTP | requests | ✅ |
| printify | HTTP | requests | ✅ |
| productboard | HTTP | requests | ✅ |
+| pulumi_cloud | HTTP | requests | ✅ |
| pylon | HTTP | requests | ✅ |
| pypi | HTTP | requests | ✅ |
| qualaroo | HTTP | requests | ✅ |
@@ -838,7 +839,6 @@ doesn't conflict with concurrent PRs.
- primetric
- productive
- prompting_company
-- pulumi_cloud
- qdrant
- qonto
- qualtrics
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 04a3e87e6941..e199c6a1614a 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
@@ -3365,7 +3365,8 @@ class PromptingCompanySourceConfig(config.Config):
@config.config
class PulumiCloudSourceConfig(config.Config):
- pass
+ access_token: str
+ organization: str
@config.config
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/pulumi_cloud/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/pulumi_cloud/canonical_descriptions.py
new file mode 100644
index 000000000000..56cb04826f26
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/pulumi_cloud/canonical_descriptions.py
@@ -0,0 +1,105 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+# Descriptions sourced from the Pulumi Cloud REST API reference
+# (https://www.pulumi.com/docs/reference/cloud-rest-api/) and the OpenAPI spec the service publishes
+# at https://api.pulumi.com/api/openapi/pulumi-spec.json.
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "stacks": {
+ "description": "One row per stack the token can access in the configured organization, without the stack's resources.",
+ "docs_url": "https://www.pulumi.com/docs/reference/cloud-rest-api/stacks/",
+ "columns": {
+ "id": "The logical identifier of the stack.",
+ "orgName": "The organization the stack belongs to.",
+ "projectName": "The name of the project the stack is associated with.",
+ "stackName": "The name of the stack.",
+ "lastUpdate": "Unix timestamp of the start time of the stack's last update, if any.",
+ "resourceCount": "The number of resources currently managed by the stack.",
+ "links": "Links to the stack in the Pulumi Console.",
+ },
+ },
+ "stack_updates": {
+ "description": "The update history of every stack: one row per update, preview, refresh, destroy, or import operation, with its outcome and timings.",
+ "docs_url": "https://www.pulumi.com/docs/reference/cloud-rest-api/stack-updates/",
+ "columns": {
+ "orgName": "The organization of the stack this update ran against.",
+ "projectName": "The project of the stack this update ran against.",
+ "stackName": "The stack this update ran against.",
+ "version": "Version of the stack that this update produced (ordinal within the stack).",
+ "latestVersion": "The stack's latest version at read time; equals version for the most recent update.",
+ "updateID": "The unique identifier of the update.",
+ "kind": "The type of operation: update, preview, refresh, rename, destroy, or import (P-prefixed kinds are previews).",
+ "startTime": "Unix epoch timestamp (seconds) when the update started.",
+ "endTime": "Unix epoch timestamp (seconds) when the update completed.",
+ "result": "The outcome of the update: not-started, in-progress, succeeded, or failed.",
+ "message": "User-provided message describing the purpose of the update.",
+ "environment": "Environment variables that were set during the update, keyed by variable name.",
+ "config": "Stack configuration values used during the update, keyed by config key.",
+ "resourceChanges": "Count of resource changes by operation type (e.g. create, update, delete).",
+ "resourceCount": "Total number of resources managed by the stack after this update.",
+ "requestedBy": "The user who requested the update.",
+ "githubCommitInfo": "The commit that was HEAD at the time of the update, when the update came from a GitHub-based repo.",
+ },
+ },
+ "deployments": {
+ "description": "Pulumi Deployments runs across the organization, newest first, with per-job details.",
+ "docs_url": "https://www.pulumi.com/docs/reference/cloud-rest-api/deployments/",
+ "columns": {
+ "id": "Unique identifier for this deployment.",
+ "created": "When the deployment was created.",
+ "modified": "When the deployment's workflow run was last modified.",
+ "status": "Current status of the deployment: not-started, accepted, running, failed, succeeded, or skipped.",
+ "version": "The ordinal version of the stack the deployment produced.",
+ "projectName": "The name of the project the deployment ran against.",
+ "stackName": "The name of the stack the deployment ran against.",
+ "pulumiOperation": "The operation performed: update, preview, destroy, refresh, detect-drift, or remediate-drift.",
+ "initiator": "The initiation source of the deployment.",
+ "paused": "Whether deployments are paused for this program.",
+ "jobs": "The list of jobs in this deployment, with their steps and statuses.",
+ "requestedBy": "The user who created the deployment.",
+ },
+ },
+ "audit_logs": {
+ "description": "Organization audit log events: who did what, when, and from where. Requires a Pulumi Cloud plan with audit logs enabled.",
+ "docs_url": "https://www.pulumi.com/docs/reference/cloud-rest-api/audit-logs/",
+ "columns": {
+ "event_id": "Synthetic primary key derived by hashing the full event payload (Pulumi does not assign audit events an id).",
+ "timestamp": "Unix epoch timestamp (seconds) when the event occurred.",
+ "event": "The audit event type identifier (e.g. 'stack.update', 'member.added').",
+ "description": "Human-readable description of the event.",
+ "sourceIP": "IP address of the client that triggered the event.",
+ "user": "The user who performed the action.",
+ "actorName": "Display name of the non-human actor (e.g. deploy token name) that triggered the event.",
+ "actorUrn": "Pulumi URN of the non-human actor that triggered the event.",
+ "authFailure": "Whether this event represents a failed authentication attempt.",
+ "tokenID": "ID of the access token used to authenticate, if applicable.",
+ "tokenName": "Name of the access token used to authenticate, if applicable.",
+ "reqOrgAdmin": "Whether the action required the organization admin role.",
+ "reqStackAdmin": "Whether the action required stack admin privileges.",
+ },
+ },
+ "resources": {
+ "description": "Every resource in the organization's Pulumi Insights resource index, one row per resource.",
+ "docs_url": "https://www.pulumi.com/docs/reference/cloud-rest-api/resource-search/",
+ "columns": {
+ "urn": "The URN identifying this resource within its stack.",
+ "project": "The project that contains this resource.",
+ "stack": "The stack that contains this resource.",
+ "name": "The name of the resource.",
+ "type": "The full type token of the resource (e.g. aws:s3/bucket:Bucket).",
+ "package": "The package that provides this resource.",
+ "module": "The module that contains this resource.",
+ "id": "The provider-assigned resource ID.",
+ "created": "ISO 8601 timestamp when the resource was first indexed.",
+ "modified": "ISO 8601 timestamp when the resource was last updated in the index.",
+ "custom": "Whether this is a custom resource managed by a provider plugin.",
+ "protected": "Whether this resource is protected from deletion.",
+ "pending": "The pending operation on this resource, if any (e.g. creating, updating, deleting).",
+ "parent_urn": "The URN of the parent resource, if any.",
+ "provider_urn": "The URN of the provider for this resource.",
+ "dependencies": "URNs of resources that this resource depends on.",
+ "managed": "Whether this resource is managed by Pulumi IaC stacks or discovered by Insights scanning.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/pulumi_cloud/pulumi_cloud.posthog-doc.mdx b/products/warehouse_sources/backend/temporal/data_imports/sources/pulumi_cloud/pulumi_cloud.posthog-doc.mdx
new file mode 100644
index 000000000000..fc431512ad39
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/pulumi_cloud/pulumi_cloud.posthog-doc.mdx
@@ -0,0 +1,79 @@
+<!--
+This is the user-facing source documentation. It belongs in the posthog.com repo at
+contents/docs/cdp/sources/pulumi-cloud.md (served at /docs/cdp/sources/pulumi-cloud). It is kept here
+only because a posthog.com checkout was not available when the source was implemented — copy it across
+and delete this file from this repo. Run `python manage.py audit_source_docs --docs-dir <posthog.com>/contents/docs/cdp/sources`
+once it lands.
+-->
+
+---
+
+title: Linking Pulumi as a source
+sidebar: Docs
+showTitle: true
+availability: { free: full, selfServe: full, enterprise: full }
+sourceId: PulumiCloud
+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 />
+
+[Pulumi Cloud](https://www.pulumi.com/product/pulumi-cloud/) is the managed control plane for Pulumi
+infrastructure as code. This connector pulls your stacks, their full update history, Pulumi Deployments
+runs, the Insights resource index, and organization audit logs into the PostHog Data warehouse, so you
+can measure deployment frequency, change-failure rate, and lead time for infrastructure changes alongside
+your product data.
+
+## Prerequisites
+
+You need a Pulumi Cloud account and an access token for a member of the organization you want to sync.
+The **Audit logs** table additionally requires a Pulumi Cloud plan with audit logs enabled (Enterprise or
+Business Critical), and the **Deployments** table only has data if your organization uses Pulumi
+Deployments.
+
+## Adding a data source
+
+<SourceSetupIntro />
+
+Pulumi authenticates with an access token (it starts with `pul-`). Create a personal access token on your
+[access tokens page](https://app.pulumi.com/account/tokens), or an organization access token from your
+organization's settings, and paste it into the **Access token** field. The token inherits its owner's
+access, so no extra scopes are required.
+
+The **Organization** field takes your organization name as it appears in your Pulumi Cloud console URL
+(`app.pulumi.com/<organization>`).
+
+## Sync modes
+
+<SyncModes />
+
+**Audit logs** syncs incrementally using the API's server-side time filter, and **Stack updates** syncs
+incrementally by reading each stack's history newest-first and stopping at the last synced update. Both
+re-read a short trailing window each run so late-completing updates and boundary events are picked up.
+The other tables are current-state snapshots, so they sync as full refresh.
+
+## Configuration
+
+<SourceParameters />
+
+## Supported tables
+
+<SourceTables />
+
+## Troubleshooting
+
+- **401 Unauthorized** — the access token is invalid or has been revoked. Create a new access token in
+ Pulumi Cloud and reconnect.
+- **403 Forbidden** — the token is valid but does not have access to the requested data. Check that the
+ token's owner is a member of the organization, and for audit logs, that your plan has audit logs
+ enabled.
+- **Audit logs table is empty or fails** — audit logs are only available on Pulumi Cloud plans with audit
+ logs enabled. Deselect the table if your plan does not include them.
+
+<TroubleshootingLink />
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/pulumi_cloud/pulumi_cloud.py b/products/warehouse_sources/backend/temporal/data_imports/sources/pulumi_cloud/pulumi_cloud.py
new file mode 100644
index 000000000000..7b7bb3d0f762
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/pulumi_cloud/pulumi_cloud.py
@@ -0,0 +1,530 @@
+import hashlib
+import dataclasses
+from collections.abc import Iterator
+from datetime import date, datetime
+from typing import Any, Optional
+from urllib.parse import quote
+
+import orjson
+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.pulumi_cloud.settings import (
+ PULUMI_CLOUD_ENDPOINTS,
+ PulumiCloudEndpointConfig,
+)
+
+PULUMI_CLOUD_BASE_URL = "https://api.pulumi.com"
+PAGE_SIZE = 100
+# Bound every paginator so a misbehaving API can't loop forever.
+MAX_PAGES = 10_000
+# Incremental stack_updates re-pulls a trailing window below the watermark: the watermark is the max
+# startTime seen, and an update that was still in-progress at the previous sync only flips its
+# `result` once it completes — without the overlap that completion would never be re-fetched. Merge
+# dedupes the re-pulled rows on the primary key. Updates rarely run longer than a day.
+STACK_UPDATES_LOOKBACK_SECONDS = 24 * 60 * 60
+# Small overlap below the audit-log watermark: the spec doesn't state whether the server-side
+# `startTime` lower bound is inclusive, so re-pull a window rather than risk dropping events that
+# share the watermark second. Merge dedupes the re-pulled rows on the synthetic `event_id`.
+AUDIT_LOGS_LOOKBACK_SECONDS = 15 * 60
+
+
+class PulumiCloudRetryableError(Exception):
+ pass
+
+
+class PulumiCloudResumeConfig:
+ # Opaque pagination token to resume from: the `continuationToken` for stacks/audit logs, or the
+ # resource-search `cursor`. None means "start from the first page".
+ next_token: str | None = None
+ # 1-based page number to resume the deployments listing from.
+ page: int | None = None
+ # Stable "org/project/stack" keys of the fan-out stacks already fully processed in an earlier
+ # attempt of this job. We resume by processing any stack NOT in this set, so a stack created
+ # between a crash and the retry is picked up rather than silently skipped (fan-out persists the
+ # incremental watermark only at successful job end, so a skipped stack's older updates would
+ # never be fetched again outside the trailing lookback window).
+ completed_stack_keys: list[str] = dataclasses.field(default_factory=list)
+
+
+def _get_headers(access_token: str) -> dict[str, str]:
+ # Pulumi Cloud requires the versioned vnd.pulumi Accept header alongside the token.
+ return {
+ "Authorization": f"token {access_token}",
+ "Accept": "application/vnd.pulumi+8",
+ "Content-Type": "application/json",
+ }
+
+
+def _as_unix_seconds(value: Any) -> int | None:
+ """Coerce a stored incremental watermark into unix seconds, or None when not coercible."""
+ if isinstance(value, bool):
+ return None
+ if isinstance(value, int | float):
+ return int(value)
+ if isinstance(value, datetime):
+ return int(value.timestamp())
+ if isinstance(value, date):
+ return int(datetime(value.year, value.month, value.day).timestamp())
+ if isinstance(value, str):
+ try:
+ return int(float(value))
+ except ValueError:
+ return None
+ return None
+
+
+@retry(
+ retry=retry_if_exception_type(
+ (
+ PulumiCloudRetryableError,
+ requests.ReadTimeout,
+ requests.ConnectionError,
+ requests.exceptions.ChunkedEncodingError,
+ )
+ ),
+ stop=stop_after_attempt(5),
+ wait=wait_exponential_jitter(initial=1, max=30),
+ reraise=True,
+)
+def _fetch(
+ session: requests.Session,
+ url: str,
+ headers: dict[str, str],
+ logger: FilteringBoundLogger,
+ params: Optional[dict[str, Any]] = None,
+) -> Any:
+ response = session.get(url, headers=headers, params=params, timeout=60)
+
+ if response.status_code == 429 or response.status_code >= 500:
+ raise PulumiCloudRetryableError(f"Pulumi Cloud API error (retryable): status={response.status_code}, url={url}")
+
+ if not response.ok:
+ # Log only status and URL — never the response body. Pulumi error bodies can echo
+ # request-specific data (stack config keys, audit descriptions), which must not spill into
+ # application logs where access is broader than the source data itself.
+ logger.error(f"Pulumi Cloud API error: status={response.status_code}, url={url}")
+ response.raise_for_status()
+
+ return response.json()
+
+
+def validate_credentials(access_token: str) -> bool:
+ """Probe the token with the cheapest account-level call. GET /api/user needs no org access, so a
+ 200 confirms the token is genuine; a 401 means it is invalid or revoked."""
+ try:
+ response = make_tracked_session(redact_values=(access_token,), capture=False).get(
+ f"{PULUMI_CLOUD_BASE_URL}/api/user", headers=_get_headers(access_token), timeout=10
+ )
+ return response.status_code == 200
+ except Exception:
+ return False
+
+
+def _format_path(path: str, org: str, project: str | None = None, stack: str | None = None) -> str:
+ return path.format(
+ org=quote(org, safe=""),
+ project=quote(project, safe="") if project is not None else "",
+ stack=quote(stack, safe="") if stack is not None else "",
+ )
+
+
+def _iter_stack_pages(
+ session: requests.Session,
+ headers: dict[str, str],
+ logger: FilteringBoundLogger,
+ organization: str,
+ start_token: str | None = None,
+) -> Iterator[tuple[list[dict[str, Any]], str | None]]:
+ """Page through GET /api/user/stacks for the organization, yielding (stacks, next_token) pairs.
+
+ A nil continuationToken in the response signals the final page.
+ """
+ token = start_token
+ for _ in range(MAX_PAGES):
+ params: dict[str, Any] = {"organization": organization, "maxResults": PAGE_SIZE}
+ if token:
+ params["continuationToken"] = token
+ data = _fetch(session, f"{PULUMI_CLOUD_BASE_URL}/api/user/stacks", headers, logger, params=params)
+ stacks = data.get("stacks", [])
+ token = data.get("continuationToken") or None
+ yield stacks, token
+ if not token:
+ return
+ logger.warning(f"Pulumi Cloud: stack listing hit the page cap ({MAX_PAGES}) for org={organization}")
+
+
+def _get_stack_rows(
+ session: requests.Session,
+ headers: dict[str, str],
+ logger: FilteringBoundLogger,
+ organization: str,
+ resumable_source_manager: ResumableSourceManager[PulumiCloudResumeConfig],
+) -> Iterator[list[dict[str, Any]]]:
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ start_token = resume.next_token if resume else None
+
+ for stacks, next_token in _iter_stack_pages(session, headers, logger, organization, start_token=start_token):
+ if stacks:
+ yield stacks
+ # 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_token:
+ resumable_source_manager.save_state(PulumiCloudResumeConfig(next_token=next_token))
+
+
+def _redact_secret_config(config: Any) -> Any:
+ """Strip encrypted secret values out of a Pulumi stack `config` map.
+
+ Secret config entries come back as ``{"secret": true, "string": "<ciphertext>"}``. The
+ ciphertext is recoverable offline against a passphrase-protected stack, so drop the `string`
+ while keeping the metadata (that the key exists and is a secret) — anyone with warehouse read
+ access must not be able to export the ciphertexts.
+ """
+ if not isinstance(config, dict):
+ return config
+ redacted: dict[Any, Any] = {}
+ for key, entry in config.items():
+ if isinstance(entry, dict) and entry.get("secret"):
+ entry = {k: v for k, v in entry.items() if k != "string"}
+ redacted[key] = entry
+ return redacted
+
+
+def _flatten_update(item: dict[str, Any], org: str, project: str, stack: str) -> dict[str, Any]:
+ """Flatten an UpdateInfo item (nested `info` from the Pulumi CLI) into one flat row, injecting
+ the stack coordinates the composite primary key needs."""
+ row = dict(item)
+ info = row.pop("info", None)
+ if isinstance(info, dict):
+ merged = dict(info)
+ # The raw deployment state snapshot can be enormous and is not list-level data.
+ merged.pop("deployment", None)
+ # `environment` records the env vars supplied to the update — it can hold cloud credentials,
+ # CI tokens, or PULUMI_CONFIG_PASSPHRASE, so it must never land in a queryable warehouse row.
+ merged.pop("environment", None)
+ merged.update(row)
+ row = merged
+ # `requestedByToken` is the access token that requested the update — a live credential that
+ # would let anyone with warehouse read access act as the token owner. Never persist it.
+ row.pop("requestedByToken", None)
+ if "config" in row:
+ row["config"] = _redact_secret_config(row["config"])
+ row["orgName"] = org
+ row["projectName"] = project
+ row["stackName"] = stack
+ return row
+
+
+def _get_single_stack_update_rows(
+ session: requests.Session,
+ headers: dict[str, str],
+ logger: FilteringBoundLogger,
+ config: PulumiCloudEndpointConfig,
+ org: str,
+ project: str,
+ stack: str,
+ watermark: int | None,
+) -> Iterator[list[dict[str, Any]]]:
+ """Page through one stack's update history (newest-first), stopping early at the watermark.
+
+ The endpoint has no server-side time filter, but its paginated format returns updates
+ newest-first, so once any row on a page predates the watermark every later page is older and
+ pagination can stop — an incremental sync only pays for the new pages.
+ """
+ url = f"{PULUMI_CLOUD_BASE_URL}{_format_path(config.path, org, project, stack)}"
+ page = 1
+ while page <= MAX_PAGES:
+ # `output-type=service` selects the paginated response format ({updates, itemsPerPage, total});
+ # unset returns a legacy unpaginated format.
+ data = _fetch(
+ session, url, headers, logger, params={"output-type": "service", "page": page, "pageSize": PAGE_SIZE}
+ )
+ updates = data.get("updates", [])
+ if not updates:
+ return
+
+ rows = [_flatten_update(item, org, project, stack) for item in updates]
+
+ if watermark is not None:
+ # Rows without a usable startTime can't be compared to the watermark; keep them rather
+ # than silently drop a new update the API returned untimestamped. Merge dedupes the
+ # re-yielded ones on the primary key, so this costs a rewrite, not duplicate rows.
+ kept = [row for row in rows if not isinstance(row.get("startTime"), int) or row["startTime"] >= watermark]
+ if kept:
+ yield kept
+ start_times = [row["startTime"] for row in rows if isinstance(row.get("startTime"), int)]
+ # Newest-first: if this page already reaches below the watermark, every later page is older.
+ if start_times and min(start_times) < watermark:
+ return
+ # A full page carrying no usable startTime gives no signal to stop on; bail rather than
+ # walk to the page cap should the API ever return updates without a startTime.
+ if not start_times:
+ return
+ else:
+ yield rows
+
+ if len(updates) < PAGE_SIZE:
+ return
+ page += 1
+ logger.warning(f"Pulumi Cloud: stack_updates hit the page cap ({MAX_PAGES}) for {org}/{project}/{stack}")
+
+
+def _get_stack_update_rows(
+ session: requests.Session,
+ headers: dict[str, str],
+ logger: FilteringBoundLogger,
+ organization: str,
+ resumable_source_manager: ResumableSourceManager[PulumiCloudResumeConfig],
+ config: PulumiCloudEndpointConfig,
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Any,
+) -> Iterator[list[dict[str, Any]]]:
+ stacks = [stack for page, _ in _iter_stack_pages(session, headers, logger, organization) for stack in page]
+
+ watermark: int | None = None
+ if should_use_incremental_field:
+ last_value = _as_unix_seconds(db_incremental_field_last_value)
+ if last_value is not None:
+ watermark = last_value - STACK_UPDATES_LOOKBACK_SECONDS
+
+ # Resume by skipping only stacks already fully processed in an earlier attempt of this job.
+ # Within a stack we always re-fetch from the first page; merge dedupes re-pulled rows.
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ completed_stack_keys = list(resume.completed_stack_keys) if resume is not None else []
+ completed = set(completed_stack_keys)
+
+ for stack_summary in stacks:
+ org = stack_summary.get("orgName")
+ project = stack_summary.get("projectName")
+ stack = stack_summary.get("stackName")
+ if not org or not project or not stack:
+ continue
+ stack_key = f"{org}/{project}/{stack}"
+ if stack_key in completed:
+ logger.debug(f"Pulumi Cloud: skipping already-processed stack={stack_key} for stack_updates fan-out")
+ continue
+
+ yield from _get_single_stack_update_rows(session, headers, logger, config, org, project, stack, watermark)
+
+ # Mark this stack done so a crash resumes with the stacks still owed. Saved AFTER yielding
+ # this stack's pages so a crash mid-stack re-processes it (merge dedupes) rather than skipping it.
+ completed_stack_keys.append(stack_key)
+ completed.add(stack_key)
+ resumable_source_manager.save_state(PulumiCloudResumeConfig(completed_stack_keys=list(completed_stack_keys)))
+
+
+def _redact_deployment_environments(deployments: list[dict[str, Any]]) -> None:
+ """Strip per-update `environment` maps out of org deployment records in place.
+
+ A deployment embeds the updates it ran, and each update's `environment` holds the env vars
+ supplied to the operation — cloud credentials, CI tokens, or PULUMI_CONFIG_PASSPHRASE. These
+ rows skip `_flatten_update`, so redact them here just like stack-update rows before they land
+ in a queryable warehouse row.
+ """
+ for deployment in deployments:
+ if isinstance(deployment, dict):
+ for update in deployment.get("updates") or []:
+ if isinstance(update, dict):
+ update.pop("environment", None)
+
+
+def _get_deployment_rows(
+ session: requests.Session,
+ headers: dict[str, str],
+ logger: FilteringBoundLogger,
+ organization: str,
+ resumable_source_manager: ResumableSourceManager[PulumiCloudResumeConfig],
+ config: PulumiCloudEndpointConfig,
+) -> Iterator[list[dict[str, Any]]]:
+ url = f"{PULUMI_CLOUD_BASE_URL}{_format_path(config.path, organization)}"
+
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ page = resume.page if resume is not None and resume.page else 1
+
+ while page <= MAX_PAGES:
+ data = _fetch(session, url, headers, logger, params={"page": page, "pageSize": PAGE_SIZE})
+ deployments = data.get("deployments", [])
+ if not deployments:
+ return
+ _redact_deployment_environments(deployments)
+ yield deployments
+ if len(deployments) < PAGE_SIZE:
+ return
+ page += 1
+ resumable_source_manager.save_state(PulumiCloudResumeConfig(page=page))
+ logger.warning(f"Pulumi Cloud: deployments hit the page cap ({MAX_PAGES}) for org={organization}")
+
+
+def _audit_event_id(event: dict[str, Any]) -> str:
+ # Pulumi audit events carry no server-assigned id, so we derive a stable synthetic key by
+ # hashing the full event payload. This keeps genuinely distinct events apart even when they
+ # share a timestamp/type/description (different actor, token, or source IP hash differently),
+ # while an identical row re-pulled inside the overlap window still collapses onto one row.
+ return hashlib.sha256(orjson.dumps(event, option=orjson.OPT_SORT_KEYS, default=str)).hexdigest()
+
+
+def _get_audit_log_rows(
+ session: requests.Session,
+ headers: dict[str, str],
+ logger: FilteringBoundLogger,
+ organization: str,
+ resumable_source_manager: ResumableSourceManager[PulumiCloudResumeConfig],
+ config: PulumiCloudEndpointConfig,
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Any,
+) -> Iterator[list[dict[str, Any]]]:
+ url = f"{PULUMI_CLOUD_BASE_URL}{_format_path(config.path, organization)}"
+
+ base_params: dict[str, Any] = {}
+ if should_use_incremental_field:
+ last_value = _as_unix_seconds(db_incremental_field_last_value)
+ if last_value is not None:
+ # The v2 endpoint's startTime is a server-side lower bound on the query range.
+ base_params["startTime"] = max(last_value - AUDIT_LOGS_LOOKBACK_SECONDS, 0)
+
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ token = resume.next_token if resume else None
+
+ for _ in range(MAX_PAGES):
+ params = dict(base_params)
+ if token:
+ params["continuationToken"] = token
+ data = _fetch(session, url, headers, logger, params=params)
+ events = data.get("auditLogEvents", [])
+ token = data.get("continuationToken") or None
+ if events:
+ for event in events:
+ event["event_id"] = _audit_event_id(event)
+ yield events
+ if token:
+ resumable_source_manager.save_state(PulumiCloudResumeConfig(next_token=token))
+ if not token:
+ return
+ logger.warning(f"Pulumi Cloud: audit_logs hit the page cap ({MAX_PAGES}) for org={organization}")
+
+
+def _get_resource_rows(
+ session: requests.Session,
+ headers: dict[str, str],
+ logger: FilteringBoundLogger,
+ organization: str,
+ resumable_source_manager: ResumableSourceManager[PulumiCloudResumeConfig],
+ config: PulumiCloudEndpointConfig,
+) -> Iterator[list[dict[str, Any]]]:
+ url = f"{PULUMI_CLOUD_BASE_URL}{_format_path(config.path, organization)}"
+
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ cursor = resume.next_token if resume else None
+
+ for _ in range(MAX_PAGES):
+ params: dict[str, Any] = {"size": PAGE_SIZE}
+ if cursor:
+ params["cursor"] = cursor
+ data = _fetch(session, url, headers, logger, params=params)
+ resources = data.get("resources", [])
+ if not resources:
+ return
+ yield resources
+ # The response carries both a `next` link and an opaque `cursor`; an absent `next` link
+ # signals the final page (the cursor may still be echoed back on it).
+ pagination = data.get("pagination") or {}
+ cursor = pagination.get("cursor") if pagination.get("next") else None
+ if not cursor:
+ return
+ resumable_source_manager.save_state(PulumiCloudResumeConfig(next_token=cursor))
+ logger.warning(f"Pulumi Cloud: resources hit the page cap ({MAX_PAGES}) for org={organization}")
+
+
+def get_rows(
+ access_token: str,
+ organization: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[PulumiCloudResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+ incremental_field: str | None = None,
+) -> Iterator[list[dict[str, Any]]]:
+ config = PULUMI_CLOUD_ENDPOINTS[endpoint]
+ headers = _get_headers(access_token)
+ # One session reused across every page (and, for fan-out, every stack) so urllib3 keeps the
+ # connection alive. Register the token for value-based redaction so it can't surface in logged
+ # URLs, and disable sample capture: responses carry arbitrary infrastructure data (stack config,
+ # environment variables, audit descriptions) that the name-based scrubber can't sanitise.
+ session = make_tracked_session(redact_values=(access_token,), capture=False)
+
+ if endpoint == "stacks":
+ yield from _get_stack_rows(session, headers, logger, organization, resumable_source_manager)
+ elif endpoint == "stack_updates":
+ yield from _get_stack_update_rows(
+ session,
+ headers,
+ logger,
+ organization,
+ resumable_source_manager,
+ config,
+ should_use_incremental_field,
+ db_incremental_field_last_value,
+ )
+ elif endpoint == "deployments":
+ yield from _get_deployment_rows(session, headers, logger, organization, resumable_source_manager, config)
+ elif endpoint == "audit_logs":
+ yield from _get_audit_log_rows(
+ session,
+ headers,
+ logger,
+ organization,
+ resumable_source_manager,
+ config,
+ should_use_incremental_field,
+ db_incremental_field_last_value,
+ )
+ elif endpoint == "resources":
+ yield from _get_resource_rows(session, headers, logger, organization, resumable_source_manager, config)
+ else:
+ raise ValueError(f"Unknown Pulumi Cloud endpoint: {endpoint}")
+
+
+def pulumi_cloud_source(
+ access_token: str,
+ organization: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[PulumiCloudResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+ incremental_field: str | None = None,
+) -> SourceResponse:
+ config = PULUMI_CLOUD_ENDPOINTS[endpoint]
+
+ # stack_updates and audit_logs arrive newest-first; stack_updates additionally fans out per
+ # stack, so its watermark must persist only at successful job end (a partial run's max says
+ # nothing about stacks it never reached). Deployments also list newest-first by default.
+ descending_endpoints = {"stack_updates", "audit_logs", "deployments"}
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ access_token=access_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,
+ incremental_field=incremental_field,
+ ),
+ primary_keys=config.primary_keys,
+ sort_mode="desc" if endpoint in descending_endpoints else "asc",
+ partition_count=1,
+ partition_size=1,
+ partition_mode="datetime" if config.partition_key else None,
+ partition_format="month" if config.partition_key else None,
+ partition_keys=[config.partition_key] if config.partition_key else None,
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/pulumi_cloud/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/pulumi_cloud/settings.py
new file mode 100644
index 000000000000..b149c4d074a6
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/pulumi_cloud/settings.py
@@ -0,0 +1,121 @@
+from dataclasses import dataclass, field
+from typing import Literal, Optional
+
+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+
+PaginationStyle = Literal["continuation_token", "page", "cursor"]
+
+
+@dataclass
+class PulumiCloudEndpointConfig:
+ name: str
+ path: str
+ # Primary key columns for the merge upsert. Fan-out endpoints aggregate rows from every
+ # stack, so their keys include the stack coordinates (orgName/projectName/stackName) to stay
+ # unique table-wide — a bare per-stack `version` would collide across stacks.
+ primary_keys: list[str]
+ pagination: PaginationStyle
+ incremental_fields: list[IncrementalField] = field(default_factory=list)
+ # Stable creation-style field to partition by (never a mutable `modified`-style field).
+ partition_key: Optional[str] = None
+ # When True the endpoint is called once per stack discovered via GET /api/user/stacks,
+ # formatting the stack's org/project/stack into `path`. When False it is a single top-level
+ # request against the configured organization.
+ fan_out_over_stacks: bool = False
+ default_incremental_field: Optional[str] = None
+ # Whether the table is selected for sync by default in the schema picker.
+ should_sync_default: bool = True
+ # Table description surfaced in the schema picker.
+ description: Optional[str] = None
+
+
+# Endpoint catalog. Pulumi Cloud's REST API lives at api.pulumi.com and is authenticated with a
+# self-serve access token (`Authorization: token pul-...`) plus a versioned Accept header
+# (`application/vnd.pulumi+8`). Endpoint parameters and response shapes below were verified against
+# the live OpenAPI spec the service publishes at https://api.pulumi.com/api/openapi/pulumi-spec.json.
+#
+# Incremental sync:
+# - `audit_logs` uses GET /api/orgs/{org}/auditlogs/v2, whose `startTime` param is a genuine
+# server-side lower bound on the query range ("Lower bound of the query range (unix timestamp)"),
+# so it maps straight from the stored watermark.
+# - `stack_updates` has no server-side time filter, but the paginated format is documented to return
+# newest-first ("pageSize=1 with page=1 returns only the most recent update"), so the paginator
+# stops client-side once an entire page predates the watermark — each incremental run only pays
+# for the new pages instead of re-walking every stack's full history.
+# - `stacks`, `deployments`, and `resources` are current-state listings/indexes with no reliable
+# server-side timestamp filter, so they ship as full refresh.
+PULUMI_CLOUD_ENDPOINTS: dict[str, PulumiCloudEndpointConfig] = {
+ "stacks": PulumiCloudEndpointConfig(
+ name="stacks",
+ path="/api/user/stacks",
+ # `id` is "the logical identifier of the stack" and is a required response field.
+ primary_keys=["id"],
+ pagination="continuation_token",
+ description="One row per stack the token can access in the organization, with its last update time and resource count",
+ ),
+ "stack_updates": PulumiCloudEndpointConfig(
+ name="stack_updates",
+ path="/api/stacks/{org}/{project}/{stack}/updates",
+ # `version` is the stack-scoped ordinal of the update, so the stack coordinates are what
+ # make the key unique table-wide across the fan-out.
+ primary_keys=["orgName", "projectName", "stackName", "version"],
+ pagination="page",
+ fan_out_over_stacks=True,
+ default_incremental_field="startTime",
+ incremental_fields=[
+ {
+ "label": "startTime",
+ "type": IncrementalFieldType.Integer,
+ "field": "startTime",
+ "field_type": IncrementalFieldType.Integer,
+ },
+ ],
+ description="The full update/preview/refresh/destroy history of every stack, with outcomes, timings, and resource change counts",
+ ),
+ "deployments": PulumiCloudEndpointConfig(
+ name="deployments",
+ path="/api/orgs/{org}/deployments",
+ primary_keys=["id"],
+ pagination="page",
+ partition_key="created",
+ description="Pulumi Deployments runs across the organization, with status, operation, and job details. Empty unless the organization uses Pulumi Deployments",
+ ),
+ "audit_logs": PulumiCloudEndpointConfig(
+ name="audit_logs",
+ path="/api/orgs/{org}/auditlogs/v2",
+ # Audit log events carry no server-assigned id, so the source derives a synthetic `event_id`
+ # by hashing the full event payload (see `_audit_event_id`). A composite of timestamp/type/
+ # description alone would collapse distinct events that differ only by actor, token, or source
+ # IP; hashing every field keeps those apart while identical overlap re-pulls still dedupe.
+ primary_keys=["event_id"],
+ pagination="continuation_token",
+ default_incremental_field="timestamp",
+ incremental_fields=[
+ {
+ "label": "timestamp",
+ "type": IncrementalFieldType.Integer,
+ "field": "timestamp",
+ "field_type": IncrementalFieldType.Integer,
+ },
+ ],
+ # Audit logs are gated to higher Pulumi Cloud tiers (Enterprise / Business Critical), so a
+ # default-on selection would fail the first sync for most organizations.
+ should_sync_default=False,
+ description="Organization audit log events (who did what, when, from where). Requires a Pulumi Cloud plan with audit logs enabled",
+ ),
+ "resources": PulumiCloudEndpointConfig(
+ name="resources",
+ path="/api/orgs/{org}/search/resources",
+ # `urn` is only unique within a stack, so project/stack complete the key table-wide.
+ primary_keys=["project", "stack", "urn"],
+ pagination="cursor",
+ partition_key="created",
+ description="Every resource in the organization's Pulumi Insights resource index, one row per resource",
+ ),
+}
+
+ENDPOINTS = tuple(PULUMI_CLOUD_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in PULUMI_CLOUD_ENDPOINTS.items()
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/pulumi_cloud/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/pulumi_cloud/source.py
index 9a3d5c3a56ba..fa49e876e046 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/pulumi_cloud/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/pulumi_cloud/source.py
@@ -1,30 +1,159 @@
-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.generated_configs import PulumiCloudSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.pulumi_cloud.pulumi_cloud import (
+ PulumiCloudResumeConfig,
+ pulumi_cloud_source,
+ validate_credentials as validate_pulumi_cloud_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.pulumi_cloud.settings import (
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+ PULUMI_CLOUD_ENDPOINTS,
+)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class PulumiCloudSource(SimpleSource[PulumiCloudSourceConfig]):
+class PulumiCloudSource(ResumableSource[PulumiCloudSourceConfig, PulumiCloudResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.PULUMICLOUD
+ @property
+ def connection_host_fields(self) -> list[str]:
+ # `organization` selects which Pulumi tenant the stored token queries, so retargeting it
+ # must re-require the token — otherwise a preserved credential could be aimed at another
+ # organization the token can access without the editor knowing the redacted secret.
+ return ["organization"]
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=SchemaExternalDataSourceType.PULUMI_CLOUD,
category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,
label="Pulumi",
+ releaseStatus=ReleaseStatus.ALPHA,
+ caption="""Enter your Pulumi Cloud access token and organization name to pull your infrastructure-as-code data into the PostHog Data warehouse.
+
+Create a personal access token from your [Pulumi Cloud access tokens page](https://app.pulumi.com/account/tokens), or an organization access token from your organization's settings. The token inherits its owner's access, so no extra scopes are required.
+
+The organization name is the one shown in your Pulumi Cloud console URL (`app.pulumi.com/<organization>`). Audit logs additionally require a Pulumi Cloud plan with audit logs enabled.""",
iconPath="/static/services/pulumi_cloud.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/pulumi-cloud",
+ keywords=["iac", "infrastructure as code", "deployments", "devops"],
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="access_token",
+ label="Access token",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="pul-...",
+ secret=True,
+ ),
+ SourceFieldInputConfig(
+ name="organization",
+ label="Organization",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="my-org",
+ secret=False,
+ ),
+ ],
+ ),
+ )
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.pulumi_cloud.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error: Unauthorized for url: https://api.pulumi.com": "Your Pulumi Cloud access token is invalid or has been revoked. Create a new access token in Pulumi Cloud, then reconnect.",
+ "403 Client Error: Forbidden for url: https://api.pulumi.com": "Your Pulumi Cloud access token does not have access to this data. Check the token's organization membership (audit logs also require a plan with audit logs enabled), then reconnect.",
+ }
+
+ def get_schemas(
+ self,
+ config: PulumiCloudSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ def _build_schema(endpoint: str) -> SourceSchema:
+ endpoint_config = PULUMI_CLOUD_ENDPOINTS[endpoint]
+ has_incremental = bool(INCREMENTAL_FIELDS.get(endpoint))
+ return SourceSchema(
+ name=endpoint,
+ supports_incremental=has_incremental,
+ # Incremental runs re-pull a trailing safety window that merge dedupes on the
+ # primary key; append would materialize those re-pulled rows as duplicates.
+ supports_append=False,
+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),
+ should_sync_default=endpoint_config.should_sync_default,
+ description=endpoint_config.description,
+ )
+
+ schemas = [_build_schema(endpoint) for endpoint in ENDPOINTS]
+ if names is not None:
+ names_set = set(names)
+ schemas = [s for s in schemas if s.name in names_set]
+ return schemas
+
+ def validate_credentials(
+ self, config: PulumiCloudSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ if validate_pulumi_cloud_credentials(config.access_token):
+ return True, None
+
+ return False, "Invalid Pulumi Cloud access token"
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[PulumiCloudResumeConfig]:
+ return ResumableSourceManager[PulumiCloudResumeConfig](inputs, PulumiCloudResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: PulumiCloudSourceConfig,
+ resumable_source_manager: ResumableSourceManager[PulumiCloudResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return pulumi_cloud_source(
+ access_token=config.access_token,
+ organization=config.organization,
+ endpoint=inputs.schema_name,
+ logger=inputs.logger,
+ resumable_source_manager=resumable_source_manager,
+ should_use_incremental_field=inputs.should_use_incremental_field,
+ db_incremental_field_last_value=inputs.db_incremental_field_last_value
+ if inputs.should_use_incremental_field
+ else None,
+ incremental_field=inputs.incremental_field,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/pulumi_cloud/tests/test_pulumi_cloud.py b/products/warehouse_sources/backend/temporal/data_imports/sources/pulumi_cloud/tests/test_pulumi_cloud.py
new file mode 100644
index 000000000000..2829e93cfe56
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/pulumi_cloud/tests/test_pulumi_cloud.py
@@ -0,0 +1,508 @@
+from datetime import UTC, datetime
+from typing import Any
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+from parameterized import parameterized
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.pulumi_cloud import pulumi_cloud
+from products.warehouse_sources.backend.temporal.data_imports.sources.pulumi_cloud.pulumi_cloud import (
+ AUDIT_LOGS_LOOKBACK_SECONDS,
+ PAGE_SIZE,
+ STACK_UPDATES_LOOKBACK_SECONDS,
+ PulumiCloudResumeConfig,
+ _as_unix_seconds,
+ _flatten_update,
+ get_rows,
+ pulumi_cloud_source,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.pulumi_cloud.settings import (
+ PULUMI_CLOUD_ENDPOINTS,
+)
+
+
+class _FakeResumableManager:
+ def __init__(self, state: PulumiCloudResumeConfig | None = None) -> None:
+ self._state = state
+ self.saved: list[PulumiCloudResumeConfig] = []
+
+ def can_resume(self) -> bool:
+ return self._state is not None
+
+ def load_state(self) -> PulumiCloudResumeConfig | None:
+ return self._state
+
+ def save_state(self, data: PulumiCloudResumeConfig) -> None:
+ self.saved.append(data)
+
+
+def _run_rows(
+ endpoint: str,
+ fake_fetch: Any,
+ manager: _FakeResumableManager,
+ **incremental: Any,
+) -> list[dict]:
+ rows: list[dict] = []
+ with patch.object(pulumi_cloud, "_fetch", fake_fetch):
+ for page in get_rows(
+ access_token="pul-test",
+ organization="my-org",
+ endpoint=endpoint,
+ logger=MagicMock(),
+ resumable_source_manager=manager, # type: ignore[arg-type]
+ **incremental,
+ ):
+ rows.extend(page)
+ return rows
+
+
+def _stack_summary(project: str, stack: str) -> dict[str, Any]:
+ return {"id": f"my-org/{project}/{stack}", "orgName": "my-org", "projectName": project, "stackName": stack}
+
+
+class TestAsUnixSeconds:
+ @parameterized.expand(
+ [
+ ("int", 1750000000, 1750000000),
+ ("float", 1750000000.7, 1750000000),
+ ("numeric_string", "1750000000", 1750000000),
+ ("datetime", datetime(2026, 6, 15, tzinfo=UTC), 1781481600),
+ ("bool", True, None),
+ ("garbage_string", "not-a-timestamp", None),
+ ("none", None, None),
+ ]
+ )
+ def test_coercion(self, _name: str, value: Any, expected: int | None) -> None:
+ # A miscoerced watermark would either crash the sync or silently disable the incremental
+ # bound and re-pull full history every run.
+ assert _as_unix_seconds(value) == expected
+
+
+class TestStacks:
+ def test_pagination_follows_continuation_token_and_saves_state_after_yield(self) -> None:
+ pages = {
+ None: {"stacks": [_stack_summary("proj", "dev")], "continuationToken": "tok-2"},
+ "tok-2": {"stacks": [_stack_summary("proj", "prod")]},
+ }
+ seen_tokens: list[str | None] = []
+
+ def fake_fetch(session: Any, url: str, headers: dict, logger: Any, params: dict | None = None) -> Any:
+ token = (params or {}).get("continuationToken")
+ seen_tokens.append(token)
+ return pages[token]
+
+ manager = _FakeResumableManager()
+ rows = _run_rows("stacks", fake_fetch, manager)
+
+ assert seen_tokens == [None, "tok-2"]
+ assert [r["stackName"] for r in rows] == ["dev", "prod"]
+ # State is saved after yielding a page, and only while more pages remain — so a crash
+ # re-yields the last page (merge dedupes) instead of skipping it.
+ assert [s.next_token for s in manager.saved] == ["tok-2"]
+
+ def test_resume_starts_from_saved_token(self) -> None:
+ def fake_fetch(session: Any, url: str, headers: dict, logger: Any, params: dict | None = None) -> Any:
+ assert (params or {}).get("continuationToken") == "tok-2"
+ return {"stacks": [_stack_summary("proj", "prod")]}
+
+ manager = _FakeResumableManager(PulumiCloudResumeConfig(next_token="tok-2"))
+ rows = _run_rows("stacks", fake_fetch, manager)
+ assert [r["stackName"] for r in rows] == ["prod"]
+
+
+class TestFlattenUpdate:
+ def test_flattens_info_injects_stack_coordinates_and_drops_deployment(self) -> None:
+ # The nested `info` carries the analytics payload (kind/result/times); the raw deployment
+ # state snapshot can be enormous and must not reach the warehouse row, and `environment` can
+ # hold credentials so it must be dropped too. The injected stack coordinates are what make
+ # the composite primary key unique table-wide.
+ item = {
+ "updateID": "u-1",
+ "version": 3,
+ "latestVersion": 5,
+ "requestedBy": {"githubLogin": "alice"},
+ # A live access token the API returns on the outer update object — must never persist.
+ "requestedByToken": "pul-secret-token",
+ "info": {
+ "kind": "update",
+ "startTime": 1750000000,
+ "endTime": 1750000060,
+ "result": "succeeded",
+ "resourceChanges": {"create": 2},
+ "deployment": {"huge": "snapshot"},
+ # Env vars supplied to the update — can carry cloud creds / PULUMI_CONFIG_PASSPHRASE.
+ "environment": {"AWS_SECRET_ACCESS_KEY": "shh", "PULUMI_CONFIG_PASSPHRASE": "shh"},
+ },
+ }
+ row = _flatten_update(item, "my-org", "proj", "dev")
+ assert row == {
+ "updateID": "u-1",
+ "version": 3,
+ "latestVersion": 5,
+ "requestedBy": {"githubLogin": "alice"},
+ "kind": "update",
+ "startTime": 1750000000,
+ "endTime": 1750000060,
+ "result": "succeeded",
+ "resourceChanges": {"create": 2},
+ "orgName": "my-org",
+ "projectName": "proj",
+ "stackName": "dev",
+ }
+
+ def test_item_without_info_still_gets_stack_coordinates(self) -> None:
+ row = _flatten_update({"updateID": "u-2", "version": 1}, "my-org", "proj", "dev")
+ assert row["projectName"] == "proj"
+ assert row["version"] == 1
+
+ def test_secret_config_ciphertext_is_stripped_but_plaintext_kept(self) -> None:
+ # Secret config entries carry an encrypted `string` that is recoverable offline; it must not
+ # reach the warehouse row. Non-secret entries and the secret's metadata are preserved.
+ item = {
+ "version": 1,
+ "info": {
+ "config": {
+ "aws:region": {"string": "us-east-1"},
+ "app:dbPassword": {"secret": True, "string": "AAABBBencrypted"},
+ }
+ },
+ }
+ row = _flatten_update(item, "my-org", "proj", "dev")
+ assert row["config"]["aws:region"] == {"string": "us-east-1"}
+ assert row["config"]["app:dbPassword"] == {"secret": True}
+
+
+class TestStackUpdates:
+ def _make_pages(self, start_times_per_page: list[list[int]]) -> Any:
+ stack_list = {"stacks": [_stack_summary("proj", "dev")]}
+
+ def fake_fetch(session: Any, url: str, headers: dict, logger: Any, params: dict | None = None) -> Any:
+ if url.endswith("/api/user/stacks"):
+ return stack_list
+ page = (params or {}).get("page", 1)
+ if page > len(start_times_per_page):
+ return {"updates": []}
+ return {
+ "updates": [
+ {"updateID": f"u-{t}", "version": t, "info": {"startTime": t}}
+ for t in start_times_per_page[page - 1]
+ ]
+ }
+
+ return fake_fetch
+
+ def test_full_refresh_walks_pages_until_short_page(self) -> None:
+ pages = [list(range(2 * PAGE_SIZE, PAGE_SIZE, -1)), list(range(PAGE_SIZE, PAGE_SIZE - 30, -1))]
+ rows = _run_rows("stack_updates", self._make_pages(pages), _FakeResumableManager())
+ assert len(rows) == PAGE_SIZE + 30
+ assert rows[0]["orgName"] == "my-org"
+
+ def test_incremental_stops_once_a_page_predates_the_watermark(self) -> None:
+ # Updates arrive newest-first with no server-side time filter; without the client-side stop
+ # every incremental sync would re-walk each stack's full history (API-cost bug and memory
+ # amplifier). Rows below the effective watermark must also not be re-yielded.
+ effective_watermark = 2000
+ raw_watermark = effective_watermark + STACK_UPDATES_LOOKBACK_SECONDS
+ first_page = list(range(2050, 2050 - PAGE_SIZE, -1)) # full page reaching below 2000
+ second_page = list(range(1950, 1850, -1)) # must never be fetched
+
+ fetched_pages: list[int] = []
+ inner = self._make_pages([first_page, second_page])
+
+ def fake_fetch(session: Any, url: str, headers: dict, logger: Any, params: dict | None = None) -> Any:
+ if not url.endswith("/api/user/stacks"):
+ fetched_pages.append((params or {}).get("page", 1))
+ return inner(session, url, headers, logger, params)
+
+ rows = _run_rows(
+ "stack_updates",
+ fake_fetch,
+ _FakeResumableManager(),
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=raw_watermark,
+ incremental_field="startTime",
+ )
+
+ assert fetched_pages == [1]
+ assert [r["startTime"] for r in rows] == list(range(2050, effective_watermark - 1, -1))
+
+ def test_incremental_stops_on_full_page_without_usable_start_times(self) -> None:
+ # If the API ever returns a full page of updates with no usable startTime, the newest-first
+ # stop signal is absent; pagination must bail instead of walking to the page cap. The rows on
+ # that page are still yielded (kept) so an untimestamped update isn't silently dropped.
+ fetched_pages: list[int] = []
+
+ def fake_fetch(session: Any, url: str, headers: dict, logger: Any, params: dict | None = None) -> Any:
+ if url.endswith("/api/user/stacks"):
+ return {"stacks": [_stack_summary("proj", "dev")]}
+ page = (params or {}).get("page", 1)
+ fetched_pages.append(page)
+ # A full page (would otherwise trigger another fetch) with no startTime on any row.
+ return {"updates": [{"updateID": f"u-{page}-{i}", "version": i, "info": {}} for i in range(PAGE_SIZE)]}
+
+ rows = _run_rows(
+ "stack_updates",
+ fake_fetch,
+ _FakeResumableManager(),
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=5000,
+ incremental_field="startTime",
+ )
+
+ assert fetched_pages == [1]
+ assert len(rows) == PAGE_SIZE
+
+ def test_incremental_without_watermark_walks_full_history(self) -> None:
+ pages = [list(range(2 * PAGE_SIZE, PAGE_SIZE, -1)), [50]]
+ rows = _run_rows(
+ "stack_updates",
+ self._make_pages(pages),
+ _FakeResumableManager(),
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=None,
+ incremental_field="startTime",
+ )
+ assert len(rows) == PAGE_SIZE + 1
+
+ def test_fan_out_marks_stacks_completed_and_resume_skips_them(self) -> None:
+ stacks = [_stack_summary("proj", "dev"), _stack_summary("proj", "prod")]
+
+ def fake_fetch(session: Any, url: str, headers: dict, logger: Any, params: dict | None = None) -> Any:
+ if url.endswith("/api/user/stacks"):
+ return {"stacks": stacks}
+ stack = url.split("/updates")[0].rsplit("/", 1)[-1]
+ return {"updates": [{"updateID": f"u-{stack}", "version": 1, "info": {"startTime": 1}}]}
+
+ manager = _FakeResumableManager()
+ _run_rows("stack_updates", fake_fetch, manager)
+ # Completed keys accumulate AFTER each stack's rows are yielded, so a crash mid-stack
+ # re-processes that stack (merge dedupes) rather than skipping it.
+ assert [s.completed_stack_keys for s in manager.saved] == [
+ ["my-org/proj/dev"],
+ ["my-org/proj/dev", "my-org/proj/prod"],
+ ]
+
+ resumed = _FakeResumableManager(PulumiCloudResumeConfig(completed_stack_keys=["my-org/proj/dev"]))
+ rows = _run_rows("stack_updates", fake_fetch, resumed)
+ assert [r["stackName"] for r in rows] == ["prod"]
+
+
+class TestDeployments:
+ def test_paginates_until_short_page_and_saves_next_page_after_yield(self) -> None:
+ pages = {
+ 1: {"deployments": [{"id": f"d{i}", "created": "2026-06-01T00:00:00Z"} for i in range(PAGE_SIZE)]},
+ 2: {"deployments": [{"id": "last", "created": "2026-05-01T00:00:00Z"}]},
+ }
+ seen_pages: list[int] = []
+
+ def fake_fetch(session: Any, url: str, headers: dict, logger: Any, params: dict | None = None) -> Any:
+ page = (params or {}).get("page", 1)
+ seen_pages.append(page)
+ return pages[page]
+
+ manager = _FakeResumableManager()
+ rows = _run_rows("deployments", fake_fetch, manager)
+
+ assert seen_pages == [1, 2]
+ assert len(rows) == PAGE_SIZE + 1
+ # Saved AFTER yielding page 1: a crash between yield and save re-fetches page 1 (merge
+ # dedupes) instead of skipping it.
+ assert [s.page for s in manager.saved] == [2]
+
+ def test_resume_starts_from_saved_page(self) -> None:
+ def fake_fetch(session: Any, url: str, headers: dict, logger: Any, params: dict | None = None) -> Any:
+ assert (params or {}).get("page") == 3
+ return {"deployments": [{"id": "d-resumed"}]}
+
+ manager = _FakeResumableManager(PulumiCloudResumeConfig(page=3))
+ rows = _run_rows("deployments", fake_fetch, manager)
+ assert [r["id"] for r in rows] == ["d-resumed"]
+
+ def test_empty_first_page_yields_nothing(self) -> None:
+ # Orgs without Pulumi Deployments get an empty listing, not an error.
+ rows = _run_rows("deployments", lambda *a, **k: {"deployments": []}, _FakeResumableManager())
+ assert rows == []
+
+ def test_drops_environment_secrets_from_embedded_updates(self) -> None:
+ # A deployment embeds the updates it ran, and each update's `environment` can hold cloud
+ # credentials or PULUMI_CONFIG_PASSPHRASE; these rows skip `_flatten_update`, so the yield
+ # path must strip them before they reach a queryable warehouse row.
+ page = {
+ "deployments": [
+ {
+ "id": "d1",
+ "updates": [
+ {"updateID": "u1", "environment": {"AWS_SECRET_ACCESS_KEY": "shh"}},
+ {"updateID": "u2"},
+ ],
+ }
+ ]
+ }
+ rows = _run_rows("deployments", lambda *a, **k: page, _FakeResumableManager())
+ assert len(rows) == 1
+ updates = rows[0]["updates"]
+ assert all("environment" not in update for update in updates)
+ assert [u["updateID"] for u in updates] == ["u1", "u2"]
+
+
+class TestAuditLogs:
+ def _pages_fetch(self, captured: list[dict]) -> Any:
+ pages = {
+ None: {"auditLogEvents": [{"timestamp": 100, "event": "stack.update"}], "continuationToken": "c-2"},
+ "c-2": {"auditLogEvents": [{"timestamp": 90, "event": "member.added"}]},
+ }
+
+ def fake_fetch(session: Any, url: str, headers: dict, logger: Any, params: dict | None = None) -> Any:
+ captured.append(dict(params or {}))
+ return pages[(params or {}).get("continuationToken")]
+
+ return fake_fetch
+
+ def test_incremental_passes_server_side_start_time_lower_bound(self) -> None:
+ # The v2 endpoint's startTime is the genuine server-side filter this table's incremental
+ # support is built on; dropping it would re-pull the org's entire audit history every run.
+ captured: list[dict] = []
+ manager = _FakeResumableManager()
+ rows = _run_rows(
+ "audit_logs",
+ self._pages_fetch(captured),
+ manager,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=1750000000,
+ incremental_field="timestamp",
+ )
+
+ expected_start = 1750000000 - AUDIT_LOGS_LOOKBACK_SECONDS
+ assert all(p.get("startTime") == expected_start for p in captured)
+ assert captured[1]["continuationToken"] == "c-2"
+ assert [r["timestamp"] for r in rows] == [100, 90]
+ assert [s.next_token for s in manager.saved] == ["c-2"]
+
+ def test_full_refresh_omits_start_time(self) -> None:
+ captured: list[dict] = []
+ _run_rows("audit_logs", self._pages_fetch(captured), _FakeResumableManager())
+ assert all("startTime" not in p for p in captured)
+
+ def test_synthetic_event_id_distinguishes_events_colliding_on_time_type_description(self) -> None:
+ # Two distinct events sharing timestamp/type/description but differing only by actor must not
+ # collapse onto one primary key; an identical re-pulled event must reuse its key so it dedupes.
+ page = {
+ "auditLogEvents": [
+ {"timestamp": 100, "event": "stack.update", "description": "updated prod", "user": "alice"},
+ {"timestamp": 100, "event": "stack.update", "description": "updated prod", "user": "bob"},
+ {"timestamp": 100, "event": "stack.update", "description": "updated prod", "user": "alice"},
+ ]
+ }
+ rows = _run_rows("audit_logs", lambda *a, **k: page, _FakeResumableManager())
+
+ assert PULUMI_CLOUD_ENDPOINTS["audit_logs"].primary_keys == ["event_id"]
+ assert rows[0]["event_id"] != rows[1]["event_id"]
+ assert rows[0]["event_id"] == rows[2]["event_id"]
+
+
+class TestResources:
+ def test_cursor_advances_only_while_next_link_present(self) -> None:
+ # The final page can still echo a cursor back; only the `next` link signals another page.
+ # Following the echoed cursor would loop on the last page forever.
+ pages = {
+ None: {
+ "resources": [{"urn": "urn:1", "project": "p", "stack": "s"}],
+ "pagination": {"cursor": "cur-2", "next": "https://api.pulumi.com/next"},
+ },
+ "cur-2": {
+ "resources": [{"urn": "urn:2", "project": "p", "stack": "s"}],
+ "pagination": {"cursor": "cur-2"},
+ },
+ }
+ seen_cursors: list[str | None] = []
+
+ def fake_fetch(session: Any, url: str, headers: dict, logger: Any, params: dict | None = None) -> Any:
+ cursor = (params or {}).get("cursor")
+ seen_cursors.append(cursor)
+ return pages[cursor]
+
+ manager = _FakeResumableManager()
+ rows = _run_rows("resources", fake_fetch, manager)
+
+ assert seen_cursors == [None, "cur-2"]
+ assert [r["urn"] for r in rows] == ["urn:1", "urn:2"]
+ assert [s.next_token for s in manager.saved] == ["cur-2"]
+
+ def test_empty_page_terminates(self) -> None:
+ rows = _run_rows("resources", lambda *a, **k: {"resources": []}, _FakeResumableManager())
+ assert rows == []
+
+
+class TestValidateCredentials:
+ @parameterized.expand([("ok", 200, True), ("unauthorized", 401, False), ("forbidden", 403, False)])
+ def test_status_maps_to_validity(self, _name: str, status: int, expected: bool) -> None:
+ response = MagicMock()
+ response.status_code = status
+ session = MagicMock()
+ session.get.return_value = response
+ with patch.object(pulumi_cloud, "make_tracked_session", return_value=session):
+ assert validate_credentials("pul-test") is expected
+
+ def test_network_error_is_not_valid(self) -> None:
+ session = MagicMock()
+ session.get.side_effect = Exception("boom")
+ with patch.object(pulumi_cloud, "make_tracked_session", return_value=session):
+ assert validate_credentials("pul-test") is False
+
+
+class TestFetchRetries:
+ @parameterized.expand([("rate_limited", 429), ("server_error", 503)])
+ def test_retryable_status_codes_are_retried(self, _name: str, status: int) -> None:
+ bad = MagicMock(status_code=status)
+ good = MagicMock(status_code=200, ok=True)
+ good.json.return_value = {"ok": True}
+ session = MagicMock()
+ session.get.side_effect = [bad, good]
+
+ with patch.object(pulumi_cloud._fetch.retry, "sleep", lambda *_: None): # type: ignore[attr-defined]
+ result = pulumi_cloud._fetch(session, "https://api.pulumi.com/api/user", {}, MagicMock())
+
+ assert result == {"ok": True}
+ assert session.get.call_count == 2
+
+ def test_client_error_raises_without_retry(self) -> None:
+ import requests
+
+ bad = requests.Response()
+ bad.status_code = 401
+ session = MagicMock()
+ session.get.return_value = bad
+
+ with pytest.raises(requests.HTTPError):
+ pulumi_cloud._fetch(session, "https://api.pulumi.com/api/user", {}, MagicMock())
+ assert session.get.call_count == 1
+
+
+class TestSourceResponse:
+ @parameterized.expand(
+ [
+ ("stacks", "asc", None),
+ # Newest-first endpoints report "desc" so the incremental watermark persists only at
+ # successful job end; "asc" per-batch persistence would checkpoint the watermark to
+ # ≈now after the first (newest) batch and lose everything a crashed run still owed.
+ ("stack_updates", "desc", None),
+ ("deployments", "desc", "created"),
+ ("audit_logs", "desc", None),
+ ("resources", "asc", "created"),
+ ]
+ )
+ def test_sort_mode_partition_and_primary_keys(
+ self, endpoint: str, expected_sort: str, partition_key: str | None
+ ) -> None:
+ response = pulumi_cloud_source(
+ access_token="pul-test",
+ organization="my-org",
+ endpoint=endpoint,
+ logger=MagicMock(),
+ resumable_source_manager=MagicMock(),
+ )
+ assert response.sort_mode == expected_sort
+ assert response.partition_keys == ([partition_key] if partition_key else None)
+ assert response.primary_keys == PULUMI_CLOUD_ENDPOINTS[endpoint].primary_keys
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/pulumi_cloud/tests/test_pulumi_cloud_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/pulumi_cloud/tests/test_pulumi_cloud_source.py
new file mode 100644
index 000000000000..c9195a706840
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/pulumi_cloud/tests/test_pulumi_cloud_source.py
@@ -0,0 +1,153 @@
+from typing import Optional
+
+from unittest.mock import MagicMock, patch
+
+from parameterized import parameterized
+
+from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceInputs
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import PulumiCloudSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.pulumi_cloud import source as source_module
+from products.warehouse_sources.backend.temporal.data_imports.sources.pulumi_cloud.pulumi_cloud import (
+ PulumiCloudResumeConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.pulumi_cloud.settings import ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.pulumi_cloud.source import PulumiCloudSource
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+def _source_inputs(
+ schema_name: str, last_value: Optional[object] = None, use_incremental: bool = False
+) -> SourceInputs:
+ return SourceInputs(
+ schema_name=schema_name,
+ schema_id="schema-1",
+ source_id="source-1",
+ team_id=1,
+ should_use_incremental_field=use_incremental,
+ db_incremental_field_last_value=last_value,
+ db_incremental_field_earliest_value=None,
+ incremental_field="timestamp" if use_incremental else None,
+ incremental_field_type=None,
+ job_id="job-1",
+ logger=MagicMock(),
+ reset_pipeline=False,
+ )
+
+
+class TestPulumiCloudSource:
+ def setup_method(self) -> None:
+ self.source = PulumiCloudSource()
+
+ def test_source_type(self) -> None:
+ assert self.source.source_type == ExternalDataSourceType.PULUMICLOUD
+
+ def test_source_config_fields(self) -> None:
+ config = self.source.get_source_config
+ assert [f.name for f in config.fields] == ["access_token", "organization"]
+ token_field, org_field = config.fields
+ assert isinstance(token_field, SourceFieldInputConfig)
+ assert token_field.type == SourceFieldInputConfigType.PASSWORD
+ assert token_field.required is True
+ assert token_field.secret is True
+ assert isinstance(org_field, SourceFieldInputConfig)
+ assert org_field.required is True
+ assert org_field.secret is False
+
+ def test_source_is_released_as_alpha(self) -> None:
+ # unreleasedSource hides the connector from every user; a finished source must ship visible
+ # with a soft ALPHA label instead.
+ config = self.source.get_source_config
+ assert not config.unreleasedSource
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/pulumi-cloud"
+
+ def test_lists_tables_without_credentials(self) -> None:
+ # get_schemas is a static, no-I/O catalog, so the public docs table list must render.
+ assert self.source.lists_tables_without_credentials is True
+
+ def test_connection_host_fields_includes_organization(self) -> None:
+ # `organization` picks which Pulumi tenant the stored token queries; retargeting it must
+ # force token re-entry so a preserved credential can't be aimed at another organization.
+ assert self.source.connection_host_fields == ["organization"]
+
+ def test_get_schemas_returns_every_endpoint(self) -> None:
+ schemas = self.source.get_schemas(MagicMock(), team_id=1)
+ assert {s.name for s in schemas} == set(ENDPOINTS)
+
+ def test_get_schemas_filters_by_names(self) -> None:
+ schemas = self.source.get_schemas(MagicMock(), team_id=1, names=["stacks"])
+ assert [s.name for s in schemas] == ["stacks"]
+
+ @parameterized.expand(
+ [
+ # audit_logs has a server-side startTime lower bound; stack_updates pages newest-first
+ # and stops client-side at the watermark. The snapshot/index endpoints are full refresh.
+ ("stacks", False, [], True),
+ ("stack_updates", True, ["startTime"], True),
+ ("deployments", False, [], True),
+ ("audit_logs", True, ["timestamp"], False),
+ ("resources", False, [], True),
+ ]
+ )
+ def test_incremental_support_per_endpoint(
+ self, endpoint: str, supports_incremental: bool, incremental_fields: list[str], sync_default: bool
+ ) -> None:
+ schema = next(s for s in self.source.get_schemas(MagicMock(), team_id=1) if s.name == endpoint)
+ assert schema.supports_incremental is supports_incremental
+ # Incremental runs re-pull an overlap window that merge dedupes; append would duplicate it.
+ assert schema.supports_append is False
+ assert [f["field"] for f in schema.incremental_fields] == incremental_fields
+ # audit_logs is tier-gated in Pulumi Cloud; defaulting it on would fail most first syncs.
+ assert schema.should_sync_default is sync_default
+
+ @parameterized.expand([("valid", True, True), ("invalid", False, False)])
+ def test_validate_credentials(self, _name: str, probe_result: bool, expected_ok: bool) -> None:
+ config = PulumiCloudSourceConfig(access_token="pul-test", organization="my-org")
+ with patch.object(source_module, "validate_pulumi_cloud_credentials", return_value=probe_result):
+ ok, error = self.source.validate_credentials(config, team_id=1)
+ assert ok is expected_ok
+ assert (error is None) is expected_ok
+
+ @parameterized.expand(
+ [
+ ("unauthorized", "401 Client Error: Unauthorized for url: https://api.pulumi.com/api/user/stacks"),
+ ("forbidden", "403 Client Error: Forbidden for url: https://api.pulumi.com/api/orgs/my-org/auditlogs/v2"),
+ ]
+ )
+ def test_credential_errors_are_non_retryable(self, _name: str, observed_error: str) -> None:
+ non_retryable = self.source.get_non_retryable_errors()
+ assert any(key in observed_error for key in non_retryable)
+
+ def test_get_resumable_source_manager_is_bound_to_resume_config(self) -> None:
+ manager = self.source.get_resumable_source_manager(_source_inputs("stacks"))
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is PulumiCloudResumeConfig
+
+ def test_source_for_pipeline_plumbs_credentials_and_endpoint(self) -> None:
+ config = PulumiCloudSourceConfig(access_token="pul-test", organization="my-org")
+ inputs = _source_inputs("audit_logs", last_value=1750000000, use_incremental=True)
+ with patch.object(source_module, "pulumi_cloud_source") as mock_source:
+ self.source.source_for_pipeline(config, MagicMock(), inputs)
+ kwargs = mock_source.call_args.kwargs
+ assert kwargs["access_token"] == "pul-test"
+ assert kwargs["organization"] == "my-org"
+ assert kwargs["endpoint"] == "audit_logs"
+ assert kwargs["should_use_incremental_field"] is True
+ assert kwargs["db_incremental_field_last_value"] == 1750000000
+
+ def test_source_for_pipeline_omits_last_value_when_not_incremental(self) -> None:
+ # Passing a stale watermark on a full-refresh run would wrongly narrow the audit-log window.
+ config = PulumiCloudSourceConfig(access_token="pul-test", organization="my-org")
+ inputs = _source_inputs("audit_logs", last_value=1750000000, use_incremental=False)
+ with patch.object(source_module, "pulumi_cloud_source") as mock_source:
+ self.source.source_for_pipeline(config, MagicMock(), inputs)
+ assert mock_source.call_args.kwargs["db_incremental_field_last_value"] is None
+
+ def test_canonical_descriptions_cover_every_endpoint(self) -> None:
+ # Drift here (an endpoint renamed in settings but not here) silently drops the curated docs
+ # and falls back to LLM enrichment, so keep the two in lockstep.
+ descriptions = self.source.get_canonical_descriptions()
+ assert set(descriptions.keys()) == set(ENDPOINTS)