:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(auth): fix "project id is not known" on oauth cloud login (#64922)
Patricio725f8f409742
diff --git a/frontend/src/lib/oauth/oauthClient.ts b/frontend/src/lib/oauth/oauthClient.tsindex 9cbdf94a5989..1285e4b742b2 100644--- a/frontend/src/lib/oauth/oauthClient.ts+++ b/frontend/src/lib/oauth/oauthClient.ts@@ -2,7 +2,7 @@// `api.ts` and other non-React callers can read a valid bearer token directly.// `oauthLogic` wraps this for the login UI.-import { Region } from '~/types'+import { OrganizationType, Region, TeamType, UserType } from '~/types'import { generateCodeChallenge } from './pkce'@@ -102,6 +102,29 @@ function storeSession(session: OAuthSession): void {export function clearSession(): void {window.localStorage.removeItem(SESSION_KEY)document.cookie = `${OAUTH_MODE_COOKIE}=; path=/; Max-Age=0; SameSite=Lax`+ // Drop the bootstrap ids with the session so a later login in the same tab can't read the+ // previous account's ids before its own /api/users/@me/ resolves.+ oauthContextIds = null+}++export interface OAuthContextIds {+ teamId?: TeamType['id']+ organizationId?: OrganizationType['id']+ userId?: UserType['uuid']+}++// In OAuth mode getAppContext() has no server-rendered context, so these bootstrap ids are pushed+// here from userLogic once the remote user loads, and read back by getAppContext's synchronous+// getters. Lives alongside the session (not in getAppContext) so clearSession() can reset it, and+// so getAppContext stays a leaf module — importing the heavy lib/api there caused a module-init cycle.+let oauthContextIds: OAuthContextIds | null = null++export function setOAuthContextIds(ids: OAuthContextIds | null): void {+ oauthContextIds = ids+}++export function getOAuthContextIds(): OAuthContextIds | null {+ return oauthContextIds}function sessionFromTokenResponse(backendHost: string, clientId: string, data: TokenResponse): OAuthSession {diff --git a/frontend/src/lib/utils/getAppContext.ts b/frontend/src/lib/utils/getAppContext.tsindex dc0900d6c3aa..41ae67a0b42f 100644--- a/frontend/src/lib/utils/getAppContext.ts+++ b/frontend/src/lib/utils/getAppContext.ts@@ -1,4 +1,4 @@-import { isOAuthMode } from 'lib/oauth/oauthClient'+import { getOAuthContextIds, isOAuthMode } from 'lib/oauth/oauthClient'import { AppContext, OrganizationType, PathType, TeamType, UserType } from '~/types'@@ -47,7 +47,7 @@ export function getDefaultEventLabel(): string {// NOTE: Any changes to the teamId trigger a full page load so we don't use the logic// This helps avoid circular importsexport function getCurrentTeamId(): TeamType['id'] {- const maybeTeamId = getAppContext()?.current_team?.id+ const maybeTeamId = getAppContext()?.current_team?.id ?? (isOAuthMode() ? getOAuthContextIds()?.teamId : undefined)if (!maybeTeamId) {throw new Error(`Project ID is not known.${getAppContext()?.anonymous ? ' User is anonymous.' : ''}`)}@@ -55,13 +55,14 @@ export function getCurrentTeamId(): TeamType['id'] {}export function getCurrentTeamIdOrNone(): TeamType['id'] | null {- return getAppContext()?.current_team?.id ?? null+ return getAppContext()?.current_team?.id ?? (isOAuthMode() ? (getOAuthContextIds()?.teamId ?? null) : null)}// NOTE: Any changes to the userId trigger a full page load so we don't use the logic// This helps avoid circular importsexport function getCurrentUserId(): UserType['uuid'] {- const maybeUserId = getAppContext()?.current_user?.uuid+ const maybeUserId =+ getAppContext()?.current_user?.uuid ?? (isOAuthMode() ? getOAuthContextIds()?.userId : undefined)if (!maybeUserId) {throw new Error(`User ID is not known.${getAppContext()?.anonymous ? ' User is anonymous.' : ''}`)}@@ -69,13 +70,15 @@ export function getCurrentUserId(): UserType['uuid'] {}export function getCurrentUserIdOrNone(): UserType['uuid'] | null {- return getAppContext()?.current_user?.uuid ?? null+ return getAppContext()?.current_user?.uuid ?? (isOAuthMode() ? (getOAuthContextIds()?.userId ?? null) : null)}// NOTE: Any changes to the organizationId trigger a full page load so we don't use the logic// This helps avoid circular importsexport function getCurrentOrganizationId(): OrganizationType['id'] {- const maybeOrgId = getAppContext()?.current_team?.organization+ const maybeOrgId =+ getAppContext()?.current_team?.organization ??+ (isOAuthMode() ? getOAuthContextIds()?.organizationId : undefined)if (!maybeOrgId) {throw new Error(`Organization ID is not known.${getAppContext()?.anonymous ? ' User is anonymous.' : ''}`)}diff --git a/frontend/src/scenes/userLogic.ts b/frontend/src/scenes/userLogic.tsindex fd59e37bca13..904988e9c9cd 100644--- a/frontend/src/scenes/userLogic.ts+++ b/frontend/src/scenes/userLogic.ts@@ -4,11 +4,11 @@ import { loaders } from 'kea-loaders'import { router } from 'kea-router'import posthog from 'posthog-js'-import api, { getCookie } from 'lib/api'+import api, { ApiConfig, getCookie } from 'lib/api'import { DashboardCompatibleScenes } from 'lib/components/SceneDashboardChoice/sceneDashboardChoiceModalLogic'// eslint-disable-next-line import/no-cycleimport { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'-import { clearSession, isOAuthMode } from 'lib/oauth/oauthClient'+import { clearSession, isOAuthMode, setOAuthContextIds } from 'lib/oauth/oauthClient'import { getAppContext } from 'lib/utils/getAppContext'import { sidePanelStateLogic } from '~/layout/navigation-3000/sidepanel/sidePanelStateLogic'@@ -294,6 +294,27 @@ export const userLogic = kea<userLogicType>([},loadUserSuccess: ({ user }) => {if (user && user.uuid) {+ // OAuth mode has no server-rendered app context, so seed the current ids from the+ // freshly loaded remote user. This makes them available synchronously before the first+ // project-scoped URL is built, avoiding "Project ID is not known." (and the sibling+ // user/org id errors) on bootstrap. The API layer reads default project/team-id params+ // from ApiConfig; getAppContext's synchronous getters read the pushed ids (it stays a+ // leaf module — importing ApiConfig there would create a module-init cycle).+ if (isOAuthMode()) {+ if (user.team) {+ ApiConfig.setCurrentTeamId(user.team.id)+ ApiConfig.setCurrentProjectId(user.team.project_id)+ }+ if (user.organization) {+ ApiConfig.setCurrentOrganizationId(user.organization.id)+ }+ setOAuthContextIds({+ teamId: user.team?.id,+ organizationId: user.organization?.id,+ userId: user.uuid,+ })+ }+if (posthog) {posthog.identify(user.distinct_id)posthog.people.set({