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 8 Anthropic Claude Enterprise tables (#99200)

Tom Owers3122de98266c
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 d981a51a020e..0c57755797e4 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
@@ -303,7 +303,7 @@ Note: Endpoint paths confirmed by reading https://amplitude.com/docs/apis/analyt
## Anthropic — gaps
-Today (12): `analytics_user_activity`, `analytics_user_cost`, `analytics_user_usage`, `api_keys`, `claude_code_analytics`, `claude_code_model_breakdown`, `cost_report`, `invites`, `usage_report`, `users`, `workspace_members`, `workspaces`
+Today (20): `analytics_connector_usage`, `analytics_plugin_usage`, `analytics_skill_usage`, `analytics_summaries`, `analytics_user_activity`, `analytics_user_cost`, `analytics_user_usage`, `api_keys`, `claude_code_analytics`, `claude_code_model_breakdown`, `cost_report`, `invites`, `rbac_group_members`, `rbac_groups`, `rbac_role_permissions`, `rbac_roles`, `usage_report`, `users`, `workspace_members`, `workspaces`
Diffed against: <https://platform.claude.com/llms.txt>
@@ -311,16 +311,16 @@ Diffed against: <https://platform.claude.com/llms.txt>
- [x] `GET /v1/organizations/analytics/users (List User Activity)` — per-seat activity, the core seat-utilization table (high)
- [x] `GET /v1/organizations/analytics/user_cost_report (Get Per-User Cost)` — cost attribution per user rather than only org-level cost_report (high)
- [x] `GET /v1/organizations/analytics/user_usage_report (Get Per-User Token Usage)` — token usage per user, needed for chargeback and adoption analysis (high)
-- [ ] `GET /v1/organizations/rbac_groups and .../rbac_groups/{id}/members` — group definitions plus the membership join for the users already synced (high)
-- [ ] `GET /v1/organizations/rbac_roles and .../rbac_roles/{id}/permissions` — lookup resolving the role identifiers carried on users and workspace_members (medium)
-- [ ] `GET /v1/organizations/analytics/summaries (Get Activity Summaries)` — rolled-up org activity as the vendor reports it (medium)
+- [x] `GET /v1/organizations/rbac_groups and .../rbac_groups/{id}/members` — group definitions plus the membership join for the users already synced (high)
+- [x] `GET /v1/organizations/rbac_roles and .../rbac_roles/{id}/permissions` — lookup resolving the role identifiers carried on the groups a user holds (medium)
+- [x] `GET /v1/organizations/analytics/summaries (Get Activity Summaries)` — rolled-up org activity as the vendor reports it (medium)
+- [x] `GET /v1/organizations/analytics/connectors, /plugins, /skills` — adoption breakdown by connector, plugin and skill (medium)
- ~~`GET /v1/organizations/service_accounts/{id}/workspaces and /workspaces/{id}/service_accounts`~~ — not reachable: Anthropic serves the service-account endpoints only to an `org:admin` OAuth token, which this source never holds
-- [ ] `GET /v1/organizations/analytics/connectors, /plugins, /skills` — adoption breakdown by connector, plugin and skill (medium)
- [ ] `GET /v1/messages/batches` — batch job history with request counts and status, for batch spend analysis (medium)
- [ ] `GET /v1/organizations/analytics/chat_projects and /analytics/artifacts` — Claude project and artifact usage breakdown (low)
- [ ] `GET /v1/organizations/me` — organization lookup row to anchor the org-scoped tables (low)
-Note: Admin API coverage of the identity objects is good. The three per-seat tables from the /v1/organizations/analytics/\* family are covered; the rest of that family (summaries, connectors, plugins, skills, chat projects, artifacts) is not. Those endpoints need a Claude Enterprise key carrying the `read:analytics` scope, which is a different key from the Claude Console Admin API key, so they stay off by default and `get_endpoint_permissions` reports whether the configured key can reach them. There is still no model lookup for the model IDs carried in usage_report/cost_report. The Compliance API (chats, projects, code artifacts, organization users) is a separate auth-gated surface for Enterprise plans and would need its own credential.
+Note: Admin API coverage of the identity objects is good. The /v1/organizations/analytics/\* family is covered except for chat projects and artifacts. Those endpoints need a Claude Enterprise key carrying the `read:analytics` scope, which is a different key from the Claude Console Admin API key, so they stay off by default and `get_endpoint_permissions` reports whether the configured key can reach them. The group and custom-role reads are Claude Enterprise only too, and take their own `read:rbac_groups` and `read:members` scopes, so they are off by default and separately probed. There is still no model lookup for the model IDs carried in usage_report/cost_report. The Compliance API (chats, projects, code artifacts, organization users) is a separate auth-gated surface for Enterprise plans and would need its own credential.
## ApifyDataset — **thin**
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/anthropic/anthropic.py b/products/warehouse_sources/backend/temporal/data_imports/sources/anthropic/anthropic.py
index b4e553a151ac..fd8ceb5bfeb0 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/anthropic/anthropic.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/anthropic/anthropic.py
@@ -14,9 +14,12 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.anthropic.
ANALYTICS_PATH_PREFIX,
ANTHROPIC_ENDPOINTS,
ENDPOINT_RETIRED_ERROR,
+ RBAC_GROUPS_PATH,
+ RBAC_ROLES_PATH,
USAGE_GROUP_BY_FALLBACKS,
AnalyticsWindowKind,
AnthropicEndpointConfig,
+ FanOutConfig,
PaginationType,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
@@ -66,6 +69,18 @@ ANALYTICS_ACCESS_MISSING = (
"a Claude Enterprise key with the read:analytics scope, created in claude.ai organization "
"settings by your primary owner."
)
+# Shown against the Claude Enterprise group and custom role tables in the schema picker when the
+# configured key cannot reach them. The two families take different scopes, so they get their own
+# probes and their own messages.
+RBAC_GROUP_ACCESS_MISSING = (
+ "This table comes from the Claude Enterprise user management API, which this key can't reach. It "
+ "needs an Admin API key with the read:rbac_groups scope, created in claude.ai organization "
+ "settings for all your linked organizations."
+)
+RBAC_ROLE_ACCESS_MISSING = (
+ "This table comes from the Claude Enterprise user management API, which this key can't reach. It "
+ "needs an Admin API key with the read:members scope, created in claude.ai organization settings."
+)
@frozen
@@ -247,8 +262,8 @@ def validate_credentials(api_key: str) -> bool:
return ok
-def check_analytics_access(api_key: str) -> Optional[str]:
- """Report whether the configured key can read the Claude Enterprise Analytics API.
+def _check_path_access(api_key: str, path: str, missing_reason: str) -> Optional[str]:
+ """Report whether the configured key can read a path that needs access beyond the Admin API key.
Returns None when it can, or the reason to show against the tables that need it. Only a real
denial counts as missing access: a throttle, a server error, or a network failure leaves those
@@ -257,16 +272,30 @@ def check_analytics_access(api_key: str) -> Optional[str]:
"""
_ok, status = validate_via_probe(
lambda: make_tracked_session(redact_values=(api_key,)),
- f"{ANTHROPIC_BASE_URL}{ANALYTICS_PATH_PREFIX}users?limit=1",
+ f"{ANTHROPIC_BASE_URL}{path}",
headers={"x-api-key": api_key, **_version_headers()},
)
# 404 as well as 403: an organization that is not on a Claude Enterprise plan does not serve
# these routes at all.
if status in (403, 404):
- return ANALYTICS_ACCESS_MISSING
+ return missing_reason
return None
+def check_analytics_access(api_key: str) -> Optional[str]:
+ return _check_path_access(api_key, f"{ANALYTICS_PATH_PREFIX}users?limit=1", ANALYTICS_ACCESS_MISSING)
+
+
+def check_rbac_group_access(api_key: str) -> Optional[str]:
+ return _check_path_access(api_key, f"{RBAC_GROUPS_PATH}?limit=1", RBAC_GROUP_ACCESS_MISSING)
+
+
+def check_rbac_role_access(api_key: str) -> Optional[str]:
+ # The custom role reads take their own scope, so a key that reaches the group tables can still
+ # be denied here.
+ return _check_path_access(api_key, f"{RBAC_ROLES_PATH}?limit=1", RBAC_ROLE_ACCESS_MISSING)
+
+
def _flatten_created_by(item: dict[str, Any]) -> dict[str, Any]:
"""api_keys carry a nested `created_by: {id, type}`; surface it as flat columns."""
created_by = item.get("created_by")
@@ -538,14 +567,18 @@ def _analytics_resume_day(resume: Optional[AnthropicResumeConfig]) -> Optional[d
def _analytics_params(config: AnthropicEndpointConfig, window: AnalyticsWindow) -> dict[str, Any]:
- params: dict[str, Any] = {"limit": config.limit}
if window.end is None:
- params["date"] = window.start.isoformat()
- return params
- params["starting_at"] = _format_rfc3339(window.start)
- params["ending_at"] = _format_rfc3339(window.end)
- params["bucket_width"] = config.bucket_width
- return params
+ return {"limit": config.limit, "date": window.start.isoformat()}
+ if config.analytics_window == AnalyticsWindowKind.DATE_RANGE:
+ # Calendar dates rather than RFC 3339 instants, and no `limit`: the summaries endpoint
+ # answers a whole range in one response and rejects pagination parameters.
+ return {"starting_date": window.start.isoformat(), "ending_date": window.end.isoformat()}
+ return {
+ "limit": config.limit,
+ "starting_at": _format_rfc3339(window.start),
+ "ending_at": _format_rfc3339(window.end),
+ "bucket_width": config.bucket_width,
+ }
def _iter_analytics_windows(
@@ -600,6 +633,71 @@ def _flatten_analytics_user_activity(day: date, item: dict[str, Any]) -> dict[st
return row
+def _flatten_analytics_entity_usage(name_field: str, day: date, item: dict[str, Any]) -> dict[str, Any]:
+ """One row per (day, entity) for the connector, plugin and skill adoption breakdowns.
+
+ Each record carries no day of its own, so the day the request asked for is stamped on. The
+ nested per-product metric blocks are flattened the same way the activity record's are, so a new
+ product's metrics arrive as columns with no change here.
+ """
+ row: dict[str, Any] = {"date": _format_rfc3339(day)}
+ for key, value in item.items():
+ if isinstance(value, dict):
+ # `chat_metrics` becomes `chat_distinct_conversation_skill_used_count`, and
+ # `office_metrics.excel` becomes `office_excel_distinct_session_skill_used_count`.
+ _flatten_metrics(key.removesuffix("_metrics"), value, row)
+ else:
+ row[key] = value
+ row["id"] = _row_id(row["date"], row.get(name_field))
+ return row
+
+
+# Endpoints whose rows carry no day, mapped to the flattener that stamps the requested day onto each
+# row. `analytics_row_map` binds the day before handing the mapper to the resource.
+_ANALYTICS_DAY_ROW_MAPS: dict[str, Callable[[date, dict[str, Any]], dict[str, Any]]] = {
+ "analytics_user_activity": _flatten_analytics_user_activity,
+ "analytics_connector_usage": partial(_flatten_analytics_entity_usage, "connector_name"),
+ "analytics_plugin_usage": partial(_flatten_analytics_entity_usage, "plugin_name"),
+ "analytics_skill_usage": partial(_flatten_analytics_entity_usage, "skill_name"),
+}
+
+
+def _flatten_rbac_role_permission(item: dict[str, Any]) -> dict[str, Any]:
+ """One row per (role, action, resource) grant.
+
+ `resource` is a tagged union whose `type` decides which identifier fields it carries, so every
+ identifier gets a column of its own and the ones a given tag does not use stay null. A blanket
+ `capability_access_all` or `capability_access_all_ga` action arrives as one row rather than
+ expanded per feature, so a query that tallies a role's grants has to treat it as covering every
+ product feature its variant describes.
+ """
+ resource = item.get("resource") or {}
+ role_id = item.get("role_id")
+ action = item.get("action")
+ resource_type = resource.get("type")
+ organization_id = resource.get("organization_id")
+ connector_id = resource.get("connector_id")
+ tool_name = resource.get("tool_name")
+ scope = resource.get("scope")
+ return {
+ "id": _row_id(role_id, action, resource_type, organization_id, connector_id, tool_name, scope),
+ "role_id": role_id,
+ "action": action,
+ "resource_type": resource_type,
+ "organization_id": organization_id,
+ "connector_id": connector_id,
+ "tool_name": tool_name,
+ "scope": scope,
+ }
+
+
+# Row mapping applied to a fan-out child after the parent id is stamped on. A child with no entry
+# needs nothing beyond the stamp.
+_FAN_OUT_ROW_MAPS: dict[str, Callable[[dict[str, Any]], dict[str, Any]]] = {
+ "rbac_role_permissions": _flatten_rbac_role_permission,
+}
+
+
def _analytics_actor_columns(item: dict[str, Any]) -> dict[str, Any]:
"""Surface the seat user a per-user report row is attributed to as flat columns."""
actor = item.get("actor") or {}
@@ -654,15 +752,18 @@ def _flatten_analytics_user_usage(item: dict[str, Any]) -> dict[str, Any]:
}
-def _stamp_workspace_id(row: dict[str, Any]) -> dict[str, Any]:
- # The member object already carries workspace_id, but fall back to the parent workspace's id
- # (injected by the fan-out as `_workspaces_id`) so the composite primary key is always populated.
- parent_id = row.pop("_workspaces_id", None)
- row["workspace_id"] = row.get("workspace_id") or parent_id
+def _stamp_parent_id(fan_out: FanOutConfig, row: dict[str, Any]) -> dict[str, Any]:
+ # The fan-out injects the parent's id as `_<parent>_id`. Fall back to it so the primary key is
+ # always populated: the member objects carry their own parent id, but a role permission object
+ # carries no role id at all.
+ parent_id = row.pop(f"_{fan_out.parent}_id", None)
+ row[fan_out.id_column] = row.get(fan_out.id_column) or parent_id
return row
-def _entity_paginator() -> AnthropicCursorPaginator:
+def _list_paginator(config: AnthropicEndpointConfig) -> AnthropicCursorPaginator:
+ if config.pagination == PaginationType.PAGE_TOKEN:
+ return AnthropicCursorPaginator(cursor_path="next_page", cursor_param="page")
return AnthropicCursorPaginator(cursor_path="last_id", cursor_param="after_id")
@@ -747,10 +848,13 @@ def anthropic_source(
def analytics_row_map(
window: AnalyticsWindow,
- ) -> Callable[[dict[str, Any]], dict[str, Any] | list[dict[str, Any]]]:
+ ) -> Optional[Callable[[dict[str, Any]], dict[str, Any] | list[dict[str, Any]]]]:
if config.analytics_window == AnalyticsWindowKind.DATE:
- # The engagement record carries no day, so bind the day this request asks for.
- return partial(_flatten_analytics_user_activity, window.start)
+ # These records carry no day, so bind the day this request asks for.
+ return partial(_ANALYTICS_DAY_ROW_MAPS[endpoint], window.start)
+ if config.analytics_window == AnalyticsWindowKind.DATE_RANGE:
+ # A summary row is already flat and carries its own `starting_at`.
+ return None
return _flatten_analytics_user_cost if endpoint == "analytics_user_cost" else _flatten_analytics_user_usage
def save_analytics_checkpoint(next_start: date) -> None:
@@ -764,7 +868,7 @@ def anthropic_source(
"endpoint": {
"path": config.path,
"params": _analytics_params(config, window),
- "data_selector": "data",
+ "data_selector": config.data_selector,
"paginator": AnthropicCursorPaginator(cursor_path="next_page", cursor_param="page"),
},
"data_map": analytics_row_map(window),
@@ -828,21 +932,29 @@ def anthropic_source(
resume_hook=save_day_checkpoint,
initial_paginator_state=initial_day_state,
)
- elif config.fan_out_over_workspaces:
- # No org-wide member list exists; enumerate every workspace (archived included, since they
- # are still referenced by historical usage/cost rows) and fetch its /members per workspace.
- workspaces_config = ANTHROPIC_ENDPOINTS["workspaces"]
+ elif config.fan_out is not None:
+ # Anthropic serves no org-wide list for this sub-resource, so enumerate the parent endpoint
+ # and fetch the sub-resource once per parent row. The workspaces parent includes archived
+ # workspaces (see its extra_params), since historical usage and cost rows still name them.
+ fan_out = config.fan_out
+ parent_config = ANTHROPIC_ENDPOINTS[fan_out.parent]
+ child_row_map = _FAN_OUT_ROW_MAPS.get(endpoint)
+
+ def fan_out_data_map(row: dict[str, Any]) -> dict[str, Any]:
+ stamped = _stamp_parent_id(fan_out, row)
+ return child_row_map(stamped) if child_row_map else stamped
+
rest_config: RESTAPIConfig = {
"client": client_config,
"resource_defaults": None,
"resources": [
{
- "name": "workspaces",
+ "name": fan_out.parent,
"endpoint": {
- "path": workspaces_config.path,
- "params": {"limit": ENTITY_PAGE_SIZE, **workspaces_config.extra_params},
- "data_selector": "data",
- "paginator": _entity_paginator(),
+ "path": parent_config.path,
+ "params": {"limit": ENTITY_PAGE_SIZE, **parent_config.extra_params},
+ "data_selector": parent_config.data_selector,
+ "paginator": _list_paginator(parent_config),
},
},
{
@@ -851,24 +963,24 @@ def anthropic_source(
"path": config.path,
"params": {
"limit": ENTITY_PAGE_SIZE,
- "workspace_id": {"type": "resolve", "resource": "workspaces", "field": "id"},
+ fan_out.path_param: {"type": "resolve", "resource": fan_out.parent, "field": "id"},
},
- "data_selector": "data",
- "paginator": _entity_paginator(),
- # A workspace that does not serve this sub-resource (or was archived between
- # enumeration and the child fetch) answers 404 — skip it rather than fail the
- # whole schema. 429/5xx are retried by the client before hooks run, and any
- # other 4xx still raises.
+ "data_selector": config.data_selector,
+ "paginator": _list_paginator(config),
+ # A parent that does not serve this sub-resource, or that was archived or
+ # deleted between enumeration and the child fetch, answers 404. Skip that
+ # parent instead of failing the whole schema. 429/5xx are retried by the
+ # client before hooks run, and any other 4xx still raises.
"response_actions": [{"status_code": 404, "action": "ignore"}],
},
"include_from_parent": ["id"],
- "data_map": _stamp_workspace_id,
+ "data_map": fan_out_data_map,
},
],
}
- # Only a framework-shaped checkpoint can seed the fan-out; a legacy (cursor, workspace_id)
- # state restarts the fan-out fresh — the overlap merge dedupes on the composite key.
+ # Only a framework-shaped checkpoint can seed the fan-out. A legacy (cursor, workspace_id)
+ # state restarts the fan-out fresh, and the overlap merge dedupes on the composite key.
initial_fanout_state = resume.fanout_state if resume is not None else None
def save_fanout_checkpoint(state: Optional[dict[str, Any]]) -> None:
@@ -923,14 +1035,14 @@ def anthropic_source(
paginator: BasePaginator = AnthropicCursorPaginator(cursor_path="next_page", cursor_param="page")
else:
params = {"limit": ENTITY_PAGE_SIZE, **config.extra_params}
- paginator = _entity_paginator()
+ paginator = _list_paginator(config)
endpoint_resource: EndpointResource = {
"name": endpoint,
"endpoint": {
"path": config.path,
"params": params,
- "data_selector": "data",
+ "data_selector": config.data_selector,
"paginator": paginator,
},
"data_map": data_map,
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/anthropic/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/anthropic/canonical_descriptions.py
index 83306b09b3c2..4545c8d24b83 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/anthropic/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/anthropic/canonical_descriptions.py
@@ -4,6 +4,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.can
_ADMIN_API_DOCS = "https://platform.claude.com/docs/en/api/admin-api"
_ANALYTICS_API_DOCS = "https://platform.claude.com/docs/en/api/admin/analytics"
+_USER_MANAGEMENT_API_DOCS = "https://platform.claude.com/docs/en/api/admin"
CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"users": {
@@ -233,4 +234,186 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"web_search_requests": "Web search requests made through server-side tool use.",
},
},
+ "rbac_groups": {
+ "description": (
+ "Groups in your Claude Enterprise organization, the join between members and the custom "
+ "roles that grant their permissions. Groups are owned by the enterprise as a whole, so "
+ "this table spans every linked organization."
+ ),
+ "docs_url": f"{_USER_MANAGEMENT_API_DOCS}/rbac_groups/list",
+ "columns": {
+ "id": "Unique identifier for the group, prefixed rbac_group_.",
+ "type": 'Object type, always "rbac_group".',
+ "name": "Display name of the group. Anthropic does not enforce uniqueness.",
+ "roles": "IDs of the custom roles attached to the group. Null when role data was temporarily unavailable, rather than empty.",
+ "source_type": 'How the group was created: "direct" in claude.ai, or "scim" by your identity provider.',
+ "created_at": "RFC 3339 timestamp of when the group was created.",
+ "updated_at": "RFC 3339 timestamp of when the group was last updated.",
+ },
+ },
+ "rbac_group_members": {
+ "description": (
+ "Membership rows mapping users to the Claude Enterprise groups they hold, one row per "
+ "(group, user). Joins to users on user_id and to rbac_groups on group_id."
+ ),
+ "docs_url": f"{_USER_MANAGEMENT_API_DOCS}/rbac_groups/members/list",
+ "columns": {
+ "type": 'Object type, always "rbac_group_member".',
+ "group_id": "ID of the group the user holds.",
+ "user_id": "ID of the member user.",
+ "email": "Email address of the member user.",
+ "created_at": "RFC 3339 timestamp of when the user was added to the group.",
+ },
+ },
+ "rbac_roles": {
+ "description": (
+ "Custom roles defined in your Claude Enterprise organization, the lookup resolving the "
+ "role IDs carried on rbac_groups. The role catalog is per-organization while groups span "
+ "the enterprise, so a group can name a role this table does not contain."
+ ),
+ "docs_url": f"{_USER_MANAGEMENT_API_DOCS}/rbac_roles/list",
+ "columns": {
+ "id": "Unique identifier for the custom role, prefixed rbac_role_.",
+ "type": 'Object type, always "rbac_role".',
+ "name": "Display name of the custom role.",
+ "created_at": "RFC 3339 timestamp of when the role was created.",
+ "updated_at": "RFC 3339 timestamp of when the role was last updated.",
+ },
+ },
+ "rbac_role_permissions": {
+ "description": (
+ "What each custom role grants, one row per (role, action, resource). Anthropic omits rows "
+ "for features your organization has not enabled. A capability_access_all or "
+ "capability_access_all_ga action is a blanket grant listed as a single row, so a tally of "
+ "a role's access has to treat it as covering every product feature it describes rather "
+ "than only the features named in other rows."
+ ),
+ "docs_url": f"{_USER_MANAGEMENT_API_DOCS}/rbac_roles/permissions/list",
+ "columns": {
+ "id": "Synthesized surrogate key: a hash of the role plus the action and resource the row grants.",
+ "role_id": "ID of the custom role the permission belongs to.",
+ "action": "What the permission grants on the resource: a product-feature or admin-panel entitlement on an organization resource, a tool-access action (use, always_allow) on a connector, an authentication-method action (interactive, managed), or grant on a connector OAuth scope.",
+ "resource_type": "What the permission applies to: organization, connector, all_connectors, connector_tool, or connector_scope.",
+ "organization_id": "UUID of the organization, on an organization resource. Null otherwise.",
+ "connector_id": "ID of the connector, on a connector, connector_tool or connector_scope resource. Null otherwise.",
+ "tool_name": "Published name of the connector tool, on a connector_tool resource. Server-encoded to a prefix plus hash when the published name holds characters outside [a-zA-Z0-9_-].",
+ "scope": "OAuth scope the role may receive when tokens are minted for the connector, on a connector_scope resource. Usually server-encoded, because OAuth scopes commonly contain : and /.",
+ },
+ },
+ "analytics_connector_usage": {
+ "description": (
+ "Connector adoption, one row per connector per UTC day. Connector names are normalized "
+ 'across their sources, so "Atlassian MCP server" and "mcp-atlassian" both appear as '
+ '"atlassian". Metric columns are prefixed by the product surface they measure: chat, '
+ "claude_code, cowork and office (per Office app)."
+ ),
+ "docs_url": f"{_ANALYTICS_API_DOCS}/connectors/list",
+ "columns": {
+ "id": "Synthesized surrogate key: a hash of the day and the connector name.",
+ "date": "UTC day the metrics are aggregated over, in RFC 3339 format.",
+ "connector_name": "Normalized name of the connector, and the row's stable key. Holds an opaque connector ID on some rows.",
+ "connector_display_name": "Readable name for rows whose connector_name is an opaque ID. Null when connector_name is already readable or the ID no longer resolves. Not unique.",
+ "distinct_user_count": "Distinct users who used the connector that day.",
+ "individual_auth_distinct_user_count": "Distinct users whose use of the connector ran on their own credential, connected through their own consent flow.",
+ "managed_auth_distinct_user_count": "Distinct users whose use of the connector ran on an organization-managed credential provisioned through your identity provider. Null, never 0, when managed-auth reporting is off or the day predates 2026-07-01.",
+ "read_call_count": "Connector tool calls whose read-only annotation marked them read-only. Null, never 0, when the read/write split is off for your organization or the day predates 2026-05-29.",
+ "write_call_count": "Connector tool calls whose read-only annotation marked them not read-only.",
+ "unclassified_call_count": "Connector tool calls with no trusted read-only annotation. The annotation is optional in the MCP spec, so this bucket is commonly large.",
+ "chat_distinct_conversation_connector_used_count": "Distinct Claude chat conversations the connector was used in.",
+ "claude_code_distinct_session_connector_used_count": "Distinct Claude Code sessions the connector was used in.",
+ "cowork_distinct_session_connector_used_count": "Distinct Cowork sessions the connector was used in.",
+ "office_excel_distinct_session_connector_used_count": "Distinct Claude in Excel sessions the connector was used in.",
+ "office_outlook_distinct_session_connector_used_count": "Distinct Claude in Outlook sessions the connector was used in.",
+ "office_powerpoint_distinct_session_connector_used_count": "Distinct Claude in PowerPoint sessions the connector was used in.",
+ "office_word_distinct_session_connector_used_count": "Distinct Claude in Word sessions the connector was used in.",
+ },
+ },
+ "analytics_plugin_usage": {
+ "description": (
+ "Plugin installs and invocations across Cowork and Claude Code, one row per plugin per "
+ 'UTC day. The plugin_name value "third-party" is an aggregate bucket rather than a '
+ "plugin: it collects activity the reporting client sent no plugin name for."
+ ),
+ "docs_url": f"{_ANALYTICS_API_DOCS}/plugins/list",
+ "columns": {
+ "id": "Synthesized surrogate key: a hash of the day and the plugin name.",
+ "date": "UTC day the metrics are aggregated over, in RFC 3339 format.",
+ "plugin_name": "Name of the plugin, and the row's stable key.",
+ "plugin_id": "Stable plugin identifier (for example serena@claude-plugins-official). Null for third-party Claude Code plugins and for Cowork slash commands that carry only a hashed ID.",
+ "distinct_user_count": "Distinct users with install or invocation activity for the plugin that day. Install-only users count.",
+ "install_count": "Distinct users who installed the plugin that day.",
+ "invocation_count": "Plugin invocations that day.",
+ "claude_code_distinct_session_plugin_used_count": "Distinct Claude Code sessions the plugin was invoked in.",
+ "cowork_distinct_session_plugin_used_count": "Distinct Cowork sessions the plugin was invoked in.",
+ },
+ },
+ "analytics_skill_usage": {
+ "description": (
+ "Skill adoption and the spend attributed to each skill, one row per skill per UTC day. A "
+ "skill counts as used only when it is explicitly activated, so a skill that is merely "
+ "installed, listed, or read as a plain file is not counted. Metric columns are prefixed "
+ "by the product surface they measure: chat, claude_code, cowork and office (per Office app)."
+ ),
+ "docs_url": f"{_ANALYTICS_API_DOCS}/skills/list",
+ "columns": {
+ "id": "Synthesized surrogate key: a hash of the day and the skill name.",
+ "date": "UTC day the metrics are aggregated over, in RFC 3339 format.",
+ "skill_name": "Name of the skill, and the row's stable key. Holds an opaque skill ID for user and organization skill types and plugin-delivered skills.",
+ "skill_display_name": "Readable name for rows whose skill_name is an opaque ID. Null for private user-defined skills, whose names are not disclosed to analytics keys.",
+ "share_status": "Share status on claude.ai: private, organization, or public. Null for skills used only in Claude Code or Office.",
+ "distinct_user_count": "Distinct users who activated the skill that day.",
+ "invocation_count": "Times the skill was activated that day. Null when invocation reporting is off for your organization.",
+ "enable_count": "Distinct accounts that enabled the skill that day, on claude.ai only. Null when enable reporting is off for your organization.",
+ "estimated_overage_spend": "Estimated post-discount, pre-credit overage spend attributed to the skill, in fractional cents as a decimal string. An estimate of the cost of the requests the skill took part in, not the skill's incremental cost. Usage covered by seat allowances allocates 0.",
+ "attributed_list_price": "List-price value of the member requests attributed to the skill, in fractional cents as a decimal string. Counts seat-covered usage too, so it does not tie to billed spend. Null on chat rows, which carry no request-level attribution.",
+ "currency": 'Currency code for the monetary columns, always "USD" when either is populated and null when both are null.',
+ "chat_distinct_conversation_skill_used_count": "Distinct Claude chat conversations the skill was activated in.",
+ "claude_code_distinct_session_skill_used_count": "Distinct Claude Code sessions the skill was activated in.",
+ "cowork_distinct_session_skill_used_count": "Distinct Cowork sessions the skill was activated in.",
+ "office_excel_distinct_session_skill_used_count": "Distinct Claude in Excel sessions the skill was activated in.",
+ "office_outlook_distinct_session_skill_used_count": "Distinct Claude in Outlook sessions the skill was activated in.",
+ "office_powerpoint_distinct_session_skill_used_count": "Distinct Claude in PowerPoint sessions the skill was activated in.",
+ "office_word_distinct_session_skill_used_count": "Distinct Claude in Word sessions the skill was activated in.",
+ },
+ },
+ "analytics_summaries": {
+ "description": (
+ "Organization-wide activity and adoption as Anthropic rolls it up, one row per UTC day. "
+ "Active-user counts come in three windows: the day itself, and the 7- and 30-day rolling "
+ "windows ending on it. Per-product columns are omitted while the per-product breakdown is "
+ "not enabled for your organization."
+ ),
+ "docs_url": f"{_ANALYTICS_API_DOCS}/retrieve_summaries",
+ "columns": {
+ "starting_at": "Start of the day the row covers, UTC midnight in RFC 3339 format.",
+ "ending_at": "End of the day the row covers (exclusive), UTC midnight in RFC 3339 format.",
+ "assigned_seat_count": "Seats assigned to members at the time of the daily snapshot.",
+ "pending_invite_count": "Invitations to join the organization still pending.",
+ "daily_active_user_count": "Members with token consumption on the day.",
+ "weekly_active_user_count": "Members with token consumption in the 7-day rolling window.",
+ "monthly_active_user_count": "Members with token consumption in the 30-day rolling window.",
+ "daily_adoption_rate": "Percentage of assigned seats active on the day (DAU / assigned_seat_count * 100).",
+ "weekly_adoption_rate": "Percentage of assigned seats active in the 7-day rolling window.",
+ "monthly_adoption_rate": "Percentage of assigned seats active in the 30-day rolling window.",
+ "chat_daily_active_user_count": "Members with claude.ai chat activity on the day.",
+ "chat_weekly_active_user_count": "Members with claude.ai chat activity in the 7-day rolling window.",
+ "chat_monthly_active_user_count": "Members with claude.ai chat activity in the 30-day rolling window.",
+ "claude_code_daily_active_user_count": "Members with Claude Code activity on the day.",
+ "claude_code_weekly_active_user_count": "Members with Claude Code activity in the 7-day rolling window.",
+ "claude_code_monthly_active_user_count": "Members with Claude Code activity in the 30-day rolling window.",
+ "cowork_daily_active_user_count": "Members with Cowork activity on the day.",
+ "cowork_weekly_active_user_count": "Members with Cowork activity in the 7-day rolling window.",
+ "cowork_monthly_active_user_count": "Members with Cowork activity in the 30-day rolling window.",
+ "claude_design_daily_active_user_count": "Members with Claude Design activity on the day.",
+ "claude_design_weekly_active_user_count": "Members with Claude Design activity in the 7-day rolling window.",
+ "claude_design_monthly_active_user_count": "Members with Claude Design activity in the 30-day rolling window.",
+ "office_agent_daily_active_user_count": "Members with Claude in Office activity on the day.",
+ "office_agent_weekly_active_user_count": "Members with Claude in Office activity in the 7-day rolling window.",
+ "office_agent_monthly_active_user_count": "Members with Claude in Office activity in the 30-day rolling window.",
+ "science_daily_active_user_count": "Members with Claude Science activity on the day.",
+ "science_weekly_active_user_count": "Members with Claude Science activity in the 7-day rolling window.",
+ "science_monthly_active_user_count": "Members with Claude Science activity in the 30-day rolling window.",
+ "science_entitled_user_count": "Members holding a Claude Science seat entitlement at the time of the daily snapshot, independent of the organization-level Claude Science toggle.",
+ },
+ },
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/anthropic/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/anthropic/settings.py
index 04596f2fe17d..99ba3e022315 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/anthropic/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/anthropic/settings.py
@@ -15,13 +15,38 @@ class PaginationType(Enum):
# The usage_report/cost_report endpoints page with an opaque `page` token echoed back as
# `next_page`, alongside has_more.
PAGE = "page"
+ # The RBAC group and role endpoints are entity lists, but page with the same opaque
+ # `page`/`next_page` token the reports use instead of an `after_id` cursor.
+ PAGE_TOKEN = "page_token"
class AnalyticsWindowKind(Enum):
- # `/organizations/analytics/users` answers for one `date`.
+ # `/organizations/analytics/users` and the connector/plugin/skill breakdowns answer for one `date`.
DATE = "date"
# The per-user cost and token usage reports answer for a `starting_at`/`ending_at` range.
RANGE = "range"
+ # `/organizations/analytics/summaries` answers for a `starting_date`/`ending_date` calendar-date
+ # range, returning one entry per day in it.
+ DATE_RANGE = "date_range"
+
+
+class AccessFamily(Enum):
+ """Credential a group of endpoints needs beyond the Claude Console Admin API key.
+
+ `get_endpoint_permissions` probes one endpoint per family and reports the result against every
+ table in that family, so the customer deselects the tables their key cannot reach instead of
+ watching them fail to sync.
+ """
+
+ # Claude Enterprise Analytics API: a claude.ai Analytics key carrying `read:analytics`.
+ ANALYTICS = "analytics"
+ # Claude Enterprise group reads: an Admin API key created in claude.ai for every linked
+ # organization, carrying `read:rbac_groups`. Groups are owned by the enterprise as a whole, which
+ # is why the key has to cover all linked organizations.
+ RBAC_GROUPS = "rbac_groups"
+ # Claude Enterprise custom-role reads: an Admin API key created in claude.ai carrying
+ # `read:members`. Anthropic exposes no separate role scope.
+ RBAC_ROLES = "rbac_roles"
def _datetime_incremental_field(name: str) -> IncrementalField:
@@ -33,6 +58,23 @@ def _datetime_incremental_field(name: str) -> IncrementalField:
}
+@frozen
+class FanOutConfig:
+ """Single-hop fan-out over a parent endpoint in this same catalog.
+
+ Anthropic serves no org-wide list for these sub-resources, so the source enumerates the parent
+ endpoint and requests the sub-resource once per parent row.
+ """
+
+ # Catalog name of the parent endpoint.
+ parent: str
+ # Placeholder in the child `path` that the parent's id fills.
+ path_param: str
+ # Column the parent's id is stamped onto. The member rows already carry their parent id, but the
+ # role permission rows carry none of their own, so without the stamp their key is unpopulated.
+ id_column: str
+
+
@frozen
class AnthropicEndpointConfig:
name: str
@@ -57,8 +99,8 @@ class AnthropicEndpointConfig:
# Re-read window (seconds) applied to the incremental watermark by the pipeline before it reaches
# the source, so each run re-pulls recently-restated buckets. Merge dedupes them on the primary key.
default_incremental_lookback_seconds: Optional[int] = None
- # workspace_members has no org-wide list endpoint, so it fans out one request per workspace.
- fan_out_over_workspaces: bool = False
+ # Set where the endpoint has no org-wide list and has to be reached one parent at a time.
+ fan_out: Optional[FanOutConfig] = None
# Claude Code analytics takes a single `starting_at` day per request, so it fans out one windowed
# request per calendar day from the watermark (or launch floor) to today.
fan_out_over_days: bool = False
@@ -72,6 +114,10 @@ class AnthropicEndpointConfig:
analytics_lag_days: int = 0
# Oldest `starting_at` the endpoint accepts, in days before today. None means no such limit.
analytics_max_history_days: Optional[int] = None
+ # Response key the rows sit under. Every endpoint uses `data` except the summaries endpoint.
+ data_selector: str = "data"
+ # Set where the endpoint needs a credential the Claude Console Admin API key is not.
+ access_family: Optional[AccessFamily] = None
should_sync_default: bool = True
@@ -137,6 +183,12 @@ _ANALYTICS_ENGAGEMENT_LOOKBACK_SECONDS = 60 * 60 * 24 * 3
# tail accurate at a bounded request cost; run a full refresh for invoicing-grade totals.
_ANALYTICS_REPORT_LOOKBACK_SECONDS = 60 * 60 * 24 * 7
+# Path prefixes for the Claude Enterprise user management reads. A denial from one of these means
+# the key lacks that family's scope, or the organization is not on Claude Enterprise at all, so the
+# source maps them to their own messages in `get_non_retryable_errors`.
+RBAC_GROUPS_PATH = "/v1/organizations/rbac_groups"
+RBAC_ROLES_PATH = "/v1/organizations/rbac_roles"
+
ANTHROPIC_ENDPOINTS: dict[str, AnthropicEndpointConfig] = {
"users": AnthropicEndpointConfig(
name="users",
@@ -176,7 +228,52 @@ ANTHROPIC_ENDPOINTS: dict[str, AnthropicEndpointConfig] = {
path="/v1/organizations/workspaces/{workspace_id}/members",
pagination=PaginationType.CURSOR,
primary_keys=["workspace_id", "user_id"],
- fan_out_over_workspaces=True,
+ fan_out=FanOutConfig(parent="workspaces", path_param="workspace_id", id_column="workspace_id"),
+ ),
+ # Claude Enterprise user management: the groups a member can hold, the membership join onto the
+ # users above, and the custom roles a group's `roles` field points at. These need an Admin API
+ # key created in claude.ai for a Claude Enterprise organization, which a Claude Console Admin API
+ # key is not, so they stay off by default and `get_endpoint_permissions` reports whether the
+ # configured key can reach them.
+ "rbac_groups": AnthropicEndpointConfig(
+ name="rbac_groups",
+ path=RBAC_GROUPS_PATH,
+ pagination=PaginationType.PAGE_TOKEN,
+ primary_keys=["id"],
+ partition_key="created_at",
+ access_family=AccessFamily.RBAC_GROUPS,
+ should_sync_default=False,
+ ),
+ "rbac_group_members": AnthropicEndpointConfig(
+ name="rbac_group_members",
+ path=f"{RBAC_GROUPS_PATH}/{{group_id}}/members",
+ pagination=PaginationType.PAGE_TOKEN,
+ # One user can hold many groups, so the key carries the group id.
+ primary_keys=["group_id", "user_id"],
+ partition_key="created_at",
+ fan_out=FanOutConfig(parent="rbac_groups", path_param="group_id", id_column="group_id"),
+ access_family=AccessFamily.RBAC_GROUPS,
+ should_sync_default=False,
+ ),
+ "rbac_roles": AnthropicEndpointConfig(
+ name="rbac_roles",
+ path=RBAC_ROLES_PATH,
+ pagination=PaginationType.PAGE_TOKEN,
+ primary_keys=["id"],
+ partition_key="created_at",
+ access_family=AccessFamily.RBAC_ROLES,
+ should_sync_default=False,
+ ),
+ # A permission row carries neither an id nor a timestamp, so `id` is synthesized from the role
+ # plus the action and resource the row grants (see anthropic.py) and the table is not partitioned.
+ "rbac_role_permissions": AnthropicEndpointConfig(
+ name="rbac_role_permissions",
+ path=f"{RBAC_ROLES_PATH}/{{role_id}}/permissions",
+ pagination=PaginationType.PAGE_TOKEN,
+ primary_keys=["id"],
+ fan_out=FanOutConfig(parent="rbac_roles", path_param="role_id", id_column="role_id"),
+ access_family=AccessFamily.RBAC_ROLES,
+ should_sync_default=False,
),
# No service_accounts endpoint: Anthropic serves service accounts only to an org:admin OAuth
# token and rejects the Admin API key this source authenticates with, so the table can never
@@ -258,6 +355,7 @@ ANTHROPIC_ENDPOINTS: dict[str, AnthropicEndpointConfig] = {
analytics_lag_days=ANALYTICS_ENGAGEMENT_LAG_DAYS,
limit=ANALYTICS_PAGE_SIZE,
default_incremental_lookback_seconds=_ANALYTICS_ENGAGEMENT_LOOKBACK_SECONDS,
+ access_family=AccessFamily.ANALYTICS,
should_sync_default=False,
),
"analytics_user_cost": AnthropicEndpointConfig(
@@ -276,6 +374,7 @@ ANTHROPIC_ENDPOINTS: dict[str, AnthropicEndpointConfig] = {
bucket_width="1d",
limit=ANALYTICS_PAGE_SIZE,
default_incremental_lookback_seconds=_ANALYTICS_REPORT_LOOKBACK_SECONDS,
+ access_family=AccessFamily.ANALYTICS,
should_sync_default=False,
),
"analytics_user_usage": AnthropicEndpointConfig(
@@ -291,6 +390,78 @@ ANTHROPIC_ENDPOINTS: dict[str, AnthropicEndpointConfig] = {
bucket_width="1d",
limit=ANALYTICS_PAGE_SIZE,
default_incremental_lookback_seconds=_ANALYTICS_REPORT_LOOKBACK_SECONDS,
+ access_family=AccessFamily.ANALYTICS,
+ should_sync_default=False,
+ ),
+ # Adoption breakdowns from the same Claude Enterprise Analytics export as the per-seat tables
+ # above: one row per (day, connector), (day, plugin) and (day, skill). Each answers for one
+ # `date` and page-cursors within it, so they take the same day-by-day fan-out as the per-seat
+ # activity table. No `group_by` is requested, so the row grain is the entity alone.
+ "analytics_connector_usage": AnthropicEndpointConfig(
+ name="analytics_connector_usage",
+ path="/v1/organizations/analytics/connectors",
+ pagination=PaginationType.PAGE,
+ # `id` is synthesized from the requested day and the entity name (see anthropic.py). The
+ # response carries no day of its own, so the source stamps the day it asked for onto every row.
+ primary_keys=["id"],
+ partition_key="date",
+ supports_incremental=True,
+ incremental_fields=[_datetime_incremental_field("date")],
+ analytics_window=AnalyticsWindowKind.DATE,
+ analytics_lag_days=ANALYTICS_ENGAGEMENT_LAG_DAYS,
+ limit=ANALYTICS_PAGE_SIZE,
+ default_incremental_lookback_seconds=_ANALYTICS_ENGAGEMENT_LOOKBACK_SECONDS,
+ access_family=AccessFamily.ANALYTICS,
+ should_sync_default=False,
+ ),
+ "analytics_plugin_usage": AnthropicEndpointConfig(
+ name="analytics_plugin_usage",
+ path="/v1/organizations/analytics/plugins",
+ pagination=PaginationType.PAGE,
+ primary_keys=["id"],
+ partition_key="date",
+ supports_incremental=True,
+ incremental_fields=[_datetime_incremental_field("date")],
+ analytics_window=AnalyticsWindowKind.DATE,
+ analytics_lag_days=ANALYTICS_ENGAGEMENT_LAG_DAYS,
+ limit=ANALYTICS_PAGE_SIZE,
+ default_incremental_lookback_seconds=_ANALYTICS_ENGAGEMENT_LOOKBACK_SECONDS,
+ access_family=AccessFamily.ANALYTICS,
+ should_sync_default=False,
+ ),
+ "analytics_skill_usage": AnthropicEndpointConfig(
+ name="analytics_skill_usage",
+ path="/v1/organizations/analytics/skills",
+ pagination=PaginationType.PAGE,
+ primary_keys=["id"],
+ partition_key="date",
+ supports_incremental=True,
+ incremental_fields=[_datetime_incremental_field("date")],
+ analytics_window=AnalyticsWindowKind.DATE,
+ analytics_lag_days=ANALYTICS_ENGAGEMENT_LAG_DAYS,
+ limit=ANALYTICS_PAGE_SIZE,
+ default_incremental_lookback_seconds=_ANALYTICS_ENGAGEMENT_LOOKBACK_SECONDS,
+ access_family=AccessFamily.ANALYTICS,
+ should_sync_default=False,
+ ),
+ # Org-wide rolled-up activity as Anthropic reports it: active users over the day plus the 7- and
+ # 30-day rolling windows, assigned seats, and the adoption rates derived from them. One row per
+ # UTC day, each carrying its own `starting_at`, so the day is the grain and the key.
+ "analytics_summaries": AnthropicEndpointConfig(
+ name="analytics_summaries",
+ path="/v1/organizations/analytics/summaries",
+ pagination=PaginationType.PAGE,
+ primary_keys=["starting_at"],
+ partition_key="starting_at",
+ supports_incremental=True,
+ incremental_fields=[_datetime_incremental_field("starting_at")],
+ analytics_window=AnalyticsWindowKind.DATE_RANGE,
+ analytics_lag_days=ANALYTICS_ENGAGEMENT_LAG_DAYS,
+ # The endpoint answers a whole range in one response and takes no pagination parameters, so
+ # it gets no `limit` and its rows sit under `summaries` rather than `data`.
+ data_selector="summaries",
+ default_incremental_lookback_seconds=_ANALYTICS_ENGAGEMENT_LOOKBACK_SECONDS,
+ access_family=AccessFamily.ANALYTICS,
should_sync_default=False,
),
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/anthropic/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/anthropic/source.py
index 5621bd5da080..386c318e6eb3 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/anthropic/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/anthropic/source.py
@@ -1,3 +1,4 @@
+from collections import defaultdict
from typing import Optional, cast
from posthog.schema import (
@@ -13,6 +14,8 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.anthropic.
AnthropicResumeConfig,
anthropic_source,
check_analytics_access,
+ check_rbac_group_access,
+ check_rbac_role_access,
validate_credentials as validate_anthropic_credentials,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.anthropic.settings import (
@@ -21,6 +24,9 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.anthropic.
ENDPOINT_RETIRED_ERROR,
ENDPOINTS,
INCREMENTAL_FIELDS,
+ RBAC_GROUPS_PATH,
+ RBAC_ROLES_PATH,
+ AccessFamily,
)
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 (
@@ -58,7 +64,11 @@ class AnthropicSource(ResumableSource[AnthropicSourceConfig, AnthropicResumeConf
Create an Admin API key (prefixed `sk-ant-admin...`) in your [Anthropic Console](https://console.anthropic.com/settings/admin-keys). Only organization admins can create one, and the Admin API is not available for individual accounts.
-The per-seat activity, cost, and token usage tables come from the Claude Enterprise Analytics API, which needs a different key: a Claude Enterprise key carrying the `read:analytics` scope, created by your primary owner in [claude.ai organization settings](https://claude.ai/admin-settings/api-access). A key works with one of the two APIs, so pick the one that matches the tables you want.""",
+Some tables need a Claude Enterprise key instead, created by your primary owner in [claude.ai organization settings](https://claude.ai/admin-settings/api-access). A key works with one API only, so pick the one that matches the tables you want.
+
+The per-seat activity, cost and token usage tables, and the connector, plugin, skill and summary tables, come from the Claude Enterprise Analytics API. They need a Claude Enterprise key carrying the `read:analytics` scope.
+
+The group, group membership and custom role tables come from the Claude Enterprise user management API. They need an Admin API key carrying the `read:rbac_groups` scope for the group tables, or `read:members` for the custom role tables.""",
iconPath="/static/services/anthropic.svg",
docsUrl="https://posthog.com/docs/cdp/sources/anthropic",
keywords=["llm", "claude", "ai usage", "cost"],
@@ -85,10 +95,18 @@ The per-seat activity, cost, and token usage tables come from the Claude Enterpr
return CANONICAL_DESCRIPTIONS
def get_non_retryable_errors(self) -> dict[str, str | None]:
+ rbac_group_denied = "This table comes from the Claude Enterprise user management API, which your key can't reach. Reconnect the source with an Admin API key created in claude.ai for all your linked organizations, carrying the read:rbac_groups scope, or turn this table's sync off."
+ rbac_role_denied = "This table comes from the Claude Enterprise user management API, which your key can't reach. Reconnect the source with an Admin API key created in claude.ai carrying the read:members scope, or turn this table's sync off."
return {
# Matched before the generic 403 below, because the first matching pattern supplies the
# message and a denial from this path is about a missing scope, not admin access.
f"403 Client Error: Forbidden for url: https://api.anthropic.com{ANALYTICS_PATH_PREFIX}": "This table comes from the Claude Enterprise Analytics API, which your key can't reach. Reconnect the source with a Claude Enterprise key carrying the read:analytics scope, or turn this table's sync off.",
+ # An organization that is not on Claude Enterprise does not serve these routes at all,
+ # so a 404 here means the same thing as a 403 and must not retry either.
+ f"403 Client Error: Forbidden for url: https://api.anthropic.com{RBAC_GROUPS_PATH}": rbac_group_denied,
+ f"404 Client Error: Not Found for url: https://api.anthropic.com{RBAC_GROUPS_PATH}": rbac_group_denied,
+ f"403 Client Error: Forbidden for url: https://api.anthropic.com{RBAC_ROLES_PATH}": rbac_role_denied,
+ f"404 Client Error: Not Found for url: https://api.anthropic.com{RBAC_ROLES_PATH}": rbac_role_denied,
"401 Client Error: Unauthorized for url: https://api.anthropic.com": "Your Anthropic Admin API key is invalid or has been revoked. Create a new Admin API key in the Anthropic Console, then reconnect.",
"403 Client Error: Forbidden for url: https://api.anthropic.com": "Your Anthropic API key does not have organization admin access. Use an Admin API key (prefixed sk-ant-admin) created by an organization admin, then reconnect.",
ENDPOINT_RETIRED_ERROR: "Anthropic no longer offers this table, so it can't sync. PostHog has turned its sync off for you, and any rows already imported stay in your warehouse.",
@@ -127,19 +145,22 @@ The per-seat activity, cost, and token usage tables come from the Claude Enterpr
endpoints: list[str],
api_version: str | None = None,
) -> dict[str, str | None]:
+ probes = {
+ AccessFamily.ANALYTICS: check_analytics_access,
+ AccessFamily.RBAC_GROUPS: check_rbac_group_access,
+ AccessFamily.RBAC_ROLES: check_rbac_role_access,
+ }
permissions: dict[str, str | None] = dict.fromkeys(endpoints)
- analytics_endpoints = [
- name
- for name in endpoints
- if name in ANTHROPIC_ENDPOINTS and ANTHROPIC_ENDPOINTS[name].analytics_window is not None
- ]
- if not analytics_endpoints:
- return permissions
- # Every analytics endpoint needs the same scope on the same plan, so one probe answers for
- # all of them.
- reason = check_analytics_access(config.api_key)
- for name in analytics_endpoints:
- permissions[name] = reason
+ by_family: dict[AccessFamily, list[str]] = defaultdict(list)
+ for name in endpoints:
+ endpoint_config = ANTHROPIC_ENDPOINTS.get(name)
+ if endpoint_config is not None and endpoint_config.access_family is not None:
+ by_family[endpoint_config.access_family].append(name)
+ for family, names in by_family.items():
+ # Every endpoint in a family needs the same access, so one probe answers for all of them.
+ reason = probes[family](config.api_key)
+ for name in names:
+ permissions[name] = reason
return permissions
def validate_credentials(
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/anthropic/tests/test_anthropic.py b/products/warehouse_sources/backend/temporal/data_imports/sources/anthropic/tests/test_anthropic.py
index 1f146e15aa01..57483b270804 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/anthropic/tests/test_anthropic.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/anthropic/tests/test_anthropic.py
@@ -19,12 +19,14 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.anthropic.
ClaudeCodeDayPaginator,
_analytics_windows,
_claude_code_start_day,
+ _flatten_analytics_entity_usage,
_flatten_analytics_user_activity,
_flatten_analytics_user_cost,
_flatten_analytics_user_usage,
_flatten_claude_code_core,
_flatten_claude_code_models,
_flatten_cost_result,
+ _flatten_rbac_role_permission,
_flatten_usage_result,
_row_id,
anthropic_source,
@@ -38,6 +40,8 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.anthropic.
ANALYTICS_REPORT_MAX_HISTORY_DAYS,
ANTHROPIC_ENDPOINTS,
COST_REPORT_PAGE_BUCKETS,
+ RBAC_GROUPS_PATH,
+ RBAC_ROLES_PATH,
USAGE_GROUP_BY_FALLBACKS,
USAGE_REPORT_PAGE_BUCKETS,
)
@@ -1211,3 +1215,348 @@ class TestAnalyticsNonRetryableError:
matched = [message for pattern, message in errors.items() if error_message_matches(observed, [pattern])]
assert len(matched) == 2
assert "read:analytics" in (matched[0] or "")
+
+
+def _token_page(items: list[dict[str, Any]], *, has_more: bool, next_page: str | None) -> Response:
+ # The RBAC group and role lists page with an opaque `page`/`next_page` token, not an after_id.
+ return _response({"data": items, "has_more": has_more, "next_page": next_page})
+
+
+class TestRbacListPagination:
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_pages_with_the_page_token_not_an_after_id_cursor(self, MockSession) -> None:
+ # These endpoints send no `last_id`, so paging them with the entity cursor would stop after
+ # the first page and silently drop every group past it.
+ session = MockSession.return_value
+ params = _wire(
+ session,
+ [
+ _token_page([{"id": "rbac_group_1"}], has_more=True, next_page="P2"),
+ _token_page([{"id": "rbac_group_2"}], has_more=False, next_page=None),
+ ],
+ )
+
+ rows = _rows(_source("rbac_groups", _make_manager()))
+
+ assert [r["id"] for r in rows] == ["rbac_group_1", "rbac_group_2"]
+ assert "page" not in params[0]["params"]
+ assert "after_id" not in params[1]["params"]
+ assert params[1]["params"]["page"] == "P2"
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_resumes_from_the_saved_page_token(self, MockSession) -> None:
+ session = MockSession.return_value
+ params = _wire(session, [_token_page([{"id": "rbac_role_2"}], has_more=False, next_page=None)])
+
+ _rows(_source("rbac_roles", _make_manager(AnthropicResumeConfig(cursor="P2"))))
+
+ assert params[0]["params"]["page"] == "P2"
+
+
+class TestRbacFanOut:
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_group_members_carry_the_group_id_from_the_parent(self, MockSession) -> None:
+ session = MockSession.return_value
+ params = _wire(
+ session,
+ [
+ _token_page([{"id": "rbac_group_1"}, {"id": "rbac_group_2"}], has_more=False, next_page=None),
+ _token_page(
+ [{"type": "rbac_group_member", "user_id": "u1", "group_id": "rbac_group_1"}],
+ has_more=False,
+ next_page=None,
+ ),
+ # The API always sends group_id, but stamp it from the parent defensively so the
+ # composite primary key is populated even if it goes missing.
+ _token_page([{"type": "rbac_group_member", "user_id": "u2"}], has_more=False, next_page=None),
+ ],
+ )
+
+ rows = _rows(_source("rbac_group_members", _make_manager()))
+
+ assert [(r["group_id"], r["user_id"]) for r in rows] == [("rbac_group_1", "u1"), ("rbac_group_2", "u2")]
+ assert all("_rbac_groups_id" not in r for r in rows)
+ assert params[0]["url"].endswith("/v1/organizations/rbac_groups")
+ assert params[1]["url"].endswith("/v1/organizations/rbac_groups/rbac_group_1/members")
+ assert params[2]["url"].endswith("/v1/organizations/rbac_groups/rbac_group_2/members")
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_permissions_take_their_role_id_from_the_parent(self, MockSession) -> None:
+ # A permission object carries no role id at all, so without the parent stamp every row would
+ # land with a null role_id and collide on the synthesized key.
+ session = MockSession.return_value
+ params = _wire(
+ session,
+ [
+ _token_page([{"id": "rbac_role_1"}, {"id": "rbac_role_2"}], has_more=False, next_page=None),
+ _token_page(
+ [{"type": "rbac_role_permission", "action": "chat", "resource": {"type": "organization"}}],
+ has_more=False,
+ next_page=None,
+ ),
+ _token_page(
+ [{"type": "rbac_role_permission", "action": "chat", "resource": {"type": "organization"}}],
+ has_more=False,
+ next_page=None,
+ ),
+ ],
+ )
+
+ rows = _rows(_source("rbac_role_permissions", _make_manager()))
+
+ assert [r["role_id"] for r in rows] == ["rbac_role_1", "rbac_role_2"]
+ # The same grant under two roles must not share a key, or merge would keep only one row.
+ assert rows[0]["id"] != rows[1]["id"]
+ assert params[1]["url"].endswith("/v1/organizations/rbac_roles/rbac_role_1/permissions")
+ assert params[2]["url"].endswith("/v1/organizations/rbac_roles/rbac_role_2/permissions")
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_a_role_that_belongs_to_another_organization_is_skipped(self, MockSession) -> None:
+ # Groups span the enterprise while the role catalog is per-organization, so a role the key
+ # cannot read answers 404. Skip that role rather than failing the whole schema.
+ session = MockSession.return_value
+ _wire(
+ session,
+ [
+ _token_page([{"id": "rbac_role_1"}, {"id": "rbac_role_2"}], has_more=False, next_page=None),
+ _response({"error": "not_found"}, status=404),
+ _token_page(
+ [{"type": "rbac_role_permission", "action": "chat", "resource": {"type": "organization"}}],
+ has_more=False,
+ next_page=None,
+ ),
+ ],
+ )
+
+ rows = _rows(_source("rbac_role_permissions", _make_manager()))
+
+ assert [r["role_id"] for r in rows] == ["rbac_role_2"]
+
+
+class TestFlattenRbacRolePermission:
+ @parameterized.expand(
+ [
+ (
+ "organization",
+ {"type": "organization", "organization_id": "org-uuid"},
+ {"organization_id": "org-uuid", "connector_id": None, "tool_name": None, "scope": None},
+ ),
+ (
+ "connector_tool",
+ {"type": "connector_tool", "connector_id": "mcpsrv_1", "tool_name": "search_tickets"},
+ {
+ "organization_id": None,
+ "connector_id": "mcpsrv_1",
+ "tool_name": "search_tickets",
+ "scope": None,
+ },
+ ),
+ (
+ "connector_scope",
+ {"type": "connector_scope", "connector_id": "mcpsrv_1", "scope": "read_scope_deadbeef"},
+ {
+ "organization_id": None,
+ "connector_id": "mcpsrv_1",
+ "tool_name": None,
+ "scope": "read_scope_deadbeef",
+ },
+ ),
+ (
+ "all_connectors",
+ {"type": "all_connectors"},
+ {"organization_id": None, "connector_id": None, "tool_name": None, "scope": None},
+ ),
+ ]
+ )
+ def test_each_resource_tag_fills_only_its_own_identifiers(
+ self, _name: str, resource: dict[str, Any], expected: dict[str, Any]
+ ) -> None:
+ row = _flatten_rbac_role_permission({"role_id": "rbac_role_1", "action": "use", "resource": resource})
+ assert row["resource_type"] == resource["type"]
+ assert {key: row[key] for key in expected} == expected
+
+ def test_two_grants_on_one_role_get_distinct_ids(self) -> None:
+ base = {"role_id": "rbac_role_1", "resource": {"type": "all_connectors"}}
+ use = _flatten_rbac_role_permission({**base, "action": "use"})
+ always = _flatten_rbac_role_permission({**base, "action": "always_allow"})
+ assert use["id"] != always["id"]
+
+ def test_missing_resource_object_does_not_crash(self) -> None:
+ row = _flatten_rbac_role_permission({"role_id": "rbac_role_1", "action": "chat"})
+ assert row["resource_type"] is None
+ assert row["id"]
+
+
+def _usage_breakdown_page(rows: list[dict[str, Any]], *, next_page: str | None) -> Response:
+ # The connector/plugin/skill breakdowns send no `has_more`: a null `next_page` is the last page.
+ return _response({"data": rows, "next_page": next_page})
+
+
+def _summaries_page(rows: list[dict[str, Any]]) -> Response:
+ # The summaries endpoint answers a whole range in one response, under `summaries`, with no cursor.
+ return _response({"summaries": rows})
+
+
+def _summary_row(starting_at: str = "2026-03-04T00:00:00Z") -> dict[str, Any]:
+ return {
+ "starting_at": starting_at,
+ "ending_at": "2026-03-05T00:00:00Z",
+ "assigned_seat_count": 120,
+ "pending_invite_count": 3,
+ "daily_active_user_count": 84,
+ "weekly_active_user_count": 101,
+ "monthly_active_user_count": 112,
+ "daily_adoption_rate": 70,
+ "cowork_daily_active_user_count": 12,
+ "cowork_weekly_active_user_count": 20,
+ "cowork_monthly_active_user_count": 25,
+ }
+
+
+class TestFlattenAnalyticsEntityUsage:
+ _SKILL_ROW = {
+ "skill_name": "writing-tests",
+ "skill_display_name": "Writing tests",
+ "distinct_user_count": 9,
+ "invocation_count": 31,
+ "chat_metrics": {"distinct_conversation_skill_used_count": 4},
+ "office_metrics": {"excel": {"distinct_session_skill_used_count": 2}},
+ }
+
+ def test_stamps_the_requested_day_and_flattens_the_product_blocks(self) -> None:
+ row = _flatten_analytics_entity_usage("skill_name", date(2026, 3, 4), self._SKILL_ROW)
+ assert row["date"] == "2026-03-04T00:00:00Z"
+ assert row["skill_name"] == "writing-tests"
+ assert row["distinct_user_count"] == 9
+ assert row["chat_distinct_conversation_skill_used_count"] == 4
+ assert row["office_excel_distinct_session_skill_used_count"] == 2
+ # The nested blocks must not survive as columns of their own.
+ assert "chat_metrics" not in row and "office_metrics" not in row
+
+ def test_id_is_stable_across_metric_changes(self) -> None:
+ revised = {**self._SKILL_ROW, "distinct_user_count": 11, "invocation_count": 40}
+ assert (
+ _flatten_analytics_entity_usage("skill_name", date(2026, 3, 4), self._SKILL_ROW)["id"]
+ == _flatten_analytics_entity_usage("skill_name", date(2026, 3, 4), revised)["id"]
+ )
+
+ def test_id_differs_by_day_and_by_entity(self) -> None:
+ same_day = _flatten_analytics_entity_usage("skill_name", date(2026, 3, 4), self._SKILL_ROW)
+ next_day = _flatten_analytics_entity_usage("skill_name", date(2026, 3, 5), self._SKILL_ROW)
+ other_skill = _flatten_analytics_entity_usage(
+ "skill_name", date(2026, 3, 4), {**self._SKILL_ROW, "skill_name": "writing-skills"}
+ )
+ assert len({same_day["id"], next_day["id"], other_skill["id"]}) == 3
+
+
+class TestAnalyticsBreakdownFanOut:
+ @parameterized.expand(
+ [
+ ("analytics_connector_usage", "connector_name", "atlassian"),
+ ("analytics_plugin_usage", "plugin_name", "serena"),
+ ("analytics_skill_usage", "skill_name", "writing-tests"),
+ ]
+ )
+ @mock.patch(ANTHROPIC_SESSION_PATCH)
+ def test_fans_out_one_dated_request_per_day(self, endpoint: str, name_field: str, name: str, MockSession) -> None:
+ session = MockSession.return_value
+ today = datetime.now(UTC).date()
+ watermark = _midnight(today - timedelta(days=ANALYTICS_ENGAGEMENT_LAG_DAYS + 1))
+ params = _wire(session, [_usage_breakdown_page([{name_field: name}], next_page=None) for _ in range(2)])
+
+ rows = _rows(_source(endpoint, _make_manager(), last_value=watermark))
+
+ assert [p["params"]["date"] for p in params] == [
+ (watermark.date() + timedelta(days=i)).isoformat() for i in range(2)
+ ]
+ assert [r["date"] for r in rows] == [
+ f"{(watermark.date() + timedelta(days=i)).isoformat()}T00:00:00Z" for i in range(2)
+ ]
+ assert [r[name_field] for r in rows] == [name, name]
+ # A row's day comes from the request, so the request must never carry a range.
+ assert "starting_at" not in params[0]["params"]
+
+ @mock.patch(ANTHROPIC_SESSION_PATCH)
+ def test_paginates_within_a_day_on_next_page_alone(self, MockSession) -> None:
+ session = MockSession.return_value
+ today = datetime.now(UTC).date()
+ params = _wire(
+ session,
+ [
+ _usage_breakdown_page([{"connector_name": "atlassian"}], next_page="P2"),
+ _usage_breakdown_page([{"connector_name": "github"}], next_page=None),
+ ],
+ )
+
+ rows = _rows(_source("analytics_connector_usage", _make_manager(), last_value=_midnight(today)))
+
+ assert {r["connector_name"] for r in rows} == {"atlassian", "github"}
+ assert params[1]["params"]["page"] == "P2"
+ assert params[1]["params"]["date"] == params[0]["params"]["date"]
+
+
+class TestAnalyticsSummaries:
+ @mock.patch(ANTHROPIC_SESSION_PATCH)
+ def test_requests_a_single_day_as_calendar_dates_with_no_pagination_params(self, MockSession) -> None:
+ session = MockSession.return_value
+ today = datetime.now(UTC).date()
+ params = _wire(session, [_summaries_page([_summary_row()])])
+
+ _rows(_source("analytics_summaries", _make_manager(), last_value=_midnight(today)))
+
+ last_day = today - timedelta(days=ANALYTICS_ENGAGEMENT_LAG_DAYS)
+ assert params[0]["params"]["starting_date"] == last_day.isoformat()
+ # `ending_date` is exclusive, and the endpoint rejects `limit` and `bucket_width`.
+ assert params[0]["params"]["ending_date"] == (last_day + timedelta(days=1)).isoformat()
+ assert "limit" not in params[0]["params"]
+ assert "bucket_width" not in params[0]["params"]
+ assert "starting_at" not in params[0]["params"]
+
+ @mock.patch(ANTHROPIC_SESSION_PATCH)
+ def test_rows_come_from_the_summaries_key_and_keep_their_own_day(self, MockSession) -> None:
+ session = MockSession.return_value
+ today = datetime.now(UTC).date()
+ _wire(session, [_summaries_page([_summary_row("2026-03-04T00:00:00Z")])])
+
+ rows = _rows(_source("analytics_summaries", _make_manager(), last_value=_midnight(today)))
+
+ # The row's own `starting_at` is the primary key, so nothing may overwrite or synthesize it.
+ assert [r["starting_at"] for r in rows] == ["2026-03-04T00:00:00Z"]
+ assert rows[0]["daily_active_user_count"] == 84
+ assert rows[0]["cowork_weekly_active_user_count"] == 20
+ assert "id" not in rows[0]
+
+ @mock.patch(ANTHROPIC_SESSION_PATCH)
+ def test_a_day_ends_after_one_request(self, MockSession) -> None:
+ # The response carries neither `has_more` nor `next_page`, so a paginator that treated a
+ # missing token as "keep going" would re-request the same day forever.
+ session = MockSession.return_value
+ today = datetime.now(UTC).date()
+ _wire(session, [_summaries_page([_summary_row()])])
+
+ _rows(_source("analytics_summaries", _make_manager(), last_value=_midnight(today)))
+
+ assert session.send.call_count == 1
+
+
+class TestRbacNonRetryableErrors:
+ @parameterized.expand(
+ [
+ ("groups_forbidden", 403, "Forbidden", RBAC_GROUPS_PATH, "read:rbac_groups"),
+ # A Claude Console organization does not serve these routes at all.
+ ("groups_absent", 404, "Not Found", f"{RBAC_GROUPS_PATH}/rbac_group_1/members", "read:rbac_groups"),
+ ("roles_forbidden", 403, "Forbidden", RBAC_ROLES_PATH, "read:members"),
+ ("roles_absent", 404, "Not Found", f"{RBAC_ROLES_PATH}/rbac_role_1/permissions", "read:members"),
+ ]
+ )
+ def test_denial_names_the_scope_not_admin_access(
+ self, _name: str, status: int, reason: str, path: str, expected_scope: str
+ ) -> None:
+ # The generic api.anthropic.com 403 also matches a group or role denial, and the first
+ # matching entry supplies the message the customer reads. If it wins, the customer is told to
+ # swap their key for a Console Admin API key when the real problem is a missing scope.
+ errors = AnthropicSource().get_non_retryable_errors()
+ observed = f"{status} Client Error: {reason} for url: https://api.anthropic.com{path}"
+ matched = [message for pattern, message in errors.items() if error_message_matches(observed, [pattern])]
+ assert matched, "a group or role denial must be non-retryable"
+ assert expected_scope in (matched[0] or "")
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/anthropic/tests/test_anthropic_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/anthropic/tests/test_anthropic_source.py
index 89d6d5f40aae..ae55206cf48e 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/anthropic/tests/test_anthropic_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/anthropic/tests/test_anthropic_source.py
@@ -5,9 +5,10 @@ from parameterized import parameterized
from products.warehouse_sources.backend.temporal.data_imports.sources.anthropic.settings import ANTHROPIC_ENDPOINTS
from products.warehouse_sources.backend.temporal.data_imports.sources.anthropic.source import AnthropicSource
-_CHECK_ANALYTICS_ACCESS = (
- "products.warehouse_sources.backend.temporal.data_imports.sources.anthropic.source.check_analytics_access"
-)
+_SOURCE_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.anthropic.source"
+_CHECK_ANALYTICS_ACCESS = f"{_SOURCE_MODULE}.check_analytics_access"
+_CHECK_RBAC_GROUP_ACCESS = f"{_SOURCE_MODULE}.check_rbac_group_access"
+_CHECK_RBAC_ROLE_ACCESS = f"{_SOURCE_MODULE}.check_rbac_role_access"
class TestAnthropicSchemas:
@@ -26,6 +27,14 @@ class TestAnthropicSchemas:
"analytics_user_activity",
"analytics_user_cost",
"analytics_user_usage",
+ "analytics_connector_usage",
+ "analytics_plugin_usage",
+ "analytics_skill_usage",
+ "analytics_summaries",
+ "rbac_groups",
+ "rbac_group_members",
+ "rbac_roles",
+ "rbac_role_permissions",
}
@parameterized.expand([("usage_report",), ("cost_report",)])
@@ -46,7 +55,20 @@ class TestAnthropicSchemas:
assert [f["field"] for f in schema.incremental_fields] == ["date"]
assert schema.default_incremental_lookback_seconds == 60 * 60 * 24
- @parameterized.expand([("users",), ("workspaces",), ("api_keys",), ("workspace_members",), ("invites",)])
+ @parameterized.expand(
+ [
+ ("users",),
+ ("workspaces",),
+ ("api_keys",),
+ ("workspace_members",),
+ ("invites",),
+ # The group and role objects carry an `updated_at`, but no endpoint filters on it.
+ ("rbac_groups",),
+ ("rbac_group_members",),
+ ("rbac_roles",),
+ ("rbac_role_permissions",),
+ ]
+ )
def test_entity_endpoints_are_full_refresh_only(self, endpoint: str) -> None:
# No updated-since filter exists on the entity lists, so they must not advertise incremental.
schema = next(s for s in AnthropicSource().get_schemas(MagicMock(), team_id=1) if s.name == endpoint)
@@ -90,6 +112,14 @@ class TestAnthropicSourceForPipeline:
("analytics_user_activity", ["id"], "datetime"),
("analytics_user_cost", ["id"], "datetime"),
("analytics_user_usage", ["id"], "datetime"),
+ ("analytics_connector_usage", ["id"], "datetime"),
+ ("analytics_plugin_usage", ["id"], "datetime"),
+ ("analytics_skill_usage", ["id"], "datetime"),
+ ("analytics_summaries", ["starting_at"], "datetime"),
+ ("rbac_groups", ["id"], "datetime"),
+ ("rbac_group_members", ["group_id", "user_id"], "datetime"),
+ ("rbac_roles", ["id"], "datetime"),
+ ("rbac_role_permissions", ["id"], None),
]
)
def test_primary_keys_and_partitioning(
@@ -99,7 +129,8 @@ class TestAnthropicSourceForPipeline:
assert response.name == endpoint # type: ignore[attr-defined]
assert response.primary_keys == primary_keys # type: ignore[attr-defined]
assert response.sort_mode == "asc" # type: ignore[attr-defined]
- # workspace_members has no stable timestamp field, so it is not partitioned.
+ # workspace_members and rbac_role_permissions carry no stable timestamp field, so they are
+ # not partitioned.
assert response.partition_mode == partition_mode # type: ignore[attr-defined]
@@ -131,3 +162,34 @@ class TestAnalyticsEndpointPermissions:
)
assert permissions == {"users": None, "cost_report": None}
probe.assert_not_called()
+
+ @patch(_CHECK_RBAC_ROLE_ACCESS, return_value="needs read:members")
+ @patch(_CHECK_RBAC_GROUP_ACCESS, return_value="needs read:rbac_groups")
+ @patch(_CHECK_ANALYTICS_ACCESS, return_value="needs read:analytics")
+ def test_each_family_reports_its_own_scope(self, _analytics, _groups, _roles) -> None:
+ # The three families take different credentials, so a table must carry its own family's
+ # reason. Reporting one family's result against another tells the customer to fix the wrong
+ # key.
+ permissions = AnthropicSource().get_endpoint_permissions(
+ MagicMock(api_key="sk-ant-admin-test"),
+ team_id=1,
+ endpoints=["analytics_summaries", "rbac_groups", "rbac_group_members", "rbac_role_permissions", "users"],
+ )
+ assert permissions == {
+ "analytics_summaries": "needs read:analytics",
+ "rbac_groups": "needs read:rbac_groups",
+ "rbac_group_members": "needs read:rbac_groups",
+ "rbac_role_permissions": "needs read:members",
+ "users": None,
+ }
+
+ @patch(_CHECK_RBAC_ROLE_ACCESS)
+ @patch(_CHECK_RBAC_GROUP_ACCESS, return_value=None)
+ @patch(_CHECK_ANALYTICS_ACCESS)
+ def test_one_probe_answers_for_every_table_in_a_family(self, analytics, groups, roles) -> None:
+ AnthropicSource().get_endpoint_permissions(
+ MagicMock(api_key="sk-ant-admin-test"), team_id=1, endpoints=["rbac_groups", "rbac_group_members"]
+ )
+ assert groups.call_count == 1
+ analytics.assert_not_called()
+ roles.assert_not_called()