:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): add infisical roles, groups and secret scanning tables (#111527)
Tom Owers281df3a20d93
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.mdindex 621227d737a1..bdcd83ecacca 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@@ -4251,16 +4251,16 @@ Note: The Mintlify docs site serves the same 537KB SPA shell for every path (inc## Infisical — gaps-Today (5): `audit_logs`, `identities`, `organization_memberships`, `project_memberships`, `projects`+Today (11): `audit_logs`, `group_members`, `groups`, `identities`, `organization_memberships`, `organization_roles`, `project_group_memberships`, `project_memberships`, `project_roles`, `projects`, `secret_scanning_findings`Diffed against: <https://app.infisical.com/api/docs/json>-- [ ] `/api/v1/organization/roles and /api/v2/workspace/{projectId}/roles` — lookup resolving the role IDs already carried on the synced organization_memberships and project_memberships rows (high)-- [ ] `/api/v1/groups (+ /{id}/users, /{id}/machine-identities, /{id}/projects)` — org group membership - the main way access is actually granted, invisible today (high)-- [ ] `/api/v2/workspace/{projectId}/groups` — which groups are attached to which project, the group half of project access (high)+- [x] `/api/v1/organization/roles and /api/v2/workspace/{projectId}/roles` — lookup resolving the role IDs already carried on the synced organization_memberships and project_memberships rows (high)+- [x] `/api/v1/groups (+ /{id}/users, /{id}/machine-identities, /{id}/projects)` — org group membership - the main way access is actually granted, invisible today (high)+- [x] `/api/v2/workspace/{projectId}/groups` — which groups are attached to which project, the group half of project access (high)- [ ] `/api/v2/workspace/{projectId}/identity-memberships` — machine identities scoped per project; `identities` today is org-level only, so no one can see which CI identity can read which project (high)- [ ] `/api/v1/projects/{projectId}/environments/{envId}` — lookup resolving the environment IDs/slugs that audit_logs, folders and secrets all key on (also embedded in the project detail payload) (high)-- [ ] `/api/v2/secret-scanning/findings` — leaked-credential findings - the headline security metric of the product and the most obviously dashboardable table (high)+- [x] `/api/v2/secret-scanning/findings` — leaked-credential findings - the headline security metric of the product and the most obviously dashboardable table (high)- [ ] `/api/v2/folders` — the secret path tree; without it secret/audit rows referencing folderId cannot be resolved to a path (medium)- [ ] `/api/v2/secret-rotations` — rotation configs and last/next rotation timestamps - compliance reporting on stale credentials (medium)- [ ] `/api/v1/secret-syncs` — sync destinations and their last sync status, for pipeline health reporting (medium)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/infisical/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/infisical/canonical_descriptions.pyindex 53f7d79835cb..f1d0d80aea25 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/infisical/canonical_descriptions.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/infisical/canonical_descriptions.py@@ -86,4 +86,90 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"roles": "Project roles assigned to the user, including any temporary role windows.",},},+ "organization_roles": {+ "description": "Organization roles: the built-in admin, member, and no-access roles plus any custom roles. Resolves the role and roleId columns on organization_memberships, identities, and groups.",+ "docs_url": "https://infisical.com/docs/documentation/platform/access-controls/role-based-access-controls",+ "columns": {+ "id": "Unique identifier for the role.",+ "name": "Display name of the role.",+ "slug": "Role slug, as stored in the role column of membership rows.",+ "description": "Description of the role.",+ "orgId": "ID of the organization the role belongs to.",+ "createdAt": "When the role was created.",+ "updatedAt": "When the role was last updated.",+ },+ },+ "project_roles": {+ "description": "Project roles per project: the built-in roles plus any custom roles. Resolves the roles on project_memberships and project_group_memberships. Built-in roles get a new id on every sync, so join on projectId and slug.",+ "docs_url": "https://infisical.com/docs/documentation/platform/access-controls/role-based-access-controls",+ "columns": {+ "id": "Identifier for the role. Only stable for custom roles.",+ "name": "Display name of the role.",+ "slug": "Role slug, unique within the project.",+ "description": "Description of the role.",+ "projectId": "ID of the project the role belongs to.",+ "createdAt": "When the role was created.",+ "updatedAt": "When the role was last updated.",+ },+ },+ "groups": {+ "description": "User groups in the organization, with the organization role each group grants its members.",+ "docs_url": "https://infisical.com/docs/documentation/platform/groups",+ "columns": {+ "id": "Unique identifier for the group.",+ "orgId": "ID of the organization the group belongs to.",+ "name": "Display name of the group.",+ "slug": "URL-friendly slug of the group.",+ "role": "Organization role granted to group members (e.g. admin, member, or custom).",+ "roleId": "ID of the custom role, when a custom role is assigned.",+ "createdAt": "When the group was created.",+ "updatedAt": "When the group was last updated.",+ },+ },+ "group_members": {+ "description": "Members of each group: one row per user or machine identity in a group.",+ "docs_url": "https://infisical.com/docs/documentation/platform/groups",+ "columns": {+ "groupId": "ID of the group.",+ "id": "Identifier for the member.",+ "type": "Member type: user or machineIdentity.",+ "joinedGroupAt": "When the member joined the group.",+ "user": "User object with the user's ID, email, name, and username, when the member is a user.",+ "machineIdentity": "Machine identity object with the identity's ID and name, when the member is a machine identity.",+ },+ },+ "project_group_memberships": {+ "description": "Groups attached to each project and the project roles they grant. One row per group-project membership across every project the machine identity can read.",+ "docs_url": "https://infisical.com/docs/documentation/platform/groups",+ "columns": {+ "id": "Unique identifier for the project group membership.",+ "groupId": "ID of the group.",+ "projectId": "ID of the project.",+ "group": "Group object with the group's ID, name, slug, and organization ID.",+ "roles": "Project roles granted to the group, including any temporary role windows.",+ "createdAt": "When the group was added to the project.",+ "updatedAt": "When the membership was last updated.",+ },+ },+ "secret_scanning_findings": {+ "description": "Leaked credentials found by secret scanning in connected data sources such as GitHub, GitLab, or Bitbucket repositories. One row per finding across every secret scanning project the machine identity can read. The secret value itself is not included.",+ "docs_url": "https://infisical.com/docs/documentation/platform/secret-scanning/overview",+ "columns": {+ "id": "Unique identifier for the finding.",+ "dataSourceName": "Name of the data source the finding came from.",+ "dataSourceType": "Data source type (e.g. github, gitlab, bitbucket).",+ "resourceName": "Name of the scanned resource, such as a repository.",+ "resourceType": "Type of the scanned resource (e.g. repository).",+ "rule": "Detection rule that matched.",+ "severity": "Severity of the finding.",+ "status": "Triage status (e.g. unresolved, resolved, false-positive, ignore).",+ "remarks": "Remarks added when the finding was triaged.",+ "fingerprint": "Fingerprint that identifies the leaked credential occurrence.",+ "details": "Location details: file, line and column range, commit, author, and link.",+ "projectId": "ID of the secret scanning project.",+ "scanId": "ID of the scan that produced the finding.",+ "createdAt": "When the finding was recorded.",+ "updatedAt": "When the finding was last updated.",+ },+ },}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/infisical/infisical.py b/products/warehouse_sources/backend/temporal/data_imports/sources/infisical/infisical.pyindex 09476257da3d..792a626c798a 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/infisical/infisical.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/infisical/infisical.py@@ -54,13 +54,13 @@ MAX_PAGES = 100_000# abort (non-retryably) once the budget is spent. Generous for any legitimate sync (fast pages# drain millions of rows well inside it).MAX_PAGINATION_SECONDS = 6 * 60 * 60-# The project fan-out makes one request per project, so a customer-controlled host that returns-# a huge project list (still under the byte cap) could turn one sync into millions of requests-# and hold an import worker for the activity's lifetime. Bound the fan-out; far above any-# legitimate org's project count.-MAX_FAN_OUT_PROJECTS = 10_000-# The project-count cap alone doesn't bound worker occupancy: a hostile host can return-# MAX_FAN_OUT_PROJECTS in-org projects and then drain each membership response's full+# The project/group fan-out makes at least one request per parent, so a customer-controlled host+# that returns a huge parent list (still under the byte cap) could turn one sync into millions of+# requests and hold an import worker for the activity's lifetime. Bound the fan-out; far above+# any legitimate org's project or group count.+MAX_FAN_OUT_PARENTS = 10_000+# The parent-count cap alone doesn't bound worker occupancy: a hostile host can return+# MAX_FAN_OUT_PARENTS in-org parents and then drain each child response's full# MAX_RESPONSE_SECONDS deadline, so 10,000 * 300s is ~34 days of work — far past this# resumable activity's week-long start_to_close_timeout. Bound the whole fan-out by wall-clock# too and abort once the budget is spent, keeping occupancy well under the activity timeout no@@ -453,9 +453,14 @@ def validate_credentials(if config is None:return False, f"Unknown Infisical table: {schema_name}"- # The fan-out endpoint's per-project scopes can't be probed cheaply, so probe the- # project list it iterates instead.- path = "/api/v1/projects" if config.fan_out_over_projects else _format_path(config.path, organization_id.strip())+ # Fan-out endpoints' per-parent scopes can't be probed cheaply, so probe the parent list+ # they iterate instead.+ if config.fan_out_over == "groups":+ path = "/api/v1/groups"+ elif config.fan_out_over == "projects":+ path = "/api/v1/projects"+ else:+ path = _format_path(config.path, organization_id.strip())params: dict[str, Any] = {"limit": 1, "offset": 0} if config.paginated else {}try:client.get(path, params)@@ -607,54 +612,128 @@ def _list_org_projects(client: InfisicalClient, organization_id: str) -> list[direturn [p for p in projects if p.get("orgId") == organization_id]-def _get_project_fan_out_rows(+def _extract_rows(body: Any, data_key: str | None) -> list[dict[str, Any]]:+ rows = body if data_key is None else (body.get(data_key) if isinstance(body, dict) else None)+ return rows if isinstance(rows, list) else []+++def _list_org_groups(client: InfisicalClient, organization_id: str) -> list[dict[str, Any]]:+ """List the configured org's groups.++ ``/api/v1/groups`` is scoped by the access token's org, not a path parameter, so filter on+ ``orgId`` for the same reason as ``_list_org_projects``.+ """+ groups = _extract_rows(client.get("/api/v1/groups").json(), None)+ return [g for g in groups if g.get("orgId") == organization_id]+++def _check_fan_out_budget(deadline: float, config_name: str) -> None:+ if time.monotonic() > deadline:+ raise InfisicalFanOutBudgetExceededError(+ f"Infisical fan-out for {config_name} exceeded its {MAX_FAN_OUT_SECONDS}s "+ f"budget before finishing all parents; aborting the sync"+ )+++def _get_fan_out_child_pages(+ client: InfisicalClient,+ config: InfisicalEndpointConfig,+ path: str,+ params: dict[str, Any],+ fan_out_deadline: float,+ logger: FilteringBoundLogger,+) -> Iterator[list[dict[str, Any]]]:+ if not config.paginated:+ _check_fan_out_budget(fan_out_deadline, config.name)+ rows = _extract_rows(client.get(path, params).json(), config.data_key)+ if rows:+ yield rows+ return++ offset = 0+ for page in range(MAX_PAGES):+ _check_fan_out_budget(fan_out_deadline, config.name)+ page_params = {**params, "limit": config.page_limit, "offset": offset, **config.extra_params}+ rows = _extract_rows(client.get(path, page_params).json(), config.data_key)+ if not rows:+ break++ yield rows++ offset += len(rows)+ if len(rows) < config.page_limit:+ break++ if page == MAX_PAGES - 1:+ logger.warning(f"Infisical: hit MAX_PAGES={MAX_PAGES} for {config.name} at {path}, stopping pagination")+++def _get_fan_out_rows(client: InfisicalClient,config: InfisicalEndpointConfig,organization_id: str,logger: FilteringBoundLogger,) -> Iterator[list[dict[str, Any]]]:- projects = _list_org_projects(client, organization_id)- if len(projects) > MAX_FAN_OUT_PROJECTS:- # base_url is customer-controlled, so a hostile host could return far more projects than+ if config.fan_out_over == "groups":+ parents = _list_org_groups(client, organization_id)+ placeholder = "{group_id}"+ else:+ parents = _list_org_projects(client, organization_id)+ if config.fan_out_project_type:+ parents = [p for p in parents if p.get("type") == config.fan_out_project_type]+ placeholder = "{project_id}"++ if len(parents) > MAX_FAN_OUT_PARENTS:+ # base_url is customer-controlled, so a hostile host could return far more parents than# any real org has to fan the sync out into unbounded requests. Cap it.logger.warning(- f"Infisical: {len(projects)} projects for {config.name} exceeds "- f"MAX_FAN_OUT_PROJECTS={MAX_FAN_OUT_PROJECTS}; capping fan-out"+ f"Infisical: {len(parents)} {config.fan_out_over} for {config.name} exceeds "+ f"MAX_FAN_OUT_PARENTS={MAX_FAN_OUT_PARENTS}; capping fan-out")- projects = projects[:MAX_FAN_OUT_PROJECTS]+ parents = parents[:MAX_FAN_OUT_PARENTS]- # The count cap bounds how many projects we fan out over, but not how long each one takes:- # a hostile host can drain every membership response's full deadline. Bound total wall-clock+ # The count cap bounds how many parents we fan out over, but not how long each one takes:+ # a hostile host can drain every child response's full deadline. Bound total wall-clock# across the loop (retries included) and abort rather than truncate, so a slow host can't# hold the worker for the activity's lifetime. Checked before each request; the in-flight# request may overrun by at most one response deadline, which is already bounded elsewhere.fan_out_deadline = time.monotonic() + MAX_FAN_OUT_SECONDS- for project in projects:- if time.monotonic() > fan_out_deadline:- raise InfisicalFanOutBudgetExceededError(- f"Infisical project fan-out for {config.name} exceeded its {MAX_FAN_OUT_SECONDS}s "- f"budget before finishing all {len(projects)} projects; aborting the sync"- )+ any_parent_read = False+ last_forbidden: requests.HTTPError | None = None+ for parent in parents:+ _check_fan_out_budget(fan_out_deadline, config.name)- project_id = project.get("id")- if not project_id:+ parent_id = parent.get("id")+ if not parent_id:continue- path = config.path.replace("{project_id}", quote(str(project_id), safe=""))+ path = config.path.replace(placeholder, quote(str(parent_id), safe=""))+ params: dict[str, Any] = {config.parent_id_param: parent_id} if config.parent_id_param else {}+ yielded = Falsetry:- rows = client.get(path).json().get(config.data_key) or []+ for rows in _get_fan_out_child_pages(client, config, path, params, fan_out_deadline, logger):+ if config.parent_id_field:+ rows = [{**row, config.parent_id_field: parent_id} for row in rows]+ yielded = True+ yield rows+ any_parent_read = Trueexcept requests.HTTPError as exc:status = exc.response.status_code if exc.response is not None else None- # The machine identity's project grants are per-project, and a project can be- # deleted between enumeration and this fetch. Skip rather than failing the sync.- if status in (403, 404):- logger.warning(f"Infisical: skipping project {project_id} {config.name} (status={status})")+ # The machine identity's grants are per-project, and a parent can be deleted+ # between enumeration and this fetch. Skip rather than failing the sync, unless+ # pages were already yielded: skipping then would leave a partial parent behind.+ if status in (403, 404) and not yielded:+ if status == 403:+ last_forbidden = exc+ logger.warning(f"Infisical: skipping {parent_id} for {config.name} (status={status})")continueraise- if rows:- yield rows+ # Every parent forbidden means the identity lacks the permission outright. Fail rather than+ # report an empty full refresh as a success.+ if last_forbidden is not None and not any_parent_read:+ raise last_forbiddendef get_rows(@@ -681,8 +760,8 @@ def get_rows(client = InfisicalClient(normalized, client_id, client_secret, logger)organization_id = organization_id.strip()- if config.fan_out_over_projects:- yield from _get_project_fan_out_rows(client, config, organization_id, logger)+ if config.fan_out_over:+ yield from _get_fan_out_rows(client, config, organization_id, logger)returnif endpoint == "projects":@@ -709,7 +788,15 @@ def get_rows(yield from _get_offset_paginated_rows(client, config, organization_id, resumable_source_manager, logger)return- rows = client.get(_format_path(config.path, organization_id)).json().get(config.data_key) or []+ rows = _extract_rows(client.get(_format_path(config.path, organization_id)).json(), config.data_key)+ if config.filter_by_org_id:+ scoped = [row for row in rows if row.get("orgId") == organization_id]+ if len(scoped) != len(rows):+ logger.warning(+ f"Infisical: dropped {len(rows) - len(scoped)} {config.name} rows from another org "+ f"(configured org={organization_id})"+ )+ rows = scopedif rows:yield rows@@ -742,7 +829,7 @@ def infisical_source(should_use_incremental_field=should_use_incremental_field,db_incremental_field_last_value=db_incremental_field_last_value,),- primary_keys=[endpoint_config.primary_key],+ primary_keys=endpoint_config.primary_keys,# The audit log has no sort param and returns newest-first (verified against the# open-source server, which orders by createdAt DESC), so desc — the pipeline then# persists the incremental watermark only at successful job end. Every incrementaldiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/infisical/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/infisical/settings.pyindex 2c64104047c9..d832adab513e 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/infisical/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/infisical/settings.py@@ -1,27 +1,37 @@from dataclasses import dataclass, field+from typing import Literalfrom products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType-@dataclass+@dataclass(frozen=False)class InfisicalEndpointConfig:name: str# API path, optionally with `{organization_id}` / `{project_id}` placeholders.path: str- # Key holding the row list in the response body (Infisical wraps every list).- data_key: str+ # Key holding the row list in the response body, or None when the body is the list itself.+ data_key: str | Noneincremental_fields: list[IncrementalField] = field(default_factory=list)# Stable, immutable field to partition by. Never a mutable timestamp.partition_key: str | None = None- primary_key: str = "id"+ primary_keys: list[str] = field(default_factory=lambda: ["id"])# Whether the endpoint supports `offset`/`limit` pagination. Unpaginated endpoints# return the full list in one response.paginated: bool = Falsepage_limit: int = 500# Extra query params sent on every request (e.g. an explicit stable sort).extra_params: dict[str, str] = field(default_factory=dict)- # Fan out over every project from /api/v1/projects, formatting `{project_id}` per project.- fan_out_over_projects: bool = False+ # Fan out over every project (`{project_id}`) or group (`{group_id}`) in the configured org.+ fan_out_over: Literal["projects", "groups"] | None = None+ # Only fan out over projects of this type, for endpoints that reject other project types.+ fan_out_project_type: str | None = None+ # Send the parent ID as this query param rather than as a path placeholder.+ parent_id_param: str | None = None+ # Stamp the parent ID onto child rows under this key, for children that don't carry it.+ parent_id_field: str | None = None+ # The endpoint is scoped by the access token's org rather than a path parameter, so an+ # identity in several orgs could see other orgs' rows. Keep only the configured org's rows.+ filter_by_org_id: bool = FalseINFISICAL_ENDPOINTS: dict[str, InfisicalEndpointConfig] = {@@ -69,7 +79,57 @@ INFISICAL_ENDPOINTS: dict[str, InfisicalEndpointConfig] = {name="project_memberships",path="/api/v1/projects/{project_id}/memberships",data_key="memberships",- fan_out_over_projects=True,+ fan_out_over="projects",+ ),+ "organization_roles": InfisicalEndpointConfig(+ name="organization_roles",+ path="/api/v1/organization/roles",+ data_key="roles",+ filter_by_org_id=True,+ ),+ "project_roles": InfisicalEndpointConfig(+ name="project_roles",+ path="/api/v1/projects/{project_id}/roles",+ data_key="roles",+ # Built-in project roles (admin, member, viewer, ...) get a fresh random id on every+ # request, so key on the slug, which is unique within a project.+ primary_keys=["projectId", "slug"],+ fan_out_over="projects",+ ),+ "groups": InfisicalEndpointConfig(+ name="groups",+ path="/api/v1/groups",+ data_key=None,+ filter_by_org_id=True,+ ),+ # Users and machine identities in each group. Member rows don't carry the group ID.+ "group_members": InfisicalEndpointConfig(+ name="group_members",+ path="/api/v1/groups/{group_id}/members",+ data_key="members",+ primary_keys=["groupId", "id"],+ paginated=True,+ page_limit=100, # documented maximum+ extra_params={"orderBy": "name", "orderDirection": "asc"},+ fan_out_over="groups",+ parent_id_field="groupId",+ ),+ "project_group_memberships": InfisicalEndpointConfig(+ name="project_group_memberships",+ path="/api/v1/projects/{project_id}/memberships/groups",+ data_key="groupMemberships",+ fan_out_over="projects",+ ),+ # Not in the published API reference, but the endpoint accepts machine identity tokens and+ # backs the dashboard's findings view. The response omits the matched secret value.+ "secret_scanning_findings": InfisicalEndpointConfig(+ name="secret_scanning_findings",+ path="/api/v2/secret-scanning/findings",+ data_key="findings",+ partition_key="createdAt",+ fan_out_over="projects",+ fan_out_project_type="secret-scanning",+ parent_id_param="projectId",),}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/infisical/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/infisical/source.pyindex 97ecbb938766..619dad2e6653 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/infisical/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/infisical/source.py@@ -55,9 +55,9 @@ class InfisicalSource(ResumableSource[InfisicalSourceConfig, InfisicalResumeConfcategory=DataWarehouseSourceCategory.ENGINEERING___MONITORING,label="Infisical",releaseStatus=ReleaseStatus.ALPHA,- caption="""Connect an Infisical machine identity to pull your organization's audit logs, projects, identities, and memberships into the PostHog Data warehouse. Secret values are never synced.+ caption="""Connect an Infisical machine identity to pull your organization's audit logs, projects, identities, memberships, roles, groups, and secret scanning findings into the PostHog Data warehouse. Secret values are never synced.-In Infisical, create a machine identity under **Organization settings > Access control > Identities**, add a **Universal Auth** method to it, and grant it read permissions for the data you want to sync (audit logs, projects, identities, and memberships). Note that audit log access is plan-gated on Infisical Cloud.+In Infisical, create a machine identity under **Organization settings > Access control > Identities**, add a **Universal Auth** method to it, and grant it read permissions for the data you want to sync (audit logs, projects, identities, memberships, roles, groups, and secret scanning findings). Note that audit log access and secret scanning are plan-gated on Infisical Cloud.- **Base URL**: `https://app.infisical.com` (US cloud), `https://eu.infisical.com` (EU cloud), or your self-hosted URL.- **Organization ID**: found in your Infisical URL after `/org/`, or in organization settings.diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/infisical/tests/test_infisical.py b/products/warehouse_sources/backend/temporal/data_imports/sources/infisical/tests/test_infisical.pyindex a43bdf0273be..1aa3197970fc 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/infisical/tests/test_infisical.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/infisical/tests/test_infisical.py@@ -21,8 +21,8 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.infisical.InfisicalResumeConfig,_format_incremental_value,_get_audit_log_rows,+ _get_fan_out_rows,_get_offset_paginated_rows,- _get_project_fan_out_rows,_parse_retry_after,_retry_wait,get_rows,@@ -283,19 +283,22 @@ class TestProjectMembershipsFanOut:"/api/v1/projects/p3/memberships",]- def test_non_permission_error_fails_the_sync(self):+ @pytest.mark.parametrize("status_code", [400, 403])+ def test_fails_the_sync_when_no_project_is_readable(self, status_code):+ # A 403 on every project means the identity lacks the permission outright, so an empty+ # full refresh must not be reported as a success.projects = _response(json_data={"projects": [{"id": "p1", "orgId": "org-123"}]})- bad_request = _response(status_code=400)+ error = _response(status_code=status_code)with pytest.raises(requests.HTTPError):- _run_get_rows([_login_response(), projects, bad_request], "project_memberships")+ _run_get_rows([_login_response(), projects, error], "project_memberships")def test_fan_out_is_capped(self):# base_url is customer-controlled: a host returning far more projects than any real org# (still under the byte cap) would fan one sync out into a request per project and hold- # the worker. The fan-out must stop at MAX_FAN_OUT_PROJECTS.+ # the worker. The fan-out must stop at MAX_FAN_OUT_PARENTS.projects = _response(json_data={"projects": [{"id": f"p{i}", "orgId": "org-123"} for i in range(3)]})membership = _response(json_data={"memberships": [{"id": "m1", "projectId": "p0"}]})- with mock.patch.object(infisical_module, "MAX_FAN_OUT_PROJECTS", 2):+ with mock.patch.object(infisical_module, "MAX_FAN_OUT_PARENTS", 2):_rows, session, _manager = _run_get_rows([_login_response(), projects, membership, membership], "project_memberships")@@ -322,13 +325,52 @@ class TestProjectMembershipsFanOut:mock.patch.object(infisical_module.time, "monotonic", lambda: next(clock)),pytest.raises(InfisicalFanOutBudgetExceededError),):- list(_get_project_fan_out_rows(client, config, "org-123", mock.MagicMock()))+ list(_get_fan_out_rows(client, config, "org-123", mock.MagicMock()))# Aborted mid-fan-out: not every project was fetched.membership_calls = [c for c in client.get.call_args_list if "memberships" in c.args[0]]assert 0 < len(membership_calls) < 5+class TestGroupMembersFanOut:+ def test_paginates_each_group_and_stamps_group_id(self):+ groups = _response(json_data=[{"id": "g1", "orgId": "org-123"}, {"id": "g2", "orgId": "other-org"}])+ page1 = _response(+ json_data={"members": [{"id": "u1", "type": "user"}, {"id": "i1", "type": "machineIdentity"}]}+ )+ page2 = _response(json_data={"members": [{"id": "u2", "type": "user"}]})+ with mock.patch.object(INFISICAL_ENDPOINTS["group_members"], "page_limit", 2):+ rows, session, _manager = _run_get_rows([_login_response(), groups, page1, page2], "group_members")++ # Member rows don't carry their group, so without the stamp the composite key collapses+ # across groups.+ assert [(r["groupId"], r["id"]) for r in rows] == [("g1", "u1"), ("g1", "i1"), ("g1", "u2")]+ urls = _get_urls(session)+ # The other org's group is never fetched.+ assert [urlparse(u).path for u in urls] == ["/api/v1/groups", *["/api/v1/groups/g1/members"] * 2]+ assert [_query(u)["offset"] for u in urls[1:]] == [["0"], ["2"]]+++class TestSecretScanningFindingsFanOut:+ def test_only_secret_scanning_projects_are_queried_by_project_id(self):+ # The findings endpoint rejects other project types with a 400, which would fail the sync.+ projects = _response(+ json_data={+ "projects": [+ {"id": "p1", "orgId": "org-123", "type": "secret-manager"},+ {"id": "p2", "orgId": "org-123", "type": "secret-scanning"},+ ]+ }+ )+ findings = _response(json_data={"findings": [{"id": "f1", "projectId": "p2"}]})+ rows, session, _manager = _run_get_rows([_login_response(), projects, findings], "secret_scanning_findings")++ assert [r["id"] for r in rows] == ["f1"]+ findings_url = _get_urls(session)[1]+ assert urlparse(findings_url).path == "/api/v2/secret-scanning/findings"+ assert _query(findings_url) == {"projectId": ["p2"]}++class TestOrgScoping:# /api/v1/projects isn't org-scoped — a machine identity shared with several orgs sees them# all. Without the orgId filter, the projects table and the project_memberships fan-out would@@ -338,6 +380,17 @@ class TestOrgScoping:rows, _session, _manager = _run_get_rows([_login_response(), page], "projects")assert [r["id"] for r in rows] == ["p1"]+ @pytest.mark.parametrize(+ "endpoint, body",+ [+ ("organization_roles", {"roles": [{"id": "r1", "orgId": "org-123"}, {"id": "r2", "orgId": "other-org"}]}),+ ("groups", [{"id": "r1", "orgId": "org-123"}, {"id": "r2", "orgId": "other-org"}]),+ ],+ )+ def test_token_scoped_tables_exclude_other_orgs(self, endpoint, body):+ rows, _session, _manager = _run_get_rows([_login_response(), _response(json_data=body)], endpoint)+ assert [r["id"] for r in rows] == ["r1"]+def test_project_memberships_fan_out_skips_other_orgs(self):projects = _response(json_data={"projects": [{"id": "p1", "orgId": "org-123"}, {"id": "p2", "orgId": "other-org"}]}