: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(agentic-provisioning): add partner-scoped GitHub grant store and endpoints (#69857)
Rafael Audibertc3d18e8a4233
diff --git a/ee/api/agentic_provisioning/__init__.py b/ee/api/agentic_provisioning/__init__.pyindex 16c3c648d135..98ed821f0cf9 100644--- a/ee/api/agentic_provisioning/__init__.py+++ b/ee/api/agentic_provisioning/__init__.py@@ -1,2 +1,3 @@AUTH_CODE_CACHE_PREFIX = "provisioning_auth_code:"PENDING_AUTH_CACHE_PREFIX = "provisioning_pending_auth:"+GITHUB_GRANT_CACHE_PREFIX = "provisioning_github_grant:"diff --git a/ee/api/agentic_provisioning/github_grants.py b/ee/api/agentic_provisioning/github_grants.pynew file mode 100644index 000000000000..2badaee88c1c--- /dev/null+++ b/ee/api/agentic_provisioning/github_grants.py@@ -0,0 +1,273 @@+"""Server-side store for GitHub user authorizations minted during a partner drop flow.++A partner (e.g. posthog.com) exchanges a GitHub OAuth code via the provisioning API and+receives only an opaque ``grant_id`` — the GitHub user-to-server tokens never leave+PostHog. The grant is later consumed when the GitHub installation is linked to a team+(the ``github_integration`` resource action or the ``configuration.wizard`` block in+``account_requests``).++Grants are region-local: they live in this region's cache, so every follow-up call that+references a ``grant_id`` must hit the region that minted it. v1 partners are US-only.+"""++from __future__ import annotations++import json+import secrets+from dataclasses import dataclass+from typing import Any++from django.core.cache import cache+from django.utils import timezone++import requests+import structlog+from cryptography.fernet import InvalidToken++from posthog.egress.github.transport import github_request+from posthog.helpers.encrypted_fields import EncryptedTextField+from posthog.models.integration import GitHubUserAuthorization+from posthog.models.oauth import OAuthApplication++from . import GITHUB_GRANT_CACHE_PREFIX++logger = structlog.get_logger(__name__)++# Long enough to survive the existing-user consent detour (login + in-app approval),+# short enough that a stored user token goes stale quickly if never used.+GITHUB_GRANT_TTL_SECONDS = 3600++# The payload holds GitHub user-to-server tokens, so it is encrypted at rest in the+# cache with the same MultiFernet keys that back EncryptedJSONField columns.+_grant_cipher = EncryptedTextField()+++class GitHubEmailAccessDenied(Exception):+ """GitHub refused the /user/emails read — almost always the App missing the+ "Email addresses (read)" account permission, i.e. our misconfiguration.++ Kept distinct from "the user has no verified email" (a legitimate state the+ partner recovers from by collecting an email inline) so the misconfiguration+ stays a loud error instead of silently degrading every drop."""+++@dataclass(frozen=True)+class GitHubGrant:+ """A stored GitHub user authorization, bound to the partner that created it."""++ grant_id: str+ partner_id: str+ gh_id: int+ gh_login: str+ email: str | None+ access_token: str+ refresh_token: str | None+ access_token_expires_in: int | None+ refresh_token_expires_in: int | None+ created_at: str++ def to_authorization(self) -> GitHubUserAuthorization:+ return GitHubUserAuthorization(+ gh_id=self.gh_id,+ gh_login=self.gh_login,+ access_token=self.access_token,+ refresh_token=self.refresh_token,+ access_token_expires_in=self.access_token_expires_in,+ refresh_token_expires_in=self.refresh_token_expires_in,+ )++ def cache_payload(self) -> dict[str, Any]:+ return {+ "partner_id": self.partner_id,+ "gh_id": self.gh_id,+ "gh_login": self.gh_login,+ "email": self.email,+ "access_token": self.access_token,+ "refresh_token": self.refresh_token,+ "access_token_expires_in": self.access_token_expires_in,+ "refresh_token_expires_in": self.refresh_token_expires_in,+ "created_at": self.created_at,+ }++ @classmethod+ def from_cache(cls, grant_id: str, payload: dict[str, Any]) -> GitHubGrant:+ return cls(+ grant_id=grant_id,+ partner_id=payload["partner_id"],+ gh_id=payload["gh_id"],+ gh_login=payload["gh_login"],+ email=payload["email"],+ access_token=payload["access_token"],+ refresh_token=payload.get("refresh_token"),+ access_token_expires_in=payload.get("access_token_expires_in"),+ refresh_token_expires_in=payload.get("refresh_token_expires_in"),+ created_at=payload["created_at"],+ )+++def create_grant(partner: OAuthApplication, authorization: GitHubUserAuthorization, email: str | None) -> GitHubGrant:+ grant = GitHubGrant(+ grant_id=secrets.token_urlsafe(32),+ partner_id=str(partner.id),+ gh_id=authorization.gh_id,+ gh_login=authorization.gh_login,+ email=email,+ access_token=authorization.access_token,+ refresh_token=authorization.refresh_token,+ access_token_expires_in=authorization.access_token_expires_in,+ refresh_token_expires_in=authorization.refresh_token_expires_in,+ created_at=timezone.now().isoformat(),+ )+ cache.set(+ f"{GITHUB_GRANT_CACHE_PREFIX}{grant.grant_id}",+ _grant_cipher.encrypt(json.dumps(grant.cache_payload())),+ timeout=GITHUB_GRANT_TTL_SECONDS,+ )+ return grant+++def load_grant(grant_id: str, partner: OAuthApplication) -> GitHubGrant | None:+ """Load a grant if it exists and was created by ``partner``, else None.++ Partner mismatch deliberately looks identical to a missing grant so the endpoint+ can't be used as an existence oracle for other partners' grants.+ """+ if not grant_id:+ return None+ raw = cache.get(f"{GITHUB_GRANT_CACHE_PREFIX}{grant_id}")+ if raw is None:+ return None+ try:+ payload = json.loads(_grant_cipher.decrypt(raw))+ grant = GitHubGrant.from_cache(grant_id, payload)+ except (InvalidToken, ValueError, KeyError, TypeError):+ logger.warning("github_grant.corrupt_payload", grant_id=grant_id)+ return None+ if grant.partner_id != str(partner.id):+ logger.warning("github_grant.partner_mismatch", grant_id=grant_id, partner_id=str(partner.id))+ return None+ return grant+++def consume_grant(grant_id: str) -> None:+ cache.delete(f"{GITHUB_GRANT_CACHE_PREFIX}{grant_id}")+++def fetch_primary_email(access_token: str) -> str | None:+ """Fetch the user's primary verified email with a user-to-server token.++ Returns None when the user simply has no verified email (the partner collects one+ inline instead). Raises ``GitHubEmailAccessDenied`` when GitHub refuses the read+ (missing App permission) and ``requests.RequestException`` on network errors or+ GitHub 5xx so callers can distinguish "retry" from "won't work".+ """+ # Identity-blind: user OAuth token, metered against the user's budget.+ response = github_request(+ "GET",+ "https://api.github.com/user/emails",+ source="integration",+ headers={"Authorization": f"Bearer {access_token}"},+ params={"per_page": 100},+ timeout=10,+ )+ if response.status_code >= 500:+ raise requests.RequestException(f"Unexpected status {response.status_code} listing user emails")+ if response.status_code != 200:+ logger.warning("github_grant.user_emails_denied", status_code=response.status_code)+ raise GitHubEmailAccessDenied(f"GitHub returned {response.status_code} listing user emails")+ emails = response.json()+ if not isinstance(emails, list):+ return None+ verified = [e for e in emails if isinstance(e, dict) and e.get("verified") and e.get("email")]+ for entry in verified:+ if entry.get("primary"):+ return str(entry["email"])+ if verified:+ return str(verified[0]["email"])+ return None+++# A single page covers the overwhelmingly common case; the cap bounds request fan-out+# for users with huge installations so the endpoint stays cheap to poll.+_REPOSITORY_PAGE_SIZE = 100+_REPOSITORY_MAX_PAGES = 3+++def list_installations_and_repositories(access_token: str) -> dict[str, Any]:+ """List the user's installations of our GitHub App and the repos each grants.++ A user-to-server token only ever sees installations of the App that minted it,+ so no app filtering is needed. Raises ``requests.RequestException`` on failure.+ """+ # Identity-blind: user OAuth token, metered against the user's budget.+ response = github_request(+ "GET",+ "https://api.github.com/user/installations",+ source="integration",+ headers={"Authorization": f"Bearer {access_token}"},+ params={"per_page": 100},+ timeout=10,+ )+ if response.status_code != 200:+ logger.warning("github_grant.list_installations_failed", status_code=response.status_code)+ raise requests.RequestException(f"Unexpected status {response.status_code} listing user installations")++ installations: list[dict[str, Any]] = []+ repositories: list[dict[str, Any]] = []+ raw_installations = response.json().get("installations", [])+ if not isinstance(raw_installations, list):+ raw_installations = []++ for installation in raw_installations:+ if not isinstance(installation, dict) or installation.get("id") is None:+ continue+ installation_id = str(installation["id"])+ installations.append(+ {+ "id": installation_id,+ "account_login": (installation.get("account") or {}).get("login"),+ "repository_selection": installation.get("repository_selection"),+ }+ )+ repositories.extend(_list_installation_repositories(access_token, installation_id))++ return {"installations": installations, "repositories": repositories}+++def _list_installation_repositories(access_token: str, installation_id: str) -> list[dict[str, Any]]:+ repositories: list[dict[str, Any]] = []+ for page in range(1, _REPOSITORY_MAX_PAGES + 1):+ response = github_request(+ "GET",+ f"https://api.github.com/user/installations/{installation_id}/repositories",+ source="integration",+ headers={"Authorization": f"Bearer {access_token}"},+ params={"per_page": _REPOSITORY_PAGE_SIZE, "page": page},+ timeout=10,+ )+ if response.status_code != 200:+ logger.warning(+ "github_grant.list_repositories_failed",+ status_code=response.status_code,+ installation_id=installation_id,+ )+ raise requests.RequestException(+ f"Unexpected status {response.status_code} listing installation repositories"+ )+ raw_repositories = response.json().get("repositories", [])+ if not isinstance(raw_repositories, list):+ break+ for repository in raw_repositories:+ if not isinstance(repository, dict) or not repository.get("full_name"):+ continue+ repositories.append(+ {+ "installation_id": installation_id,+ "full_name": repository["full_name"],+ "default_branch": repository.get("default_branch"),+ "private": repository.get("private"),+ }+ )+ if len(raw_repositories) < _REPOSITORY_PAGE_SIZE:+ break+ return repositoriesdiff --git a/ee/api/agentic_provisioning/test/test_github_grants.py b/ee/api/agentic_provisioning/test/test_github_grants.pynew file mode 100644index 000000000000..434bb1360bce--- /dev/null+++ b/ee/api/agentic_provisioning/test/test_github_grants.py@@ -0,0 +1,310 @@+from unittest.mock import MagicMock, patch++from django.core.cache import cache++import requests+from parameterized import parameterized++from posthog.models.integration import GitHubUserAuthorization+from posthog.models.oauth import OAuthApplication++from ee.api.agentic_provisioning import GITHUB_GRANT_CACHE_PREFIX, github_grants+from ee.api.agentic_provisioning.test.base import HMAC_SECRET, ProvisioningTestBase++ACCESS_TOKEN = "gho_secret_user_token"++AUTHORIZATION = GitHubUserAuthorization(+ gh_id=12345,+ gh_login="octocat",+ access_token=ACCESS_TOKEN,+ refresh_token="ghr_refresh_token",+ access_token_expires_in=28800,+ refresh_token_expires_in=15897600,+)+++def _github_response(status_code: int, payload: object) -> MagicMock:+ response = MagicMock()+ response.status_code = status_code+ response.json.return_value = payload+ return response+++EMAILS_RESPONSE = _github_response(+ 200,+ [+ {"email": "[email protected]", "primary": False, "verified": True},+ {"email": "[email protected]", "primary": True, "verified": True},+ {"email": "[email protected]", "primary": False, "verified": False},+ ],+)++INSTALLATIONS_RESPONSE = _github_response(+ 200,+ {+ "installations": [+ {"id": 777, "account": {"login": "octocat"}, "repository_selection": "selected"},+ ]+ },+)++REPOSITORIES_RESPONSE = _github_response(+ 200,+ {+ "repositories": [+ {"full_name": "octocat/hello-world", "default_branch": "main", "private": False},+ ]+ },+)+++class TestGitHubGrants(ProvisioningTestBase):+ def setUp(self):+ super().setUp()+ self.partner = OAuthApplication.objects.create(+ name="Drop Partner",+ client_id="drop_partner_client_id",+ client_secret="",+ client_type=OAuthApplication.CLIENT_CONFIDENTIAL,+ authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,+ redirect_uris="https://posthog.com/api/wizard/oauth-callback",+ algorithm="RS256",+ provisioning_auth_method="hmac",+ provisioning_signing_secret=HMAC_SECRET,+ provisioning_partner_type="posthog_website",+ provisioning_active=True,+ provisioning_can_create_accounts=True,+ )++ def _create_grant_via_api(self):+ with (+ patch(+ "ee.api.agentic_provisioning.views.GitHubIntegration.github_user_from_code",+ return_value=AUTHORIZATION,+ ),+ patch("ee.api.agentic_provisioning.github_grants.github_request", return_value=EMAILS_RESPONSE),+ ):+ return self._post_signed(+ "/api/agentic/provisioning/github/grants",+ {"code": "gh_code", "redirect_uri": "https://posthog.com/api/wizard/github/callback"},+ )++ def test_create_grant_happy_path(self):+ with (+ patch(+ "ee.api.agentic_provisioning.views.GitHubIntegration.github_user_from_code",+ return_value=AUTHORIZATION,+ ) as mock_exchange,+ patch("ee.api.agentic_provisioning.github_grants.github_request", return_value=EMAILS_RESPONSE),+ ):+ response = self._post_signed(+ "/api/agentic/provisioning/github/grants",+ {"code": "gh_code", "redirect_uri": "https://posthog.com/api/wizard/github/callback"},+ )++ assert response.status_code == 200, response.json()+ body = response.json()+ assert body["gh_login"] == "octocat"+ assert body["email"] == "[email protected]"+ assert body["grant_id"]+ # The redirect_uri must flow into the exchange — GitHub rejects mismatches.+ mock_exchange.assert_called_once_with("gh_code", redirect_uri="https://posthog.com/api/wizard/github/callback")++ # Tokens are encrypted at rest in the cache; the loaded grant round-trips them.+ raw = cache.get(f"{GITHUB_GRANT_CACHE_PREFIX}{body['grant_id']}")+ assert isinstance(raw, str)+ assert ACCESS_TOKEN not in raw+ grant = github_grants.load_grant(body["grant_id"], self.partner)+ assert grant is not None+ assert grant.access_token == ACCESS_TOKEN+ assert grant.email == "[email protected]"++ @parameterized.expand(+ [+ ("missing_code", {}, 400, "invalid_request"),+ ("blank_code", {"code": ""}, 400, "invalid_request"),+ ]+ )+ def test_create_grant_requires_code(self, _name, body, expected_status, expected_code):+ response = self._post_signed("/api/agentic/provisioning/github/grants", body)+ assert response.status_code == expected_status+ assert response.json()["error"]["code"] == expected_code++ def test_create_grant_exchange_failure_returns_502(self):+ with patch(+ "ee.api.agentic_provisioning.views.GitHubIntegration.github_user_from_code",+ return_value=None,+ ):+ response = self._post_signed("/api/agentic/provisioning/github/grants", {"code": "bad_code"})+ assert response.status_code == 502+ assert response.json()["error"]["code"] == "github_exchange_failed"++ def test_create_grant_github_request_failure_returns_502(self):+ with patch(+ "ee.api.agentic_provisioning.views.GitHubIntegration.github_user_from_code",+ side_effect=requests.RequestException("boom"),+ ):+ response = self._post_signed("/api/agentic/provisioning/github/grants", {"code": "gh_code"})+ assert response.status_code == 502+ assert response.json()["error"]["code"] == "github_unavailable"++ def test_create_grant_rejects_pkce_partner(self):+ # PKCE partners are identified only by a public client_id, so they carry no proof+ # of controlling the partner and must not reach the GitHub code exchange.+ pkce_partner = OAuthApplication.objects.create(+ name="PKCE Partner",+ client_id="pkce_partner_client_id",+ client_secret="",+ client_type=OAuthApplication.CLIENT_PUBLIC,+ authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,+ redirect_uris="https://pkce.example.com",+ algorithm="RS256",+ provisioning_auth_method="pkce",+ provisioning_active=True,+ provisioning_can_create_accounts=True,+ )+ response = self.client.post(+ "/api/agentic/provisioning/github/grants",+ data={"client_id": pkce_partner.client_id, "code": "gh_code"},+ format="json",+ HTTP_API_VERSION="0.1d",+ )+ assert response.status_code == 403+ assert response.json()["error"]["code"] == "forbidden"++ def test_create_grant_without_verified_email_returns_null_email(self):+ no_verified = _github_response(200, [{"email": "[email protected]", "primary": True, "verified": False}])+ with (+ patch(+ "ee.api.agentic_provisioning.views.GitHubIntegration.github_user_from_code",+ return_value=AUTHORIZATION,+ ),+ patch("ee.api.agentic_provisioning.github_grants.github_request", return_value=no_verified),+ ):+ response = self._post_signed("/api/agentic/provisioning/github/grants", {"code": "gh_code"})+ assert response.status_code == 200, response.json()+ body = response.json()+ assert body["email"] is None+ grant = github_grants.load_grant(body["grant_id"], self.partner)+ assert grant is not None+ assert grant.email is None++ def test_create_grant_email_access_denied_returns_502(self):+ denied = _github_response(404, {"message": "Not Found"})+ with (+ patch(+ "ee.api.agentic_provisioning.views.GitHubIntegration.github_user_from_code",+ return_value=AUTHORIZATION,+ ),+ patch("ee.api.agentic_provisioning.github_grants.github_request", return_value=denied),+ ):+ response = self._post_signed("/api/agentic/provisioning/github/grants", {"code": "gh_code"})+ assert response.status_code == 502+ assert response.json()["error"]["code"] == "email_unavailable"++ def test_create_grant_requires_partner_auth(self):+ response = self.client.post(+ "/api/agentic/provisioning/github/grants",+ data={"code": "gh_code"},+ format="json",+ HTTP_API_VERSION="0.1d",+ )+ assert response.status_code == 401++ def test_create_grant_requires_account_creation_permission(self):+ self.partner.provisioning_can_create_accounts = False+ self.partner.save()+ response = self._post_signed("/api/agentic/provisioning/github/grants", {"code": "gh_code"})+ assert response.status_code == 403+ assert response.json()["error"]["code"] == "forbidden"++ def test_create_grant_partner_rate_limited(self):+ self.partner.provisioning_rate_limit_github_grants = 1+ self.partner.save()+ first = self._create_grant_via_api()+ assert first.status_code == 200+ second = self._create_grant_via_api()+ assert second.status_code == 429+ assert second["Retry-After"]++ @parameterized.expand(+ [+ ("agentic_tree", "/api/agentic/provisioning/github/grants"),+ ("alias_tree", "/api/provisioning/github/grants"),+ ]+ )+ def test_repositories_happy_path(self, _name, base_url):+ grant = github_grants.create_grant(self.partner, AUTHORIZATION, "[email protected]")++ def fake_github_request(method, url, **kwargs):+ if url.endswith("/user/installations"):+ return INSTALLATIONS_RESPONSE+ return REPOSITORIES_RESPONSE++ with patch("ee.api.agentic_provisioning.github_grants.github_request", side_effect=fake_github_request):+ response = self._get_signed(f"{base_url}/{grant.grant_id}/repositories")++ assert response.status_code == 200, response.json()+ body = response.json()+ assert body["gh_login"] == "octocat"+ assert body["installations"] == [{"id": "777", "account_login": "octocat", "repository_selection": "selected"}]+ assert body["repositories"] == [+ {+ "installation_id": "777",+ "full_name": "octocat/hello-world",+ "default_branch": "main",+ "private": False,+ }+ ]++ def test_repositories_unknown_grant_returns_404(self):+ response = self._get_signed("/api/agentic/provisioning/github/grants/nonexistent/repositories")+ assert response.status_code == 404+ assert response.json()["error"]["code"] == "grant_not_found"++ def test_repositories_grant_of_other_partner_returns_404(self):+ other_partner = OAuthApplication.objects.create(+ name="Other Partner",+ client_id="other_partner_client_id",+ client_secret="",+ client_type=OAuthApplication.CLIENT_CONFIDENTIAL,+ authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,+ redirect_uris="https://other.example.com",+ algorithm="RS256",+ provisioning_auth_method="bearer",+ provisioning_active=True,+ provisioning_can_create_accounts=True,+ )+ grant = github_grants.create_grant(other_partner, AUTHORIZATION, "[email protected]")+ response = self._get_signed(f"/api/agentic/provisioning/github/grants/{grant.grant_id}/repositories")+ assert response.status_code == 404+ assert response.json()["error"]["code"] == "grant_not_found"++ def test_repositories_poll_rate_limited(self):+ grant = github_grants.create_grant(self.partner, AUTHORIZATION, "[email protected]")+ url = f"/api/agentic/provisioning/github/grants/{grant.grant_id}/repositories"++ def fake_github_request(method, request_url, **kwargs):+ if request_url.endswith("/user/installations"):+ return INSTALLATIONS_RESPONSE+ return REPOSITORIES_RESPONSE++ with (+ patch("ee.api.agentic_provisioning.views.GITHUB_GRANT_POLL_RATE_LIMIT_MAX", 1),+ patch("ee.api.agentic_provisioning.github_grants.github_request", side_effect=fake_github_request),+ ):+ first = self._get_signed(url)+ second = self._get_signed(url)+ assert first.status_code == 200+ assert second.status_code == 429+ assert second["Retry-After"]++ def test_repositories_github_failure_returns_502(self):+ grant = github_grants.create_grant(self.partner, AUTHORIZATION, "[email protected]")+ with patch(+ "ee.api.agentic_provisioning.github_grants.github_request",+ return_value=_github_response(500, {}),+ ):+ response = self._get_signed(f"/api/agentic/provisioning/github/grants/{grant.grant_id}/repositories")+ assert response.status_code == 502+ assert response.json()["error"]["code"] == "github_unavailable"diff --git a/ee/api/agentic_provisioning/test/test_url_aliases.py b/ee/api/agentic_provisioning/test/test_url_aliases.pyindex e80df42ef0c9..8847e4a4b4aa 100644--- a/ee/api/agentic_provisioning/test/test_url_aliases.py+++ b/ee/api/agentic_provisioning/test/test_url_aliases.py@@ -15,6 +15,7 @@ PROVISIONING_ALIAS_URLS = [("resource_remove", f"/api/provisioning/resources/{RESOURCE_ID}/remove", "POST"),("resource_detail", f"/api/provisioning/resources/{RESOURCE_ID}", "GET"),("deep_links", "/api/provisioning/deep_links", "POST"),+ ("github_grants_create", "/api/provisioning/github/grants", "POST"),]diff --git a/ee/api/agentic_provisioning/views.py b/ee/api/agentic_provisioning/views.pyindex 67109ae1cf8a..5ea6854d0566 100644--- a/ee/api/agentic_provisioning/views.py+++ b/ee/api/agentic_provisioning/views.py@@ -35,7 +35,7 @@ from posthog.api.authentication import password_reset_token_generatorfrom posthog.api.email_verification import EmailVerifierfrom posthog.event_usage import report_user_signed_upfrom posthog.exceptions_capture import capture_exception-from posthog.models.integration import StripeIntegration+from posthog.models.integration import GitHubIntegration, StripeIntegrationfrom posthog.models.oauth import OAuthAccessToken, OAuthApplication, OAuthRefreshToken, find_oauth_access_tokenfrom posthog.models.personal_api_key import PersonalAPIKey, hash_key_valuefrom posthog.models.team.team import Team@@ -54,7 +54,7 @@ from posthog.utils import get_instance_regionfrom ee.settings import BILLING_SERVICE_URL-from . import AUTH_CODE_CACHE_PREFIX, PENDING_AUTH_CACHE_PREFIX+from . import AUTH_CODE_CACHE_PREFIX, PENDING_AUTH_CACHE_PREFIX, github_grantsfrom .authentication import ProvisioningAuthenticationfrom .region_proxy import region_proxyfrom .signature import SUPPORTED_VERSIONS, verify_api_version, verify_provisioning_signature@@ -83,13 +83,21 @@ PARTNER_RATE_LIMIT_DEFAULTS: dict[str, int] = {"account_requests": 10,"token_exchanges": 20,"resource_creates": 20,+ "github_grants": 10,}PARTNER_RATE_LIMIT_EVENT_NAMES: dict[str, str] = {"account_requests": "account_request","token_exchanges": "token_exchange","resource_creates": "resource_created",+ "github_grants": "github_grant",}+# 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+_SAFE_STATE_RE = re.compile(r"^[A-Za-z0-9_\-]{1,256}$")# Stripe's contracted scope ceiling, seeded onto the legacy Stripe Projects OAuth@@ -792,6 +800,201 @@ def _build_authorize_url(confirmation_secret: str, scopes: list[str], region: streturn f"{base}/api/agentic/authorize?{params}"+# ---------------------------------------------------------------------------+# POST /provisioning/github/grants+# GET /provisioning/github/grants/:grant_id/repositories+# GitHub grants for drop-style partner flows: the partner forwards a GitHub 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).+# ---------------------------------------------------------------------------+++def _authenticate_provisioning_partner(request: Request) -> tuple[Response | None, OAuthApplication | None]:+ """Identify a provisioning partner, requiring proof-bearing auth (unlike+ account_requests' legacy Stripe fallback). Returns (error_response, partner).++ Only HMAC and Bearer partners carry proof that the caller controls the partner.+ PKCE partners are identified solely by a public ``client_id`` anyone can send, so+ they never qualify for these endpoints — they exchange GitHub OAuth codes and read+ back GitHub account metadata, which must sit behind a real partner trust boundary.+ """+ auth = ProvisioningAuthentication()+ try:+ result = auth.authenticate(request)+ except AuthenticationFailed:+ result = None+ partner = result[1] if result else None+ if partner is None:+ return (+ Response(+ {"type": "error", "error": {"code": "unauthorized", "message": "Authentication required"}},+ status=401,+ ),+ None,+ )+ if partner.provisioning_auth_method not in ("hmac", "bearer"):+ return (+ Response(+ {+ "type": "error",+ "error": {"code": "forbidden", "message": "This endpoint requires a confidential partner"},+ },+ status=403,+ ),+ None,+ )+ return None, partner+++@api_view(["POST"])+@authentication_classes([])+@permission_classes([])+def github_grants_create(request: Request) -> Response:+ if error := verify_api_version(request):+ return error++ auth_error, partner = _authenticate_provisioning_partner(request)+ if auth_error or partner is None:+ return auth_error or Response(status=401)++ if not partner.provisioning_can_create_accounts:+ _capture_provisioning_event("github_grant", "error", partner=partner, error_code="account_creation_disabled")+ return Response(+ {+ "type": "error",+ "error": {"code": "forbidden", "message": "Account creation is not enabled for this partner"},+ },+ status=403,+ )++ if error := _enforce_partner_rate_limit(partner, "github_grants"):+ return error++ code = request.data.get("code")+ redirect_uri = request.data.get("redirect_uri") or None+ if not code or not isinstance(code, str):+ _capture_provisioning_event("github_grant", "error", partner=partner, error_code="missing_code")+ return Response(+ {"type": "error", "error": {"code": "invalid_request", "message": "code is required"}}, status=400+ )++ try:+ authorization = GitHubIntegration.github_user_from_code(code, redirect_uri=redirect_uri)+ except requests.RequestException:+ # Network failure or a non-JSON GitHub error body raising through .json() — retryable,+ # distinct from a clean "bad code" exchange failure (which returns None below).+ _capture_provisioning_event("github_grant", "error", partner=partner, error_code="github_unavailable")+ return Response(+ {"type": "error", "error": {"code": "github_unavailable", "message": "GitHub request failed"}},+ status=502,+ )+ if authorization is None:+ _capture_provisioning_event("github_grant", "error", partner=partner, error_code="github_exchange_failed")+ return Response(+ {+ "type": "error",+ "error": {+ "code": "github_exchange_failed",+ "message": "Could not exchange the GitHub OAuth code",+ },+ },+ status=502,+ )++ # A user with no verified email gets a grant with email=null — the partner+ # collects an email inline instead. Only an access refusal (App permission+ # misconfiguration) hard-fails, so it can't masquerade as that user state.+ try:+ email = github_grants.fetch_primary_email(authorization.access_token)+ except github_grants.GitHubEmailAccessDenied:+ _capture_provisioning_event("github_grant", "error", partner=partner, error_code="email_unavailable")+ return Response(+ {+ "type": "error",+ "error": {+ "code": "email_unavailable",+ "message": "GitHub denied reading the user's email addresses",+ },+ },+ status=502,+ )+ except requests.RequestException:+ _capture_provisioning_event("github_grant", "error", partner=partner, error_code="github_unavailable")+ return Response(+ {"type": "error", "error": {"code": "github_unavailable", "message": "GitHub request failed"}},+ status=502,+ )++ grant = github_grants.create_grant(partner, authorization, email)+ _capture_provisioning_event("github_grant", "created", partner=partner, gh_login=grant.gh_login)+ return Response(+ {+ "grant_id": grant.grant_id,+ "gh_login": grant.gh_login,+ "email": grant.email,+ "expires_in": github_grants.GITHUB_GRANT_TTL_SECONDS,+ }+ )+++def _enforce_grant_poll_rate_limit(grant_id: str) -> Response | None:+ window_index = int(time.time()) // GITHUB_GRANT_POLL_RATE_LIMIT_WINDOW_SECONDS+ key = f"{GITHUB_GRANT_POLL_RATE_LIMIT_PREFIX}{grant_id}:{window_index}"+ try:+ cache.add(key, 0, timeout=GITHUB_GRANT_POLL_RATE_LIMIT_WINDOW_SECONDS)+ count = cache.incr(key)+ except (ValueError, ConnectionError, TimeoutError):+ count = 1+ if count > GITHUB_GRANT_POLL_RATE_LIMIT_MAX:+ response = Response(+ {+ "type": "error",+ "error": {"code": "rate_limited", "message": "Too many repository listing requests for this grant"},+ },+ status=429,+ )+ response["Retry-After"] = str(+ GITHUB_GRANT_POLL_RATE_LIMIT_WINDOW_SECONDS+ - (int(time.time()) % GITHUB_GRANT_POLL_RATE_LIMIT_WINDOW_SECONDS)+ )+ return response+ return None+++@api_view(["GET"])+@authentication_classes([])+@permission_classes([])+def github_grant_repositories(request: Request, grant_id: str) -> Response:+ if error := verify_api_version(request):+ return error++ auth_error, partner = _authenticate_provisioning_partner(request)+ if auth_error or partner is None:+ return auth_error or Response(status=401)++ grant = github_grants.load_grant(grant_id, partner)+ if grant is None:+ return Response(+ {"type": "error", "error": {"code": "grant_not_found", "message": "Grant not found or expired"}},+ status=404,+ )++ if error := _enforce_grant_poll_rate_limit(grant_id):+ return error++ try:+ listing = github_grants.list_installations_and_repositories(grant.access_token)+ except requests.RequestException:+ _capture_provisioning_event("github_grant", "listing_failed", partner=partner)+ return Response(+ {"type": "error", "error": {"code": "github_unavailable", "message": "GitHub request failed"}},+ status=502,+ )++ return Response({"gh_login": grant.gh_login, **listing})++# ---------------------------------------------------------------------------# GET /api/agentic/authorize# Interactive OAuth consent for existing users (APP 0.1d §A1 "requires_auth").diff --git a/ee/urls.py b/ee/urls.pyindex 252a4ef8858e..be73ca7bb258 100644--- a/ee/urls.py+++ b/ee/urls.py@@ -356,6 +356,16 @@ urlpatterns: list[Any] = [csrf_exempt(agentic_provisioning_views.deep_links),name="agentic_provisioning_deep_links",),+ path(+ "api/agentic/provisioning/github/grants",+ csrf_exempt(agentic_provisioning_views.github_grants_create),+ name="agentic_provisioning_github_grants_create",+ ),+ path(+ "api/agentic/provisioning/github/grants/<str:grant_id>/repositories",+ csrf_exempt(agentic_provisioning_views.github_grant_repositories),+ name="agentic_provisioning_github_grant_repositories",+ ),path("agentic/login",agentic_provisioning_views.agentic_login,@@ -412,5 +422,15 @@ urlpatterns: list[Any] = [csrf_exempt(agentic_provisioning_views.deep_links),name="provisioning_deep_links",),+ path(+ "api/provisioning/github/grants",+ csrf_exempt(agentic_provisioning_views.github_grants_create),+ name="provisioning_github_grants_create",+ ),+ path(+ "api/provisioning/github/grants/<str:grant_id>/repositories",+ csrf_exempt(agentic_provisioning_views.github_grant_repositories),+ name="provisioning_github_grant_repositories",+ ),*admin_urlpatterns,]diff --git a/posthog/migrations/1253_oauth_application_github_grants_rate_limit.py b/posthog/migrations/1253_oauth_application_github_grants_rate_limit.pynew file mode 100644index 000000000000..4f662b9a84b6--- /dev/null+++ b/posthog/migrations/1253_oauth_application_github_grants_rate_limit.py@@ -0,0 +1,19 @@+# Generated by Django 5.2.14 on 2026-07-09 22:40++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [("posthog", "1252_datadeletionrequest_property_removal_marker")]++ operations = [+ migrations.AddField(+ model_name="oauthapplication",+ name="provisioning_rate_limit_github_grants",+ field=models.IntegerField(+ blank=True,+ help_text="Override default rate limit for GitHub grant creation (per hour)",+ null=True,+ ),+ ),+ ]diff --git a/posthog/migrations/max_migration.txt b/posthog/migrations/max_migration.txtindex c4e1282ca1e0..ab59c5775002 100644--- a/posthog/migrations/max_migration.txt+++ b/posthog/migrations/max_migration.txt@@ -1 +1 @@-1252_datadeletionrequest_property_removal_marker+1253_oauth_application_github_grants_rate_limitdiff --git a/posthog/models/oauth.py b/posthog/models/oauth.pyindex 85f46238ed8c..b8841c145050 100644--- a/posthog/models/oauth.py+++ b/posthog/models/oauth.py@@ -234,6 +234,9 @@ class OAuthApplication(ModelActivityMixin, AbstractApplication): # type: ignoreprovisioning_rate_limit_resource_creates: models.IntegerField = models.IntegerField(null=True, blank=True, help_text="Override default rate limit for resource creates (per hour)")+ provisioning_rate_limit_github_grants: models.IntegerField = models.IntegerField(+ null=True, blank=True, help_text="Override default rate limit for GitHub grant creation (per hour)"+ )provisioning_disabled: models.BooleanField = models.BooleanField(default=False,help_text=(diff --git a/posthog/tasks/email.py b/posthog/tasks/email.pyindex 5c024fc0b0cc..d158949cfa7c 100644--- a/posthog/tasks/email.py+++ b/posthog/tasks/email.py@@ -383,7 +383,7 @@ def send_member_join(invitee_uuid: str, organization_id: str) -> None:@shared_task(**EMAIL_TASK_KWARGS)@skip_team_scope_audit-def send_provisioning_welcome(user_id: int, token: str, partner_name: str = "") -> None:+def send_provisioning_welcome(user_id: int, token: str, partner_name: str = "", repository: str | None = None) -> None:user = User.objects.get(pk=user_id)message = EmailMessage(use_http=True,@@ -396,6 +396,7 @@ def send_provisioning_welcome(user_id: int, token: str, partner_name: str = "")"cloud": is_cloud(),"site_url": settings.SITE_URL,"partner_name": partner_name,+ "repository": repository or "",},)message.add_user_recipient(user)diff --git a/posthog/tasks/test/test_email.py b/posthog/tasks/test/test_email.pyindex bfed64cfeff7..fd803185ca54 100644--- a/posthog/tasks/test/test_email.py+++ b/posthog/tasks/test/test_email.py@@ -367,6 +367,17 @@ class TestEmail(APIBaseTest, ClickhouseTestMixin):assert "Set your password" in mocked_email_messages[0].html_bodyassert "Wizard" in mocked_email_messages[0].html_body+ def test_send_provisioning_welcome_with_repository(self, MockEmailMessage: MagicMock) -> None:+ mocked_email_messages = mock_email_messages(MockEmailMessage)+ org, user = create_org_team_and_user("2022-01-02 00:00:00", "[email protected]")+ token = password_reset_token_generator.make_token(self.user)++ send_provisioning_welcome(user.id, token, "posthog.com", repository="octocat/hello-world")++ assert len(mocked_email_messages) == 1+ assert "octocat/hello-world" in mocked_email_messages[0].html_body+ assert "pull request" in mocked_email_messages[0].html_body+def test_send_provisioning_welcome_without_partner(self, MockEmailMessage: MagicMock) -> None:mocked_email_messages = mock_email_messages(MockEmailMessage)org, user = create_org_team_and_user("2022-01-02 00:00:00", "[email protected]")diff --git a/posthog/templates/email/provisioning_welcome.html b/posthog/templates/email/provisioning_welcome.htmlindex 08de36fa4375..581ac442c675 100644--- a/posthog/templates/email/provisioning_welcome.html+++ b/posthog/templates/email/provisioning_welcome.html@@ -2,6 +2,11 @@<p>Welcome to PostHog! Your account was created{% if partner_name %} via {{ partner_name }}{% endif %}.</p>+{% if repository %}+<p>+ We're setting up PostHog in <strong>{{ repository }}</strong> in the background — a pull request will appear on the repository shortly.+</p>+{% endif %}<p>Set a password to log in to PostHog directly.</p>