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(warehouse-sources): add descope permissions, groups, user history and analytics tables (#105172)

Tom Owersf158a76e7466
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
index 9dcde3a0875b..2cde71e6f6fd 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
@@ -2421,14 +2421,14 @@ Note: The v2 Deploy API is tiny — 15 GET operations. Everything queryable as a
## Descope — gaps
-Today (5): `AccessKeys`, `Audit`, `Roles`, `Tenants`, `Users`
+Today (9): `AccessKeys`, `Analytics`, `Audit`, `Groups`, `Permissions`, `Roles`, `Tenants`, `UserHistory`, `Users`
Diffed against: <https://docs.descope.com/examples/Descope_API.yaml>
-- [ ] `/v1/mgmt/permission/all` — lookup table for the permission names referenced by every synced role (high)
-- [ ] `/v2/mgmt/user/history` — per-user authentication history — sign-in events, method and device, the core auth analytics fact (high)
-- [ ] `/v1/mgmt/analytics/search` — Descope's own aggregated auth analytics (sign-ins, conversions) over a time range (high)
-- [ ] `/v1/mgmt/group/all and /v1/mgmt/group/members (+ /v1/mgmt/group/member/all)` — tenant group membership — the user-to-group join table missing from users/tenants (medium)
+- [x] `/v1/mgmt/permission/all` — lookup table for the permission names referenced by every synced role (high)
+- [x] `/v2/mgmt/user/history` — per-user authentication history — sign-in events, method and device, the core auth analytics fact (high)
+- [x] `/v1/mgmt/analytics/search` — Descope's own aggregated auth analytics (sign-ins, conversions) over a time range (high)
+- [x] `/v1/mgmt/group/all and /v1/mgmt/group/members (+ /v1/mgmt/group/member/all)` — tenant group membership — the user-to-group join table missing from users/tenants (medium)
- [ ] `/v1/mgmt/projects/list` — project lookup so multi-project tenants can attribute users and audit rows (medium)
- [ ] `/v1/mgmt/sso/idp/apps/load and /v1/mgmt/thirdparty/apps/load` — SSO and third-party application registry that resolves app IDs seen in audit events (medium)
- [ ] `/v1/mgmt/thirdparty/consents/search` — user consent grants per third-party app — auditable authorization state (medium)
@@ -2439,6 +2439,8 @@ Diffed against: <https://docs.descope.com/examples/Descope_API.yaml>
Note: The downloadable spec (Descope_API.yaml, 474 paths, 318 under /mgmt) is a POST-heavy RPC-style API, so 'endpoints' here are search/load operations rather than REST collections. Flows, themes, JWT templates, management keys, MCP servers and outbound apps were excluded as config/plumbing.
+Note: `Groups` covers all three group operations. `/v1/mgmt/group/all` returns each group with its `members` array already attached, so `/v1/mgmt/group/members` and `/v1/mgmt/group/member/all` only re-return filtered views of the same rows and were not given tables of their own.
+
## DevinAI — **thin**
Today (9): `consumption_daily`, `consumption_daily_users`, `knowledge_notes`, `members`, `playbooks`, `secrets`, `session_insights`, `session_messages`, `sessions`
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
index 140e85bbfefb..0cfbd6db22ac 100644
--- 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
@@ -83,4 +83,55 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"boundUserId": "The user id this access key is bound to, if any.",
},
},
+ "Permissions": {
+ "description": "Permissions defined in the Descope project. Roles reference these by name.",
+ "docs_url": "https://docs.descope.com/api/management/permissions",
+ "columns": {
+ "id": "Descope's unique identifier for the permission.",
+ "name": "The permission's name, as referenced by a role's permissionNames.",
+ "description": "A description of what the permission allows.",
+ "systemDefault": "Whether Descope created the permission, rather than the project's admins.",
+ },
+ },
+ "Groups": {
+ "description": "External groups synced into each tenant from its identity provider, with their members. One row per group per tenant.",
+ "docs_url": "https://docs.descope.com/api/management/groups",
+ "columns": {
+ "tenantId": "The tenant the group was loaded for. Group ids come from the identity provider, so they are only unique within a tenant.",
+ "id": "The group's identifier in the identity provider.",
+ "display": "The group's display name.",
+ "members": "The users in the group, each with their loginId, userId and display name.",
+ "source": "Where the group came from, for example SCIM or a JIT login.",
+ "ssoId": "The SSO configuration the group came from. Groups from the tenant's default configuration report the reserved id default_ssoid.",
+ },
+ },
+ "UserHistory": {
+ "description": "Authentication history per user: one row per sign-in, with where it came from.",
+ "docs_url": "https://docs.descope.com/api/management/users",
+ "columns": {
+ "id": "A synthetic identifier PostHog derives from the sign-in's fields, since Descope returns no record id.",
+ "userId": "The id of the user who signed in.",
+ "loginTime": "Unix timestamp of when the sign-in happened.",
+ "city": "City the sign-in came from.",
+ "country": "Country the sign-in came from.",
+ "ip": "IP address the sign-in came from.",
+ "selectedTenant": "The tenant the user signed in to, if the project uses tenants.",
+ },
+ },
+ "Analytics": {
+ "description": "Descope's own aggregated authentication analytics, counted per day and broken down by action, device, method, country, tenant and referrer. Covers the last 12 months, which is as far back as the endpoint reports.",
+ "docs_url": "https://docs.descope.com/audit-trails-and-integrations",
+ "columns": {
+ "id": "A synthetic identifier PostHog derives from the row's grouping fields, since Descope returns no record id.",
+ "projectId": "The Descope project the counts belong to.",
+ "created": "The day the counted events happened on.",
+ "action": "The action counted, for example a sign-in.",
+ "device": "Device category the events came from (Bot, Mobile, Desktop, Tablet or Unknown).",
+ "method": "Authentication method used (otp, totp, magiclink, oauth, saml or password).",
+ "geo": "Country code the events came from.",
+ "tenant": "The tenant the events belong to.",
+ "referrer": "The referrer the events came from.",
+ "cnt": "How many events fall into this bucket.",
+ },
+ },
}
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
index 6e5528da7524..5097ba478682 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/descope/descope.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/descope/descope.py
@@ -1,16 +1,21 @@
+import time
import hashlib
-import dataclasses
+from collections.abc import Callable, Iterator
from typing import Any, Optional
+from posthog.dataclasses import frozen
+
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.auth import BearerTokenAuth
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.rest_client import RESTClient
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (
Endpoint,
EndpointResource,
@@ -18,6 +23,8 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.res
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
from products.warehouse_sources.backend.temporal.data_imports.sources.descope.settings import (
+ ANALYTICS_BUCKET,
+ ANALYTICS_LOOKBACK_DAYS,
PARTITION_KEYS,
PRIMARY_KEYS,
USER_INCREMENTAL_TIME_PARAMS,
@@ -25,12 +32,18 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.descope.se
DESCOPE_BASE_URL = "https://api.descope.com"
USERS_PAGE_SIZE = 100
+DAY_MS = 24 * 60 * 60 * 1000
+# The fan-out endpoints issue one request per parent, so a single stalled request would hang a
+# whole sync with no progress. Bound each one instead.
+REQUEST_TIMEOUT_SECONDS = 60
+@frozen
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.
+ # The `POST /v2/mgmt/user/search` page to pick back up at. `Users` and `UserHistory` both walk
+ # that list, and each schema syncs under its own job id, so the two never read each other's
+ # cursor. Every other endpoint returns its full result in one response, so there's nothing to
+ # save between heartbeats.
page: int
@@ -64,23 +77,47 @@ def _audit_body(should_use_incremental_field: bool, db_incremental_field_last_va
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)
+def _analytics_body(now_ms: int) -> dict[str, Any]:
+ # Group on every dimension the endpoint offers so the aggregate keeps its detail; grouping on
+ # fewer would collapse rows we cannot split apart again. The official SDK sends `from` as epoch
+ # milliseconds even though the published spec types it as a string.
+ return {
+ "from": now_ms - ANALYTICS_LOOKBACK_DAYS * DAY_MS,
+ "groupByAction": True,
+ "groupByDevice": True,
+ "groupByMethod": True,
+ "groupByGeo": True,
+ "groupByTenant": True,
+ "groupByReferrer": True,
+ "groupByCreated": ANALYTICS_BUCKET,
+ }
+
+
+def _synthetic_row_id(row: dict[str, Any], fields: tuple[str, ...]) -> dict[str, Any]:
+ """Synthesize a stable id for a response that carries no record id of its own.
+
+ Deterministic across reruns: overlapping fetches merge onto the same row instead of
+ duplicating it."""
+ joined = "|".join("\x00" if row.get(field) is None else str(row.get(field)) for field in fields)
row["id"] = hashlib.sha256(joined.encode()).hexdigest()
return row
+# Descope's audit search, authentication history and analytics aggregate all answer without a
+# unique record id (verified against the published spec and both official SDKs' response types).
+_AUDIT_ID_FIELDS = ("userId", "action", "occurred", "device", "method", "remoteAddress")
+_USER_HISTORY_ID_FIELDS = ("userId", "loginTime", "ip", "city", "country", "selectedTenant")
+_ANALYTICS_ID_FIELDS = ("created", "action", "device", "method", "geo", "tenant", "referrer")
+
+
+def _audit_row_id(row: dict[str, Any]) -> dict[str, Any]:
+ return _synthetic_row_id(row, _AUDIT_ID_FIELDS)
+
+
+def _analytics_row_id(row: dict[str, Any]) -> dict[str, Any]:
+ return _synthetic_row_id(row, _ANALYTICS_ID_FIELDS)
+
+
def get_resource(
name: str,
should_use_incremental_field: bool,
@@ -156,6 +193,42 @@ def get_resource(
}
return roles_resource
+ if name == "Permissions":
+ endpoint = {
+ "path": "/v1/mgmt/permission/all",
+ "paginator": SinglePagePaginator(),
+ "data_selector": "permissions",
+ }
+ permissions_resource: EndpointResource = {
+ "name": name,
+ "table_name": "permissions",
+ "write_disposition": "replace",
+ "endpoint": endpoint,
+ "table_format": "delta",
+ }
+ return permissions_resource
+
+ if name == "Analytics":
+ endpoint = {
+ "path": "/v1/mgmt/analytics/search",
+ "method": "POST",
+ "json": _analytics_body(int(time.time() * 1000)),
+ "paginator": SinglePagePaginator(),
+ "data_selector": "analytics",
+ }
+ analytics_resource: EndpointResource = {
+ "name": name,
+ "table_name": "analytics",
+ # The aggregate restates every bucket in the window on each sync, including buckets a
+ # previous sync already wrote, so replacing the window is the only way counts stay
+ # right. The endpoint takes a `from` filter but returns no cursor to resume from.
+ "write_disposition": "replace",
+ "endpoint": endpoint,
+ "data_map": _analytics_row_id,
+ "table_format": "delta",
+ }
+ return analytics_resource
+
if name == "AccessKeys":
endpoint = {
"path": "/v1/mgmt/accesskey/search",
@@ -176,6 +249,98 @@ def get_resource(
raise ValueError(f"Unknown Descope endpoint: {name}")
+def _client(project_id: str, management_key: str) -> RESTClient:
+ return RESTClient(
+ base_url=DESCOPE_BASE_URL,
+ auth=BearerTokenAuth(token=bearer_token(project_id, management_key)),
+ request_timeout=REQUEST_TIMEOUT_SECONDS,
+ )
+
+
+def _tenant_ids(client: RESTClient) -> Iterator[str]:
+ for page in client.paginate(
+ path="/v1/mgmt/tenant/all",
+ paginator=SinglePagePaginator(),
+ data_selector="tenants",
+ ):
+ for tenant in page:
+ tenant_id = tenant.get("id")
+ if tenant_id:
+ yield str(tenant_id)
+
+
+def _groups_rows(project_id: str, management_key: str) -> Iterator[list[dict[str, Any]]]:
+ """Every external group in the project, fanned out over the tenant list.
+
+ Groups are only addressable per tenant, and each group already carries its members, so
+ `/v1/mgmt/group/members` and `/v1/mgmt/group/member/all` would only re-return filtered views
+ of these same rows.
+ """
+ client = _client(project_id, management_key)
+ for tenant_id in _tenant_ids(client):
+ for page in client.paginate(
+ method="post",
+ path="/v1/mgmt/group/all",
+ json={"tenantId": tenant_id},
+ paginator=SinglePagePaginator(),
+ data_selector="groups",
+ ):
+ rows = [{**group, "tenantId": tenant_id} for group in page]
+ if rows:
+ yield rows
+
+
+def _history_for_users(client: RESTClient, user_ids: list[str]) -> list[dict[str, Any]]:
+ rows: list[dict[str, Any]] = []
+ for page in client.paginate(
+ method="post",
+ path="/v2/mgmt/user/history",
+ json={"userIds": user_ids},
+ paginator=SinglePagePaginator(),
+ data_selector="usersAuthHistory",
+ ):
+ rows.extend(_synthetic_row_id(dict(row), _USER_HISTORY_ID_FIELDS) for row in page)
+ return rows
+
+
+def _user_history_rows(
+ project_id: str,
+ management_key: str,
+ resumable_source_manager: ResumableSourceManager[DescopeResumeConfig],
+) -> Iterator[list[dict[str, Any]]]:
+ """Authentication history for every user, one request per page of the user search.
+
+ The endpoint takes the user ids it reports on, so the user list has to be walked first. It
+ takes no timestamp filter, which is why this table is full refresh only.
+ """
+ client = _client(project_id, management_key)
+ next_page = 0
+ if resumable_source_manager.can_resume():
+ resume = resumable_source_manager.load_state()
+ if resume is not None:
+ next_page = resume.page
+
+ for page in client.paginate(
+ method="post",
+ path="/v2/mgmt/user/search",
+ json=_users_body(
+ should_use_incremental_field=False, incremental_field=None, db_incremental_field_last_value=None
+ ),
+ paginator=PageNumberPaginator(base_page=0, page_param="page", param_location="json"),
+ data_selector="users",
+ initial_paginator_state={"page": next_page},
+ ):
+ user_ids = [str(user["userId"]) for user in page if user.get("userId")]
+ next_page += 1
+ if user_ids:
+ rows = _history_for_users(client, user_ids)
+ if rows:
+ yield rows
+ # Checkpoint the page just drained, so a resume starts at the one after it rather than
+ # re-emitting history rows the pipeline has already written.
+ resumable_source_manager.save_state(DescopeResumeConfig(page=next_page))
+
+
def descope_source(
project_id: str,
management_key: str,
@@ -187,51 +352,61 @@ def descope_source(
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
- )
+ # Groups and UserHistory bind their parent through the POST body, which the declarative
+ # fan-out cannot express: it only resolves a parent field into the path or the query string.
+ items: Callable[[], Any]
+ if endpoint == "Groups":
+ items = lambda: _groups_rows(project_id, management_key)
+ elif endpoint == "UserHistory":
+ items = lambda: _user_history_rows(project_id, management_key, resumable_source_manager)
+ else:
+ 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),
+ config: RESTAPIConfig = {
+ "client": {
+ "base_url": DESCOPE_BASE_URL,
+ "auth": {
+ "type": "bearer",
+ "token": bearer_token(project_id, management_key),
+ },
},
- },
- "resources": [resource_config],
- }
+ "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,
- )
+ 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,
+ )
+ items = lambda: resource
+ partition_key = PARTITION_KEYS.get(endpoint)
return SourceResponse(
- name=resource.name,
- items=lambda: resource,
+ name=endpoint,
+ items=items,
primary_keys=PRIMARY_KEYS[endpoint],
- partition_mode="datetime",
- partition_keys=[PARTITION_KEYS[endpoint]],
+ partition_mode="datetime" if partition_key else None,
+ partition_keys=[partition_key] if partition_key else None,
sort_mode="asc",
)
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
index e7e864edd247..539c2103bb38 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/descope/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/descope/settings.py
@@ -6,11 +6,15 @@ ENDPOINTS = (
"Tenants",
"Roles",
"AccessKeys",
+ "Permissions",
+ "Groups",
+ "UserHistory",
+ "Analytics",
)
# 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).
+# descope/python-sdk and descope/node-sdk management clients). Every other endpoint is an
+# unpaginated full list with no timestamp filter, so they're full-refresh only (omitted here).
INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
"Users": [
{
@@ -50,14 +54,32 @@ PRIMARY_KEYS: dict[str, list[str]] = {
"Tenants": ["id"],
"Roles": ["id"],
"AccessKeys": ["id"],
+ "Permissions": ["id"],
+ # Group ids come from the customer's identity provider, so they are only unique within the
+ # tenant the group was loaded for.
+ "Groups": ["tenantId", "id"],
+ # Neither authentication history nor the analytics aggregate carries a record id, so both get
+ # a synthetic one derived from the fields that make the row unique — see descope.py.
+ "UserHistory": ["id"],
+ "Analytics": ["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.
+# since that changes over time and would rewrite partitions on every sync. Endpoints absent here
+# carry no timestamp at all: permissions, groups and the analytics aggregate sync unpartitioned.
PARTITION_KEYS: dict[str, str] = {
"Users": "createdTime",
"Audit": "occurred",
"Tenants": "createdTime",
"Roles": "createdTime",
"AccessKeys": "createdTime",
+ "UserHistory": "loginTime",
}
+
+# `POST /v1/mgmt/analytics/search` rejects a `from` further back than 12 months. Ask for a day
+# less: the window is computed when the resource is built and the request goes out later, so
+# asking for the full 365 days would put a retry outside the limit. Every sync pulls the whole
+# window, since the response carries no cursor a later sync could resume from.
+ANALYTICS_LOOKBACK_DAYS = 364
+# How the aggregate buckets its dates: "h" hour, "d" day, "w" week, "m" month, "q" quarter.
+ANALYTICS_BUCKET = "d"
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 dd7dbceaaec3..1f9566dd22b5 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
@@ -107,7 +107,7 @@ class DescopeSource(ResumableSource[DescopeSourceConfig, DescopeResumeConfig]):
name=ExternalDataSourceType.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.",
+ caption="Sync users, their authentication history, audit trail events, sign-in analytics, tenants, groups, roles, permissions, 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",
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
index 94cfb5b87567..55da8cb68b68 100644
--- 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
@@ -7,7 +7,9 @@ from unittest import mock
from requests import Response
from products.warehouse_sources.backend.temporal.data_imports.sources.descope.descope import (
+ DAY_MS,
DescopeResumeConfig,
+ _analytics_body,
_audit_body,
_audit_row_id,
_users_body,
@@ -17,6 +19,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.descope.de
validate_credentials,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.descope.settings import (
+ ANALYTICS_LOOKBACK_DAYS,
ENDPOINTS,
PARTITION_KEYS,
PRIMARY_KEYS,
@@ -30,6 +33,19 @@ DESCOPE_SESSION_PATCH = (
)
+SELECTORS = {
+ "Users": "users",
+ "Audit": "audits",
+ "Tenants": "tenants",
+ "Roles": "roles",
+ "AccessKeys": "keys",
+ "Permissions": "permissions",
+ "Analytics": "analytics",
+ "Groups": "groups",
+ "UserHistory": "users",
+}
+
+
def _response(payload: dict[str, Any]) -> Response:
resp = Response()
resp.status_code = 200
@@ -162,6 +178,47 @@ class TestAuditRowId:
row = _audit_row_id({})
assert isinstance(row["id"], str) and len(row["id"]) == 64
+ def test_hash_is_stable_across_releases(self):
+ # Audit rows already in customers' tables are keyed on this digest. Changing how it is
+ # built re-keys every row and duplicates the table on the next merge.
+ row = _audit_row_id(
+ {
+ "userId": "u1",
+ "action": "login",
+ "occurred": 1700000000000,
+ "device": "Desktop",
+ "method": "otp",
+ "remoteAddress": "1.2.3.4",
+ }
+ )
+ assert row["id"] == "9355be9401127bf98697c12f126210eb29af88dfe8a1eb6e7b665ff3d041acd0"
+
+
+class TestAnalyticsBody:
+ def test_window_starts_one_year_before_now(self):
+ now_ms = 1_700_000_000_000
+ body = _analytics_body(now_ms)
+
+ assert body["from"] == now_ms - ANALYTICS_LOOKBACK_DAYS * DAY_MS
+ assert "to" not in body
+
+ def test_groups_on_every_dimension(self):
+ # Dropping a groupBy collapses rows into counts we cannot split apart again.
+ body = _analytics_body(1_700_000_000_000)
+
+ assert body["groupByCreated"] == "d"
+ assert all(
+ body[key] is True
+ for key in (
+ "groupByAction",
+ "groupByDevice",
+ "groupByMethod",
+ "groupByGeo",
+ "groupByTenant",
+ "groupByReferrer",
+ )
+ )
+
class TestGetResource:
@pytest.mark.parametrize(
@@ -172,6 +229,8 @@ class TestGetResource:
("Tenants", "/v1/mgmt/tenant/all", None, "tenants"),
("Roles", "/v1/mgmt/role/search", "POST", "roles"),
("AccessKeys", "/v1/mgmt/accesskey/search", "POST", "keys"),
+ ("Permissions", "/v1/mgmt/permission/all", None, "permissions"),
+ ("Analytics", "/v1/mgmt/analytics/search", "POST", "analytics"),
],
)
def test_endpoint_shape(self, endpoint, expected_path, expected_method, expected_selector):
@@ -201,7 +260,7 @@ class TestGetResource:
)
assert resource["write_disposition"] == {"disposition": "merge", "strategy": "upsert"}
- @pytest.mark.parametrize("endpoint", ["Tenants", "Roles", "AccessKeys"])
+ @pytest.mark.parametrize("endpoint", ["Tenants", "Roles", "AccessKeys", "Permissions", "Analytics"])
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
@@ -347,6 +406,7 @@ class TestFullRefreshEndpoints:
("Tenants", "tenants", "tenants"),
("Roles", "roles", "roles"),
("AccessKeys", "keys", "keys"),
+ ("Permissions", "permissions", "permissions"),
],
)
@mock.patch(CLIENT_SESSION_PATCH)
@@ -365,14 +425,118 @@ class TestDescopeSourceResponse:
@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: []})])
+ _wire(session, [_response({selector: []}) for selector in SELECTORS.values()])
response = _source(endpoint=endpoint)
+ assert response.name == 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]]
+ # Permissions, Groups and Analytics carry no timestamp, so they sync unpartitioned;
+ # partitioning them on a field their rows lack would fail the write.
+ partition_key = PARTITION_KEYS.get(endpoint)
+ assert response.partition_mode == ("datetime" if partition_key else None)
+ assert response.partition_keys == ([partition_key] if partition_key else None)
+
+
+class TestGroupsFanOut:
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_loads_groups_per_tenant_and_stamps_the_tenant_id(self, MockSession):
+ session = MockSession.return_value
+ bodies = _wire(
+ session,
+ [
+ _response({"tenants": [{"id": "T1"}, {"id": "T2"}]}),
+ _response({"groups": [{"id": "g1", "display": "Engineering"}]}),
+ _response({"groups": [{"id": "g1", "display": "Support"}]}),
+ ],
+ )
+
+ rows = _rows(_source(endpoint="Groups"))
+
+ # The group id repeats across tenants, which is why the tenant has to ride on the row —
+ # the primary key is ["tenantId", "id"].
+ assert rows == [
+ {"id": "g1", "display": "Engineering", "tenantId": "T1"},
+ {"id": "g1", "display": "Support", "tenantId": "T2"},
+ ]
+ assert bodies[1] == {"tenantId": "T1"}
+ assert bodies[2] == {"tenantId": "T2"}
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_tenant_without_groups_yields_nothing(self, MockSession):
+ session = MockSession.return_value
+ # Descope omits the `groups` key entirely for a tenant with none.
+ _wire(session, [_response({"tenants": [{"id": "T1"}]}), _response({})])
+
+ assert _rows(_source(endpoint="Groups")) == []
+
+
+class TestUserHistoryFanOut:
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_posts_each_user_page_and_checkpoints_after_it(self, MockSession):
+ session = MockSession.return_value
+ bodies = _wire(
+ session,
+ [
+ _response({"users": [{"userId": "u1"}, {"userId": "u2"}]}),
+ _response({"usersAuthHistory": [{"userId": "u1", "loginTime": 1700000000}]}),
+ _response({"users": []}),
+ ],
+ )
+
+ manager = _make_manager()
+ rows = _rows(_source(endpoint="UserHistory", manager=manager))
+
+ assert bodies[0]["page"] == 0
+ assert bodies[1] == {"userIds": ["u1", "u2"]}
+ assert bodies[2]["page"] == 1
+ assert len(rows) == 1
+ assert len(rows[0]["id"]) == 64
+ # Saved only once the page's history rows were yielded, so a resume cannot skip them.
+ assert manager.save_state.call_args_list == [
+ mock.call(DescopeResumeConfig(page=1)),
+ mock.call(DescopeResumeConfig(page=2)),
+ ]
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_resumes_from_the_saved_user_page(self, MockSession):
+ session = MockSession.return_value
+ bodies = _wire(session, [_response({"users": []})])
+
+ manager = _make_manager(DescopeResumeConfig(page=4))
+ _rows(_source(endpoint="UserHistory", manager=manager))
+
+ assert bodies[0]["page"] == 4
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_user_page_without_ids_skips_the_history_request(self, MockSession):
+ session = MockSession.return_value
+ _wire(session, [_response({"users": [{"loginIds": ["[email protected]"]}]}), _response({"users": []})])
+
+ assert _rows(_source(endpoint="UserHistory")) == []
+ assert session.send.call_count == 2
+
+
+class TestAnalyticsFetch:
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_synthesizes_a_row_id_per_grouping_bucket(self, MockSession):
+ session = MockSession.return_value
+ _wire(
+ session,
+ [
+ _response(
+ {
+ "analytics": [
+ {"created": "2026-09-01", "action": "login", "method": "otp", "cnt": "12"},
+ {"created": "2026-09-01", "action": "login", "method": "oauth", "cnt": "3"},
+ ]
+ }
+ )
+ ],
+ )
+
+ rows = _rows(_source(endpoint="Analytics"))
+
+ assert session.send.call_count == 1
+ assert rows[0]["id"] != rows[1]["id"]