: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 bamboohr import source (#61139)
Tom Owers212cca0bd7b8
diff --git a/posthog/temporal/data_imports/sources/SOURCES.md b/posthog/temporal/data_imports/sources/SOURCES.mdindex 6b6c681e839a..1422ec2d36eb 100644--- a/posthog/temporal/data_imports/sources/SOURCES.md+++ b/posthog/temporal/data_imports/sources/SOURCES.md@@ -46,6 +46,7 @@ the row lists both.| ------------- | --------------------------- | --------------------------------------------------------------- | --------------------------- || aircall | HTTP | requests | ✅ || attio | HTTP | requests + `rest_source.RESTClient` | ✅ |+| bamboohr | HTTP | requests | ✅ || bigquery | HTTP + gRPC | google-cloud-bigquery + bigquery-storage | ✅ (HTTP + gRPC) || bing_ads | HTTP (vendor SDK, SOAP) | bingads SDK | ⚠️ || buildbetter | HTTP | requests | ✅ |@@ -145,7 +146,6 @@ doesn't conflict with concurrent PRs.- ashby- auth0- azure_blob-- bamboohr- bigcommerce- box- braintreediff --git a/posthog/temporal/data_imports/sources/bamboohr/bamboohr.py b/posthog/temporal/data_imports/sources/bamboohr/bamboohr.pynew file mode 100644index 000000000000..27b0b4d0f5c1--- /dev/null+++ b/posthog/temporal/data_imports/sources/bamboohr/bamboohr.py@@ -0,0 +1,225 @@+import re+import dataclasses+from collections.abc import Iterator+from datetime import UTC, datetime, timedelta+from typing import Any, Optional, cast+from urllib.parse import urlencode++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.bamboohr.settings import BAMBOOHR_ENDPOINTS, BambooHREndpointConfig+from posthog.temporal.data_imports.sources.common.http import make_tracked_session+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager++# BambooHR's API is served through a single gateway host; the company subdomain is a path segment.+# Confirmed live: the gateway returns 401 (not 404) for the v1 paths below, so the route shape is correct.+BAMBOOHR_API_HOST = "https://api.bamboohr.com/api/gateway.php"+# Basic auth uses the API key as the username and any non-empty string as the password.+BAMBOOHR_BASIC_AUTH_PASSWORD = "x"+REQUEST_TIMEOUT_SECONDS = 60+# Credential validation is a single cheap probe; keep it snappy so source creation doesn't feel hung.+VALIDATE_TIMEOUT_SECONDS = 10+# Time-off endpoints require an explicit window; widen it enough to capture all history and pending future requests.+TIME_OFF_WINDOW_START = "2000-01-01"+TIME_OFF_FUTURE_DAYS = 730++# A BambooHR company subdomain is the "<company>" slug from <company>.bamboohr.com — letters, digits,+# and hyphens only. It's an editable, non-secret field spliced straight into the request path, so pin+# it to this allowlist before building any URL. Without it a value like "acme/v1/employees/123?" would+# inject extra path segments / query params and redirect the authenticated request (which carries the+# API key in its Basic auth header) at an arbitrary BambooHR endpoint.+SUBDOMAIN_PATTERN = re.compile(r"^[A-Za-z0-9][A-Za-z0-9-]{0,62}$")+INVALID_SUBDOMAIN_MESSAGE = (+ "Invalid BambooHR company subdomain. Use only the company name from your BambooHR URL "+ "(letters, digits, and hyphens)."+)+++class BambooHRRetryableError(Exception):+ pass+++def _validate_subdomain(subdomain: str) -> None:+ if not SUBDOMAIN_PATTERN.fullmatch(subdomain):+ raise ValueError(f"Invalid BambooHR subdomain: {subdomain!r}")+++class BambooHRResumeConfig:+ next_url: str+++def _base_url(subdomain: str) -> str:+ _validate_subdomain(subdomain)+ return f"{BAMBOOHR_API_HOST}/{subdomain}/v1"+++def _headers() -> dict[str, str]:+ return {"Accept": "application/json"}+++def _auth(api_key: str) -> tuple[str, str]:+ return (api_key, BAMBOOHR_BASIC_AUTH_PASSWORD)+++def _build_url(subdomain: str, config: BambooHREndpointConfig) -> str:+ url = f"{_base_url(subdomain)}/{config.path}"+ params: dict[str, str] = {}+ if config.requires_date_window:+ end = (datetime.now(UTC) + timedelta(days=TIME_OFF_FUTURE_DAYS)).strftime("%Y-%m-%d")+ params["start"] = TIME_OFF_WINDOW_START+ params["end"] = end+ if params:+ return f"{url}?{urlencode(params)}"+ return url+++def _extract_records(payload: Any, config: BambooHREndpointConfig) -> list[dict[str, Any]]:+ records: Any = payload+ if config.data_key is not None and isinstance(payload, dict):+ # Direct key access so a missing envelope key (e.g. an API change) fails loudly+ # rather than silently syncing zero rows.+ records = payload[config.data_key]++ if config.data_shape == "dict":+ # e.g. meta/users returns ``{"<id>": {...}}`` — flatten to the list of records.+ return cast(list[dict[str, Any]], list(records.values())) if isinstance(records, dict) else []++ return cast(list[dict[str, Any]], records) if isinstance(records, list) else []+++def _next_url(payload: Any) -> str | None:+ """Follow BambooHR's cursor pagination if the response advertises a next page.++ Classic endpoints (directory, meta, time off) return everything in a single response with no+ ``_links``, so this yields once. Cursor-paginated endpoints expose a full URL under ``_links.next``.+ """+ if not isinstance(payload, dict):+ return None+ links = payload.get("_links")+ if links is None:+ links = payload.get("links")+ if not isinstance(links, dict):+ return None+ next_link = links.get("next")+ # Only follow pagination URLs that stay on the canonical BambooHR gateway host, so a+ # tampered or compromised API response can't point our authenticated request at an internal+ # address (SSRF) and leak the API key carried in the Basic auth header.+ if isinstance(next_link, str) and next_link.startswith(BAMBOOHR_API_HOST):+ return next_link+ return None+++def validate_credentials(subdomain: str, api_key: str, schema_name: Optional[str] = None) -> tuple[bool, str | None]:+ """Cheap probe against ``meta/fields`` to confirm the subdomain + API key are genuine.++ A 403 means the key is valid but lacks scope for this endpoint — accept it at source-create+ (``schema_name is None``) since users may only grant the scopes they intend to sync.+ """+ try:+ url = f"{_base_url(subdomain)}/meta/fields"+ except ValueError:+ return False, INVALID_SUBDOMAIN_MESSAGE+ try:+ response = make_tracked_session().get(+ url, auth=_auth(api_key), headers=_headers(), timeout=VALIDATE_TIMEOUT_SECONDS+ )+ except Exception:+ return False, "Could not connect to BambooHR. Check the company subdomain and try again."++ if response.status_code == 200:+ return True, None+ if response.status_code == 401:+ return False, "Invalid BambooHR API key."+ if response.status_code == 404:+ return False, "BambooHR company subdomain not found. Use the subdomain from your BambooHR URL."+ if response.status_code == 403:+ if schema_name is None:+ return True, None+ return False, "Your BambooHR API key does not have permission to access this data."+ return False, f"BambooHR API returned an unexpected status code: {response.status_code}"+++def get_rows(+ subdomain: str,+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[BambooHRResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ config = BAMBOOHR_ENDPOINTS[endpoint]+ headers = _headers()+ auth = _auth(api_key)++ resume_config = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ if resume_config is not None:+ url = resume_config.next_url+ # Guard the persisted resume URL too — only ever saved from _next_url (host-pinned),+ # but re-check so a tampered Redis state can't redirect our authenticated request.+ if not url.startswith(BAMBOOHR_API_HOST):+ raise ValueError(f"BambooHR resume state contains an unexpected URL: {url!r}")+ logger.debug(f"BambooHR: resuming {endpoint} from URL: {url}")+ else:+ url = _build_url(subdomain, config)++ @retry(+ retry=retry_if_exception_type((BambooHRRetryableError, requests.ReadTimeout, requests.ConnectionError)),+ stop=stop_after_attempt(5),+ wait=wait_exponential_jitter(initial=1, max=30),+ reraise=True,+ )+ def fetch_page(page_url: str) -> Any:+ response = make_tracked_session().get(page_url, auth=auth, headers=headers, timeout=REQUEST_TIMEOUT_SECONDS)++ if response.status_code == 429 or response.status_code >= 500:+ raise BambooHRRetryableError(+ f"BambooHR API error (retryable): status={response.status_code}, url={page_url}"+ )++ if not response.ok:+ logger.error(f"BambooHR API error: status={response.status_code}, body={response.text}, url={page_url}")+ response.raise_for_status()++ return response.json()++ while True:+ payload = fetch_page(url)+ records = _extract_records(payload, config)+ next_url = _next_url(payload)++ if records:+ yield records+ # Save state only after yielding so a crash re-yields the last batch (merge dedupes on PK)+ # rather than skipping it.+ if next_url:+ resumable_source_manager.save_state(BambooHRResumeConfig(next_url=next_url))++ if not next_url:+ break++ url = next_url+++def bamboohr_source(+ subdomain: str,+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[BambooHRResumeConfig],+) -> SourceResponse:+ config = BAMBOOHR_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ subdomain=subdomain,+ api_key=api_key,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ ),+ primary_keys=config.primary_keys,+ )diff --git a/posthog/temporal/data_imports/sources/bamboohr/settings.py b/posthog/temporal/data_imports/sources/bamboohr/settings.pynew file mode 100644index 000000000000..0a88057fbde4--- /dev/null+++ b/posthog/temporal/data_imports/sources/bamboohr/settings.py@@ -0,0 +1,69 @@+from dataclasses import dataclass, field+from typing import Literal++from products.data_warehouse.backend.types import IncrementalField++# How records are laid out in a BambooHR JSON response.+# "list" — the records are a JSON array (either the whole body or under ``data_key``)+# "dict" — the records are a JSON object keyed by id (e.g. ``meta/users``); we take ``.values()``+DataShape = Literal["list", "dict"]+++@dataclass+class BambooHREndpointConfig:+ name: str+ # Path relative to ``/api/gateway.php/{subdomain}/v1/``.+ path: str+ primary_keys: list[str]+ # JSON key holding the records, or ``None`` when the body itself is the collection.+ data_key: str | None = None+ data_shape: DataShape = "list"+ # Some endpoints (time off) reject requests without an explicit date window.+ requires_date_window: bool = False+ # No BambooHR endpoint we ship exposes a verified server-side "modified since" filter+ # that also returns full records, so every stream is full-refresh for now. See bamboohr.py.+ incremental_fields: list[IncrementalField] = field(default_factory=list)+++BAMBOOHR_ENDPOINTS: dict[str, BambooHREndpointConfig] = {+ "employees": BambooHREndpointConfig(+ name="employees",+ path="employees/directory",+ data_key="employees",+ primary_keys=["id"],+ ),+ "time_off_requests": BambooHREndpointConfig(+ name="time_off_requests",+ path="time_off/requests",+ primary_keys=["id"],+ requires_date_window=True,+ ),+ "time_off_types": BambooHREndpointConfig(+ name="time_off_types",+ path="meta/time_off/types",+ data_key="timeOffTypes",+ primary_keys=["id"],+ ),+ "meta_fields": BambooHREndpointConfig(+ name="meta_fields",+ path="meta/fields",+ primary_keys=["id"],+ ),+ "meta_lists": BambooHREndpointConfig(+ name="meta_lists",+ path="meta/lists",+ primary_keys=["fieldId"],+ ),+ "meta_users": BambooHREndpointConfig(+ name="meta_users",+ path="meta/users",+ data_shape="dict",+ primary_keys=["id"],+ ),+}++ENDPOINTS = tuple(BAMBOOHR_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in BAMBOOHR_ENDPOINTS.items()+}diff --git a/posthog/temporal/data_imports/sources/bamboohr/source.py b/posthog/temporal/data_imports/sources/bamboohr/source.pyindex 086c355acd73..3584f905ace2 100644--- a/posthog/temporal/data_imports/sources/bamboohr/source.py+++ b/posthog/temporal/data_imports/sources/bamboohr/source.py@@ -1,19 +1,31 @@-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.bamboohr.bamboohr import (+ BambooHRResumeConfig,+ bamboohr_source,+ validate_credentials as validate_bamboohr_credentials,+)+from posthog.temporal.data_imports.sources.bamboohr.settings import ENDPOINTS, INCREMENTAL_FIELDS+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 BambooHRSourceConfigfrom products.data_warehouse.backend.types import ExternalDataSourceType@SourceRegistry.register-class BambooHRSource(SimpleSource[BambooHRSourceConfig]):+class BambooHRSource(ResumableSource[BambooHRSourceConfig, BambooHRResumeConfig]):@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.BAMBOOHR@@ -23,7 +35,83 @@ class BambooHRSource(SimpleSource[BambooHRSourceConfig]):return SourceConfig(name=SchemaExternalDataSourceType.BAMBOO_HR,label="BambooHR",+ releaseStatus=ReleaseStatus.ALPHA,+ caption="""Enter your BambooHR company subdomain and API key to pull your HR data into the PostHog Data warehouse.++You can generate an API key from your BambooHR account under **Account Settings → API Keys** (requires admin permissions).++Make sure your API key has access to the data you want to sync (employee, time off, and account metadata).""",iconPath="/static/services/bamboohr.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/bamboohr",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="subdomain",+ label="Company subdomain",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="yourcompany",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ ],+ ),+ )++ def get_schemas(+ self,+ config: BambooHRSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ schemas = [+ SourceSchema(+ name=endpoint,+ supports_incremental=False,+ supports_append=False,+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),+ )+ for endpoint in list(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: BambooHRSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ return validate_bamboohr_credentials(config.subdomain, config.api_key, schema_name)++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error: Unauthorized for url": "Your BambooHR API key is invalid or expired. Please generate a new key and reconnect.",+ "403 Client Error: Forbidden for url": "Your BambooHR API key does not have the required permissions. Please check the key permissions and try again.",+ }++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[BambooHRResumeConfig]:+ return ResumableSourceManager[BambooHRResumeConfig](inputs, BambooHRResumeConfig)++ def source_for_pipeline(+ self,+ config: BambooHRSourceConfig,+ resumable_source_manager: ResumableSourceManager[BambooHRResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return bamboohr_source(+ subdomain=config.subdomain,+ api_key=config.api_key,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,)diff --git a/posthog/temporal/data_imports/sources/bamboohr/tests/test_bamboohr.py b/posthog/temporal/data_imports/sources/bamboohr/tests/test_bamboohr.pynew file mode 100644index 000000000000..3edf41ab9558--- /dev/null+++ b/posthog/temporal/data_imports/sources/bamboohr/tests/test_bamboohr.py@@ -0,0 +1,250 @@+from typing import Any++import pytest+from unittest.mock import MagicMock, patch++from parameterized import parameterized++from posthog.temporal.data_imports.sources.bamboohr.bamboohr import (+ INVALID_SUBDOMAIN_MESSAGE,+ BambooHRResumeConfig,+ _base_url,+ _build_url,+ _extract_records,+ _next_url,+ bamboohr_source,+ get_rows,+ validate_credentials,+)+from posthog.temporal.data_imports.sources.bamboohr.settings import BAMBOOHR_ENDPOINTS+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager++MODULE = "posthog.temporal.data_imports.sources.bamboohr.bamboohr"+++def _mock_response(status_code: int = 200, payload: Any = None) -> MagicMock:+ response = MagicMock()+ response.status_code = status_code+ response.ok = 200 <= status_code < 300+ response.json.return_value = payload if payload is not None else {}+ response.text = ""+ return response+++def _mock_session_returning(*responses: MagicMock) -> MagicMock:+ session = MagicMock()+ session.get.side_effect = list(responses)+ return session+++class TestExtractRecords:+ @parameterized.expand(+ [+ (+ "employees_directory",+ "employees",+ {"fields": [{"id": "displayName"}], "employees": [{"id": "1"}, {"id": "2"}]},+ [{"id": "1"}, {"id": "2"}],+ ),+ (+ "top_level_list",+ "meta_fields",+ [{"id": "1", "name": "First Name"}],+ [{"id": "1", "name": "First Name"}],+ ),+ (+ "wrapped_list",+ "time_off_types",+ {"timeOffTypes": [{"id": "1"}]},+ [{"id": "1"}],+ ),+ (+ "dict_keyed_by_id",+ "meta_users",+ {"7": {"id": "7", "employeeId": "1"}, "8": {"id": "8", "employeeId": "2"}},+ [{"id": "7", "employeeId": "1"}, {"id": "8", "employeeId": "2"}],+ ),+ ("non_list_returns_empty", "meta_fields", {"id": "1"}, []),+ ]+ )+ def test_extract_records(self, _name: str, endpoint: str, payload: Any, expected: list[dict[str, Any]]) -> None:+ assert _extract_records(payload, BAMBOOHR_ENDPOINTS[endpoint]) == expected++ def test_missing_data_key_raises(self) -> None:+ # A missing envelope key should fail loudly rather than silently sync zero rows.+ with pytest.raises(KeyError):+ _extract_records({"somethingElse": []}, BAMBOOHR_ENDPOINTS["time_off_types"])+++class TestNextUrl:+ @parameterized.expand(+ [+ (+ "underscore_links",+ {"_links": {"next": "https://api.bamboohr.com/api/gateway.php/acme/v1/p2"}},+ "https://api.bamboohr.com/api/gateway.php/acme/v1/p2",+ ),+ (+ "plain_links",+ {"links": {"next": "https://api.bamboohr.com/api/gateway.php/acme/v1/p2"}},+ "https://api.bamboohr.com/api/gateway.php/acme/v1/p2",+ ),+ ("no_links", {"data": []}, None),+ ("null_next", {"_links": {"next": None}}, None),+ ("empty_links_dict", {"_links": {}}, None),+ ("relative_next_ignored", {"_links": {"next": "/v1/employees?page=2"}}, None),+ ("off_host_ignored", {"_links": {"next": "http://169.254.169.254/latest/meta-data/"}}, None),+ ("list_payload", [{"id": "1"}], None),+ ]+ )+ def test_next_url(self, _name: str, payload: Any, expected: str | None) -> None:+ assert _next_url(payload) == expected+++class TestValidateSubdomain:+ @parameterized.expand(+ [+ ("simple", "acme"),+ ("with_hyphen", "acme-corp"),+ ("with_digits", "acme123"),+ ]+ )+ def test_valid_subdomains_build_urls(self, _name: str, subdomain: str) -> None:+ assert _base_url(subdomain) == f"https://api.bamboohr.com/api/gateway.php/{subdomain}/v1"++ @parameterized.expand(+ [+ ("path_injection", "acme/v1/employees/123/tables/jobInfo?"),+ ("slash", "acme/admin"),+ ("query", "acme?foo=bar"),+ ("dot_segment", "../internal"),+ ("empty", ""),+ ("whitespace", "acme corp"),+ ("scheme", "http://169.254.169.254"),+ ]+ )+ def test_invalid_subdomains_rejected(self, _name: str, subdomain: str) -> None:+ # An editable, non-secret subdomain must never be able to inject path segments or query params.+ with pytest.raises(ValueError):+ _base_url(subdomain)+++class TestBuildUrl:+ def test_employees_directory_has_no_params(self) -> None:+ url = _build_url("acme", BAMBOOHR_ENDPOINTS["employees"])+ assert url == "https://api.bamboohr.com/api/gateway.php/acme/v1/employees/directory"++ def test_time_off_requests_includes_date_window(self) -> None:+ url = _build_url("acme", BAMBOOHR_ENDPOINTS["time_off_requests"])+ assert url.startswith("https://api.bamboohr.com/api/gateway.php/acme/v1/time_off/requests?")+ assert "start=2000-01-01" in url+ assert "end=" in url+++class TestValidateCredentials:+ @parameterized.expand(+ [+ ("ok", 200, None, True),+ ("unauthorized", 401, None, False),+ ("not_found_subdomain", 404, None, False),+ ("forbidden_at_source_create", 403, None, True),+ ("forbidden_for_schema", 403, "employees", False),+ ("unexpected", 500, None, False),+ ]+ )+ def test_validate_credentials_status_mapping(+ self, _name: str, status_code: int, schema_name: str | None, expected_valid: bool+ ) -> None:+ with patch(f"{MODULE}.make_tracked_session", return_value=_mock_session_returning(_mock_response(status_code))):+ valid, message = validate_credentials("acme", "key", schema_name)+ assert valid is expected_valid+ if not expected_valid:+ assert message is not None++ def test_validate_credentials_connection_error(self) -> None:+ session = MagicMock()+ session.get.side_effect = Exception("boom")+ with patch(f"{MODULE}.make_tracked_session", return_value=session):+ valid, message = validate_credentials("acme", "key")+ assert valid is False+ assert message is not None++ def test_invalid_subdomain_rejected_before_request(self) -> None:+ session = MagicMock()+ with patch(f"{MODULE}.make_tracked_session", return_value=session):+ valid, message = validate_credentials("acme/v1/employees/123?", "key")+ assert valid is False+ assert message == INVALID_SUBDOMAIN_MESSAGE+ session.get.assert_not_called()+++class TestBambooHRSource:+ @parameterized.expand([(endpoint,) for endpoint in BAMBOOHR_ENDPOINTS])+ def test_source_response_shape(self, endpoint: str) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ response = bamboohr_source("acme", "key", endpoint, MagicMock(), manager)+ assert response.name == endpoint+ assert response.primary_keys == BAMBOOHR_ENDPOINTS[endpoint].primary_keys+++class TestGetRows:+ def _run(+ self, manager: MagicMock, *responses: MagicMock, endpoint: str = "employees"+ ) -> list[list[dict[str, Any]]]:+ with patch(f"{MODULE}.make_tracked_session", return_value=_mock_session_returning(*responses)):+ return list(+ get_rows(+ subdomain="acme",+ api_key="key",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=manager,+ )+ )++ def test_single_page_yields_once_and_does_not_save_state(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False+ payload = {"fields": [], "employees": [{"id": "1"}, {"id": "2"}]}++ batches = self._run(manager, _mock_response(200, payload))++ assert batches == [[{"id": "1"}, {"id": "2"}]]+ manager.save_state.assert_not_called()++ def test_paginates_and_saves_state_after_each_yield(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False+ page1 = {"employees": [{"id": "1"}], "_links": {"next": "https://api.bamboohr.com/api/gateway.php/acme/v1/p2"}}+ page2 = {"employees": [{"id": "2"}]}++ batches = self._run(manager, _mock_response(200, page1), _mock_response(200, page2))++ assert batches == [[{"id": "1"}], [{"id": "2"}]]+ manager.save_state.assert_called_once()+ saved = manager.save_state.call_args[0][0]+ assert isinstance(saved, BambooHRResumeConfig)+ assert saved.next_url == "https://api.bamboohr.com/api/gateway.php/acme/v1/p2"++ def test_resumes_from_saved_state(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = True+ manager.load_state.return_value = BambooHRResumeConfig(+ next_url="https://api.bamboohr.com/api/gateway.php/acme/v1/resume"+ )+ session = _mock_session_returning(_mock_response(200, {"employees": [{"id": "9"}]}))++ with patch(f"{MODULE}.make_tracked_session", return_value=session):+ batches = list(+ get_rows(+ subdomain="acme",+ api_key="key",+ endpoint="employees",+ logger=MagicMock(),+ resumable_source_manager=manager,+ )+ )++ assert batches == [[{"id": "9"}]]+ called_url = session.get.call_args[0][0]+ assert called_url == "https://api.bamboohr.com/api/gateway.php/acme/v1/resume"diff --git a/posthog/temporal/data_imports/sources/bamboohr/tests/test_bamboohr_source.py b/posthog/temporal/data_imports/sources/bamboohr/tests/test_bamboohr_source.pynew file mode 100644index 000000000000..e8b15a23ec4f--- /dev/null+++ b/posthog/temporal/data_imports/sources/bamboohr/tests/test_bamboohr_source.py@@ -0,0 +1,81 @@+from typing import cast++from unittest.mock import MagicMock, patch++from posthog.schema import SourceFieldInputConfig, SourceFieldInputConfigType++from posthog.temporal.data_imports.sources.bamboohr.bamboohr import BambooHRResumeConfig+from posthog.temporal.data_imports.sources.bamboohr.settings import ENDPOINTS+from posthog.temporal.data_imports.sources.bamboohr.source import BambooHRSource+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from posthog.temporal.data_imports.sources.generated_configs import BambooHRSourceConfig++from products.data_warehouse.backend.types import ExternalDataSourceType++MODULE = "posthog.temporal.data_imports.sources.bamboohr.source"+++def _config() -> BambooHRSourceConfig:+ return BambooHRSourceConfig(subdomain="acme", api_key="key")+++class TestBambooHRSource:+ def test_source_type(self) -> None:+ assert BambooHRSource().source_type == ExternalDataSourceType.BAMBOOHR++ def test_source_config_fields(self) -> None:+ config = BambooHRSource().get_source_config+ assert config.label == "BambooHR"+ assert not config.unreleasedSource++ fields = cast(list[SourceFieldInputConfig], config.fields)+ by_name = {f.name: f for f in fields}+ assert set(by_name) == {"subdomain", "api_key"}+ assert by_name["subdomain"].type == SourceFieldInputConfigType.TEXT+ assert by_name["subdomain"].required is True+ assert by_name["api_key"].type == SourceFieldInputConfigType.PASSWORD+ assert by_name["api_key"].secret is True++ def test_get_schemas_returns_all_endpoints_full_refresh(self) -> None:+ schemas = BambooHRSource().get_schemas(_config(), team_id=1)+ assert {s.name for s in schemas} == set(ENDPOINTS)+ assert all(s.supports_incremental is False for s in schemas)+ assert all(s.supports_append is False for s in schemas)++ def test_get_schemas_filters_by_names(self) -> None:+ schemas = BambooHRSource().get_schemas(_config(), team_id=1, names=["employees"])+ assert [s.name for s in schemas] == ["employees"]++ def test_validate_credentials_delegates(self) -> None:+ with patch(f"{MODULE}.validate_bamboohr_credentials", return_value=(True, None)) as mock_validate:+ valid, message = BambooHRSource().validate_credentials(_config(), team_id=1, schema_name="employees")+ assert valid is True+ assert message is None+ mock_validate.assert_called_once_with("acme", "key", "employees")++ def test_get_non_retryable_errors_covers_auth(self) -> None:+ errors = BambooHRSource().get_non_retryable_errors()+ assert any("401" in key for key in errors)+ assert any("403" in key for key in errors)++ def test_get_resumable_source_manager(self) -> None:+ inputs = MagicMock()+ manager = BambooHRSource().get_resumable_source_manager(inputs)+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is BambooHRResumeConfig++ def test_source_for_pipeline_plumbs_arguments(self) -> None:+ inputs = MagicMock()+ inputs.schema_name = "employees"+ manager = MagicMock(spec=ResumableSourceManager)++ with patch(f"{MODULE}.bamboohr_source") as mock_source:+ BambooHRSource().source_for_pipeline(_config(), manager, inputs)++ mock_source.assert_called_once_with(+ subdomain="acme",+ api_key="key",+ endpoint="employees",+ logger=inputs.logger,+ resumable_source_manager=manager,+ )diff --git a/posthog/temporal/data_imports/sources/generated_configs.py b/posthog/temporal/data_imports/sources/generated_configs.pyindex f6ec61a40e1b..b8216161d7b8 100644--- a/posthog/temporal/data_imports/sources/generated_configs.py+++ b/posthog/temporal/data_imports/sources/generated_configs.py@@ -151,7 +151,8 @@ class AzureBlobSourceConfig(config.Config):@config.configclass BambooHRSourceConfig(config.Config):- pass+ subdomain: str+ api_key: str@config.config