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(billing): preserve safe field validation errors (#103551)

Pawel Cebula9b5583a38204
diff --git a/docs/published/handbook/engineering/ai/implementing-mcp-tools.md b/docs/published/handbook/engineering/ai/implementing-mcp-tools.md
index 5c2530bd81b6..bf63d9fa8755 100644
--- a/docs/published/handbook/engineering/ai/implementing-mcp-tools.md
+++ b/docs/published/handbook/engineering/ai/implementing-mcp-tools.md
@@ -144,6 +144,12 @@ return distinct API-visible error details. Agents should stop on true authorizat
failures, but they can often recover from a bad project/team filter if the response says
the requested scope is unavailable.
+The billing usage/spend proxy also returns recognized field-validation failures as
+standard DRF validation errors (`type`, `code`, `attr`, `detail`). It keeps known
+codes and public request fields, replaces upstream messages with controlled text,
+and masks unrecognized failures. The shared MCP client handles these errors without
+a billing-specific tool wrapper.
+
System tables are defined in [`posthog/hogql/database/schema/system.py`](https://github.com/PostHog/posthog/blob/master/posthog/hogql/database/schema/system.py) as `PostgresTable` instances.
Each table must include a `team_id` column for data isolation.
diff --git a/ee/api/billing.py b/ee/api/billing.py
index 87d7246e9900..c6935df4876a 100644
--- a/ee/api/billing.py
+++ b/ee/api/billing.py
@@ -123,6 +123,12 @@ BILLING_GUIDANCE_ERRORS: dict[str, type[APIException]] = {
BillingDateRangeTooLong.default_code: BillingDateRangeTooLong,
}
+BILLING_VALIDATION_ERROR_MESSAGES = {
+ "required": "This field is required.",
+ "invalid_input": "Invalid value. Check this parameter's format and allowed values.",
+ "invalid_choice": "Select a valid option for this parameter.",
+}
+
BILLING_LIMIT_TODAYS_USAGE_KEYS = ("posthog_code_credits",)
BILLING_ACCESS_DENIED_MESSAGE = (
@@ -1339,10 +1345,9 @@ class BillingViewset(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
"""Raise the named exception for an error billing returned on a usage, spend or export request.
handle_billing_service_error raises with the status in its message and the parsed body as
- the third argument. A guidance code maps to its named exception, whose text the page owns;
- anything else is a 400 or a 502 with a fixed message. Billing's body goes to the log and
- nowhere else. An exception of any other shape is not billing's answer and is re-raised as
- it is.
+ the third argument. Known guidance and validation codes use controlled messages because
+ upstream detail can contain caller input or internal data. Unknown errors remain a generic
+ 400 or 502. An exception of any other shape is not billing's answer and is re-raised as it is.
"""
status_match = re.search(r"status code: (\d+)", str(error.args[0]) if error.args else "")
if not status_match:
@@ -1361,8 +1366,17 @@ class BillingViewset(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
# Billing evaluates the same permission from its own cache, so flag rollout windows
# can still return a downstream permission denial.
raise PermissionDenied(HasBillingUsageSpendReadAccess.message) from error
- if code in BILLING_GUIDANCE_ERRORS:
+ if isinstance(code, str) and code in BILLING_GUIDANCE_ERRORS:
raise BILLING_GUIDANCE_ERRORS[code]() from error
+ if upstream_status == 400 and isinstance(body, dict) and body.get("type") == "validation_error":
+ field = body.get("attr")
+ if (
+ isinstance(field, str)
+ and field in BillingUsageRequestSerializer().fields
+ and isinstance(code, str)
+ and code in BILLING_VALIDATION_ERROR_MESSAGES
+ ):
+ raise ValidationError({field: [BILLING_VALIDATION_ERROR_MESSAGES[code]]}, code=code) from error
if 400 <= upstream_status < 500:
raise BillingQueryRejected() from error
raise BillingServiceError() from error
diff --git a/ee/api/test/test_billing.py b/ee/api/test/test_billing.py
index 93ce020a1812..1671afeed447 100644
--- a/ee/api/test/test_billing.py
+++ b/ee/api/test/test_billing.py
@@ -11,6 +11,7 @@ from unittest import TestCase
from unittest.mock import MagicMock, PropertyMock, patch
from django.core.cache import cache
+from django.test import SimpleTestCase
from django.utils.timezone import now
import jwt
@@ -19,11 +20,12 @@ from dateutil.relativedelta import relativedelta
from parameterized import parameterized
from requests import Response, get
from rest_framework import status
+from rest_framework.exceptions import ValidationError
from posthog.cloud_utils import TEST_clear_instance_license_cache, get_cached_instance_license
from posthog.constants import AvailableFeature
from posthog.models.oauth import OAuthAccessToken, OAuthApplication
-from posthog.models.organization import OrganizationMembership
+from posthog.models.organization import Organization, OrganizationMembership
from posthog.models.personal_api_key import PersonalAPIKey
from posthog.models.team import Team
from posthog.models.user import User
@@ -1256,6 +1258,60 @@ class TestBillingUsageRequestSerializer(TestCase):
self.assertIsNone(serializer.validated_data.get("end_date"))
+class TestBillingUpstreamValidationErrors(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("start_date", "required", "This field is required."),
+ ("usage_types", "invalid_input", "Invalid value. Check this parameter's format and allowed values."),
+ ("interval", "invalid_choice", "Select a valid option for this parameter."),
+ ]
+ )
+ def test_preserves_safe_field_and_code(self, field: str, code: str, detail: str) -> None:
+ error = Exception(
+ "Billing service returned bad status code: 400",
+ "body:",
+ {
+ "type": "validation_error",
+ "code": code,
+ "attr": field,
+ "detail": "Rejected [email protected]",
+ "extra": {"private": "upstream context"},
+ },
+ )
+
+ with self.assertRaises(ValidationError) as raised:
+ BillingViewset._raise_billing_error(error, Organization(id=uuid4()))
+
+ self.assertEqual(raised.exception.detail, {field: [detail]})
+ self.assertEqual(raised.exception.get_codes(), {field: [code]})
+
+ @parameterized.expand(
+ [
+ ("unknown_field", "validation_error", "private_field", "invalid_input"),
+ ("unknown_code", "validation_error", "start_date", "private_code"),
+ ("wrong_type", "server_error", "start_date", "required"),
+ ("missing_field", "validation_error", None, "invalid_input"),
+ ("malformed_field", "validation_error", ["start_date"], "required"),
+ ("malformed_code", "validation_error", "start_date", ["required"]),
+ ]
+ )
+ def test_masks_unrecognized_validation_errors(
+ self, _name: str, error_type: str, field: object, code: object
+ ) -> None:
+ error = Exception(
+ "Billing service returned bad status code: 400",
+ "body:",
+ {"type": error_type, "code": code, "attr": field, "detail": "Private upstream context"},
+ )
+
+ with self.assertRaises(BillingQueryRejected) as raised:
+ BillingViewset._raise_billing_error(error, Organization(id=uuid4()))
+
+ self.assertEqual(
+ str(raised.exception.detail), "Billing could not answer this request. Adjust the filters and try again."
+ )
+
+
class TestBillingUsageAndSpendAPI(APILicensedTest):
MOCK_USAGE_DATA = {"results": [{"data": [1, 2], "count": 2}]}
MOCK_SPEND_DATA = {"results": [{"spend": 100.0, "usage": 10000}]}
@@ -1420,6 +1476,28 @@ class TestBillingUsageAndSpendAPI(APILicensedTest):
self.assertEqual(response.json()["detail"], BillingQueryRejected.default_detail)
self.assertNotIn("managers.py", response.content.decode())
+ @parameterized.expand([("usage",), ("spend",)])
+ def test_billing_validation_errors_use_standard_response(self, endpoint: str) -> None:
+ with patch(f"ee.billing.billing_manager.BillingManager.get_{endpoint}_data") as mock_fetch:
+ mock_fetch.side_effect = self._billing_refusal(
+ 400,
+ {
+ "type": "validation_error",
+ "code": "required",
+ "attr": "start_date",
+ "detail": "Rejected [email protected]",
+ "extra": {"private": "upstream context"},
+ },
+ )
+
+ response = self.client.get(f"/api/billing/{endpoint}/")
+
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ self.assertEqual(
+ response.json(),
+ {"type": "validation_error", "code": "required", "attr": "start_date", "detail": "This field is required."},
+ )
+
@patch("ee.billing.billing_manager.BillingManager.get_usage_data")
def test_a_failure_inside_billing_is_a_502_without_its_body(self, mock_get_usage_data):
mock_get_usage_data.side_effect = self._billing_refusal(500, "<html>Internal Server Error: stack trace</html>")