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(partners): move stripe provisioning limits onto token buckets (#83938)

Rafael Audiberte0e584d98569
diff --git a/ee/partners/stripe/api/provisioning/constants.py b/ee/partners/stripe/api/provisioning/constants.py
index 0a9e09f86ca5..1b3b450bfc85 100644
--- a/ee/partners/stripe/api/provisioning/constants.py
+++ b/ee/partners/stripe/api/provisioning/constants.py
@@ -69,18 +69,10 @@ SERVICES_CACHE_EXPIRES_KEY = "stripe_provisioning:services:expires_at"
SERVICES_CACHE_STORE_TTL = 86400
# ---------------------------------------------------------------------------
-# Rate limiting - fixed-window counters keyed within this namespace on a fixed
-# Stripe identity. Limits come from RATE_LIMIT_DEFAULTS; a value <= 0 disables
-# the limit for that endpoint.
+# Rate limiting - token buckets keyed within this namespace on a fixed Stripe
+# identity. Budgets are hardcoded in throttling.py.
# ---------------------------------------------------------------------------
-RATE_LIMIT_CACHE_PREFIX = "stripe_provisioning_rate:"
-RATE_LIMIT_WINDOW_SECONDS = 3600
-RATE_LIMIT_DEFAULTS: dict[str, int] = {
- "account_requests": 10,
- "token_exchanges": 20,
- "resource_creates": 20,
-}
RATE_LIMIT_EVENT_NAMES: dict[str, str] = {
"account_requests": "account_request",
"token_exchanges": "token_exchange",
diff --git a/ee/partners/stripe/api/provisioning/region_proxy.py b/ee/partners/stripe/api/provisioning/region_proxy.py
index 274dfe87438c..971b4f4362c7 100644
--- a/ee/partners/stripe/api/provisioning/region_proxy.py
+++ b/ee/partners/stripe/api/provisioning/region_proxy.py
@@ -143,17 +143,52 @@ def _proxy_to_region(request: HttpRequest, target_domain: str) -> HttpResponse:
except ValueError:
data = {"error": "Invalid response from alternate region"}
- return HttpResponse(
+ proxied = HttpResponse(
json.dumps(data, separators=_JSON_SEPARATORS),
status=response.status_code,
content_type="application/json",
)
+ # The region that handled the request computed this wait, and rebuilding
+ # the response would otherwise drop it: a forwarded 429 would tell the
+ # caller nothing about when to retry.
+ retry_after = response.headers.get("Retry-After")
+ if retry_after:
+ proxied["Retry-After"] = retry_after
+ return proxied
except requests.exceptions.RequestException as e:
capture_exception(e, {"target_url": target_url, "step": "stripe_provisioning.proxy.failed"})
raise
+# Sentinel for "the cache backend didn't answer", which is not the same as a
+# real ``None``: a miss is information, an outage is the absence of it.
+_CACHE_UNAVAILABLE = object()
+
+
+def _cache_get(key: str) -> Any:
+ """Read from the cache, returning ``_CACHE_UNAVAILABLE`` on a backend failure.
+
+ The proxy decides whether to forward before authentication or DRF's
+ exception handling run, so an unreachable Redis here would surface as a 500
+ outside this namespace's envelopes. Each caller decides what an outage means
+ for its own check instead.
+ """
+ try:
+ return cache.get(key)
+ except Exception:
+ logger.warning("stripe_provisioning.proxy.cache_unavailable", operation="get")
+ return _CACHE_UNAVAILABLE
+
+
+def _cache_set(key: str, value: Any, timeout: int) -> None:
+ """Best-effort memo: losing it costs the next request a DB lookup, nothing more."""
+ try:
+ cache.set(key, value, timeout=timeout)
+ except Exception:
+ logger.warning("stripe_provisioning.proxy.cache_unavailable", operation="set")
+
+
def _should_proxy_body_region(request: HttpRequest, current_region: str) -> bool:
configuration = _request_payload(request).get("configuration")
if not isinstance(configuration, dict):
@@ -170,7 +205,14 @@ def _should_proxy_token_lookup(request: HttpRequest, current_region: str) -> boo
code = payload.get("code", "")
if not code:
return False
- return cache.get(f"{AUTH_CODE_CACHE_PREFIX}{code}") is None
+ cached = _cache_get(f"{AUTH_CODE_CACHE_PREFIX}{code}")
+ # An unreachable cache can't confirm the code is local, and handling it
+ # here would need that same cache to succeed. Forwarding gives a code
+ # minted in the other region a working path, and turns one minted here
+ # into that region's invalid_grant rather than a 500.
+ if cached is _CACHE_UNAVAILABLE:
+ return True
+ return cached is None
if grant_type == "refresh_token":
refresh_token_value = payload.get("refresh_token", "")
@@ -182,22 +224,20 @@ def _should_proxy_token_lookup(request: HttpRequest, current_region: str) -> boo
def _bearer_exists_locally(token_value: str) -> bool:
- # TODO: latent bug - cache backend failures here (and in the token-lookup
- # check above) propagate as 500s instead of falling back to the local DB
- # lookup.
# SHA-256 the token before using it as a cache key so raw bearer tokens
# never appear in Redis keyspace dumps or logs. Tokens are already
# high-entropy (256 bits from secrets.token_urlsafe), so an unsalted hash
# is sufficient - rainbow tables against 2^256 random inputs are a non-issue.
token_hash = hashlib.sha256(token_value.encode("utf-8")).hexdigest()
cache_key = f"{BEARER_EXISTS_CACHE_PREFIX}{token_hash}"
- cached = cache.get(cache_key)
- if cached is not None:
+ cached = _cache_get(cache_key)
+ if cached is not None and cached is not _CACHE_UNAVAILABLE:
return bool(cached)
+ # The DB is authoritative, so it answers a miss and an outage alike.
exists = find_oauth_access_token(token_value) is not None
ttl = BEARER_EXISTS_POSITIVE_TTL if exists else BEARER_EXISTS_NEGATIVE_TTL
- cache.set(cache_key, exists, timeout=ttl)
+ _cache_set(cache_key, exists, ttl)
return exists
@@ -224,14 +264,11 @@ class RegionProxyMixin:
"""Forward the request to the other region when its resources live there.
Set ``region_proxy_strategy`` on the view. Runs before authentication (a
- bearer that only exists in the other region must proxy, not 401 locally).
- On proxy failure, ``body_region`` returns a flat ``proxy_failed`` 502 (the
+ bearer that only exists in the other region must proxy, not 401 locally),
+ so DRF's throttles never see a forwarded request. The endpoint's own budget
+ applies at the region that handles it. On proxy failure, ``body_region`` returns a flat ``proxy_failed`` 502 (the
request can't be served locally at all); the lookup strategies fall through
to local handling, which produces the appropriate auth error.
-
- TODO: latent gap - because this runs before authentication and rate
- limiting, an unauthenticated caller can induce outbound cross-region
- requests (bounded request amplification).
"""
region_proxy_strategy: str | None = None
@@ -260,18 +297,18 @@ class RegionProxyMixin:
if _STRATEGY_CHECKS[strategy](request, current):
target = _other_region_domain(current)
- logger.info(
- "stripe_provisioning.proxy.routing",
- strategy=strategy,
- current_region=current,
- target_domain=target,
- )
proxy_props = {
"strategy": strategy,
"from_region": current,
"to_domain": target,
"endpoint": request.path,
}
+ logger.info(
+ "stripe_provisioning.proxy.routing",
+ strategy=strategy,
+ current_region=current,
+ target_domain=target,
+ )
try:
response = _proxy_to_region(request, target)
capture_region_proxy_event("proxied", **proxy_props)
diff --git a/ee/partners/stripe/api/provisioning/test/test_region_proxy.py b/ee/partners/stripe/api/provisioning/test/test_region_proxy.py
index d3f098273971..f0a7cca38438 100644
--- a/ee/partners/stripe/api/provisioning/test/test_region_proxy.py
+++ b/ee/partners/stripe/api/provisioning/test/test_region_proxy.py
@@ -5,17 +5,28 @@ from unittest.mock import MagicMock, patch
from django.utils import timezone
+from django_redis.exceptions import ConnectionInterrupted
+
from ee.partners.stripe.api.provisioning.test.base import BASE_PATH, StripeProvisioningTestBase
-def _fake_upstream(payload: dict, status_code: int = 200) -> MagicMock:
+def _fake_upstream(payload: dict, status_code: int = 200, headers: dict | None = None) -> MagicMock:
response = MagicMock()
response.status_code = status_code
response.content = json.dumps(payload).encode()
response.json.return_value = payload
+ # A real dict, so a header the proxy doesn't copy reads as absent here.
+ response.headers = headers or {}
return response
+def _unreachable_cache() -> MagicMock:
+ cache = MagicMock()
+ cache.get.side_effect = ConnectionInterrupted("redis is down")
+ cache.set.side_effect = ConnectionInterrupted("redis is down")
+ return cache
+
+
class TestRegionProxy(StripeProvisioningTestBase):
def _account_request(self, region: str) -> dict:
return {
@@ -107,3 +118,60 @@ class TestRegionProxy(StripeProvisioningTestBase):
res = self._post_signed(f"{BASE_PATH}/provisioning/account_requests", data=self._account_request("EU"))
assert res.status_code == 502
assert res.json() == {"error": {"code": "proxy_failed", "message": "Failed to route to correct region"}}
+
+ def test_forwarded_rejection_keeps_the_wait_the_other_region_computed(self):
+ # The far region owns the bucket, so it owns the wait. Rebuilding the
+ # response here dropped the header and left the caller guessing.
+ with (
+ patch("ee.partners.stripe.api.provisioning.region_proxy.get_instance_region", return_value="US"),
+ patch(
+ "ee.partners.stripe.api.provisioning.region_proxy.requests.request",
+ return_value=_fake_upstream(
+ {"type": "error", "error": {"code": "rate_limited", "message": "Rate limit exceeded."}},
+ status_code=429,
+ headers={"Retry-After": "137"},
+ ),
+ ),
+ ):
+ res = self._post_signed(f"{BASE_PATH}/provisioning/account_requests", data=self._account_request("EU"))
+
+ assert res.status_code == 429
+ assert res["Retry-After"] == "137"
+ assert res.json()["error"]["code"] == "rate_limited"
+
+ def test_unreachable_cache_routes_an_auth_code_it_cannot_look_up(self):
+ # The code lives only in the local cache, so an outage here can't rule it
+ # out and a local exchange would need that same cache anyway.
+ with (
+ patch("ee.partners.stripe.api.provisioning.region_proxy.get_instance_region", return_value="US"),
+ patch("ee.partners.stripe.api.provisioning.region_proxy.cache", _unreachable_cache()),
+ patch(
+ "ee.partners.stripe.api.provisioning.region_proxy.requests.request",
+ return_value=_fake_upstream({"token_type": "bearer", "access_token": "pha_eu"}),
+ ) as proxied,
+ ):
+ res = self._post_signed(
+ f"{BASE_PATH}/oauth/token",
+ data={"grant_type": "authorization_code", "code": "code_of_unknown_region"},
+ content_type="application/x-www-form-urlencoded",
+ )
+
+ assert res.status_code == 200
+ assert res.json()["access_token"] == "pha_eu"
+ proxied.assert_called_once()
+
+ def test_unreachable_cache_falls_back_to_the_db_for_a_local_bearer(self):
+ # A bearer that exists here must not be routed away on an outage: the
+ # other region would reject it. The DB answers the same question.
+ token = self._get_bearer_token()
+
+ with (
+ patch("ee.partners.stripe.api.provisioning.region_proxy.get_instance_region", return_value="US"),
+ patch("ee.partners.stripe.api.provisioning.region_proxy.cache", _unreachable_cache()),
+ patch("ee.partners.stripe.api.provisioning.region_proxy.requests.request") as proxied,
+ ):
+ res = self._get_signed_with_bearer(f"{BASE_PATH}/provisioning/resources/{self.team.id}", token=token)
+
+ assert res.status_code == 200
+ assert res.json()["status"] == "complete"
+ proxied.assert_not_called()
diff --git a/ee/partners/stripe/api/provisioning/test/test_throttles.py b/ee/partners/stripe/api/provisioning/test/test_throttles.py
index 3b3b3c730982..d9f8b18304ba 100644
--- a/ee/partners/stripe/api/provisioning/test/test_throttles.py
+++ b/ee/partners/stripe/api/provisioning/test/test_throttles.py
@@ -5,6 +5,11 @@ from unittest.mock import patch
from django.core.cache import cache
from django.utils import timezone
+from parameterized import parameterized
+
+from posthog.redis import TEST_clear_clients
+from posthog.token_bucket import Budget, TEST_reset_scripts
+
from ee.partners.stripe.api.provisioning.test.base import BASE_PATH, StripeProvisioningTestBase
URL = f"{BASE_PATH}/provisioning/account_requests"
@@ -14,6 +19,10 @@ class TestRateLimits(StripeProvisioningTestBase):
def setUp(self):
super().setUp()
cache.clear()
+ TEST_clear_clients()
+ TEST_reset_scripts()
+ self.addCleanup(TEST_clear_clients)
+ self.addCleanup(TEST_reset_scripts)
def _account_request(self) -> dict:
return {
@@ -24,7 +33,10 @@ class TestRateLimits(StripeProvisioningTestBase):
}
def test_account_requests_are_rate_limited(self):
- with patch.dict("ee.partners.stripe.api.provisioning.throttling.RATE_LIMIT_DEFAULTS", {"account_requests": 1}):
+ with patch.dict(
+ "ee.partners.stripe.api.provisioning.throttling.BUDGETS",
+ {"account_requests": Budget(burst=1, per_hour=1)},
+ ):
assert self._post_signed(URL, data=self._account_request()).status_code == 200
res = self._post_signed(URL, data=self._account_request())
assert res.status_code == 429
@@ -37,14 +49,17 @@ class TestRateLimits(StripeProvisioningTestBase):
}
assert int(res["Retry-After"]) > 0
- def test_zero_default_disables_the_limit(self):
- with patch.dict("ee.partners.stripe.api.provisioning.throttling.RATE_LIMIT_DEFAULTS", {"account_requests": 0}):
+ def test_none_budget_disables_the_limit(self):
+ with patch.dict("ee.partners.stripe.api.provisioning.throttling.BUDGETS", {"account_requests": None}):
assert self._post_signed(URL, data=self._account_request()).status_code == 200
assert self._post_signed(URL, data=self._account_request()).status_code == 200
def test_resource_creates_use_status_envelope(self):
token = self._get_bearer_token()
- with patch.dict("ee.partners.stripe.api.provisioning.throttling.RATE_LIMIT_DEFAULTS", {"resource_creates": 1}):
+ with patch.dict(
+ "ee.partners.stripe.api.provisioning.throttling.BUDGETS",
+ {"resource_creates": Budget(burst=1, per_hour=1)},
+ ):
first = self._post_signed_with_bearer(
f"{BASE_PATH}/provisioning/resources", data={"service_id": "analytics"}, token=token
)
@@ -62,3 +77,68 @@ class TestRateLimits(StripeProvisioningTestBase):
},
}
assert int(res["Retry-After"]) > 0
+
+ @parameterized.expand(
+ [
+ (
+ "account_requests",
+ "typed",
+ {
+ "type": "error",
+ "error": {"code": "rate_limited", "message": "Rate limit exceeded. Try again later."},
+ },
+ ),
+ (
+ "token",
+ "typed",
+ {
+ "type": "error",
+ "error": {"code": "rate_limited", "message": "Rate limit exceeded. Try again later."},
+ },
+ ),
+ (
+ "resources",
+ "status",
+ {
+ "status": "error",
+ "id": "",
+ "error": {"code": "rate_limited", "message": "Rate limit exceeded. Try again later."},
+ },
+ ),
+ ]
+ )
+ def test_global_throttle_rejections_match_the_endpoint_bucket_envelope(self, endpoint, _shape, expected_body):
+ # A rejection from DEFAULT_THROTTLE_CLASSES must render the spec shape,
+ # not DRF's {"detail": ...}, which this namespace's contract never
+ # defines. It must also match what the endpoint's own bucket returns:
+ # the token endpoint declares the oauth envelope but owes typed here.
+ class RefuseEverything:
+ def allow_request(self, request, view):
+ return False
+
+ def wait(self):
+ return 30
+
+ # Minted before the patch, since it spends the token endpoint.
+ token = self._get_bearer_token() if endpoint == "resources" else ""
+
+ with patch(
+ "ee.partners.stripe.api.provisioning.views.StripeProvisioningAPIView.get_throttles",
+ return_value=[RefuseEverything()],
+ ):
+ if endpoint == "account_requests":
+ res = self._post_signed(URL, data=self._account_request())
+ elif endpoint == "token":
+ res = self._post_signed(
+ f"{BASE_PATH}/oauth/token",
+ data={"grant_type": "authorization_code", "code": "unused"},
+ content_type="application/x-www-form-urlencoded",
+ )
+ else:
+ res = self._post_signed_with_bearer(
+ f"{BASE_PATH}/provisioning/resources", data={"service_id": "analytics"}, token=token
+ )
+
+ assert res.status_code == 429
+ assert res.json() == expected_body
+ assert res["Retry-After"] == "30"
diff --git a/ee/partners/stripe/api/provisioning/throttling.py b/ee/partners/stripe/api/provisioning/throttling.py
index 175f84c5231f..2478809de770 100644
--- a/ee/partners/stripe/api/provisioning/throttling.py
+++ b/ee/partners/stripe/api/provisioning/throttling.py
@@ -1,99 +1,86 @@
"""Rate limiting for the Stripe provisioning namespace.
-Fixed-window counters with fixed per-endpoint limits from ``RATE_LIMIT_DEFAULTS``
-- this namespace serves a single caller (Stripe), so the window is keyed on a
-constant identity rather than any OAuthApplication field. A limit <= 0 disables
-it. The caller can burst up to 2x the limit across a window boundary; switch to
-a sliding window if that ever matters.
+Token buckets (:mod:`posthog.token_bucket`) with budgets hardcoded inline: this
+namespace serves a single caller (Stripe), so there are no tiers, no
+per-partner overrides, and the bucket is keyed on a constant identity rather
+than any OAuthApplication field. Burst equals the hourly rate, so the full
+budget is available at once (matching the fixed window this replaced) while
+the continuous refill removes the 2x window-boundary burst and gives a real
+per-caller Retry-After.
"""
from __future__ import annotations
-import time
from typing import ClassVar
-from django.core.cache import cache
-
import structlog
-from django_redis.exceptions import ConnectionInterrupted
-from redis.exceptions import RedisError
from rest_framework.request import Request
from rest_framework.throttling import BaseThrottle
from rest_framework.views import APIView
+from posthog.token_bucket import BucketDecision, BucketUnavailable, Budget, consume
+
from ee.partners.stripe.api.provisioning.analytics import capture_provisioning_event
-from ee.partners.stripe.api.provisioning.constants import (
- RATE_LIMIT_CACHE_PREFIX,
- RATE_LIMIT_DEFAULTS,
- RATE_LIMIT_EVENT_NAMES,
- RATE_LIMIT_WINDOW_SECONDS,
-)
+from ee.partners.stripe.api.provisioning.constants import RATE_LIMIT_EVENT_NAMES
from ee.partners.stripe.api.provisioning.exceptions import SpecError
logger = structlog.get_logger(__name__)
-# Single-caller namespace: the rate-limit window is keyed on this constant, not
-# on any per-app identity or config.
+# Single-caller namespace: buckets are keyed on this constant, not on any
+# per-app identity or config.
_STRIPE_RATE_LIMIT_KEY = "stripe"
+BUCKET_KEY_PREFIX = "stripe_provisioning_bucket:"
+
+# None disables the endpoint's limit.
+BUDGETS: dict[str, Budget | None] = {
+ "account_requests": Budget(burst=10, per_hour=10),
+ "token_exchanges": Budget(burst=20, per_hour=20),
+ "resource_creates": Budget(burst=20, per_hour=20),
+}
-class StripeFixedWindowThrottle(BaseThrottle):
- """Fixed-window counter keyed on the endpoint + window-of-epoch."""
+class StripeBucketThrottle(BaseThrottle):
+ """Token bucket keyed on the endpoint + the constant Stripe identity."""
endpoint: ClassVar[str]
def __init__(self) -> None:
- self.limit = RATE_LIMIT_DEFAULTS[self.endpoint]
- self.count = 0
+ self.limit = 0
+ self.decision: BucketDecision | None = None
def allow_request(self, request: Request, view: APIView) -> bool:
- if self.limit <= 0:
+ budget = BUDGETS[self.endpoint]
+ if budget is None:
return True
+ self.limit = budget.per_hour
- window_index = int(time.time()) // RATE_LIMIT_WINDOW_SECONDS
- cache_key = f"{RATE_LIMIT_CACHE_PREFIX}{self.endpoint}:{_STRIPE_RATE_LIMIT_KEY}:{window_index}"
-
- try:
- cache.add(cache_key, 0, timeout=RATE_LIMIT_WINDOW_SECONDS)
- self.count = cache.incr(cache_key)
- except ValueError as e:
- # incr raises ValueError when the key expired between add and incr.
- logger.warning("stripe_provisioning_rate_limit_cache_error", endpoint=self.endpoint, error=str(e))
- try:
- # cache.add preserves any counter a concurrent request already initialized,
- # so a transient cache error doesn't reset the window when at the limit.
- cache.add(cache_key, 1, timeout=RATE_LIMIT_WINDOW_SECONDS)
- except (RedisError, ConnectionInterrupted):
- pass
- self.count = 1
- except (RedisError, ConnectionInterrupted) as e:
- # Redis is unreachable (its errors subclass RedisError/Exception, not the
- # builtin ConnectionError/TimeoutError). Fail open without touching the
- # cache again: a second cache call would raise the same way and turn every
- # provisioning request into a 500 for as long as Redis is down.
- logger.warning("stripe_provisioning_rate_limit_cache_error", endpoint=self.endpoint, error=str(e))
- self.count = 1
-
- return self.count <= self.limit
+ decision = consume(f"{BUCKET_KEY_PREFIX}{self.endpoint}:{_STRIPE_RATE_LIMIT_KEY}", budget)
+ if isinstance(decision, BucketUnavailable):
+ # Fail open: an unreachable Redis must not take the namespace down.
+ logger.warning("stripe_provisioning_rate_limit_unavailable", endpoint=self.endpoint)
+ return True
+
+ self.decision = decision
+ return decision.allowed
def wait(self) -> float:
- return float(RATE_LIMIT_WINDOW_SECONDS - (int(time.time()) % RATE_LIMIT_WINDOW_SECONDS))
+ return float(self.decision.retry_after) if self.decision is not None else 0.0
-class AccountRequestsThrottle(StripeFixedWindowThrottle):
+class AccountRequestsThrottle(StripeBucketThrottle):
endpoint = "account_requests"
-class TokenExchangesThrottle(StripeFixedWindowThrottle):
+class TokenExchangesThrottle(StripeBucketThrottle):
endpoint = "token_exchanges"
-class ResourceCreatesThrottle(StripeFixedWindowThrottle):
+class ResourceCreatesThrottle(StripeBucketThrottle):
endpoint = "resource_creates"
def enforce_stripe_rate_limit(
- throttle_cls: type[StripeFixedWindowThrottle],
+ throttle_cls: type[StripeBucketThrottle],
request: Request,
view: APIView,
*,
@@ -115,7 +102,7 @@ def enforce_stripe_rate_limit(
RATE_LIMIT_EVENT_NAMES[endpoint],
"rate_limited",
limit=throttle.limit,
- count=throttle.count,
+ retry_after=int(throttle.wait()),
)
raise SpecError(
"rate_limited",
diff --git a/ee/partners/stripe/api/provisioning/views.py b/ee/partners/stripe/api/provisioning/views.py
index 313d3bd463da..0865fce94154 100644
--- a/ee/partners/stripe/api/provisioning/views.py
+++ b/ee/partners/stripe/api/provisioning/views.py
@@ -17,6 +17,7 @@ of the HMAC), so those two run every check explicitly in the handler.
from __future__ import annotations
import re
+import math
import base64
import hashlib
import secrets
@@ -103,6 +104,32 @@ class StripeProvisioningAPIView(RegionProxyMixin, APIView):
authentication_classes: list[type[BaseAuthentication]] = []
permission_classes: list = []
spec_envelope: ClassVar[Envelope] = "flat"
+ # Rate-limit errors keep one shape per endpoint whichever throttle refuses,
+ # so a global throttle can't answer a bucket rejection in another envelope.
+ # The token endpoint keeps the typed shape here, not its own oauth one.
+ rate_limit_envelope: ClassVar[Envelope] = "typed"
+
+ def check_throttles(self, request: Request) -> None:
+ """Reject in the endpoint's rate-limit envelope: DRF's default
+ ``{"detail": ...}`` shape is not part of this namespace's wire contract
+ and must not leak out of it, whichever throttle refuses. Consults every throttle and keeps
+ the longest wait, mirroring DRF's own ``check_throttles`` so
+ ``Retry-After`` is the real time until the request would be allowed,
+ not the first refusing throttle's shorter window."""
+ durations: list[float | None] = []
+ for throttle in self.get_throttles():
+ if not throttle.allow_request(request, self):
+ durations.append(throttle.wait())
+ if not durations:
+ return
+ wait = max((d for d in durations if d is not None), default=None)
+ raise SpecError(
+ "rate_limited",
+ "Rate limit exceeded. Try again later.",
+ status=429,
+ envelope=self.rate_limit_envelope,
+ retry_after=math.ceil(wait) if wait else None,
+ )
def handle_exception(self, exc: Exception) -> Response:
if isinstance(exc, PreRenderedError):
@@ -538,6 +565,7 @@ class OAuthTokenView(StripeProvisioningAPIView):
class StripeResourceAPIView(SignatureCheckedMixin, StripeProvisioningAPIView):
spec_envelope = "status"
+ rate_limit_envelope: ClassVar[Envelope] = "status"
region_proxy_strategy = "bearer_lookup"
authentication_classes = [StripeBearerAuthentication]