: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 tailscale import source (#71199)
Tom Owersb6ae060c95bc
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 2145922fa806..cc1af5acae4c 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -464,6 +464,7 @@ the row lists both.| svix | HTTP | requests | ✅ || swarmia | HTTP | requests | ✅ || taboola | HTTP | requests | ✅ |+| tailscale | HTTP | requests | ✅ || tavus | HTTP | requests | ✅ || teamcity | HTTP | requests | ✅ || teamtailor | HTTP | requests | ✅ |@@ -934,7 +935,6 @@ doesn't conflict with concurrent PRs.- swonkie- synthesia- systeme-- tailscale- tawk_to- teachable- tellidiff --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 317a7b06f078..17e2ac88a22b 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@@ -117,6 +117,14 @@ class StripeAuthMethodConfig(config.Config):stripe_secret_key: str | None = None+class TailscaleAuthMethodConfig(config.Config):+ selection: Literal["oauth_client", "api_key"] = "oauth_client"+ client_id: str | None = None+ client_secret: str | None = None+ api_key: str | None = None++@config.configclass TwilioAuthMethodConfig(config.Config):selection: Literal["api_key", "auth_token"] = "api_key"@@ -4198,7 +4206,8 @@ class TaboolaSourceConfig(config.Config):@config.configclass TailscaleSourceConfig(config.Config):- pass+ auth_method: TailscaleAuthMethodConfig+ tailnet: str | None = None@config.configdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/tailscale/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/tailscale/canonical_descriptions.pynew file mode 100644index 000000000000..0badadc1561c--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/tailscale/canonical_descriptions.py@@ -0,0 +1,83 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "devices": {+ "description": "Devices (nodes) in the tailnet, including connectivity details, routes, and key expiry.",+ "docs_url": "https://tailscale.com/api#tag/devices",+ "columns": {+ "id": "The legacy identifier for the device.",+ "nodeId": "The preferred, stable identifier for the device.",+ "name": "The MagicDNS name of the device.",+ "hostname": "The machine name in the admin console.",+ "addresses": "The list of Tailscale IP addresses for the device.",+ "user": "The user who registered the node (for tagged nodes, the tag owner).",+ "os": "The operating system the device is running.",+ "clientVersion": "The version of the Tailscale client software.",+ "created": "The date the device was added to the tailnet; empty for external devices.",+ "lastSeen": "When the device was last active on the tailnet.",+ "expires": "The expiration date of the device's auth key.",+ "keyExpiryDisabled": "Whether the device's key will never expire.",+ "authorized": "Whether the device has been authorized to join the tailnet.",+ "isExternal": "Whether the device is shared into the tailnet rather than a member of it.",+ "machineKey": "For internal use; do not depend on this value.",+ "nodeKey": "The device's public key, mainly used by internal Tailscale systems.",+ "blocksIncomingConnections": "Whether the device is not allowed to accept connections over Tailscale.",+ "updateAvailable": "Whether a Tailscale client version upgrade is available.",+ "enabledRoutes": "The subnet routes for this device that have been approved by an admin.",+ "advertisedRoutes": "The subnet routes this device intends to expose.",+ "clientConnectivity": "The device's connectivity report (endpoints, DERP latency, NAT traversal).",+ "tags": "The ACL tags applied to the device.",+ "tailnetLockKey": "The node's tailnet lock key.",+ "tailnetLockError": "An issue with the tailnet lock node-key signature on this device, if any.",+ },+ },+ "users": {+ "description": "Users of the tailnet, including their role, status, and device count.",+ "docs_url": "https://tailscale.com/api#tag/users",+ "columns": {+ "id": "The unique identifier for the user.",+ "displayName": "The name of the user.",+ "loginName": "The email-like login name of the user.",+ "profilePicUrl": "The profile picture URL for the user.",+ "tailnetId": "The tailnet that owns the user.",+ "created": "The time the user joined their tailnet.",+ "type": "The type of relation this user has to the tailnet (member or shared).",+ "role": "The role of the user (owner, admin, member, and so on).",+ "status": "The status of the user (active, idle, suspended, needs-approval, over-billing-limit).",+ "deviceCount": "Number of devices the user owns.",+ "lastSeen": "The later of either the last login time or the last time a device owned by the user was active.",+ "currentlyConnected": "Whether the user has a device that is currently connected to the control server.",+ },+ },+ "keys": {+ "description": "Active auth keys and API access tokens in the tailnet, with their capabilities and expiry.",+ "docs_url": "https://tailscale.com/api#tag/keys",+ "columns": {+ "id": "The unique identifier for the key.",+ "keyType": "The type of the key (client for auth keys, api for access tokens).",+ "description": "A short string specifying the purpose of the key.",+ "created": "When the key was created.",+ "expires": "When the key expires.",+ "revoked": "When the key was revoked, if it has been.",+ "invalid": "Whether the key is no longer valid (expired or revoked).",+ "capabilities": "The capabilities granted by the key, such as device creation attributes.",+ "userId": "The user who owns the key.",+ },+ },+ "configuration_audit_logs": {+ "description": "Configuration audit log records: who changed what in the tailnet, with old and new values. Tailscale retains the most recent 90 days; syncing to the warehouse preserves them for longer.",+ "docs_url": "https://tailscale.com/api#tag/logging",+ "columns": {+ "eventGroupID": "Identifier shared by all records of a single configuration change event.",+ "action": "The action taken, e.g. CREATE, UPDATE, or DELETE.",+ "actor": "The user, API key, or system component that performed the action.",+ "target": "The object the action was performed on, such as a device or policy file.",+ "old": "The value before the change, for update actions.",+ "new": "The value after the change.",+ "origin": "Where the change originated from.",+ "eventTime": "The time at which the change occurred.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/tailscale/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/tailscale/settings.pynew file mode 100644index 000000000000..3b3bf704bbf9--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/tailscale/settings.py@@ -0,0 +1,76 @@+from dataclasses import dataclass, field+from typing import Optional++from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType++AUDIT_LOGS_ENDPOINT = "configuration_audit_logs"++# Tailscale keeps configuration audit logs for the most recent 90 days only.+AUDIT_LOG_RETENTION_DAYS = 90+# The audit log endpoint has no pagination, so we bound each request with a time window.+# Windows keep single responses small and give the resumable manager a checkpoint boundary.+AUDIT_LOG_WINDOW_DAYS = 7+++@dataclass+class TailscaleEndpointConfig:+ name: str+ # Path relative to https://api.tailscale.com/api/v2, with a `{tailnet}` placeholder.+ path: str+ # Key wrapping the row list in the JSON response (e.g. {"devices": [...]}).+ data_key: str+ primary_key: Optional[str] = "id"+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ # Stable, immutable field to partition by. Only set where rows are immutable or the+ # field never changes after creation.+ partition_key: Optional[str] = None+ params: dict[str, str] = field(default_factory=dict)+++TAILSCALE_ENDPOINTS: dict[str, TailscaleEndpointConfig] = {+ # The Tailscale API does not paginate list endpoints — each returns the full result+ # set in one response — and none of devices/users/keys accept a server-side time+ # filter, so those tables are full refresh only.+ "devices": TailscaleEndpointConfig(+ name="devices",+ path="/tailnet/{tailnet}/devices",+ data_key="devices",+ # Without `fields=all` the API omits detail fields like enabledRoutes,+ # advertisedRoutes and clientConnectivity.+ params={"fields": "all"},+ ),+ "users": TailscaleEndpointConfig(+ name="users",+ path="/tailnet/{tailnet}/users",+ data_key="users",+ ),+ "keys": TailscaleEndpointConfig(+ name="keys",+ path="/tailnet/{tailnet}/keys",+ data_key="keys",+ ),+ AUDIT_LOGS_ENDPOINT: TailscaleEndpointConfig(+ name=AUDIT_LOGS_ENDPOINT,+ path="/tailnet/{tailnet}/logging/configuration",+ data_key="logs",+ # Audit log records carry no unique identifier (eventGroupID groups several+ # records of one event), so rows are appended rather than merged.+ primary_key=None,+ incremental_fields=[+ {+ "label": "eventTime",+ "type": IncrementalFieldType.DateTime,+ "field": "eventTime",+ "field_type": IncrementalFieldType.DateTime,+ }+ ],+ # Log records are immutable, so eventTime is a stable partition key.+ partition_key="eventTime",+ ),+}++ENDPOINTS = tuple(TAILSCALE_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in TAILSCALE_ENDPOINTS.items()+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/tailscale/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/tailscale/source.pyindex c55d98d24869..c62281ee4027 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/tailscale/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/tailscale/source.py@@ -1,30 +1,212 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,+ SourceFieldSelectConfig,+ SourceFieldSelectConfigOption,)-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 TailscaleSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.tailscale.settings import (+ AUDIT_LOG_RETENTION_DAYS,+ AUDIT_LOGS_ENDPOINT,+ ENDPOINTS,+ INCREMENTAL_FIELDS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.tailscale.tailscale import (+ OAUTH_CREDENTIALS_ERROR,+ TailscaleResumeConfig,+ tailscale_source,+ validate_credentials as validate_tailscale_credentials,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class TailscaleSource(SimpleSource[TailscaleSourceConfig]):+class TailscaleSource(ResumableSource[TailscaleSourceConfig, TailscaleResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.TAILSCALE+ @property+ def connection_host_fields(self) -> list[str]:+ # `tailnet` selects which tailnet the stored credential reads from; retargeting it+ # must re-require the secret so a preserved multi-tailnet credential can't be aimed+ # at another tailnet by an editor who doesn't hold the credential.+ return ["tailnet"]+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.TAILSCALE,category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,label="Tailscale",+ releaseStatus=ReleaseStatus.ALPHA,+ keywords=["vpn", "wireguard", "tailnet"],+ caption="""Sync your Tailscale devices, users, keys, and configuration audit logs into the PostHog Data warehouse.++An **OAuth client** is the recommended credential for recurring syncs — API access tokens expire after at most 90 days. Create one in the [Tailscale admin console](https://login.tailscale.com/admin/settings/oauth) under **Settings > OAuth clients**, with read scopes for the tables you want to sync (for example `devices:core:read`, `users:read`, `auth_keys:read`, and `logs:configuration:read`).++Alternatively, generate an API access token under **Settings > Keys**. Leave the tailnet field blank to use the credential's default tailnet.""",iconPath="/static/services/tailscale.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/tailscale",+ fields=cast(+ list[FieldType],+ [+ SourceFieldSelectConfig(+ name="auth_method",+ label="Authentication method",+ required=True,+ defaultValue="oauth_client",+ options=[+ SourceFieldSelectConfigOption(+ label="OAuth client",+ value="oauth_client",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="client_id",+ label="OAuth client ID",+ type=SourceFieldInputConfigType.TEXT,+ required=False,+ placeholder="",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="client_secret",+ label="OAuth client secret",+ type=SourceFieldInputConfigType.PASSWORD,+ required=False,+ placeholder="tskey-client-...",+ secret=True,+ ),+ ],+ ),+ ),+ SourceFieldSelectConfigOption(+ label="API access token",+ value="api_key",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API access token",+ type=SourceFieldInputConfigType.PASSWORD,+ required=False,+ placeholder="tskey-api-...",+ caption="API access tokens expire after at most 90 days — prefer an OAuth client for long-running syncs.",+ secret=True,+ ),+ ],+ ),+ ),+ ],+ ),+ SourceFieldInputConfig(+ name="tailnet",+ label="Tailnet",+ type=SourceFieldInputConfigType.TEXT,+ required=False,+ placeholder="-",+ caption="Your tailnet name, e.g. `example.com`. Leave blank to use the credential's default tailnet.",+ secret=False,+ ),+ ],+ ),+ )++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error": "Invalid or expired Tailscale credentials. API access tokens expire after at most 90 days — generate a new token (or switch to an OAuth client) and reconnect.",+ "403 Client Error": "Your Tailscale credentials lack the required scopes. Grant the read scopes for the tables you sync (e.g. `devices:core:read`, `logs:configuration:read`) and reconnect.",+ "404 Client Error": "Tailnet not found. Check the tailnet name on the source, or leave it blank to use the credential's default tailnet.",+ OAUTH_CREDENTIALS_ERROR: "Invalid Tailscale OAuth client credentials. Please check the client ID and secret and reconnect.",+ }++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.tailscale.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_schemas(+ self,+ config: TailscaleSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ schemas = [+ SourceSchema(+ name=endpoint,+ # Audit log records carry no unique id, so incremental (merge) syncs are+ # impossible — the server-side time filter powers append syncs instead.+ supports_incremental=False,+ supports_append=bool(INCREMENTAL_FIELDS.get(endpoint)),+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),+ description=f"Only syncs the last {AUDIT_LOG_RETENTION_DAYS} days (Tailscale's audit log retention)"+ if endpoint == AUDIT_LOGS_ENDPOINT+ 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: TailscaleSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ return validate_tailscale_credentials(+ api_key=config.auth_method.api_key,+ client_id=config.auth_method.client_id,+ client_secret=config.auth_method.client_secret,+ tailnet=config.tailnet,+ schema_name=schema_name,+ )++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[TailscaleResumeConfig]:+ return ResumableSourceManager[TailscaleResumeConfig](inputs, TailscaleResumeConfig)++ def source_for_pipeline(+ self,+ config: TailscaleSourceConfig,+ resumable_source_manager: ResumableSourceManager[TailscaleResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return tailscale_source(+ api_key=config.auth_method.api_key,+ client_id=config.auth_method.client_id,+ client_secret=config.auth_method.client_secret,+ tailnet=config.tailnet,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=inputs.should_use_incremental_field,+ db_incremental_field_last_value=inputs.db_incremental_field_last_value+ if inputs.should_use_incremental_field+ else None,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/tailscale/tailscale.py b/products/warehouse_sources/backend/temporal/data_imports/sources/tailscale/tailscale.pynew file mode 100644index 000000000000..ae2e2e259475--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/tailscale/tailscale.py@@ -0,0 +1,415 @@+import re+import time+import dataclasses+from collections.abc import Iterator+from datetime import UTC, date, datetime, timedelta+from typing import Any, Optional+from urllib.parse import quote++import requests+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.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.tailscale.settings import (+ AUDIT_LOG_RETENTION_DAYS,+ AUDIT_LOG_WINDOW_DAYS,+ AUDIT_LOGS_ENDPOINT,+ TAILSCALE_ENDPOINTS,+ TailscaleEndpointConfig,+)++BASE_URL = "https://api.tailscale.com/api/v2"++REQUEST_TIMEOUT_SECONDS = 60+MAX_RETRIES = 5+MAX_RETRY_AFTER_SECONDS = 60+# Refresh OAuth access tokens (1h lifetime) with headroom so a token can't expire mid-request.+OAUTH_TOKEN_REFRESH_MARGIN_SECONDS = 300++OAUTH_CREDENTIALS_ERROR = "Invalid Tailscale OAuth client credentials"+++class TailscaleRetryableError(Exception):+ def __init__(self, message: str, retry_after: float | None = None) -> None:+ super().__init__(message)+ self.retry_after = retry_after+++class TailscaleAuthError(Exception):+ pass+++class TailscaleResumeConfig:+ # Start of the next unfetched audit-log window (RFC 3339). Only the audit log+ # endpoint checkpoints — the other endpoints are single unpaginated requests.+ window_start: str+++def normalize_tailnet(tailnet: str | None) -> str:+ """Return the tailnet path segment, defaulting to ``-`` (the credential's own tailnet)."""+ normalized = (tailnet or "").strip()+ return normalized if normalized else "-"+++def _endpoint_url(config: TailscaleEndpointConfig, tailnet: str | None) -> str:+ # The tailnet is user input placed in the URL path (often a domain like `example.com`),+ # so quote it to keep it a single path segment.+ return f"{BASE_URL}{config.path.format(tailnet=quote(normalize_tailnet(tailnet), safe=''))}"+++class TailscaleAuth:+ """Produces the ``Authorization`` header for either auth method.++ API access tokens are sent directly as a Bearer token. OAuth clients exchange their+ client credentials for a short-lived access token, cached until close to expiry.+ """++ def __init__(+ self,+ api_key: str | None = None,+ client_id: str | None = None,+ client_secret: str | None = None,+ ) -> None:+ self._api_key = (api_key or "").strip()+ self._client_id = (client_id or "").strip()+ self._client_secret = (client_secret or "").strip()+ self._access_token: str | None = None+ self._token_expires_at: float = 0.0++ def get_headers(self) -> dict[str, str]:+ return {"Authorization": f"Bearer {self._get_token()}", "Accept": "application/json"}++ def _get_token(self) -> str:+ if self._api_key:+ return self._api_key++ if not self._client_id or not self._client_secret:+ raise TailscaleAuthError(+ "Missing Tailscale credentials. Provide an API access token or an OAuth client ID and secret."+ )++ if self._access_token and time.monotonic() < self._token_expires_at - OAUTH_TOKEN_REFRESH_MARGIN_SECONDS:+ return self._access_token++ response = make_tracked_session().post(+ f"{BASE_URL}/oauth/token",+ data={"client_id": self._client_id, "client_secret": self._client_secret},+ timeout=REQUEST_TIMEOUT_SECONDS,+ )+ if response.status_code != 200:+ raise TailscaleAuthError(f"{OAUTH_CREDENTIALS_ERROR} (status={response.status_code})")++ payload = response.json()+ token = payload.get("access_token")+ if not token:+ raise TailscaleAuthError(f"{OAUTH_CREDENTIALS_ERROR} (no access token in response)")++ self._access_token = str(token)+ self._token_expires_at = time.monotonic() + float(payload.get("expires_in") or 3600)+ return self._access_token+++def _format_rfc3339(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:%SZ")+++def _parse_datetime(value: Any) -> datetime | None:+ if isinstance(value, datetime):+ return value.replace(tzinfo=UTC) if value.tzinfo is None else value.astimezone(UTC)+ if isinstance(value, date):+ return datetime.combine(value, datetime.min.time(), tzinfo=UTC)+ if not isinstance(value, str) or not value:+ return None+ # Tailscale timestamps carry nanosecond precision; trim to microseconds so+ # `fromisoformat` accepts them.+ trimmed = re.sub(r"\.(\d{6})\d+", r".\1", value.strip())+ try:+ parsed = datetime.fromisoformat(trimmed.replace("Z", "+00:00"))+ except ValueError:+ return None+ return parsed.replace(tzinfo=UTC) if parsed.tzinfo is None else parsed.astimezone(UTC)+++def _parse_retry_after(response: requests.Response) -> float | None:+ 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:+ exc = retry_state.outcome.exception() if retry_state.outcome else None+ if isinstance(exc, TailscaleRetryableError) and exc.retry_after is not None:+ return exc.retry_after+ return wait_exponential_jitter(initial=1, max=30)(retry_state)+++@retry(+ retry=retry_if_exception_type((TailscaleRetryableError, requests.ReadTimeout, requests.ConnectionError)),+ stop=stop_after_attempt(MAX_RETRIES),+ wait=_retry_wait,+ reraise=True,+)+def _fetch(auth: TailscaleAuth, url: str, params: dict[str, Any] | None = None) -> requests.Response:+ response = make_tracked_session().get(+ url, headers=auth.get_headers(), params=params or None, timeout=REQUEST_TIMEOUT_SECONDS+ )++ if response.status_code == 429 or response.status_code >= 500:+ retry_after = _parse_retry_after(response) if response.status_code == 429 else None+ raise TailscaleRetryableError(+ f"Tailscale API error (retryable): status={response.status_code}, url={url}",+ retry_after=retry_after,+ )++ return response+++def _extract_rows(payload: Any, data_key: str) -> list[dict[str, Any]]:+ if isinstance(payload, dict):+ rows = payload.get(data_key)+ return rows if isinstance(rows, list) else []+ # Defensive: undocumented bare-list responses.+ return payload if isinstance(payload, list) else []+++def _list_rows(+ auth: TailscaleAuth, config: TailscaleEndpointConfig, tailnet: str | None, logger: FilteringBoundLogger+) -> Iterator[list[dict[str, Any]]]:+ url = _endpoint_url(config, tailnet)+ response = _fetch(auth, url, dict(config.params))+ response.raise_for_status()++ rows = _extract_rows(response.json(), config.data_key)+ logger.debug(f"Tailscale: fetched {len(rows)} rows from {config.name}")+ if rows:+ yield rows+++def _key_rows(+ auth: TailscaleAuth, config: TailscaleEndpointConfig, tailnet: str | None, logger: FilteringBoundLogger+) -> Iterator[list[dict[str, Any]]]:+ """The keys list endpoint only returns id + description, so fetch each key's detail+ (created, expires, revoked, capabilities) individually. Tailnets hold few keys."""+ url = _endpoint_url(config, tailnet)+ response = _fetch(auth, url, dict(config.params))+ response.raise_for_status()++ listed = _extract_rows(response.json(), config.data_key)+ rows: list[dict[str, Any]] = []+ for key in listed:+ key_id = key.get("id") if isinstance(key, dict) else None+ if not key_id:+ continue+ detail_response = _fetch(auth, f"{url}/{quote(str(key_id), safe='')}")+ if detail_response.status_code == 404:+ # The key was deleted between the list and detail calls.+ logger.debug(f"Tailscale: key {key_id} disappeared mid-sync, skipping")+ continue+ detail_response.raise_for_status()+ detail = detail_response.json()+ rows.append(detail if isinstance(detail, dict) else key)++ logger.debug(f"Tailscale: fetched {len(rows)} rows from {config.name}")+ if rows:+ yield rows+++def _audit_log_rows(+ auth: TailscaleAuth,+ config: TailscaleEndpointConfig,+ tailnet: str | None,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[TailscaleResumeConfig],+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+) -> Iterator[list[dict[str, Any]]]:+ """Walk the configuration audit log in ascending time windows.++ The endpoint requires inclusive `start`/`end` params and returns everything in the+ window (no pagination), so each window is one request, yielded as one batch, then+ checkpointed. Because `start` is inclusive, each incremental run (and each window+ boundary) would re-fetch the records at the boundary timestamp — a client-side+ cursor drops those already-seen rows.+ """+ url = _endpoint_url(config, tailnet)+ now = datetime.now(UTC)+ retention_floor = now - timedelta(days=AUDIT_LOG_RETENTION_DAYS)++ cursor: datetime | None = None+ start = retention_floor+ if should_use_incremental_field:+ watermark = _parse_datetime(db_incremental_field_last_value)+ if watermark is not None:+ cursor = watermark+ # A watermark older than the retention window would request a range Tailscale+ # no longer holds; clamp rather than risk a 4xx for out-of-retention starts.+ start = max(watermark, retention_floor)++ if resumable_source_manager.can_resume():+ resume_config = resumable_source_manager.load_state()+ resume_start = _parse_datetime(resume_config.window_start) if resume_config else None+ if resume_start is not None and resume_start > start:+ start = resume_start+ logger.debug(f"Tailscale: resuming audit log sync from {_format_rfc3339(resume_start)}")++ while start < now:+ window_end = min(start + timedelta(days=AUDIT_LOG_WINDOW_DAYS), now)+ response = _fetch(auth, url, {"start": _format_rfc3339(start), "end": _format_rfc3339(window_end)})+ response.raise_for_status()++ rows = _extract_rows(response.json(), config.data_key)+ fresh: list[tuple[datetime | None, dict[str, Any]]] = []+ for row in rows:+ event_time = _parse_datetime(row.get("eventTime"))+ # Rows with an unparsable eventTime are kept — dropping audit records is+ # worse than a rare duplicate.+ if cursor is not None and event_time is not None and event_time <= cursor:+ continue+ fresh.append((event_time, row))++ # sort_mode="asc" lets the pipeline checkpoint the watermark per batch, so rows+ # must be yielded in ascending eventTime order.+ fresh.sort(key=lambda item: item[0] or datetime.min.replace(tzinfo=UTC))++ if fresh:+ yield [row for _, row in fresh]+ parsed_times = [event_time for event_time, _ in fresh if event_time is not None]+ if parsed_times:+ cursor = max(parsed_times)++ # Checkpoint AFTER yielding so a crash re-fetches (and dedupes) the last window+ # instead of skipping it.+ resumable_source_manager.save_state(TailscaleResumeConfig(window_start=_format_rfc3339(window_end)))+ start = window_end+++def get_rows(+ api_key: str | None,+ client_id: str | None,+ client_secret: str | None,+ tailnet: str | None,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[TailscaleResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+) -> Iterator[list[dict[str, Any]]]:+ config = TAILSCALE_ENDPOINTS[endpoint]+ auth = TailscaleAuth(api_key=api_key, client_id=client_id, client_secret=client_secret)++ if endpoint == AUDIT_LOGS_ENDPOINT:+ yield from _audit_log_rows(+ auth,+ config,+ tailnet,+ logger,+ resumable_source_manager,+ should_use_incremental_field,+ db_incremental_field_last_value,+ )+ elif endpoint == "keys":+ yield from _key_rows(auth, config, tailnet, logger)+ else:+ yield from _list_rows(auth, config, tailnet, logger)+++def tailscale_source(+ api_key: str | None,+ client_id: str | None,+ client_secret: str | None,+ tailnet: str | None,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[TailscaleResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+) -> SourceResponse:+ endpoint_config = TAILSCALE_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ api_key=api_key,+ client_id=client_id,+ client_secret=client_secret,+ tailnet=tailnet,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=db_incremental_field_last_value,+ ),+ primary_keys=[endpoint_config.primary_key] if endpoint_config.primary_key else None,+ # Audit log windows advance forward in time and each window is sorted ascending;+ # the other endpoints are single full-refresh responses where order is irrelevant.+ sort_mode="asc",+ partition_count=1 if endpoint_config.partition_key else None,+ partition_size=1 if endpoint_config.partition_key else None,+ partition_mode="datetime" if endpoint_config.partition_key else None,+ partition_format="month" if endpoint_config.partition_key else None,+ partition_keys=[endpoint_config.partition_key] if endpoint_config.partition_key else None,+ )+++def _probe_url_and_params(schema_name: str | None, tailnet: str | None) -> tuple[str, dict[str, Any]]:+ """A cheap request proving the credential can reach `schema_name` (or the tailnet at all).++ The keys list is the default probe: it is small on every tailnet (devices can be+ huge and the API has no `limit` param). The audit log probe uses a 1-hour window+ to satisfy the required start/end params without pulling real volume.+ """+ config = TAILSCALE_ENDPOINTS.get(schema_name or "") or TAILSCALE_ENDPOINTS["keys"]+ url = _endpoint_url(config, tailnet)+ if config.name == AUDIT_LOGS_ENDPOINT:+ now = datetime.now(UTC)+ return url, {"start": _format_rfc3339(now - timedelta(hours=1)), "end": _format_rfc3339(now)}+ if config.name == "devices":+ # Probe with the lighter default field set.+ return url, {}+ return url, dict(config.params)+++def validate_credentials(+ api_key: str | None,+ client_id: str | None,+ client_secret: str | None,+ tailnet: str | None,+ schema_name: str | None = None,+) -> tuple[bool, str | None]:+ auth = TailscaleAuth(api_key=api_key, client_id=client_id, client_secret=client_secret)+ url, params = _probe_url_and_params(schema_name, tailnet)++ try:+ response = make_tracked_session().get(url, headers=auth.get_headers(), params=params or None, timeout=10)+ except TailscaleAuthError as e:+ return False, str(e)+ except requests.exceptions.RequestException as e:+ return False, str(e)++ if response.status_code == 200:+ return True, None++ if response.status_code == 401:+ return False, "Invalid Tailscale credentials. API access tokens expire after at most 90 days."++ if response.status_code == 403:+ if schema_name is None:+ # Valid credential without the probe's scope (OAuth clients are scoped per+ # resource) — let source creation through; per-endpoint access is checked later.+ return True, None+ return False, f"Your Tailscale credentials lack the scope required to read '{schema_name}'."++ if response.status_code == 404:+ return False, "Tailnet not found. Check the tailnet name, or leave it blank to use the default tailnet."++ try:+ body = response.json()+ return False, str(body.get("message", response.text))+ except Exception:+ return False, response.textdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/tailscale/tests/test_tailscale.py b/products/warehouse_sources/backend/temporal/data_imports/sources/tailscale/tests/test_tailscale.pynew file mode 100644index 000000000000..443c2fde985e--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/tailscale/tests/test_tailscale.py@@ -0,0 +1,381 @@+from datetime import UTC, datetime+from typing import Any, Optional++import pytest+from freezegun import freeze_time+from unittest import mock++from products.warehouse_sources.backend.temporal.data_imports.sources.tailscale import tailscale as tailscale_module+from products.warehouse_sources.backend.temporal.data_imports.sources.tailscale.settings import TAILSCALE_ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.tailscale.tailscale import (+ TailscaleAuth,+ TailscaleAuthError,+ TailscaleResumeConfig,+ _endpoint_url,+ _parse_datetime,+ _parse_retry_after,+ get_rows,+ normalize_tailnet,+ tailscale_source,+ validate_credentials,+)+++def _response(*, status_code: int = 200, json_data: Any = None, text: str = "") -> mock.MagicMock:+ response = mock.MagicMock()+ response.status_code = status_code+ response.ok = 200 <= status_code < 400+ response.text = text+ response.json.return_value = json_data+ response.headers = {}+ if status_code >= 400:+ response.raise_for_status.side_effect = Exception(f"{status_code} Client Error")+ else:+ response.raise_for_status.return_value = None+ return response+++def _patch_session(responses: list[Any]) -> tuple[mock.MagicMock, Any]:+ session = mock.MagicMock()+ session.get.side_effect = responses+ return session, mock.patch.object(tailscale_module, "make_tracked_session", return_value=session)+++class TestNormalizeTailnet:+ @pytest.mark.parametrize(+ "raw, expected",+ [+ (None, "-"),+ ("", "-"),+ (" ", "-"),+ ("-", "-"),+ ("example.com", "example.com"),+ (" example.com ", "example.com"),+ ],+ )+ def test_normalize(self, raw, expected):+ assert normalize_tailnet(raw) == expected++ def test_endpoint_url_quotes_tailnet_as_single_path_segment(self):+ url = _endpoint_url(TAILSCALE_ENDPOINTS["devices"], "bad/../segment")+ assert url == "https://api.tailscale.com/api/v2/tailnet/bad%2F..%2Fsegment/devices"+++class TestParseDatetime:+ @pytest.mark.parametrize(+ "value, expected",+ [+ # Tailscale timestamps carry nanosecond precision, which fromisoformat rejects untrimmed.+ ("2026-01-15T10:30:45.687985429Z", datetime(2026, 1, 15, 10, 30, 45, 687985, tzinfo=UTC)),+ ("2026-01-15T10:30:45Z", datetime(2026, 1, 15, 10, 30, 45, tzinfo=UTC)),+ (datetime(2026, 1, 15, 10, 30, 45), datetime(2026, 1, 15, 10, 30, 45, tzinfo=UTC)),+ ("not-a-date", None),+ ("", None),+ (None, None),+ ],+ )+ def test_parse(self, value, expected):+ assert _parse_datetime(value) == expected+++class TestTailscaleAuth:+ def test_api_key_used_directly_without_token_exchange(self):+ session, patched = _patch_session([])+ with patched:+ headers = TailscaleAuth(api_key="tskey-api-x").get_headers()+ assert headers["Authorization"] == "Bearer tskey-api-x"+ session.post.assert_not_called()++ def test_oauth_client_exchanges_and_caches_token(self):+ session = mock.MagicMock()+ session.post.return_value = _response(json_data={"access_token": "at-123", "expires_in": 3600})+ with mock.patch.object(tailscale_module, "make_tracked_session", return_value=session):+ auth = TailscaleAuth(client_id="cid", client_secret="csecret")+ first = auth.get_headers()+ second = auth.get_headers()++ assert first["Authorization"] == "Bearer at-123"+ assert second == first+ assert session.post.call_count == 1+ assert session.post.call_args.kwargs["data"] == {"client_id": "cid", "client_secret": "csecret"}++ @pytest.mark.parametrize("json_data", [{"error": "bad"}, {}])+ def test_oauth_failure_raises_auth_error(self, json_data):+ session = mock.MagicMock()+ session.post.return_value = _response(status_code=401, json_data=json_data)+ with mock.patch.object(tailscale_module, "make_tracked_session", return_value=session):+ with pytest.raises(TailscaleAuthError):+ TailscaleAuth(client_id="cid", client_secret="wrong").get_headers()++ def test_missing_credentials_raises_auth_error(self):+ with pytest.raises(TailscaleAuthError):+ TailscaleAuth().get_headers()+++class TestTailscaleSourceResponse:+ @pytest.mark.parametrize(+ "endpoint, primary_keys, partition_key",+ [+ ("devices", ["id"], None),+ ("users", ["id"], None),+ ("keys", ["id"], None),+ ("configuration_audit_logs", None, "eventTime"),+ ],+ )+ def test_response_shape(self, endpoint, primary_keys, partition_key):+ response = tailscale_source(+ api_key="tskey-api-x",+ client_id=None,+ client_secret=None,+ tailnet=None,+ endpoint=endpoint,+ logger=mock.MagicMock(),+ resumable_source_manager=mock.MagicMock(),+ )+ assert response.name == endpoint+ assert response.primary_keys == primary_keys+ assert response.sort_mode == "asc"+ 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 TestGetRows:+ def _run(self, endpoint: str, responses: list[Any], manager: Optional[mock.MagicMock] = None, **kwargs: Any):+ if manager is None:+ manager = mock.MagicMock()+ manager.can_resume.return_value = False+ session, patched = _patch_session(responses)+ with patched:+ rows: list[dict[str, Any]] = []+ for batch in get_rows(+ api_key="tskey-api-x",+ client_id=None,+ client_secret=None,+ tailnet="example.com",+ endpoint=endpoint,+ logger=mock.MagicMock(),+ resumable_source_manager=manager,+ **kwargs,+ ):+ rows.extend(batch)+ return rows, session, manager++ def test_devices_single_request_with_all_fields(self):+ rows, session, _ = self._run("devices", [_response(json_data={"devices": [{"id": "1"}, {"id": "2"}]})])+ assert [r["id"] for r in rows] == ["1", "2"]+ assert session.get.call_count == 1+ call = session.get.call_args+ assert call.args[0] == "https://api.tailscale.com/api/v2/tailnet/example.com/devices"+ assert call.kwargs["params"] == {"fields": "all"}++ def test_keys_fans_out_to_details_and_skips_deleted(self):+ responses = [+ _response(json_data={"keys": [{"id": "k1"}, {"id": "k2"}]}),+ _response(json_data={"id": "k1", "created": "2026-01-01T00:00:00Z"}),+ _response(status_code=404),+ ]+ rows, session, _ = self._run("keys", responses)++ # The deleted key's 404 is skipped rather than failing the sync.+ assert rows == [{"id": "k1", "created": "2026-01-01T00:00:00Z"}]+ detail_urls = [call.args[0] for call in session.get.call_args_list[1:]]+ assert detail_urls == [+ "https://api.tailscale.com/api/v2/tailnet/example.com/keys/k1",+ "https://api.tailscale.com/api/v2/tailnet/example.com/keys/k2",+ ]+++@freeze_time("2026-01-30T00:00:00Z")+class TestAuditLogRows:+ def _run(self, responses: list[Any], manager: Optional[mock.MagicMock] = None, **kwargs: Any):+ if manager is None:+ manager = mock.MagicMock()+ manager.can_resume.return_value = False+ session, patched = _patch_session(responses)+ with patched:+ batches = list(+ get_rows(+ api_key="tskey-api-x",+ client_id=None,+ client_secret=None,+ tailnet="example.com",+ endpoint="configuration_audit_logs",+ logger=mock.MagicMock(),+ resumable_source_manager=manager,+ **kwargs,+ )+ )+ return batches, session, manager++ def _log(self, event_time: str, action: str = "UPDATE") -> dict[str, Any]:+ return {"eventTime": event_time, "action": action}++ def test_incremental_sync_windows_filters_and_checkpoints(self):+ # Watermark 2026-01-20 with 7-day windows and now=2026-01-30 → two windows:+ # [01-20, 01-27] and [01-27, 01-30].+ window1 = _response(+ json_data={+ "logs": [+ # Returned newest-first to prove client-side ascending sort.+ self._log("2026-01-25T00:00:00Z"),+ self._log("2026-01-21T00:00:00Z"),+ # `start` is inclusive, so the watermark row comes back — it must be dropped.+ self._log("2026-01-20T00:00:00Z"),+ ]+ }+ )+ window2 = _response(+ json_data={+ "logs": [+ # Window boundaries are inclusive on both ends, so the last row of window 1+ # would reappear if it fell exactly on the boundary; the max-seen cursor+ # drops anything at or before it.+ self._log("2026-01-25T00:00:00Z"),+ self._log("2026-01-29T00:00:00Z"),+ ]+ }+ )+ batches, session, manager = self._run(+ [window1, window2],+ should_use_incremental_field=True,+ db_incremental_field_last_value="2026-01-20T00:00:00Z",+ )++ assert [[r["eventTime"] for r in batch] for batch in batches] == [+ ["2026-01-21T00:00:00Z", "2026-01-25T00:00:00Z"],+ ["2026-01-29T00:00:00Z"],+ ]++ requested_windows = [call.kwargs["params"] for call in session.get.call_args_list]+ assert requested_windows == [+ {"start": "2026-01-20T00:00:00Z", "end": "2026-01-27T00:00:00Z"},+ {"start": "2026-01-27T00:00:00Z", "end": "2026-01-30T00:00:00Z"},+ ]++ saved = [call.args[0].window_start for call in manager.save_state.call_args_list]+ assert saved == ["2026-01-27T00:00:00Z", "2026-01-30T00:00:00Z"]++ def test_resumes_from_saved_window(self):+ manager = mock.MagicMock()+ manager.can_resume.return_value = True+ manager.load_state.return_value = TailscaleResumeConfig(window_start="2026-01-28T00:00:00Z")++ _batches, session, _ = self._run(+ [_response(json_data={"logs": []})],+ manager=manager,+ should_use_incremental_field=True,+ db_incremental_field_last_value="2026-01-20T00:00:00Z",+ )++ assert session.get.call_count == 1+ assert session.get.call_args.kwargs["params"]["start"] == "2026-01-28T00:00:00Z"++ def test_watermark_older_than_retention_is_clamped(self):+ # Requesting a start older than the 90-day retention window risks a 4xx, so the+ # start is clamped to now - 90 days.+ with mock.patch.object(tailscale_module, "AUDIT_LOG_WINDOW_DAYS", 365):+ _batches, session, _ = self._run(+ [_response(json_data={"logs": []})],+ should_use_incremental_field=True,+ db_incremental_field_last_value="2025-01-01T00:00:00Z",+ )+ assert session.get.call_args.kwargs["params"] == {+ "start": "2025-11-01T00:00:00Z",+ "end": "2026-01-30T00:00:00Z",+ }++ def test_full_refresh_keeps_all_rows(self):+ with mock.patch.object(tailscale_module, "AUDIT_LOG_WINDOW_DAYS", 365):+ batches, _session, _ = self._run(+ [_response(json_data={"logs": [self._log("2025-11-02T00:00:00Z")]})],+ should_use_incremental_field=False,+ db_incremental_field_last_value=None,+ )+ assert [[r["eventTime"] for r in batch] for batch in batches] == [["2025-11-02T00:00:00Z"]]+++class TestValidateCredentials:+ @pytest.mark.parametrize(+ "status_code, schema_name, expected_valid",+ [+ (200, None, True),+ (401, None, False),+ # A 403 at source-create passes (scoped OAuth clients may not grant the+ # probe's scope), but a scoped per-schema probe fails.+ (403, None, True),+ (403, "devices", False),+ (404, None, False),+ ],+ )+ def test_status_mapping(self, status_code, schema_name, expected_valid):+ _session, patched = _patch_session([_response(status_code=status_code, json_data={"message": "nope"})])+ with patched:+ valid, message = validate_credentials(+ api_key="tskey-api-x",+ client_id=None,+ client_secret=None,+ tailnet=None,+ schema_name=schema_name,+ )+ assert valid is expected_valid+ if not expected_valid:+ assert message++ def test_audit_logs_probe_sends_required_time_window(self):+ session, patched = _patch_session([_response(json_data={"logs": []})])+ with patched:+ valid, _ = validate_credentials(+ api_key="tskey-api-x",+ client_id=None,+ client_secret=None,+ tailnet=None,+ schema_name="configuration_audit_logs",+ )+ assert valid is True+ params = session.get.call_args.kwargs["params"]+ assert "start" in params and "end" in params++ def test_oauth_exchange_failure_is_reported(self):+ session = mock.MagicMock()+ session.post.return_value = _response(status_code=401, json_data={})+ with mock.patch.object(tailscale_module, "make_tracked_session", return_value=session):+ valid, message = validate_credentials(+ api_key=None,+ client_id="cid",+ client_secret="wrong",+ tailnet=None,+ )+ assert valid is False+ assert "OAuth" in (message or "")++ def test_request_exception_returns_failure(self):+ import requests++ session = mock.MagicMock()+ session.get.side_effect = requests.exceptions.ConnectionError("boom")+ with mock.patch.object(tailscale_module, "make_tracked_session", return_value=session):+ valid, message = validate_credentials(+ api_key="tskey-api-x", client_id=None, client_secret=None, tailnet=None+ )+ assert valid is False+ assert "boom" in (message or "")+++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) == expecteddiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/tailscale/tests/test_tailscale_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/tailscale/tests/test_tailscale_source.pynew file mode 100644index 000000000000..4b3731eb7cb1--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/tailscale/tests/test_tailscale_source.py@@ -0,0 +1,154 @@+import pytest+from unittest import mock++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldSelectConfig++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 (+ TailscaleAuthMethodConfig,+ TailscaleSourceConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.tailscale.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.tailscale.source import TailscaleSource+from products.warehouse_sources.backend.temporal.data_imports.sources.tailscale.tailscale import (+ OAUTH_CREDENTIALS_ERROR,+ TailscaleResumeConfig,+)+from products.warehouse_sources.backend.types import ExternalDataSourceType+++class TestTailscaleSource:+ def setup_method(self):+ self.source = TailscaleSource()+ self.team_id = 123+ self.config = TailscaleSourceConfig(+ auth_method=TailscaleAuthMethodConfig(selection="api_key", api_key="tskey-api-test"),+ tailnet="example.com",+ )++ def test_source_type(self):+ assert self.source.source_type == ExternalDataSourceType.TAILSCALE++ def test_tailnet_change_requires_reentering_secrets(self):+ # The update serializer keys off this to force re-entry of the stored credential+ # when the tailnet is retargeted.+ assert self.source.connection_host_fields == ["tailnet"]++ def test_get_source_config(self):+ config = self.source.get_source_config++ assert config.name.value == "Tailscale"+ assert config.label == "Tailscale"+ assert config.unreleasedSource is None+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.iconPath == "/static/services/tailscale.png"+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/tailscale"++ field_names = [f.name for f in config.fields]+ assert field_names == ["auth_method", "tailnet"]++ auth_field, tailnet_field = config.fields+ assert isinstance(auth_field, SourceFieldSelectConfig)+ assert [option.value for option in auth_field.options] == ["oauth_client", "api_key"]++ secret_fields = {+ sub_field.name: sub_field.secret+ for option in auth_field.options+ for sub_field in option.fields or []+ if isinstance(sub_field, SourceFieldInputConfig)+ }+ assert secret_fields == {"client_id": False, "client_secret": True, "api_key": True}++ assert isinstance(tailnet_field, SourceFieldInputConfig)+ assert tailnet_field.required is False++ @pytest.mark.parametrize(+ "expected_key",+ ["401 Client Error", "403 Client Error", "404 Client Error", OAUTH_CREDENTIALS_ERROR],+ )+ 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, supports_append",+ [+ ("devices", False),+ ("users", False),+ ("keys", False),+ ("configuration_audit_logs", True),+ ],+ )+ def test_schema_sync_support(self, endpoint, supports_append):+ schemas = {s.name: s for s in self.source.get_schemas(self.config, self.team_id)}+ # Audit log records have no unique id, so merge-based incremental syncs must never+ # be offered — the time filter powers append syncs only.+ assert schemas[endpoint].supports_incremental is False+ assert schemas[endpoint].supports_append is supports_append+ assert bool(schemas[endpoint].incremental_fields) is supports_append++ def test_audit_logs_schema_mentions_retention(self):+ schemas = {s.name: s for s in self.source.get_schemas(self.config, self.team_id)}+ assert "90 days" in (schemas["configuration_audit_logs"].description or "")++ def test_get_schemas_filtered_by_names(self):+ schemas = self.source.get_schemas(self.config, self.team_id, names=["devices"])+ assert [s.name for s in schemas] == ["devices"]++ def test_get_schemas_unknown_name_returns_empty(self):+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.tailscale.source.validate_tailscale_credentials"+ )+ def test_validate_credentials_plumbs_config(self, mock_validate):+ mock_validate.return_value = (True, None)++ result = self.source.validate_credentials(self.config, self.team_id, schema_name="devices")++ assert result == (True, None)+ mock_validate.assert_called_once_with(+ api_key="tskey-api-test",+ client_id=None,+ client_secret=None,+ tailnet="example.com",+ schema_name="devices",+ )++ def test_get_resumable_source_manager(self):+ inputs = mock.MagicMock()+ manager = self.source.get_resumable_source_manager(inputs)+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is TailscaleResumeConfig++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.tailscale.source.tailscale_source")+ def test_source_for_pipeline_plumbs_arguments(self, mock_tailscale_source):+ inputs = mock.MagicMock()+ inputs.schema_name = "configuration_audit_logs"+ inputs.should_use_incremental_field = True+ inputs.db_incremental_field_last_value = "2026-01-01T00:00:00Z"+ manager = mock.MagicMock()++ self.source.source_for_pipeline(self.config, manager, inputs)++ kwargs = mock_tailscale_source.call_args.kwargs+ assert kwargs["api_key"] == "tskey-api-test"+ assert kwargs["tailnet"] == "example.com"+ assert kwargs["endpoint"] == "configuration_audit_logs"+ assert kwargs["resumable_source_manager"] is manager+ assert kwargs["should_use_incremental_field"] is True+ assert kwargs["db_incremental_field_last_value"] == "2026-01-01T00:00:00Z"++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.tailscale.source.tailscale_source")+ def test_source_for_pipeline_omits_last_value_when_not_incremental(self, mock_tailscale_source):+ inputs = mock.MagicMock()+ inputs.schema_name = "devices"+ 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_tailscale_source.call_args.kwargs["db_incremental_field_last_value"] is None