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(agentic-provisioning): support a bundled wizard block in account_requests (#69859)

Rafael Audibert95af2205c45e
diff --git a/ee/api/agentic_provisioning/test/test_account_requests_wizard.py b/ee/api/agentic_provisioning/test/test_account_requests_wizard.py
new file mode 100644
index 000000000000..e208561c627c
--- /dev/null
+++ b/ee/api/agentic_provisioning/test/test_account_requests_wizard.py
@@ -0,0 +1,211 @@
+from datetime import timedelta
+
+from unittest.mock import MagicMock, patch
+
+from django.core.cache import cache
+from django.test import override_settings
+from django.utils import timezone
+
+from posthog.models.integration import GitHubInstallationAccess, GitHubIntegration, GitHubUserAuthorization
+from posthog.models.oauth import OAuthApplication
+from posthog.models.user import OnboardingSkippedReason, User
+
+from ee.api.agentic_provisioning import GITHUB_GRANT_CACHE_PREFIX, github_grants
+from ee.api.agentic_provisioning.test.base import HMAC_SECRET, ProvisioningTestBase
+
+INSTALLATION_ID = "777"
+CODE_CHALLENGE = "a" * 43
+
+AUTHORIZATION = GitHubUserAuthorization(
+ gh_id=12345,
+ gh_login="octocat",
+ access_token="gho_secret_user_token",
+ refresh_token="ghr_refresh_token",
+ access_token_expires_in=28800,
+ refresh_token_expires_in=15897600,
+)
+
+
+def _installation_access() -> GitHubInstallationAccess:
+ return GitHubInstallationAccess(
+ installation_id=INSTALLATION_ID,
+ installation_info={"account": {"type": "User", "login": "octocat"}},
+ access_token="ghs_installation_token",
+ token_expires_at=(timezone.now() + timedelta(hours=1)).isoformat(),
+ repository_selection="selected",
+ )
+
+
+@override_settings(WIZARD_CLOUD_RUN_OAUTH_CLIENT_ID="wizard-client-id")
+class TestAccountRequestsWizardBlock(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 _payload(self, email: str, wizard: dict | None = None) -> dict:
+ configuration: dict = {"region": "US"}
+ if wizard is not None:
+ configuration["wizard"] = wizard
+ return {
+ "id": "acctreq_wizard123",
+ "email": email,
+ "code_challenge": CODE_CHALLENGE,
+ "configuration": configuration,
+ }
+
+ def _grant(self, email: str) -> github_grants.GitHubGrant:
+ return github_grants.create_grant(self.partner, AUTHORIZATION, email)
+
+ def _post(self, payload: dict):
+ return self._post_signed("/api/agentic/provisioning/account_requests", data=payload)
+
+ def test_without_wizard_block_response_and_email_unchanged(self):
+ with patch("ee.api.agentic_provisioning.views.send_provisioning_welcome") as mock_email:
+ response = self._post(self._payload("[email protected]"))
+ assert response.status_code == 200, response.json()
+ body = response.json()
+ assert body["type"] == "oauth"
+ assert "wizard" not in body
+ assert mock_email.delay.call_count == 1
+ args, kwargs = mock_email.delay.call_args
+ assert len(args) == 3
+ assert kwargs == {}
+
+ def test_bundled_happy_path_runs_wizard_then_emails(self):
+ grant = self._grant("[email protected]")
+ created = MagicMock(task_id="task-uuid", latest_run=MagicMock(id="run-uuid", status="queued"))
+ manager = MagicMock()
+ with (
+ patch.object(GitHubIntegration, "verify_user_installation_access", return_value=True),
+ patch.object(GitHubIntegration, "fetch_installation_access", return_value=_installation_access()),
+ patch.object(GitHubIntegration, "first_for_team_repository", return_value=MagicMock()),
+ patch(
+ "ee.api.agentic_provisioning.views.tasks_facade.create_wizard_cloud_run", return_value=created
+ ) as mock_create,
+ patch("ee.api.agentic_provisioning.views.send_provisioning_welcome") as mock_email,
+ ):
+ manager.attach_mock(mock_create, "create_run")
+ manager.attach_mock(mock_email.delay, "email_delay")
+ response = self._post(
+ self._payload(
+ wizard={
+ "grant_id": grant.grant_id,
+ "installation_id": INSTALLATION_ID,
+ "repository": "octocat/hello-world",
+ "branch": "main",
+ },
+ )
+ )
+
+ assert response.status_code == 200, response.json()
+ body = response.json()
+ assert body["type"] == "oauth"
+ assert body["wizard"] == {"task_id": "task-uuid", "run_id": "run-uuid", "status": "queued"}
+
+ user = User.objects.get(email="[email protected]")
+ team = user.teams.get()
+ mock_create.assert_called_once_with(team=team, user_id=user.id, repository="octocat/hello-world", branch="main")
+
+ assert cache.get(f"{GITHUB_GRANT_CACHE_PREFIX}{grant.grant_id}") is None
+ assert user.onboarding_skipped_reason == OnboardingSkippedReason.PROVISIONED
+ team.refresh_from_db()
+ assert team.completed_snippet_onboarding is True
+
+ assert mock_email.delay.call_args.kwargs == {"repository": "octocat/hello-world"}
+ call_names = [name for name, _args, _kwargs in manager.mock_calls]
+ assert call_names.index("create_run") < call_names.index("email_delay")
+
+ def test_wizard_grant_not_found_returns_account_with_wizard_error(self):
+ with patch("ee.api.agentic_provisioning.views.send_provisioning_welcome") as mock_email:
+ response = self._post(
+ self._payload(
+ wizard={
+ "grant_id": "nonexistent",
+ "installation_id": INSTALLATION_ID,
+ "repository": "octocat/hello-world",
+ },
+ )
+ )
+ assert response.status_code == 200, response.json()
+ body = response.json()
+ assert body["type"] == "oauth"
+ assert "code" in body["oauth"]
+ assert body["wizard"]["error"]["code"] == "grant_not_found"
+ assert User.objects.filter(email="[email protected]").exists()
+ assert mock_email.delay.call_args.kwargs == {}
+
+ def test_wizard_ownership_denied_preserves_grant(self):
+ grant = self._grant("[email protected]")
+ with (
+ patch.object(GitHubIntegration, "verify_user_installation_access", return_value=False),
+ patch("ee.api.agentic_provisioning.views.send_provisioning_welcome"),
+ ):
+ response = self._post(
+ self._payload(
+ wizard={
+ "grant_id": grant.grant_id,
+ "installation_id": INSTALLATION_ID,
+ "repository": "octocat/hello-world",
+ },
+ )
+ )
+ assert response.status_code == 200
+ assert response.json()["wizard"]["error"]["code"] == "installation_access_denied"
+ assert cache.get(f"{GITHUB_GRANT_CACHE_PREFIX}{grant.grant_id}") is not None
+
+ @override_settings(WIZARD_CLOUD_RUN_OAUTH_CLIENT_ID="")
+ def test_wizard_unavailable_when_cloud_run_not_configured(self):
+ grant = self._grant("[email protected]")
+ with (
+ patch.object(GitHubIntegration, "verify_user_installation_access", return_value=True),
+ patch.object(GitHubIntegration, "fetch_installation_access", return_value=_installation_access()),
+ patch("ee.api.agentic_provisioning.views.send_provisioning_welcome") as mock_email,
+ ):
+ response = self._post(
+ self._payload(
+ wizard={
+ "grant_id": grant.grant_id,
+ "installation_id": INSTALLATION_ID,
+ "repository": "octocat/hello-world",
+ },
+ )
+ )
+ assert response.status_code == 200
+ assert response.json()["wizard"]["error"]["code"] == "wizard_unavailable"
+ assert mock_email.delay.call_args.kwargs == {}
+
+ def test_existing_user_with_wizard_block_gets_requires_auth_and_grant_survives(self):
+ User.objects.create_user(email="[email protected]", password="hunter2!!", first_name="Ex")
+ grant = self._grant("[email protected]")
+ response = self._post(
+ self._payload(
+ wizard={
+ "grant_id": grant.grant_id,
+ "installation_id": INSTALLATION_ID,
+ "repository": "octocat/hello-world",
+ },
+ )
+ )
+ assert response.status_code == 200, response.json()
+ body = response.json()
+ assert body["type"] == "requires_auth"
+ assert "wizard" not in body
+ assert cache.get(f"{GITHUB_GRANT_CACHE_PREFIX}{grant.grant_id}") is not None
diff --git a/ee/api/agentic_provisioning/test/test_wizard_resource_actions.py b/ee/api/agentic_provisioning/test/test_wizard_resource_actions.py
index 9908623c668a..eaf9e1403eb3 100644
--- a/ee/api/agentic_provisioning/test/test_wizard_resource_actions.py
+++ b/ee/api/agentic_provisioning/test/test_wizard_resource_actions.py
@@ -177,9 +177,12 @@ class TestWizardResourceActions(ProvisioningTestBase):
@override_settings(WIZARD_CLOUD_RUN_OAUTH_CLIENT_ID="wizard-client-id")
def test_wizard_runs_happy_path(self):
created = MagicMock(task_id="task-uuid", latest_run=MagicMock(id="run-uuid", status="queued"))
- with patch(
- "ee.api.agentic_provisioning.views.tasks_facade.create_wizard_cloud_run", return_value=created
- ) as mock_create:
+ with (
+ patch.object(GitHubIntegration, "first_for_team_repository", return_value=MagicMock()),
+ patch(
+ "ee.api.agentic_provisioning.views.tasks_facade.create_wizard_cloud_run", return_value=created
+ ) as mock_create,
+ ):
response = self._post_wizard_runs(self.team.id, {"repository": "octocat/hello-world", "branch": "main"})
assert response.status_code == 200, response.json()
@@ -206,7 +209,10 @@ class TestWizardResourceActions(ProvisioningTestBase):
@override_settings(WIZARD_CLOUD_RUN_OAUTH_CLIENT_ID="wizard-client-id")
def test_wizard_runs_per_user_burst_limit(self):
created = MagicMock(task_id="task-uuid", latest_run=None)
- with patch("ee.api.agentic_provisioning.views.tasks_facade.create_wizard_cloud_run", return_value=created):
+ with (
+ patch.object(GitHubIntegration, "first_for_team_repository", return_value=MagicMock()),
+ patch("ee.api.agentic_provisioning.views.tasks_facade.create_wizard_cloud_run", return_value=created),
+ ):
first = self._post_wizard_runs(self.team.id, {"repository": "octocat/one"})
second = self._post_wizard_runs(self.team.id, {"repository": "octocat/two"})
third = self._post_wizard_runs(self.team.id, {"repository": "octocat/three"})
@@ -216,11 +222,14 @@ class TestWizardResourceActions(ProvisioningTestBase):
assert third["Retry-After"]
@override_settings(WIZARD_CLOUD_RUN_OAUTH_CLIENT_ID="wizard-client-id")
- def test_wizard_runs_without_github_integration_returns_400(self):
- with patch(
- "ee.api.agentic_provisioning.views.tasks_facade.create_wizard_cloud_run",
- side_effect=ValueError("Team has no GitHub integration"),
+ def test_wizard_runs_rejects_repository_the_installation_cannot_access(self):
+ # No team integration can reach the repo -> fail fast without ever creating a run,
+ # so a grant for one installation can't report success for an unrelated owner/repo.
+ with (
+ patch.object(GitHubIntegration, "first_for_team_repository", return_value=None),
+ patch("ee.api.agentic_provisioning.views.tasks_facade.create_wizard_cloud_run") as mock_create,
):
response = self._post_wizard_runs(self.team.id, {"repository": "octocat/hello-world"})
assert response.status_code == 400
assert response.json()["error"]["code"] == "github_integration_required"
+ mock_create.assert_not_called()
diff --git a/ee/api/agentic_provisioning/views.py b/ee/api/agentic_provisioning/views.py
index 4a80ecc7c29b..3ae7cd73cc86 100644
--- a/ee/api/agentic_provisioning/views.py
+++ b/ee/api/agentic_provisioning/views.py
@@ -727,9 +727,29 @@ def _handle_new_user(
org_analytics_metadata=organization.get_analytics_metadata(),
)
+ # Optional drop-flow wizard block: link the GitHub grant to the bootstrap team and
+ # enqueue a cloud wizard run in the same call. A wizard failure never fails the
+ # request — the account exists, so the partner gets the account plus a structured
+ # wizard.error and retries via the granular resource actions. Partners that don't
+ # send a wizard block are unaffected (no wizard key, unchanged email behavior).
+ # Grants are region-local, so this request must hit the region that minted the grant.
+ wizard_config = configuration.get("wizard")
+ wizard_payload: dict[str, Any] | None = None
+ if isinstance(wizard_config, dict) and partner is not None:
+ wizard_payload = _process_wizard_block(partner=partner, user=user, team=team, wizard_config=wizard_config)
+
+ # Queued after the wizard block so the "we're setting up your repo" email only
+ # sends once the run actually exists; the email still goes out (without the
+ # repository paragraph) when the wizard block failed, since the account is real.
try:
reset_token = password_reset_token_generator.make_token(user)
- send_provisioning_welcome.delay(user.id, reset_token, partner_label)
+ wizard_repository: str | None = None
+ if wizard_payload is not None and "error" not in wizard_payload and isinstance(wizard_config, dict):
+ wizard_repository = str(wizard_config.get("repository"))
+ if wizard_repository:
+ send_provisioning_welcome.delay(user.id, reset_token, partner_label, repository=wizard_repository)
+ else:
+ send_provisioning_welcome.delay(user.id, reset_token, partner_label)
except Exception:
capture_exception(additional_properties={"user_id": user.id, "step": "provisioning_welcome_email"})
@@ -752,7 +772,59 @@ def _handle_new_user(
timeout=AUTH_CODE_TTL_SECONDS,
)
- return Response({"id": request_id, "type": "oauth", "oauth": {"code": code}})
+ response_body: dict[str, Any] = {"id": request_id, "type": "oauth", "oauth": {"code": code}}
+ if wizard_payload is not None:
+ response_body["wizard"] = wizard_payload
+ return Response(response_body)
+
+
+def _process_wizard_block(*, partner: OAuthApplication, user: User, team: Team, wizard_config: dict) -> dict[str, Any]:
+ """Run the bundled drop flow for a freshly bootstrapped account: link the GitHub
+ grant to the team, then enqueue the cloud wizard run.
+
+ Never raises — returns either the run payload ({task_id, run_id, status}) or
+ {"error": {code, message}} for the partner to branch on and retry granularly.
+ """
+ try:
+ grant_id = wizard_config.get("grant_id")
+ installation_id = wizard_config.get("installation_id")
+ repository = wizard_config.get("repository")
+ if not grant_id or not installation_id or not repository:
+ return {
+ "error": {
+ "code": "invalid_request",
+ "message": "wizard requires grant_id, installation_id and repository",
+ }
+ }
+
+ error, _integration, _already_linked = _link_github_grant_to_team(
+ partner=partner,
+ user=user,
+ team=team,
+ grant_id=str(grant_id),
+ installation_id=str(installation_id),
+ )
+ if error is not None:
+ return {"error": error.data.get("error", {"code": "invalid_request", "message": "GitHub link failed"})}
+
+ error, run_payload = _create_wizard_run(
+ partner=partner,
+ user_id=user.id,
+ team=team,
+ repository=str(repository),
+ branch=str(wizard_config.get("branch") or "") or None,
+ )
+ if error is not None:
+ return {
+ "error": error.data.get(
+ "error", {"code": "run_creation_failed", "message": "Failed to start the wizard run"}
+ )
+ }
+ assert run_payload is not None
+ return dict(run_payload)
+ except Exception:
+ capture_exception(additional_properties={"team_id": team.id, "step": "account_requests_wizard_block"})
+ return {"error": {"code": "run_creation_failed", "message": "Unexpected error starting the wizard run"}}
def _build_authorize_url(confirmation_secret: str, scopes: list[str], region: str = "") -> str:
@@ -2109,7 +2181,10 @@ def _apply_provisioned_onboarding_flags(user: User, team: Team) -> None:
"""Keep the app from routing a partner-provisioned account into onboarding on first
login. Only applied to unclaimed accounts (never logged in, no password set) so an
existing user going through the consent path keeps their onboarding state."""
- if user.last_login is not None or user.has_usable_password():
+ # Bootstrapped accounts store password="" (create_user skips set_password when the
+ # password is None), which Django counts as *usable* — treat it as no password.
+ has_password = bool(user.password) and user.has_usable_password()
+ if user.last_login is not None or has_password:
return
if user.onboarding_skipped_at is None:
user.onboarding_skipped_at = timezone.now()
@@ -2317,6 +2392,24 @@ def _create_wizard_run(
if error := _enforce_partner_rate_limit(partner, "wizard_runs"):
return error, None
+ # Verifying the grant user owns the installation doesn't prove the installation can
+ # reach the requested repo — a valid grant for one installation could otherwise report
+ # wizard success for an owner/repo it can't operate on. Fail fast instead (after the
+ # rate limits, so this GitHub call can't be used as an unthrottled probe).
+ if GitHubIntegration.first_for_team_repository(team.id, repository, source="integration") is None:
+ _capture_provisioning_event(
+ "wizard_run", "error", partner=partner, error_code="github_integration_required", team_id=team.id
+ )
+ return (
+ error_response(
+ "github_integration_required",
+ "The team does not have a GitHub integration that can access this repository",
+ resource_id=str(team.id),
+ status=400,
+ ),
+ None,
+ )
+
try:
created = tasks_facade.create_wizard_cloud_run(
team=team, user_id=user_id, repository=repository, branch=branch or None