Skip to content

: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.

fix(warehouse-sources): refuse vendor redirects in Persona, Sprig and Bill.com (#101797)

jake sciottob9e6467cfd0c
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bill_com/bill_com.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bill_com/bill_com.py
index d5d86eaaf0db..852f37143f1c 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/bill_com/bill_com.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bill_com/bill_com.py
@@ -2,6 +2,7 @@ import dataclasses
from collections.abc import Iterator
from datetime import UTC, date, datetime
from typing import Any, Optional
+from urllib.parse import urljoin, urlparse
import requests
from structlog.types import FilteringBoundLogger
@@ -34,6 +35,18 @@ class BillComAuthError(Exception):
"""Sign-in was rejected — the credentials are wrong, not a transient failure."""
+class BillComRedirectError(Exception):
+ """The API answered with a 3xx. Redirects are refused so the credentials stay on the API host."""
+
+
+def _refuse_redirect(response: requests.Response) -> None:
+ if not 300 <= response.status_code < 400:
+ return
+ location = response.headers.get("Location") or ""
+ target = urlparse(urljoin(response.url or "", location)).hostname or "an unknown host"
+ raise BillComRedirectError(f"BILL redirected the API request to {target}; refusing to follow")
+
+
def base_url(environment: str) -> str:
host = BILL_COM_HOSTS.get(environment)
if host is None:
@@ -102,7 +115,10 @@ class BillComClient:
# capture: BILL responses carry raw financial records (bank accounts, routing numbers,
# payments, invoices, customers, vendors) and the login exchange returns a freshly minted
# session ID in a generic field — content the name-based scrubbers can't reliably redact.
- self._session = make_tracked_session(redact_values=(password, dev_key), capture=False)
+ # allow_redirects=False: `requests` drops `Authorization` on a cross-host redirect but
+ # replays custom headers (`sessionId`, `devKey`) and a 307/308 POST body (the sign-in
+ # password), so a redirect must never be followed.
+ self._session = make_tracked_session(redact_values=(password, dev_key), capture=False, allow_redirects=False)
@property
def api_root(self) -> str:
@@ -125,6 +141,7 @@ class BillComClient:
)
if response.status_code in (400, 401, 403):
raise BillComAuthError(f"BILL sign-in failed: {error_message(response)}")
+ _refuse_redirect(response)
response.raise_for_status()
session_id = response.json().get("sessionId")
@@ -152,6 +169,7 @@ class BillComClient:
self.login()
response = self._get(path, params)
+ _refuse_redirect(response)
response.raise_for_status()
body = response.json()
return body if isinstance(body, dict) else {}
@@ -241,7 +259,7 @@ def validate_credentials(
api_version=api_version,
)
client.login()
- except (BillComAuthError, ValueError) as e:
+ except (BillComAuthError, BillComRedirectError, ValueError) as e:
return False, str(e)
except Exception:
return False, "Could not reach BILL. Please check your credentials and try again."
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bill_com/tests/test_bill_com.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bill_com/tests/test_bill_com.py
index 1c77d2b44511..6cae1e4b4843 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/bill_com/tests/test_bill_com.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bill_com/tests/test_bill_com.py
@@ -6,11 +6,13 @@ import pytest
from unittest import mock
import requests
+import requests_mock
from products.warehouse_sources.backend.temporal.data_imports.sources.bill_com.bill_com import (
PAGE_SIZE,
BillComAuthError,
BillComClient,
+ BillComRedirectError,
BillComResumeConfig,
base_url,
bill_com_source,
@@ -382,3 +384,55 @@ class TestBillCom:
assert pages == [[{"id": "00n1", "createdTime": "2026-03-01T00:00:00Z"}]]
assert session.get.call_args.kwargs["params"]["filters"] == "updatedTime:gte:2026-03-01T00:00:00.000Z"
+
+
+class TestRedirectsRefused:
+ # `requests` drops `Authorization` on a cross-host redirect but replays custom headers, so
+ # `sessionId` and `devKey` would reach the redirect target. The session refuses every 3xx.
+ API_ROOT = "https://gateway.prod.bill.com/connect/v3"
+ TARGET_URL = "https://www.bill.com/connect/v3/bills"
+
+ def _real_client(self) -> BillComClient:
+ return BillComClient(
+ username="[email protected]",
+ password="pw",
+ organization_id="org-1",
+ dev_key="dev-key",
+ environment="production",
+ api_version="v3",
+ )
+
+ @pytest.mark.parametrize("status", [301, 302])
+ def test_list_page_refuses_redirect_and_keeps_session_headers_on_api_host(self, status: int) -> None:
+ with requests_mock.Mocker() as m:
+ m.post(f"{self.API_ROOT}/login", json={"sessionId": "sess-1"})
+ m.get(f"{self.API_ROOT}/bills", status_code=status, headers={"Location": self.TARGET_URL})
+ m.get(self.TARGET_URL, status_code=403)
+
+ with pytest.raises(BillComRedirectError, match="redirected the API request to www.bill.com"):
+ self._real_client().list_page("/bills", {"max": PAGE_SIZE})
+
+ assert [r.hostname for r in m.request_history] == ["gateway.prod.bill.com", "gateway.prod.bill.com"]
+ list_request = m.request_history[-1]
+ assert list_request.headers["sessionId"] == "sess-1"
+ assert list_request.headers["devKey"] == "dev-key"
+
+ def test_login_refuses_redirect_so_the_sign_in_body_is_not_replayed(self) -> None:
+ # A 307 keeps the POST body (password and developer key) on the redirected request.
+ with requests_mock.Mocker() as m:
+ m.post(f"{self.API_ROOT}/login", status_code=307, headers={"Location": self.TARGET_URL})
+ m.post(self.TARGET_URL, json={"sessionId": "stolen"})
+
+ with pytest.raises(BillComRedirectError):
+ self._real_client().login()
+
+ assert [r.hostname for r in m.request_history] == ["gateway.prod.bill.com"]
+
+ def test_validate_credentials_reports_the_redirect(self) -> None:
+ with requests_mock.Mocker() as m:
+ m.post(f"{self.API_ROOT}/login", status_code=302, headers={"Location": self.TARGET_URL})
+
+ is_valid, message = validate_credentials("[email protected]", "pw", "org-1", "dev-key", "production", "v3")
+
+ assert is_valid is False
+ assert message == "BILL redirected the API request to www.bill.com; refusing to follow"
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/persona/persona.py b/products/warehouse_sources/backend/temporal/data_imports/sources/persona/persona.py
index ab6bdfd29493..07aef419da16 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/persona/persona.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/persona/persona.py
@@ -2,6 +2,7 @@ import dataclasses
from collections.abc import Iterator
from datetime import UTC, date, datetime
from typing import Any, Optional
+from urllib.parse import urljoin, urlparse
import requests
from dateutil import parser as date_parser
@@ -28,6 +29,18 @@ class PersonaRetryableError(Exception):
pass
+class PersonaRedirectError(Exception):
+ """The API answered with a 3xx. Redirects are refused so the API key stays on the API host."""
+
+
+def _refuse_redirect(response: requests.Response) -> None:
+ if not 300 <= response.status_code < 400:
+ return
+ location = response.headers.get("Location") or ""
+ target = urlparse(urljoin(response.url or "", location)).hostname or "an unknown host"
+ raise PersonaRedirectError(f"Persona redirected the API request to {target}; refusing to follow")
+
+
@dataclasses.dataclass
class PersonaResumeConfig:
# `page[after]` cursor (the id of the last list object whose rows we durably yielded). On resume
@@ -112,8 +125,11 @@ def validate_credentials(api_key: str) -> int:
try:
# Inquiry and verification bodies carry KYC PII (names, DOBs, government-ID and selfie check
# results) that the name-based scrubber can't reliably strip, so keep them out of HTTP sample
- # capture, following the same pattern as gusto and workday.
- response = make_tracked_session(capture=False).get(url, headers=_get_headers(api_key), timeout=10)
+ # capture, following the same pattern as gusto and workday. Redirects are refused so the key
+ # is only ever sent to the API host.
+ response = make_tracked_session(capture=False, allow_redirects=False).get(
+ url, headers=_get_headers(api_key), timeout=10
+ )
return response.status_code
except Exception:
return 0
@@ -142,6 +158,10 @@ def _fetch_page(
if response.status_code == 429 or response.status_code >= 500:
raise PersonaRetryableError(f"Persona API error (retryable): status={response.status_code}, url={page_url}")
+ # The session does not follow redirects, so a 3xx reaches here. `raise_for_status` treats it as
+ # success, so reject it explicitly.
+ _refuse_redirect(response)
+
if not response.ok:
logger.error(f"Persona API error: status={response.status_code}, body={response.text}, url={page_url}")
response.raise_for_status()
@@ -207,8 +227,9 @@ def get_rows(
batcher = Batcher(logger=logger, chunk_size=2000, chunk_size_bytes=100 * 1024 * 1024)
# One session reused across every page so urllib3 keeps the connection alive. Inquiry and
# verification bodies carry KYC PII the name-based scrubber can't reliably strip, so keep them
- # out of HTTP sample capture, following the same pattern as gusto and workday.
- session = make_tracked_session(capture=False)
+ # out of HTTP sample capture, following the same pattern as gusto and workday. Redirects are
+ # refused so the key is only ever sent to the API host.
+ session = make_tracked_session(capture=False, allow_redirects=False)
use_incremental = should_use_incremental_field and config.supports_incremental
watermark = _to_datetime(db_incremental_field_last_value) if use_incremental else None
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/persona/tests/test_persona.py b/products/warehouse_sources/backend/temporal/data_imports/sources/persona/tests/test_persona.py
index 8782df3dd56e..caaa71ad963c 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/persona/tests/test_persona.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/persona/tests/test_persona.py
@@ -5,10 +5,13 @@ import pytest
from unittest.mock import MagicMock, patch
import requests
+import requests_mock
from parameterized import parameterized
from products.warehouse_sources.backend.temporal.data_imports.sources.persona import persona
from products.warehouse_sources.backend.temporal.data_imports.sources.persona.persona import (
+ PERSONA_BASE_URL,
+ PersonaRedirectError,
PersonaResumeConfig,
PersonaRetryableError,
_build_params,
@@ -152,6 +155,40 @@ class TestFetchPageRetryClassification:
assert session.get.call_count == 1
+class TestRedirectsRefused:
+ # The apex host answers a redirected request with a 403 bot challenge, which must not be read
+ # as an auth failure. The session refuses the redirect so the key never leaves the API host.
+ API_URL = f"{PERSONA_BASE_URL}/inquiries"
+ TARGET_URL = "https://withpersona.com/api/v1/inquiries"
+
+ @parameterized.expand([("moved_permanently", 301), ("found", 302)])
+ def test_sync_refuses_redirect_and_keeps_key_on_api_host(self, _name: str, status: int) -> None:
+ with requests_mock.Mocker() as m:
+ m.get(self.API_URL, status_code=status, headers={"Location": self.TARGET_URL})
+ m.get(self.TARGET_URL, status_code=403)
+
+ with pytest.raises(PersonaRedirectError, match="redirected the API request to withpersona.com"):
+ list(
+ get_rows(
+ api_key="persona_test",
+ endpoint="inquiries",
+ logger=MagicMock(),
+ resumable_source_manager=_FakeResumableManager(), # type: ignore[arg-type]
+ )
+ )
+
+ assert [r.hostname for r in m.request_history] == ["api.withpersona.com"]
+ assert m.request_history[0].headers["Authorization"] == "Bearer persona_test"
+
+ def test_validate_credentials_returns_the_redirect_status_without_following(self) -> None:
+ with requests_mock.Mocker() as m:
+ m.get(self.API_URL, status_code=302, headers={"Location": self.TARGET_URL})
+ m.get(self.TARGET_URL, status_code=403)
+
+ assert persona.validate_credentials("persona_test") == 302
+ assert [r.hostname for r in m.request_history] == ["api.withpersona.com"]
+
+
def _collect(
manager: _FakeResumableManager,
monkeypatch: Any,
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sprig/sprig.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sprig/sprig.py
index ae5a5462f0ec..f2a5dd578338 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/sprig/sprig.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sprig/sprig.py
@@ -1,6 +1,9 @@
import dataclasses
from datetime import UTC, date, datetime
from typing import Any, Optional
+from urllib.parse import urljoin, urlparse
+
+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.rest_source import (
@@ -25,6 +28,18 @@ class SprigResumeConfig:
next_cursor: str
+class SprigRedirectError(Exception):
+ """The API answered with a 3xx. Redirects are refused so the API key stays on the API host."""
+
+
+def _refuse_redirect(response: requests.Response) -> None:
+ if not 300 <= response.status_code < 400:
+ return
+ location = response.headers.get("Location") or ""
+ target = urlparse(urljoin(response.url or "", location)).hostname or "an unknown host"
+ raise SprigRedirectError(f"Sprig redirected the API request to {target}; refusing to follow")
+
+
def _format_incremental_value(value: Any) -> Optional[int]:
"""Format an incremental cursor value as milliseconds since epoch for Sprig's `start` filter.
@@ -99,6 +114,9 @@ def sprig_source(
# Sprig returns `{"data": [...], "cursor": "<base64>"|null}` — the same field name
# both as the response's next-page pointer and the request's pagination param.
"paginator": JSONResponseCursorPaginator(cursor_path="cursor", cursor_param="cursor"),
+ # A redirect must not carry the bearer token to another host; the REST client rejects
+ # any 3xx when redirects are off.
+ "allow_redirects": False,
},
"resource_defaults": None,
"resources": [get_resource(endpoint, should_use_incremental_field)],
@@ -151,9 +169,10 @@ def validate_credentials(api_key: str) -> bool:
Returns False only for auth failures (401/403). Transient or unexpected statuses (429,
5xx, ...) are raised via `raise_for_status()` so they surface as a real error rather than
- being misreported to the user as an invalid API key.
+ being misreported to the user as an invalid API key. A 3xx is refused before that check,
+ because `raise_for_status()` treats it as success.
"""
- response = make_tracked_session().get(
+ response = make_tracked_session(allow_redirects=False).get(
f"{SPRIG_API_BASE_URL}/v1/surveys",
params={"limit": 1},
headers={"Authorization": f"Bearer {api_key}"},
@@ -161,5 +180,6 @@ def validate_credentials(api_key: str) -> bool:
)
if response.status_code in (401, 403):
return False
+ _refuse_redirect(response)
response.raise_for_status()
return True
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sprig/tests/test_sprig.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sprig/tests/test_sprig.py
index 9324a6d023b4..0fa422aa6c25 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/sprig/tests/test_sprig.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sprig/tests/test_sprig.py
@@ -4,6 +4,7 @@ from typing import Any, cast
import pytest
from unittest.mock import MagicMock, patch
+import requests_mock
from parameterized import parameterized
from requests.exceptions import HTTPError
@@ -11,8 +12,13 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.res
JSONResponseCursorPaginator,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
-from products.warehouse_sources.backend.temporal.data_imports.sources.sprig.settings import ENDPOINTS, SPRIG_ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.sprig.settings import (
+ ENDPOINTS,
+ SPRIG_API_BASE_URL,
+ SPRIG_ENDPOINTS,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.sprig.sprig import (
+ SprigRedirectError,
SprigResumeConfig,
_format_incremental_value,
get_resource,
@@ -241,3 +247,43 @@ class TestValidateCredentials:
with pytest.raises(HTTPError):
validate_credentials("key")
+
+
+class TestRedirectsRefused:
+ # A redirected request lands on a host that answers 403 with a bot challenge, which must not
+ # be read as an auth failure. Redirects are refused so the token never leaves the API host.
+ API_URL = f"{SPRIG_API_BASE_URL}/v1/surveys"
+ TARGET_URL = "https://sprig.com/v1/surveys"
+
+ @parameterized.expand([("moved_permanently", 301), ("found", 302)])
+ def test_sync_refuses_redirect_and_keeps_token_on_api_host(self, _label: str, status: int) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+
+ with requests_mock.Mocker() as m:
+ m.get(self.API_URL, status_code=status, headers={"Location": self.TARGET_URL})
+ m.get(self.TARGET_URL, status_code=403)
+
+ source = sprig_source(
+ api_key="key",
+ endpoint="Surveys",
+ team_id=1,
+ job_id="job",
+ resumable_source_manager=manager,
+ db_incremental_field_last_value=None,
+ )
+ with pytest.raises(ValueError, match="Unexpected redirect .*refusing to follow"):
+ list(cast(Any, source.items()))
+
+ assert [r.hostname for r in m.request_history] == ["api.sprig.com"]
+ assert m.request_history[0].headers["Authorization"] == "Bearer key"
+
+ def test_validate_credentials_refuses_redirect_instead_of_reporting_a_valid_key(self) -> None:
+ with requests_mock.Mocker() as m:
+ m.get(self.API_URL, status_code=302, headers={"Location": self.TARGET_URL})
+ m.get(self.TARGET_URL, status_code=403)
+
+ with pytest.raises(SprigRedirectError, match="redirected the API request to sprig.com"):
+ validate_credentials("key")
+
+ assert [r.hostname for r in m.request_history] == ["api.sprig.com"]