: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
fix(warehouse-sources): say what to fix when an OpenAI key is rejected (#99285)
Tom Owers0f0e21a0475c
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/openai/openai.py b/products/warehouse_sources/backend/temporal/data_imports/sources/openai/openai.pyindex b033f088b64e..c451fbcb2b8d 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/openai/openai.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/openai/openai.py@@ -189,17 +189,32 @@ def _from_unix_seconds(value: Any) -> datetime | None:return datetime.fromtimestamp(int(value), tz=UTC)-def validate_credentials(api_key: str) -> bool:+_KEY_REJECTED_MESSAGE = (+ "OpenAI rejected your Admin API key. Check the key starts with sk-admin, was created by an "+ "organization owner, and hasn't been revoked."+)++# `validate_via_probe` reports a transport failure as a `None` status, so anything that isn't a 401+# leaves the key unjudged. Kept apart from the rejection message: telling someone their key is wrong+# when OpenAI never answered sends them off to mint a replacement that fails the same way.+_PROBE_FAILED_MESSAGE = "PostHog couldn't check your Admin API key with OpenAI. Wait a few minutes and try again."+++def validate_credentials(api_key: str) -> tuple[bool, str | None]:# A single cheap probe against the smallest list endpoint confirms the admin key is genuine.# 200 => valid. 403 => valid key without a scope we probed here; still a real key, so accept it# at create time (sync-time 403s are caught by get_non_retryable_errors). 401 => bad key.- ok, _status = validate_via_probe(+ ok, status = validate_via_probe(lambda: make_tracked_session(redact_values=(api_key,)),f"{OPENAI_BASE_URL}/v1/organization/projects?limit=1",headers={"Authorization": f"Bearer {api_key}", **_headers()},ok_statuses=(200, 403),)- return ok+ if ok:+ return True, None+ if status == 401:+ return False, _KEY_REJECTED_MESSAGE+ return False, _PROBE_FAILED_MESSAGEdef _row_id(*parts: Any) -> str:diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/openai/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/openai/source.pyindex a989d84cf7e8..ecdb5e02c689 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/openai/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/openai/source.py@@ -128,10 +128,7 @@ Create an Admin API key (prefixed `sk-admin...`) in your [OpenAI organization seschema_name: Optional[str] = None,api_version: str | None = None,) -> tuple[bool, str | None]:- if validate_openai_credentials(config.api_key):- return True, None-- return False, "Invalid OpenAI Admin API key"+ return validate_openai_credentials(config.api_key)def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[OpenAIResumeConfig]:return ResumableSourceManager[OpenAIResumeConfig](inputs, OpenAIResumeConfig)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/openai/tests/test_openai.py b/products/warehouse_sources/backend/temporal/data_imports/sources/openai/tests/test_openai.pyindex 7f1cfcc73f13..d1c5017db376 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/openai/tests/test_openai.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/openai/tests/test_openai.py@@ -620,19 +620,36 @@ class TestRetries:class TestValidateCredentials:- @parameterized.expand([("ok", 200, True), ("forbidden_scope", 403, True), ("unauthorized", 401, False)])- def test_status_mapping(self, _name: str, status: int, expected: bool) -> None:- # 403 is accepted at create time (real key, unprobed scope); 401 means a bad key.+ @parameterized.expand(+ [+ ("ok", 200, True, None),+ ("forbidden_scope", 403, True, None),+ ("unauthorized", 401, False, "rejected your Admin API key"),+ ("service_unavailable", 503, False, "couldn't check your Admin API key"),+ ]+ )+ def test_status_mapping(self, _name: str, status: int, expected: bool, fragment: str | None) -> None:+ # 403 is accepted at create time (real key, unprobed scope); 401 means a bad key. Anything+ # else leaves the key unjudged, so it must not read as a rejection.session = mock.MagicMock()session.get.return_value = mock.MagicMock(status_code=status)with mock.patch(OPENAI_SESSION_PATCH, return_value=session):- assert validate_credentials("sk-admin-test") is expected+ is_valid, message = validate_credentials("sk-admin-test")++ assert is_valid is expected+ if fragment is None:+ assert message is None+ else:+ assert message is not None and fragment in messagedef test_network_error_is_invalid(self) -> None:session = mock.MagicMock()session.get.side_effect = requests.ConnectionError("boom")with mock.patch(OPENAI_SESSION_PATCH, return_value=session):- assert validate_credentials("sk-admin-test") is False+ is_valid, message = validate_credentials("sk-admin-test")++ assert is_valid is False+ assert message is not None and "couldn't check your Admin API key" in messageclass TestNonRetryableErrors: