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 coupa import source (#63013)

Tom Owers326dd59b9356
diff --git a/posthog/temporal/data_imports/sources/SOURCES.md b/posthog/temporal/data_imports/sources/SOURCES.md
index 72d332cbff5f..3ef59c0368bd 100644
--- a/posthog/temporal/data_imports/sources/SOURCES.md
+++ b/posthog/temporal/data_imports/sources/SOURCES.md
@@ -79,6 +79,7 @@ the row lists both.
| convertkit | HTTP | requests | ✅ |
| convex | HTTP | requests | ✅ |
| copper | HTTP | requests | ✅ |
+| coupa | HTTP | requests | ✅ |
| crunchbase | HTTP | requests | ✅ |
| culture_amp | HTTP | requests | ✅ |
| customer_io | HTTP + Webhook | requests + `WebhookSourceManager` | ✅ (App API) / ➖ (webhook) |
@@ -244,7 +245,6 @@ doesn't conflict with concurrent PRs.
- constant_contact
- copper
- cosmosdb
-- coupa
- criteo
- databricks
- db2
diff --git a/posthog/temporal/data_imports/sources/coupa/coupa.py b/posthog/temporal/data_imports/sources/coupa/coupa.py
new file mode 100644
index 000000000000..cdf155dd41d6
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/coupa/coupa.py
@@ -0,0 +1,217 @@
+import dataclasses
+from collections.abc import Iterator
+from datetime import UTC, date, datetime
+from typing import Any, Optional
+from urllib.parse import urlencode, urlparse
+
+import requests
+from structlog.types import FilteringBoundLogger
+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+
+from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
+from posthog.temporal.data_imports.sources.common.http import make_tracked_session
+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from posthog.temporal.data_imports.sources.coupa.settings import COUPA_ENDPOINTS, PAGE_SIZE
+
+REQUEST_TIMEOUT_SECONDS = 60
+# Instance-level limits are unpublished (~25 req/s commonly cited) and Coupa
+# sends no Retry-After header; back off on 429/503.
+MAX_RETRY_ATTEMPTS = 5
+
+
+class CoupaRetryableError(Exception):
+ pass
+
+
+class CoupaResumeConfig:
+ # Offset of the next unfetched page within the current sync.
+ next_offset: int
+
+
+def normalize_host(host: str) -> str:
+ """Normalize the instance URL and reject anything that isn't HTTPS.
+
+ Credentials travel as HTTP Basic auth, so plaintext http:// is rejected to
+ keep them off the wire in the clear. Bare hosts default to https.
+ """
+ host = host.strip()
+ if not host:
+ raise ValueError("Coupa instance URL is required")
+ if "://" not in host:
+ host = f"https://{host}"
+ host = host.rstrip("/")
+ parsed = urlparse(host)
+ if parsed.scheme != "https" or not parsed.hostname:
+ raise ValueError(f"Invalid Coupa instance URL (must be https): {host}")
+ return host
+
+
+def hostname_of(host: str) -> str:
+ return urlparse(normalize_host(host)).hostname or ""
+
+
+def _get_session(client_secret: str) -> requests.Session:
+ # No-redirect session is an SSRF boundary: a user-supplied instance_url must
+ # not be able to bounce token/API calls to an internal host via a 3xx.
+ return make_tracked_session(
+ redact_values=(client_secret,), headers={"Accept": "application/json"}, allow_redirects=False
+ )
+
+
+def _is_scope_error(response: requests.Response) -> bool:
+ try:
+ return response.json().get("error") == "invalid_scope"
+ except Exception:
+ return False
+
+
+def _mint_token(
+ session: requests.Session, instance_url: str, client_id: str, client_secret: str, scope: Optional[str]
+) -> str:
+ """Exchange client credentials for a bearer token (~24h lifetime).
+
+ Falls back to a scope-less request when the instance rejects the
+ endpoint-specific scope, in which case the token carries every scope the
+ admin granted the OIDC client.
+ """
+ data: dict[str, str] = {"grant_type": "client_credentials"}
+ if scope:
+ data["scope"] = scope
+
+ response = session.post(
+ f"{normalize_host(instance_url)}/oauth2/token",
+ data=data,
+ auth=(client_id, client_secret),
+ timeout=REQUEST_TIMEOUT_SECONDS,
+ )
+ if scope and response.status_code == 400 and _is_scope_error(response):
+ return _mint_token(session, instance_url, client_id, client_secret, None)
+ response.raise_for_status()
+ return response.json()["access_token"]
+
+
+def _format_timestamp(value: Any) -> str:
+ if isinstance(value, datetime):
+ dt = value if value.tzinfo else value.replace(tzinfo=UTC)
+ return dt.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%SZ")
+ if isinstance(value, date):
+ return value.strftime("%Y-%m-%dT00:00:00Z")
+ return str(value)
+
+
+def _normalize_keys(row: dict[str, Any]) -> dict[str, Any]:
+ # Coupa serializes keys with hyphens in some responses (e.g. updated-at);
+ # normalize the top level so the updated_at cursor is always present.
+ return {key.replace("-", "_"): value for key, value in row.items()}
+
+
+def validate_credentials(instance_url: str, client_id: str, client_secret: str) -> bool:
+ """Confirm the OIDC client credentials are valid by minting a token."""
+ try:
+ _mint_token(_get_session(client_secret), instance_url, client_id, client_secret, None)
+ return True
+ except Exception:
+ return False
+
+
+def get_rows(
+ instance_url: str,
+ client_id: str,
+ client_secret: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[CoupaResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+) -> Iterator[list[dict[str, Any]]]:
+ config = COUPA_ENDPOINTS[endpoint]
+ session = _get_session(client_secret)
+ base_url = normalize_host(instance_url)
+ token = _mint_token(session, instance_url, client_id, client_secret, config.scope)
+
+ @retry(
+ retry=retry_if_exception_type((CoupaRetryableError, requests.ReadTimeout, requests.ConnectionError)),
+ stop=stop_after_attempt(MAX_RETRY_ATTEMPTS),
+ wait=wait_exponential_jitter(initial=2, max=90),
+ reraise=True,
+ )
+ def fetch(url: str) -> Any:
+ nonlocal token
+ response = session.get(url, headers={"Authorization": f"Bearer {token}"}, timeout=REQUEST_TIMEOUT_SECONDS)
+
+ # Tokens last ~24h; re-mint once if one expires mid-sync.
+ if response.status_code == 401:
+ token = _mint_token(session, instance_url, client_id, client_secret, config.scope)
+ response = session.get(url, headers={"Authorization": f"Bearer {token}"}, timeout=REQUEST_TIMEOUT_SECONDS)
+
+ if response.status_code in (429, 503) or response.status_code >= 500:
+ raise CoupaRetryableError(f"Coupa API error (retryable): status={response.status_code}, url={url}")
+
+ # The session never follows redirects (SSRF boundary); a 3xx means the
+ # instance is pointing us elsewhere, so treat it as a hard upstream error.
+ if 300 <= response.status_code < 400:
+ raise ValueError(f"Coupa API returned an unexpected redirect: status={response.status_code}, url={url}")
+
+ if not response.ok:
+ logger.error("Coupa API error", status=response.status_code, body=response.text[:500], url=url)
+ response.raise_for_status()
+
+ return response.json()
+
+ params: dict[str, Any] = {"limit": PAGE_SIZE}
+ if should_use_incremental_field and db_incremental_field_last_value is not None:
+ params["updated_at[gt]"] = _format_timestamp(db_incremental_field_last_value)
+
+ resume_config = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ offset = resume_config.next_offset if resume_config is not None else 0
+ if resume_config is not None:
+ logger.debug("Coupa: resuming from offset", endpoint=endpoint, offset=offset)
+
+ while True:
+ url = f"{base_url}/api{config.path}?{urlencode({**params, 'offset': offset})}"
+ body = fetch(url)
+ rows = [_normalize_keys(row) for row in body if isinstance(row, dict)] if isinstance(body, list) else []
+
+ if rows:
+ yield rows
+
+ # Coupa hard-caps pages at 50; a short page means we're done.
+ if len(rows) < PAGE_SIZE:
+ return
+
+ offset += len(rows)
+ # Save state AFTER yielding so a crash re-yields the in-flight page
+ # (merge dedupes on primary key).
+ resumable_source_manager.save_state(CoupaResumeConfig(next_offset=offset))
+
+
+def coupa_source(
+ instance_url: str,
+ client_id: str,
+ client_secret: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[CoupaResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+) -> SourceResponse:
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ instance_url=instance_url,
+ client_id=client_id,
+ client_secret=client_secret,
+ endpoint=endpoint,
+ logger=logger,
+ resumable_source_manager=resumable_source_manager,
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ ),
+ primary_keys=["id"],
+ partition_count=1,
+ partition_size=1,
+ # Result ordering within an updated_at[gt] window is undocumented, so
+ # the pipeline defers incremental watermark commits until a run completes.
+ sort_mode="desc",
+ )
diff --git a/posthog/temporal/data_imports/sources/coupa/settings.py b/posthog/temporal/data_imports/sources/coupa/settings.py
new file mode 100644
index 000000000000..291aa6aa926e
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/coupa/settings.py
@@ -0,0 +1,79 @@
+from dataclasses import dataclass, field
+
+from products.data_warehouse.backend.types import IncrementalField, IncrementalFieldType
+
+# Coupa hard-caps GET responses at 50 records per page.
+PAGE_SIZE = 50
+
+_UPDATED_AT_INCREMENTAL_FIELDS: list[IncrementalField] = [
+ {
+ "label": "updated_at",
+ "type": IncrementalFieldType.DateTime,
+ "field": "updated_at",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+]
+
+
+@dataclass
+class CoupaEndpointConfig:
+ name: str
+ # Path under {instance}/api.
+ path: str
+ # OAuth scope minted for this endpoint only, so OIDC clients granted a
+ # subset of per-object scopes can still sync the streams they cover.
+ scope: str
+ incremental_fields: list[IncrementalField] = field(default_factory=lambda: list(_UPDATED_AT_INCREMENTAL_FIELDS))
+
+
+# Every stream filters server-side on updated_at[gt] (bracket-notation
+# filters), so they're all honestly incremental. Tables documented as having
+# unreliable updated_at bumps (e.g. budget_lines) are deliberately excluded.
+COUPA_ENDPOINTS: dict[str, CoupaEndpointConfig] = {
+ "invoices": CoupaEndpointConfig(
+ name="invoices",
+ path="/invoices",
+ scope="core.invoice.read",
+ ),
+ "purchase_orders": CoupaEndpointConfig(
+ name="purchase_orders",
+ path="/purchase_orders",
+ scope="core.purchase_order.read",
+ ),
+ "requisitions": CoupaEndpointConfig(
+ name="requisitions",
+ path="/requisitions",
+ scope="core.requisition.read",
+ ),
+ "suppliers": CoupaEndpointConfig(
+ name="suppliers",
+ path="/suppliers",
+ scope="core.supplier.read",
+ ),
+ "contracts": CoupaEndpointConfig(
+ name="contracts",
+ path="/contracts",
+ scope="core.contract.read",
+ ),
+ "expense_reports": CoupaEndpointConfig(
+ name="expense_reports",
+ path="/expense_reports",
+ scope="core.expense.read",
+ ),
+ "users": CoupaEndpointConfig(
+ name="users",
+ path="/users",
+ scope="core.user.read",
+ ),
+ "approvals": CoupaEndpointConfig(
+ name="approvals",
+ path="/approvals",
+ scope="core.approval.read",
+ ),
+}
+
+ENDPOINTS = tuple(COUPA_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in COUPA_ENDPOINTS.items() if config.incremental_fields
+}
diff --git a/posthog/temporal/data_imports/sources/coupa/source.py b/posthog/temporal/data_imports/sources/coupa/source.py
index 763da7a116ac..e290b02647aa 100644
--- a/posthog/temporal/data_imports/sources/coupa/source.py
+++ b/posthog/temporal/data_imports/sources/coupa/source.py
@@ -1,29 +1,152 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
)
-from posthog.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceInputs, SourceResponse
+from posthog.temporal.data_imports.sources.common.base import FieldType, ResumableSource
+from posthog.temporal.data_imports.sources.common.mixins import ValidateDatabaseHostMixin
from posthog.temporal.data_imports.sources.common.registry import SourceRegistry
+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from posthog.temporal.data_imports.sources.common.schema import SourceSchema
+from posthog.temporal.data_imports.sources.coupa.coupa import (
+ CoupaResumeConfig,
+ coupa_source,
+ hostname_of,
+ validate_credentials as validate_coupa_credentials,
+)
+from posthog.temporal.data_imports.sources.coupa.settings import ENDPOINTS, INCREMENTAL_FIELDS
from posthog.temporal.data_imports.sources.generated_configs import CoupaSourceConfig
from products.data_warehouse.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class CoupaSource(SimpleSource[CoupaSourceConfig]):
+class CoupaSource(ResumableSource[CoupaSourceConfig, CoupaResumeConfig], ValidateDatabaseHostMixin):
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.COUPA
+ @property
+ def connection_host_fields(self) -> list[str]:
+ # The instance URL decides where the stored credentials are sent;
+ # retargeting it must re-require the secret.
+ return ["instance_url"]
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "400 Client Error: Bad Request for url": "Coupa rejected the token request. Please check your client ID, client secret, and that the OIDC client has the required scopes.",
+ "403 Client Error: Forbidden for url": "Coupa denied access. Please check that the OIDC client has the read scope for this dataset (e.g. core.invoice.read).",
+ }
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=SchemaExternalDataSourceType.COUPA,
label="Coupa",
+ caption="""Connect your Coupa instance to pull your spend management data into the PostHog Data warehouse.
+
+A Coupa admin can create an OIDC client under Setup > Integrations > OAuth2/OpenID Connect Clients with the client credentials grant. Grant it the read scopes for the objects you want to sync (e.g. `core.invoice.read`, `core.purchase_order.read`). The instance URL is your Coupa host, e.g. `https://myorg.coupahost.com`.""",
iconPath="/static/services/coupa.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/coupa",
+ releaseStatus=ReleaseStatus.ALPHA,
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="instance_url",
+ label="Instance URL",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="https://myorg.coupahost.com",
+ secret=False,
+ ),
+ SourceFieldInputConfig(
+ name="client_id",
+ label="Client ID",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="",
+ secret=False,
+ ),
+ SourceFieldInputConfig(
+ name="client_secret",
+ label="Client secret",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
+ )
+
+ def get_schemas(
+ self,
+ config: CoupaSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ schemas = [
+ SourceSchema(
+ name=endpoint,
+ supports_incremental=INCREMENTAL_FIELDS.get(endpoint) is not None,
+ supports_append=INCREMENTAL_FIELDS.get(endpoint) is not None,
+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),
+ )
+ for endpoint in ENDPOINTS
+ ]
+
+ if names is not None:
+ names_set = set(names)
+ schemas = [s for s in schemas if s.name in names_set]
+
+ return schemas
+
+ def validate_credentials(
+ self, config: CoupaSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ try:
+ host_valid, host_error = self.is_database_host_valid(hostname_of(config.instance_url), team_id)
+ except ValueError:
+ return False, "Invalid Coupa instance URL"
+ if not host_valid:
+ return False, host_error
+
+ if validate_coupa_credentials(config.instance_url, config.client_id, config.client_secret):
+ return True, None
+
+ return False, "Invalid Coupa credentials. Check the instance URL, client ID, and client secret."
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[CoupaResumeConfig]:
+ return ResumableSourceManager[CoupaResumeConfig](inputs, CoupaResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: CoupaSourceConfig,
+ resumable_source_manager: ResumableSourceManager[CoupaResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ host_valid, host_error = self.is_database_host_valid(hostname_of(config.instance_url), inputs.team_id)
+ if not host_valid:
+ raise ValueError(host_error or "Invalid Coupa host")
+
+ return coupa_source(
+ instance_url=config.instance_url,
+ client_id=config.client_id,
+ client_secret=config.client_secret,
+ endpoint=inputs.schema_name,
+ logger=inputs.logger,
+ resumable_source_manager=resumable_source_manager,
+ should_use_incremental_field=inputs.should_use_incremental_field,
+ db_incremental_field_last_value=inputs.db_incremental_field_last_value
+ if inputs.should_use_incremental_field
+ else None,
)
diff --git a/posthog/temporal/data_imports/sources/coupa/tests/test_coupa.py b/posthog/temporal/data_imports/sources/coupa/tests/test_coupa.py
new file mode 100644
index 000000000000..675270f9ed3e
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/coupa/tests/test_coupa.py
@@ -0,0 +1,207 @@
+from datetime import UTC, datetime
+from typing import Any
+
+import pytest
+from unittest import mock
+
+from posthog.temporal.data_imports.sources.coupa.coupa import (
+ CoupaResumeConfig,
+ _normalize_keys,
+ get_rows,
+ hostname_of,
+ normalize_host,
+ validate_credentials,
+)
+from posthog.temporal.data_imports.sources.coupa.settings import ENDPOINTS, PAGE_SIZE
+
+_MODULE = "posthog.temporal.data_imports.sources.coupa.coupa"
+
+
+def _make_manager(resume_state: CoupaResumeConfig | None = None) -> mock.MagicMock:
+ manager = mock.MagicMock()
+ manager.can_resume.return_value = resume_state is not None
+ manager.load_state.return_value = resume_state
+ return manager
+
+
+def _response(body: Any, status_code: int = 200) -> mock.MagicMock:
+ resp = mock.MagicMock()
+ resp.json.return_value = body
+ resp.status_code = status_code
+ resp.ok = status_code < 400
+ return resp
+
+
+def _token_response() -> mock.MagicMock:
+ return _response({"access_token": "tok-1", "token_type": "bearer", "expires_in": 86399})
+
+
+class TestNormalizeHost:
+ @pytest.mark.parametrize(
+ "value, expected",
+ [
+ ("https://myorg.coupahost.com", "https://myorg.coupahost.com"),
+ ("myorg.coupahost.com", "https://myorg.coupahost.com"),
+ ("https://myorg.coupacloud.com/", "https://myorg.coupacloud.com"),
+ ],
+ )
+ def test_valid_hosts(self, value, expected):
+ assert normalize_host(value) == expected
+
+ @pytest.mark.parametrize("value", ["", " ", "ftp://example.com", "https://", "http://myorg.coupahost.com"])
+ def test_invalid_hosts_raise(self, value):
+ with pytest.raises(ValueError):
+ normalize_host(value)
+
+ def test_hostname_of(self):
+ assert hostname_of("https://myorg.coupahost.com/api") == "myorg.coupahost.com"
+
+
+class TestNormalizeKeys:
+ def test_hyphenated_keys_become_underscored(self):
+ row = {"id": 1, "updated-at": "2024-01-01T00:00:00Z", "invoice-number": "INV-1", "plain": "x"}
+ assert _normalize_keys(row) == {
+ "id": 1,
+ "updated_at": "2024-01-01T00:00:00Z",
+ "invoice_number": "INV-1",
+ "plain": "x",
+ }
+
+
+class TestValidateCredentials:
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_valid_credentials_mint_a_token(self, mock_session):
+ mock_session.return_value.post.return_value = _token_response()
+
+ assert validate_credentials("https://myorg.coupahost.com", "cid", "sec") is True
+ call = mock_session.return_value.post.call_args
+ assert call.args[0] == "https://myorg.coupahost.com/oauth2/token"
+ assert call.kwargs["auth"] == ("cid", "sec")
+ assert call.kwargs["data"] == {"grant_type": "client_credentials"}
+
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_invalid_credentials(self, mock_session):
+ response = _response({}, status_code=401)
+ response.raise_for_status.side_effect = Exception("401")
+ mock_session.return_value.post.return_value = response
+
+ assert validate_credentials("https://myorg.coupahost.com", "cid", "bad") is False
+
+
+class TestGetRows:
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_mints_endpoint_scoped_token_and_paginates(self, mock_session):
+ full_page = [{"id": i, "updated-at": "2024-01-01T00:00:00Z"} for i in range(PAGE_SIZE)]
+ mock_session.return_value.post.return_value = _token_response()
+ mock_session.return_value.get.side_effect = [
+ _response(full_page),
+ _response([{"id": "last", "updated-at": "2024-01-02T00:00:00Z"}]),
+ ]
+
+ manager = _make_manager()
+ batches = list(get_rows("https://myorg.coupahost.com", "cid", "sec", "invoices", mock.MagicMock(), manager))
+
+ assert [len(batch) for batch in batches] == [PAGE_SIZE, 1]
+ # Keys are normalized so the cursor field always exists.
+ assert all("updated_at" in row for batch in batches for row in batch)
+ token_body = mock_session.return_value.post.call_args.kwargs["data"]
+ assert token_body["scope"] == "core.invoice.read"
+ second_url = mock_session.return_value.get.call_args_list[1].args[0]
+ assert f"offset={PAGE_SIZE}" in second_url
+ assert [call.args[0].next_offset for call in manager.save_state.call_args_list] == [PAGE_SIZE]
+
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_scope_rejection_falls_back_to_scopeless_token(self, mock_session):
+ scope_rejected = _response({"error": "invalid_scope"}, status_code=400)
+ mock_session.return_value.post.side_effect = [scope_rejected, _token_response()]
+ mock_session.return_value.get.return_value = _response([])
+
+ list(get_rows("https://myorg.coupahost.com", "cid", "sec", "invoices", mock.MagicMock(), _make_manager()))
+
+ second_token_body = mock_session.return_value.post.call_args_list[1].kwargs["data"]
+ assert "scope" not in second_token_body
+
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_non_scope_400_does_not_fall_back(self, mock_session):
+ rejected = _response({"error": "invalid_client"}, status_code=400)
+ rejected.raise_for_status.side_effect = Exception("400")
+ mock_session.return_value.post.return_value = rejected
+
+ with pytest.raises(Exception):
+ list(get_rows("https://myorg.coupahost.com", "cid", "sec", "invoices", mock.MagicMock(), _make_manager()))
+
+ # Only the original (scoped) request is made; no scopeless retry.
+ assert mock_session.return_value.post.call_count == 1
+
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_incremental_passes_updated_at_gt(self, mock_session):
+ mock_session.return_value.post.return_value = _token_response()
+ mock_session.return_value.get.return_value = _response([])
+
+ list(
+ get_rows(
+ "https://myorg.coupahost.com",
+ "cid",
+ "sec",
+ "invoices",
+ mock.MagicMock(),
+ _make_manager(),
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2024, 1, 2, 3, 4, 5, tzinfo=UTC),
+ )
+ )
+
+ url = mock_session.return_value.get.call_args.args[0]
+ assert "updated_at%5Bgt%5D=2024-01-02T03%3A04%3A05Z" in url
+
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_resumes_from_saved_offset(self, mock_session):
+ mock_session.return_value.post.return_value = _token_response()
+ mock_session.return_value.get.return_value = _response([{"id": 1}])
+
+ manager = _make_manager(CoupaResumeConfig(next_offset=150))
+ list(get_rows("https://myorg.coupahost.com", "cid", "sec", "invoices", mock.MagicMock(), manager))
+
+ url = mock_session.return_value.get.call_args.args[0]
+ assert "offset=150" in url
+
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_mid_sync_401_re_mints_token(self, mock_session):
+ mock_session.return_value.post.side_effect = [_token_response(), _token_response()]
+ mock_session.return_value.get.side_effect = [
+ _response({}, status_code=401),
+ _response([{"id": 1}]),
+ ]
+
+ batches = list(
+ get_rows("https://myorg.coupahost.com", "cid", "sec", "invoices", mock.MagicMock(), _make_manager())
+ )
+
+ assert [row["id"] for batch in batches for row in batch] == [1]
+ assert mock_session.return_value.post.call_count == 2
+
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_session_forces_json_accept_header(self, mock_session):
+ mock_session.return_value.post.return_value = _token_response()
+ mock_session.return_value.get.return_value = _response([])
+
+ list(get_rows("https://myorg.coupahost.com", "cid", "sec", "users", mock.MagicMock(), _make_manager()))
+
+ # Coupa defaults to XML — the session must be created with Accept: application/json.
+ session_headers = mock_session.call_args.kwargs["headers"]
+ assert session_headers == {"Accept": "application/json"}
+
+
+class TestCoupaSourceResponse:
+ @pytest.mark.parametrize("endpoint", list(ENDPOINTS))
+ def test_response_metadata_per_endpoint(self, endpoint):
+ from posthog.temporal.data_imports.sources.coupa.coupa import coupa_source
+
+ response = coupa_source(
+ "https://myorg.coupahost.com", "cid", "sec", endpoint, mock.MagicMock(), _make_manager()
+ )
+
+ assert response.name == endpoint
+ assert response.primary_keys == ["id"]
+ # Ordering within an updated_at window is undocumented — deferred watermark.
+ assert response.sort_mode == "desc"
diff --git a/posthog/temporal/data_imports/sources/coupa/tests/test_coupa_source.py b/posthog/temporal/data_imports/sources/coupa/tests/test_coupa_source.py
new file mode 100644
index 000000000000..76bdea9ae3f5
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/coupa/tests/test_coupa_source.py
@@ -0,0 +1,184 @@
+import pytest
+from unittest import mock
+
+from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType
+
+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from posthog.temporal.data_imports.sources.coupa.coupa import CoupaResumeConfig
+from posthog.temporal.data_imports.sources.coupa.settings import ENDPOINTS, INCREMENTAL_FIELDS
+from posthog.temporal.data_imports.sources.coupa.source import CoupaSource
+from posthog.temporal.data_imports.sources.generated_configs import CoupaSourceConfig
+
+from products.data_warehouse.backend.types import ExternalDataSourceType
+
+
+class TestCoupaSource:
+ def setup_method(self):
+ self.source = CoupaSource()
+ self.team_id = 123
+ self.config = CoupaSourceConfig(
+ instance_url="https://myorg.coupahost.com", client_id="cid", client_secret="sec"
+ )
+
+ def test_source_type(self):
+ assert self.source.source_type == ExternalDataSourceType.COUPA
+
+ def test_get_source_config(self):
+ config = self.source.get_source_config
+
+ assert config.name.value == "Coupa"
+ assert config.label == "Coupa"
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.unreleasedSource is None
+ assert config.iconPath == "/static/services/coupa.png"
+
+ field_names = [f.name for f in config.fields]
+ assert field_names == ["instance_url", "client_id", "client_secret"]
+
+ def test_client_secret_field_is_secret_password(self):
+ config = self.source.get_source_config
+ secret_field = next(
+ f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "client_secret"
+ )
+ assert secret_field.type == SourceFieldInputConfigType.PASSWORD
+ assert secret_field.secret is True
+ assert secret_field.required is True
+
+ def test_connection_host_fields_cover_instance_url(self):
+ # The instance URL decides where the stored credentials get sent.
+ assert self.source.connection_host_fields == ["instance_url"]
+
+ @pytest.mark.parametrize(
+ "observed_error",
+ [
+ "400 Client Error: Bad Request for url: https://myorg.coupahost.com/oauth2/token",
+ "403 Client Error: Forbidden for url: https://myorg.coupahost.com/api/invoices",
+ ],
+ )
+ def test_non_retryable_errors_match_known_failures(self, observed_error):
+ non_retryable_errors = self.source.get_non_retryable_errors()
+ assert any(key in observed_error for key in non_retryable_errors)
+
+ @pytest.mark.parametrize(
+ "other_error",
+ [
+ "500 Server Error for url: https://myorg.coupahost.com/api/invoices",
+ # Mid-sync 401s on data endpoints are handled by token re-mint.
+ "401 Client Error: Unauthorized for url: https://myorg.coupahost.com/api/invoices",
+ ],
+ )
+ def test_non_retryable_errors_does_not_match_unrelated(self, other_error):
+ non_retryable_errors = self.source.get_non_retryable_errors()
+ assert not any(key in other_error for key in non_retryable_errors)
+
+ def test_get_schemas(self):
+ schemas = self.source.get_schemas(self.config, self.team_id)
+
+ assert {schema.name for schema in schemas} == set(ENDPOINTS)
+ # Every stream filters server-side on updated_at[gt].
+ assert all(schema.supports_incremental for schema in schemas)
+ assert all([f["field"] for f in schema.incremental_fields] == ["updated_at"] for schema in schemas)
+ assert {schema.name: schema.incremental_fields for schema in schemas} == INCREMENTAL_FIELDS
+
+ def test_get_schemas_filtered_by_names(self):
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["invoices"])
+ assert len(schemas) == 1
+ assert schemas[0].name == "invoices"
+
+ def test_get_schemas_filtered_unknown_name_returns_empty(self):
+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []
+
+ @mock.patch("posthog.temporal.data_imports.sources.coupa.source.validate_coupa_credentials")
+ @mock.patch.object(CoupaSource, "is_database_host_valid")
+ def test_validate_credentials_happy_path(self, mock_host_valid, mock_validate):
+ mock_host_valid.return_value = (True, None)
+ mock_validate.return_value = True
+
+ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id)
+
+ assert is_valid is True
+ assert error_message is None
+ mock_host_valid.assert_called_once_with("myorg.coupahost.com", self.team_id)
+ mock_validate.assert_called_once_with("https://myorg.coupahost.com", "cid", "sec")
+
+ @mock.patch.object(CoupaSource, "is_database_host_valid")
+ def test_validate_credentials_rejects_unsafe_host(self, mock_host_valid):
+ mock_host_valid.return_value = (False, "Host is not allowed")
+
+ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id)
+
+ assert is_valid is False
+ assert error_message == "Host is not allowed"
+
+ def test_validate_credentials_rejects_invalid_url(self):
+ config = CoupaSourceConfig(instance_url="ftp://nope", client_id="cid", client_secret="sec")
+
+ is_valid, error_message = self.source.validate_credentials(config, self.team_id)
+
+ assert is_valid is False
+ assert error_message == "Invalid Coupa instance URL"
+
+ @mock.patch("posthog.temporal.data_imports.sources.coupa.source.validate_coupa_credentials")
+ @mock.patch.object(CoupaSource, "is_database_host_valid")
+ def test_validate_credentials_bad_secret(self, mock_host_valid, mock_validate):
+ mock_host_valid.return_value = (True, None)
+ mock_validate.return_value = False
+
+ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id)
+
+ assert is_valid is False
+ assert "Invalid Coupa credentials" in (error_message or "")
+
+ def test_get_resumable_source_manager_binds_resume_config(self):
+ inputs = mock.MagicMock()
+ manager = self.source.get_resumable_source_manager(inputs)
+
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is CoupaResumeConfig
+
+ @mock.patch("posthog.temporal.data_imports.sources.coupa.source.coupa_source")
+ @mock.patch.object(CoupaSource, "is_database_host_valid")
+ def test_source_for_pipeline_plumbs_arguments(self, mock_host_valid, mock_coupa_source):
+ mock_host_valid.return_value = (True, None)
+ inputs = mock.MagicMock()
+ inputs.schema_name = "invoices"
+ inputs.team_id = self.team_id
+ inputs.should_use_incremental_field = True
+ inputs.db_incremental_field_last_value = "2024-01-02T03:04:05Z"
+ manager = mock.MagicMock()
+
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ mock_coupa_source.assert_called_once()
+ kwargs = mock_coupa_source.call_args.kwargs
+ assert kwargs["instance_url"] == "https://myorg.coupahost.com"
+ assert kwargs["client_id"] == "cid"
+ assert kwargs["client_secret"] == "sec"
+ assert kwargs["endpoint"] == "invoices"
+ assert kwargs["resumable_source_manager"] is manager
+ assert kwargs["should_use_incremental_field"] is True
+ assert kwargs["db_incremental_field_last_value"] == "2024-01-02T03:04:05Z"
+
+ @mock.patch.object(CoupaSource, "is_database_host_valid")
+ def test_source_for_pipeline_rejects_unsafe_host(self, mock_host_valid):
+ mock_host_valid.return_value = (False, "Host is not allowed")
+ inputs = mock.MagicMock()
+ inputs.schema_name = "invoices"
+ inputs.team_id = self.team_id
+
+ with pytest.raises(ValueError, match="Host is not allowed"):
+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)
+
+ @mock.patch("posthog.temporal.data_imports.sources.coupa.source.coupa_source")
+ @mock.patch.object(CoupaSource, "is_database_host_valid")
+ def test_source_for_pipeline_omits_last_value_on_full_refresh(self, mock_host_valid, mock_coupa_source):
+ mock_host_valid.return_value = (True, None)
+ inputs = mock.MagicMock()
+ inputs.schema_name = "users"
+ inputs.team_id = self.team_id
+ inputs.should_use_incremental_field = False
+ inputs.db_incremental_field_last_value = "2024-01-02T03:04:05Z"
+
+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)
+
+ assert mock_coupa_source.call_args.kwargs["db_incremental_field_last_value"] is None
diff --git a/posthog/temporal/data_imports/sources/generated_configs.py b/posthog/temporal/data_imports/sources/generated_configs.py
index 5cf1b68cd081..88720d0fea30 100644
--- a/posthog/temporal/data_imports/sources/generated_configs.py
+++ b/posthog/temporal/data_imports/sources/generated_configs.py
@@ -461,7 +461,9 @@ class CosmosDBSourceConfig(config.Config):
@config.config
class CoupaSourceConfig(config.Config):
- pass
+ instance_url: str
+ client_id: str
+ client_secret: str
@config.config