: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(warehouse_sources): support Greenhouse API version v3 (#71666)
Tom Owers2a93321b97c4
diff --git a/.agents/skills/warehouse-source-new-version/SKILL.md b/.agents/skills/warehouse-source-new-version/SKILL.mdindex cc327344afb3..32323ec7512e 100644--- a/.agents/skills/warehouse-source-new-version/SKILL.md+++ b/.agents/skills/warehouse-source-new-version/SKILL.md@@ -101,3 +101,7 @@ After you finish a version-update or deprecation PR using this skill, **append w- Test pattern that stayed cheap: parameterize the header builder over supported versions (header carries requested version) + mock `notion_source` in the source module and assert `call_args.kwargs["api_version"]` for none/legacy/new pins (resolution + threading in one).- Auto-inferred-schema sources (`has_managed_hogql_schema=False`) turn new attributes into new columns automatically, so a version bump whose breaking changes only touch fields the source never reads needs no data/schema transform — the repin migration is a plain idempotent `api_version` UPDATE. Verify field-by-field against the changelog instead of assuming a date bump is breaking.- A repin migration's reverse must be a no-op: after repinning, rows on the new default are indistinguishable from natively-created ones, so a blanket downgrade would clobber legitimate native pins (same reasoning as the 0075 api_version backfill).+- A version bump can change the _auth scheme_, not just the wire format (Greenhouse Harvest v3 drops HTTP Basic API keys for OAuth2 client-credentials Bearer JWTs). Then the source config needs both credential shapes as optional fields, `_build_auth(api_version, ...)` picks one, and `validate_credentials` enforces the pair the resolved version needs — form-level `required` can't express "depends on the pin".+- When the new version's credentials can't be derived from the old ones, there is no repin migration to write: an `api_version` UPDATE would point existing rows at credentials they don't have. Ship the `deprecated_versions` banner and document the manual re-credential path instead.+- Keep the schema/table name set identical across versions even when the vendor renames a collection (Harvest `scheduled_interviews` -> v3 `interviews`): put the rename in a per-version path on the endpoint config, so discovery diffs can't orphan a table on repin.+- Vendor OpenAPI is often embedded in the docs pages themselves (`/reference/get_v3-<resource>.md`, indexed by `llms.txt`) — parse it to confirm paths, filter params, response envelope, and id types for all endpoints at once instead of trusting a prose migration guide.diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/greenhouse.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/greenhouse.pyindex e5dedae6ee23..1c40d4d2fa59 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/greenhouse.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/greenhouse.py@@ -6,4 +6,6 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp@config.configclass GreenhouseSourceConfig(config.Config):- api_key: str+ client_id: str | None = None+ client_secret: str | None = None+ api_key: str | None = Nonediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/greenhouse/greenhouse.py b/products/warehouse_sources/backend/temporal/data_imports/sources/greenhouse/greenhouse.pyindex b3a54d5a5bb6..26bd46bfba9c 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/greenhouse/greenhouse.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/greenhouse/greenhouse.py@@ -2,7 +2,8 @@ import dataclassesfrom datetime import UTC, date, datetimefrom typing import Any, Optional-from requests.auth import HTTPBasicAuth+import requests+from requests import Requestfrom products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponsefrom products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session@@ -10,6 +11,11 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.resRESTAPIConfig,rest_api_resource,)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.auth import (+ HttpBasicAuth,+ OAuth2Auth,+ OAuth2AuthRequestError,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (HeaderLinkPaginator,)@@ -17,14 +23,29 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.resfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.source_helpers import validate_via_probefrom products.warehouse_sources.backend.temporal.data_imports.sources.greenhouse.settings import (GREENHOUSE_ENDPOINTS,+ GREENHOUSE_V3,GreenhouseEndpointConfig,)-GREENHOUSE_BASE_URL = "https://harvest.greenhouse.io/v1"-# Harvest's documented maximum page size. Fewer requests keeps us comfortably under the-# per-10-second rate limit advertised via the `X-RateLimit-*` response headers.+GREENHOUSE_BASE_HOST = "https://harvest.greenhouse.io"+# v3 mints short-lived JWTs from the customer's own OAuth2 client credentials; v1 has no+# token exchange (the API key is sent directly as HTTP Basic on every request).+GREENHOUSE_TOKEN_URL = "https://auth.greenhouse.io/token"+# Harvest's documented maximum page size, on both v1 and v3. Fewer requests keeps us comfortably+# under the per-10-second rate limit advertised via the `X-RateLimit-*` response headers.PAGE_SIZE = 500+MISSING_V3_CREDENTIALS_ERROR = (+ "Greenhouse Harvest v3 requires OAuth client credentials. "+ "In Greenhouse, go to Configure → Dev Center → API Credential Management, create a "+ "**Harvest V3 (OAuth)** credential, and enter its client ID and client secret."+)+MISSING_V1_CREDENTIALS_ERROR = "Greenhouse Harvest v1 requires an API key."+++def _base_url(api_version: str) -> str:+ return f"{GREENHOUSE_BASE_HOST}/{api_version}"+@dataclasses.dataclassclass GreenhouseResumeConfig:@@ -46,35 +67,96 @@ def _format_datetime(value: Any) -> str:def _build_initial_params(config: GreenhouseEndpointConfig,+ api_version: str,should_use_incremental_field: bool,db_incremental_field_last_value: Any,incremental_field: str | None,) -> dict[str, Any]:params: dict[str, Any] = {"per_page": PAGE_SIZE}- if should_use_incremental_field and incremental_field and db_incremental_field_last_value is not None:- filter_param = config.incremental_filter_params.get(incremental_field)- if filter_param:- # Harvest's `*_after` filters are inclusive — merge dedupes the boundary rows.- params[filter_param] = _format_datetime(db_incremental_field_last_value)+ if not (should_use_incremental_field and incremental_field and db_incremental_field_last_value is not None):+ return params++ cursor = _format_datetime(db_incremental_field_last_value)++ if api_version == GREENHOUSE_V3:+ # v3 filters on the timestamp field itself with a pipe-delimited operator+ # (`updated_at=gte|<iso>`) instead of v1's separate `*_after` params.+ if any(field["field"] == incremental_field for field in config.incremental_fields):+ params[incremental_field] = f"gte|{cursor}"+ return params++ filter_param = config.incremental_filter_params.get(incremental_field)+ if filter_param:+ # Both versions filter inclusively (`*_after` on v1, `gte` on v3) — merge dedupes the+ # boundary rows.+ params[filter_param] = cursorreturn params+def _build_auth(+ api_version: str, api_key: str | None, client_id: str | None, client_secret: str | None+) -> HttpBasicAuth | OAuth2Auth:+ """Build the per-version request auth.++ v1 sends the Harvest API key as HTTP Basic (key as username, blank password). v3 rejects Basic+ entirely and requires a Bearer JWT minted from the customer's OAuth2 client credentials, so the+ two versions take different secrets. Supplied via framework auth either way, so the credential+ is redacted from logs and error messages.+ """+ if api_version == GREENHOUSE_V3:+ if not client_id or not client_secret:+ raise ValueError(MISSING_V3_CREDENTIALS_ERROR)+ return OAuth2Auth(+ token_url=GREENHOUSE_TOKEN_URL,+ client_id=client_id,+ client_secret=client_secret,+ grant_type="client_credentials",+ # Greenhouse takes the client credentials as HTTP Basic on the token request, not in+ # the body. Its response carries `expires_at` (an absolute ISO 8601 string) rather than+ # `expires_in`, in an unpinned format — leave the expiry hint unparsed and let the+ # framework's conservative default TTL drive re-minting.+ client_auth_method="basic",+ )++ if not api_key:+ raise ValueError(MISSING_V1_CREDENTIALS_ERROR)+ return HttpBasicAuth(api_key, "")++def validate_credentials(- api_key: str, path: str = "/candidates", accept_forbidden: bool = True+ api_version: str,+ api_key: str | None = None,+ client_id: str | None = None,+ client_secret: str | None = None,+ path: str = "/candidates",+ accept_forbidden: bool = True,) -> tuple[bool, str | None]:- """Probe a Harvest endpoint to confirm the API key is genuine.+ """Probe a Harvest endpoint on ``api_version`` to confirm the credentials are genuine.- Harvest keys are scoped per-resource: a valid key may still 403 on an endpoint it wasn't+ Harvest credentials are scoped per-resource: a valid one may still 403 on an endpoint it wasn'tgranted. At source-create time (``accept_forbidden=True``) we treat 403 as success so users- can connect with keys scoped only to the endpoints they want; per-schema checks pass+ can connect with credentials scoped only to the endpoints they want; per-schema checks pass``accept_forbidden=False`` to surface a missing-scope error for that specific endpoint."""+ try:+ auth = _build_auth(api_version, api_key, client_id, client_secret)+ except ValueError as e:+ return False, str(e)++ if isinstance(auth, OAuth2Auth):+ # Mint up front so a bad client credential reports itself instead of surfacing as an+ # unreachable probe — `validate_via_probe` swallows the exception into `(False, None)`.+ try:+ auth(Request(method="GET", url=_base_url(api_version)).prepare())+ except (OAuth2AuthRequestError, requests.RequestException):+ return False, "Invalid Greenhouse client credentials. Please check them and try again."+_ok, status = validate_via_probe(- lambda: make_tracked_session(redact_values=(api_key,)),- f"{GREENHOUSE_BASE_URL}{path}?per_page=1",- auth=HTTPBasicAuth(api_key, ""),+ lambda: make_tracked_session(redact_values=tuple(v for v in (api_key, client_secret) if v)),+ f"{_base_url(api_version)}{path}?per_page=1",+ auth=auth,)if status == 200:@@ -83,10 +165,10 @@ def validate_credentials(if status == 403:if accept_forbidden:return True, None- return False, "Your Greenhouse API key does not have permission to access this endpoint."+ return False, "Your Greenhouse credentials do not have permission to access this endpoint."if status == 401:- return False, "Invalid Greenhouse API key. Please check your key and try again."+ return False, "Invalid Greenhouse credentials. Please check them and try again."if status is None:return False, "Could not reach the Greenhouse API. Please try again."@@ -95,11 +177,14 @@ def validate_credentials(def greenhouse_source(- api_key: str,endpoint: str,team_id: int,job_id: str,+ api_version: str,resumable_source_manager: ResumableSourceManager[GreenhouseResumeConfig],+ api_key: str | None = None,+ client_id: str | None = None,+ client_secret: str | None = None,should_use_incremental_field: bool = False,db_incremental_field_last_value: Optional[Any] = None,incremental_field: str | None = None,@@ -107,24 +192,29 @@ def greenhouse_source(config = GREENHOUSE_ENDPOINTS[endpoint]params = _build_initial_params(- config, should_use_incremental_field, db_incremental_field_last_value, incremental_field+ config, api_version, should_use_incremental_field, db_incremental_field_last_value, incremental_field)rest_config: RESTAPIConfig = {"client": {- "base_url": GREENHOUSE_BASE_URL,- # Harvest uses HTTP Basic auth with the API key as the username and a blank password.- # Supplied via framework auth so the key is redacted from logs and error messages.- "auth": {"type": "http_basic", "username": api_key, "password": ""},- # Harvest paginates with RFC 5988 `Link` headers; the paginator follows the- # `rel="next"` URL verbatim (it already encodes per_page + filters).+ "base_url": _base_url(api_version),+ "auth": _build_auth(api_version, api_key, client_id, client_secret),+ # Both versions paginate with RFC 5988 `Link` headers; the paginator follows the+ # `rel="next"` URL verbatim. v1's carries per_page + filters, v3's carries an opaque+ # cursor that must travel alone — following it verbatim satisfies both."paginator": HeaderLinkPaginator(),+ # Because that next URL is followed verbatim, pin every request (paginator and seeded+ # resume URLs included) to the base host and reject cross-host redirects: a spoofed+ # link must not be able to replay the credential — v3's minted Bearer token especially+ # — to another origin. `allowed_hosts=[]` means "same host as base_url only".+ "allowed_hosts": [],+ "allow_redirects": False,},"resources": [{"name": endpoint,"endpoint": {- "path": config.path,+ "path": config.path_for_version(api_version),"params": params,},}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/greenhouse/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/greenhouse/settings.pyindex cf89ca42e181..9908995190bf 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/greenhouse/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/greenhouse/settings.py@@ -3,6 +3,10 @@ from typing import Optionalfrom products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType+# Harvest embeds the API version as the first path segment (`/v1/candidates`, `/v3/candidates`).+GREENHOUSE_V1 = "v1"+GREENHOUSE_V3 = "v3"+@dataclassclass GreenhouseEndpointConfig:@@ -14,10 +18,18 @@ class GreenhouseEndpointConfig:# object's lifetime (so `created_at`, never `updated_at`). Left as ``None`` for the small# reference endpoints whose objects don't expose a creation timestamp.partition_key: Optional[str] = None- # Maps an advertised incremental field name to the Harvest query param that filters it+ # Maps an advertised incremental field name to the Harvest v1 query param that filters it# server-side (e.g. `updated_at` -> `updated_after`). Only populated for endpoints with a- # genuine documented server-side timestamp filter.+ # genuine documented server-side timestamp filter. v3 filters on the field name itself, so+ # it needs no mapping.incremental_filter_params: dict[str, str] = field(default_factory=dict)+ # Harvest v3 path, where v3 renamed the collection. ``None`` means v3 kept the v1 name.+ v3_path: Optional[str] = None++ def path_for_version(self, api_version: str) -> str:+ if api_version == GREENHOUSE_V3 and self.v3_path is not None:+ return self.v3_path+ return self.pathdef _datetime_incremental_field(name: str) -> IncrementalField:@@ -126,6 +138,9 @@ GREENHOUSE_ENDPOINTS: dict[str, GreenhouseEndpointConfig] = {"scheduled_interviews": GreenhouseEndpointConfig(name="scheduled_interviews",path="/scheduled_interviews",+ # v3 renamed this collection to `interviews`. The schema (and so the warehouse table) keeps+ # its v1 name so the table set is identical on both versions and a repin can't orphan a table.+ v3_path="/interviews",primary_keys=["id"],partition_key="created_at",incremental_fields=[diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/greenhouse/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/greenhouse/source.pyindex 83237b9c561f..bb6fa1f1ab11 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/greenhouse/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/greenhouse/source.py@@ -1,3 +1,4 @@+from datetime import datefrom typing import Optional, castfrom posthog.schema import (@@ -13,11 +14,18 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipelineSourceInputs,SourceResponse,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import (+ FieldType,+ ResumableSource,+ VersionDeprecation,+)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.rest_source.auth import (+ OAUTH2_PERMANENT_ERROR_MARKER,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManagerfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import (SourceSchema,@@ -27,6 +35,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.generated_GreenhouseSourceConfig,)from products.warehouse_sources.backend.temporal.data_imports.sources.greenhouse.greenhouse import (+ MISSING_V3_CREDENTIALS_ERROR,GreenhouseResumeConfig,greenhouse_source,validate_credentials as validate_greenhouse_credentials,@@ -34,6 +43,8 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.greenhousefrom products.warehouse_sources.backend.temporal.data_imports.sources.greenhouse.settings import (ENDPOINTS,GREENHOUSE_ENDPOINTS,+ GREENHOUSE_V1,+ GREENHOUSE_V3,INCREMENTAL_FIELDS,)from products.warehouse_sources.backend.types import ExternalDataSourceType@@ -41,9 +52,11 @@ from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.registerclass GreenhouseSource(ResumableSource[GreenhouseSourceConfig, GreenhouseResumeConfig]):- supported_versions = ("v1",)- default_version = "v1"- api_docs_url = "https://developers.greenhouse.io/harvest.html"+ supported_versions = (GREENHOUSE_V1, GREENHOUSE_V3)+ default_version = GREENHOUSE_V3+ api_docs_url = "https://harvestdocs.greenhouse.io"+ # Greenhouse removes the v1/v2 Harvest API on 2026-08-31 in favour of v3.+ deprecated_versions = (VersionDeprecation(version=GREENHOUSE_V1, sunset_at=date(2026, 8, 31)),)lists_tables_without_credentials = True # static endpoint catalog — safe for public docs@@ -58,21 +71,42 @@ class GreenhouseSource(ResumableSource[GreenhouseSourceConfig, GreenhouseResumeCcategory=DataWarehouseSourceCategory.HR___RECRUITING,label="Greenhouse",releaseStatus=ReleaseStatus.ALPHA,- caption="""Enter your Greenhouse Harvest API key to automatically pull your Greenhouse recruiting data into the PostHog Data warehouse.+ caption="""Enter your Greenhouse Harvest credentials to automatically pull your Greenhouse recruiting data into the PostHog Data warehouse.-You can create a Harvest API key in Greenhouse under **Configure → Dev Center → API Credential Management**.+Create credentials in Greenhouse under **Configure → Dev Center → API Credential Management**.-Grant the key read (`GET`) access to the resources you want to sync — for example **Candidates**, **Applications**, **Jobs**, **Job Posts**, **Offers**, **Scorecards**, **Scheduled Interviews**, and **Users**.""",+New connections use Harvest v3, which needs a **Harvest V3 (OAuth)** credential — enter its client ID and client secret. Grant it the list scopes for the resources you want to sync (for example `harvest:candidates:list`), and make sure the authorizing user is a site admin, since every list endpoint requires one.++The API key field is only for connections still on Harvest v1, which Greenhouse removes on 31 August 2026.""",iconPath="/static/services/greenhouse.png",docsUrl="https://posthog.com/docs/cdp/sources/greenhouse",fields=cast(list[FieldType],+ # No field is required at the form level because the two versions take different+ # secrets — v3 the OAuth client pair, v1 the API key. `validate_credentials`+ # enforces the pair the resolved version actually needs.[+ SourceFieldInputConfig(+ name="client_id",+ label="Client ID (Harvest v3)",+ type=SourceFieldInputConfigType.TEXT,+ required=False,+ placeholder="",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="client_secret",+ label="Client secret (Harvest v3)",+ type=SourceFieldInputConfigType.PASSWORD,+ required=False,+ placeholder="",+ secret=True,+ ),SourceFieldInputConfig(name="api_key",- label="API key",+ label="API key (Harvest v1)",type=SourceFieldInputConfigType.PASSWORD,- required=True,+ required=False,placeholder="",secret=True,),@@ -105,20 +139,37 @@ Grant the key read (`GET`) access to the resources you want to sync — for examschema_name: Optional[str] = None,api_version: str | None = None,) -> tuple[bool, str | None]:- # At source-create (`schema_name is None`) accept a 403 — the key may legitimately be- # scoped only to the endpoints the user wants. For a per-schema check, probe that+ # The probe differs by version (path segment, and Basic vs Bearer), so a v1-pinned source+ # must be probed on v1 even though new sources default to v3.+ version = self.resolve_api_version(api_version)++ # At source-create (`schema_name is None`) accept a 403 — the credential may legitimately+ # be scoped only to the endpoints the user wants. For a per-schema check, probe that# endpoint and surface a missing-scope error.if schema_name is not None and schema_name in GREENHOUSE_ENDPOINTS:return validate_greenhouse_credentials(- config.api_key, path=GREENHOUSE_ENDPOINTS[schema_name].path, accept_forbidden=False+ version,+ api_key=config.api_key,+ client_id=config.client_id,+ client_secret=config.client_secret,+ path=GREENHOUSE_ENDPOINTS[schema_name].path_for_version(version),+ accept_forbidden=False,)- return validate_greenhouse_credentials(config.api_key, accept_forbidden=True)+ return validate_greenhouse_credentials(+ version,+ api_key=config.api_key,+ client_id=config.client_id,+ client_secret=config.client_secret,+ accept_forbidden=True,+ )def get_non_retryable_errors(self) -> dict[str, str | None]:return {- "401 Client Error: Unauthorized for url: https://harvest.greenhouse.io": "Your Greenhouse API key is invalid or expired. Please generate a new key and reconnect.",- "403 Client Error: Forbidden for url: https://harvest.greenhouse.io": "Your Greenhouse API key does not have the required permissions. Please grant read access to this resource and try again.",+ "401 Client Error: Unauthorized for url: https://harvest.greenhouse.io": "Your Greenhouse credentials are invalid or expired. Please generate new credentials and reconnect.",+ "403 Client Error: Forbidden for url: https://harvest.greenhouse.io": "Your Greenhouse credentials do not have the required permissions. Please grant read access to this resource and try again. Harvest v3 list endpoints also require the authorizing user to be a site admin.",+ OAUTH2_PERMANENT_ERROR_MARKER: "Greenhouse authentication failed. Please check the client ID and client secret of your Harvest V3 (OAuth) credential.",+ MISSING_V3_CREDENTIALS_ERROR: None,}def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[GreenhouseResumeConfig]:@@ -132,9 +183,12 @@ Grant the key read (`GET`) access to the resources you want to sync — for exam) -> SourceResponse:return greenhouse_source(api_key=config.api_key,+ client_id=config.client_id,+ client_secret=config.client_secret,endpoint=inputs.schema_name,team_id=inputs.team_id,job_id=inputs.job_id,+ api_version=self.resolve_api_version(inputs.api_version),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_valuediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/greenhouse/tests/test_greenhouse.py b/products/warehouse_sources/backend/temporal/data_imports/sources/greenhouse/tests/test_greenhouse.pyindex 24f13684a2c8..905020d7b21d 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/greenhouse/tests/test_greenhouse.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/greenhouse/tests/test_greenhouse.py@@ -9,16 +9,26 @@ from unittest.mock import MagicMockfrom requests import Response+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.auth import (+ HttpBasicAuth,+ OAuth2Auth,+)from products.warehouse_sources.backend.temporal.data_imports.sources.greenhouse.greenhouse import (GREENHOUSE_ENDPOINTS,+ GREENHOUSE_TOKEN_URL,PAGE_SIZE,GreenhouseResumeConfig,+ _build_auth,_build_initial_params,_format_datetime,greenhouse_source,validate_credentials,)-from products.warehouse_sources.backend.temporal.data_imports.sources.greenhouse.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.greenhouse.settings import (+ ENDPOINTS,+ GREENHOUSE_V1,+ GREENHOUSE_V3,+)# 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"@@ -26,6 +36,7 @@ CLIENT_SESSION_PATCH = "products.warehouse_sources.backend.temporal.data_importsGREENHOUSE_SESSION_PATCH = ("products.warehouse_sources.backend.temporal.data_imports.sources.greenhouse.greenhouse.make_tracked_session")+OAUTH_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.auth"def _make_response(body: Any, status_code: int = 200, next_url: str | None = None) -> Response:@@ -46,6 +57,15 @@ def _make_manager(resume_state: GreenhouseResumeConfig | None = None) -> MagicMoreturn manager+def _source(endpoint: str, **kwargs: Any) -> Any:+ # Transport tests run on v1: its HTTP Basic auth needs no token exchange, so the only network+ # boundary is the patched rest_client session. Version-specific request shape is covered by the+ # param/auth/url tests below.+ kwargs.setdefault("resumable_source_manager", _make_manager())+ kwargs.setdefault("api_version", GREENHOUSE_V1)+ return greenhouse_source(endpoint, team_id=1, job_id="j", api_key="key", **kwargs)++class TestFormatDatetime:@pytest.mark.parametrize("value, expected",@@ -64,35 +84,73 @@ class TestFormatDatetime:assert "+00:00" not in _format_datetime(datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC))+WATERMARK = datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC)++class TestBuildInitialParams:- def test_full_refresh_only_sets_per_page(self) -> None:- params = _build_initial_params(GREENHOUSE_ENDPOINTS["departments"], False, None, None)+ @pytest.mark.parametrize("api_version", [GREENHOUSE_V1, GREENHOUSE_V3])+ def test_full_refresh_only_sets_per_page(self, api_version: str) -> None:+ params = _build_initial_params(GREENHOUSE_ENDPOINTS["departments"], api_version, False, None, None)assert params == {"per_page": PAGE_SIZE}- def test_first_incremental_sync_has_no_filter(self) -> None:+ @pytest.mark.parametrize("api_version", [GREENHOUSE_V1, GREENHOUSE_V3])+ def test_first_incremental_sync_has_no_filter(self, api_version: str) -> None:# No watermark yet -> pull everything, only per_page is set.- params = _build_initial_params(GREENHOUSE_ENDPOINTS["candidates"], True, None, "updated_at")+ params = _build_initial_params(GREENHOUSE_ENDPOINTS["candidates"], api_version, True, None, "updated_at")assert params == {"per_page": PAGE_SIZE}- def test_incremental_filter_maps_updated_at_to_updated_after(self) -> None:- watermark = datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC)- params = _build_initial_params(GREENHOUSE_ENDPOINTS["candidates"], True, watermark, "updated_at")- assert params == {"per_page": PAGE_SIZE, "updated_after": "2026-03-04T02:58:14.000Z"}+ @pytest.mark.parametrize(+ "endpoint, api_version, incremental_field, expected_filter",+ [+ # v1 filters through a separate `*_after` param; v3 filters on the field itself with a+ # pipe-delimited operator. Sending one version's syntax to the other silently drops the+ # filter (full re-sync every run) or 422s.+ ("candidates", GREENHOUSE_V1, "updated_at", {"updated_after": "2026-03-04T02:58:14.000Z"}),+ ("candidates", GREENHOUSE_V3, "updated_at", {"updated_at": "gte|2026-03-04T02:58:14.000Z"}),+ ("candidates", GREENHOUSE_V1, "created_at", {"created_after": "2026-03-04T02:58:14.000Z"}),+ ("candidates", GREENHOUSE_V3, "created_at", {"created_at": "gte|2026-03-04T02:58:14.000Z"}),+ ("applications", GREENHOUSE_V1, "last_activity_at", {"last_activity_after": "2026-03-04T02:58:14.000Z"}),+ ("applications", GREENHOUSE_V3, "last_activity_at", {"last_activity_at": "gte|2026-03-04T02:58:14.000Z"}),+ ("candidates", GREENHOUSE_V1, "somethingElse", {}),+ ("candidates", GREENHOUSE_V3, "somethingElse", {}),+ ],+ )+ def test_incremental_filter_syntax_per_version(+ self, endpoint: str, api_version: str, incremental_field: str, expected_filter: dict[str, str]+ ) -> None:+ params = _build_initial_params(GREENHOUSE_ENDPOINTS[endpoint], api_version, True, WATERMARK, incremental_field)+ assert params == {"per_page": PAGE_SIZE, **expected_filter}- def test_incremental_filter_uses_chosen_cursor_field(self) -> None:- watermark = datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC)- params = _build_initial_params(GREENHOUSE_ENDPOINTS["candidates"], True, watermark, "created_at")- assert params == {"per_page": PAGE_SIZE, "created_after": "2026-03-04T02:58:14.000Z"}- def test_applications_uses_last_activity_after(self) -> None:- watermark = datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC)- params = _build_initial_params(GREENHOUSE_ENDPOINTS["applications"], True, watermark, "last_activity_at")- assert params == {"per_page": PAGE_SIZE, "last_activity_after": "2026-03-04T02:58:14.000Z"}+class TestBuildAuth:+ def test_v1_sends_the_api_key_as_http_basic(self) -> None:+ auth = _build_auth(GREENHOUSE_V1, "test_key", None, None)+ assert isinstance(auth, HttpBasicAuth)+ assert (auth.username, auth.password) == ("test_key", "")- def test_unknown_cursor_field_is_ignored(self) -> None:- watermark = datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC)- params = _build_initial_params(GREENHOUSE_ENDPOINTS["candidates"], True, watermark, "somethingElse")- assert params == {"per_page": PAGE_SIZE}+ def test_v3_mints_a_bearer_token_from_oauth_client_credentials(self) -> None:+ # v3 rejects Basic outright, so an api_key-shaped auth here 401s on every request.+ auth = _build_auth(GREENHOUSE_V3, "test_key", "cid", "csecret")+ assert isinstance(auth, OAuth2Auth)+ assert auth.token_url == GREENHOUSE_TOKEN_URL+ assert (auth.client_id, auth.client_secret) == ("cid", "csecret")+ assert auth.grant_type == "client_credentials"+ # Greenhouse takes the client pair as Basic on the token request, not in the body.+ assert auth.client_auth_method == "basic"++ @pytest.mark.parametrize(+ "api_version, api_key, client_id, client_secret",+ [+ (GREENHOUSE_V3, "test_key", None, None),+ (GREENHOUSE_V3, "test_key", "cid", None),+ (GREENHOUSE_V1, None, "cid", "csecret"),+ ],+ )+ def test_credentials_for_the_other_version_are_rejected(+ self, api_version: str, api_key: str | None, client_id: str | None, client_secret: str | None+ ) -> None:+ with pytest.raises(ValueError):+ _build_auth(api_version, api_key, client_id, client_secret)class TestValidateCredentials:@@ -114,7 +172,7 @@ class TestValidateCredentials:) -> None:mock_session_factory.return_value.get.return_value = MagicMock(status_code=status_code)- is_valid, error = validate_credentials("test_key", accept_forbidden=accept_forbidden)+ is_valid, error = validate_credentials(GREENHOUSE_V1, api_key="test_key", accept_forbidden=accept_forbidden)assert is_valid is expected_validassert (error is None) is expected_valid@@ -122,7 +180,9 @@ class TestValidateCredentials:@mock.patch(GREENHOUSE_SESSION_PATCH)def test_per_schema_forbidden_surfaces_scope_error(self, mock_session_factory: MagicMock) -> None:mock_session_factory.return_value.get.return_value = MagicMock(status_code=403)- is_valid, error = validate_credentials("test_key", path="/candidates", accept_forbidden=False)+ is_valid, error = validate_credentials(+ GREENHOUSE_V1, api_key="test_key", path="/candidates", accept_forbidden=False+ )assert is_valid is Falseassert error is not None and "permission" in error@@ -130,7 +190,7 @@ class TestValidateCredentials:def test_network_error_is_not_valid(self, mock_session_factory: MagicMock) -> None:# validate_via_probe swallows transport errors and reports "not validated".mock_session_factory.return_value.get.side_effect = Exception("boom")- is_valid, error = validate_credentials("test_key")+ is_valid, error = validate_credentials(GREENHOUSE_V1, api_key="test_key")assert is_valid is Falseassert error is not None@@ -139,21 +199,46 @@ class TestValidateCredentials:mock_get = mock_session_factory.return_value.getmock_get.return_value = MagicMock(status_code=200)- validate_credentials("test_key")+ validate_credentials(GREENHOUSE_V1, api_key="test_key")auth = mock_get.call_args.kwargs["auth"]assert (auth.username, auth.password) == ("test_key", "")+ @pytest.mark.parametrize(+ "api_version, expected_url",+ [+ (GREENHOUSE_V1, "https://harvest.greenhouse.io/v1/candidates?per_page=1"),+ (GREENHOUSE_V3, "https://harvest.greenhouse.io/v3/candidates?per_page=1"),+ ],+ )+ @mock.patch(f"{OAUTH_MODULE}.OAuth2Auth._obtain_token")+ @mock.patch(GREENHOUSE_SESSION_PATCH)+ def test_probes_the_pinned_version(+ self, mock_session_factory: MagicMock, mock_mint: MagicMock, api_version: str, expected_url: str+ ) -> None:+ # A v1-pinned source probed on the v3 path (or vice versa) reports a working key as broken.+ mock_get = mock_session_factory.return_value.get+ mock_get.return_value = MagicMock(status_code=200)++ validate_credentials(api_version, api_key="test_key", client_id="cid", client_secret="csecret")++ assert mock_get.call_args.args[0] == expected_url++ def test_v3_without_client_credentials_explains_what_to_create(self) -> None:+ is_valid, error = validate_credentials(GREENHOUSE_V3, api_key="test_key")+ assert is_valid is False+ assert error is not None and "OAuth" in error+class TestGreenhouseSourceResponse:@pytest.mark.parametrize("endpoint", list(ENDPOINTS))def test_primary_keys_match_settings(self, endpoint: str) -> None:- response = greenhouse_source("key", endpoint, team_id=1, job_id="j", resumable_source_manager=_make_manager())+ response = _source(endpoint)assert response.primary_keys == GREENHOUSE_ENDPOINTS[endpoint].primary_keys@pytest.mark.parametrize("endpoint", list(ENDPOINTS))def test_partitioning_only_when_partition_key_present(self, endpoint: str) -> None:- response = greenhouse_source("key", endpoint, team_id=1, job_id="j", resumable_source_manager=_make_manager())+ response = _source(endpoint)partition_key = GREENHOUSE_ENDPOINTS[endpoint].partition_keyif partition_key:@@ -168,10 +253,58 @@ class TestGreenhouseSourceResponse:assert GREENHOUSE_ENDPOINTS[endpoint].partition_key not in ("updated_at", "last_activity_at")def test_sort_mode_is_ascending(self) -> None:+ response = _source("candidates")+ assert response.sort_mode == "asc"+++class TestRequestUrlPerVersion:+ @pytest.mark.parametrize(+ "endpoint, api_version, expected_url",+ [+ ("candidates", GREENHOUSE_V1, "https://harvest.greenhouse.io/v1/candidates"),+ ("candidates", GREENHOUSE_V3, "https://harvest.greenhouse.io/v3/candidates"),+ # v3 renamed this collection; the schema (and warehouse table) keeps the v1 name.+ ("scheduled_interviews", GREENHOUSE_V1, "https://harvest.greenhouse.io/v1/scheduled_interviews"),+ ("scheduled_interviews", GREENHOUSE_V3, "https://harvest.greenhouse.io/v3/interviews"),+ ],+ )+ @mock.patch(f"{OAUTH_MODULE}.OAuth2Auth._obtain_token")+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_first_request_targets_the_versioned_collection(+ self,+ mock_factory: MagicMock,+ mock_mint: MagicMock,+ endpoint: str,+ api_version: str,+ expected_url: str,+ ) -> None:+ session = mock_factory.return_value+ session.headers = {}+ sent: list[str] = []++ def _prepare(request: Any) -> MagicMock:+ sent.append(request.url)+ prepared = MagicMock()+ prepared.url = request.url+ return prepared++ session.prepare_request.side_effect = _prepare+ session.send.side_effect = [_make_response([])]+response = greenhouse_source(- "key", "candidates", team_id=1, job_id="j", resumable_source_manager=_make_manager()+ endpoint,+ team_id=1,+ job_id="j",+ api_version=api_version,+ resumable_source_manager=_make_manager(),+ api_key="key",+ client_id="cid",+ client_secret="csecret",)- assert response.sort_mode == "asc"+ pages: Any = response.items()+ [row for page in pages for row in page]++ assert sent[0] == expected_urlclass TestGreenhousePaginationAndResume:@@ -207,15 +340,45 @@ class TestGreenhousePaginationAndResume:],)- rows = self._rows(- greenhouse_source("key", "candidates", team_id=1, job_id="j", resumable_source_manager=_make_manager())- )+ rows = self._rows(_source("candidates"))# First request hits the path with params; second follows the Link URL verbatim (no params).assert sent[0] == ("https://harvest.greenhouse.io/v1/candidates", {"per_page": PAGE_SIZE})assert sent[1] == (next_url, {})assert rows == [{"id": 1}, {"id": 2}]+ @pytest.mark.parametrize(+ "hostile_next_url",+ [+ "https://evil.example.com/v1/candidates?page=2",+ # An allowed hostname over a downgraded scheme still puts the credential on the wire.+ "http://harvest.greenhouse.io/v1/candidates?page=2",+ ],+ )+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_off_origin_next_link_is_rejected_before_a_request_is_sent(+ self, mock_factory: MagicMock, hostile_next_url: str+ ) -> None:+ # The Link URL is followed verbatim, so a spoofed one would otherwise replay the+ # Authorization header (v3: a freshly minted Bearer token) to another origin.+ session = mock_factory.return_value+ self._wire(session, [_make_response([{"id": 1}], next_url=hostile_next_url)])++ with pytest.raises(ValueError):+ self._rows(_source("candidates"))++ assert session.send.call_count == 1++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_cross_origin_redirect_is_not_followed(self, mock_factory: MagicMock) -> None:+ session = mock_factory.return_value+ redirect = _make_response([], status_code=302)+ redirect.headers["Location"] = "https://evil.example.com/v1/candidates"+ self._wire(session, [redirect])++ with pytest.raises(ValueError):+ self._rows(_source("candidates"))+@mock.patch(CLIENT_SESSION_PATCH)def test_incremental_filter_applied_to_first_request(self, mock_factory: MagicMock) -> None:session = mock_factory.return_value@@ -223,12 +386,8 @@ class TestGreenhousePaginationAndResume:watermark = datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC)self._rows(- greenhouse_source(- "key",+ _source("candidates",- team_id=1,- job_id="j",- resumable_source_manager=_make_manager(),should_use_incremental_field=True,db_incremental_field_last_value=watermark,incremental_field="updated_at",@@ -252,7 +411,7 @@ class TestGreenhousePaginationAndResume:)manager = _make_manager()- self._rows(greenhouse_source("key", "jobs", team_id=1, job_id="j", resumable_source_manager=manager))+ self._rows(_source("jobs", resumable_source_manager=manager))saved = [call.args[0] for call in manager.save_state.call_args_list]assert saved == [GreenhouseResumeConfig(next_url=url2), GreenhouseResumeConfig(next_url=url3)]@@ -263,7 +422,7 @@ class TestGreenhousePaginationAndResume:self._wire(session, [_make_response([{"id": 1}])])manager = _make_manager()- self._rows(greenhouse_source("key", "jobs", team_id=1, job_id="j", resumable_source_manager=manager))+ self._rows(_source("jobs", resumable_source_manager=manager))manager.save_state.assert_not_called()@mock.patch(CLIENT_SESSION_PATCH)@@ -273,7 +432,7 @@ class TestGreenhousePaginationAndResume:sent = self._wire(session, [_make_response([{"id": 9}])])manager = _make_manager(GreenhouseResumeConfig(next_url=saved_url))- self._rows(greenhouse_source("key", "candidates", team_id=1, job_id="j", resumable_source_manager=manager))+ self._rows(_source("candidates", resumable_source_manager=manager))assert sent[0] == (saved_url, {})@@ -282,9 +441,7 @@ class TestGreenhousePaginationAndResume:session = mock_factory.return_valuesent = self._wire(session, [_make_response([])])- rows = self._rows(- greenhouse_source("key", "jobs", team_id=1, job_id="j", resumable_source_manager=_make_manager())- )+ rows = self._rows(_source("jobs"))assert rows == []assert session.send.call_count == 1assert len(sent) == 1diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/greenhouse/tests/test_greenhouse_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/greenhouse/tests/test_greenhouse_source.pyindex 9f8b1cdb8748..662e1c461ae1 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/greenhouse/tests/test_greenhouse_source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/greenhouse/tests/test_greenhouse_source.py@@ -30,7 +30,7 @@ class TestGreenhouseSource:def setup_method(self) -> None:self.source = GreenhouseSource()self.team_id = 123- self.config = GreenhouseSourceConfig(api_key="test_api_key")+ self.config = GreenhouseSourceConfig(api_key="test_api_key", client_id="cid", client_secret="csecret")def test_source_type(self) -> None:assert self.source.source_type == ExternalDataSourceType.GREENHOUSE@@ -43,14 +43,14 @@ class TestGreenhouseSource:assert config.releaseStatus == "alpha"assert not config.unreleasedSourceassert config.iconPath == "/static/services/greenhouse.png"- assert len(config.fields) == 1- api_key_field = config.fields[0]- assert isinstance(api_key_field, SourceFieldInputConfig)- assert api_key_field.name == "api_key"- assert api_key_field.type == SourceFieldInputConfigType.PASSWORD- assert api_key_field.required is True- assert api_key_field.secret is True+ fields = {field.name: field for field in config.fields if isinstance(field, SourceFieldInputConfig)}+ assert set(fields) == {"client_id", "client_secret", "api_key"}+ # No field is required at the form level: v3 takes the OAuth client pair and v1 the API key,+ # so `validate_credentials` enforces whichever the resolved version needs.+ assert not any(field.required for field in fields.values())+ assert {name for name, field in fields.items() if field.secret} == {"client_secret", "api_key"}+ assert fields["client_secret"].type == SourceFieldInputConfigType.PASSWORD@pytest.mark.parametrize("expected_key",@@ -119,7 +119,9 @@ class TestGreenhouseSource:assert is_valid is Trueassert error is None- mock_validate.assert_called_once_with("test_api_key", accept_forbidden=True)+ mock_validate.assert_called_once_with(+ "v3", api_key="test_api_key", client_id="cid", client_secret="csecret", accept_forbidden=True+ )@mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.greenhouse.source.validate_greenhouse_credentials"@@ -129,7 +131,57 @@ class TestGreenhouseSource:self.source.validate_credentials(self.config, self.team_id, schema_name="candidates")- mock_validate.assert_called_once_with("test_api_key", path="/candidates", accept_forbidden=False)+ mock_validate.assert_called_once_with(+ "v3",+ api_key="test_api_key",+ client_id="cid",+ client_secret="csecret",+ path="/candidates",+ accept_forbidden=False,+ )++ @pytest.mark.parametrize(+ "pinned_version, expected_version, expected_path",+ [+ (None, "v3", "/interviews"),+ ("v3", "v3", "/interviews"),+ # A v1-pinned source must be probed on v1, not on the (newer) default.+ ("v1", "v1", "/scheduled_interviews"),+ ],+ )+ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.greenhouse.source.validate_greenhouse_credentials"+ )+ def test_validate_credentials_probes_the_pinned_version(+ self,+ mock_validate: mock.MagicMock,+ pinned_version: str | None,+ expected_version: str,+ expected_path: str,+ ) -> None:+ mock_validate.return_value = (True, None)++ self.source.validate_credentials(+ self.config, self.team_id, schema_name="scheduled_interviews", api_version=pinned_version+ )++ assert mock_validate.call_args.args[0] == expected_version+ assert mock_validate.call_args.kwargs["path"] == expected_path++ @pytest.mark.parametrize("pinned_version, expected_version", [(None, "v3"), ("v3", "v3"), ("v1", "v1")])+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.greenhouse.source.greenhouse_source")+ def test_source_for_pipeline_passes_the_resolved_version(+ self, mock_greenhouse_source: mock.MagicMock, pinned_version: str | None, expected_version: str+ ) -> None:+ inputs = mock.MagicMock()+ inputs.schema_name = "candidates"+ inputs.api_version = pinned_version++ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)++ kwargs = mock_greenhouse_source.call_args.kwargs+ assert kwargs["api_version"] == expected_version+ assert (kwargs["client_id"], kwargs["client_secret"]) == ("cid", "csecret")def test_get_resumable_source_manager_binds_resume_config(self) -> None:manager = self.source.get_resumable_source_manager(mock.MagicMock())