: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(scenes): guard scene URL handling against malformed input (#70254)
posthog[bot]e857e8c923b9
diff --git a/frontend/src/initKea.ts b/frontend/src/initKea.tsindex f2bcfe35d918..a46a593f67e7 100644--- a/frontend/src/initKea.ts+++ b/frontend/src/initKea.ts@@ -9,7 +9,12 @@ import { windowValuesPlugin } from 'kea-window-values'import posthog from 'posthog-js'import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'-import { addProjectIdIfMissing, removeProjectIdIfPresent, stripTrailingSlash } from 'lib/utils/kea-router'+import {+ addProjectIdIfMissing,+ ensureRoutablePathname,+ removeProjectIdIfPresent,+ stripTrailingSlash,+} from 'lib/utils/kea-router'import { identifierToHuman } from 'lib/utils/strings'import { disposablesPlugin } from '~/kea-disposables'@@ -82,7 +87,10 @@ export function initKea({return addProjectIdIfMissing(path)},transformPathInActions: (path) => {- return addProjectIdIfMissing(path)+ // Runs before kea-router's `decodeURI(pathname)` on every navigation (initial+ // load, push/replace, popstate). Keep the path decodable so a malformed `%`+ // routes to 404 instead of crashing the router.+ return addProjectIdIfMissing(ensureRoutablePathname(path))},pathFromWindowToRoutes: (path) => {return stripTrailingSlash(removeProjectIdIfPresent(path))diff --git a/frontend/src/lib/utils/kea-router.test.ts b/frontend/src/lib/utils/kea-router.test.tsindex c2e993478b44..6c22afb7d53d 100644--- a/frontend/src/lib/utils/kea-router.test.ts+++ b/frontend/src/lib/utils/kea-router.test.ts@@ -1,4 +1,4 @@-import { addProjectIdIfMissing, stripTrailingSlash } from 'lib/utils/kea-router'+import { addProjectIdIfMissing, ensureRoutablePathname, stripTrailingSlash } from 'lib/utils/kea-router'describe('router-utils', () => {it('does not redirect account URLs to a project URL', () => {@@ -67,4 +67,20 @@ describe('router-utils', () => {expect(stripTrailingSlash('')).toEqual('')})})++ describe('ensureRoutablePathname', () => {+ // kea-router runs decodeURI(pathname) while matching; a stray `%` used to throw URIError+ // and crash routing before any scene loaded. Whatever we return must be decodeURI-safe.+ it.each([+ ['/person/50%off', '/person/50%25off'], // lone `%` gets escaped+ ['/person/foo%', '/person/foo%25'], // trailing `%` gets escaped+ ['/person/50%25off', '/person/50%25off'], // already-valid escape is untouched+ ['/person/foo bar', '/person/foo bar'], // whitespace decodes fine, left alone+ ['/insights/abc', '/insights/abc'], // plain path untouched+ ])('makes %s routable as %s', (input, expected) => {+ const result = ensureRoutablePathname(input)+ expect(result).toEqual(expected)+ expect(() => decodeURI(result)).not.toThrow()+ })+ })})diff --git a/frontend/src/lib/utils/kea-router.ts b/frontend/src/lib/utils/kea-router.tsindex 0782d95288b2..2f37e7e9c203 100644--- a/frontend/src/lib/utils/kea-router.ts+++ b/frontend/src/lib/utils/kea-router.ts@@ -73,6 +73,22 @@ export function removeProjectIdIfPresent(path: string): string {return path}+/**+ * kea-router runs `decodeURI(pathname)` while matching routes. A stray `%` that isn't a valid+ * escape (e.g. a distinct id like `50%off` in `/person/50%off`) makes `decodeURI` throw+ * `URIError` synchronously inside the router, before any scene loads, crashing the whole app.+ * Escape every `%` so the path stays decodable and routing falls through to the scene (or 404)+ * instead of throwing. Well-formed paths are returned untouched.+ */+export function ensureRoutablePathname(path: string): string {+ try {+ decodeURI(path)+ return path+ } catch {+ return path.replace(/%/g, '%25')+ }+}+export function stripTrailingSlash(path: string): string {if (path.length > 1 && path.endsWith('/')) {return path.replace(/\/+$/, '')diff --git a/frontend/src/scenes/persons/PersonScene.test.tsx b/frontend/src/scenes/persons/PersonScene.test.tsxnew file mode 100644index 000000000000..ea1b035f0ebf--- /dev/null+++ b/frontend/src/scenes/persons/PersonScene.test.tsx@@ -0,0 +1,17 @@+import { scene } from './PersonScene'++describe('PersonScene', () => {+ // A distinct ID with a stray `%` (e.g. `50%off`) makes decodeURIComponent throw+ // `URIError: URI malformed`; paramsToProps must fall back to the raw id so the+ // scene still renders instead of hard-crashing.+ it.each<[string, string]>([+ ['50%25off', '50%off'], // valid encoding is decoded+ ['50%off', '50%off'], // malformed `%` falls back to the raw id+ ['foo bar', 'foo bar'], // whitespace passes through untouched+ ])('paramsToProps turns raw id %s into urlId %s without throwing', (rawUrlId, expected) => {+ expect(scene.paramsToProps?.({ params: { _: rawUrlId }, searchParams: {}, hashParams: {} })).toEqual({+ syncWithUrl: true,+ urlId: expected,+ })+ })+})diff --git a/frontend/src/scenes/persons/PersonScene.tsx b/frontend/src/scenes/persons/PersonScene.tsxindex ca2bd796a151..c5f9d5c52f53 100644--- a/frontend/src/scenes/persons/PersonScene.tsx+++ b/frontend/src/scenes/persons/PersonScene.tsx@@ -21,6 +21,7 @@ import { Tooltip } from 'lib/lemon-ui/Tooltip'import { copyToClipboard } from 'lib/utils/copyToClipboard'import { isMobile } from 'lib/utils/dom'import { pluralize } from 'lib/utils/strings'+import { tryDecodeURIComponent } from 'lib/utils/url'import { RelatedGroups } from 'scenes/groups/RelatedGroups'import { NotebookSelectButton } from 'scenes/notebooks/NotebookSelectButton/NotebookSelectButton'import { NotebookNodeType } from 'scenes/notebooks/types'@@ -57,7 +58,9 @@ export const scene: SceneExport<PersonsLogicProps> = {logic: personsLogic,paramsToProps: ({ params: { _: rawUrlId } }) => ({syncWithUrl: true,- urlId: decodeURIComponent(rawUrlId),+ // A distinct ID with a stray `%` (e.g. `50%off`) makes decodeURIComponent throw+ // `URIError: URI malformed`. Fall back to the raw id so the scene still renders.+ urlId: tryDecodeURIComponent(rawUrlId),}),}diff --git a/frontend/src/scenes/sceneLogic.tsx b/frontend/src/scenes/sceneLogic.tsxindex a9326dd6f76a..bb0d911faabb 100644--- a/frontend/src/scenes/sceneLogic.tsx+++ b/frontend/src/scenes/sceneLogic.tsx@@ -746,20 +746,33 @@ export const sceneLogic = kea<sceneLogicType>([})),urlToAction(({ actions, values }) => {- const mapping: Record<- string,- (- params: Params,- searchParams: Params,- hashParams: Params,- payload: {- method: string+ type RouteHandler = (+ params: Params,+ searchParams: Params,+ hashParams: Params,+ payload: {+ method: string+ }+ ) => any+ const mapping: Record<string, RouteHandler> = {}++ // Malformed URLs (a stray `%`, embedded whitespace) can make redirect building or+ // scene dispatch throw synchronously while kea-router matches the route. Nothing+ // upstream catches it, so the whole app fails to render. Guard every route handler:+ // capture the error and fall back to a 404 instead of crashing.+ const guardRoute =+ (handler: RouteHandler): RouteHandler =>+ (params, searchParams, hashParams, payload) => {+ try {+ return handler(params, searchParams, hashParams, payload)+ } catch (error) {+ posthog.captureException(error, { extra: { source: 'sceneLogic.urlToAction' } })+ actions.loadScene(Scene.Error404, undefined, emptySceneParams, payload.method)}- ) => any- > = {}+ }for (const path of Object.keys(redirects)) {- mapping[path] = (params, searchParams, hashParams) => {+ mapping[path] = guardRoute((params, searchParams, hashParams) => {const redirect = redirects[path]const redirectUrl =typeof redirect === 'function' ? redirect(params, searchParams, hashParams) : redirect@@ -767,7 +780,7 @@ export const sceneLogic = kea<sceneLogicType>([router.actions.replace(withForwardedSearchParams(redirectUrl, searchParams, forwardedRedirectQueryParams))- }+ })}// The Home button (via `/`) and a direct visit to /home should both land on the user's// configured homepage (set in the Configure home modal). Redirect there unless we're@@ -796,18 +809,18 @@ export const sceneLogic = kea<sceneLogicType>([return true}- mapping['/'] = (_params, searchParams) => {+ mapping['/'] = guardRoute((_params, searchParams) => {if (redirectToConfiguredHomepage(searchParams)) {return}router.actions.replace(withForwardedSearchParams(urls.projectHomepage(), searchParams, forwardedRedirectQueryParams))- }+ })const projectHomepagePath = urls.projectHomepage()for (const [path, [scene, sceneKey]] of Object.entries(routes)) {- mapping[path] = (params, searchParams, hashParams, { method }) => {+ mapping[path] = guardRoute((params, searchParams, hashParams, { method }) => {// A direct visit to /home honors the configured homepage just like the Home button.if (path === projectHomepagePath && redirectToConfiguredHomepage(searchParams)) {return@@ -822,7 +835,7 @@ export const sceneLogic = kea<sceneLogicType>([},method)- }+ })}mapping['/*'] = (_, __, { method }) => {