: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 personio import source (#62893)
Tom Owers18b9646be029
diff --git a/posthog/temporal/data_imports/sources/SOURCES.md b/posthog/temporal/data_imports/sources/SOURCES.mdindex 9e2a0d43ffdc..e5291f076671 100644--- a/posthog/temporal/data_imports/sources/SOURCES.md+++ b/posthog/temporal/data_imports/sources/SOURCES.md@@ -113,6 +113,7 @@ the row lists both.| pagerduty | HTTP | requests | ✅ || pandadoc | HTTP | requests | ✅ || pendo | HTTP | requests | ✅ |+| personio | HTTP | requests | ✅ || pingdom | HTTP | requests | ✅ || pinterest_ads | HTTP | requests | ✅ || pipedrive | HTTP | requests | ✅ |@@ -278,7 +279,6 @@ doesn't conflict with concurrent PRs.- paylocity- paypal- pendo-- personio- plaid- planetscale- qualtricsdiff --git a/posthog/temporal/data_imports/sources/common/http/sampling.py b/posthog/temporal/data_imports/sources/common/http/sampling.pyindex f4f677569fed..dd149798dc27 100644--- a/posthog/temporal/data_imports/sources/common/http/sampling.py+++ b/posthog/temporal/data_imports/sources/common/http/sampling.py@@ -21,9 +21,10 @@ Goals:`*` defaults.- Per-rule capture limit enforced via Redis `INCR` so multiple workersshare the same counter.-- All response keys preserved — values pass through `scrubadub`. Known- auth headers are dropped wholesale; auth-bearing query params are- scrubbed by `url_utils.scrub_url`.+- Response values pass through `scrubadub`; auth-bearing JSON keys+ (`access_token`, `client_secret`, …) are dropped wholesale by name.+ Known auth headers are dropped wholesale; auth-bearing query params+ are scrubbed by `url_utils.scrub_url`."""from __future__ import annotations@@ -47,6 +48,7 @@ from posthog.temporal.data_imports.sources.common.http.url_utils import (scrub_url,)from posthog.temporal.data_imports.sources.common.sample_scrub import (+ REDACT_FIELD_NAMES,CaptureConfig,CaptureRule,scrub_string as _scrub_string,@@ -285,7 +287,10 @@ def _scrub_body(body: Any) -> Any:if isinstance(body, str):parsed = _try_json(body)if parsed is not None:- return _scrub_value(parsed)+ # Drop auth-bearing keys (e.g. an OAuth token-exchange response's+ # `access_token`) before scrubadub, which can't recognise opaque+ # tokens by value alone.+ return _scrub_value(_redact_field_keys(parsed))# OAuth token-exchange / refresh / authorization-code flows post# `application/x-www-form-urlencoded` bodies like# `grant_type=refresh_token&client_id=...&client_secret=...&refresh_token=...`.@@ -299,6 +304,19 @@ def _scrub_body(body: Any) -> Any:return _scrub_value(body)+def _redact_field_keys(value: Any) -> Any:+ """Recursively replace auth-bearing dict values (matched by key name against+ `REDACT_FIELD_NAMES`) with a placeholder — mirrors the gRPC sample path."""+ if isinstance(value, dict):+ return {+ k: (_REDACTED_FORM_VALUE if str(k).lower() in REDACT_FIELD_NAMES else _redact_field_keys(v))+ for k, v in value.items()+ }+ if isinstance(value, list):+ return [_redact_field_keys(item) for item in value]+ return value++def _try_json(text: str) -> Any | None:text_stripped = text.lstrip()if not text_stripped or text_stripped[0] not in "{[":diff --git a/posthog/temporal/data_imports/sources/common/test/test_http_sampling.py b/posthog/temporal/data_imports/sources/common/test/test_http_sampling.pyindex 1fd83264d8b9..dd3cf5ae8b62 100644--- a/posthog/temporal/data_imports/sources/common/test/test_http_sampling.py+++ b/posthog/temporal/data_imports/sources/common/test/test_http_sampling.py@@ -433,6 +433,23 @@ def test_scrub_body_handles_json_list():assert "email" in out[0]+def test_scrub_body_redacts_oauth_json_secrets():+ out = _scrub_body('{"access_token": "tok_live_abc", "token_type": "Bearer", "expires_in": 86400}')+ assert isinstance(out, dict)+ # Key preserved, secret value dropped; non-secret fields flow through.+ assert out["access_token"] == "REDACTED"+ assert out["token_type"] == "Bearer"+ assert out["expires_in"] == 86400+++def test_scrub_body_redacts_nested_json_secrets():+ out = _scrub_body('{"data": {"refresh_token": "rt_secret", "client_secret": "cs_secret", "page": 2}}')+ assert isinstance(out, dict)+ assert out["data"]["refresh_token"] == "REDACTED"+ assert out["data"]["client_secret"] == "REDACTED"+ assert out["data"]["page"] == 2++def test_scrub_body_passes_through_non_json_string():out = _scrub_body("just a string")assert isinstance(out, str)diff --git a/posthog/temporal/data_imports/sources/generated_configs.py b/posthog/temporal/data_imports/sources/generated_configs.pyindex 74a4135d6696..09c620e958c3 100644--- a/posthog/temporal/data_imports/sources/generated_configs.py+++ b/posthog/temporal/data_imports/sources/generated_configs.py@@ -965,7 +965,8 @@ class PendoSourceConfig(config.Config):@config.configclass PersonioSourceConfig(config.Config):- pass+ client_id: str+ client_secret: str@config.configdiff --git a/posthog/temporal/data_imports/sources/personio/personio.py b/posthog/temporal/data_imports/sources/personio/personio.pynew file mode 100644index 000000000000..f52085c7f682--- /dev/null+++ b/posthog/temporal/data_imports/sources/personio/personio.py@@ -0,0 +1,225 @@+import dataclasses+from collections.abc import Iterator+from datetime import UTC, date, datetime+from typing import Any, Optional+from urllib.parse import urlencode, urlparse++import requests+from structlog.types import FilteringBoundLogger+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter++from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+from posthog.temporal.data_imports.sources.common.http import make_tracked_session+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from posthog.temporal.data_imports.sources.personio.settings import PERSONIO_ENDPOINTS, PersonioEndpointConfig++PERSONIO_BASE_URL = "https://api.personio.de"+PERSONIO_API_HOST = "api.personio.de"+TOKEN_URL = f"{PERSONIO_BASE_URL}/v2/auth/token"+REQUEST_TIMEOUT_SECONDS = 60+# ~200 req/min per credential (persons 300/min); 429s carry X-RateLimit headers+# but exponential backoff is sufficient.+MAX_RETRY_ATTEMPTS = 5+# Raised (and matched by get_non_retryable_errors) when a freshly minted token is+# still rejected — the credential was revoked or lost its scope mid-sync.+AUTH_REVOKED_ERROR = "Personio rejected a freshly minted access token (401)"+++class PersonioRetryableError(Exception):+ pass+++class PersonioAuthError(Exception):+ pass+++def _is_personio_url(url: str) -> bool:+ """True only for https URLs whose host is api.personio.de. Guards against a+ tampered pagination/resume URL redirecting our authenticated request (along+ with the bearer token) to an internal host (SSRF)."""+ parsed = urlparse(url)+ return parsed.scheme == "https" and (parsed.hostname or "").lower() == PERSONIO_API_HOST+++class PersonioResumeConfig:+ # Personio v2 paginates via _meta.links.next.href, a self-contained URL+ # (opaque cursor), so the URL is all we persist.+ next_url: str+++def _get_session(client_secret: str) -> requests.Session:+ # allow_redirects=False so a redirect chain can't bypass the host check below.+ return make_tracked_session(redact_values=(client_secret,), allow_redirects=False)+++def _mint_token(session: requests.Session, client_id: str, client_secret: str) -> str:+ """Exchange client credentials for a bearer token (~24h lifetime)."""+ response = session.post(+ TOKEN_URL,+ data={+ "grant_type": "client_credentials",+ "client_id": client_id,+ "client_secret": client_secret,+ },+ timeout=REQUEST_TIMEOUT_SECONDS,+ )+ response.raise_for_status()+ return response.json()["access_token"]+++def _format_updated_at(value: Any) -> str:+ """Format an incremental cursor for Personio's RFC3339 date-time filters."""+ if isinstance(value, datetime):+ dt = value if value.tzinfo else value.replace(tzinfo=UTC)+ return dt.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%SZ")+ if isinstance(value, date):+ return value.strftime("%Y-%m-%dT00:00:00Z")+ return str(value)+++def _build_initial_url(+ config: PersonioEndpointConfig,+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+) -> str:+ params: dict[str, Any] = {"limit": config.page_size}++ if (+ config.incremental_param is not None+ and should_use_incremental_field+ and db_incremental_field_last_value is not None+ ):+ params[config.incremental_param] = _format_updated_at(db_incremental_field_last_value)++ return f"{PERSONIO_BASE_URL}{config.path}?{urlencode(params)}"+++def validate_credentials(client_id: str, client_secret: str) -> bool:+ """Confirm the credentials are valid by minting a token — scopes are+ granted per credential, so a successful mint is the only universal probe."""+ try:+ _mint_token(_get_session(client_secret), client_id, client_secret)+ return True+ except Exception:+ return False+++def get_rows(+ client_id: str,+ client_secret: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[PersonioResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+) -> Iterator[list[dict[str, Any]]]:+ config = PERSONIO_ENDPOINTS[endpoint]+ session = _get_session(client_secret)+ token = _mint_token(session, client_id, client_secret)++ resume_config = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ if resume_config is not None:+ url: str = resume_config.next_url+ # Only ever saved from a host-pinned next_url, but re-check so a tampered+ # Redis state can't redirect our authenticated request (SSRF).+ if not _is_personio_url(url):+ raise ValueError(f"Personio resume state contains an unexpected URL: {url!r}")+ logger.debug(f"Personio: resuming {endpoint} from URL: {url}")+ else:+ url = _build_initial_url(config, should_use_incremental_field, db_incremental_field_last_value)++ @retry(+ retry=retry_if_exception_type((PersonioRetryableError, requests.ReadTimeout, requests.ConnectionError)),+ stop=stop_after_attempt(MAX_RETRY_ATTEMPTS),+ wait=wait_exponential_jitter(initial=1, max=60),+ reraise=True,+ )+ def fetch_page(page_url: str) -> dict[str, Any]:+ nonlocal token+ response = session.get(page_url, headers={"Authorization": f"Bearer {token}"}, timeout=REQUEST_TIMEOUT_SECONDS)++ # Tokens last ~24h; re-mint once if the sync outlives one.+ if response.status_code == 401:+ token = _mint_token(session, client_id, client_secret)+ response = session.get(+ page_url, headers={"Authorization": f"Bearer {token}"}, timeout=REQUEST_TIMEOUT_SECONDS+ )+ # A freshly minted token still rejected means the credential was revoked+ # or lost its scope mid-sync — retrying never succeeds, so fail fast with+ # a friendly message instead of a raw HTTPError carrying the data URL.+ if response.status_code == 401:+ raise PersonioAuthError(+ f"{AUTH_REVOKED_ERROR}. The API credential may have been revoked or had its scope removed."+ )++ if response.status_code == 429 or response.status_code >= 500:+ raise PersonioRetryableError(+ f"Personio API error (retryable): status={response.status_code}, url={page_url}"+ )++ if not response.ok:+ logger.error(f"Personio API error: status={response.status_code}, body={response.text}, url={page_url}")+ response.raise_for_status()++ return response.json()++ while True:+ data = fetch_page(url)+ items = data.get("_data", []) or []++ if items:+ yield items++ # Guard against malformed responses where intermediate values aren't dicts.+ next_url = None+ meta = data.get("_meta")+ links = meta.get("links") if isinstance(meta, dict) else None+ next_obj = links.get("next") if isinstance(links, dict) else None+ if isinstance(next_obj, dict):+ next_url = next_obj.get("href")+ if not next_url or not items:+ break++ # Only follow pagination URLs that stay on api.personio.de so a tampered+ # response can't point our authenticated request at an internal host (SSRF).+ if not _is_personio_url(next_url):+ logger.warning(f"Personio: stopping pagination, next URL is not on {PERSONIO_API_HOST}: {next_url!r}")+ break++ # Save state AFTER yielding the page so a crash re-yields the last page+ # (merge dedupes on primary key) rather than skipping it.+ resumable_source_manager.save_state(PersonioResumeConfig(next_url=next_url))+ url = next_url+++def personio_source(+ client_id: str,+ client_secret: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[PersonioResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+) -> SourceResponse:+ config = PERSONIO_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ client_id=client_id,+ client_secret=client_secret,+ 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=[config.primary_key],+ 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,+ sort_mode="asc",+ )diff --git a/posthog/temporal/data_imports/sources/personio/settings.py b/posthog/temporal/data_imports/sources/personio/settings.pynew file mode 100644index 000000000000..fd90ecfdd97c--- /dev/null+++ b/posthog/temporal/data_imports/sources/personio/settings.py@@ -0,0 +1,63 @@+from dataclasses import dataclass, field+from typing import Optional++from products.data_warehouse.backend.types import IncrementalField, IncrementalFieldType++_UPDATED_AT_INCREMENTAL_FIELDS: list[IncrementalField] = [+ {+ "label": "updated_at",+ "type": IncrementalFieldType.DateTime,+ "field": "updated_at",+ "field_type": IncrementalFieldType.DateTime,+ },+]+++@dataclass+class PersonioEndpointConfig:+ name: str+ path: str+ # OAuth scope the endpoint needs (surfaced in the source caption).+ scope: str+ primary_key: str = "id"+ # Server-side updated_at filter param. Personio v2 is inconsistent per+ # endpoint: persons use strict `.gt`, the period endpoints use `.gte`.+ incremental_param: Optional[str] = None+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ # Max page size the endpoint accepts (persons cap at 50, periods at 100).+ page_size: int = 100+ # Stable creation-time field used for datetime partitioning.+ partition_key: Optional[str] = None+++PERSONIO_ENDPOINTS: dict[str, PersonioEndpointConfig] = {+ "persons": PersonioEndpointConfig(+ name="persons",+ path="/v2/persons",+ scope="personio:persons:read",+ incremental_param="updated_at.gt",+ incremental_fields=list(_UPDATED_AT_INCREMENTAL_FIELDS),+ page_size=50,+ partition_key="created_at",+ ),+ "absence_periods": PersonioEndpointConfig(+ name="absence_periods",+ path="/v2/absence-periods",+ scope="personio:absences:read",+ incremental_param="updated_at.gte",+ incremental_fields=list(_UPDATED_AT_INCREMENTAL_FIELDS),+ ),+ "attendance_periods": PersonioEndpointConfig(+ name="attendance_periods",+ path="/v2/attendance-periods",+ scope="personio:attendances:read",+ incremental_param="updated_at.gte",+ incremental_fields=list(_UPDATED_AT_INCREMENTAL_FIELDS),+ ),+}++ENDPOINTS = tuple(PERSONIO_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in PERSONIO_ENDPOINTS.items() if config.incremental_fields+}diff --git a/posthog/temporal/data_imports/sources/personio/source.py b/posthog/temporal/data_imports/sources/personio/source.pyindex a68a2847ce79..971b6e52b645 100644--- a/posthog/temporal/data_imports/sources/personio/source.py+++ b/posthog/temporal/data_imports/sources/personio/source.py@@ -1,29 +1,127 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,)-from posthog.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceInputs, SourceResponse+from posthog.temporal.data_imports.sources.common.base import FieldType, ResumableSourcefrom posthog.temporal.data_imports.sources.common.registry import SourceRegistry+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from posthog.temporal.data_imports.sources.common.schema import SourceSchemafrom posthog.temporal.data_imports.sources.generated_configs import PersonioSourceConfig+from posthog.temporal.data_imports.sources.personio.personio import (+ AUTH_REVOKED_ERROR,+ PersonioResumeConfig,+ personio_source,+ validate_credentials as validate_personio_credentials,+)+from posthog.temporal.data_imports.sources.personio.settings import ENDPOINTS, INCREMENTAL_FIELDSfrom products.data_warehouse.backend.types import ExternalDataSourceType@SourceRegistry.register-class PersonioSource(SimpleSource[PersonioSourceConfig]):+class PersonioSource(ResumableSource[PersonioSourceConfig, PersonioResumeConfig]):@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.PERSONIO+ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error: Unauthorized for url: https://api.personio.de/v2/auth/token": "Personio authentication failed. Please check your client ID and client secret.",+ "400 Client Error: Bad Request for url: https://api.personio.de/v2/auth/token": "Personio authentication failed. Please check your client ID and client secret.",+ "403 Client Error: Forbidden for url: https://api.personio.de": "Personio denied access. Please check that your API credential has the required scope for this dataset.",+ AUTH_REVOKED_ERROR: "Personio authentication failed mid-sync. Please check that your API credential is still valid and has the required scope.",+ }+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.PERSONIO,label="Personio",+ caption="""Enter your Personio API credentials to pull your Personio HR data into the PostHog Data warehouse.++An admin can create API credentials in Personio under Settings > Integrations > API credentials. Grant the read scopes for the datasets you want to sync (`personio:persons:read`, `personio:absences:read`, `personio:attendances:read`) and whitelist the employee attributes you need — attributes that aren't whitelisted are silently omitted from responses.""",iconPath="/static/services/personio.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/personio",+ releaseStatus=ReleaseStatus.ALPHA,+ fields=cast(+ list[FieldType],+ [+ 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_schemas(+ self,+ config: PersonioSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ schemas = [+ SourceSchema(+ name=endpoint,+ supports_incremental=INCREMENTAL_FIELDS.get(endpoint) is not None,+ supports_append=INCREMENTAL_FIELDS.get(endpoint) is not None,+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),+ )+ 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: PersonioSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ if validate_personio_credentials(config.client_id, config.client_secret):+ return True, None++ return False, "Invalid Personio API credentials"++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[PersonioResumeConfig]:+ return ResumableSourceManager[PersonioResumeConfig](inputs, PersonioResumeConfig)++ def source_for_pipeline(+ self,+ config: PersonioSourceConfig,+ resumable_source_manager: ResumableSourceManager[PersonioResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return personio_source(+ client_id=config.client_id,+ client_secret=config.client_secret,+ 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/posthog/temporal/data_imports/sources/personio/tests/test_personio.py b/posthog/temporal/data_imports/sources/personio/tests/test_personio.pynew file mode 100644index 000000000000..2630936018d1--- /dev/null+++ b/posthog/temporal/data_imports/sources/personio/tests/test_personio.py@@ -0,0 +1,245 @@+from datetime import UTC, date, datetime+from typing import Any+from urllib.parse import parse_qs, urlparse++import pytest+from unittest import mock++import requests++from posthog.temporal.data_imports.sources.personio.personio import (+ AUTH_REVOKED_ERROR,+ PersonioAuthError,+ PersonioResumeConfig,+ _build_initial_url,+ _format_updated_at,+ get_rows,+ personio_source,+ validate_credentials,+)+from posthog.temporal.data_imports.sources.personio.settings import ENDPOINTS, PERSONIO_ENDPOINTS+++def _make_manager(resume_state: PersonioResumeConfig | None = None) -> mock.MagicMock:+ manager = mock.MagicMock()+ manager.can_resume.return_value = resume_state is not None+ manager.load_state.return_value = resume_state+ return manager+++def _token_response() -> mock.MagicMock:+ resp = mock.MagicMock()+ resp.json.return_value = {"access_token": "the-token", "token_type": "Bearer", "expires_in": 86400}+ resp.status_code = 200+ resp.ok = True+ return resp+++def _page_response(items: list[dict[str, Any]], next_url: str | None = None) -> mock.MagicMock:+ resp = mock.MagicMock()+ body: dict[str, Any] = {"_data": items, "_meta": {"links": {}}}+ if next_url:+ body["_meta"]["links"]["next"] = {"href": next_url}+ resp.json.return_value = body+ resp.status_code = 200+ resp.ok = True+ return resp+++class TestFormatUpdatedAt:+ @pytest.mark.parametrize(+ "value, expected",+ [+ (datetime(2024, 1, 2, 3, 4, 5, tzinfo=UTC), "2024-01-02T03:04:05Z"),+ (datetime(2024, 1, 2, 3, 4, 5), "2024-01-02T03:04:05Z"),+ (date(2024, 1, 2), "2024-01-02T00:00:00Z"),+ ("2024-01-02T03:04:05Z", "2024-01-02T03:04:05Z"),+ ],+ )+ def test_format_values(self, value, expected):+ assert _format_updated_at(value) == expected+++class TestBuildInitialUrl:+ def test_incremental_persons_uses_strict_gt_filter(self):+ url = _build_initial_url(+ PERSONIO_ENDPOINTS["persons"],+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2024, 1, 2, tzinfo=UTC),+ )+ query = parse_qs(urlparse(url).query)+ assert query["updated_at.gt"] == ["2024-01-02T00:00:00Z"]+ assert query["limit"] == ["50"]++ def test_incremental_absence_periods_uses_gte_filter(self):+ url = _build_initial_url(+ PERSONIO_ENDPOINTS["absence_periods"],+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2024, 1, 2, tzinfo=UTC),+ )+ query = parse_qs(urlparse(url).query)+ assert query["updated_at.gte"] == ["2024-01-02T00:00:00Z"]+ assert query["limit"] == ["100"]++ def test_full_refresh_has_no_filter(self):+ url = _build_initial_url(+ PERSONIO_ENDPOINTS["persons"],+ should_use_incremental_field=False,+ db_incremental_field_last_value=None,+ )+ query = parse_qs(urlparse(url).query)+ assert "updated_at.gt" not in query+ assert query["limit"] == ["50"]+++class TestValidateCredentials:+ @mock.patch("posthog.temporal.data_imports.sources.personio.personio.make_tracked_session")+ def test_valid_when_token_mints(self, mock_session):+ mock_session.return_value.post.return_value = _token_response()+ assert validate_credentials("id", "secret") is True++ @mock.patch("posthog.temporal.data_imports.sources.personio.personio.make_tracked_session")+ def test_invalid_when_token_mint_fails(self, mock_session):+ resp = mock.MagicMock()+ resp.raise_for_status.side_effect = requests.HTTPError("401 Client Error", response=resp)+ mock_session.return_value.post.return_value = resp+ assert validate_credentials("id", "secret") is False++ @mock.patch("posthog.temporal.data_imports.sources.personio.personio.make_tracked_session")+ def test_invalid_on_exception(self, mock_session):+ mock_session.return_value.post.side_effect = Exception("boom")+ assert validate_credentials("id", "secret") is False+++class TestGetRows:+ @mock.patch("posthog.temporal.data_imports.sources.personio.personio.make_tracked_session")+ def test_paginates_via_meta_next_link(self, mock_session):+ next_url = "https://api.personio.de/v2/persons?cursor=cur_abc&limit=50"+ mock_session.return_value.post.return_value = _token_response()+ mock_session.return_value.get.side_effect = [+ _page_response([{"id": "1"}], next_url=next_url),+ _page_response([{"id": "2"}]),+ ]++ manager = _make_manager()+ batches = list(get_rows("id", "secret", "persons", mock.MagicMock(), manager))++ assert [item["id"] for batch in batches for item in batch] == ["1", "2"]+ manager.save_state.assert_called_once()+ assert manager.save_state.call_args.args[0].next_url == next_url+ assert mock_session.return_value.get.call_args_list[1].args[0] == next_url++ @mock.patch("posthog.temporal.data_imports.sources.personio.personio.make_tracked_session")+ def test_requests_carry_bearer_token(self, mock_session):+ mock_session.return_value.post.return_value = _token_response()+ mock_session.return_value.get.return_value = _page_response([])++ manager = _make_manager()+ list(get_rows("id", "secret", "persons", mock.MagicMock(), manager))++ headers = mock_session.return_value.get.call_args.kwargs["headers"]+ assert headers["Authorization"] == "Bearer the-token"++ @mock.patch("posthog.temporal.data_imports.sources.personio.personio.make_tracked_session")+ def test_remints_token_on_401(self, mock_session):+ expired = mock.MagicMock()+ expired.status_code = 401+ expired.ok = False+ mock_session.return_value.post.return_value = _token_response()+ mock_session.return_value.get.side_effect = [expired, _page_response([{"id": "1"}])]++ manager = _make_manager()+ batches = list(get_rows("id", "secret", "persons", mock.MagicMock(), manager))++ assert batches == [[{"id": "1"}]]+ # One mint at start + one re-mint after the 401.+ assert mock_session.return_value.post.call_count == 2++ @mock.patch("posthog.temporal.data_imports.sources.personio.personio.make_tracked_session")+ def test_second_401_after_remint_raises_auth_error(self, mock_session):+ expired = mock.MagicMock()+ expired.status_code = 401+ expired.ok = False+ mock_session.return_value.post.return_value = _token_response()+ # Both the original and the post-remint GET return 401 (credential revoked mid-sync).+ mock_session.return_value.get.side_effect = [expired, expired]++ manager = _make_manager()+ with pytest.raises(PersonioAuthError) as exc:+ list(get_rows("id", "secret", "persons", mock.MagicMock(), manager))++ # The message must be matchable by get_non_retryable_errors so the job fails fast.+ assert AUTH_REVOKED_ERROR in str(exc.value)++ @mock.patch("posthog.temporal.data_imports.sources.personio.personio.make_tracked_session")+ def test_stops_pagination_when_next_url_is_foreign_host(self, mock_session):+ mock_session.return_value.post.return_value = _token_response()+ mock_session.return_value.get.return_value = _page_response(+ [{"id": "1"}], next_url="https://evil.example.com/v2/persons?cursor=x"+ )++ manager = _make_manager()+ batches = list(get_rows("id", "secret", "persons", mock.MagicMock(), manager))++ # The first page is yielded, but the off-host next URL is never followed or saved.+ assert batches == [[{"id": "1"}]]+ assert mock_session.return_value.get.call_count == 1+ manager.save_state.assert_not_called()++ @mock.patch("posthog.temporal.data_imports.sources.personio.personio.make_tracked_session")+ def test_resume_state_with_foreign_host_raises(self, mock_session):+ mock_session.return_value.post.return_value = _token_response()+ manager = _make_manager(PersonioResumeConfig(next_url="https://evil.example.com/v2/persons"))++ with pytest.raises(ValueError):+ list(get_rows("id", "secret", "persons", mock.MagicMock(), manager))++ mock_session.return_value.get.assert_not_called()++ @mock.patch("posthog.temporal.data_imports.sources.personio.personio.make_tracked_session")+ def test_resumes_from_saved_state(self, mock_session):+ mock_session.return_value.post.return_value = _token_response()+ mock_session.return_value.get.return_value = _page_response([{"id": "9"}])++ resume_url = "https://api.personio.de/v2/persons?cursor=cur_resume"+ manager = _make_manager(PersonioResumeConfig(next_url=resume_url))++ list(get_rows("id", "secret", "persons", mock.MagicMock(), manager))++ assert mock_session.return_value.get.call_args_list[0].args[0] == resume_url++ @mock.patch("posthog.temporal.data_imports.sources.personio.personio.make_tracked_session")+ def test_empty_page_stops_even_with_next_link(self, mock_session):+ mock_session.return_value.post.return_value = _token_response()+ mock_session.return_value.get.return_value = _page_response(+ [], next_url="https://api.personio.de/v2/persons?cursor=loop"+ )++ manager = _make_manager()+ batches = list(get_rows("id", "secret", "persons", mock.MagicMock(), manager))++ assert batches == []+ assert mock_session.return_value.get.call_count == 1+ manager.save_state.assert_not_called()+++class TestPersonioSourceResponse:+ @pytest.mark.parametrize("endpoint", list(ENDPOINTS))+ def test_response_metadata_per_endpoint(self, endpoint):+ config = PERSONIO_ENDPOINTS[endpoint]+ response = personio_source("id", "secret", endpoint, mock.MagicMock(), _make_manager())++ assert response.name == endpoint+ assert response.primary_keys == [config.primary_key]+ assert response.sort_mode == "asc"+ if config.partition_key:+ assert response.partition_mode == "datetime"+ assert response.partition_keys == [config.partition_key]+ else:+ assert response.partition_mode is None+ assert response.partition_keys is None++ @pytest.mark.parametrize("config", list(PERSONIO_ENDPOINTS.values()))+ def test_partition_keys_are_stable_creation_fields(self, config):+ if config.partition_key:+ assert config.partition_key == "created_at"diff --git a/posthog/temporal/data_imports/sources/personio/tests/test_personio_source.py b/posthog/temporal/data_imports/sources/personio/tests/test_personio_source.pynew file mode 100644index 000000000000..970777398dd1--- /dev/null+++ b/posthog/temporal/data_imports/sources/personio/tests/test_personio_source.py@@ -0,0 +1,145 @@+import pytest+from unittest import mock++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType++from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from posthog.temporal.data_imports.sources.generated_configs import PersonioSourceConfig+from posthog.temporal.data_imports.sources.personio.personio import PersonioResumeConfig+from posthog.temporal.data_imports.sources.personio.settings import ENDPOINTS, INCREMENTAL_FIELDS+from posthog.temporal.data_imports.sources.personio.source import PersonioSource++from products.data_warehouse.backend.types import ExternalDataSourceType+++class TestPersonioSource:+ def setup_method(self):+ self.source = PersonioSource()+ self.team_id = 123+ self.config = PersonioSourceConfig(client_id="client-id", client_secret="client-secret")++ def test_source_type(self):+ assert self.source.source_type == ExternalDataSourceType.PERSONIO++ def test_get_source_config(self):+ config = self.source.get_source_config++ assert config.name.value == "Personio"+ assert config.label == "Personio"+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.unreleasedSource is None+ assert config.iconPath == "/static/services/personio.png"++ field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]+ assert field_names == ["client_id", "client_secret"]++ def test_client_secret_field_is_secret_password(self):+ config = self.source.get_source_config+ secret_field = next(+ f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "client_secret"+ )+ assert secret_field.type == SourceFieldInputConfigType.PASSWORD+ assert secret_field.secret is True+ assert secret_field.required is True++ @pytest.mark.parametrize(+ "observed_error",+ [+ "401 Client Error: Unauthorized for url: https://api.personio.de/v2/auth/token",+ "400 Client Error: Bad Request for url: https://api.personio.de/v2/auth/token",+ "403 Client Error: Forbidden for url: https://api.personio.de/v2/persons?limit=50",+ "Personio rejected a freshly minted access token (401). The API credential may have been revoked or had its scope removed.",+ ],+ )+ def test_non_retryable_errors_match_auth_failures(self, observed_error):+ non_retryable_errors = self.source.get_non_retryable_errors()+ assert any(key in observed_error for key in non_retryable_errors)++ @pytest.mark.parametrize(+ "other_vendor_error",+ [+ "401 Client Error: Unauthorized for url: https://api.stripe.com/v1/customers",+ "500 Server Error for url: https://api.personio.de/v2/persons",+ # A mid-sync 401 on a data endpoint is handled by token re-mint, not disable.+ "401 Client Error: Unauthorized for url: https://api.personio.de/v2/persons",+ ],+ )+ def test_non_retryable_errors_does_not_match_unrelated(self, other_vendor_error):+ non_retryable_errors = self.source.get_non_retryable_errors()+ assert not any(key in other_vendor_error for key in non_retryable_errors)++ def test_get_schemas(self):+ schemas = self.source.get_schemas(self.config, self.team_id)++ assert {schema.name for schema in schemas} == set(ENDPOINTS)+ # All shipped endpoints expose a server-side updated_at filter.+ assert all(schema.supports_incremental for schema in schemas)+ assert all(schema.supports_append for schema in schemas)++ def test_schemas_advertise_updated_at_cursor(self):+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}++ assert schemas["persons"].incremental_fields == INCREMENTAL_FIELDS["persons"]+ assert [f["field"] for f in schemas["persons"].incremental_fields] == ["updated_at"]++ def test_get_schemas_filtered_by_names(self):+ schemas = self.source.get_schemas(self.config, self.team_id, names=["persons"])+ assert len(schemas) == 1+ assert schemas[0].name == "persons"++ def test_get_schemas_filtered_unknown_name_returns_empty(self):+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []++ @pytest.mark.parametrize(+ "mock_return, expected_valid, expected_message",+ [+ (True, True, None),+ (False, False, "Invalid Personio API credentials"),+ ],+ )+ @mock.patch("posthog.temporal.data_imports.sources.personio.source.validate_personio_credentials")+ def test_validate_credentials(self, mock_validate, mock_return, expected_valid, expected_message):+ mock_validate.return_value = mock_return++ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id)++ assert is_valid is expected_valid+ assert error_message == expected_message+ mock_validate.assert_called_once_with(self.config.client_id, self.config.client_secret)++ def test_get_resumable_source_manager_binds_resume_config(self):+ inputs = mock.MagicMock()+ manager = self.source.get_resumable_source_manager(inputs)++ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is PersonioResumeConfig++ @mock.patch("posthog.temporal.data_imports.sources.personio.source.personio_source")+ def test_source_for_pipeline_plumbs_arguments(self, mock_personio_source):+ inputs = mock.MagicMock()+ inputs.schema_name = "persons"+ inputs.should_use_incremental_field = True+ inputs.db_incremental_field_last_value = "2024-01-02T03:04:05Z"+ manager = mock.MagicMock()++ self.source.source_for_pipeline(self.config, manager, inputs)++ mock_personio_source.assert_called_once()+ kwargs = mock_personio_source.call_args.kwargs+ assert kwargs["client_id"] == "client-id"+ assert kwargs["client_secret"] == "client-secret"+ assert kwargs["endpoint"] == "persons"+ assert kwargs["resumable_source_manager"] is manager+ assert kwargs["should_use_incremental_field"] is True+ assert kwargs["db_incremental_field_last_value"] == "2024-01-02T03:04:05Z"++ @mock.patch("posthog.temporal.data_imports.sources.personio.source.personio_source")+ def test_source_for_pipeline_omits_last_value_on_full_refresh(self, mock_personio_source):+ inputs = mock.MagicMock()+ inputs.schema_name = "persons"+ inputs.should_use_incremental_field = False+ inputs.db_incremental_field_last_value = "2024-01-02T03:04:05Z"++ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)++ assert mock_personio_source.call_args.kwargs["db_incremental_field_last_value"] is None