Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(data-warehouse): add Descope source (#73190)

Tom Owersb7321c756480
diff --git a/frontend/public/services/descope.png b/frontend/public/services/descope.png
index bdc21cf21749..66c7104083bf 100644
Binary files a/frontend/public/services/descope.png and b/frontend/public/services/descope.png differ
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
index 6e6a696d026f..8d3c6db12920 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -181,6 +181,7 @@ the row lists both.
| deepgram | HTTP | requests | ✅ |
| deepsource | HTTP (GraphQL) | requests | ✅ |
| deno_deploy | HTTP | requests | ✅ |
+| descope | HTTP | requests + `rest_source.RESTClient` | ✅ |
| devin_ai | HTTP | requests | ✅ |
| ding_connect | HTTP | requests | ✅ |
| digitalocean | HTTP | requests + `rest_source.RESTClient` | ✅ |
@@ -867,7 +868,6 @@ doesn't conflict with concurrent PRs.
- debugbear
- deno_deploy
- deputy
-- descope
- develocity
- dialpad
- discord
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/descope/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/descope/canonical_descriptions.py
new file mode 100644
index 000000000000..140e85bbfefb
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/descope/canonical_descriptions.py
@@ -0,0 +1,86 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "Users": {
+ "description": "Users registered in the Descope project, searchable across tenants, roles, and status.",
+ "docs_url": "https://docs.descope.com/api/management/users",
+ "columns": {
+ "userId": "Descope's unique identifier for the user.",
+ "loginIds": "Every login identifier (email, phone, username, etc.) associated with the user.",
+ "name": "The user's display name.",
+ "email": "The user's primary email address.",
+ "phone": "The user's primary phone number.",
+ "verifiedEmail": "Whether the user's email address has been verified.",
+ "verifiedPhone": "Whether the user's phone number has been verified.",
+ "roleNames": "Role names assigned to the user outside of any tenant.",
+ "userTenants": "The tenants the user belongs to, along with their per-tenant roles.",
+ "status": "The user's account status (e.g. enabled, disabled, invited).",
+ "externalIds": "External identifiers associated with the user, if any.",
+ "picture": "URL of the user's profile picture.",
+ "test": "Whether this is a test user.",
+ "customAttributes": "Custom attribute values configured for the project.",
+ "createdTime": "Unix timestamp (milliseconds) of when the user was created.",
+ "modifiedTime": "Unix timestamp (milliseconds) of when the user was last modified.",
+ "SAML": "Whether the user authenticates via SAML SSO.",
+ "OAuth": "Per-provider flags indicating whether the user has an OAuth connection.",
+ "webauthn": "Whether the user has a WebAuthn (passkey) credential registered.",
+ "password": "Whether the user has a password set.",
+ "SCIM": "Whether the user was provisioned via SCIM.",
+ },
+ },
+ "Audit": {
+ "description": "Authentication and management audit trail events for the project, available for up to the last 30 days.",
+ "docs_url": "https://docs.descope.com/audit-trails-and-integrations",
+ "columns": {
+ "userId": "The id of the user the audit event pertains to.",
+ "action": "The action recorded by the event (e.g. a login or management operation).",
+ "occurred": "Unix timestamp (milliseconds) of when the event occurred.",
+ "device": "Device category the event originated from (e.g. Desktop, Mobile).",
+ "method": "The authentication method involved (e.g. otp, totp, magiclink, oauth, saml, password).",
+ "geo": "Country code the event originated from.",
+ "remoteAddress": "IP address the event originated from.",
+ "externalIds": "Login identifiers associated with the event's user.",
+ "tenants": "Tenant ids associated with the event.",
+ "data": "Additional event-specific details.",
+ },
+ },
+ "Tenants": {
+ "description": "Tenants configured in the Descope project.",
+ "docs_url": "https://docs.descope.com/api/management/tenants",
+ "columns": {
+ "id": "Descope's unique identifier for the tenant.",
+ "name": "The tenant's display name.",
+ "selfProvisioningDomains": "Email domains that automatically provision new users into this tenant.",
+ "customAttributes": "Custom attribute values configured for the tenant.",
+ "createdTime": "Unix timestamp (milliseconds) of when the tenant was created.",
+ },
+ },
+ "Roles": {
+ "description": "Roles defined in the Descope project, with their granted permissions.",
+ "docs_url": "https://docs.descope.com/api/management/roles",
+ "columns": {
+ "id": "Descope's unique identifier for the role.",
+ "name": "The role's name.",
+ "description": "A description of what the role grants.",
+ "permissionNames": "Permission names granted by this role.",
+ "tenantId": "The tenant this role is scoped to, if any.",
+ "createdTime": "Unix timestamp (milliseconds) of when the role was created.",
+ },
+ },
+ "AccessKeys": {
+ "description": "Access keys used to authenticate machine-to-machine requests against the Descope project.",
+ "docs_url": "https://docs.descope.com/api/management/access-keys",
+ "columns": {
+ "id": "Descope's unique identifier for the access key.",
+ "name": "The access key's display name.",
+ "status": "The access key's status (e.g. active, disabled).",
+ "roleNames": "Role names granted to the access key outside of any tenant.",
+ "createdTime": "Unix timestamp (milliseconds) of when the access key was created.",
+ "expiresTime": "Unix timestamp (milliseconds) of when the access key expires.",
+ "createdBy": "Identifier of who created the access key.",
+ "boundUserId": "The user id this access key is bound to, if any.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/descope/descope.py b/products/warehouse_sources/backend/temporal/data_imports/sources/descope/descope.py
new file mode 100644
index 000000000000..4f2c87542e00
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/descope/descope.py
@@ -0,0 +1,248 @@
+import hashlib
+import dataclasses
+from typing import Any, Optional
+
+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.rest_source import (
+ RESTAPIConfig,
+ rest_api_resource,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (
+ PageNumberPaginator,
+ SinglePagePaginator,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (
+ Endpoint,
+ EndpointResource,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.descope.settings import (
+ PARTITION_KEYS,
+ PRIMARY_KEYS,
+ USER_INCREMENTAL_TIME_PARAMS,
+)
+
+DESCOPE_BASE_URL = "https://api.descope.com"
+USERS_PAGE_SIZE = 100
+
+
+class DescopeResumeConfig:
+ # Only the paginated `Users` endpoint resumes mid-sync; every other endpoint returns its
+ # full result in one response, so there's nothing to save between heartbeats.
+ page: int
+
+
+def bearer_token(project_id: str, management_key: str) -> str:
+ return f"{project_id}:{management_key}"
+
+
+def _users_body(
+ should_use_incremental_field: bool,
+ incremental_field: Optional[str],
+ db_incremental_field_last_value: Any,
+) -> dict[str, Any]:
+ # Sort on whichever field drives incrementality (falling back to createdTime for full
+ # refresh) so pages stay stable and the watermark advances monotonically.
+ sort_field = incremental_field if incremental_field in USER_INCREMENTAL_TIME_PARAMS else "createdTime"
+ body: dict[str, Any] = {
+ "limit": USERS_PAGE_SIZE,
+ "sort": [{"field": sort_field, "desc": False}],
+ }
+ if should_use_incremental_field and incremental_field and db_incremental_field_last_value is not None:
+ param_name = USER_INCREMENTAL_TIME_PARAMS.get(incremental_field)
+ if param_name:
+ body[param_name] = int(db_incremental_field_last_value)
+ return body
+
+
+def _audit_body(should_use_incremental_field: bool, db_incremental_field_last_value: Any) -> dict[str, Any]:
+ body: dict[str, Any] = {}
+ if should_use_incremental_field and db_incremental_field_last_value is not None:
+ body["from"] = int(db_incremental_field_last_value)
+ return body
+
+
+def _audit_row_id(row: dict[str, Any]) -> dict[str, Any]:
+ """Descope's audit search response carries no unique record id, so synthesize a stable one
+ from the event's identity fields. Deterministic across reruns: overlapping incremental
+ fetches merge onto the same row instead of duplicating it."""
+ parts = (
+ row.get("userId"),
+ row.get("action"),
+ row.get("occurred"),
+ row.get("device"),
+ row.get("method"),
+ row.get("remoteAddress"),
+ )
+ joined = "|".join("\x00" if part is None else str(part) for part in parts)
+ row["id"] = hashlib.sha256(joined.encode()).hexdigest()
+ return row
+
+
+def get_resource(
+ name: str,
+ should_use_incremental_field: bool,
+ incremental_field: Optional[str],
+ db_incremental_field_last_value: Any,
+) -> EndpointResource:
+ write_disposition = {"disposition": "merge", "strategy": "upsert"} if should_use_incremental_field else "replace"
+
+ if name == "Users":
+ endpoint: Endpoint = {
+ "path": "/v2/mgmt/user/search",
+ "method": "POST",
+ "json": _users_body(should_use_incremental_field, incremental_field, db_incremental_field_last_value),
+ "paginator": PageNumberPaginator(base_page=0, page_param="page", param_location="json"),
+ "data_selector": "users",
+ }
+ users_resource: EndpointResource = {
+ "name": name,
+ "table_name": "users",
+ "write_disposition": write_disposition,
+ "endpoint": endpoint,
+ "table_format": "delta",
+ }
+ return users_resource
+
+ if name == "Audit":
+ endpoint = {
+ "path": "/v1/mgmt/audit/search",
+ "method": "POST",
+ "json": _audit_body(should_use_incremental_field, db_incremental_field_last_value),
+ "paginator": SinglePagePaginator(),
+ "data_selector": "audits",
+ }
+ audit_resource: EndpointResource = {
+ "name": name,
+ "table_name": "audit",
+ "write_disposition": write_disposition,
+ "endpoint": endpoint,
+ "data_map": _audit_row_id,
+ "table_format": "delta",
+ }
+ return audit_resource
+
+ if name == "Tenants":
+ endpoint = {
+ "path": "/v1/mgmt/tenant/all",
+ "paginator": SinglePagePaginator(),
+ "data_selector": "tenants",
+ }
+ tenants_resource: EndpointResource = {
+ "name": name,
+ "table_name": "tenants",
+ "write_disposition": "replace",
+ "endpoint": endpoint,
+ "table_format": "delta",
+ }
+ return tenants_resource
+
+ if name == "Roles":
+ endpoint = {
+ "path": "/v1/mgmt/role/search",
+ "method": "POST",
+ "json": {},
+ "paginator": SinglePagePaginator(),
+ "data_selector": "roles",
+ }
+ roles_resource: EndpointResource = {
+ "name": name,
+ "table_name": "roles",
+ "write_disposition": "replace",
+ "endpoint": endpoint,
+ "table_format": "delta",
+ }
+ return roles_resource
+
+ if name == "AccessKeys":
+ endpoint = {
+ "path": "/v1/mgmt/accesskey/search",
+ "method": "POST",
+ "json": {"tenantIds": []},
+ "paginator": SinglePagePaginator(),
+ "data_selector": "keys",
+ }
+ access_keys_resource: EndpointResource = {
+ "name": name,
+ "table_name": "access_keys",
+ "write_disposition": "replace",
+ "endpoint": endpoint,
+ "table_format": "delta",
+ }
+ return access_keys_resource
+
+ raise ValueError(f"Unknown Descope endpoint: {name}")
+
+
+def descope_source(
+ project_id: str,
+ management_key: str,
+ endpoint: str,
+ team_id: int,
+ job_id: str,
+ resumable_source_manager: ResumableSourceManager[DescopeResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+ incremental_field: Optional[str] = None,
+) -> SourceResponse:
+ resource_config = get_resource(
+ endpoint, should_use_incremental_field, incremental_field, db_incremental_field_last_value
+ )
+
+ config: RESTAPIConfig = {
+ "client": {
+ "base_url": DESCOPE_BASE_URL,
+ "auth": {
+ "type": "bearer",
+ "token": bearer_token(project_id, management_key),
+ },
+ },
+ "resources": [resource_config],
+ }
+
+ initial_paginator_state: Optional[dict[str, Any]] = None
+ if endpoint == "Users" and resumable_source_manager.can_resume():
+ resume_config = resumable_source_manager.load_state()
+ if resume_config is not None:
+ initial_paginator_state = {"page": resume_config.page}
+
+ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:
+ # Only Users paginates; other endpoints never call this (SinglePagePaginator never
+ # reports a resume state), so this is a no-op for them.
+ if endpoint != "Users" or not state:
+ return
+ page = state.get("page")
+ if page is not None:
+ resumable_source_manager.save_state(DescopeResumeConfig(page=int(page)))
+
+ resource = rest_api_resource(
+ config,
+ team_id,
+ job_id,
+ db_incremental_field_last_value,
+ resume_hook=save_checkpoint,
+ initial_paginator_state=initial_paginator_state,
+ )
+
+ return SourceResponse(
+ name=resource.name,
+ items=lambda: resource,
+ primary_keys=PRIMARY_KEYS[endpoint],
+ partition_mode="datetime",
+ partition_keys=[PARTITION_KEYS[endpoint]],
+ sort_mode="asc",
+ )
+
+
+def validate_credentials(project_id: str, management_key: str) -> bool:
+ token = bearer_token(project_id, management_key)
+ session = make_tracked_session(redact_values=(management_key, token))
+ response = session.post(
+ f"{DESCOPE_BASE_URL}/v1/mgmt/projects/list",
+ json={},
+ headers={"Authorization": f"Bearer {token}"},
+ timeout=10,
+ )
+ return response.status_code == 200
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/descope/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/descope/settings.py
new file mode 100644
index 000000000000..e7e864edd247
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/descope/settings.py
@@ -0,0 +1,63 @@
+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+
+ENDPOINTS = (
+ "Users",
+ "Audit",
+ "Tenants",
+ "Roles",
+ "AccessKeys",
+)
+
+# Users and Audit support real server-side timestamp filters (verified against the official
+# descope/python-sdk and descope/node-sdk management clients). Tenants/Roles/AccessKeys are small,
+# unpaginated full lists with no timestamp filter, so they're full-refresh only (omitted here).
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ "Users": [
+ {
+ "label": "createdTime",
+ "type": IncrementalFieldType.DateTime,
+ "field": "createdTime",
+ "field_type": IncrementalFieldType.Integer,
+ },
+ {
+ "label": "modifiedTime",
+ "type": IncrementalFieldType.DateTime,
+ "field": "modifiedTime",
+ "field_type": IncrementalFieldType.Integer,
+ },
+ ],
+ "Audit": [
+ {
+ "label": "occurred",
+ "type": IncrementalFieldType.DateTime,
+ "field": "occurred",
+ "field_type": IncrementalFieldType.Integer,
+ },
+ ],
+}
+
+# `POST /v2/mgmt/user/search` field name for each advertised incremental cursor.
+USER_INCREMENTAL_TIME_PARAMS: dict[str, str] = {
+ "createdTime": "fromCreatedTime",
+ "modifiedTime": "fromModifiedTime",
+}
+
+PRIMARY_KEYS: dict[str, list[str]] = {
+ "Users": ["userId"],
+ # Descope's audit search has no unique record id (verified: absent from both official SDKs'
+ # response types) — a synthetic one is derived from the event's identity fields, see descope.py.
+ "Audit": ["id"],
+ "Tenants": ["id"],
+ "Roles": ["id"],
+ "AccessKeys": ["id"],
+}
+
+# A stable field to partition on — never the incremental cursor a user could pick (e.g. modifiedTime),
+# since that changes over time and would rewrite partitions on every sync.
+PARTITION_KEYS: dict[str, str] = {
+ "Users": "createdTime",
+ "Audit": "occurred",
+ "Tenants": "createdTime",
+ "Roles": "createdTime",
+ "AccessKeys": "createdTime",
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/descope/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/descope/source.py
index aaf4c136b1d9..4ec2450f2f15 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/descope/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/descope/source.py
@@ -1,13 +1,37 @@
-from typing import cast
+from typing import Optional, cast
from 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 (
+ SourceSchema,
+ build_endpoint_schemas,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.descope.descope import (
+ DescopeResumeConfig,
+ descope_source,
+ validate_credentials as validate_descope_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.descope.settings import (
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.descope import (
DescopeSourceConfig,
)
@@ -15,18 +39,103 @@ from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class DescopeSource(SimpleSource[DescopeSourceConfig]):
+class DescopeSource(ResumableSource[DescopeSourceConfig, DescopeResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+ api_docs_url = "https://docs.descope.com/api"
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.DESCOPE
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error: Unauthorized for url: https://api.descope.com": "Descope authentication failed. Please check your Project ID and Management Key.",
+ "403 Client Error: Forbidden for url: https://api.descope.com": "Descope authentication failed. Please check your Project ID and Management Key.",
+ }
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.descope.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_schemas(
+ self,
+ config: DescopeSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ api_version: str | None = None,
+ ) -> list[SourceSchema]:
+ return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names)
+
+ def validate_credentials(
+ self,
+ config: DescopeSourceConfig,
+ team_id: int,
+ schema_name: Optional[str] = None,
+ api_version: str | None = None,
+ ) -> tuple[bool, str | None]:
+ if validate_descope_credentials(config.project_id, config.management_key):
+ return True, None
+
+ return False, "Invalid credentials. Please check your Project ID and Management Key."
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[DescopeResumeConfig]:
+ return ResumableSourceManager[DescopeResumeConfig](inputs, DescopeResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: DescopeSourceConfig,
+ resumable_source_manager: ResumableSourceManager[DescopeResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return descope_source(
+ project_id=config.project_id,
+ management_key=config.management_key,
+ endpoint=inputs.schema_name,
+ team_id=inputs.team_id,
+ job_id=inputs.job_id,
+ 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,
+ incremental_field=inputs.incremental_field,
+ )
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=SchemaExternalDataSourceType.DESCOPE,
category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,
label="Descope",
+ caption="Sync users, audit trail events, tenants, roles, and access keys from your Descope project. Requires a Management Key, generated from the [Descope Console](https://app.descope.com) under Project Settings > Company/Management Keys.",
+ docsUrl="https://posthog.com/docs/cdp/sources/descope",
+ releaseStatus=ReleaseStatus.ALPHA,
iconPath="/static/services/descope.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ keywords=["ciam"],
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="project_id",
+ label="Project ID",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="P2...",
+ secret=False,
+ ),
+ SourceFieldInputConfig(
+ name="management_key",
+ label="Management key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/descope/tests/test_descope.py b/products/warehouse_sources/backend/temporal/data_imports/sources/descope/tests/test_descope.py
new file mode 100644
index 000000000000..94cfb5b87567
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/descope/tests/test_descope.py
@@ -0,0 +1,378 @@
+import json
+from typing import Any
+
+import pytest
+from unittest import mock
+
+from requests import Response
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.descope.descope import (
+ DescopeResumeConfig,
+ _audit_body,
+ _audit_row_id,
+ _users_body,
+ bearer_token,
+ descope_source,
+ get_resource,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.descope.settings import (
+ ENDPOINTS,
+ PARTITION_KEYS,
+ PRIMARY_KEYS,
+)
+
+# RESTClient builds its session via make_tracked_session in the rest_client module.
+CLIENT_SESSION_PATCH = "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"
+# validate_credentials builds its own tracked session in the descope module.
+DESCOPE_SESSION_PATCH = (
+ "products.warehouse_sources.backend.temporal.data_imports.sources.descope.descope.make_tracked_session"
+)
+
+
+def _response(payload: dict[str, Any]) -> Response:
+ resp = Response()
+ resp.status_code = 200
+ resp._content = json.dumps(payload).encode()
+ return resp
+
+
+def _make_manager(resume_state: DescopeResumeConfig | 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 _wire(session: mock.MagicMock, responses: list[Response]) -> list[dict[str, Any]]:
+ """Wire a mock session and capture each request's JSON body AT SEND TIME.
+
+ ``request.json`` is a single dict mutated in place across pages (the paginator injects
+ ``page`` into it), so inspecting it after the run shows only the final state — snapshot
+ a copy when each request is prepared instead.
+ """
+ session.headers = {}
+ body_snapshots: list[dict[str, Any]] = []
+
+ def _prepare(request: Any) -> mock.MagicMock:
+ body_snapshots.append(dict(request.json or {}))
+ return mock.MagicMock()
+
+ session.prepare_request.side_effect = _prepare
+ session.send.side_effect = responses
+ return body_snapshots
+
+
+def _rows(source_response) -> list[dict[str, Any]]:
+ return [row for page in source_response.items() for row in page]
+
+
+def _source(endpoint: str = "Users", manager: mock.MagicMock | None = None, **kwargs: Any):
+ return descope_source(
+ "P2abc",
+ "mgmt-key",
+ endpoint,
+ team_id=1,
+ job_id="j",
+ resumable_source_manager=manager if manager is not None else _make_manager(),
+ **kwargs,
+ )
+
+
+class TestBearerToken:
+ def test_joins_project_id_and_key(self):
+ assert bearer_token("P2abc", "secretkey") == "P2abc:secretkey"
+
+
+class TestUsersBody:
+ def test_full_refresh_defaults_to_created_time_sort(self):
+ body = _users_body(
+ should_use_incremental_field=False, incremental_field=None, db_incremental_field_last_value=None
+ )
+
+ assert body["limit"] == 100
+ assert body["sort"] == [{"field": "createdTime", "desc": False}]
+ assert "fromCreatedTime" not in body
+ assert "fromModifiedTime" not in body
+
+ @pytest.mark.parametrize(
+ "incremental_field, expected_param",
+ [
+ ("createdTime", "fromCreatedTime"),
+ ("modifiedTime", "fromModifiedTime"),
+ ],
+ )
+ def test_incremental_sets_matching_time_param_and_sort(self, incremental_field, expected_param):
+ body = _users_body(
+ should_use_incremental_field=True,
+ incremental_field=incremental_field,
+ db_incremental_field_last_value=1700000000000,
+ )
+
+ assert body["sort"] == [{"field": incremental_field, "desc": False}]
+ assert body[expected_param] == 1700000000000
+
+ def test_incremental_without_last_value_omits_time_param(self):
+ body = _users_body(
+ should_use_incremental_field=True, incremental_field="createdTime", db_incremental_field_last_value=None
+ )
+ assert "fromCreatedTime" not in body
+
+
+class TestAuditBody:
+ def test_full_refresh_body_is_empty(self):
+ assert _audit_body(should_use_incremental_field=False, db_incremental_field_last_value=None) == {}
+
+ def test_incremental_body_sets_from(self):
+ body = _audit_body(should_use_incremental_field=True, db_incremental_field_last_value=1700000000000)
+ assert body == {"from": 1700000000000}
+
+ def test_incremental_without_last_value_stays_empty(self):
+ assert _audit_body(should_use_incremental_field=True, db_incremental_field_last_value=None) == {}
+
+
+class TestAuditRowId:
+ def test_deterministic_for_identical_events(self):
+ row_a = {
+ "userId": "u1",
+ "action": "login",
+ "occurred": 1700000000000,
+ "device": "Desktop",
+ "method": "otp",
+ "remoteAddress": "1.2.3.4",
+ }
+ row_b = dict(row_a)
+
+ assert _audit_row_id(row_a)["id"] == _audit_row_id(row_b)["id"]
+
+ def test_differs_for_different_events(self):
+ base = {
+ "userId": "u1",
+ "action": "login",
+ "occurred": 1700000000000,
+ "device": "Desktop",
+ "method": "otp",
+ "remoteAddress": "1.2.3.4",
+ }
+ other = {**base, "userId": "u2"}
+
+ assert _audit_row_id(dict(base))["id"] != _audit_row_id(other)["id"]
+
+ def test_handles_missing_fields(self):
+ row = _audit_row_id({})
+ assert isinstance(row["id"], str) and len(row["id"]) == 64
+
+
+class TestGetResource:
+ @pytest.mark.parametrize(
+ "endpoint, expected_path, expected_method, expected_selector",
+ [
+ ("Users", "/v2/mgmt/user/search", "POST", "users"),
+ ("Audit", "/v1/mgmt/audit/search", "POST", "audits"),
+ ("Tenants", "/v1/mgmt/tenant/all", None, "tenants"),
+ ("Roles", "/v1/mgmt/role/search", "POST", "roles"),
+ ("AccessKeys", "/v1/mgmt/accesskey/search", "POST", "keys"),
+ ],
+ )
+ def test_endpoint_shape(self, endpoint, expected_path, expected_method, expected_selector):
+ resource = get_resource(
+ endpoint, should_use_incremental_field=False, incremental_field=None, db_incremental_field_last_value=None
+ )
+ endpoint_config = resource["endpoint"]
+ assert isinstance(endpoint_config, dict)
+
+ assert endpoint_config["path"] == expected_path
+ assert endpoint_config.get("method") == expected_method
+ assert endpoint_config["data_selector"] == expected_selector
+
+ def test_unknown_endpoint_raises(self):
+ with pytest.raises(ValueError):
+ get_resource(
+ "Nope", should_use_incremental_field=False, incremental_field=None, db_incremental_field_last_value=None
+ )
+
+ @pytest.mark.parametrize("endpoint", ["Users", "Audit"])
+ def test_incremental_endpoints_use_merge_when_enabled(self, endpoint):
+ resource = get_resource(
+ endpoint,
+ should_use_incremental_field=True,
+ incremental_field="createdTime",
+ db_incremental_field_last_value=1,
+ )
+ assert resource["write_disposition"] == {"disposition": "merge", "strategy": "upsert"}
+
+ @pytest.mark.parametrize("endpoint", ["Tenants", "Roles", "AccessKeys"])
+ def test_full_refresh_endpoints_always_replace(self, endpoint):
+ resource = get_resource(
+ endpoint, should_use_incremental_field=True, incremental_field=None, db_incremental_field_last_value=None
+ )
+ assert resource["write_disposition"] == "replace"
+
+
+class TestValidateCredentials:
+ @pytest.mark.parametrize(
+ "status_code, expected",
+ [
+ (200, True),
+ (401, False),
+ (403, False),
+ ],
+ )
+ @mock.patch(DESCOPE_SESSION_PATCH)
+ def test_validate_credentials_status_mapping(self, mock_session, status_code, expected):
+ response = mock.MagicMock()
+ response.status_code = status_code
+ mock_session.return_value.post.return_value = response
+
+ assert validate_credentials("P2abc", "mgmt-key") is expected
+
+ @mock.patch(DESCOPE_SESSION_PATCH)
+ def test_sends_bearer_token(self, mock_session):
+ response = mock.MagicMock()
+ response.status_code = 200
+ mock_session.return_value.post.return_value = response
+
+ validate_credentials("P2abc", "mgmt-key")
+
+ _, kwargs = mock_session.return_value.post.call_args
+ assert kwargs["headers"]["Authorization"] == "Bearer P2abc:mgmt-key"
+
+
+class TestUsersPagination:
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_paginates_via_page_number_in_json_body(self, MockSession):
+ session = MockSession.return_value
+ full_page = [{"userId": f"u{i}"} for i in range(100)]
+ # PageNumberPaginator only stops on a fully empty page, so a short (but non-empty)
+ # second page still triggers a third, empty request before pagination ends.
+ bodies = _wire(
+ session,
+ [
+ _response({"users": full_page}),
+ _response({"users": [{"userId": "last"}]}),
+ _response({"users": []}),
+ ],
+ )
+
+ manager = _make_manager()
+ rows = _rows(_source(manager=manager))
+
+ assert len(rows) == 101
+ assert bodies[0]["page"] == 0
+ assert bodies[1]["page"] == 1
+ assert bodies[2]["page"] == 2
+ # Checkpoint saved after each page with a next page pending.
+ assert manager.save_state.call_args_list == [
+ mock.call(DescopeResumeConfig(page=1)),
+ mock.call(DescopeResumeConfig(page=2)),
+ ]
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_empty_page_stops_pagination(self, MockSession):
+ session = MockSession.return_value
+ _wire(session, [_response({"users": []})])
+
+ manager = _make_manager()
+ rows = _rows(_source(manager=manager))
+
+ assert rows == []
+ assert session.send.call_count == 1
+ manager.save_state.assert_not_called()
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_resumes_from_saved_page(self, MockSession):
+ session = MockSession.return_value
+ bodies = _wire(session, [_response({"users": []})])
+
+ manager = _make_manager(DescopeResumeConfig(page=3))
+ _rows(_source(manager=manager))
+
+ assert bodies[0]["page"] == 3
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_incremental_body_carries_watermark(self, MockSession):
+ session = MockSession.return_value
+ bodies = _wire(session, [_response({"users": []})])
+
+ _rows(
+ _source(
+ should_use_incremental_field=True,
+ incremental_field="modifiedTime",
+ db_incremental_field_last_value=1700000000000,
+ )
+ )
+
+ assert bodies[0]["fromModifiedTime"] == 1700000000000
+ assert bodies[0]["sort"] == [{"field": "modifiedTime", "desc": False}]
+
+
+class TestAuditFetch:
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_single_fetch_synthesizes_row_id(self, MockSession):
+ session = MockSession.return_value
+ _wire(
+ session,
+ [
+ _response(
+ {
+ "audits": [
+ {"userId": "u1", "action": "login", "occurred": 1700000000000},
+ ]
+ }
+ )
+ ],
+ )
+
+ rows = _rows(_source(endpoint="Audit"))
+
+ assert session.send.call_count == 1
+ assert "id" in rows[0]
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_incremental_sends_from_timestamp(self, MockSession):
+ session = MockSession.return_value
+ bodies = _wire(session, [_response({"audits": []})])
+
+ _rows(
+ _source(endpoint="Audit", should_use_incremental_field=True, db_incremental_field_last_value=1700000000000)
+ )
+
+ assert bodies[0]["from"] == 1700000000000
+
+
+class TestFullRefreshEndpoints:
+ @pytest.mark.parametrize(
+ "endpoint, selector, response_key",
+ [
+ ("Tenants", "tenants", "tenants"),
+ ("Roles", "roles", "roles"),
+ ("AccessKeys", "keys", "keys"),
+ ],
+ )
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_fetches_full_list_in_one_request(self, MockSession, endpoint, selector, response_key):
+ session = MockSession.return_value
+ _wire(session, [_response({response_key: [{"id": "1"}, {"id": "2"}]})])
+
+ rows = _rows(_source(endpoint=endpoint))
+
+ assert session.send.call_count == 1
+ assert rows == [{"id": "1"}, {"id": "2"}]
+
+
+class TestDescopeSourceResponse:
+ @pytest.mark.parametrize("endpoint", list(ENDPOINTS))
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_response_metadata_per_endpoint(self, MockSession, endpoint):
+ session = MockSession.return_value
+ selector = {"Users": "users", "Audit": "audits", "Tenants": "tenants", "Roles": "roles", "AccessKeys": "keys"}[
+ endpoint
+ ]
+ _wire(session, [_response({selector: []})])
+
+ response = _source(endpoint=endpoint)
+
+ assert response.primary_keys == PRIMARY_KEYS[endpoint]
+ assert response.sort_mode == "asc"
+ assert response.partition_mode == "datetime"
+ assert response.partition_keys == [PARTITION_KEYS[endpoint]]
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/descope/tests/test_descope_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/descope/tests/test_descope_source.py
new file mode 100644
index 000000000000..a274671ceaf5
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/descope/tests/test_descope_source.py
@@ -0,0 +1,172 @@
+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.descope.descope import DescopeResumeConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.descope.settings import (
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.descope.source import DescopeSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.descope import (
+ DescopeSourceConfig,
+)
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+class TestDescopeSource:
+ def setup_method(self):
+ self.source = DescopeSource()
+ self.team_id = 123
+ self.config = DescopeSourceConfig(project_id="P2abc", management_key="mgmt-key")
+
+ def test_source_type(self):
+ assert self.source.source_type == ExternalDataSourceType.DESCOPE
+
+ def test_get_source_config(self):
+ config = self.source.get_source_config
+
+ assert config.name.value == "Descope"
+ assert config.label == "Descope"
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.unreleasedSource is None
+ assert config.iconPath == "/static/services/descope.png"
+ assert config.category is not None
+
+ field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]
+ assert field_names == ["project_id", "management_key"]
+
+ def test_management_key_field_is_secret_password(self):
+ config = self.source.get_source_config
+ key_field = next(
+ f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "management_key"
+ )
+ assert key_field.type == SourceFieldInputConfigType.PASSWORD
+ assert key_field.secret is True
+ assert key_field.required is True
+
+ def test_project_id_field_is_not_secret(self):
+ config = self.source.get_source_config
+ project_field = next(
+ f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "project_id"
+ )
+ assert project_field.type == SourceFieldInputConfigType.TEXT
+ assert project_field.secret is False
+ assert project_field.required is True
+
+ @pytest.mark.parametrize(
+ "observed_error",
+ [
+ "401 Client Error: Unauthorized for url: https://api.descope.com/v1/mgmt/projects/list",
+ "403 Client Error: Forbidden for url: https://api.descope.com/v2/mgmt/user/search",
+ ],
+ )
+ 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(
+ "other_vendor_error",
+ [
+ "401 Client Error: Unauthorized for url: https://api.stripe.com/v1/customers",
+ "500 Server Error for url: https://api.descope.com/v1/mgmt/audit/search",
+ ],
+ )
+ def test_non_retryable_errors_does_not_match_unrelated(self, other_vendor_error):
+ non_retryable_errors = self.source.get_non_retryable_errors()
+ assert not any(key in other_vendor_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)
+
+ @pytest.mark.parametrize(
+ "endpoint, expected_incremental, expected_fields",
+ [
+ ("Users", True, ["createdTime", "modifiedTime"]),
+ ("Audit", True, ["occurred"]),
+ ("Tenants", False, []),
+ ("Roles", False, []),
+ ("AccessKeys", False, []),
+ ],
+ )
+ def test_schemas_advertise_expected_incremental_fields(self, endpoint, expected_incremental, expected_fields):
+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}
+
+ assert schemas[endpoint].supports_incremental is expected_incremental
+ assert schemas[endpoint].incremental_fields == INCREMENTAL_FIELDS.get(endpoint, [])
+ assert [f["field"] for f in schemas[endpoint].incremental_fields] == expected_fields
+
+ def test_get_schemas_filtered_by_names(self):
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["Users"])
+ assert len(schemas) == 1
+ assert schemas[0].name == "Users"
+
+ def test_get_schemas_filtered_unknown_name_returns_empty(self):
+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []
+
+ @pytest.mark.parametrize(
+ "mock_return, expected_valid",
+ [
+ (True, True),
+ (False, False),
+ ],
+ )
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.descope.source.validate_descope_credentials"
+ )
+ def test_validate_credentials(self, mock_validate, mock_return, expected_valid):
+ 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
+ if not expected_valid:
+ assert error_message
+ mock_validate.assert_called_once_with(self.config.project_id, self.config.management_key)
+
+ def test_get_resumable_source_manager_binds_resume_config(self):
+ inputs = mock.MagicMock()
+ manager = self.source.get_resumable_source_manager(inputs)
+
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is DescopeResumeConfig
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.descope.source.descope_source")
+ def test_source_for_pipeline_plumbs_arguments(self, mock_descope_source):
+ inputs = mock.MagicMock()
+ inputs.schema_name = "Users"
+ inputs.team_id = 123
+ inputs.job_id = "job-1"
+ inputs.should_use_incremental_field = True
+ inputs.db_incremental_field_last_value = 1700000000000
+ inputs.incremental_field = "modifiedTime"
+ manager = mock.MagicMock()
+
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ mock_descope_source.assert_called_once()
+ kwargs = mock_descope_source.call_args.kwargs
+ assert kwargs["project_id"] == "P2abc"
+ assert kwargs["management_key"] == "mgmt-key"
+ assert kwargs["endpoint"] == "Users"
+ assert kwargs["team_id"] == 123
+ assert kwargs["job_id"] == "job-1"
+ assert kwargs["resumable_source_manager"] is manager
+ assert kwargs["should_use_incremental_field"] is True
+ assert kwargs["db_incremental_field_last_value"] == 1700000000000
+ assert kwargs["incremental_field"] == "modifiedTime"
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.descope.source.descope_source")
+ def test_source_for_pipeline_omits_last_value_on_full_refresh(self, mock_descope_source):
+ inputs = mock.MagicMock()
+ inputs.schema_name = "Users"
+ inputs.should_use_incremental_field = False
+ inputs.db_incremental_field_last_value = 1700000000000
+
+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)
+
+ assert mock_descope_source.call_args.kwargs["db_incremental_field_last_value"] is None
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/descope.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/descope.py
index dcc0f3b184a3..f3f6762c9742 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/descope.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/descope.py
@@ -6,4 +6,5 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp
@config.config
class DescopeSourceConfig(config.Config):
- pass
+ project_id: str
+ management_key: str