: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): implement infisical import source (#70720)
Tom Owers69fe1ea60292
diff --git a/frontend/public/services/infisical.svg b/frontend/public/services/infisical.svgnew file mode 100644index 000000000000..5104ae47e222--- /dev/null+++ b/frontend/public/services/infisical.svg@@ -0,0 +1,5 @@+<svg width="91" height="91" viewBox="0 0 91 91" fill="none" xmlns="http://www.w3.org/2000/svg">+<g transform="translate(0 24)">+<path d="M21.9734 0C24.8526 0 27.4793 0.412021 29.8535 1.23606C32.2528 2.06011 34.4123 3.13386 36.3318 4.45732C38.2766 5.75581 39.9814 7.10424 41.4463 8.50261C42.2545 9.25174 42.987 9.98839 43.6436 10.7125C44.3003 11.4367 44.9317 12.1609 45.5379 12.885C46.0935 12.1609 46.6618 11.4617 47.2427 10.7875C47.8489 10.0883 48.6066 9.32665 49.5158 8.50261C51.7132 6.38008 54.4409 4.43235 57.699 2.65941C60.9824 0.886471 64.7835 0 69.1024 0C73.1435 0 76.8183 0.97387 80.127 2.92161C83.4609 4.84437 86.1002 7.42886 88.045 10.6751C90.015 13.9213 91 17.5171 91 21.4625C91 24.4591 90.4317 27.2683 89.2952 29.8902C88.1586 32.4872 86.5927 34.7721 84.5974 36.7448C82.6021 38.6925 80.2785 40.2282 77.6266 41.3519C74.9746 42.4506 72.1332 43 69.1024 43C66.2231 43 63.5712 42.6005 61.1465 41.8014C58.7472 40.9774 56.5751 39.9286 54.6303 38.6551C52.7108 37.3815 51.0186 36.0706 49.5537 34.7221C48.7202 33.8981 47.9752 33.124 47.3185 32.3998C46.6871 31.6507 46.0935 30.9141 45.5379 30.1899C44.9065 30.9141 44.2624 31.6507 43.6057 32.3998C42.9491 33.149 42.2166 33.9231 41.4084 34.7221C39.9688 36.0706 38.2766 37.3815 36.3318 38.6551C34.4123 39.9036 32.2528 40.9399 29.8535 41.7639C27.4793 42.588 24.8526 43 21.9734 43C17.8818 43 14.1817 42.0386 10.873 40.1159C7.56439 38.1931 4.92506 35.6086 2.95504 32.3624C0.985013 29.0912 0 25.4579 0 21.4625C0 18.491 0.555648 15.7192 1.66694 13.1472C2.8035 10.5502 4.36941 8.26539 6.3647 6.29269C8.38523 4.31998 10.7215 2.78427 13.3734 1.68554C16.0507 0.561848 18.9173 0 21.9734 0ZM10.4563 21.4625C10.4563 23.5351 10.974 25.4204 12.0096 27.1185C13.0451 28.8165 14.4342 30.1649 16.1769 31.1638C17.9197 32.1626 19.8518 32.662 21.9734 32.662C24.3475 32.662 26.5322 32.1376 28.5275 31.0889C30.5228 30.0401 32.3791 28.7166 34.0966 27.1185C35.1826 26.0947 36.1171 25.1083 36.9001 24.1594C37.683 23.2105 38.365 22.3116 38.9459 21.4625C38.3397 20.6635 37.6199 19.777 36.7864 18.8031C35.9782 17.8043 35.0816 16.8554 34.0966 15.9564C32.4802 14.3833 30.649 13.0598 28.6032 11.9861C26.5575 10.8873 24.3475 10.338 21.9734 10.338C19.8518 10.338 17.9197 10.8499 16.1769 11.8737C14.4342 12.8725 13.0451 14.221 12.0096 15.919C10.974 17.592 10.4563 19.4399 10.4563 21.4625ZM80.4679 21.4625C80.4679 19.4399 79.9502 17.592 78.9146 15.919C77.9044 14.221 76.5405 12.8725 74.8231 11.8737C73.1056 10.8499 71.1987 10.338 69.1024 10.338C67.486 10.338 65.9453 10.5877 64.4804 11.0871C63.0155 11.5865 61.639 12.2607 60.351 13.1098C59.0881 13.9588 57.9263 14.9077 56.8655 15.9564C55.729 17.0052 54.7313 18.079 53.8726 19.1777C53.0139 20.2515 52.3951 21.0131 52.0162 21.4625C52.6477 22.3365 53.3549 23.248 54.1378 24.1969C54.9208 25.1208 55.83 26.0947 56.8655 27.1185C58.5577 28.7166 60.4015 30.0401 62.3968 31.0889C64.4173 32.1376 66.6525 32.662 69.1024 32.662C71.1987 32.662 73.1056 32.1626 74.8231 31.1638C76.5405 30.1649 77.9044 28.8165 78.9146 27.1185C79.9502 25.4204 80.4679 23.5351 80.4679 21.4625Z" fill="#0D0F12"/>+</g>+</svg>diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 0fbcb70cb57e..4f31ab92ece4 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -248,6 +248,7 @@ the row lists both.| hyperspell | HTTP | requests | ✅ || imagga | HTTP | requests | ✅ || incident_io | HTTP | requests | ✅ |+| infisical | HTTP | requests | ✅ || inflowinventory | HTTP | requests | ✅ || inngest | HTTP | requests | ✅ || insightly | HTTP | requests | ✅ |@@ -715,7 +716,6 @@ doesn't conflict with concurrent PRs.- ikas- illumina_basespace- impact-- infisical- infor_nexus- insightfuldiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.pyindex 998b71c6a87f..d1d5285f2093 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py@@ -2070,7 +2070,10 @@ class IncidentIoSourceConfig(config.Config):@config.configclass InfisicalSourceConfig(config.Config):- pass+ base_url: str+ organization_id: str+ client_id: str+ client_secret: str@config.configdiff --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.pynew file mode 100644index 000000000000..53f7d79835cb--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/infisical/canonical_descriptions.py@@ -0,0 +1,89 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "audit_logs": {+ "description": "Organization audit log events: every secret read/write, login, identity, policy, and settings change with actor, IP address, user agent, and event metadata.",+ "docs_url": "https://infisical.com/docs/api-reference/endpoints/audit-logs/export-audit-log",+ "columns": {+ "id": "Unique identifier for the audit log event.",+ "ipAddress": "IP address the request originated from.",+ "userAgent": "User agent string of the client that performed the action.",+ "userAgentType": "Consuming application category (e.g. web, cli, k8-operator, other).",+ "expiresAt": "When the event falls out of the plan's audit log retention window.",+ "createdAt": "When the event occurred.",+ "updatedAt": "When the event row was last updated.",+ "orgId": "ID of the organization the event belongs to.",+ "projectId": "ID of the project the event occurred in, if project-scoped.",+ "projectName": "Name of the project the event occurred in, if project-scoped.",+ "event": "Event object with the event type (e.g. get-secrets, create-secret, login-identity-universal-auth) and type-specific metadata.",+ "actor": "Actor object with the actor type (user, identity, service, platform) and actor-specific metadata such as the user or identity ID and name.",+ },+ },+ "projects": {+ "description": "Projects (workspaces) in the organization, including their environments and settings.",+ "docs_url": "https://infisical.com/docs/api-reference/endpoints/projects/list-projects",+ "columns": {+ "id": "Unique identifier for the project.",+ "name": "Display name of the project.",+ "description": "Description of the project.",+ "type": "Project type (e.g. secret-manager, cert-manager, ssh, kms).",+ "slug": "URL-friendly slug of the project.",+ "orgId": "ID of the organization the project belongs to.",+ "createdAt": "When the project was created.",+ "updatedAt": "When the project was last updated.",+ "version": "Internal project version.",+ "auditLogsRetentionDays": "Project-level audit log retention override, in days.",+ "hasDeleteProtection": "Whether delete protection is enabled for the project.",+ "environments": "Environments configured in the project (e.g. dev, staging, prod).",+ },+ },+ "identities": {+ "description": "Machine identity memberships in the organization: each machine identity with its organization role and last login details.",+ "docs_url": "https://infisical.com/docs/api-reference/endpoints/organizations/list-identity-memberships",+ "columns": {+ "id": "Unique identifier for the identity's organization membership.",+ "role": "Organization role assigned to the identity (e.g. admin, member, or custom).",+ "roleId": "ID of the custom role, when a custom role is assigned.",+ "orgId": "ID of the organization the identity belongs to.",+ "createdAt": "When the identity was added to the organization.",+ "updatedAt": "When the membership was last updated.",+ "identityId": "ID of the machine identity.",+ "lastLoginAuthMethod": "Auth method used for the identity's most recent login (e.g. universal-auth).",+ "lastLoginTime": "When the identity last logged in.",+ "customRole": "Custom role object, when a custom role is assigned.",+ "identity": "Identity object with the identity's ID, name, and enabled auth methods.",+ },+ },+ "organization_memberships": {+ "description": "User memberships in the organization: each member with their role, status, and last login details.",+ "docs_url": "https://infisical.com/docs/api-reference/endpoints/organizations/memberships",+ "columns": {+ "id": "Unique identifier for the user's organization membership.",+ "role": "Organization role assigned to the user (e.g. admin, member, or custom).",+ "roleId": "ID of the custom role, when a custom role is assigned.",+ "status": "Membership status (e.g. invited, accepted).",+ "inviteEmail": "Email address the invitation was sent to.",+ "userId": "ID of the user.",+ "orgId": "ID of the organization.",+ "isActive": "Whether the membership is currently active.",+ "lastInvitedAt": "When the user was last sent an invitation.",+ "lastLoginAuthMethod": "Auth method used for the user's most recent login.",+ "lastLoginTime": "When the user last logged in.",+ "user": "User object with the user's ID, email, name, and username.",+ },+ },+ "project_memberships": {+ "description": "User memberships per project: which users belong to which project and the roles they hold there. One row per user-project membership across every project the machine identity can read.",+ "docs_url": "https://infisical.com/docs/api-reference/endpoints/project-users/memberships",+ "columns": {+ "id": "Unique identifier for the project membership.",+ "createdAt": "When the user was added to the project.",+ "userId": "ID of the user.",+ "projectId": "ID of the project.",+ "user": "User object with the user's ID, email, name, and public key.",+ "roles": "Project roles assigned to the user, including any temporary role windows.",+ },+ },+}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.pynew file mode 100644index 000000000000..87fb18d3ba81--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/infisical/infisical.py@@ -0,0 +1,758 @@+import re+import time+import socket+import threading+import contextlib+import dataclasses+from collections.abc import Iterator+from datetime import UTC, date, datetime+from typing import Any, Optional+from urllib.parse import quote, urlencode, urlparse++import requests+import structlog+from structlog.types import FilteringBoundLogger+from tenacity import RetryCallState, retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session+from products.warehouse_sources.backend.temporal.data_imports.sources.common.mixins import _is_host_safe+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.infisical.settings import (+ INFISICAL_ENDPOINTS,+ InfisicalEndpointConfig,+)++DEFAULT_BASE_URL = "https://app.infisical.com"+REQUEST_TIMEOUT_SECONDS = 60+MAX_RETRIES = 5+MAX_RETRY_AFTER_SECONDS = 60+# Re-login this many seconds before the access token's advertised expiry, so a token can't+# lapse between the check and the request during a long sync.+TOKEN_EXPIRY_MARGIN_SECONDS = 60+# base_url points at a customer-controlled host, so cap what a single response may buffer into+# memory and how many pages a paginating loop may fetch — a hostile or misbehaving server can+# otherwise stream an unbounded (chunked) body or hand back full pages forever and exhaust the+# import worker. Both bounds are far above any legitimate Infisical response.+MAX_RESPONSE_BYTES = 128 * 1024 * 1024+RESPONSE_CHUNK_BYTES = 1024 * 1024+# Total wall-clock a single response body may take to drain. requests' timeout is an idle+# read timeout, not a transfer deadline, so a customer-controlled host could drip one byte+# just often enough to dodge it — never idling, never hitting the byte cap — and hold an+# import-worker thread for the activity's (week-long) lifetime. This bounds the whole+# transfer regardless of chunk cadence; it's far above any legitimate Infisical response.+MAX_RESPONSE_SECONDS = 300+# Ask for an uncompressed body so we can drain it with single, non-blocking reads (read1)+# that keep the deadline enforceable — see _read_capped_body. A host that ignores this and+# compresses anyway only breaks its own JSON parse; the size/time caps still hold.+IDENTITY_ENCODING_HEADERS = {"Accept-Encoding": "identity"}+MAX_PAGES = 100_000+# The page-count cap alone doesn't bound worker occupancy either: a hostile host can hand back a+# full page (still under the byte cap) that drains its whole MAX_RESPONSE_SECONDS deadline on every+# one of MAX_PAGES requests, so 100,000 * 300s is ~1 year of work — far past this resumable+# activity's week-long start_to_close_timeout. Bound each paginating loop by wall-clock too and+# 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+# 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+# matter how slowly the host answers. Generous for any legitimate org (thousands of fast+# per-project reads finish in minutes).+MAX_FAN_OUT_SECONDS = 6 * 60 * 60+# Cap how much of an error response body reaches the logs — the host is untrusted.+ERROR_BODY_LOG_LIMIT = 500++HOST_NOT_ALLOWED_ERROR = "Infisical host is not allowed"+INVALID_CREDENTIALS_ERROR = "Invalid Infisical machine identity credentials"++module_logger = structlog.get_logger(__name__)+++class InfisicalRetryableError(Exception):+ def __init__(self, message: str, retry_after: float | None = None) -> None:+ super().__init__(message)+ self.retry_after = retry_after+++class InfisicalHostNotAllowedError(Exception):+ pass+++class InfisicalResponseTooLargeError(Exception):+ pass+++class InfisicalAuthError(Exception):+ pass+++class InfisicalFanOutBudgetExceededError(Exception):+ pass+++class InfisicalPaginationBudgetExceededError(Exception):+ pass+++class InfisicalResumeConfig:+ # Offset of the next unfetched page within the (window_start, window_end) query.+ offset: int = 0+ # Audit-log time window pinned at sync start. Pinning end_date keeps offset pagination+ # stable while new logs keep arriving at the top of the (newest-first) result set.+ window_start: str | None = None+ window_end: str | None = None+++def normalize_base_url(base_url: str) -> str:+ """Turn whatever the user typed into ``https://<host>[:port]``.++ Accepts values like ``app.infisical.com``, ``https://eu.infisical.com/``, or a+ self-hosted URL with a stray path. Always https — machine identity secrets must+ never travel in plaintext.+ """+ value = base_url.strip()+ if not re.match(r"^https?://", value, flags=re.IGNORECASE):+ value = f"https://{value}"+ parsed = urlparse(value)+ host = (parsed.hostname or "").strip().lower()+ if not host or not re.match(r"^[a-z0-9.\-]+$", host):+ raise ValueError("Invalid Infisical base URL")+ port = f":{parsed.port}" if parsed.port else ""+ return f"https://{host}{port}"+++def _format_datetime_z(dt: datetime) -> str:+ utc_dt = dt.replace(tzinfo=UTC) if dt.tzinfo is None else dt.astimezone(UTC)+ return utc_dt.strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z"+++def _format_incremental_value(value: Any) -> str:+ if isinstance(value, datetime):+ return _format_datetime_z(value)+ if isinstance(value, date):+ return _format_datetime_z(datetime.combine(value, datetime.min.time(), tzinfo=UTC))+ return str(value)+++def _format_path(path: str, organization_id: str) -> str:+ # quote() with safe="" also encodes slashes, so a malformed org ID can't traverse the path.+ return path.replace("{organization_id}", quote(organization_id, safe=""))+++def _parse_retry_after(response: requests.Response) -> float | None:+ """Infisical sends ``Retry-After`` in whole seconds on 429. Ignore HTTP-date forms."""+ raw = response.headers.get("Retry-After")+ if raw and raw.strip().isdigit():+ return min(float(raw.strip()), MAX_RETRY_AFTER_SECONDS)+ return None+++def _retry_wait(retry_state: RetryCallState) -> float:+ """Honor a server-provided Retry-After when present, else exponential backoff."""+ exc = retry_state.outcome.exception() if retry_state.outcome else None+ if isinstance(exc, InfisicalRetryableError) and exc.retry_after is not None:+ return exc.retry_after+ return wait_exponential_jitter(initial=1, max=30)(retry_state)+++def _abort_on_deadline(response: requests.Response, tripped: threading.Event) -> None:+ """Watchdog: fire once the total-transfer deadline passes and unblock any in-progress read.++ ``read1`` bounds a *plain* drip because the deadline is re-checked between reads, but for a+ ``Transfer-Encoding: chunked`` body it falls through to the stdlib ``readline()`` that parses+ the chunk-size line, which loops until CRLF — a host dripping an unterminated size line stays+ inside one read past the deadline. Shutting the socket down forces that blocked read to+ return so the caller can abort, at the socket layer, regardless of what it's blocked on.+ Closing the response is the fallback when the raw socket isn't reachable (the read then+ unwinds on its idle timeout).+ """+ tripped.set()+ raw = getattr(response, "raw", None)+ conn = getattr(raw, "_connection", None) or getattr(raw, "connection", None)+ sock = getattr(conn, "sock", None)+ if sock is not None:+ with contextlib.suppress(Exception):+ sock.shutdown(socket.SHUT_RDWR)+ with contextlib.suppress(Exception):+ response.close()+++def _read_body_chunk(response: requests.Response, size: int) -> bytes:+ """Read up to ``size`` bytes with a *single* underlying socket read.++ ``read(size)`` / ``iter_content(size)`` loop until ``size`` bytes accumulate, so a host+ that drips a byte at a time — never idling long enough to trip the read timeout — stalls+ inside one read and the wall-clock deadline (only checked between reads) never fires.+ ``read1`` returns whatever a single read yields instead, so the deadline is re-checked+ after every read. urllib3 1.x exposes it only on the wrapped stdlib response (``_fp``);+ urllib3 2.x and any test double may expose it directly on ``raw``.+ """+ raw = response.raw+ read1 = getattr(raw, "read1", None) or getattr(getattr(raw, "_fp", None), "read1", None)+ if read1 is not None:+ return read1(size)+ # Defensive fallback for a raw object without read1: a filling read, still bounded by the+ # byte cap the caller enforces. Loses the deadline granularity but never buffers unbounded.+ return raw.read(size)+++@retry(+ retry=retry_if_exception_type(+ (+ InfisicalRetryableError,+ requests.ReadTimeout,+ requests.ConnectionError,+ requests.exceptions.ChunkedEncodingError,+ )+ ),+ stop=stop_after_attempt(MAX_RETRIES),+ wait=_retry_wait,+ reraise=True,+)+def _read_capped_body(response: requests.Response) -> None:+ """Buffer a streamed response body into memory under ``MAX_RESPONSE_BYTES``.++ Aborts (closing the connection) once the byte cap or the total-transfer deadline is+ crossed rather than letting a hostile or misbehaving host stream an unbounded chunked+ body — or drip one byte at a time forever — and exhaust the worker. Reads a single socket+ read at a time (see ``_read_body_chunk``) so the deadline is enforceable between reads, and+ a watchdog shuts the socket down at the deadline so a read stuck parsing a dripped chunk+ frame can't outlast it either. Pins the bytes onto the response so downstream ``.json()`` /+ ``.text`` keep working.+ """+ total = 0+ chunks: list[bytes] = []+ deadline = time.monotonic() + MAX_RESPONSE_SECONDS+ tripped = threading.Event()+ watchdog = threading.Timer(MAX_RESPONSE_SECONDS, _abort_on_deadline, args=(response, tripped))+ watchdog.daemon = True+ watchdog.start()+ deadline_msg = f"Infisical response did not finish within {MAX_RESPONSE_SECONDS}s; aborting"+ try:+ while True:+ # A slow-drip host can stay under the byte cap and never trip the idle read+ # timeout, so bound the total transfer time as well. Checked before every single+ # read; the watchdog is the backstop for a read that blocks past the deadline.+ if tripped.is_set() or time.monotonic() > deadline:+ response.close()+ raise InfisicalResponseTooLargeError(deadline_msg)+ chunk = _read_body_chunk(response, RESPONSE_CHUNK_BYTES)+ if not chunk:+ break+ total += len(chunk)+ if total > MAX_RESPONSE_BYTES:+ response.close()+ raise InfisicalResponseTooLargeError(+ f"Infisical response exceeded {MAX_RESPONSE_BYTES} bytes; refusing to buffer it"+ )+ chunks.append(chunk)+ except Exception as exc:+ # The watchdog shutting the socket down (and closing the response) unblocks the in-flight+ # read, which surfaces as whatever that read was mid-way through — a socket/connection+ # error, an incomplete chunked read, or an attribute error from the concurrent close.+ # Whatever it is, if the watchdog tripped it's a deadline abort, not a retryable blip.+ if tripped.is_set():+ raise InfisicalResponseTooLargeError(deadline_msg) from exc+ raise+ finally:+ watchdog.cancel()+ # A body that finished exactly as the watchdog fired still counts as over-deadline.+ if tripped.is_set():+ raise InfisicalResponseTooLargeError(deadline_msg)+ # Reading raw bypasses urllib3's own connection release, so return the drained connection+ # to the pool ourselves to keep the reused session's keep-alive working.+ with contextlib.suppress(Exception):+ response.raw.release_conn()+ # Setting _content to real bytes short-circuits Response.content, so downstream+ # .json()/.text return this buffer instead of re-reading the consumed stream.+ response._content = b"".join(chunks)+++def _send(+ session: requests.Session,+ method: str,+ url: str,+ logger: FilteringBoundLogger,+ headers: dict[str, str] | None = None,+ json_body: dict[str, Any] | None = None,+) -> requests.Response:+ # Don't follow redirects: the base URL is customer-controlled, so a 3xx could point at an+ # internal address and defeat the host validation done before the request (SSRF).+ # stream=True keeps the body unread until _read_capped_body enforces the size cap below;+ # Accept-Encoding: identity lets that reader drain the body with single non-blocking reads.+ response = session.request(+ method,+ url,+ headers={**IDENTITY_ENCODING_HEADERS, **(headers or {})},+ json=json_body,+ timeout=REQUEST_TIMEOUT_SECONDS,+ allow_redirects=False,+ stream=True,+ )++ if response.status_code == 429 or response.status_code >= 500:+ retry_after = _parse_retry_after(response) if response.status_code == 429 else None+ response.close()+ raise InfisicalRetryableError(+ f"Infisical API error (retryable): status={response.status_code}, url={url}",+ retry_after=retry_after,+ )++ # A 3xx isn't an error status (`response.ok` is True), so reject it explicitly rather than+ # silently parsing the redirect body as data.+ if response.is_redirect or response.is_permanent_redirect:+ response.close()+ raise InfisicalHostNotAllowedError(+ f"Infisical API returned an unexpected redirect (status={response.status_code}); refusing to follow it"+ )++ _read_capped_body(response)++ if not response.ok:+ logger.error(+ f"Infisical API error: status={response.status_code}, body={response.text[:ERROR_BODY_LOG_LIMIT]}, url={url}"+ )+ response.raise_for_status()++ return response+++class InfisicalClient:+ """Minimal Universal Auth client: exchanges the machine identity's client ID/secret for a+ short-lived bearer token and re-logins when the token nears expiry (or is rejected)."""++ def __init__(self, base_url: str, client_id: str, client_secret: str, logger: FilteringBoundLogger) -> None:+ self._base_url = normalize_base_url(base_url)+ self._client_id = client_id+ self._client_secret = client_secret+ self._logger = logger+ # capture=False on both sessions. HTTP sample capture reads response.text inside the+ # tracked adapter's send() — before _send's _read_capped_body runs — so an armed+ # capture rule would buffer an unbounded body from the customer-controlled host and+ # defeat the size cap. The auth exchange additionally carries the client secret and+ # minted accessToken in camelCase fields the name-based scrubbers don't recognise.+ # One session reused across every request so urllib3 keeps the connection alive.+ self._session = make_tracked_session(redact_values=(client_secret,), capture=False)+ self._auth_session = make_tracked_session(redact_values=(client_secret,), capture=False)+ self._access_token: str | None = None+ self._token_refresh_at: float = 0.0++ @property+ def base_url(self) -> str:+ return self._base_url++ def ensure_token(self) -> str:+ if self._access_token is not None and time.monotonic() < self._token_refresh_at:+ return self._access_token++ try:+ response = _send(+ self._auth_session,+ "post",+ f"{self._base_url}/api/v1/auth/universal-auth/login",+ self._logger,+ headers={"Accept": "application/json"},+ json_body={"clientId": self._client_id, "clientSecret": self._client_secret},+ )+ except requests.HTTPError as exc:+ status = exc.response.status_code if exc.response is not None else None+ if status in (400, 401, 403):+ raise InfisicalAuthError(INVALID_CREDENTIALS_ERROR) from exc+ raise++ data = response.json()+ self._access_token = data["accessToken"]+ expires_in = float(data.get("expiresIn") or 0)+ # expiresIn <= margin (including a non-expiring token reported as 0) falls back to a+ # periodic hourly re-login, which is always safe.+ refresh_after = expires_in - TOKEN_EXPIRY_MARGIN_SECONDS+ if refresh_after <= 0:+ refresh_after = 3600+ self._token_refresh_at = time.monotonic() + refresh_after+ return self._access_token++ def get(self, path: str, params: dict[str, Any] | None = None) -> requests.Response:+ url = f"{self._base_url}{path}"+ if params:+ url = f"{url}?{urlencode(params)}"++ token = self.ensure_token()+ try:+ return self._get(url, token)+ except requests.HTTPError as exc:+ # A 401 mid-sync usually means the token was revoked/expired server-side earlier+ # than advertised — re-login once before giving up.+ if exc.response is not None and exc.response.status_code == 401:+ self._access_token = None+ return self._get(url, self.ensure_token())+ raise++ def _get(self, url: str, token: str) -> requests.Response:+ return _send(+ self._session,+ "get",+ url,+ self._logger,+ headers={"Authorization": f"Bearer {token}", "Accept": "application/json"},+ )+++def validate_credentials(+ base_url: str,+ client_id: str,+ client_secret: str,+ organization_id: str,+ schema_name: Optional[str] = None,+ team_id: Optional[int] = None,+) -> tuple[bool, str | None]:+ """Exchange the machine identity credentials for a token to confirm they are genuine.++ At source-create (``schema_name is None``) a successful login is enough — per-endpoint+ permissions are granted separately in Infisical and users may only scope the identity to+ the tables they want. A scoped probe (``schema_name`` set) also hits that endpoint and+ treats 403 as a hard failure.+ """+ try:+ normalized = normalize_base_url(base_url)+ except ValueError:+ return False, "Invalid Infisical base URL"++ if not re.match(r"^[A-Za-z0-9\-]+$", organization_id.strip()):+ return False, "Invalid Infisical organization ID"++ # The base URL is fully customer-controlled, so block hosts that resolve to private/+ # internal addresses (SSRF). Only enforced on cloud — see _is_host_safe.+ if team_id is not None:+ host_ok, host_err = _is_host_safe(urlparse(normalized).hostname or "", team_id)+ if not host_ok:+ return False, host_err or HOST_NOT_ALLOWED_ERROR++ client = InfisicalClient(normalized, client_id, client_secret, module_logger)+ try:+ client.ensure_token()+ except InfisicalAuthError as exc:+ return False, str(exc)+ except InfisicalHostNotAllowedError:+ return False, HOST_NOT_ALLOWED_ERROR+ except requests.RequestException as exc:+ return False, str(exc)++ if schema_name is None:+ return True, None++ config = INFISICAL_ENDPOINTS.get(schema_name)+ 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())+ params: dict[str, Any] = {"limit": 1, "offset": 0} if config.paginated else {}+ try:+ client.get(path, params)+ except requests.HTTPError as exc:+ status = exc.response.status_code if exc.response is not None else None+ if status == 401:+ return False, INVALID_CREDENTIALS_ERROR+ if status == 403:+ return False, f"Your Infisical machine identity lacks permission to read {schema_name}"+ return False, str(exc)+ except InfisicalHostNotAllowedError:+ return False, HOST_NOT_ALLOWED_ERROR+ except requests.RequestException as exc:+ return False, str(exc)++ return True, None+++def _check_pagination_budget(deadline: float, config_name: str) -> None:+ """Abort a paginating loop once its wall-clock budget is spent.++ The page-count cap (MAX_PAGES) bounds how many pages we fetch, not how long each one takes: a+ hostile host can drain every page's full response deadline. Bound the whole loop by wall-clock+ and abort — checked before each request, so the in-flight request may overrun by at most one+ response deadline, which is already bounded elsewhere.+ """+ if time.monotonic() > deadline:+ raise InfisicalPaginationBudgetExceededError(+ f"Infisical pagination for {config_name} exceeded its {MAX_PAGINATION_SECONDS}s "+ f"budget before draining all pages; aborting the sync"+ )+++def _get_audit_log_rows(+ client: InfisicalClient,+ config: InfisicalEndpointConfig,+ organization_id: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[InfisicalResumeConfig],+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+) -> Iterator[list[dict[str, Any]]]:+ """Page through the org audit log newest-first within a pinned time window.++ The endpoint has no sort param and returns rows newest-first, so the window's endDate is+ pinned at sync start: logs arriving mid-sync land before the window and can't shift rows+ across page boundaries. Incremental runs set startDate to the createdAt watermark+ (inclusive — the boundary row is re-pulled and deduped on the primary key).++ This endpoint is scoped by the org in the access token rather than by a path parameter, so+ drop any row whose ``orgId`` isn't the configured org as defense in depth — a machine+ identity with access to more than one org must not leak another org's audit events here.+ Pagination still advances by the raw page size so the server-side offset stays correct.+ """+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ if resume is not None and resume.window_end:+ offset = resume.offset+ window_start = resume.window_start+ window_end = resume.window_end+ logger.debug(f"Infisical: resuming audit_logs at offset={offset}, window_end={window_end}")+ else:+ offset = 0+ window_end = _format_datetime_z(datetime.now(UTC))+ window_start = (+ _format_incremental_value(db_incremental_field_last_value)+ if should_use_incremental_field and db_incremental_field_last_value+ else None+ )++ pagination_deadline = time.monotonic() + MAX_PAGINATION_SECONDS+ for page in range(MAX_PAGES):+ _check_pagination_budget(pagination_deadline, config.name)++ params: dict[str, Any] = {"limit": config.page_limit, "offset": offset, "endDate": window_end}+ if window_start:+ params["startDate"] = window_start++ rows = client.get(config.path, params).json().get(config.data_key) or []+ if not rows:+ break++ 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)} audit_logs rows from another org "+ f"(configured org={organization_id})"+ )+ if scoped:+ yield scoped++ offset += len(rows)+ # Save AFTER yielding so a crash re-yields the last page rather than skipping it —+ # merge dedupes on the primary key.+ resumable_source_manager.save_state(+ InfisicalResumeConfig(offset=offset, window_start=window_start, window_end=window_end)+ )++ if len(rows) < config.page_limit:+ break++ if page == MAX_PAGES - 1:+ logger.warning(f"Infisical: hit MAX_PAGES={MAX_PAGES} for audit_logs, stopping pagination")+++def _get_offset_paginated_rows(+ client: InfisicalClient,+ config: InfisicalEndpointConfig,+ organization_id: str,+ resumable_source_manager: ResumableSourceManager[InfisicalResumeConfig],+ logger: FilteringBoundLogger,+) -> Iterator[list[dict[str, Any]]]:+ path = _format_path(config.path, organization_id)++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ offset = resume.offset if resume is not None else 0+ if offset:+ logger.debug(f"Infisical: resuming {config.name} at offset={offset}")++ pagination_deadline = time.monotonic() + MAX_PAGINATION_SECONDS+ for page in range(MAX_PAGES):+ _check_pagination_budget(pagination_deadline, config.name)++ params: dict[str, Any] = {"limit": config.page_limit, "offset": offset, **config.extra_params}+ rows = client.get(path, params).json().get(config.data_key) or []+ if not rows:+ break++ yield rows++ offset += len(rows)+ resumable_source_manager.save_state(InfisicalResumeConfig(offset=offset))++ if len(rows) < config.page_limit:+ break++ if page == MAX_PAGES - 1:+ logger.warning(f"Infisical: hit MAX_PAGES={MAX_PAGES} for {config.name}, stopping pagination")+++def _list_org_projects(client: InfisicalClient, organization_id: str) -> list[dict[str, Any]]:+ """List the configured org's projects.++ ``/api/v1/projects`` isn't scoped by org — it returns every project the machine identity+ can read across all orgs it belongs to. Keep only the configured org so an identity shared+ with several orgs can't pull project (or, via the fan-out, membership) data from orgs other+ than the one this source is configured for.+ """+ projects = client.get("/api/v1/projects").json().get("projects") or []+ return [p for p in projects if p.get("orgId") == organization_id]+++def _get_project_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+ # 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"+ )+ projects = projects[:MAX_FAN_OUT_PROJECTS]++ # 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+ # 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"+ )++ project_id = project.get("id")+ if not project_id:+ continue++ path = config.path.replace("{project_id}", quote(str(project_id), safe=""))+ try:+ rows = client.get(path).json().get(config.data_key) or []+ except 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})")+ continue+ raise++ if rows:+ yield rows+++def get_rows(+ base_url: str,+ client_id: str,+ client_secret: str,+ organization_id: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[InfisicalResumeConfig],+ team_id: int,+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+) -> Iterator[list[dict[str, Any]]]:+ config = INFISICAL_ENDPOINTS[endpoint]+ normalized = normalize_base_url(base_url)++ # Re-check at run time (not just at source-create) in case the base URL was edited or now+ # resolves to an internal address (SSRF / DNS rebinding). Only enforced on cloud.+ host_ok, host_err = _is_host_safe(urlparse(normalized).hostname or "", team_id)+ if not host_ok:+ raise InfisicalHostNotAllowedError(host_err or HOST_NOT_ALLOWED_ERROR)++ 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)+ return++ if endpoint == "projects":+ # /api/v1/projects isn't org-scoped, so filter to the configured org rather than+ # syncing every project the machine identity can see across all its orgs.+ projects = _list_org_projects(client, organization_id)+ if projects:+ yield projects+ return++ if endpoint == "audit_logs":+ yield from _get_audit_log_rows(+ client,+ config,+ organization_id,+ logger,+ resumable_source_manager,+ should_use_incremental_field,+ db_incremental_field_last_value,+ )+ return++ if config.paginated:+ 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 []+ if rows:+ yield rows+++def infisical_source(+ base_url: str,+ client_id: str,+ client_secret: str,+ organization_id: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[InfisicalResumeConfig],+ team_id: int,+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+) -> SourceResponse:+ endpoint_config = INFISICAL_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ base_url=base_url,+ client_id=client_id,+ client_secret=client_secret,+ organization_id=organization_id,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ team_id=team_id,+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=db_incremental_field_last_value,+ ),+ primary_keys=[endpoint_config.primary_key],+ # 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 incremental+ # run covers the full [watermark, sync-start] window in one job, so no+ # earliest-value backscroll is needed. The other endpoints are full refresh, where+ # ordering doesn't affect correctness.+ sort_mode="desc" if endpoint == "audit_logs" else "asc",+ partition_count=1,+ partition_size=1,+ partition_mode="datetime" if endpoint_config.partition_key else None,+ partition_format="week" if endpoint_config.partition_key else None,+ partition_keys=[endpoint_config.partition_key] if endpoint_config.partition_key else None,+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/infisical/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/infisical/settings.pynew file mode 100644index 000000000000..2c64104047c9--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/infisical/settings.py@@ -0,0 +1,80 @@+from dataclasses import dataclass, field++from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType+++@dataclass+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+ incremental_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"+ # Whether the endpoint supports `offset`/`limit` pagination. Unpaginated endpoints+ # return the full list in one response.+ paginated: bool = False+ page_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+++INFISICAL_ENDPOINTS: dict[str, InfisicalEndpointConfig] = {+ # Audit log rows are immutable and the endpoint takes server-side startDate/endDate+ # filters, so createdAt is a true incremental cursor. Retention on Infisical Cloud is+ # plan-based, which bounds the first sync's history.+ "audit_logs": InfisicalEndpointConfig(+ name="audit_logs",+ path="/api/v1/organization/audit-logs",+ data_key="auditLogs",+ incremental_fields=[+ {+ "label": "createdAt",+ "type": IncrementalFieldType.DateTime,+ "field": "createdAt",+ "field_type": IncrementalFieldType.DateTime,+ },+ ],+ partition_key="createdAt",+ paginated=True,+ page_limit=1000, # documented maximum+ ),+ # Small dimension tables. None of these expose a server-side updated-since filter,+ # so they are full refresh only.+ "projects": InfisicalEndpointConfig(+ name="projects",+ path="/api/v1/projects",+ data_key="projects",+ ),+ "identities": InfisicalEndpointConfig(+ name="identities",+ path="/api/v2/organizations/{organization_id}/identity-memberships",+ data_key="identityMemberships",+ paginated=True,+ page_limit=500,+ # Explicit stable sort so page boundaries don't shift mid-sync.+ extra_params={"orderBy": "name", "orderDirection": "asc"},+ ),+ "organization_memberships": InfisicalEndpointConfig(+ name="organization_memberships",+ path="/api/v2/organizations/{organization_id}/memberships",+ data_key="users",+ ),+ "project_memberships": InfisicalEndpointConfig(+ name="project_memberships",+ path="/api/v1/projects/{project_id}/memberships",+ data_key="memberships",+ fan_out_over_projects=True,+ ),+}++ENDPOINTS = tuple(INFISICAL_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in INFISICAL_ENDPOINTS.items()+}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 54399250954b..1748959fdead 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@@ -1,31 +1,185 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (+ SourceInputs,+ SourceResponse,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchemafrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import InfisicalSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.infisical.infisical import (+ HOST_NOT_ALLOWED_ERROR,+ INVALID_CREDENTIALS_ERROR,+ InfisicalResumeConfig,+ infisical_source,+ validate_credentials as validate_infisical_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.infisical.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class InfisicalSource(SimpleSource[InfisicalSourceConfig]):+class InfisicalSource(ResumableSource[InfisicalSourceConfig, InfisicalResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.INFISICAL+ @property+ def connection_host_fields(self) -> list[str]:+ # `base_url` is where the stored client secret is sent, and `organization_id` selects+ # which org the credential is used against. Retargeting either must re-require the+ # credentials so an editor who can't see the stored secret can't repoint it at a+ # different host or org the machine identity can also reach.+ return ["base_url", "organization_id"]+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.INFISICAL,category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,label="Infisical",- iconPath="/static/services/infisical.png",+ 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.++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.++- **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.+- **Client ID / Client secret**: from the identity's Universal Auth configuration.+""",+ iconPath="/static/services/infisical.svg",+ docsUrl="https://posthog.com/docs/cdp/sources/infisical",keywords=["secrets", "security", "audit", "devops"],- fields=cast(list[FieldType], []),- unreleasedSource=True,+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="base_url",+ label="Base URL",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="https://app.infisical.com",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="organization_id",+ label="Organization ID",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="00000000-0000-0000-0000-000000000000",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="client_id",+ label="Client ID",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="client_secret",+ label="Client secret",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ ],+ ),+ )++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ INVALID_CREDENTIALS_ERROR: "Your Infisical machine identity credentials are invalid or have been revoked. Update the client ID and client secret, then try again.",+ "401 Client Error": "Your Infisical machine identity credentials were rejected. Update the client ID and client secret, then try again.",+ "403 Client Error": "Your Infisical machine identity lacks the required permissions. Grant it read access to the data you want to sync, then try again.",+ HOST_NOT_ALLOWED_ERROR: "The Infisical base URL is not allowed. Use your Infisical Cloud or self-hosted instance URL.",+ }++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.infisical.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_schemas(+ self,+ config: InfisicalSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ schemas = [+ SourceSchema(+ name=endpoint,+ supports_incremental=bool(INCREMENTAL_FIELDS.get(endpoint)),+ supports_append=bool(INCREMENTAL_FIELDS.get(endpoint)),+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),+ description="The first sync fetches your plan's full retained history"+ if endpoint == "audit_logs"+ else None,+ )+ for endpoint in ENDPOINTS+ ]+ if names is not None:+ names_set = set(names)+ schemas = [s for s in schemas if s.name in names_set]+ return schemas++ def validate_credentials(+ self, config: InfisicalSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ return validate_infisical_credentials(+ config.base_url,+ config.client_id,+ config.client_secret,+ config.organization_id,+ schema_name,+ team_id,+ )++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[InfisicalResumeConfig]:+ return ResumableSourceManager[InfisicalResumeConfig](inputs, InfisicalResumeConfig)++ def source_for_pipeline(+ self,+ config: InfisicalSourceConfig,+ resumable_source_manager: ResumableSourceManager[InfisicalResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return infisical_source(+ base_url=config.base_url,+ client_id=config.client_id,+ client_secret=config.client_secret,+ organization_id=config.organization_id,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,+ team_id=inputs.team_id,+ should_use_incremental_field=inputs.should_use_incremental_field,+ db_incremental_field_last_value=inputs.db_incremental_field_last_value+ if inputs.should_use_incremental_field+ else None,)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.pynew file mode 100644index 000000000000..a43bdf0273be--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/infisical/tests/test_infisical.py@@ -0,0 +1,729 @@+import time+import socket+import itertools+import threading+from datetime import UTC, date, datetime+from typing import Any, Optional+from urllib.parse import parse_qs, urlparse++import pytest+from unittest import mock++import requests++from products.warehouse_sources.backend.temporal.data_imports.sources.infisical import infisical as infisical_module+from products.warehouse_sources.backend.temporal.data_imports.sources.infisical.infisical import (+ INVALID_CREDENTIALS_ERROR,+ InfisicalAuthError,+ InfisicalFanOutBudgetExceededError,+ InfisicalPaginationBudgetExceededError,+ InfisicalResponseTooLargeError,+ InfisicalResumeConfig,+ _format_incremental_value,+ _get_audit_log_rows,+ _get_offset_paginated_rows,+ _get_project_fan_out_rows,+ _parse_retry_after,+ _retry_wait,+ get_rows,+ infisical_source,+ normalize_base_url,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.infisical.settings import INFISICAL_ENDPOINTS++LOGIN_JSON = {"accessToken": "tok", "expiresIn": 3600, "accessTokenMaxTTL": 7200, "tokenType": "Bearer"}+++def _response(+ *, status_code: int = 200, json_data: Any = None, text: str = "", body_chunks: Optional[list[bytes]] = None+) -> mock.MagicMock:+ response = mock.MagicMock(spec=requests.Response)+ response.status_code = status_code+ response.ok = 200 <= status_code < 400+ response.is_redirect = status_code in (302, 303, 307)+ response.is_permanent_redirect = status_code in (301, 308)+ response.text = text+ response.headers = {}+ response.json.return_value = json_data+ # _send streams the body and drains it with single reads (read1), so the response's raw+ # stream must hand back the chunks then an empty read to signal EOF.+ chunks = body_chunks if body_chunks is not None else [text.encode("utf-8")]+ response.raw = mock.MagicMock()+ response.raw.read1.side_effect = [*chunks, b""]+ if status_code >= 400:+ response.raise_for_status.side_effect = requests.HTTPError(f"{status_code} Client Error", response=response)+ return response+++def _login_response() -> mock.MagicMock:+ return _response(json_data=LOGIN_JSON)+++def _run_get_rows(+ responses: list[Any],+ endpoint: str,+ manager: Optional[mock.MagicMock] = None,+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+) -> tuple[list[dict[str, Any]], mock.MagicMock, mock.MagicMock]:+ if manager is None:+ manager = mock.MagicMock()+ manager.can_resume.return_value = False+ session = mock.MagicMock()+ session.request.side_effect = responses+ with (+ mock.patch.object(infisical_module, "make_tracked_session", return_value=session),+ mock.patch.object(infisical_module, "_is_host_safe", return_value=(True, None)),+ ):+ rows: list[dict[str, Any]] = []+ for batch in get_rows(+ base_url="https://app.infisical.com",+ client_id="cid",+ client_secret="csecret",+ organization_id="org-123",+ endpoint=endpoint,+ logger=mock.MagicMock(),+ resumable_source_manager=manager,+ team_id=1,+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=db_incremental_field_last_value,+ ):+ rows.extend(batch)+ return rows, session, manager+++def _get_urls(session: mock.MagicMock) -> list[str]:+ return [call.args[1] for call in session.request.call_args_list if call.args[0] == "get"]+++def _query(url: str) -> dict[str, list[str]]:+ return parse_qs(urlparse(url).query)+++class TestNormalizeBaseUrl:+ @pytest.mark.parametrize(+ "raw, expected",+ [+ ("app.infisical.com", "https://app.infisical.com"),+ ("https://eu.infisical.com/", "https://eu.infisical.com"),+ (" https://app.infisical.com/api/v1 ", "https://app.infisical.com"),+ ("http://secrets.example.com:8443/some/path", "https://secrets.example.com:8443"),+ ("HTTPS://Secrets.Example.COM", "https://secrets.example.com"),+ ],+ )+ def test_normalizes(self, raw, expected):+ assert normalize_base_url(raw) == expected++ @pytest.mark.parametrize("bad", ["", "https://", "not a url!", "https://bad_host/"])+ def test_rejects_invalid(self, bad):+ with pytest.raises(ValueError):+ normalize_base_url(bad)+++class TestFormatIncrementalValue:+ @pytest.mark.parametrize(+ "value, expected",+ [+ (datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC), "2026-03-04T02:58:14.000Z"),+ (datetime(2026, 3, 4, 2, 58, 14), "2026-03-04T02:58:14.000Z"),+ (date(2026, 3, 4), "2026-03-04T00:00:00.000Z"),+ ("already-a-cursor", "already-a-cursor"),+ ],+ )+ def test_format(self, value, expected):+ assert _format_incremental_value(value) == expected+++class TestAuditLogRows:+ def test_incremental_run_windows_and_paginates(self):+ audit_config = INFISICAL_ENDPOINTS["audit_logs"]+ page1 = _response(json_data={"auditLogs": [{"id": i, "orgId": "org-123"} for i in ("3", "2", "1")]})+ page2 = _response(json_data={"auditLogs": [{"id": "0", "orgId": "org-123"}]})+ with mock.patch.object(audit_config, "page_limit", 3):+ rows, session, manager = _run_get_rows(+ [_login_response(), page1, page2],+ "audit_logs",+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2024, 1, 1, tzinfo=UTC),+ )++ assert [r["id"] for r in rows] == ["3", "2", "1", "0"]++ first, second = (_query(u) for u in _get_urls(session))+ assert first["startDate"] == ["2024-01-01T00:00:00.000Z"]+ assert first["offset"] == ["0"]+ assert second["offset"] == ["3"]+ # endDate is pinned at sync start so offset pagination stays stable while new logs arrive.+ assert first["endDate"] == second["endDate"]+ # A short page terminates pagination.+ assert len(_get_urls(session)) == 2++ saved_offsets = [call.args[0].offset for call in manager.save_state.call_args_list]+ assert saved_offsets == [3, 4]++ def test_full_refresh_has_no_start_date(self):+ page = _response(json_data={"auditLogs": [{"id": "1", "orgId": "org-123"}]})+ _rows, session, _manager = _run_get_rows([_login_response(), page], "audit_logs")++ params = _query(_get_urls(session)[0])+ assert "startDate" not in params+ assert "endDate" in params++ def test_resumes_saved_window_and_offset(self):+ manager = mock.MagicMock()+ manager.can_resume.return_value = True+ manager.load_state.return_value = InfisicalResumeConfig(+ offset=7, window_start="2024-01-01T00:00:00.000Z", window_end="2024-06-01T00:00:00.000Z"+ )+ page = _response(json_data={"auditLogs": [{"id": "1", "orgId": "org-123"}]})+ _rows, session, _manager = _run_get_rows([_login_response(), page], "audit_logs", manager=manager)++ params = _query(_get_urls(session)[0])+ assert params["offset"] == ["7"]+ assert params["startDate"] == ["2024-01-01T00:00:00.000Z"]+ assert params["endDate"] == ["2024-06-01T00:00:00.000Z"]++ def test_empty_first_page_yields_nothing(self):+ page = _response(json_data={"auditLogs": []})+ rows, _session, manager = _run_get_rows([_login_response(), page], "audit_logs")++ assert rows == []+ manager.save_state.assert_not_called()++ def test_drops_rows_from_other_orgs(self):+ # The audit-log endpoint is scoped by the token's org, not a path param, so an identity+ # with access to more than one org could receive another org's events. Defense in depth:+ # rows whose orgId isn't the configured org are dropped, but pagination still advances by+ # the raw page size so the server offset stays correct.+ audit_config = INFISICAL_ENDPOINTS["audit_logs"]+ page1 = _response(+ json_data={+ "auditLogs": [+ {"id": "a", "orgId": "org-123"},+ {"id": "b", "orgId": "other-org"},+ {"id": "c", "orgId": "org-123"},+ ]+ }+ )+ page2 = _response(json_data={"auditLogs": [{"id": "d", "orgId": "org-123"}]})+ with mock.patch.object(audit_config, "page_limit", 3):+ rows, session, manager = _run_get_rows([_login_response(), page1, page2], "audit_logs")++ assert [r["id"] for r in rows] == ["a", "c", "d"]+ # Offset advances by the raw (unfiltered) page size, so the second page is requested at 3.+ assert _query(_get_urls(session)[1])["offset"] == ["3"]+ assert [call.args[0].offset for call in manager.save_state.call_args_list] == [3, 4]+++class TestOffsetPaginatedRows:+ def test_identities_paginates_with_stable_sort(self):+ identities_config = INFISICAL_ENDPOINTS["identities"]+ page1 = _response(json_data={"identityMemberships": [{"id": "a"}, {"id": "b"}]})+ page2 = _response(json_data={"identityMemberships": [{"id": "c"}]})+ with mock.patch.object(identities_config, "page_limit", 2):+ rows, session, manager = _run_get_rows([_login_response(), page1, page2], "identities")++ assert [r["id"] for r in rows] == ["a", "b", "c"]++ urls = _get_urls(session)+ assert all("/api/v2/organizations/org-123/identity-memberships" in u for u in urls)+ first, second = (_query(u) for u in urls)+ assert first["orderBy"] == ["name"]+ assert first["orderDirection"] == ["asc"]+ assert first["offset"] == ["0"]+ assert second["offset"] == ["2"]+ assert [call.args[0].offset for call in manager.save_state.call_args_list] == [2, 3]+++class TestUnpaginatedRows:+ @pytest.mark.parametrize(+ "endpoint, path, data_key",+ [+ ("projects", "/api/v1/projects", "projects"),+ ("organization_memberships", "/api/v2/organizations/org-123/memberships", "users"),+ ],+ )+ def test_single_request_list(self, endpoint, path, data_key):+ page = _response(json_data={data_key: [{"id": "1", "orgId": "org-123"}, {"id": "2", "orgId": "org-123"}]})+ rows, session, _manager = _run_get_rows([_login_response(), page], endpoint)++ assert [r["id"] for r in rows] == ["1", "2"]+ urls = _get_urls(session)+ assert len(urls) == 1+ assert urlparse(urls[0]).path == path+++class TestProjectMembershipsFanOut:+ def test_fans_out_over_projects_and_skips_forbidden(self):+ projects = _response(+ json_data={+ "projects": [+ {"id": "p1", "orgId": "org-123"},+ {"id": "p2", "orgId": "org-123"},+ {"id": "p3", "orgId": "org-123"},+ ]+ }+ )+ memberships_p1 = _response(json_data={"memberships": [{"id": "m1", "projectId": "p1"}]})+ memberships_p2 = _response(status_code=403)+ memberships_p3 = _response(json_data={"memberships": [{"id": "m2", "projectId": "p3"}]})+ rows, session, _manager = _run_get_rows(+ [_login_response(), projects, memberships_p1, memberships_p2, memberships_p3],+ "project_memberships",+ )++ # The 403 project is skipped (per-project grants), the rest still sync.+ assert [r["id"] for r in rows] == ["m1", "m2"]+ paths = [urlparse(u).path for u in _get_urls(session)]+ assert paths == [+ "/api/v1/projects",+ "/api/v1/projects/p1/memberships",+ "/api/v1/projects/p2/memberships",+ "/api/v1/projects/p3/memberships",+ ]++ def test_non_permission_error_fails_the_sync(self):+ projects = _response(json_data={"projects": [{"id": "p1", "orgId": "org-123"}]})+ bad_request = _response(status_code=400)+ with pytest.raises(requests.HTTPError):+ _run_get_rows([_login_response(), projects, bad_request], "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.+ 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):+ _rows, session, _manager = _run_get_rows(+ [_login_response(), projects, membership, membership], "project_memberships"+ )++ # Only the first 2 of the 3 projects are fetched (1 project list + 2 membership calls).+ membership_paths = [p for p in (urlparse(u).path for u in _get_urls(session)) if "memberships" in p]+ assert membership_paths == ["/api/v1/projects/p0/memberships", "/api/v1/projects/p1/memberships"]++ def test_fan_out_aborts_when_time_budget_exhausted(self):+ # The project-count cap doesn't bound how long each membership response takes: a hostile+ # host can stay under the cap yet drain every response's full deadline, holding the worker+ # for weeks. The wall-clock fan-out budget must abort the sync — not truncate — once spent.+ config = INFISICAL_ENDPOINTS["project_memberships"]+ client = mock.MagicMock()+ projects = _response(json_data={"projects": [{"id": f"p{i}", "orgId": "org-123"} for i in range(5)]})+ membership = _response(json_data={"memberships": [{"id": "m", "projectId": "p"}]})+ client.get.side_effect = [projects, *([membership] * 5)]++ # A clock that jumps one per-response deadline on every check, so a two-response budget is+ # spent after the first couple of projects — simulating each response draining its deadline.+ clock = itertools.count(0, infisical_module.MAX_RESPONSE_SECONDS)+ with (+ mock.patch.object(infisical_module, "MAX_FAN_OUT_SECONDS", infisical_module.MAX_RESPONSE_SECONDS * 2),+ 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()))++ # 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 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+ # leak project and membership data from orgs other than the configured one.+ def test_projects_table_excludes_other_orgs(self):+ page = _response(json_data={"projects": [{"id": "p1", "orgId": "org-123"}, {"id": "p2", "orgId": "other-org"}]})+ rows, _session, _manager = _run_get_rows([_login_response(), page], "projects")+ assert [r["id"] for r in rows] == ["p1"]++ 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"}]}+ )+ memberships_p1 = _response(json_data={"memberships": [{"id": "m1", "projectId": "p1"}]})+ rows, session, _manager = _run_get_rows([_login_response(), projects, memberships_p1], "project_memberships")+ assert [r["id"] for r in rows] == ["m1"]+ # Only the configured org's project is ever fetched; the foreign project is skipped.+ paths = [urlparse(u).path for u in _get_urls(session)]+ assert paths == ["/api/v1/projects", "/api/v1/projects/p1/memberships"]+++class TestTokenHandling:+ def test_logs_in_once_across_pages(self):+ page1 = _response(json_data={"auditLogs": [{"id": "1"}]})+ _rows, session, _manager = _run_get_rows([_login_response(), page1], "audit_logs")++ logins = [call for call in session.request.call_args_list if call.args[0] == "post"]+ assert len(logins) == 1+ assert logins[0].args[1] == "https://app.infisical.com/api/v1/auth/universal-auth/login"+ assert logins[0].kwargs["json"] == {"clientId": "cid", "clientSecret": "csecret"}++ def test_relogins_once_when_token_rejected_mid_sync(self):+ rejected = _response(status_code=401)+ page = _response(json_data={"projects": [{"id": "1", "orgId": "org-123"}]})+ rows, session, _manager = _run_get_rows([_login_response(), rejected, _login_response(), page], "projects")++ assert [r["id"] for r in rows] == ["1"]+ logins = [call for call in session.request.call_args_list if call.args[0] == "post"]+ assert len(logins) == 2++ def test_both_sessions_disable_sample_capture(self):+ # Sample capture reads response.text inside the adapter before _send's size cap runs,+ # so both sessions must ride capture-disabled adapters to keep an unbounded body from+ # a customer-controlled host out of memory. The auth body additionally carries the+ # client secret and minted accessToken in camelCase fields the name-based scrubbers+ # don't recognise. The secret is value-redacted on every session.+ data_session, auth_session = mock.MagicMock(), mock.MagicMock()+ auth_session.request.side_effect = [_login_response()]+ data_session.request.side_effect = [_response(json_data={"projects": [{"id": "1", "orgId": "org-123"}]})]+ factory = mock.MagicMock(side_effect=[data_session, auth_session])+ with (+ mock.patch.object(infisical_module, "make_tracked_session", factory),+ mock.patch.object(infisical_module, "_is_host_safe", return_value=(True, None)),+ ):+ rows = [+ row+ for batch in get_rows(+ base_url="https://app.infisical.com",+ client_id="cid",+ client_secret="csecret",+ organization_id="org-123",+ endpoint="projects",+ logger=mock.MagicMock(),+ resumable_source_manager=mock.MagicMock(),+ team_id=1,+ )+ for row in batch+ ]++ assert rows == [{"id": "1", "orgId": "org-123"}]+ data_session_kwargs, auth_session_kwargs = (call.kwargs for call in factory.call_args_list)+ assert data_session_kwargs["capture"] is False+ assert auth_session_kwargs["capture"] is False+ assert "csecret" in auth_session_kwargs["redact_values"]+ assert "csecret" in data_session_kwargs["redact_values"]+ # Only the login POST goes through the capture-disabled session.+ assert [call.args[0] for call in auth_session.request.call_args_list] == ["post"]+ assert [call.args[0] for call in data_session.request.call_args_list] == ["get"]++ def test_requests_never_follow_redirects(self):+ page = _response(json_data={"projects": [{"id": "1"}]})+ _rows, session, _manager = _run_get_rows([_login_response(), page], "projects")++ assert all(call.kwargs["allow_redirects"] is False for call in session.request.call_args_list)++ def test_rejects_unsafe_host_before_any_request(self):+ session = mock.MagicMock()+ with (+ mock.patch.object(infisical_module, "make_tracked_session", return_value=session),+ mock.patch.object(infisical_module, "_is_host_safe", return_value=(False, "internal address")),+ ):+ with pytest.raises(infisical_module.InfisicalHostNotAllowedError):+ list(+ get_rows(+ base_url="https://10.0.0.1",+ client_id="cid",+ client_secret="csecret",+ organization_id="org-123",+ endpoint="projects",+ logger=mock.MagicMock(),+ resumable_source_manager=mock.MagicMock(),+ team_id=1,+ )+ )+ session.request.assert_not_called()+++class TestResponseLimits:+ def test_oversized_response_is_rejected(self):+ # base_url is customer-controlled, so an unbounded body must abort rather than buffer+ # into memory and exhaust the worker.+ oversized = _response(json_data={"projects": []}, body_chunks=[b"x" * 2048])+ with mock.patch.object(infisical_module, "MAX_RESPONSE_BYTES", 1024):+ with pytest.raises(InfisicalResponseTooLargeError):+ _run_get_rows([_login_response(), oversized], "projects")++ def test_slow_drip_body_aborts_on_total_deadline(self):+ # requests' timeout is an idle read timeout: a host that trickles bytes under the size+ # cap without ever idling long enough to trip it would otherwise hold the worker until+ # the activity's week-long timeout. The total-transfer deadline must abort it. Draining+ # via single reads (read1) means the deadline is checked before every read, so a host+ # dripping one byte per read can't stall inside a single read to dodge it. A monotonic+ # clock that advances one second per read crosses the (patched) 1s deadline within the+ # loop regardless of any monotonic() calls tenacity makes around it.+ response = mock.MagicMock(spec=requests.Response)+ response.raw = mock.MagicMock()+ response.raw.read1.side_effect = [b"x", b"y", b"z", b""]+ clock = itertools.count()+ with (+ mock.patch.object(infisical_module, "MAX_RESPONSE_SECONDS", 1),+ mock.patch.object(infisical_module.time, "monotonic", lambda: float(next(clock))),+ ):+ with pytest.raises(InfisicalResponseTooLargeError):+ infisical_module._read_capped_body(response)+ response.close.assert_called_once()++ def test_watchdog_shuts_socket_down_when_read_blocks_past_deadline(self):+ # read1 keeps the deadline enforceable between reads, but a chunked body falls through+ # to readline() while parsing the chunk-size line, which loops until CRLF — a host+ # dripping an unterminated size line stays inside one read past the deadline, so the+ # between-reads check never fires. The socket-level watchdog must shut the connection+ # down to force that read to return and abort. Firing the timer synchronously simulates+ # the deadline elapsing while a read is in flight.+ response = mock.MagicMock()++ class _ImmediateTimer:+ def __init__(self, interval, function, args=(), kwargs=None):+ self._function = function+ self._args = args++ def start(self):+ self._function(*self._args)++ def cancel(self):+ pass++ with mock.patch.object(infisical_module.threading, "Timer", _ImmediateTimer):+ with pytest.raises(InfisicalResponseTooLargeError):+ infisical_module._read_capped_body(response)+ response.raw._connection.sock.shutdown.assert_called_once()+ response.close.assert_called()++ def test_chunked_size_line_drip_aborts_as_deadline_error(self):+ # End-to-end over a real socket: a chunked host drips an unterminated chunk-size line,+ # so read1 blocks inside the stdlib readline() past the deadline. The watchdog shutting+ # the socket down unblocks that read, and whatever error the interrupted/closed read+ # raises must surface as InfisicalResponseTooLargeError — not a raw socket/attribute+ # error. The synchronous-timer test above can't reach this: it fires before any read,+ # so it never exercises the interrupted-read translation path. Aborting near the+ # (patched) deadline rather than when the drip ends proves the watchdog fired.+ server = socket.socket()+ server.bind(("127.0.0.1", 0))+ server.listen(1)+ port = server.getsockname()[1]+ stop = threading.Event()++ def drip() -> None:+ conn, _ = server.accept()+ conn.recv(65536)+ conn.sendall(b"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n")+ # Digits with no CRLF, so readline never completes the chunk-size line. Bounded so a+ # broken watchdog fails the timing assertion instead of hanging the suite.+ for _ in range(250):+ if stop.is_set():+ break+ try:+ conn.sendall(b"1")+ except OSError:+ break+ stop.wait(0.02)+ conn.close()++ thread = threading.Thread(target=drip, daemon=True)+ thread.start()+ try:+ response = requests.get(f"http://127.0.0.1:{port}/", stream=True, timeout=30)+ started = time.monotonic()+ with mock.patch.object(infisical_module, "MAX_RESPONSE_SECONDS", 1.0):+ with pytest.raises(InfisicalResponseTooLargeError):+ infisical_module._read_capped_body(response)+ assert time.monotonic() - started < 3.0+ finally:+ stop.set()+ server.close()+ thread.join(timeout=5)++ def test_pagination_stops_at_max_pages(self):+ # A host that always returns a full page would loop forever without the page cap.+ identities_config = INFISICAL_ENDPOINTS["identities"]+ full1 = _response(json_data={"identityMemberships": [{"id": "a"}]})+ full2 = _response(json_data={"identityMemberships": [{"id": "b"}]})+ with (+ mock.patch.object(identities_config, "page_limit", 1),+ mock.patch.object(infisical_module, "MAX_PAGES", 2),+ ):+ rows, session, _manager = _run_get_rows([_login_response(), full1, full2], "identities")++ assert [r["id"] for r in rows] == ["a", "b"]+ assert len(_get_urls(session)) == 2++ @pytest.mark.parametrize(+ "endpoint, run_loop",+ [+ (+ "identities",+ lambda client, config, manager: _get_offset_paginated_rows(+ client, config, "org-123", manager, mock.MagicMock()+ ),+ ),+ (+ "audit_logs",+ lambda client, config, manager: _get_audit_log_rows(+ client, config, "org-123", mock.MagicMock(), manager, False, None+ ),+ ),+ ],+ )+ def test_pagination_aborts_when_time_budget_exhausted(self, endpoint, run_loop):+ # MAX_PAGES bounds page count, not per-page time: a hostile host can return a full page that+ # drains its whole response deadline on every one of MAX_PAGES pages, holding the worker for+ # ~a year. The wall-clock pagination budget must abort the sync — not silently truncate —+ # once spent.+ config = INFISICAL_ENDPOINTS[endpoint]+ client = mock.MagicMock()+ full_page = _response(json_data={config.data_key: [{"id": f"r{i}"} for i in range(config.page_limit)]})+ client.get.return_value = full_page+ manager = mock.MagicMock()+ manager.can_resume.return_value = False++ # A clock that jumps one per-response deadline on every check, so a two-response budget is+ # spent after the first couple of pages — simulating each page draining its full deadline.+ clock = itertools.count(0, infisical_module.MAX_RESPONSE_SECONDS)+ with (+ mock.patch.object(infisical_module, "MAX_PAGINATION_SECONDS", infisical_module.MAX_RESPONSE_SECONDS * 2),+ mock.patch.object(infisical_module.time, "monotonic", lambda: next(clock)),+ pytest.raises(InfisicalPaginationBudgetExceededError),+ ):+ list(run_loop(client, config, manager))++ # Aborted mid-pagination rather than running all the way to MAX_PAGES.+ assert 0 < client.get.call_count < infisical_module.MAX_PAGES+++class TestValidateCredentials:+ def _run(self, responses: list[Any], schema_name: Optional[str] = None, **kwargs: Any):+ session = mock.MagicMock()+ session.request.side_effect = responses+ with (+ mock.patch.object(infisical_module, "make_tracked_session", return_value=session),+ mock.patch.object(infisical_module, "_is_host_safe", return_value=(True, None)),+ ):+ return (+ validate_credentials(+ kwargs.pop("base_url", "https://app.infisical.com"),+ "cid",+ "csecret",+ kwargs.pop("organization_id", "org-123"),+ schema_name,+ team_id=kwargs.pop("team_id", 1),+ ),+ session,+ )++ def test_login_success_at_source_create(self):+ result, session = self._run([_login_response()])+ assert result == (True, None)+ # Only the login probe — per-endpoint permissions are granted separately.+ assert session.request.call_count == 1++ @pytest.mark.parametrize("status_code", [400, 401, 403])+ def test_login_rejection_is_invalid_credentials(self, status_code):+ result, _session = self._run([_response(status_code=status_code)])+ assert result == (False, INVALID_CREDENTIALS_ERROR)++ def test_scoped_probe_success(self):+ result, session = self._run(+ [_login_response(), _response(json_data={"auditLogs": []})], schema_name="audit_logs"+ )+ assert result == (True, None)+ assert "/api/v1/organization/audit-logs" in _get_urls(session)[0]++ def test_scoped_probe_403_names_the_table(self):+ result, _session = self._run([_login_response(), _response(status_code=403)], schema_name="audit_logs")+ valid, message = result+ assert valid is False+ assert "audit_logs" in (message or "")++ def test_invalid_base_url_short_circuits(self):+ result, session = self._run([], base_url="not a url!")+ assert result == (False, "Invalid Infisical base URL")+ session.request.assert_not_called()++ def test_invalid_organization_id_short_circuits(self):+ result, session = self._run([], organization_id="../../etc/passwd")+ assert result == (False, "Invalid Infisical organization ID")+ session.request.assert_not_called()++ def test_blocks_unsafe_host(self):+ session = mock.MagicMock()+ with (+ mock.patch.object(infisical_module, "make_tracked_session", return_value=session),+ mock.patch.object(infisical_module, "_is_host_safe", return_value=(False, "internal address")),+ ):+ result = validate_credentials("https://10.0.0.1", "cid", "csecret", "org-123", None, team_id=99)+ assert result == (False, "internal address")+ session.request.assert_not_called()++ def test_redirecting_host_is_rejected(self):+ # A validated host that 3xx-redirects (potentially to an internal address) must be+ # rejected, not followed (SSRF).+ result, _session = self._run([_response(status_code=302)])+ assert result == (False, infisical_module.HOST_NOT_ALLOWED_ERROR)++ def test_request_exception_returns_failure(self):+ result, _session = self._run([requests.exceptions.RequestException("boom")])+ valid, message = result+ assert valid is False+ assert "boom" in (message or "")+++class TestInfisicalSourceResponse:+ @pytest.mark.parametrize(+ "endpoint, sort_mode, partition_key",+ [+ ("audit_logs", "desc", "createdAt"),+ ("projects", "asc", None),+ ("identities", "asc", None),+ ("organization_memberships", "asc", None),+ ("project_memberships", "asc", None),+ ],+ )+ def test_response_shape(self, endpoint, sort_mode, partition_key):+ response = infisical_source(+ base_url="https://app.infisical.com",+ client_id="cid",+ client_secret="csecret",+ organization_id="org-123",+ endpoint=endpoint,+ logger=mock.MagicMock(),+ resumable_source_manager=mock.MagicMock(),+ team_id=1,+ )+ assert response.name == endpoint+ assert response.primary_keys == ["id"]+ assert response.sort_mode == sort_mode+ if partition_key:+ assert response.partition_keys == [partition_key]+ assert response.partition_mode == "datetime"+ else:+ assert response.partition_keys is None+ assert response.partition_mode is None+++class TestRetryAfter:+ @pytest.mark.parametrize(+ "headers, expected",+ [+ ({"Retry-After": "5"}, 5.0),+ ({"Retry-After": "100000"}, 60.0), # capped+ ({"Retry-After": "Wed, 21 Oct 2026 07:28:00 GMT"}, None), # HTTP-date ignored+ ({}, None),+ ],+ )+ def test_parse_retry_after(self, headers, expected):+ response = mock.MagicMock()+ response.headers = headers+ assert _parse_retry_after(response) == expected++ def test_retry_wait_prefers_retry_after(self):+ state = mock.MagicMock()+ state.outcome.exception.return_value = infisical_module.InfisicalRetryableError("rate limited", retry_after=7.0)+ assert _retry_wait(state) == 7.0+++class TestAuthErrors:+ def test_login_failure_raises_auth_error_from_get_rows(self):+ with pytest.raises(InfisicalAuthError):+ _run_get_rows([_response(status_code=401)], "projects")diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/infisical/tests/test_infisical_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/infisical/tests/test_infisical_source.pynew file mode 100644index 000000000000..1a58d8c00888--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/infisical/tests/test_infisical_source.py@@ -0,0 +1,152 @@+import pytest+from unittest import mock++from posthog.schema import (+ DataWarehouseSourceCategory,+ ReleaseStatus,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,+)++from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import InfisicalSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.infisical.infisical import InfisicalResumeConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.infisical.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.infisical.source import InfisicalSource+from products.warehouse_sources.backend.types import ExternalDataSourceType+++class TestInfisicalSource:+ def setup_method(self):+ self.source = InfisicalSource()+ self.team_id = 123+ self.config = InfisicalSourceConfig(+ base_url="https://app.infisical.com",+ organization_id="org-123",+ client_id="cid",+ client_secret="csecret",+ )++ def test_source_type(self):+ assert self.source.source_type == ExternalDataSourceType.INFISICAL++ def test_get_source_config(self):+ config = self.source.get_source_config++ assert config.name.value == "Infisical"+ assert config.label == "Infisical"+ assert config.category == DataWarehouseSourceCategory.ENGINEERING___MONITORING+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.iconPath == "/static/services/infisical.svg"+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/infisical"++ field_names = [f.name for f in config.fields]+ assert field_names == ["base_url", "organization_id", "client_id", "client_secret"]++ secret_field = config.fields[-1]+ assert isinstance(secret_field, SourceFieldInputConfig)+ assert secret_field.type == SourceFieldInputConfigType.PASSWORD+ assert secret_field.secret is True+ assert all(+ isinstance(f, SourceFieldInputConfig) and f.secret is False and f.required is True+ for f in config.fields[:-1]+ )++ def test_connection_host_fields_require_credential_reentry(self):+ # Both the host and the org selector gate the stored credential: changing either must+ # force re-entry so an editor who can't read the secret can't repoint it.+ assert self.source.connection_host_fields == ["base_url", "organization_id"]++ @pytest.mark.parametrize(+ "expected_key",+ [+ "401 Client Error",+ "403 Client Error",+ "Invalid Infisical machine identity credentials",+ "Infisical host is not allowed",+ ],+ )+ def test_non_retryable_errors(self, expected_key):+ assert expected_key in self.source.get_non_retryable_errors()++ def test_get_schemas_returns_all_endpoints(self):+ schemas = self.source.get_schemas(self.config, self.team_id)+ assert {s.name for s in schemas} == set(ENDPOINTS)++ @pytest.mark.parametrize(+ "endpoint, incremental",+ [+ ("audit_logs", True),+ ("projects", False),+ ("identities", False),+ ("organization_memberships", False),+ ("project_memberships", False),+ ],+ )+ def test_schema_incremental_support(self, endpoint, incremental):+ schemas = {s.name: s for s in self.source.get_schemas(self.config, self.team_id)}+ assert schemas[endpoint].supports_incremental is incremental+ assert schemas[endpoint].supports_append is incremental++ def test_get_schemas_filtered_by_names(self):+ schemas = self.source.get_schemas(self.config, self.team_id, names=["audit_logs"])+ assert [s.name for s in schemas] == ["audit_logs"]+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []++ @pytest.mark.parametrize(+ "mock_return",+ [+ (True, None),+ (False, "Invalid Infisical machine identity credentials"),+ ],+ )+ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.infisical.source.validate_infisical_credentials"+ )+ def test_validate_credentials(self, mock_validate, mock_return):+ mock_validate.return_value = mock_return++ result = self.source.validate_credentials(self.config, self.team_id, schema_name="audit_logs")++ assert result == mock_return+ mock_validate.assert_called_once_with(+ "https://app.infisical.com", "cid", "csecret", "org-123", "audit_logs", 123+ )++ def test_get_resumable_source_manager(self):+ manager = self.source.get_resumable_source_manager(mock.MagicMock())+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is InfisicalResumeConfig++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.infisical.source.infisical_source")+ def test_source_for_pipeline_plumbs_arguments(self, mock_infisical_source):+ inputs = mock.MagicMock()+ inputs.schema_name = "audit_logs"+ inputs.team_id = 42+ inputs.should_use_incremental_field = True+ inputs.db_incremental_field_last_value = "2024-01-01T00:00:00.000Z"+ manager = mock.MagicMock()++ self.source.source_for_pipeline(self.config, manager, inputs)++ kwargs = mock_infisical_source.call_args.kwargs+ assert kwargs["base_url"] == "https://app.infisical.com"+ assert kwargs["client_id"] == "cid"+ assert kwargs["client_secret"] == "csecret"+ assert kwargs["organization_id"] == "org-123"+ assert kwargs["endpoint"] == "audit_logs"+ assert kwargs["resumable_source_manager"] is manager+ assert kwargs["team_id"] == 42+ assert kwargs["should_use_incremental_field"] is True+ assert kwargs["db_incremental_field_last_value"] == "2024-01-01T00:00:00.000Z"++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.infisical.source.infisical_source")+ def test_source_for_pipeline_omits_last_value_when_not_incremental(self, mock_infisical_source):+ inputs = mock.MagicMock()+ inputs.schema_name = "projects"+ inputs.should_use_incremental_field = False+ inputs.db_incremental_field_last_value = "ignored"++ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)++ assert mock_infisical_source.call_args.kwargs["db_incremental_field_last_value"] is None