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.

feat(provisioning): derive partner tiers and cut rate limits over to token buckets (#83935)

Rafael Audibert75ed83d3e4dd
diff --git a/.agents/skills/using-redis-token-buckets/SKILL.md b/.agents/skills/using-redis-token-buckets/SKILL.md
index ff455b899647..ca4b52259696 100644
--- a/.agents/skills/using-redis-token-buckets/SKILL.md
+++ b/.agents/skills/using-redis-token-buckets/SKILL.md
@@ -62,6 +62,10 @@ Semantics worth knowing:
- Keys are fully caller-constructed. Prefix them (`<feature>_rate:`), include every identity the budget is scoped to, and never include secrets. The bucket self-expires once it would be full again, so idle keys clean themselves up.
- Nothing raises on Redis failure: every operation returns `BucketUnavailable` and the **caller** decides fail-open vs fall-through. Do not swallow it silently; log or count it so an outage is visible.
+## Reference consumer
+
+The agentic provisioning rate limits (`ee/api/agentic_provisioning/ratelimits.py`) are the canonical consumer: per-partner budgets declared on handlers with `@rate_limited`, tier multipliers, refund-on-no-work in `handle_exception`, `RateLimit-*` headers from the decision, and Prometheus counters around every outcome. Read it before building a second rate-limit layer on top of the bucket.
+
## Testing
Under `settings.TEST`, `posthog.redis.get_client()` returns fakeredis, which executes the Lua scripts (via lupa). Control time with `freeze_time` (the script's clock is passed in from Python), reset between tests with `posthog.redis.TEST_clear_clients()` + `posthog.token_bucket.TEST_reset_scripts()`, and see `posthog/test/test_token_bucket.py` for the pattern.
diff --git a/ee/api/agentic_provisioning/accounts.py b/ee/api/agentic_provisioning/accounts.py
index ddcea9496d64..d449bdb1737d 100644
--- a/ee/api/agentic_provisioning/accounts.py
+++ b/ee/api/agentic_provisioning/accounts.py
@@ -16,6 +16,7 @@ from posthog.event_usage import report_user_signed_up
from posthog.exceptions_capture import capture_exception
from posthog.models.oauth import OAuthApplication
from posthog.models.team.team import Team
+from posthog.models.team.team_provisioning_config import TeamProvisioningConfig
from posthog.models.user import User
from posthog.scopes import scopes_within_ceiling
from posthog.tasks.email import send_provisioning_welcome
@@ -266,6 +267,12 @@ def handle_new_user(
team_id=team.id,
)
+ # Attribute the bootstrap team to the creating partner. The row already exists
+ # (the Team extension signal created it inside bootstrap), so this is an update.
+ # Without it the mapping stays unclaimed, and resource removal treats unclaimed as
+ # fair game for any partner whose token happens to scope the team.
+ TeamProvisioningConfig.objects.filter(team_id=team.id, application__isnull=True).update(application=partner)
+
# Every provisioned account is treated as already onboarded — apply the flags at
# bootstrap so the account is covered regardless of which follow-up blocks (if any)
# run, rather than only on the GitHub wizard path.
diff --git a/ee/api/agentic_provisioning/constants.py b/ee/api/agentic_provisioning/constants.py
index b078904360f9..9424747e3ef8 100644
--- a/ee/api/agentic_provisioning/constants.py
+++ b/ee/api/agentic_provisioning/constants.py
@@ -33,22 +33,8 @@ CLIENT_REGISTRATION_RATE_LIMIT_WINDOW_SECONDS = 3600
# should still be able to spend a full budget on each.
CLIENT_REGISTRATION_IP_RATE_LIMIT_MAX = 120
-PARTNER_RATE_LIMIT_PREFIX = "provisioning_partner_rate:"
-PARTNER_RATE_LIMIT_WINDOW_SECONDS = 3600
-PARTNER_RATE_LIMIT_DEFAULTS: dict[str, int] = {
- "account_requests": 10,
- "token_exchanges": 20,
- "resource_creates": 20,
- "github_grants": 10,
- "wizard_runs": 20,
-}
-PARTNER_RATE_LIMIT_EVENT_NAMES: dict[str, str] = {
- "account_requests": "account_request",
- "token_exchanges": "token_exchange",
- "resource_creates": "resource_created",
- "github_grants": "github_grant",
- "wizard_runs": "wizard_run",
-}
+# Per-partner endpoint budgets live in ee/api/agentic_provisioning/ratelimits.py,
+# declared on each handler with @rate_limited.
# Per-user wizard-run budget matching the session endpoint's limits (2/hour, 5/day), which
# can't run here — the partner path has no session user on the request. Unlike the session
@@ -61,12 +47,6 @@ WIZARD_RUN_USER_RATE_LIMITS: list[tuple[str, int, int]] = [
("day", 5, 86400),
]
-# Repo-picker polling budget per grant (the website polls while the visitor installs the
-# GitHub App in another tab). Keyed per grant, so one stuck visitor can't starve others.
-GITHUB_GRANT_POLL_RATE_LIMIT_PREFIX = "provisioning_github_grant_poll:"
-GITHUB_GRANT_POLL_RATE_LIMIT_MAX = 120
-GITHUB_GRANT_POLL_RATE_LIMIT_WINDOW_SECONDS = 3600
-
# Per-IP ceiling on cross-region forwarding. The region proxy decides to forward before
# DRF authenticates or throttles anything, and each forwarded request occupies a worker
# until the other region answers, so this is the only limit an unauthenticated caller
diff --git a/ee/api/agentic_provisioning/ratelimits.py b/ee/api/agentic_provisioning/ratelimits.py
new file mode 100644
index 000000000000..38f00bdfb707
--- /dev/null
+++ b/ee/api/agentic_provisioning/ratelimits.py
@@ -0,0 +1,368 @@
+"""Partner rate limits for the agentic provisioning API.
+
+Every partner-scoped limit is a token bucket (:mod:`posthog.token_bucket`)
+whose size is declared on the endpoint handler with :func:`rate_limited` and
+scaled by the partner's derived tier
+(:class:`~posthog.models.oauth_provisioning.PartnerTier`): stronger client
+authentication and attestation each raise the budget, with no stored state and
+no admin involvement. An explicit per-partner override in the provisioning
+config outranks the computed value.
+
+Charging happens two ways, mirroring where the partner becomes known:
+
+- ``charge="auto"``: the base view charges in ``check_throttles`` from the
+ partner on ``request.auth``. Runs after the per-IP throttles, so a request
+ those refuse spends no partner quota.
+- ``charge="manual"``: the handler calls ``self.charge_rate_limit(...)`` once
+ it has resolved its partner (the token endpoint decodes a grant first,
+ account_requests must clear the capability check before spending quota), or
+ a flow outside any view (the bundled account-request wizard block) calls
+ :func:`charge_partner_by_name`.
+
+A charge is refunded in ``handle_exception`` when the request provably did no
+work (the error code is in the declaration's ``refund_on``), so a partner
+debugging a 400 does not spend its budget on rejections.
+
+The buckets are best-effort: Redis eviction or an outage hands a caller a
+fresh budget, and charging fails open. Losing a key costs one extra burst
+before the normal refill resumes, which is the overage this accepts.
+"""
+
+from __future__ import annotations
+
+import math
+from collections.abc import Callable, Mapping
+from typing import ClassVar, Literal
+
+from django.core.exceptions import ImproperlyConfigured
+
+import structlog
+from prometheus_client import Counter, Histogram
+from rest_framework.request import Request
+
+from posthog.dataclasses import frozen
+from posthog.models.oauth import OAuthAccessToken, OAuthApplication
+from posthog.models.oauth_provisioning import PartnerTier
+from posthog.token_bucket import BucketDecision, BucketUnavailable, Budget, consume, refund
+
+from ee.api.agentic_provisioning.analytics import capture_provisioning_event
+from ee.api.agentic_provisioning.exceptions import Envelope, ProvisioningError
+
+logger = structlog.get_logger(__name__)
+
+BUCKET_KEY_PREFIX = "provisioning_bucket:"
+
+RATE_LIMITED_MESSAGE = "Rate limit exceeded for this partner. Try again later."
+TIER_BLOCKED_MESSAGE = (
+ "This endpoint is not available for this partner's tier. "
+ "Publish a JWKS document or verify your organization to raise your tier."
+)
+
+# One PUBLIC-tier budget fits most endpoints; only endpoints where it is wrong
+# declare their own. Scaling: PUBLIC x1, PUBLIC_ATTESTED x2, JWKS x5, JWKS_ATTESTED x10.
+DEFAULT_BUDGET = Budget(burst=30, per_hour=120)
+TIER_MULTIPLIERS: dict[PartnerTier, int] = {
+ PartnerTier.PUBLIC: 1,
+ PartnerTier.PUBLIC_ATTESTED: 2,
+ PartnerTier.JWKS: 5,
+ PartnerTier.JWKS_ATTESTED: 10,
+}
+# A tier multiplier of BLOCKED means the tier may not use the endpoint at all.
+# An explicit per-partner override outranks it.
+BLOCKED = 0
+# Multipliers for budgets that must not scale with tier (polling caps).
+FLAT_MULTIPLIERS: dict[PartnerTier, int] = dict.fromkeys(TIER_MULTIPLIERS, 1)
+
+# Error codes whose requests provably did no work: rejections raised before the
+# endpoint writes anything or calls out. Any invalid_* code counts as no-work too
+# (see _did_no_work), so validation codes need no entry here. Codes like
+# github_unavailable are deliberately absent because the outbound call already
+# happened, and so is not_found: the endpoints that raise it do so only after
+# resolving the resource, so refunding it would make repeated probes free. An
+# endpoint that rejects before resolving anything can name its own code in
+# refund_on.
+DID_NO_WORK_CODES: frozenset[str] = frozenset(
+ {
+ "forbidden",
+ "unauthorized",
+ "no_team",
+ "team_not_found",
+ "grant_not_found",
+ "deep_links_not_enabled",
+ "wizard_unavailable",
+ }
+)
+
+# The endpoints whose per-partner override fields exist on ProvisioningRateLimits
+# today. Endpoints outside this set are tier-derived only until the override
+# storage becomes a per-endpoint dict.
+LEGACY_OVERRIDE_ENDPOINTS: frozenset[str] = frozenset(
+ {"account_requests", "token_exchanges", "resource_creates", "github_grants", "wizard_runs"}
+)
+
+DECISIONS_COUNTER = Counter(
+ "provisioning_rate_limit_decisions_total",
+ "Partner rate limit decisions on the agentic provisioning API.",
+ labelnames=["endpoint", "tier", "outcome"],
+)
+HEADROOM_HISTOGRAM = Histogram(
+ "provisioning_rate_limit_headroom_ratio",
+ "Remaining/limit ratio at decision time, for spotting partners near their budget.",
+ labelnames=["endpoint", "tier"],
+ buckets=(0.0, 0.1, 0.25, 0.5, 0.75, 0.9, 1.0),
+)
+BACKEND_ERRORS_COUNTER = Counter(
+ "provisioning_rate_limit_backend_errors_total",
+ "Rate limit decisions Redis could not answer, by fallback mode.",
+ labelnames=["endpoint", "mode"],
+)
+
+
+@frozen
+class BudgetDeclaration:
+ endpoint: str
+ budget: Budget
+ multipliers: Mapping[PartnerTier, int]
+ charge: Literal["auto", "manual"]
+ refund_on: frozenset[str]
+ key: Callable[[Request, object], str] | None
+ # Overrides the view's error envelope on the 429 (the token endpoint keeps
+ # the typed envelope, its historical wire shape).
+ envelope: Envelope | None
+
+
+@frozen(frozen=False)
+class RateLimitLedger:
+ """One charge against a bucket, kept on the request for refunds and headers."""
+
+ declaration: BudgetDeclaration
+ bucket_key: str
+ budget: Budget
+ decision: BucketDecision
+ tier: PartnerTier
+ refunded: bool = False
+
+ LEDGERS_ATTR: ClassVar[str] = "_provisioning_ledgers"
+
+
+_REGISTRY: dict[str, BudgetDeclaration] = {}
+
+
+def rate_limited(
+ endpoint: str,
+ *,
+ budget: Budget = DEFAULT_BUDGET,
+ multipliers: Mapping[PartnerTier, int] | None = None,
+ charge: Literal["auto", "manual"] = "auto",
+ refund_on: frozenset[str] = DID_NO_WORK_CODES,
+ key: Callable[[Request, object], str] | None = None,
+ envelope: Envelope | None = None,
+) -> Callable:
+ """Declare an endpoint's rate limit budget on its handler.
+
+ Pure metadata, like DRF's own ``@throttle_classes``: nothing is wrapped, the
+ base view reads the declaration from the handler. ``multipliers`` merges over
+ :data:`TIER_MULTIPLIERS`, so an endpoint states only the cells where the
+ default grid is wrong. Stacking two declarations on one handler is allowed
+ (the token endpoint charges different buckets per grant type); a manual
+ handler with several then names the endpoint when it charges.
+ """
+ declaration = BudgetDeclaration(
+ endpoint=endpoint,
+ budget=budget,
+ multipliers={**TIER_MULTIPLIERS, **(multipliers or {})},
+ charge=charge,
+ refund_on=refund_on,
+ key=key,
+ envelope=envelope,
+ )
+
+ existing = _REGISTRY.get(endpoint)
+ if existing is not None and existing != declaration:
+ raise ImproperlyConfigured(
+ f"Conflicting rate limit declarations for endpoint {endpoint!r}. "
+ "One endpoint name means one budget; declare it once and share it."
+ )
+ _REGISTRY[endpoint] = declaration
+
+ def decorate(handler: Callable) -> Callable:
+ budgets = dict(getattr(handler, "_provisioning_budgets", {}))
+ budgets[endpoint] = declaration
+ handler._provisioning_budgets = budgets # type: ignore[attr-defined]
+ return handler
+
+ return decorate
+
+
+def registered_budgets() -> Mapping[str, BudgetDeclaration]:
+ """Every declared endpoint budget, for introspection surfaces."""
+ return dict(_REGISTRY)
+
+
+def partner_for_rate_limiting(request: Request) -> OAuthApplication | None:
+ """The app to charge, from either bearer or client authentication.
+
+ Keyed on carrying provisioning config rather than is_provisioning_partner, so
+ disabling a partner does not also un-throttle its outstanding tokens. Plain
+ OAuth apps whose tokens reach these endpoints carry no partner quota.
+ """
+ auth = request.auth
+ if isinstance(auth, OAuthAccessToken):
+ app = auth.application
+ elif isinstance(auth, OAuthApplication):
+ app = auth
+ else:
+ return None
+ if app is None or not app.carries_provisioning_config:
+ return None
+ return app
+
+
+def _legacy_override(partner: OAuthApplication, endpoint: str) -> int | None:
+ if endpoint not in LEGACY_OVERRIDE_ENDPOINTS:
+ return None
+ return getattr(partner.provisioning.rate_limits, endpoint, None)
+
+
+def resolve_budget(declaration: BudgetDeclaration, partner: OAuthApplication) -> Budget | None:
+ """The bucket to charge for this partner, or None when it is unlimited.
+
+ Raises the tier-blocked error when the tier multiplier is BLOCKED and no
+ override exists; an admin override outranks BLOCKED, so a specific partner
+ can be granted an endpoint without moving its whole tier.
+ """
+ tier = partner.partner_tier
+ multiplier = declaration.multipliers[tier]
+ override = _legacy_override(partner, declaration.endpoint)
+
+ if override is not None:
+ if override <= 0:
+ return None
+ # The override replaces the hourly rate; burst keeps the endpoint's
+ # declared burst-to-rate proportion, independent of tier, so an
+ # override means the same thing whatever tier the partner sits on.
+ burst = max(1, math.ceil(declaration.budget.burst * override / declaration.budget.per_hour))
+ return Budget(burst=burst, per_hour=override)
+
+ if multiplier == BLOCKED:
+ DECISIONS_COUNTER.labels(endpoint=declaration.endpoint, tier=tier, outcome="tier_blocked").inc()
+ capture_provisioning_event("rate_limited", "tier_blocked", partner=partner, endpoint=declaration.endpoint)
+ raise ProvisioningError("forbidden", TIER_BLOCKED_MESSAGE, status=403, envelope=declaration.envelope)
+
+ return Budget(burst=declaration.budget.burst * multiplier, per_hour=declaration.budget.per_hour * multiplier)
+
+
+def _bucket_key(endpoint: str, partner: OAuthApplication, key_suffix: str = "") -> str:
+ key = f"{BUCKET_KEY_PREFIX}{endpoint}:{partner.id}"
+ return f"{key}:{key_suffix}" if key_suffix else key
+
+
+def charge_partner(
+ declaration: BudgetDeclaration,
+ partner: OAuthApplication,
+ *,
+ request: Request | None = None,
+ key_suffix: str = "",
+ resource_id: str = "",
+) -> None:
+ """Charge one request against the partner's bucket for this endpoint.
+
+ Raises the wire-contract ``rate_limited`` error when over budget. When a
+ request is passed, the charge lands on its ledger so ``handle_exception``
+ can refund it and ``finalize_response`` can emit RateLimit-* headers.
+ """
+ tier = partner.partner_tier
+ budget = resolve_budget(declaration, partner)
+ if budget is None:
+ return
+
+ bucket_key = _bucket_key(declaration.endpoint, partner, key_suffix)
+
+ decision = consume(bucket_key, budget)
+ if isinstance(decision, BucketUnavailable):
+ # Fail open: an unreachable Redis must not take the API down.
+ BACKEND_ERRORS_COUNTER.labels(endpoint=declaration.endpoint, mode="failed_open").inc()
+ return
+
+ HEADROOM_HISTOGRAM.labels(endpoint=declaration.endpoint, tier=tier).observe(
+ decision.remaining / decision.limit if decision.limit else 0.0
+ )
+
+ if request is not None:
+ ledgers = getattr(request, RateLimitLedger.LEDGERS_ATTR, None)
+ if ledgers is None:
+ ledgers = []
+ setattr(request, RateLimitLedger.LEDGERS_ATTR, ledgers)
+ ledgers.append(
+ RateLimitLedger(declaration=declaration, bucket_key=bucket_key, budget=budget, decision=decision, tier=tier)
+ )
+
+ if not decision.allowed:
+ DECISIONS_COUNTER.labels(endpoint=declaration.endpoint, tier=tier, outcome="throttled").inc()
+ capture_provisioning_event(
+ "rate_limited",
+ "rate_limited",
+ partner=partner,
+ endpoint=declaration.endpoint,
+ limit=budget.per_hour,
+ retry_after=decision.retry_after,
+ )
+ raise ProvisioningError(
+ "rate_limited",
+ RATE_LIMITED_MESSAGE,
+ status=429,
+ envelope=declaration.envelope,
+ resource_id=resource_id,
+ retry_after=decision.retry_after,
+ )
+
+ DECISIONS_COUNTER.labels(endpoint=declaration.endpoint, tier=tier, outcome="allowed").inc()
+
+
+def charge_partner_by_name(
+ endpoint: str, partner: OAuthApplication, *, request: Request | None = None, resource_id: str = ""
+) -> None:
+ """Charge by registry name, for flows that run outside any view dispatch
+ (the bundled account-request wizard block)."""
+ declaration = _REGISTRY.get(endpoint)
+ if declaration is None:
+ # Declarations register when the view modules import. Web processes load
+ # them through the URLconf; anything else (a test importing accounts.py
+ # directly) gets them here. Function-local to break the views->ratelimits
+ # import cycle.
+ from ee.api.agentic_provisioning import views # noqa: F401, PLC0415
+
+ declaration = _REGISTRY.get(endpoint)
+ if declaration is None:
+ raise ImproperlyConfigured(f"No rate limit declared for endpoint {endpoint!r}")
+ charge_partner(declaration, partner, request=request, resource_id=resource_id)
+
+
+def _did_no_work(error_code: str, refund_on: frozenset[str]) -> bool:
+ # invalid_* is the convention every validation rejection follows, including
+ # per-endpoint serializer codes (invalid_label_prefix, invalid_path, ...), so
+ # the prefix refunds them without enumerating each one.
+ return error_code in refund_on or error_code.startswith("invalid_")
+
+
+def refund_no_work(request: Request, error_code: str) -> None:
+ """Give charges back when the request's failure proves it did no work."""
+ for ledger in getattr(request, RateLimitLedger.LEDGERS_ATTR, []):
+ if ledger.refunded or not _did_no_work(error_code, ledger.declaration.refund_on):
+ continue
+ refund(ledger.bucket_key, ledger.budget)
+ ledger.refunded = True
+ DECISIONS_COUNTER.labels(endpoint=ledger.declaration.endpoint, tier=ledger.tier, outcome="refunded").inc()
+
+
+def apply_rate_limit_headers(request: Request, response) -> None:
+ """RateLimit-Limit/Remaining/Reset on every response that charged a bucket,
+ so a partner can pace itself instead of discovering the limit through 429s."""
+ ledgers = getattr(request, RateLimitLedger.LEDGERS_ATTR, None)
+ if not ledgers:
+ return
+ ledger = ledgers[-1]
+ remaining = ledger.decision.remaining + (1 if ledger.refunded else 0)
+ response["RateLimit-Limit"] = str(ledger.decision.limit)
+ response["RateLimit-Remaining"] = str(min(remaining, ledger.decision.limit))
+ response["RateLimit-Reset"] = str(ledger.decision.reset)
diff --git a/ee/api/agentic_provisioning/test/base.py b/ee/api/agentic_provisioning/test/base.py
index cb839bfb0aa1..87bf69ed1c9b 100644
--- a/ee/api/agentic_provisioning/test/base.py
+++ b/ee/api/agentic_provisioning/test/base.py
@@ -2,9 +2,11 @@ import json
import base64
import hashlib
import secrets
+import dataclasses
from urllib.parse import quote_plus
from posthog.test.base import APIBaseTest
+from unittest.mock import patch
from django.core.cache import cache
from django.utils import timezone
@@ -57,6 +59,21 @@ def provisioning_config(**overrides) -> dict:
return ProvisioningConfig(**{**TEST_PARTNER_PROVISIONING, **overrides}).model_dump(mode="json")
+def patched_budget(view_cls, method: str, endpoint: str, budget, *, multipliers=None):
+ """Shrink a handler's declared bucket budget for a test.
+
+ The declaration lives on the handler function, so tests patch it there
+ rather than replaying dozens of requests to exhaust a real budget. Pass
+ ``multipliers`` (e.g. FLAT_MULTIPLIERS) when the test partner's tier would
+ otherwise scale the patched budget back up.
+ """
+ budgets = getattr(view_cls, method)._provisioning_budgets
+ changes: dict = {"budget": budget}
+ if multipliers is not None:
+ changes["multipliers"] = multipliers
+ return patch.dict(budgets, {endpoint: dataclasses.replace(budgets[endpoint], **changes)})
+
+
class ProvisioningTestBase(APIBaseTest):
def setUp(self):
super().setUp()
diff --git a/ee/api/agentic_provisioning/test/test_github_grants.py b/ee/api/agentic_provisioning/test/test_github_grants.py
index 88a53c915aec..b6e4cefe6c47 100644
--- a/ee/api/agentic_provisioning/test/test_github_grants.py
+++ b/ee/api/agentic_provisioning/test/test_github_grants.py
@@ -7,10 +7,17 @@ from parameterized import parameterized
from posthog.models.integration import GitHubUserAuthorization
from posthog.models.oauth import OAuthApplication
+from posthog.token_bucket import Budget
from ee.api.agentic_provisioning import github_grants
from ee.api.agentic_provisioning.constants import GITHUB_GRANT_CACHE_PREFIX
-from ee.api.agentic_provisioning.test.base import TEST_PARTNER_CLIENT_SECRET, ProvisioningTestBase, provisioning_config
+from ee.api.agentic_provisioning.test.base import (
+ TEST_PARTNER_CLIENT_SECRET,
+ ProvisioningTestBase,
+ patched_budget,
+ provisioning_config,
+)
+from ee.api.agentic_provisioning.views.github_grants import GitHubGrantRepositoriesView
ACCESS_TOKEN = "gho_secret_user_token"
@@ -292,7 +299,7 @@ class TestGitHubGrants(ProvisioningTestBase):
return REPOSITORIES_RESPONSE
with (
- patch("ee.api.agentic_provisioning.throttling.GITHUB_GRANT_POLL_RATE_LIMIT_MAX", 1),
+ patched_budget(GitHubGrantRepositoriesView, "get", "grant_repo_polls", Budget(burst=1, per_hour=1)),
patch("ee.api.agentic_provisioning.github_grants.github_request", side_effect=fake_github_request),
):
first = self._get_grants(url)
@@ -312,7 +319,7 @@ class TestGitHubGrants(ProvisioningTestBase):
return REPOSITORIES_RESPONSE
with (
- patch("ee.api.agentic_provisioning.throttling.GITHUB_GRANT_POLL_RATE_LIMIT_MAX", 1),
+ patched_budget(GitHubGrantRepositoriesView, "get", "grant_repo_polls", Budget(burst=1, per_hour=1)),
patch("ee.api.agentic_provisioning.github_grants.github_request", side_effect=fake_github_request),
):
foreign = self._get_api(url, HTTP_AUTHORIZATION=self._basic_auth_header(other_partner))
diff --git a/ee/api/agentic_provisioning/test/test_partner_rate_limits.py b/ee/api/agentic_provisioning/test/test_partner_rate_limits.py
index 1cc43ebdecdc..f52aaacd54bb 100644
--- a/ee/api/agentic_provisioning/test/test_partner_rate_limits.py
+++ b/ee/api/agentic_provisioning/test/test_partner_rate_limits.py
@@ -1,6 +1,8 @@
from datetime import timedelta
from urllib.parse import urlencode
+from freezegun import freeze_time
+
from django.core.cache import cache
from django.utils import timezone
@@ -8,21 +10,42 @@ from parameterized import parameterized
from rest_framework.test import APIClient
from posthog.models.oauth import OAuthAccessToken, OAuthApplication, OAuthRefreshToken
-from posthog.models.oauth_provisioning import ProvisioningRateLimits
+from posthog.models.oauth_provisioning import PartnerTier
+from posthog.redis import TEST_clear_clients
+from posthog.token_bucket import Budget, TEST_reset_scripts
-from ee.api.agentic_provisioning.constants import AUTH_CODE_CACHE_PREFIX, PARTNER_RATE_LIMIT_DEFAULTS
+from ee.api.agentic_provisioning.constants import AUTH_CODE_CACHE_PREFIX
from ee.api.agentic_provisioning.exceptions import ProvisioningError
-from ee.api.agentic_provisioning.test.base import TEST_PARTNER_CLIENT_SECRET, ProvisioningTestBase, provisioning_config
-from ee.api.agentic_provisioning.throttling import enforce_partner_rate_limit
+from ee.api.agentic_provisioning.ratelimits import FLAT_MULTIPLIERS, charge_partner_by_name
+from ee.api.agentic_provisioning.test.base import (
+ TEST_PARTNER_CLIENT_SECRET,
+ ProvisioningTestBase,
+ patched_budget,
+ provisioning_config,
+)
+from ee.api.agentic_provisioning.views.resources import RotateCredentialsView
+from ee.api.agentic_provisioning.wizard import create_wizard_run
PARTNER_CLIENT_ID = "partner_rate_limit_test"
+# account_requests declares Budget(burst=5, per_hour=10); the tier grid scales it.
+ACCOUNT_REQUESTS_BURST_BY_TIER = {
+ PartnerTier.PUBLIC: 5,
+ PartnerTier.PUBLIC_ATTESTED: 10,
+ PartnerTier.JWKS: 25,
+ PartnerTier.JWKS_ATTESTED: 50,
+}
+
class TestPartnerRateLimits(ProvisioningTestBase):
def setUp(self):
super().setUp()
self.client = APIClient()
cache.clear()
+ TEST_clear_clients()
+ TEST_reset_scripts()
+ self.addCleanup(TEST_clear_clients)
+ self.addCleanup(TEST_reset_scripts)
OAuthApplication.objects.filter(client_id=PARTNER_CLIENT_ID).delete()
self.partner_app = OAuthApplication.objects.create(
@@ -47,82 +70,89 @@ class TestPartnerRateLimits(ProvisioningTestBase):
def _get_partner_bearer_token(self) -> str:
return self._request_bearer_token(partner=self.partner_app).json()["access_token"]
- # --- Unit tests for the rate limit helper ---
+ def _partner_at_tier(self, tier: PartnerTier) -> OAuthApplication:
+ confidential = tier in (PartnerTier.JWKS, PartnerTier.JWKS_ATTESTED)
+ attested = tier in (PartnerTier.PUBLIC_ATTESTED, PartnerTier.JWKS_ATTESTED)
+ return OAuthApplication.objects.create(
+ client_id=f"tier_partner_{tier}",
+ name=f"Tier partner {tier}",
+ client_secret=TEST_PARTNER_CLIENT_SECRET if confidential else "",
+ client_type=OAuthApplication.CLIENT_CONFIDENTIAL if confidential else OAuthApplication.CLIENT_PUBLIC,
+ authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,
+ redirect_uris="https://partner.example.com/callback",
+ algorithm="RS256",
+ is_provisioning_partner=True,
+ organization=self.organization if attested else None,
+ _provisioning_config=provisioning_config(active=True, can_create_accounts=True),
+ )
+
+ # --- Tier-scaled budgets ---
- @parameterized.expand(
- [
- ("account_requests",),
- ("token_exchanges",),
- ("resource_creates",),
- ]
- )
- def test_default_limit_applies_when_field_is_null(self, endpoint):
- assert getattr(self.partner_app.provisioning.rate_limits, endpoint) is None
- expected_limit = PARTNER_RATE_LIMIT_DEFAULTS[endpoint]
+ @parameterized.expand([(tier.value, tier) for tier in PartnerTier])
+ def test_tier_scales_the_budget(self, _name: str, tier: PartnerTier):
+ partner = self._partner_at_tier(tier)
+ assert partner.partner_tier == tier
+ burst = ACCOUNT_REQUESTS_BURST_BY_TIER[tier]
- for _ in range(expected_limit):
- enforce_partner_rate_limit(self.partner_app, endpoint)
+ with freeze_time("2026-01-01 00:00:00"):
+ for _ in range(burst):
+ charge_partner_by_name("account_requests", partner)
- with self.assertRaises(ProvisioningError) as ctx:
- enforce_partner_rate_limit(self.partner_app, endpoint)
+ with self.assertRaises(ProvisioningError) as ctx:
+ charge_partner_by_name("account_requests", partner)
assert ctx.exception.status == 429
+ assert ctx.exception.retry_after is not None
+
+ # --- Per-partner overrides ---
- def test_custom_override_respected(self):
+ def test_custom_override_replaces_the_computed_rate(self):
+ # Override 3/hour on a declared 5-burst/10-per-hour budget scales the burst
+ # to ceil(5 * 3/10) = 2, regardless of the partner's tier.
self.partner_app.update_provisioning_rate_limits(account_requests=3)
- for _ in range(3):
- enforce_partner_rate_limit(self.partner_app, "account_requests")
+ with freeze_time("2026-01-01 00:00:00"):
+ for _ in range(2):
+ charge_partner_by_name("account_requests", self.partner_app)
- with self.assertRaises(ProvisioningError) as ctx:
- enforce_partner_rate_limit(self.partner_app, "account_requests")
+ with self.assertRaises(ProvisioningError) as ctx:
+ charge_partner_by_name("account_requests", self.partner_app)
assert ctx.exception.status == 429
assert ctx.exception.retry_after is not None
def test_zero_override_disables_limiting(self):
self.partner_app.update_provisioning_rate_limits(account_requests=0)
- for _ in range(100):
- enforce_partner_rate_limit(self.partner_app, "account_requests")
+ with freeze_time("2026-01-01 00:00:00"):
+ for _ in range(100):
+ charge_partner_by_name("account_requests", self.partner_app)
def test_separate_buckets_per_endpoint(self):
- self.partner_app.update_provisioning_rate_limits(account_requests=2, resource_creates=2)
- for _ in range(2):
- enforce_partner_rate_limit(self.partner_app, "account_requests")
+ self.partner_app.update_provisioning_rate_limits(account_requests=1, resource_creates=1)
+ with freeze_time("2026-01-01 00:00:00"):
+ charge_partner_by_name("account_requests", self.partner_app)
- with self.assertRaises(ProvisioningError):
- enforce_partner_rate_limit(self.partner_app, "account_requests")
- enforce_partner_rate_limit(self.partner_app, "resource_creates")
+ with self.assertRaises(ProvisioningError):
+ charge_partner_by_name("account_requests", self.partner_app)
+ charge_partner_by_name("resource_creates", self.partner_app)
def test_separate_buckets_per_partner(self):
- other_partner = OAuthApplication.objects.create(
- client_id="other_partner",
- name="Other Partner",
- client_secret="",
- client_type=OAuthApplication.CLIENT_CONFIDENTIAL,
- authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,
- redirect_uris="https://other.example.com/callback",
- algorithm="RS256",
- is_provisioning_partner=True,
- _provisioning_config=provisioning_config(
- active=True, rate_limits=ProvisioningRateLimits(account_requests=2)
- ),
- )
-
- self.partner_app.update_provisioning_rate_limits(account_requests=2)
+ other_partner = self._partner_at_tier(PartnerTier.JWKS)
+ self.partner_app.update_provisioning_rate_limits(account_requests=1)
+ other_partner.update_provisioning_rate_limits(account_requests=1)
- for _ in range(2):
- enforce_partner_rate_limit(self.partner_app, "account_requests")
+ with freeze_time("2026-01-01 00:00:00"):
+ charge_partner_by_name("account_requests", self.partner_app)
- with self.assertRaises(ProvisioningError):
- enforce_partner_rate_limit(self.partner_app, "account_requests")
- enforce_partner_rate_limit(other_partner, "account_requests")
+ with self.assertRaises(ProvisioningError):
+ charge_partner_by_name("account_requests", self.partner_app)
+ charge_partner_by_name("account_requests", other_partner)
- # --- Integration: token exchange rate limiting ---
+ # --- Integration: token endpoint ---
def test_token_exchange_auth_code_rate_limited(self):
self.partner_app.update_provisioning_rate_limits(token_exchanges=1)
- # First exchange succeeds
+ # First exchange succeeds and spends the single-token bucket.
self._get_partner_bearer_token()
# Second exchange should be rate limited
@@ -141,15 +171,19 @@ class TestPartnerRateLimits(ProvisioningTestBase):
content_type="application/x-www-form-urlencoded",
)
assert res.status_code == 429
+ assert res["Retry-After"]
# Auth code is consumed before the rate-limit check so a leaked code
# can't be replayed to exhaust the bucket
assert cache.get(f"{AUTH_CODE_CACHE_PREFIX}{code}") is None
- def test_token_exchange_refresh_rate_limited(self):
+ def test_refreshes_do_not_spend_the_exchange_bucket(self):
+ # The split is what lets a partner keep more live tokens than its
+ # hourly authorization budget: an exhausted exchange bucket must not
+ # block refresh rotations.
self.partner_app.update_provisioning_rate_limits(token_exchanges=1)
+ self._get_partner_bearer_token() # exhausts token_exchanges
- # Create access + refresh token for the partner
access_token = OAuthAccessToken.objects.create(
application=self.partner_app,
token="test_access_token",
@@ -166,7 +200,6 @@ class TestPartnerRateLimits(ProvisioningTestBase):
scoped_teams=[self.team.id],
)
- # First refresh succeeds
body = urlencode(
{
"grant_type": "refresh_token",
@@ -181,53 +214,87 @@ class TestPartnerRateLimits(ProvisioningTestBase):
)
assert res.status_code == 200
- # Create a second refresh token
- new_access = OAuthAccessToken.objects.create(
- application=self.partner_app,
- token="test_access_token_2",
- user=self.user,
- expires=timezone.now() + timedelta(hours=1),
- scope="query:read",
- scoped_teams=[self.team.id],
- )
- OAuthRefreshToken.objects.create(
- application=self.partner_app,
- token="test_refresh_token_2",
- user=self.user,
- access_token=new_access,
- scoped_teams=[self.team.id],
- )
-
- body = urlencode(
- {
- "grant_type": "refresh_token",
- "refresh_token": "test_refresh_token_2",
- **self._client_credentials(self.partner_app),
- }
- ).encode()
- res = self.client.post(
- "/api/agentic/oauth/token",
- data=body,
- content_type="application/x-www-form-urlencoded",
- )
- assert res.status_code == 429
-
- # --- Integration: resource creation rate limiting ---
-
- def test_resource_create_rate_limited(self):
- self.partner_app.update_provisioning_rate_limits(resource_creates=1)
+ # --- Integration: resource endpoints ---
+ def test_resource_create_rate_limited_with_headers(self):
token = self._get_partner_bearer_token()
-
- # Reset the token_exchanges counter so it doesn't interfere
- cache.clear()
- # Re-set the resource_creates limit counter fresh
- # (cache.clear wiped it, but we need 1 request to fill it)
+ # Override 1/hour -> Budget(burst=1, per_hour=1), tier-independent.
+ self.partner_app.update_provisioning_rate_limits(resource_creates=1)
res = self._post_with_bearer("/api/agentic/provisioning/resources", {}, token=token)
assert res.status_code == 200
+ assert res["RateLimit-Limit"] == "1"
+ assert res["RateLimit-Remaining"] == "0"
res = self._post_with_bearer("/api/agentic/provisioning/resources", {}, token=token)
assert res.status_code == 429
assert res.json()["status"] == "error"
assert res.json()["error"]["code"] == "rate_limited"
+ assert res["Retry-After"]
+ assert res["RateLimit-Remaining"] == "0"
+
+ def test_rejected_request_is_refunded(self):
+ # A request that provably did no work (validation failure) costs no
+ # quota: with a burst of 1, a 400 followed by a valid request must not
+ # 429 the valid one.
+ token = self._get_partner_bearer_token()
+
+ with patched_budget(
+ RotateCredentialsView,
+ "post",
+ "credential_rotations",
+ Budget(burst=1, per_hour=1),
+ multipliers=FLAT_MULTIPLIERS,
+ ):
+ res = self._post_with_bearer(
+ f"/api/agentic/provisioning/resources/{self.team.id}/rotate_credentials",
+ {"label_prefix": "x" * 100},
+ token=token,
+ )
+ assert res.status_code == 400
+
+ res = self._post_with_bearer(
+ f"/api/agentic/provisioning/resources/{self.team.id}/rotate_credentials",
+ {},
+ token=token,
+ )
+ assert res.status_code == 200
+
+ # --- Tier gating ---
+
+ def test_blocked_tier_cannot_use_deep_links(self):
+ public_partner = self._partner_at_tier(PartnerTier.PUBLIC)
+ with self.assertRaises(ProvisioningError) as ctx:
+ charge_partner_by_name("deep_links", public_partner)
+ assert ctx.exception.status == 403
+
+ # The JWKS tiers keep their budget.
+ charge_partner_by_name("deep_links", self._partner_at_tier(PartnerTier.JWKS))
+
+ def test_failed_repository_probe_keeps_the_charge(self):
+ # The repository check is an authenticated GitHub call, so a rejected run has
+ # already done outbound work. With a budget of 1, a second attempt must be
+ # rate limited rather than probing GitHub again for free.
+ self.partner_app.update_provisioning(can_start_wizard_runs=True)
+ self.partner_app.update_provisioning_rate_limits(wizard_runs=1)
+
+ with self.settings(WIZARD_CLOUD_RUN_OAUTH_CLIENT_ID="wizard-client"):
+ with self.assertRaises(ProvisioningError) as ctx:
+ create_wizard_run(
+ partner=self.partner_app,
+ user_id=self.user.id,
+ team=self.team,
+ repository="acme/widgets",
+ branch=None,
+ )
+ assert ctx.exception.code == "github_integration_required"
+
+ with self.assertRaises(ProvisioningError) as ctx:
+ create_wizard_run(
+ partner=self.partner_app,
+ user_id=self.user.id,
+ team=self.team,
+ repository="acme/other",
+ branch=None,
+ )
+ assert ctx.exception.code == "rate_limited"
diff --git a/ee/api/agentic_provisioning/throttling.py b/ee/api/agentic_provisioning/throttling.py
index 69884288a8ad..d08e5aa7bdbc 100644
--- a/ee/api/agentic_provisioning/throttling.py
+++ b/ee/api/agentic_provisioning/throttling.py
@@ -1,26 +1,18 @@
-"""Rate limiting for the agentic provisioning API.
-
-Fixed-window cache counters over one set of keys, reachable two ways:
-
-- :class:`~rest_framework.throttling.BaseThrottle` subclasses, declared in
- ``partner_throttle_classes`` on the view, for limits whose key DRF already
- has when it calls ``check_throttles``: the partner on ``request.auth``, a
- grant id in the URL, a client_id in the body. The base view runs these on
- top of ``DEFAULT_THROTTLE_CLASSES`` and renders rejections in the view's
- wire envelope rather than DRF's ``{"detail": ...}``.
-- ``enforce_*`` helpers, for limits that can't be spent as early as
- ``check_throttles`` runs: the token endpoint learns the partner only by
- decoding an auth code or refresh token; account_requests and github_grants
- must clear the partner's capability *before* charging quota, so a partner
- that is refused outright keeps its budget; and the wizard budget is shared
- with the bundled account_requests wizard block, which runs outside any view
- dispatch.
-- :class:`RegionProxyThrottle`, checked by the region proxy in ``dispatch``,
- before DRF has authenticated the caller and before either of the above can
- run at all.
-
-A caller can burst up to 2x a limit across a window boundary (``limit`` at
-:59:59 plus ``limit`` at :00:00); switch to a sliding window if that matters.
+"""Rate limiting for the agentic provisioning API that is NOT per partner.
+
+The per-partner budgets live in :mod:`ee.api.agentic_provisioning.ratelimits`
+(tier-scaled token buckets declared on the handlers). What stays here are the
+limits keyed on something other than a partner:
+
+- :class:`ClientRegistrationThrottle` and :class:`CIMDRegistrationThrottle`,
+ per client_id / IP / domain, screening callers that are not partners yet.
+- ``enforce_wizard_run_user_rate_limit``, per end user, shared between the
+ granular wizard_runs action and the bundled account_requests wizard block.
+- :class:`RegionProxyThrottle`, per IP, checked by the region proxy in
+ ``dispatch`` before DRF has authenticated the caller.
+
+These are fixed-window cache counters: a caller can burst up to 2x a limit
+across a window boundary (``limit`` at :59:59 plus ``limit`` at :00:00).
"""
from __future__ import annotations
@@ -41,8 +33,7 @@ from rest_framework.throttling import BaseThrottle
from rest_framework.views import APIView
from posthog.api.oauth import cimd
-from posthog.dataclasses import frozen
-from posthog.models.oauth import OAuthAccessToken, OAuthApplication
+from posthog.models.oauth import OAuthApplication
from posthog.rate_limit import IPThrottle
from ee.api.agentic_provisioning.analytics import capture_provisioning_event
@@ -54,28 +45,15 @@ from ee.api.agentic_provisioning.constants import (
CLIENT_REGISTRATION_RATE_LIMIT_MAX,
CLIENT_REGISTRATION_RATE_LIMIT_PREFIX,
CLIENT_REGISTRATION_RATE_LIMIT_WINDOW_SECONDS,
- GITHUB_GRANT_POLL_RATE_LIMIT_MAX,
- GITHUB_GRANT_POLL_RATE_LIMIT_PREFIX,
- GITHUB_GRANT_POLL_RATE_LIMIT_WINDOW_SECONDS,
- PARTNER_RATE_LIMIT_DEFAULTS,
- PARTNER_RATE_LIMIT_EVENT_NAMES,
- PARTNER_RATE_LIMIT_PREFIX,
- PARTNER_RATE_LIMIT_WINDOW_SECONDS,
REGION_PROXY_RATE_LIMIT,
WIZARD_RUN_USER_RATE_LIMIT_PREFIX,
WIZARD_RUN_USER_RATE_LIMITS,
)
-from ee.api.agentic_provisioning.exceptions import Envelope, ProvisioningError
+from ee.api.agentic_provisioning.exceptions import ProvisioningError
logger = structlog.get_logger(__name__)
-@frozen
-class RateWindowUsage:
- count: int
- limit: int
-
-
def _fixed_window_count(cache_key: str, window_seconds: int) -> int:
try:
cache.add(cache_key, 0, timeout=window_seconds)
@@ -103,132 +81,6 @@ def _window_retry_after(window_seconds: int) -> int:
return window_seconds - (int(time.time()) % window_seconds)
-def _count_partner_request(partner: OAuthApplication, endpoint: str) -> RateWindowUsage | None:
- """Count one request against the partner's per-endpoint fixed window.
-
- Returns the window's usage, or None when rate limiting is disabled for the
- endpoint (model override of 0). The model's override field takes precedence
- over the conservative default; the window is keyed on partner id +
- window-of-epoch.
- """
- if endpoint not in PARTNER_RATE_LIMIT_DEFAULTS:
- raise ValueError(f"Unknown rate limit endpoint: {endpoint}")
-
- override = getattr(partner.provisioning.rate_limits, endpoint, None)
- limit = override if override is not None else PARTNER_RATE_LIMIT_DEFAULTS[endpoint]
-
- if limit <= 0:
- return None
-
- window_index = int(time.time()) // PARTNER_RATE_LIMIT_WINDOW_SECONDS
- cache_key = f"{PARTNER_RATE_LIMIT_PREFIX}{endpoint}:{partner.id}:{window_index}"
- return RateWindowUsage(count=_fixed_window_count(cache_key, PARTNER_RATE_LIMIT_WINDOW_SECONDS), limit=limit)
-
-
-def _capture_partner_rate_limited(partner: OAuthApplication, endpoint: str, limit: int, count: int) -> None:
- capture_provisioning_event(
- PARTNER_RATE_LIMIT_EVENT_NAMES[endpoint], "rate_limited", partner=partner, limit=limit, count=count
- )
-
-
-def enforce_partner_rate_limit(
- partner: OAuthApplication,
- endpoint: str,
- *,
- message: str | None = None,
- envelope: Envelope | None = None,
-) -> None:
- """Mid-flow form of :class:`PartnerRateThrottle`, sharing its counters, for
- flows that identify the partner only after dispatch (token exchange,
- account_requests, wizard runs).
-
- Raises a ``rate_limited`` :class:`ProvisioningError` when the limit is exceeded.
- """
- usage = _count_partner_request(partner, endpoint)
- if usage is None:
- return
-
- if usage.count > usage.limit:
- _capture_partner_rate_limited(partner, endpoint, usage.limit, usage.count)
- raise ProvisioningError(
- "rate_limited",
- message or f"Rate limit exceeded for this partner ({endpoint}). Try again later.",
- status=429,
- envelope=envelope or "typed",
- retry_after=_window_retry_after(PARTNER_RATE_LIMIT_WINDOW_SECONDS),
- )
-
-
-class PartnerRateThrottle(BaseThrottle):
- """Per-partner fixed-window limit as a DRF throttle, for views whose
- partner is on ``request.auth`` after authentication."""
-
- endpoint: ClassVar[str]
- error_message: ClassVar[str]
-
- def get_partner(self, request: Request) -> OAuthApplication | None:
- auth = request.auth
- if isinstance(auth, OAuthAccessToken):
- return auth.application
- if isinstance(auth, OAuthApplication):
- return auth
- return None
-
- def allow_request(self, request: Request, view: APIView) -> bool:
- partner = self.get_partner(request)
- if partner is None:
- return True
- usage = _count_partner_request(partner, self.endpoint)
- if usage is None:
- return True
- if usage.count > usage.limit:
- _capture_partner_rate_limited(partner, self.endpoint, usage.limit, usage.count)
- return False
- return True
-
- def wait(self) -> int:
- return _window_retry_after(PARTNER_RATE_LIMIT_WINDOW_SECONDS)
-
-
-class ResourceCreatesThrottle(PartnerRateThrottle):
- endpoint = "resource_creates"
- error_message = "Rate limit exceeded for this partner. Try again later."
-
- def get_partner(self, request: Request) -> OAuthApplication | None:
- # Plain OAuth apps whose tokens reach this endpoint are not partners and carry no
- # partner quota. Keyed on carrying provisioning config rather than on a capability or
- # on is_provisioning_partner, so neither revoking a capability nor disabling the
- # partner outright also un-throttles its outstanding tokens.
- partner = super().get_partner(request)
- if partner is None or not partner.carries_provisioning_config:
- return None
- return partner
-
-
-class GrantPollThrottle(BaseThrottle):
- """Cap repository-listing polls per grant while the visitor installs the GitHub App."""
-
- error_message: ClassVar[str] = "Too many repository listing requests for this grant"
-
- def allow_request(self, request: Request, view: APIView) -> bool:
- grant_id = getattr(view, "kwargs", {}).get("grant_id", "")
- if not grant_id:
- return True
- # DRF checks throttles before the handler loads the grant and rejects a
- # partner mismatch, so the key carries the caller's partner too. Without it a
- # partner that learns another partner's grant id could spend the owner's
- # budget on it. A grant only ever belongs to one partner, so scoping the key
- # this way does not split any legitimate caller's quota.
- partner_id = getattr(request.auth, "id", "unauthenticated")
- window_index = int(time.time()) // GITHUB_GRANT_POLL_RATE_LIMIT_WINDOW_SECONDS
- key = f"{GITHUB_GRANT_POLL_RATE_LIMIT_PREFIX}{partner_id}:{grant_id}:{window_index}"
- count = _fixed_window_count(key, GITHUB_GRANT_POLL_RATE_LIMIT_WINDOW_SECONDS)
- return count <= GITHUB_GRANT_POLL_RATE_LIMIT_MAX
-
- def wait(self) -> int:
- return _window_retry_after(GITHUB_GRANT_POLL_RATE_LIMIT_WINDOW_SECONDS)
-
-
class RegionProxyThrottle(IPThrottle):
"""Per-IP cap on forwarding a request to the other region.
@@ -261,6 +113,9 @@ def enforce_wizard_run_user_rate_limit(user_id: int, resource_id: str = "") -> N
key = f"{WIZARD_RUN_USER_RATE_LIMIT_PREFIX}{label}:{user_id}:{window_index}"
count = _fixed_window_count(key, window_seconds)
if count > limit:
+ capture_provisioning_event(
+ "rate_limited", "rate_limited", endpoint="wizard_runs_user", limit=limit, window=label
+ )
raise ProvisioningError(
"rate_limited",
"Too many wizard runs for this user. Try later.",
@@ -296,6 +151,7 @@ class ClientRegistrationThrottle(BaseThrottle):
window_index = int(time.time()) // CLIENT_REGISTRATION_RATE_LIMIT_WINDOW_SECONDS
key = f"{CLIENT_REGISTRATION_RATE_LIMIT_PREFIX}{sha256(client_id.encode()).hexdigest()}:{window_index}"
if _fixed_window_count(key, CLIENT_REGISTRATION_RATE_LIMIT_WINDOW_SECONDS) > CLIENT_REGISTRATION_RATE_LIMIT_MAX:
+ capture_provisioning_event("rate_limited", "rate_limited", endpoint="client_registration")
return False
ident = self.get_ident(request)
@@ -305,6 +161,7 @@ class ClientRegistrationThrottle(BaseThrottle):
if _fixed_window_count(ip_key, CLIENT_REGISTRATION_RATE_LIMIT_WINDOW_SECONDS) > (
CLIENT_REGISTRATION_IP_RATE_LIMIT_MAX
):
+ capture_provisioning_event("rate_limited", "rate_limited", endpoint="client_registration_ip")
self.error_message = "Too many registration checks from this address. Try again later."
return False
return True
diff --git a/ee/api/agentic_provisioning/views/account_requests.py b/ee/api/agentic_provisioning/views/account_requests.py
index 2b950135da24..3db99f574a2e 100644
--- a/ee/api/agentic_provisioning/views/account_requests.py
+++ b/ee/api/agentic_provisioning/views/account_requests.py
@@ -22,8 +22,9 @@ from ee.api.agentic_provisioning.analytics import capture_provisioning_event
from ee.api.agentic_provisioning.authentication import CLIENT_NOT_REGISTERED_MESSAGE, ProvisioningAuthentication
from ee.api.agentic_provisioning.constants import CODE_CHALLENGE_RE
from ee.api.agentic_provisioning.exceptions import ProvisioningError
+from ee.api.agentic_provisioning.ratelimits import Budget, rate_limited
from ee.api.agentic_provisioning.serializers import AccountRequestSerializer
-from ee.api.agentic_provisioning.throttling import CIMDRegistrationThrottle, enforce_partner_rate_limit
+from ee.api.agentic_provisioning.throttling import CIMDRegistrationThrottle
from ee.api.agentic_provisioning.views.base import ProvisioningAPIView
@@ -34,6 +35,14 @@ class AccountRequestsView(ProvisioningAPIView):
# region proxy and the request-id echo both need the parsed body alongside the partner.
authenticates_in_handler = True
+ # charge="manual": the partner is only known mid-handler, and a partner refused
+ # the capability outright must keep its budget. The tier grid puts this at
+ # 10/20/50/100 per hour.
+ @rate_limited(
+ "account_requests",
+ budget=Budget(burst=5, per_hour=10),
+ charge="manual",
+ )
def post(self, request: Request) -> Response:
# --- Identify partner ---
auth = ProvisioningAuthentication()
@@ -68,7 +77,7 @@ class AccountRequestsView(ProvisioningAPIView):
capture_provisioning_event("account_request", "error", error_code="account_creation_disabled")
raise ProvisioningError("forbidden", "Account creation is not enabled for this partner", status=403)
- enforce_partner_rate_limit(partner, "account_requests")
+ self.charge_rate_limit(request, partner)
# PKCE: capture code_challenge for later verification
code_challenge = data["code_challenge"]
diff --git a/ee/api/agentic_provisioning/views/base.py b/ee/api/agentic_provisioning/views/base.py
index 649ad18ce8d2..419bfa9bd22d 100644
--- a/ee/api/agentic_provisioning/views/base.py
+++ b/ee/api/agentic_provisioning/views/base.py
@@ -11,6 +11,8 @@ from __future__ import annotations
from typing import Any, ClassVar
+from django.core.exceptions import ImproperlyConfigured
+
from rest_framework import serializers
from rest_framework.authentication import BaseAuthentication
from rest_framework.request import Request
@@ -18,11 +20,18 @@ from rest_framework.response import Response
from rest_framework.throttling import BaseThrottle
from rest_framework.views import APIView
-from posthog.models.oauth import OAuthAccessToken
+from posthog.models.oauth import OAuthAccessToken, OAuthApplication
from posthog.models.team.team import Team
from ee.api.agentic_provisioning.authentication import GitHubGrantsAuthentication, ProvisioningBearerAuthentication
from ee.api.agentic_provisioning.exceptions import Envelope, ProvisioningError, render_provisioning_error
+from ee.api.agentic_provisioning.ratelimits import (
+ BudgetDeclaration,
+ apply_rate_limit_headers,
+ charge_partner,
+ partner_for_rate_limiting,
+ refund_no_work,
+)
from ee.api.agentic_provisioning.region_proxy import RegionProxyMixin
from ee.api.agentic_provisioning.serializers import first_error_message
@@ -98,11 +107,61 @@ class ProvisioningAPIView(RegionProxyMixin, APIView):
retry_after=int(wait) if wait else None,
)
+ # Partner bucket charges declared with @rate_limited(charge="auto") on the
+ # handler. After the throttles above, so a request they refuse spends nothing.
+ for declaration in self._budget_declarations(request).values():
+ if declaration.charge != "auto":
+ continue
+ partner = partner_for_rate_limiting(request)
+ if partner is None:
+ continue
+ key_suffix = declaration.key(request, self) if declaration.key else ""
+ charge_partner(
+ declaration,
+ partner,
+ request=request,
+ key_suffix=key_suffix,
+ resource_id=str(self.kwargs.get("resource_id", "")),
+ )
+
+ def _budget_declarations(self, request: Request) -> dict[str, BudgetDeclaration]:
+ handler = getattr(self, (request.method or "").lower(), None)
+ return getattr(handler, "_provisioning_budgets", {})
+
+ def charge_rate_limit(
+ self, request: Request, partner: OAuthApplication, *, endpoint: str | None = None, resource_id: str = ""
+ ) -> None:
+ """Charge a ``charge="manual"`` budget declared on the current handler.
+
+ ``endpoint`` is only needed when the handler declares more than one
+ budget; the declaration itself stays on the decorator, so the policy is
+ stated exactly once.
+ """
+ declarations = self._budget_declarations(request)
+ if endpoint is None:
+ if len(declarations) != 1:
+ raise ImproperlyConfigured(
+ f"{type(self).__name__} declares {len(declarations)} budgets; pass endpoint= to charge_rate_limit"
+ )
+ declaration = next(iter(declarations.values()))
+ else:
+ declaration = declarations[endpoint]
+ charge_partner(declaration, partner, request=request, resource_id=resource_id)
+
def handle_exception(self, exc: Exception) -> Response:
if isinstance(exc, ProvisioningError):
+ # A rejection that provably did no work costs no quota. The one
+ # exception class carries the code, so the refund decision needs no
+ # per-endpoint choreography in the handlers.
+ refund_no_work(self.request, exc.code)
return render_provisioning_error(exc, self.error_envelope)
return super().handle_exception(exc)
+ def finalize_response(self, request: Request, response: Response, *args: Any, **kwargs: Any) -> Response:
+ response = super().finalize_response(request, response, *args, **kwargs)
+ apply_rate_limit_headers(request, response)
+ return response
+
def validated_body(
self,
serializer_class: type[serializers.Serializer],
diff --git a/ee/api/agentic_provisioning/views/deep_links.py b/ee/api/agentic_provisioning/views/deep_links.py
index 1289ecb31b77..f9ed17c1470a 100644
--- a/ee/api/agentic_provisioning/views/deep_links.py
+++ b/ee/api/agentic_provisioning/views/deep_links.py
@@ -21,6 +21,7 @@ from rest_framework.response import Response
from posthog.api.email_verification import EmailVerifier
from posthog.exceptions_capture import capture_exception
from posthog.models.oauth import OAuthAccessToken
+from posthog.models.oauth_provisioning import PartnerTier
from posthog.models.team.team import Team
from posthog.models.user import User
@@ -32,6 +33,7 @@ from ee.api.agentic_provisioning.constants import (
DEEP_LINK_TTL_SECONDS,
)
from ee.api.agentic_provisioning.exceptions import ProvisioningError
+from ee.api.agentic_provisioning.ratelimits import BLOCKED, rate_limited
from ee.api.agentic_provisioning.regions import current_region_host
from ee.api.agentic_provisioning.serializers import DeepLinkSerializer
from ee.api.agentic_provisioning.views.base import BearerResourceAPIView
@@ -54,6 +56,14 @@ def is_safe_deep_link_path(path: object) -> bool:
class DeepLinksView(BearerResourceAPIView):
+ # A deep link mints a full web session, so on top of the admin-granted
+ # capability the public tiers get no budget at all: a client identified only
+ # by a client_id anyone can send has no business minting sessions. An
+ # explicit per-partner override outranks BLOCKED if one is ever needed.
+ @rate_limited(
+ "deep_links",
+ multipliers={PartnerTier.PUBLIC: BLOCKED, PartnerTier.PUBLIC_ATTESTED: BLOCKED},
+ )
def post(self, request: Request) -> Response:
access_token = cast(OAuthAccessToken, request.auth)
diff --git a/ee/api/agentic_provisioning/views/github_grants.py b/ee/api/agentic_provisioning/views/github_grants.py
index a71c70e03c2d..ad98a1976f4d 100644
--- a/ee/api/agentic_provisioning/views/github_grants.py
+++ b/ee/api/agentic_provisioning/views/github_grants.py
@@ -3,10 +3,9 @@ OAuth code, we exchange and hold the user tokens server-side, and the partner
only ever sees an opaque grant_id. No region proxy: grants are region-local
(the partner must call the region that minted the grant).
-Grant creation enforces its partner quota inline rather than through
-``partner_throttle_classes``, so the capability check runs first: a partner
-without ``can_create_accounts`` is refused for free instead of
-burning its hourly grant budget on requests it can never complete.
+Grant creation is charged automatically but the capability refusal is in the
+budget's refund set, so a partner without ``can_create_accounts`` still spends
+nothing on requests it can never complete.
"""
from __future__ import annotations
@@ -23,12 +22,13 @@ from posthog.models.oauth import OAuthApplication
from ee.api.agentic_provisioning import github_grants
from ee.api.agentic_provisioning.analytics import capture_provisioning_event
from ee.api.agentic_provisioning.exceptions import ProvisioningError
+from ee.api.agentic_provisioning.ratelimits import FLAT_MULTIPLIERS, rate_limited
from ee.api.agentic_provisioning.serializers import GitHubGrantCreateSerializer
-from ee.api.agentic_provisioning.throttling import GrantPollThrottle, enforce_partner_rate_limit
from ee.api.agentic_provisioning.views.base import GitHubGrantsAPIView
class GitHubGrantsCreateView(GitHubGrantsAPIView):
+ @rate_limited("github_grants")
def post(self, request: Request) -> Response:
partner = cast(OAuthApplication, request.auth)
@@ -36,8 +36,6 @@ class GitHubGrantsCreateView(GitHubGrantsAPIView):
capture_provisioning_event("github_grant", "error", partner=partner, error_code="account_creation_disabled")
raise ProvisioningError("forbidden", "Account creation is not enabled for this partner", status=403)
- enforce_partner_rate_limit(partner, "github_grants")
-
data = self.validated_body(GitHubGrantCreateSerializer, request, context={"partner": partner})
code = data["code"]
redirect_uri = data["redirect_uri"]
@@ -79,9 +77,13 @@ class GitHubGrantsCreateView(GitHubGrantsAPIView):
class GitHubGrantRepositoriesView(GitHubGrantsAPIView):
# Keyed per calling partner and grant id, so polls against an id the caller does
- # not own can only exhaust the caller's own budget.
- partner_throttle_classes = [GrantPollThrottle]
-
+ # not own can only exhaust the caller's own budget. Flat multipliers: how fast a
+ # visitor's repo picker polls has nothing to do with the partner's trust tier.
+ @rate_limited(
+ "grant_repo_polls",
+ multipliers=FLAT_MULTIPLIERS,
+ key=lambda request, view: str(getattr(view, "kwargs", {}).get("grant_id", "")),
+ )
def get(self, request: Request, grant_id: str) -> Response:
partner = cast(OAuthApplication, request.auth)
diff --git a/ee/api/agentic_provisioning/views/oauth_token.py b/ee/api/agentic_provisioning/views/oauth_token.py
index 48a4f86dbed0..3434ab2501c2 100644
--- a/ee/api/agentic_provisioning/views/oauth_token.py
+++ b/ee/api/agentic_provisioning/views/oauth_token.py
@@ -35,7 +35,7 @@ from ee.api.agentic_provisioning.constants import (
PARTNER_TOKEN_EXPIRY_SECONDS,
)
from ee.api.agentic_provisioning.exceptions import ProvisioningError
-from ee.api.agentic_provisioning.throttling import enforce_partner_rate_limit
+from ee.api.agentic_provisioning.ratelimits import Budget, rate_limited
from ee.api.agentic_provisioning.tokens import (
compute_partner_scoped_teams,
get_available_teams_for_user,
@@ -109,6 +109,12 @@ class OAuthTokenView(ProvisioningAPIView):
# authentication happens in _require_client_authentication once the grant is known.
authenticates_in_handler = True
+ # Two buckets, charged manually once the grant names the partner. Refreshes are
+ # split from new authorizations because partner tokens live one hour: charging
+ # rotations to the exchange budget capped a partner's live end users at roughly
+ # that budget. Both keep the typed envelope, their historical wire shape here.
+ @rate_limited("token_exchanges", budget=Budget(burst=10, per_hour=20), charge="manual", envelope="typed")
+ @rate_limited("token_refreshes", charge="manual", envelope="typed")
def post(self, request: Request) -> Response:
grant_type = request.data.get("grant_type", "")
@@ -175,7 +181,7 @@ class OAuthTokenView(ProvisioningAPIView):
# re-initiate the OAuth flow if rate-limited.
cache.delete(cache_key)
- enforce_partner_rate_limit(oauth_app, "token_exchanges")
+ self.charge_rate_limit(request, oauth_app, endpoint="token_exchanges")
user_id = code_data["user_id"]
team_id = code_data["team_id"]
@@ -371,7 +377,7 @@ class OAuthTokenView(ProvisioningAPIView):
# Not is_provisioning_partner: an admin clearing that flag to disable a partner
# leaves its outstanding refresh tokens working, and they must stay throttled.
if oauth_app and oauth_app.carries_provisioning_config:
- enforce_partner_rate_limit(oauth_app, "token_exchanges")
+ self.charge_rate_limit(request, oauth_app, endpoint="token_refreshes")
old_access = old_refresh.access_token
old_refresh.access_token = None
diff --git a/ee/api/agentic_provisioning/views/resources.py b/ee/api/agentic_provisioning/views/resources.py
index e3d5ff61180f..c8cf7619956c 100644
--- a/ee/api/agentic_provisioning/views/resources.py
+++ b/ee/api/agentic_provisioning/views/resources.py
@@ -21,6 +21,7 @@ from posthog.models.user import User
from ee.api.agentic_provisioning.analytics import capture_provisioning_event
from ee.api.agentic_provisioning.credentials import maybe_create_provisioned_pat
from ee.api.agentic_provisioning.exceptions import ProvisioningError
+from ee.api.agentic_provisioning.ratelimits import Budget, rate_limited
from ee.api.agentic_provisioning.regions import current_region_host
from ee.api.agentic_provisioning.serializers import (
GitHubIntegrationSerializer,
@@ -29,7 +30,6 @@ from ee.api.agentic_provisioning.serializers import (
WizardRunSerializer,
)
from ee.api.agentic_provisioning.teams import ProjectIdCollisionError, resolve_or_create_project_team
-from ee.api.agentic_provisioning.throttling import ResourceCreatesThrottle
from ee.api.agentic_provisioning.tokens import remove_team_from_token_scopes
from ee.api.agentic_provisioning.views.base import BearerResourceAPIView
from ee.api.agentic_provisioning.wizard import create_wizard_run, link_github_grant_to_team
@@ -67,8 +67,7 @@ def _access_configuration_response(
class ResourcesCreateView(BearerResourceAPIView):
- partner_throttle_classes = [ResourceCreatesThrottle]
-
+ @rate_limited("resource_creates", budget=Budget(burst=10, per_hour=30))
def post(self, request: Request) -> Response:
user = cast(User, request.user)
access_token = cast(OAuthAccessToken, request.auth)
@@ -133,6 +132,7 @@ class ResourcesCreateView(BearerResourceAPIView):
class ResourceDetailView(BearerResourceAPIView):
+ @rate_limited("resource_reads")
def get(self, request: Request, resource_id: str) -> Response:
user = cast(User, request.user)
access_token = cast(OAuthAccessToken, request.auth)
@@ -150,6 +150,7 @@ class ResourceDetailView(BearerResourceAPIView):
class RotateCredentialsView(BearerResourceAPIView):
+ @rate_limited("credential_rotations")
def post(self, request: Request, resource_id: str) -> Response:
user = cast(User, request.user)
access_token = cast(OAuthAccessToken, request.auth)
@@ -188,6 +189,7 @@ class ResourceRemoveView(BearerResourceAPIView):
scope and clears provisioning metadata. Preserves the underlying team and
user data so the customer can still access PostHog directly."""
+ @rate_limited("resource_removals")
def post(self, request: Request, resource_id: str) -> Response:
access_token = cast(OAuthAccessToken, request.auth)
@@ -215,6 +217,7 @@ class ResourceRemoveView(BearerResourceAPIView):
class GitHubIntegrationView(BearerResourceAPIView):
"""Link a GitHub installation to the team from a stored grant."""
+ @rate_limited("github_integrations")
def post(self, request: Request, resource_id: str) -> Response:
user = cast(User, request.user)
access_token = cast(OAuthAccessToken, request.auth)
@@ -256,6 +259,10 @@ class WizardRunsView(BearerResourceAPIView):
this endpoint and the account-request wizard block alike.
"""
+ # charge="manual": the charge lives inside create_wizard_run, which the bundled
+ # account-request wizard block also calls, so retries can't double-spend and the
+ # capability check runs before any quota is spent on either path.
+ @rate_limited("wizard_runs", charge="manual")
def post(self, request: Request, resource_id: str) -> Response:
user = cast(User, request.user)
access_token = cast(OAuthAccessToken, request.auth)
diff --git a/ee/api/agentic_provisioning/wizard.py b/ee/api/agentic_provisioning/wizard.py
index b720e154c4f4..b6d588ccb9d2 100644
--- a/ee/api/agentic_provisioning/wizard.py
+++ b/ee/api/agentic_provisioning/wizard.py
@@ -20,7 +20,8 @@ from products.tasks.backend.facade import api as tasks_facade
from ee.api.agentic_provisioning import github_grants
from ee.api.agentic_provisioning.analytics import capture_provisioning_event
from ee.api.agentic_provisioning.exceptions import ProvisioningError
-from ee.api.agentic_provisioning.throttling import enforce_partner_rate_limit, enforce_wizard_run_user_rate_limit
+from ee.api.agentic_provisioning.ratelimits import charge_partner_by_name
+from ee.api.agentic_provisioning.throttling import enforce_wizard_run_user_rate_limit
def _drf_validation_error_code(exc: DRFValidationError) -> str | None:
@@ -157,7 +158,13 @@ def create_wizard_run(
)
enforce_wizard_run_user_rate_limit(user_id, resource_id=str(team.id))
- enforce_partner_rate_limit(partner, "wizard_runs")
+ # By registry name because the budget is declared on WizardRunsView, and this
+ # function is also reached by the bundled account-request wizard block, which
+ # runs outside any view dispatch.
+ # Not refunded past this point: the repository check below is an authenticated
+ # GitHub call, so a partner cycling inaccessible repository names would otherwise
+ # generate unbounded egress for free.
+ charge_partner_by_name("wizard_runs", partner, resource_id=str(team.id))
# Verifying the grant user owns the installation doesn't prove the installation can
# reach the requested repo — a valid grant for one installation could otherwise report
diff --git a/posthog/models/oauth.py b/posthog/models/oauth.py
index 3305dfe22d2d..a689f375bcda 100644
--- a/posthog/models/oauth.py
+++ b/posthog/models/oauth.py
@@ -32,7 +32,7 @@ if TYPE_CHECKING:
# This model loads at django.setup() in every process; the pydantic schema is
# runtime-imported in the accessors that materialize it.
- from posthog.models.oauth_provisioning import ProvisioningConfig
+ from posthog.models.oauth_provisioning import PartnerTier, ProvisioningConfig
class OAuthApplicationAccessLevel(enum.Enum):
@@ -270,6 +270,18 @@ class OAuthApplication(ModelActivityMixin, AbstractApplication): # type: ignore
self._provisioning_config = current._provisioning_config
return self.update_provisioning(rate_limits=self.provisioning.rate_limits.model_copy(update=changes))
+ @property
+ def partner_tier(self) -> "PartnerTier":
+ """See :class:`~posthog.models.oauth_provisioning.PartnerTier`. The attested
+ signal is the CIMD verification-token binding (``organization_id``), the same
+ one CIMD registration reads."""
+ from posthog.models.oauth_provisioning import PartnerTier # noqa: PLC0415
+
+ attested = self.organization_id is not None
+ if self.requires_client_authentication:
+ return PartnerTier.JWKS_ATTESTED if attested else PartnerTier.JWKS
+ return PartnerTier.PUBLIC_ATTESTED if attested else PartnerTier.PUBLIC
+
@property
def carries_provisioning_config(self) -> bool:
"""Whether this app has ever been configured for provisioning, whatever
diff --git a/posthog/models/oauth_provisioning.py b/posthog/models/oauth_provisioning.py
index 6340dfb6a4a0..41fa4d6d40c6 100644
--- a/posthog/models/oauth_provisioning.py
+++ b/posthog/models/oauth_provisioning.py
@@ -17,10 +17,31 @@ to an operator as a capability that was granted.
from __future__ import annotations
+from enum import StrEnum
from typing import Literal
from pydantic import BaseModel, ConfigDict, Field
+
+class PartnerTier(StrEnum):
+ """Where a partner sits on the two trust axes, derived from the app row on every read.
+
+ Auth axis: a client that must prove itself (private_key_jwt against a published key
+ set, or a client secret) sits in the JWKS rows; a PKCE-public client, whose client_id
+ anyone can send, sits in the PUBLIC rows. Attested axis: the app presented a valid
+ ``posthog_verification_token`` at CIMD registration, so abuse is traceable to a real
+ PostHog organization.
+
+ Derived, never stored: a partner moves tier the moment it publishes a key set or
+ attests, with no admin involvement and no persisted value to go stale.
+ """
+
+ PUBLIC = "public"
+ PUBLIC_ATTESTED = "public_attested"
+ JWKS = "jwks"
+ JWKS_ATTESTED = "jwks_attested"
+
+
# Records who set the account-request rate limit, so a verification flip doesn't overwrite an
# explicit admin override. Empty for rows that pre-date the field.
RateLimitSource = Literal["", "default_unverified", "default_verified", "admin"]