: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 workday source (#73790)
Tom Owers7a45100212d0
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex e3ff7055865a..f75de6070a8b 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -634,6 +634,7 @@ the row lists both.| woocommerce | HTTP | requests + `rest_source.RESTClient` | ✅ || wordpress | HTTP | requests | ✅ || workable | HTTP | requests | ✅ |+| workday | HTTP | requests + `rest_source.RESTClient` | ✅ || workos | HTTP | requests + `rest_source.RESTClient` | ✅ || wrike | HTTP | requests | ✅ || writesonic | HTTP | requests | ✅ |@@ -1386,7 +1387,6 @@ doesn't conflict with concurrent PRs.- wiz- wompi- workato-- workday- workflowmax- workiz- workrampdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/workday.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/workday.pyindex 8cf856c17232..649356b9e5ce 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/workday.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/workday.py@@ -6,4 +6,8 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp@config.configclass WorkdaySourceConfig(config.Config):- pass+ hostname: str+ tenant: str+ client_id: str+ client_secret: str+ refresh_token: strdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/workday/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/workday/canonical_descriptions.pynew file mode 100644index 000000000000..8b7b3f78841e--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/workday/canonical_descriptions.py@@ -0,0 +1,99 @@+"""Canonical, documentation-sourced descriptions for Workday REST endpoints and columns.++Sourced from the Workday REST API reference+(https://community.workday.com/sites/default/files/file-hosting/restapi/index.html). Keyed by the+endpoint names in `settings.py` `WORKDAY_ENDPOINTS`, which match the `ExternalDataSchema.name` of a+synced Workday table. Columns absent here fall back to LLM enrichment.++Every Workday REST collection item carries the same instance envelope — `id` (the Workday ID, a+32-char hex WID), `descriptor` (the human-readable label Workday renders for the instance) and+`href` (the absolute API URL of the instance) — so those three are described on every table.+"""++from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++_DOCS_URL = "https://community.workday.com/sites/default/files/file-hosting/restapi/index.html"++_INSTANCE_COLUMNS = {+ "id": "Workday ID (WID) uniquely identifying the instance.",+ "descriptor": "Human-readable label Workday displays for the instance.",+ "href": "Absolute Workday REST URL of the instance.",+}++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "workers": {+ "description": "A worker in the tenant — an employee or contingent worker — with their current staffing information.",+ "docs_url": _DOCS_URL,+ "columns": {+ **_INSTANCE_COLUMNS,+ "primaryWorkEmail": "Worker's primary work email address.",+ "isManager": "Whether the worker manages at least one supervisory organization.",+ "businessTitle": "Business title shown on the worker's primary job.",+ "primaryWorkPhone": "Worker's primary work phone number.",+ "person": "Reference to the person record behind the worker.",+ "supervisoryOrganization": "Supervisory organization the worker's primary position belongs to.",+ },+ },+ "jobs": {+ "description": "A job — the instance of a position a worker is assigned to, including its staffing details.",+ "docs_url": _DOCS_URL,+ "columns": {+ **_INSTANCE_COLUMNS,+ "worker": "Worker assigned to the job.",+ "jobProfile": "Job profile the job is based on.",+ "supervisoryOrganization": "Supervisory organization the job reports into.",+ "effectiveDate": "Date the current job details took effect.",+ },+ },+ "job_profiles": {+ "description": "A job profile — the reusable definition of a job's title, level, and pay-rate type that positions are created from.",+ "docs_url": _DOCS_URL,+ "columns": {+ **_INSTANCE_COLUMNS,+ "jobFamily": "Job families the profile belongs to.",+ "managementLevel": "Management level associated with the profile.",+ "inactive": "Whether the profile is inactive and can no longer be assigned.",+ },+ },+ "job_families": {+ "description": "A job family — the grouping of related job profiles used for reporting and compensation.",+ "docs_url": _DOCS_URL,+ "columns": {+ **_INSTANCE_COLUMNS,+ "inactive": "Whether the job family is inactive.",+ },+ },+ "supervisory_organizations": {+ "description": "A supervisory organization — the manager-led org unit that positions and workers are assigned to.",+ "docs_url": _DOCS_URL,+ "columns": {+ **_INSTANCE_COLUMNS,+ "manager": "Worker who manages the organization.",+ "superiorOrganization": "Parent supervisory organization in the hierarchy.",+ "code": "Organization code assigned in the tenant.",+ "availableForHire": "Whether the organization is available for hiring.",+ },+ },+ "job_changes": {+ "description": "A job change event — a Change Job business process recording a worker's move between positions, titles, or organizations.",+ "docs_url": _DOCS_URL,+ "columns": {+ **_INSTANCE_COLUMNS,+ "worker": "Worker whose job changed.",+ "effectiveDate": "Date the job change takes effect.",+ "reason": "Reason selected for the job change.",+ },+ },+ "organization_assignment_changes": {+ "description": "An organization assignment change event — a business process recording a change to the organizations (company, cost center, region) a position is assigned to.",+ "docs_url": _DOCS_URL,+ "columns": {+ **_INSTANCE_COLUMNS,+ "worker": "Worker whose organization assignments changed.",+ "effectiveDate": "Date the organization assignment change takes effect.",+ "reason": "Reason selected for the organization assignment change.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/workday/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/workday/settings.pynew file mode 100644index 000000000000..3d4e17e29974--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/workday/settings.py@@ -0,0 +1,51 @@+from dataclasses import dataclass++from products.warehouse_sources.backend.types import IncrementalField++# Workday's REST collection endpoints default to 20 objects per page and cap `limit` at 100.+DEFAULT_PAGE_SIZE = 100++# Most of the catalog lives in the Staffing service, which is versioned per service+# (`/ccx/api/staffing/v7/{tenant}/...`). That version is what the source pins.+STAFFING_SERVICE = "staffing"+# The Common service is served straight off `/ccx/api/v1/{tenant}/...` with no service segment,+# and its v1 has never been re-versioned, so it is not part of the pin.+COMMON_SERVICE = "common"+++@dataclass(frozen=True)+class WorkdayEndpointConfig:+ name: str+ resource: str+ service: str = STAFFING_SERVICE+ primary_key: str = "id"+++WORKDAY_ENDPOINTS: dict[str, WorkdayEndpointConfig] = {+ "workers": WorkdayEndpointConfig(name="workers", resource="workers", service=COMMON_SERVICE),+ "jobs": WorkdayEndpointConfig(name="jobs", resource="jobs"),+ "job_profiles": WorkdayEndpointConfig(name="job_profiles", resource="jobProfiles"),+ "job_families": WorkdayEndpointConfig(name="job_families", resource="jobFamilies"),+ "supervisory_organizations": WorkdayEndpointConfig(+ name="supervisory_organizations", resource="supervisoryOrganizations"+ ),+ "job_changes": WorkdayEndpointConfig(name="job_changes", resource="jobChanges"),+ "organization_assignment_changes": WorkdayEndpointConfig(+ name="organization_assignment_changes", resource="organizationAssignmentChanges"+ ),+}++ENDPOINTS = tuple(WORKDAY_ENDPOINTS.keys())++# Workday's server-side `Updated_From` / `Updated_Through` range filters live on the SOAP web+# services, not on the REST collections exposed here, so every endpoint is full-refresh only.+# Advertising an incremental cursor we can't push down would re-read the whole collection each+# run at the same API cost while pretending otherwise.+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {name: [] for name in WORKDAY_ENDPOINTS}+++def build_endpoint_path(config: WorkdayEndpointConfig, tenant: str, staffing_version: str) -> str:+ """Path of a collection endpoint relative to the `/ccx/api` base URL."""+ if config.service == COMMON_SERVICE:+ return f"/v1/{tenant}/{config.resource}"+ return f"/{config.service}/{staffing_version}/{tenant}/{config.resource}"diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/workday/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/workday/source.pyindex 5b6e8cbab42c..ef53c7583a1a 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/workday/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/workday/source.py@@ -1,32 +1,187 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import (+ 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.workday import (WorkdaySourceConfig,)+from products.warehouse_sources.backend.temporal.data_imports.sources.workday.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.workday.workday import (+ HOST_NOT_ALLOWED_ERROR,+ TOKEN_ERROR,+ WorkdayResumeConfig,+ validate_credentials as validate_workday_credentials,+ workday_source,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class WorkdaySource(SimpleSource[WorkdaySourceConfig]):+class WorkdaySource(ResumableSource[WorkdaySourceConfig, WorkdayResumeConfig]):+ # Workday versions each REST service separately. The Staffing service carries all but one+ # of the endpoints below, so its version is what a source pins; the Common service that+ # serves `workers` is fixed at the `/ccx/api/v1` path.+ supported_versions = ("v7",)+ default_version = "v7"+ api_docs_url = "https://community.workday.com/sites/default/files/file-hosting/restapi/index.html"++ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.WORKDAY+ @property+ def connection_host_fields(self) -> list[str]:+ # `hostname` is where the stored client secret and refresh token are sent; retargeting+ # it must re-require those secrets.+ return ["hostname"]+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.WORKDAY,category=DataWarehouseSourceCategory.HR___RECRUITING,label="Workday",+ releaseStatus=ReleaseStatus.ALPHA,+ caption="""Pull your Workday HCM data into the PostHog Data warehouse over the Workday REST API.++Register an API client for integrations in Workday (**Register API Client for Integrations**) with the `staffing` scope, then paste its client ID, client secret and refresh token below.++Your hostname and tenant are the first two parts of your Workday URL — for `https://wd2-impl-services1.workday.com/acme_pt1`, the hostname is `wd2-impl-services1.workday.com` and the tenant is `acme_pt1`.""",iconPath="/static/services/workday.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/workday",+ keywords=["hcm", "hris"],+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="hostname",+ label="Hostname",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="wd2-impl-services1.workday.com",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="tenant",+ label="Tenant",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="acme_pt1",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="client_id",+ label="Client ID",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="client_secret",+ label="Client secret",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ SourceFieldInputConfig(+ name="refresh_token",+ label="Refresh token",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ ],+ ),+ )++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ TOKEN_ERROR: "Workday rejected your API client credentials. Please check the client ID, secret and refresh token, then reconnect.",+ "401 Client Error": "Workday rejected the access token. Please reconnect the source with a fresh refresh token.",+ "403 Client Error": "Your Workday API client is not authorized for this resource. Please check its scopes and domain security policies.",+ HOST_NOT_ALLOWED_ERROR: "The Workday hostname is not allowed. Please use your tenant's Workday hostname.",+ }++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.workday.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_schemas(+ self,+ config: WorkdaySourceConfig,+ 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: WorkdaySourceConfig,+ team_id: int,+ schema_name: Optional[str] = None,+ api_version: str | None = None,+ ) -> tuple[bool, str | None]:+ return validate_workday_credentials(+ hostname=config.hostname,+ tenant=config.tenant,+ client_id=config.client_id,+ client_secret=config.client_secret,+ refresh_token=config.refresh_token,+ staffing_version=self.resolve_api_version(api_version),+ schema_name=schema_name,+ team_id=team_id,+ )++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[WorkdayResumeConfig]:+ return ResumableSourceManager[WorkdayResumeConfig](inputs, WorkdayResumeConfig)++ def source_for_pipeline(+ self,+ config: WorkdaySourceConfig,+ resumable_source_manager: ResumableSourceManager[WorkdayResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return workday_source(+ hostname=config.hostname,+ tenant=config.tenant,+ client_id=config.client_id,+ client_secret=config.client_secret,+ refresh_token=config.refresh_token,+ endpoint=inputs.schema_name,+ staffing_version=self.resolve_api_version(inputs.api_version),+ team_id=inputs.team_id,+ job_id=inputs.job_id,+ resumable_source_manager=resumable_source_manager,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/workday/tests/test_workday.py b/products/warehouse_sources/backend/temporal/data_imports/sources/workday/tests/test_workday.pynew file mode 100644index 000000000000..357da848c8e7--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/workday/tests/test_workday.py@@ -0,0 +1,432 @@+import json+from collections.abc import Iterable+from typing import Any, Optional, cast++import pytest+from unittest import mock++from requests import Response+from requests.exceptions import ConnectionError as RequestsConnectionError++from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.workday.settings import (+ WORKDAY_ENDPOINTS,+ build_endpoint_path,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.workday.workday import (+ HOST_NOT_ALLOWED_ERROR,+ TOKEN_ERROR,+ WorkdayAuthError,+ WorkdayHostNotAllowedError,+ WorkdayResumeConfig,+ base_url,+ mint_access_token,+ normalize_hostname,+ token_url,+ validate_credentials,+ workday_source,+)++WORKDAY_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.workday.workday"+# RESTClient builds its session via make_tracked_session in the rest_client module.+CLIENT_SESSION_PATCH = "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"++HOSTNAME = "wd2-impl-services1.workday.com"+TENANT = "acme_pt1"+++class FakeResumeManager(ResumableSourceManager[WorkdayResumeConfig]):+ """Stands in for the Redis-backed manager: no I/O, records what was checkpointed."""++ def __init__(self, state: Optional[WorkdayResumeConfig] = None) -> None:+ self.state = state+ self.saved: list[WorkdayResumeConfig] = []++ def can_resume(self) -> bool:+ return self.state is not None++ def load_state(self) -> Optional[WorkdayResumeConfig]:+ return self.state++ def save_state(self, data: WorkdayResumeConfig) -> None:+ self.saved.append(data)+++def _raw_response(content: bytes, *, status_code: int = 200) -> Response:+ response = Response()+ response.status_code = status_code+ response._content = content+ # Callers stream these (stream=True + iter_content) and close them; marking the content+ # consumed makes iter_content replay `_content` and keeps `.close()` a no-op (raw is None).+ response._content_consumed = True # type: ignore[attr-defined]+ return response+++def _json_response(payload: Any, *, status_code: int = 200) -> Response:+ return _raw_response(json.dumps(payload).encode(), status_code=status_code)+++def _redirect_response(location: str = "https://internal.example/") -> Response:+ response = _raw_response(b"", status_code=302)+ response.headers["Location"] = location+ return response+++def _page(rows: list[dict[str, Any]], total: int) -> Response:+ return _json_response({"total": total, "data": rows})+++def _wire(session: mock.MagicMock, responses: list[Response]) -> list[dict[str, Any]]:+ """Wire a mock session, snapshotting each request's url + params AT PREPARE TIME.++ ``request.params`` is one dict mutated in place across pages, so it has to be copied when+ each request is prepared rather than read back after the run.+ """+ session.headers = {}+ snapshots: list[dict[str, Any]] = []++ def _prepare(request: Any) -> mock.MagicMock:+ prepared = mock.MagicMock()+ # `_check_allowed_host` urlsplits the prepared URL, so it must be a real string.+ prepared.url = request.url+ snapshots.append({"url": request.url, "params": dict(request.params or {})})+ return prepared++ session.prepare_request.side_effect = _prepare+ session.send.side_effect = responses+ return snapshots+++def _rows(source_response: SourceResponse) -> list[dict[str, Any]]:+ pages = cast("Iterable[Any]", source_response.items())+ return [row for page in pages for row in page]+++def _build_source(+ endpoint: str = "workers",+ manager: Optional[FakeResumeManager] = None,+ staffing_version: str = "v7",+) -> SourceResponse:+ return workday_source(+ hostname=HOSTNAME,+ tenant=TENANT,+ client_id="client",+ client_secret="secret",+ refresh_token="refresh",+ endpoint=endpoint,+ staffing_version=staffing_version,+ team_id=1,+ job_id="job-1",+ resumable_source_manager=manager or FakeResumeManager(),+ )+++class TestUrlHelpers:+ @pytest.mark.parametrize(+ "raw, expected",+ [+ (HOSTNAME, HOSTNAME),+ (f"https://{HOSTNAME}", HOSTNAME),+ (f"http://{HOSTNAME}/", HOSTNAME),+ (f" {HOSTNAME} ", HOSTNAME),+ (f"{HOSTNAME}/acme_pt1", HOSTNAME),+ (f"https://{HOSTNAME}/ccx/api/v1/acme_pt1/workers", HOSTNAME),+ ],+ )+ def test_normalize_hostname(self, raw: str, expected: str) -> None:+ assert normalize_hostname(raw) == expected++ def test_base_url(self) -> None:+ assert base_url(f"https://{HOSTNAME}/") == f"https://{HOSTNAME}/ccx/api"++ def test_token_url(self) -> None:+ assert token_url(HOSTNAME, TENANT) == f"https://{HOSTNAME}/ccx/oauth2/{TENANT}/token"++ @pytest.mark.parametrize(+ "endpoint, expected",+ [+ # The Common service is served straight off /ccx/api/v1 with no service segment.+ ("workers", "/v1/acme_pt1/workers"),+ ("jobs", "/staffing/v7/acme_pt1/jobs"),+ ("job_profiles", "/staffing/v7/acme_pt1/jobProfiles"),+ ("job_families", "/staffing/v7/acme_pt1/jobFamilies"),+ ("supervisory_organizations", "/staffing/v7/acme_pt1/supervisoryOrganizations"),+ ("job_changes", "/staffing/v7/acme_pt1/jobChanges"),+ ("organization_assignment_changes", "/staffing/v7/acme_pt1/organizationAssignmentChanges"),+ ],+ )+ def test_build_endpoint_path(self, endpoint: str, expected: str) -> None:+ assert build_endpoint_path(WORKDAY_ENDPOINTS[endpoint], "acme_pt1", "v7") == expected++ def test_staffing_paths_follow_the_pinned_version(self) -> None:+ assert build_endpoint_path(WORKDAY_ENDPOINTS["jobs"], TENANT, "v6") == f"/staffing/v6/{TENANT}/jobs"+++class TestMintAccessToken:+ def test_posts_refresh_grant_with_basic_client_auth(self) -> None:+ session = mock.MagicMock()+ session.post.return_value = _json_response({"access_token": "tok", "expires_in": 3600})++ with mock.patch(f"{WORKDAY_MODULE}.make_tracked_session", return_value=session):+ assert mint_access_token(HOSTNAME, TENANT, "client", "secret", "refresh") == "tok"++ args, kwargs = session.post.call_args+ assert args[0] == f"https://{HOSTNAME}/ccx/oauth2/{TENANT}/token"+ assert kwargs["data"] == {"grant_type": "refresh_token", "refresh_token": "refresh"}+ assert kwargs["auth"] == ("client", "secret")+ # A 3xx must not bounce the client secret to another origin.+ assert kwargs["allow_redirects"] is False++ @pytest.mark.parametrize(+ "response, expected_fragment",+ [+ (_json_response({"error": "invalid_grant"}, status_code=400), TOKEN_ERROR),+ (_json_response({"error": "invalid_client"}, status_code=401), TOKEN_ERROR),+ (_raw_response(b"<html>login</html>"), "non-JSON"),+ (_json_response({"token_type": "Bearer"}), "no access token"),+ (_json_response({"access_token": ""}), "no access token"),+ ],+ )+ def test_token_failures_raise(self, response: Response, expected_fragment: str) -> None:+ session = mock.MagicMock()+ session.post.return_value = response++ with mock.patch(f"{WORKDAY_MODULE}.make_tracked_session", return_value=session):+ with pytest.raises(WorkdayAuthError) as excinfo:+ mint_access_token(HOSTNAME, TENANT, "client", "secret", "refresh")++ assert expected_fragment in str(excinfo.value)++ def test_oversized_token_body_is_refused(self) -> None:+ # A customer-controlled host could stream an unbounded token body to exhaust the worker;+ # the read is capped rather than buffered whole.+ session = mock.MagicMock()+ session.post.return_value = _json_response({"access_token": "tok"})++ with (+ mock.patch(f"{WORKDAY_MODULE}.make_tracked_session", return_value=session),+ mock.patch(f"{WORKDAY_MODULE}.MAX_VALIDATE_RESPONSE_BYTES", 4),+ ):+ with pytest.raises(WorkdayAuthError) as excinfo:+ mint_access_token(HOSTNAME, TENANT, "client", "secret", "refresh")++ assert "oversized" in str(excinfo.value)+++class TestValidateCredentials:+ def _validate(+ self,+ probe: Optional[Response] = None,+ *,+ hostname: str = HOSTNAME,+ tenant: str = TENANT,+ schema_name: Optional[str] = None,+ token_side_effect: Optional[Exception] = None,+ ) -> tuple[bool, Optional[str]]:+ session = mock.MagicMock()+ # `Response.__bool__` is `ok`, so a non-2xx probe must not be treated as absent.+ session.get.return_value = _json_response({"total": 1, "data": []}) if probe is None else probe+ with (+ mock.patch(f"{WORKDAY_MODULE}.make_tracked_session", return_value=session),+ mock.patch(+ f"{WORKDAY_MODULE}.mint_access_token",+ side_effect=token_side_effect,+ return_value="tok",+ ),+ ):+ return validate_credentials(+ hostname=hostname,+ tenant=tenant,+ client_id="client",+ client_secret="secret",+ refresh_token="refresh",+ staffing_version="v7",+ schema_name=schema_name,+ )++ @pytest.mark.parametrize(+ "hostname, tenant, expected_error",+ [+ ("not a host", TENANT, "Invalid Workday hostname"),+ ("", TENANT, "Invalid Workday hostname"),+ (HOSTNAME, "bad tenant", "Invalid Workday tenant"),+ (HOSTNAME, "", "Invalid Workday tenant"),+ ],+ )+ def test_rejects_malformed_target_before_sending_credentials(+ self, hostname: str, tenant: str, expected_error: str+ ) -> None:+ session = mock.MagicMock()+ with mock.patch(f"{WORKDAY_MODULE}.make_tracked_session", return_value=session):+ ok, error = validate_credentials(+ hostname=hostname,+ tenant=tenant,+ client_id="client",+ client_secret="secret",+ refresh_token="refresh",+ staffing_version="v7",+ )++ assert (ok, error) == (False, expected_error)+ session.post.assert_not_called()+ session.get.assert_not_called()++ def test_success(self) -> None:+ assert self._validate() == (True, None)++ def test_probes_the_named_schema_endpoint(self) -> None:+ session = mock.MagicMock()+ session.get.return_value = _json_response({"total": 0, "data": []})+ with (+ mock.patch(f"{WORKDAY_MODULE}.make_tracked_session", return_value=session),+ mock.patch(f"{WORKDAY_MODULE}.mint_access_token", return_value="tok"),+ ):+ validate_credentials(+ hostname=HOSTNAME,+ tenant=TENANT,+ client_id="client",+ client_secret="secret",+ refresh_token="refresh",+ staffing_version="v7",+ schema_name="job_profiles",+ )++ args, kwargs = session.get.call_args+ assert args[0] == f"https://{HOSTNAME}/ccx/api/staffing/v7/{TENANT}/jobProfiles"+ assert kwargs["headers"]["Authorization"] == "Bearer tok"+ assert kwargs["allow_redirects"] is False++ @pytest.mark.parametrize(+ "status_code, schema_name, expected_ok",+ [+ (200, None, True),+ (401, None, False),+ # A genuine client may simply lack the domain security policy for the create-time+ # probe, so 403 must not block source creation — but it fails a scoped probe.+ (403, None, True),+ (403, "workers", False),+ (404, None, False),+ (500, None, False),+ ],+ )+ def test_status_mapping(self, status_code: int, schema_name: Optional[str], expected_ok: bool) -> None:+ ok, _ = self._validate(_json_response({}, status_code=status_code), schema_name=schema_name)+ assert ok is expected_ok++ def test_redirect_is_rejected(self) -> None:+ ok, error = self._validate(_redirect_response())+ assert ok is False+ assert error == HOST_NOT_ALLOWED_ERROR++ def test_token_failure_is_surfaced(self) -> None:+ ok, error = self._validate(token_side_effect=WorkdayAuthError(f"{TOKEN_ERROR} (HTTP 401)"))+ assert ok is False+ assert error is not None and TOKEN_ERROR in error++ def test_network_failure_is_surfaced(self) -> None:+ ok, error = self._validate(token_side_effect=RequestsConnectionError("dns failure"))+ assert (ok, error) == (False, "dns failure")+++class TestWorkdaySource:+ def test_paginates_until_the_total_is_reached(self) -> None:+ session = mock.MagicMock()+ first = [{"id": str(index)} for index in range(100)]+ second = [{"id": "100"}]+ snapshots = _wire(session, [_page(first, total=101), _page(second, total=101)])++ with mock.patch(CLIENT_SESSION_PATCH, return_value=session):+ rows = _rows(_build_source())++ assert [row["id"] for row in rows] == [str(index) for index in range(101)]+ assert [snapshot["params"]["offset"] for snapshot in snapshots] == [0, 100]+ assert snapshots[0]["params"]["limit"] == 100+ assert snapshots[0]["url"] == f"https://{HOSTNAME}/ccx/api/v1/{TENANT}/workers"++ def test_stops_on_an_empty_page_when_the_total_overstates(self) -> None:+ session = mock.MagicMock()+ # `total` overstates what the tenant actually hands back, so termination has to fall back+ # to the empty page rather than looping on the same offset until the total is "reached".+ full_page = [{"id": str(index)} for index in range(100)]+ _wire(session, [_page(full_page, total=5000), _page([], total=5000)])++ with mock.patch(CLIENT_SESSION_PATCH, return_value=session):+ rows = _rows(_build_source())++ assert len(rows) == 100+ assert session.send.call_count == 2++ def test_stops_on_a_short_page(self) -> None:+ session = mock.MagicMock()+ _wire(session, [_page([{"id": "1"}], total=5000)])++ with mock.patch(CLIENT_SESSION_PATCH, return_value=session):+ rows = _rows(_build_source())++ assert [row["id"] for row in rows] == ["1"]+ assert session.send.call_count == 1++ def test_checkpoints_after_each_page(self) -> None:+ session = mock.MagicMock()+ _wire(session, [_page([{"id": str(i)} for i in range(100)], total=101), _page([{"id": "100"}], total=101)])+ manager = FakeResumeManager()++ with mock.patch(CLIENT_SESSION_PATCH, return_value=session):+ _rows(_build_source(manager=manager))++ # One checkpoint after the first page (pointing at the next offset); none once the walk+ # finished, so a later attempt restarts cleanly instead of resuming past the end.+ assert [state.offset for state in manager.saved] == [100]++ def test_resumes_from_the_saved_offset(self) -> None:+ session = mock.MagicMock()+ snapshots = _wire(session, [_page([{"id": "200"}], total=201)])+ manager = FakeResumeManager(WorkdayResumeConfig(offset=200))++ with mock.patch(CLIENT_SESSION_PATCH, return_value=session):+ rows = _rows(_build_source(manager=manager))++ assert snapshots[0]["params"]["offset"] == 200+ assert [row["id"] for row in rows] == ["200"]++ def test_ignores_a_zero_resume_offset(self) -> None:+ session = mock.MagicMock()+ snapshots = _wire(session, [_page([{"id": "0"}], total=1)])++ with mock.patch(CLIENT_SESSION_PATCH, return_value=session):+ _rows(_build_source(manager=FakeResumeManager(WorkdayResumeConfig(offset=0))))++ assert snapshots[0]["params"]["offset"] == 0++ @pytest.mark.parametrize("endpoint", sorted(WORKDAY_ENDPOINTS))+ def test_every_endpoint_requests_its_documented_path(self, endpoint: str) -> None:+ session = mock.MagicMock()+ snapshots = _wire(session, [_page([], total=0)])++ with mock.patch(CLIENT_SESSION_PATCH, return_value=session):+ response = _build_source(endpoint=endpoint)+ _rows(response)++ expected_path = build_endpoint_path(WORKDAY_ENDPOINTS[endpoint], TENANT, "v7")+ assert snapshots[0]["url"] == f"https://{HOSTNAME}/ccx/api{expected_path}"+ assert response.name == endpoint+ assert response.primary_keys == ["id"]++ def test_full_refresh_declares_no_sort_order(self) -> None:+ # Workday's REST collections have no ordering guarantee and no server-side time filter,+ # so claiming "asc" would be a lie the incremental checkpointing could act on.+ assert _build_source().sort_mode is None++ def test_internal_hostname_is_blocked_at_run_time(self) -> None:+ session = mock.MagicMock()+ _wire(session, [_page([], total=0)])++ with (+ mock.patch(CLIENT_SESSION_PATCH, return_value=session),+ mock.patch(f"{WORKDAY_MODULE}._is_host_safe", return_value=(False, None)),+ ):+ with pytest.raises(WorkdayHostNotAllowedError):+ _rows(_build_source())++ session.send.assert_not_called()diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/workday/tests/test_workday_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/workday/tests/test_workday_source.pynew file mode 100644index 000000000000..472342f24019--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/workday/tests/test_workday_source.py@@ -0,0 +1,160 @@+from typing import Optional, cast++import pytest+from unittest import mock++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType++from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.workday import (+ WorkdaySourceConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.workday.settings import (+ ENDPOINTS,+ WORKDAY_ENDPOINTS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.workday.source import WorkdaySource+from products.warehouse_sources.backend.temporal.data_imports.sources.workday.workday import WorkdayResumeConfig+from products.warehouse_sources.backend.types import ExternalDataSourceType++SOURCE_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.workday.source"+++def _config() -> WorkdaySourceConfig:+ return WorkdaySourceConfig(+ hostname="wd2-impl-services1.workday.com",+ tenant="acme_pt1",+ client_id="client",+ client_secret="secret",+ refresh_token="refresh",+ )+++class TestWorkdaySource:+ def setup_method(self) -> None:+ self.source = WorkdaySource()+ self.team_id = 123+ self.config = _config()++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.WORKDAY++ def test_get_source_config_is_released(self) -> None:+ config = self.source.get_source_config++ assert config.name.value == "Workday"+ assert config.label == "Workday"+ assert config.unreleasedSource is None+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.iconPath == "/static/services/workday.png"++ def test_source_fields(self) -> None:+ config = self.source.get_source_config+ assert [f.name for f in config.fields] == [+ "hostname",+ "tenant",+ "client_id",+ "client_secret",+ "refresh_token",+ ]++ @pytest.mark.parametrize(+ "field_name, field_type, secret",+ [+ ("hostname", SourceFieldInputConfigType.TEXT, False),+ ("tenant", SourceFieldInputConfigType.TEXT, False),+ ("client_id", SourceFieldInputConfigType.TEXT, False),+ ("client_secret", SourceFieldInputConfigType.PASSWORD, True),+ ("refresh_token", SourceFieldInputConfigType.PASSWORD, True),+ ],+ )+ def test_field_types_and_secrecy(+ self, field_name: str, field_type: SourceFieldInputConfigType, secret: bool+ ) -> None:+ field = next(f for f in self.source.get_source_config.fields if f.name == field_name)+ assert isinstance(field, SourceFieldInputConfig)+ assert field.type == field_type+ assert field.secret is secret+ assert field.required is True++ def test_hostname_is_a_connection_host_field(self) -> None:+ # Retargeting the hostname must force the client secret / refresh token to be re-entered,+ # otherwise the preserved secrets would be replayed at an attacker-chosen host.+ assert self.source.connection_host_fields == ["hostname"]++ def test_get_schemas_returns_all_endpoints(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id)+ assert {s.name for s in schemas} == set(ENDPOINTS)++ def test_schemas_are_full_refresh_only(self) -> None:+ # Workday's Updated_From/Updated_Through range filters are SOAP-only, so advertising an+ # incremental cursor here would re-read everything at full cost while claiming otherwise.+ for schema in self.source.get_schemas(self.config, self.team_id):+ assert schema.supports_incremental is False+ assert schema.supports_append is False+ assert schema.incremental_fields == []++ def test_get_schemas_filtered_by_names(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id, names=["workers"])+ assert [s.name for s in schemas] == ["workers"]++ def test_get_schemas_unknown_name_returns_empty(self) -> None:+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []++ def test_canonical_descriptions_cover_every_endpoint(self) -> None:+ descriptions = self.source.get_canonical_descriptions()+ assert set(descriptions.keys()) == set(ENDPOINTS)++ @pytest.mark.parametrize("expected_key", ["401 Client Error", "403 Client Error"])+ def test_non_retryable_errors(self, expected_key: str) -> None:+ assert expected_key in self.source.get_non_retryable_errors()++ @pytest.mark.parametrize(+ "mock_return",+ [(True, None), (False, "Invalid Workday hostname")],+ )+ def test_validate_credentials_passes_through(self, mock_return: tuple[bool, Optional[str]]) -> None:+ with mock.patch(f"{SOURCE_MODULE}.validate_workday_credentials", return_value=mock_return) as validate:+ assert self.source.validate_credentials(self.config, self.team_id) == mock_return++ kwargs = validate.call_args.kwargs+ assert kwargs["hostname"] == "wd2-impl-services1.workday.com"+ assert kwargs["tenant"] == "acme_pt1"+ assert kwargs["team_id"] == self.team_id+ assert kwargs["schema_name"] is None+ # An unpinned source falls back to the declared default staffing version.+ assert kwargs["staffing_version"] == "v7"++ def test_validate_credentials_honors_pinned_version(self) -> None:+ with mock.patch(f"{SOURCE_MODULE}.validate_workday_credentials", return_value=(True, None)) as validate:+ self.source.validate_credentials(self.config, self.team_id, schema_name="jobs", api_version="v6")++ assert validate.call_args.kwargs["staffing_version"] == "v6"+ assert validate.call_args.kwargs["schema_name"] == "jobs"++ def test_get_resumable_source_manager_is_bound_to_the_resume_dataclass(self) -> None:+ manager = self.source.get_resumable_source_manager(cast(SourceInputs, mock.MagicMock()))+ assert manager._data_class is WorkdayResumeConfig++ def test_source_for_pipeline_plumbs_inputs(self) -> None:+ inputs = mock.MagicMock()+ inputs.schema_name = "job_profiles"+ inputs.team_id = 7+ inputs.job_id = "job-1"+ inputs.api_version = None+ manager = cast(ResumableSourceManager[WorkdayResumeConfig], mock.MagicMock())++ with mock.patch(f"{SOURCE_MODULE}.workday_source") as source_fn:+ self.source.source_for_pipeline(self.config, manager, cast(SourceInputs, inputs))++ kwargs = source_fn.call_args.kwargs+ assert kwargs["endpoint"] == "job_profiles"+ assert kwargs["team_id"] == 7+ assert kwargs["job_id"] == "job-1"+ assert kwargs["staffing_version"] == "v7"+ assert kwargs["client_secret"] == "secret"+ assert kwargs["resumable_source_manager"] is manager++ def test_every_endpoint_has_a_primary_key(self) -> None:+ assert all(WORKDAY_ENDPOINTS[name].primary_key for name in ENDPOINTS)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/workday/workday.py b/products/warehouse_sources/backend/temporal/data_imports/sources/workday/workday.pynew file mode 100644index 000000000000..e088861e50e6--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/workday/workday.py@@ -0,0 +1,330 @@+import re+import json+import time+import dataclasses+from collections.abc import Iterator+from typing import Any, Optional++import requests++from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session+from products.warehouse_sources.backend.temporal.data_imports.sources.common.mixins import _is_host_safe+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import (+ RESTAPIConfig,+ rest_api_resource,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (+ OffsetPaginator,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.workday.settings import (+ DEFAULT_PAGE_SIZE,+ WORKDAY_ENDPOINTS,+ build_endpoint_path,+)++HOST_NOT_ALLOWED_ERROR = "Workday hostname is not allowed"+TOKEN_ERROR = "Workday rejected the API client credentials"++_HOSTNAME_RE = re.compile(r"^[A-Za-z0-9.\-]+$")+# Workday tenant names are lowercase alphanumerics with underscores/hyphens (e.g. `acme_pt1`).+_TENANT_RE = re.compile(r"^[A-Za-z0-9_\-]+$")++# (connect, read). Workday tenants are customer-controlled hosts, so an unbounded read would+# pin an import worker on a stalled tenant forever.+REQUEST_TIMEOUT: tuple[float, float] = (10.0, 120.0)+VALIDATE_TIMEOUT = 15++# The tenant host is customer-controlled, so a validation body must never be buffered unbounded:+# requests reads the whole response into memory by default, and the read timeout only guards idle+# gaps between reads, not a steady large transfer. A token/probe body is a few KB, so this cap is+# generous for anything real while refusing an exhaustion attempt outright.+MAX_VALIDATE_RESPONSE_BYTES = 8 * 1024 * 1024+RESPONSE_CHUNK_BYTES = 256 * 1024+# Wall-clock budget for reading one validation body — the per-read timeout can't stop a host that+# dribbles bytes slowly enough to stay under it while holding a worker open.+MAX_VALIDATE_DOWNLOAD_SECONDS = 30++RESPONSE_TOO_LARGE_ERROR = "The Workday token endpoint returned an oversized response"+RESPONSE_TOO_SLOW_ERROR = "The Workday token endpoint response was too slow"+++class WorkdayHostNotAllowedError(Exception):+ pass+++class WorkdayAuthError(Exception):+ pass+++def _read_capped_body(response: requests.Response) -> bytes:+ """Stream a validation body into memory, aborting past the byte or time cap.++ The host is customer-controlled, so the body must never be buffered unbounded (size cap) nor be+ allowed to hold the worker open by dribbling under the per-read timeout (time cap). Raises+ `WorkdayAuthError` on either — re-fetching the same request yields the same oversized/slow body.+ """+ chunks: list[bytes] = []+ total = 0+ deadline = time.monotonic() + MAX_VALIDATE_DOWNLOAD_SECONDS+ try:+ for chunk in response.iter_content(chunk_size=RESPONSE_CHUNK_BYTES):+ if time.monotonic() > deadline:+ raise WorkdayAuthError(f"{RESPONSE_TOO_SLOW_ERROR} (over {MAX_VALIDATE_DOWNLOAD_SECONDS}s)")+ if not chunk:+ continue+ total += len(chunk)+ if total > MAX_VALIDATE_RESPONSE_BYTES:+ raise WorkdayAuthError(f"{RESPONSE_TOO_LARGE_ERROR} (over {MAX_VALIDATE_RESPONSE_BYTES} bytes)")+ chunks.append(chunk)+ finally:+ response.close()+ return b"".join(chunks)+++class WorkdayResumeConfig:+ offset: int+++def normalize_hostname(hostname: str) -> str:+ """Turn whatever the user typed into a bare Workday host.++ Accepts `wd2-impl-services1.workday.com`, `https://wd2-impl-services1.workday.com/`, or+ a value with a trailing path, and returns the bare host.+ """+ hostname = hostname.strip()+ hostname = re.sub(r"^https?://", "", hostname, flags=re.IGNORECASE)+ return hostname.split("/")[0].strip().rstrip("/")+++def normalize_tenant(tenant: str) -> str:+ return tenant.strip().strip("/")+++def base_url(hostname: str) -> str:+ return f"https://{normalize_hostname(hostname)}/ccx/api"+++def token_url(hostname: str, tenant: str) -> str:+ return f"https://{normalize_hostname(hostname)}/ccx/oauth2/{normalize_tenant(tenant)}/token"+++def check_connection_target(hostname: str, tenant: str, team_id: Optional[int] = None) -> tuple[bool, str | None]:+ """Reject a malformed or internally-resolving tenant target before any credential is sent."""+ host = normalize_hostname(hostname)+ if not host or not _HOSTNAME_RE.match(host):+ return False, "Invalid Workday hostname"++ if not normalize_tenant(tenant) or not _TENANT_RE.match(normalize_tenant(tenant)):+ return False, "Invalid Workday tenant"++ # The hostname is fully customer-controlled and the OAuth2 client secret is sent to it, so+ # block hosts resolving to private/internal addresses (SSRF). Only enforced on cloud.+ if team_id is not None:+ host_ok, host_err = _is_host_safe(host, team_id)+ if not host_ok:+ return False, host_err or HOST_NOT_ALLOWED_ERROR++ return True, None+++def mint_access_token(+ hostname: str,+ tenant: str,+ client_id: str,+ client_secret: str,+ refresh_token: str,+ timeout: int = VALIDATE_TIMEOUT,+) -> str:+ """Exchange the API client's refresh token for a ~1h tenant access token.++ Workday's token endpoint takes the client credentials as HTTP Basic and the grant in the+ form body. `allow_redirects=False` keeps the secret pinned to the validated tenant host.+ """+ session = make_tracked_session(redact_values=(client_secret, refresh_token), capture=False)+ # stream=True so a customer-controlled host can't force us to buffer an unbounded token body;+ # the body is read under byte/time caps by _read_capped_body.+ response = session.post(+ token_url(hostname, tenant),+ data={"grant_type": "refresh_token", "refresh_token": refresh_token},+ auth=(client_id, client_secret),+ timeout=timeout,+ allow_redirects=False,+ stream=True,+ )++ if response.status_code != 200:+ response.close()+ raise WorkdayAuthError(f"{TOKEN_ERROR} (HTTP {response.status_code})")++ body = _read_capped_body(response)+ try:+ token = json.loads(body).get("access_token")+ except ValueError:+ raise WorkdayAuthError("The Workday token endpoint returned a non-JSON response")+ except AttributeError:+ raise WorkdayAuthError("The Workday token endpoint returned an unexpected response")++ if not isinstance(token, str) or not token:+ raise WorkdayAuthError("The Workday token endpoint returned no access token")++ return token+++def validate_credentials(+ hostname: str,+ tenant: str,+ client_id: str,+ client_secret: str,+ refresh_token: str,+ staffing_version: str,+ schema_name: Optional[str] = None,+ team_id: Optional[int] = None,+) -> tuple[bool, str | None]:+ """Mint a token, then probe one cheap collection to confirm the client can read the tenant.++ At source-create (`schema_name is None`) a 403 is accepted: the API client is genuine but+ may simply lack the domain security policy for this probe. A scoped probe treats 403 as a+ hard failure.+ """+ target_ok, target_err = check_connection_target(hostname, tenant, team_id)+ if not target_ok:+ return False, target_err++ try:+ token = mint_access_token(hostname, tenant, client_id, client_secret, refresh_token)+ except WorkdayAuthError as e:+ return False, str(e)+ except requests.exceptions.RequestException as e:+ return False, str(e)++ endpoint = WORKDAY_ENDPOINTS.get(schema_name or "") or WORKDAY_ENDPOINTS["workers"]+ url = f"{base_url(hostname)}{build_endpoint_path(endpoint, normalize_tenant(tenant), staffing_version)}"++ try:+ response = make_tracked_session(redact_values=(client_secret, refresh_token)).get(+ url,+ headers={"Authorization": f"Bearer {token}", "Accept": "application/json"},+ params={"limit": 1},+ timeout=VALIDATE_TIMEOUT,+ # A validated host could 3xx to an internal address; don't follow it (SSRF).+ allow_redirects=False,+ # stream=True so a customer-controlled host can't force us to buffer an unbounded probe+ # body — only the status line is inspected below, so the body is never read.+ stream=True,+ )+ response.close()+ except requests.exceptions.RequestException as e:+ return False, str(e)++ if response.is_redirect or response.is_permanent_redirect:+ return False, HOST_NOT_ALLOWED_ERROR++ if response.status_code == 200:+ return True, None++ if response.status_code == 401:+ return False, "Workday rejected the access token for this tenant"++ if response.status_code == 403:+ if schema_name is None:+ return True, None+ return False, "The Workday API client is not authorized for this resource"++ if response.status_code == 404:+ return False, "Workday returned 404 — check the tenant name and that the REST API is enabled"++ return False, f"Workday returned an unexpected response (HTTP {response.status_code})"+++def workday_source(+ hostname: str,+ tenant: str,+ client_id: str,+ client_secret: str,+ refresh_token: str,+ endpoint: str,+ staffing_version: str,+ team_id: int,+ job_id: str,+ resumable_source_manager: ResumableSourceManager[WorkdayResumeConfig],+) -> SourceResponse:+ endpoint_config = WORKDAY_ENDPOINTS[endpoint]+ host = normalize_hostname(hostname)+ normalized_tenant = normalize_tenant(tenant)++ rest_config: RESTAPIConfig = {+ "client": {+ "base_url": base_url(hostname),+ "headers": {"Accept": "application/json"},+ # The framework auth mints (and re-mints on expiry) the ~1h tenant access token, and+ # redacts the client secret / refresh token / access token from logs and samples.+ "auth": {+ "type": "oauth2",+ "token_url": token_url(hostname, tenant),+ "client_id": client_id,+ "client_secret": client_secret,+ "refresh_token": refresh_token,+ "grant_type": "refresh_token",+ # Workday's token endpoint expects the client credentials as HTTP Basic.+ "client_auth_method": "basic",+ },+ "paginator": OffsetPaginator(limit=DEFAULT_PAGE_SIZE, total_path="total"),+ # Pin every request — including resumed pages — to the validated tenant host, and+ # refuse redirects so a 3xx can't bounce the bearer token off-host (SSRF).+ "allowed_hosts": [host],+ "allow_redirects": False,+ "request_timeout": REQUEST_TIMEOUT,+ },+ "resources": [+ {+ "name": endpoint,+ "endpoint": {+ "path": build_endpoint_path(endpoint_config, normalized_tenant, staffing_version),+ "data_selector": "data",+ },+ }+ ],+ }++ initial_paginator_state: Optional[dict[str, Any]] = None+ if resumable_source_manager.can_resume():+ resume = resumable_source_manager.load_state()+ if resume is not None and resume.offset > 0:+ initial_paginator_state = {"offset": resume.offset}++ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:+ # Saved AFTER a page is yielded, so a crash re-fetches the last page (merge dedupes)+ # rather than skipping it.+ if state and state.get("offset"):+ resumable_source_manager.save_state(WorkdayResumeConfig(offset=int(state["offset"])))++ resource = rest_api_resource(+ rest_config,+ team_id,+ job_id,+ None,+ resume_hook=save_checkpoint,+ initial_paginator_state=initial_paginator_state,+ )++ def items() -> Iterator[Any]:+ # Re-check at run time in case the hostname was edited, or now resolves to an internal+ # address (DNS rebinding). Only enforced on cloud.+ host_ok, host_err = _is_host_safe(host, team_id)+ if not host_ok:+ raise WorkdayHostNotAllowedError(host_err or HOST_NOT_ALLOWED_ERROR)+ yield from resource++ return SourceResponse(+ name=endpoint,+ items=items,+ primary_keys=[endpoint_config.primary_key],+ partition_count=1,+ partition_size=1,+ # Workday's REST collections have no documented ordering guarantee and no server-side+ # time filter, so every run is a full refresh — nothing downstream depends on an order.+ sort_mode=None,+ )