: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(convex): stop a copy-pasted deploy key crashing source setup (#105045)
Tom Owersdc5bad2acb68
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/convex/convex.py b/products/warehouse_sources/backend/temporal/data_imports/sources/convex/convex.pyindex f0fa8b38aa0f..d3cabf6ad1e2 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/convex/convex.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/convex/convex.py@@ -96,9 +96,41 @@ def validate_deploy_url(deploy_url: str) -> str:return f"https://{host}"+class InvalidDeployKeyError(Exception):+ """Raised when the deploy key cannot be sent in an Authorization header."""++ pass+++def validate_deploy_key(deploy_key: str) -> str:+ """Validate and normalize a Convex deploy key.++ Returns the key without surrounding whitespace.+ """+ deploy_key = deploy_key.strip()++ if not deploy_key:+ raise InvalidDeployKeyError("Enter your Convex deploy key.")++ try:+ # http.client encodes header values as latin-1, so a character outside that range+ # aborts the request with a UnicodeEncodeError raised from inside urllib3. That error+ # names a codec and a string offset, so neither the user nor error tracking can tell+ # which field is at fault. Copying a key out of a browser can pick up such a character,+ # so reject it here with a message the user can act on.+ deploy_key.encode("latin-1")+ except UnicodeEncodeError:+ raise InvalidDeployKeyError(+ "Your deploy key contains characters PostHog can't send to Convex. "+ "Copy the key again from your Convex dashboard, then try again."+ ) from None++ return deploy_key++def _headers(deploy_key: str) -> dict[str, str]:return {- "Authorization": f"Convex {deploy_key}",+ "Authorization": f"Convex {validate_deploy_key(deploy_key)}","Content-Type": "application/json",}@@ -328,7 +360,8 @@ def document_deltas(def validate_credentials(deploy_url: str, deploy_key: str) -> tuple[bool, str | None]:try:clean_url = validate_deploy_url(deploy_url)- except InvalidDeployUrlError as e:+ deploy_key = validate_deploy_key(deploy_key)+ except (InvalidDeployUrlError, InvalidDeployKeyError) as e:return False, str(e)try:get_json_schemas(clean_url, deploy_key)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/convex/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/convex/source.pyindex 0062c3b031c5..e8ac57a83524 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/convex/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/convex/source.py@@ -125,6 +125,13 @@ You can find your deployment URL and deploy key in your [Convex Dashboard](https"turn off syncing for this table, then re-enable the sync."),"StreamingExportNotEnabled": "Streaming export requires the Convex Professional plan. See https://www.convex.dev/plans to upgrade.",+ # A deploy key that cannot be encoded into an Authorization header is rejected before+ # any request leaves PostHog, so every retry rebuilds the same unsendable request. The+ # user has to re-enter the key, which makes this a credential error rather than a blip.+ "contains characters PostHog can't send to Convex": (+ "PostHog can't send your Convex deploy key. Copy the key again from your Convex "+ "dashboard, then update this source's credentials."+ ),# Convex treats a document_deltas/list_snapshot cursor conflict as deterministic, not# transient (it's one of the few codes their own backend classifies as a user error# rather than retryable). It surfaces when a data import or backup restore on thediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/convex/tests/test_convex.py b/products/warehouse_sources/backend/temporal/data_imports/sources/convex/tests/test_convex.pyindex 2d726c293d68..6391bd309ae3 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/convex/tests/test_convex.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/convex/tests/test_convex.py@@ -17,6 +17,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.resfrom products.warehouse_sources.backend.temporal.data_imports.sources.convex.convex import (_CONVEX_RETRY,ConvexResumeConfig,+ InvalidDeployKeyError,InvalidDeployUrlError,InvalidWindowError,StreamingExportNotEnabledError,@@ -29,6 +30,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.convex.conqualified_table_name,split_qualified_table_name,validate_credentials,+ validate_deploy_key,validate_deploy_url,)from products.warehouse_sources.backend.temporal.data_imports.sources.convex.source import ConvexSource@@ -102,9 +104,16 @@ class TestValidateDeployUrl:with pytest.raises(InvalidDeployUrlError):validate_deploy_url(url)+ @parameterized.expand(+ [+ ("bad_url", "http://169.254.169.254", "deploy-key"),+ ("unsendable_key", "https://swift-lemur-123.convex.cloud", "prod:swift-lemur-123|ab\u2028cd"),+ ("blank_key", "https://swift-lemur-123.convex.cloud", " "),+ ]+ )@patch("products.warehouse_sources.backend.temporal.data_imports.sources.convex.convex.make_tracked_session")- def test_validate_credentials_rejects_bad_url_without_network_call(self, mock_get):- ok, err = validate_credentials("http://169.254.169.254", "deploy-key")+ def test_validate_credentials_rejects_bad_input_without_network_call(self, _name, url, deploy_key, mock_get):+ ok, err = validate_credentials(url, deploy_key)assert not okassert err is not Nonemock_get.assert_not_called()@@ -149,6 +158,42 @@ class TestValidateDeployUrl:assert "400" in err+class TestValidateDeployKey:+ @parameterized.expand(+ [+ ("plain", "prod:swift-lemur-123|abc", "prod:swift-lemur-123|abc"),+ ("surrounding_spaces", " prod:swift-lemur-123|abc ", "prod:swift-lemur-123|abc"),+ ("trailing_newline", "prod:swift-lemur-123|abc\n", "prod:swift-lemur-123|abc"),+ # A key copied out of a browser can carry an invisible separator that latin-1 cannot+ # encode. Both are whitespace to str.strip, so a key that only has one at either end+ # stays usable.+ ("trailing_line_separator", "prod:swift-lemur-123|abc\u2028", "prod:swift-lemur-123|abc"),+ ("leading_no_break_space", "\u00a0prod:swift-lemur-123|abc", "prod:swift-lemur-123|abc"),+ # invalid - should raise+ ("blank", " ", None),+ ("embedded_line_separator", "prod:swift-lemur\u2028-123|abc", None),+ ("embedded_non_latin_1", "prod:swift-lemur-123|ab\u2603cd", None),+ ]+ )+ def test_validate_deploy_key(self, _name: str, deploy_key: str, expected: str | None) -> None:+ if expected is not None:+ cleaned = validate_deploy_key(deploy_key)+ assert cleaned == expected+ cleaned.encode("latin-1")+ else:+ with pytest.raises(InvalidDeployKeyError):+ validate_deploy_key(deploy_key)++ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.convex.convex.make_tracked_session")+ def test_request_header_is_encodable_for_a_copy_pasted_key(self, mock_session: Mock) -> None:+ mock_session.return_value.get.return_value = _make_response({})++ get_json_schemas("https://swift-lemur-123.convex.cloud", "prod:swift-lemur-123|abc\u2028")++ headers = mock_session.return_value.get.call_args.kwargs["headers"]+ assert headers["Authorization"] == "Convex prod:swift-lemur-123|abc"++class TestListSnapshotResumable:@patch("products.warehouse_sources.backend.temporal.data_imports.sources.convex.convex.make_tracked_session")def test_fresh_run_saves_state_after_each_page(self, mock_get: Mock) -> None:@@ -574,6 +619,11 @@ class TestConvexNonRetryableErrors:"Delta cursor for table 'events' is older than Convex's ~30 day retention window. ""Please trigger a full resync of this source.",),+ (+ "unsendable_deploy_key",+ "Your deploy key contains characters PostHog can't send to Convex. "+ "Copy the key again from your Convex dashboard, then try again.",+ ),])def test_known_errors_match(self, _name: str, observed_error: str) -> None: