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.

fix(warehouse-sources): Checkout.com customers and instruments sync zero rows (#82961)

jake sciotto8a178cceaf7a
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/checkout_com/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/checkout_com/canonical_descriptions.py
index c844ec84ed23..1cac9718a1fb 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/checkout_com/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/checkout_com/canonical_descriptions.py
@@ -80,6 +80,7 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"payment_type": "Type of the payment (e.g. Regular, Recurring).",
"source": "Payment source details (instrument identifier, type, card metadata).",
"customer": "Customer associated with the payment (identifier, email, name).",
+ "customer_id": "Identifier of the customer associated with the payment. Joins to the customers table's id column.",
"processing": "Processing details such as acquirer identifiers.",
"metadata": "Custom key-value pairs attached to the payment.",
},
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/checkout_com/payments.py b/products/warehouse_sources/backend/temporal/data_imports/sources/checkout_com/payments.py
index 8cb5cb98edd0..9c2443f3fd28 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/checkout_com/payments.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/checkout_com/payments.py
@@ -16,15 +16,21 @@ over months holding no rows. Each fully-drained window is checkpointed, so the
retry resumes where the budget ran out.
``payment_actions``, ``customers`` and ``instruments`` have no listing
-endpoints at all, so their syncs walk the same payment windows and fan out to
-``GET /payments/{id}/actions``, ``GET /customers/{id}`` and
-``GET /instruments/{id}`` for the ids those payments reference.
+endpoints at all, so their syncs walk the same payment windows and fan out per
+referenced record. The search response references a customer by email alone
+(its ``customer`` object carries no ``cus_`` id) and describes a card source
+without an instrument id, so customers are fetched via ``GET
+/customers/{identifier}`` (the endpoint accepts an email) and instruments via
+``GET /payments/{id}`` (whose detail response carries the source id) followed
+by ``GET /instruments/{id}``. Payment rows get a ``customer_id`` column from
+the same customer lookups so they join to the customers table.
"""
import dataclasses
from collections.abc import Iterator
from datetime import UTC, date, datetime, timedelta
from typing import Any, Optional
+from urllib.parse import quote
import requests
from structlog.types import FilteringBoundLogger
@@ -74,18 +80,31 @@ MIN_WINDOW = timedelta(seconds=1)
# each chunk is still split further on page-fullness as before.
MAX_SEARCH_WINDOW = timedelta(days=90)
# Bound one sync's API usage: searches are one call per ~1000 payments, fan-out lookups
-# are one call per payment/customer/instrument. A capped run stops after the last fully
-# processed window, so the next run continues from its watermark.
+# are one call per referenced payment/customer/instrument. A capped run stops after the
+# last fully processed window, so the next run continues from its watermark.
MAX_SEARCH_REQUESTS_PER_SYNC = 2_000
MAX_FANOUT_LOOKUPS_PER_SYNC = 10_000
+# The payments schema enriches each row with `customer_id` via one `GET
+# /customers/{email}` per unique email per run (see _CustomerIdResolver). The cap bounds
+# a pathological backfill; past it, rows keep syncing with `customer_id` null. This is
+# deliberately a soft stop, unlike the fan-out budget: covered windows are checkpointed
+# and never re-read, so raising could not backfill the nulls anyway.
+MAX_CUSTOMER_ID_LOOKUPS_PER_SYNC = 10_000
FANOUT_CHUNK_SIZE = 500
# Bucket count for the md5(id) partitioning of `payments` (see
# checkout_com_payments_source): enough buckets to keep each per-partition merge small
# on multi-million-row accounts, matching the count other id-hashed sources use.
PAYMENTS_PARTITION_COUNT = 200
+# Only vault-stored records are fetchable; other source ids (tokens, one-off payment
+# methods) have no GET endpoint.
+CUSTOMER_ID_PREFIX = "cus_"
+INSTRUMENT_ID_PREFIX = "src_"
+
# Stable marker so the source can classify a budget stop as retryable rather than a bug.
SYNC_BUDGET_EXCEEDED_MARKER = "Checkout.com sync hit its per-run API budget"
+# Stable marker so the source can map an id-less run to a customer-facing error.
+UNRESOLVED_REFERENCES_MARKER = "Checkout.com payments reference records without a usable identifier"
class CheckoutComSyncBudgetExceeded(Exception):
@@ -98,6 +117,16 @@ class CheckoutComSyncBudgetExceeded(Exception):
"""
+class CheckoutComUnresolvedReferencesError(Exception):
+ """Every reference a customers/instruments run saw was impossible to look up.
+
+ Raised rather than returned. Returning would report the schema `Completed` while the
+ table silently stays empty, hiding that the account's payments carry references we
+ cannot resolve. A run that resolves at least one reference completes and only logs
+ the leftover count: partial data with a visible log beats pausing a working table.
+ """
+
+
class _SyncBudget:
"""Counts API calls for one sync and says when to stop cleanly."""
@@ -106,6 +135,14 @@ class _SyncBudget:
self.lookups_left = lookups
self.exhausted = False
+ def take_lookup(self) -> bool:
+ """Consume one fan-out lookup; False (and exhausted) once the budget is spent."""
+ if self.lookups_left <= 0:
+ self.exhausted = True
+ return False
+ self.lookups_left -= 1
+ return True
+
@dataclasses.dataclass(frozen=True, kw_only=True)
class _Window:
@@ -113,6 +150,31 @@ class _Window:
end: datetime
[email protected](frozen=True, kw_only=True)
+class _CardIdentity:
+ """One customer's use of one card, the granularity payment-detail lookups dedupe on.
+
+ Payments sharing a fingerprint alone can still resolve to different instruments (two
+ customers storing the same card), so the holder's email is part of the key. A payment
+ whose customer carries no usable email has no identity at all: keying it on the
+ fingerprint alone would let one customer's instrument stand in for another's, so such
+ payments resolve individually instead of sharing a cache entry.
+ """
+
+ fingerprint: str
+ customer_email: str
+
+
[email protected](frozen=False)
+class _FanoutRunState:
+ """Dedupe sets, caches and resolution counters shared across one run's windows."""
+
+ seen_keys: set[str] = dataclasses.field(default_factory=set)
+ instrument_ids_by_card: dict[_CardIdentity, Optional[str]] = dataclasses.field(default_factory=dict)
+ unresolvable_references: int = 0
+ rows_landed: int = 0
+
+
def _to_datetime(value: Any) -> datetime | None:
"""Coerce a stored watermark or configured start date (datetime, date or ISO string) into UTC."""
if value is None:
@@ -287,31 +349,210 @@ def _payment_actions_rows(
return rows
-def _referenced_id(payment: dict[str, Any], endpoint: str) -> Optional[str]:
- if endpoint == "customers":
+def _customer_email(customer: dict[str, Any]) -> Optional[str]:
+ email = str(customer.get("email") or "").strip()
+ return email if "@" in email else None
+
+
+def _customer_identifier(customer: dict[str, Any]) -> Optional[str]:
+ """The value ``GET /customers/{identifier}`` accepts for this payment's customer.
+
+ The endpoint takes a ``cus_`` id or an email address. The search response usually
+ carries only the email (its ``customer`` object omits the id), so the email is the
+ primary route to the record rather than a fallback.
+ """
+ raw_id = str(customer.get("id") or "")
+ if raw_id.startswith(CUSTOMER_ID_PREFIX):
+ return raw_id
+ return _customer_email(customer)
+
+
+def _fetch_customer(
+ session: requests.Session,
+ auth: OAuth2Auth,
+ api_base: str,
+ identifier: str,
+ logger: FilteringBoundLogger,
+) -> Optional[dict[str, Any]]:
+ """One customer lookup by ``cus_`` id or email; None when no such customer exists.
+
+ Email identifiers are personal data, and both job logs and ``latest_error`` are
+ readable by anyone with project access. This module's own log lines and raised error
+ messages show an ``{email}`` placeholder, and the tracked transport masks the address
+ out of the request URL it records (``url_utils.scrub_url``), so neither carries it.
+ """
+ is_email = "@" in identifier
+ url = f"{api_base}/customers/{quote(identifier, safe='')}"
+ display_url = f"{api_base}/customers/{{email}}" if is_email else url
+ response = session.get(url, auth=auth, timeout=REQUEST_TIMEOUT_SECONDS)
+ if response.status_code == 404:
+ return None
+ if not response.ok:
+ logger.error(
+ f"Checkout.com API error: status={response.status_code}, url={display_url}, body={_error_details(response)}"
+ )
+ if not is_email:
+ response.raise_for_status()
+ kind = "Client Error" if response.status_code < 500 else "Server Error"
+ reason = str(getattr(response, "reason", "") or "")
+ raise requests.HTTPError(
+ f"{response.status_code} {kind}: {reason} for url: {display_url}",
+ response=response,
+ )
+ payload = response.json()
+ return payload if isinstance(payload, dict) else None
+
+
+class _CustomerIdResolver:
+ """Fills the ``customer_id`` column on payment rows.
+
+ ``/payments/search`` returns customers as an email with no ``cus_`` id, so the id
+ that joins payments to the customers table has to come from ``GET /customers/{email}``:
+ one call per unique email per run, with misses cached too. The column is enrichment on
+ top of otherwise-complete payment rows, so resolution degrades to null instead of
+ failing the payments sync: a 401/403 (an access key without the vault scope) or the
+ per-run lookup cap stops further lookups for the run.
+ """
+
+ def __init__(
+ self,
+ session: requests.Session,
+ auth: OAuth2Auth,
+ api_base: str,
+ logger: FilteringBoundLogger,
+ ) -> None:
+ self._session = session
+ self._auth = auth
+ self._api_base = api_base
+ self._logger = logger
+ self._ids_by_email: dict[str, Optional[str]] = {}
+ self._lookups_left = MAX_CUSTOMER_ID_LOOKUPS_PER_SYNC
+ self._stopped = False
+
+ def resolve(self, payment: dict[str, Any]) -> Optional[str]:
customer = payment.get("customer")
- raw = customer.get("id") if isinstance(customer, dict) else None
- prefix = "cus_"
- else:
- source = payment.get("source")
- raw = source.get("id") if isinstance(source, dict) else None
- prefix = "src_"
+ if not isinstance(customer, dict):
+ return None
+ raw_id = str(customer.get("id") or "")
+ if raw_id.startswith(CUSTOMER_ID_PREFIX):
+ return raw_id
+ email = _customer_email(customer)
+ if email is None:
+ return None
+ key = email.lower()
+ if key in self._ids_by_email:
+ return self._ids_by_email[key]
+ if self._stopped:
+ return None
+ if self._lookups_left <= 0:
+ self._stop("the per-run customer lookup cap was reached")
+ return None
+ self._lookups_left -= 1
+ try:
+ record = _fetch_customer(self._session, self._auth, self._api_base, email, self._logger)
+ except requests.HTTPError as error:
+ status = error.response.status_code if error.response is not None else None
+ if status in (401, 403):
+ self._stop("Checkout.com denied customer lookups (the access key lacks the vault scope)")
+ return None
+ raise
+ resolved: Optional[str] = None
+ if record is not None:
+ value = str(record.get("id") or "")
+ if value.startswith(CUSTOMER_ID_PREFIX):
+ resolved = value
+ self._ids_by_email[key] = resolved
+ return resolved
+
+ def _stop(self, reason: str) -> None:
+ self._stopped = True
+ self._logger.warning(
+ f"Stopping payments customer_id resolution for this run: {reason}; "
+ "remaining rows sync with customer_id null"
+ )
+
+
+def _customer_row(
+ session: requests.Session,
+ auth: OAuth2Auth,
+ api_base: str,
+ payment: dict[str, Any],
+ logger: FilteringBoundLogger,
+ budget: _SyncBudget,
+ state: _FanoutRunState,
+) -> Optional[dict[str, Any]]:
+ customer = payment.get("customer")
+ if not isinstance(customer, dict) or not customer:
+ return None
+ identifier = _customer_identifier(customer)
+ if identifier is None:
+ state.unresolvable_references += 1
+ return None
+ key = identifier.lower()
+ if key in state.seen_keys:
+ return None
+ state.seen_keys.add(key)
+ if not budget.take_lookup():
+ return None
+ record = _fetch_customer(session, auth, api_base, identifier, logger)
+ if record is None:
+ return None
+ row = _strip_links(record)
+ record_id = str(row.get("id") or "")
+ if not record_id:
+ # Without an id the row can't be merged on the table's primary key.
+ return None
+ # An email lookup teaches us the id, so a later payment carrying the raw id
+ # doesn't fetch the same customer again.
+ state.seen_keys.add(record_id.lower())
+ row["payment_requested_on"] = payment.get("requested_on")
+ return row
+
+
+def _card_identity(payment: dict[str, Any]) -> Optional[_CardIdentity]:
+ source = payment.get("source")
+ fingerprint = str(source.get("fingerprint") or "") if isinstance(source, dict) else ""
+ if not fingerprint:
+ return None
+ customer = payment.get("customer")
+ email = _customer_email(customer) if isinstance(customer, dict) else None
+ if not email:
+ return None
+ return _CardIdentity(fingerprint=fingerprint, customer_email=email.lower())
+
+
+def _payment_detail_instrument_id(
+ session: requests.Session,
+ auth: OAuth2Auth,
+ api_base: str,
+ payment_id: str,
+ logger: FilteringBoundLogger,
+) -> Optional[str]:
+ """The vault instrument id behind one payment, from ``GET /payments/{id}``.
+
+ The search response's ``source`` describes the card (fingerprint, bin, last4) but
+ carries no id; the detail response includes the full source object. A detail whose
+ source still has no ``src_`` id means the payment wasn't made with a vault-stored
+ instrument, which is an answer rather than a failure.
+ """
+ payload = _fanout_get(session, auth, f"{api_base}/payments/{quote(payment_id, safe='')}", logger)
+ if not isinstance(payload, dict):
+ return None
+ source = payload.get("source")
+ raw = source.get("id") if isinstance(source, dict) else None
value = str(raw or "")
- # Only vault-stored records are fetchable; other source ids (tokens, one-off
- # payment methods) have no GET endpoint.
- return value if value.startswith(prefix) else None
+ return value if value.startswith(INSTRUMENT_ID_PREFIX) else None
-def _referenced_record_row(
+def _instrument_record_row(
session: requests.Session,
auth: OAuth2Auth,
api_base: str,
- endpoint: str,
record_id: str,
payment: dict[str, Any],
logger: FilteringBoundLogger,
) -> Optional[dict[str, Any]]:
- payload = _fanout_get(session, auth, f"{api_base}/{endpoint}/{record_id}", logger)
+ payload = _fanout_get(session, auth, f"{api_base}/instruments/{quote(record_id, safe='')}", logger)
if not isinstance(payload, dict):
return None
row = _strip_links(payload)
@@ -319,6 +560,58 @@ def _referenced_record_row(
return row
+def _instrument_row(
+ session: requests.Session,
+ auth: OAuth2Auth,
+ api_base: str,
+ payment: dict[str, Any],
+ logger: FilteringBoundLogger,
+ budget: _SyncBudget,
+ state: _FanoutRunState,
+) -> Optional[dict[str, Any]]:
+ source = payment.get("source")
+ if not isinstance(source, dict) or not source:
+ return None
+ record_id_value = str(source.get("id") or "")
+ record_id: Optional[str] = record_id_value if record_id_value.startswith(INSTRUMENT_ID_PREFIX) else None
+ if record_id is None:
+ payment_id = str(payment.get("id") or "")
+ if not payment_id:
+ # No id to fetch payment details with, so the reference is a dead end.
+ state.unresolvable_references += 1
+ return None
+ card = _card_identity(payment)
+ if card is not None and card in state.instrument_ids_by_card:
+ record_id = state.instrument_ids_by_card[card]
+ else:
+ if not budget.take_lookup():
+ return None
+ record_id = _payment_detail_instrument_id(session, auth, api_base, payment_id, logger)
+ if card is not None:
+ state.instrument_ids_by_card[card] = record_id
+ if record_id is None:
+ return None
+ if record_id in state.seen_keys:
+ return None
+ state.seen_keys.add(record_id)
+ if not budget.take_lookup():
+ return None
+ return _instrument_record_row(session, auth, api_base, record_id, payment, logger)
+
+
+def _report_unresolved_references(schema_name: str, state: _FanoutRunState, logger: FilteringBoundLogger) -> None:
+ noun = "customer" if schema_name == "customers" else "payment instrument"
+ if state.rows_landed == 0:
+ raise CheckoutComUnresolvedReferencesError(
+ f"{UNRESOLVED_REFERENCES_MARKER}: {state.unresolvable_references} payment(s) in this run "
+ f"reference a {noun} that carries no fetchable identifier, and no {schema_name} could be resolved"
+ )
+ logger.error(
+ f"Checkout.com {schema_name} sync left {state.unresolvable_references} payment reference(s) "
+ "unresolved: those payments carry no fetchable identifier"
+ )
+
+
def _get_rows(
environment: str,
client_id: str,
@@ -334,6 +627,8 @@ def _get_rows(
auth = _make_auth(environment, client_id, client_secret)
session = _make_api_session(client_secret)
budget = _SyncBudget(searches=MAX_SEARCH_REQUESTS_PER_SYNC, lookups=MAX_FANOUT_LOOKUPS_PER_SYNC)
+ state = _FanoutRunState()
+ customer_ids = _CustomerIdResolver(session, auth, hosts["api"], logger) if schema_name == "payments" else None
resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
now = datetime.now(UTC)
@@ -344,31 +639,32 @@ def _get_rows(
resume.search_window_to if resume is not None else None,
now,
)
- seen_ids: set[str] = set()
chunk: list[dict[str, Any]] = []
for window, payments in _iter_bounded_payment_windows(session, auth, hosts["api"], start, now, logger, budget):
for payment in payments:
if schema_name == "payments":
- chunk.append(_strip_links(payment))
+ payment_row = _strip_links(payment)
+ # Search rows reference their customer without a `cus_` id, so the id that
+ # keys the join to the customers table is resolved separately; it always
+ # wins over a same-named field.
+ payment_row["customer_id"] = customer_ids.resolve(payment) if customer_ids is not None else None
+ chunk.append(payment_row)
elif schema_name == "payment_actions":
if not str(payment.get("id") or ""):
continue
- if budget.lookups_left <= 0:
- budget.exhausted = True
+ if not budget.take_lookup():
break
- budget.lookups_left -= 1
chunk.extend(_payment_actions_rows(session, auth, hosts["api"], payment, logger))
else:
- record_id = _referenced_id(payment, schema_name)
- if record_id is None or record_id in seen_ids:
- continue
- seen_ids.add(record_id)
- if budget.lookups_left <= 0:
- budget.exhausted = True
+ row = (
+ _customer_row(session, auth, hosts["api"], payment, logger, budget, state)
+ if schema_name == "customers"
+ else _instrument_row(session, auth, hosts["api"], payment, logger, budget, state)
+ )
+ if budget.exhausted:
break
- budget.lookups_left -= 1
- row = _referenced_record_row(session, auth, hosts["api"], schema_name, record_id, payment, logger)
if row is not None:
+ state.rows_landed += 1
chunk.append(row)
if len(chunk) >= FANOUT_CHUNK_SIZE:
yield chunk
@@ -385,6 +681,8 @@ def _get_rows(
f"{SYNC_BUDGET_EXCEEDED_MARKER} for {schema_name} before reaching "
f"{_format_timestamp(now)}; the range past the last complete window holds no rows yet"
)
+ if state.unresolvable_references:
+ _report_unresolved_references(schema_name, state, logger)
def checkout_com_payments_source(
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/checkout_com/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/checkout_com/source.py
index 8a5bc879234e..e52c9e27cdec 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/checkout_com/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/checkout_com/source.py
@@ -23,6 +23,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.checkout_c
from products.warehouse_sources.backend.temporal.data_imports.sources.checkout_com.payments import (
PAYMENTS_ENDPOINTS,
SYNC_BUDGET_EXCEEDED_MARKER,
+ UNRESOLVED_REFERENCES_MARKER,
checkout_com_payments_source,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.checkout_com.reports import (
@@ -97,13 +98,21 @@ class CheckoutComSource(ResumableSource[CheckoutComSourceConfig, CheckoutComResu
def get_non_retryable_errors(self) -> dict[str, str | None]:
# The 403 matches are path-qualified so an expired signed storage URL (a different
- # host) stays retryable, and so each endpoint gets the right scope hint. Action
- # lookups match on `/payments/pay_` because `/payments` alone would also match
- # the search path.
+ # host) stays retryable, and so each endpoint gets the right scope hint. Action and
+ # payment-detail lookups match on `/payments/pay_` because `/payments` alone would
+ # also match the search path.
errors: dict[str, str | None] = {
# Permanent token-exchange failures (invalid_client, bad request, …) all carry
# the framework's stable marker; transient 429/5xx token errors don't.
OAUTH2_PERMANENT_ERROR_MARKER: "Checkout.com authentication failed. Please check your access key ID and secret (and that they match the selected environment).",
+ # A customers/instruments run whose references all lack a fetchable identifier
+ # fails identically on every retry: the account's payments simply don't carry
+ # ids or emails for the records this table would hold.
+ UNRESOLVED_REFERENCES_MARKER: (
+ "Checkout.com returned payments whose customer or instrument references carry no usable "
+ "identifier, so the referenced records can't be fetched and this table can't be filled. "
+ "Re-enable syncing to skip those payments and continue with newer ones."
+ ),
}
for host in ("https://api.checkout.com", "https://api.sandbox.checkout.com"):
errors[f"403 Client Error: Forbidden for url: {host}/disputes"] = (
@@ -157,7 +166,7 @@ class CheckoutComSource(ResumableSource[CheckoutComSourceConfig, CheckoutComResu
label="Checkout.com",
caption="""Enter your Checkout.com API access keys to pull your payments data into the PostHog Data warehouse.
-Create an access key in the [Checkout.com dashboard](https://dashboard.checkout.com/) under Settings > Access keys. Grant it the scopes for the tables you want to sync: `disputes`, `reports`, `payments` (search), `gateway` (payment actions), and `vault` (customers and instruments).
+Create an access key in the [Checkout.com dashboard](https://dashboard.checkout.com/) under Settings > Access keys. Grant it the scopes for the tables you want to sync: `disputes`, `reports`, `payments` (search), `gateway` (payment actions and instruments), and `vault` (customers and instruments).
Payments, payment actions, customers and instruments sync from the payments search API. It reaches back 90 days by default. Set a start date to sync more history. Financial reporting data (financial actions, payouts, balances) syncs from your generated report files: each report type available for your account becomes a table. If no report tables show up, set up scheduled reports in your Checkout.com dashboard first.""",
iconPath="/static/services/checkout_com.png",
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/checkout_com/tests/test_checkout_com_payments.py b/products/warehouse_sources/backend/temporal/data_imports/sources/checkout_com/tests/test_checkout_com_payments.py
index 813653e3a152..04d2b3e3c4ac 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/checkout_com/tests/test_checkout_com_payments.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/checkout_com/tests/test_checkout_com_payments.py
@@ -5,6 +5,7 @@ from freezegun import freeze_time
from unittest import mock
import pyarrow as pa
+import requests
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.consts import PARTITION_KEY
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.partitioning import (
@@ -15,7 +16,9 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.checkout_c
)
from products.warehouse_sources.backend.temporal.data_imports.sources.checkout_com.payments import (
SYNC_BUDGET_EXCEEDED_MARKER,
+ UNRESOLVED_REFERENCES_MARKER,
CheckoutComSyncBudgetExceeded,
+ CheckoutComUnresolvedReferencesError,
checkout_com_payments_source,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
@@ -26,6 +29,7 @@ PAGE_LIMIT_PATCH = (
LOOKUP_BUDGET_PATCH = (
"products.warehouse_sources.backend.temporal.data_imports.sources.checkout_com.payments.MAX_FANOUT_LOOKUPS_PER_SYNC"
)
+CUSTOMER_LOOKUP_CAP_PATCH = "products.warehouse_sources.backend.temporal.data_imports.sources.checkout_com.payments.MAX_CUSTOMER_ID_LOOKUPS_PER_SYNC"
SESSION_PATCH = (
"products.warehouse_sources.backend.temporal.data_imports.sources.checkout_com.reports.make_tracked_session"
)
@@ -136,13 +140,14 @@ def _source(
start_date: Optional[str] = None,
should_use_incremental_field: bool = False,
db_incremental_field_last_value: Any = None,
+ logger: Optional[mock.MagicMock] = None,
):
return checkout_com_payments_source(
environment="production",
client_id="ack_id",
client_secret="secret",
schema_name=schema_name,
- logger=mock.MagicMock(),
+ logger=logger if logger is not None else mock.MagicMock(),
resumable_source_manager=manager or _FakeManager(),
start_date=start_date,
should_use_incremental_field=should_use_incremental_field,
@@ -380,33 +385,65 @@ class TestPaymentActionsFanout:
@freeze_time(NOW)
-class TestReferencedRecordFanout:
- @pytest.mark.parametrize(
- "schema_name, record_id, url",
- [
- ("customers", "cus_1", "https://api.checkout.com/customers/cus_1"),
- ("instruments", "src_1", "https://api.checkout.com/instruments/src_1"),
- ],
- )
+class TestCustomersFanout:
+ @mock.patch(SESSION_PATCH)
+ def test_email_only_references_resolve_once_per_customer(self, mock_make_session):
+ # `/payments/search` returns customers as an email with no `cus_` id; requiring an
+ # id from the search payload made the fan-out land zero rows for such accounts.
+ payments: list[dict[str, Any]] = [
+ {"id": "pay_1", "requested_on": "2024-02-29T06:00:00Z", "customer": {"email": "[email protected]"}},
+ {"id": "pay_2", "requested_on": "2024-02-29T07:00:00Z", "customer": {"email": "[email protected]"}},
+ {"id": "pay_3", "requested_on": "2024-02-29T08:00:00Z", "amount": 100},
+ ]
+ session = _FakeSession(
+ search_responses=[_search_page(payments)],
+ lookup_responses=[
+ _FakeResponse(json_data={"id": "cus_jo", "email": "[email protected]", "_links": {}}),
+ ],
+ )
+ mock_make_session.side_effect = [session]
+
+ rows = _rows(_source("customers", start_date="2024-02-28"))
+
+ assert rows == [{"id": "cus_jo", "email": "[email protected]", "payment_requested_on": "2024-02-29T06:00:00Z"}]
+ # One lookup per unique email (case-insensitive), percent-encoded into the path.
+ assert [lookup["url"] for lookup in session.lookups] == [
+ "https://api.checkout.com/customers/jo%40example.com",
+ ]
+
@mock.patch(SESSION_PATCH)
- def test_fetches_each_referenced_record_once(self, mock_make_session, schema_name, record_id, url):
- # Two payments reference the same record; a third has no fetchable reference
- # (a one-off token is not a vault instrument, a missing customer is skipped).
+ def test_id_references_win_and_dedupe_against_resolved_emails(self, mock_make_session):
payments = [
- _payment("pay_1", "2024-02-29T06:00:00Z", customer_id="cus_1", source_id="src_1"),
- _payment("pay_2", "2024-02-29T07:00:00Z", customer_id="cus_1", source_id="src_1"),
- _payment("pay_3", "2024-02-29T08:00:00Z", source_id="tok_1"),
+ {"id": "pay_1", "requested_on": "2024-02-29T06:00:00Z", "customer": {"email": "[email protected]"}},
+ # Same customer, now carrying the id its email already resolved to: no re-fetch.
+ {
+ "id": "pay_2",
+ "requested_on": "2024-02-29T07:00:00Z",
+ "customer": {"id": "cus_jo", "email": "[email protected]"},
+ },
+ {
+ "id": "pay_3",
+ "requested_on": "2024-02-29T08:00:00Z",
+ "customer": {"id": "cus_amy", "email": "[email protected]"},
+ },
]
session = _FakeSession(
search_responses=[_search_page(payments)],
- lookup_responses=[_FakeResponse(json_data={"id": record_id, "_links": {}})],
+ lookup_responses=[
+ _FakeResponse(json_data={"id": "cus_jo", "email": "[email protected]"}),
+ _FakeResponse(json_data={"id": "cus_amy", "email": "[email protected]"}),
+ ],
)
mock_make_session.side_effect = [session]
- rows = _rows(_source(schema_name, start_date="2024-02-28"))
+ rows = _rows(_source("customers", start_date="2024-02-28"))
- assert rows == [{"id": record_id, "payment_requested_on": "2024-02-29T06:00:00Z"}]
- assert [lookup["url"] for lookup in session.lookups] == [url]
+ assert [row["id"] for row in rows] == ["cus_jo", "cus_amy"]
+ # An id in the payload is used directly (no email round-trip for pay_3's customer).
+ assert [lookup["url"] for lookup in session.lookups] == [
+ "https://api.checkout.com/customers/jo%40example.com",
+ "https://api.checkout.com/customers/cus_amy",
+ ]
@mock.patch(SESSION_PATCH)
def test_deleted_record_is_skipped_and_sync_continues(self, mock_make_session):
@@ -427,6 +464,276 @@ class TestReferencedRecordFanout:
# A deleted record doesn't fail the window; it still checkpoints.
assert [state.search_window_to for state in manager.saved_states] == [NOW]
+ @mock.patch(SESSION_PATCH)
+ def test_failed_email_lookup_redacts_the_address(self, mock_make_session):
+ # The raised message reaches job logs and latest_error; the address must not.
+ payments = [{"id": "pay_1", "requested_on": "2024-02-29T06:00:00Z", "customer": {"email": "[email protected]"}}]
+ session = _FakeSession(
+ search_responses=[_search_page(payments)],
+ lookup_responses=[_FakeResponse(status_code=500, text="upstream error")],
+ )
+ mock_make_session.side_effect = [session]
+ logger = mock.MagicMock()
+
+ with pytest.raises(requests.HTTPError) as excinfo:
+ _rows(_source("customers", start_date="2024-02-28", logger=logger))
+
+ assert "[email protected]" not in str(excinfo.value)
+ assert "customers/{email}" in str(excinfo.value)
+ assert "[email protected]" not in logger.error.call_args[0][0]
+
+
+@freeze_time(NOW)
+class TestInstrumentsFanout:
+ @mock.patch(SESSION_PATCH)
+ def test_resolves_instrument_ids_via_payment_detail(self, mock_make_session):
+ # `/payments/search` describes a card source (fingerprint, last4) without an
+ # instrument id; the payment detail response carries it. Repeat payments with the
+ # same card and customer reuse one detail lookup.
+ payments = [
+ {"id": "pay_1", "requested_on": "2024-02-29T06:00:00Z", "source": {"id": "src_1", "type": "card"}},
+ {
+ "id": "pay_2",
+ "requested_on": "2024-02-29T07:00:00Z",
+ "source": {"type": "card", "fingerprint": "fp_a", "last4": "4242"},
+ "customer": {"email": "[email protected]"},
+ },
+ {
+ "id": "pay_3",
+ "requested_on": "2024-02-29T08:00:00Z",
+ "source": {"type": "card", "fingerprint": "fp_a", "last4": "4242"},
+ "customer": {"email": "[email protected]"},
+ },
+ {
+ "id": "pay_4",
+ "requested_on": "2024-02-29T09:00:00Z",
+ "source": {"type": "card", "fingerprint": "fp_b", "last4": "1111"},
+ },
+ ]
+ session = _FakeSession(
+ search_responses=[_search_page(payments)],
+ lookup_responses=[
+ _FakeResponse(json_data={"id": "src_1", "type": "card", "fingerprint": "fp_a", "_links": {}}),
+ _FakeResponse(json_data={"id": "pay_2", "source": {"id": "src_1", "type": "card"}}),
+ # A detail response whose source has no `src_` id is an authoritative
+ # answer: the payment wasn't made with a stored instrument.
+ _FakeResponse(json_data={"id": "pay_4", "source": {"type": "card", "fingerprint": "fp_b"}}),
+ ],
+ )
+ mock_make_session.side_effect = [session]
+
+ rows = _rows(_source("instruments", start_date="2024-02-28"))
+
+ assert rows == [
+ {"id": "src_1", "type": "card", "fingerprint": "fp_a", "payment_requested_on": "2024-02-29T06:00:00Z"}
+ ]
+ assert [lookup["url"] for lookup in session.lookups] == [
+ "https://api.checkout.com/instruments/src_1",
+ "https://api.checkout.com/payments/pay_2",
+ "https://api.checkout.com/payments/pay_4",
+ ]
+
+ @mock.patch(SESSION_PATCH)
+ def test_payments_without_a_holder_email_do_not_share_a_card_identity(self, mock_make_session):
+ # Two customers can store the same card, so a fingerprint with no holder email
+ # identifies nobody. Sharing one cache entry would silently drop the second
+ # instrument: its payment reuses the first id and never looks up its own.
+ payments = [
+ {
+ "id": "pay_1",
+ "requested_on": "2024-02-29T06:00:00Z",
+ "source": {"type": "card", "fingerprint": "fp_a", "last4": "4242"},
+ },
+ {
+ "id": "pay_2",
+ "requested_on": "2024-02-29T07:00:00Z",
+ "source": {"type": "card", "fingerprint": "fp_a", "last4": "4242"},
+ },
+ ]
+ session = _FakeSession(
+ search_responses=[_search_page(payments)],
+ lookup_responses=[
+ _FakeResponse(json_data={"id": "pay_1", "source": {"id": "src_1", "type": "card"}}),
+ _FakeResponse(json_data={"id": "src_1", "type": "card", "fingerprint": "fp_a", "_links": {}}),
+ _FakeResponse(json_data={"id": "pay_2", "source": {"id": "src_2", "type": "card"}}),
+ _FakeResponse(json_data={"id": "src_2", "type": "card", "fingerprint": "fp_a", "_links": {}}),
+ ],
+ )
+ mock_make_session.side_effect = [session]
+
+ rows = _rows(_source("instruments", start_date="2024-02-28"))
+
+ assert rows == [
+ {"id": "src_1", "type": "card", "fingerprint": "fp_a", "payment_requested_on": "2024-02-29T06:00:00Z"},
+ {"id": "src_2", "type": "card", "fingerprint": "fp_a", "payment_requested_on": "2024-02-29T07:00:00Z"},
+ ]
+ assert [lookup["url"] for lookup in session.lookups] == [
+ "https://api.checkout.com/payments/pay_1",
+ "https://api.checkout.com/instruments/src_1",
+ "https://api.checkout.com/payments/pay_2",
+ "https://api.checkout.com/instruments/src_2",
+ ]
+
+ @mock.patch(LOOKUP_BUDGET_PATCH, 1)
+ @mock.patch(SESSION_PATCH)
+ def test_lookup_budget_stops_between_detail_and_instrument_fetch(self, mock_make_session):
+ # The detail lookup spends the last budget unit, so the run must stop before the
+ # instrument fetch, leave the window un-checkpointed, and raise; checkpointing here
+ # would permanently skip the instrument whose detail was already paid for.
+ payments = [
+ {"id": "pay_1", "requested_on": "2024-02-29T06:00:00Z", "source": {"type": "card", "fingerprint": "fp_a"}}
+ ]
+ session = _FakeSession(
+ search_responses=[_search_page(payments)],
+ lookup_responses=[_FakeResponse(json_data={"id": "pay_1", "source": {"id": "src_1", "type": "card"}})],
+ )
+ mock_make_session.side_effect = [session]
+ manager = _FakeManager()
+
+ collected: list[dict[str, Any]] = []
+ with pytest.raises(CheckoutComSyncBudgetExceeded):
+ _collect_rows(_source("instruments", manager=manager, start_date="2024-02-28"), collected)
+
+ assert collected == []
+ assert [lookup["url"] for lookup in session.lookups] == ["https://api.checkout.com/payments/pay_1"]
+ assert manager.saved_states == []
+
+
+@freeze_time(NOW)
+class TestPaymentsCustomerIdColumn:
+ @mock.patch(SESSION_PATCH)
+ def test_rows_carry_customer_id_resolved_once_per_email(self, mock_make_session):
+ # Search rows reference their customer by email alone, so without resolution the
+ # payments table has no key that joins to customers.id.
+ payments: list[dict[str, Any]] = [
+ {"id": "pay_1", "requested_on": "2024-02-29T06:00:00Z", "customer": {"email": "[email protected]"}},
+ {"id": "pay_2", "requested_on": "2024-02-29T07:00:00Z", "customer": {"email": "[email protected]"}},
+ {
+ "id": "pay_3",
+ "requested_on": "2024-02-29T08:00:00Z",
+ "customer": {"id": "cus_amy", "email": "[email protected]"},
+ },
+ {"id": "pay_4", "requested_on": "2024-02-29T09:00:00Z"},
+ ]
+ session = _FakeSession(
+ search_responses=[_search_page(payments)],
+ lookup_responses=[_FakeResponse(json_data={"id": "cus_jo", "email": "[email protected]"})],
+ )
+ mock_make_session.side_effect = [session]
+
+ rows = _rows(_source("payments", start_date="2024-02-28"))
+
+ assert [(row["id"], row["customer_id"]) for row in rows] == [
+ ("pay_1", "cus_jo"),
+ ("pay_2", "cus_jo"),
+ ("pay_3", "cus_amy"),
+ ("pay_4", None),
+ ]
+ assert [lookup["url"] for lookup in session.lookups] == [
+ "https://api.checkout.com/customers/jo%40example.com",
+ ]
+
+ @mock.patch(SESSION_PATCH)
+ def test_denied_lookup_stops_enrichment_but_not_the_sync(self, mock_make_session):
+ # An access key without the vault scope must not take the payments table down:
+ # the first 401/403 stops further lookups and rows sync with customer_id null.
+ payments = [
+ {"id": "pay_1", "requested_on": "2024-02-29T06:00:00Z", "customer": {"email": "[email protected]"}},
+ {"id": "pay_2", "requested_on": "2024-02-29T07:00:00Z", "customer": {"email": "[email protected]"}},
+ ]
+ session = _FakeSession(
+ search_responses=[_search_page(payments)],
+ lookup_responses=[_FakeResponse(status_code=403, text="forbidden")],
+ )
+ mock_make_session.side_effect = [session]
+ logger = mock.MagicMock()
+
+ rows = _rows(_source("payments", start_date="2024-02-28", logger=logger))
+
+ assert [(row["id"], row["customer_id"]) for row in rows] == [("pay_1", None), ("pay_2", None)]
+ assert len(session.lookups) == 1
+ logger.warning.assert_called_once()
+
+ @mock.patch(CUSTOMER_LOOKUP_CAP_PATCH, 1)
+ @mock.patch(SESSION_PATCH)
+ def test_lookup_cap_stops_enrichment_but_serves_cached_ids(self, mock_make_session):
+ payments = [
+ {"id": "pay_1", "requested_on": "2024-02-29T06:00:00Z", "customer": {"email": "[email protected]"}},
+ {"id": "pay_2", "requested_on": "2024-02-29T07:00:00Z", "customer": {"email": "[email protected]"}},
+ {"id": "pay_3", "requested_on": "2024-02-29T08:00:00Z", "customer": {"email": "[email protected]"}},
+ ]
+ session = _FakeSession(
+ search_responses=[_search_page(payments)],
+ lookup_responses=[_FakeResponse(json_data={"id": "cus_jo", "email": "[email protected]"})],
+ )
+ mock_make_session.side_effect = [session]
+
+ rows = _rows(_source("payments", start_date="2024-02-28"))
+
+ # Past the cap the run keeps syncing rows (null customer_id) and still serves
+ # already-resolved ids from the cache.
+ assert [(row["id"], row["customer_id"]) for row in rows] == [
+ ("pay_1", "cus_jo"),
+ ("pay_2", None),
+ ("pay_3", "cus_jo"),
+ ]
+ assert len(session.lookups) == 1
+
+
+@freeze_time(NOW)
+class TestUnresolvableReferences:
+ @pytest.mark.parametrize(
+ "schema_name, payment",
+ [
+ # A customer reference with neither an id nor an email can't be looked up.
+ (
+ "customers",
+ {"id": "pay_1", "requested_on": "2024-02-29T06:00:00Z", "customer": {"name": "Jo"}},
+ ),
+ # A source on a payment without an id leaves no route to a payment detail.
+ (
+ "instruments",
+ {"requested_on": "2024-02-29T06:00:00Z", "source": {"type": "card", "fingerprint": "fp_a"}},
+ ),
+ ],
+ )
+ @mock.patch(SESSION_PATCH)
+ def test_run_resolving_nothing_raises_instead_of_completing_empty(self, mock_make_session, schema_name, payment):
+ # Completing here reported the schema Completed while the table silently stayed
+ # empty; the run must instead fail with the marker the source maps to latest_error.
+ session = _FakeSession(search_responses=[_search_page([payment])])
+ mock_make_session.side_effect = [session]
+ manager = _FakeManager()
+
+ with pytest.raises(CheckoutComUnresolvedReferencesError) as excinfo:
+ _rows(_source(schema_name, manager=manager, start_date="2024-02-28"))
+
+ assert UNRESOLVED_REFERENCES_MARKER in str(excinfo.value)
+ assert session.lookups == []
+ # Completed windows still checkpoint, so re-enabling the paused schema moves on
+ # instead of replaying the same unresolvable payments forever.
+ assert [state.search_window_to for state in manager.saved_states] == [NOW]
+
+ @mock.patch(SESSION_PATCH)
+ def test_partially_resolved_run_lands_rows_and_logs(self, mock_make_session):
+ # One weird payment must not pause a table that otherwise resolves fine: the run
+ # completes with the rows it found and the leftover count goes to the job log.
+ payments = [
+ {"id": "pay_1", "requested_on": "2024-02-29T06:00:00Z", "customer": {"name": "Jo"}},
+ {"id": "pay_2", "requested_on": "2024-02-29T07:00:00Z", "customer": {"email": "[email protected]"}},
+ ]
+ session = _FakeSession(
+ search_responses=[_search_page(payments)],
+ lookup_responses=[_FakeResponse(json_data={"id": "cus_amy", "email": "[email protected]"})],
+ )
+ mock_make_session.side_effect = [session]
+ logger = mock.MagicMock()
+
+ rows = _rows(_source("customers", start_date="2024-02-28", logger=logger))
+
+ assert [row["id"] for row in rows] == ["cus_amy"]
+ logger.error.assert_called_once()
+
def _yielded_payment(payment_id: str, requested_on: Optional[str]) -> dict[str, Any]:
# The row shape the source yields: a search result with `_links` stripped; the
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/checkout_com/tests/test_checkout_com_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/checkout_com/tests/test_checkout_com_source.py
index e3488e44bd94..dbd9232bf055 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/checkout_com/tests/test_checkout_com_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/checkout_com/tests/test_checkout_com_source.py
@@ -5,6 +5,7 @@ import requests
from products.warehouse_sources.backend.temporal.data_imports.sources.checkout_com.payments import (
SYNC_BUDGET_EXCEEDED_MARKER,
+ UNRESOLVED_REFERENCES_MARKER,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.checkout_com.source import CheckoutComSource
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.auth import (
@@ -45,6 +46,10 @@ class TestCheckoutComSource:
# key lacks the reports scope, so a mid-sync re-mint never resolves it.
"401 Client Error: Unauthorized for url: https://api.checkout.com/reports?limit=100",
"401 Client Error: Unauthorized for url: https://api.sandbox.checkout.com/reports/rpt_1/files/file_1",
+ # A run whose references all lack a fetchable identifier fails identically every
+ # retry, so it pauses with a customer-facing message instead of retrying.
+ f"{UNRESOLVED_REFERENCES_MARKER}: 3 payment(s) in this run reference a customer that "
+ "carries no fetchable identifier, and no customers could be resolved",
],
)
def test_non_retryable_errors_match_auth_failures(self, observed_error):
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/http/url_utils.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/http/url_utils.py
index 01c0ea23cb29..cfc5c003b8d9 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/http/url_utils.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/http/url_utils.py
@@ -1,8 +1,10 @@
"""URL helpers used by the tracked HTTP transport.
`scrub_url` redacts auth-bearing query parameters before a URL is logged
-or written into a captured sample. Path is preserved verbatim — query
-values for matching keys are replaced with `REDACTED`.
+or written into a captured sample: query values for matching keys are
+replaced with `REDACTED`. The path is otherwise preserved verbatim, except
+for segments that look like an email address, which become `{email}` —
+some APIs take an address as a lookup key, and it is personal data.
`url_template` returns a low-cardinality variant where path segments that
look like IDs are replaced with `{id}`. We don't use it for log fields any
@@ -79,25 +81,47 @@ _NUMERIC_ID = re.compile(r"^\d+$")
_UUID_ID = re.compile(r"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$")
_HEX_ID = re.compile(r"^[0-9a-fA-F]{16,}$")
+# An email address in a path segment is personal data rather than an identifier worth
+# keeping. APIs accept one as a lookup key (Checkout.com's `/customers/{identifier}` takes
+# either a customer id or an address), and percent-encoding does not redact it, so a
+# recorded request would otherwise carry the address into job logs and captured samples.
+# Masking here rather than at each call site means a source that adds such a lookup later
+# is covered without knowing to ask. Requires a dot-suffixed domain after the `@` so that
+# non-email uses of `@` in a path (an `image@sha256:...` digest) stay readable.
+_EMAIL_SEGMENT = re.compile(r"^[^/]*(?:@|%40)[^/]*\.[A-Za-z]{2,}$", re.IGNORECASE)
+_EMAIL_PLACEHOLDER: Final[str] = "{email}"
+
+
+def _scrub_path(path: str) -> str:
+ if "@" not in path and "%40" not in path.lower():
+ return path
+ return "/".join(_EMAIL_PLACEHOLDER if _EMAIL_SEGMENT.match(part) else part for part in path.split("/"))
+
def scrub_url(url: str) -> str:
- """Return `url` with auth-bearing query-param values replaced by REDACTED.
+ """Return `url` with auth-bearing query-param values and email path segments masked.
- Param names are matched case-insensitively against `_REDACT_PARAM_NAMES`.
- Order, encoding, and unrelated params are preserved.
+ Param names are matched case-insensitively against `_REDACT_PARAM_NAMES`, their values
+ replaced by REDACTED. Order, encoding, and unrelated params are preserved. Path segments
+ that look like an email address become `{email}` — see `_EMAIL_SEGMENT`.
"""
try:
parts = urlsplit(url)
except Exception:
return url
+ path = _scrub_path(parts.path)
if not parts.query:
- return url
+ # Round-trip through urlunsplit only when the path actually changed, so a URL with
+ # nothing to scrub is returned byte-for-byte rather than normalized.
+ if path == parts.path:
+ return url
+ return urlunsplit((parts.scheme, parts.netloc, path, "", parts.fragment))
pairs = parse_qsl(parts.query, keep_blank_values=True)
scrubbed = [(name, _REDACTED if name.lower() in _REDACT_PARAM_NAMES else value) for name, value in pairs]
new_query = urlencode(scrubbed, doseq=False)
- return urlunsplit((parts.scheme, parts.netloc, parts.path, new_query, parts.fragment))
+ return urlunsplit((parts.scheme, parts.netloc, path, new_query, parts.fragment))
def url_template(url: str) -> str:
@@ -120,6 +144,9 @@ def url_template(url: str) -> str:
def _template_segment(segment: str) -> str:
if not segment:
return segment
+ # Logged alongside the scrubbed URL, so an address survives here if it isn't masked here too.
+ if _EMAIL_SEGMENT.match(segment):
+ return _EMAIL_PLACEHOLDER
if _NUMERIC_ID.match(segment) or _UUID_ID.match(segment) or _HEX_ID.match(segment):
return "{id}"
return segment
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/test/test_http_url_utils.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/test/test_http_url_utils.py
index 338c82716701..01585fbdd809 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/test/test_http_url_utils.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/test/test_http_url_utils.py
@@ -74,6 +74,40 @@ def test_scrub_url_returns_input_on_garbage():
assert scrub_url("not-a-url") == "not-a-url"
+ "url,expected",
+ [
+ # An API that takes an address as a lookup key: percent-encoded is not redacted.
+ (
+ "https://api.checkout.com/customers/jo%40example.com",
+ "https://api.checkout.com/customers/{email}",
+ ),
+ ("https://x.test/customers/[email protected]", "https://x.test/customers/{email}"),
+ # Subdomains, plus plus-addressing and dots in the local part.
+ (
+ "https://x.test/c/jo.doe%2Btag%40mail.corp.example.co.uk/detail",
+ "https://x.test/c/{email}/detail",
+ ),
+ # Query scrubbing still applies alongside a masked path.
+ (
+ "https://x.test/customers/jo%40example.com?api_key=secret&page=2",
+ "https://x.test/customers/{email}?api_key=REDACTED&page=2",
+ ),
+ # An `@` without a dot-suffixed domain is not an address — keep it readable.
+ ("https://x.test/images/base@sha256:abc", "https://x.test/images/base@sha256:abc"),
+ # Untouched paths come back byte-for-byte rather than normalized.
+ ("https://api.example.com/v1/users", "https://api.example.com/v1/users"),
+ ],
+)
+def test_scrub_url_masks_email_path_segments(url: str, expected: str) -> None:
+ assert scrub_url(url) == expected
+
+
+def test_url_template_masks_email_path_segments() -> None:
+ # Logged as its own field beside the scrubbed URL, so it leaks independently.
+ assert url_template("https://x.test/customers/jo%40example.com") == "https://x.test/customers/{email}"
+
+
@pytest.mark.parametrize(
"url,expected",
[