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): require partners that create accounts to sign requests (#112182)

Matt Brooker6889f4b50781
diff --git a/ee/api/agentic_provisioning/authentication.py b/ee/api/agentic_provisioning/authentication.py
index 243418752c5b..3a8c12723811 100644
--- a/ee/api/agentic_provisioning/authentication.py
+++ b/ee/api/agentic_provisioning/authentication.py
@@ -1,5 +1,6 @@
from __future__ import annotations
+from enum import StrEnum
from typing import NoReturn
from django.utils import timezone
@@ -11,15 +12,18 @@ from rest_framework.request import Request
from posthog.api.oauth.cimd import enqueue_cimd_refresh_if_stale
from posthog.api.oauth.client_assertion import (
+ PRIVATE_KEY_REQUIRED_MESSAGE,
+ UNREADABLE_CLIENT_ASSERTION_MESSAGE,
ClientAssertionError,
ResolvedClientAssertion,
extract_client_assertion,
+ presents_client_assertion,
verify_client_assertion,
)
from posthog.api.oauth.client_auth import ClientCredentials, extract_client_credentials, verify_client_secret
from posthog.auth import ACCOUNT_BLOCKED_DETAIL, account_refused
from posthog.models.activity_logging.utils import ActivityCredentialMixin
-from posthog.models.oauth import OAuthAccessToken, OAuthApplication, find_oauth_access_token
+from posthog.models.oauth import OAuthAccessToken, OAuthApplication, ProvisioningSigning, find_oauth_access_token
from posthog.models.user import User
from products.security.backend.facade.api import REFUSAL_CODE as SECURITY_REFUSAL_CODE
@@ -39,6 +43,12 @@ CLIENT_NOT_REGISTERED_MESSAGE = (
)
+class ClientProof(StrEnum):
+ ASSERTION = "assertion"
+ CLIENT_SECRET = "client_secret"
+ CLIENT_ID = "client_id"
+
+
class BearerTokenError(Exception):
"""The bearer header is missing, unknown, or expired; the message is the
wire-safe reason each authenticator maps into its own failure type."""
@@ -86,27 +96,51 @@ class ProvisioningAuthentication(ActivityCredentialMixin, BaseAuthentication):
activity_credential_type = "partner"
+ def __init__(self) -> None:
+ super().__init__()
+ self.client_proof: ClientProof | None = None
+
def authenticate(self, request: Request) -> tuple[None, OAuthApplication] | None:
- app = self._identify_partner(request)
- if app is None:
+ identified = self._identify_partner(request)
+ if identified is None:
return None
-
- capture_auth_event(app, "success", endpoint=request.path)
- # A public partner is named by a client_id that anyone can send, so only a partner that proved
- # itself with a secret or a signed assertion is recorded by id.
- self.record_activity_actor(None, str(app.id) if app.requires_client_authentication else None)
+ app, proof = identified
+
+ signing = app.provisioning_signing
+ signed = proof is ClientProof.ASSERTION
+ if not signed and signing is ProvisioningSigning.REQUIRED:
+ self._reject(
+ request,
+ app,
+ PRIVATE_KEY_REQUIRED_MESSAGE,
+ outcome="private_key_required",
+ provisioning_signing=signing.request_tag(signed=False),
+ )
+
+ self.client_proof = proof
+ capture_auth_event(
+ app, "success", endpoint=request.path, provisioning_signing=signing.request_tag(signed=signed)
+ )
+ # A client_id alone is something anyone can send, so only a partner that proved itself with a
+ # secret or a signed assertion is recorded by id.
+ self.record_activity_actor(None, str(app.id) if proof is not ClientProof.CLIENT_ID else None)
return (None, app)
- def _identify_partner(self, request: Request) -> OAuthApplication | None:
+ def _identify_partner(self, request: Request) -> tuple[OAuthApplication, ClientProof] | None:
# 1. A signed assertion identifies and proves a private_key_jwt partner at once.
assertion = extract_client_assertion(request)
if assertion is not None:
- return self._identify_assertion_partner(request, assertion)
+ return self._identify_assertion_partner(request, assertion), ClientProof.ASSERTION
# 2. So do client credentials, for a partner registered with a secret.
credentials = extract_client_credentials(request)
if credentials is not None:
- return self._identify_client_secret_partner(request, credentials)
+ secret_partner = self._identify_client_secret_partner(request, credentials)
+ return None if secret_partner is None else (secret_partner, ClientProof.CLIENT_SECRET)
+
+ # An assertion that does not resolve must fail here, or the bare client_id below would accept it unverified.
+ if presents_client_assertion(request):
+ raise AuthenticationFailed(UNREADABLE_CLIENT_ASSERTION_MESSAGE)
# 3. A bare client_id identifies a public client, which relies on PKCE.
client_id = request.data.get("client_id") or request.query_params.get("client_id")
@@ -119,22 +153,28 @@ class ProvisioningAuthentication(ActivityCredentialMixin, BaseAuthentication):
# returning a bare "unauthorized" it cannot act on.
raise AuthenticationFailed(CLIENT_NOT_REGISTERED_MESSAGE)
- # A confidential partner that presented no proof must not fall through to the public
- # path. Its client_id is published like any other, so honoring it here would let
- # anyone act as that partner simply by sending nothing else.
- if app.requires_client_authentication:
+ # A client_id proves nothing. A key-based partner that must sign goes on to the signing check, which refuses it.
+ if app.requires_client_authentication and not (
+ app.uses_private_key_jwt_auth and app.provisioning_signing is not ProvisioningSigning.NOT_REQUIRED
+ ):
self._reject(request, app, "This client must authenticate")
- return app
-
- def _reject(self, request: Request, app: OAuthApplication, reason: str) -> NoReturn:
+ return app, ClientProof.CLIENT_ID
+
+ def _reject(
+ self,
+ request: Request,
+ app: OAuthApplication,
+ reason: str,
+ *,
+ outcome: str = "verification_failed",
+ **extra: object,
+ ) -> NoReturn:
"""Fail a partner that was identified but did not prove itself."""
- capture_auth_event(app, "verification_failed", endpoint=request.path)
+ capture_auth_event(app, outcome, endpoint=request.path, **extra)
raise AuthenticationFailed(reason)
- def _identify_assertion_partner(
- self, request: Request, assertion: ResolvedClientAssertion
- ) -> OAuthApplication | None:
+ def _identify_assertion_partner(self, request: Request, assertion: ResolvedClientAssertion) -> OAuthApplication:
app = self._resolve_partner(assertion.client_id)
if app is None:
raise AuthenticationFailed(CLIENT_NOT_REGISTERED_MESSAGE)
@@ -230,6 +270,8 @@ class ProvisioningBearerAuthentication(ActivityCredentialMixin, BaseAuthenticati
if not app.provisioning.active:
raise ProvisioningError("unauthorized", "Partner is deactivated", status=401)
+ if app.cannot_meet_provisioning_signature:
+ raise ProvisioningError("unauthorized", PRIVATE_KEY_REQUIRED_MESSAGE, status=401)
if not app.provisioning.can_provision_resources:
raise ProvisioningError("forbidden", "Resource provisioning not enabled for this partner", status=403)
diff --git a/ee/api/agentic_provisioning/test/base.py b/ee/api/agentic_provisioning/test/base.py
index 621407e70a74..8a88d0bd08fb 100644
--- a/ee/api/agentic_provisioning/test/base.py
+++ b/ee/api/agentic_provisioning/test/base.py
@@ -3,6 +3,7 @@ import base64
import hashlib
import secrets
import dataclasses
+from datetime import UTC, datetime
from typing import TYPE_CHECKING
from urllib.parse import quote_plus
@@ -10,6 +11,7 @@ from posthog.test.base import APIBaseTest
from unittest.mock import patch
from django.core.cache import cache
+from django.test import override_settings
from django.utils import timezone
from rest_framework.test import APIClient
@@ -57,6 +59,18 @@ TEST_PARTNER_PROVISIONING: dict[str, bool] = {
}
+# Signing depends on the clock, so tests pin the window rather than age against the real dates.
+SIGNING_WINDOW_IN_THE_FUTURE = datetime(2100, 1, 1, tzinfo=UTC)
+SIGNING_WINDOW_IN_THE_PAST = datetime(2000, 1, 1, tzinfo=UTC)
+
+
+def signing_required() -> override_settings:
+ return override_settings(
+ PROVISIONING_SIGNING_REQUIRED_SINCE=SIGNING_WINDOW_IN_THE_PAST,
+ PROVISIONING_UNSIGNED_GRACE_UNTIL=SIGNING_WINDOW_IN_THE_PAST,
+ )
+
+
def provisioning_config(**overrides) -> dict:
"""The stored form of the test partner's config. Goes into ``_provisioning_config``."""
from posthog.models.oauth_provisioning import ProvisioningConfig
@@ -79,6 +93,10 @@ def patched_budget(view_cls, method: str, endpoint: str, budget, *, multipliers=
return patch.dict(budgets, {endpoint: dataclasses.replace(budgets[endpoint], **changes)})
+@override_settings(
+ PROVISIONING_SIGNING_REQUIRED_SINCE=SIGNING_WINDOW_IN_THE_FUTURE,
+ PROVISIONING_UNSIGNED_GRACE_UNTIL=SIGNING_WINDOW_IN_THE_FUTURE,
+)
class ProvisioningTestBase(APIBaseTest):
def setUp(self):
super().setUp()
diff --git a/ee/api/agentic_provisioning/test/test_client_registration.py b/ee/api/agentic_provisioning/test/test_client_registration.py
index 67e4830a9948..2c9fab9405da 100644
--- a/ee/api/agentic_provisioning/test/test_client_registration.py
+++ b/ee/api/agentic_provisioning/test/test_client_registration.py
@@ -1,21 +1,32 @@
import json
import time
+from datetime import timedelta
from ipaddress import ip_address
from unittest.mock import patch
from django.core.cache import cache
from django.test import override_settings
+from django.utils import timezone
import jwt
from cryptography.hazmat.primitives.asymmetric import rsa
from parameterized import parameterized
from posthog.api.oauth.cimd import apply_provisioning_defaults
-from posthog.api.oauth.client_assertion import CLIENT_ASSERTION_TYPE_JWT_BEARER, ClientAssertionError
+from posthog.api.oauth.client_assertion import (
+ CLIENT_ASSERTION_TYPE_JWT_BEARER,
+ PRIVATE_KEY_REQUIRED_MESSAGE,
+ ClientAssertionError,
+)
from posthog.models.oauth import OAuthApplication
-from ee.api.agentic_provisioning.test.base import TEST_PARTNER_SCOPES, ProvisioningTestBase, provisioning_config
+from ee.api.agentic_provisioning.test.base import (
+ TEST_PARTNER_SCOPES,
+ ProvisioningTestBase,
+ provisioning_config,
+ signing_required,
+)
REGISTRATION_URL = "/api/agentic/provisioning/client_registration"
ACCOUNT_REQUESTS_URL = "/api/agentic/provisioning/account_requests"
@@ -47,7 +58,7 @@ class TestClientRegistration(ProvisioningTestBase):
super().setUp()
cache.clear()
- def _document(self, *, com_posthog: object = _DECLARES_PROVISIONING) -> dict:
+ def _document(self, *, com_posthog: object = _DECLARES_PROVISIONING, signs: bool = True) -> dict:
"""The document a client wanting to register publishes. Passing com_posthog=None leaves
the namespace out, which is the shape of a third party that never asked for any of
this."""
@@ -57,9 +68,10 @@ class TestClientRegistration(ProvisioningTestBase):
"redirect_uris": ["https://newpartner.example.com/callback"],
"grant_types": ["authorization_code"],
"response_types": ["code"],
- "token_endpoint_auth_method": "private_key_jwt",
- "jwks_uri": JWKS_URI,
+ "token_endpoint_auth_method": "private_key_jwt" if signs else "none",
}
+ if signs:
+ document["jwks_uri"] = JWKS_URI
if com_posthog is not None:
document["com.posthog"] = com_posthog
return document
@@ -150,18 +162,70 @@ class TestClientRegistration(ProvisioningTestBase):
def test_reports_diagnostics_for_a_private_key_jwt_partner(self):
self._make_partner()
- res = self._register({"client_id": CIMD_URL})
+ with signing_required():
+ res = self._register({"client_id": CIMD_URL})
assert res.status_code == 200, res.json()
body = res.json()
assert body["registered"] is True
assert body["client_id"] == CIMD_URL
assert body["token_endpoint_auth_method"] == "private_key_jwt"
- assert body["capabilities"] == {"account_requests": True}
+ assert body["capabilities"] == {
+ "account_requests": True,
+ "unsigned_requests": False,
+ "unsigned_requests_allowed_until": None,
+ }
checks = {check["name"]: check for check in body["checks"]}
assert checks["jwks"]["ok"] is True
assert KID in checks["jwks"]["detail"]
+ @parameterized.expand(
+ [
+ ("during_grace", True, True),
+ ("after_grace", True, False),
+ # The row predates the requirement, but the partnership starts with this registration.
+ ("promoted_after_the_requirement", False, True),
+ ]
+ )
+ def test_reports_whether_a_partner_without_a_key_may_still_call_unsigned(
+ self, _name: str, already_a_partner: bool, grace_ongoing: bool
+ ) -> None:
+ app = self._make_partner(
+ client_type=OAuthApplication.CLIENT_PUBLIC, jwks_uri=None, is_provisioning_partner=already_a_partner
+ )
+ OAuthApplication.objects.filter(pk=app.pk).update(created=timezone.now() - timedelta(days=14))
+ grace_until = timezone.now() + timedelta(days=7 if grace_ongoing else -1)
+ in_grace = already_a_partner and grace_ongoing
+
+ with override_settings(
+ PROVISIONING_SIGNING_REQUIRED_SINCE=timezone.now() - timedelta(days=7),
+ PROVISIONING_UNSIGNED_GRACE_UNTIL=grace_until,
+ ):
+ res = self._register({"client_id": CIMD_URL}, document=self._document(signs=False))
+
+ assert res.status_code == 200, res.json()
+ body = res.json()
+ assert body["token_endpoint_auth_method"] == "none"
+ jwks = {check["name"]: check for check in body["checks"]}["jwks"]
+ if in_grace:
+ assert jwks == {
+ "name": "jwks",
+ "ok": True,
+ "detail": f"Unsigned requests allowed until {grace_until.isoformat()}. {PRIVATE_KEY_REQUIRED_MESSAGE}",
+ }
+ assert body["capabilities"] == {
+ "account_requests": True,
+ "unsigned_requests": True,
+ "unsigned_requests_allowed_until": grace_until.isoformat(),
+ }
+ else:
+ assert jwks == {"name": "jwks", "ok": False, "detail": PRIVATE_KEY_REQUIRED_MESSAGE}
+ assert body["capabilities"] == {
+ "account_requests": False,
+ "unsigned_requests": False,
+ "unsigned_requests_allowed_until": None,
+ }
+
def test_brand_new_partner_is_confidential_on_its_first_registration(self):
# No pre-existing row: this is the client_id's first ever contact with PostHog, so the
# promotion has to happen inline with _create_cimd_application, not wait for the next
diff --git a/ee/api/agentic_provisioning/test/test_limits.py b/ee/api/agentic_provisioning/test/test_limits.py
index 577a47378ce7..f2aa8a26ae85 100644
--- a/ee/api/agentic_provisioning/test/test_limits.py
+++ b/ee/api/agentic_provisioning/test/test_limits.py
@@ -1,20 +1,30 @@
+from contextlib import nullcontext
+
from parameterized import parameterized
from posthog.models.oauth import OAuthApplication
from ee.api.agentic_provisioning.ratelimits import describe_budgets
-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,
+ provisioning_config,
+ signing_required,
+)
LIMITS_URL = "/api/agentic/provisioning/limits"
class TestLimitsEndpoint(ProvisioningTestBase):
- def _public_partner(self) -> OAuthApplication:
+ def _self_registered_partner(self, *, switched_to_private_key_jwt: bool = False) -> OAuthApplication:
return OAuthApplication.objects.create(
client_id="limits_public_partner",
name="Limits Public Partner",
client_secret="",
- client_type=OAuthApplication.CLIENT_PUBLIC,
+ client_type=OAuthApplication.CLIENT_CONFIDENTIAL
+ if switched_to_private_key_jwt
+ else OAuthApplication.CLIENT_PUBLIC,
+ jwks_uri="https://partner.example.com/.well-known/jwks.json" if switched_to_private_key_jwt else None,
authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,
redirect_uris="https://partner.example.com/callback",
algorithm="RS256",
@@ -57,30 +67,44 @@ class TestLimitsEndpoint(ProvisioningTestBase):
[
# A public partner's client_id is published, so honoring it would hand its
# tier and live headroom to any caller, and charge its bucket to do it.
- ("bare_client_id", "post", True, 401),
- ("no_credentials", "post", False, 401),
+ ("bare_client_id", "post", True, False, 401),
+ ("no_credentials", "post", False, False, 401),
# GET has nowhere to carry client authentication, so the verb is gone. If it
# comes back, the bare client_id path comes back with it.
- ("get_with_client_id", "get", True, 405),
+ ("get_with_client_id", "get", True, False, 405),
+ # Its grace lets it call unsigned elsewhere, but a client_id still proves nothing.
+ ("bare_client_id_of_a_switched_partner_in_grace", "post", True, True, 401),
]
)
- def test_caller_without_proof_is_rejected(self, _name: str, method: str, name_a_partner: bool, expected: int):
- public = self._public_partner()
- body = {"client_id": public.client_id} if name_a_partner else {}
+ def test_caller_without_proof_is_rejected(
+ self, _name: str, method: str, name_a_partner: bool, switched_to_private_key_jwt: bool, expected: int
+ ):
+ partner = self._self_registered_partner(switched_to_private_key_jwt=switched_to_private_key_jwt)
+ body = {"client_id": partner.client_id} if name_a_partner else {}
res = getattr(self.client, method)(LIMITS_URL, body)
assert res.status_code == expected
- def test_deactivated_partner_bearer_is_rejected(self):
+ @parameterized.expand(
+ [
+ ("deactivated", {"active": False}, False),
+ ("grace_ended_without_a_private_key", {}, True),
+ ]
+ )
+ def test_bearer_is_rejected_after_partner_changes(
+ self, _name: str, change: dict[str, bool], grace_ended: bool
+ ) -> None:
token = self._request_bearer_token().json()["access_token"]
- self.partner.update_provisioning(active=False)
+ if change:
+ self.partner.update_provisioning(**change)
- res = self.client.post(LIMITS_URL, HTTP_AUTHORIZATION=f"Bearer {token}")
+ with signing_required() if grace_ended else nullcontext():
+ res = self.client.post(LIMITS_URL, HTTP_AUTHORIZATION=f"Bearer {token}")
assert res.status_code == 401
def test_describe_budgets_marks_endpoints_the_tier_blocks(self):
# Reported as blocked rather than as a budget, so a partner is not told it has
# headroom on an endpoint its tier refuses outright.
- assert describe_budgets(self._public_partner())["deep_links"] == {"blocked": True}
+ assert describe_budgets(self._self_registered_partner())["deep_links"] == {"blocked": True}
diff --git a/ee/api/agentic_provisioning/test/test_oauth_token.py b/ee/api/agentic_provisioning/test/test_oauth_token.py
index 7aa2d42a45a1..ae20c855ed8a 100644
--- a/ee/api/agentic_provisioning/test/test_oauth_token.py
+++ b/ee/api/agentic_provisioning/test/test_oauth_token.py
@@ -1,22 +1,33 @@
import uuid
from datetime import timedelta
+from urllib.parse import urlencode
+
+from unittest.mock import patch
from django.core.cache import cache
from django.utils import timezone
from parameterized import parameterized
+from posthog.api.id_jag import JWT_BEARER_GRANT_TYPE
+from posthog.api.oauth.client_assertion import PRIVATE_KEY_REQUIRED_MESSAGE
from posthog.constants import AvailableFeature
-from posthog.models.oauth import OAuthAccessToken, OAuthApplication
+from posthog.models.oauth import OAuthAccessToken, OAuthApplication, OAuthRefreshToken
from posthog.models.organization import OrganizationMembership
from posthog.models.team.team import Team
from products.access_control.backend.models.access_control import AccessControl
from ee.api.agentic_provisioning.constants import AUTH_CODE_CACHE_PREFIX
-from ee.api.agentic_provisioning.test.base import TEST_PARTNER_SCOPES, ProvisioningTestBase, provisioning_config
+from ee.api.agentic_provisioning.test.base import (
+ TEST_PARTNER_SCOPES,
+ ProvisioningTestBase,
+ provisioning_config,
+ signing_required,
+)
TOKEN_URL = "/api/agentic/oauth/token"
+OAUTH_TOKEN_URL = "/oauth/token/"
class TestOAuthTokenExchange(ProvisioningTestBase):
@@ -55,6 +66,20 @@ class TestOAuthTokenExchange(ProvisioningTestBase):
def _stamp_session_revoke(self, when=None) -> None:
OAuthApplication.objects.filter(id=self.partner.id).update(sessions_revoked_at=when or timezone.now())
+ def _public_partner(self, **provisioning: bool) -> OAuthApplication:
+ return OAuthApplication.objects.create(
+ client_id="pkce-token-partner",
+ name="PKCE Token Partner",
+ client_secret="",
+ client_type=OAuthApplication.CLIENT_PUBLIC,
+ authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,
+ redirect_uris="https://partner.example.com/callback",
+ algorithm="RS256",
+ scopes=TEST_PARTNER_SCOPES,
+ is_provisioning_partner=True,
+ _provisioning_config=provisioning_config(active=True, **provisioning),
+ )
+
def test_valid_code_exchange_returns_tokens(self):
res = self._request_bearer_token()
assert res.status_code == 200
@@ -172,25 +197,108 @@ class TestOAuthTokenExchange(ProvisioningTestBase):
def test_pkce_partner_exchanges_code_without_a_secret(self):
# PKCE partners are public clients: code_verifier is their only client authentication,
# so requiring a secret from confidential partners must not reach them.
- pkce_partner = OAuthApplication.objects.create(
- client_id="pkce-token-partner",
- name="PKCE Token Partner",
- client_secret="",
- client_type=OAuthApplication.CLIENT_PUBLIC,
- authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,
- redirect_uris="https://partner.example.com/callback",
- algorithm="RS256",
- scopes=TEST_PARTNER_SCOPES,
- is_provisioning_partner=True,
- _provisioning_config=provisioning_config(active=True),
- )
- code, verifier = self._mint_auth_code(partner=pkce_partner)
+ code, verifier = self._mint_auth_code(partner=self._public_partner())
res = self._post_api(TOKEN_URL, {"grant_type": "authorization_code", "code": code, "code_verifier": verifier})
assert res.status_code == 200
assert res.json()["access_token"].startswith("pha_")
+ @parameterized.expand(
+ [
+ ("public_code_exchange", True, {}, "authorization_code", TOKEN_URL, 401),
+ ("public_refresh", True, {}, "refresh_token", TOKEN_URL, 401),
+ ("client_secret_refresh", False, {}, "refresh_token", TOKEN_URL, 401),
+ (
+ "paying_public_refresh",
+ True,
+ {"can_create_accounts": False, "pays_for_customers": True},
+ "refresh_token",
+ TOKEN_URL,
+ 401,
+ ),
+ ("public_refresh_at_oauth_token", True, {}, "refresh_token", OAUTH_TOKEN_URL, 401),
+ ("client_secret_refresh_at_oauth_token", False, {}, "refresh_token", OAUTH_TOKEN_URL, 401),
+ ("exempt_public_refresh", True, {"can_create_accounts": False}, "refresh_token", TOKEN_URL, 200),
+ (
+ "exempt_public_refresh_at_oauth_token",
+ True,
+ {"can_create_accounts": False},
+ "refresh_token",
+ OAUTH_TOKEN_URL,
+ 200,
+ ),
+ # The Wizard's production shape: a client secret, and no account creation.
+ ("exempt_client_secret_refresh", False, {"can_create_accounts": False}, "refresh_token", TOKEN_URL, 200),
+ (
+ "exempt_client_secret_refresh_at_oauth_token",
+ False,
+ {"can_create_accounts": False},
+ "refresh_token",
+ OAUTH_TOKEN_URL,
+ 200,
+ ),
+ ]
+ )
+ def test_unsigned_token_request_after_grace(
+ self,
+ _name: str,
+ public: bool,
+ capabilities: dict[str, bool],
+ grant_type: str,
+ url: str,
+ expected_status: int,
+ ) -> None:
+ if public:
+ partner = self._public_partner(**capabilities)
+ else:
+ partner = self.partner
+ if capabilities:
+ partner.update_provisioning(**capabilities)
+ credentials = self._client_credentials(partner) if not public else {"client_id": partner.client_id}
+ if grant_type == "authorization_code":
+ code, verifier = self._mint_auth_code(partner=partner)
+ body = {"grant_type": grant_type, "code": code, "code_verifier": verifier, **credentials}
+ else:
+ refresh_token = self._request_bearer_token(partner=partner).json()["refresh_token"]
+ body = {"grant_type": grant_type, "refresh_token": refresh_token, **credentials}
+
+ with signing_required(), patch("posthoganalytics.capture") as capture:
+ res = self._post_api(url, body)
+
+ assert res.status_code == expected_status, res.json()
+ tags = {call.kwargs.get("properties", {}).get("provisioning_signing") for call in capture.call_args_list}
+ assert ("refused" if expected_status == 401 else "unsigned_exempt") in tags
+ if expected_status == 401:
+ assert res.json()["error"] == "invalid_client"
+ assert res.json()["error_description"] == PRIVATE_KEY_REQUIRED_MESSAGE
+
+ @parameterized.expand([("public", True), ("client_secret", False)])
+ def test_refused_partner_can_still_revoke_its_tokens(self, _name: str, public: bool) -> None:
+ partner = self._public_partner() if public else self.partner
+ credentials = {"client_id": partner.client_id} if public else self._client_credentials(partner)
+ refresh_token = self._request_bearer_token(partner=partner).json()["refresh_token"]
+
+ with signing_required():
+ res = self._post_api(
+ "/oauth/revoke/",
+ urlencode({"token": refresh_token, "token_type_hint": "refresh_token", **credentials}).encode(),
+ content_type="application/x-www-form-urlencoded",
+ )
+
+ assert res.status_code == 200, res.content
+ assert not OAuthRefreshToken.objects.filter(token=refresh_token, revoked__isnull=True).exists()
+
+ def test_refused_partner_gets_a_401_from_the_jwt_bearer_grant(self):
+ with signing_required():
+ res = self._post_api(
+ OAUTH_TOKEN_URL,
+ {"grant_type": JWT_BEARER_GRANT_TYPE, "assertion": "not-an-id-jag", **self._client_credentials()},
+ )
+
+ assert res.status_code == 401
+ assert res.json()["error"] == "invalid_client"
+
def test_pkce_mismatch_returns_400_without_consuming_code(self):
code, verifier = self._mint_auth_code()
res = self._exchange_code(code, "wrong_verifier_" + "a" * 32)
diff --git a/ee/api/agentic_provisioning/test/test_private_key_jwt_partner.py b/ee/api/agentic_provisioning/test/test_private_key_jwt_partner.py
index 0fdbcf892f86..d62ba18f59f0 100644
--- a/ee/api/agentic_provisioning/test/test_private_key_jwt_partner.py
+++ b/ee/api/agentic_provisioning/test/test_private_key_jwt_partner.py
@@ -1,21 +1,30 @@
import json
import time
+from contextlib import nullcontext
-from unittest.mock import patch
+from unittest.mock import MagicMock, patch
from django.core.cache import cache
from django.test import override_settings
import jwt
from cryptography.hazmat.primitives.asymmetric import rsa
+from parameterized import parameterized
-from posthog.api.oauth.client_assertion import CLIENT_ASSERTION_TYPE_JWT_BEARER
+from posthog.api.oauth.client_assertion import CLIENT_ASSERTION_TYPE_JWT_BEARER, PRIVATE_KEY_REQUIRED_MESSAGE
from posthog.models.oauth import OAuthAccessToken, OAuthApplication
+from posthog.models.user import User
-from ee.api.agentic_provisioning.test.base import TEST_PARTNER_SCOPES, ProvisioningTestBase, provisioning_config
+from ee.api.agentic_provisioning.test.base import (
+ TEST_PARTNER_SCOPES,
+ ProvisioningTestBase,
+ provisioning_config,
+ signing_required,
+)
ACCOUNT_REQUESTS_URL = "/api/agentic/provisioning/account_requests"
TOKEN_URL = "/api/agentic/oauth/token"
+OAUTH_TOKEN_URL = "/oauth/token/"
PARTNER_CLIENT_ID = "https://jwtpartner.example.com/.well-known/oauth-client-metadata.json"
PARTNER_JWKS_URI = "https://jwtpartner.example.com/.well-known/jwks.json"
KID = "jwt-partner-key"
@@ -55,7 +64,7 @@ class TestPrivateKeyJwtPartner(ProvisioningTestBase):
),
)
- def _assertion(self, **overrides) -> str:
+ def _assertion(self, *, key: rsa.RSAPrivateKey | None = None, **overrides) -> str:
now = int(time.time())
claims = {
"iss": PARTNER_CLIENT_ID,
@@ -66,7 +75,7 @@ class TestPrivateKeyJwtPartner(ProvisioningTestBase):
"exp": now + 60,
}
claims.update(overrides)
- return jwt.encode(claims, self.private_key, algorithm="RS256", headers={"kid": KID})
+ return jwt.encode(claims, key or self.private_key, algorithm="RS256", headers={"kid": KID})
def _assertion_body(self, **overrides) -> dict:
return {
@@ -86,54 +95,87 @@ class TestPrivateKeyJwtPartner(ProvisioningTestBase):
assert res.status_code == 200, res.json()
assert res.json()["type"] == "oauth"
- def test_account_request_rejected_without_an_assertion(self):
- # The client_id is public, so presenting it alone must not authenticate a confidential
- # partner.
- res = self._post_api(
- ACCOUNT_REQUESTS_URL,
- {
- "id": "req_jwt_bare",
- "email": "[email protected]",
- "client_id": PARTNER_CLIENT_ID,
- "code_challenge": "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM",
- "code_challenge_method": "S256",
- },
- )
- assert res.status_code == 401
- assert res.json()["error"]["code"] == "unauthorized"
+ @parameterized.expand(
+ [
+ # The client_id is public, so presenting it alone must not authenticate a key-based partner,
+ # even while partners that have not switched yet are still in grace.
+ ("during_grace", {}, False, 401),
+ ("after_grace", {}, True, 401),
+ ("cannot_create_accounts_or_pay", {"can_create_accounts": False}, False, 401),
+ ]
+ )
+ def test_account_request_without_an_assertion(
+ self, _name: str, capabilities: dict[str, bool], grace_ended: bool, expected_status: int
+ ) -> None:
+ if capabilities:
+ self.jwt_partner.update_provisioning(**capabilities)
- def test_account_request_rejected_when_signed_by_another_key(self):
- now = int(time.time())
- forged = jwt.encode(
- {
- "iss": PARTNER_CLIENT_ID,
- "sub": PARTNER_CLIENT_ID,
- "aud": "https://us.posthog.com/api/agentic/oauth/token",
- "jti": "forged",
- "iat": now,
- "exp": now + 60,
- },
- FOREIGN_KEY,
- algorithm="RS256",
- headers={"kid": KID},
- )
- res = self._post(
- ACCOUNT_REQUESTS_URL,
- {
- "id": "req_forged",
- "email": "[email protected]",
- "client_assertion": forged,
- "client_assertion_type": CLIENT_ASSERTION_TYPE_JWT_BEARER,
- },
- )
- assert res.status_code == 401
+ with signing_required() if grace_ended else nullcontext():
+ res = self._post_api(
+ ACCOUNT_REQUESTS_URL,
+ {
+ "id": "req_jwt_bare",
+ "email": "[email protected]",
+ "client_id": PARTNER_CLIENT_ID,
+ "code_challenge": "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM",
+ "code_challenge_method": "S256",
+ },
+ )
+
+ assert res.status_code == expected_status, res.json()
+ if not capabilities:
+ assert res.json()["error"] == {"code": "unauthorized", "message": PRIVATE_KEY_REQUIRED_MESSAGE}
+
+ @parameterized.expand(
+ [
+ ("jwt_bearer_type", CLIENT_ASSERTION_TYPE_JWT_BEARER),
+ # An assertion with a missing or wrong type must not fall back to the bare client_id path unverified.
+ ("no_type", None),
+ ("wrong_type", "urn:ietf:params:oauth:client-assertion-type:saml2-bearer"),
+ ]
+ )
+ def test_account_request_rejected_when_signed_by_another_key(self, _name: str, assertion_type: str | None) -> None:
+ body = {
+ "id": "req_forged",
+ "email": "[email protected]",
+ "client_id": PARTNER_CLIENT_ID,
+ "client_assertion": self._assertion(key=FOREIGN_KEY, jti_suffix="forged"),
+ "code_challenge": "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM",
+ "code_challenge_method": "S256",
+ }
+ if assertion_type is not None:
+ body["client_assertion_type"] = assertion_type
- def test_token_exchange_requires_an_assertion(self):
+ res = self._post(ACCOUNT_REQUESTS_URL, body)
+
+ assert res.status_code == 401, res.json()
+ assert not User.objects.filter(email="[email protected]").exists()
+
+ @parameterized.expand(
+ [
+ ("unsigned_during_grace", False, None, 401),
+ ("unsigned_after_grace", True, None, 401),
+ ("signed_by_another_key_during_grace", False, CLIENT_ASSERTION_TYPE_JWT_BEARER, 401),
+ ("signed_by_another_key_without_a_type_during_grace", False, "", 401),
+ ]
+ )
+ def test_token_exchange_assertion(
+ self, _name: str, grace_ended: bool, forged_assertion_type: str | None, expected_status: int
+ ) -> None:
code, verifier = self._mint_auth_code(partner=self.jwt_partner)
+ body = {"grant_type": "authorization_code", "code": code, "code_verifier": verifier}
+ if forged_assertion_type is not None:
+ body.update(
+ client_assertion=self._assertion(key=FOREIGN_KEY, jti_suffix="forged"),
+ client_assertion_type=forged_assertion_type,
+ )
- res = self._post_api(TOKEN_URL, {"grant_type": "authorization_code", "code": code, "code_verifier": verifier})
+ with signing_required() if grace_ended else nullcontext():
+ res = self._post(TOKEN_URL, body)
- assert res.status_code == 401
+ assert res.status_code == expected_status, res.json()
+ if expected_status == 200:
+ return
assert res.json()["error"] == "invalid_client"
# Client authentication runs before the code is consumed, so the caller can retry.
retry = self._post(
@@ -147,7 +189,37 @@ class TestPrivateKeyJwtPartner(ProvisioningTestBase):
)
assert retry.status_code == 200, retry.json()
- def test_full_flow_from_account_request_to_resource(self):
+ @parameterized.expand([("during_grace", False, 401, "refused"), ("after_grace", True, 401, "refused")])
+ def test_unsigned_refresh_at_the_oauth_token_endpoint(
+ self, _name: str, grace_ended: bool, expected_status: int, expected_signing: str
+ ) -> None:
+ code, verifier = self._mint_auth_code(partner=self.jwt_partner)
+ tokens = self._post(
+ TOKEN_URL,
+ {"grant_type": "authorization_code", "code": code, "code_verifier": verifier, **self._assertion_body()},
+ )
+ assert tokens.status_code == 200, tokens.json()
+
+ with signing_required() if grace_ended else nullcontext(), patch("posthoganalytics.capture") as capture:
+ res = self._post_api(
+ OAUTH_TOKEN_URL,
+ {
+ "grant_type": "refresh_token",
+ "refresh_token": tokens.json()["refresh_token"],
+ "client_id": PARTNER_CLIENT_ID,
+ },
+ )
+
+ assert res.status_code == expected_status, res.json()
+ signing = {call.kwargs.get("properties", {}).get("provisioning_signing") for call in capture.call_args_list}
+ assert expected_signing in signing
+
+ @parameterized.expand([("non_paying", False), ("paying", True)])
+ @patch("posthoganalytics.capture")
+ def test_full_flow_from_account_request_to_resource(
+ self, _name: str, pays_for_customers: bool, capture: MagicMock
+ ) -> None:
+ self.jwt_partner.update_provisioning(pays_for_customers=pays_for_customers)
verifier, challenge = self._pkce_pair()
res = self._post(
ACCOUNT_REQUESTS_URL,
@@ -191,6 +263,12 @@ class TestPrivateKeyJwtPartner(ProvisioningTestBase):
)
assert refreshed.status_code == 200, refreshed.json()
assert OAuthAccessToken.objects.filter(token=refreshed.json()["access_token"]).exists()
+ # One each from the account request, the code exchange and the refresh.
+ assert [
+ call.kwargs["properties"]["provisioning_signing"]
+ for call in capture.call_args_list
+ if "provisioning_signing" in call.kwargs.get("properties", {})
+ ] == ["signed"] * 3
def test_assertion_cannot_be_replayed_across_requests(self):
body = {"id": "req_replay", "email": "[email protected]", **self._assertion_body()}
diff --git a/ee/api/agentic_provisioning/test/test_provisioning_auth.py b/ee/api/agentic_provisioning/test/test_provisioning_auth.py
index a2fb1bb53c4e..e1e0b27c73e4 100644
--- a/ee/api/agentic_provisioning/test/test_provisioning_auth.py
+++ b/ee/api/agentic_provisioning/test/test_provisioning_auth.py
@@ -1,9 +1,14 @@
import json
+from contextlib import nullcontext
+from datetime import UTC, datetime, timedelta
from ipaddress import ip_address
+import time_machine
from unittest.mock import MagicMock, patch
+from django.conf import settings
from django.core.cache import cache as real_cache
+from django.test import override_settings
from parameterized import parameterized
from rest_framework.parsers import JSONParser
@@ -11,13 +16,19 @@ from rest_framework.request import Request
from rest_framework.test import APIRequestFactory
from posthog.api.oauth.cimd import _cache_key, fetch_and_upsert_cimd_application
+from posthog.api.oauth.client_assertion import PRIVATE_KEY_REQUIRED_MESSAGE
from posthog.models.activity_logging.utils import ActivityCredential, activity_storage
from posthog.models.oauth import OAuthApplication
from posthog.models.personal_api_key import PersonalAPIKey
from posthog.models.user import User
from ee.api.agentic_provisioning.authentication import ProvisioningAuthentication
-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,
+ provisioning_config,
+ signing_required,
+)
WIZARD_CLIENT_ID = "test-wizard-client"
@@ -314,15 +325,27 @@ class TestProvisioningAuthentication(ProvisioningTestBase):
res = self._post_with_bearer("/api/agentic/provisioning/resources", {}, token=token)
assert res.status_code == 401
- # --- can_provision_resources enforcement ---
+ # --- partner config changes apply to tokens minted before them ---
- def test_partner_without_can_provision_resources_rejected(self):
+ @parameterized.expand(
+ [
+ ("cannot_provision_resources", {"can_provision_resources": False}, False, 403),
+ ("grace_ended_without_a_private_key", {}, True, 401),
+ # The Wizard's production shape: a client secret, and no account creation.
+ ("grace_ended_for_a_partner_that_cannot_create_accounts", {"can_create_accounts": False}, True, 200),
+ ]
+ )
+ def test_bearer_after_partner_changes(
+ self, _name: str, change: dict[str, bool], grace_ended: bool, expected_status: int
+ ) -> None:
token = self._get_bearer_token()
- self.partner.update_provisioning(can_provision_resources=False)
+ if change:
+ self.partner.update_provisioning(**change)
- res = self._post_with_bearer("/api/agentic/provisioning/resources", {}, token=token)
- assert res.status_code == 403
+ with signing_required() if grace_ended else nullcontext():
+ res = self._post_with_bearer("/api/agentic/provisioning/resources", {}, token=token)
+ assert res.status_code == expected_status
# --- CIMD URL-based PKCE identification ---
@@ -443,6 +466,115 @@ class TestProvisioningAuthentication(ProvisioningTestBase):
assert "S256" in res.json()["error"]["message"]
+@override_settings(
+ PROVISIONING_SIGNING_REQUIRED_SINCE=datetime(2026, 10, 15, tzinfo=UTC),
+ PROVISIONING_UNSIGNED_GRACE_UNTIL=datetime(2026, 10, 21, 16, tzinfo=UTC),
+)
+class TestUnsignedProvisioningGrace(ProvisioningTestBase):
+ def _public_partner(
+ self, *, client_id: str = "grace-public-partner", capabilities: dict[str, bool] | None = None
+ ) -> OAuthApplication:
+ return OAuthApplication.objects.create(
+ client_id=client_id,
+ name="Grace partner",
+ client_type=OAuthApplication.CLIENT_PUBLIC,
+ authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,
+ redirect_uris="https://partner.example.com/callback",
+ algorithm="RS256",
+ is_provisioning_partner=True,
+ _provisioning_config=provisioning_config(**(capabilities or {})),
+ )
+
+ def _account_request(self, partner: OAuthApplication, email: str):
+ _, challenge = self._pkce_pair()
+ with patch("ee.api.agentic_provisioning.authentication.capture_auth_event") as capture_auth_event:
+ res = self._post_api(
+ "/api/agentic/provisioning/account_requests",
+ {
+ "id": f"req_{email}",
+ "email": email,
+ "code_challenge": challenge,
+ "code_challenge_method": "S256",
+ "client_id": partner.client_id,
+ },
+ )
+ signing = capture_auth_event.call_args.kwargs.get("provisioning_signing") if capture_auth_event.called else None
+ return res, signing
+
+ def _assert_refused(self, res, email: str) -> None:
+ assert res.status_code == 401, res.json()
+ assert res.json()["error"] == {"code": "unauthorized", "message": PRIVATE_KEY_REQUIRED_MESSAGE}
+ assert not User.objects.filter(email=email).exists()
+
+ @parameterized.expand(
+ [
+ ("before_the_cutoff", timedelta(seconds=-1), "unsigned_grace"),
+ ("after_the_cutoff", timedelta(seconds=1), "refused"),
+ ]
+ )
+ def test_partner_that_predates_the_requirement_calls_unsigned_until_the_cutoff(
+ self, name: str, offset: timedelta, expected_signing: str
+ ) -> None:
+ with time_machine.travel(settings.PROVISIONING_SIGNING_REQUIRED_SINCE - timedelta(days=1), tick=False):
+ partner = self._public_partner()
+ email = f"grace-{name}@example.com"
+
+ with time_machine.travel(settings.PROVISIONING_UNSIGNED_GRACE_UNTIL + offset, tick=False):
+ res, signing = self._account_request(partner, email)
+
+ assert signing == expected_signing
+ if expected_signing == "refused":
+ self._assert_refused(res, email)
+ else:
+ assert res.status_code == 200, res.json()
+
+ @parameterized.expand(
+ [
+ ("creates_accounts", {}, 401, "refused"),
+ ("pays_for_customers", {"can_create_accounts": False, "pays_for_customers": True}, 401, "refused"),
+ # Not asked to sign, so it gets past authentication to the capability check.
+ ("neither", {"can_create_accounts": False}, 403, "unsigned_exempt"),
+ ]
+ )
+ def test_partner_created_after_the_requirement_signs_from_its_first_request(
+ self, name: str, capabilities: dict[str, bool], expected_status: int, expected_signing: str
+ ) -> None:
+ email = f"new-partner-{name}@example.com"
+ with time_machine.travel(settings.PROVISIONING_SIGNING_REQUIRED_SINCE + timedelta(hours=1), tick=False):
+ partner = self._public_partner(capabilities=capabilities)
+ res, signing = self._account_request(partner, email)
+
+ assert signing == expected_signing
+ if expected_status == 401:
+ self._assert_refused(res, email)
+ else:
+ assert res.status_code == expected_status, res.json()
+ assert res.json()["error"]["code"] == "forbidden"
+
+ @parameterized.expand(
+ [
+ ("predates_the_requirement", timedelta(days=-1)),
+ ("created_after_the_requirement", timedelta(hours=1)),
+ ]
+ )
+ def test_override_extends_one_partners_grace(self, _name: str, created_relative_to_requirement: timedelta) -> None:
+ created_at = settings.PROVISIONING_SIGNING_REQUIRED_SINCE + created_relative_to_requirement
+ with time_machine.travel(created_at, tick=False):
+ extended = self._public_partner()
+ other = self._public_partner(client_id="grace-other-partner")
+ extended.update_provisioning(
+ unsigned_allowed_until=settings.PROVISIONING_UNSIGNED_GRACE_UNTIL + timedelta(days=7)
+ )
+
+ with time_machine.travel(settings.PROVISIONING_UNSIGNED_GRACE_UNTIL + timedelta(days=1), tick=False):
+ extended_res, extended_signing = self._account_request(extended, "[email protected]")
+ other_res, _ = self._account_request(other, "[email protected]")
+
+ assert extended_res.status_code == 200, extended_res.json()
+ assert extended_signing == "unsigned_grace"
+ self._assert_refused(other_res, "[email protected]")
+
+
CIMD_PROV_URL = "https://partner.example.com/.well-known/oauth-client-metadata.json"
diff --git a/ee/api/agentic_provisioning/views/client_registration.py b/ee/api/agentic_provisioning/views/client_registration.py
index 47dffb6724ed..d200d3254ae6 100644
--- a/ee/api/agentic_provisioning/views/client_registration.py
+++ b/ee/api/agentic_provisioning/views/client_registration.py
@@ -31,8 +31,13 @@ from posthog.api.oauth.cimd import (
fetch_and_upsert_cimd_application,
is_cimd_client_id,
)
-from posthog.api.oauth.client_assertion import ClientAssertionError, describe_jwks, verify_client_assertion
-from posthog.models.oauth import OAuthApplication
+from posthog.api.oauth.client_assertion import (
+ PRIVATE_KEY_REQUIRED_MESSAGE,
+ ClientAssertionError,
+ describe_jwks,
+ verify_client_assertion,
+)
+from posthog.models.oauth import OAuthApplication, ProvisioningSigning
from ee.api.agentic_provisioning.analytics import capture_provisioning_event
from ee.api.agentic_provisioning.exceptions import ProvisioningError
@@ -85,7 +90,11 @@ class ClientRegistrationView(ProvisioningAPIView):
"can_provision_resources": app.provisioning.can_provision_resources,
},
"capabilities": {
- "account_requests": app.provisioning.active and app.provisioning.can_create_accounts,
+ "account_requests": app.provisioning.active
+ and app.provisioning.can_create_accounts
+ and not app.cannot_meet_provisioning_signature,
+ "unsigned_requests": not app.requires_provisioning_signature,
+ "unsigned_requests_allowed_until": _unsigned_requests_allowed_until(app),
},
"checks": checks,
}
@@ -143,6 +152,21 @@ class ClientRegistrationView(ProvisioningAPIView):
return app
def _check_jwks(self, app: OAuthApplication, checks: list[dict[str, Any]]) -> None:
+ if not app.uses_private_key_jwt_auth:
+ signing = app.provisioning_signing
+ if signing is ProvisioningSigning.REQUIRED:
+ _record(checks, "jwks", False, PRIVATE_KEY_REQUIRED_MESSAGE)
+ return
+ if signing is ProvisioningSigning.GRACE:
+ _record(
+ checks,
+ "jwks",
+ True,
+ f"Unsigned requests allowed until {_unsigned_requests_allowed_until(app)}. "
+ f"{PRIVATE_KEY_REQUIRED_MESSAGE}",
+ )
+ return
+
if not app.jwks_uri:
# Not a failure: a public client legitimately publishes no keys. Reported so the
# response says which of the two situations the caller is in.
@@ -197,6 +221,13 @@ def _not_a_partner_detail(app: OAuthApplication, *, document_read: bool) -> str:
return "This client is not enabled for agentic provisioning"
+def _unsigned_requests_allowed_until(app: OAuthApplication) -> str | None:
+ allowed_until = app.provisioning_unsigned_allowed_until
+ if allowed_until is None or app.provisioning_signing is not ProvisioningSigning.GRACE:
+ return None
+ return allowed_until.isoformat()
+
+
def _record(checks: list[dict[str, Any]], name: str, ok: bool, detail: str) -> None:
checks.append({"name": name, "ok": ok, "detail": detail})
diff --git a/ee/api/agentic_provisioning/views/limits.py b/ee/api/agentic_provisioning/views/limits.py
index d7bbb4af61ff..d73ea579bbe5 100644
--- a/ee/api/agentic_provisioning/views/limits.py
+++ b/ee/api/agentic_provisioning/views/limits.py
@@ -17,11 +17,13 @@ from rest_framework.exceptions import AuthenticationFailed
from rest_framework.request import Request
from rest_framework.response import Response
+from posthog.api.oauth.client_assertion import PRIVATE_KEY_REQUIRED_MESSAGE
from posthog.models.oauth import OAuthApplication
from ee.api.agentic_provisioning.authentication import (
CLIENT_NOT_REGISTERED_MESSAGE,
BearerTokenError,
+ ClientProof,
ProvisioningAuthentication,
resolve_bearer_access_token,
)
@@ -64,18 +66,20 @@ class LimitsView(ProvisioningAPIView):
raise ProvisioningError("unauthorized", "Authentication failed", status=401)
if not app.provisioning.active:
raise ProvisioningError("unauthorized", "Partner is deactivated", status=401)
+ if app.cannot_meet_provisioning_signature:
+ raise ProvisioningError("unauthorized", PRIVATE_KEY_REQUIRED_MESSAGE, status=401)
return app
+ authentication = ProvisioningAuthentication()
try:
- result = ProvisioningAuthentication().authenticate(request)
+ result = authentication.authenticate(request)
except AuthenticationFailed as exc:
raise ProvisioningError("unauthorized", str(exc.detail), status=401)
if result is None:
raise ProvisioningError("unauthorized", CLIENT_NOT_REGISTERED_MESSAGE, status=401)
- partner = result[1]
- # A public partner presents a client_id anyone can send, which identifies it
- # without proving the caller is it. Its bearer does.
- if not partner.requires_client_authentication:
+ # A client_id anyone can send identifies the partner without proving the caller is it.
+ # Its bearer does.
+ if authentication.client_proof is ClientProof.CLIENT_ID:
raise ProvisioningError("unauthorized", "This client must authenticate with a bearer token", status=401)
- return partner
+ return result[1]
diff --git a/ee/api/agentic_provisioning/views/oauth_token.py b/ee/api/agentic_provisioning/views/oauth_token.py
index d38c8f113bd5..3087eedbbb9d 100644
--- a/ee/api/agentic_provisioning/views/oauth_token.py
+++ b/ee/api/agentic_provisioning/views/oauth_token.py
@@ -21,9 +21,16 @@ import structlog
from rest_framework.request import Request
from rest_framework.response import Response
-from posthog.api.oauth.client_assertion import ClientAssertionError, extract_client_assertion, verify_client_assertion
+from posthog.api.oauth.client_assertion import (
+ PRIVATE_KEY_REQUIRED_MESSAGE,
+ UNREADABLE_CLIENT_ASSERTION_MESSAGE,
+ ClientAssertionError,
+ extract_client_assertion,
+ presents_client_assertion,
+ verify_client_assertion,
+)
from posthog.api.oauth.client_auth import extract_client_credentials, verify_client_secret
-from posthog.models.oauth import OAuthAccessToken, OAuthApplication, OAuthRefreshToken
+from posthog.models.oauth import OAuthAccessToken, OAuthApplication, OAuthRefreshToken, ProvisioningSigning
from posthog.models.user import User
from posthog.models.utils import generate_random_oauth_access_token, generate_random_oauth_refresh_token
from posthog.scopes import narrow_scopes_to_ceiling, scopes_within_ceiling
@@ -47,20 +54,33 @@ from ee.api.agentic_provisioning.views.base import ProvisioningAPIView
logger = structlog.get_logger(__name__)
-def _require_client_authentication(request: Request, oauth_app: OAuthApplication, grant_type: str) -> None:
- """Make confidential partners prove themselves before their grant is spent.
+def _require_client_authentication(request: Request, oauth_app: OAuthApplication, grant_type: str) -> str:
+ """Make confidential partners, and partners that must sign, prove themselves before their grant is spent.
Public partners keep ``code_verifier`` as their only client authentication, which is what
- RFC 7636 prescribes and RFC 6749 section 3.2.1 expects. The app is resolved from the grant
- rather than from a caller-supplied client_id, so a confidential partner cannot reach the
- public path by presenting nothing.
+ RFC 7636 prescribes and RFC 6749 section 3.2.1 expects, unless they must sign: see
+ ``OAuthApplication.provisioning_signing``. The app is resolved from the grant rather than
+ from a caller-supplied client_id, so a confidential partner cannot reach the public path by
+ presenting nothing. Returns the request's signing tag for analytics.
"""
- if not oauth_app.requires_client_authentication:
- return
-
+ signing = oauth_app.provisioning_signing
if oauth_app.uses_private_key_jwt_auth:
_verify_assertion_or_fail(request, oauth_app, grant_type)
- return
+ return signing.request_tag(signed=True)
+
+ signing_tag = signing.request_tag(signed=False)
+ if signing is ProvisioningSigning.REQUIRED:
+ capture_provisioning_event(
+ "token_exchange",
+ "private_key_required",
+ partner=oauth_app,
+ grant_type=grant_type,
+ provisioning_signing=signing_tag,
+ )
+ raise ProvisioningError("invalid_client", PRIVATE_KEY_REQUIRED_MESSAGE, status=401)
+
+ if not oauth_app.uses_client_secret_auth:
+ return signing_tag
credentials = extract_client_credentials(request)
if credentials is None:
@@ -76,15 +96,24 @@ def _require_client_authentication(request: Request, oauth_app: OAuthApplication
"token_exchange", "invalid_client_credentials", partner=oauth_app, grant_type=grant_type
)
raise ProvisioningError("invalid_client", "Invalid client credentials", status=401)
+ return signing_tag
def _verify_assertion_or_fail(request: Request, oauth_app: OAuthApplication, grant_type: str) -> None:
assertion = extract_client_assertion(request)
if assertion is None:
+ presented = presents_client_assertion(request)
capture_provisioning_event(
- "token_exchange", "missing_client_assertion", partner=oauth_app, grant_type=grant_type
+ "token_exchange",
+ "unreadable_client_assertion" if presented else "missing_client_assertion",
+ partner=oauth_app,
+ grant_type=grant_type,
+ )
+ raise ProvisioningError(
+ "invalid_client",
+ UNREADABLE_CLIENT_ASSERTION_MESSAGE if presented else "A client_assertion is required",
+ status=401,
)
- raise ProvisioningError("invalid_client", "A client_assertion is required", status=401)
# The assertion is verified against the app the grant names, so an assertion validly
# signed by a different client cannot be used to redeem this one's grant.
@@ -174,7 +203,7 @@ class OAuthTokenView(ProvisioningAPIView):
capture_provisioning_event("token_exchange", "oauth_app_missing", grant_type="authorization_code")
raise ProvisioningError("invalid_grant", "Unknown application for this authorization code")
- _require_client_authentication(request, oauth_app, "authorization_code")
+ signing_tag = _require_client_authentication(request, oauth_app, "authorization_code")
# Consume the code before rate limiting so a leaked auth code can't be replayed
# to burn the partner's bucket. Auth codes are single-use by spec, so the
@@ -273,6 +302,7 @@ class OAuthTokenView(ProvisioningAPIView):
team_id=team_id,
user_id=user.id,
granted_team_count=len(scoped_teams),
+ provisioning_signing=signing_tag,
)
return Response(
@@ -305,10 +335,11 @@ class OAuthTokenView(ProvisioningAPIView):
.values_list("application_id", flat=True)
.first()
)
+ signing_tag: str | None = None
if application_id:
unlocked_app = OAuthApplication.objects.filter(id=application_id).first()
if unlocked_app is not None:
- _require_client_authentication(request, unlocked_app, "refresh_token")
+ signing_tag = _require_client_authentication(request, unlocked_app, "refresh_token")
# Lock the app row first (revoke_application_sessions locks it before sweeping tokens),
# then re-read the refresh token under that lock, so the rotate-and-mint serializes with
@@ -426,6 +457,7 @@ class OAuthTokenView(ProvisioningAPIView):
team_id=base_team_id,
user_id=user.id if user else None,
granted_team_count=len(scoped_teams),
+ provisioning_signing=signing_tag,
)
return Response(
diff --git a/posthog/admin/admins/oauth_admin.py b/posthog/admin/admins/oauth_admin.py
index 3559a3532bd6..51fd35908654 100644
--- a/posthog/admin/admins/oauth_admin.py
+++ b/posthog/admin/admins/oauth_admin.py
@@ -8,6 +8,7 @@ from django import forms
from django.contrib import admin, messages
from django.contrib.admin import helpers
from django.template.response import TemplateResponse
+from django.utils import timezone
from django.utils.html import format_html
from oauth2_provider.generators import generate_client_id, generate_client_secret
@@ -15,7 +16,7 @@ from oauth2_provider.models import AbstractApplication
from posthog.api.oauth.cimd import is_cimd_client_id
from posthog.models.oauth import OAuthApplication, revoke_application_sessions
-from posthog.models.oauth_provisioning import UNLIMITED_OVERRIDE, ProvisioningConfig
+from posthog.models.oauth_provisioning import PROVISIONING_CAPABILITIES, UNLIMITED_OVERRIDE, ProvisioningConfig
# The provisioning config is one JSONB column, but an operator should still get the checkboxes
# they had when it was a column each: a raw JSON textarea turns a mistyped capability key into
@@ -23,18 +24,27 @@ from posthog.models.oauth_provisioning import UNLIMITED_OVERRIDE, ProvisioningCo
# Derived from the pydantic schema so a capability added there shows up here automatically.
PROVISIONING_FIELD_PREFIX = "provisioning_"
PROVISIONING_RATE_LIMIT_PREFIX = "provisioning_rate_limit_"
+UNSIGNED_ALLOWED_UNTIL_FIELD = f"{PROVISIONING_FIELD_PREFIX}unsigned_allowed_until"
+SIGNING_CAPABILITY_FIELDS = tuple(
+ f"{PROVISIONING_FIELD_PREFIX}{name}" for name in ("pays_for_customers", "can_create_accounts")
+)
def _provisioning_form_fields() -> dict[str, forms.Field]:
- """One form field per capability. Rate-limit override fields are generated
- per request in ``get_form`` from the endpoint registry."""
+ """One form field per capability, plus the unsigned-requests deadline. Rate-limit
+ override fields are generated per request in ``get_form`` from the endpoint registry."""
fields: dict[str, forms.Field] = {}
- for name, info in ProvisioningConfig.model_fields.items():
- if name == "rate_limits":
- continue
+ for name in PROVISIONING_CAPABILITIES:
fields[f"{PROVISIONING_FIELD_PREFIX}{name}"] = forms.BooleanField(
- required=False, label=name.replace("_", " "), help_text=info.description or ""
+ required=False,
+ label=name.replace("_", " "),
+ help_text=ProvisioningConfig.model_fields[name].description or "",
)
+ fields[UNSIGNED_ALLOWED_UNTIL_FIELD] = forms.DateTimeField(
+ required=False,
+ label="unsigned allowed until",
+ help_text=ProvisioningConfig.model_fields["unsigned_allowed_until"].description or "",
+ )
return fields
@@ -108,10 +118,9 @@ class OAuthApplicationForm(forms.ModelForm):
def _load_provisioning_initial(self) -> None:
config = self.instance.provisioning if self.instance.pk else ProvisioningConfig()
- for name in ProvisioningConfig.model_fields:
- if name == "rate_limits":
- continue
+ for name in PROVISIONING_CAPABILITIES:
self.fields[f"{PROVISIONING_FIELD_PREFIX}{name}"].initial = getattr(config, name)
+ self.fields[UNSIGNED_ALLOWED_UNTIL_FIELD].initial = config.unsigned_allowed_until
for field_name in self._rate_limit_field_names():
endpoint = field_name.removeprefix(PROVISIONING_RATE_LIMIT_PREFIX)
self.fields[field_name].initial = config.rate_limits.get(endpoint)
@@ -133,9 +142,56 @@ class OAuthApplicationForm(forms.ModelForm):
"themselves. Use the generated value, or an ID that is not a URL.",
)
+ def _provisioning_after_save(self, cleaned: dict) -> ProvisioningConfig:
+ # Built while self.instance still holds the stored row, which is the only point the promotion is visible.
+ before = self.instance
+ promoted = not before.is_provisioning_partner and cleaned.get(
+ "is_provisioning_partner", before.is_provisioning_partner
+ )
+ return ProvisioningConfig(
+ **{name: bool(cleaned.get(f"{PROVISIONING_FIELD_PREFIX}{name}")) for name in PROVISIONING_CAPABILITIES},
+ rate_limits={
+ field_name.removeprefix(PROVISIONING_RATE_LIMIT_PREFIX): value
+ for field_name in self._rate_limit_field_names()
+ if (value := cleaned.get(field_name)) is not None
+ },
+ unsigned_allowed_until=cleaned.get(UNSIGNED_ALLOWED_UNTIL_FIELD),
+ partner_since=timezone.now() if promoted else before.provisioning.partner_since,
+ )
+
+ def _reject_partner_that_cannot_sign(self, cleaned: dict, provisioning: ProvisioningConfig) -> None:
+ """Keep a provisioning partner that has to sign from being set up without a key to sign with.
+
+ Provisioning auth refuses every request from such a partner. Only the edit that creates the
+ combination is refused: a partner already in it, such as a CIMD client whose metadata dropped
+ its key, stays editable, so staff can still switch it off without unticking a capability.
+ An app that is not a provisioning partner never authenticates through provisioning auth, which
+ leaves the HMAC-signed Stripe Projects app free to pay.
+ """
+ before = self.instance
+ after = OAuthApplication(
+ created=before.created,
+ is_provisioning_partner=cleaned.get("is_provisioning_partner", before.is_provisioning_partner),
+ client_type=cleaned.get("client_type", before.client_type),
+ jwks_uri=cleaned.get("jwks_uri", before.jwks_uri),
+ )
+ after.provisioning = provisioning
+ if not after.cannot_meet_provisioning_signature or before.cannot_meet_provisioning_signature:
+ return
+ for field_name in SIGNING_CAPABILITY_FIELDS:
+ if cleaned.get(field_name):
+ self.add_error(
+ field_name,
+ "A provisioning partner that can create accounts or pays for its customers must sign its "
+ "requests with a private key. Make it a confidential client with a jwks_uri first, or set "
+ "a date it may send unsigned requests until.",
+ )
+
def clean(self):
cleaned = super().clean() or {}
self._reject_cimd_shaped_client_id(cleaned)
+ self.provisioning_after_save = self._provisioning_after_save(cleaned)
+ self._reject_partner_that_cannot_sign(cleaned, self.provisioning_after_save)
for field_name in self._rate_limit_field_names():
# 0 is rejected rather than meaning "unlimited": that footgun is why the
# unlimited sentinel is -1 (UNLIMITED_OVERRIDE).
@@ -145,19 +201,7 @@ class OAuthApplicationForm(forms.ModelForm):
def save(self, commit: bool = True):
instance = super().save(commit=False)
-
- capabilities = {
- name: self.cleaned_data[f"{PROVISIONING_FIELD_PREFIX}{name}"]
- for name in ProvisioningConfig.model_fields
- if name != "rate_limits"
- }
- rate_limits = {
- field_name.removeprefix(PROVISIONING_RATE_LIMIT_PREFIX): value
- for field_name in self._rate_limit_field_names()
- if (value := self.cleaned_data.get(field_name)) is not None
- }
-
- instance.provisioning = ProvisioningConfig(**capabilities, rate_limits=rate_limits)
+ instance.provisioning = self.provisioning_after_save
if commit:
instance.save()
@@ -172,6 +216,20 @@ for _field_name, _form_field in _provisioning_form_fields().items():
OAuthApplicationForm.base_fields[_field_name] = _form_field
+class UnsignedProvisioningDeadlineForm(forms.Form):
+ unsigned_allowed_until = forms.DateTimeField(
+ label="Allow unsigned requests until",
+ help_text="In UTC, for example 2026-11-02 16:00. Replaces the shared grace period for the selected partners.",
+ )
+
+ def clean_unsigned_allowed_until(self):
+ value = self.cleaned_data["unsigned_allowed_until"]
+ # A past date would end the partner's grace at once, which is not what this action is for.
+ if value <= timezone.now():
+ raise forms.ValidationError("Choose a date in the future.")
+ return value
+
+
class ProvisioningCapabilityFilter(admin.SimpleListFilter):
"""Filter partners by a granted capability.
@@ -184,11 +242,11 @@ class ProvisioningCapabilityFilter(admin.SimpleListFilter):
parameter_name = "provisioning_capability"
def lookups(self, request, model_admin):
- return [(name, name.replace("_", " ")) for name in ProvisioningConfig.model_fields if name != "rate_limits"]
+ return [(name, name.replace("_", " ")) for name in PROVISIONING_CAPABILITIES]
def queryset(self, request, queryset):
capability = self.value()
- if not capability or capability not in ProvisioningConfig.model_fields:
+ if not capability or capability not in PROVISIONING_CAPABILITIES:
return queryset
# nosemgrep: orm-field-injection -- capability is allowlisted above, and the JSONField prefix keeps any __ as a JSON key lookup
return queryset.filter(**{f"_provisioning_config__{capability}": True})
@@ -223,7 +281,7 @@ class OAuthApplicationAdmin(admin.ModelAdmin): # nosemgrep: admin-modeladmin-ne
search_fields = ("name", "client_id", "user__email", "organization__name")
autocomplete_fields = ("user", "organization")
ordering = ("name",)
- actions = ("revoke_all_sessions", "regenerate_client_secret")
+ actions = ("revoke_all_sessions", "regenerate_client_secret", "allow_unsigned_provisioning_until")
@admin.action(description="Generate a new client secret")
def regenerate_client_secret(self, request, queryset):
@@ -273,6 +331,38 @@ class OAuthApplicationAdmin(admin.ModelAdmin): # nosemgrep: admin-modeladmin-ne
}
return TemplateResponse(request, "admin/posthog/oauthapplication/revoke_all_sessions_confirm.html", context)
+ @admin.action(description="Allow unsigned provisioning requests until a date")
+ def allow_unsigned_provisioning_until(self, request, queryset):
+ form = UnsignedProvisioningDeadlineForm(request.POST if request.POST.get("apply") else None)
+ if form.is_valid():
+ until = form.cleaned_data["unsigned_allowed_until"]
+ updated = 0
+ for application in queryset:
+ if not application.is_provisioning_partner:
+ self.message_user(
+ request,
+ f"{application.name}: skipped, it is not a provisioning partner.",
+ level=messages.ERROR,
+ )
+ continue
+ application.update_provisioning(unsigned_allowed_until=until)
+ updated += 1
+ self.message_user(
+ request, f"{updated} partner(s) may send unsigned provisioning requests until {until.isoformat()}."
+ )
+ return None
+ context = {
+ **self.admin_site.each_context(request),
+ "title": "Allow unsigned provisioning requests until a date",
+ "form": form,
+ "queryset": queryset,
+ "opts": self.model._meta,
+ "action_checkbox_name": helpers.ACTION_CHECKBOX_NAME,
+ }
+ return TemplateResponse(
+ request, "admin/posthog/oauthapplication/allow_unsigned_provisioning_until.html", context
+ )
+
def view_on_site(self, obj: OAuthApplication):
code_verifier = "test"
digest = hashlib.sha256(code_verifier.encode("utf-8")).digest()
diff --git a/posthog/admin/test_oauth_admin.py b/posthog/admin/test_oauth_admin.py
index 579119b2e0c5..52eb9cf19f5b 100644
--- a/posthog/admin/test_oauth_admin.py
+++ b/posthog/admin/test_oauth_admin.py
@@ -1,4 +1,4 @@
-from datetime import timedelta
+from datetime import UTC, datetime, timedelta
import time_machine
from posthog.test.base import BaseTest
@@ -6,15 +6,19 @@ from unittest.mock import patch
from django.contrib.admin import AdminSite
from django.contrib.auth.hashers import check_password
-from django.test import RequestFactory
+from django.test import RequestFactory, override_settings
from django.utils import timezone
from parameterized import parameterized
from posthog.admin.admins.oauth_admin import OAuthApplicationAdmin
-from posthog.models.oauth import OAuthAccessToken, OAuthApplication, OAuthRefreshToken
+from posthog.models.oauth import OAuthAccessToken, OAuthApplication, OAuthRefreshToken, ProvisioningSigning
+LONG_AGO = datetime(2000, 1, 1, tzinfo=UTC)
+
+# Every app a test creates is past its grace period, whatever the real date, unless the test says otherwise.
+@override_settings(PROVISIONING_SIGNING_REQUIRED_SINCE=LONG_AGO, PROVISIONING_UNSIGNED_GRACE_UNTIL=LONG_AGO)
class TestOAuthApplicationAdmin(BaseTest):
def setUp(self):
super().setUp()
@@ -93,6 +97,191 @@ class TestOAuthApplicationAdmin(BaseTest):
app.refresh_from_db()
assert app.provisioning.rate_limits == {"account_requests": -1}
+ @parameterized.expand(
+ [
+ ("public_partner_pays", OAuthApplication.CLIENT_PUBLIC, None, True, {}, "pays_for_customers", True),
+ (
+ "client_secret_partner_pays",
+ OAuthApplication.CLIENT_CONFIDENTIAL,
+ None,
+ True,
+ {},
+ "pays_for_customers",
+ True,
+ ),
+ (
+ "public_partner_creates_accounts",
+ OAuthApplication.CLIENT_PUBLIC,
+ None,
+ True,
+ {},
+ "can_create_accounts",
+ True,
+ ),
+ (
+ "private_key_jwt_partner",
+ OAuthApplication.CLIENT_CONFIDENTIAL,
+ "https://example.com/.well-known/jwks.json",
+ True,
+ {},
+ "pays_for_customers",
+ False,
+ ),
+ # Never authenticates through provisioning auth, like the HMAC-signed Stripe Projects app.
+ (
+ "not_a_provisioning_partner",
+ OAuthApplication.CLIENT_CONFIDENTIAL,
+ None,
+ False,
+ {},
+ "pays_for_customers",
+ False,
+ ),
+ # Already refused at runtime, like a CIMD partner whose metadata dropped its key. Staff must
+ # still be able to save it, for example to switch it off.
+ (
+ "already_paying_without_a_key",
+ OAuthApplication.CLIENT_PUBLIC,
+ None,
+ True,
+ {"pays_for_customers": True},
+ "pays_for_customers",
+ False,
+ ),
+ (
+ "public_partner_with_a_later_unsigned_deadline",
+ OAuthApplication.CLIENT_PUBLIC,
+ None,
+ True,
+ {"unsigned_allowed_until": "2100-01-01T00:00:00+00:00"},
+ "pays_for_customers",
+ False,
+ ),
+ ]
+ )
+ def test_partner_that_must_sign_needs_a_private_key(
+ self,
+ name: str,
+ client_type: str,
+ jwks_uri: str | None,
+ is_partner: bool,
+ stored_config: dict,
+ ticked_capability: str,
+ expects_error: bool,
+ ) -> None:
+ app = OAuthApplication.objects.create(
+ name=f"Signing App {name}",
+ client_id=f"signing_client_id_{name}",
+ client_secret="secret",
+ client_type=client_type,
+ jwks_uri=jwks_uri,
+ authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,
+ redirect_uris="https://example.com/callback",
+ algorithm="RS256",
+ is_provisioning_partner=is_partner,
+ _provisioning_config=stored_config,
+ )
+ fields = {f"provisioning_{ticked_capability}": "on"}
+ if is_partner:
+ fields["is_provisioning_partner"] = "on"
+ if jwks_uri:
+ fields["jwks_uri"] = jwks_uri
+ if deadline := stored_config.get("unsigned_allowed_until"):
+ fields["provisioning_unsigned_allowed_until"] = deadline
+
+ form = self._provisioning_form(app, **fields)
+
+ assert form.is_valid() is not expects_error, form.errors
+ assert (f"provisioning_{ticked_capability}" in form.errors) is expects_error
+
+ def test_saving_the_form_keeps_the_signing_dates(self):
+ app = self._rate_limit_app()
+ partner_since = datetime(2026, 10, 16, tzinfo=UTC)
+ app.update_provisioning(unsigned_allowed_until=datetime(2100, 1, 1, tzinfo=UTC), partner_since=partner_since)
+
+ form = self._provisioning_form(app, provisioning_unsigned_allowed_until="2100-01-01 00:00:00")
+ assert form.is_valid(), form.errors
+ form.save()
+
+ app.refresh_from_db()
+ assert app.provisioning.unsigned_allowed_until == datetime(2100, 1, 1, tzinfo=UTC)
+ assert app.provisioning.partner_since == partner_since
+
+ def _signing_partner(self, client_id: str, **overrides) -> OAuthApplication:
+ return OAuthApplication.objects.create(
+ name=f"Signing Partner {client_id}",
+ client_id=client_id,
+ client_type=OAuthApplication.CLIENT_PUBLIC,
+ authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,
+ redirect_uris="https://example.com/callback",
+ algorithm="RS256",
+ **{"is_provisioning_partner": True, "_provisioning_config": {"can_create_accounts": True}, **overrides},
+ )
+
+ @parameterized.expand([("already_a_partner", True, False), ("promoted_by_this_edit", False, True)])
+ def test_old_app_promoted_to_partner_must_sign_from_the_promotion(
+ self, _name: str, already_a_partner: bool, expects_error: bool
+ ) -> None:
+ app = self._signing_partner("promoted_old_app", is_provisioning_partner=already_a_partner)
+ OAuthApplication.objects.filter(pk=app.pk).update(created=datetime(2001, 1, 1, tzinfo=UTC))
+ app.refresh_from_db()
+
+ with override_settings(
+ PROVISIONING_SIGNING_REQUIRED_SINCE=datetime(2002, 1, 1, tzinfo=UTC),
+ PROVISIONING_UNSIGNED_GRACE_UNTIL=datetime(2100, 1, 1, tzinfo=UTC),
+ ):
+ form = self._provisioning_form(
+ app, is_provisioning_partner="on", provisioning_active="on", provisioning_can_create_accounts="on"
+ )
+ assert form.is_valid() is not expects_error, form.errors
+
+ assert ("provisioning_can_create_accounts" in form.errors) is expects_error
+
+ def test_allow_unsigned_action_extends_the_selected_partners_grace(self):
+ selected = self._signing_partner("allow_unsigned_selected")
+ not_selected = self._signing_partner("allow_unsigned_not_selected")
+ not_a_partner = self._signing_partner("allow_unsigned_not_a_partner", is_provisioning_partner=False)
+ until = datetime(2100, 1, 8, 12, 0, tzinfo=UTC)
+
+ request = RequestFactory().post(
+ "/", {"apply": "yes", "unsigned_allowed_until": until.strftime("%Y-%m-%d %H:%M:%S")}
+ )
+ with patch.object(self.admin, "message_user"):
+ response = self.admin.allow_unsigned_provisioning_until(
+ request=request, queryset=OAuthApplication.objects.filter(id__in=[selected.id, not_a_partner.id])
+ )
+
+ assert response is None
+ for app in (selected, not_selected, not_a_partner):
+ app.refresh_from_db()
+ assert selected.provisioning.unsigned_allowed_until == until.replace(microsecond=0)
+ assert selected.provisioning_signing is ProvisioningSigning.GRACE
+ assert not_selected.provisioning_signing is ProvisioningSigning.REQUIRED
+ assert not_a_partner.provisioning.unsigned_allowed_until is None
+
+ @parameterized.expand(
+ [
+ ("no_date_yet", None),
+ # A past date would end the partner's grace at once.
+ ("date_in_the_past", "2001-01-01 00:00:00"),
+ ]
+ )
+ def test_allow_unsigned_action_asks_for_a_future_date(self, _name: str, until: str | None) -> None:
+ partner = self._signing_partner("allow_unsigned_needs_a_date")
+
+ self.user.is_staff = True
+ request = RequestFactory().post("/", {"apply": "yes", "unsigned_allowed_until": until} if until else {})
+ request.user = self.user
+ response = self.admin.allow_unsigned_provisioning_until(
+ request=request, queryset=OAuthApplication.objects.filter(id=partner.id)
+ )
+
+ assert response.status_code == 200
+ assert "allow_unsigned_provisioning_until.html" in response.template_name
+ assert response.context_data["form"].is_bound is bool(until)
+ partner.refresh_from_db()
+ assert partner.provisioning.unsigned_allowed_until is None
+
@parameterized.expand(
[
("client_secret", OAuthApplication.CLIENT_CONFIDENTIAL, None, True),
diff --git a/posthog/api/oauth/cimd.py b/posthog/api/oauth/cimd.py
index 26957775bcc4..59d99e91e37b 100644
--- a/posthog/api/oauth/cimd.py
+++ b/posthog/api/oauth/cimd.py
@@ -995,7 +995,12 @@ def _cimd_provisioning_defaults_for(app: OAuthApplication) -> "ProvisioningConfi
the same thing.
"""
return app.provisioning.model_copy(
- update={"active": True, "can_create_accounts": True, "can_provision_resources": True}
+ update={
+ "active": True,
+ "can_create_accounts": True,
+ "can_provision_resources": True,
+ "partner_since": timezone.now(),
+ }
)
diff --git a/posthog/api/oauth/client_assertion.py b/posthog/api/oauth/client_assertion.py
index 830f10d9d2a1..8fa74fcc3671 100644
--- a/posthog/api/oauth/client_assertion.py
+++ b/posthog/api/oauth/client_assertion.py
@@ -42,6 +42,15 @@ class ResolvedClientAssertion:
CLIENT_ASSERTION_TYPE_JWT_BEARER = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer"
+PRIVATE_KEY_REQUIRED_MESSAGE = (
+ "Set token_endpoint_auth_method to private_key_jwt and publish a jwks_uri in your client metadata, "
+ "call client_registration, then sign a client_assertion."
+)
+UNREADABLE_CLIENT_ASSERTION_MESSAGE = (
+ f"Send client_assertion_type {CLIENT_ASSERTION_TYPE_JWT_BEARER} with the client_assertion, "
+ "and name the client in client_id or the assertion's sub claim."
+)
+
# An assertion is a single-use credential presented immediately, so it needs no real
# lifetime. Capping it bounds how long a captured assertion is replayable if the jti cache
@@ -78,6 +87,10 @@ def _request_field(request: Any, name: str) -> str:
return str(from_body or "")
+def presents_client_assertion(request: Any) -> bool:
+ return bool(_request_field(request, "client_assertion"))
+
+
def extract_client_assertion(request: Any) -> ResolvedClientAssertion | None:
"""Return the client assertion and client_id a request presents, or None.
diff --git a/posthog/api/oauth/views.py b/posthog/api/oauth/views.py
index 92ee6c533e5d..1278c90cc766 100644
--- a/posthog/api/oauth/views.py
+++ b/posthog/api/oauth/views.py
@@ -34,7 +34,7 @@ from oauth2_provider.views import (
)
from oauth2_provider.views.mixins import OAuthLibMixin
from oauthlib.common import Request as OauthlibRequest
-from oauthlib.oauth2 import InvalidClientIdError, InvalidGrantError
+from oauthlib.oauth2 import InvalidClientError, InvalidClientIdError, InvalidGrantError
from redis.exceptions import RedisError
from rest_framework import serializers, status
from rest_framework.exceptions import AuthenticationFailed, NotFound
@@ -53,6 +53,7 @@ from posthog.api.oauth.cimd import (
)
from posthog.api.oauth.claims import OIDC_CLAIMS
from posthog.api.oauth.client_assertion import (
+ PRIVATE_KEY_REQUIRED_MESSAGE,
ClientAssertionError,
ResolvedClientAssertion,
expected_assertion_audiences,
@@ -252,6 +253,12 @@ def _oauth_app_event_properties(application: OAuthApplication) -> dict:
}
+def _provisioning_signing_properties(application: OAuthApplication, *, signed: bool) -> dict:
+ if not application.is_provisioning_partner:
+ return {}
+ return {"provisioning_signing": application.provisioning_signing.request_tag(signed=signed)}
+
+
def _token_error_code(response: HttpResponse) -> str:
"""RFC 6749 §5.2 error code from a token-endpoint failure, falling back to the status
code when the body isn't the documented JSON shape."""
@@ -553,9 +560,7 @@ class OAuthValidator(OAuth2Validator):
exchange, in place and with no operator involved on either side. PKCE remains the
enforced baseline for the fallback, exactly as for any public client. The
grant-type gate in ``_credentialless_cimd_private_key_jwt_client`` keeps the
- fallback off revocation, which shares this validator; the agentic provisioning
- endpoints keep requiring the declared method, and partners there demonstrably
- send assertions.
+ fallback off revocation, which shares this validator.
"""
if getattr(request, "client_assertion", None):
return True
@@ -572,6 +577,7 @@ class OAuthValidator(OAuth2Validator):
living on credential-less refresh grants would keep stale scopes and config
forever."""
if super().authenticate_client_id(request_client_id, request, *args, **kwargs):
+ self._refuse_unsigned_provisioning_partner(request)
return True
app = self._credentialless_cimd_private_key_jwt_client(request)
if app is None:
@@ -587,10 +593,9 @@ class OAuthValidator(OAuth2Validator):
authenticates or fails, and the grant-type gate excludes requests without a token
grant, which is how revocation stays on the declared method.
- Provisioning partners are excluded. They register through CIMD and declare
- private_key_jwt too, so they match this shape without needing it: they do send
- assertions, and the key is the credential their registration is built on. Including
- them would hand every partner a way to downgrade itself by sending nothing."""
+ Provisioning partners never get it. The key is the credential their registration is
+ built on, and the fallback would hand every partner a way to downgrade itself by
+ sending nothing."""
if getattr(request, "grant_type", None) not in ("authorization_code", "refresh_token"):
return None
if getattr(request, "client_assertion", None):
@@ -600,9 +605,11 @@ class OAuthValidator(OAuth2Validator):
if getattr(request, "client_secret", None):
return None
app = self._load_application(getattr(request, "client_id", None) or "", request)
- if app is not None and app.is_cimd_client and app.uses_private_key_jwt_auth:
- return None if app.is_provisioning_partner else app
- return None
+ if app is None or not app.is_cimd_client or not app.uses_private_key_jwt_auth:
+ return None
+ if app.is_provisioning_partner:
+ return None
+ return app
def authenticate_client(self, request, *args, **kwargs):
"""Authenticate a client presenting ``private_key_jwt`` (RFC 7523).
@@ -617,7 +624,20 @@ class OAuthValidator(OAuth2Validator):
"""
if self._authenticate_client_assertion(request):
return True
- return super().authenticate_client(request, *args, **kwargs)
+ if not super().authenticate_client(request, *args, **kwargs):
+ return False
+ self._refuse_unsigned_provisioning_partner(request)
+ return True
+
+ @staticmethod
+ def _refuse_unsigned_provisioning_partner(request) -> None:
+ # Only grants issue tokens. Revocation shares this validator and must keep working, so a
+ # refused partner can still kill the tokens it holds.
+ if not getattr(request, "grant_type", None):
+ return
+ client = getattr(request, "client", None)
+ if client is not None and client.requires_provisioning_signature:
+ raise InvalidClientError(description=PRIVATE_KEY_REQUIRED_MESSAGE, request=request)
@staticmethod
def _enqueue_cimd_metadata_refresh(client_id: str) -> None:
@@ -1439,7 +1459,10 @@ def authenticated_oauth_client(view, request, *, resolve_cimd: bool = False) ->
return None
if is_cimd_client_id(client_id) and not validator.validate_client_id(client_id, oauth_request):
return None
- if not validator.authenticate_client(oauth_request):
+ try:
+ if not validator.authenticate_client(oauth_request):
+ return None
+ except InvalidClientError:
return None
return oauth_request.client
@@ -2034,6 +2057,11 @@ class OAuthTokenView(TokenView):
}
if access_token.application:
properties.update(_oauth_app_event_properties(access_token.application))
+ properties.update(
+ _provisioning_signing_properties(
+ access_token.application, signed=client_auth_method == "client_assertion"
+ )
+ )
# `user` is nullable on an access token (client-credentials grants have no
# resource owner), so fall back to the client id and skip person processing.
if access_token.user is None:
@@ -2073,6 +2101,9 @@ class OAuthTokenView(TokenView):
pass
else:
properties.update(_oauth_app_event_properties(application))
+ # A rejected assertion may not have verified, so only unsigned rejections are tagged.
+ if client_auth_method != "client_assertion":
+ properties.update(_provisioning_signing_properties(application, signed=False))
posthoganalytics.capture(
distinct_id=client_id or "unknown",
event="oauth_token_rejected",
diff --git a/posthog/models/oauth.py b/posthog/models/oauth.py
index 696aad334c61..5bd094f3bd10 100644
--- a/posthog/models/oauth.py
+++ b/posthog/models/oauth.py
@@ -1,6 +1,6 @@
import enum
import uuid
-from datetime import timedelta
+from datetime import datetime, timedelta
from typing import TYPE_CHECKING, cast
from urllib.parse import urlparse
@@ -71,6 +71,21 @@ class TokenEndpointAuthMethod(enum.Enum):
PRIVATE_KEY_JWT = "private_key_jwt"
+class ProvisioningSigning(enum.Enum):
+ NOT_REQUIRED = "not_required"
+ GRACE = "grace"
+ REQUIRED = "required"
+
+ def request_tag(self, *, signed: bool) -> str:
+ if signed:
+ return "signed"
+ return {
+ ProvisioningSigning.NOT_REQUIRED: "unsigned_exempt",
+ ProvisioningSigning.GRACE: "unsigned_grace",
+ ProvisioningSigning.REQUIRED: "refused",
+ }[self]
+
+
def is_loopback_host(hostname: str | None) -> bool:
"""Check if hostname is a loopback address (localhost, 127.0.0.0/8, or ::1)."""
if not hostname:
@@ -342,6 +357,42 @@ class OAuthApplication(ModelActivityMixin, AbstractApplication): # type: ignore
def uses_private_key_jwt_auth(self) -> bool:
return self.token_endpoint_auth_method is TokenEndpointAuthMethod.PRIVATE_KEY_JWT
+ @property
+ def provisioning_unsigned_allowed_until(self) -> datetime | None:
+ provisioning = self.provisioning
+ if provisioning.unsigned_allowed_until is not None:
+ return provisioning.unsigned_allowed_until
+ # Rows promoted before partner_since was recorded fall back to their creation date.
+ became_partner = provisioning.partner_since or self.created or timezone.now()
+ if became_partner < settings.PROVISIONING_SIGNING_REQUIRED_SINCE:
+ return settings.PROVISIONING_UNSIGNED_GRACE_UNTIL
+ return None
+
+ @property
+ def provisioning_signing(self) -> ProvisioningSigning:
+ provisioning = self.provisioning
+ if not self.is_provisioning_partner or not (
+ provisioning.can_create_accounts or provisioning.pays_for_customers
+ ):
+ return ProvisioningSigning.NOT_REQUIRED
+ # Grace covers partners that have not switched yet. Once a partner publishes a key it signs from then on.
+ if self.uses_private_key_jwt_auth:
+ return ProvisioningSigning.REQUIRED
+ allowed_until = self.provisioning_unsigned_allowed_until
+ if allowed_until is not None and timezone.now() < allowed_until:
+ return ProvisioningSigning.GRACE
+ return ProvisioningSigning.REQUIRED
+
+ @property
+ def requires_provisioning_signature(self) -> bool:
+ return self.provisioning_signing is ProvisioningSigning.REQUIRED
+
+ @property
+ def cannot_meet_provisioning_signature(self) -> bool:
+ # Checked per request rather than stored, because a CIMD refresh demotes a partner to public once its
+ # metadata drops its key.
+ return self.requires_provisioning_signature and not self.uses_private_key_jwt_auth
+
class Meta(AbstractApplication.Meta):
verbose_name = "OAuth Application"
verbose_name_plural = "OAuth Applications"
diff --git a/posthog/models/oauth_provisioning.py b/posthog/models/oauth_provisioning.py
index 2ab109b06a37..df7d59accd75 100644
--- a/posthog/models/oauth_provisioning.py
+++ b/posthog/models/oauth_provisioning.py
@@ -17,6 +17,7 @@ to an operator as a capability that was granted.
from __future__ import annotations
+from datetime import UTC, datetime
from enum import StrEnum
from pydantic import BaseModel, ConfigDict, Field, field_validator
@@ -80,7 +81,25 @@ class ProvisioningConfig(BaseModel):
# Staff-only. Billing refuses to move an organization to partner billing once the organization
# has its own Stripe customer, so the partner's organizations must not start self-serve billing.
- pays_for_customers: bool = False
+ pays_for_customers: bool = Field(
+ default=False,
+ description=(
+ "The partner pays for the organizations it creates, and those organizations can't set up their "
+ "own billing. A provisioning partner needs private_key_jwt client authentication before it can pay."
+ ),
+ )
+
+ # Staff-only, so support can move one partner's deadline without a deploy.
+ unsigned_allowed_until: datetime | None = Field(
+ default=None,
+ description=(
+ "Until when this partner may send provisioning requests without a private_key_jwt signature. "
+ "Replaces the shared grace period for this partner. Blank uses the shared grace period."
+ ),
+ )
+
+ # Stamped at promotion, because the app row can predate the partnership by any amount.
+ partner_since: datetime | None = None
# Per-endpoint hourly overrides, keyed by rate-limit endpoint name. An absent key
# means the tier-derived budget applies; UNLIMITED_OVERRIDE disables the limit.
@@ -106,3 +125,16 @@ class ProvisioningConfig(BaseModel):
continue
limits[str(key)] = UNLIMITED_OVERRIDE if parsed <= 0 else parsed
return limits
+
+ @field_validator("unsigned_allowed_until", "partner_since")
+ @classmethod
+ def _read_naive_datetime_as_utc(cls, value: datetime | None) -> datetime | None:
+ # Compared with the aware current time on every request, where a naive value would raise.
+ if value is None or value.tzinfo is not None:
+ return value
+ return value.replace(tzinfo=UTC)
+
+
+PROVISIONING_CAPABILITIES: tuple[str, ...] = tuple(
+ name for name, info in ProvisioningConfig.model_fields.items() if info.annotation is bool
+)
diff --git a/posthog/settings/utils.py b/posthog/settings/utils.py
index fa112d01e042..9da0576fd13c 100644
--- a/posthog/settings/utils.py
+++ b/posthog/settings/utils.py
@@ -1,5 +1,6 @@
import os
from collections.abc import Callable
+from datetime import UTC, datetime
from typing import Any, Optional
from django.core.exceptions import ImproperlyConfigured
@@ -12,6 +13,7 @@ __all__ = [
"get_from_env",
"get_list",
"str_to_bool",
+ "str_to_utc_datetime",
]
@@ -68,6 +70,12 @@ def get_from_env(
return value
+def str_to_utc_datetime(value: str) -> datetime:
+ # Read without an offset as UTC, so the value compares with the aware datetimes Django produces.
+ parsed = datetime.fromisoformat(value)
+ return parsed if parsed.tzinfo else parsed.replace(tzinfo=UTC)
+
+
def get_list(text: str) -> list[str]:
if not text:
return []
diff --git a/posthog/settings/web.py b/posthog/settings/web.py
index 8d3be17e5e0b..8d442c75f31e 100644
--- a/posthog/settings/web.py
+++ b/posthog/settings/web.py
@@ -1,7 +1,7 @@
# Web app specific settings/middleware/apps setup
import os
import json
-from datetime import timedelta
+from datetime import UTC, datetime, timedelta
from django.core.exceptions import ImproperlyConfigured
@@ -12,7 +12,13 @@ from whitenoise.compress import Compressor
from posthog.openapi.enum_names import ChoicesEnumNameOverrides
from posthog.scopes import get_scope_descriptions
from posthog.settings.base_variables import BASE_DIR, CLOUD_DEPLOYMENT, DEBUG, TEST
-from posthog.settings.utils import generate_rsa_private_key_pem, get_from_env, get_list, str_to_bool
+from posthog.settings.utils import (
+ generate_rsa_private_key_pem,
+ get_from_env,
+ get_list,
+ str_to_bool,
+ str_to_utc_datetime,
+)
from posthog.utils_cors import CORS_ALLOWED_TRACING_HEADERS
logger = structlog.get_logger(__name__)
@@ -1270,6 +1276,14 @@ OAUTH2_PROVIDER_REFRESH_TOKEN_MODEL = "posthog.OAuthRefreshToken"
OAUTH2_PROVIDER_ID_TOKEN_MODEL = "posthog.OAuthIDToken"
OAUTH2_PROVIDER_GRANT_MODEL = "posthog.OAuthGrant"
+# A provisioning partner whose app predates the signing requirement may call unsigned until the grace period ends.
+PROVISIONING_SIGNING_REQUIRED_SINCE: datetime = get_from_env(
+ "PROVISIONING_SIGNING_REQUIRED_SINCE", datetime(2026, 10, 16, tzinfo=UTC), type_cast=str_to_utc_datetime
+)
+PROVISIONING_UNSIGNED_GRACE_UNTIL: datetime = get_from_env(
+ "PROVISIONING_UNSIGNED_GRACE_UNTIL", datetime(2026, 10, 23, 16, tzinfo=UTC), type_cast=str_to_utc_datetime
+)
+
ID_JAG_ACCESS_TOKEN_TTL_SECONDS: int = get_from_env("ID_JAG_ACCESS_TOKEN_TTL_SECONDS", 60 * 60 * 2, type_cast=int)
ID_JAG_CLOCK_SKEW_SECONDS: int = get_from_env("ID_JAG_CLOCK_SKEW_SECONDS", 30, type_cast=int)
# IdPs issue ID-JAGs for immediate use (5 minutes is typical); the cap leaves headroom above that.
diff --git a/posthog/templates/admin/posthog/oauthapplication/allow_unsigned_provisioning_until.html b/posthog/templates/admin/posthog/oauthapplication/allow_unsigned_provisioning_until.html
new file mode 100644
index 000000000000..9d258f6ae8d5
--- /dev/null
+++ b/posthog/templates/admin/posthog/oauthapplication/allow_unsigned_provisioning_until.html
@@ -0,0 +1,40 @@
+{% extends "admin/base_site.html" %}
+{% load i18n l10n admin_urls %}
+{% block breadcrumbs %}
+ <div class="breadcrumbs">
+ <a href="{% url 'admin:index' %}">{% translate 'Home' %}</a>
+ &rsaquo; <a href="{% url 'admin:app_list' app_label=opts.app_label %}">{{ opts.app_config.verbose_name }}</a>
+ &rsaquo; <a href="{% url opts|admin_urlname:'changelist' %}">{{ opts.verbose_name_plural|capfirst }}</a>
+ &rsaquo; {% translate 'Allow unsigned provisioning requests' %}
+ </div>
+{% endblock %}
+{% block content %}
+ <p>Until the date you choose, the selected partners may send provisioning requests without a private_key_jwt signature. After it, they have to sign every request. The date replaces the shared grace period for these partners only.</p>
+ <ul>
+ {% for obj in queryset %}<li>{{ obj }}</li>{% endfor %}
+ </ul>
+ <form method="post">
+ {% csrf_token %}
+ {% for obj in queryset %}
+ <input type="hidden"
+ name="{{ action_checkbox_name }}"
+ value="{{ obj.pk|unlocalize }}">
+ {% endfor %}
+ <fieldset class="module aligned">
+ {% for field in form %}
+ <div class="form-row field-{{ field.name }}">
+ {{ field.errors }}
+ {{ field.label_tag }} {{ field }}
+ {% if field.help_text %}
+ <div class="help">{{ field.help_text }}</div>
+ {% endif %}
+ </div>
+ {% endfor %}
+ </fieldset>
+ <input type="hidden" name="action" value="allow_unsigned_provisioning_until">
+ <input type="hidden" name="apply" value="yes">
+ <input type="submit" value="Allow unsigned requests" class="default">
+ <a href="{% url opts|admin_urlname:'changelist' %}"
+ class="button cancel-link">Cancel</a>
+ </form>
+{% endblock %}