: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 strato import source (#107238)
Tom Owerse3d3d7bd16ce
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex a9d059a381d2..017634dcb59f 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -676,6 +676,7 @@ the row lists both.| statuspage | HTTP | requests | ✅ || stigg | HTTP | requests | ✅ || stockdata | HTTP | requests + `rest_source.RESTClient` | ✅ |+| strato | HTTP | requests + `rest_source.RESTClient` | ✅ || streamelements | HTTP | requests | ✅ || stripe | HTTP (vendor SDK) + Webhook | stripe (StripeClient + RequestsClient) + `WebhookSourceManager` | ✅ (pull) / ➖ (webhook) || stytch | HTTP | requests | ✅ |@@ -1405,7 +1406,6 @@ doesn't conflict with concurrent PRs.- starburst- statsig- stockx-- strato- strava- streamlabs- substackdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/strato.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/strato.pyindex 3cc72d5a8cca..e265a5837d98 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/strato.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/strato.py@@ -6,4 +6,4 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp@config.configclass StratoSourceConfig(config.Config):- pass+ api_token: strdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/strato/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/strato/canonical_descriptions.pynew file mode 100644index 000000000000..a81ce2e4f359--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/strato/canonical_descriptions.py@@ -0,0 +1,235 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++_DOCS_URL = "https://scp-api.strato.de/documentation/v1/en/api/documentation.html"++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "Servers": {+ "description": "Cloud servers in the STRATO ServerCloud account, with hardware, image, IP, and status details.",+ "docs_url": _DOCS_URL,+ "columns": {+ "id": "Server ID.",+ "cloudpanel_id": "Public identifier shown in the CloudPanel, used when contacting support.",+ "name": "Server name.",+ "server_type": "Server type.",+ "description": "Server description.",+ "creation_date": "Date when the server was created.",+ "ssh_password": "True when server access through an SSH password is enabled.",+ "status": "Server state.",+ "datacenter": "Data center where the server is located.",+ "hardware": "Hardware features of the server, including vCores, RAM, and HDDs.",+ "image": "Image installed on the server.",+ "dvd": "DVD loaded into the server, if any.",+ "snapshot": "Information about the server's snapshot, if any.",+ "ips": "IPs assigned to the server.",+ "alerts": "Server alerts.",+ "monitoring_policy": "Monitoring policy assigned to the server.",+ "private_networks": "Private networks the server is added to.",+ },+ },+ "Snapshots": {+ "description": "Snapshots of each cloud server.",+ "docs_url": _DOCS_URL,+ "columns": {+ "id": "Snapshot ID.",+ "server_id": "ID of the server the snapshot belongs to.",+ "creation_date": "Date when the snapshot was created.",+ },+ },+ "Images": {+ "description": "Server images, including operating system details and backup frequency.",+ "docs_url": _DOCS_URL,+ "columns": {+ "id": "Image ID.",+ "name": "Image name.",+ "datacenter": "Data center where the image is available.",+ "os_family": "Operating system family.",+ "os": "Operating system version.",+ "os_version": "Operating system distribution.",+ "os_architecture": "Hardware architecture required for the selected OS.",+ "os_image_type": "Operating system image type.",+ "type": "Image type.",+ "min_hdd_size": "Minimum required HDD size.",+ "licenses": "Licenses acquired for the image.",+ "state": "Image state.",+ "description": "Image description.",+ "hdds": "HDDs of the image.",+ "server_id": "ID of the server that is the source of the image.",+ "frequency": "Frequency with which the image is made.",+ "num_images": "Maximum number of images that will be stored.",+ "creation_date": "Date when the image was created.",+ },+ },+ "BlockStorages": {+ "description": "Block storage volumes and the server each one is attached to.",+ "docs_url": _DOCS_URL,+ "columns": {+ "id": "Block storage ID.",+ "size": "Block storage total size.",+ "state": "Block storage state.",+ "description": "Block storage description.",+ "datacenter": "Data center where the block storage is available.",+ "name": "Block storage name.",+ "creation_date": "Date when the block storage was created.",+ "server": "Server the block storage is attached to.",+ },+ },+ "SharedStorages": {+ "description": "Shared storage volumes with CIFS/NFS paths and attached servers.",+ "docs_url": _DOCS_URL,+ "columns": {+ "id": "Shared storage ID.",+ "size": "Shared storage total size.",+ "state": "Shared storage status.",+ "description": "Shared storage description.",+ "datacenter": "Data center where the shared storage is available.",+ "size_used": "Size used of the shared storage, as a percentage.",+ "cifs_path": "CIFS path for accessing the shared storage from Windows systems.",+ "nfs_path": "NFS path for accessing the shared storage from UNIX systems.",+ "name": "Shared storage name.",+ "creation_date": "Date when the shared storage was created.",+ "servers": "Servers with access to the shared storage.",+ },+ },+ "FirewallPolicies": {+ "description": "Firewall policies with their rules and the server IPs they are assigned to.",+ "docs_url": _DOCS_URL,+ "columns": {+ "id": "Firewall policy ID.",+ "name": "Firewall policy name.",+ "description": "Firewall policy description.",+ "state": "Firewall policy state.",+ "creation_date": "Date when the firewall policy was created.",+ "default": "1 when this is a default panel firewall policy.",+ "rules": "Firewall policy rules.",+ "server_ips": "Server IPs assigned to the firewall policy.",+ },+ },+ "LoadBalancers": {+ "description": "Load balancers with health check settings, rules, and assigned server IPs.",+ "docs_url": _DOCS_URL,+ "columns": {+ "id": "Load balancer ID.",+ "name": "Load balancer name.",+ "state": "Load balancer status.",+ "creation_date": "Date when the load balancer was created.",+ "description": "Load balancer description.",+ "ip": "Load balancer IP.",+ "health_check_test": "Type of health check.",+ "health_check_interval": "Health check period.",+ "health_check_path": "URL to call for checking.",+ "health_check_path_parser": "Regular expression to check the health check response against.",+ "persistence": "Whether session persistence is enabled.",+ "persistence_time": "Persistence time.",+ "method": "Balancing procedure.",+ "datacenter": "Data center where the load balancer is available.",+ "rules": "Load balancer rules.",+ "server_ips": "Server IPs assigned to the load balancer.",+ },+ },+ "PublicIps": {+ "description": "Public IP addresses and the resource each one is assigned to.",+ "docs_url": _DOCS_URL,+ "columns": {+ "id": "IP ID.",+ "ip": "The IP address.",+ "type": "Type of IP (currently only IPv4 is available).",+ "datacenter": "Data center where the IP is available.",+ "assigned_to": "Resource the IP is assigned to.",+ "reverse_dns": "Reverse DNS name.",+ "is_dhcp": "True when the IP is assigned using DHCP.",+ "state": "IP status.",+ "creation_date": "Date when the IP was created.",+ },+ },+ "PrivateNetworks": {+ "description": "Private networks and the servers assigned to each one.",+ "docs_url": _DOCS_URL,+ "columns": {+ "id": "Private network ID.",+ "name": "Private network name.",+ "description": "Private network description.",+ "datacenter": "Data center where the private network is available.",+ "network_address": "Network address.",+ "subnet_mask": "Subnet mask.",+ "state": "State of the private network.",+ "creation_date": "Date when the private network was created.",+ "servers": "Servers assigned to the private network.",+ },+ },+ "Vpns": {+ "description": "VPNs configured in the account.",+ "docs_url": _DOCS_URL,+ "columns": {+ "id": "VPN ID.",+ "name": "VPN name.",+ "description": "VPN description.",+ "state": "VPN status.",+ "datacenter": "Data center where the VPN is available.",+ "type": "VPN type.",+ "ips": "VPN IPs.",+ "creation_date": "Date when the VPN was created.",+ },+ },+ "MonitoringPolicies": {+ "description": "Monitoring policies with thresholds, monitored ports and processes, and assigned servers.",+ "docs_url": _DOCS_URL,+ "columns": {+ "id": "Monitoring policy ID.",+ "name": "Monitoring policy name.",+ "description": "Monitoring policy description.",+ "default": "1 when this is a default policy.",+ "state": "Monitoring policy status.",+ "creation_date": "Date when the monitoring policy was created.",+ "email": "Email address that receives notifications.",+ "agent": "True when the monitoring agent will be installed.",+ "servers": "Servers assigned to the monitoring policy.",+ "thresholds": "Monitoring thresholds.",+ "ports": "Ports that will be monitored.",+ "processes": "Processes that will be monitored.",+ },+ },+ "SshKeys": {+ "description": "SSH public keys registered in the account and the servers using them.",+ "docs_url": _DOCS_URL,+ "columns": {+ "id": "SSH key ID.",+ "name": "SSH key name.",+ "description": "SSH key description.",+ "state": "SSH key state.",+ "servers": "Servers using the SSH key.",+ "md5": "MD5 fingerprint of the SSH key.",+ "public_key": "The SSH public key.",+ "creation_date": "Date when the SSH key was created.",+ },+ },+ "Users": {+ "description": "CloudPanel users with their roles and API access settings. The API key itself is removed before rows are stored.",+ "docs_url": _DOCS_URL,+ "columns": {+ "id": "User ID.",+ "name": "User name.",+ "description": "User description.",+ "email": "User email address.",+ "state": "User status.",+ "creation_date": "Date when the user was created.",+ "api": "API access settings for the user (active flag and allowed IPs; the key is removed).",+ "roles": "Role the user belongs to.",+ },+ },+ "Roles": {+ "description": "CloudPanel roles with their permissions and assigned users.",+ "docs_url": _DOCS_URL,+ "columns": {+ "id": "Role ID.",+ "name": "Role name.",+ "description": "Role description.",+ "state": "Role status.",+ "default": "1 when this is a default panel role.",+ "creation_date": "Date when the role was created.",+ "users": "Users assigned to the role.",+ "permissions": "Actions allowed for the role.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/strato/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/strato/settings.pynew file mode 100644index 000000000000..6acbeda9f304--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/strato/settings.py@@ -0,0 +1,70 @@+from dataclasses import field++from posthog.dataclasses import frozen++from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (+ DependentEndpointConfig,+)+from products.warehouse_sources.backend.types import IncrementalField++STRATO_BASE_URL = "https://scp-api.strato.de/v1"++# Snapshots only exist per server (/servers/{server_id}/snapshots); Servers is the parent list+# the endpoint fans out from. A server deleted between the parent listing and the child fetch+# returns 404, which must not fail the whole sync.+SERVER_SNAPSHOTS_FANOUT = DependentEndpointConfig(+ parent_name="Servers",+ resolve_param="server_id",+ resolve_field="id",+ include_from_parent=["id"],+ parent_field_renames={"id": "server_id"},+ child_response_actions=[{"status_code": 404, "action": "ignore"}],+)+++@frozen+class StratoEndpointConfig:+ name: str+ path: str+ # Every STRATO resource carries an ISO-8601 `creation_date`, which never changes after create.+ partition_key: str | None = "creation_date"+ primary_key: str | list[str] = "id"+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ default_incremental_field: str | None = None+ # Unused: STRATO list endpoints return the whole collection, so no page-size param is sent+ # (page_size_param=None everywhere). Kept to satisfy the fan-out builder's endpoint protocol.+ page_size: int = 100+ fanout: DependentEndpointConfig | None = None+++# The STRATO Cloud Server API documents `page`/`per_page` params, but collections are small and+# returned whole when the params are omitted, and the API exposes no server-side timestamp filter+# (only `sort` and free-text `q`), so every endpoint is an unpaginated full refresh.+STRATO_ENDPOINTS: dict[str, StratoEndpointConfig] = {+ "Servers": StratoEndpointConfig(name="Servers", path="/servers"),+ "Snapshots": StratoEndpointConfig(+ name="Snapshots",+ path="/servers/{server_id}/snapshots",+ # Snapshot ids are only documented as unique per server, so the parent id is part of the key.+ primary_key=["server_id", "id"],+ fanout=SERVER_SNAPSHOTS_FANOUT,+ ),+ "Images": StratoEndpointConfig(name="Images", path="/images"),+ "BlockStorages": StratoEndpointConfig(name="BlockStorages", path="/block_storages"),+ "SharedStorages": StratoEndpointConfig(name="SharedStorages", path="/shared_storages"),+ "FirewallPolicies": StratoEndpointConfig(name="FirewallPolicies", path="/firewall_policies"),+ "LoadBalancers": StratoEndpointConfig(name="LoadBalancers", path="/load_balancers"),+ "PublicIps": StratoEndpointConfig(name="PublicIps", path="/public_ips"),+ "PrivateNetworks": StratoEndpointConfig(name="PrivateNetworks", path="/private_networks"),+ "Vpns": StratoEndpointConfig(name="Vpns", path="/vpns"),+ "MonitoringPolicies": StratoEndpointConfig(name="MonitoringPolicies", path="/monitoring_policies"),+ "SshKeys": StratoEndpointConfig(name="SshKeys", path="/ssh_keys"),+ "Users": StratoEndpointConfig(name="Users", path="/users"),+ "Roles": StratoEndpointConfig(name="Roles", path="/roles"),+}++ENDPOINTS = tuple(STRATO_ENDPOINTS)++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in STRATO_ENDPOINTS.items()+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/strato/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/strato/source.pyindex 936bbdc925df..0dc6f8b97e04 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/strato/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/strato/source.py@@ -1,26 +1,115 @@-from typing import cast+from typing import Optional, cast-from products.warehouse_sources.backend.facade.source_config import DataWarehouseSourceCategory, SourceConfig+from products.warehouse_sources.backend.facade.source_config import (+ DataWarehouseSourceCategory,+ 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.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.schema import (+ SourceSchema,+ build_endpoint_schemas,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponsefrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.strato import StratoSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.strato.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.strato.strato import (+ strato_source,+ validate_credentials as validate_strato_credentials,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.registerclass StratoSource(SimpleSource[StratoSourceConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+ supported_versions = ("v1",)+ default_version = "v1"+ api_docs_url = "https://scp-api.strato.de/documentation/v1/en/api/documentation.html"+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.STRATO+ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error": "Invalid STRATO API token. Create a token in the STRATO CloudPanel under Management > Users and update the source.",+ "403 Client Error": "Your STRATO API user is not allowed to read this resource. Check the user's role permissions in the STRATO CloudPanel.",+ "406 Client Error": "Your STRATO API user only accepts requests from specific IP addresses. Remove the IP restriction for this API user in the STRATO CloudPanel.",+ }++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.strato.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_schemas(+ self,+ config: StratoSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ api_version: str | None = None,+ ) -> list[SourceSchema]:+ return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names)++ def validate_credentials(+ self,+ config: StratoSourceConfig,+ team_id: int,+ schema_name: Optional[str] = None,+ api_version: str | None = None,+ ) -> tuple[bool, str | None]:+ return validate_strato_credentials(config.api_token)++ def source_for_pipeline(self, config: StratoSourceConfig, inputs: SourceInputs) -> SourceResponse:+ return strato_source(+ api_token=config.api_token,+ endpoint=inputs.schema_name,+ team_id=inputs.team_id,+ job_id=inputs.job_id,+ )+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=ExternalDataSourceType.STRATO,category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,- label="Strato",+ label="STRATO",+ caption=(+ "Sync your STRATO ServerCloud resources, such as servers, snapshots, images, storage, "+ "networking, and users, into the PostHog Data warehouse.\n\n"+ "This source covers the STRATO ServerCloud product only. To get an API token, open the "+ "STRATO CloudPanel, go to **Management** > **Users**, select or create a user, enable "+ "API access, and copy the API key."+ ),iconPath="/static/services/strato.png",- keywords=["hosting", "web hosting", "webserver"],- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/strato",+ keywords=["hosting", "servercloud", "cloud server"],+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_token",+ label="API token",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ ],+ ),+ releaseStatus=ReleaseStatus.ALPHA,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/strato/strato.py b/products/warehouse_sources/backend/temporal/data_imports/sources/strato/strato.pynew file mode 100644index 000000000000..2a6c7c59f3ae--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/strato/strato.py@@ -0,0 +1,174 @@+from collections.abc import Callable, Iterable+from typing import Any, cast++from requests.exceptions import RequestException++from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import (+ RESTAPIConfig,+ rest_api_resource,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (+ build_dependent_resource,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (+ SinglePagePaginator,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (+ ClientConfig,+ EndpointResource,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.strato.settings import (+ STRATO_BASE_URL,+ STRATO_ENDPOINTS,+ StratoEndpointConfig,+)++# Connect/read timeout for import requests. Unset means requests never time out, which would let+# a stalled STRATO host block an import worker indefinitely (the ten-second timeout on+# /ping_auth in validate_credentials below is separate and does not apply here).+REQUEST_TIMEOUT_SECONDS = 30.0+++def _client_config(api_token: str) -> ClientConfig:+ return {+ "base_url": STRATO_BASE_URL,+ "auth": {"type": "api_key", "name": "X-TOKEN", "api_key": api_token, "location": "header"},+ "headers": {"Accept": "application/json"},+ # Every list endpoint returns the whole collection in one response (see settings.py).+ "paginator": SinglePagePaginator(),+ # `requests` only strips its built-in `Authorization` header on a cross-origin redirect, so+ # the nonstandard `X-TOKEN` header would ride along to whatever host a 3xx points at. Refuse+ # to follow redirects so the token never leaves scp-api.strato.de.+ "allow_redirects": False,+ "request_timeout": REQUEST_TIMEOUT_SECONDS,+ # Server rows carry `first_password` and user rows carry a nested `api.key`; both are+ # credentials scrubbed by the data maps below, but only after the response is received.+ # The name-based sample scrubber doesn't specifically guarantee those field names, so+ # disable HTTP sample capture for this client rather than rely on it. Requests are still+ # metered and logged.+ "capture": False,+ }+++def _scrub_server_row(row: dict[str, Any]) -> dict[str, Any]:+ # `first_password` is the server's initial root password. It must never land in the warehouse.+ row.pop("first_password", None)+ return row+++def _scrub_user_row(row: dict[str, Any]) -> dict[str, Any]:+ # `api.key` is the account's API token, the same credential this source authenticates with.+ # It must never land in the warehouse.+ api = row.get("api")+ if isinstance(api, dict):+ api.pop("key", None)+ return row+++_DATA_MAPS: dict[str, Callable[[dict[str, Any]], dict[str, Any]]] = {+ "Servers": _scrub_server_row,+ "Users": _scrub_user_row,+}+++def get_resource(endpoint: str) -> EndpointResource:+ """Builds a top-level (non-fan-out) resource. `Snapshots` fans out from `Servers` and is+ built via `build_dependent_resource` in `strato_source`."""+ config = STRATO_ENDPOINTS[endpoint]+ if config.fanout:+ raise ValueError(f"Fan-out endpoint '{endpoint}' must use the fan-out path")++ resource: EndpointResource = {+ "name": config.name,+ "table_name": config.name,+ "write_disposition": "replace",+ "endpoint": {"path": config.path},+ "table_format": "delta",+ }+ data_map = _DATA_MAPS.get(endpoint)+ if data_map is not None:+ resource["data_map"] = data_map+ return resource+++def _make_source_response(config: StratoEndpointConfig, items_fn: Callable[[], Iterable[Any]]) -> SourceResponse:+ primary_keys = config.primary_key if isinstance(config.primary_key, list) else [config.primary_key]+ return SourceResponse(+ name=config.name,+ items=items_fn,+ primary_keys=primary_keys,+ partition_count=1,+ partition_size=1,+ partition_mode="datetime" if config.partition_key else None,+ partition_format="month" if config.partition_key else None,+ partition_keys=[config.partition_key] if config.partition_key else None,+ )+++def strato_source(+ api_token: str,+ endpoint: str,+ team_id: int,+ job_id: str,+) -> SourceResponse:+ endpoint_config = STRATO_ENDPOINTS[endpoint]+ client_config = _client_config(api_token)++ if endpoint_config.fanout:+ dependent_resource = cast(+ Iterable[Any],+ build_dependent_resource(+ endpoint_configs=STRATO_ENDPOINTS,+ child_endpoint=endpoint,+ fanout=endpoint_config.fanout,+ client_config=client_config,+ path_format_values={},+ team_id=team_id,+ job_id=job_id,+ db_incremental_field_last_value=None,+ page_size_param=None,+ ),+ )+ return _make_source_response(endpoint_config, lambda: dependent_resource)++ config: RESTAPIConfig = {+ "client": client_config,+ "resource_defaults": {},+ "resources": [get_resource(endpoint)],+ }++ resource = rest_api_resource(config, team_id, job_id, None)+ return _make_source_response(endpoint_config, lambda: resource)+++def validate_credentials(api_token: str) -> tuple[bool, str | None]:+ try:+ # /ping_auth answers ["PONG"] when the token is valid, without touching any resource scope.+ # `allow_redirects=False`: keep the `X-TOKEN` header from being replayed to a redirect+ # target off scp-api.strato.de. A 3xx then falls through to the error return below.+ response = make_tracked_session(redact_values=(api_token,), allow_redirects=False).get(+ f"{STRATO_BASE_URL}/ping_auth",+ headers={"X-TOKEN": api_token, "Accept": "application/json"},+ timeout=10,+ )+ except RequestException as exc:+ return False, str(exc)++ if response.status_code == 200:+ return True, None+ if response.status_code == 401:+ return False, "Invalid STRATO API token. Create a token in the STRATO CloudPanel under Management > Users."+ if response.status_code == 406:+ return (+ False,+ "Your STRATO API user only accepts requests from specific IP addresses. "+ "Remove the IP restriction for this API user in the STRATO CloudPanel and try again.",+ )++ try:+ detail = response.json().get("message", response.text)+ except Exception:+ detail = response.text+ return False, str(detail)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/strato/tests/test_strato.py b/products/warehouse_sources/backend/temporal/data_imports/sources/strato/tests/test_strato.pynew file mode 100644index 000000000000..66297d7bf755--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/strato/tests/test_strato.py@@ -0,0 +1,199 @@+from typing import Any, cast++from unittest.mock import Mock, patch++from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (+ SinglePagePaginator,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.strato.strato import (+ get_resource,+ strato_source,+ validate_credentials,+)+++class _FakeDltResource:+ """Lightweight stand-in for a DltResource returned by rest_api_resources.++ ``process_parent_data_item`` injects parent fields as ``_<parent_resource>_<field>``+ (see ``make_parent_key_name``), so test data should include those prefixed keys to+ exercise the row mappers.+ """++ def __init__(self, name: str, rows: list[dict]) -> None:+ self.name = name+ self._rows = rows++ def add_map(self, mapper):+ self._rows = [mapper(dict(row)) for row in self._rows]+ return self++ def __iter__(self):+ return iter(self._rows)+++def _response(status_code: int = 200, json_body: Any = None, text: str = "") -> Mock:+ response = Mock()+ response.status_code = status_code+ response.json.return_value = json_body if json_body is not None else {}+ response.text = text+ return response+++class TestValidateCredentials:+ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.strato.strato.make_tracked_session")+ def test_valid_token(self, mock_make_session) -> None:+ mock_make_session.return_value.get.return_value = _response(200, ["PONG"])++ result = validate_credentials("valid-token")++ assert result == (True, None)++ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.strato.strato.make_tracked_session")+ def test_invalid_token(self, mock_make_session) -> None:+ # Verbatim error body the live API returns for a bad token.+ mock_make_session.return_value.get.return_value = _response(+ 401, {"type": "UNAUTHORIZED", "message": "The Token you are using is not valid", "errors": None}+ )++ valid, message = validate_credentials("bad-token")++ assert valid is False+ assert message is not None+ assert "Invalid STRATO API token" in message++ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.strato.strato.make_tracked_session")+ def test_ip_restricted_token_points_to_the_restriction(self, mock_make_session) -> None:+ mock_make_session.return_value.get.return_value = _response(406)++ valid, message = validate_credentials("token")++ assert valid is False+ assert message is not None+ assert "IP" in message++ @parameterized.expand([(500,), (503,)])+ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.strato.strato.make_tracked_session")+ def test_other_error_uses_response_message(self, status_code: int, mock_make_session) -> None:+ mock_make_session.return_value.get.return_value = _response(status_code, {"message": "Internal error"})++ result = validate_credentials("token")++ assert result == (False, "Internal error")++ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.strato.strato.make_tracked_session")+ def test_network_error_returns_false(self, mock_make_session) -> None:+ from requests.exceptions import ConnectionError++ mock_make_session.return_value.get.side_effect = ConnectionError("boom")++ result = validate_credentials("token")++ assert result == (False, "boom")+++class TestGetResource:+ def test_top_level_shape_is_unpaginated_full_refresh(self) -> None:+ resource = get_resource("Images")++ assert resource["write_disposition"] == "replace"+ endpoint = cast(dict[str, Any], resource["endpoint"])+ assert endpoint["path"] == "/images"+ assert "params" not in endpoint+ assert "data_map" not in resource++ def test_rejects_fanout_endpoint(self) -> None:+ try:+ get_resource("Snapshots")+ raise AssertionError("expected ValueError for fan-out endpoint")+ except ValueError as exc:+ assert "Snapshots" in str(exc)+++class TestSecretScrubbing:+ def test_server_rows_drop_the_initial_root_password(self) -> None:+ data_map = get_resource("Servers")["data_map"]+ assert data_map is not None++ row = cast(dict[str, Any], data_map({"id": "srv1", "name": "web-1", "first_password": "hunter2"}))++ assert "first_password" not in row+ assert row["id"] == "srv1"+ assert row["name"] == "web-1"++ def test_user_rows_drop_the_api_key_but_keep_other_api_settings(self) -> None:+ data_map = get_resource("Users")["data_map"]+ assert data_map is not None++ row = cast(+ dict[str, Any],+ data_map({"id": "u1", "api": {"active": True, "key": "secret-token", "allowed_ips": ["1.2.3.4"]}}),+ )++ assert row["api"] == {"active": True, "allowed_ips": ["1.2.3.4"]}++ @parameterized.expand(+ [+ ("Servers", {"id": "srv1"}),+ ("Users", {"id": "u1"}),+ ("Users", {"id": "u1", "api": None}),+ ]+ )+ def test_rows_without_secret_fields_pass_through(self, endpoint: str, row: dict[str, Any]) -> None:+ data_map = get_resource(endpoint)["data_map"]+ assert data_map is not None++ assert data_map(dict(row)) == row+++class TestStratoSourceTopLevel:+ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.strato.strato.rest_api_resource")+ def test_servers_builds_response(self, mock_rest_api_resource) -> None:+ mock_rest_api_resource.return_value = Mock()++ resp = strato_source(api_token="token", endpoint="Servers", team_id=1, job_id="job-1")++ assert resp.name == "Servers"+ assert resp.primary_keys == ["id"]+ assert resp.partition_mode == "datetime"+ assert resp.partition_keys == ["creation_date"]+++class TestStratoFanout:+ @patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout.rest_api_resources"+ )+ def test_snapshot_rows_carry_the_parent_server_id(self, mock_rest_api_resources) -> None:+ mock_rest_api_resources.return_value = [+ _FakeDltResource("Servers", [{"id": "srv1"}]),+ _FakeDltResource("Snapshots", [{"id": "snap1", "_Servers_id": "srv1"}]),+ ]++ resp = strato_source(api_token="token", endpoint="Snapshots", team_id=1, job_id="job-1")++ assert resp.primary_keys == ["server_id", "id"]+ rows = list(cast(Any, resp.items()))+ assert len(rows) == 1+ assert rows[0]["server_id"] == "srv1"+ assert "_Servers_id" not in rows[0]++ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.strato.strato.build_dependent_resource")+ def test_client_sends_token_header_and_refuses_redirects(self, mock_build) -> None:+ mock_build.return_value = iter([])++ strato_source(api_token="secret-token", endpoint="Snapshots", team_id=1, job_id="job-1")++ _, kwargs = mock_build.call_args+ client_config = kwargs["client_config"]+ assert client_config["auth"] == {+ "type": "api_key",+ "name": "X-TOKEN",+ "api_key": "secret-token",+ "location": "header",+ }+ assert client_config["allow_redirects"] is False+ assert isinstance(client_config["paginator"], SinglePagePaginator)+ # STRATO list endpoints take no page-size param; sending one would be undocumented.+ assert kwargs["page_size_param"] is Nonediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/strato/tests/test_strato_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/strato/tests/test_strato_source.pynew file mode 100644index 000000000000..5ff8020e6c00--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/strato/tests/test_strato_source.py@@ -0,0 +1,19 @@+from products.warehouse_sources.backend.facade.source_config import ReleaseStatus+from products.warehouse_sources.backend.temporal.data_imports.sources.strato.source import StratoSource+++class TestStratoSourceConfig:+ def setup_method(self) -> None:+ self.source = StratoSource()++ def test_source_config_is_released_and_alpha(self) -> None:+ config = self.source.get_source_config++ # A finished source must ship with no `unreleasedSource` flag — see+ # implementing-warehouse-sources skill.+ assert config.unreleasedSource is None+ assert config.releaseStatus == ReleaseStatus.ALPHA++ def test_lists_tables_without_credentials(self) -> None:+ # get_schemas iterates a static endpoint catalog with no I/O.+ assert self.source.lists_tables_without_credentials is True