: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
feat(customer-analytics): Return to accounts on back from a group (#65547)
Arthur Moreira de Deusac69e09b7568
diff --git a/frontend/src/scenes/groups/Group.tsx b/frontend/src/scenes/groups/Group.tsxindex 116b7ea0a987..e499afcd2c2f 100644--- a/frontend/src/scenes/groups/Group.tsx+++ b/frontend/src/scenes/groups/Group.tsx@@ -14,7 +14,6 @@ import { LemonTabs } from 'lib/lemon-ui/LemonTabs'import { Link } from 'lib/lemon-ui/Link'import { Spinner, SpinnerOverlay } from 'lib/lemon-ui/Spinner/Spinner'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'-import { capitalizeFirstLetter } from 'lib/utils/strings'import { GroupLogicProps, groupLogic } from 'scenes/groups/groupLogic'import { NotebookSelectButton } from 'scenes/notebooks/NotebookSelectButton/NotebookSelectButton'import { NotebookNodeType } from 'scenes/notebooks/types'@@ -29,7 +28,6 @@ import { urls } from 'scenes/urls'import { SceneContent } from '~/layout/scenes/components/SceneContent'import { SceneDivider } from '~/layout/scenes/components/SceneDivider'import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'-import { groupsModel } from '~/models/groupsModel'import { Query } from '~/queries/Query/Query'import type { ActionFilter } from '~/types'import {@@ -71,12 +69,13 @@ export function Group(): JSX.Element {groupTab,groupEventsQuery,groupEventsQueryIsDirty,+ backTo,+ backNavigation,} = useValues(mountedGroupLogic)const { groupKey, groupTypeIndex } = logicPropsconst { setGroupEventsQuery, resetGroupEventsQuery, editProperty, deleteProperty } = useActions(mountedGroupLogic)const { currentTeam } = useValues(teamLogic)const { featureFlags } = useValues(featureFlagLogic)- const { aggregationLabel } = useValues(groupsModel)const groupProfileVariant = useFeatureFlagVariantKey(FEATURE_FLAGS.GROUP_PROFILE_EXPERIMENT)const isProfileEnabled = groupProfileVariant === 'test'const showProfile = featureFlags[FEATURE_FLAGS.CUSTOMER_ANALYTICS] || isProfileEnabled@@ -92,11 +91,7 @@ export function Group(): JSX.Element {<SceneTitleSectionname={groupDisplayId(groupData.group_key, groupData.group_properties)}resourceType={{ type: 'group' }}- forceBackTo={{- name: capitalizeFirstLetter(aggregationLabel(groupTypeIndex).plural),- key: 'groups',- path: urls.groups(groupTypeIndex),- }}+ forceBackTo={backTo}actions={<><FeedbackButton id="customer-analytics-group-profile-feedback-button" />@@ -119,7 +114,12 @@ export function Group(): JSX.Element {<LemonTabssceneInsetactiveKey={activeTab}- onChange={(tab) => router.actions.push(urls.group(String(groupTypeIndex), groupKey, true, tab))}+ onChange={(tab) =>+ router.actions.push(+ urls.group(String(groupTypeIndex), groupKey, true, tab),+ backNavigation ? { backUrl: backNavigation.url, backName: backNavigation.name } : undefined+ )+ }tabs={[...(showProfile? [diff --git a/frontend/src/scenes/groups/groupLogic.test.ts b/frontend/src/scenes/groups/groupLogic.test.tsnew file mode 100644index 000000000000..80fe620f82c3--- /dev/null+++ b/frontend/src/scenes/groups/groupLogic.test.ts@@ -0,0 +1,32 @@+import { resolveBackNavigation } from './groupLogic'++describe('resolveBackNavigation', () => {+ it('returns the sanitized internal path and name', () => {+ expect(resolveBackNavigation({ backUrl: '/customer_analytics/accounts', backName: 'Accounts' })).toEqual({+ url: '/customer_analytics/accounts',+ name: 'Accounts',+ })+ })++ it('preserves search and hash on the internal path', () => {+ expect(+ resolveBackNavigation({ backUrl: '/customer_analytics/accounts?tab=usage#view=abc', backName: 'Accounts' })+ ).toEqual({ url: '/customer_analytics/accounts?tab=usage#view=abc', name: 'Accounts' })+ })++ it('rejects an absolute external URL (open redirect guard)', () => {+ expect(resolveBackNavigation({ backUrl: 'https://evil.com', backName: 'Accounts' })).toBeNull()+ })++ it('rejects a protocol-relative URL', () => {+ expect(resolveBackNavigation({ backUrl: '//evil.com' })).toBeNull()+ })++ it('returns null when backUrl is absent', () => {+ expect(resolveBackNavigation({})).toBeNull()+ })++ it('falls back to a default name when backName is missing', () => {+ expect(resolveBackNavigation({ backUrl: '/groups/0/acme' })).toEqual({ url: '/groups/0/acme', name: 'Back' })+ })+})diff --git a/frontend/src/scenes/groups/groupLogic.ts b/frontend/src/scenes/groups/groupLogic.tsindex 00381abd47b1..0ac2d4115273 100644--- a/frontend/src/scenes/groups/groupLogic.ts+++ b/frontend/src/scenes/groups/groupLogic.ts@@ -1,6 +1,6 @@import { actions, afterMount, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'import { loaders } from 'kea-loaders'-import { urlToAction } from 'kea-router'+import { router, urlToAction } from 'kea-router'import posthog from 'posthog-js'import api from 'lib/api'@@ -10,7 +10,7 @@ import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { eventUsageLogic } from 'lib/utils/eventUsageLogic'import { objectsEqual } from 'lib/utils/objects'import { capitalizeFirstLetter } from 'lib/utils/strings'-import { toParams } from 'lib/utils/url'+import { getRelativeNextPath, toParams } from 'lib/utils/url'import { groupDisplayId } from 'scenes/persons/GroupActorDisplay'import { Scene } from 'scenes/sceneTypes'import { teamLogic } from 'scenes/teamLogic'@@ -53,6 +53,22 @@ export type GroupLogicProps = {groupKey: string}+export interface GroupBackNavigation {+ url: string+ name: string+}++// `backUrl` comes from an untrusted search param; only honor it as an internal relative path so a+// crafted link can't turn the back button into an open redirect. `getRelativeNextPath` also sanitizes.+export function resolveBackNavigation(searchParams: Record<string, any>): GroupBackNavigation | null {+ const url = getRelativeNextPath(searchParams.backUrl, window.location)+ if (!url) {+ return null+ }+ const name = searchParams.backName+ return { url, name: typeof name === 'string' && name ? name : 'Back' }+}+export const groupLogic = kea<groupLogicType>([props({} as GroupLogicProps),key(({ groupKey, groupTypeIndex }) => `${groupTypeIndex}-${groupKey}`),@@ -279,6 +295,23 @@ export const groupLogic = kea<groupLogicType>([(s) => [s.effectiveMRR, s.effectiveLifetimeValue],(mrr, ltv): boolean => mrr.value !== null || ltv.value !== null,],+ backNavigation: [+ () => [router.selectors.searchParams],+ (searchParams): GroupBackNavigation | null => resolveBackNavigation(searchParams),+ ],+ backTo: [+ (s, p) => [s.aggregationLabel, p.groupTypeIndex, s.backNavigation],+ (aggregationLabel, groupTypeIndex, backNavigation): Breadcrumb => {+ if (backNavigation) {+ return { key: 'group-back', name: backNavigation.name, path: backNavigation.url }+ }+ return {+ key: 'groups',+ name: capitalizeFirstLetter(aggregationLabel(groupTypeIndex).plural),+ path: urls.groups(groupTypeIndex),+ }+ },+ ],breadcrumbs: [(s, p) => [s.groupTypeName, p.groupTypeIndex, p.groupKey, s.groupData],(groupTypeName, groupTypeIndex, groupKey, groupData): Breadcrumb[] => {diff --git a/products/customer_analytics/frontend/components/Accounts/accountLinksLogic.test.ts b/products/customer_analytics/frontend/components/Accounts/accountLinksLogic.test.tsindex 1df4cb0bee67..1e2816f16d9e 100644--- a/products/customer_analytics/frontend/components/Accounts/accountLinksLogic.test.ts+++ b/products/customer_analytics/frontend/components/Accounts/accountLinksLogic.test.ts@@ -1,5 +1,6 @@import { MOCK_DEFAULT_TEAM } from '~/lib/api.mock'+import { combineUrl, router } from 'kea-router'import { expectLogic } from 'kea-test-utils'import { initKeaTests } from '~/test/init'@@ -172,4 +173,24 @@ describe('accountLinksLogic', () => {expect(logic.values.savingLinks).toBe(false)expect(logic.values.account).toEqual(initial)})++ it('organization link opens the group and carries the accounts list as backUrl', async () => {+ router.actions.push('/customer_analytics/accounts', {}, { view: { search: 'acme' } })+ await mountWith(buildAccount({ external_id: 'ext-1' }))++ const organization = logic.values.links.find((link) => link.key === 'organization')+ const destination = combineUrl(organization!.to!)+ expect(destination.pathname).toBe('/groups/0/ext-1')+ expect(destination.searchParams.backName).toBe('Accounts')+ expect(destination.searchParams.backUrl).toContain('/customer_analytics/accounts')+ expect(destination.searchParams.backUrl).toContain('#view=')+ })++ it('organization link is disabled without an external_id', async () => {+ await mountWith(buildAccount({ external_id: null }))++ const organization = logic.values.links.find((link) => link.key === 'organization')+ expect(organization?.to).toBeNull()+ expect(organization?.disabledReason).toBe('No external ID set')+ })})diff --git a/products/customer_analytics/frontend/components/Accounts/accountLinksLogic.ts b/products/customer_analytics/frontend/components/Accounts/accountLinksLogic.tsindex fb0d0bad639c..0712c633838a 100644--- a/products/customer_analytics/frontend/components/Accounts/accountLinksLogic.ts+++ b/products/customer_analytics/frontend/components/Accounts/accountLinksLogic.ts@@ -1,8 +1,10 @@import { actions, afterMount, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'import { loaders } from 'kea-loaders'+import { combineUrl, router } from 'kea-router'import posthog from 'posthog-js'import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'+import { removeProjectIdIfPresent } from 'lib/utils/kea-router'import { teamLogic } from 'scenes/teamLogic'import { urls } from 'scenes/urls'@@ -125,17 +127,24 @@ export const accountLinksLogic = kea<accountLinksLogicType>([}),],links: [- (s) => [s.account],- (account: AccountApi | null): AccountLink[] => {+ (s) => [s.account, router.selectors.currentLocation],+ (account: AccountApi | null, currentLocation): AccountLink[] => {const externalId = account?.external_id ?? nullconst billingId = account?.properties?.billing_id ?? nullconst slackChannelId = account?.properties?.slack_channel_id ?? nullconst usageDashboardLink = account?.properties?.usage_dashboard_link ?? null+ const backUrl =+ removeProjectIdIfPresent(currentLocation.pathname) + currentLocation.search + currentLocation.hashreturn [{key: 'organization',label: 'Organization',- to: externalId ? urls.group(ORGANIZATION_GROUP_TYPE_INDEX, externalId) : null,+ to: externalId+ ? combineUrl(urls.group(ORGANIZATION_GROUP_TYPE_INDEX, externalId), {+ backUrl,+ backName: 'Accounts',+ }).url+ : null,targetBlank: false,disabledReason: externalId ? null : 'No external ID set',},