: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): add 23 tables to the Clerk source (#73848)
Tom Owers3a14e1afc4d4
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/clerk/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/clerk/canonical_descriptions.pyindex 8fc3442a26c5..5ba28cdaa34a 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/clerk/canonical_descriptions.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/clerk/canonical_descriptions.py@@ -81,4 +81,356 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {public_metadata="Metadata visible to the frontend and backend.",),},+ "sessions": {+ "description": "A session created when a user signs in, tracking that sign-in until it ends or expires.",+ "docs_url": "https://clerk.com/docs/reference/backend-api/tag/Sessions",+ "columns": _columns(+ user_id="ID of the user the session belongs to.",+ client_id="ID of the client the session was created on.",+ actor="Details of the actor impersonating the user, when the session was created by impersonation.",+ status="Status of the session (abandoned, active, ended, expired, removed, replaced, or revoked).",+ last_active_organization_id="ID of the organization that was last active in the session.",+ last_active_at="Time the session was last active, as a Unix timestamp in milliseconds.",+ latest_activity="Details of the latest activity on the session, such as device, browser and location.",+ expire_at="Time the session expires, as a Unix timestamp in milliseconds.",+ abandon_at="Time the session is abandoned, as a Unix timestamp in milliseconds.",+ ),+ },+ "clients": {+ "description": "A client representing a browser or native app the Clerk instance has seen.",+ "docs_url": "https://clerk.com/docs/reference/backend-api/tag/Clients",+ "columns": _columns(+ session_ids="IDs of the sessions that belong to the client.",+ sessions="The sessions that belong to the client.",+ sign_in_id="ID of the sign-in attempt in progress on the client.",+ sign_up_id="ID of the sign-up attempt in progress on the client.",+ last_active_session_id="ID of the session that was last active on the client.",+ last_authentication_strategy="The authentication strategy last used to authenticate on the client.",+ ),+ },+ "organization_invitations": {+ "description": "An invitation asking a user to join an organization in the Clerk instance.",+ "docs_url": "https://clerk.com/docs/reference/backend-api/tag/Organization-Invitations",+ "columns": _columns(+ email_address="Email address the invitation was sent to.",+ role="Key of the role the invitee will get in the organization.",+ role_name="Display name of the role the invitee will get.",+ organization_id="ID of the organization the invitee is invited to.",+ inviter_id="ID of the user who sent the invitation.",+ public_inviter_data="Public profile data of the user who sent the invitation.",+ status="Status of the invitation (pending, accepted, revoked, or expired).",+ url="URL the invitee follows to accept the invitation.",+ expires_at="Time the invitation expires, as a Unix timestamp in milliseconds.",+ public_organization_data="Public data of the organization the invitee is invited to.",+ public_metadata="Metadata visible to the frontend and backend.",+ private_metadata="Metadata visible only to the backend.",+ ),+ },+ "organization_domains": {+ "description": "A verified email domain attached to an organization, used to enroll matching users.",+ "docs_url": "https://clerk.com/docs/reference/backend-api/tag/Organization-Domains",+ "columns": _columns(+ organization_id="ID of the organization the domain belongs to.",+ name="The domain name.",+ enrollment_mode="How users with a matching email are enrolled (e.g. manual_invitation, automatic_invitation).",+ affiliation_email_address="Email address used to verify affiliation between the domain and the organization.",+ affiliation_verification="Verification details for the affiliation between the domain and the organization.",+ ownership_verification="Verification details for the DNS ownership proof of the domain.",+ total_pending_invitations="Number of pending invitations associated with the domain.",+ total_pending_suggestions="Number of pending suggestions associated with the domain.",+ public_organization_data="Public data of the organization the domain belongs to.",+ ),+ },+ "organization_roles": {+ "description": "A role that can be assigned to members of an organization, with the permissions it grants.",+ "docs_url": "https://clerk.com/docs/reference/backend-api/tag/Organization-Roles",+ "columns": _columns(+ name="Display name of the role.",+ key="Unique key of the role (e.g. org:admin).",+ description="Description of what the role is for.",+ is_creator_eligible="Whether the role can be used as the organization creator role.",+ permissions="Permissions granted by the role.",+ ),+ },+ "organization_permissions": {+ "description": "A permission that can be granted to an organization role.",+ "docs_url": "https://clerk.com/docs/reference/backend-api/tag/Organization-Permissions",+ "columns": _columns(+ name="Display name of the permission.",+ key="Unique key of the permission (e.g. org:members:manage).",+ description="Description of what the permission allows.",+ type="Whether the permission is a system or a user-defined one.",+ ),+ },+ "role_sets": {+ "description": "A named set of organization roles, including the default and creator roles it assigns.",+ "docs_url": "https://clerk.com/docs/reference/backend-api/tag/Role-Sets",+ "columns": _columns(+ name="Display name of the role set.",+ key="Unique key of the role set (e.g. role_set:default).",+ description="Description of the role set.",+ roles="The roles contained in the role set.",+ default_role="Role assigned to new organization members.",+ creator_role="Role assigned to the creator of an organization.",+ type="Whether the role set is the initial one or a custom one.",+ role_set_migration="Details of an in-progress migration to this role set, when one is running.",+ ),+ },+ "waitlist_entries": {+ "description": "An email address on the instance waitlist, with where it is in the waitlist flow.",+ "docs_url": "https://clerk.com/docs/reference/backend-api/tag/Waitlist-Entries",+ "columns": _columns(+ email_address="Email address that joined the waitlist.",+ status="Status of the entry (pending, invited, completed, or rejected).",+ is_locked="Whether the entry is locked while a batch action processes it.",+ invitation="The invitation sent to the entry, if one has been sent.",+ ),+ },+ "allowlist_identifiers": {+ "description": "An email address, phone number or domain allowed to sign up to the Clerk instance.",+ "docs_url": "https://clerk.com/docs/reference/backend-api/tag/Allow-list-Block-list",+ "columns": _columns(+ identifier="The allowed email address or phone number.",+ identifier_type="Type of the identifier (e.g. email_address, phone_number, web3_wallet).",+ invitation_id="ID of the invitation created alongside the identifier, if any.",+ instance_id="ID of the Clerk instance the identifier belongs to.",+ ),+ },+ "blocklist_identifiers": {+ "description": "An email address, domain, phone number or wallet blocked from signing up to the instance.",+ "docs_url": "https://clerk.com/docs/reference/backend-api/tag/Allow-list-Block-list",+ "columns": _columns(+ identifier="The blocked email address, email domain, phone number or web3 wallet.",+ identifier_type="Type of the identifier (e.g. email_address, phone_number, web3_wallet).",+ instance_id="ID of the Clerk instance the identifier belongs to.",+ ),+ },+ "domains": {+ "description": "A primary or satellite domain the Clerk instance is served from.",+ "docs_url": "https://clerk.com/docs/reference/backend-api/tag/Domains",+ "columns": {+ "id": _COMMON_COLUMNS["id"],+ "object": _COMMON_COLUMNS["object"],+ "name": "The domain name.",+ "is_satellite": "Whether the domain is a satellite of the instance's primary domain.",+ "frontend_api_url": "URL of the Frontend API served from the domain.",+ "accounts_portal_url": "URL of the Account Portal for the domain; null for satellite domains.",+ "proxy_url": "URL of the proxy that forwards Frontend API requests, when a proxy is configured.",+ "development_origin": "Origin the domain accepts requests from in development instances.",+ "cname_targets": "CNAME records that need to be set up for the domain.",+ },+ },+ "saml_connections": {+ "description": "A SAML connection linking the Clerk instance to an external identity provider.",+ "docs_url": "https://clerk.com/docs/reference/backend-api/tag/SAML-Connections",+ "columns": _columns(+ name="Display name of the connection.",+ domain="Primary email domain the connection applies to.",+ domains="All email domains the connection applies to.",+ idp_entity_id="Entity ID of the identity provider.",+ idp_sso_url="Single sign-on URL of the identity provider.",+ idp_certificate_issued_at="Start of the identity provider certificate's validity window, as a Unix timestamp in milliseconds.",+ idp_certificate_expires_at="End of the identity provider certificate's validity window, as a Unix timestamp in milliseconds.",+ acs_url="Assertion consumer service URL Clerk exposes for the connection.",+ sp_entity_id="Entity ID Clerk uses as the service provider.",+ organization_id="ID of the organization the connection is attached to, if any.",+ attribute_mapping="Mapping from identity provider attributes to Clerk user fields.",+ active="Whether the connection is active.",+ provider="The identity provider backing the connection.",+ user_count="Number of users signed in through the connection.",+ sync_user_attributes="Whether user attributes are refreshed from the identity provider on each sign-in.",+ enterprise_connection_id="ID of the enterprise connection this SAML connection belongs to.",+ ),+ },+ "enterprise_connections": {+ "description": "An enterprise SSO connection (SAML, OIDC or EASIE) configured on the Clerk instance.",+ "docs_url": "https://clerk.com/docs/reference/backend-api/tag/Enterprise-Connections",+ "columns": _columns(+ name="Display name of the connection.",+ provider="The identity provider backing the connection.",+ logo_public_url="URL of the identity provider's logo.",+ active="Whether the connection is active.",+ domains="Email domains associated with the connection.",+ organization_id="ID of the organization the connection is linked to, if any.",+ sync_user_attributes="Whether user attributes are refreshed from the identity provider on each sign-in.",+ custom_attributes="Custom attributes mapped from the identity provider onto the user profile.",+ saml_connection="SAML configuration, present when the connection uses SAML.",+ oauth_config="OAuth configuration, present when the connection uses OIDC or EASIE.",+ ),+ },+ "oauth_applications": {+ "description": "An OAuth application registered on the Clerk instance so other apps can sign users in with it.",+ "docs_url": "https://clerk.com/docs/reference/backend-api/tag/OAuth-Applications",+ "columns": _columns(+ instance_id="ID of the Clerk instance the application belongs to.",+ name="Display name of the application.",+ client_id="The application's OAuth client ID.",+ client_uri="Homepage URL of the application.",+ dynamically_registered="Whether the application was registered through dynamic client registration.",+ consent_screen_enabled="Whether users are shown a consent screen.",+ pkce_required="Whether the application must use PKCE.",+ public="Whether the application is a public client.",+ scopes="Scopes the application may request.",+ redirect_uris="Redirect URIs the application is allowed to use.",+ authorize_url="Authorization endpoint for the application.",+ token_fetch_url="Token endpoint for the application.",+ user_info_url="User info endpoint for the application.",+ discovery_url="OpenID Connect discovery endpoint for the application.",+ ),+ },+ "machines": {+ "description": "A machine identity that can authenticate to the Clerk instance without a user.",+ "docs_url": "https://clerk.com/docs/reference/backend-api/tag/Machines",+ "columns": _columns(+ name="Display name of the machine.",+ instance_id="ID of the Clerk instance the machine belongs to.",+ default_token_ttl="Default lifetime, in seconds, of tokens the machine creates.",+ scoped_machines="Other machines this machine is allowed to reach.",+ ),+ },+ "api_keys": {+ "description": "An API key issued by the Clerk instance to a user, organization or machine.",+ "docs_url": "https://clerk.com/docs/reference/backend-api/tag/API-Keys",+ "columns": _columns(+ type="Type of the key.",+ subject="ID of the user, organization or machine the key belongs to.",+ name="Display name of the key.",+ description="Description of what the key is for.",+ claims="Custom claims embedded in tokens minted from the key.",+ scopes="Scopes granted to the key.",+ revoked="Whether the key has been revoked.",+ revocation_reason="Why the key was revoked.",+ expired="Whether the key has expired.",+ expiration="Time the key expires, as a Unix timestamp in milliseconds.",+ created_by="ID of the user who created the key.",+ last_used_at="Time the key was last used, as a Unix timestamp in milliseconds.",+ ),+ },+ "m2m_tokens": {+ "description": "A machine-to-machine token minted for a machine identity.",+ "docs_url": "https://clerk.com/docs/reference/backend-api/tag/M2M-Tokens",+ "columns": _columns(+ subject="ID of the machine the token was minted for.",+ claims="Custom claims embedded in the token.",+ scopes="Machines the token is allowed to reach.",+ revoked="Whether the token has been revoked.",+ revocation_reason="Why the token was revoked.",+ expired="Whether the token has expired.",+ expiration="Time the token expires, as a Unix timestamp in milliseconds.",+ last_used_at="Time the token was last used, as a Unix timestamp in milliseconds.",+ ),+ },+ "redirect_urls": {+ "description": "A URL allowed as a redirect target for the Clerk instance's authentication flows.",+ "docs_url": "https://clerk.com/docs/reference/backend-api/tag/Redirect-URLs",+ "columns": _columns(+ url="The allowed redirect URL.",+ ),+ },+ "jwt_templates": {+ "description": "A template describing the claims Clerk puts into JWTs it mints for your app.",+ "docs_url": "https://clerk.com/docs/reference/backend-api/tag/JWT-Templates",+ "columns": _columns(+ name="Display name of the template.",+ claims="The claims the template adds to the token.",+ lifetime="Lifetime of tokens issued from the template, in seconds.",+ allowed_clock_skew="Clock skew tolerated when validating tokens, in seconds.",+ custom_signing_key="Whether the template signs tokens with a custom key.",+ signing_algorithm="Algorithm used to sign tokens issued from the template.",+ ),+ },+ "email_templates": {+ "description": "An email template the Clerk instance sends, either the Clerk default or your override.",+ "docs_url": "https://clerk.com/docs/reference/backend-api/tag/Templates",+ "columns": _columns(+ instance_id="ID of the Clerk instance the template belongs to.",+ resource_type="Whether the template is a system default or a user override.",+ template_type="The template's channel; always email for this table.",+ name="Display name of the template.",+ slug="Machine-friendly name of the template.",+ position="Position of the template in the template listing.",+ subject="Subject line of the email.",+ markup="Editor markup the body is generated from.",+ body="The template body before variable interpolation.",+ available_variables="Variables that can be used in the template body.",+ required_variables="Variables the template body must contain.",+ from_email_name="Local part of the address the email is sent from.",+ reply_to_email_name="Local part of the reply-to address.",+ delivered_by_clerk="Whether Clerk delivers the email, rather than your own provider.",+ enabled="Whether the template is enabled.",+ ),+ },+ "sms_templates": {+ "description": "An SMS template the Clerk instance sends, either the Clerk default or your override.",+ "docs_url": "https://clerk.com/docs/reference/backend-api/tag/Templates",+ "columns": _columns(+ instance_id="ID of the Clerk instance the template belongs to.",+ resource_type="Whether the template is a system default or a user override.",+ template_type="The template's channel; always sms for this table.",+ name="Display name of the template.",+ slug="Machine-friendly name of the template.",+ position="Position of the template in the template listing.",+ markup="Editor markup the body is generated from.",+ body="The template body before variable interpolation.",+ available_variables="Variables that can be used in the template body.",+ required_variables="Variables the template body must contain.",+ delivered_by_clerk="Whether Clerk delivers the message, rather than your own provider.",+ enabled="Whether the template is enabled.",+ ),+ },+ "commerce_plans": {+ "description": "A billing plan users or organizations can subscribe to through Clerk billing.",+ "docs_url": "https://clerk.com/docs/reference/backend-api/tag/Commerce",+ "columns": {+ "id": _COMMON_COLUMNS["id"],+ "object": _COMMON_COLUMNS["object"],+ "name": "The plan's name.",+ "description": "Description of the plan.",+ "slug": "URL-friendly slug for the plan.",+ "product_id": "ID of the product the plan belongs to.",+ "amount": "Monthly amount for the plan, in cents.",+ "amount_formatted": "Monthly amount formatted for display (e.g. $49.99).",+ "annual_amount": "Total annual amount for the plan, in cents.",+ "annual_monthly_amount": "Monthly amount when billed annually, in cents.",+ "currency": "Currency code the plan is priced in (e.g. USD).",+ "currency_symbol": "Currency symbol the plan is priced in (e.g. $).",+ "is_default": "Whether this is the instance's default plan.",+ "is_recurring": "Whether the plan bills on a recurring basis.",+ "publicly_visible": "Whether the plan is shown publicly.",+ "has_base_fee": "Whether the plan charges a base fee.",+ "payer_type": "Payer types allowed to subscribe to the plan.",+ "for_payer_type": "Payer type the plan is designed for (user or org).",+ "period": "Billing period for the plan.",+ "interval": "Billing interval for the plan.",+ "features": "Features included in the plan.",+ "free_trial_enabled": "Whether the plan offers a free trial.",+ "free_trial_days": "Length of the plan's free trial, in days.",+ },+ },+ "commerce_subscription_items": {+ "description": "A subscription to a Clerk billing plan held by a user or an organization.",+ "docs_url": "https://clerk.com/docs/reference/backend-api/tag/Commerce",+ "columns": _columns(+ instance_id="ID of the Clerk instance the subscription belongs to.",+ status="Current status of the subscription (e.g. active, ended, past_due, upcoming, free_trial).",+ plan_id="ID of the plan the subscription is for.",+ price_id="ID of the price the subscription is billed at.",+ plan="The plan the subscription is for.",+ plan_period="Billing period of the subscription.",+ payment_source_id="ID of the payment source the subscription is charged to.",+ payer_id="ID of the user or organization paying for the subscription.",+ payer="The user or organization paying for the subscription.",+ lifetime_paid="Total amount paid over the lifetime of the subscription.",+ amount="Current amount charged for the subscription.",+ next_invoice="Details of the subscription's next invoice.",+ next_payment="Details of the subscription's next payment.",+ is_free_trial="Whether the subscription is currently in a free trial.",+ period_start="Start of the current billing period, as a Unix timestamp in milliseconds.",+ period_end="End of the current billing period, as a Unix timestamp in milliseconds.",+ proration_date="Date used for proration calculations.",+ canceled_at="Time the subscription was canceled, as a Unix timestamp in milliseconds.",+ past_due_at="Time the subscription became past due, as a Unix timestamp in milliseconds.",+ ended_at="Time the subscription ended, as a Unix timestamp in milliseconds.",+ ),+ },}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/clerk/clerk.py b/products/warehouse_sources/backend/temporal/data_imports/sources/clerk/clerk.pyindex 789ee7bf623d..f864694f2733 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/clerk/clerk.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/clerk/clerk.py@@ -1,3 +1,4 @@+import functoolsimport dataclassesfrom typing import Any, Optional@@ -46,7 +47,7 @@ def get_resource(name: str) -> EndpointResource:# Only set data_selector for endpoints that return wrapped responses {data: [...], total_count: ...}if config.is_wrapped_response:- endpoint_config["data_selector"] = "data"+ endpoint_config["data_selector"] = config.data_keyreturn {"name": config.name,@@ -60,10 +61,11 @@ def get_resource(name: str) -> EndpointResource:class ClerkPaginator(BasePaginator):"""Paginator for Clerk API using offset-based pagination."""- def __init__(self, limit: int = 100) -> None:+ def __init__(self, limit: int = 100, data_key: str = "data") -> None:super().__init__()self._limit = limitself._offset = 0+ self._data_key = data_keydef init_request(self, request: Request) -> None:# Emit the seeded offset on the first request so resume starts from the@@ -91,9 +93,10 @@ class ClerkPaginator(BasePaginator):# Clerk endpoints return either:# - Direct array: /users, /invitations# - Wrapped object {data: [...], total_count: ...}: /organizations, /organization_memberships+ # (/m2m_tokens wraps under `m2m_tokens` instead of `data`)total_count: Optional[int] = None- if isinstance(res, dict) and "data" in res:- items = res["data"]+ if isinstance(res, dict) and self._data_key in res:+ items = res[self._data_key]raw_total = res.get("total_count")if isinstance(raw_total, int):total_count = raw_total@@ -143,6 +146,17 @@ TIMESTAMP_FIELDS = ["password_last_updated_at","legal_accepted_at","expires_at", # invitations+ "expire_at", # sessions+ "abandon_at", # sessions+ "expiration", # api_keys, m2m_tokens+ "last_used_at", # api_keys, m2m_tokens+ "idp_certificate_issued_at", # saml_connections+ "idp_certificate_expires_at", # saml_connections+ "period_start", # commerce_subscription_items+ "period_end", # commerce_subscription_items+ "canceled_at", # commerce_subscription_items+ "past_due_at", # commerce_subscription_items+ "ended_at", # commerce_subscription_items]@@ -156,6 +170,30 @@ def _convert_timestamps(item: dict[str, Any]) -> dict[str, Any]:return item+# Redeemable invitation links Clerk returns on invitation rows. Anyone who can read the+# warehouse table could otherwise copy one of these and accept the invitation, so drop them+# before the row is stored. Values are dotted paths into each endpoint's row shape.+SENSITIVE_FIELDS_BY_ENDPOINT: dict[str, tuple[str, ...]] = {+ "invitations": ("url",),+ "organization_invitations": ("url",),+ "waitlist_entries": ("invitation.url",),+}+++def _strip_sensitive_fields(item: dict[str, Any], paths: tuple[str, ...]) -> dict[str, Any]:+ """Remove the given dotted-path fields from a row in place."""+ for path in paths:+ parts = path.split(".")+ target: Any = item+ for part in parts[:-1]:+ target = target.get(part) if isinstance(target, dict) else None+ if target is None:+ break+ if isinstance(target, dict):+ target.pop(parts[-1], None)+ return item++def validate_credentials(secret_key: str) -> tuple[bool, str | None]:"""Validate Clerk API credentials by making a test request."""url = "https://api.clerk.com/v1/users"@@ -201,7 +239,7 @@ def clerk_source("headers": {"Content-Type": "application/json",},- "paginator": ClerkPaginator(limit=endpoint_config.page_size),+ "paginator": ClerkPaginator(limit=endpoint_config.page_size, data_key=endpoint_config.data_key),},"resource_defaults": {"write_disposition": "replace",@@ -235,6 +273,17 @@ def clerk_source(initial_paginator_state=initial_paginator_state,).add_map(_convert_timestamps)+ sensitive_fields = SENSITIVE_FIELDS_BY_ENDPOINT.get(endpoint)+ if sensitive_fields:+ resource = resource.add_map(functools.partial(_strip_sensitive_fields, paths=sensitive_fields))++ if endpoint_config.partition_key is None:+ return SourceResponse(+ name=endpoint,+ items=lambda: resource,+ primary_keys=["id"],+ )+return SourceResponse(name=endpoint,items=lambda: resource,diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/clerk/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/clerk/settings.pyindex 7e1285bfe434..97a7e1db72a5 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/clerk/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/clerk/settings.py@@ -1,14 +1,19 @@from dataclasses import dataclass+from typing import Optional@dataclassclass ClerkEndpointConfig:name: strpath: str- partition_key: str = "created_at"+ # `None` for endpoints whose objects carry no creation timestamp, so there is nothing stable+ # to partition on (Clerk's `/domains` and `/commerce/plans`).+ partition_key: Optional[str] = "created_at"page_size: int = 100 # Clerk default, max is 500# Some Clerk endpoints return {data: [...], total_count: ...}, others return direct arraysis_wrapped_response: bool = False+ # Key holding the row array in a wrapped response — `/m2m_tokens` uses `m2m_tokens`, not `data`.+ data_key: str = "data"# Note: Clerk API does not support filtering by updated_at, so only full refresh is supported.@@ -19,6 +24,54 @@ CLERK_ENDPOINTS: dict[str, ClerkEndpointConfig] = {name="organization_memberships", path="/organization_memberships", is_wrapped_response=True),"invitations": ClerkEndpointConfig(name="invitations", path="/invitations"),+ "sessions": ClerkEndpointConfig(name="sessions", path="/sessions"),+ "clients": ClerkEndpointConfig(name="clients", path="/clients"),+ "organization_invitations": ClerkEndpointConfig(+ name="organization_invitations", path="/organization_invitations", is_wrapped_response=True+ ),+ "organization_domains": ClerkEndpointConfig(+ name="organization_domains", path="/organization_domains", is_wrapped_response=True+ ),+ "organization_roles": ClerkEndpointConfig(+ name="organization_roles", path="/organization_roles", is_wrapped_response=True+ ),+ "organization_permissions": ClerkEndpointConfig(+ name="organization_permissions", path="/organization_permissions", is_wrapped_response=True+ ),+ "role_sets": ClerkEndpointConfig(name="role_sets", path="/role_sets", is_wrapped_response=True),+ "waitlist_entries": ClerkEndpointConfig(+ name="waitlist_entries", path="/waitlist_entries", is_wrapped_response=True+ ),+ "allowlist_identifiers": ClerkEndpointConfig(name="allowlist_identifiers", path="/allowlist_identifiers"),+ "blocklist_identifiers": ClerkEndpointConfig(+ name="blocklist_identifiers", path="/blocklist_identifiers", is_wrapped_response=True+ ),+ "domains": ClerkEndpointConfig(name="domains", path="/domains", partition_key=None, is_wrapped_response=True),+ "saml_connections": ClerkEndpointConfig(+ name="saml_connections", path="/saml_connections", is_wrapped_response=True+ ),+ "enterprise_connections": ClerkEndpointConfig(+ name="enterprise_connections", path="/enterprise_connections", is_wrapped_response=True+ ),+ "oauth_applications": ClerkEndpointConfig(+ name="oauth_applications", path="/oauth_applications", is_wrapped_response=True+ ),+ "machines": ClerkEndpointConfig(name="machines", path="/machines", is_wrapped_response=True),+ # /api_keys and /m2m_tokens cap `limit` at 100 rather than 500.+ "api_keys": ClerkEndpointConfig(name="api_keys", path="/api_keys", is_wrapped_response=True),+ "m2m_tokens": ClerkEndpointConfig(+ name="m2m_tokens", path="/m2m_tokens", is_wrapped_response=True, data_key="m2m_tokens"+ ),+ "redirect_urls": ClerkEndpointConfig(name="redirect_urls", path="/redirect_urls"),+ "jwt_templates": ClerkEndpointConfig(name="jwt_templates", path="/jwt_templates"),+ "email_templates": ClerkEndpointConfig(name="email_templates", path="/templates/email"),+ "sms_templates": ClerkEndpointConfig(name="sms_templates", path="/templates/sms"),+ "commerce_plans": ClerkEndpointConfig(+ name="commerce_plans", path="/commerce/plans", partition_key=None, is_wrapped_response=True+ ),+ "commerce_subscription_items": ClerkEndpointConfig(+ name="commerce_subscription_items", path="/commerce/subscription_items", is_wrapped_response=True+ ),}ENDPOINTS = tuple(CLERK_ENDPOINTS.keys())diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/clerk/tests/test_clerk.py b/products/warehouse_sources/backend/temporal/data_imports/sources/clerk/tests/test_clerk.pyindex 39bd2e723077..ad36187abee7 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/clerk/tests/test_clerk.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/clerk/tests/test_clerk.py@@ -11,8 +11,13 @@ from requests import Request, Responsefrom products.warehouse_sources.backend.temporal.data_imports.sources.clerk.clerk import (ClerkPaginator,ClerkResumeConfig,+ _convert_timestamps,+ _strip_sensitive_fields,clerk_source,+ get_resource,)+from products.warehouse_sources.backend.temporal.data_imports.sources.clerk.settings import CLERK_ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import Endpointfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager@@ -112,6 +117,27 @@ class TestClerkPaginator:paginator.set_resume_state({})assert paginator._offset == 0+ @pytest.mark.parametrize(+ ("label", "response_body", "has_next", "expected_offset"),+ [+ ("full_page", {"m2m_tokens": [{"id": f"mt{i}"} for i in range(100)], "total_count": 250}, True, 100),+ ("terminal_page", {"m2m_tokens": [{"id": "mt1"}], "total_count": 1}, False, 0),+ # Reading the default `data` key here would see zero rows and stop after page one.+ ("wrong_key_is_not_read", {"data": [{"id": f"mt{i}"} for i in range(100)]}, False, 0),+ ],+ )+ def test_update_state_with_custom_data_key(+ self, label: str, response_body: Any, has_next: bool, expected_offset: int+ ) -> None:+ paginator = ClerkPaginator(limit=100, data_key="m2m_tokens")+ response = MagicMock()+ response.json.return_value = response_body++ paginator.update_state(response)++ assert paginator._has_next_page is has_next+ assert paginator._offset == expected_offset+def _make_http_response(body: Any, status_code: int = 200) -> Response:resp = Response()@@ -241,3 +267,122 @@ class TestClerkSourceResumeBehavior:as_json = json.dumps(dataclasses.asdict(cfg))reconstituted = ClerkResumeConfig(**json.loads(as_json))assert reconstituted == cfg+++class TestClerkEndpoints:+ @pytest.mark.parametrize("endpoint", sorted(CLERK_ENDPOINTS))+ def test_resource_targets_the_configured_path(self, endpoint: str) -> None:+ config = CLERK_ENDPOINTS[endpoint]+ resource = get_resource(endpoint)+ endpoint_definition = cast(Endpoint, resource["endpoint"])++ assert resource["table_name"] == endpoint+ assert endpoint_definition["path"] == config.path+ assert config.path.startswith("/")+ # Rows are only found under the wrapper key the endpoint actually uses; the default+ # `data` selector silently yields nothing for /m2m_tokens.+ assert endpoint_definition.get("data_selector") == (config.data_key if config.is_wrapped_response else None)++ @pytest.mark.parametrize(+ "item",+ [+ # sessions+ {"created_at": 1700000000000, "expire_at": 1700000600000, "abandon_at": None},+ # api_keys / m2m_tokens+ {"created_at": 1700000000000, "expiration": 1700000600000, "last_used_at": 1700000300000},+ # commerce_subscription_items+ {"period_start": 1700000000000, "period_end": 1700000600000, "ended_at": 1700000300000},+ # saml_connections+ {"idp_certificate_issued_at": 1700000000000, "idp_certificate_expires_at": 1700000600000},+ ],+ )+ def test_millisecond_timestamps_are_converted_to_seconds(self, item: dict[str, Any]) -> None:+ # Left unconverted these land ~1000x in the future, which breaks the datetime partitioning+ # the source declares on created_at.+ converted = _convert_timestamps(dict(item))++ for field, value in item.items():+ assert converted[field] == (value // 1000 if value is not None else None)++ @pytest.mark.parametrize(+ "item,paths,expected",+ [+ # top-level redeemable link on invitations / organization_invitations+ (+ {"id": "inv_1", "email_address": "[email protected]", "url": "https://clerk.example/accept?ticket=secret"},+ ("url",),+ {"id": "inv_1", "email_address": "[email protected]"},+ ),+ # nested link on waitlist_entries+ (+ {"id": "wl_1", "invitation": {"id": "inv_2", "url": "https://clerk.example/accept?ticket=secret"}},+ ("invitation.url",),+ {"id": "wl_1", "invitation": {"id": "inv_2"}},+ ),+ # nested field absent (no invitation was sent) — nothing to strip, no crash+ (+ {"id": "wl_1", "invitation": None},+ ("invitation.url",),+ {"id": "wl_1", "invitation": None},+ ),+ ],+ )+ def test_sensitive_url_fields_are_stripped(+ self, item: dict[str, Any], paths: tuple[str, ...], expected: dict[str, Any]+ ) -> None:+ # Redeemable invitation links must never reach the warehouse table, where any viewer+ # could copy one and accept the invitation.+ assert _strip_sensitive_fields(dict(item), paths) == expected+++class TestClerkSourceResponse:+ def _source_response(self, endpoint: str) -> Any:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False+ return clerk_source(+ secret_key="sk_live_test",+ endpoint=endpoint,+ team_id=123,+ job_id="test_job",+ resumable_source_manager=manager,+ )++ @pytest.mark.parametrize("endpoint", sorted(CLERK_ENDPOINTS))+ def test_partitioning_matches_endpoint_config(self, endpoint: str) -> None:+ # Endpoints whose objects carry no creation timestamp must not declare a datetime+ # partition, or every row lands in the same fallback bucket.+ expected_key = CLERK_ENDPOINTS[endpoint].partition_key+ response = self._source_response(endpoint)++ assert response.primary_keys == ["id"]+ if expected_key is None:+ assert response.partition_keys is None+ assert response.partition_mode is None+ else:+ assert response.partition_keys == [expected_key]+ assert response.partition_mode == "datetime"+ assert response.partition_format == "week"++ def test_rows_are_read_from_the_endpoints_wrapper_key(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False+ response = _make_http_response({"m2m_tokens": [{"id": "mt_1", "created_at": 1700000000000}], "total_count": 1})++ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"+ ) as MockSession:+ mock_session = MockSession.return_value+ mock_session.headers = {}+ mock_session.prepare_request.side_effect = lambda req: req+ mock_session.send.return_value = response++ source_response = clerk_source(+ secret_key="sk_live_test",+ endpoint="m2m_tokens",+ team_id=123,+ job_id="test_job",+ resumable_source_manager=manager,+ )+ pages = list(cast(Iterable[Any], source_response.items()))++ assert pages == [[{"id": "mt_1", "created_at": 1700000000}]]diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/clerk/tests/test_clerk_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/clerk/tests/test_clerk_source.pyindex 15dfc43086d0..06d3e3e536e1 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/clerk/tests/test_clerk_source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/clerk/tests/test_clerk_source.py@@ -3,7 +3,7 @@ from unittest import mockfrom posthog.schema import SourceFieldInputConfig, SourceFieldInputConfigType-from products.warehouse_sources.backend.temporal.data_imports.sources.clerk.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.clerk.settings import CLERK_ENDPOINTS, ENDPOINTSfrom products.warehouse_sources.backend.temporal.data_imports.sources.clerk.source import ClerkSourcefrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.clerk import ClerkSourceConfigfrom products.warehouse_sources.backend.types import ExternalDataSourceType@@ -84,6 +84,16 @@ class TestClerkSource:assert schemas == []+ @pytest.mark.parametrize("endpoint", sorted(CLERK_ENDPOINTS))+ def test_every_endpoint_is_documented(self, endpoint):+ # `lists_tables_without_credentials` publishes this catalog to the public docs, so an+ # endpoint added without a canonical entry ships an undocumented table.+ entry = self.source.get_canonical_descriptions()[endpoint]++ assert entry["description"]+ assert entry["docs_url"].startswith("https://clerk.com/")+ assert entry["columns"]["id"]+@pytest.mark.parametrize("mock_return, expected_valid, expected_message",[