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(integrations): Robust & unified GitHub setup callback (#59778)

Michael Matloka20d2d6e625c2
diff --git a/frontend/src/generated/core/api.schemas.ts b/frontend/src/generated/core/api.schemas.ts
index 9956476aebf4..f77a6c109fae 100644
--- a/frontend/src/generated/core/api.schemas.ts
+++ b/frontend/src/generated/core/api.schemas.ts
@@ -3644,6 +3644,11 @@ export interface GitHubReposRefreshResponseApi {
repositories: GitHubRepoApi[]
}
+export interface UserGitHubPrepareCallbackRequestApi {
+ /** GitHub App installation id being managed on github.com. */
+ installation_id: string
+}
+
export interface UserGitHubLinkStartRequestApi {
/**
* Optional team/project id (e.g. PostHog Code); web UI uses the session's current team.
diff --git a/frontend/src/generated/core/api.ts b/frontend/src/generated/core/api.ts
index 49dccb9c7b99..0090ff783c84 100644
--- a/frontend/src/generated/core/api.ts
+++ b/frontend/src/generated/core/api.ts
@@ -78,6 +78,7 @@ import type {
UserAuthSessionApi,
UserGitHubLinkStartRequestApi,
UserGitHubLinkStartResponseApi,
+ UserGitHubPrepareCallbackRequestApi,
UserPushTokenItemApi,
UserPushTokenRegisterRequestApi,
UserPushTokenUnregisterRequestApi,
@@ -3331,6 +3332,26 @@ export const usersIntegrationsGithubReposRefreshCreate = async (
)
}
+export const getUsersIntegrationsGithubPrepareCallbackCreateUrl = (uuid: string) => {
+ return `/api/users/${uuid}/integrations/github/prepare_callback/`
+}
+
+/**
+ * Seed personal GitHub manage callback state before opening installation settings on GitHub.
+ */
+export const usersIntegrationsGithubPrepareCallbackCreate = async (
+ uuid: string,
+ userGitHubPrepareCallbackRequestApi: UserGitHubPrepareCallbackRequestApi,
+ options?: RequestInit
+): Promise<void> => {
+ return apiMutator<void>(getUsersIntegrationsGithubPrepareCallbackCreateUrl(uuid), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(userGitHubPrepareCallbackRequestApi),
+ })
+}
+
export const getUsersIntegrationsGithubStartCreateUrl = (uuid: string) => {
return `/api/users/${uuid}/integrations/github/start/`
}
diff --git a/frontend/src/generated/core/api.zod.ts b/frontend/src/generated/core/api.zod.ts
index ddc8e34e5c89..e92e78a08239 100644
--- a/frontend/src/generated/core/api.zod.ts
+++ b/frontend/src/generated/core/api.zod.ts
@@ -10010,6 +10010,13 @@ export const UsersHedgehogConfigPartialUpdateBody = /* @__PURE__ */ zod.object({
),
})
+/**
+ * Seed personal GitHub manage callback state before opening installation settings on GitHub.
+ */
+export const UsersIntegrationsGithubPrepareCallbackCreateBody = /* @__PURE__ */ zod.object({
+ installation_id: zod.string().describe('GitHub App installation id being managed on github.com.'),
+})
+
/**
* Start GitHub linking: either full App install or OAuth-only (user-to-server).
*
diff --git a/frontend/src/lib/integrations/GitHubRepoSummary.tsx b/frontend/src/lib/integrations/GitHubRepoSummary.tsx
index 822a94845fc1..dc523f6965b8 100644
--- a/frontend/src/lib/integrations/GitHubRepoSummary.tsx
+++ b/frontend/src/lib/integrations/GitHubRepoSummary.tsx
@@ -15,19 +15,32 @@ export function GitHubRepoSummary({
installationId,
accountType,
accountName,
+ onBeforeManage,
}: {
repoNames: string[]
loading: boolean
installationId?: string | null
accountType?: string
accountName?: string
+ /** Called before opening the GitHub installation settings page. Use this to seed
+ * server-side state (via the `github_prepare_callback` endpoints) so the eventual
+ * Setup URL callback can be dispatched to the right team/personal handler. */
+ onBeforeManage?: (installationId: string) => Promise<void> | void
}): JSX.Element {
const manageButton = installationId ? (
<LemonButton
size="xsmall"
type="secondary"
icon={<IconGear />}
- onClick={() => window.open(manageInstallationUrl(installationId, accountType, accountName), '_blank')}
+ onClick={async () => {
+ try {
+ await onBeforeManage?.(installationId)
+ } catch {
+ // Failing to seed state is non-fatal — the server falls back to UserIntegration
+ // membership detection. We surface the GitHub page either way.
+ }
+ window.open(manageInstallationUrl(installationId, accountType, accountName), '_blank')
+ }}
tooltip={repoNames.length > 0 ? 'Manage repository access on GitHub' : 'Configure repository access'}
/>
) : null
diff --git a/frontend/src/lib/integrations/IntegrationView.tsx b/frontend/src/lib/integrations/IntegrationView.tsx
index db2612bebd99..e2a94a78901e 100644
--- a/frontend/src/lib/integrations/IntegrationView.tsx
+++ b/frontend/src/lib/integrations/IntegrationView.tsx
@@ -12,6 +12,8 @@ import { TeamMembershipLevel } from 'lib/constants'
import { dayjs } from 'lib/dayjs'
import { GitHubRepoSummary } from 'lib/integrations/GitHubRepoSummary'
import { IntegrationScopesWarning } from 'lib/integrations/IntegrationScopesWarning'
+import { teamLogic } from 'scenes/teamLogic'
+import { urls } from 'scenes/urls'
import { IntegrationType } from '~/types'
@@ -28,6 +30,7 @@ export function IntegrationView({
schema?: { requiredScopes?: string }
}): JSX.Element {
const { deleteIntegration } = useActions(integrationsLogic)
+ const { currentTeam } = useValues(teamLogic)
const restrictedReason = useRestrictedArea({
scope: RestrictionScope.Project,
minimumAccessLevel: TeamMembershipLevel.Admin,
@@ -109,6 +112,22 @@ export function IntegrationView({
installationId={integration.config?.installation_id}
accountType={integration.config?.account?.type}
accountName={integration.config?.account?.name}
+ onBeforeManage={
+ currentTeam?.id
+ ? async () => {
+ await api.create(
+ `api/projects/${currentTeam.id}/integrations/github/prepare_callback/`,
+ {
+ next: urls.project(
+ currentTeam.id,
+ urls.settings('project-integrations')
+ ),
+ installation_id: integration.config?.installation_id,
+ }
+ )
+ }
+ : undefined
+ }
/>
)}
</div>
diff --git a/frontend/src/lib/integrations/githubSetupErrors.ts b/frontend/src/lib/integrations/githubSetupErrors.ts
new file mode 100644
index 000000000000..04063fc02818
--- /dev/null
+++ b/frontend/src/lib/integrations/githubSetupErrors.ts
@@ -0,0 +1,61 @@
+export const GITHUB_INSTALL_PENDING_MESSAGE =
+ 'GitHub requires an organization owner to complete this installation. If you requested access, an organization owner will need to approve it.'
+
+export const GITHUB_SETUP_ERROR_MESSAGES: Record<string, string> = {
+ access_denied: 'GitHub authorization was canceled.',
+ github_oauth_error: 'GitHub rejected the authorization. Please try again.',
+ missing_params: "GitHub didn't send back the expected parameters. Please try again.",
+ invalid_state: 'The GitHub setup request expired or could not be verified. Please try again.',
+ invalid_installation_id: 'GitHub returned an invalid installation. Please try again.',
+ exchange_failed: 'GitHub rejected the authorization code. Please try again.',
+ installation_verify_failed: 'Could not verify your access to this GitHub installation. Please try again.',
+ installation_not_authorized:
+ "Your GitHub account isn't authorized for this installation. Ask the org admin to grant access, or sign in with a different GitHub account.",
+ installation_fetch_failed: 'Could not fetch installation details from GitHub. Please try again.',
+ installation_token_failed: 'Could not get an access token from GitHub. Please try again.',
+ integration_create_failed: 'Could not save the GitHub connection. Please try again.',
+ github_install_failed: 'Could not connect GitHub. Please try again.',
+ github_install_pending: GITHUB_INSTALL_PENDING_MESSAGE,
+ insufficient_permissions:
+ 'You need admin access to this project to connect a GitHub integration. Ask a project admin to set it up.',
+}
+
+export function normalizeGithubOAuthCallbackError(githubError: string): string {
+ return githubError === 'access_denied' ? 'access_denied' : 'github_oauth_error'
+}
+
+export function getGithubSetupErrorCode(searchParams: Record<string, unknown>): string {
+ const pending = searchParams.github_install_pending
+ // An install awaiting org-owner approval isn't a hard error, but surfacing it as an error code routes
+ // it through the existing `failed` path — so the desktop deep-link contract stays `status=success|error`
+ // and doesn't falsely read as a completed connection.
+ const isPending = pending === '1' || pending === 1 || pending === true || pending === 'true'
+ return (
+ (typeof searchParams.error === 'string' && searchParams.error) ||
+ (typeof searchParams.github_setup_error === 'string' && searchParams.github_setup_error) ||
+ (isPending ? 'github_install_pending' : '') ||
+ ''
+ )
+}
+
+export function describeGithubSetupError(code: string | null, detail: string | null = null): string {
+ if (code && GITHUB_SETUP_ERROR_MESSAGES[code]) {
+ return GITHUB_SETUP_ERROR_MESSAGES[code]
+ }
+ if (detail) {
+ return detail
+ }
+ return GITHUB_SETUP_ERROR_MESSAGES.github_install_failed
+}
+
+const GITHUB_LINK_ERROR_OVERRIDES: Record<string, string> = {
+ invalid_state: 'The GitHub link request expired or could not be verified. Please try again.',
+ exchange_failed: 'GitHub rejected the authorization code. Check that the GitHub App is configured correctly.',
+}
+
+export function describeGithubLinkError(code: string | null): string {
+ if (code && GITHUB_LINK_ERROR_OVERRIDES[code]) {
+ return GITHUB_LINK_ERROR_OVERRIDES[code]
+ }
+ return describeGithubSetupError(code)
+}
diff --git a/frontend/src/lib/integrations/integrationsLogic.ts b/frontend/src/lib/integrations/integrationsLogic.ts
index 785a8148ad26..358107b60ccc 100644
--- a/frontend/src/lib/integrations/integrationsLogic.ts
+++ b/frontend/src/lib/integrations/integrationsLogic.ts
@@ -1,11 +1,12 @@
import { actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
-import { combineUrl, router, urlToAction } from 'kea-router'
+import { router, urlToAction } from 'kea-router'
import { LemonDialog, lemonToast } from '@posthog/lemon-ui'
import api, { ApiError, getCookie } from 'lib/api'
import { globalSetupLogic } from 'lib/components/ProductSetup'
+import { describeGithubSetupError, GITHUB_INSTALL_PENDING_MESSAGE } from 'lib/integrations/githubSetupErrors'
import { isKeyOf } from 'lib/utils/guards'
import { fromParamsGivenUrl } from 'lib/utils/url'
import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'
@@ -37,7 +38,6 @@ export const integrationsLogic = kea<integrationsLogicType>([
})),
actions({
- handleGithubCallback: (searchParams: any) => ({ searchParams }),
handleOauthCallback: (kind: IntegrationKind, searchParams: any) => ({ kind, searchParams }),
newGoogleCloudKey: (kind: string, key: File, callback?: (integration: IntegrationType) => void) => ({
kind,
@@ -221,102 +221,6 @@ export const integrationsLogic = kea<integrationsLogicType>([
actions.loadGitHubRepositoriesPageFailure(integrationId)
}
},
- handleGithubCallback: async ({ searchParams }) => {
- const { state, installation_id, code, setup_action } = searchParams
- const { next, token, source } = fromParamsGivenUrl(state ?? '')
- const stateToken = token || state
-
- // User-level GitHub flow (personal integrations / UserIntegration): redirect to the
- // backend endpoint which handles UserIntegration creation server-side.
- if (source === 'user_integration') {
- const backendUrl = combineUrl('/complete/github-link/', {
- installation_id,
- code,
- state: stateToken,
- }).url
- window.location.href = backendUrl
- return
- }
-
- let replaceUrl: string = next || urls.settings('project-integrations')
-
- // GitHub callback runs on a non-scoped route where currentTeamId may differ from the
- // team that started the flow; recover it from `next`'s project_id.
- const nextParams: Record<string, any> = next ? combineUrl(next).searchParams : {}
- const projectIdFromNext = nextParams.project_id
- const teamIdForIntegration = projectIdFromNext ? parseInt(projectIdFromNext, 10) : undefined
-
- try {
- if (installation_id) {
- if (stateToken !== getCookie('ph_github_state')) {
- throw new Error('Invalid state token')
- }
-
- // setup_action=update / missing code means the App was already installed on the org;
- // try cloning from a sibling team, and fall back to a User OAuth round-trip when the
- // server can't auto-link (orphan install, no personal GitHub yet, or stale token).
- const isAlreadyInstalled = setup_action === 'update' || !code
-
- let integration: IntegrationType | null = null
- if (isAlreadyInstalled) {
- try {
- integration = await api.integrations.githubLinkExisting(
- { installation_id: String(installation_id) },
- teamIdForIntegration
- )
- } catch (e) {
- const errorCode = e instanceof ApiError ? e.code : null
- const needsUserOAuth =
- errorCode === 'github_link_existing_orphan_installation' ||
- errorCode === 'github_link_existing_personal_github_required'
- if (!needsUserOAuth) {
- throw e
- }
- const { oauth_url } = await api.integrations.githubOAuthAuthorize(
- {
- installation_id: String(installation_id),
- next: replaceUrl,
- connect_from: nextParams.connect_from ?? undefined,
- },
- teamIdForIntegration
- )
- window.location.href = oauth_url
- return
- }
- } else {
- integration = await api.integrations.create({
- kind: 'github',
- config: { installation_id, state: stateToken, code },
- })
- }
-
- // Forward the ids so the `next` landing page (e.g. the PostHog Code
- // deep link) knows which install was just completed.
- replaceUrl = combineUrl(replaceUrl, {
- installation_id: String(installation_id),
- integration_id: String(integration!.id),
- }).url
-
- actions.loadIntegrations()
- lemonToast.success(`Integration successful.`)
- } else {
- // If the requesting user does not have permissions an installation_id will not be returned
- // we assume in this situation that a request has been made to the GitHub organization owners
- lemonToast.info(
- 'Your request to connect to GitHub has been sent to the organization owners. They will need to complete the installation.'
- )
- }
- } catch (e) {
- toastApiError(e)
- const detail = e instanceof ApiError ? e.detail : null
- replaceUrl = combineUrl(replaceUrl, {
- error: 'github_install_failed',
- error_message: detail || (e instanceof Error ? e.message : 'Unknown error'),
- }).url
- } finally {
- router.actions.replace(replaceUrl)
- }
- },
handleOauthCallback: async ({ kind, searchParams }) => {
const { state, code, error, stripe_user_id, account_id, user_id } = searchParams
const { next, token, source, server_id } = fromParamsGivenUrl(state)
@@ -414,12 +318,18 @@ export const integrationsLogic = kea<integrationsLogicType>([
})),
afterMount(({ actions }) => {
actions.loadIntegrations()
+
+ const params = new URLSearchParams(window.location.search)
+ if (params.has('github_setup_error')) {
+ const reason = params.get('github_setup_error')
+ const detail = params.get('error_message')
+ lemonToast.error(describeGithubSetupError(reason, detail))
+ } else if (params.has('github_install_pending')) {
+ lemonToast.info(GITHUB_INSTALL_PENDING_MESSAGE)
+ }
}),
urlToAction(({ actions }) => ({
- '/integrations/github/callback': (_, searchParams) => {
- actions.handleGithubCallback(searchParams)
- },
'/integrations/:kind/callback': ({ kind = '' }, searchParams) => {
actions.handleOauthCallback(kind as IntegrationKind, searchParams)
},
diff --git a/frontend/src/scenes/authentication/account/AccountConnected.tsx b/frontend/src/scenes/authentication/account/AccountConnected.tsx
index 9a0366434260..ecef746ff4cd 100644
--- a/frontend/src/scenes/authentication/account/AccountConnected.tsx
+++ b/frontend/src/scenes/authentication/account/AccountConnected.tsx
@@ -6,6 +6,7 @@ import { IconCheckCircle, IconWarning } from '@posthog/icons'
import { BridgePage } from 'lib/components/BridgePage/BridgePage'
import { SSO_PROVIDER_NAMES } from 'lib/constants'
+import { describeGithubSetupError, getGithubSetupErrorCode } from 'lib/integrations/githubSetupErrors'
import { SceneExport } from 'scenes/sceneTypes'
import type { SSOProvider } from '~/types'
@@ -39,14 +40,14 @@ function posthogCodeDeepUrl(
url.searchParams.set(key, String(value))
}
}
- const errorCode = typeof searchParams.error === 'string' ? searchParams.error : ''
+ const errorCode = getGithubSetupErrorCode(searchParams)
url.searchParams.set('status', errorCode ? 'error' : 'success')
if (errorCode) {
url.searchParams.set('error_code', errorCode)
- const errorMessage = typeof searchParams.error_message === 'string' ? searchParams.error_message : ''
- if (errorMessage) {
- url.searchParams.set('error_message', errorMessage)
- }
+ const errorMessage =
+ (typeof searchParams.error_message === 'string' && searchParams.error_message) ||
+ describeGithubSetupError(errorCode)
+ url.searchParams.set('error_message', errorMessage)
}
return url.toString()
}
@@ -97,22 +98,31 @@ export const scene: SceneExport<AccountConnectedProps> = {
* except when started from Slack (`connect_from=slack`), where it shows a terminal success state
* and the user returns to Slack manually (no deep link).
*/
+function isValidKind(kind: AccountConnectedKind | undefined): kind is Exclude<AccountConnectedKind, 'invalid'> {
+ return typeof kind === 'string' && (VALID_KINDS as readonly string[]).includes(kind)
+}
+
export function AccountConnected({ kind }: AccountConnectedProps): JSX.Element {
const { searchParams } = useValues(router)
const provider = typeof searchParams.provider === 'string' ? searchParams.provider : undefined
const label = providerLabel(provider)
- const isError = typeof searchParams.error === 'string' && searchParams.error.length > 0
+ const errorCode = getGithubSetupErrorCode(searchParams)
+ const isError = errorCode.length > 0
// The Slack flow has no deep link back — the user just returns to Slack themselves, so we only
// show the success state. PostHog Code refreshes its integrations via a desktop deep link.
const startedFromSlack = searchParams.connect_from === 'slack'
+ // Allowlist-style check — `paramsToProps` is expected to map unknown kinds to `'invalid'`,
+ // but guarding directly against the valid set means a route mismatch (e.g. project-prefix
+ // edge case) can't crash `posthogCodeDeepUrl` with an undefined deep-link host.
+ const hasValidKind = isValidKind(kind)
useEffect(() => {
- if (kind !== 'invalid' && !startedFromSlack) {
+ if (hasValidKind && !startedFromSlack) {
window.location.href = posthogCodeDeepUrl(kind, searchParams)
}
- }, [kind, searchParams, startedFromSlack])
+ }, [hasValidKind, kind, searchParams, startedFromSlack])
- if (kind === 'invalid') {
+ if (!hasValidKind) {
return (
<BridgePage view="account-connected">
<div className="flex flex-col items-center gap-4 text-center max-w-lg mx-auto">
diff --git a/frontend/src/scenes/integrations/components/Integrations.tsx b/frontend/src/scenes/integrations/components/Integrations.tsx
index f487ee146375..9f49772dea68 100644
--- a/frontend/src/scenes/integrations/components/Integrations.tsx
+++ b/frontend/src/scenes/integrations/components/Integrations.tsx
@@ -9,6 +9,7 @@ import { TeamMembershipLevel } from 'lib/constants'
import { integrationsLogic } from 'lib/integrations/integrationsLogic'
import { IntegrationView } from 'lib/integrations/IntegrationView'
import { GitLabSetupModal } from 'scenes/integrations/gitlab/GitLabSetupModal'
+import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
import { IntegrationKind, IntegrationType } from '~/types'
@@ -50,12 +51,14 @@ const OAuthIntegration = ({
connectText: string
next?: string
}): JSX.Element => {
+ const { currentTeam } = useValues(teamLogic)
const restrictedReason = useRestrictedArea({
scope: RestrictionScope.Project,
minimumAccessLevel: TeamMembershipLevel.Admin,
})
+ const settingsPath = next ?? urls.settings('environment-integrations')
const authorizationUrl = api.integrations.authorizeUrl({
- next: next ?? urls.settings('environment-integrations'),
+ next: currentTeam?.id ? urls.project(currentTeam.id, settingsPath) : settingsPath,
kind,
})
diff --git a/frontend/src/scenes/settings/user/PersonalIntegrations.tsx b/frontend/src/scenes/settings/user/PersonalIntegrations.tsx
index 973342940703..1e7b0ffbfbc6 100644
--- a/frontend/src/scenes/settings/user/PersonalIntegrations.tsx
+++ b/frontend/src/scenes/settings/user/PersonalIntegrations.tsx
@@ -160,7 +160,7 @@ function SlackLinkRow({ integration }: { integration: PersonalSlackIntegration }
}
export function PersonalGitHubIntegrations(): JSX.Element {
- const { integrations, integrationsLoading } = useValues(personalIntegrationsLogic)
+ const { integrations, integrationsLoading, githubConnecting } = useValues(personalIntegrationsLogic)
const { connectGitHub } = useActions(personalIntegrationsLogic)
if (integrationsLoading && integrations.length === 0) {
@@ -188,7 +188,14 @@ export function PersonalGitHubIntegrations(): JSX.Element {
))
)}
<div className="flex flex-wrap items-center gap-x-3 gap-y-2 px-4 py-3">
- <LemonButton type="secondary" size="small" icon={<IconPlus />} onClick={connectGitHub}>
+ <LemonButton
+ type="secondary"
+ size="small"
+ icon={<IconPlus />}
+ onClick={connectGitHub}
+ loading={githubConnecting}
+ disabledReason={githubConnecting ? 'Starting GitHub installation…' : undefined}
+ >
{integrations.length === 0 ? 'Connect GitHub' : 'Add account/organization'}
</LemonButton>
<span className="text-xs text-secondary text-balance">
diff --git a/frontend/src/scenes/settings/user/personalIntegrationsLogic.ts b/frontend/src/scenes/settings/user/personalIntegrationsLogic.ts
index d0860c589e2e..b41e8652a01a 100644
--- a/frontend/src/scenes/settings/user/personalIntegrationsLogic.ts
+++ b/frontend/src/scenes/settings/user/personalIntegrationsLogic.ts
@@ -1,12 +1,14 @@
-import { actions, connect, events, kea, listeners, path, selectors } from 'kea'
+import { actions, connect, events, kea, listeners, path, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
import { lemonToast } from '@posthog/lemon-ui'
import api from 'lib/api'
import { FEATURE_FLAGS } from 'lib/constants'
+import { describeGithubLinkError } from 'lib/integrations/githubSetupErrors'
import { integrationsLogic } from 'lib/integrations/integrationsLogic'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+import { teamLogic } from 'scenes/teamLogic'
import {
usersIntegrationsGithubDestroy,
@@ -90,19 +92,32 @@ export const personalIntegrationsLogic = kea<personalIntegrationsLogicType>([
path(['scenes', 'settings', 'user', 'personalIntegrationsLogic']),
connect(() => ({
+ values: [teamLogic, ['currentTeam'], featureFlagLogic, ['featureFlags']],
actions: [
integrationsLogic,
['loadIntegrations as loadProjectIntegrations', 'loadIntegrationsSuccess as projectIntegrationsLoaded'],
],
- values: [featureFlagLogic, ['featureFlags']],
})),
actions({
connectGitHub: true,
+ connectGitHubFailure: true,
disconnectGitHub: (installationId: string) => ({ installationId }),
disconnectSlack: (slackUserId: string) => ({ slackUserId }),
}),
+ reducers({
+ // Guards against double-submission: the install request redirects to github.com on success
+ // (so it never needs resetting then), and resets on failure so the user can retry.
+ githubConnecting: [
+ false,
+ {
+ connectGitHub: () => true,
+ connectGitHubFailure: () => false,
+ },
+ ],
+ }),
+
loaders(() => ({
integrations: [
[] as PersonalGitHubIntegration[],
@@ -188,7 +203,7 @@ export const personalIntegrationsLogic = kea<personalIntegrationsLogicType>([
],
}),
- listeners(({ actions }) => ({
+ listeners(({ actions, values }) => ({
projectIntegrationsLoaded: () => {
// When a project-level integration is added/removed, the backend may
// auto-create a user-level integration. Reload to pick it up.
@@ -209,10 +224,17 @@ export const personalIntegrationsLogic = kea<personalIntegrationsLogicType>([
connectGitHub: async () => {
try {
const connectFrom = readConnectFromStorage()
- const body = connectFrom === 'posthog_code' ? { connect_from: 'posthog_code' } : {}
+ const body: { connect_from?: 'posthog_code'; team_id?: number } = {}
+ if (connectFrom === 'posthog_code') {
+ body.connect_from = 'posthog_code'
+ }
+ if (values.currentTeam?.id) {
+ body.team_id = values.currentTeam.id
+ }
const response = await usersIntegrationsGithubStartCreate('@me', body)
window.location.href = response.install_url
} catch (error: unknown) {
+ actions.connectGitHubFailure()
const message = error instanceof Error && 'detail' in error ? (error as any).detail : undefined
lemonToast.error(message || 'Could not start GitHub installation.')
}
@@ -248,24 +270,7 @@ export const personalIntegrationsLogic = kea<personalIntegrationsLogicType>([
lemonToast.success('GitHub connected.')
} else if (params.has('github_link_error')) {
writeConnectFromStorage(null)
- const reason = params.get('github_link_error')
- const message =
- reason === 'access_denied'
- ? 'GitHub authorization was canceled.'
- : reason === 'github_oauth_error'
- ? 'GitHub rejected the authorization. Please try again.'
- : reason === 'missing_params'
- ? "GitHub didn't send back the expected parameters. Please try again."
- : reason === 'invalid_state'
- ? 'The GitHub link request expired or could not be verified. Please try again.'
- : reason === 'exchange_failed'
- ? 'GitHub rejected the authorization code. Check that the GitHub App is configured correctly.'
- : reason === 'installation_fetch_failed'
- ? 'Could not fetch installation details from GitHub. Please try again.'
- : reason === 'installation_token_failed'
- ? 'Could not get an installation token from GitHub. Please try again.'
- : 'Could not connect GitHub. Please try again.'
- lemonToast.error(message)
+ lemonToast.error(describeGithubLinkError(params.get('github_link_error')))
}
if (params.has('slack_link_success')) {
diff --git a/posthog/api/github_callback/__init__.py b/posthog/api/github_callback/__init__.py
index 053857781974..e69de29bb2d1 100644
--- a/posthog/api/github_callback/__init__.py
+++ b/posthog/api/github_callback/__init__.py
@@ -1 +0,0 @@
-"""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
index 418029de051a..cb6be03cb87d 100644
--- a/posthog/api/github_callback/personal_finish.py
+++ b/posthog/api/github_callback/personal_finish.py
@@ -1,164 +1,155 @@
-"""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 urllib.parse import parse_qs, 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
+from django.http import HttpRequest
+from django.utils.crypto import get_random_string
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 import state
from posthog.api.github_callback.types import (
- APP_CONNECT_FROM_VALUES,
- GITHUB_INSTALL_STATE_CACHE_PREFIX,
+ FinishResult,
+ FlowKind,
+ GitHubAuthorizeState,
+ github_app_install_url,
+ github_oauth_authorize_url,
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
+from posthog.models import User
+from posthog.models.integration import GitHubInstallationAccessFetchError, GitHubIntegration, Integration
+from posthog.models.user_integration import (
+ UserIntegration,
+ refresh_user_github_installation_access,
+ 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
-
+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
-@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``.
- """
+def finish_personal(request: HttpRequest) -> FinishResult:
+ """Complete personal GitHub App install or OAuth flows."""
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:
+ def _error(reason: str) -> FinishResult:
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")
+ return FinishResult(redirect_kind="personal_finish", connect_from=connect_from_value, error=reason)
code = request.GET.get("code")
state_raw = request.GET.get("state")
- if not code or not state_raw:
+ if 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:
+ token = _github_state_token(state_raw)
+ authorize_state = state.consume_authorize_state(token, user_id=user.id)
+ if authorize_state is None:
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
+
+ connect_from_value = authorize_state.connect_from
+ flow = authorize_state.flow
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:
+ if not code:
+ # GitHub omits the OAuth `code` when the App is already installed on the
+ # account: the install URL returns a setup update (installation_id, no code)
+ # instead of a fresh-install authorization. Bounce through OAuth-discover to
+ # mint a code, then link the installation(s) the user can already access.
+ if flow == FlowKind.PERSONAL_INSTALL and request.GET.get("installation_id"):
+ discover_token = get_random_string(48)
+ discover_state = urlencode({"token": discover_token, "source": "user_integration"})
+ state.store_unified_authorize_state(
+ GitHubAuthorizeState(
+ token=discover_token,
+ flow=FlowKind.OAUTH_DISCOVER,
+ user_id=user.id,
+ connect_from=connect_from_value,
+ ),
+ )
+ return FinishResult(redirect_kind="oauth_url", oauth_url=github_oauth_authorize_url(discover_state))
+ return _error("missing_params")
+
+ match flow:
+ case FlowKind.PERSONAL_OAUTH:
+ installation_id = authorize_state.installation_id
+ if not installation_id:
+ return _error("missing_params")
+ 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]
+ case FlowKind.TEAM_OAUTH:
+ installation_id = authorize_state.installation_id
+ if not installation_id:
+ return _error("missing_params")
+ if authorize_state.team_id is None:
+ return _error("invalid_state")
+ # `user.teams` membership is no longer re-checked here — losing access between
+ # OAuth-trigger and OAuth-return is a rare timing edge case. If it happens,
+ # `integration_from_installation_id` below will raise rather than emit a typed code.
+ installation_ids = [installation_id]
+ case FlowKind.OAUTH_DISCOVER:
+ pass
+ case _:
+ installation_id = request.GET.get("installation_id")
+ if not installation_id:
+ return _error("missing_params")
+ installation_ids = [installation_id]
+
+ if flow.is_oauth_redirect:
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:
+ if flow.discovers_installations:
try:
- installation_ids = personal_state.github_user_installation_ids(authorization.access_token)
+ response = requests.get(
+ "https://api.github.com/user/installations",
+ headers={
+ "Accept": "application/vnd.github+json",
+ "Authorization": f"Bearer {authorization.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", [])
+ installation_ids = []
+ if isinstance(installations, list):
+ for installation in installations:
+ if isinstance(installation, dict) and installation.get("id") is not None:
+ installation_ids.append(str(installation["id"]))
except requests.RequestException:
return _error("installation_fetch_failed")
if not installation_ids:
- return personal_state.redirect_to_github_app_install(user, connect_from_value)
+ token = get_random_string(48)
+ state_query = urlencode({"token": token, "source": "user_integration"})
+ state.store_unified_authorize_state(
+ GitHubAuthorizeState(
+ token=token,
+ flow=FlowKind.PERSONAL_INSTALL,
+ user_id=user.id,
+ connect_from=connect_from_value,
+ ),
+ )
+ return FinishResult(
+ redirect_kind="oauth_url",
+ oauth_url=github_app_install_url(state_query),
+ )
for installation_id in installation_ids:
if not is_valid_github_installation_id(installation_id):
@@ -166,10 +157,7 @@ def github_link_complete(request: HttpRequest) -> HttpResponseRedirect:
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:
+ if not flow.discovers_installations:
try:
has_access = GitHubIntegration.verify_user_installation_access(
installation_id, authorization.access_token
@@ -190,65 +178,83 @@ def github_link_complete(request: HttpRequest) -> HttpResponseRedirect:
)
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")
+ installation_access = GitHubIntegration.fetch_installation_access(installation_id)
+ except GitHubInstallationAccessFetchError as exc:
+ if exc.code == "installation_fetch_failed":
+ logger.warning("github_link: failed to fetch installation info", exc_info=True)
+ return _error(exc.code)
- 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,
- )
+ user_github_integration_from_installation(user, installation_access, authorization)
- if team_oauth_flow and team_oauth_team_id is not None:
+ if flow.creates_team_integration and authorize_state.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
+ installation_id, authorize_state.team_id, user
)
- except Exception:
+ except (GitHubInstallationAccessFetchError, requests.RequestException):
logger.warning(
"github_link: failed to create team integration",
installation_id=installation_id,
- team_id=team_oauth_team_id,
+ team_id=authorize_state.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 FinishResult(
+ redirect_kind="team_oauth_success",
+ next_url=authorize_state.next_url,
+ installation_id=installation_id,
+ integration_id=str(team_integration.id),
+ )
+
+ return FinishResult(redirect_kind="personal_finish", connect_from=connect_from_value)
+
+
+def finish_personal_setup_update(request: HttpRequest) -> FinishResult:
+ """Refresh a personal UserIntegration after GitHub installation settings change."""
+ user = cast(User, request.user)
+ installation_id = request.GET.get("installation_id")
+
+ def _error(reason: str) -> FinishResult:
+ logger.warning("github_link: personal setup update failed", reason=reason, user_id=user.id)
+ return FinishResult(redirect_kind="personal_finish", connect_from=None, error=reason)
+
+ if not is_valid_github_installation_id(installation_id):
+ return _error("invalid_installation_id")
+
+ installation_id = str(installation_id)
+ try:
+ integration = UserIntegration.objects.get(
+ user=user,
+ kind=UserIntegration.IntegrationKind.GITHUB,
+ integration_id=installation_id,
+ )
+ except UserIntegration.DoesNotExist:
+ return _error("invalid_installation")
+
+ try:
+ installation_access = GitHubIntegration.fetch_installation_access(installation_id)
+ except GitHubInstallationAccessFetchError as exc:
+ if exc.code == "installation_fetch_failed":
+ logger.warning(
+ "github_link: failed to refresh installation after update",
+ installation_id=installation_id,
+ user_id=user.id,
+ exc_info=True,
+ )
+ return _error(exc.code)
+
+ refresh_user_github_installation_access(integration, installation_access)
+
+ # Burn the pending authorize state so a repeated GitHub setup-URL ping within
+ # the 5-minute TTL doesn't re-run the refresh.
+ pending_token = cache.get(state.unified_authorize_pending_cache_key(user.id))
+ if pending_token:
+ state.consume_authorize_state(str(pending_token), user_id=user.id)
- return final_github_redirect(connect_from_value)
+ return FinishResult(redirect_kind="personal_finish", connect_from=None)
diff --git a/posthog/api/github_callback/personal_state.py b/posthog/api/github_callback/personal_state.py
deleted file mode 100644
index dbac7d857172..000000000000
--- a/posthog/api/github_callback/personal_state.py
+++ /dev/null
@@ -1,100 +0,0 @@
-"""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
index a940695e3197..19a5669437a6 100644
--- a/posthog/api/github_callback/redirects.py
+++ b/posthog/api/github_callback/redirects.py
@@ -1,50 +1,95 @@
-"""Post-callback redirect helpers for the personal GitHub linking flow."""
-
-from urllib.parse import urlencode
+from urllib.parse import parse_qsl, urlencode, urlparse
from django.http import HttpResponseRedirect
from django.shortcuts import redirect
-from posthog.api.github_callback.types import MOBILE_GITHUB_CALLBACK_URL
+from posthog.api.github_callback.types import (
+ ACCOUNT_CONNECTED_GITHUB_INTEGRATION_PATH,
+ MOBILE_GITHUB_CALLBACK_URL,
+ PERSONAL_INTEGRATIONS_SETTINGS_PATH,
+ FinishResult,
+)
+from posthog.utils import is_relative_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."""
-class AppDeepLinkRedirect(HttpResponseRedirect):
- """Redirect that also permits the mobile app's custom ``posthog://`` scheme.
+ allowed_schemes = [*HttpResponseRedirect.allowed_schemes, "posthog"]
- 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 _append_query_params(url: str, params: dict[str, str]) -> str:
+ if not params:
+ return url
+ parsed = urlparse(url)
+ merged = dict(parse_qsl(parsed.query))
+ merged.update(params)
+ query = urlencode(merged)
+ fragment = f"#{parsed.fragment}" if parsed.fragment else ""
+ return f"{parsed.path}{('?' + query) if query else ''}{fragment}"
+
+
+def landing_url(next_url: str | None, team_id: int | None) -> str:
+ if next_url and is_relative_url(next_url):
+ return next_url
+ if team_id is not None:
+ return f"/project/{team_id}/settings/project-integrations"
+ return "/settings/environment-integrations"
+
+
+def redirect_from_finish_result(result: FinishResult) -> HttpResponseRedirect:
+ if result.redirect_kind == "oauth_url" and result.oauth_url:
+ return redirect(result.oauth_url)
+
+ if result.redirect_kind == "team_oauth_success":
+ assert result.installation_id and result.integration_id
+ target = result.next_url or PERSONAL_INTEGRATIONS_SETTINGS_PATH
+ return redirect(
+ _append_query_params(
+ target,
+ {
+ "installation_id": result.installation_id,
+ "integration_id": result.integration_id,
+ },
+ )
+ )
+
+ if result.redirect_kind == "personal_finish":
+ app_base_urls: dict[str, str] = {
+ "posthog_mobile": MOBILE_GITHUB_CALLBACK_URL,
+ "posthog_code": ACCOUNT_CONNECTED_GITHUB_INTEGRATION_PATH,
+ # Slack lands on the same web page; the ``connect_from`` marker tells it to bounce back
+ # to the Slack app (deep link) rather than the desktop app.
+ "slack": ACCOUNT_CONNECTED_GITHUB_INTEGRATION_PATH,
+ }
+ if result.connect_from in app_base_urls:
+ app_params = {"provider": "github"}
+ if result.connect_from == "slack":
+ app_params["connect_from"] = "slack"
+ if result.error:
+ app_params["error"] = result.error
+ return _AppDeepLinkRedirect(f"{app_base_urls[result.connect_from]}?{urlencode(app_params)}")
+ if result.error:
+ return redirect(f"{PERSONAL_INTEGRATIONS_SETTINGS_PATH}?github_link_error={result.error}")
+ return redirect(f"{PERSONAL_INTEGRATIONS_SETTINGS_PATH}?github_link_success=1")
+
+ target = landing_url(result.next_url, result.team_id)
+ params: dict[str, str] = {}
+
+ if result.pending:
+ params["github_install_pending"] = "1"
+ if result.error:
+ if ACCOUNT_CONNECTED_GITHUB_INTEGRATION_PATH in target:
+ params["error"] = result.error
+ else:
+ params["github_setup_error"] = result.error
+ if result.error_message:
+ params["error_message"] = result.error_message
+ else:
+ if result.installation_id:
+ params["installation_id"] = result.installation_id
+ if result.integration_id:
+ params["integration_id"] = result.integration_id
-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,
- # Slack lands on the same web page; the ``connect_from`` marker tells it to bounce back
- # to the Slack app (deep link) rather than the desktop app.
- "slack": ACCOUNT_CONNECTED_GITHUB_INTEGRATION_PATH,
- }
- if connect_from in app_base_urls:
- params = {"provider": "github"}
- if connect_from == "slack":
- params["connect_from"] = "slack"
- 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")
+ return redirect(_append_query_params(target, params))
diff --git a/posthog/api/github_callback/state.py b/posthog/api/github_callback/state.py
new file mode 100644
index 000000000000..ce91773350d3
--- /dev/null
+++ b/posthog/api/github_callback/state.py
@@ -0,0 +1,184 @@
+from typing import cast
+from urllib.parse import parse_qsl
+
+from django.core.cache import cache
+
+from rest_framework.exceptions import ValidationError
+from rest_framework.request import Request
+
+from posthog.api.github_callback.types import (
+ GITHUB_AUTHORIZE_STATE_CACHE_TTL_SECONDS,
+ GITHUB_UNIFIED_AUTHORIZE_CACHE_PREFIX,
+ GITHUB_UNIFIED_AUTHORIZE_PENDING_PREFIX,
+ FlowKind,
+ GitHubAuthorizeState,
+ team_id_from_next_url,
+)
+from posthog.models import Team, User
+from posthog.models.organization import OrganizationMembership
+from posthog.user_permissions import UserPermissions
+
+
+def parse_github_authorize_state_param(state_raw: str | None) -> tuple[str | None, str | None]:
+ if not state_raw:
+ return None, None
+ parsed = dict(parse_qsl(state_raw))
+ if "token" in parsed:
+ return parsed.get("token"), parsed.get("next")
+ return state_raw, None
+
+
+def unified_authorize_cache_key(token: str) -> str:
+ return f"{GITHUB_UNIFIED_AUTHORIZE_CACHE_PREFIX}{token}"
+
+
+def unified_authorize_pending_cache_key(user_id: int) -> str:
+ return f"{GITHUB_UNIFIED_AUTHORIZE_PENDING_PREFIX}{user_id}"
+
+
+def authenticated_user_id(request: Request) -> int:
+ if not request.user.is_authenticated:
+ raise ValidationError("Authentication required", code="invalid_state")
+ return cast(User, request.user).id
+
+
+def store_unified_authorize_state(state: GitHubAuthorizeState, *, ttl: int | None = None) -> None:
+ timeout = ttl or GITHUB_AUTHORIZE_STATE_CACHE_TTL_SECONDS
+ cache.set(unified_authorize_cache_key(state.token), state.cache_payload(), timeout=timeout)
+ cache.set(unified_authorize_pending_cache_key(state.user_id), state.token, timeout=timeout)
+
+
+def has_team_management_access(user: User, team: Team) -> bool:
+ """Whether ``user`` may create or modify a team-level integration for ``team``.
+
+ Mirrors ``TeamMemberStrictManagementPermission`` (which gates integration setup on the
+ DRF side) for these plain Django callback views: writing a team integration requires
+ admin-level effective access, not mere membership. The callback's ``team_id`` can be
+ derived from a user-controlled ``next``/``state`` param, so a bare membership check would
+ let any project member attach an integration that initiation reserves for admins.
+ """
+ level = UserPermissions(user).team(team).effective_membership_level
+ return level is not None and level >= OrganizationMembership.Level.ADMIN
+
+
+def resolve_github_setup_callback_context(
+ user: User,
+ state_raw: str | None,
+) -> tuple[int | None, str | None]:
+ """Reads from both the authorize cache and the GitHub ``state`` query param, preferring the query param."""
+ cached_next: str | None = None
+ cached_team_id: int | None = None
+
+ pending_token = cache.get(unified_authorize_pending_cache_key(user.id))
+ if pending_token:
+ cached = cache.get(unified_authorize_cache_key(str(pending_token)))
+ if isinstance(cached, dict):
+ token = str(cached.get("token") or "") or None
+ authorize_state = GitHubAuthorizeState.try_from_cache(token, cached) if token else None
+ if authorize_state is None:
+ cached_next = str(cached.get("next") or "") or None
+ cached_team_id = team_id_from_next_url(cached_next or "")
+ else:
+ cached_next = authorize_state.next_url
+ cached_team_id = authorize_state.team_id
+
+ team_id = cached_team_id
+ next_url = cached_next
+
+ if state_raw:
+ _, state_next = parse_github_authorize_state_param(state_raw)
+ if state_next:
+ next_url = state_next
+ if team_id is None and state_next:
+ team_id = team_id_from_next_url(state_next)
+
+ if team_id is None and next_url:
+ team_id = team_id_from_next_url(next_url)
+
+ if team_id is not None and not user.teams.filter(id=team_id).exists():
+ team_id = None
+
+ return team_id, next_url
+
+
+def has_pending_personal_setup_update(user: User, installation_id: str | None) -> bool:
+ pending_token = cache.get(unified_authorize_pending_cache_key(user.id))
+ if pending_token is None:
+ return False
+ authorize_state = load_authorize_state(str(pending_token), user_id=user.id)
+ if authorize_state is None or authorize_state.flow != FlowKind.PERSONAL_UPDATE:
+ return False
+ if installation_id is None:
+ return True
+ if authorize_state.installation_id is None:
+ return True
+ return str(authorize_state.installation_id) == str(installation_id)
+
+
+def load_authorize_state(token: str, *, user_id: int | None = None) -> GitHubAuthorizeState | None:
+ unified = cache.get(unified_authorize_cache_key(token))
+ if not isinstance(unified, dict):
+ return None
+ state = GitHubAuthorizeState.try_from_cache(token, unified)
+ if state is None:
+ return None
+ if user_id is not None and state.user_id != user_id:
+ return None
+ return state
+
+
+def consume_authorize_state(token: str, *, user_id: int | None = None) -> GitHubAuthorizeState | None:
+ state = load_authorize_state(token, user_id=user_id)
+ if state is None:
+ return None
+ cache.delete(unified_authorize_cache_key(token))
+ if user_id is not None:
+ pending = cache.get(unified_authorize_pending_cache_key(user_id))
+ if pending == token:
+ cache.delete(unified_authorize_pending_cache_key(user_id))
+ return state
+
+
+def consume_github_authorize_state(
+ request: Request,
+ state_raw: str | None,
+ *,
+ setup_action: str = "",
+ code: str | None = None,
+ installation_id: str | None = None,
+) -> tuple[str, str, int | None]:
+ user_id = authenticated_user_id(request)
+ pending_token = cache.get(unified_authorize_pending_cache_key(user_id))
+ cached = cache.get(unified_authorize_cache_key(str(pending_token))) if pending_token else None
+ if not isinstance(cached, dict):
+ raise ValidationError("Invalid or expired state token", code="invalid_state")
+
+ expected_token = str(cached.get("token") or "")
+ cached_next = str(cached.get("next") or "")
+
+ if not state_raw:
+ # State-less update callbacks must consume a TEAM_UPDATE pending record — otherwise an
+ # attacker could seed any pending state (e.g. TEAM_INSTALL) and trigger a silent link.
+ if code is not None or setup_action != "update" or cached.get("flow") != FlowKind.TEAM_UPDATE.value:
+ raise ValidationError("Invalid or expired state token", code="invalid_state")
+ param_next = None
+ else:
+ param_token, param_next = parse_github_authorize_state_param(state_raw)
+ if param_token is not None and param_token != expected_token:
+ raise ValidationError("Invalid or expired state token", code="invalid_state")
+
+ cached_state = GitHubAuthorizeState.try_from_cache(expected_token, cached)
+
+ # Bind the callback to the installation the seeded state intended. The callback's
+ # `installation_id` is taken from the user-controlled query string, so without this a member
+ # who learns a sibling installation ID could swap it in and have an admin's pending update flow
+ # link that installation into this team. Raise before consuming so a genuine callback still works.
+ if cached_state is not None and cached_state.installation_id is not None:
+ if installation_id is None or str(installation_id) != str(cached_state.installation_id):
+ raise ValidationError("Invalid or expired state token", code="invalid_state")
+
+ team_id = cached_state.team_id if cached_state is not None else team_id_from_next_url(cached_next)
+
+ cache.delete(unified_authorize_cache_key(expected_token))
+ cache.delete(unified_authorize_pending_cache_key(user_id))
+ return expected_token, param_next or cached_next, team_id
diff --git a/posthog/api/github_callback/team_services.py b/posthog/api/github_callback/team_services.py
index 4b21761a10c8..10b36a0839eb 100644
--- a/posthog/api/github_callback/team_services.py
+++ b/posthog/api/github_callback/team_services.py
@@ -1,32 +1,38 @@
-"""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.
-"""
-
+import os
+from dataclasses import dataclass
from datetime import UTC, datetime
-from typing import Any
-from urllib.parse import urlencode
+from typing import Any, cast
+from urllib.parse import parse_qsl, urlencode, urlparse
-from django.conf import settings
from django.core.cache import cache
-from django.db.models import Q
+from django.http import HttpRequest
from django.utils.crypto import get_random_string
import requests
import structlog
from rest_framework.exceptions import ValidationError
+from rest_framework.request import Request
+from posthog.api.github_callback import (
+ redirects,
+ state as github_callback_state,
+)
from posthog.api.github_callback.types import (
- GITHUB_INSTALL_STATE_CACHE_PREFIX,
- GITHUB_INSTALL_STATE_TTL_SECONDS,
- github_oauth_redirect_uri,
+ FinishResult,
+ FlowKind,
+ GitHubAuthorizeState,
+ github_oauth_authorize_url,
is_valid_github_installation_id,
)
-from posthog.models.integration import GitHubInstallationAccess, GitHubIntegration, Integration
+from posthog.auth import SessionAuthentication
+from posthog.models import Team
+from posthog.models.integration import (
+ GitHubInstallationAccess,
+ GitHubInstallationAccessFetchError,
+ GitHubIntegration,
+ Integration,
+ invalidate_github_repository_caches_for_installation,
+)
from posthog.models.organization import Organization
from posthog.models.user import User
from posthog.models.user_integration import UserIntegration, user_github_integration_from_installation
@@ -42,29 +48,42 @@ PERSONAL_GITHUB_REQUIRED_MESSAGE = (
)
-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()
+@dataclass(frozen=True)
+class TeamGitHubFinishSetupResult:
+ next_url: str
+ installation_id: str
+ integration: Integration | None = None
+ oauth_url: str | None = None
+
+
+def _validation_error_code(exc: ValidationError) -> str | None:
+ codes = exc.get_codes()
+ if isinstance(codes, list) and codes:
+ return str(codes[0])
+ if isinstance(codes, dict) and codes:
+ first = next(iter(codes.values()))
+ if isinstance(first, list) and first:
+ return str(first[0])
+ return str(first)
+ if isinstance(codes, str):
+ return codes
+ return None
+
+
+def _connect_from_for_next(next_url: str) -> str | None:
+ connect_from = dict(parse_qsl(urlparse(next_url).query)).get("connect_from")
+ return connect_from if connect_from == "posthog_code" else None
def create_team_github_integration_from_oauth_code(
*,
+ request: Request,
user: User,
team_id: int,
- installation_id: Any | None,
+ installation_id: str | 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")
@@ -74,22 +93,12 @@ def create_team_github_integration_from_oauth_code(
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)
+ github_callback_state.consume_github_authorize_state(request, state_token)
- # 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:
@@ -112,23 +121,18 @@ def create_team_github_integration_from_oauth_code(
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.
+ refreshed_at = instance.config.get("refreshed_at", 0)
+ expires_in = instance.config.get("expires_in", 3600)
+ token_expires_at = datetime.fromtimestamp(refreshed_at + expires_in, tz=UTC).isoformat()
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),
+ token_expires_at=token_expires_at,
repository_selection=instance.config.get("repository_selection", "selected"),
),
authorization,
@@ -138,6 +142,222 @@ def create_team_github_integration_from_oauth_code(
return instance
+def finish_team_github_setup_update(
+ *,
+ user: User,
+ team_id: int,
+ request: Request,
+ installation_id: str,
+ existing: Integration,
+ state_raw: str | None,
+ fallback_next_url: str | None,
+) -> TeamGitHubFinishSetupResult:
+ installation_id_str = str(installation_id)
+ next_url = fallback_next_url or ""
+
+ if cache.get(github_callback_state.unified_authorize_pending_cache_key(user.id)) is not None:
+ _, next_url, _ = github_callback_state.consume_github_authorize_state(
+ request, state_raw, setup_action="update", code=None, installation_id=installation_id_str
+ )
+
+ refreshed = refresh_team_github_integration(user, team_id, installation_id_str, existing=existing)
+ return TeamGitHubFinishSetupResult(
+ next_url=next_url or redirects.landing_url(fallback_next_url, team_id),
+ installation_id=installation_id_str,
+ integration=refreshed,
+ )
+
+
+def execute_team_github_finish_setup(
+ *,
+ user: User,
+ team: Team,
+ request: Request,
+ installation_id: str,
+ code: str | None,
+ setup_action: str,
+ state_raw: str | None,
+) -> TeamGitHubFinishSetupResult:
+ if not is_valid_github_installation_id(installation_id):
+ raise ValidationError("Invalid installation_id")
+
+ installation_id_str = str(installation_id)
+
+ _state_token, next_url, _team_id = github_callback_state.consume_github_authorize_state(
+ request, state_raw, setup_action=setup_action, code=code, installation_id=installation_id_str
+ )
+
+ is_already_installed = setup_action == "update" or not code
+ connect_from = _connect_from_for_next(next_url)
+
+ if is_already_installed:
+ try:
+ organization = team.organization
+ existing_install = (
+ Integration.objects.filter(
+ team__organization_id=organization.id,
+ kind="github",
+ )
+ .for_github_installation_id(installation_id_str)
+ .order_by("id")
+ .first()
+ )
+ if existing_install is None:
+ raise ValidationError(
+ "No team in your organization has this GitHub installation linked",
+ code=GITHUB_LINK_EXISTING_ERROR_ORPHAN_INSTALLATION,
+ )
+
+ source_installation_id = (existing_install.config or {}).get("installation_id")
+ if not source_installation_id:
+ raise ValidationError("Source integration is missing installation_id")
+
+ 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(source_installation_id), user_access_token
+ )
+ except requests.RequestException:
+ raise ValidationError("Failed to verify installation access")
+ if not has_access:
+ raise ValidationError(
+ PERSONAL_GITHUB_REQUIRED_MESSAGE,
+ code=GITHUB_LINK_EXISTING_ERROR_PERSONAL_GITHUB_REQUIRED,
+ )
+
+ integration = GitHubIntegration.integration_from_installation_id(str(source_installation_id), team.id, user)
+
+ source_login = (existing_install.config or {}).get("connecting_user_github_login")
+ if source_login and not (integration.config or {}).get("connecting_user_github_login"):
+ integration.config["connecting_user_github_login"] = source_login
+ integration.save(update_fields=["config"])
+ except ValidationError as exc:
+ error_code = _validation_error_code(exc)
+ if error_code not in (
+ GITHUB_LINK_EXISTING_ERROR_ORPHAN_INSTALLATION,
+ GITHUB_LINK_EXISTING_ERROR_PERSONAL_GITHUB_REQUIRED,
+ ):
+ raise
+ oauth_url = build_team_github_oauth_authorize_url(
+ user_id=user.id,
+ team_id=team.id,
+ installation_id=installation_id_str,
+ next_url=next_url,
+ connect_from=connect_from,
+ )
+ return TeamGitHubFinishSetupResult(
+ next_url=next_url,
+ installation_id=installation_id_str,
+ oauth_url=oauth_url,
+ )
+
+ return TeamGitHubFinishSetupResult(
+ next_url=next_url,
+ installation_id=installation_id_str,
+ integration=integration,
+ )
+
+ fresh_token = os.urandom(33).hex()
+ github_callback_state.store_unified_authorize_state(
+ GitHubAuthorizeState(
+ token=fresh_token,
+ flow=FlowKind.TEAM_INSTALL,
+ user_id=github_callback_state.authenticated_user_id(request),
+ team_id=team.id,
+ next_url=next_url or None,
+ ),
+ )
+ integration = create_team_github_integration_from_oauth_code(
+ request=request,
+ user=user,
+ team_id=team.id,
+ installation_id=installation_id_str,
+ state_token=fresh_token,
+ code=code,
+ )
+ return TeamGitHubFinishSetupResult(
+ next_url=next_url,
+ installation_id=installation_id_str,
+ integration=integration,
+ )
+
+
+def refresh_team_github_integration(
+ user: User,
+ team_id: int,
+ installation_id: str,
+ *,
+ existing: Integration,
+) -> Integration:
+ try:
+ return GitHubIntegration.integration_from_installation_id(installation_id, team_id, user)
+ except GitHubInstallationAccessFetchError:
+ logger.warning(
+ "github_team_setup: failed to refresh integration after update",
+ installation_id=installation_id,
+ user_id=user.id,
+ team_id=team_id,
+ exc_info=True,
+ )
+ invalidate_github_repository_caches_for_installation(installation_id)
+ return existing
+
+
+def build_team_github_oauth_authorize_url(
+ *,
+ user_id: int,
+ team_id: int,
+ installation_id: str,
+ next_url: str,
+ connect_from: str | None,
+) -> str:
+ if not installation_id:
+ raise ValidationError("installation_id is required")
+
+ if not is_valid_github_installation_id(installation_id):
+ raise ValidationError("Invalid installation_id")
+
+ if next_url and not is_relative_url(next_url):
+ raise ValidationError("next must be a relative path starting with /")
+
+ token = get_random_string(48)
+ resolved_connect_from = connect_from if connect_from == "posthog_code" else _connect_from_for_next(next_url)
+ authorize_state = GitHubAuthorizeState(
+ token=token,
+ flow=FlowKind.TEAM_OAUTH,
+ user_id=user_id,
+ team_id=team_id,
+ installation_id=str(installation_id),
+ next_url=next_url or None,
+ connect_from=resolved_connect_from,
+ )
+ github_callback_state.store_unified_authorize_state(authorize_state)
+
+ return github_oauth_authorize_url(urlencode({"token": token}))
+
+
+def authenticated_drf_request(http_request: HttpRequest) -> Request:
+ drf_request = Request(http_request)
+ auth_result = SessionAuthentication().authenticate(drf_request)
+ if auth_result is not None:
+ drf_request.user, drf_request.auth = auth_result
+ elif http_request.user.is_authenticated:
+ mutable_request = cast(Any, drf_request)
+ mutable_request._user = http_request.user
+ mutable_request._auth = None
+ return cast(Request, drf_request)
+
+
def link_existing_team_github_integration(
*,
user: User,
@@ -146,18 +366,9 @@ def link_existing_team_github_integration(
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)
@@ -168,10 +379,8 @@ def link_existing_team_github_integration(
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)
+ if installation_id_param:
+ qs = qs.for_github_installation_id(str(installation_id_param))
source = qs.order_by("id").first()
if source is None:
@@ -182,7 +391,7 @@ def link_existing_team_github_integration(
team__organization_id=organization.id,
kind="github",
)
- .filter(installation_id_match)
+ .for_github_installation_id(str(installation_id_param))
.order_by("id")
.first()
)
@@ -199,8 +408,6 @@ def link_existing_team_github_integration(
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
@@ -213,19 +420,8 @@ def link_existing_team_github_integration(
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,
@@ -241,50 +437,149 @@ def link_existing_team_github_integration(
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."""
+def finish_team_setup(http_request) -> FinishResult:
+ state_raw = http_request.GET.get("state")
+ user = cast(User, http_request.user)
+ installation_id = http_request.GET.get("installation_id")
+ setup_action = http_request.GET.get("setup_action") or ""
+ team_id, next_url = github_callback_state.resolve_github_setup_callback_context(user, state_raw)
+
+ if github_error := http_request.GET.get("error"):
+ logger.warning(
+ "github_team_setup: GitHub returned error on callback",
+ error=github_error,
+ description=http_request.GET.get("error_description"),
+ user_id=user.id,
+ )
+ error_code = "access_denied" if github_error == "access_denied" else "github_oauth_error"
+ return FinishResult(
+ redirect_kind="team_setup",
+ next_url=next_url,
+ team_id=team_id,
+ error=error_code,
+ )
+
if not installation_id:
- raise ValidationError("installation_id is required")
+ return FinishResult(
+ redirect_kind="team_setup",
+ next_url=next_url,
+ team_id=team_id,
+ pending=True,
+ )
- if not is_valid_github_installation_id(installation_id):
- raise ValidationError("Invalid installation_id")
+ installation_id_str = str(installation_id)
+ if setup_action == "update" and team_id is None and is_valid_github_installation_id(installation_id):
+ existing_for_user = Integration.objects.first_github_for_user_installation(user, installation_id_str)
+ if existing_for_user is not None:
+ team_id = existing_for_user.team_id
+
+ if team_id is None:
+ return FinishResult(
+ redirect_kind="team_setup",
+ next_url=next_url,
+ team_id=team_id,
+ error="invalid_state",
+ )
- # 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 /")
+ # `resolve_github_setup_callback_context` already filtered team_id by `user.teams`.
+ # Permission changes between authorize-click and callback-return (removed from team,
+ # team deleted) are rare enough to not warrant a typed error; let them 500.
+ team = Team.objects.select_related("organization").get(id=team_id)
+
+ # Membership alone isn't enough — creating a team integration requires admin access, matching
+ # the strict permission that gates setup initiation. The callback's team_id can come from a
+ # user-controlled `next`/`state` param, so a plain member must not complete the install here.
+ if not github_callback_state.has_team_management_access(user, team):
+ return FinishResult(
+ redirect_kind="team_setup",
+ next_url=next_url,
+ team_id=team_id,
+ error="insufficient_permissions",
+ )
- client_id = settings.GITHUB_APP_CLIENT_ID
- if not client_id:
- raise ValidationError("GitHub App client ID is not configured")
+ code = http_request.GET.get("code") or None
+ request = authenticated_drf_request(http_request)
- 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,
- )
+ if setup_action == "update":
+ if not is_valid_github_installation_id(installation_id):
+ return FinishResult(
+ redirect_kind="team_setup",
+ next_url=next_url,
+ team_id=team_id,
+ error="invalid_installation_id",
+ )
+
+ existing = Integration.objects.first_github_for_team_installation(team.id, installation_id_str)
+ if existing is not None:
+ update_result = finish_team_github_setup_update(
+ user=user,
+ team_id=team.id,
+ request=request,
+ installation_id=installation_id_str,
+ existing=existing,
+ state_raw=state_raw,
+ fallback_next_url=next_url,
+ )
+ return FinishResult(
+ redirect_kind="team_setup",
+ next_url=str(update_result.next_url),
+ team_id=team_id,
+ installation_id=update_result.installation_id,
+ integration_id=str(update_result.integration.id) if update_result.integration is not None else None,
+ )
- return "https://github.com/login/oauth/authorize?" + urlencode(
- {
- "client_id": client_id,
- "redirect_uri": github_oauth_redirect_uri(),
- "state": urlencode({"token": token}),
- }
+ try:
+ result = execute_team_github_finish_setup(
+ user=user,
+ team=team,
+ request=request,
+ installation_id=installation_id_str,
+ code=code,
+ setup_action=setup_action,
+ state_raw=state_raw,
+ )
+ except ValidationError as exc:
+ error_code = _validation_error_code(exc) or "github_install_failed"
+ detail: object = exc.detail
+ if isinstance(detail, list) and detail:
+ error_message = str(detail[0])
+ elif isinstance(detail, dict):
+ error_message = str(detail)
+ for value in detail.values():
+ if isinstance(value, list) and value:
+ error_message = str(value[0])
+ else:
+ error_message = str(value)
+ break
+ else:
+ error_message = str(detail)
+ logger.warning(
+ "github_team_setup: finish setup failed",
+ error_code=error_code,
+ user_id=user.id,
+ team_id=team_id,
+ )
+ return FinishResult(
+ redirect_kind="team_setup",
+ next_url=next_url,
+ team_id=team_id,
+ error=error_code,
+ error_message=error_message,
+ )
+
+ if result.oauth_url:
+ return FinishResult(redirect_kind="oauth_url", oauth_url=result.oauth_url)
+
+ success_next = str(result.next_url or redirects.landing_url(next_url, team_id))
+ integration_id = str(result.integration.id) if result.integration is not None else None
+ return FinishResult(
+ redirect_kind="team_setup",
+ next_url=success_next,
+ team_id=team_id,
+ installation_id=str(result.installation_id or installation_id),
+ integration_id=integration_id,
)
+
+
+# Backwards-compatible alias for integration.py
+build_team_oauth_authorize_url = build_team_github_oauth_authorize_url
diff --git a/posthog/api/github_callback/types.py b/posthog/api/github_callback/types.py
index fcfaf47ac4b5..2586c3290473 100644
--- a/posthog/api/github_callback/types.py
+++ b/posthog/api/github_callback/types.py
@@ -1,38 +1,170 @@
-"""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.
-"""
+"""Constants and small helpers shared across the GitHub callback modules."""
import re
+from enum import StrEnum
+from typing import Any, Literal, Self
+from urllib.parse import parse_qsl, urlencode, urlparse
from django.conf import settings
+from pydantic import AliasChoices, BaseModel, ConfigDict, Field, ValidationError
+from rest_framework.exceptions import ValidationError as ApiValidationError
+
+from posthog.models.instance_setting import get_instance_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"
+GITHUB_INSTALLATION_ID_PATTERN = re.compile(r"\d{1,20}")
+GITHUB_AUTHORIZE_STATE_CACHE_TTL_SECONDS = 60 * 15
+GITHUB_UNIFIED_AUTHORIZE_CACHE_PREFIX = "github_authorize:"
+GITHUB_UNIFIED_AUTHORIZE_PENDING_PREFIX = "github_authorize_pending:"
+
+ACCOUNT_CONNECTED_GITHUB_INTEGRATION_PATH = "/account-connected/github-integration"
+PERSONAL_INTEGRATIONS_SETTINGS_PATH = "/settings/user-personal-integrations"
+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", "slack")
-# 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}")
+
+class FlowKind(StrEnum):
+ TEAM_INSTALL = "team_install"
+ TEAM_UPDATE = "team_update"
+ TEAM_OAUTH = "team_oauth"
+ PERSONAL_INSTALL = "personal_install"
+ PERSONAL_OAUTH = "personal_oauth"
+ PERSONAL_UPDATE = "personal_update"
+ OAUTH_DISCOVER = "oauth_discover"
+
+ @property
+ def is_oauth_redirect(self) -> bool:
+ """OAuth returned to /complete/github-link/ — code exchange uses redirect_uri."""
+ return self in (FlowKind.PERSONAL_OAUTH, FlowKind.OAUTH_DISCOVER, FlowKind.TEAM_OAUTH)
+
+ @property
+ def discovers_installations(self) -> bool:
+ return self is FlowKind.OAUTH_DISCOVER
+
+ @property
+ def creates_team_integration(self) -> bool:
+ return self is FlowKind.TEAM_OAUTH
+
+ @property
+ def is_personal(self) -> bool:
+ return self in (
+ FlowKind.PERSONAL_INSTALL,
+ FlowKind.PERSONAL_OAUTH,
+ FlowKind.PERSONAL_UPDATE,
+ FlowKind.OAUTH_DISCOVER,
+ )
+
+
+def team_id_from_next_url(next_url: str) -> int | None:
+ if not next_url:
+ return None
+ path_parts = [part for part in urlparse(next_url).path.split("/") if part]
+ if len(path_parts) >= 2 and path_parts[0] == "project":
+ try:
+ return int(path_parts[1])
+ except ValueError:
+ pass
+ return None
+
+
+def is_personal_github_setup_state(state_raw: str | None) -> bool:
+ """True when GitHub's Setup URL callback belongs to a personal UserIntegration flow."""
+ if not state_raw:
+ return False
+ return dict(parse_qsl(state_raw)).get("source") == "user_integration"
+
+
+class GitHubAuthorizeState(BaseModel):
+ model_config = ConfigDict(frozen=True, extra="ignore")
+
+ token: str
+ flow: FlowKind
+ user_id: int
+ team_id: int | None = None
+ installation_id: str | None = None
+ next_url: str | None = Field(
+ default=None,
+ validation_alias=AliasChoices("next_url", "next"),
+ serialization_alias="next",
+ )
+ connect_from: str | None = None
+
+ @classmethod
+ def from_cache(cls, token: str, payload: dict[str, Any]) -> Self:
+ return cls.model_validate({**payload, "token": token})
+
+ @classmethod
+ def try_from_cache(cls, token: str, payload: dict[str, Any]) -> Self | None:
+ try:
+ return cls.from_cache(token, payload)
+ except ValidationError:
+ return None
+
+ def cache_payload(self) -> dict[str, Any]:
+ return self.model_dump(mode="json", exclude_none=True, by_alias=True)
+
+
+class CallbackContext(BaseModel):
+ model_config = ConfigDict(extra="forbid")
+
+ entry: Literal["setup_url", "oauth_redirect"]
+ resume_path: str
+ installation_id: str | None
+ setup_action: str | None
+ code: str | None
+ state_raw: str | None
+ github_error: str | None
+ github_error_description: str | None
+ flow: FlowKind | None = None
+ authorize_state: GitHubAuthorizeState | None = None
+
+
+class FinishResult(BaseModel):
+ model_config = ConfigDict(frozen=True, extra="forbid")
+
+ redirect_kind: Literal["team_setup", "personal_finish", "oauth_url", "team_oauth_success"]
+ next_url: str | None = None
+ team_id: int | None = None
+ connect_from: str | None = None
+ installation_id: str | None = None
+ integration_id: str | None = None
+ oauth_url: str | None = None
+ error: str | None = None
+ error_message: str | None = None
+ pending: bool = False
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)))
+def github_app_install_url(state: str) -> str:
+ instance_settings = get_instance_settings(["GITHUB_APP_SLUG"])
+ app_slug = instance_settings.get("GITHUB_APP_SLUG")
+ if not app_slug:
+ raise ApiValidationError("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:
+ if not settings.GITHUB_APP_CLIENT_ID:
+ raise ApiValidationError("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 is_valid_github_installation_id(installation_id: object | None) -> bool:
+ if installation_id is None:
+ return False
+ return bool(GITHUB_INSTALLATION_ID_PATTERN.fullmatch(str(installation_id)))
diff --git a/posthog/api/github_callback/views.py b/posthog/api/github_callback/views.py
new file mode 100644
index 000000000000..bcfab9bb220c
--- /dev/null
+++ b/posthog/api/github_callback/views.py
@@ -0,0 +1,144 @@
+from typing import Literal, cast
+
+from django.core.cache import cache
+from django.http import HttpRequest, HttpResponseRedirect
+from django.views.decorators.http import require_http_methods
+
+from posthog.api.github_callback import personal_finish, redirects, state, team_services
+from posthog.api.github_callback.types import CallbackContext, FinishResult, FlowKind, is_personal_github_setup_state
+from posthog.auth import session_auth_required
+from posthog.models import User
+from posthog.models.user_integration import UserIntegration
+from posthog.views import login_required
+
+
+def _parse_callback(request: HttpRequest, entry: Literal["setup_url", "oauth_redirect"]) -> CallbackContext:
+ state_raw = request.GET.get("state")
+ ctx = CallbackContext(
+ entry=entry,
+ resume_path=request.get_full_path(),
+ installation_id=request.GET.get("installation_id"),
+ setup_action=request.GET.get("setup_action") or None,
+ code=request.GET.get("code") or None,
+ state_raw=state_raw,
+ github_error=request.GET.get("error"),
+ github_error_description=request.GET.get("error_description"),
+ )
+
+ user = cast(User, request.user)
+ token: str | None = None
+ if state_raw:
+ token, _ = state.parse_github_authorize_state_param(state_raw)
+ if token is None:
+ pending_token = cache.get(state.unified_authorize_pending_cache_key(user.id))
+ if pending_token is not None:
+ token = str(pending_token)
+
+ if token:
+ ctx.authorize_state = state.load_authorize_state(token, user_id=user.id)
+ if ctx.authorize_state is not None:
+ ctx.flow = ctx.authorize_state.flow
+ return ctx
+
+ if entry == "setup_url" and is_personal_github_setup_state(state_raw):
+ ctx.flow = FlowKind.PERSONAL_INSTALL
+ elif entry == "setup_url" and ctx.setup_action == "update":
+ if state.has_pending_personal_setup_update(user, ctx.installation_id):
+ ctx.flow = FlowKind.PERSONAL_UPDATE
+
+ return ctx
+
+
+def _is_personal_github_setup_update(user: User, ctx: CallbackContext) -> bool:
+ # When state was present and loaded, trust the flow it encodes. Only the explicit
+ # personal-update flow should route here — any team-side flow (install, update,
+ # oauth recovery) must fall through to finish_team_setup. The UserIntegration
+ # fallback below only applies when state is missing (e.g. user opened GitHub
+ # directly without going through PostHog UI).
+ if ctx.flow is not None:
+ return ctx.flow == FlowKind.PERSONAL_UPDATE
+ if not ctx.installation_id:
+ return False
+ return UserIntegration.objects.filter(
+ user=user,
+ kind=UserIntegration.IntegrationKind.GITHUB,
+ integration_id=str(ctx.installation_id),
+ ).exists()
+
+
+def _finish(http_request: HttpRequest, ctx: CallbackContext) -> FinishResult:
+ user = http_request.user
+ assert user.is_authenticated
+
+ if ctx.github_error:
+ error_code = "access_denied" if ctx.github_error == "access_denied" else "github_oauth_error"
+ # Team-flow failures should land on the project page, not the personal page —
+ # the user was trying to set up a team integration. State is still in cache at this point
+ # (load_authorize_state is read-only), so we have the team_id and next_url to redirect with.
+ if (
+ ctx.flow in (FlowKind.TEAM_OAUTH, FlowKind.TEAM_INSTALL, FlowKind.TEAM_UPDATE)
+ and ctx.authorize_state is not None
+ ):
+ return FinishResult(
+ redirect_kind="team_setup",
+ next_url=ctx.authorize_state.next_url,
+ team_id=ctx.authorize_state.team_id,
+ error=error_code,
+ )
+ # Trust the server-side cached flow over the mutable callback query string.
+ if (
+ (ctx.flow is not None and ctx.flow.is_personal)
+ or ctx.entry == "oauth_redirect"
+ or is_personal_github_setup_state(ctx.state_raw)
+ ):
+ connect_from = ctx.authorize_state.connect_from if ctx.authorize_state else None
+ return FinishResult(redirect_kind="personal_finish", connect_from=connect_from, error=error_code)
+ team_id, next_url = state.resolve_github_setup_callback_context(user, ctx.state_raw)
+ return FinishResult(
+ redirect_kind="team_setup",
+ next_url=next_url,
+ team_id=team_id,
+ error=error_code,
+ )
+
+ # Trust the server-side cached flow over the mutable callback query string: a personal
+ # state with `source=user_integration` stripped must never fall through to team setup.
+ if ctx.flow is not None and ctx.flow.is_personal:
+ if ctx.flow == FlowKind.PERSONAL_UPDATE:
+ return personal_finish.finish_personal_setup_update(http_request)
+ return personal_finish.finish_personal(http_request)
+
+ # Team install/update flows complete via finish_team_setup even when GitHub returns
+ # them to the OAuth callback URL — which it does when the App is already installed
+ # (setup_action=update) or when "request user authorization during installation" is on.
+ # Without this, the oauth_redirect branch below would hand the team flow to
+ # finish_personal, which links the installation personally and never creates the team
+ # Integration. (TEAM_OAUTH is intentionally completed by finish_personal.)
+ if ctx.flow in (FlowKind.TEAM_INSTALL, FlowKind.TEAM_UPDATE):
+ return team_services.finish_team_setup(http_request)
+
+ if ctx.entry == "oauth_redirect" or is_personal_github_setup_state(ctx.state_raw):
+ return personal_finish.finish_personal(http_request)
+
+ if ctx.setup_action == "update" and ctx.installation_id and _is_personal_github_setup_update(user, ctx):
+ return personal_finish.finish_personal_setup_update(http_request)
+
+ return team_services.finish_team_setup(http_request)
+
+
+@require_http_methods(["GET"])
+@login_required
+def github_setup_callback(request: HttpRequest) -> HttpResponseRedirect:
+ """GitHub App Setup URL — team finish or personal install."""
+ ctx = _parse_callback(request, "setup_url")
+ result = _finish(request, ctx)
+ return redirects.redirect_from_finish_result(result)
+
+
+@require_http_methods(["GET"])
+@session_auth_required
+def github_oauth_callback(request: HttpRequest) -> HttpResponseRedirect:
+ """GitHub User OAuth redirect_uri — personal and team-oauth recovery flows."""
+ ctx = _parse_callback(request, "oauth_redirect")
+ result = _finish(request, ctx)
+ return redirects.redirect_from_finish_result(result)
diff --git a/posthog/api/integration.py b/posthog/api/integration.py
index e50f35fb2d74..f7ccd700a922 100644
--- a/posthog/api/integration.py
+++ b/posthog/api/integration.py
@@ -20,11 +20,18 @@ from rest_framework.permissions import IsAuthenticated
from rest_framework.request import Request
from rest_framework.response import Response
+from posthog.api.github_callback import state as github_callback_state
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.github_callback.types import (
+ FlowKind,
+ GitHubAuthorizeState,
+ github_app_install_url,
+ is_valid_github_installation_id,
+)
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.api.shared import UserBasicSerializer
from posthog.api.utils import action
@@ -34,7 +41,6 @@ from posthog.event_usage import report_user_action
from posthog.exceptions_capture import capture_exception
from posthog.helpers.fuzzy_search import fuzzy_filter
from posthog.models import OrganizationMembership, User
-from posthog.models.instance_setting import get_instance_setting
from posthog.models.integration import (
ANTHROPIC_DEFAULT_INTEGRATION_ID_PREFIX,
ANTHROPIC_MANAGED_AGENT_LIST_PAGE_LIMIT,
@@ -81,6 +87,7 @@ from posthog.permissions import (
from posthog.rate_limit import GitHubRepositoryRefreshThrottle
from posthog.rbac.user_access_control import UserAccessControlSerializerMixin
from posthog.tasks.email import send_integration_access_request
+from posthog.utils import is_relative_url
from products.cdp.backend.services.integration_usage import get_enabled_hog_functions_using_integration
from products.workflows.backend.services.integration_usage import get_active_hog_flows_using_integration
@@ -408,6 +415,7 @@ class IntegrationSerializer(serializers.ModelSerializer, UserAccessControlSerial
elif validated_data["kind"] == "github":
config = validated_data.get("config", {})
return create_team_github_integration_from_oauth_code(
+ request=request,
user=request.user,
team_id=team_id,
installation_id=config.get("installation_id"),
@@ -727,6 +735,54 @@ class IntegrationSerializer(serializers.ModelSerializer, UserAccessControlSerial
raise ValidationError("Kind not supported")
+class GitHubPrepareCallbackRequestSerializer(serializers.Serializer):
+ next = serializers.CharField(
+ required=False,
+ allow_blank=True,
+ help_text="Relative URL to redirect to after GitHub setup completes (e.g. account-connected for PostHog Code).",
+ )
+ installation_id = serializers.CharField(
+ required=False,
+ allow_blank=True,
+ help_text="GitHub installation ID being managed; binds the seeded update state so a callback can't swap in a different installation.",
+ )
+
+
+class GitHubLinkExistingRequestSerializer(serializers.Serializer):
+ source_team_id = serializers.IntegerField(
+ required=False,
+ allow_null=True,
+ help_text="Sibling team in the same organization whose GitHub installation should be reused.",
+ )
+ installation_id = serializers.CharField(
+ required=False,
+ allow_blank=True,
+ help_text="GitHub installation ID to link; resolved within the organization when source_team_id is omitted.",
+ )
+
+
+class GitHubOAuthAuthorizeRequestSerializer(serializers.Serializer):
+ installation_id = serializers.CharField(
+ required=False,
+ allow_blank=True,
+ help_text="GitHub installation ID to carry through the User OAuth flow.",
+ )
+ next = serializers.CharField(
+ required=False,
+ allow_blank=True,
+ help_text="Relative URL to redirect to after the OAuth flow completes.",
+ )
+ connect_from = serializers.ChoiceField(
+ required=False,
+ choices=["posthog_code"],
+ help_text="Originating surface for the connect flow; only 'posthog_code' is recognized.",
+ )
+
+
+class GitHubOAuthAuthorizeResponseSerializer(serializers.Serializer):
+ oauth_url = serializers.CharField(help_text="GitHub User OAuth URL the client should redirect to.")
+
+
@extend_schema(extensions={"x-product": "integrations"})
class IntegrationViewSet(
TeamAndOrgViewSetMixin,
@@ -755,6 +811,7 @@ class IntegrationViewSet(
"patch",
"destroy",
"refresh_github_repos",
+ "github_prepare_callback",
"github_link_existing",
"github_oauth_authorize",
# Side-effecting POST (emails admins) — a read-only token must not be able to trigger it.
@@ -872,17 +929,20 @@ class IntegrationViewSet(
except NotImplementedError:
raise ValidationError("Kind not configured")
elif kind == "github":
- query_params = urlencode({"state": urlencode({"next": next, "token": token})})
- app_slug = get_instance_setting("GITHUB_APP_SLUG")
- installation_url = f"https://github.com/apps/{app_slug}/installations/new?{query_params}"
- response = redirect(installation_url)
- # nosemgrep: python.django.security.audit.secure-cookies.django-secure-set-cookie (OAuth state, short-lived, needed for cross-site redirect)
- response.set_cookie("ph_github_state", token, max_age=60 * 5)
- # Store server-side so the backend can enforce that the same user who
- # initiated the flow is the one completing it (not just cookie-validated).
- cache.set(f"github_state:{request.user.id}", token, timeout=60 * 5)
-
- return response
+ if next and not is_relative_url(next):
+ raise ValidationError("next must be a relative path starting with /")
+ state_param = urlencode({"next": next, "token": token})
+ installation_url = github_app_install_url(state_param)
+ github_callback_state.store_unified_authorize_state(
+ GitHubAuthorizeState(
+ token=token,
+ flow=FlowKind.TEAM_INSTALL,
+ user_id=github_callback_state.authenticated_user_id(request),
+ team_id=self.team_id,
+ next_url=next or None,
+ ),
+ )
+ return redirect(installation_url)
raise ValidationError("Kind not supported")
@@ -1324,6 +1384,39 @@ class IntegrationViewSet(
return Response({"repositories": repositories, "has_more": has_more})
+ @extend_schema(request=GitHubPrepareCallbackRequestSerializer, responses={204: None})
+ @action(methods=["POST"], detail=False, url_path="github/prepare_callback")
+ def github_prepare_callback(self, request: Request, *args: Any, **kwargs: Any) -> Response:
+ """Seed GitHub setup callback state without redirecting to GitHub.
+
+ Used when the user opens an existing installation's settings on github.com (e.g. PostHog
+ Code "Update in GitHub") so the subsequent Setup URL redirect can be validated.
+ """
+ serializer = GitHubPrepareCallbackRequestSerializer(data=request.data)
+ serializer.is_valid(raise_exception=True)
+ next_url = str(serializer.validated_data.get("next") or "")
+ if next_url and not is_relative_url(next_url):
+ raise ValidationError("next must be a relative path starting with /")
+ installation_id = str(serializer.validated_data.get("installation_id") or "") or None
+ if installation_id is not None and not is_valid_github_installation_id(installation_id):
+ raise ValidationError("Invalid installation_id")
+ token = os.urandom(33).hex()
+ github_callback_state.store_unified_authorize_state(
+ GitHubAuthorizeState(
+ token=token,
+ flow=FlowKind.TEAM_UPDATE,
+ user_id=github_callback_state.authenticated_user_id(request),
+ team_id=self.team_id,
+ installation_id=installation_id,
+ next_url=next_url or None,
+ ),
+ )
+ return Response(status=204)
+
+ @extend_schema(
+ request=GitHubLinkExistingRequestSerializer,
+ responses={200: IntegrationSerializer},
+ )
@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."""
@@ -1336,13 +1429,17 @@ class IntegrationViewSet(
)
return Response(self.get_serializer(instance).data)
+ @extend_schema(
+ request=GitHubOAuthAuthorizeRequestSerializer,
+ responses={200: GitHubOAuthAuthorizeResponseSerializer},
+ )
@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."""
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"),
+ installation_id=str(request.data.get("installation_id") or ""),
next_url=str(request.data.get("next") or ""),
connect_from=request.data.get("connect_from")
if request.data.get("connect_from") == "posthog_code"
diff --git a/posthog/api/test/test_integration.py b/posthog/api/test/test_integration.py
index b63eed117c42..f678eeaac2ab 100644
--- a/posthog/api/test/test_integration.py
+++ b/posthog/api/test/test_integration.py
@@ -1,16 +1,14 @@
-import re
import hmac
import json
import time
import hashlib
from datetime import timedelta
-from urllib.parse import quote
+from urllib.parse import quote, urlencode
import pytest
from posthog.test.base import APIBaseTest
from unittest.mock import MagicMock, patch
-from django.conf import settings as django_settings
from django.core.cache import cache
from django.test import override_settings
from django.test.client import Client as HttpClient
@@ -20,6 +18,8 @@ import requests
from parameterized import parameterized
from rest_framework import status
+from posthog.api.github_callback.state import store_unified_authorize_state
+from posthog.api.github_callback.types import FlowKind, GitHubAuthorizeState
from posthog.api.integration import IntegrationSerializer, IntegrationViewSet
from posthog.models.integration import (
ERROR_TOKEN_REFRESH_FAILED,
@@ -29,6 +29,7 @@ from posthog.models.integration import (
EmailIntegration,
GitHubIntegration,
GitHubIntegrationError,
+ GitHubUserAuthorization,
Integration,
SlackIntegration,
StripeIntegration,
@@ -1705,7 +1706,15 @@ class TestGitHubIntegrationStateValidation:
@patch("posthog.models.integration.GitHubIntegration.integration_from_installation_id")
def test_create_github_integration_with_invalid_state_rejected(self, mock_from_install, client: HttpClient):
client.force_login(self.user)
- cache.set(f"github_state:{self.user.id}", "correct-token", timeout=300)
+ store_unified_authorize_state(
+ GitHubAuthorizeState(
+ token="correct-token",
+ flow=FlowKind.TEAM_INSTALL,
+ user_id=self.user.id,
+ team_id=self.team.pk,
+ next_url="" or None,
+ ),
+ )
response = client.post(
f"/api/environments/{self.team.pk}/integrations/",
@@ -1732,6 +1741,38 @@ class TestGitHubIntegrationStateValidation:
assert "Invalid or expired state token" in response.json()["detail"]
mock_from_install.assert_not_called()
+ def test_github_prepare_callback_stores_authorize_state(self, client: HttpClient):
+ client.force_login(self.user)
+ next_path = (
+ f"/account-connected/github-integration?provider=github&project_id={self.team.pk}&connect_from=posthog_code"
+ )
+
+ response = client.post(
+ f"/api/environments/{self.team.pk}/integrations/github/prepare_callback/",
+ {"next": next_path},
+ content_type="application/json",
+ )
+
+ assert response.status_code == status.HTTP_204_NO_CONTENT
+ pending_token = cache.get(f"github_authorize_pending:{self.user.id}")
+ assert pending_token
+ cached = cache.get(f"github_authorize:{pending_token}")
+ assert cached is not None
+ assert cached["next"] == next_path
+ assert cached["token"] == pending_token
+ assert cached["team_id"] == self.team.pk
+
+ def test_github_authorize_rejects_absolute_next_url(self, client: HttpClient):
+ client.force_login(self.user)
+
+ response = client.get(
+ f"/api/environments/{self.team.pk}/integrations/authorize/",
+ {"kind": "github", "next": "https://evil.com"},
+ )
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert "next must be a relative path" in response.json()["detail"]
+
@patch("posthog.models.github_integration_base.GitHubIntegrationBase.verify_user_installation_access")
@patch("posthog.models.integration.GitHubIntegration.github_user_from_code")
@patch("posthog.models.integration.GitHubIntegration.integration_from_installation_id")
@@ -1743,7 +1784,15 @@ class TestGitHubIntegrationStateValidation:
client.force_login(self.user)
state_token = "valid-token-abc123"
- cache.set(f"github_state:{self.user.id}", state_token, timeout=300)
+ store_unified_authorize_state(
+ GitHubAuthorizeState(
+ token=state_token,
+ flow=FlowKind.TEAM_INSTALL,
+ user_id=self.user.id,
+ team_id=self.team.pk,
+ next_url="" or None,
+ ),
+ )
mock_from_code.return_value = GitHubUserAuthorization(
gh_id=42,
@@ -1774,7 +1823,8 @@ class TestGitHubIntegrationStateValidation:
mock_verify.assert_called_once_with("12345", "ghu_test")
mock_from_install.assert_called_once_with("12345", self.team.pk, self.user)
# Token consumed — cannot be reused
- assert cache.get(f"github_state:{self.user.id}") is None
+ assert cache.get(f"github_authorize:{state_token}") is None
+ assert cache.get(f"github_authorize_pending:{self.user.id}") is None
@patch("posthog.models.github_integration_base.GitHubIntegrationBase.verify_user_installation_access")
@patch("posthog.models.integration.GitHubIntegration.github_user_from_code")
@@ -1787,7 +1837,15 @@ class TestGitHubIntegrationStateValidation:
client.force_login(self.user)
state_token = "single-use-token"
- cache.set(f"github_state:{self.user.id}", state_token, timeout=300)
+ store_unified_authorize_state(
+ GitHubAuthorizeState(
+ token=state_token,
+ flow=FlowKind.TEAM_INSTALL,
+ user_id=self.user.id,
+ team_id=self.team.pk,
+ next_url="" or None,
+ ),
+ )
mock_from_code.return_value = GitHubUserAuthorization(
gh_id=42,
@@ -1831,7 +1889,15 @@ class TestGitHubIntegrationStateValidation:
)
client.force_login(other_user)
# Token belongs to self.user, not other_user
- cache.set(f"github_state:{self.user.id}", "victim-token", timeout=300)
+ store_unified_authorize_state(
+ GitHubAuthorizeState(
+ token="victim-token",
+ flow=FlowKind.TEAM_INSTALL,
+ user_id=self.user.id,
+ team_id=self.team.pk,
+ next_url="" or None,
+ ),
+ )
response = client.post(
f"/api/environments/{self.team.pk}/integrations/",
@@ -1850,7 +1916,15 @@ class TestGitHubIntegrationStateValidation:
):
client.force_login(self.user)
state_token = "valid-token"
- cache.set(f"github_state:{self.user.id}", state_token, timeout=300)
+ store_unified_authorize_state(
+ GitHubAuthorizeState(
+ token=state_token,
+ flow=FlowKind.TEAM_INSTALL,
+ user_id=self.user.id,
+ team_id=self.team.pk,
+ next_url="" or None,
+ ),
+ )
mock_from_code.return_value = None
@@ -1892,7 +1966,15 @@ class TestGitHubIntegrationStateValidation:
client.force_login(self.user)
state_token = "valid-attacker-state"
- cache.set(f"github_state:{self.user.id}", state_token, timeout=300)
+ store_unified_authorize_state(
+ GitHubAuthorizeState(
+ token=state_token,
+ flow=FlowKind.TEAM_INSTALL,
+ user_id=self.user.id,
+ team_id=self.team.pk,
+ next_url="" or None,
+ ),
+ )
# The App-JWT call in integration_from_installation_id succeeds for any of the
# App's installations (this is intrinsic to GitHub Apps — the JWT is App-scoped,
@@ -1953,1208 +2035,1376 @@ class TestGitHubIntegrationStateValidation:
)
-class TestStripeIntegration:
+class TestGitHubTeamIntegrationComplete:
@pytest.fixture(autouse=True)
- def setup_integration(self, db):
+ def setup_environment(self, db):
self.organization = Organization.objects.create(name="Test Org")
self.team = Team.objects.create(organization=self.organization, name="Test Team")
self.user = User.objects.create_and_join(
self.organization, "[email protected]", "test", level=OrganizationMembership.Level.ADMIN
)
- def _create_stripe_integration(self) -> Integration:
+ def _team_github_integration(self, installation_id: str = "12345") -> Integration:
return Integration.objects.create(
team=self.team,
- kind="stripe",
- config={"account_name": "Test Business (acct_123)"},
- sensitive_config={"access_token": "sk_live_test123"},
- integration_id="acct_123",
- created_by=self.user,
+ kind="github",
+ integration_id=installation_id,
+ config={"installation_id": installation_id},
+ sensitive_config={"access_token": "ghs_test"},
)
- @patch("posthog.api.integration.StripeIntegration")
- def test_destroy_calls_clear_posthog_secrets(self, MockStripeIntegration, client: HttpClient):
- integration = self._create_stripe_integration()
- mock_instance = MagicMock()
- MockStripeIntegration.return_value = mock_instance
+ def _github_user_authorization(self) -> GitHubUserAuthorization:
+ return GitHubUserAuthorization(
+ gh_id=42,
+ gh_login="testuser",
+ access_token="ghu_test",
+ refresh_token=None,
+ access_token_expires_in=None,
+ refresh_token_expires_in=None,
+ )
+ @pytest.mark.parametrize(
+ "query,must_not_contain",
+ [
+ ({"installation_id": "12345", "code": "abc", "setup_action": "install"}, []),
+ (
+ {
+ "installation_id": "12345",
+ "code": "abc",
+ "state": urlencode({"token": "personal-token", "source": "user_integration"}),
+ },
+ ["/complete/github-link"],
+ ),
+ ],
+ )
+ def test_unauthenticated_redirects_to_login(self, query, must_not_contain, client: HttpClient):
+ response = client.get("/integrations/github/callback/", query)
+ assert response.status_code == status.HTTP_302_FOUND
+ location = response["Location"]
+ assert location.startswith("/login?next=")
+ assert "/integrations/github/callback" in location
+ for forbidden in must_not_contain:
+ assert forbidden not in location
+
+ def test_github_error_redirects_with_setup_error(self, client: HttpClient):
client.force_login(self.user)
- response = client.delete(f"/api/environments/{self.team.pk}/integrations/{integration.id}/")
+ next_path = f"/project/{self.team.pk}/settings/project-integrations"
+ store_unified_authorize_state(
+ GitHubAuthorizeState(
+ token="t",
+ flow=FlowKind.TEAM_INSTALL,
+ user_id=self.user.id,
+ team_id=self.team.pk,
+ next_url=next_path or None,
+ ),
+ )
- assert response.status_code == status.HTTP_204_NO_CONTENT
- MockStripeIntegration.assert_called_once()
- mock_instance.clear_posthog_secrets.assert_called_once()
- assert not Integration.objects.filter(id=integration.id).exists()
+ response = client.get("/integrations/github/callback/", {"error": "access_denied"})
- @patch("posthog.api.integration.StripeIntegration")
- def test_destroy_still_deletes_when_clear_secrets_fails(self, MockStripeIntegration, client: HttpClient):
- integration = self._create_stripe_integration()
- mock_instance = MagicMock()
- mock_instance.clear_posthog_secrets.side_effect = Exception("Stripe API error")
- MockStripeIntegration.return_value = mock_instance
+ assert response.status_code == status.HTTP_302_FOUND
+ assert "github_setup_error=access_denied" in response["Location"]
+ assert f"project/{self.team.pk}/settings/project-integrations" in response["Location"]
+ @override_settings(GITHUB_APP_CLIENT_ID="client_id", SITE_URL="https://us.posthog.com")
+ def test_team_install_via_oauth_callback_routes_to_team_not_personal(self, client: HttpClient):
+ # "Connect organization" seeds TEAM_INSTALL and sends the user to the App install URL. When
+ # the App is already installed, GitHub returns to the OAuth callback URL (/complete/github-link/)
+ # rather than the setup URL. The dispatcher must still complete this as a team flow — not hand it
+ # to the personal finisher, which would link the installation personally and never create the team
+ # Integration (landing on user-personal-integrations).
client.force_login(self.user)
- response = client.delete(f"/api/environments/{self.team.pk}/integrations/{integration.id}/")
-
- assert response.status_code == status.HTTP_204_NO_CONTENT
- assert not Integration.objects.filter(id=integration.id).exists()
+ next_path = f"/project/{self.team.pk}/settings/environment-integrations"
+ store_unified_authorize_state(
+ GitHubAuthorizeState(
+ token="team-install-token",
+ flow=FlowKind.TEAM_INSTALL,
+ user_id=self.user.id,
+ team_id=self.team.pk,
+ next_url=next_path,
+ ),
+ )
- def test_destroy_non_stripe_does_not_call_clear_secrets(self, client: HttpClient):
- integration = Integration.objects.create(
- team=self.team,
- kind="slack",
- config={"authed_user": {"id": "U123"}},
- sensitive_config={"access_token": "xoxb-test"},
- created_by=self.user,
+ response = client.get(
+ "/complete/github-link/",
+ {
+ "installation_id": "75826265",
+ "setup_action": "update",
+ "state": urlencode({"token": "team-install-token"}),
+ },
)
- client.force_login(self.user)
- with patch("posthog.api.integration.StripeIntegration") as MockStripeIntegration:
- response = client.delete(f"/api/environments/{self.team.pk}/integrations/{integration.id}/")
+ assert response.status_code == status.HTTP_302_FOUND
+ # Installation isn't a team integration yet, so the team flow bounces to team OAuth to mint a
+ # code — it must NOT land on the personal success page.
+ assert "github.com/login/oauth/authorize" in response["Location"]
+ assert "user-personal-integrations" not in response["Location"]
- assert response.status_code == status.HTTP_204_NO_CONTENT
- MockStripeIntegration.assert_not_called()
- assert not Integration.objects.filter(id=integration.id).exists()
+ def test_missing_installation_id_redirects_pending(self, client: HttpClient):
+ client.force_login(self.user)
+ next_path = f"/project/{self.team.pk}/settings/project-integrations"
+ store_unified_authorize_state(
+ GitHubAuthorizeState(
+ token="t",
+ flow=FlowKind.TEAM_INSTALL,
+ user_id=self.user.id,
+ team_id=self.team.pk,
+ next_url=next_path or None,
+ ),
+ )
- @pytest.fixture()
- def stripe_settings(self, settings):
- settings.STRIPE_APP_CLIENT_ID = "ca_test123"
- settings.STRIPE_APP_SECRET_KEY = "sk_test_secret"
- settings.STRIPE_SIGNING_SECRET = "whsec_test_signing"
- return settings
+ response = client.get("/integrations/github/callback/")
- def _make_install_signature(
- self, state: str, user_id: str, account_id: str, secret: str = "whsec_test_signing"
- ) -> str:
- """Build a valid t=...,v1=... header for a marketplace install callback."""
- ts = int(time.time())
- payload = json.dumps(
- {"state": state, "user_id": user_id, "account_id": account_id},
- separators=(",", ":"),
- )
- signed = f"{ts}.{payload}".encode()
- digest = hmac.new(secret.encode("utf-8"), signed, hashlib.sha256).hexdigest()
- return f"t={ts},v1={digest}"
+ assert response.status_code == status.HTTP_302_FOUND
+ assert "github_install_pending=1" in response["Location"]
- @patch("posthog.api.integration.StripeIntegration")
- @patch("posthog.api.integration.OauthIntegration.integration_from_oauth_response")
- def test_create_calls_write_posthog_secrets(
- self, mock_oauth_response, MockStripeIntegration, stripe_settings, client: HttpClient
+ @patch("posthog.models.github_integration_base.GitHubIntegrationBase.verify_user_installation_access")
+ @patch("posthog.models.integration.GitHubIntegration.github_user_from_code")
+ @patch("posthog.models.integration.GitHubIntegration.integration_from_installation_id")
+ @patch("posthog.models.user_integration.user_github_integration_from_installation")
+ def test_success_redirects_to_next_with_integration_id(
+ self, mock_user_integration, mock_from_install, mock_from_code, mock_verify, client: HttpClient
):
- created_integration = self._create_stripe_integration()
- mock_oauth_response.return_value = created_integration
- mock_instance = MagicMock()
- MockStripeIntegration.return_value = mock_instance
-
client.force_login(self.user)
- response = client.post(
- f"/api/environments/{self.team.pk}/integrations",
- {"kind": "stripe", "config": {"code": "oauth_code_123"}},
- content_type="application/json",
+ next_path = (
+ f"/account-connected/github-integration?provider=github&project_id={self.team.pk}&connect_from=posthog_code"
+ )
+ state_token = "valid-token"
+ store_unified_authorize_state(
+ GitHubAuthorizeState(
+ token=state_token,
+ flow=FlowKind.TEAM_INSTALL,
+ user_id=self.user.id,
+ team_id=self.team.pk,
+ next_url=next_path or None,
+ ),
)
- assert response.status_code == status.HTTP_201_CREATED
- MockStripeIntegration.assert_called_once_with(created_integration)
- mock_instance.write_posthog_secrets.assert_called_once_with(self.team.pk, self.user)
-
- @patch("posthog.api.integration.StripeIntegration")
- @patch("posthog.api.integration.OauthIntegration.integration_from_oauth_response")
- def test_create_succeeds_when_write_secrets_fails(
- self, mock_oauth_response, MockStripeIntegration, stripe_settings, client: HttpClient
- ):
- created_integration = self._create_stripe_integration()
- mock_oauth_response.return_value = created_integration
- mock_instance = MagicMock()
- mock_instance.write_posthog_secrets.side_effect = Exception("Stripe API error")
- MockStripeIntegration.return_value = mock_instance
+ mock_from_code.return_value = self._github_user_authorization()
+ mock_verify.return_value = True
+ mock_from_install.return_value = self._team_github_integration()
- client.force_login(self.user)
- response = client.post(
- f"/api/environments/{self.team.pk}/integrations",
- {"kind": "stripe", "config": {"code": "oauth_code_123"}},
- content_type="application/json",
+ response = client.get(
+ "/integrations/github/callback/",
+ {
+ "installation_id": "12345",
+ "code": "oauth-code-abc",
+ "setup_action": "install",
+ "state": urlencode({"next": next_path, "token": state_token}),
+ },
)
- assert response.status_code == status.HTTP_201_CREATED
+ assert response.status_code == status.HTTP_302_FOUND
+ location = response["Location"]
+ assert "account-connected/github-integration" in location
+ assert "integration_id=" in location
+ assert "installation_id=12345" in location
+ assert cache.get(f"github_authorize:{state_token}") is None
+ assert cache.get(f"github_authorize_pending:{self.user.id}") is None
- @patch("posthog.api.integration.StripeIntegration")
- @patch("posthog.api.integration.OauthIntegration.integration_from_oauth_response")
- def test_posthog_initiated_oauth_with_state_still_works(
- self, mock_oauth_response, MockStripeIntegration, stripe_settings, client: HttpClient
- ):
- created_integration = self._create_stripe_integration()
- mock_oauth_response.return_value = created_integration
- mock_instance = MagicMock()
- MockStripeIntegration.return_value = mock_instance
+ def test_non_admin_member_cannot_complete_team_install(self, client: HttpClient):
+ member = User.objects.create_and_join(
+ self.organization, "[email protected]", "test", level=OrganizationMembership.Level.MEMBER
+ )
+ client.force_login(member)
- client.force_login(self.user)
- response = client.post(
- f"/api/environments/{self.team.pk}/integrations",
- {"kind": "stripe", "config": {"state": "next=/foo&token=abc123", "code": "oauth_code_123"}},
- content_type="application/json",
+ # No valid authorize state — the member supplies the team via the user-controlled `state` `next`,
+ # which resolves team_id purely from the path. Membership alone must not let them complete it.
+ next_path = f"/project/{self.team.pk}/settings/project-integrations"
+ response = client.get(
+ "/integrations/github/callback/",
+ {
+ "installation_id": "12345",
+ "code": "oauth-code-abc",
+ "setup_action": "install",
+ "state": urlencode({"next": next_path, "token": "no-such-token"}),
+ },
)
- assert response.status_code == status.HTTP_201_CREATED
- mock_instance.write_posthog_secrets.assert_called_once_with(self.team.pk, self.user)
+ assert response.status_code == status.HTTP_302_FOUND
+ assert "github_setup_error=insufficient_permissions" in response["Location"]
+ assert not Integration.objects.filter(team=self.team, kind="github").exists()
- @patch("posthog.api.integration.StripeIntegration")
- @patch("posthog.api.integration.OauthIntegration.integration_from_oauth_response")
- def test_posthog_initiated_oauth_ignores_marketplace_conflict_guard(
- self, mock_oauth_response, MockStripeIntegration, stripe_settings, client: HttpClient
+ @patch("posthog.models.github_integration_base.GitHubIntegrationBase.verify_user_installation_access")
+ @patch("posthog.models.integration.GitHubIntegration.github_user_from_code")
+ @patch("posthog.models.integration.GitHubIntegration.integration_from_installation_id")
+ @patch("posthog.models.user_integration.user_github_integration_from_installation")
+ def test_environment_integrations_flow_uses_team_id_from_authorize_cache(
+ self, mock_user_integration, mock_from_install, mock_from_code, mock_verify, client: HttpClient
):
- self._create_stripe_integration()
- new_integration = Integration(
- team=self.team,
- kind="stripe",
- integration_id="acct_999",
- config={},
- sensitive_config={},
+ client.force_login(self.user)
+
+ next_path = f"/project/{self.team.pk}/settings/environment-integrations"
+ state_token = "legacy-token"
+ store_unified_authorize_state(
+ GitHubAuthorizeState(
+ token=state_token,
+ flow=FlowKind.TEAM_INSTALL,
+ user_id=self.user.id,
+ team_id=self.team.pk,
+ next_url=next_path or None,
+ ),
)
- mock_oauth_response.return_value = new_integration
- mock_instance = MagicMock()
- MockStripeIntegration.return_value = mock_instance
- client.force_login(self.user)
- response = client.post(
- f"/api/environments/{self.team.pk}/integrations",
+ mock_from_code.return_value = self._github_user_authorization()
+ mock_verify.return_value = True
+ mock_from_install.return_value = self._team_github_integration()
+
+ response = client.get(
+ "/integrations/github/callback/",
{
- "kind": "stripe",
- "config": {"state": "next=/foo&token=abc123", "code": "oauth_code_999"},
+ "installation_id": "12345",
+ "code": "oauth-code-abc",
+ "setup_action": "install",
+ "state": urlencode({"next": next_path, "token": state_token}),
},
- content_type="application/json",
)
- assert response.status_code == status.HTTP_201_CREATED
- mock_oauth_response.assert_called_once()
+ assert response.status_code == status.HTTP_302_FOUND
+ assert "github_setup_error=invalid_state" not in response["Location"]
+ assert "integration_id=" in response["Location"]
- # The Stripe Apps OAuth flow (used by stripe_api_access_type: oauth) doesn't sign the
- # callback redirect — only the install-link OAuth mechanism emits install_signature.
- # The conflict guard is the defense-in-depth here, not signature verification.
- @pytest.mark.parametrize("include_install_signature", [True, False])
- @patch("posthog.api.integration.StripeIntegration")
- @patch("posthog.api.integration.OauthIntegration.integration_from_oauth_response")
- def test_marketplace_callback_without_state_succeeds(
- self,
- mock_oauth_response,
- MockStripeIntegration,
- include_install_signature,
- stripe_settings,
- client: HttpClient,
+ @patch("posthog.models.integration.GitHubIntegration.verify_user_installation_access", return_value=True)
+ @patch("posthog.models.integration.GitHubIntegration.client_request")
+ @patch("posthog.models.integration.GitHubIntegration.github_user_from_code")
+ def test_personal_github_setup_finishes_inline(
+ self, mock_user_from_code, mock_client_request, mock_verify, client: HttpClient
):
- created_integration = self._create_stripe_integration()
- mock_oauth_response.return_value = created_integration
- mock_instance = MagicMock()
- MockStripeIntegration.return_value = mock_instance
-
- config: dict = {
- "code": "oauth_code_123",
- "stripe_user_id": "acct_123",
- "account_id": "acct_123",
- "user_id": "usr_abc",
- }
- if include_install_signature:
- config["install_signature"] = self._make_install_signature(
- state="", user_id="usr_abc", account_id="acct_123"
- )
-
client.force_login(self.user)
- response = client.post(
- f"/api/environments/{self.team.pk}/integrations",
- {"kind": "stripe", "config": config},
- content_type="application/json",
+ state_token = "personal-install-token"
+ state = urlencode({"token": state_token, "source": "user_integration"})
+ store_unified_authorize_state(
+ GitHubAuthorizeState(token=state_token, flow=FlowKind.PERSONAL_INSTALL, user_id=self.user.id),
)
- assert response.status_code == status.HTTP_201_CREATED
- mock_instance.write_posthog_secrets.assert_called_once_with(self.team.pk, self.user)
+ mock_user_from_code.return_value = GitHubUserAuthorization(
+ gh_id=99,
+ gh_login="octocat",
+ access_token="gho_access",
+ refresh_token="ghr_refresh",
+ access_token_expires_in=28800,
+ refresh_token_expires_in=15897600,
+ )
+ mock_install_info = MagicMock()
+ mock_install_info.json.return_value = {
+ "account": {"type": "User", "login": "octocat"},
+ }
+ mock_access_token = MagicMock()
+ mock_access_token.json.return_value = {
+ "token": "ghs_install_token",
+ "expires_at": "2099-01-01T00:00:00Z",
+ "repository_selection": "selected",
+ }
+ mock_client_request.side_effect = [mock_install_info, mock_access_token]
- @patch("posthog.api.integration.StripeIntegration")
- @patch("posthog.api.integration.OauthIntegration.integration_from_oauth_response")
- def test_marketplace_callback_rejects_forged_install_signature_when_present(
- self, mock_oauth_response, MockStripeIntegration, stripe_settings, client: HttpClient
- ):
- forged = self._make_install_signature(state="", user_id="usr_abc", account_id="acct_123", secret="wrong_secret")
- client.force_login(self.user)
- response = client.post(
- f"/api/environments/{self.team.pk}/integrations",
+ response = client.get(
+ "/integrations/github/callback/",
{
- "kind": "stripe",
- "config": {
- "code": "oauth_code_123",
- "stripe_user_id": "acct_123",
- "account_id": "acct_123",
- "user_id": "usr_abc",
- "install_signature": forged,
- },
+ "installation_id": "12345",
+ "code": "oauth-code-abc",
+ "setup_action": "install",
+ "state": state,
},
- content_type="application/json",
)
- assert response.status_code == status.HTTP_400_BAD_REQUEST
- assert "stripe_install_signature_invalid" in response.content.decode()
- mock_oauth_response.assert_not_called()
- MockStripeIntegration.assert_not_called()
+ assert response.status_code == status.HTTP_302_FOUND
+ assert "github_link_success=1" in response["Location"]
+ assert "/complete/github-link" not in response["Location"]
+ mock_user_from_code.assert_called_once_with("oauth-code-abc")
- @patch("posthog.api.integration.StripeIntegration")
- @patch("posthog.api.integration.OauthIntegration.integration_from_oauth_response")
- def test_marketplace_callback_rejects_when_different_stripe_account_connected(
- self, mock_oauth_response, MockStripeIntegration, stripe_settings, client: HttpClient
+ @patch("posthog.models.integration.GitHubIntegration.verify_user_installation_access", return_value=True)
+ @patch("posthog.models.integration.GitHubIntegration.client_request")
+ @patch("posthog.models.integration.GitHubIntegration.github_user_from_code")
+ def test_personal_github_setup_with_forged_team_next_still_finishes_personal(
+ self, mock_user_from_code, mock_client_request, mock_verify, client: HttpClient
):
- self._create_stripe_integration()
-
- sig = self._make_install_signature(state="", user_id="usr_xyz", account_id="acct_999")
+ # A personal install whose callback `state` has been tampered — `source=user_integration`
+ # stripped and a team `next` injected — must route by the server-side cached flow to the
+ # personal finisher, never fall through to team setup. self.user is an org admin, so without
+ # flow-based routing the forged `next` would otherwise reach team setup and pass its admin gate.
client.force_login(self.user)
- response = client.post(
- f"/api/environments/{self.team.pk}/integrations",
+ state_token = "personal-install-token"
+ forged_state = urlencode(
+ {"token": state_token, "next": f"/project/{self.team.pk}/settings/project-integrations"}
+ )
+ store_unified_authorize_state(
+ GitHubAuthorizeState(token=state_token, flow=FlowKind.PERSONAL_INSTALL, user_id=self.user.id),
+ )
+
+ mock_user_from_code.return_value = GitHubUserAuthorization(
+ gh_id=99,
+ gh_login="octocat",
+ access_token="gho_access",
+ refresh_token="ghr_refresh",
+ access_token_expires_in=28800,
+ refresh_token_expires_in=15897600,
+ )
+ mock_install_info = MagicMock()
+ mock_install_info.json.return_value = {"account": {"type": "User", "login": "octocat"}}
+ mock_access_token = MagicMock()
+ mock_access_token.json.return_value = {
+ "token": "ghs_install_token",
+ "expires_at": "2099-01-01T00:00:00Z",
+ "repository_selection": "selected",
+ }
+ mock_client_request.side_effect = [mock_install_info, mock_access_token]
+
+ response = client.get(
+ "/integrations/github/callback/",
{
- "kind": "stripe",
- "config": {
- "code": "oauth_code_999",
- "stripe_user_id": "acct_999",
- "account_id": "acct_999",
- "user_id": "usr_xyz",
- "install_signature": sig,
- },
+ "installation_id": "12345",
+ "code": "oauth-code-abc",
+ "setup_action": "install",
+ "state": forged_state,
},
- content_type="application/json",
)
- assert response.status_code == status.HTTP_400_BAD_REQUEST
- assert "stripe_integration_conflict" in response.content.decode()
- mock_oauth_response.assert_not_called()
- MockStripeIntegration.assert_not_called()
+ assert response.status_code == status.HTTP_302_FOUND
+ assert "github_link_success=1" in response["Location"]
+ # Personal install exchanges the code without the OAuth redirect_uri — proving the personal path ran.
+ mock_user_from_code.assert_called_once_with("oauth-code-abc")
+ # The forged team `next` created no team integration; only the user's personal one exists.
+ assert not Integration.objects.filter(team=self.team, kind="github").exists()
+ assert UserIntegration.objects.filter(user=self.user, kind="github", integration_id="12345").exists()
- @patch("posthog.api.integration.StripeIntegration")
- @patch("posthog.api.integration.OauthIntegration.integration_from_oauth_response")
- def test_marketplace_callback_allows_reinstall_of_same_stripe_account(
- self, mock_oauth_response, MockStripeIntegration, stripe_settings, client: HttpClient
+ @patch("posthog.models.integration.GitHubIntegration.client_request")
+ def test_personal_github_setup_update_redirects_to_personal_settings(self, mock_client_request, client: HttpClient):
+ client.force_login(self.user)
+ UserIntegration.objects.create(
+ user=self.user,
+ kind="github",
+ integration_id="12345",
+ config={"installation_id": "12345", "repository_selection": "selected"},
+ sensitive_config={"access_token": "ghs_old", "user_access_token": "gho_user"},
+ )
+ mock_install_info = MagicMock()
+ mock_install_info.json.return_value = {
+ "account": {"type": "User", "login": "octocat"},
+ }
+ mock_access_token = MagicMock()
+ mock_access_token.json.return_value = {
+ "token": "ghs_install_token",
+ "expires_at": "2099-01-01T00:00:00Z",
+ "repository_selection": "all",
+ }
+ mock_client_request.side_effect = [mock_install_info, mock_access_token]
+
+ response = client.get(
+ "/integrations/github/callback/",
+ {"installation_id": "12345", "setup_action": "update"},
+ )
+
+ assert response.status_code == status.HTTP_302_FOUND
+ assert "github_link_success=1" in response["Location"]
+ assert "user-personal-integrations" in response["Location"]
+ assert "github_setup_error" not in response["Location"]
+ assert "project-integrations" not in response["Location"]
+
+ integration = UserIntegration.objects.get(user=self.user, integration_id="12345")
+ assert integration.config["repository_selection"] == "all"
+ assert integration.sensitive_config["access_token"] == "ghs_install_token"
+ assert integration.sensitive_config["user_access_token"] == "gho_user"
+
+ @patch("posthog.models.integration.GitHubIntegration.integration_from_installation_id")
+ def test_team_github_setup_update_without_state_redirects_to_project_integrations(
+ self, mock_refresh, client: HttpClient
):
- existing = self._create_stripe_integration()
- mock_oauth_response.return_value = existing
- mock_instance = MagicMock()
- MockStripeIntegration.return_value = mock_instance
+ client.force_login(self.user)
+ mock_refresh.return_value = self._team_github_integration()
- sig = self._make_install_signature(state="", user_id="usr_abc", account_id="acct_123")
+ response = client.get(
+ "/integrations/github/callback/",
+ {"installation_id": "12345", "setup_action": "update"},
+ )
+
+ assert response.status_code == status.HTTP_302_FOUND
+ assert f"project/{self.team.pk}/settings/project-integrations" in response["Location"]
+ assert "integration_id=" in response["Location"]
+ assert "github_setup_error" not in response["Location"]
+ mock_refresh.assert_called_once_with("12345", self.team.pk, self.user)
+
+ @patch("posthog.models.integration.GitHubIntegration.integration_from_installation_id")
+ def test_update_setup_action_via_callback_redirects_successfully(self, mock_refresh, client: HttpClient):
client.force_login(self.user)
- response = client.post(
- f"/api/environments/{self.team.pk}/integrations",
+ mock_refresh.return_value = self._team_github_integration(installation_id="98797544")
+ next_path = f"/project/{self.team.pk}/settings/environment-integrations"
+ state_token = "ad89fbef5ced409fa055f4918b4a06b664f938506ed7aa8007cdc6cfd819be1055"
+ store_unified_authorize_state(
+ GitHubAuthorizeState(
+ token=state_token,
+ flow=FlowKind.TEAM_INSTALL,
+ user_id=self.user.id,
+ team_id=self.team.pk,
+ next_url=next_path or None,
+ ),
+ )
+
+ response = client.get(
+ "/integrations/github/callback/",
{
- "kind": "stripe",
- "config": {
- "code": "oauth_code_123",
- "stripe_user_id": "acct_123",
- "account_id": "acct_123",
- "user_id": "usr_abc",
- "install_signature": sig,
- },
+ "installation_id": "98797544",
+ "code": "5e9f6928598ebb891367",
+ "setup_action": "update",
+ "state": urlencode({"next": next_path, "token": state_token}),
},
- content_type="application/json",
)
- assert response.status_code == status.HTTP_201_CREATED
- mock_oauth_response.assert_called_once()
+ assert response.status_code == status.HTTP_302_FOUND
+ assert "github_setup_error" not in response["Location"]
+ assert "integration_id=" in response["Location"]
+ mock_refresh.assert_called_once()
- @patch("posthog.api.integration.OauthIntegration.integration_from_oauth_response")
- def test_stripe_oauth_exchange_failure_returns_error(
- self, mock_oauth_response, stripe_settings, client: HttpClient
+ @patch("posthog.models.integration.GitHubIntegration.integration_from_installation_id")
+ def test_prepare_callback_update_without_state_redirects_to_account_connected(
+ self, mock_refresh, client: HttpClient
):
- mock_oauth_response.side_effect = Exception("Stripe returned invalid_grant")
-
- sig = self._make_install_signature(state="", user_id="usr_abc", account_id="acct_123")
client.force_login(self.user)
- response = client.post(
- f"/api/environments/{self.team.pk}/integrations",
- {
- "kind": "stripe",
- "config": {
- "code": "ac_invalid",
- "stripe_user_id": "acct_123",
- "account_id": "acct_123",
- "user_id": "usr_abc",
- "install_signature": sig,
- },
- },
- content_type="application/json",
+ mock_refresh.return_value = self._team_github_integration()
+ next_path = (
+ f"/account-connected/github-integration?provider=github&project_id={self.team.pk}&connect_from=posthog_code"
+ )
+ store_unified_authorize_state(
+ GitHubAuthorizeState(
+ token="prepare-token",
+ flow=FlowKind.TEAM_UPDATE,
+ user_id=self.user.id,
+ team_id=self.team.pk,
+ next_url=next_path or None,
+ ),
)
- assert response.status_code == status.HTTP_500_INTERNAL_SERVER_ERROR
- assert not Integration.objects.filter(team_id=self.team.pk, kind="stripe").exists()
+ response = client.get(
+ "/integrations/github/callback/",
+ {"installation_id": "12345", "setup_action": "update"},
+ )
+ assert response.status_code == status.HTTP_302_FOUND
+ assert "account-connected/github-integration" in response["Location"]
+ assert "integration_id=" in response["Location"]
+ mock_refresh.assert_called_once()
-class TestStripeIntegrationOAuthTokens:
- @pytest.fixture(autouse=True)
- def setup(self, db):
- self.organization = Organization.objects.create(name="Test Org")
- self.team = Team.objects.create(organization=self.organization, name="Test Team")
- self.user = User.objects.create_and_join(self.organization, "[email protected]", "test")
- self.oauth_app = OAuthApplication.objects.create(
- name="PostHog for Stripe",
- client_id="stripe_oauth_client_id",
- client_type=OAuthApplication.CLIENT_CONFIDENTIAL,
- authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,
- redirect_uris="https://example.com/callback",
- algorithm="RS256",
+ @pytest.mark.parametrize("callback_installation_id,expect_error", [("12345", False), ("99999", True)])
+ @patch("posthog.models.integration.GitHubIntegration.integration_from_installation_id")
+ def test_team_update_callback_binds_seeded_installation_id(
+ self, mock_refresh, callback_installation_id, expect_error, client: HttpClient
+ ):
+ client.force_login(self.user)
+ mock_refresh.return_value = self._team_github_integration(installation_id="12345")
+ store_unified_authorize_state(
+ GitHubAuthorizeState(
+ token="prepare-token",
+ flow=FlowKind.TEAM_UPDATE,
+ user_id=self.user.id,
+ team_id=self.team.pk,
+ installation_id="12345",
+ ),
)
- def _create_integration_with_tokens(self) -> tuple[Integration, OAuthAccessToken, OAuthRefreshToken]:
- integration = Integration.objects.create(
- team=self.team,
- kind="stripe",
- config={"account_name": "Test (acct_123)"},
- sensitive_config={"access_token": "sk_live_test"},
- integration_id="acct_123",
- created_by=self.user,
+ response = client.get(
+ "/integrations/github/callback/",
+ {"installation_id": callback_installation_id, "setup_action": "update"},
)
- access_token = OAuthAccessToken.objects.create(
- application=self.oauth_app,
- token="ph_access_token_test",
- user=self.user,
- expires=timezone.now() + timedelta(days=365),
- scope=StripeIntegration.SCOPES,
- scoped_teams=[self.team.pk],
+
+ assert response.status_code == status.HTTP_302_FOUND
+ if expect_error:
+ assert "github_setup_error=invalid_state" in response["Location"]
+ assert not Integration.objects.filter(team=self.team, integration_id=callback_installation_id).exists()
+ else:
+ assert "github_setup_error" not in response["Location"]
+ assert "integration_id=" in response["Location"]
+
+ def test_install_callback_without_state_redirects_invalid_state(self, client: HttpClient):
+ client.force_login(self.user)
+ next_path = f"/project/{self.team.pk}/settings/project-integrations"
+ store_unified_authorize_state(
+ GitHubAuthorizeState(
+ token="valid-token",
+ flow=FlowKind.TEAM_INSTALL,
+ user_id=self.user.id,
+ team_id=self.team.pk,
+ next_url=next_path or None,
+ ),
)
- refresh_token = OAuthRefreshToken.objects.create(
- application=self.oauth_app,
- token="ph_refresh_token_test",
- user=self.user,
- access_token=access_token,
- scoped_teams=[self.team.pk],
+
+ response = client.get(
+ "/integrations/github/callback/",
+ {"installation_id": "12345", "code": "oauth-code-abc", "setup_action": "install"},
)
- return integration, access_token, refresh_token
- @patch("posthog.models.integration.settings")
- def test_destroy_oauth_tokens_deletes_tokens(self, mock_settings):
- mock_settings.STRIPE_POSTHOG_OAUTH_CLIENT_ID = self.oauth_app.client_id
- integration, access_token, refresh_token = self._create_integration_with_tokens()
- stripe_int = StripeIntegration(integration)
+ assert response.status_code == status.HTTP_302_FOUND
+ assert "github_setup_error=invalid_state" in response["Location"]
- stripe_int._destroy_posthog_oauth_tokens()
+ @patch("posthog.api.github_callback.team_services.build_team_github_oauth_authorize_url")
+ def test_orphan_installation_update_redirects_to_oauth(self, mock_build_oauth_url, client: HttpClient):
+ mock_build_oauth_url.return_value = "https://github.com/login/oauth/authorize?client_id=test"
+ client.force_login(self.user)
+ next_path = f"/project/{self.team.pk}/settings/project-integrations"
+ state_token = "orphan-token"
+ store_unified_authorize_state(
+ GitHubAuthorizeState(
+ token=state_token,
+ flow=FlowKind.TEAM_INSTALL,
+ user_id=self.user.id,
+ team_id=self.team.pk,
+ next_url=next_path or None,
+ ),
+ )
- assert not OAuthAccessToken.objects.filter(pk=access_token.pk).exists()
- assert not OAuthRefreshToken.objects.filter(pk=refresh_token.pk).exists()
+ response = client.get(
+ "/integrations/github/callback/",
+ {
+ "installation_id": "99999",
+ "setup_action": "update",
+ "state": urlencode({"next": next_path, "token": state_token}),
+ },
+ )
- @patch("posthog.models.integration.settings")
- def test_destroy_oauth_tokens_only_affects_same_team(self, mock_settings):
- mock_settings.STRIPE_POSTHOG_OAUTH_CLIENT_ID = self.oauth_app.client_id
- integration, _, _ = self._create_integration_with_tokens()
+ assert response.status_code == status.HTTP_302_FOUND
+ assert response["Location"].startswith("https://github.com/login/oauth/authorize")
+ mock_build_oauth_url.assert_called_once()
- other_team = Team.objects.create(organization=self.organization, name="Other Team")
- other_access_token = OAuthAccessToken.objects.create(
- application=self.oauth_app,
- token="ph_access_other",
- user=self.user,
- expires=timezone.now() + timedelta(days=365),
- scope=StripeIntegration.SCOPES,
- scoped_teams=[other_team.pk],
+ def test_cross_user_state_rejected_on_unified_callback(self, client: HttpClient):
+ # State tokens are bound to a user via the pending-pointer cache key.
+ # Another admin in the same team must not be able to finish a callback
+ # by submitting the victim's state token.
+ attacker = User.objects.create_and_join(
+ self.organization, "[email protected]", "test", level=OrganizationMembership.Level.ADMIN
)
- other_refresh_token = OAuthRefreshToken.objects.create(
- application=self.oauth_app,
- token="ph_refresh_other",
- user=self.user,
- access_token=other_access_token,
- scoped_teams=[other_team.pk],
+ next_path = f"/project/{self.team.pk}/settings/project-integrations"
+ state_token = "victim-token"
+ store_unified_authorize_state(
+ GitHubAuthorizeState(
+ token=state_token,
+ flow=FlowKind.TEAM_INSTALL,
+ user_id=self.user.id,
+ team_id=self.team.pk,
+ next_url=next_path or None,
+ ),
)
- stripe_int = StripeIntegration(integration)
- stripe_int._destroy_posthog_oauth_tokens()
-
- assert OAuthAccessToken.objects.filter(pk=other_access_token.pk).exists()
- assert OAuthRefreshToken.objects.filter(pk=other_refresh_token.pk).exists()
+ client.force_login(attacker)
+ response = client.get(
+ "/integrations/github/callback/",
+ {
+ "installation_id": "12345",
+ "code": "oauth-code-abc",
+ "setup_action": "install",
+ "state": urlencode({"next": next_path, "token": state_token}),
+ },
+ )
- @patch("posthog.models.integration.settings")
- def test_destroy_oauth_tokens_noop_when_no_oauth_app(self, mock_settings):
- mock_settings.STRIPE_POSTHOG_OAUTH_CLIENT_ID = None
- integration, access_token, refresh_token = self._create_integration_with_tokens()
- stripe_int = StripeIntegration(integration)
+ assert response.status_code == status.HTTP_302_FOUND
+ assert "github_setup_error=invalid_state" in response["Location"]
- stripe_int._destroy_posthog_oauth_tokens()
+ @pytest.mark.parametrize("stored_installation_id", [12345, "12345"])
+ @patch("posthog.models.integration.GitHubIntegration.integration_from_installation_id")
+ def test_team_update_heuristic_finds_existing_integration_regardless_of_jsonb_id_type(
+ self, mock_refresh, stored_installation_id, client: HttpClient
+ ):
+ # ``config.installation_id`` has historically been written as either a
+ # JSONB number or string; the update-without-state heuristic must match
+ # either (it previously raised ``MultipleObjectsReturned`` when mixed).
+ client.force_login(self.user)
+ existing = Integration.objects.create(
+ team=self.team,
+ kind="github",
+ integration_id="12345",
+ config={"installation_id": stored_installation_id},
+ sensitive_config={"access_token": "ghs_test"},
+ )
+ mock_refresh.return_value = existing
- assert OAuthAccessToken.objects.filter(pk=access_token.pk).exists()
- assert OAuthRefreshToken.objects.filter(pk=refresh_token.pk).exists()
+ response = client.get(
+ "/integrations/github/callback/",
+ {"installation_id": "12345", "setup_action": "update"},
+ )
- @patch("stripe.StripeClient")
- @patch("posthog.models.integration.settings")
- def test_write_posthog_secrets_uses_account_scope(self, mock_settings, MockStripeClient):
- mock_settings.STRIPE_POSTHOG_OAUTH_CLIENT_ID = self.oauth_app.client_id
- mock_settings.STRIPE_APP_SECRET_KEY = "sk_test"
- mock_client = MagicMock()
- MockStripeClient.return_value = mock_client
+ assert response.status_code == status.HTTP_302_FOUND
+ assert "github_setup_error" not in response["Location"]
+ assert f"integration_id={existing.id}" in response["Location"]
- integration = Integration.objects.create(
- team=self.team,
- kind="stripe",
- config={},
- sensitive_config={},
- integration_id="acct_456",
- created_by=self.user,
+ @patch("posthog.models.integration.GitHubIntegration.integration_from_installation_id")
+ def test_team_prepare_callback_update_wins_when_personal_integration_also_exists(
+ self, mock_refresh, client: HttpClient
+ ):
+ client.force_login(self.user)
+ team_integration = self._team_github_integration()
+ UserIntegration.objects.create(
+ user=self.user,
+ kind="github",
+ integration_id="12345",
+ config={"installation_id": "12345"},
+ sensitive_config={"access_token": "ghs_old", "user_access_token": "gho_user"},
+ )
+ next_path = f"/project/{self.team.pk}/settings/environment-integrations"
+ store_unified_authorize_state(
+ GitHubAuthorizeState(
+ token="team-update-token",
+ flow=FlowKind.TEAM_UPDATE,
+ user_id=self.user.id,
+ team_id=self.team.pk,
+ next_url=next_path,
+ ),
)
- stripe_int = StripeIntegration(integration)
- stripe_int.write_posthog_secrets(self.team.pk, self.user)
+ mock_refresh.return_value = team_integration
- calls = mock_client.apps.secrets.create.call_args_list
- assert len(calls) == 5
- for call in calls:
- assert call.kwargs["params"]["scope"] == {"type": "account"}
- assert call.kwargs["options"] == {"stripe_account": "acct_456"}
+ response = client.get(
+ "/integrations/github/callback/",
+ {"installation_id": "12345", "setup_action": "update"},
+ )
- secret_payloads = {call.kwargs["params"]["name"]: call.kwargs["params"]["payload"] for call in calls}
- assert secret_payloads["posthog_project_id"] == str(self.team.pk)
- assert secret_payloads["posthog_oauth_client_id"] == self.oauth_app.client_id
+ assert response.status_code == status.HTTP_302_FOUND
+ assert "environment-integrations" in response["Location"]
+ assert "user-personal-integrations" not in response["Location"]
+ assert "github_link_success" not in response["Location"]
+ assert f"integration_id={team_integration.id}" in response["Location"]
+ mock_refresh.assert_called_once()
- @patch("stripe.StripeClient")
- @patch("posthog.models.integration.settings")
- def test_clear_posthog_secrets_uses_account_scope(self, mock_settings, MockStripeClient):
- mock_settings.STRIPE_APP_SECRET_KEY = "sk_test"
- mock_settings.STRIPE_POSTHOG_OAUTH_CLIENT_ID = None
- mock_client = MagicMock()
- MockStripeClient.return_value = mock_client
- integration = Integration.objects.create(
+class TestStripeIntegration:
+ @pytest.fixture(autouse=True)
+ def setup_integration(self, db):
+ self.organization = Organization.objects.create(name="Test Org")
+ self.team = Team.objects.create(organization=self.organization, name="Test Team")
+ self.user = User.objects.create_and_join(
+ self.organization, "[email protected]", "test", level=OrganizationMembership.Level.ADMIN
+ )
+
+ def _create_stripe_integration(self) -> Integration:
+ return Integration.objects.create(
team=self.team,
kind="stripe",
- config={},
- sensitive_config={},
- integration_id="acct_789",
+ config={"account_name": "Test Business (acct_123)"},
+ sensitive_config={"access_token": "sk_live_test123"},
+ integration_id="acct_123",
created_by=self.user,
)
- stripe_int = StripeIntegration(integration)
- stripe_int.clear_posthog_secrets()
- calls = mock_client.apps.secrets.delete_where.call_args_list
- assert len(calls) == 5
- for call in calls:
- assert call.kwargs["params"]["scope"] == {"type": "account"}
- assert call.kwargs["options"] == {"stripe_account": "acct_789"}
+ @patch("posthog.api.integration.StripeIntegration")
+ def test_destroy_calls_clear_posthog_secrets(self, MockStripeIntegration, client: HttpClient):
+ integration = self._create_stripe_integration()
+ mock_instance = MagicMock()
+ MockStripeIntegration.return_value = mock_instance
- @parameterized.expand(
- [
- ("write", "write_posthog_secrets"),
- ("clear", "clear_posthog_secrets"),
- ]
- )
- @patch("stripe.StripeClient")
- @patch("posthog.models.integration.settings")
- def test_stripe_client_uses_live_secret(self, _name, method_name, mock_settings, MockStripeClient):
- mock_settings.STRIPE_POSTHOG_OAUTH_CLIENT_ID = self.oauth_app.client_id
- mock_settings.STRIPE_APP_SECRET_KEY = "sk_live"
- MockStripeClient.return_value = MagicMock()
+ client.force_login(self.user)
+ response = client.delete(f"/api/environments/{self.team.pk}/integrations/{integration.id}/")
- integration = Integration.objects.create(
- team=self.team,
- kind="stripe",
- config={},
- sensitive_config={},
- integration_id=f"acct_{_name}",
- created_by=self.user,
- )
- stripe_int = StripeIntegration(integration)
- if method_name == "write_posthog_secrets":
- stripe_int.write_posthog_secrets(self.team.pk, self.user)
- else:
- stripe_int.clear_posthog_secrets()
+ assert response.status_code == status.HTTP_204_NO_CONTENT
+ MockStripeIntegration.assert_called_once()
+ mock_instance.clear_posthog_secrets.assert_called_once()
+ assert not Integration.objects.filter(id=integration.id).exists()
- MockStripeClient.assert_called_once_with("sk_live")
+ @patch("posthog.api.integration.StripeIntegration")
+ def test_destroy_still_deletes_when_clear_secrets_fails(self, MockStripeIntegration, client: HttpClient):
+ integration = self._create_stripe_integration()
+ mock_instance = MagicMock()
+ mock_instance.clear_posthog_secrets.side_effect = Exception("Stripe API error")
+ MockStripeIntegration.return_value = mock_instance
- @patch("posthog.models.integration.capture_exception")
- @patch("stripe.StripeClient")
- @patch("posthog.models.integration.settings")
- def test_write_posthog_secrets_skips_when_keys_missing(self, mock_settings, MockStripeClient, mock_capture):
- mock_settings.STRIPE_POSTHOG_OAUTH_CLIENT_ID = self.oauth_app.client_id
- mock_settings.STRIPE_APP_CLIENT_ID = None
- mock_settings.STRIPE_APP_SECRET_KEY = None
- MockStripeClient.return_value = MagicMock()
+ client.force_login(self.user)
+ response = client.delete(f"/api/environments/{self.team.pk}/integrations/{integration.id}/")
+
+ assert response.status_code == status.HTTP_204_NO_CONTENT
+ assert not Integration.objects.filter(id=integration.id).exists()
+ def test_destroy_non_stripe_does_not_call_clear_secrets(self, client: HttpClient):
integration = Integration.objects.create(
team=self.team,
- kind="stripe",
- config={},
- sensitive_config={},
- integration_id="acct_missing_write",
+ kind="slack",
+ config={"authed_user": {"id": "U123"}},
+ sensitive_config={"access_token": "xoxb-test"},
created_by=self.user,
)
- stripe_int = StripeIntegration(integration)
- stripe_int.write_posthog_secrets(self.team.pk, self.user)
- MockStripeClient.assert_not_called()
- mock_capture.assert_called_once()
- captured_exc = mock_capture.call_args.args[0]
- assert isinstance(captured_exc, NotImplementedError)
+ client.force_login(self.user)
+ with patch("posthog.api.integration.StripeIntegration") as MockStripeIntegration:
+ response = client.delete(f"/api/environments/{self.team.pk}/integrations/{integration.id}/")
- @patch("posthog.models.integration.capture_exception")
- @patch("stripe.StripeClient")
- @patch("posthog.models.integration.settings")
- def test_clear_posthog_secrets_skips_and_revokes_tokens_when_keys_missing(
- self, mock_settings, MockStripeClient, mock_capture
- ):
- mock_settings.STRIPE_POSTHOG_OAUTH_CLIENT_ID = self.oauth_app.client_id
- mock_settings.STRIPE_APP_CLIENT_ID = None
- mock_settings.STRIPE_APP_SECRET_KEY = None
- MockStripeClient.return_value = MagicMock()
+ assert response.status_code == status.HTTP_204_NO_CONTENT
+ MockStripeIntegration.assert_not_called()
+ assert not Integration.objects.filter(id=integration.id).exists()
- integration, access_token, refresh_token = self._create_integration_with_tokens()
+ @pytest.fixture()
+ def stripe_settings(self, settings):
+ settings.STRIPE_APP_CLIENT_ID = "ca_test123"
+ settings.STRIPE_APP_SECRET_KEY = "sk_test_secret"
+ settings.STRIPE_SIGNING_SECRET = "whsec_test_signing"
+ return settings
- stripe_int = StripeIntegration(integration)
- stripe_int.clear_posthog_secrets()
+ def _make_install_signature(
+ self, state: str, user_id: str, account_id: str, secret: str = "whsec_test_signing"
+ ) -> str:
+ """Build a valid t=...,v1=... header for a marketplace install callback."""
+ ts = int(time.time())
+ payload = json.dumps(
+ {"state": state, "user_id": user_id, "account_id": account_id},
+ separators=(",", ":"),
+ )
+ signed = f"{ts}.{payload}".encode()
+ digest = hmac.new(secret.encode("utf-8"), signed, hashlib.sha256).hexdigest()
+ return f"t={ts},v1={digest}"
- MockStripeClient.assert_not_called()
- mock_capture.assert_called_once()
- assert not OAuthAccessToken.objects.filter(pk=access_token.pk).exists()
- assert not OAuthRefreshToken.objects.filter(pk=refresh_token.pk).exists()
+ @patch("posthog.api.integration.StripeIntegration")
+ @patch("posthog.api.integration.OauthIntegration.integration_from_oauth_response")
+ def test_create_calls_write_posthog_secrets(
+ self, mock_oauth_response, MockStripeIntegration, stripe_settings, client: HttpClient
+ ):
+ created_integration = self._create_stripe_integration()
+ mock_oauth_response.return_value = created_integration
+ mock_instance = MagicMock()
+ MockStripeIntegration.return_value = mock_instance
+ client.force_login(self.user)
+ response = client.post(
+ f"/api/environments/{self.team.pk}/integrations",
+ {"kind": "stripe", "config": {"code": "oauth_code_123"}},
+ content_type="application/json",
+ )
-def _make_github_branches_response(names: list[str], has_next: bool = False) -> MagicMock:
- """Build a mock requests.Response for the GitHub branches API."""
- response = MagicMock()
- response.status_code = 200
- response.json.return_value = [{"name": n} for n in names]
- link = '<https://api.github.com/next>; rel="next"' if has_next else ""
- response.headers = {"Link": link}
- return response
+ assert response.status_code == status.HTTP_201_CREATED
+ MockStripeIntegration.assert_called_once_with(created_integration)
+ mock_instance.write_posthog_secrets.assert_called_once_with(self.team.pk, self.user)
+ @patch("posthog.api.integration.StripeIntegration")
+ @patch("posthog.api.integration.OauthIntegration.integration_from_oauth_response")
+ def test_create_succeeds_when_write_secrets_fails(
+ self, mock_oauth_response, MockStripeIntegration, stripe_settings, client: HttpClient
+ ):
+ created_integration = self._create_stripe_integration()
+ mock_oauth_response.return_value = created_integration
+ mock_instance = MagicMock()
+ mock_instance.write_posthog_secrets.side_effect = Exception("Stripe API error")
+ MockStripeIntegration.return_value = mock_instance
-class TestGitHubBranches:
- @pytest.fixture(autouse=True)
- def setup_integration(self, db):
- self.organization = Organization.objects.create(name="Test Org")
- self.team = Team.objects.create(organization=self.organization, name="Test Team")
- self.user = User.objects.create_and_join(
- self.organization, "[email protected]", "test", level=OrganizationMembership.Level.ADMIN
- )
- self.integration = Integration.objects.create(
- team=self.team,
- kind="github",
- config={"installation_id": "12345", "refreshed_at": 0, "expires_in": 999999},
- sensitive_config={"access_token": "test-token"},
+ client.force_login(self.user)
+ response = client.post(
+ f"/api/environments/{self.team.pk}/integrations",
+ {"kind": "stripe", "config": {"code": "oauth_code_123"}},
+ content_type="application/json",
)
- self.github = GitHubIntegration(self.integration)
- @patch("posthog.models.integration.requests.get")
- def test_list_branches_returns_first_page(self, mock_get):
- names = [f"branch-{i}" for i in range(100)]
- mock_get.return_value = _make_github_branches_response(names, has_next=True)
+ assert response.status_code == status.HTTP_201_CREATED
- branches, has_more = self.github.list_branches("org/repo", limit=100, offset=0)
+ @patch("posthog.api.integration.StripeIntegration")
+ @patch("posthog.api.integration.OauthIntegration.integration_from_oauth_response")
+ def test_posthog_initiated_oauth_with_state_still_works(
+ self, mock_oauth_response, MockStripeIntegration, stripe_settings, client: HttpClient
+ ):
+ created_integration = self._create_stripe_integration()
+ mock_oauth_response.return_value = created_integration
+ mock_instance = MagicMock()
+ MockStripeIntegration.return_value = mock_instance
- assert branches == names
- assert has_more is True
- mock_get.assert_called_once()
- assert "page=1" in mock_get.call_args[0][0]
+ client.force_login(self.user)
+ response = client.post(
+ f"/api/environments/{self.team.pk}/integrations",
+ {"kind": "stripe", "config": {"state": "next=/foo&token=abc123", "code": "oauth_code_123"}},
+ content_type="application/json",
+ )
- @patch("posthog.models.integration.requests.get")
- def test_list_branches_offset_skips_pages(self, mock_get):
- """Requesting offset=200 should start fetching from GitHub page 3."""
- page3_names = [f"branch-{i}" for i in range(200, 300)]
- mock_get.return_value = _make_github_branches_response(page3_names, has_next=True)
+ assert response.status_code == status.HTTP_201_CREATED
+ mock_instance.write_posthog_secrets.assert_called_once_with(self.team.pk, self.user)
- branches, has_more = self.github.list_branches("org/repo", limit=100, offset=200)
-
- assert branches == page3_names
- assert has_more is True
- assert mock_get.call_count == 1
- assert "page=3" in mock_get.call_args[0][0]
-
- @patch("posthog.models.integration.requests.get")
- def test_list_branches_last_page_no_more(self, mock_get):
- names = [f"branch-{i}" for i in range(50)]
- mock_get.return_value = _make_github_branches_response(names, has_next=False)
-
- branches, has_more = self.github.list_branches("org/repo", limit=100, offset=0)
-
- assert branches == names
- assert has_more is False
-
- @patch("posthog.models.integration.requests.get")
- def test_list_branches_spans_two_github_pages(self, mock_get):
- """An offset that doesn't align with per_page=100 requires fetching two GitHub pages."""
- page1_names = [f"branch-{i}" for i in range(100)]
- page2_names = [f"branch-{i}" for i in range(100, 200)]
-
- mock_get.side_effect = [
- _make_github_branches_response(page1_names, has_next=True),
- _make_github_branches_response(page2_names, has_next=False),
- ]
-
- branches, has_more = self.github.list_branches("org/repo", limit=100, offset=50)
-
- assert len(branches) == 100
- assert branches == [f"branch-{i}" for i in range(50, 150)]
- # There are still branches 150-199 beyond this window
- assert has_more is True
- assert mock_get.call_count == 2
-
- @patch("posthog.models.integration.requests.get")
- def test_list_branches_empty_repo(self, mock_get):
- mock_get.return_value = _make_github_branches_response([], has_next=False)
-
- branches, has_more = self.github.list_branches("org/repo")
-
- assert branches == []
- assert has_more is False
-
- @patch("posthog.models.integration.requests.get")
- def test_list_branches_401_triggers_refresh_and_retry(self, mock_get):
- unauthorized = MagicMock()
- unauthorized.status_code = 401
-
- names = ["main", "develop"]
- success = _make_github_branches_response(names, has_next=False)
-
- mock_get.side_effect = [unauthorized, success]
-
- with patch.object(self.github, "refresh_access_token"):
- branches, has_more = self.github.list_branches("org/repo")
-
- assert branches == names
- assert mock_get.call_count == 2
-
- @patch("posthog.models.integration.GitHubIntegration.list_cached_branches")
- def test_api_endpoint_passes_search_limit_offset(self, mock_list_cached, client: HttpClient):
- mock_list_cached.return_value = ([f"branch-{i}" for i in range(10)], "main", True)
- client.force_login(self.user)
-
- response = client.get(
- f"/api/environments/{self.team.pk}/integrations/{self.integration.pk}/github_branches/",
- {"repo": "org/repo", "search": "feature", "limit": "10", "offset": "50"},
+ @patch("posthog.api.integration.StripeIntegration")
+ @patch("posthog.api.integration.OauthIntegration.integration_from_oauth_response")
+ def test_posthog_initiated_oauth_ignores_marketplace_conflict_guard(
+ self, mock_oauth_response, MockStripeIntegration, stripe_settings, client: HttpClient
+ ):
+ self._create_stripe_integration()
+ new_integration = Integration(
+ team=self.team,
+ kind="stripe",
+ integration_id="acct_999",
+ config={},
+ sensitive_config={},
)
+ mock_oauth_response.return_value = new_integration
+ mock_instance = MagicMock()
+ MockStripeIntegration.return_value = mock_instance
- assert response.status_code == 200
- data = response.json()
- assert len(data["branches"]) == 10
- assert data["has_more"] is True
- assert data["default_branch"] == "main"
- mock_list_cached.assert_called_once_with(
- "org/repo",
- search="feature",
- limit=10,
- offset=50,
+ client.force_login(self.user)
+ response = client.post(
+ f"/api/environments/{self.team.pk}/integrations",
+ {
+ "kind": "stripe",
+ "config": {"state": "next=/foo&token=abc123", "code": "oauth_code_999"},
+ },
+ content_type="application/json",
)
- @patch("posthog.models.integration.GitHubIntegration.list_cached_branches")
- def test_api_endpoint_default_branch_first_on_page_one(self, mock_list_cached, client: HttpClient):
- mock_list_cached.return_value = (["main", "alpha", "zebra"], "main", False)
- client.force_login(self.user)
+ assert response.status_code == status.HTTP_201_CREATED
+ mock_oauth_response.assert_called_once()
- response = client.get(
- f"/api/environments/{self.team.pk}/integrations/{self.integration.pk}/github_branches/",
- {"repo": "org/repo"},
- )
+ # The Stripe Apps OAuth flow (used by stripe_api_access_type: oauth) doesn't sign the
+ # callback redirect — only the install-link OAuth mechanism emits install_signature.
+ # The conflict guard is the defense-in-depth here, not signature verification.
+ @pytest.mark.parametrize("include_install_signature", [True, False])
+ @patch("posthog.api.integration.StripeIntegration")
+ @patch("posthog.api.integration.OauthIntegration.integration_from_oauth_response")
+ def test_marketplace_callback_without_state_succeeds(
+ self,
+ mock_oauth_response,
+ MockStripeIntegration,
+ include_install_signature,
+ stripe_settings,
+ client: HttpClient,
+ ):
+ created_integration = self._create_stripe_integration()
+ mock_oauth_response.return_value = created_integration
+ mock_instance = MagicMock()
+ MockStripeIntegration.return_value = mock_instance
- data = response.json()
- assert data["branches"][0] == "main"
- assert data["default_branch"] == "main"
+ config: dict = {
+ "code": "oauth_code_123",
+ "stripe_user_id": "acct_123",
+ "account_id": "acct_123",
+ "user_id": "usr_abc",
+ }
+ if include_install_signature:
+ config["install_signature"] = self._make_install_signature(
+ state="", user_id="usr_abc", account_id="acct_123"
+ )
- @patch("posthog.models.integration.GitHubIntegration.list_cached_branches")
- def test_api_endpoint_pages_cached_branches_without_reinserting_default(self, mock_list_cached, client: HttpClient):
- mock_list_cached.return_value = (["other"], "main", False)
client.force_login(self.user)
-
- response = client.get(
- f"/api/environments/{self.team.pk}/integrations/{self.integration.pk}/github_branches/",
- {"repo": "org/repo", "offset": "100"},
+ response = client.post(
+ f"/api/environments/{self.team.pk}/integrations",
+ {"kind": "stripe", "config": config},
+ content_type="application/json",
)
- data = response.json()
- assert data["branches"] == ["other"]
+ assert response.status_code == status.HTTP_201_CREATED
+ mock_instance.write_posthog_secrets.assert_called_once_with(self.team.pk, self.user)
- @patch("posthog.models.integration.GitHubIntegration.list_cached_branches")
- def test_api_endpoint_prepends_default_branch_even_when_not_in_list(self, mock_list_cached, client: HttpClient):
- mock_list_cached.return_value = (["main", "alpha", "beta"], "main", False)
+ @patch("posthog.api.integration.StripeIntegration")
+ @patch("posthog.api.integration.OauthIntegration.integration_from_oauth_response")
+ def test_marketplace_callback_rejects_forged_install_signature_when_present(
+ self, mock_oauth_response, MockStripeIntegration, stripe_settings, client: HttpClient
+ ):
+ forged = self._make_install_signature(state="", user_id="usr_abc", account_id="acct_123", secret="wrong_secret")
client.force_login(self.user)
-
- response = client.get(
- f"/api/environments/{self.team.pk}/integrations/{self.integration.pk}/github_branches/",
- {"repo": "org/repo"},
+ response = client.post(
+ f"/api/environments/{self.team.pk}/integrations",
+ {
+ "kind": "stripe",
+ "config": {
+ "code": "oauth_code_123",
+ "stripe_user_id": "acct_123",
+ "account_id": "acct_123",
+ "user_id": "usr_abc",
+ "install_signature": forged,
+ },
+ },
+ content_type="application/json",
)
- data = response.json()
- assert data["branches"] == ["main", "alpha", "beta"]
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert "stripe_install_signature_invalid" in response.content.decode()
+ mock_oauth_response.assert_not_called()
+ MockStripeIntegration.assert_not_called()
- @patch("posthog.models.integration.GitHubIntegration.get_default_branch", return_value="main")
- @patch("posthog.models.integration.GitHubIntegration.list_branches")
- def test_api_endpoint_validates_limit_max(self, mock_list, mock_default, client: HttpClient):
- mock_list.return_value = ([], False)
- client.force_login(self.user)
+ @patch("posthog.api.integration.StripeIntegration")
+ @patch("posthog.api.integration.OauthIntegration.integration_from_oauth_response")
+ def test_marketplace_callback_rejects_when_different_stripe_account_connected(
+ self, mock_oauth_response, MockStripeIntegration, stripe_settings, client: HttpClient
+ ):
+ self._create_stripe_integration()
- response = client.get(
- f"/api/environments/{self.team.pk}/integrations/{self.integration.pk}/github_branches/",
- {"repo": "org/repo", "limit": "1001"},
+ sig = self._make_install_signature(state="", user_id="usr_xyz", account_id="acct_999")
+ client.force_login(self.user)
+ response = client.post(
+ f"/api/environments/{self.team.pk}/integrations",
+ {
+ "kind": "stripe",
+ "config": {
+ "code": "oauth_code_999",
+ "stripe_user_id": "acct_999",
+ "account_id": "acct_999",
+ "user_id": "usr_xyz",
+ "install_signature": sig,
+ },
+ },
+ content_type="application/json",
)
- assert response.status_code == 400
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert "stripe_integration_conflict" in response.content.decode()
+ mock_oauth_response.assert_not_called()
+ MockStripeIntegration.assert_not_called()
- @patch("posthog.models.integration.requests.get")
- def test_get_default_branch_is_cached(self, mock_get):
- from django.core.cache import cache
+ @patch("posthog.api.integration.StripeIntegration")
+ @patch("posthog.api.integration.OauthIntegration.integration_from_oauth_response")
+ def test_marketplace_callback_allows_reinstall_of_same_stripe_account(
+ self, mock_oauth_response, MockStripeIntegration, stripe_settings, client: HttpClient
+ ):
+ existing = self._create_stripe_integration()
+ mock_oauth_response.return_value = existing
+ mock_instance = MagicMock()
+ MockStripeIntegration.return_value = mock_instance
- cache.clear()
+ sig = self._make_install_signature(state="", user_id="usr_abc", account_id="acct_123")
+ client.force_login(self.user)
+ response = client.post(
+ f"/api/environments/{self.team.pk}/integrations",
+ {
+ "kind": "stripe",
+ "config": {
+ "code": "oauth_code_123",
+ "stripe_user_id": "acct_123",
+ "account_id": "acct_123",
+ "user_id": "usr_abc",
+ "install_signature": sig,
+ },
+ },
+ content_type="application/json",
+ )
- response = MagicMock()
- response.status_code = 200
- response.json.return_value = {"default_branch": "develop"}
- mock_get.return_value = response
+ assert response.status_code == status.HTTP_201_CREATED
+ mock_oauth_response.assert_called_once()
- first = self.github.get_default_branch("org/repo-cache-test")
- second = self.github.get_default_branch("org/repo-cache-test")
+ @patch("posthog.api.integration.OauthIntegration.integration_from_oauth_response")
+ def test_stripe_oauth_exchange_failure_returns_error(
+ self, mock_oauth_response, stripe_settings, client: HttpClient
+ ):
+ mock_oauth_response.side_effect = Exception("Stripe returned invalid_grant")
- assert first == "develop"
- assert second == "develop"
- assert mock_get.call_count == 1
+ sig = self._make_install_signature(state="", user_id="usr_abc", account_id="acct_123")
+ client.force_login(self.user)
+ response = client.post(
+ f"/api/environments/{self.team.pk}/integrations",
+ {
+ "kind": "stripe",
+ "config": {
+ "code": "ac_invalid",
+ "stripe_user_id": "acct_123",
+ "account_id": "acct_123",
+ "user_id": "usr_abc",
+ "install_signature": sig,
+ },
+ },
+ content_type="application/json",
+ )
+ assert response.status_code == status.HTTP_500_INTERNAL_SERVER_ERROR
+ assert not Integration.objects.filter(team_id=self.team.pk, kind="stripe").exists()
-class TestGitHubLinkExisting:
- """Tests for POST /integrations/github/link_existing/ — clones a GitHub Integration
- row from another team in the same organization onto the current team without
- going through the GitHub install flow.
- """
+class TestStripeIntegrationOAuthTokens:
@pytest.fixture(autouse=True)
- def setup_environment(self, db):
- from posthog.models.user_integration import UserIntegration
-
+ def setup(self, db):
self.organization = Organization.objects.create(name="Test Org")
- self.source_team = Team.objects.create(organization=self.organization, name="Source Team")
- self.dest_team = Team.objects.create(organization=self.organization, name="Dest Team")
- self.user = User.objects.create_and_join(
- self.organization, "[email protected]", "test", level=OrganizationMembership.Level.ADMIN
+ self.team = Team.objects.create(organization=self.organization, name="Test Team")
+ self.user = User.objects.create_and_join(self.organization, "[email protected]", "test")
+ self.oauth_app = OAuthApplication.objects.create(
+ name="PostHog for Stripe",
+ client_id="stripe_oauth_client_id",
+ client_type=OAuthApplication.CLIENT_CONFIDENTIAL,
+ authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,
+ redirect_uris="https://example.com/callback",
+ algorithm="RS256",
)
- self.source_integration = Integration.objects.create(
- team=self.source_team,
- kind="github",
- integration_id="12345",
- config={
- "installation_id": "12345",
- "expires_in": 3600,
- "refreshed_at": int(time.time()),
- "repository_selection": "all",
- "account": {"type": "Organization", "name": "acme"},
- "connecting_user_github_login": "octocat",
- },
- sensitive_config={"access_token": "ghs_source"},
+ def _create_integration_with_tokens(self) -> tuple[Integration, OAuthAccessToken, OAuthRefreshToken]:
+ integration = Integration.objects.create(
+ team=self.team,
+ kind="stripe",
+ config={"account_name": "Test (acct_123)"},
+ sensitive_config={"access_token": "sk_live_test"},
+ integration_id="acct_123",
created_by=self.user,
)
-
- # Personal GitHub integration that proves the requesting user has access to the
- # GitHub installation — required by the link_existing security check.
- self.user_github_integration = UserIntegration.objects.create(
+ access_token = OAuthAccessToken.objects.create(
+ application=self.oauth_app,
+ token="ph_access_token_test",
user=self.user,
- kind="github",
- integration_id="12345",
- config={"account": {"type": "Organization", "name": "acme"}},
- sensitive_config={"access_token": "ghu_user"},
+ expires=timezone.now() + timedelta(days=365),
+ scope=StripeIntegration.SCOPES,
+ scoped_teams=[self.team.pk],
+ )
+ refresh_token = OAuthRefreshToken.objects.create(
+ application=self.oauth_app,
+ token="ph_refresh_token_test",
+ user=self.user,
+ access_token=access_token,
+ scoped_teams=[self.team.pk],
)
+ return integration, access_token, refresh_token
- @patch("posthog.models.integration.GitHubIntegration.verify_user_installation_access", return_value=True)
- @patch("posthog.models.integration.GitHubIntegration.integration_from_installation_id")
- def test_link_existing_clones_integration_to_dest_team(self, mock_from_install, mock_verify, client: HttpClient):
- client.force_login(self.user)
+ @patch("posthog.models.integration.settings")
+ def test_destroy_oauth_tokens_deletes_tokens(self, mock_settings):
+ mock_settings.STRIPE_POSTHOG_OAUTH_CLIENT_ID = self.oauth_app.client_id
+ integration, access_token, refresh_token = self._create_integration_with_tokens()
+ stripe_int = StripeIntegration(integration)
- cloned = Integration.objects.create(
- team=self.dest_team,
- kind="github",
- integration_id="12345",
- config={
- "installation_id": "12345",
- "expires_in": 3600,
- "refreshed_at": int(time.time()),
- "repository_selection": "all",
- "account": {"type": "Organization", "name": "acme"},
- },
- sensitive_config={"access_token": "ghs_cloned"},
- created_by=self.user,
- )
- mock_from_install.return_value = cloned
+ stripe_int._destroy_posthog_oauth_tokens()
- response = client.post(
- f"/api/environments/{self.dest_team.pk}/integrations/github/link_existing/",
- {"source_team_id": self.source_team.id},
- content_type="application/json",
+ assert not OAuthAccessToken.objects.filter(pk=access_token.pk).exists()
+ assert not OAuthRefreshToken.objects.filter(pk=refresh_token.pk).exists()
+
+ @patch("posthog.models.integration.settings")
+ def test_destroy_oauth_tokens_only_affects_same_team(self, mock_settings):
+ mock_settings.STRIPE_POSTHOG_OAUTH_CLIENT_ID = self.oauth_app.client_id
+ integration, _, _ = self._create_integration_with_tokens()
+
+ other_team = Team.objects.create(organization=self.organization, name="Other Team")
+ other_access_token = OAuthAccessToken.objects.create(
+ application=self.oauth_app,
+ token="ph_access_other",
+ user=self.user,
+ expires=timezone.now() + timedelta(days=365),
+ scope=StripeIntegration.SCOPES,
+ scoped_teams=[other_team.pk],
+ )
+ other_refresh_token = OAuthRefreshToken.objects.create(
+ application=self.oauth_app,
+ token="ph_refresh_other",
+ user=self.user,
+ access_token=other_access_token,
+ scoped_teams=[other_team.pk],
)
- assert response.status_code == status.HTTP_200_OK
- mock_verify.assert_called_once_with("12345", "ghu_user")
- mock_from_install.assert_called_once_with("12345", self.dest_team.pk, self.user)
+ stripe_int = StripeIntegration(integration)
+ stripe_int._destroy_posthog_oauth_tokens()
- cloned.refresh_from_db()
- assert cloned.config.get("connecting_user_github_login") == "octocat"
+ assert OAuthAccessToken.objects.filter(pk=other_access_token.pk).exists()
+ assert OAuthRefreshToken.objects.filter(pk=other_refresh_token.pk).exists()
- @patch("posthog.models.integration.GitHubIntegration.integration_from_installation_id")
- def test_link_existing_rejects_cross_organization(self, mock_from_install, client: HttpClient):
- other_org = Organization.objects.create(name="Other Org")
- other_team = Team.objects.create(organization=other_org, name="Other Team")
- Integration.objects.create(
- team=other_team,
- kind="github",
- integration_id="99999",
- config={"installation_id": "99999"},
- sensitive_config={"access_token": "ghs_foreign"},
- )
+ @patch("posthog.models.integration.settings")
+ def test_destroy_oauth_tokens_noop_when_no_oauth_app(self, mock_settings):
+ mock_settings.STRIPE_POSTHOG_OAUTH_CLIENT_ID = None
+ integration, access_token, refresh_token = self._create_integration_with_tokens()
+ stripe_int = StripeIntegration(integration)
- client.force_login(self.user)
+ stripe_int._destroy_posthog_oauth_tokens()
- response = client.post(
- f"/api/environments/{self.dest_team.pk}/integrations/github/link_existing/",
- {"source_team_id": other_team.id},
- content_type="application/json",
- )
+ assert OAuthAccessToken.objects.filter(pk=access_token.pk).exists()
+ assert OAuthRefreshToken.objects.filter(pk=refresh_token.pk).exists()
- assert response.status_code == status.HTTP_400_BAD_REQUEST
- assert "Source team not found in your organization" in response.json()["detail"]
- mock_from_install.assert_not_called()
+ @patch("stripe.StripeClient")
+ @patch("posthog.models.integration.settings")
+ def test_write_posthog_secrets_uses_account_scope(self, mock_settings, MockStripeClient):
+ mock_settings.STRIPE_POSTHOG_OAUTH_CLIENT_ID = self.oauth_app.client_id
+ mock_settings.STRIPE_APP_SECRET_KEY = "sk_test"
+ mock_client = MagicMock()
+ MockStripeClient.return_value = mock_client
- @patch("posthog.models.integration.GitHubIntegration.integration_from_installation_id")
- def test_link_existing_rejects_team_without_github_integration(self, mock_from_install, client: HttpClient):
- slack_only_team = Team.objects.create(organization=self.organization, name="Slack Only Team")
- Integration.objects.create(
- team=slack_only_team,
- kind="slack",
- config={"team_id": "T123"},
- sensitive_config={"access_token": "xoxb_test"},
+ integration = Integration.objects.create(
+ team=self.team,
+ kind="stripe",
+ config={},
+ sensitive_config={},
+ integration_id="acct_456",
+ created_by=self.user,
)
+ stripe_int = StripeIntegration(integration)
+ stripe_int.write_posthog_secrets(self.team.pk, self.user)
- client.force_login(self.user)
+ calls = mock_client.apps.secrets.create.call_args_list
+ assert len(calls) == 5
+ for call in calls:
+ assert call.kwargs["params"]["scope"] == {"type": "account"}
+ assert call.kwargs["options"] == {"stripe_account": "acct_456"}
- response = client.post(
- f"/api/environments/{self.dest_team.pk}/integrations/github/link_existing/",
- {"source_team_id": slack_only_team.id},
- content_type="application/json",
- )
+ secret_payloads = {call.kwargs["params"]["name"]: call.kwargs["params"]["payload"] for call in calls}
+ assert secret_payloads["posthog_project_id"] == str(self.team.pk)
+ assert secret_payloads["posthog_oauth_client_id"] == self.oauth_app.client_id
- assert response.status_code == status.HTTP_400_BAD_REQUEST
- assert "Source team does not have a GitHub integration" in response.json()["detail"]
- mock_from_install.assert_not_called()
+ @patch("stripe.StripeClient")
+ @patch("posthog.models.integration.settings")
+ def test_clear_posthog_secrets_uses_account_scope(self, mock_settings, MockStripeClient):
+ mock_settings.STRIPE_APP_SECRET_KEY = "sk_test"
+ mock_settings.STRIPE_POSTHOG_OAUTH_CLIENT_ID = None
+ mock_client = MagicMock()
+ MockStripeClient.return_value = mock_client
- @patch("posthog.models.integration.GitHubIntegration.integration_from_installation_id")
- def test_link_existing_rejects_source_missing_installation_id(self, mock_from_install, client: HttpClient):
- broken_team = Team.objects.create(organization=self.organization, name="Broken Team")
- Integration.objects.create(
- team=broken_team,
- kind="github",
- integration_id="broken",
+ integration = Integration.objects.create(
+ team=self.team,
+ kind="stripe",
config={},
sensitive_config={},
+ integration_id="acct_789",
+ created_by=self.user,
)
+ stripe_int = StripeIntegration(integration)
+ stripe_int.clear_posthog_secrets()
- client.force_login(self.user)
+ calls = mock_client.apps.secrets.delete_where.call_args_list
+ assert len(calls) == 5
+ for call in calls:
+ assert call.kwargs["params"]["scope"] == {"type": "account"}
+ assert call.kwargs["options"] == {"stripe_account": "acct_789"}
- response = client.post(
- f"/api/environments/{self.dest_team.pk}/integrations/github/link_existing/",
- {"source_team_id": broken_team.id},
- content_type="application/json",
+ @parameterized.expand(
+ [
+ ("write", "write_posthog_secrets"),
+ ("clear", "clear_posthog_secrets"),
+ ]
+ )
+ @patch("stripe.StripeClient")
+ @patch("posthog.models.integration.settings")
+ def test_stripe_client_uses_live_secret(self, _name, method_name, mock_settings, MockStripeClient):
+ mock_settings.STRIPE_POSTHOG_OAUTH_CLIENT_ID = self.oauth_app.client_id
+ mock_settings.STRIPE_APP_SECRET_KEY = "sk_live"
+ MockStripeClient.return_value = MagicMock()
+
+ integration = Integration.objects.create(
+ team=self.team,
+ kind="stripe",
+ config={},
+ sensitive_config={},
+ integration_id=f"acct_{_name}",
+ created_by=self.user,
)
+ stripe_int = StripeIntegration(integration)
+ if method_name == "write_posthog_secrets":
+ stripe_int.write_posthog_secrets(self.team.pk, self.user)
+ else:
+ stripe_int.clear_posthog_secrets()
- assert response.status_code == status.HTTP_400_BAD_REQUEST
- assert "missing installation_id" in response.json()["detail"]
- mock_from_install.assert_not_called()
+ MockStripeClient.assert_called_once_with("sk_live")
- @patch("posthog.models.integration.GitHubIntegration.verify_user_installation_access", return_value=True)
- @patch("posthog.models.integration.GitHubIntegration.integration_from_installation_id")
- def test_link_existing_by_installation_id_links_to_dest_team(
- self, mock_from_install, mock_verify, client: HttpClient
- ):
- client.force_login(self.user)
+ @patch("posthog.models.integration.capture_exception")
+ @patch("stripe.StripeClient")
+ @patch("posthog.models.integration.settings")
+ def test_write_posthog_secrets_skips_when_keys_missing(self, mock_settings, MockStripeClient, mock_capture):
+ mock_settings.STRIPE_POSTHOG_OAUTH_CLIENT_ID = self.oauth_app.client_id
+ mock_settings.STRIPE_APP_CLIENT_ID = None
+ mock_settings.STRIPE_APP_SECRET_KEY = None
+ MockStripeClient.return_value = MagicMock()
- cloned = Integration.objects.create(
- team=self.dest_team,
- kind="github",
- integration_id="12345",
- config={"installation_id": "12345"},
- sensitive_config={"access_token": "ghs_cloned"},
+ integration = Integration.objects.create(
+ team=self.team,
+ kind="stripe",
+ config={},
+ sensitive_config={},
+ integration_id="acct_missing_write",
created_by=self.user,
)
- mock_from_install.return_value = cloned
+ stripe_int = StripeIntegration(integration)
+ stripe_int.write_posthog_secrets(self.team.pk, self.user)
- response = client.post(
- f"/api/environments/{self.dest_team.pk}/integrations/github/link_existing/",
- {"installation_id": "12345"},
- content_type="application/json",
- )
+ MockStripeClient.assert_not_called()
+ mock_capture.assert_called_once()
+ captured_exc = mock_capture.call_args.args[0]
+ assert isinstance(captured_exc, NotImplementedError)
+
+ @patch("posthog.models.integration.capture_exception")
+ @patch("stripe.StripeClient")
+ @patch("posthog.models.integration.settings")
+ def test_clear_posthog_secrets_skips_and_revokes_tokens_when_keys_missing(
+ self, mock_settings, MockStripeClient, mock_capture
+ ):
+ mock_settings.STRIPE_POSTHOG_OAUTH_CLIENT_ID = self.oauth_app.client_id
+ mock_settings.STRIPE_APP_CLIENT_ID = None
+ mock_settings.STRIPE_APP_SECRET_KEY = None
+ MockStripeClient.return_value = MagicMock()
+
+ integration, access_token, refresh_token = self._create_integration_with_tokens()
- assert response.status_code == status.HTTP_200_OK
- mock_verify.assert_called_once_with("12345", "ghu_user")
- mock_from_install.assert_called_once_with("12345", self.dest_team.pk, self.user)
+ stripe_int = StripeIntegration(integration)
+ stripe_int.clear_posthog_secrets()
- @patch("posthog.models.integration.GitHubIntegration.integration_from_installation_id")
- def test_link_existing_by_installation_id_rejects_unknown_installation(self, mock_from_install, client: HttpClient):
- client.force_login(self.user)
+ MockStripeClient.assert_not_called()
+ mock_capture.assert_called_once()
+ assert not OAuthAccessToken.objects.filter(pk=access_token.pk).exists()
+ assert not OAuthRefreshToken.objects.filter(pk=refresh_token.pk).exists()
- response = client.post(
- f"/api/environments/{self.dest_team.pk}/integrations/github/link_existing/",
- {"installation_id": "99999"},
- content_type="application/json",
- )
- assert response.status_code == status.HTTP_400_BAD_REQUEST
- assert "No team in your organization" in response.json()["detail"]
- mock_from_install.assert_not_called()
+def _make_github_branches_response(names: list[str], has_next: bool = False) -> MagicMock:
+ """Build a mock requests.Response for the GitHub branches API."""
+ response = MagicMock()
+ response.status_code = 200
+ response.json.return_value = [{"name": n} for n in names]
+ link = '<https://api.github.com/next>; rel="next"' if has_next else ""
+ response.headers = {"Link": link}
+ return response
- @patch("posthog.models.integration.GitHubIntegration.integration_from_installation_id")
- def test_link_existing_by_installation_id_rejects_non_numeric(self, mock_from_install, client: HttpClient):
- client.force_login(self.user)
- response = client.post(
- f"/api/environments/{self.dest_team.pk}/integrations/github/link_existing/",
- {"installation_id": "not-a-number"},
- content_type="application/json",
+class TestGitHubBranches:
+ @pytest.fixture(autouse=True)
+ def setup_integration(self, db):
+ self.organization = Organization.objects.create(name="Test Org")
+ self.team = Team.objects.create(organization=self.organization, name="Test Team")
+ self.user = User.objects.create_and_join(
+ self.organization, "[email protected]", "test", level=OrganizationMembership.Level.ADMIN
)
+ self.integration = Integration.objects.create(
+ team=self.team,
+ kind="github",
+ config={"installation_id": "12345", "refreshed_at": 0, "expires_in": 999999},
+ sensitive_config={"access_token": "test-token"},
+ )
+ self.github = GitHubIntegration(self.integration)
- assert response.status_code == status.HTTP_400_BAD_REQUEST
- assert "Invalid installation_id" in response.json()["detail"]
- mock_from_install.assert_not_called()
-
- def test_link_existing_requires_source_team_id_or_installation_id(self, client: HttpClient):
- client.force_login(self.user)
+ @patch("posthog.models.integration.requests.get")
+ def test_list_branches_returns_first_page(self, mock_get):
+ names = [f"branch-{i}" for i in range(100)]
+ mock_get.return_value = _make_github_branches_response(names, has_next=True)
- response = client.post(
- f"/api/environments/{self.dest_team.pk}/integrations/github/link_existing/",
- {},
- content_type="application/json",
- )
+ branches, has_more = self.github.list_branches("org/repo", limit=100, offset=0)
- assert response.status_code == status.HTTP_400_BAD_REQUEST
- assert "source_team_id or installation_id is required" in response.json()["detail"]
+ assert branches == names
+ assert has_more is True
+ mock_get.assert_called_once()
+ assert "page=1" in mock_get.call_args[0][0]
- @patch("posthog.models.integration.GitHubIntegration.verify_user_installation_access")
- @patch("posthog.models.integration.GitHubIntegration.integration_from_installation_id")
- def test_link_existing_rejects_user_without_personal_github(
- self, mock_from_install, mock_verify, client: HttpClient
- ):
- # Stranger from the same org has no personal GitHub UserIntegration; can't prove access.
- stranger = User.objects.create_and_join(
- self.organization, "[email protected]", "stranger", level=OrganizationMembership.Level.ADMIN
- )
- client.force_login(stranger)
+ @patch("posthog.models.integration.requests.get")
+ def test_list_branches_offset_skips_pages(self, mock_get):
+ """Requesting offset=200 should start fetching from GitHub page 3."""
+ page3_names = [f"branch-{i}" for i in range(200, 300)]
+ mock_get.return_value = _make_github_branches_response(page3_names, has_next=True)
- response = client.post(
- f"/api/environments/{self.dest_team.pk}/integrations/github/link_existing/",
- {"source_team_id": self.source_team.id},
- content_type="application/json",
- )
+ branches, has_more = self.github.list_branches("org/repo", limit=100, offset=200)
- assert response.status_code == status.HTTP_400_BAD_REQUEST
- assert "connect your personal GitHub account" in response.json()["detail"]
- mock_verify.assert_not_called()
- mock_from_install.assert_not_called()
+ assert branches == page3_names
+ assert has_more is True
+ assert mock_get.call_count == 1
+ assert "page=3" in mock_get.call_args[0][0]
- @patch("posthog.models.integration.GitHubIntegration.verify_user_installation_access", return_value=False)
- @patch("posthog.models.integration.GitHubIntegration.integration_from_installation_id")
- def test_link_existing_rejects_user_without_installation_access(
- self, mock_from_install, mock_verify, client: HttpClient
- ):
- # User has a personal GitHub integration but GitHub says they can't see this installation.
- client.force_login(self.user)
+ @patch("posthog.models.integration.requests.get")
+ def test_list_branches_last_page_no_more(self, mock_get):
+ names = [f"branch-{i}" for i in range(50)]
+ mock_get.return_value = _make_github_branches_response(names, has_next=False)
- response = client.post(
- f"/api/environments/{self.dest_team.pk}/integrations/github/link_existing/",
- {"source_team_id": self.source_team.id},
- content_type="application/json",
- )
+ branches, has_more = self.github.list_branches("org/repo", limit=100, offset=0)
- assert response.status_code == status.HTTP_400_BAD_REQUEST
- assert "connect your personal GitHub account" in response.json()["detail"]
- mock_verify.assert_called_once_with("12345", "ghu_user")
- mock_from_install.assert_not_called()
+ assert branches == names
+ assert has_more is False
- @patch("posthog.models.integration.GitHubIntegration.verify_user_installation_access")
- @patch("posthog.models.integration.GitHubIntegration.integration_from_installation_id")
- def test_link_existing_surfaces_verify_network_failures(self, mock_from_install, mock_verify, client: HttpClient):
- import requests as _requests
+ @patch("posthog.models.integration.requests.get")
+ def test_list_branches_spans_two_github_pages(self, mock_get):
+ """An offset that doesn't align with per_page=100 requires fetching two GitHub pages."""
+ page1_names = [f"branch-{i}" for i in range(100)]
+ page2_names = [f"branch-{i}" for i in range(100, 200)]
- mock_verify.side_effect = _requests.RequestException("boom")
- client.force_login(self.user)
+ mock_get.side_effect = [
+ _make_github_branches_response(page1_names, has_next=True),
+ _make_github_branches_response(page2_names, has_next=False),
+ ]
- response = client.post(
- f"/api/environments/{self.dest_team.pk}/integrations/github/link_existing/",
- {"source_team_id": self.source_team.id},
- content_type="application/json",
- )
+ branches, has_more = self.github.list_branches("org/repo", limit=100, offset=50)
- assert response.status_code == status.HTTP_400_BAD_REQUEST
- assert "Failed to verify installation access" in response.json()["detail"]
- mock_from_install.assert_not_called()
+ assert len(branches) == 100
+ assert branches == [f"branch-{i}" for i in range(50, 150)]
+ # There are still branches 150-199 beyond this window
+ assert has_more is True
+ assert mock_get.call_count == 2
- @patch("posthog.models.integration.GitHubIntegration.verify_user_installation_access", return_value=True)
- @patch("posthog.models.integration.GitHubIntegration.integration_from_installation_id")
- def test_link_existing_disambiguates_multi_install_team_via_installation_id(
- self, mock_from_install, mock_verify, client: HttpClient
- ):
- # Source team has multiple GitHub installations linked. Without installation_id
- # the request was crashing on MultipleObjectsReturned; passing installation_id
- # should pick exactly that row.
- Integration.objects.create(
- team=self.source_team,
- kind="github",
- integration_id="22222",
- config={"installation_id": "22222", "account": {"type": "Organization", "name": "other"}},
- sensitive_config={"access_token": "ghs_other"},
- created_by=self.user,
- )
+ @patch("posthog.models.integration.requests.get")
+ def test_list_branches_empty_repo(self, mock_get):
+ mock_get.return_value = _make_github_branches_response([], has_next=False)
- cloned = Integration.objects.create(
- team=self.dest_team,
- kind="github",
- integration_id="12345",
- config={"installation_id": "12345"},
- sensitive_config={"access_token": "ghs_cloned"},
- created_by=self.user,
- )
- mock_from_install.return_value = cloned
+ branches, has_more = self.github.list_branches("org/repo")
- client.force_login(self.user)
- response = client.post(
- f"/api/environments/{self.dest_team.pk}/integrations/github/link_existing/",
- {"source_team_id": self.source_team.id, "installation_id": "12345"},
- content_type="application/json",
- )
+ assert branches == []
+ assert has_more is False
- assert response.status_code == status.HTTP_200_OK
- mock_verify.assert_called_once_with("12345", "ghu_user")
- mock_from_install.assert_called_once_with("12345", self.dest_team.pk, self.user)
+ @patch("posthog.models.integration.requests.get")
+ def test_list_branches_401_triggers_refresh_and_retry(self, mock_get):
+ unauthorized = MagicMock()
+ unauthorized.status_code = 401
- @patch("posthog.models.integration.GitHubIntegration.verify_user_installation_access", return_value=True)
- @patch("posthog.models.integration.GitHubIntegration.integration_from_installation_id")
- def test_link_existing_matches_installation_id_stored_as_int(
- self, mock_from_install, mock_verify, client: HttpClient
- ):
- # Some integrations have installation_id stored as a JSONB number rather than
- # a string; the lookup must match either representation.
- int_team = Team.objects.create(organization=self.organization, name="Int Team")
- Integration.objects.create(
- team=int_team,
- kind="github",
- integration_id="77777",
- config={"installation_id": 77777, "account": {"type": "Organization", "name": "intacme"}},
- sensitive_config={"access_token": "ghs_int"},
- created_by=self.user,
- )
+ names = ["main", "develop"]
+ success = _make_github_branches_response(names, has_next=False)
- cloned = Integration.objects.create(
- team=self.dest_team,
- kind="github",
- integration_id="77777",
- config={"installation_id": "77777"},
- sensitive_config={"access_token": "ghs_cloned"},
- created_by=self.user,
- )
- mock_from_install.return_value = cloned
+ mock_get.side_effect = [unauthorized, success]
- client.force_login(self.user)
- response = client.post(
- f"/api/environments/{self.dest_team.pk}/integrations/github/link_existing/",
- {"installation_id": "77777"},
- content_type="application/json",
- )
+ with patch.object(self.github, "refresh_access_token"):
+ branches, has_more = self.github.list_branches("org/repo")
- assert response.status_code == status.HTTP_200_OK
- mock_verify.assert_called_once_with("77777", "ghu_user")
- mock_from_install.assert_called_once_with("77777", self.dest_team.pk, self.user)
+ assert branches == names
+ assert mock_get.call_count == 2
+ @patch("posthog.models.integration.GitHubIntegration.list_cached_branches")
+ def test_api_endpoint_passes_search_limit_offset(self, mock_list_cached, client: HttpClient):
+ mock_list_cached.return_value = ([f"branch-{i}" for i in range(10)], "main", True)
+ client.force_login(self.user)
-class TestGitHubOAuthAuthorize:
- """Tests for POST /integrations/github/oauth_authorize/ — mints a User OAuth URL
- so the frontend can recover from `setup_action=update` redirects (no code).
- """
+ response = client.get(
+ f"/api/environments/{self.team.pk}/integrations/{self.integration.pk}/github_branches/",
+ {"repo": "org/repo", "search": "feature", "limit": "10", "offset": "50"},
+ )
- @pytest.fixture(autouse=True)
- def setup_environment(self, db):
- self.organization = Organization.objects.create(name="Test Org")
- self.team = Team.objects.create(organization=self.organization, name="Test Team")
- self.user = User.objects.create_and_join(
- self.organization, "[email protected]", "test", level=OrganizationMembership.Level.ADMIN
+ assert response.status_code == 200
+ data = response.json()
+ assert len(data["branches"]) == 10
+ assert data["has_more"] is True
+ assert data["default_branch"] == "main"
+ mock_list_cached.assert_called_once_with(
+ "org/repo",
+ search="feature",
+ limit=10,
+ offset=50,
)
- def test_oauth_authorize_returns_github_url_with_state_in_cache(self, client: HttpClient):
+ @patch("posthog.models.integration.GitHubIntegration.list_cached_branches")
+ def test_api_endpoint_default_branch_first_on_page_one(self, mock_list_cached, client: HttpClient):
+ mock_list_cached.return_value = (["main", "alpha", "zebra"], "main", False)
client.force_login(self.user)
- with patch.object(django_settings, "GITHUB_APP_CLIENT_ID", "test-client-id"):
- response = client.post(
- f"/api/environments/{self.team.pk}/integrations/github/oauth_authorize/",
- {"installation_id": "12345", "next": "/some/return/path"},
- content_type="application/json",
- )
+ response = client.get(
+ f"/api/environments/{self.team.pk}/integrations/{self.integration.pk}/github_branches/",
+ {"repo": "org/repo"},
+ )
- assert response.status_code == status.HTTP_200_OK
- body = response.json()
- assert "oauth_url" in body
- assert body["oauth_url"].startswith("https://github.com/login/oauth/authorize?")
- assert "client_id=test-client-id" in body["oauth_url"]
-
- # Pull the state token out of the URL and verify the cache entry is bound
- # to user_id + team_id + installation_id.
- token_match = re.search(r"state=token%3D([^&]+)", body["oauth_url"])
- assert token_match is not None
- token = token_match.group(1)
- cached = cache.get(f"github_user_install_state:{token}")
- assert cached is not None
- assert cached["user_id"] == self.user.id
- assert cached["team_id"] == self.team.pk
- assert cached["installation_id"] == "12345"
- assert cached["flow"] == "team_oauth_authorize"
- assert cached["next"] == "/some/return/path"
+ data = response.json()
+ assert data["branches"][0] == "main"
+ assert data["default_branch"] == "main"
- def test_oauth_authorize_requires_installation_id(self, client: HttpClient):
+ @patch("posthog.models.integration.GitHubIntegration.list_cached_branches")
+ def test_api_endpoint_pages_cached_branches_without_reinserting_default(self, mock_list_cached, client: HttpClient):
+ mock_list_cached.return_value = (["other"], "main", False)
client.force_login(self.user)
- with patch.object(django_settings, "GITHUB_APP_CLIENT_ID", "test-client-id"):
- response = client.post(
- f"/api/environments/{self.team.pk}/integrations/github/oauth_authorize/",
- {},
- content_type="application/json",
- )
+ response = client.get(
+ f"/api/environments/{self.team.pk}/integrations/{self.integration.pk}/github_branches/",
+ {"repo": "org/repo", "offset": "100"},
+ )
- assert response.status_code == status.HTTP_400_BAD_REQUEST
- assert "installation_id is required" in response.json()["detail"]
+ data = response.json()
+ assert data["branches"] == ["other"]
- def test_oauth_authorize_rejects_non_numeric_installation_id(self, client: HttpClient):
+ @patch("posthog.models.integration.GitHubIntegration.list_cached_branches")
+ def test_api_endpoint_prepends_default_branch_even_when_not_in_list(self, mock_list_cached, client: HttpClient):
+ mock_list_cached.return_value = (["main", "alpha", "beta"], "main", False)
client.force_login(self.user)
- with patch.object(django_settings, "GITHUB_APP_CLIENT_ID", "test-client-id"):
- response = client.post(
- f"/api/environments/{self.team.pk}/integrations/github/oauth_authorize/",
- {"installation_id": "abc"},
- content_type="application/json",
- )
+ response = client.get(
+ f"/api/environments/{self.team.pk}/integrations/{self.integration.pk}/github_branches/",
+ {"repo": "org/repo"},
+ )
- assert response.status_code == status.HTTP_400_BAD_REQUEST
- assert "Invalid installation_id" in response.json()["detail"]
+ data = response.json()
+ assert data["branches"] == ["main", "alpha", "beta"]
- def test_oauth_authorize_rejects_absolute_next_url(self, client: HttpClient):
+ @patch("posthog.models.integration.GitHubIntegration.get_default_branch", return_value="main")
+ @patch("posthog.models.integration.GitHubIntegration.list_branches")
+ def test_api_endpoint_validates_limit_max(self, mock_list, mock_default, client: HttpClient):
+ mock_list.return_value = ([], False)
client.force_login(self.user)
- with patch.object(django_settings, "GITHUB_APP_CLIENT_ID", "test-client-id"):
- response = client.post(
- f"/api/environments/{self.team.pk}/integrations/github/oauth_authorize/",
- {"installation_id": "12345", "next": "https://evil.com/steal"},
- content_type="application/json",
- )
-
- assert response.status_code == status.HTTP_400_BAD_REQUEST
- assert "next must be a relative path" in response.json()["detail"]
+ response = client.get(
+ f"/api/environments/{self.team.pk}/integrations/{self.integration.pk}/github_branches/",
+ {"repo": "org/repo", "limit": "1001"},
+ )
- def test_oauth_authorize_rejects_protocol_relative_next_url(self, client: HttpClient):
- client.force_login(self.user)
+ assert response.status_code == 400
- with patch.object(django_settings, "GITHUB_APP_CLIENT_ID", "test-client-id"):
- response = client.post(
- f"/api/environments/{self.team.pk}/integrations/github/oauth_authorize/",
- {"installation_id": "12345", "next": "//evil.com/steal"},
- content_type="application/json",
- )
+ @patch("posthog.models.integration.requests.get")
+ def test_get_default_branch_is_cached(self, mock_get):
+ from django.core.cache import cache
- assert response.status_code == status.HTTP_400_BAD_REQUEST
- assert "next must be a relative path" in response.json()["detail"]
+ cache.clear()
- def test_oauth_authorize_requires_client_id_configured(self, client: HttpClient):
- client.force_login(self.user)
+ response = MagicMock()
+ response.status_code = 200
+ response.json.return_value = {"default_branch": "develop"}
+ mock_get.return_value = response
- with patch.object(django_settings, "GITHUB_APP_CLIENT_ID", ""):
- response = client.post(
- f"/api/environments/{self.team.pk}/integrations/github/oauth_authorize/",
- {"installation_id": "12345"},
- content_type="application/json",
- )
+ first = self.github.get_default_branch("org/repo-cache-test")
+ second = self.github.get_default_branch("org/repo-cache-test")
- assert response.status_code == status.HTTP_400_BAD_REQUEST
- assert "GitHub App client ID is not configured" in response.json()["detail"]
+ assert first == "develop"
+ assert second == "develop"
+ assert mock_get.call_count == 1
class TestAnthropicIntegration:
diff --git a/posthog/api/test/test_user_integration.py b/posthog/api/test/test_user_integration.py
index 6f89e722514d..6887a19bbb1e 100644
--- a/posthog/api/test/test_user_integration.py
+++ b/posthog/api/test/test_user_integration.py
@@ -1,16 +1,22 @@
import time
from typing import Any
+from urllib.parse import parse_qs, urlencode, urlparse
from posthog.test.base import APIBaseTest
from unittest.mock import MagicMock, patch
-from django.core.cache import cache
from django.test import override_settings
from parameterized import parameterized
from rest_framework import status
-from posthog.models import User
+from posthog.api.github_callback.state import (
+ load_authorize_state,
+ parse_github_authorize_state_param,
+ store_unified_authorize_state,
+)
+from posthog.api.github_callback.types import FlowKind, GitHubAuthorizeState
+from posthog.models import OrganizationMembership, User
from posthog.models.integration import GitHubInstallationAccess, GitHubUserAuthorization, Integration
from posthog.models.user_integration import (
ReauthorizationRequired,
@@ -182,7 +188,7 @@ class TestUserIntegrationEndpoints(APIBaseTest):
@override_settings(GITHUB_APP_CLIENT_ID="client_id")
@patch(
- "posthog.api.github_callback.personal_state.get_instance_settings",
+ "posthog.api.github_callback.types.get_instance_settings",
return_value={"GITHUB_APP_SLUG": "posthog-dev"},
)
def test_github_start_returns_install_url_when_no_team_github(self, _mock_settings):
@@ -259,7 +265,7 @@ class TestUserIntegrationEndpoints(APIBaseTest):
@override_settings(GITHUB_APP_CLIENT_ID="gh_client_123")
@patch(
- "posthog.api.github_callback.personal_state.get_instance_settings",
+ "posthog.api.github_callback.types.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):
@@ -291,7 +297,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.github_callback.personal_state.get_instance_settings",
+ "posthog.api.github_callback.types.get_instance_settings",
return_value={"GITHUB_APP_SLUG": "posthog-dev"},
)
def test_github_start_rejects_when_all_installations_linked(self, _mock_settings, _mock_unlinked):
@@ -308,7 +314,7 @@ class TestUserIntegrationEndpoints(APIBaseTest):
def test_github_start_without_app_slug_returns_400(self):
with patch(
- "posthog.api.github_callback.personal_state.get_instance_settings",
+ "posthog.api.github_callback.types.get_instance_settings",
return_value={"GITHUB_APP_SLUG": ""},
):
response = self.client.post("/api/users/@me/integrations/github/start/")
@@ -349,16 +355,14 @@ class TestUserIntegrationEndpoints(APIBaseTest):
created_by=self.user,
)
state = "tok_oauth_123"
- cache.set(
- f"github_user_install_state:{state}",
- {
- "user_id": self.user.id,
- "installation_id": "12345",
- "flow": "oauth_authorize",
- },
- timeout=600,
+ store_unified_authorize_state(
+ GitHubAuthorizeState(
+ token=state,
+ flow=FlowKind.PERSONAL_OAUTH,
+ user_id=self.user.id,
+ installation_id="12345",
+ ),
)
- from urllib.parse import urlencode
state_q = urlencode({"token": state, "source": "user_integration"})
@@ -376,6 +380,65 @@ class TestUserIntegrationEndpoints(APIBaseTest):
integration = UserIntegration.objects.get(user=self.user, kind="github")
self.assertEqual(integration.integration_id, "12345")
+ @override_settings(
+ GITHUB_APP_CLIENT_ID="client_id",
+ GITHUB_APP_CLIENT_SECRET="client_secret",
+ SITE_URL="https://us.posthog.com",
+ )
+ @patch("posthog.api.user_integration.requests.get")
+ @patch("posthog.models.integration.GitHubIntegration.client_request")
+ @patch("posthog.models.integration.GitHubIntegration.github_user_from_code")
+ def test_github_link_oauth_callback_ignores_query_installation_id_when_state_binds_one(
+ self, mock_user_from_code, mock_client_request, mock_verify_get
+ ):
+ # PERSONAL_OAUTH binds ``installation_id`` in the authorize cache. A
+ # tampered ``installation_id`` query param must not steer the resulting
+ # UserIntegration to a different installation.
+ mock_verify_get.return_value = MagicMock(status_code=200)
+ mock_user_from_code.return_value = _authorization()
+ mock_install_info = MagicMock()
+ mock_install_info.json.return_value = {"account": {"type": "User", "login": "octocat"}}
+ mock_access_token = MagicMock()
+ mock_access_token.json.return_value = {
+ "token": "ghs_install_token",
+ "expires_at": "2099-01-01T00:00:00Z",
+ "repository_selection": "selected",
+ }
+ mock_client_request.side_effect = [mock_install_info, mock_access_token]
+
+ Integration.objects.create(
+ team=self.team,
+ kind="github",
+ integration_id="12345",
+ config={},
+ sensitive_config={},
+ created_by=self.user,
+ )
+ state = "tok_oauth_mismatch"
+ store_unified_authorize_state(
+ GitHubAuthorizeState(
+ token=state,
+ flow=FlowKind.PERSONAL_OAUTH,
+ user_id=self.user.id,
+ installation_id="12345",
+ ),
+ )
+ state_q = urlencode({"token": state, "source": "user_integration"})
+
+ response = self.client.get(
+ "/complete/github-link/",
+ {"code": "test_code", "state": state_q, "installation_id": "999"},
+ )
+
+ self.assertEqual(response.status_code, 302)
+ self.assertIn("github_link_success=1", response["Location"])
+ self.assertTrue(UserIntegration.objects.filter(user=self.user, integration_id="12345").exists())
+ self.assertFalse(UserIntegration.objects.filter(integration_id="999").exists())
+ # The installation-access check went against the cached id, not the query one.
+ verify_url = mock_verify_get.call_args[0][0]
+ self.assertIn("/installations/12345/repositories", verify_url)
+ self.assertNotIn("/installations/999/repositories", verify_url)
+
@override_settings(
GITHUB_APP_CLIENT_ID="client_id",
GITHUB_APP_CLIENT_SECRET="client_secret",
@@ -405,10 +468,13 @@ class TestUserIntegrationEndpoints(APIBaseTest):
mock_client_request.side_effect = [mock_install_info, mock_access_token]
state = "tok_oauth_discover_123"
- cache.set(
- f"github_user_install_state:{state}",
- {"user_id": self.user.id, "connect_from": "posthog_code", "flow": "oauth_discover"},
- timeout=600,
+ store_unified_authorize_state(
+ GitHubAuthorizeState(
+ token=state,
+ flow=FlowKind.OAUTH_DISCOVER,
+ user_id=self.user.id,
+ connect_from="posthog_code",
+ ),
)
response = self.client.get(
@@ -431,7 +497,7 @@ class TestUserIntegrationEndpoints(APIBaseTest):
SITE_URL="https://us.posthog.com",
)
@patch(
- "posthog.api.github_callback.personal_state.get_instance_settings",
+ "posthog.api.github_callback.types.get_instance_settings",
return_value={"GITHUB_APP_SLUG": "posthog-dev"},
)
@patch("posthog.api.user_integration.requests.get")
@@ -446,10 +512,13 @@ class TestUserIntegrationEndpoints(APIBaseTest):
)
state = "tok_oauth_discover_empty"
- cache.set(
- f"github_user_install_state:{state}",
- {"user_id": self.user.id, "connect_from": "posthog_code", "flow": "oauth_discover"},
- timeout=600,
+ store_unified_authorize_state(
+ GitHubAuthorizeState(
+ token=state,
+ flow=FlowKind.OAUTH_DISCOVER,
+ user_id=self.user.id,
+ connect_from="posthog_code",
+ ),
)
response = self.client.get(
@@ -482,7 +551,9 @@ class TestUserIntegrationEndpoints(APIBaseTest):
mock_client_request.side_effect = [mock_install_info, mock_access_token]
state = "test_state_123"
- cache.set(f"github_user_install_state:{state}", {"user_id": self.user.id}, timeout=600)
+ store_unified_authorize_state(
+ GitHubAuthorizeState(token=state, flow=FlowKind.PERSONAL_INSTALL, user_id=self.user.id),
+ )
response = self.client.get(
"/complete/github-link/",
@@ -532,10 +603,13 @@ class TestUserIntegrationEndpoints(APIBaseTest):
mock_client_request.side_effect = [mock_install_info, mock_access_token]
state = f"test_state_{connect_from}"
- cache.set(
- f"github_user_install_state:{state}",
- {"user_id": self.user.id, "connect_from": connect_from},
- timeout=600,
+ store_unified_authorize_state(
+ GitHubAuthorizeState(
+ token=state,
+ flow=FlowKind.PERSONAL_INSTALL,
+ user_id=self.user.id,
+ connect_from=connect_from,
+ ),
)
response = self.client.get(
@@ -552,10 +626,13 @@ class TestUserIntegrationEndpoints(APIBaseTest):
def test_github_link_redirects_to_mobile_deep_link_with_error(self):
"""When GitHub returns an error, the mobile deep link still carries provider + error."""
state = "test_state_posthog_mobile_error"
- cache.set(
- f"github_user_install_state:{state}",
- {"user_id": self.user.id, "connect_from": "posthog_mobile"},
- timeout=600,
+ store_unified_authorize_state(
+ GitHubAuthorizeState(
+ token=state,
+ flow=FlowKind.PERSONAL_INSTALL,
+ user_id=self.user.id,
+ connect_from="posthog_mobile",
+ ),
)
response = self.client.get(
@@ -570,7 +647,9 @@ class TestUserIntegrationEndpoints(APIBaseTest):
self.assertIn("error=access_denied", loc)
def test_github_link_callback_rejects_mismatched_state(self):
- cache.set("github_user_install_state:valid_state", {"user_id": self.user.id}, timeout=600)
+ store_unified_authorize_state(
+ GitHubAuthorizeState(token="valid_state", flow=FlowKind.PERSONAL_INSTALL, user_id=self.user.id),
+ )
response = self.client.get(
"/complete/github-link/",
{"installation_id": "123", "code": "test_code", "state": "wrong_state"},
@@ -583,6 +662,36 @@ class TestUserIntegrationEndpoints(APIBaseTest):
self.assertEqual(response.status_code, 302)
self.assertIn("github_link_error=missing_params", response["Location"])
+ @override_settings(GITHUB_APP_CLIENT_ID="client_id", SITE_URL="https://us.posthog.com")
+ def test_github_link_personal_install_without_code_recovers_via_oauth_discover(self):
+ # GitHub omits the OAuth code when the App is already installed, returning a
+ # setup update (installation_id, setup_action=update) instead. The callback
+ # must bounce through OAuth-discover to obtain a code rather than erroring.
+ store_unified_authorize_state(
+ GitHubAuthorizeState(
+ token="tok_already_installed",
+ flow=FlowKind.PERSONAL_INSTALL,
+ user_id=self.user.id,
+ connect_from="posthog_code",
+ ),
+ )
+
+ response = self.client.get(
+ "/complete/github-link/",
+ {"installation_id": "75826265", "setup_action": "update", "state": "token=tok_already_installed"},
+ )
+
+ self.assertEqual(response.status_code, 302)
+ self.assertIn("github.com/login/oauth/authorize", response["Location"])
+
+ discover_state_param = parse_qs(urlparse(response["Location"]).query)["state"][0]
+ discover_token, _ = parse_github_authorize_state_param(discover_state_param)
+ assert discover_token is not None
+ discover_state = load_authorize_state(discover_token, user_id=self.user.id)
+ assert discover_state is not None
+ self.assertEqual(discover_state.flow, FlowKind.OAUTH_DISCOVER)
+ self.assertEqual(discover_state.connect_from, "posthog_code")
+
@override_settings(GITHUB_APP_CLIENT_ID="client_id", GITHUB_APP_CLIENT_SECRET="client_secret")
@patch("posthog.models.integration.GitHubIntegration.integration_from_installation_id")
@patch("posthog.api.user_integration.requests.get")
@@ -608,6 +717,10 @@ class TestUserIntegrationEndpoints(APIBaseTest):
}
mock_client_request.side_effect = [mock_install_info, mock_access_token]
+ # Writing a team integration requires admin-level access.
+ self.organization_membership.level = OrganizationMembership.Level.ADMIN
+ self.organization_membership.save()
+
team_integration = Integration.objects.create(
team=self.team,
kind="github",
@@ -619,16 +732,15 @@ class TestUserIntegrationEndpoints(APIBaseTest):
mock_integration_from_install.return_value = team_integration
state = "tok_team_oauth_123"
- cache.set(
- f"github_user_install_state:{state}",
- {
- "user_id": self.user.id,
- "team_id": self.team.pk,
- "installation_id": "12345",
- "flow": "team_oauth_authorize",
- "next": "/project/{}/settings/project-integrations".format(self.team.pk),
- },
- timeout=600,
+ store_unified_authorize_state(
+ GitHubAuthorizeState(
+ token=state,
+ flow=FlowKind.TEAM_OAUTH,
+ user_id=self.user.id,
+ team_id=self.team.pk,
+ installation_id="12345",
+ next_url="/project/{}/settings/project-integrations".format(self.team.pk),
+ ),
)
response = self.client.get(
@@ -648,28 +760,6 @@ class TestUserIntegrationEndpoints(APIBaseTest):
self.assertIn("installation_id=12345", location)
self.assertIn(f"integration_id={team_integration.id}", location)
- def test_github_link_callback_team_oauth_authorize_rejects_user_outside_team(self):
- state = "tok_team_outside"
- # Random team_id that the user doesn't belong to.
- cache.set(
- f"github_user_install_state:{state}",
- {
- "user_id": self.user.id,
- "team_id": 999_999,
- "installation_id": "12345",
- "flow": "team_oauth_authorize",
- },
- timeout=600,
- )
-
- response = self.client.get(
- "/complete/github-link/",
- {"code": "test_code", "state": state},
- )
-
- self.assertEqual(response.status_code, 302)
- self.assertIn("github_link_error=invalid_team", response["Location"])
-
class TestGetGithubLoginPrecedence(APIBaseTest):
"""User.get_github_login() precedence: UserIntegration > UserSocialAuth > team-level GitHub Integration."""
diff --git a/posthog/api/user_integration.py b/posthog/api/user_integration.py
index 45f1356895ea..257e4b9cc01a 100644
--- a/posthog/api/user_integration.py
+++ b/posthog/api/user_integration.py
@@ -11,11 +11,10 @@ Login management is fully handled by ``UserSocialAuth`` (python-social-auth) and
is not controlled here.
"""
+import os
from typing import Any, cast
from urllib.parse import urlencode
-from django.core.cache import cache
-
import requests
import structlog
from drf_spectacular.types import OpenApiTypes
@@ -26,11 +25,14 @@ from rest_framework.permissions import IsAuthenticated
from rest_framework.request import Request
from rest_framework.response import Response
-from posthog.api.github_callback.personal_state import github_app_install_url, github_oauth_authorize_url
+from posthog.api.github_callback import state as github_callback_state
from posthog.api.github_callback.types import (
APP_CONNECT_FROM_VALUES,
- GITHUB_INSTALL_STATE_CACHE_PREFIX,
- GITHUB_INSTALL_STATE_TTL_SECONDS,
+ PERSONAL_INTEGRATIONS_SETTINGS_PATH,
+ FlowKind,
+ GitHubAuthorizeState,
+ github_app_install_url,
+ github_oauth_authorize_url,
)
from posthog.api.integration import (
GitHubBranchesQuerySerializer,
@@ -95,6 +97,10 @@ class UserGitHubIntegrationListResponseSerializer(serializers.Serializer):
)
+class UserGitHubPrepareCallbackRequestSerializer(serializers.Serializer):
+ installation_id = serializers.CharField(help_text="GitHub App installation id being managed on github.com.")
+
+
class UserGitHubLinkStartRequestSerializer(serializers.Serializer):
team_id = serializers.IntegerField(
required=False,
@@ -210,6 +216,7 @@ class UserIntegrationViewSet(viewsets.GenericViewSet):
"patch",
"destroy",
"github_start",
+ "github_prepare_callback",
"github_destroy",
"github_repos_refresh",
"slack_start",
@@ -453,10 +460,13 @@ class UserIntegrationViewSet(viewsets.GenericViewSet):
if connect_from in APP_CONNECT_FROM_VALUES:
if _team_github_installation_id(team) is None:
- cache.set(
- f"{GITHUB_INSTALL_STATE_CACHE_PREFIX}{token}",
- {"user_id": user.id, "connect_from": connect_from, "flow": "oauth_discover"},
- timeout=GITHUB_INSTALL_STATE_TTL_SECONDS,
+ github_callback_state.store_unified_authorize_state(
+ GitHubAuthorizeState(
+ token=token,
+ flow=FlowKind.OAUTH_DISCOVER,
+ user_id=user.id,
+ connect_from=connect_from,
+ ),
)
return Response({"install_url": github_oauth_authorize_url(state), "connect_flow": "oauth_discover"})
@@ -469,13 +479,13 @@ class UserIntegrationViewSet(viewsets.GenericViewSet):
"All GitHub App installations accessible to your account are already linked."
)
- 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,
+ github_callback_state.store_unified_authorize_state(
+ GitHubAuthorizeState(
+ token=token,
+ flow=FlowKind.PERSONAL_INSTALL,
+ user_id=user.id,
+ connect_from=str(connect_from) if connect_from else None,
+ ),
)
return Response(
{
@@ -484,6 +494,28 @@ class UserIntegrationViewSet(viewsets.GenericViewSet):
}
)
+ @extend_schema(
+ request=UserGitHubPrepareCallbackRequestSerializer, responses={204: OpenApiResponse(description="No content")}
+ )
+ @action(methods=["POST"], detail=False, url_path="github/prepare_callback")
+ def github_prepare_callback(self, request: Request, **_kwargs) -> Response:
+ """Seed personal GitHub manage callback state before opening installation settings on GitHub."""
+ serializer = UserGitHubPrepareCallbackRequestSerializer(data=request.data)
+ serializer.is_valid(raise_exception=True)
+ installation_id = str(serializer.validated_data["installation_id"])
+ user = self._get_user()
+ token = os.urandom(33).hex()
+ github_callback_state.store_unified_authorize_state(
+ GitHubAuthorizeState(
+ token=token,
+ flow=FlowKind.PERSONAL_UPDATE,
+ user_id=user.id,
+ installation_id=installation_id,
+ next_url=PERSONAL_INTEGRATIONS_SETTINGS_PATH,
+ ),
+ )
+ return Response(status=204)
+
@extend_schema(
summary="List Slack workspaces this user could link to",
responses={200: UserSlackLinkableWorkspaceListResponseSerializer},
@@ -728,15 +760,14 @@ def _attempt_app_oauth_fast_path(
return None
if UserIntegration.objects.filter(user=user, kind="github", integration_id=team_installation_id).exists():
return None
- cache.set(
- f"{GITHUB_INSTALL_STATE_CACHE_PREFIX}{token}",
- {
- "user_id": user.id,
- "installation_id": team_installation_id,
- "flow": "oauth_authorize",
- "connect_from": connect_from,
- },
- timeout=GITHUB_INSTALL_STATE_TTL_SECONDS,
+ github_callback_state.store_unified_authorize_state(
+ GitHubAuthorizeState(
+ token=token,
+ flow=FlowKind.PERSONAL_OAUTH,
+ user_id=user.id,
+ installation_id=team_installation_id,
+ connect_from=connect_from,
+ ),
)
return Response({"install_url": github_oauth_authorize_url(state), "connect_flow": "oauth_authorize"})
diff --git a/posthog/models/integration.py b/posthog/models/integration.py
index bc67b521819f..8a58077bdf3e 100644
--- a/posthog/models/integration.py
+++ b/posthog/models/integration.py
@@ -8,7 +8,7 @@ import hashlib
from collections.abc import Iterable
from dataclasses import dataclass
from datetime import datetime, timedelta
-from typing import TYPE_CHECKING, Any, Literal, NamedTuple, NoReturn, Optional
+from typing import TYPE_CHECKING, Any, Literal, NamedTuple, NoReturn, Optional, Self
from urllib.parse import urlencode
from products.workflows.backend.providers import MAILDEV_MOCK_DNS_RECORDS
@@ -21,6 +21,7 @@ if TYPE_CHECKING:
from django.conf import settings
from django.db import models, transaction
+from django.db.models import Q
from django.http import HttpRequest
from django.utils import timezone
@@ -178,6 +179,38 @@ def _raise_oauth_validation_error(kind: str, res: requests.Response) -> NoReturn
ERROR_TOKEN_REFRESH_FAILED = "TOKEN_REFRESH_FAILED"
+class IntegrationQuerySet(models.QuerySet["Integration"]):
+ def for_github_installation_id(self, installation_id: str | int) -> Self:
+ return self.filter(
+ Q(config__installation_id=str(installation_id)) | Q(config__installation_id=int(installation_id))
+ )
+
+
+class IntegrationManager(models.Manager["Integration"]):
+ _queryset_class = IntegrationQuerySet
+
+ def get_queryset(self) -> IntegrationQuerySet:
+ return IntegrationQuerySet(self.model, using=self._db)
+
+ def filter(self, *args: Any, **kwargs: Any) -> IntegrationQuerySet:
+ return self.get_queryset().filter(*args, **kwargs)
+
+ def first_github_for_team_installation(self, team_id: int, installation_id: str) -> "Integration | None":
+ return (
+ self.filter(team_id=team_id, kind=Integration.IntegrationKind.GITHUB)
+ .for_github_installation_id(installation_id)
+ .first()
+ )
+
+ def first_github_for_user_installation(self, user: User, installation_id: str) -> "Integration | None":
+ user_team_ids = user.teams.values_list("id", flat=True)
+ return (
+ self.filter(team_id__in=user_team_ids, kind=Integration.IntegrationKind.GITHUB)
+ .for_github_installation_id(installation_id)
+ .first()
+ )
+
+
class Integration(models.Model):
class IntegrationKind(models.TextChoices):
ANTHROPIC = "anthropic"
@@ -247,6 +280,8 @@ class Integration(models.Model):
created_at = models.DateTimeField(auto_now_add=True, blank=True)
created_by = models.ForeignKey("User", on_delete=models.SET_NULL, null=True, blank=True)
+ objects: IntegrationManager = IntegrationManager()
+
class Meta:
constraints = [
models.UniqueConstraint(
@@ -2399,28 +2434,72 @@ class GitHubInstallationAccess:
repository_selection: str
+class GitHubInstallationAccessFetchError(Exception):
+ def __init__(self, code: str) -> None:
+ self.code = code
+ super().__init__(code)
+
+
+def invalidate_github_repository_caches_for_installation(installation_id: str | int) -> None:
+ """Affects both team Integration and personal UserIntegration rows."""
+ from posthog.models.user_integration import UserIntegration
+
+ installation_id_str = str(installation_id)
+ Integration.objects.filter(kind="github", integration_id=installation_id_str).update(
+ repository_cache_updated_at=None
+ )
+ UserIntegration.objects.filter(
+ kind=UserIntegration.IntegrationKind.GITHUB,
+ integration_id=installation_id_str,
+ ).update(repository_cache_updated_at=None)
+
+
class GitHubIntegration(GitHubIntegrationBase):
integration: Integration
+ @classmethod
+ def fetch_installation_access(cls, installation_id: str) -> GitHubInstallationAccess:
+ try:
+ installation_info = cls.client_request(f"installations/{installation_id}").json()
+ access_token_response = cls.client_request(
+ f"installations/{installation_id}/access_tokens", method="POST"
+ ).json()
+ except Exception as exc:
+ raise GitHubInstallationAccessFetchError("installation_fetch_failed") from exc
+
+ installation_access_token = access_token_response.get("token")
+ token_expires_at = access_token_response.get("expires_at")
+ if not installation_access_token or not token_expires_at:
+ raise GitHubInstallationAccessFetchError("installation_token_failed")
+
+ return 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"),
+ )
+
@classmethod
def integration_from_installation_id(
cls, installation_id: str, team_id: int, created_by: User | None = None
) -> Integration:
- installation_info = cls.client_request(f"installations/{installation_id}").json()
- access_token = cls.client_request(f"installations/{installation_id}/access_tokens", method="POST").json()
+ installation_access = cls.fetch_installation_access(installation_id)
+ now = int(time.time())
+ expires_in = int(datetime.fromisoformat(installation_access.token_expires_at).timestamp() - now)
config = {
"installation_id": installation_id,
- "expires_in": datetime.fromisoformat(access_token["expires_at"]).timestamp() - int(time.time()),
- "refreshed_at": int(time.time()),
- "repository_selection": access_token["repository_selection"],
+ "expires_in": expires_in,
+ "refreshed_at": now,
+ "repository_selection": installation_access.repository_selection,
"account": {
- "type": dot_get(installation_info, "account.type", None),
- "name": dot_get(installation_info, "account.login", installation_id),
+ "type": dot_get(installation_access.installation_info, "account.type", None),
+ "name": dot_get(installation_access.installation_info, "account.login", installation_id),
},
}
- sensitive_config = {"access_token": access_token["token"]}
+ sensitive_config = {"access_token": installation_access.access_token}
integration, created = Integration.objects.update_or_create(
team_id=team_id,
@@ -2437,6 +2516,8 @@ class GitHubIntegration(GitHubIntegrationBase):
integration.errors = ""
integration.save()
+ invalidate_github_repository_caches_for_installation(installation_id)
+
return integration
@classmethod
diff --git a/posthog/models/test/test_integration_model.py b/posthog/models/test/test_integration_model.py
index 5fe94920e871..cfabba5f8aba 100644
--- a/posthog/models/test/test_integration_model.py
+++ b/posthog/models/test/test_integration_model.py
@@ -42,6 +42,7 @@ from posthog.models.integration import (
S3CompatibleIntegration,
S3CredentialIntegrationError,
SlackIntegration,
+ invalidate_github_repository_caches_for_installation,
raise_if_github_rate_limited,
)
from posthog.models.organization import Organization
@@ -1462,6 +1463,36 @@ class TestGitHubIntegrationModel(BaseTest):
assert integration.repository_cache_updated_at is None
mock_list_all.assert_called_once_with()
+ def test_invalidate_github_repository_caches_for_installation_clears_team_and_personal_rows(self):
+ from posthog.models.user_integration import UserIntegration
+
+ team_integration = self.create_integration(
+ {"installation_id": "12345", "account": {"name": "PostHog"}},
+ {"access_token": "ACCESS_TOKEN"},
+ )
+ team_integration.integration_id = "12345"
+ team_integration.repository_cache = [{"id": 1, "name": "a", "full_name": "org/a"}]
+ team_integration.repository_cache_updated_at = timezone.now()
+ team_integration.save(update_fields=["integration_id", "repository_cache", "repository_cache_updated_at"])
+
+ user_integration = UserIntegration.objects.create(
+ user=self.user,
+ kind=UserIntegration.IntegrationKind.GITHUB,
+ integration_id="12345",
+ config={"installation_id": "12345"},
+ sensitive_config={"access_token": "ACCESS_TOKEN"},
+ repository_cache=[{"id": 2, "name": "b", "full_name": "org/b"}],
+ repository_cache_updated_at=timezone.now(),
+ )
+
+ invalidate_github_repository_caches_for_installation("12345")
+
+ team_integration = Integration.objects.get(pk=team_integration.pk)
+ user_integration = UserIntegration.objects.get(pk=user_integration.pk)
+ assert team_integration.repository_cache_updated_at is None
+ assert user_integration.repository_cache_updated_at is None
+ assert team_integration.repository_cache == [{"id": 1, "name": "a", "full_name": "org/a"}]
+
@patch("posthog.models.integration.GitHubIntegration.list_all_repositories")
def test_list_cached_repositories_pages_with_full_cached_snapshot(self, mock_list_all):
fetched_repositories = [{"id": i, "name": f"repo-{i}", "full_name": f"PostHog/repo-{i}"} for i in range(650)]
diff --git a/posthog/models/user_integration.py b/posthog/models/user_integration.py
index edc6d63bbba7..f01c0437d755 100644
--- a/posthog/models/user_integration.py
+++ b/posthog/models/user_integration.py
@@ -10,6 +10,7 @@ import structlog
from posthog.helpers.encrypted_fields import EncryptedJSONField
from posthog.models.github_integration_base import GitHubIntegrationBase
+from posthog.models.integration import invalidate_github_repository_caches_for_installation
from posthog.models.utils import UUIDModel
if TYPE_CHECKING:
@@ -334,8 +335,7 @@ def user_github_integration_from_installation(
"""
now = int(time.time())
try:
- raw_expires = installation.token_expires_at
- expires_in = int(datetime.fromisoformat(raw_expires.replace("Z", "+00:00")).timestamp() - now)
+ expires_in = int(datetime.fromisoformat(installation.token_expires_at).timestamp() - now)
except (ValueError, AttributeError):
expires_in = 3600
@@ -382,6 +382,43 @@ def user_github_integration_from_installation(
"sensitive_config": sensitive_config,
},
)
+ invalidate_github_repository_caches_for_installation(installation.installation_id)
+ return integration
+
+
+def refresh_user_github_installation_access(
+ integration: UserIntegration,
+ installation: "GitHubInstallationAccess",
+) -> UserIntegration:
+ """Refresh installation token metadata without overwriting stored user OAuth credentials."""
+ now = int(time.time())
+ try:
+ expires_in = int(datetime.fromisoformat(installation.token_expires_at).timestamp() - now)
+ except (ValueError, AttributeError):
+ expires_in = 3600
+
+ config = dict(integration.config)
+ config.update(
+ {
+ "expires_in": expires_in,
+ "refreshed_at": now,
+ "repository_selection": installation.repository_selection,
+ "account": {
+ "type": (installation.installation_info.get("account") or {}).get("type"),
+ "name": (installation.installation_info.get("account") or {}).get(
+ "login", installation.installation_id
+ ),
+ },
+ }
+ )
+
+ sensitive_config = dict(integration.sensitive_config)
+ sensitive_config["access_token"] = installation.access_token
+
+ integration.config = config
+ integration.sensitive_config = sensitive_config
+ integration.save(update_fields=["config", "sensitive_config"])
+ invalidate_github_repository_caches_for_installation(installation.installation_id)
return integration
diff --git a/posthog/temporal/tests/product_analytics/__snapshots__/test_upgrade_queries_workflow.ambr b/posthog/temporal/tests/product_analytics/__snapshots__/test_upgrade_queries_workflow.ambr
index a1c0325ab25a..0839c952c78f 100644
--- a/posthog/temporal/tests/product_analytics/__snapshots__/test_upgrade_queries_workflow.ambr
+++ b/posthog/temporal/tests/product_analytics/__snapshots__/test_upgrade_queries_workflow.ambr
@@ -11,14 +11,6 @@
OR query @? '$.** ? (
@.kind == "InsightVizNode" &&
(!exists(@.version) || @.version == null || @.version < 4)
- )'
- OR query @? '$.** ? (
- @.kind == "RetentionQuery" &&
- (!exists(@.version) || @.version == null || @.version < 2)
- )'
- OR query @? '$.** ? (
- @.kind == "StickinessQuery" &&
- (!exists(@.version) || @.version == null || @.version < 2)
)'
OR query @? '$.** ? (
@.kind == "TrendsQuery" &&
diff --git a/posthog/urls.py b/posthog/urls.py
index d7d8af602371..8d009d350a57 100644
--- a/posthog/urls.py
+++ b/posthog/urls.py
@@ -29,7 +29,7 @@ from posthog.api import (
uploaded_media,
user,
)
-from posthog.api.github_callback.personal_finish import github_link_complete
+from posthog.api.github_callback.views import github_oauth_callback, github_setup_callback
from posthog.api.oauth.connected_apps import ConnectedAppsViewSet
from posthog.api.oauth.raycast_metadata import RAYCAST_METADATA_PATH, RaycastClientMetadataView
from posthog.api.oauth.wizard_metadata import WIZARD_METADATA_PATH, WizardClientMetadataView
@@ -451,7 +451,10 @@ urlpatterns = [
), # overrides from `social_django.urls` to validate proper license
# GitHub account linking (identity-only, separate from the login pipeline).
# Must precede `social_django.urls` so the latter's `complete/<str:backend>/` doesn't swallow it.
- path("complete/github-link/", github_link_complete, name="github_link_complete"),
+ path("complete/github-link/", github_oauth_callback, name="github_link_complete"),
+ opt_slash_path(
+ "integrations/github/callback", github_setup_callback, name="github_team_integration_setup_callback"
+ ),
# Slack user-identity linking — mirrors the GitHub per-user pattern above,
# and likewise must precede `social_django.urls` for the same reason.
path("complete/slack-link/start/", slack_user_link_authorize, name="slack_link_start"),
diff --git a/posthog/user_permissions.py b/posthog/user_permissions.py
index 48ae81823f3c..fd423ebf4cdc 100644
--- a/posthog/user_permissions.py
+++ b/posthog/user_permissions.py
@@ -376,3 +376,16 @@ class UserPermissionsSerializerMixin:
if "user_permissions" in self.context:
return self.context["user_permissions"]
return self.context["view"].user_permissions
+
+
+def user_is_team_admin(user: User, team: Team | int) -> bool:
+ team_obj: Team
+ if isinstance(team, int):
+ try:
+ team_obj = Team.objects.get(id=team)
+ except Team.DoesNotExist:
+ return False
+ else:
+ team_obj = team
+ level = UserPermissions(user).team(team_obj).effective_membership_level
+ return level is not None and level >= OrganizationMembership.Level.ADMIN
diff --git a/products/integrations/frontend/generated/api.schemas.ts b/products/integrations/frontend/generated/api.schemas.ts
index 7565b6015ad2..a1ebf5af1e4a 100644
--- a/products/integrations/frontend/generated/api.schemas.ts
+++ b/products/integrations/frontend/generated/api.schemas.ts
@@ -351,6 +351,48 @@ export interface GoogleSearchConsoleSitesResponseApi {
sites: GoogleSearchConsoleSiteApi[]
}
+export interface GitHubLinkExistingRequestApi {
+ /**
+ * Sibling team in the same organization whose GitHub installation should be reused.
+ * @nullable
+ */
+ source_team_id?: number | null
+ /** GitHub installation ID to link; resolved within the organization when source_team_id is omitted. */
+ installation_id?: string
+}
+
+/**
+ * * `posthog_code` - posthog_code
+ */
+export type ConnectFromEnumApi = (typeof ConnectFromEnumApi)[keyof typeof ConnectFromEnumApi]
+
+export const ConnectFromEnumApi = {
+ PosthogCode: 'posthog_code',
+} as const
+
+export interface GitHubOAuthAuthorizeRequestApi {
+ /** GitHub installation ID to carry through the User OAuth flow. */
+ installation_id?: string
+ /** Relative URL to redirect to after the OAuth flow completes. */
+ next?: string
+ /** Originating surface for the connect flow; only 'posthog_code' is recognized.
+ *
+ * * `posthog_code` - posthog_code */
+ connect_from?: ConnectFromEnumApi
+}
+
+export interface GitHubOAuthAuthorizeResponseApi {
+ /** GitHub User OAuth URL the client should redirect to. */
+ oauth_url: string
+}
+
+export interface GitHubPrepareCallbackRequestApi {
+ /** Relative URL to redirect to after GitHub setup completes (e.g. account-connected for PostHog Code). */
+ next?: string
+ /** GitHub installation ID being managed; binds the seeded update state so a callback can't swap in a different installation. */
+ installation_id?: string
+}
+
export interface IntegrationAccessRequestApi {
/** The kind of integration the member is requesting be connected (e.g. 'slack', 'github').
*
diff --git a/products/integrations/frontend/generated/api.ts b/products/integrations/frontend/generated/api.ts
index f22877f6f755..e80f5a4b8064 100644
--- a/products/integrations/frontend/generated/api.ts
+++ b/products/integrations/frontend/generated/api.ts
@@ -10,6 +10,10 @@ import { apiMutator } from '../../../../frontend/src/lib/api-orval-mutator'
*/
import type {
GitHubBranchesResponseApi,
+ GitHubLinkExistingRequestApi,
+ GitHubOAuthAuthorizeRequestApi,
+ GitHubOAuthAuthorizeResponseApi,
+ GitHubPrepareCallbackRequestApi,
GitHubReposRefreshResponseApi,
GitHubReposResponseApi,
GitHubTeamsResponseApi,
@@ -694,14 +698,14 @@ export const getIntegrationsGithubLinkExistingCreateUrl = (projectId: string) =>
*/
export const integrationsGithubLinkExistingCreate = async (
projectId: string,
- integrationConfigApi: NonReadonly<IntegrationConfigApi>,
+ gitHubLinkExistingRequestApi?: GitHubLinkExistingRequestApi,
options?: RequestInit
-): Promise<void> => {
- return apiMutator<void>(getIntegrationsGithubLinkExistingCreateUrl(projectId), {
+): Promise<IntegrationConfigApi> => {
+ return apiMutator<IntegrationConfigApi>(getIntegrationsGithubLinkExistingCreateUrl(projectId), {
...options,
method: 'POST',
headers: { 'Content-Type': 'application/json', ...options?.headers },
- body: JSON.stringify(integrationConfigApi),
+ body: JSON.stringify(gitHubLinkExistingRequestApi),
})
}
@@ -714,14 +718,37 @@ export const getIntegrationsGithubOauthAuthorizeCreateUrl = (projectId: string)
*/
export const integrationsGithubOauthAuthorizeCreate = async (
projectId: string,
- integrationConfigApi: NonReadonly<IntegrationConfigApi>,
+ gitHubOAuthAuthorizeRequestApi?: GitHubOAuthAuthorizeRequestApi,
+ options?: RequestInit
+): Promise<GitHubOAuthAuthorizeResponseApi> => {
+ return apiMutator<GitHubOAuthAuthorizeResponseApi>(getIntegrationsGithubOauthAuthorizeCreateUrl(projectId), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(gitHubOAuthAuthorizeRequestApi),
+ })
+}
+
+export const getIntegrationsGithubPrepareCallbackCreateUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/integrations/github/prepare_callback/`
+}
+
+/**
+ * Seed GitHub setup callback state without redirecting to GitHub.
+ *
+ * Used when the user opens an existing installation's settings on github.com (e.g. PostHog
+ * Code "Update in GitHub") so the subsequent Setup URL redirect can be validated.
+ */
+export const integrationsGithubPrepareCallbackCreate = async (
+ projectId: string,
+ gitHubPrepareCallbackRequestApi?: GitHubPrepareCallbackRequestApi,
options?: RequestInit
): Promise<void> => {
- return apiMutator<void>(getIntegrationsGithubOauthAuthorizeCreateUrl(projectId), {
+ return apiMutator<void>(getIntegrationsGithubPrepareCallbackCreateUrl(projectId), {
...options,
method: 'POST',
headers: { 'Content-Type': 'application/json', ...options?.headers },
- body: JSON.stringify(integrationConfigApi),
+ body: JSON.stringify(gitHubPrepareCallbackRequestApi),
})
}
diff --git a/products/integrations/frontend/generated/api.zod.ts b/products/integrations/frontend/generated/api.zod.ts
index 134c0e94d170..68f3f4bc0d15 100644
--- a/products/integrations/frontend/generated/api.zod.ts
+++ b/products/integrations/frontend/generated/api.zod.ts
@@ -273,110 +273,52 @@ export const IntegrationsDomainConnectApplyUrlCreateBody = /* @__PURE__ */ zod
/**
* Reuse a GitHub installation already linked to a sibling team in the same organization.
*/
-export const IntegrationsGithubLinkExistingCreateBody = /* @__PURE__ */ zod
- .object({
- kind: zod
- .enum([
- 'anthropic',
- 'apns',
- 'aws-s3',
- 'azure-blob',
- 'bing-ads',
- 'clickup',
- 'customerio-app',
- 'customerio-track',
- 'customerio-webhook',
- 'databricks',
- 'email',
- 'firebase',
- 'github',
- 'gitlab',
- 'google-ads',
- 'google-analytics',
- 'google-cloud-service-account',
- 'google-cloud-storage',
- 'google-pubsub',
- 'google-search-console',
- 'google-sheets',
- 'hubspot',
- 'intercom',
- 'jira',
- 'linear',
- 'linkedin-ads',
- 'meta-ads',
- 'pinterest-ads',
- 'postgresql',
- 'reddit-ads',
- 's3-compatible',
- 'salesforce',
- 'slack',
- 'slack-posthog-code',
- 'snapchat',
- 'stripe',
- 'tiktok-ads',
- 'twilio',
- 'vercel',
- ])
- .describe(
- '\* `anthropic` - Anthropic\n\* `apns` - Apple Push\n\* `aws-s3` - Aws S3\n\* `azure-blob` - Azure Blob\n\* `bing-ads` - Bing Ads\n\* `clickup` - Clickup\n\* `customerio-app` - Customerio App\n\* `customerio-track` - Customerio Track\n\* `customerio-webhook` - Customerio Webhook\n\* `databricks` - Databricks\n\* `email` - Email\n\* `firebase` - Firebase\n\* `github` - Github\n\* `gitlab` - Gitlab\n\* `google-ads` - Google Ads\n\* `google-analytics` - Google Analytics\n\* `google-cloud-service-account` - Google Cloud Service Account\n\* `google-cloud-storage` - Google Cloud Storage\n\* `google-pubsub` - Google Pubsub\n\* `google-search-console` - Google Search Console\n\* `google-sheets` - Google Sheets\n\* `hubspot` - Hubspot\n\* `intercom` - Intercom\n\* `jira` - Jira\n\* `linear` - Linear\n\* `linkedin-ads` - Linkedin Ads\n\* `meta-ads` - Meta Ads\n\* `pinterest-ads` - Pinterest Ads\n\* `postgresql` - Postgresql\n\* `reddit-ads` - Reddit Ads\n\* `s3-compatible` - S3 Compatible\n\* `salesforce` - Salesforce\n\* `slack` - Slack\n\* `slack-posthog-code` - Slack Posthog Code\n\* `snapchat` - Snapchat\n\* `stripe` - Stripe\n\* `tiktok-ads` - Tiktok Ads\n\* `twilio` - Twilio\n\* `vercel` - Vercel'
- ),
- config: zod.unknown().optional(),
- })
- .describe('Standard Integration serializer.')
+export const IntegrationsGithubLinkExistingCreateBody = /* @__PURE__ */ zod.object({
+ source_team_id: zod
+ .number()
+ .nullish()
+ .describe('Sibling team in the same organization whose GitHub installation should be reused.'),
+ installation_id: zod
+ .string()
+ .optional()
+ .describe('GitHub installation ID to link; resolved within the organization when source_team_id is omitted.'),
+})
/**
* Mint a User OAuth URL to bootstrap a fresh `code` when the install flow returns without one.
*/
-export const IntegrationsGithubOauthAuthorizeCreateBody = /* @__PURE__ */ zod
- .object({
- kind: zod
- .enum([
- 'anthropic',
- 'apns',
- 'aws-s3',
- 'azure-blob',
- 'bing-ads',
- 'clickup',
- 'customerio-app',
- 'customerio-track',
- 'customerio-webhook',
- 'databricks',
- 'email',
- 'firebase',
- 'github',
- 'gitlab',
- 'google-ads',
- 'google-analytics',
- 'google-cloud-service-account',
- 'google-cloud-storage',
- 'google-pubsub',
- 'google-search-console',
- 'google-sheets',
- 'hubspot',
- 'intercom',
- 'jira',
- 'linear',
- 'linkedin-ads',
- 'meta-ads',
- 'pinterest-ads',
- 'postgresql',
- 'reddit-ads',
- 's3-compatible',
- 'salesforce',
- 'slack',
- 'slack-posthog-code',
- 'snapchat',
- 'stripe',
- 'tiktok-ads',
- 'twilio',
- 'vercel',
- ])
- .describe(
- '\* `anthropic` - Anthropic\n\* `apns` - Apple Push\n\* `aws-s3` - Aws S3\n\* `azure-blob` - Azure Blob\n\* `bing-ads` - Bing Ads\n\* `clickup` - Clickup\n\* `customerio-app` - Customerio App\n\* `customerio-track` - Customerio Track\n\* `customerio-webhook` - Customerio Webhook\n\* `databricks` - Databricks\n\* `email` - Email\n\* `firebase` - Firebase\n\* `github` - Github\n\* `gitlab` - Gitlab\n\* `google-ads` - Google Ads\n\* `google-analytics` - Google Analytics\n\* `google-cloud-service-account` - Google Cloud Service Account\n\* `google-cloud-storage` - Google Cloud Storage\n\* `google-pubsub` - Google Pubsub\n\* `google-search-console` - Google Search Console\n\* `google-sheets` - Google Sheets\n\* `hubspot` - Hubspot\n\* `intercom` - Intercom\n\* `jira` - Jira\n\* `linear` - Linear\n\* `linkedin-ads` - Linkedin Ads\n\* `meta-ads` - Meta Ads\n\* `pinterest-ads` - Pinterest Ads\n\* `postgresql` - Postgresql\n\* `reddit-ads` - Reddit Ads\n\* `s3-compatible` - S3 Compatible\n\* `salesforce` - Salesforce\n\* `slack` - Slack\n\* `slack-posthog-code` - Slack Posthog Code\n\* `snapchat` - Snapchat\n\* `stripe` - Stripe\n\* `tiktok-ads` - Tiktok Ads\n\* `twilio` - Twilio\n\* `vercel` - Vercel'
- ),
- config: zod.unknown().optional(),
- })
- .describe('Standard Integration serializer.')
+export const IntegrationsGithubOauthAuthorizeCreateBody = /* @__PURE__ */ zod.object({
+ installation_id: zod.string().optional().describe('GitHub installation ID to carry through the User OAuth flow.'),
+ next: zod.string().optional().describe('Relative URL to redirect to after the OAuth flow completes.'),
+ connect_from: zod
+ .enum(['posthog_code'])
+ .describe('\* `posthog_code` - posthog_code')
+ .optional()
+ .describe(
+ "Originating surface for the connect flow; only 'posthog_code' is recognized.\n\n\* `posthog_code` - posthog_code"
+ ),
+})
+
+/**
+ * Seed GitHub setup callback state without redirecting to GitHub.
+ *
+ * Used when the user opens an existing installation's settings on github.com (e.g. PostHog
+ * Code "Update in GitHub") so the subsequent Setup URL redirect can be validated.
+ */
+export const IntegrationsGithubPrepareCallbackCreateBody = /* @__PURE__ */ zod.object({
+ next: zod
+ .string()
+ .optional()
+ .describe(
+ 'Relative URL to redirect to after GitHub setup completes (e.g. account-connected for PostHog Code).'
+ ),
+ installation_id: zod
+ .string()
+ .optional()
+ .describe(
+ "GitHub installation ID being managed; binds the seeded update state so a callback can't swap in a different installation."
+ ),
+})
/**
* Notify project admins that a member is requesting an integration be connected.
diff --git a/products/integrations/mcp/tools.yaml b/products/integrations/mcp/tools.yaml
index a6558d46ca35..ea50ac3c4fc7 100644
--- a/products/integrations/mcp/tools.yaml
+++ b/products/integrations/mcp/tools.yaml
@@ -109,6 +109,9 @@ tools:
integrations-github-oauth-authorize-create:
operation: integrations_github_oauth_authorize_create
enabled: false
+ integrations-github-prepare-callback-create:
+ operation: integrations_github_prepare_callback_create
+ enabled: false
integrations-github-repos-refresh-create:
operation: integrations_github_repos_refresh_create
enabled: false
diff --git a/services/mcp/definitions/core.yaml b/services/mcp/definitions/core.yaml
index 117b28627b23..343d142ab4cd 100644
--- a/services/mcp/definitions/core.yaml
+++ b/services/mcp/definitions/core.yaml
@@ -708,6 +708,9 @@ tools:
users-integrations-github-destroy:
operation: users_integrations_github_destroy
enabled: false
+ users-integrations-github-prepare-callback-create:
+ operation: users_integrations_github_prepare_callback_create
+ enabled: false
users-integrations-github-repos-refresh-create:
operation: users_integrations_github_repos_refresh_create
enabled: false
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 8dbada7640c9..7a8f885fa30a 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -13186,6 +13186,16 @@ export namespace Schemas {
Invalid: 'invalid',
} as const;
+ /**
+ * * `posthog_code` - posthog_code
+ */
+ export type ConnectFromEnum = typeof ConnectFromEnum[keyof typeof ConnectFromEnum];
+
+
+ export const ConnectFromEnum = {
+ PosthogCode: 'posthog_code',
+ } as const;
+
/**
* Response containing a JWT token for direct sandbox connection
*/
@@ -23722,6 +23732,39 @@ export namespace Schemas {
has_more: boolean;
}
+ export interface GitHubLinkExistingRequest {
+ /**
+ * Sibling team in the same organization whose GitHub installation should be reused.
+ * @nullable
+ */
+ source_team_id?: number | null;
+ /** GitHub installation ID to link; resolved within the organization when source_team_id is omitted. */
+ installation_id?: string;
+ }
+
+ export interface GitHubOAuthAuthorizeRequest {
+ /** GitHub installation ID to carry through the User OAuth flow. */
+ installation_id?: string;
+ /** Relative URL to redirect to after the OAuth flow completes. */
+ next?: string;
+ /** Originating surface for the connect flow; only 'posthog_code' is recognized.
+ *
+ * * `posthog_code` - posthog_code */
+ connect_from?: ConnectFromEnum;
+ }
+
+ export interface GitHubOAuthAuthorizeResponse {
+ /** GitHub User OAuth URL the client should redirect to. */
+ oauth_url: string;
+ }
+
+ export interface GitHubPrepareCallbackRequest {
+ /** Relative URL to redirect to after GitHub setup completes (e.g. account-connected for PostHog Code). */
+ next?: string;
+ /** GitHub installation ID being managed; binds the seeded update state so a callback can't swap in a different installation. */
+ installation_id?: string;
+ }
+
export interface GitHubRepo {
id: number;
name: string;
@@ -50698,6 +50741,11 @@ export namespace Schemas {
connect_flow: string;
}
+ export interface UserGitHubPrepareCallbackRequest {
+ /** GitHub App installation id being managed on github.com. */
+ installation_id: string;
+ }
+
/**
* * `transcript` - transcript
* * `summary` - summary