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(agentic-provisioning): check all stripe signatures on rotation (#61131)

Matt Brooker3d174cf0f886
diff --git a/ee/api/agentic_provisioning/signature.py b/ee/api/agentic_provisioning/signature.py
index 54f8ce337f40..ac058cb8c04e 100644
--- a/ee/api/agentic_provisioning/signature.py
+++ b/ee/api/agentic_provisioning/signature.py
@@ -1,12 +1,12 @@
import re
import hmac
-import time
import uuid
import hashlib
from django.conf import settings
from django.http.request import RawPostDataException
+import stripe
import structlog
import posthoganalytics
from rest_framework.request import Request
@@ -49,6 +49,12 @@ def verify_provisioning_signature(request: Request) -> Response | None:
Returns None if verification passes, or an error Response if it fails.
Called at the top of every view (Vercel-style, not middleware).
+
+ Delegates to the Stripe SDK, which checks the timestamp and every ``v1``
+ signature in the header. During a ``STRIPE_SIGNING_SECRET`` rotation the
+ sender dual-signs each request, so the header carries the old and new
+ signatures at once; matching against any of them keeps verification working
+ across the switch-over instead of breaking the moment the secret changes.
"""
endpoint = request.path
@@ -57,28 +63,6 @@ def verify_provisioning_signature(request: Request) -> Response | None:
_log_and_capture_event("server_error", 500, endpoint)
return Response({"error": {"code": "server_error", "message": "Signing secret not configured"}}, status=500)
- sig_header = request.headers.get("stripe-signature", "")
- parsed = _parse_signature_header(sig_header)
- if parsed is None:
- _log_and_capture_event("invalid_signature", 401, endpoint, reason="missing_or_malformed_header")
- return Response(
- {"error": {"code": "invalid_signature", "message": "Missing or malformed Stripe-Signature header"}},
- status=401,
- )
-
- timestamp_str, signature_hex = parsed
-
- now = int(time.time())
- timestamp = int(timestamp_str)
- if abs(now - timestamp) > MAX_TIMESTAMP_DRIFT_SECONDS:
- _log_and_capture_event(
- "invalid_signature", 401, endpoint, reason="timestamp_drift", drift_seconds=abs(now - timestamp)
- )
- return Response(
- {"error": {"code": "invalid_signature", "message": "Timestamp too old or too far in the future"}},
- status=401,
- )
-
body = _get_raw_body(request)
if body is None:
_log_and_capture_event("body_not_readable", 400, endpoint)
@@ -92,10 +76,20 @@ def verify_provisioning_signature(request: Request) -> Response | None:
status=400,
)
- expected_hex = _compute_hmac(secret, timestamp_str, body)
+ try:
+ decoded_body = body.decode("utf-8")
+ except UnicodeDecodeError as e:
+ _log_and_capture_event("body_not_decodable", 400, endpoint, reason=str(e))
+ return Response(
+ {"error": {"code": "body_not_decodable", "message": "Request body must be UTF-8 encoded"}},
+ status=400,
+ )
- if not hmac.compare_digest(expected_hex.lower(), signature_hex.lower()):
- _log_and_capture_event("invalid_signature", 401, endpoint, reason="hmac_mismatch")
+ sig_header = request.headers.get("stripe-signature", "")
+ try:
+ stripe.WebhookSignature.verify_header(decoded_body, sig_header, secret, tolerance=MAX_TIMESTAMP_DRIFT_SECONDS)
+ except stripe.SignatureVerificationError as e:
+ _log_and_capture_event("invalid_signature", 401, endpoint, reason=str(e))
return Response(
{"error": {"code": "invalid_signature", "message": "Signature verification failed"}}, status=401
)
diff --git a/ee/api/agentic_provisioning/test/test_signature.py b/ee/api/agentic_provisioning/test/test_signature.py
index 7824347d709e..0a253a56fdc4 100644
--- a/ee/api/agentic_provisioning/test/test_signature.py
+++ b/ee/api/agentic_provisioning/test/test_signature.py
@@ -142,3 +142,62 @@ class TestVerifySignatureAfterDRFParsing(TestCase):
drf_request = Request(django_request, parsers=[JSONParser()])
result = verify_provisioning_signature(drf_request)
assert result is None
+
+ def _make_request(self, body: bytes, sig_header: str) -> Request:
+ django_request = HttpRequest()
+ django_request.method = "POST"
+ django_request.content_type = "application/json"
+ django_request.META = {
+ "REQUEST_METHOD": "POST",
+ "CONTENT_TYPE": "application/json",
+ "CONTENT_LENGTH": str(len(body)),
+ "HTTP_STRIPE_SIGNATURE": sig_header,
+ }
+ django_request._stream = io.BytesIO(body)
+ django_request._read_started = False # type: ignore[attr-defined]
+ return cast(Request, Request(django_request, parsers=[JSONParser()]))
+
+ def test_succeeds_with_multiple_signatures_during_rotation(self):
+ # Stripe dual-signs while a signing-secret rotation is in flight, so the header
+ # carries the stale (old secret) signature alongside the current one. The current
+ # signature appears second here to guard against only checking the first v1.
+ body = b'{"email":"[email protected]"}'
+ ts = int(time.time())
+ stale_sig = compute_signature("rotated_out_secret", ts, body)
+ current_sig = compute_signature(HMAC_SECRET, ts, body)
+
+ drf_request = self._make_request(body, f"t={ts},v1={stale_sig},v1={current_sig}")
+ result = verify_provisioning_signature(drf_request)
+ assert result is None
+
+ @parameterized.expand(
+ [
+ (
+ "no_signature_matches",
+ lambda body,
+ ts: f"t={ts},v1={compute_signature('wrong_a', ts, body)},v1={compute_signature('wrong_b', ts, body)}",
+ ),
+ ("stale_timestamp", lambda body, ts: f"t={ts - 301},v1={compute_signature(HMAC_SECRET, ts - 301, body)}"),
+ ("wrong_scheme_only", lambda body, ts: f"t={ts},v0={compute_signature(HMAC_SECRET, ts, body)}"),
+ ("missing_header", lambda body, ts: ""),
+ ]
+ )
+ def test_rejects_invalid_signature(self, _name, build_header):
+ body = b'{"email":"[email protected]"}'
+ ts = int(time.time())
+
+ drf_request = self._make_request(body, build_header(body, ts))
+ result = verify_provisioning_signature(drf_request)
+ assert result is not None
+ assert result.status_code == 401
+ assert result.data["error"]["code"] == "invalid_signature"
+
+ def test_non_utf8_body_is_a_bad_request_not_a_signature_failure(self):
+ body = b"\xff\xfe not valid utf-8"
+ ts = int(time.time())
+
+ drf_request = self._make_request(body, f"t={ts},v1={'ab' * 32}")
+ result = verify_provisioning_signature(drf_request)
+ assert result is not None
+ assert result.status_code == 400
+ assert result.data["error"]["code"] == "body_not_decodable"