: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 the gcp cloud billing import source (#115545)
Tom Owers329eea4871e2
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 4a7309385ee0..28516e60c459 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -366,6 +366,7 @@ the row lists both.| gainsight_cs | HTTP | requests | ✅ || gainsight_px | HTTP | requests | ✅ || gcore | HTTP | requests | ✅ |+| gcp_cloud_billing | HTTP | google-auth + `rest_source.RESTClient` | ✅ || genesys_cloud | HTTP | requests | ✅ || gerrit | HTTP | requests | ✅ || getdx | HTTP | requests | ✅ |@@ -1153,7 +1154,6 @@ doesn't conflict with concurrent PRs.- gcp_bigtable- gcp_chronicle- gcp_cloud_asset_inventory-- gcp_cloud_billing- gcp_cloud_build- gcp_cloud_deploy- gcp_cloud_dnsdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gcp_cloud_billing/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gcp_cloud_billing/canonical_descriptions.pynew file mode 100644index 000000000000..2523073692a4--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gcp_cloud_billing/canonical_descriptions.py@@ -0,0 +1,74 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "billing_accounts": {+ "description": "Billing accounts accessible to the service account.",+ "docs_url": "https://cloud.google.com/billing/docs/reference/rest/v1/billingAccounts",+ "columns": {+ "name": "The billing account resource name.",+ "displayName": "The billing account name shown in Google Cloud.",+ "open": "Whether the billing account can pay for usage.",+ "masterBillingAccount": "The parent billing account for a reseller subaccount.",+ "currencyCode": "The currency used by the billing account.",+ },+ },+ "projects": {+ "description": "Projects linked to each accessible billing account.",+ "docs_url": "https://cloud.google.com/billing/docs/reference/rest/v1/billingAccounts.projects",+ "columns": {+ "name": "The resource name for the project's billing information.",+ "projectId": "The Google Cloud project ID.",+ "billingAccountName": "The billing account that pays for this project.",+ "billingEnabled": "Whether the project has active billing.",+ "parent_billing_account": "The billing account used to list this project.",+ },+ },+ "sub_accounts": {+ "description": "Billing subaccounts under each accessible reseller account.",+ "docs_url": "https://cloud.google.com/billing/docs/reference/rest/v1/billingAccounts.subAccounts/list",+ "columns": {+ "name": "The billing subaccount resource name.",+ "displayName": "The billing subaccount name shown in Google Cloud.",+ "masterBillingAccount": "The parent billing account for this subaccount.",+ "parent_billing_account": "The billing account used to list this subaccount.",+ },+ },+ "services": {+ "description": "Google Cloud services in the public price catalog.",+ "docs_url": "https://cloud.google.com/billing/docs/reference/rest/v1/services",+ "columns": {+ "name": "The service resource name.",+ "serviceId": "The unique identifier for the service.",+ "displayName": "The service name shown in Google Cloud.",+ "businessEntityName": "The business entity that provides the service.",+ },+ },+ "skus": {+ "description": "Public SKUs and their latest prices in USD for each Google Cloud service.",+ "docs_url": "https://cloud.google.com/billing/docs/reference/rest/v1/services.skus",+ "columns": {+ "name": "The SKU resource name, including its service.",+ "skuId": "The unique identifier for the SKU.",+ "description": "The description of the billable resource.",+ "category": "The service and resource categories for the SKU.",+ "serviceRegions": "The regions where the SKU is available.",+ "pricingInfo": "The pricing expressions and their effective times.",+ "parent_service": "The service used to list this SKU.",+ },+ },+ "budgets": {+ "description": "Budget amounts, cost filters, thresholds, and notification settings for each accessible billing account.",+ "docs_url": "https://cloud.google.com/billing/docs/reference/budget/rest/v1/billingAccounts.budgets",+ "columns": {+ "name": "The budget resource name, including its billing account.",+ "displayName": "The budget name shown in Google Cloud.",+ "amount": "The configured budget amount.",+ "budgetFilter": "The cost filters that define which usage the budget tracks.",+ "thresholdRules": "The thresholds that trigger budget alerts.",+ "allUpdatesRule": "The notification settings for budget updates.",+ "parent_billing_account": "The billing account used to list this budget.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gcp_cloud_billing/gcp_cloud_billing.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gcp_cloud_billing/gcp_cloud_billing.pynew file mode 100644index 000000000000..4fd7ee2e63f8--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gcp_cloud_billing/gcp_cloud_billing.py@@ -0,0 +1,206 @@+from collections.abc import Mapping+from typing import Any++from google.auth.exceptions import RefreshError, TransportError+from google.auth.transport import Response as GoogleResponse+from google.auth.transport.requests import Request as GoogleRequest+from google.oauth2 import service_account+from requests import PreparedRequest++from posthog.dataclasses import frozen++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.rest_source import (+ RESTAPIConfig,+ rest_api_resource,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.auth import AuthConfigBase+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (+ build_dependent_resource,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import ClientConfig+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 schema_for_resource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.gcp_cloud_billing.settings import (+ CLOUD_BILLING_URL,+ ENDPOINTS,+ SCOPES,+ TOKEN_URL,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.gcpcloudbilling import (+ GcpCloudBillingKeyFileConfig,+)+++class GcpCloudBillingCredentialsError(ValueError):+ pass+++class BillingTokenRequest(GoogleRequest):+ def __call__(+ self,+ url: str,+ method: str = "GET",+ body: bytes | None = None,+ headers: Mapping[str, str] | None = None,+ timeout: float = 30,+ **kwargs: Any,+ ) -> GoogleResponse:+ response = super().__call__(url, method=method, body=body, headers=headers, timeout=30, allow_redirects=False)+ # The tracked transport already retries these statuses. Stop google-auth from retrying them again.+ if response.status == 429 or response.status >= 500:+ raise TransportError(f"Google token exchange failed with HTTP {response.status}")+ if 300 <= response.status < 400:+ raise GcpCloudBillingCredentialsError(+ "Google token exchange refused a redirect. Replace the service account key."+ )+ return response+++class BillingServiceAccountAuth(AuthConfigBase):+ def __init__(self, key_file: GcpCloudBillingKeyFileConfig) -> None:+ try:+ if not key_file.client_email or not key_file.private_key:+ raise ValueError("Expected a service account email and private key")+ # Pin the token host because uploaded keys can contain a customer-controlled token_uri.+ key = {+ "client_email": key_file.client_email,+ "private_key": key_file.private_key,+ "private_key_id": key_file.private_key_id,+ "token_uri": TOKEN_URL,+ }+ self.credentials = service_account.Credentials.from_service_account_info(key, scopes=SCOPES)+ except (ValueError, TypeError, KeyError) as error:+ raise GcpCloudBillingCredentialsError(+ "Invalid GCP service account key. Upload a valid JSON key file."+ ) from error+ self._private_key = key_file.private_key+ self._request = BillingTokenRequest(session=make_tracked_session(capture=False))++ def __call__(self, request: PreparedRequest) -> PreparedRequest:+ try:+ self.credentials.before_request(self._request, request.method, request.url, request.headers)+ except RefreshError as error:+ if error.retryable:+ raise+ raise GcpCloudBillingCredentialsError(+ "Google rejected the service account key. Replace the key and reconnect."+ ) from error+ return request++ def secret_values(self) -> tuple[str, ...]:+ return tuple(value for value in (self._private_key, self.credentials.token) if value)+++@frozen+class GcpCloudBillingResumeConfig:+ paginator_state: dict[str, Any] | None = None+++def probe_credentials(key_file: GcpCloudBillingKeyFileConfig, schema_name: str | None) -> None:+ endpoint = schema_for_resource(ENDPOINTS, schema_name or "billing_accounts")+ auth = BillingServiceAccountAuth(key_file)+ with make_tracked_session(redact_values=auth.secret_values()) as session:+ path = endpoint.path+ if endpoint.fanout:+ parent = ENDPOINTS[endpoint.fanout.parent_name]+ response = session.get(+ f"{CLOUD_BILLING_URL}{parent.path}",+ params={"pageSize": 1},+ auth=auth,+ timeout=(10, 30),+ allow_redirects=False,+ )+ response.raise_for_status()+ parents = response.json().get(parent.data_selector, [])+ if not parents:+ return+ path = path.format(parent=parents[0]["name"])+ url = path if path.startswith("https://") else f"{CLOUD_BILLING_URL}{path}"+ response = session.get(url, params={"pageSize": 1}, auth=auth, timeout=(10, 30), allow_redirects=False)+ response.raise_for_status()+++def gcp_cloud_billing_source(+ key_file: GcpCloudBillingKeyFileConfig,+ endpoint_name: str,+ team_id: int,+ job_id: str,+ api_version: str,+ resumable_source_manager: ResumableSourceManager[GcpCloudBillingResumeConfig],+) -> SourceResponse:+ endpoint = schema_for_resource(ENDPOINTS, endpoint_name)+ if api_version != "v1":+ raise ValueError(f"Unsupported Cloud Billing API version: {api_version}")+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None++ def save_state(state: dict[str, Any] | None) -> None:+ if state is not None:+ resumable_source_manager.save_state(GcpCloudBillingResumeConfig(paginator_state=state))++ client: ClientConfig = {+ "base_url": CLOUD_BILLING_URL,+ "auth": BillingServiceAccountAuth(key_file),+ "paginator": {+ "type": "cursor",+ "cursor_path": "nextPageToken",+ "cursor_param": "pageToken",+ "raise_on_repeated_cursor": True,+ },+ "allowed_hosts": ["cloudbilling.googleapis.com", "billingbudgets.googleapis.com"],+ "allow_redirects": False,+ "request_timeout": (10, 30),+ }+ initial_state = resume.paginator_state if resume else None+ if endpoint.fanout:+ parent = ENDPOINTS[endpoint.fanout.parent_name]+ resource = build_dependent_resource(+ endpoint_configs=ENDPOINTS,+ child_endpoint=endpoint_name,+ fanout=endpoint.fanout,+ client_config=client,+ path_format_values={},+ team_id=team_id,+ job_id=job_id,+ db_incremental_field_last_value=None,+ page_size_param="pageSize",+ parent_endpoint_extra={"data_selector": parent.data_selector},+ child_endpoint_extra={"data_selector": endpoint.data_selector},+ resume_hook=save_state,+ initial_paginator_state=initial_state,+ )+ else:+ config: RESTAPIConfig = {+ "client": client,+ "resources": [+ {+ "name": endpoint_name,+ "table_name": endpoint_name,+ "write_disposition": "replace",+ "table_format": "delta",+ "endpoint": {+ "path": endpoint.path,+ "data_selector": endpoint.data_selector,+ "params": {"pageSize": endpoint.page_size},+ },+ }+ ],+ }+ resource = rest_api_resource(+ config,+ team_id=team_id,+ job_id=job_id,+ db_incremental_field_last_value=None,+ resume_hook=save_state,+ initial_paginator_state=initial_state,+ )+ return SourceResponse(+ name=endpoint_name,+ items=lambda: resource,+ primary_keys=list(endpoint.primary_keys),+ partition_keys=list(endpoint.partition_keys),+ partition_mode=endpoint.partition_mode,+ partition_count=endpoint.partition_count,+ sort_mode=None,+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gcp_cloud_billing/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gcp_cloud_billing/settings.pynew file mode 100644index 000000000000..58ded18ab97a--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gcp_cloud_billing/settings.py@@ -0,0 +1,90 @@+from dataclasses import field++from posthog.dataclasses import frozen++from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (+ DependentEndpointConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import PartitionMode+from products.warehouse_sources.backend.types import IncrementalField++CLOUD_BILLING_URL = "https://cloudbilling.googleapis.com/"+BUDGETS_URL = "https://billingbudgets.googleapis.com/"+TOKEN_URL = "https://oauth2.googleapis.com/token"+SCOPES = ("https://www.googleapis.com/auth/cloud-billing",)+++@frozen+class BillingEndpoint:+ name: str+ path: str+ data_selector: str+ page_size: int = 100+ primary_keys: tuple[str, ...] = ("name",)+ partition_keys: tuple[str, ...] = ("name",)+ partition_mode: PartitionMode = "md5"+ partition_count: int = 16+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ default_incremental_field: str | None = None+ fanout: DependentEndpointConfig | None = None+++ENDPOINTS = {+ "billing_accounts": BillingEndpoint(+ name="billing_accounts", path="v1/billingAccounts", data_selector="billingAccounts"+ ),+ "projects": BillingEndpoint(+ name="projects",+ path="v1/{parent}/projects",+ data_selector="projectBillingInfo",+ fanout=DependentEndpointConfig(+ parent_name="billing_accounts",+ resolve_param="parent",+ resolve_field="name",+ include_from_parent=["name"],+ parent_field_renames={"name": "parent_billing_account"},+ ),+ ),+ "sub_accounts": BillingEndpoint(+ name="sub_accounts",+ path="v1/{parent}/subAccounts",+ data_selector="billingAccounts",+ fanout=DependentEndpointConfig(+ parent_name="billing_accounts",+ resolve_param="parent",+ resolve_field="name",+ include_from_parent=["name"],+ parent_field_renames={"name": "parent_billing_account"},+ ),+ ),+ "services": BillingEndpoint(name="services", path="v1/services", data_selector="services", page_size=1000),+ "skus": BillingEndpoint(+ name="skus",+ path="v1/{parent}/skus",+ data_selector="skus",+ page_size=1000,+ fanout=DependentEndpointConfig(+ parent_name="services",+ resolve_param="parent",+ resolve_field="name",+ include_from_parent=["name"],+ parent_field_renames={"name": "parent_service"},+ ),+ ),+ "budgets": BillingEndpoint(+ name="budgets",+ path=f"{BUDGETS_URL}v1/{{parent}}/budgets",+ data_selector="budgets",+ fanout=DependentEndpointConfig(+ parent_name="billing_accounts",+ resolve_param="parent",+ resolve_field="name",+ include_from_parent=["name"],+ parent_field_renames={"name": "parent_billing_account"},+ ),+ ),+}++# SKU pricing windows must stay within one calendar month, so they cannot track general updates.+# These request shapes follow Google's discovery specifications and need verification with a live account.+INCREMENTAL_FIELDS = {name: endpoint.incremental_fields for name, endpoint in ENDPOINTS.items()}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gcp_cloud_billing/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gcp_cloud_billing/source.pyindex 867f774eaf30..7d782123fcdc 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/gcp_cloud_billing/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gcp_cloud_billing/source.py@@ -1,8 +1,38 @@from typing import cast-from products.warehouse_sources.backend.facade.source_config import DataWarehouseSourceCategory, SourceConfig-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from requests import HTTPError++from products.warehouse_sources.backend.facade.source_config import (+ DataWarehouseSourceCategory,+ ReleaseStatus,+ SourceConfig,+ SourceFieldFileUploadConfig,+ SourceFieldFileUploadJsonFormatConfig,+)+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,+ build_endpoint_schemas,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.gcp_cloud_billing.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.gcp_cloud_billing.gcp_cloud_billing import (+ GcpCloudBillingCredentialsError,+ GcpCloudBillingResumeConfig,+ gcp_cloud_billing_source,+ probe_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.gcp_cloud_billing.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+)from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.gcpcloudbilling import (GcpCloudBillingSourceConfig,)@@ -10,7 +40,12 @@ from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class GcpCloudBillingSource(SimpleSource[GcpCloudBillingSourceConfig]):+class GcpCloudBillingSource(ResumableSource[GcpCloudBillingSourceConfig, GcpCloudBillingResumeConfig]):+ lists_tables_without_credentials = True+ supported_versions = ("v1",)+ default_version = "v1"+ api_docs_url = "https://cloud.google.com/billing/docs/reference/rest"+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.GCPCLOUDBILLING@@ -22,6 +57,93 @@ class GcpCloudBillingSource(SimpleSource[GcpCloudBillingSourceConfig]):category=DataWarehouseSourceCategory.FINANCE___ACCOUNTING,label="Google Cloud Platform (Cloud Billing)",iconPath="/static/services/gcp_cloud_billing.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/gcp-cloud-billing",+ releaseStatus=ReleaseStatus.ALPHA,+ keywords=["gcp", "google cloud"],+ caption=(+ "Import billing accounts, project links, budgets, and the public price catalog. "+ "Detailed spend requires a separate BigQuery billing export. "+ "Enable the Cloud Billing API and Cloud Billing Budget API. "+ "Grant billing.accounts.list, billing.resourceAssociations.list, and billing.budgets.list on the accounts to sync."+ ),+ fields=cast(+ list[FieldType],+ [+ SourceFieldFileUploadConfig(+ name="key_file",+ label="Service account JSON key file",+ fileFormat=SourceFieldFileUploadJsonFormatConfig(+ format=".json",+ keys=["client_email", "private_key", "private_key_id", "token_uri"],+ ),+ required=True,+ ),+ ],+ ),+ )++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error": "Google rejected the credentials. Replace the service account key and reconnect.",+ "403 Client Error": "Google denied access. Enable the billing APIs and grant the required billing permissions.",+ "Invalid GCP service account key": "Upload a valid service account JSON key file.",+ "Google rejected the service account key": "Replace the service account key and reconnect.",+ "Google token exchange refused a redirect": "Replace the service account key and reconnect.",+ }++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ return CANONICAL_DESCRIPTIONS++ def validate_credentials(+ self,+ config: GcpCloudBillingSourceConfig,+ team_id: int,+ schema_name: str | None = None,+ api_version: str | None = None,+ ) -> tuple[bool, str | None]:+ try:+ probe_credentials(config.key_file, schema_name)+ except GcpCloudBillingCredentialsError as error:+ return False, str(error)+ except HTTPError as error:+ status = error.response.status_code if error.response is not None else None+ if status == 403 and schema_name is None:+ return True, None+ if status in (401, 403):+ return False, self.get_non_retryable_errors()[f"{status} Client Error"]+ raise+ return True, None++ def get_schemas(+ self,+ config: GcpCloudBillingSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ api_version: str | None = None,+ ) -> list[SourceSchema]:+ return build_endpoint_schemas(+ ENDPOINTS,+ INCREMENTAL_FIELDS,+ names,+ descriptions={name: entry["description"] for name, entry in CANONICAL_DESCRIPTIONS.items()},+ )++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[GcpCloudBillingResumeConfig]:+ return ResumableSourceManager(inputs, GcpCloudBillingResumeConfig)++ def source_for_pipeline(+ self,+ config: GcpCloudBillingSourceConfig,+ resumable_source_manager: ResumableSourceManager[GcpCloudBillingResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return gcp_cloud_billing_source(+ key_file=config.key_file,+ endpoint_name=inputs.schema_name,+ team_id=inputs.team_id,+ job_id=inputs.job_id,+ api_version=self.resolve_api_version(inputs.api_version),+ resumable_source_manager=resumable_source_manager,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gcp_cloud_billing/tests/conftest.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gcp_cloud_billing/tests/conftest.pynew file mode 100644index 000000000000..604dc74acee7--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gcp_cloud_billing/tests/conftest.py@@ -0,0 +1,23 @@+import pytest++from cryptography.hazmat.primitives import serialization+from cryptography.hazmat.primitives.asymmetric import rsa++from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.gcpcloudbilling import (+ GcpCloudBillingKeyFileConfig,+)++[email protected](scope="session")+def key_file() -> GcpCloudBillingKeyFileConfig:+ private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048)+ return GcpCloudBillingKeyFileConfig(+ client_email="[email protected]",+ private_key_id="fake-key-id",+ private_key=private_key.private_bytes(+ serialization.Encoding.PEM,+ serialization.PrivateFormat.PKCS8,+ serialization.NoEncryption(),+ ).decode(),+ token_uri="https://example.com/untrusted-token-endpoint",+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gcp_cloud_billing/tests/test_gcp_cloud_billing.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gcp_cloud_billing/tests/test_gcp_cloud_billing.pynew file mode 100644index 000000000000..d61a2b5cd515--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gcp_cloud_billing/tests/test_gcp_cloud_billing.py@@ -0,0 +1,186 @@+from datetime import UTC, datetime, timedelta++import pytest++from requests import Request++from products.warehouse_sources.backend.temporal.data_imports.sources.common.testing import (+ ScriptedResponse,+ SourceDriver,+ scripted_network,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.gcp_cloud_billing.gcp_cloud_billing import (+ BillingServiceAccountAuth,+ GcpCloudBillingResumeConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.gcp_cloud_billing.source import (+ GcpCloudBillingSource,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.gcpcloudbilling import (+ GcpCloudBillingKeyFileConfig,+ GcpCloudBillingSourceConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.tests.contract_harness import (+ check_extraction,+ start_source,+)+++def token_response(token: str = "fake-access-token") -> ScriptedResponse:+ return ScriptedResponse(json={"access_token": token, "expires_in": 3600, "token_type": "Bearer"})+++def test_signed_extraction_meets_worker_contract(key_file: GcpCloudBillingKeyFileConfig) -> None:+ source = GcpCloudBillingSource()+ config = GcpCloudBillingSourceConfig(key_file=key_file)+ verdict = check_extraction(+ start_source(source, config), [schema.name for schema in source.get_schemas(config, team_id=1)]+ )+ assert verdict.failed == frozenset()+ assert verdict.requests > 0+ assert verdict.safe_point_exercised+++ ("schema", "selector", "path"),+ [("billing_accounts", "billingAccounts", "/v1/billingAccounts"), ("services", "services", "/v1/services")],+)+def test_top_level_pagination_and_committed_resume(+ key_file: GcpCloudBillingKeyFileConfig, schema: str, selector: str, path: str+) -> None:+ result = SourceDriver(GcpCloudBillingSource(), GcpCloudBillingSourceConfig(key_file=key_file)).run(+ schema,+ [+ token_response(),+ ScriptedResponse(json={selector: [{"name": "first"}], "nextPageToken": "next-page"}),+ ScriptedResponse(json={"nextPageToken": "after-empty-page"}),+ ScriptedResponse(json={selector: [{"name": "last"}]}),+ ],+ )+ assert result.raised is None+ assert result.rows == [{"name": "first"}, {"name": "last"}]+ assert result.paths == ["/token", path, path, path]+ assert result.params("pageToken") == [None, None, "next-page", "after-empty-page"]+ assert result.committed_states == [+ GcpCloudBillingResumeConfig(paginator_state={"cursor": "next-page"}),+ GcpCloudBillingResumeConfig(paginator_state={"cursor": "after-empty-page"}),+ ]+ assert result.requests[0].url == "https://oauth2.googleapis.com/token"+ assert all(request.headers.get("authorization") == "Bearer fake-access-token" for request in result.requests[1:])+++ ("schema", "parent_selector", "parent", "selector", "child_path", "parent_field", "child_host"),+ [+ (+ "projects",+ "billingAccounts",+ "billingAccounts",+ "projectBillingInfo",+ "projects",+ "parent_billing_account",+ "cloudbilling.googleapis.com",+ ),+ (+ "sub_accounts",+ "billingAccounts",+ "billingAccounts",+ "billingAccounts",+ "subAccounts",+ "parent_billing_account",+ "cloudbilling.googleapis.com",+ ),+ (+ "budgets",+ "billingAccounts",+ "billingAccounts",+ "budgets",+ "budgets",+ "parent_billing_account",+ "billingbudgets.googleapis.com",+ ),+ ("skus", "services", "services", "skus", "skus", "parent_service", "cloudbilling.googleapis.com"),+ ],+)+def test_fanout_paginates_parents_and_children(+ key_file: GcpCloudBillingKeyFileConfig,+ schema: str,+ parent_selector: str,+ parent: str,+ selector: str,+ child_path: str,+ parent_field: str,+ child_host: str,+) -> None:+ first_parent = f"{parent}/parent-a"+ second_parent = f"{parent}/parent-b"+ child = f"/v1/{first_parent}/{child_path}"+ result = SourceDriver(GcpCloudBillingSource(), GcpCloudBillingSourceConfig(key_file=key_file)).run(+ schema,+ [+ token_response(),+ ScriptedResponse(json={parent_selector: [{"name": first_parent}], "nextPageToken": "parent-next"}),+ ScriptedResponse(+ json={selector: [{"name": "child-a", "nested": {"amount": 2}}], "nextPageToken": "child-next"}+ ),+ ScriptedResponse(json={selector: [{"name": "child-b", "nested": None}]}),+ ScriptedResponse(json={parent_selector: [{"name": second_parent}]}),+ ScriptedResponse(json={}),+ ],+ )+ assert result.raised is None+ assert result.paths == [+ "/token",+ f"/v1/{parent}",+ child,+ child,+ f"/v1/{parent}",+ f"/v1/{second_parent}/{child_path}",+ ]+ assert result.params("pageToken") == [None, None, None, "child-next", "parent-next", None]+ assert result.rows == [+ {"name": "child-a", "nested": {"amount": 2}, parent_field: first_parent},+ {"name": "child-b", "nested": None, parent_field: first_parent},+ ]+ assert result.requests[2].url.startswith(f"https://{child_host}/")+ assert result.committed_states[0].paginator_state == {+ "completed": [],+ "current": child.lstrip("/") if schema != "budgets" else f"https://{child_host}{child}",+ "child_state": {"cursor": "child-next"},+ }++[email protected]("fanout", [False, True])+def test_resume_starts_after_saved_page(key_file: GcpCloudBillingKeyFileConfig, fanout: bool) -> None:+ state = (+ {+ "completed": ["v1/services/done/skus"],+ "current": "v1/services/current/skus",+ "child_state": {"cursor": "saved-page"},+ }+ if fanout+ else {"cursor": "saved-page"}+ )+ pages = [token_response()]+ if fanout:+ pages.append(ScriptedResponse(json={"services": [{"name": "services/done"}, {"name": "services/current"}]}))+ pages.append(ScriptedResponse(json={"skus" if fanout else "services": [{"name": "last"}]}))+ result = SourceDriver(GcpCloudBillingSource(), GcpCloudBillingSourceConfig(key_file=key_file)).run(+ "skus" if fanout else "services", pages, resume_state=GcpCloudBillingResumeConfig(paginator_state=state)+ )+ assert result.raised is None+ assert result.params("pageToken")[-1] == "saved-page"+ assert len(result.rows) == 1+ assert "/v1/services/done/skus" not in result.paths+++def test_auth_refreshes_expired_token_without_retargeting_key(key_file: GcpCloudBillingKeyFileConfig) -> None:+ with scripted_network([token_response("first-token"), token_response("second-token")]) as network:+ auth = BillingServiceAccountAuth(key_file)+ first = auth(Request("GET", "https://cloudbilling.googleapis.com/v1/services").prepare())+ auth.credentials.expiry = datetime.now(UTC).replace(tzinfo=None) - timedelta(seconds=1)+ second = auth(Request("GET", "https://cloudbilling.googleapis.com/v1/services").prepare())+ assert first.headers["Authorization"] == "Bearer first-token"+ assert second.headers["Authorization"] == "Bearer second-token"+ assert [request.url for request in network.requests_log] == ["https://oauth2.googleapis.com/token"] * 2+ assert any(options.get("capture") is False for options in network.session_options)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gcp_cloud_billing/tests/test_gcp_cloud_billing_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gcp_cloud_billing/tests/test_gcp_cloud_billing_source.pynew file mode 100644index 000000000000..5b7f203c849f--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gcp_cloud_billing/tests/test_gcp_cloud_billing_source.py@@ -0,0 +1,98 @@+import pytest++from google.auth.exceptions import TransportError++from products.warehouse_sources.backend.temporal.data_imports.sources.common.testing import (+ ScriptedResponse,+ scripted_network,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.gcp_cloud_billing.source import (+ GcpCloudBillingSource,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.gcpcloudbilling import (+ GcpCloudBillingKeyFileConfig,+ GcpCloudBillingSourceConfig,+)+++ ("status", "schema", "valid"),+ [(200, None, True), (401, None, False), (403, None, True), (401, "services", False), (403, "services", False)],+)+def test_credentials_distinguish_invalid_key_from_missing_scope(+ key_file: GcpCloudBillingKeyFileConfig, status: int, schema: str | None, valid: bool+) -> None:+ with scripted_network(+ [+ ScriptedResponse(json={"access_token": "fake-token", "expires_in": 3600}),+ ScriptedResponse(+ status=status, json={"error": {"code": status, "status": "PERMISSION_DENIED"}} if status != 200 else {}+ ),+ ]+ ):+ success, message = GcpCloudBillingSource().validate_credentials(+ GcpCloudBillingSourceConfig(key_file=key_file), team_id=1, schema_name=schema+ )+ assert success is valid+ assert (message is None) is valid+++ "client_email,private_key",+ [+ ("", "-----BEGIN PRIVATE KEY-----"),+ ("[email protected]", ""),+ ("[email protected]", "not-a-pem-key"),+ ],+)+def test_malformed_keys_fail_without_network(client_email: str, private_key: str) -> None:+ key = GcpCloudBillingKeyFileConfig(+ client_email=client_email, private_key=private_key, private_key_id="fake-key-id", token_uri=""+ )+ with scripted_network([]):+ valid, message = GcpCloudBillingSource().validate_credentials(+ GcpCloudBillingSourceConfig(key_file=key), team_id=1+ )+ assert valid is False+ assert message == "Invalid GCP service account key. Upload a valid JSON key file."++[email protected]("empty_parents", [False, True])+def test_child_permission_probe_uses_account_and_budget_host(+ key_file: GcpCloudBillingKeyFileConfig, empty_parents: bool+) -> None:+ script = [+ ScriptedResponse(json={"access_token": "fake-token", "expires_in": 3600}),+ ScriptedResponse(json={} if empty_parents else {"billingAccounts": [{"name": "billingAccounts/fake-account"}]}),+ ]+ if not empty_parents:+ script.append(ScriptedResponse(status=403, json={"error": {"code": 403, "status": "PERMISSION_DENIED"}}))+ with scripted_network(script) as network:+ valid, _ = GcpCloudBillingSource().validate_credentials(+ GcpCloudBillingSourceConfig(key_file=key_file), team_id=1, schema_name="budgets"+ )+ assert valid is empty_parents+ if not empty_parents:+ assert (+ network.requests_log[-1].url+ == "https://billingbudgets.googleapis.com/v1/billingAccounts/fake-account/budgets?pageSize=1"+ )+++def test_revoked_key_returns_safe_message(key_file: GcpCloudBillingKeyFileConfig) -> None:+ with scripted_network(+ [ScriptedResponse(status=400, json={"error": "invalid_grant", "error_description": "Invalid JWT Signature."})]+ ):+ valid, message = GcpCloudBillingSource().validate_credentials(+ GcpCloudBillingSourceConfig(key_file=key_file), team_id=1+ )+ assert valid is False+ assert message == "Google rejected the service account key. Replace the key and reconnect."+++def test_transient_token_failure_propagates(key_file: GcpCloudBillingKeyFileConfig) -> None:+ with (+ scripted_network([ScriptedResponse(status=503, json={"error": "temporarily_unavailable"})] * 20),+ pytest.raises(TransportError),+ ):+ GcpCloudBillingSource().validate_credentials(GcpCloudBillingSourceConfig(key_file=key_file), team_id=1)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/gcpcloudbilling.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/gcpcloudbilling.pyindex ab9d29e11785..d0ca4f7f32bd 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/gcpcloudbilling.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/gcpcloudbilling.py@@ -4,6 +4,14 @@from products.warehouse_sources.backend.temporal.data_imports.sources.common import config+class GcpCloudBillingKeyFileConfig(config.Config):+ client_email: str+ private_key: str+ private_key_id: str+ token_uri: str++@config.configclass GcpCloudBillingSourceConfig(config.Config):- pass+ key_file: GcpCloudBillingKeyFileConfigdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/tests/source_contract_baseline.txt b/products/warehouse_sources/backend/temporal/data_imports/sources/tests/source_contract_baseline.txtindex 5124a1d05eb9..7e5ed6012a91 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/tests/source_contract_baseline.txt+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/tests/source_contract_baseline.txt@@ -297,6 +297,7 @@ GNews fail:rate-limit-budget,stall-budgetGainsightCs fail:rate-limit-budgetGainsightPx fail:safe-point,stall-budgetGcore fail:stall-budget+GcpCloudBilling not-checkable:no-requestGerrit fail:rate-limit-budget,stall-budgetGetdx fail:stall-budgetGiphy fail:stall-budget