: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(cdp): switch project on post-login deep link redirect (#79632)
posthog[bot]501ff85813fc
diff --git a/frontend/src/scenes/authentication/login/loginLogic.test.ts b/frontend/src/scenes/authentication/login/loginLogic.test.tsindex 4305de5e40c2..c6a8dd825585 100644--- a/frontend/src/scenes/authentication/login/loginLogic.test.ts+++ b/frontend/src/scenes/authentication/login/loginLogic.test.ts@@ -493,4 +493,55 @@ describe('loginLogic', () => {expect(assignMock).toHaveBeenCalledTimes(1)})})++ describe('cross-project redirect after login', () => {+ const originalContext = window.POSTHOG_APP_CONTEXT+ const originalLocation = window.location+ let hrefSpy: jest.Mock++ beforeEach(() => {+ initKeaTests()+ // getCurrentTeamIdOrNone() reads the current project from the app context.+ window.POSTHOG_APP_CONTEXT = { current_team: { id: 5 } } as any+ hrefSpy = jest.fn()+ Object.defineProperty(window, 'location', {+ value: {+ origin: 'http://localhost',+ pathname: '/login',+ search: '',+ hash: '',+ set href(url: string) {+ hrefSpy(url)+ },+ },+ configurable: true,+ })+ })++ afterEach(() => {+ window.POSTHOG_APP_CONTEXT = originalContext+ Object.defineProperty(window, 'location', { value: originalLocation, configurable: true })+ })++ it('does a full navigation to a project other than the current one', () => {+ router.actions.push(`/login?next=${encodeURIComponent('/project/999/pipeline/destinations/hog-abc')}`)+ handleLoginRedirect()+ // A full load lets AutoProjectMiddleware switch the active project before the scene mounts.+ expect(hrefSpy).toHaveBeenCalledWith('/project/999/pipeline/destinations/hog-abc')+ })++ it('stays client-side when the target is already the current project', () => {+ router.actions.push(`/login?next=${encodeURIComponent('/project/5/pipeline/destinations/hog-abc')}`)+ handleLoginRedirect()+ expect(hrefSpy).not.toHaveBeenCalled()+ })++ it('does a full navigation for a project token the middleware resolves server-side', () => {+ // A `phc_` key or a legacy allowlisted api_token can't be compared to the numeric team id,+ // so it must reach AutoProjectMiddleware for resolution — client-side routing wouldn't switch.+ router.actions.push(`/login?next=${encodeURIComponent('/project/phc_ABC123/pipeline/destinations')}`)+ handleLoginRedirect()+ expect(hrefSpy).toHaveBeenCalledWith('/project/phc_ABC123/pipeline/destinations')+ })+ })})diff --git a/frontend/src/scenes/authentication/login/loginLogic.ts b/frontend/src/scenes/authentication/login/loginLogic.tsindex 9c08ccef1248..74bdcbb2cbfd 100644--- a/frontend/src/scenes/authentication/login/loginLogic.ts+++ b/frontend/src/scenes/authentication/login/loginLogic.ts@@ -13,6 +13,7 @@ import { getSocialLoginUrl } from 'lib/components/SocialLoginButton/socialLoginUimport { lemonToast } from 'lib/lemon-ui/LemonToast'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { isWebKitBrowser } from 'lib/utils/dom'+import { getCurrentTeamIdOrNone } from 'lib/utils/getAppContext'import { getRelativeNextPath } from 'lib/utils/url'import { devLoginLogic } from 'scenes/authentication/shared/devLoginLogic'import { twoFactorResetLogic } from 'scenes/authentication/two-factor-reset/twoFactorResetLogic'@@ -76,6 +77,22 @@ const BACKEND_ONLY_ROUTES = ['/toolbar_oauth/check',]+const PROJECT_PATH_PREFIX = '/project/'++// True when the path targets a project other than the one we're currently in. A client-side+// history replace can't switch the active project, so `AutoProjectMiddleware` never runs and any+// team-scoped scene resolves against the wrong project and 404s. The project segment is either a+// numeric team id or a token (a `phc_` project key, or a legacy api_token from the middleware's+// switching allowlist), and only the server can resolve a token to a team, so anything that isn't+// literally the current team id takes the full load.+function pointsToDifferentProject(path: string): boolean {+ if (!path.startsWith(PROJECT_PATH_PREFIX)) {+ return false+ }+ const identifier = path.slice(PROJECT_PATH_PREFIX.length).split('/')[0]+ return !!identifier && identifier !== String(getCurrentTeamIdOrNone())+}+export function handleLoginRedirect(): void {let nextURL = '/'try {@@ -97,6 +114,14 @@ export function handleLoginRedirect(): void {return}+ // A cross-project deep link needs a full page load so `AutoProjectMiddleware` can switch the+ // active project before the scene mounts. A client-side replace would strip the project id and+ // resolve the scene against the project we were last in, 404ing a resource that really exists.+ if (pointsToDifferentProject(nextURL)) {+ window.location.href = nextURL+ return+ }+// A safe way to redirect to a user input URL. Calls history.replaceState() ensuring the URLs origin does not changerouter.actions.replace(nextURL)}diff --git a/frontend/src/scenes/hog-functions/HogFunctionScene.tsx b/frontend/src/scenes/hog-functions/HogFunctionScene.tsxindex 0176b8572973..8a28d13beaeb 100644--- a/frontend/src/scenes/hog-functions/HogFunctionScene.tsx+++ b/frontend/src/scenes/hog-functions/HogFunctionScene.tsx@@ -502,7 +502,12 @@ export function HogFunctionScene(): JSX.Element {}if (id && !loaded) {- return <NotFound object="Hog function" />+ return (+ <NotFound+ object="Hog function"+ caption="This function may belong to a different project. Switch to that project, or ask the person who shared the link which one it's in."+ />+ )}if (!templateId && !id) {diff --git a/frontend/src/scenes/hog-functions/configuration/hogFunctionConfigurationLogic.test.ts b/frontend/src/scenes/hog-functions/configuration/hogFunctionConfigurationLogic.test.tsindex 8925de9a2af6..a50e5892fc01 100644--- a/frontend/src/scenes/hog-functions/configuration/hogFunctionConfigurationLogic.test.ts+++ b/frontend/src/scenes/hog-functions/configuration/hogFunctionConfigurationLogic.test.ts@@ -3,6 +3,7 @@ import { expectLogic } from 'kea-test-utils'import { lemonToast } from '@posthog/lemon-ui'import api from 'lib/api'+import { ApiError } from 'lib/api-error'import { initKeaTests } from '~/test/init'import { HogFunctionTemplateType, HogFunctionType } from '~/types'@@ -235,4 +236,30 @@ describe('hogFunctionConfigurationLogic', () => {expect(toastSpy).toHaveBeenCalledWith(detail)})})++ describe('loading a missing function', () => {+ beforeEach(() => {+ initKeaTests()+ })++ it('resolves to null on a 404 so the not-found state renders without filing an exception', async () => {+ // A cross-project deep link 404s here; the loader must swallow it rather than reject,+ // which would surface as an unhandled rejection in error tracking.+ mockApi.get.mockRejectedValue(new ApiError('Not found', 404))+ logic = hogFunctionConfigurationLogic({ id: 'missing-id' })+ logic.mount()++ await expectLogic(logic).toDispatchActions(['loadHogFunction', 'loadHogFunctionSuccess'])+ expect(logic.values.hogFunction).toBeNull()+ expect(logic.values.loaded).toBe(false)+ })++ it('still rejects on non-404 errors', async () => {+ mockApi.get.mockRejectedValue(new ApiError('Boom', 500))+ logic = hogFunctionConfigurationLogic({ id: 'boom-id' })+ logic.mount()++ await expectLogic(logic).toDispatchActions(['loadHogFunction', 'loadHogFunctionFailure'])+ })+ })})diff --git a/frontend/src/scenes/hog-functions/configuration/hogFunctionConfigurationLogic.tsx b/frontend/src/scenes/hog-functions/configuration/hogFunctionConfigurationLogic.tsxindex efb4e114eded..ab66f66098b4 100644--- a/frontend/src/scenes/hog-functions/configuration/hogFunctionConfigurationLogic.tsx+++ b/frontend/src/scenes/hog-functions/configuration/hogFunctionConfigurationLogic.tsx@@ -24,6 +24,7 @@ import posthog from 'posthog-js'import { lemonToast } from '@posthog/lemon-ui'import api from 'lib/api'+import { ApiError } from 'lib/api-error'import {CyclotronJobInputsValidation,CyclotronJobInputsValidationResult,@@ -1005,7 +1006,17 @@ export const hogFunctionConfigurationLogic = kea<hogFunctionConfigurationLogicTyreturn null}- return await api.hogFunctions.get(props.id)+ try {+ return await api.hogFunctions.get(props.id)+ } catch (e) {+ // A missing id, or one from another project reached via a cross-project deep+ // link, 404s here. Fall back to null so the scene renders its not-found state+ // instead of filing the rejection in error tracking.+ if (e instanceof ApiError && e.status === 404) {+ return null+ }+ throw e+ }},upsertHogFunction: async ({ configuration }) => {