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.

refactor(integrations): Extract github_callback (#59777)

Michael Matloka3a3d78bcf57a
diff --git a/posthog/api/github_callback/__init__.py b/posthog/api/github_callback/__init__.py
new file mode 100644
index 000000000000..053857781974
--- /dev/null
+++ b/posthog/api/github_callback/__init__.py
@@ -0,0 +1 @@
+"""GitHub OAuth/App callback handling, split out for clarity from ``posthog.api.integration``."""
diff --git a/posthog/api/github_callback/personal_finish.py b/posthog/api/github_callback/personal_finish.py
new file mode 100644
index 000000000000..418029de051a
--- /dev/null
+++ b/posthog/api/github_callback/personal_finish.py
@@ -0,0 +1,254 @@
+"""GitHub App install + user authorization callback handler for personal integrations.
+
+This is the view ``/complete/github-link/`` resolves to. The body is intentionally
+straight-line: figure out which flow we are completing (default install, OAuth-only
+fast path, OAuth discovery, or the team-orphan recovery flow), validate the
+server-side state, exchange the OAuth ``code`` for tokens, and upsert the
+``UserIntegration`` (and optionally the team ``Integration`` for the orphan flow).
+"""
+
+from typing import cast
+from urllib.parse import urlencode
+
+from django.core.cache import cache
+from django.http import HttpRequest, HttpResponseRedirect
+from django.shortcuts import redirect
+from django.views.decorators.http import require_http_methods
+
+import requests
+import structlog
+
+from posthog.api.github_callback import personal_state
+from posthog.api.github_callback.redirects import PERSONAL_INTEGRATIONS_SETTINGS_PATH, final_github_redirect
+from posthog.api.github_callback.types import (
+ APP_CONNECT_FROM_VALUES,
+ GITHUB_INSTALL_STATE_CACHE_PREFIX,
+ github_oauth_redirect_uri,
+ is_valid_github_installation_id,
+)
+from posthog.auth import session_auth_required
+from posthog.models.integration import GitHubInstallationAccess, GitHubIntegration, Integration
+from posthog.models.user import User
+from posthog.models.user_integration import user_github_integration_from_installation
+
+logger = structlog.get_logger(__name__)
+
+
+def _app_connect_from_from_state_query(request: HttpRequest) -> str | None:
+ """Best-effort: OAuth error callbacks may still include ``state``; read cache
+ (do not delete) to recover which first-party client started the flow so the
+ error redirect returns to the right place."""
+ state_raw = request.GET.get("state")
+ if not state_raw:
+ return None
+ token = personal_state.github_state_token(state_raw)
+ cache_key = f"{GITHUB_INSTALL_STATE_CACHE_PREFIX}{token}"
+ state_payload = cache.get(cache_key)
+ if not state_payload or state_payload.get("user_id") != request.user.id:
+ return None
+ connect_from = state_payload.get("connect_from")
+ return connect_from if connect_from in APP_CONNECT_FROM_VALUES else None
+
+
+@require_http_methods(["GET"])
+@session_auth_required
+def github_link_complete(request: HttpRequest) -> HttpResponseRedirect:
+ """GitHub App installation + user authorization callback.
+
+ **Install flow** (``/installations/new``): GitHub sends ``installation_id``,
+ ``code``, and ``state`` in the query string.
+
+ **OAuth-only flow** (``/login/oauth/authorize`` when the team already has the
+ app installed): GitHub sends only ``code`` and ``state``; ``installation_id``
+ is read from validated server-side state.
+
+ Steps: validate state, resolve ``installation_id``, exchange ``code`` for
+ user-to-server tokens, fetch installation token, create/update ``UserIntegration``.
+ """
+
+ user = cast(User, request.user)
+
+ # Which first-party client (if any) started this flow; controls the final
+ # redirect destination. Resolved from validated server-side state below.
+ connect_from_value: str | None = None
+
+ def _error(reason: str) -> HttpResponseRedirect:
+ logger.warning("github_link: redirecting with error", reason=reason, user_id=user.id)
+ return final_github_redirect(connect_from_value, error=reason)
+
+ # GitHub appends ?error=... when the user denied consent.
+ if github_error := request.GET.get("error"):
+ logger.warning(
+ "github_link: GitHub returned error on callback",
+ error=github_error,
+ description=request.GET.get("error_description"),
+ user_id=user.id,
+ )
+ connect_from_value = _app_connect_from_from_state_query(request)
+ return _error(github_error if github_error == "access_denied" else "github_oauth_error")
+
+ code = request.GET.get("code")
+ state_raw = request.GET.get("state")
+
+ if not code or not state_raw:
+ return _error("missing_params")
+
+ token = personal_state.github_state_token(state_raw)
+
+ # Validate state
+ cache_key = f"{GITHUB_INSTALL_STATE_CACHE_PREFIX}{token}"
+ state_payload = cache.get(cache_key)
+ if not state_payload or state_payload.get("user_id") != user.id:
+ return _error("invalid_state")
+ connect_from_value = state_payload.get("connect_from")
+ cache.delete(cache_key)
+
+ flow = state_payload.get("flow")
+ oauth_flow = flow == "oauth_authorize"
+ oauth_discover_flow = flow == "oauth_discover"
+ team_oauth_flow = flow == "team_oauth_authorize"
+ team_oauth_team_id: int | None = None
+ team_oauth_next: str | None = None
+ installation_ids: list[str] = []
+ if oauth_flow:
+ installation_id = state_payload.get("installation_id")
+ if not installation_id or not isinstance(installation_id, str):
+ return _error("missing_params")
+ # Do not require ``current_team`` to match: OAuth completes in a browser
+ # session whose active team may differ from the app that started the flow.
+ if not Integration.objects.filter(
+ kind="github", integration_id=installation_id, team__in=user.teams.all()
+ ).exists():
+ return _error("invalid_installation")
+ installation_ids = [installation_id]
+ elif team_oauth_flow:
+ # Triggered when the GitHub App is already installed on the org but no PostHog
+ # team has captured it (orphan installation). The frontend redirects the user
+ # through GitHub's User OAuth so we get a `code` for verify_user_installation_access.
+ installation_id = state_payload.get("installation_id")
+ team_oauth_team_id = state_payload.get("team_id")
+ team_oauth_next = state_payload.get("next") or None
+ if not installation_id or not isinstance(installation_id, str):
+ return _error("missing_params")
+ if not isinstance(team_oauth_team_id, int):
+ return _error("invalid_state")
+ # Confirm the user still has access to the team they started this flow from.
+ if not user.teams.filter(id=team_oauth_team_id).exists():
+ return _error("invalid_team")
+ installation_ids = [installation_id]
+ elif oauth_discover_flow:
+ pass
+ else:
+ installation_id = request.GET.get("installation_id")
+ if not installation_id:
+ return _error("missing_params")
+ installation_ids = [installation_id]
+
+ # Exchange code for user-to-server tokens
+ if oauth_flow or oauth_discover_flow or team_oauth_flow:
+ authorization = GitHubIntegration.github_user_from_code(code, redirect_uri=github_oauth_redirect_uri())
+ else:
+ authorization = GitHubIntegration.github_user_from_code(code)
+ if authorization is None:
+ return _error("exchange_failed")
+
+ if oauth_discover_flow:
+ try:
+ installation_ids = personal_state.github_user_installation_ids(authorization.access_token)
+ except requests.RequestException:
+ return _error("installation_fetch_failed")
+ if not installation_ids:
+ return personal_state.redirect_to_github_app_install(user, connect_from_value)
+
+ for installation_id in installation_ids:
+ if not is_valid_github_installation_id(installation_id):
+ return _error("invalid_installation_id")
+
+ for installation_id in installation_ids:
+ installation_id = str(installation_id)
+ # Verify the authorizing user actually has access to this installation.
+ # An attacker could use their own OAuth code with someone else's installation_id
+ # to obtain an installation token scoped to a different organisation's repos.
+ if not oauth_discover_flow:
+ try:
+ has_access = GitHubIntegration.verify_user_installation_access(
+ installation_id, authorization.access_token
+ )
+ except requests.RequestException:
+ logger.warning(
+ "github_link: installation ownership check failed",
+ installation_id=installation_id,
+ user_id=user.id,
+ exc_info=True,
+ )
+ return _error("installation_verify_failed")
+ if not has_access:
+ logger.warning(
+ "github_link: user does not have access to installation",
+ installation_id=installation_id,
+ user_id=user.id,
+ )
+ return _error("installation_not_authorized")
+
+ # Get installation info and access token
+ try:
+ installation_info = GitHubIntegration.client_request(f"installations/{installation_id}").json()
+ access_token_response = GitHubIntegration.client_request(
+ f"installations/{installation_id}/access_tokens", method="POST"
+ ).json()
+ except Exception:
+ logger.warning("github_link: failed to fetch installation info", exc_info=True)
+ return _error("installation_fetch_failed")
+
+ installation_access_token = access_token_response.get("token")
+ if not installation_access_token:
+ return _error("installation_token_failed")
+
+ token_expires_at = access_token_response.get("expires_at")
+ if not token_expires_at:
+ return _error("installation_token_failed")
+
+ user_github_integration_from_installation(
+ user,
+ GitHubInstallationAccess(
+ installation_id=installation_id,
+ installation_info=installation_info,
+ access_token=installation_access_token,
+ token_expires_at=token_expires_at,
+ repository_selection=access_token_response.get("repository_selection", "selected"),
+ ),
+ authorization,
+ )
+
+ if team_oauth_flow and team_oauth_team_id is not None:
+ installation_id = str(installation_ids[0])
+ # Create the team-level Integration that the user originally tried to install.
+ # ``integration_from_installation_id`` re-fetches the installation token, so it
+ # works whether or not another team in the org has already linked this install.
+ try:
+ team_integration = GitHubIntegration.integration_from_installation_id(
+ installation_id, team_oauth_team_id, user
+ )
+ except Exception:
+ logger.warning(
+ "github_link: failed to create team integration",
+ installation_id=installation_id,
+ team_id=team_oauth_team_id,
+ exc_info=True,
+ )
+ return _error("integration_create_failed")
+
+ # Mirror the fresh-install flow: stamp the connecting user's GitHub login on
+ # the team integration card.
+ team_integration.config["connecting_user_github_login"] = authorization.gh_login
+ team_integration.save(update_fields=["config"])
+
+ target = team_oauth_next or PERSONAL_INTEGRATIONS_SETTINGS_PATH
+ forwarded_params: dict[str, str] = {
+ "installation_id": installation_id,
+ "integration_id": str(team_integration.id),
+ }
+ joiner = "&" if "?" in target else "?"
+ return redirect(f"{target}{joiner}{urlencode(forwarded_params)}")
+
+ return final_github_redirect(connect_from_value)
diff --git a/posthog/api/github_callback/personal_state.py b/posthog/api/github_callback/personal_state.py
new file mode 100644
index 000000000000..dbac7d857172
--- /dev/null
+++ b/posthog/api/github_callback/personal_state.py
@@ -0,0 +1,100 @@
+"""State and URL helpers for the personal GitHub linking flow.
+
+The personal flow keeps a small JSON blob in the cache, keyed by a random
+``token``, that we look up when GitHub redirects back to us. Some helpers also
+build the off-host GitHub URLs (install page, user OAuth page) the user is
+sent to.
+"""
+
+from typing import Any
+from urllib.parse import parse_qs, urlencode
+
+from django.conf import settings
+from django.core.cache import cache
+from django.http import HttpResponseRedirect
+from django.shortcuts import redirect
+from django.utils.crypto import get_random_string
+
+import requests
+import structlog
+from rest_framework import exceptions
+
+from posthog.api.github_callback.types import (
+ GITHUB_INSTALL_STATE_CACHE_PREFIX,
+ GITHUB_INSTALL_STATE_TTL_SECONDS,
+ github_oauth_redirect_uri,
+)
+from posthog.models.instance_setting import get_instance_settings
+from posthog.models.user import User
+
+logger = structlog.get_logger(__name__)
+
+
+def github_state_token(state_raw: str) -> str:
+ """Pull the random token out of ``state``.
+
+ The frontend extracts the raw token from the URL-encoded ``state`` before
+ forwarding here, so ``state_raw`` is normally the 48-char random token.
+ Handle both forms so direct backend calls (e.g. in tests) and any future
+ flow changes work correctly.
+ """
+ state_params = parse_qs(state_raw)
+ return state_params["token"][0] if "token" in state_params else state_raw
+
+
+def github_user_installation_ids(user_access_token: str) -> list[str]:
+ """List GitHub App installations visible to a user-to-server token."""
+ response = requests.get(
+ "https://api.github.com/user/installations",
+ headers={
+ "Accept": "application/vnd.github+json",
+ "Authorization": f"Bearer {user_access_token}",
+ "X-GitHub-Api-Version": "2022-11-28",
+ },
+ params={"per_page": 100},
+ timeout=10,
+ )
+ if response.status_code != 200:
+ logger.warning("github_link: failed to list user installations", status_code=response.status_code)
+ raise requests.RequestException(f"Unexpected status {response.status_code} listing user installations")
+
+ installations = response.json().get("installations", [])
+ ids: list[str] = []
+ if isinstance(installations, list):
+ for installation in installations:
+ if isinstance(installation, dict) and installation.get("id") is not None:
+ ids.append(str(installation["id"]))
+ return ids
+
+
+def github_app_install_url(state: str) -> str:
+ """Build the GitHub App install URL."""
+ instance_settings = get_instance_settings(["GITHUB_APP_SLUG"])
+ app_slug = instance_settings.get("GITHUB_APP_SLUG")
+ if not app_slug:
+ raise exceptions.ValidationError("GitHub App is not configured on this instance (missing GITHUB_APP_SLUG).")
+ return f"https://github.com/apps/{app_slug}/installations/new?{urlencode({'state': state})}"
+
+
+def github_oauth_authorize_url(state: str) -> str:
+ """Build the GitHub App user authorization URL."""
+ if not settings.GITHUB_APP_CLIENT_ID:
+ raise exceptions.ValidationError("GitHub App client ID is not configured (GITHUB_APP_CLIENT_ID missing).")
+ return "https://github.com/login/oauth/authorize?" + urlencode(
+ {"client_id": settings.GITHUB_APP_CLIENT_ID, "redirect_uri": github_oauth_redirect_uri(), "state": state}
+ )
+
+
+def redirect_to_github_app_install(user: User, connect_from: str | None) -> HttpResponseRedirect:
+ """Continue from user OAuth discovery to app installation when no installation exists yet."""
+ token = get_random_string(48)
+ state = urlencode({"token": token, "source": "user_integration"})
+ install_state_payload: dict[str, Any] = {"user_id": user.id}
+ if connect_from:
+ install_state_payload["connect_from"] = connect_from
+ cache.set(
+ f"{GITHUB_INSTALL_STATE_CACHE_PREFIX}{token}",
+ install_state_payload,
+ timeout=GITHUB_INSTALL_STATE_TTL_SECONDS,
+ )
+ return redirect(github_app_install_url(state))
diff --git a/posthog/api/github_callback/redirects.py b/posthog/api/github_callback/redirects.py
new file mode 100644
index 000000000000..e3b422e5adf2
--- /dev/null
+++ b/posthog/api/github_callback/redirects.py
@@ -0,0 +1,45 @@
+"""Post-callback redirect helpers for the personal GitHub linking flow."""
+
+from urllib.parse import urlencode
+
+from django.http import HttpResponseRedirect
+from django.shortcuts import redirect
+
+from posthog.api.github_callback.types import MOBILE_GITHUB_CALLBACK_URL
+
+PERSONAL_INTEGRATIONS_SETTINGS_PATH = "/settings/user-personal-integrations"
+ACCOUNT_CONNECTED_GITHUB_INTEGRATION_PATH = "/account-connected/github-integration"
+
+
+class AppDeepLinkRedirect(HttpResponseRedirect):
+ """Redirect that also permits the mobile app's custom ``posthog://`` scheme.
+
+ Django's default ``HttpResponseRedirect`` rejects non-web schemes as unsafe
+ (``DisallowedRedirect``). The target here is a hardcoded first-party deep
+ link, not user input, so allowing the extra scheme is safe.
+ """
+
+ allowed_schemes = [*HttpResponseRedirect.allowed_schemes, "posthog"]
+
+
+def final_github_redirect(connect_from: str | None, *, error: str | None = None) -> HttpResponseRedirect:
+ """Pick the post-OAuth destination based on which client started the flow.
+
+ - ``posthog_mobile`` → the app's ``posthog://`` deep link so the in-app
+ browser auto-closes.
+ - ``posthog_code`` → the web ``/account-connected`` page that the desktop app
+ intercepts via its own deep link.
+ - anything else (web UI) → the personal integrations settings page.
+ """
+ app_base_urls: dict[str, str] = {
+ "posthog_mobile": MOBILE_GITHUB_CALLBACK_URL,
+ "posthog_code": ACCOUNT_CONNECTED_GITHUB_INTEGRATION_PATH,
+ }
+ if connect_from in app_base_urls:
+ params = {"provider": "github"}
+ if error:
+ params["error"] = error
+ return AppDeepLinkRedirect(f"{app_base_urls[connect_from]}?{urlencode(params)}")
+ if error:
+ return redirect(f"{PERSONAL_INTEGRATIONS_SETTINGS_PATH}?github_link_error={error}")
+ return redirect(f"{PERSONAL_INTEGRATIONS_SETTINGS_PATH}?github_link_success=1")
diff --git a/posthog/api/github_callback/team_services.py b/posthog/api/github_callback/team_services.py
new file mode 100644
index 000000000000..4b21761a10c8
--- /dev/null
+++ b/posthog/api/github_callback/team_services.py
@@ -0,0 +1,290 @@
+"""Team-level GitHub integration primitives.
+
+These wrap the three IO-heavy operations the ``IntegrationViewSet`` triggers:
+creating a new team integration from an OAuth ``code``, reusing an existing
+sibling install (``github/link_existing``), and minting a fresh OAuth URL when
+the install flow returns without a code (``github/oauth_authorize``). Keeping
+them out of the viewset lets the callback router compose the same logic.
+"""
+
+from datetime import UTC, datetime
+from typing import Any
+from urllib.parse import urlencode
+
+from django.conf import settings
+from django.core.cache import cache
+from django.db.models import Q
+from django.utils.crypto import get_random_string
+
+import requests
+import structlog
+from rest_framework.exceptions import ValidationError
+
+from posthog.api.github_callback.types import (
+ GITHUB_INSTALL_STATE_CACHE_PREFIX,
+ GITHUB_INSTALL_STATE_TTL_SECONDS,
+ github_oauth_redirect_uri,
+ is_valid_github_installation_id,
+)
+from posthog.models.integration import GitHubInstallationAccess, GitHubIntegration, Integration
+from posthog.models.organization import Organization
+from posthog.models.user import User
+from posthog.models.user_integration import UserIntegration, user_github_integration_from_installation
+from posthog.utils import is_relative_url
+
+logger = structlog.get_logger(__name__)
+
+GITHUB_LINK_EXISTING_ERROR_ORPHAN_INSTALLATION = "github_link_existing_orphan_installation"
+GITHUB_LINK_EXISTING_ERROR_PERSONAL_GITHUB_REQUIRED = "github_link_existing_personal_github_required"
+PERSONAL_GITHUB_REQUIRED_MESSAGE = (
+ "You must connect your personal GitHub account (via Linked Accounts) before linking an existing "
+ "installation, to confirm you have access to the GitHub App installation."
+)
+
+
+def installation_token_expires_at(integration: Integration) -> str:
+ """Compute an ISO 8601 timestamp for when the integration's installation token expires."""
+ refreshed_at = integration.config.get("refreshed_at", 0)
+ expires_in = integration.config.get("expires_in", 3600)
+ return datetime.fromtimestamp(refreshed_at + expires_in, tz=UTC).isoformat()
+
+
+def create_team_github_integration_from_oauth_code(
+ *,
+ user: User,
+ team_id: int,
+ installation_id: Any | None,
+ state_token: str | None,
+ code: str | None,
+) -> Integration:
+ """Body of the ``IntegrationSerializer.create`` GitHub branch.
+
+ Validates the cookie-paired server-side state token, exchanges the OAuth
+ ``code`` for user-to-server tokens, verifies the user actually has access
+ to ``installation_id`` on GitHub (so a stolen ``installation_id`` cannot
+ mint repo tokens for someone else's org), then upserts the team
+ ``Integration`` row and auto-creates a personal ``UserIntegration``.
+ """
+ if not installation_id:
+ raise ValidationError("An installation_id must be provided")
+
+ if not state_token:
+ raise ValidationError("A state token must be provided")
+
+ if not code:
+ raise ValidationError("An OAuth code must be provided")
+
+ cache_key = f"github_state:{user.id}"
+ expected_state = cache.get(cache_key)
+ if not expected_state or expected_state != state_token:
+ raise ValidationError("Invalid or expired state token")
+ cache.delete(cache_key)
+
+ # Exchange the OAuth code for the user's access token and identity.
+ # This requires GITHUB_APP_CLIENT_SECRET to be configured.
+ authorization = GitHubIntegration.github_user_from_code(code)
+ if authorization is None:
+ raise ValidationError("Failed to exchange the OAuth code — ensure GITHUB_APP_CLIENT_SECRET is configured")
+
+ # Verify the connecting user actually has access to this installation.
+ # Without this, an attacker could supply another tenant's installation_id
+ # with their own OAuth code and obtain an installation token scoped to
+ # the other tenant's repos.
+ if not is_valid_github_installation_id(installation_id):
+ raise ValidationError("Invalid installation_id")
+ try:
+ has_access = GitHubIntegration.verify_user_installation_access(installation_id, authorization.access_token)
+ except requests.RequestException:
+ logger.warning(
+ "github_integration_create: installation ownership check failed",
+ installation_id=installation_id,
+ user_id=user.id,
+ exc_info=True,
+ )
+ raise ValidationError("Failed to verify installation access")
+ if not has_access:
+ logger.warning(
+ "github_integration_create: user does not have access to installation",
+ installation_id=installation_id,
+ user_id=user.id,
+ )
+ raise ValidationError("You do not have access to this GitHub installation")
+
+ instance = GitHubIntegration.integration_from_installation_id(installation_id, team_id, user)
+
+ # Store the connecting user's GitHub login on the team integration
+ # (shown on the integration card) and auto-create a UserIntegration
+ # so the user immediately has personal GitHub credentials for
+ # PR authorship and identity attribution
+ instance.config["connecting_user_github_login"] = authorization.gh_login
+ instance.save(update_fields=["config"])
+ # Auto-create a UserIntegration so the user immediately has personal
+ # GitHub credentials. create_only=True uses get_or_create atomically —
+ # an existing personal integration (e.g. set up via Linked Accounts) is
+ # left untouched even under concurrent requests.
+ user_github_integration_from_installation(
+ user,
+ GitHubInstallationAccess(
+ installation_id=installation_id,
+ installation_info=instance.config,
+ access_token=instance.sensitive_config.get("access_token", ""),
+ token_expires_at=installation_token_expires_at(instance),
+ repository_selection=instance.config.get("repository_selection", "selected"),
+ ),
+ authorization,
+ create_only=True,
+ )
+
+ return instance
+
+
+def link_existing_team_github_integration(
+ *,
+ user: User,
+ organization: Organization,
+ team_id: int,
+ source_team_id: Any | None,
+ installation_id_param: Any | None,
+) -> Integration:
+ """Reuse a GitHub installation already linked to a sibling team in the same organization."""
+ if installation_id_param and not is_valid_github_installation_id(installation_id_param):
+ raise ValidationError("Invalid installation_id")
+
+ # installation_id is stored in JSONB and historically written as either a
+ # string or a number, so match both representations.
+ installation_id_match = (
+ Q(config__installation_id=str(installation_id_param)) | Q(config__installation_id=int(installation_id_param))
+ if installation_id_param
+ else None
+ )
+
+ if source_team_id:
+ try:
+ source_team_id_int = int(source_team_id)
+ except (TypeError, ValueError):
+ raise ValidationError("source_team_id must be an integer")
+
+ if not organization.teams.filter(id=source_team_id_int).exists():
+ raise ValidationError("Source team not found in your organization")
+
+ qs = Integration.objects.filter(team_id=source_team_id_int, kind="github")
+ # When the source team has multiple GitHub installations linked, the
+ # caller must pass installation_id to disambiguate.
+ if installation_id_match is not None:
+ qs = qs.filter(installation_id_match)
+
+ source = qs.order_by("id").first()
+ if source is None:
+ raise ValidationError("Source team does not have a GitHub integration")
+ elif installation_id_param:
+ existing = (
+ Integration.objects.filter(
+ team__organization_id=organization.id,
+ kind="github",
+ )
+ .filter(installation_id_match)
+ .order_by("id")
+ .first()
+ )
+ if existing is None:
+ raise ValidationError(
+ "No team in your organization has this GitHub installation linked",
+ code=GITHUB_LINK_EXISTING_ERROR_ORPHAN_INSTALLATION,
+ )
+ source = existing
+ else:
+ raise ValidationError("source_team_id or installation_id is required")
+
+ installation_id = (source.config or {}).get("installation_id")
+ if not installation_id:
+ raise ValidationError("Source integration is missing installation_id")
+
+ # Confirms the requesting user has access to the installation on GitHub itself,
+ # so cross-team admin access alone can't mint tokens for repos they can't see.
+ user_github_integration = UserIntegration.objects.filter(user=user, kind="github").order_by("-created_at").first()
+ user_access_token = (
+ user_github_integration.sensitive_config.get("access_token") if user_github_integration else None
+ )
+ if not user_access_token:
+ raise ValidationError(
+ PERSONAL_GITHUB_REQUIRED_MESSAGE,
+ code=GITHUB_LINK_EXISTING_ERROR_PERSONAL_GITHUB_REQUIRED,
+ )
+ try:
+ has_access = GitHubIntegration.verify_user_installation_access(str(installation_id), user_access_token)
+ except requests.RequestException:
+ logger.warning(
+ "github_link_existing: installation ownership check failed",
+ installation_id=installation_id,
+ user_id=user.id,
+ exc_info=True,
+ )
+ raise ValidationError("Failed to verify installation access")
+ if not has_access:
+ logger.warning(
+ "github_link_existing: user does not have access to installation",
+ installation_id=installation_id,
+ user_id=user.id,
+ )
+ raise ValidationError(
+ PERSONAL_GITHUB_REQUIRED_MESSAGE,
+ code=GITHUB_LINK_EXISTING_ERROR_PERSONAL_GITHUB_REQUIRED,
+ )
+
+ instance = GitHubIntegration.integration_from_installation_id(str(installation_id), team_id, user)
+
+ source_login = (source.config or {}).get("connecting_user_github_login")
+ if source_login and not (instance.config or {}).get("connecting_user_github_login"):
+ instance.config["connecting_user_github_login"] = source_login
+ instance.save(update_fields=["config"])
+
+ return instance
+
+
+def build_team_oauth_authorize_url(
+ *,
+ user_id: int,
+ team_id: int,
+ installation_id: Any | None,
+ next_url: str,
+ connect_from: str | None,
+) -> str:
+ """Mint a User OAuth URL to bootstrap a fresh ``code`` when the install flow returns without one."""
+ if not installation_id:
+ raise ValidationError("installation_id is required")
+
+ if not is_valid_github_installation_id(installation_id):
+ raise ValidationError("Invalid installation_id")
+
+ # Open-redirect guard for the success-redirect to ``next``.
+ if next_url and not is_relative_url(next_url):
+ raise ValidationError("next must be a relative path starting with /")
+
+ client_id = settings.GITHUB_APP_CLIENT_ID
+ if not client_id:
+ raise ValidationError("GitHub App client ID is not configured")
+
+ token = get_random_string(48)
+ state_payload: dict[str, Any] = {
+ "user_id": user_id,
+ "team_id": team_id,
+ "installation_id": str(installation_id),
+ "flow": "team_oauth_authorize",
+ "next": next_url,
+ }
+ if connect_from:
+ state_payload["connect_from"] = connect_from
+
+ cache.set(
+ f"{GITHUB_INSTALL_STATE_CACHE_PREFIX}{token}",
+ state_payload,
+ timeout=GITHUB_INSTALL_STATE_TTL_SECONDS,
+ )
+
+ return "https://github.com/login/oauth/authorize?" + urlencode(
+ {
+ "client_id": client_id,
+ "redirect_uri": github_oauth_redirect_uri(),
+ "state": urlencode({"token": token}),
+ }
+ )
diff --git a/posthog/api/github_callback/types.py b/posthog/api/github_callback/types.py
new file mode 100644
index 000000000000..c3775e9c9954
--- /dev/null
+++ b/posthog/api/github_callback/types.py
@@ -0,0 +1,38 @@
+"""Constants and small helpers shared across the GitHub callback modules.
+
+These were previously inlined in ``posthog.api.integration`` and
+``posthog.api.user_integration``. Grouping them avoids duplication and keeps
+the callback modules small.
+"""
+
+import re
+
+from django.conf import settings
+
+# Server-side state cache used by the personal GitHub linking flow (the install
+# callback and the OAuth-only fast paths). Keys are written when a flow starts
+# and consumed when GitHub redirects back to us.
+GITHUB_INSTALL_STATE_CACHE_PREFIX = "github_user_install_state:"
+GITHUB_INSTALL_STATE_TTL_SECONDS = 10 * 60
+
+# Native deep link the mobile app (apps/mobile) registers as the OAuth return
+# URL. The in-app browser (ASWebAuthenticationSession / Custom Tabs) closes and
+# returns control to the app when the callback 302s here.
+MOBILE_GITHUB_CALLBACK_URL = "posthog://github/callback"
+
+# ``connect_from`` values for first-party clients that use the lightweight app
+# linking flow (OAuth-only when the team already has the GitHub App installed,
+# otherwise discover/install) and return to a client-specific destination.
+APP_CONNECT_FROM_VALUES = ("posthog_code", "posthog_mobile")
+
+# GitHub App installation IDs are always positive integers. Reject anything else
+# before it touches URL construction.
+_GITHUB_INSTALLATION_ID_RE = re.compile(r"\d{1,20}")
+
+
+def github_oauth_redirect_uri() -> str:
+ return f"{settings.SITE_URL.rstrip('/')}/complete/github-link/"
+
+
+def is_valid_github_installation_id(value: object) -> bool:
+ return value is not None and bool(_GITHUB_INSTALLATION_ID_RE.fullmatch(str(value)))
diff --git a/posthog/api/integration.py b/posthog/api/integration.py
index 24e29c52ee4e..abb4e071df37 100644
--- a/posthog/api/integration.py
+++ b/posthog/api/integration.py
@@ -1,20 +1,16 @@
import os
import re
import json
-from datetime import UTC, datetime
from typing import Any, cast
from urllib.parse import urlencode
from django.conf import settings
from django.core.cache import cache
-from django.db.models import Q
from django.http import HttpResponse
from django.shortcuts import redirect
from django.utils import timezone
-from django.utils.crypto import get_random_string
import stripe
-import requests
import structlog
from anthropic import APIConnectionError, APIStatusError, AuthenticationError, PermissionDeniedError
from django_filters.rest_framework import DjangoFilterBackend
@@ -25,6 +21,11 @@ from rest_framework.permissions import IsAuthenticated
from rest_framework.request import Request
from rest_framework.response import Response
+from posthog.api.github_callback.team_services import (
+ build_team_oauth_authorize_url,
+ create_team_github_integration_from_oauth_code,
+ link_existing_team_github_integration,
+)
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.api.shared import UserBasicSerializer
from posthog.api.utils import action
@@ -48,7 +49,6 @@ from posthog.models.integration import (
DatabricksIntegrationError,
EmailIntegration,
FirebaseIntegration,
- GitHubInstallationAccess,
GitHubIntegration,
GitHubIntegrationError,
GitLabIntegration,
@@ -65,7 +65,6 @@ from posthog.models.integration import (
TwilioIntegration,
defer_repository_cache_fields,
)
-from posthog.models.user_integration import UserIntegration, user_github_integration_from_installation
from posthog.permissions import (
AccessControlPermission,
APIScopePermission,
@@ -75,26 +74,12 @@ from posthog.permissions import (
)
from posthog.rate_limit import GitHubRepositoryRefreshThrottle
from posthog.rbac.user_access_control import UserAccessControlSerializerMixin
-from posthog.utils import is_relative_url
logger = structlog.get_logger(__name__)
-GITHUB_INSTALL_STATE_CACHE_PREFIX = "github_user_install_state:"
-GITHUB_INSTALL_STATE_TTL_SECONDS = 10 * 60
-
-GITHUB_LINK_EXISTING_ERROR_ORPHAN_INSTALLATION = "github_link_existing_orphan_installation"
-GITHUB_LINK_EXISTING_ERROR_PERSONAL_GITHUB_REQUIRED = "github_link_existing_personal_github_required"
-PERSONAL_GITHUB_REQUIRED_MESSAGE = (
- "You must connect your personal GitHub account (via Linked Accounts) before linking an existing "
- "installation, to confirm you have access to the GitHub App installation."
-)
GITHUB_REPOSITORY_NAME_RE = re.compile(r"[A-Za-z0-9_.\-]+")
-def github_oauth_redirect_uri() -> str:
- return f"{settings.SITE_URL.rstrip('/')}/complete/github-link/"
-
-
def validate_github_repository_name(repo: str) -> str:
"""Validate repository paths accepted by GitHub integration endpoints."""
parts = repo.split("/")
@@ -132,13 +117,6 @@ def _verify_stripe_install_signature(state: str, user_id: str, account_id: str,
return False
-def _installation_token_expires_at(integration: Integration) -> str:
- """Compute an ISO 8601 timestamp for when the integration's installation token expires."""
- refreshed_at = integration.config.get("refreshed_at", 0)
- expires_in = integration.config.get("expires_in", 3600)
- return datetime.fromtimestamp(refreshed_at + expires_in, tz=UTC).isoformat()
-
-
def _ensure_oauth_token_valid(instance: Integration) -> None:
"""Check that an OAuth integration's token is usable, attempting refresh if needed.
@@ -367,86 +345,14 @@ class IntegrationSerializer(serializers.ModelSerializer, UserAccessControlSerial
elif validated_data["kind"] == "github":
config = validated_data.get("config", {})
- installation_id = config.get("installation_id")
- state = config.get("state")
- code = config.get("code")
-
- if not installation_id:
- raise ValidationError("An installation_id must be provided")
-
- if not state:
- raise ValidationError("A state token must be provided")
-
- if not code:
- raise ValidationError("An OAuth code must be provided")
-
- cache_key = f"github_state:{request.user.id}"
- expected_state = cache.get(cache_key)
- if not expected_state or expected_state != state:
- raise ValidationError("Invalid or expired state token")
- cache.delete(cache_key)
-
- # Exchange the OAuth code for the user's access token and identity.
- # This requires GITHUB_APP_CLIENT_SECRET to be configured.
- authorization = GitHubIntegration.github_user_from_code(code)
- if authorization is None:
- raise ValidationError(
- "Failed to exchange the OAuth code — ensure GITHUB_APP_CLIENT_SECRET is configured"
- )
-
- # Verify the connecting user actually has access to this installation.
- # Without this, an attacker could supply another tenant's installation_id
- # with their own OAuth code and obtain an installation token scoped to
- # the other tenant's repos.
- if not re.fullmatch(r"\d{1,20}", str(installation_id)):
- raise ValidationError("Invalid installation_id")
- try:
- has_access = GitHubIntegration.verify_user_installation_access(
- installation_id, authorization.access_token
- )
- except requests.RequestException:
- logger.warning(
- "github_integration_create: installation ownership check failed",
- installation_id=installation_id,
- user_id=request.user.id,
- exc_info=True,
- )
- raise ValidationError("Failed to verify installation access")
- if not has_access:
- logger.warning(
- "github_integration_create: user does not have access to installation",
- installation_id=installation_id,
- user_id=request.user.id,
- )
- raise ValidationError("You do not have access to this GitHub installation")
-
- instance = GitHubIntegration.integration_from_installation_id(installation_id, team_id, request.user)
-
- # Store the connecting user's GitHub login on the team integration
- # (shown on the integration card) and auto-create a UserIntegration
- # so the user immediately has personal GitHub credentials for
- # PR authorship and identity attribution
- instance.config["connecting_user_github_login"] = authorization.gh_login
- instance.save(update_fields=["config"])
- # Auto-create a UserIntegration so the user immediately has personal
- # GitHub credentials. create_only=True uses get_or_create atomically —
- # an existing personal integration (e.g. set up via Linked Accounts) is
- # left untouched even under concurrent requests.
- user_github_integration_from_installation(
- request.user,
- GitHubInstallationAccess(
- installation_id=installation_id,
- installation_info=instance.config,
- access_token=instance.sensitive_config.get("access_token", ""),
- token_expires_at=_installation_token_expires_at(instance),
- repository_selection=instance.config.get("repository_selection", "selected"),
- ),
- authorization,
- create_only=True,
+ return create_team_github_integration_from_oauth_code(
+ user=request.user,
+ team_id=team_id,
+ installation_id=config.get("installation_id"),
+ state_token=config.get("state"),
+ code=config.get("code"),
)
- return instance
-
elif validated_data["kind"] == "gitlab":
config = validated_data.get("config", {})
hostname = config.get("hostname")
@@ -1139,153 +1045,27 @@ class IntegrationViewSet(
@action(methods=["POST"], detail=False, url_path="github/link_existing")
def github_link_existing(self, request: Request, *args: Any, **kwargs: Any) -> Response:
"""Reuse a GitHub installation already linked to a sibling team in the same organization."""
- source_team_id = request.data.get("source_team_id")
- installation_id_param = request.data.get("installation_id")
-
- if installation_id_param and not re.fullmatch(r"\d{1,20}", str(installation_id_param)):
- raise ValidationError("Invalid installation_id")
-
- # installation_id is stored in JSONB and historically written as either a
- # string or a number, so match both representations.
- installation_id_match = (
- Q(config__installation_id=str(installation_id_param))
- | Q(config__installation_id=int(installation_id_param))
- if installation_id_param
- else None
- )
-
- if source_team_id:
- try:
- source_team_id_int = int(source_team_id)
- except (TypeError, ValueError):
- raise ValidationError("source_team_id must be an integer")
-
- if not self.organization.teams.filter(id=source_team_id_int).exists():
- raise ValidationError("Source team not found in your organization")
-
- qs = Integration.objects.filter(team_id=source_team_id_int, kind="github")
- # When the source team has multiple GitHub installations linked, the
- # caller must pass installation_id to disambiguate.
- if installation_id_match is not None:
- qs = qs.filter(installation_id_match)
-
- source = qs.order_by("id").first()
- if source is None:
- raise ValidationError("Source team does not have a GitHub integration")
- elif installation_id_param:
- existing = (
- Integration.objects.filter(
- team__organization_id=self.organization_id,
- kind="github",
- )
- .filter(installation_id_match)
- .order_by("id")
- .first()
- )
- if existing is None:
- raise ValidationError(
- "No team in your organization has this GitHub installation linked",
- code=GITHUB_LINK_EXISTING_ERROR_ORPHAN_INSTALLATION,
- )
- source = existing
- else:
- raise ValidationError("source_team_id or installation_id is required")
-
- installation_id = (source.config or {}).get("installation_id")
- if not installation_id:
- raise ValidationError("Source integration is missing installation_id")
-
- # Confirms the requesting user has access to the installation on GitHub itself,
- # so cross-team admin access alone can't mint tokens for repos they can't see.
- user_github_integration = (
- UserIntegration.objects.filter(user=cast(User, request.user), kind="github").order_by("-created_at").first()
- )
- user_access_token = (
- user_github_integration.sensitive_config.get("access_token") if user_github_integration else None
- )
- if not user_access_token:
- raise ValidationError(
- PERSONAL_GITHUB_REQUIRED_MESSAGE,
- code=GITHUB_LINK_EXISTING_ERROR_PERSONAL_GITHUB_REQUIRED,
- )
- try:
- has_access = GitHubIntegration.verify_user_installation_access(str(installation_id), user_access_token)
- except requests.RequestException:
- logger.warning(
- "github_link_existing: installation ownership check failed",
- installation_id=installation_id,
- user_id=request.user.id,
- exc_info=True,
- )
- raise ValidationError("Failed to verify installation access")
- if not has_access:
- logger.warning(
- "github_link_existing: user does not have access to installation",
- installation_id=installation_id,
- user_id=request.user.id,
- )
- raise ValidationError(
- PERSONAL_GITHUB_REQUIRED_MESSAGE,
- code=GITHUB_LINK_EXISTING_ERROR_PERSONAL_GITHUB_REQUIRED,
- )
-
- instance = GitHubIntegration.integration_from_installation_id(
- str(installation_id), self.team_id, cast(User, request.user)
+ instance = link_existing_team_github_integration(
+ user=cast(User, request.user),
+ organization=self.organization,
+ team_id=self.team_id,
+ source_team_id=request.data.get("source_team_id"),
+ installation_id_param=request.data.get("installation_id"),
)
-
- source_login = (source.config or {}).get("connecting_user_github_login")
- if source_login and not (instance.config or {}).get("connecting_user_github_login"):
- instance.config["connecting_user_github_login"] = source_login
- instance.save(update_fields=["config"])
-
return Response(self.get_serializer(instance).data)
@action(methods=["POST"], detail=False, url_path="github/oauth_authorize")
def github_oauth_authorize(self, request: Request, *args: Any, **kwargs: Any) -> Response:
"""Mint a User OAuth URL to bootstrap a fresh `code` when the install flow returns without one."""
- installation_id = request.data.get("installation_id")
- next_url = str(request.data.get("next") or "")
- connect_from = request.data.get("connect_from") if request.data.get("connect_from") == "posthog_code" else None
-
- if not installation_id:
- raise ValidationError("installation_id is required")
-
- if not re.fullmatch(r"\d{1,20}", str(installation_id)):
- raise ValidationError("Invalid installation_id")
-
- # Open-redirect guard for the success-redirect to `next`.
- if next_url and not is_relative_url(next_url):
- raise ValidationError("next must be a relative path starting with /")
-
- client_id = settings.GITHUB_APP_CLIENT_ID
- if not client_id:
- raise ValidationError("GitHub App client ID is not configured")
-
- token = get_random_string(48)
- state_payload: dict[str, Any] = {
- "user_id": request.user.id,
- "team_id": self.team_id,
- "installation_id": str(installation_id),
- "flow": "team_oauth_authorize",
- "next": next_url,
- }
- if connect_from:
- state_payload["connect_from"] = connect_from
-
- cache.set(
- f"{GITHUB_INSTALL_STATE_CACHE_PREFIX}{token}",
- state_payload,
- timeout=GITHUB_INSTALL_STATE_TTL_SECONDS,
- )
-
- oauth_url = "https://github.com/login/oauth/authorize?" + urlencode(
- {
- "client_id": client_id,
- "redirect_uri": github_oauth_redirect_uri(),
- "state": urlencode({"token": token}),
- }
+ oauth_url = build_team_oauth_authorize_url(
+ user_id=cast(User, request.user).id,
+ team_id=self.team_id,
+ installation_id=request.data.get("installation_id"),
+ next_url=str(request.data.get("next") or ""),
+ connect_from=request.data.get("connect_from")
+ if request.data.get("connect_from") == "posthog_code"
+ else None,
)
-
return Response({"oauth_url": oauth_url})
@extend_schema(request=None, responses={200: GitHubReposRefreshResponseSerializer})
diff --git a/posthog/api/test/test_user_integration.py b/posthog/api/test/test_user_integration.py
index cfa7c7cd84c4..7e706c579195 100644
--- a/posthog/api/test/test_user_integration.py
+++ b/posthog/api/test/test_user_integration.py
@@ -134,7 +134,7 @@ class TestUserIntegrationEndpoints(APIBaseTest):
@override_settings(GITHUB_APP_CLIENT_ID="client_id")
@patch(
- "posthog.api.user_integration.get_instance_settings",
+ "posthog.api.github_callback.personal_state.get_instance_settings",
return_value={"GITHUB_APP_SLUG": "posthog-dev"},
)
def test_github_start_returns_install_url_when_no_team_github(self, _mock_settings):
@@ -165,7 +165,7 @@ class TestUserIntegrationEndpoints(APIBaseTest):
@override_settings(GITHUB_APP_CLIENT_ID="gh_client_123")
@patch(
- "posthog.api.user_integration.get_instance_settings",
+ "posthog.api.github_callback.personal_state.get_instance_settings",
return_value={"GITHUB_APP_SLUG": "posthog-dev"},
)
def test_github_start_returns_install_url_even_when_team_has_github_integration(self, _mock_settings):
@@ -212,7 +212,7 @@ class TestUserIntegrationEndpoints(APIBaseTest):
@override_settings(GITHUB_APP_CLIENT_ID="gh_client_123")
@patch(
- "posthog.api.user_integration.get_instance_settings",
+ "posthog.api.github_callback.personal_state.get_instance_settings",
return_value={"GITHUB_APP_SLUG": "posthog-dev"},
)
def test_github_start_posthog_code_skips_fast_path_when_already_linked(self, _mock_settings):
@@ -244,7 +244,7 @@ class TestUserIntegrationEndpoints(APIBaseTest):
@override_settings(GITHUB_APP_CLIENT_ID="gh_client_123")
@patch("posthog.api.user_integration._has_unlinked_github_installations", return_value=False)
@patch(
- "posthog.api.user_integration.get_instance_settings",
+ "posthog.api.github_callback.personal_state.get_instance_settings",
return_value={"GITHUB_APP_SLUG": "posthog-dev"},
)
def test_github_start_rejects_when_all_installations_linked(self, _mock_settings, _mock_unlinked):
@@ -261,7 +261,7 @@ class TestUserIntegrationEndpoints(APIBaseTest):
def test_github_start_without_app_slug_returns_400(self):
with patch(
- "posthog.api.user_integration.get_instance_settings",
+ "posthog.api.github_callback.personal_state.get_instance_settings",
return_value={"GITHUB_APP_SLUG": ""},
):
response = self.client.post("/api/users/@me/integrations/github/start/")
@@ -384,7 +384,7 @@ class TestUserIntegrationEndpoints(APIBaseTest):
SITE_URL="https://us.posthog.com",
)
@patch(
- "posthog.api.user_integration.get_instance_settings",
+ "posthog.api.github_callback.personal_state.get_instance_settings",
return_value={"GITHUB_APP_SLUG": "posthog-dev"},
)
@patch("posthog.api.user_integration.requests.get")
diff --git a/posthog/api/user_integration.py b/posthog/api/user_integration.py
index d9f435bdca9f..ee4f057fa63b 100644
--- a/posthog/api/user_integration.py
+++ b/posthog/api/user_integration.py
@@ -11,15 +11,10 @@ Login management is fully handled by ``UserSocialAuth`` (python-social-auth) and
is not controlled here.
"""
-import re
from typing import Any, cast
-from urllib.parse import parse_qs, urlencode
+from urllib.parse import urlencode
-from django.conf import settings
from django.core.cache import cache
-from django.http import HttpRequest, HttpResponseRedirect
-from django.shortcuts import redirect
-from django.views.decorators.http import require_http_methods
import requests
import structlog
@@ -30,151 +25,29 @@ from rest_framework.permissions import IsAuthenticated
from rest_framework.request import Request
from rest_framework.response import Response
-from posthog.api.integration import (
+from posthog.api.github_callback.personal_state import github_app_install_url, github_oauth_authorize_url
+from posthog.api.github_callback.types import (
+ APP_CONNECT_FROM_VALUES,
GITHUB_INSTALL_STATE_CACHE_PREFIX,
GITHUB_INSTALL_STATE_TTL_SECONDS,
+)
+from posthog.api.integration import (
GitHubBranchesQuerySerializer,
GitHubBranchesResponseSerializer,
GitHubReposQuerySerializer,
GitHubReposRefreshResponseSerializer,
GitHubReposResponseSerializer,
- github_oauth_redirect_uri,
validate_github_repository_name,
)
-from posthog.auth import (
- OAuthAccessTokenAuthentication,
- PersonalAPIKeyAuthentication,
- SessionAuthentication,
- session_auth_required,
-)
-from posthog.models.instance_setting import get_instance_settings
-from posthog.models.integration import (
- GITHUB_REPOSITORY_REFRESH_COOLDOWN_SECONDS,
- GitHubInstallationAccess,
- GitHubIntegration,
- Integration,
-)
+from posthog.auth import OAuthAccessTokenAuthentication, PersonalAPIKeyAuthentication, SessionAuthentication
+from posthog.models.integration import GITHUB_REPOSITORY_REFRESH_COOLDOWN_SECONDS, Integration
from posthog.models.user import User
-from posthog.models.user_integration import (
- UserGitHubIntegration,
- UserIntegration,
- user_github_integration_from_installation,
-)
+from posthog.models.user_integration import UserGitHubIntegration, UserIntegration
from posthog.permissions import APIScopePermission
from posthog.rate_limit import UserAuthenticationThrottle
logger = structlog.get_logger(__name__)
-PERSONAL_INTEGRATIONS_SETTINGS_PATH = "/settings/user-personal-integrations"
-ACCOUNT_CONNECTED_GITHUB_INTEGRATION_PATH = "/account-connected/github-integration"
-# Native deep link the mobile app (apps/mobile) registers as the OAuth return
-# URL. The in-app browser (ASWebAuthenticationSession / Custom Tabs) closes and
-# returns control to the app when the callback 302s here.
-MOBILE_GITHUB_CALLBACK_URL = "posthog://github/callback"
-# ``connect_from`` values for first-party clients that use the lightweight app
-# linking flow (OAuth-only when the team already has the GitHub App installed,
-# otherwise discover/install) and return to a client-specific destination.
-APP_CONNECT_FROM_VALUES = ("posthog_code", "posthog_mobile")
-
-
-class _AppDeepLinkRedirect(HttpResponseRedirect):
- """Redirect that also permits the mobile app's custom ``posthog://`` scheme.
-
- Django's default ``HttpResponseRedirect`` rejects non-web schemes as unsafe
- (``DisallowedRedirect``). The target here is a hardcoded first-party deep
- link, not user input, so allowing the extra scheme is safe.
- """
-
- allowed_schemes = [*HttpResponseRedirect.allowed_schemes, "posthog"]
-
-
-def _final_github_redirect(connect_from: str | None, *, error: str | None = None) -> HttpResponseRedirect:
- """Pick the post-OAuth destination based on which client started the flow.
-
- - ``posthog_mobile`` → the app's ``posthog://`` deep link so the in-app
- browser auto-closes.
- - ``posthog_code`` → the web ``/account-connected`` page that the desktop app
- intercepts via its own deep link.
- - anything else (web UI) → the personal integrations settings page.
- """
- app_base_urls: dict[str, str] = {
- "posthog_mobile": MOBILE_GITHUB_CALLBACK_URL,
- "posthog_code": ACCOUNT_CONNECTED_GITHUB_INTEGRATION_PATH,
- }
- if connect_from in app_base_urls:
- params = {"provider": "github"}
- if error:
- params["error"] = error
- return _AppDeepLinkRedirect(f"{app_base_urls[connect_from]}?{urlencode(params)}")
- if error:
- return redirect(f"{PERSONAL_INTEGRATIONS_SETTINGS_PATH}?github_link_error={error}")
- return redirect(f"{PERSONAL_INTEGRATIONS_SETTINGS_PATH}?github_link_success=1")
-
-
-def _github_oauth_authorize_url(state: str) -> str:
- """Build the GitHub App user authorization URL."""
- if not settings.GITHUB_APP_CLIENT_ID:
- raise exceptions.ValidationError("GitHub App client ID is not configured (GITHUB_APP_CLIENT_ID missing).")
- return "https://github.com/login/oauth/authorize?" + urlencode(
- {"client_id": settings.GITHUB_APP_CLIENT_ID, "redirect_uri": github_oauth_redirect_uri(), "state": state}
- )
-
-
-def _github_app_install_url(state: str) -> str:
- """Build the GitHub App install URL."""
- instance_settings = get_instance_settings(["GITHUB_APP_SLUG"])
- app_slug = instance_settings.get("GITHUB_APP_SLUG")
- if not app_slug:
- raise exceptions.ValidationError("GitHub App is not configured on this instance (missing GITHUB_APP_SLUG).")
- return f"https://github.com/apps/{app_slug}/installations/new?{urlencode({'state': state})}"
-
-
-def _github_state_token(state_raw: str) -> str:
- state_params = parse_qs(state_raw)
- return state_params["token"][0] if "token" in state_params else state_raw
-
-
-def _github_user_installation_ids(user_access_token: str) -> list[str]:
- """List GitHub App installations visible to a user-to-server token."""
- response = requests.get(
- "https://api.github.com/user/installations",
- headers={
- "Accept": "application/vnd.github+json",
- "Authorization": f"Bearer {user_access_token}",
- "X-GitHub-Api-Version": "2022-11-28",
- },
- params={"per_page": 100},
- timeout=10,
- )
- if response.status_code != 200:
- logger.warning("github_link: failed to list user installations", status_code=response.status_code)
- raise requests.RequestException(f"Unexpected status {response.status_code} listing user installations")
-
- installations = response.json().get("installations", [])
- ids: list[str] = []
- if isinstance(installations, list):
- for installation in installations:
- if isinstance(installation, dict) and installation.get("id") is not None:
- ids.append(str(installation["id"]))
- return ids
-
-
-def _redirect_to_github_app_install(user: User, connect_from: str | None) -> HttpResponseRedirect:
- """Continue from user OAuth discovery to app installation when no installation exists yet."""
- from django.utils.crypto import get_random_string
-
- token = get_random_string(48)
- state = urlencode({"token": token, "source": "user_integration"})
- install_state_payload: dict[str, Any] = {"user_id": user.id}
- if connect_from:
- install_state_payload["connect_from"] = connect_from
- cache.set(
- f"{GITHUB_INSTALL_STATE_CACHE_PREFIX}{token}",
- install_state_payload,
- timeout=GITHUB_INSTALL_STATE_TTL_SECONDS,
- )
- return redirect(_github_app_install_url(state))
-
class UserGitHubAccountSerializer(serializers.Serializer):
type = serializers.CharField(
@@ -449,7 +322,7 @@ class UserIntegrationViewSet(viewsets.GenericViewSet):
{"user_id": user.id, "connect_from": connect_from, "flow": "oauth_discover"},
timeout=GITHUB_INSTALL_STATE_TTL_SECONDS,
)
- return Response({"install_url": _github_oauth_authorize_url(state), "connect_flow": "oauth_discover"})
+ return Response({"install_url": github_oauth_authorize_url(state), "connect_flow": "oauth_discover"})
# If the user already has linked integrations, check whether there are
# any GitHub App installations they haven't linked yet. If everything
@@ -470,237 +343,12 @@ class UserIntegrationViewSet(viewsets.GenericViewSet):
)
return Response(
{
- "install_url": _github_app_install_url(state),
+ "install_url": github_app_install_url(state),
"connect_flow": "app_install",
}
)
-def _app_connect_from_from_state_query(request: HttpRequest) -> str | None:
- """Best-effort: OAuth error callbacks may still include ``state``; read cache
- (do not delete) to recover which first-party client started the flow so the
- error redirect returns to the right place."""
- state_raw = request.GET.get("state")
- if not state_raw:
- return None
- token = _github_state_token(state_raw)
- cache_key = f"{GITHUB_INSTALL_STATE_CACHE_PREFIX}{token}"
- state_payload = cache.get(cache_key)
- if not state_payload or state_payload.get("user_id") != request.user.id:
- return None
- connect_from = state_payload.get("connect_from")
- return connect_from if connect_from in APP_CONNECT_FROM_VALUES else None
-
-
-@require_http_methods(["GET"])
-@session_auth_required
-def github_link_complete(request: HttpRequest) -> HttpResponseRedirect:
- """GitHub App installation + user authorization callback.
-
- **Install flow** (``/installations/new``): GitHub sends ``installation_id``,
- ``code``, and ``state`` in the query string.
-
- **OAuth-only flow** (``/login/oauth/authorize`` when the team already has the
- app installed): GitHub sends only ``code`` and ``state``; ``installation_id``
- is read from validated server-side state.
-
- Steps: validate state, resolve ``installation_id``, exchange ``code`` for
- user-to-server tokens, fetch installation token, create/update ``UserIntegration``.
- """
-
- user = cast(User, request.user)
-
- # Which first-party client (if any) started this flow; controls the final
- # redirect destination. Resolved from validated server-side state below.
- connect_from_value: str | None = None
-
- def _error(reason: str) -> HttpResponseRedirect:
- logger.warning("github_link: redirecting with error", reason=reason, user_id=user.id)
- return _final_github_redirect(connect_from_value, error=reason)
-
- # GitHub appends ?error=... when the user denied consent.
- if github_error := request.GET.get("error"):
- logger.warning(
- "github_link: GitHub returned error on callback",
- error=github_error,
- description=request.GET.get("error_description"),
- user_id=user.id,
- )
- connect_from_value = _app_connect_from_from_state_query(request)
- return _error(github_error if github_error == "access_denied" else "github_oauth_error")
-
- code = request.GET.get("code")
- state_raw = request.GET.get("state")
-
- if not code or not state_raw:
- return _error("missing_params")
-
- # The frontend extracts the raw token from the URL-encoded state before forwarding
- # here, so state_raw is normally the 48-char random token. Handle both forms so
- # direct backend calls (e.g. in tests) and any future flow changes work correctly.
- token = _github_state_token(state_raw)
-
- # Validate state
- cache_key = f"{GITHUB_INSTALL_STATE_CACHE_PREFIX}{token}"
- state_payload = cache.get(cache_key)
- if not state_payload or state_payload.get("user_id") != user.id:
- return _error("invalid_state")
- connect_from_value = state_payload.get("connect_from")
- cache.delete(cache_key)
-
- flow = state_payload.get("flow")
- oauth_flow = flow == "oauth_authorize"
- oauth_discover_flow = flow == "oauth_discover"
- team_oauth_flow = flow == "team_oauth_authorize"
- team_oauth_team_id: int | None = None
- team_oauth_next: str | None = None
- installation_ids: list[str] = []
- if oauth_flow:
- installation_id = state_payload.get("installation_id")
- if not installation_id or not isinstance(installation_id, str):
- return _error("missing_params")
- # Do not require ``current_team`` to match: OAuth completes in a browser
- # session whose active team may differ from the app that started the flow.
- if not Integration.objects.filter(
- kind="github", integration_id=installation_id, team__in=user.teams.all()
- ).exists():
- return _error("invalid_installation")
- installation_ids = [installation_id]
- elif team_oauth_flow:
- # Triggered when the GitHub App is already installed on the org but no PostHog
- # team has captured it (orphan installation). The frontend redirects the user
- # through GitHub's User OAuth so we get a `code` for verify_user_installation_access.
- installation_id = state_payload.get("installation_id")
- team_oauth_team_id = state_payload.get("team_id")
- team_oauth_next = state_payload.get("next") or None
- if not installation_id or not isinstance(installation_id, str):
- return _error("missing_params")
- if not isinstance(team_oauth_team_id, int):
- return _error("invalid_state")
- # Confirm the user still has access to the team they started this flow from.
- if not user.teams.filter(id=team_oauth_team_id).exists():
- return _error("invalid_team")
- installation_ids = [installation_id]
- elif oauth_discover_flow:
- pass
- else:
- installation_id = request.GET.get("installation_id")
- if not installation_id:
- return _error("missing_params")
- installation_ids = [installation_id]
-
- # Exchange code for user-to-server tokens
- if oauth_flow or oauth_discover_flow or team_oauth_flow:
- authorization = GitHubIntegration.github_user_from_code(code, redirect_uri=github_oauth_redirect_uri())
- else:
- authorization = GitHubIntegration.github_user_from_code(code)
- if authorization is None:
- return _error("exchange_failed")
-
- if oauth_discover_flow:
- try:
- installation_ids = _github_user_installation_ids(authorization.access_token)
- except requests.RequestException:
- return _error("installation_fetch_failed")
- if not installation_ids:
- return _redirect_to_github_app_install(user, connect_from_value)
-
- for installation_id in installation_ids:
- # installation_id must be a plain positive integer (GitHub App IDs always are).
- # Reject anything else before it touches URL construction.
- if not re.fullmatch(r"\d{1,20}", str(installation_id)):
- return _error("invalid_installation_id")
-
- for installation_id in installation_ids:
- installation_id = str(installation_id)
- # Verify the authorizing user actually has access to this installation.
- # An attacker could use their own OAuth code with someone else's installation_id
- # to obtain an installation token scoped to a different organisation's repos.
- if not oauth_discover_flow:
- try:
- has_access = GitHubIntegration.verify_user_installation_access(
- installation_id, authorization.access_token
- )
- except requests.RequestException:
- logger.warning(
- "github_link: installation ownership check failed",
- installation_id=installation_id,
- user_id=user.id,
- exc_info=True,
- )
- return _error("installation_verify_failed")
- if not has_access:
- logger.warning(
- "github_link: user does not have access to installation",
- installation_id=installation_id,
- user_id=user.id,
- )
- return _error("installation_not_authorized")
-
- # Get installation info and access token
- try:
- installation_info = GitHubIntegration.client_request(f"installations/{installation_id}").json()
- access_token_response = GitHubIntegration.client_request(
- f"installations/{installation_id}/access_tokens", method="POST"
- ).json()
- except Exception:
- logger.warning("github_link: failed to fetch installation info", exc_info=True)
- return _error("installation_fetch_failed")
-
- installation_access_token = access_token_response.get("token")
- if not installation_access_token:
- return _error("installation_token_failed")
-
- token_expires_at = access_token_response.get("expires_at")
- if not token_expires_at:
- return _error("installation_token_failed")
-
- user_github_integration_from_installation(
- user,
- GitHubInstallationAccess(
- installation_id=installation_id,
- installation_info=installation_info,
- access_token=installation_access_token,
- token_expires_at=token_expires_at,
- repository_selection=access_token_response.get("repository_selection", "selected"),
- ),
- authorization,
- )
-
- if team_oauth_flow and team_oauth_team_id is not None:
- installation_id = str(installation_ids[0])
- # Create the team-level Integration that the user originally tried to install.
- # ``integration_from_installation_id`` re-fetches the installation token, so it
- # works whether or not another team in the org has already linked this install.
- try:
- team_integration = GitHubIntegration.integration_from_installation_id(
- installation_id, team_oauth_team_id, user
- )
- except Exception:
- logger.warning(
- "github_link: failed to create team integration",
- installation_id=installation_id,
- team_id=team_oauth_team_id,
- exc_info=True,
- )
- return _error("integration_create_failed")
-
- # Mirror the fresh-install flow: stamp the connecting user's GitHub login on
- # the team integration card.
- team_integration.config["connecting_user_github_login"] = authorization.gh_login
- team_integration.save(update_fields=["config"])
-
- target = team_oauth_next or PERSONAL_INTEGRATIONS_SETTINGS_PATH
- forwarded_params: dict[str, str] = {
- "installation_id": installation_id,
- "integration_id": str(team_integration.id),
- }
- joiner = "&" if "?" in target else "?"
- return redirect(f"{target}{joiner}{urlencode(forwarded_params)}")
-
- return _final_github_redirect(connect_from_value)
-
-
def _resolve_team_for_github_start(user: User, request: Request):
"""Resolve which team to use for team-level GitHub install discovery.
@@ -811,7 +459,7 @@ def _attempt_app_oauth_fast_path(
},
timeout=GITHUB_INSTALL_STATE_TTL_SECONDS,
)
- return Response({"install_url": _github_oauth_authorize_url(state), "connect_flow": "oauth_authorize"})
+ return Response({"install_url": github_oauth_authorize_url(state), "connect_flow": "oauth_authorize"})
def _serialize_github_integration(
diff --git a/posthog/urls.py b/posthog/urls.py
index 9c789866bbf7..52fb19788225 100644
--- a/posthog/urls.py
+++ b/posthog/urls.py
@@ -31,12 +31,12 @@ from posthog.api import (
uploaded_media,
user,
)
+from posthog.api.github_callback.personal_finish import github_link_complete
from posthog.api.oauth.connected_apps import ConnectedAppsViewSet
from posthog.api.oauth.wizard_metadata import WIZARD_METADATA_PATH, WizardClientMetadataView
from posthog.api.query import progress
from posthog.api.sdk_doctor import sdk_doctor
from posthog.api.two_factor_qrcode import CacheAwareQRGeneratorView
-from posthog.api.user_integration import github_link_complete
from posthog.api.utils import hostname_in_allowed_url_list
from posthog.api.web_experiment import web_experiments
from posthog.api.zendesk_orgcheck import ensure_zendesk_organization