: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(sonarqube): surface the server's error message on a failed request (#98613)
posthog[bot]683af7dd8c2a
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sonarqube/docs/sonarqube.md b/products/warehouse_sources/backend/temporal/data_imports/sources/sonarqube/docs/sonarqube.mdindex 862376f9aae0..3cb60f4cfbfb 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/sonarqube/docs/sonarqube.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sonarqube/docs/sonarqube.md@@ -24,7 +24,7 @@ Sync code-quality data from your self-hosted [SonarQube Server](https://www.sona## Prerequisites-- A running SonarQube Server instance reachable from the public internet.+- A running SonarQube Server instance reachable from the public internet. For SonarQube Cloud (`sonarcloud.io` or `sonarqube.us`), use the Sonar Cloud source instead.- A user token generated in SonarQube. The token inherits the permissions of the user who created it, so it can read the projects, issues, and rules that user can see.- To sync the **users** table, the token's user needs the _Administer System_ permission. All other tables only need normal browse access.@@ -53,6 +53,7 @@ You'll need:## Troubleshooting+- **Setup rejects a SonarQube Cloud URL.** This source reads SonarQube Server. Cloud needs an organization key on every request, so connect it with the Sonar Cloud source instead.- **The users table fails to sync.** `/api/users/search` requires the _Administer System_ permission. Either grant it to the token's user or leave the users table unselected — it's off by default.- **Fewer issues than expected on a large project.** SonarQube caps issue search at 10,000 results per query window. PostHog automatically pages past this by re-windowing on the issue creation date, so all issues are synced; if you still see gaps, check that the token can browse the affected projects.diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sonarqube/sonarqube.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sonarqube/sonarqube.pyindex 7604bcb6ea59..9587fc3efb00 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/sonarqube/sonarqube.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sonarqube/sonarqube.py@@ -30,6 +30,12 @@ MAX_RETRY_ATTEMPTS = 5# worker's memory. A legitimate `ps=500` page is well under this.MAX_RESPONSE_BYTES = 64 * 1024 * 1024+# Cap on the error text this source takes from a response body. That text reaches the job log and+# the `internal_error` field of the activity input that reports a failure, and a Temporal payload+# has a size limit, so an oversized detail would replace the status it is meant to explain. The+# sibling sources cap their error detail at the same length.+MAX_ERROR_DETAIL_CHARS = 500+# Wall-clock ceiling on reading a single response. The per-read timeout resets on every byte,# so a server can drip data indefinitely and hold a shared worker; bound the whole transfer so# a slow-drip host is cut off. Generous enough that a legitimate page never trips it.@@ -45,6 +51,16 @@ ISSUES_MAX_PAGES = ISSUES_MAX_RESULTS // PAGE_SIZE# fail non-retryably if it's ever breached. 50M rows is far beyond any real instance.MAX_PAGES = 100_000+# SonarQube Cloud is a separate product from the self-hosted Server this source targets, with its+# own source. Its list endpoints require an `organization` parameter we never send, so every page+# returns a 400. Both region hosts, and any subdomain of them.+SONARQUBE_CLOUD_HOSTNAMES = ("sonarcloud.io", "sonarqube.us")++SONARQUBE_CLOUD_ERROR = (+ "This URL points to SonarQube Cloud, which this source cannot read. "+ "Connect it with the Sonar Cloud source instead, which asks for your organization key."+)+class SonarqubeRetryableError(Exception):pass@@ -65,6 +81,7 @@ def normalize_base_url(host: str) -> str:Accepts a bare host or a full URL. Bare hosts default to https; plaintext http:// is rejectedbecause the token travels as a bearer header and must stay off the wire in the clear. Rejectsanything without a hostname so the stored token can only ever be sent to the configured instance.+ Rejects SonarQube Cloud, which this source cannot sync."""cleaned = host.strip()if not cleaned:@@ -72,11 +89,19 @@ def normalize_base_url(host: str) -> str:if "://" not in cleaned:cleaned = f"https://{cleaned}"parsed = urlparse(cleaned)- if parsed.scheme != "https" or not parsed.hostname:+ # `parsed.hostname` lowercases the host but keeps a terminal DNS dot, and `sonarcloud.io.`+ # reaches the same server as `sonarcloud.io`. Strip the dot so the cloud check below cannot be+ # sidestepped, and so the host we validate is the host we request.+ hostname = (parsed.hostname or "").rstrip(".")+ if parsed.scheme != "https" or not hostname:raise ValueError(f"Invalid SonarQube server URL (must be https): {host}")+ if any(hostname == name or hostname.endswith(f".{name}") for name in SONARQUBE_CLOUD_HOSTNAMES):+ # Cloud accepts the credential probe (/api/authentication/validate answers 200 there), so+ # without this check setup succeeds and every list endpoint then fails with a 400.+ raise ValueError(SONARQUBE_CLOUD_ERROR)# Keep scheme + netloc only; drop any path/query the user pasted so we control the API paths.port = f":{parsed.port}" if parsed.port else ""- return f"https://{parsed.hostname}{port}"+ return f"https://{hostname}{port}"def hostname_of(host: str) -> str:@@ -126,6 +151,32 @@ def _extract_paging(data: dict[str, Any]) -> tuple[int, int, int]:)+def _error_detail(body: bytes) -> str:+ """Return SonarQube's own explanation of a failed request.++ Error responses carry ``{"errors": [{"msg": "..."}]}``. Fall back to the raw body so an+ unexpected shape still tells the user something. The result is capped at+ ``MAX_ERROR_DETAIL_CHARS`` because the server chooses its length.+ """+ try:+ payload = json.loads(body or b"null")+ except ValueError:+ payload = None+ # A misconfigured host, or a gateway in front of the instance, can put any JSON value under+ # `errors`, so confirm it is a list before iterating it. A non-list would raise a TypeError+ # here, which would replace the status and body this function exists to report.+ errors = payload.get("errors") if isinstance(payload, dict) else None+ if isinstance(errors, list):+ messages = [str(error["msg"]) for error in errors if isinstance(error, dict) and error.get("msg")]+ if messages:+ return "; ".join(messages)[:MAX_ERROR_DETAIL_CHARS]+ # Decode only the bytes the cap can use. The body is already in memory and can reach+ # MAX_RESPONSE_BYTES, so decoding all of it would spend that much again for a string we then+ # throw away. UTF-8 uses at most 4 bytes per character, so this slice always covers the cap.+ text = body[: MAX_ERROR_DETAIL_CHARS * 4].decode("utf-8", "replace").strip()+ return text[:MAX_ERROR_DETAIL_CHARS] if text else "no error message"++def _read_bounded(response: requests.Response) -> bytes:"""Read a streamed response body into memory under a byte cap and a wall-clock deadline.@@ -184,8 +235,12 @@ def _fetch_page(session: requests.Session, url: str, headers: dict[str, str], lobody = _read_bounded(response)if not response.ok:- logger.error(f"SonarQube API error: status={response.status_code}, body={body[:500]!r}, url={url}")- response.raise_for_status()+ detail = _error_detail(body)+ logger.error(f"SonarQube API error: status={response.status_code}, detail={detail}, url={url}")+ # Built by hand rather than with `raise_for_status()`: SonarQube sends an empty HTTP+ # reason phrase, so the library message reads "400 Client Error: for url: ..." and+ # drops the server's own explanation of what is wrong.+ raise requests.HTTPError(f"{response.status_code} Client Error: {detail} for url: {url}", response=response)return json.loads(body or b"null")finally:diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sonarqube/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sonarqube/source.pyindex 6ec3dd90de4a..5699c4c53f90 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/sonarqube/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sonarqube/source.py@@ -27,6 +27,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.sonarqube.SONARQUBE_ENDPOINTS,)from products.warehouse_sources.backend.temporal.data_imports.sources.sonarqube.sonarqube import (+ SONARQUBE_CLOUD_ERROR,SonarqubeResumeConfig,hostname_of,sonarqube_source,@@ -52,6 +53,8 @@ class SonarqubeSource(ResumableSource[SonarqubeSourceConfig, SonarqubeResumeConfreleaseStatus=ReleaseStatus.ALPHA,caption="""Connect your self-hosted SonarQube Server to pull code-quality data into the PostHog Data warehouse.+Using SonarQube Cloud (sonarcloud.io or sonarqube.us)? Connect it with the Sonar Cloud source instead.+Enter your server URL (e.g. `https://sonarqube.yourcompany.com`) and a user token. Create a token under **My Account → Security → Generate Tokens** in your SonarQube instance. The token inherits your permissions, so it can read the projects, issues, and rules you can see. Syncing the **users** table additionally requires the *Administer System* permission.""",iconPath="/static/services/sonarqube.png",docsUrl="https://posthog.com/docs/cdp/sources/sonarqube",@@ -87,19 +90,18 @@ Enter your server URL (e.g. `https://sonarqube.yourcompany.com`) and a user tokedef get_non_retryable_errors(self) -> dict[str, str | None]:return {- # This source only talks to a self-hosted SonarQube Server. If the configured host is- # actually SonarQube Cloud, every request fails identically: SonarQube Cloud's API- # requires an `organization` parameter this source never sends. Match the stable,- # vendor-owned hostnames (not anything the customer typed) rather than the endpoint path.- # The trailing slash anchors the match to the exact host, so a self-hosted domain that- # merely contains these strings (e.g. `sonarcloud.io.example.com`) doesn't match.- "for url: https://sonarcloud.io/": "This server URL points to SonarQube Cloud, which this source doesn't support. Remove this source and add it again using the SonarQube Cloud source instead.",- "for url: https://sonarqube.us/": "This server URL points to SonarQube Cloud, which this source doesn't support. Remove this source and add it again using the SonarQube Cloud source instead.",- # 401/403 surface as a requests HTTPError when `_fetch_page` calls `raise_for_status()`.- # Retrying can never fix a credential/permission problem, so fail the sync. Match the- # stable status text, not the per-request URL.- "401 Client Error: Unauthorized": "Your SonarQube token is invalid or has expired. Generate a new token in your SonarQube account settings, then reconnect.",- "403 Client Error: Forbidden": "Your SonarQube token is missing the permissions needed to sync this data (the users table needs the Administer System permission). Check the token's permissions, then reconnect.",+ # `_fetch_page` raises a requests HTTPError carrying the status and SonarQube's own+ # message. Retrying can never fix a credential, permission, or request problem, so fail+ # the sync. Match the stable status text, not the per-request message or URL.+ "401 Client Error": "Your SonarQube token is invalid or has expired. Generate a new token in your SonarQube account settings, then reconnect.",+ "403 Client Error": "Your SonarQube token is missing the permissions needed to sync this data (the users table needs the Administer System permission). Check the token's permissions, then reconnect.",+ # A 400 means the server rejected the request itself. Keep the raised message, which+ # carries SonarQube's explanation; no fixed string can name the cause as well.+ "400 Client Error": None,+ # Raised by `normalize_base_url` before the first request when the URL points at+ # SonarQube Cloud, so a cloud host never reaches the API and no URL match is needed.+ # The message is already the guidance the user needs.+ SONARQUBE_CLOUD_ERROR: None,}def get_schemas(diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sonarqube/tests/test_sonarqube.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sonarqube/tests/test_sonarqube.pyindex cdedb474fff3..1c4bcb9cee4c 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/sonarqube/tests/test_sonarqube.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sonarqube/tests/test_sonarqube.py@@ -5,11 +5,13 @@ from typing import Anyimport pytestfrom unittest.mock import MagicMock+import requestsfrom parameterized import parameterizedfrom products.warehouse_sources.backend.temporal.data_imports.sources.sonarqube import sonarqubefrom products.warehouse_sources.backend.temporal.data_imports.sources.sonarqube.sonarqube import (SonarqubeResumeConfig,+ _error_detail,_extract_paging,_format_created_after,get_rows,@@ -28,7 +30,12 @@ class TestNormalizeBaseUrl:("trailing_slash", "https://sonar.example.com/", "https://sonar.example.com"),("strips_path", "https://sonar.example.com/sonarqube/foo", "https://sonar.example.com"),("keeps_port", "https://sonar.example.com:9000", "https://sonar.example.com:9000"),+ # A self-hosted domain that only contains a cloud hostname is not the cloud product.+ ("cloud_lookalike_allowed", "https://sonarcloud.io.example.com", "https://sonarcloud.io.example.com"),("whitespace", " https://sonar.example.com ", "https://sonar.example.com"),+ # A terminal DNS dot is dropped, so the host checked is the host requested.+ ("strips_terminal_dns_dot", "https://sonar.example.com.", "https://sonar.example.com"),+ ("strips_terminal_dns_dot_with_port", "https://sonar.example.com.:9000", "https://sonar.example.com:9000"),])def test_valid(self, _name: str, value: str, expected: str) -> None:@@ -42,6 +49,16 @@ class TestNormalizeBaseUrl:("ftp", "ftp://x"),# Plaintext http would put the bearer token on the wire in the clear.("http_rejected", "http://sonar.internal"),+ # Cloud needs an `organization` on every list endpoint, so it can only fail mid-sync.+ ("cloud_eu_rejected", "https://sonarcloud.io"),+ ("cloud_us_rejected", "https://sonarqube.us"),+ ("cloud_bare_host_rejected", "sonarcloud.io"),+ ("cloud_subdomain_rejected", "https://api.sonarcloud.io"),+ # A terminal DNS dot reaches the same cloud host, so it must not sidestep the check.+ ("cloud_trailing_dot_rejected", "https://sonarcloud.io."),+ ("cloud_subdomain_trailing_dot_rejected", "https://api.sonarcloud.io."),+ # Stripping the dot leaves no hostname at all, which must stay a rejection.+ ("dot_only_host", "https://."),])def test_invalid_raises(self, _name: str, value: str) -> None:@@ -72,6 +89,31 @@ class TestExtractPaging:assert _extract_paging({"p": 1, "ps": 500, "total": 42}) == (1, 500, 42)+class TestErrorDetail:+ @parameterized.expand(+ [+ (+ "sonarqube_error_shape",+ b'{"errors":[{"msg":"The \'organization\' parameter is missing"}]}',+ "The 'organization' parameter is missing",+ ),+ ("several_errors_joined", b'{"errors":[{"msg":"first"},{"msg":"second"}]}', "first; second"),+ ("unexpected_shape_falls_back_to_body", b'{"message":"nope"}', '{"message":"nope"}'),+ ("non_json_falls_back_to_body", b"<html>gateway</html>", "<html>gateway</html>"),+ ("empty_body", b"", "no error message"),+ # A non-iterable `errors` must reach the raw-body fallback rather than raise.+ ("null_errors_falls_back_to_body", b'{"errors":null}', '{"errors":null}'),+ ("numeric_errors_falls_back_to_body", b'{"errors":1}', '{"errors":1}'),+ # The server chooses the length, and the detail reaches a Temporal activity payload.+ ("oversized_msg_capped", b'{"errors":[{"msg":"' + b"x" * 5000 + b'"}]}', "x" * 500),+ # A multi-byte body still fills the cap, so the decode slice cannot be byte-tight.+ ("oversized_multibyte_body_capped", "\U0001d11e".encode() * 600, "\U0001d11e" * 500),+ ]+ )+ def test_detail(self, _name: str, body: bytes, expected: str) -> None:+ assert _error_detail(body) == expected++class _FakeResumableManager:def __init__(self, state: SonarqubeResumeConfig | None = None) -> None:self._state = state@@ -307,6 +349,7 @@ class TestWindowedIssues:class _FakeResponse:def __init__(self, status_code: int, payload: Any = None) -> None:self.status_code = status_code+ self.ok = 200 <= status_code < 300self._payload = payloadself.closed = False@@ -356,6 +399,19 @@ class TestReadBounded:sonarqube._read_bounded(_FakeStream([b"aaaa", b"bbbb"])) # type: ignore[arg-type]+class TestFetchPageErrors:+ def test_client_error_carries_the_servers_explanation(self) -> None:+ # SonarQube sends an empty HTTP reason phrase, so the raised message has to carry the+ # server's own words or it reads "400 Client Error: for url: ..." and names no cause.+ session = MagicMock()+ session.get.return_value = _FakeResponse(400, {"errors": [{"msg": "The 'organization' parameter is missing"}]})++ with pytest.raises(requests.HTTPError) as error:+ sonarqube._fetch_page(session, f"{_BASE}/api/rules/search", {}, MagicMock())++ assert "400 Client Error: The 'organization' parameter is missing" in str(error.value)++class TestValidateCredentials:@pytest.mark.parametrize("status, payload, expected_ok, expected_code",diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sonarqube/tests/test_sonarqube_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sonarqube/tests/test_sonarqube_source.pyindex d9355c832aaa..8ad9b100ca17 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/sonarqube/tests/test_sonarqube_source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sonarqube/tests/test_sonarqube_source.py@@ -7,6 +7,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.generated_SonarqubeSourceConfig,)from products.warehouse_sources.backend.temporal.data_imports.sources.sonarqube.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.sonarqube.sonarqube import SONARQUBE_CLOUD_ERRORfrom products.warehouse_sources.backend.temporal.data_imports.sources.sonarqube.source import SonarqubeSource_INCREMENTAL_ENDPOINTS = {"issues"}@@ -35,24 +36,30 @@ class TestSonarqubeSource:@pytest.mark.parametrize("observed_error",[- "401 Client Error: Unauthorized for url: https://sonar.example.com/api/issues/search?p=1&ps=500",- "403 Client Error: Forbidden for url: https://sonar.example.com/api/users/search?p=1&ps=500",+ "401 Client Error: Insufficient privileges for url: https://sonar.example.com/api/issues/search?p=1&ps=500",+ "403 Client Error: Insufficient privileges for url: https://sonar.example.com/api/users/search?p=1&ps=500",+ # A misconfigured server URL fails the same way on every attempt, so it belongs here+ # rather than in error tracking.+ "400 Client Error: The 'organization' parameter is missing for url: https://sonar.example.com/api/rules/search",+ SONARQUBE_CLOUD_ERROR,],)- def test_non_retryable_errors_match_auth_failures(self, observed_error):+ def test_non_retryable_errors_match_permanent_failures(self, observed_error):non_retryable_errors = self.source.get_non_retryable_errors()assert any(key in observed_error for key in non_retryable_errors)+ def test_permanent_request_errors_keep_the_servers_own_message(self):+ # No fixed string can name what a 400 rejected, so the raised message must survive.+ non_retryable_errors = self.source.get_non_retryable_errors()+ assert non_retryable_errors["400 Client Error"] is None+ assert non_retryable_errors[SONARQUBE_CLOUD_ERROR] is None+@pytest.mark.parametrize("other_error",["429 Client Error: Too Many Requests for url: https://sonar.example.com/api/issues/search","500 Server Error: Internal Server Error for url: https://sonar.example.com/api/issues/search","HTTPSConnectionPool(host='sonar.example.com', port=443): Read timed out.",- # A self-hosted domain that merely contains the SonarQube Cloud hostname as a substring- # must not be caught by the host-misconfiguration match below.- "400 Client Error: Bad Request for url: https://sonarcloud.io.example.com/api/issues/search",- "400 Client Error: Bad Request for url: https://sonarqube.us-backup.mycompany.com/api/issues/search",],)def test_non_retryable_errors_do_not_match_transient(self, other_error):@@ -125,6 +132,21 @@ class TestSonarqubeSource:assert error_message == expected_messagemock_validate.assert_called_once_with("https://sonar.example.com", "tok")+ @mock.patch.object(SonarqubeSource, "is_database_host_valid", return_value=(True, None))+ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.sonarqube.source.validate_sonarqube_credentials"+ )+ def test_validate_credentials_rejects_sonarqube_cloud(self, mock_validate, _mock_host):+ # Cloud answers the credential probe with 200, so setup used to pass and every sync then+ # failed with an unexplained 400.+ config = SonarqubeSourceConfig(host="https://sonarcloud.io", token="tok")++ is_valid, error_message = self.source.validate_credentials(config, self.team_id)++ assert is_valid is False+ assert error_message == SONARQUBE_CLOUD_ERROR+ mock_validate.assert_not_called()+@mock.patch.object(SonarqubeSource, "is_database_host_valid", return_value=(False, "Blocked internal host"))@mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.sonarqube.source.validate_sonarqube_credentials"