: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 stytch import source (#71183)
Tom Owerse69a57740cf9
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex ac5cd027f197..a751bd5c1108 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -493,6 +493,7 @@ the row lists both.| statuspage | HTTP | requests | ✅ || stigg | HTTP | requests | ✅ || stripe | HTTP (vendor SDK) + Webhook | stripe (StripeClient + RequestsClient) + `WebhookSourceManager` | ✅ (pull) / ➖ (webhook) |+| stytch | HTTP | requests | ✅ || sumo_logic | HTTP | requests | ✅ || supabase | DB protocol | psycopg (delegates to PostgresSource) | ➖ || surveymonkey | HTTP | requests | ✅ |@@ -934,7 +935,6 @@ doesn't conflict with concurrent PRs.- strava- streamelements- streamlabs-- stytch- sumsub- superwall- surveymonkeydiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.pyindex c7bf4057915c..15e368ef83fc 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py@@ -4198,7 +4198,8 @@ class StripeSourceConfig(config.Config):@config.configclass StytchSourceConfig(config.Config):- pass+ project_id: str+ secret: str@config.configdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/stytch/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/stytch/canonical_descriptions.pynew file mode 100644index 000000000000..e68e174c2d42--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/stytch/canonical_descriptions.py@@ -0,0 +1,92 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "users": {+ "description": "A user of your consumer (B2C) Stytch project, with every authentication method registered to them.",+ "docs_url": "https://stytch.com/docs/api/user-object",+ "columns": {+ "user_id": "The unique ID of the user.",+ "created_at": "The timestamp of the user's creation, in RFC 3339 UTC format.",+ "status": "The status of the user. The possible values are `pending` and `active`.",+ "name": "The name of the user, as an object with `first_name`, `middle_name`, and `last_name` fields.",+ "emails": "An array of email objects for the user, each with verification status.",+ "phone_numbers": "An array of phone number objects linked to the user, each with verification status.",+ "providers": "An array of OAuth provider objects (e.g. Google, GitHub) linked to the user.",+ "totps": "An array of TOTP (authenticator app) instances registered to the user.",+ "webauthn_registrations": "An array of passkey or WebAuthn registrations for the user.",+ "biometric_registrations": "An array of biometric registrations for the user.",+ "crypto_wallets": "An array of crypto wallets linked to the user.",+ "password": "The password object, returned for users with a password.",+ "is_locked": "Whether the user is temporarily locked due to too many failed authentication attempts.",+ "lock_created_at": "When the user lock was created, if there is one.",+ "lock_expires_at": "When the user lock expires, if there is one.",+ "roles": "Roles assigned to this user.",+ "trusted_metadata": "An arbitrary JSON object of application-specific data, editable only via the API.",+ "untrusted_metadata": "An arbitrary JSON object of application-specific data, editable by end users via the SDK.",+ "external_id": "An application-supplied identifier that can be used in most API calls in place of the user ID.",+ },+ },+ "sessions": {+ "description": "An active session for a user of your consumer (B2C) Stytch project. Expired or revoked sessions are not returned by the Stytch API.",+ "docs_url": "https://stytch.com/docs/api/session-object",+ "columns": {+ "session_id": "A unique identifier for the session.",+ "user_id": "The unique ID of the user the session belongs to.",+ "started_at": "The timestamp when the session was created, in RFC 3339 UTC format.",+ "last_accessed_at": "The timestamp when the session was last accessed.",+ "expires_at": "The timestamp when the session expires.",+ "authentication_factors": "An array of the authentication factors (e.g. magic link, OAuth, TOTP) that comprise the session.",+ "attributes": "IP address and user agent attributes provided to help with fraud detection.",+ "custom_claims": "The custom claims map for the session, added during session authentication.",+ "roles": "Roles assigned to the session's user.",+ },+ },+ "organizations": {+ "description": "An organization in your Stytch B2B project.",+ "docs_url": "https://stytch.com/docs/b2b/api/organization-object",+ "columns": {+ "organization_id": "The unique ID of the organization.",+ "organization_name": "The name of the organization.",+ "organization_slug": "The unique URL slug of the organization.",+ "organization_logo_url": "The image URL of the organization's logo.",+ "created_at": "The timestamp of the organization's creation, in RFC 3339 UTC format.",+ "updated_at": "The timestamp of when the organization was last updated.",+ "email_allowed_domains": "An array of email domains that allow invites or JIT provisioning for new members.",+ "email_jit_provisioning": "The authentication setting controlling how a new member can be provisioned by authenticating via email.",+ "email_invites": "The authentication setting controlling how a new member can be invited via email.",+ "sso_default_connection_id": "The default SSO connection used for the organization, if there is one.",+ "sso_jit_provisioning": "The authentication setting controlling JIT provisioning of members via SSO.",+ "auth_methods": "The setting controlling which authentication methods are allowed: `ALL_ALLOWED` or `RESTRICTED`.",+ "allowed_auth_methods": "The list of allowed authentication methods when `auth_methods` is `RESTRICTED`.",+ "mfa_policy": "The organization's MFA policy: `REQUIRED_FOR_ALL` or `OPTIONAL`.",+ "trusted_metadata": "An arbitrary JSON object of application-specific data for the organization.",+ },+ },+ "members": {+ "description": "A member of an organization in your Stytch B2B project.",+ "docs_url": "https://stytch.com/docs/b2b/api/member-object",+ "columns": {+ "member_id": "The unique ID of the member.",+ "organization_id": "The unique ID of the organization the member belongs to.",+ "email_address": "The email address of the member.",+ "status": "The status of the member. The possible values are `pending`, `invited`, `active`, or `deleted`.",+ "name": "The name of the member.",+ "created_at": "The timestamp of the member's creation, in RFC 3339 UTC format.",+ "updated_at": "The timestamp of when the member was last updated.",+ "email_address_verified": "Whether the member's email address is verified.",+ "mfa_enrolled": "Whether the member is enrolled in MFA.",+ "mfa_phone_number": "The member's phone number used for MFA, if one is set.",+ "is_breakglass": "Whether the member can authenticate with email + password even when auth methods are restricted.",+ "is_locked": "Whether the member is temporarily locked due to too many failed authentication attempts.",+ "sso_registrations": "An array of registered SSO connections for the member.",+ "oauth_registrations": "An array of registered OAuth providers for the member.",+ "totp_registration_id": "The ID of the member's TOTP registration, if one exists.",+ "roles": "Explicit and implicit RBAC roles assigned to the member.",+ "trusted_metadata": "An arbitrary JSON object of application-specific data for the member.",+ "untrusted_metadata": "An arbitrary JSON object of application-specific data, editable by the member via the SDK.",+ "external_id": "An application-supplied identifier that can be used in most API calls in place of the member ID.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/stytch/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/stytch/settings.pynew file mode 100644index 000000000000..9ab00c5db00a--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/stytch/settings.py@@ -0,0 +1,86 @@+from dataclasses import dataclass, field+from typing import Literal, Optional++from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType++StytchFanOut = Literal["users", "organizations"]+++@dataclass+class StytchEndpointConfig:+ name: str+ path: str+ # Response field holding the rows (Stytch wraps them per endpoint: results/sessions/organizations/members).+ data_key: str+ primary_keys: list[str]+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ # Stable creation-time field for datetime partitioning; never an updated-at style field.+ partition_key: Optional[str] = None+ should_sync_default: bool = True+ description: Optional[str] = None+ # "users": one GET per user enumerated via the users search (sessions).+ # "organizations": member search fanned out over organization_id chunks (members).+ fan_out: Optional[StytchFanOut] = None+ # B2B-only endpoints error on consumer (B2C) projects, so they must not be default-on.+ b2b_only: bool = False+++STYTCH_ENDPOINTS: dict[str, StytchEndpointConfig] = {+ "users": StytchEndpointConfig(+ name="users",+ path="/v1/users/search",+ data_key="results",+ primary_keys=["user_id"],+ partition_key="created_at",+ incremental_fields=[+ {+ "label": "created_at",+ "type": IncrementalFieldType.DateTime,+ "field": "created_at",+ "field_type": IncrementalFieldType.DateTime,+ },+ ],+ description=(+ "All users in the project with their auth methods (emails, phone numbers, OAuth providers, "+ "TOTPs, passkeys). Stytch exposes no updated-at filter, so incremental syncs only pick up "+ "newly created users; run a periodic full refresh to capture changes to existing users"+ ),+ ),+ "sessions": StytchEndpointConfig(+ name="sessions",+ path="/v1/sessions",+ data_key="sessions",+ primary_keys=["session_id"],+ fan_out="users",+ should_sync_default=False,+ description=(+ "Active sessions, fetched one request per user (expired sessions are not returned by the "+ "Stytch API). Off by default because of the per-user API cost on large projects"+ ),+ ),+ "organizations": StytchEndpointConfig(+ name="organizations",+ path="/v1/b2b/organizations/search",+ data_key="organizations",+ primary_keys=["organization_id"],+ should_sync_default=False,+ b2b_only=True,+ description="Organizations in a Stytch B2B project. Errors on consumer (B2C) projects",+ ),+ "members": StytchEndpointConfig(+ name="members",+ path="/v1/b2b/organizations/members/search",+ data_key="members",+ primary_keys=["member_id"],+ fan_out="organizations",+ should_sync_default=False,+ b2b_only=True,+ description="Members across all organizations in a Stytch B2B project. Errors on consumer (B2C) projects",+ ),+}++ENDPOINTS = tuple(STYTCH_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in STYTCH_ENDPOINTS.items()+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/stytch/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/stytch/source.pyindex cef7f63e9231..99f681b9b636 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/stytch/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/stytch/source.py@@ -1,19 +1,44 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (+ SourceInputs,+ SourceResponse,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchemafrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import StytchSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.stytch.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+ STYTCH_ENDPOINTS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.stytch.stytch import (+ StytchResumeConfig,+ check_endpoint_access,+ stytch_source,+ validate_credentials as validate_stytch_credentials,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class StytchSource(SimpleSource[StytchSourceConfig]):+class StytchSource(ResumableSource[StytchSourceConfig, StytchResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.STYTCH@@ -24,7 +49,125 @@ class StytchSource(SimpleSource[StytchSourceConfig]):name=SchemaExternalDataSourceType.STYTCH,category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,label="Stytch",+ keywords=["auth", "authentication", "identity"],+ caption="""Enter your Stytch project ID and secret to pull your Stytch users and sessions into the PostHog Data warehouse.++You can find both under [API keys](https://stytch.com/dashboard/api-keys) in your Stytch dashboard. Live credentials (`project-live-...`) sync from `api.stytch.com`; test credentials (`project-test-...`) sync your test environment's data from `test.stytch.com`.++The `organizations` and `members` tables are only available for Stytch B2B projects.""",iconPath="/static/services/stytch.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/stytch",+ releaseStatus=ReleaseStatus.ALPHA,+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="project_id",+ label="Project ID",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="project-live-...",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="secret",+ label="Secret",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="secret-live-...",+ secret=True,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.stytch.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ # Stytch reports credential failures as 400/401 JSON with a stable `error_type`, which the+ # transport surfaces in the raised message. Retrying can never fix these.+ return {+ "error_type=invalid_project_id_authentication": "Your Stytch project ID is invalid. Check it in your Stytch dashboard under API keys, then reconnect.",+ "error_type=invalid_secret_authentication": "Your Stytch secret is invalid or has been revoked. Create a new secret in your Stytch dashboard under API keys, then reconnect.",+ "error_type=unauthorized_credentials": "Your Stytch credentials were rejected. Check your project ID and secret in your Stytch dashboard, then reconnect.",+ "error_type=invalid_authorization_header": "Your Stytch credentials are malformed. Re-enter your project ID and secret, then reconnect.",+ }++ def get_schemas(+ self,+ config: StytchSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ schemas = [+ SourceSchema(+ name=endpoint,+ # Users have no updated-at filter, so incremental only catches new rows; append+ # would still duplicate rows re-pulled after a crash resume, so merge only.+ supports_incremental=bool(INCREMENTAL_FIELDS.get(endpoint)),+ supports_append=False,+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),+ should_sync_default=STYTCH_ENDPOINTS[endpoint].should_sync_default,+ description=STYTCH_ENDPOINTS[endpoint].description,+ )+ 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: StytchSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ if validate_stytch_credentials(config.project_id, config.secret):+ return True, None++ return False, "Invalid Stytch project ID or secret"++ def get_endpoint_permissions(+ self, config: StytchSourceConfig, team_id: int, endpoints: list[str]+ ) -> dict[str, str | None]:+ # B2C and B2B projects have disjoint API surfaces; probe each requested surface once so+ # the schema picker can flag the tables the connected project can't serve.+ probe_paths = {False: "/v1/users/search", True: "/v1/b2b/organizations/search"}+ surfaces_needed = {+ STYTCH_ENDPOINTS[endpoint].b2b_only for endpoint in endpoints if endpoint in STYTCH_ENDPOINTS+ }+ access_by_surface = {+ b2b: check_endpoint_access(config.project_id, config.secret, probe_paths[b2b]) for b2b in surfaces_needed+ }+ return {+ endpoint: access_by_surface[STYTCH_ENDPOINTS[endpoint].b2b_only] if endpoint in STYTCH_ENDPOINTS else None+ for endpoint in endpoints+ }++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[StytchResumeConfig]:+ return ResumableSourceManager[StytchResumeConfig](inputs, StytchResumeConfig)++ def source_for_pipeline(+ self,+ config: StytchSourceConfig,+ resumable_source_manager: ResumableSourceManager[StytchResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return stytch_source(+ project_id=config.project_id,+ secret=config.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/products/warehouse_sources/backend/temporal/data_imports/sources/stytch/stytch.py b/products/warehouse_sources/backend/temporal/data_imports/sources/stytch/stytch.pynew file mode 100644index 000000000000..43383e27ae80--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/stytch/stytch.py@@ -0,0 +1,373 @@+import dataclasses+from collections.abc import Iterator+from datetime import UTC, date, datetime+from typing import Any, Optional++import requests+from structlog.types import FilteringBoundLogger+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.stytch.settings import (+ STYTCH_ENDPOINTS,+ StytchEndpointConfig,+)++LIVE_BASE_URL = "https://api.stytch.com"+TEST_BASE_URL = "https://test.stytch.com"+# Search endpoints accept up to 1000; 500 keeps response bodies (users carry nested auth-method+# arrays) a reasonable size while staying well under the ~100-150 req/min search rate limits.+PAGE_SIZE = 500+# Chunk of organization_ids per member-search request, to keep request bodies bounded.+MEMBER_SEARCH_ORG_CHUNK_SIZE = 100+REQUEST_TIMEOUT_SECONDS = 60+MAX_RETRIES = 5+++class StytchRetryableError(Exception):+ pass+++class StytchAPIError(Exception):+ """Non-2xx Stytch response. The message carries Stytch's `error_type` so permanent+ credential failures can be matched by `get_non_retryable_errors`."""+++class StytchResumeConfig:+ # Search cursor for the page chain currently being walked. For the sessions fan-out this is the+ # users-search cursor of the next page of users to fan out over (the interrupted page's sessions+ # are re-fetched and deduped on session_id by merge).+ cursor: str | None = None+ # Members fan-out bookmark: first organization_id of the chunk currently being processed.+ # Organization ids are sorted before chunking, so chunks are deterministic across resumes.+ org_bookmark: str | None = None+++def base_url_for_project(project_id: str) -> str:+ # Mirrors the official SDK: live projects talk to api.stytch.com, everything else to+ # test.stytch.com. The test environment has its own secrets and data.+ return LIVE_BASE_URL if project_id.startswith("project-live-") else TEST_BASE_URL+++def _make_stytch_session(secret: str) -> requests.Session:+ # Stytch responses carry end-user PII (phone numbers, session IP/user-agent) plus arbitrary+ # customer metadata the name-based scrubber can't anticipate, so keep every credentialed+ # request out of the shared HTTP sample bucket. Redacting the secret guards logged URLs too.+ return make_tracked_session(capture=False, redact_values=(secret,))+++def _format_timestamp(value: Any) -> str:+ """Format an incremental cursor as the RFC 3339 UTC timestamp Stytch's search filters expect."""+ if isinstance(value, datetime):+ utc_value = value.replace(tzinfo=UTC) if value.tzinfo is None else value.astimezone(UTC)+ return utc_value.strftime("%Y-%m-%dT%H:%M:%SZ")+ if isinstance(value, date):+ return datetime.combine(value, datetime.min.time(), tzinfo=UTC).strftime("%Y-%m-%dT%H:%M:%SZ")+ return str(value)+++def build_users_search_body(+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+) -> dict[str, Any]:+ body: dict[str, Any] = {"limit": PAGE_SIZE}+ if should_use_incremental_field and db_incremental_field_last_value is not None:+ # `created_at_greater_than` is a strict server-side filter, so the watermark row itself+ # (max created_at already synced) is not re-fetched.+ body["query"] = {+ "operator": "AND",+ "operands": [+ {+ "filter_name": "created_at_greater_than",+ "filter_value": _format_timestamp(db_incremental_field_last_value),+ }+ ],+ }+ return body+++@retry(+ retry=retry_if_exception_type((StytchRetryableError, requests.ReadTimeout, requests.ConnectionError)),+ stop=stop_after_attempt(MAX_RETRIES),+ wait=wait_exponential_jitter(initial=1, max=60),+ reraise=True,+)+def _request(+ session: requests.Session,+ method: str,+ url: str,+ auth: tuple[str, str],+ logger: FilteringBoundLogger,+ json_body: dict[str, Any] | None = None,+ params: dict[str, Any] | None = None,+) -> dict[str, Any]:+ response = session.request(+ method,+ url,+ auth=auth,+ json=json_body,+ params=params,+ headers={"Content-Type": "application/json"},+ timeout=REQUEST_TIMEOUT_SECONDS,+ )++ if response.status_code == 429 or response.status_code >= 500:+ raise StytchRetryableError(f"Stytch API error (retryable): status={response.status_code}, url={url}")++ if not response.ok:+ # Stytch returns auth failures as 400/401 JSON with a stable `error_type`+ # (e.g. invalid_project_id_authentication); surface it in the message so+ # get_non_retryable_errors can match on it.+ try:+ error_type = response.json().get("error_type", "unknown")+ except Exception:+ error_type = "unknown"+ logger.error(f"Stytch API error: status={response.status_code}, error_type={error_type}, url={url}")+ raise StytchAPIError(f"Stytch API error: status={response.status_code}, error_type={error_type}, url={url}")++ return response.json()+++def validate_credentials(project_id: str, secret: str) -> bool:+ """One cheap authenticated probe. B2C and B2B projects have disjoint API surfaces, so accept+ either the consumer users search or the B2B organizations search succeeding."""+ base_url = base_url_for_project(project_id)+ session = _make_stytch_session(secret)+ for path in ("/v1/users/search", "/v1/b2b/organizations/search"):+ try:+ response = session.post(+ f"{base_url}{path}",+ auth=(project_id, secret),+ json={"limit": 1},+ timeout=10,+ )+ if response.status_code == 200:+ return True+ except Exception:+ continue+ return False+++def check_endpoint_access(project_id: str, secret: str, path: str) -> str | None:+ """Probe one search endpoint. Returns None when reachable (or on transient failure — a blip+ must not mark a table unavailable), or a short reason on a real 4xx denial."""+ base_url = base_url_for_project(project_id)+ try:+ response = _make_stytch_session(secret).post(+ f"{base_url}{path}",+ auth=(project_id, secret),+ json={"limit": 1},+ timeout=10,+ )+ except Exception:+ return None+ if response.ok or response.status_code == 429 or response.status_code >= 500:+ return None+ try:+ error_type = response.json().get("error_type", "unknown")+ except Exception:+ error_type = "unknown"+ return f"Not available for this Stytch project ({error_type})"+++def _iter_search_pages(+ session: requests.Session,+ url: str,+ auth: tuple[str, str],+ logger: FilteringBoundLogger,+ body: dict[str, Any],+ cursor: str | None,+) -> Iterator[tuple[dict[str, Any], str | None]]:+ """Walk a Stytch cursor-search page chain, yielding (page, next_cursor) tuples. The cursor+ rides in the POST body; a null `results_metadata.next_cursor` terminates the chain."""+ while True:+ payload = dict(body)+ if cursor:+ payload["cursor"] = cursor+ page = _request(session, "POST", url, auth, logger, json_body=payload)+ next_cursor = (page.get("results_metadata") or {}).get("next_cursor")+ yield page, next_cursor+ if not next_cursor:+ break+ cursor = next_cursor+++def _get_search_rows(+ session: requests.Session,+ base_url: str,+ auth: tuple[str, str],+ config: StytchEndpointConfig,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[StytchResumeConfig],+ body: dict[str, Any],+) -> Iterator[list[dict[str, Any]]]:+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ cursor = resume.cursor if resume else None+ if cursor:+ logger.debug(f"Stytch: resuming {config.name} from saved cursor")++ for page, next_cursor in _iter_search_pages(session, f"{base_url}{config.path}", auth, logger, body, cursor):+ items = page.get(config.data_key, []) or []+ if items:+ yield items+ # Save AFTER yielding (and only while more pages remain) so a crash re-yields the last+ # page instead of skipping it — merge dedupes on the primary key.+ if next_cursor:+ resumable_source_manager.save_state(StytchResumeConfig(cursor=next_cursor))+++def _get_session_rows(+ session: requests.Session,+ base_url: str,+ auth: tuple[str, str],+ config: StytchEndpointConfig,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[StytchResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ """Fan out over every user, listing their active sessions (one GET per user — Stytch has no+ bulk sessions endpoint). The saved cursor is the users-search cursor of the page being fanned+ out, so a resume re-fetches that page's sessions and merge dedupes on session_id."""+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ cursor = resume.cursor if resume else None+ if cursor:+ logger.debug("Stytch: resuming sessions fan-out from saved users cursor")++ users_body = {"limit": PAGE_SIZE}+ for page, next_cursor in _iter_search_pages(+ session, f"{base_url}/v1/users/search", auth, logger, users_body, cursor+ ):+ rows: list[dict[str, Any]] = []+ for user in page.get("results", []) or []:+ sessions_page = _request(+ session, "GET", f"{base_url}{config.path}", auth, logger, params={"user_id": user["user_id"]}+ )+ rows.extend(sessions_page.get(config.data_key, []) or [])+ if rows:+ yield rows+ if next_cursor:+ resumable_source_manager.save_state(StytchResumeConfig(cursor=next_cursor))+++def _collect_organization_ids(+ session: requests.Session,+ base_url: str,+ auth: tuple[str, str],+ logger: FilteringBoundLogger,+) -> list[str]:+ org_ids: list[str] = []+ for page, _next_cursor in _iter_search_pages(+ session, f"{base_url}/v1/b2b/organizations/search", auth, logger, {"limit": PAGE_SIZE}, None+ ):+ org_ids.extend(org["organization_id"] for org in page.get("organizations", []) or [])+ # Sorted so chunk boundaries are deterministic across resumes (the API's ordering is undocumented).+ return sorted(org_ids)+++def _get_member_rows(+ session: requests.Session,+ base_url: str,+ auth: tuple[str, str],+ config: StytchEndpointConfig,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[StytchResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ """Fan the member search out over chunks of organization_ids (the endpoint requires at least+ one organization_id, so members can't be listed project-wide in one call)."""+ org_ids = _collect_organization_ids(session, base_url, auth, logger)+ chunks = [+ org_ids[i : i + MEMBER_SEARCH_ORG_CHUNK_SIZE] for i in range(0, len(org_ids), MEMBER_SEARCH_ORG_CHUNK_SIZE)+ ]++ # Resolve the saved chunk bookmark. If the bookmarked organization no longer exists (deleted+ # between attempts), start over — merge dedupes re-pulled rows on member_id.+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ remaining = chunks+ resume_cursor: str | None = None+ if resume is not None and resume.org_bookmark is not None:+ for index, chunk in enumerate(chunks):+ if chunk and chunk[0] == resume.org_bookmark:+ remaining = chunks[index:]+ resume_cursor = resume.cursor+ logger.debug(f"Stytch: resuming members fan-out from organization chunk starting {chunk[0]}")+ break++ for index, chunk in enumerate(remaining):+ body = {"limit": PAGE_SIZE, "organization_ids": chunk}+ cursor = resume_cursor+ resume_cursor = None # only the resumed-into chunk uses the saved cursor++ for page, next_cursor in _iter_search_pages(session, f"{base_url}{config.path}", auth, logger, body, cursor):+ items = page.get(config.data_key, []) or []+ if items:+ yield items+ if next_cursor:+ resumable_source_manager.save_state(StytchResumeConfig(cursor=next_cursor, org_bookmark=chunk[0]))++ # Advance the bookmark to the next chunk so a crash between chunks resumes correctly.+ if index + 1 < len(remaining):+ resumable_source_manager.save_state(StytchResumeConfig(cursor=None, org_bookmark=remaining[index + 1][0]))+++def get_rows(+ project_id: str,+ secret: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[StytchResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+) -> Iterator[list[dict[str, Any]]]:+ config = STYTCH_ENDPOINTS[endpoint]+ base_url = base_url_for_project(project_id)+ auth = (project_id, secret)+ # One session reused across every page so urllib3 keeps the connection alive.+ session = _make_stytch_session(secret)++ if config.fan_out == "users":+ yield from _get_session_rows(session, base_url, auth, config, logger, resumable_source_manager)+ elif config.fan_out == "organizations":+ yield from _get_member_rows(session, base_url, auth, config, logger, resumable_source_manager)+ else:+ body = (+ build_users_search_body(should_use_incremental_field, db_incremental_field_last_value)+ if endpoint == "users"+ else {"limit": PAGE_SIZE}+ )+ yield from _get_search_rows(session, base_url, auth, config, logger, resumable_source_manager, body)+++def stytch_source(+ project_id: str,+ secret: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[StytchResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+) -> SourceResponse:+ config = STYTCH_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ project_id=project_id,+ secret=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=config.primary_keys,+ # Stytch does not document a result ordering for its search endpoints, so the incremental+ # watermark must only persist at successful job end — that's desc-mode behavior.+ sort_mode="desc",+ partition_count=1,+ partition_size=1,+ partition_mode="datetime" if config.partition_key else None,+ partition_format="week" if config.partition_key else None,+ partition_keys=[config.partition_key] if config.partition_key else None,+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/stytch/tests/test_stytch.py b/products/warehouse_sources/backend/temporal/data_imports/sources/stytch/tests/test_stytch.pynew file mode 100644index 000000000000..919131968da1--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/stytch/tests/test_stytch.py@@ -0,0 +1,292 @@+from datetime import UTC, date, datetime+from typing import Any++import pytest+from unittest import mock++from products.warehouse_sources.backend.temporal.data_imports.sources.stytch.settings import ENDPOINTS, STYTCH_ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.stytch.stytch import (+ StytchAPIError,+ StytchResumeConfig,+ base_url_for_project,+ build_users_search_body,+ check_endpoint_access,+ get_rows,+ stytch_source,+ validate_credentials,+)++MOCK_PATH = "products.warehouse_sources.backend.temporal.data_imports.sources.stytch.stytch.make_tracked_session"+++def _make_manager(resume_state: StytchResumeConfig | 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(payload: dict[str, Any], status_code: int = 200) -> mock.MagicMock:+ response = mock.MagicMock()+ response.status_code = status_code+ response.ok = status_code < 400+ response.json.return_value = payload+ return response+++def _search_page(data_key: str, items: list[dict[str, Any]], next_cursor: str | None) -> dict[str, Any]:+ return {data_key: items, "results_metadata": {"total": len(items), "next_cursor": next_cursor}}+++class TestBaseUrl:+ @pytest.mark.parametrize(+ "project_id, expected",+ [+ ("project-live-11111111-1111-1111-1111-111111111111", "https://api.stytch.com"),+ ("project-test-11111111-1111-1111-1111-111111111111", "https://test.stytch.com"),+ ],+ )+ def test_environment_routing(self, project_id, expected):+ assert base_url_for_project(project_id) == expected+++class TestBuildUsersSearchBody:+ @pytest.mark.parametrize(+ "value, expected_filter_value",+ [+ (datetime(2026, 1, 2, 3, 4, 5, tzinfo=UTC), "2026-01-02T03:04:05Z"),+ (datetime(2026, 1, 2, 3, 4, 5), "2026-01-02T03:04:05Z"),+ (date(2026, 1, 2), "2026-01-02T00:00:00Z"),+ ("2026-01-02T03:04:05Z", "2026-01-02T03:04:05Z"),+ ],+ )+ def test_incremental_body_uses_rfc3339_created_at_filter(self, value, expected_filter_value):+ body = build_users_search_body(should_use_incremental_field=True, db_incremental_field_last_value=value)+ assert body["query"] == {+ "operator": "AND",+ "operands": [{"filter_name": "created_at_greater_than", "filter_value": expected_filter_value}],+ }++ @pytest.mark.parametrize("should_use, last_value", [(False, datetime(2026, 1, 2, tzinfo=UTC)), (True, None)])+ def test_no_query_without_watermark(self, should_use, last_value):+ body = build_users_search_body(+ should_use_incremental_field=should_use, db_incremental_field_last_value=last_value+ )+ assert "query" not in body+++class TestValidateCredentials:+ @mock.patch(MOCK_PATH)+ def test_consumer_project_valid(self, mock_session):+ mock_session.return_value.post.return_value = _response({}, 200)+ assert validate_credentials("project-live-x", "secret") is True+ # The consumer probe succeeding must short-circuit the B2B probe.+ assert mock_session.return_value.post.call_count == 1++ @mock.patch(MOCK_PATH)+ def test_b2b_project_valid_despite_consumer_surface_failing(self, mock_session):+ mock_session.return_value.post.side_effect = [_response({}, 400), _response({}, 200)]+ assert validate_credentials("project-live-x", "secret") is True++ @mock.patch(MOCK_PATH)+ def test_invalid_credentials(self, mock_session):+ mock_session.return_value.post.return_value = _response({"error_type": "unauthorized_credentials"}, 401)+ assert validate_credentials("project-live-x", "secret") is False++ @mock.patch(MOCK_PATH)+ def test_network_errors_swallowed(self, mock_session):+ mock_session.return_value.post.side_effect = Exception("boom")+ assert validate_credentials("project-live-x", "secret") is False+++class TestGetRowsUsers:+ @mock.patch(MOCK_PATH)+ def test_paginates_via_body_cursor_and_saves_state_after_yield(self, mock_session):+ mock_session.return_value.request.side_effect = [+ _response(_search_page("results", [{"user_id": "u1"}, {"user_id": "u2"}], "cursor-2")),+ _response(_search_page("results", [{"user_id": "u3"}], None)),+ ]++ manager = _make_manager()+ batches = list(get_rows("project-live-x", "secret", "users", mock.MagicMock(), manager))++ assert [item["user_id"] for batch in batches for item in batch] == ["u1", "u2", "u3"]+ second_call = mock_session.return_value.request.call_args_list[1]+ assert second_call.kwargs["json"]["cursor"] == "cursor-2"+ # State saved only while a next page exists, so a completed run restarts cleanly.+ manager.save_state.assert_called_once()+ assert manager.save_state.call_args.args[0].cursor == "cursor-2"++ @mock.patch(MOCK_PATH)+ def test_resumes_from_saved_cursor(self, mock_session):+ mock_session.return_value.request.return_value = _response(_search_page("results", [{"user_id": "u9"}], None))++ manager = _make_manager(StytchResumeConfig(cursor="cursor-5"))+ list(get_rows("project-live-x", "secret", "users", mock.MagicMock(), manager))++ first_call = mock_session.return_value.request.call_args_list[0]+ assert first_call.kwargs["json"]["cursor"] == "cursor-5"++ @mock.patch(MOCK_PATH)+ def test_incremental_filter_sent_on_every_page(self, mock_session):+ mock_session.return_value.request.side_effect = [+ _response(_search_page("results", [{"user_id": "u1"}], "cursor-2")),+ _response(_search_page("results", [{"user_id": "u2"}], None)),+ ]++ list(+ get_rows(+ "project-live-x",+ "secret",+ "users",+ mock.MagicMock(),+ _make_manager(),+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 1, 2, tzinfo=UTC),+ )+ )++ for call in mock_session.return_value.request.call_args_list:+ operands = call.kwargs["json"]["query"]["operands"]+ assert operands[0]["filter_name"] == "created_at_greater_than"++ @mock.patch(MOCK_PATH)+ def test_uses_test_host_for_test_project(self, mock_session):+ mock_session.return_value.request.return_value = _response(_search_page("results", [], None))++ list(get_rows("project-test-x", "secret", "users", mock.MagicMock(), _make_manager()))++ url = mock_session.return_value.request.call_args.args[1]+ assert url == "https://test.stytch.com/v1/users/search"++ @mock.patch(MOCK_PATH)+ def test_auth_error_raises_with_error_type(self, mock_session):+ mock_session.return_value.request.return_value = _response({"error_type": "invalid_secret_authentication"}, 401)++ with pytest.raises(StytchAPIError, match="error_type=invalid_secret_authentication"):+ list(get_rows("project-live-x", "secret", "users", mock.MagicMock(), _make_manager()))+++class TestGetRowsSessions:+ @mock.patch(MOCK_PATH)+ def test_fans_out_one_sessions_request_per_user(self, mock_session):+ mock_session.return_value.request.side_effect = [+ _response(_search_page("results", [{"user_id": "u1"}, {"user_id": "u2"}], None)),+ _response({"sessions": [{"session_id": "s1", "user_id": "u1"}]}),+ _response({"sessions": [{"session_id": "s2", "user_id": "u2"}, {"session_id": "s3", "user_id": "u2"}]}),+ ]++ manager = _make_manager()+ batches = list(get_rows("project-live-x", "secret", "sessions", mock.MagicMock(), manager))++ assert [item["session_id"] for batch in batches for item in batch] == ["s1", "s2", "s3"]+ session_calls = [call for call in mock_session.return_value.request.call_args_list if call.args[0] == "GET"]+ assert [call.kwargs["params"]["user_id"] for call in session_calls] == ["u1", "u2"]+ manager.save_state.assert_not_called()++ @mock.patch(MOCK_PATH)+ def test_saves_users_cursor_between_pages(self, mock_session):+ mock_session.return_value.request.side_effect = [+ _response(_search_page("results", [{"user_id": "u1"}], "cursor-2")),+ _response({"sessions": [{"session_id": "s1", "user_id": "u1"}]}),+ _response(_search_page("results", [], None)),+ ]++ manager = _make_manager()+ list(get_rows("project-live-x", "secret", "sessions", mock.MagicMock(), manager))++ manager.save_state.assert_called_once()+ assert manager.save_state.call_args.args[0].cursor == "cursor-2"+++class TestGetRowsMembers:+ @mock.patch(MOCK_PATH)+ def test_fans_out_over_sorted_org_chunks(self, mock_session):+ mock_session.return_value.request.side_effect = [+ # Org enumeration returns unsorted ids across two pages.+ _response(_search_page("organizations", [{"organization_id": "org-b"}], "org-cursor-2")),+ _response(_search_page("organizations", [{"organization_id": "org-a"}], None)),+ _response(_search_page("members", [{"member_id": "m1"}], None)),+ ]++ batches = list(get_rows("project-live-x", "secret", "members", mock.MagicMock(), _make_manager()))++ assert [item["member_id"] for batch in batches for item in batch] == ["m1"]+ member_call = mock_session.return_value.request.call_args_list[2]+ assert member_call.kwargs["json"]["organization_ids"] == ["org-a", "org-b"]++ @mock.patch(MOCK_PATH)+ def test_resume_bookmark_skips_completed_chunks(self, mock_session):+ org_pages = [+ _response(+ _search_page(+ "organizations",+ [{"organization_id": f"org-{i}"} for i in range(150)],+ None,+ )+ ),+ _response(_search_page("members", [{"member_id": "m-late"}], None)),+ ]+ mock_session.return_value.request.side_effect = org_pages++ # 150 sorted orgs chunk into [0..99] and [100..149]; the bookmark points at chunk two.+ sorted_ids = sorted(f"org-{i}" for i in range(150))+ manager = _make_manager(StytchResumeConfig(cursor="member-cursor-3", org_bookmark=sorted_ids[100]))+ list(get_rows("project-live-x", "secret", "members", mock.MagicMock(), manager))++ member_calls = [+ call+ for call in mock_session.return_value.request.call_args_list+ if call.args[1].endswith("/members/search")+ ]+ assert len(member_calls) == 1+ assert member_calls[0].kwargs["json"]["organization_ids"] == sorted_ids[100:]+ assert member_calls[0].kwargs["json"]["cursor"] == "member-cursor-3"+++class TestStytchSourceResponse:+ @pytest.mark.parametrize("endpoint", list(ENDPOINTS))+ def test_response_metadata_per_endpoint(self, endpoint):+ config = STYTCH_ENDPOINTS[endpoint]+ response = stytch_source("project-live-x", "secret", endpoint, mock.MagicMock(), _make_manager())++ assert response.name == endpoint+ assert response.primary_keys == config.primary_keys+ # Stytch search ordering is undocumented, so the watermark must only persist at job end.+ assert response.sort_mode == "desc"+ if config.partition_key:+ assert response.partition_mode == "datetime"+ assert response.partition_keys == [config.partition_key]+ else:+ assert response.partition_mode is None+ assert response.partition_keys is None++ @pytest.mark.parametrize("config", list(STYTCH_ENDPOINTS.values()))+ def test_partition_keys_are_stable_creation_fields(self, config):+ if config.partition_key:+ assert config.partition_key == "created_at"+++class TestHttpSampleCaptureDisabled:+ """Stytch responses carry end-user PII, so every credentialed request path must build its+ tracked session with capture disabled and the secret redacted — reverting either leaks PII+ into the shared HTTP sample bucket."""++ def _drive_validate(self, session: mock.MagicMock) -> None:+ session.post.return_value = _response({}, 200)+ validate_credentials("project-live-x", "secret")++ def _drive_check_access(self, session: mock.MagicMock) -> None:+ session.post.return_value = _response({}, 200)+ check_endpoint_access("project-live-x", "secret", "/v1/users/search")++ def _drive_get_rows(self, session: mock.MagicMock) -> None:+ session.request.return_value = _response(_search_page("results", [], None))+ list(get_rows("project-live-x", "secret", "users", mock.MagicMock(), _make_manager()))++ @pytest.mark.parametrize("driver", ["_drive_validate", "_drive_check_access", "_drive_get_rows"])+ @mock.patch(MOCK_PATH)+ def test_credentialed_paths_disable_capture_and_redact_secret(self, mock_session, driver):+ getattr(self, driver)(mock_session.return_value)++ mock_session.assert_called_with(capture=False, redact_values=("secret",))diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/stytch/tests/test_stytch_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/stytch/tests/test_stytch_source.pynew file mode 100644index 000000000000..8d95f74c550d--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/stytch/tests/test_stytch_source.py@@ -0,0 +1,155 @@+import pytest+from unittest import mock++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType++from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import StytchSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.stytch.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.stytch.source import StytchSource+from products.warehouse_sources.backend.temporal.data_imports.sources.stytch.stytch import StytchResumeConfig+from products.warehouse_sources.backend.types import ExternalDataSourceType+++class TestStytchSource:+ def setup_method(self):+ self.source = StytchSource()+ self.team_id = 123+ self.config = StytchSourceConfig(project_id="project-live-x", secret="secret-live-x")++ def test_source_type(self):+ assert self.source.source_type == ExternalDataSourceType.STYTCH++ def test_get_source_config(self):+ config = self.source.get_source_config++ assert config.name.value == "Stytch"+ assert config.label == "Stytch"+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.unreleasedSource is None+ assert config.iconPath == "/static/services/stytch.png"++ field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]+ assert field_names == ["project_id", "secret"]++ def test_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 == "secret")+ assert secret_field.type == SourceFieldInputConfigType.PASSWORD+ assert secret_field.secret is True+ assert secret_field.required is True++ @pytest.mark.parametrize(+ "observed_error",+ [+ "Stytch API error: status=400, error_type=invalid_project_id_authentication, url=https://api.stytch.com/v1/users/search",+ "Stytch API error: status=401, error_type=unauthorized_credentials, url=https://test.stytch.com/v1/users/search",+ "Stytch API error: status=401, error_type=invalid_secret_authentication, url=https://api.stytch.com/v1/sessions",+ ],+ )+ def test_non_retryable_errors_match_auth_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(+ "transient_error",+ [+ "Stytch API error (retryable): status=429, url=https://api.stytch.com/v1/users/search",+ "Stytch API error: status=400, error_type=query_params_invalid, url=https://api.stytch.com/v1/users/search",+ ],+ )+ def test_non_retryable_errors_do_not_match_transient_or_query_errors(self, transient_error):+ non_retryable_errors = self.source.get_non_retryable_errors()+ assert not any(key in transient_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)+ incremental = {schema.name for schema in schemas if schema.supports_incremental}+ # Only the users search exposes a server-side timestamp filter (created_at_greater_than).+ assert incremental == {"users"}++ def test_expensive_and_b2b_tables_are_off_by_default(self):+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}++ assert schemas["users"].should_sync_default is True+ assert schemas["sessions"].should_sync_default is False+ assert schemas["organizations"].should_sync_default is False+ assert schemas["members"].should_sync_default is False++ def test_get_schemas_filtered_by_names(self):+ schemas = self.source.get_schemas(self.config, self.team_id, names=["users"])+ assert [schema.name for schema in schemas] == ["users"]++ @pytest.mark.parametrize(+ "mock_return, expected_valid, expected_message",+ [+ (True, True, None),+ (False, False, "Invalid Stytch project ID or secret"),+ ],+ )+ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.stytch.source.validate_stytch_credentials"+ )+ def test_validate_credentials(self, mock_validate, mock_return, expected_valid, expected_message):+ mock_validate.return_value = mock_return++ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id)++ assert is_valid is expected_valid+ assert error_message == expected_message+ mock_validate.assert_called_once_with(self.config.project_id, self.config.secret)++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.stytch.source.check_endpoint_access")+ def test_endpoint_permissions_probe_each_surface_once(self, mock_check):+ # A consumer (B2C) project: the B2B surface denies, the consumer surface is fine.+ mock_check.side_effect = lambda project_id, secret, path: (+ "Not available for this Stytch project (organization_not_found)" if "/b2b/" in path else None+ )++ permissions = self.source.get_endpoint_permissions(+ self.config, self.team_id, ["users", "sessions", "organizations", "members"]+ )++ assert permissions["users"] is None+ assert permissions["sessions"] is None+ assert permissions["organizations"] is not None+ assert permissions["members"] is not None+ # One probe per surface, not per endpoint.+ assert mock_check.call_count == 2++ def test_get_resumable_source_manager_binds_resume_config(self):+ manager = self.source.get_resumable_source_manager(mock.MagicMock())++ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is StytchResumeConfig++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.stytch.source.stytch_source")+ def test_source_for_pipeline_plumbs_arguments(self, mock_stytch_source):+ inputs = mock.MagicMock()+ inputs.schema_name = "users"+ inputs.should_use_incremental_field = True+ inputs.db_incremental_field_last_value = "2026-01-02T03:04:05Z"+ manager = mock.MagicMock()++ self.source.source_for_pipeline(self.config, manager, inputs)++ kwargs = mock_stytch_source.call_args.kwargs+ assert kwargs["project_id"] == "project-live-x"+ assert kwargs["secret"] == "secret-live-x"+ assert kwargs["endpoint"] == "users"+ assert kwargs["resumable_source_manager"] is manager+ assert kwargs["should_use_incremental_field"] is True+ assert kwargs["db_incremental_field_last_value"] == "2026-01-02T03:04:05Z"++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.stytch.source.stytch_source")+ def test_source_for_pipeline_omits_last_value_on_full_refresh(self, mock_stytch_source):+ inputs = mock.MagicMock()+ inputs.schema_name = "sessions"+ inputs.should_use_incremental_field = False+ inputs.db_incremental_field_last_value = "2026-01-02T03:04:05Z"++ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)++ assert mock_stytch_source.call_args.kwargs["db_incremental_field_last_value"] is None