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.

fix(toolbar): sanitize html experiments (#58319)

Fernando Gomes009260e91098
diff --git a/frontend/src/toolbar/bar/toolbarLogic.ts b/frontend/src/toolbar/bar/toolbarLogic.ts
index e98bc0a47652..63b2c63616e8 100644
--- a/frontend/src/toolbar/bar/toolbarLogic.ts
+++ b/frontend/src/toolbar/bar/toolbarLogic.ts
@@ -715,7 +715,17 @@ export const toolbarLogic = kea<toolbarLogicType>([
if (isInIframe) {
cache.disposables.add(() => {
const iframeEventListener = (e: MessageEvent): void => {
- // TODO: Probably need to have strict checks here
+ // Only the PostHog app at uiHost should be driving these actions.
+ const expectedOrigin = toolbarConfigLogic.findMounted()?.values.uiHost
+ if (!expectedOrigin || e.origin !== expectedOrigin) {
+ if (e?.data?.type && typeof e.data.type === 'string' && e.data.type.startsWith('ph-')) {
+ toolbarLogger.warn('iframe', 'Ignoring parent message from unexpected origin', {
+ got: e.origin,
+ expected: expectedOrigin,
+ })
+ }
+ return
+ }
const type: PostHogAppToolbarEvent = e?.data?.type
if (!type || !type.startsWith('ph-')) {
diff --git a/frontend/src/toolbar/experiments/WebExperimentTransformField.tsx b/frontend/src/toolbar/experiments/WebExperimentTransformField.tsx
index 17decb59ac5b..0712d7a9b2c4 100644
--- a/frontend/src/toolbar/experiments/WebExperimentTransformField.tsx
+++ b/frontend/src/toolbar/experiments/WebExperimentTransformField.tsx
@@ -11,6 +11,12 @@ import {
ElementSelectorType,
experimentsTabLogic,
} from '~/toolbar/experiments/experimentsTabLogic'
+import {
+ htmlSanitizationWouldStrip,
+ setSanitizedHTML,
+ setSanitizedStyle,
+ styleSanitizationWouldStrip,
+} from '~/toolbar/experiments/sanitize'
import { WebExperimentTransform } from '~/toolbar/types'
interface WebExperimentTransformFieldProps {
@@ -83,12 +89,17 @@ export function WebExperimentTransformField({
? (document.querySelector(transform.selector) as HTMLElement)
: null
if (element) {
- element.innerHTML = value
+ setSanitizedHTML(element, value)
}
}}
value={transform.html}
maxRows={8}
/>
+ {htmlSanitizationWouldStrip(transform.html) && (
+ <div className="text-xs text-secondary mt-1">
+ Some markup will be removed when applied (scripts, event handlers, inline styles).
+ </div>
+ )}
</div>
<div className="mt-4">
<LemonLabel>CSS</LemonLabel>
@@ -112,13 +123,18 @@ export function WebExperimentTransformField({
? (document.querySelector(transform.selector) as HTMLElement)
: null
if (element) {
- element.setAttribute('style', value)
+ setSanitizedStyle(element, value)
}
}
}}
value={transform.css || ''}
maxRows={8}
/>
+ {styleSanitizationWouldStrip(transform.css) && (
+ <div className="text-xs text-secondary mt-1">
+ Some declarations will be removed when applied (url(), image-set, paint).
+ </div>
+ )}
</div>
</div>
)}
diff --git a/frontend/src/toolbar/experiments/experimentsTabLogic.tsx b/frontend/src/toolbar/experiments/experimentsTabLogic.tsx
index 5c908e705760..e282861fed2a 100644
--- a/frontend/src/toolbar/experiments/experimentsTabLogic.tsx
+++ b/frontend/src/toolbar/experiments/experimentsTabLogic.tsx
@@ -10,6 +10,12 @@ import { urls } from 'scenes/urls'
import { percentageDistribution } from '~/scenes/experiments/utils'
import { toolbarLogic } from '~/toolbar/bar/toolbarLogic'
import { experimentsLogic } from '~/toolbar/experiments/experimentsLogic'
+import {
+ sanitizeExperimentHTML,
+ sanitizeExperimentStyle,
+ setSanitizedHTML,
+ setSanitizedStyle,
+} from '~/toolbar/experiments/sanitize'
import { toolbarConfigLogic, toolbarFetch } from '~/toolbar/toolbarConfigLogic'
import { toolbarLogger } from '~/toolbar/toolbarLogger'
import { captureToolbarException, toolbarPosthogJS } from '~/toolbar/toolbarPosthogJS'
@@ -342,10 +348,14 @@ export const experimentsTabLogic = kea<experimentsTabLogicType>([
if (previousSelector) {
const originalHtmlState = values.experimentForm.original_html_state?.[previousSelector]
if (originalHtmlState) {
- const previousElement = document.querySelector(previousSelector) as HTMLElement
- previousElement.innerHTML = originalHtmlState.html
- if (originalHtmlState.css) {
- previousElement.setAttribute('style', originalHtmlState.css)
+ const previousElement = document.querySelector(previousSelector) as HTMLElement | null
+ // Captured from the live DOM, so script/event-handler content the customer
+ // page legitimately included is not restored — that's the sanitization trade-off.
+ if (previousElement) {
+ setSanitizedHTML(previousElement, originalHtmlState.html)
+ if (originalHtmlState.css) {
+ setSanitizedStyle(previousElement, originalHtmlState.css)
+ }
}
}
}
@@ -391,33 +401,44 @@ export const experimentsTabLogic = kea<experimentsTabLogicType>([
if (values.experimentForm && values.experimentForm.variants) {
const selectedVariant = values.experimentForm.variants[newVariantKey]
if (selectedVariant) {
- // Restore original HTML state
+ // Restore original HTML state — sanitize once per selector, reuse across matches.
Object.entries(values.experimentForm.original_html_state || {}).forEach(
([selector, originalState]) => {
+ const sanitizedHtml = sanitizeExperimentHTML(originalState.html)
+ const sanitizedCss = sanitizeExperimentStyle(originalState.css)
const elements = document.querySelectorAll(selector)
elements.forEach((element) => {
const htmlElement = element as HTMLElement
if (htmlElement) {
- htmlElement.innerHTML = originalState.html
- htmlElement.setAttribute('style', originalState.css)
+ htmlElement.innerHTML = sanitizedHtml
+ if (sanitizedCss) {
+ htmlElement.setAttribute('style', sanitizedCss)
+ } else {
+ htmlElement.removeAttribute('style')
+ }
}
})
}
)
- // Apply variant transforms
+ // Apply variant transforms — sanitize once per transform, reuse across matches.
selectedVariant.transforms?.forEach((transform) => {
if (transform.selector) {
+ const sanitizedHtml = transform.html ? sanitizeExperimentHTML(transform.html) : null
+ const sanitizedCss = transform.css ? sanitizeExperimentStyle(transform.css) : null
const elements = document.querySelectorAll(transform.selector)
elements.forEach((element) => {
const htmlElement = element as HTMLElement
if (htmlElement) {
- if (transform.html) {
- htmlElement.innerHTML = transform.html
+ if (sanitizedHtml !== null) {
+ htmlElement.innerHTML = sanitizedHtml
}
-
- if (transform.css) {
- htmlElement.setAttribute('style', transform.css)
+ if (sanitizedCss !== null) {
+ if (sanitizedCss) {
+ htmlElement.setAttribute('style', sanitizedCss)
+ } else {
+ htmlElement.removeAttribute('style')
+ }
}
}
})
diff --git a/frontend/src/toolbar/experiments/sanitize.test.ts b/frontend/src/toolbar/experiments/sanitize.test.ts
new file mode 100644
index 000000000000..3dae853307cf
--- /dev/null
+++ b/frontend/src/toolbar/experiments/sanitize.test.ts
@@ -0,0 +1,159 @@
+import {
+ htmlSanitizationWouldStrip,
+ sanitizeExperimentHTML,
+ sanitizeExperimentStyle,
+ setSanitizedHTML,
+ setSanitizedStyle,
+ styleSanitizationWouldStrip,
+} from './sanitize'
+
+describe('experiment sanitize', () => {
+ describe('sanitizeExperimentHTML', () => {
+ it.each([
+ ['empty', '', ''],
+ ['plain text passes through', 'Hello world', 'Hello world'],
+ ['basic markup passes through', '<p><strong>Hi</strong></p>', '<p><strong>Hi</strong></p>'],
+ [
+ 'anchor with href passes through',
+ '<a href="https://example.com">x</a>',
+ '<a href="https://example.com">x</a>',
+ ],
+ ])('%s', (_name, input, expected) => {
+ expect(sanitizeExperimentHTML(input)).toBe(expected)
+ })
+
+ it.each([
+ ['script tag', '<script>alert(1)</script>'],
+ ['img onerror handler', '<img src=x onerror="alert(1)">'],
+ ['svg onload handler', '<svg onload="alert(1)"></svg>'],
+ ['anchor with javascript: href', '<a href="javascript:alert(1)">x</a>'],
+ ['iframe srcdoc', '<iframe srcdoc="<script>alert(1)</script>"></iframe>'],
+ ['form with formaction', '<form action="https://evil/"></form>'],
+ ['object data URL', '<object data="data:text/html,<script>alert(1)</script>"></object>'],
+ ['embed', '<embed src="https://evil/">'],
+ ['link rel', '<link rel="stylesheet" href="https://evil/">'],
+ ['inline style tag with url()', '<style>body{background:url(https://evil/)}</style>'],
+ ['style attribute with url()', '<div style="background:url(https://evil/)">x</div>'],
+ ['style attribute legitimate', '<div style="color:red">x</div>'],
+ ])('strips dangerous content: %s', (_name, input) => {
+ const out = sanitizeExperimentHTML(input)
+ expect(out).not.toMatch(/javascript:/i)
+ expect(out).not.toMatch(/onerror=/i)
+ expect(out).not.toMatch(/onload=/i)
+ expect(out).not.toMatch(/<script/i)
+ expect(out).not.toMatch(/<iframe/i)
+ expect(out).not.toMatch(/<style/i)
+ expect(out).not.toMatch(/<object/i)
+ expect(out).not.toMatch(/<embed/i)
+ expect(out).not.toMatch(/<link/i)
+ expect(out).not.toMatch(/style=/i)
+ expect(out).not.toMatch(/srcdoc=/i)
+ expect(out).not.toMatch(/formaction=/i)
+ })
+ })
+
+ describe('sanitizeExperimentStyle', () => {
+ it('drops url() declarations', () => {
+ const out = sanitizeExperimentStyle('color: red; background-image: url(https://evil/leak)')
+ expect(out).toMatch(/color:\s*red/i)
+ expect(out).not.toMatch(/url\(/i)
+ })
+
+ it.each([
+ 'background-image: image-set(url(https://evil/) 1x)',
+ 'background: -webkit-image-set(url(https://evil/) 1x)',
+ 'background: cross-fade(url(a) 50%, url(b) 50%)',
+ 'background: paint(myPainter)',
+ 'background-image: expression(alert(1))',
+ // CSS character escapes: `\l` is a literal `l`, so the parser resolves to url().
+ 'background-image: ur\\l(https://evil/)',
+ 'background-image: u\\72l(https://evil/)',
+ ])('drops fetching-function declaration: %s', (input) => {
+ const out = sanitizeExperimentStyle(input)
+ expect(out).not.toMatch(/url\(/i)
+ expect(out).not.toMatch(/image-set\(/i)
+ expect(out).not.toMatch(/cross-fade\(/i)
+ expect(out).not.toMatch(/paint\(/i)
+ expect(out).not.toMatch(/expression\(/i)
+ })
+
+ it.each([
+ 'color: red',
+ 'font-weight: bold',
+ 'padding: 10px 20px',
+ 'border: 1px solid #ccc',
+ 'text-decoration: underline',
+ 'transform: translateX(10px)',
+ ])('preserves safe declaration: %s', (input) => {
+ const out = sanitizeExperimentStyle(input)
+ expect(out.length).toBeGreaterThan(0)
+ })
+
+ it.each([
+ ['null', null],
+ ['undefined', undefined],
+ ['empty', ''],
+ ])('returns empty for %s', (_name, input) => {
+ expect(sanitizeExperimentStyle(input as any)).toBe('')
+ })
+ })
+
+ describe('setSanitizedHTML', () => {
+ it('writes sanitized markup to innerHTML', () => {
+ const el = document.createElement('div')
+ // nosemgrep: javascript.lang.security.audit.unknown-value-with-script-tag.unknown-value-with-script-tag
+ setSanitizedHTML(el, '<p>hi<script>alert(1)</script></p>')
+ expect(el.innerHTML).toBe('<p>hi</p>')
+ })
+ })
+
+ describe('setSanitizedStyle', () => {
+ it('writes a sanitized style attribute when content survives', () => {
+ const el = document.createElement('div')
+ setSanitizedStyle(el, 'color: blue; background: url(https://evil/)')
+ const style = el.getAttribute('style') || ''
+ expect(style).toMatch(/blue/)
+ expect(style).not.toMatch(/url\(/)
+ })
+
+ it('removes the style attribute entirely when nothing survives', () => {
+ const el = document.createElement('div')
+ el.setAttribute('style', 'color: red')
+ setSanitizedStyle(el, '')
+ expect(el.hasAttribute('style')).toBe(false)
+ })
+
+ it('removes the style attribute when input is undefined', () => {
+ const el = document.createElement('div')
+ setSanitizedStyle(el, undefined)
+ expect(el.hasAttribute('style')).toBe(false)
+ })
+ })
+
+ describe('htmlSanitizationWouldStrip', () => {
+ it.each([
+ ['null', null, false],
+ ['empty', '', false],
+ ['plain text', 'hi', false],
+ ['safe markup', '<p>hi</p>', false],
+ ['onerror handler', '<img src=x onerror=alert(1)>', true],
+ ['script tag', '<script>x</script>', true],
+ ['style attribute', '<div style="color:red">x</div>', true],
+ ])('%s -> %s', (_name, input, expected) => {
+ expect(htmlSanitizationWouldStrip(input as any)).toBe(expected)
+ })
+ })
+
+ describe('styleSanitizationWouldStrip', () => {
+ it.each([
+ ['null', null, false],
+ ['empty', '', false],
+ ['safe declaration', 'color: red', false],
+ ['safe multi-declaration', 'color: red; padding: 10px', false],
+ ['url()', 'background-image: url(https://evil/)', true],
+ ['mixed safe + unsafe', 'color: red; background: url(https://evil/)', true],
+ ])('%s -> %s', (_name, input, expected) => {
+ expect(styleSanitizationWouldStrip(input as any)).toBe(expected)
+ })
+ })
+})
diff --git a/frontend/src/toolbar/experiments/sanitize.ts b/frontend/src/toolbar/experiments/sanitize.ts
new file mode 100644
index 000000000000..11887c534bcd
--- /dev/null
+++ b/frontend/src/toolbar/experiments/sanitize.ts
@@ -0,0 +1,88 @@
+import DOMPurify, { type Config } from 'dompurify'
+
+// Web-experiment transforms reach the page via innerHTML/style and are fetched
+// against uiHost, which is launch-hash-influenceable — sanitize at the sink.
+
+// USE_PROFILES is the primary allowlist; FORBID_* below are defense-in-depth in case
+// the profile is later changed. `style` is forbidden both as tag and attribute so that
+// CSS exfil channels can't slip through inside HTML payloads — legitimate CSS belongs
+// in transform.css, which goes through sanitizeExperimentStyle.
+const HTML_CONFIG: Config = {
+ FORBID_TAGS: ['script', 'iframe', 'object', 'embed', 'form', 'link', 'meta', 'base', 'style'],
+ FORBID_ATTR: ['srcdoc', 'formaction', 'style'],
+ USE_PROFILES: { html: true },
+}
+
+export function sanitizeExperimentHTML(html: string | undefined | null): string {
+ if (!html) {
+ return ''
+ }
+ return DOMPurify.sanitize(html, HTML_CONFIG)
+}
+
+// url() is the only meaningful exfil channel on inline styles (background-image,
+// cursor, mask-image, list-style-image, border-image). Houdini paint() and the
+// image-set / cross-fade / -webkit-image-set families also resolve to URL fetches.
+const CSS_FETCH_FUNCTIONS = /url\s*\(|image-set\s*\(|-webkit-image-set\s*\(|cross-fade\s*\(|paint\s*\(|expression\s*\(/i
+
+export function sanitizeExperimentStyle(css: string | undefined | null): string {
+ if (!css) {
+ return ''
+ }
+ // Always normalize through CSSOM and test the parsed value. A raw-string check
+ // would miss CSS character escapes like `ur\l(...)` and vendor-prefixed wrappers
+ // that don't embed `url(` — the browser resolves both into a real url() fetch.
+ const probe = document.createElement('div')
+ probe.setAttribute('style', css)
+ const safe = document.createElement('div')
+ for (let i = 0; i < probe.style.length; i++) {
+ const prop = probe.style[i]
+ const value = probe.style.getPropertyValue(prop)
+ if (!CSS_FETCH_FUNCTIONS.test(value)) {
+ safe.style.setProperty(prop, value)
+ }
+ }
+ return safe.getAttribute('style') || ''
+}
+
+export function setSanitizedHTML(el: Element, html: string | undefined | null): void {
+ el.innerHTML = sanitizeExperimentHTML(html)
+}
+
+export function setSanitizedStyle(el: Element, css: string | undefined | null): void {
+ const sanitized = sanitizeExperimentStyle(css)
+ if (sanitized) {
+ el.setAttribute('style', sanitized)
+ } else {
+ el.removeAttribute('style')
+ }
+}
+
+// Predicate helpers for UI affordances. String equality on the sanitized output
+// over-triggers because the browser normalizes CSS whitespace and case during
+// the setAttribute/getAttribute round-trip.
+
+export function htmlSanitizationWouldStrip(html: string | undefined | null): boolean {
+ if (!html) {
+ return false
+ }
+ return sanitizeExperimentHTML(html).length < html.length
+}
+
+export function styleSanitizationWouldStrip(css: string | undefined | null): boolean {
+ if (!css) {
+ return false
+ }
+ // Compare property counts on the normalized form so CSS escapes / vendor wrappers
+ // are correctly flagged. Whitespace-only and string-shape differences don't trip it.
+ const probe = document.createElement('div')
+ probe.setAttribute('style', css)
+ const before = probe.style.length
+ let after = 0
+ for (let i = 0; i < probe.style.length; i++) {
+ if (!CSS_FETCH_FUNCTIONS.test(probe.style.getPropertyValue(probe.style[i]))) {
+ after++
+ }
+ }
+ return after < before
+}
diff --git a/frontend/src/toolbar/toolbarAuth.ts b/frontend/src/toolbar/toolbarAuth.ts
index 7a812e3812e6..34c212c7ea59 100644
--- a/frontend/src/toolbar/toolbarAuth.ts
+++ b/frontend/src/toolbar/toolbarAuth.ts
@@ -1,5 +1,8 @@
+import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
+
import { toolbarLogger } from '~/toolbar/toolbarLogger'
import { captureToolbarException, toolbarPosthogJS } from '~/toolbar/toolbarPosthogJS'
+import { asNonEmptyString } from '~/toolbar/utils'
import { toolbarConfigLogic } from './toolbarConfigLogic'
@@ -73,11 +76,23 @@ export async function withTokenRefresh(
if (!toolbarConfigLogic.findMounted()) {
return response
}
- toolbarConfigLogic.actions.setOAuthTokens(tokens.access_token, tokens.refresh_token, clientId)
- return await retryRequest(tokens.access_token)
+ const access = asNonEmptyString(tokens?.access_token)
+ const refresh = asNonEmptyString(tokens?.refresh_token)
+ if (!access || !refresh) {
+ toolbarLogger.warn('auth', 'Refresh response missing string tokens, discarding')
+ // Refresh fired in response to a user action (not mount-time restore), so the
+ // tokenExpired suppression by source !== 'localstorage' doesn't apply — surface
+ // a toast directly so the user knows why the action failed.
+ lemonToast.error('Please re-authenticate to continue using the toolbar.')
+ toolbarConfigLogic.actions.tokenExpired()
+ return response
+ }
+ toolbarConfigLogic.actions.setOAuthTokens(access, refresh, clientId)
+ return await retryRequest(access)
} catch (e) {
toolbarLogger.error('auth', 'Token refresh retry failed', { status: response.status })
captureToolbarException(e, 'token_refresh_retry')
+ lemonToast.error('Please re-authenticate to continue using the toolbar.')
toolbarConfigLogic.actions.tokenExpired()
return response
}
diff --git a/frontend/src/toolbar/toolbarConfigLogic.test.ts b/frontend/src/toolbar/toolbarConfigLogic.test.ts
index dc2f7efcf6eb..68c904061a9d 100644
--- a/frontend/src/toolbar/toolbarConfigLogic.test.ts
+++ b/frontend/src/toolbar/toolbarConfigLogic.test.ts
@@ -1379,4 +1379,108 @@ describe('toolbar toolbarConfigLogic', () => {
expect(uploadAttempts).toHaveLength(0)
})
})
+
+ describe('hash-supplied prop type validation', () => {
+ it.each([
+ ['boolean true', true],
+ ['number 1', 1],
+ ['object', { foo: 'bar' }],
+ ['array', ['a']],
+ ['empty string', ''],
+ ['null', null],
+ ['undefined', undefined],
+ ])('rejects non-string accessToken: %s', (_label, badToken) => {
+ const logic = toolbarConfigLogic.build({
+ uiHost: 'https://us.posthog.com',
+ accessToken: badToken as any,
+ } as any)
+ logic.mount()
+ expectLogic(logic).toMatchValues({ accessToken: null, isAuthenticated: false })
+ })
+
+ it('accepts string accessToken', () => {
+ const logic = toolbarConfigLogic.build({
+ uiHost: 'https://us.posthog.com',
+ accessToken: 'pha_real',
+ } as any)
+ logic.mount()
+ expectLogic(logic).toMatchValues({ accessToken: 'pha_real', isAuthenticated: true })
+ })
+
+ it.each([
+ ['edit-experiment', 'edit-experiment'],
+ ['add-action', 'add-action'],
+ ['heatmaps', 'heatmaps'],
+ ])('accepts valid userIntent: %s', (_label, intent) => {
+ const logic = toolbarConfigLogic.build({
+ uiHost: 'https://us.posthog.com',
+ userIntent: intent as any,
+ } as any)
+ logic.mount()
+ expectLogic(logic).toMatchValues({ userIntent: intent })
+ })
+
+ it.each([
+ ['unknown string', 'totally-not-a-real-intent'],
+ ['boolean', true],
+ ['number', 1],
+ ['empty', ''],
+ ])('rejects invalid userIntent: %s', (_label, intent) => {
+ const logic = toolbarConfigLogic.build({
+ uiHost: 'https://us.posthog.com',
+ userIntent: intent as any,
+ } as any)
+ logic.mount()
+ expectLogic(logic).toMatchValues({ userIntent: null })
+ })
+ })
+
+ describe('toolbarFetch use-as-provided origin pin', () => {
+ beforeEach(() => {
+ const logic = toolbarConfigLogic.build({
+ uiHost: 'https://us.posthog.com',
+ apiURL: 'https://us.posthog.com',
+ accessToken: 'pha_token',
+ refreshToken: 'phr_token',
+ clientId: 'client',
+ } as any)
+ logic.mount()
+ ;(global.fetch as jest.Mock).mockClear()
+ })
+
+ it('allows URLs whose origin matches uiHost', async () => {
+ ;(global.fetch as jest.Mock).mockResolvedValueOnce({
+ ok: true,
+ status: 200,
+ json: () => Promise.resolve({ results: [{ id: 1 }] }),
+ } as any)
+ const res = await toolbarFetch(
+ 'https://us.posthog.com/api/element/stats/?page=2',
+ 'GET',
+ undefined,
+ 'use-as-provided'
+ )
+ expect(res.status).toBe(200)
+ const sentUrl = (global.fetch as jest.Mock).mock.calls[0][0]
+ expect(sentUrl).toBe('https://us.posthog.com/api/element/stats/?page=2')
+ })
+
+ it('rejects cross-origin URLs with status 400 and results: []', async () => {
+ const res = await toolbarFetch('https://evil.example.com/leak', 'GET', undefined, 'use-as-provided')
+ expect(res.status).toBe(400)
+ const body = await res.json()
+ expect(body.detail).toBe('origin_mismatch')
+ expect(body.results).toEqual([])
+ // No outgoing fetch happened
+ expect((global.fetch as jest.Mock).mock.calls).toHaveLength(0)
+ })
+
+ it('rejects malformed URLs with status 400', async () => {
+ const res = await toolbarFetch('not a url', 'GET', undefined, 'use-as-provided')
+ expect(res.status).toBe(400)
+ const body = await res.json()
+ expect(body.detail).toBe('invalid_url')
+ expect(body.results).toEqual([])
+ })
+ })
})
diff --git a/frontend/src/toolbar/toolbarConfigLogic.ts b/frontend/src/toolbar/toolbarConfigLogic.ts
index c656ba6839a6..9f78dc9fda34 100644
--- a/frontend/src/toolbar/toolbarConfigLogic.ts
+++ b/frontend/src/toolbar/toolbarConfigLogic.ts
@@ -5,11 +5,12 @@ import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { toolbarLogger } from '~/toolbar/toolbarLogger'
import { captureToolbarException, toolbarPosthogJS } from '~/toolbar/toolbarPosthogJS'
-import { ToolbarProps } from '~/types'
+import { TOOLBAR_USER_INTENTS, ToolbarProps, ToolbarUserIntent } from '~/types'
import { withTokenRefresh } from './toolbarAuth'
import type { toolbarConfigLogicType } from './toolbarConfigLogicType'
import {
+ asNonEmptyString,
cleanToolbarAuthHash,
generatePKCE,
LOCALSTORAGE_KEY,
@@ -20,6 +21,13 @@ import {
export type ApiHostSource = 'posthog_api_host' | 'api_url' | 'fallback_rejected' | 'fallback_absent'
+const VALID_USER_INTENTS: ReadonlySet<ToolbarUserIntent> = new Set(TOOLBAR_USER_INTENTS)
+
+const asUserIntent = (v: unknown): ToolbarUserIntent | null => {
+ const s = asNonEmptyString(v)
+ return s && VALID_USER_INTENTS.has(s as ToolbarUserIntent) ? (s as ToolbarUserIntent) : null
+}
+
export const toolbarConfigLogic = kea<toolbarConfigLogicType>([
path(['toolbar', 'toolbarConfigLogic']),
props({} as ToolbarProps),
@@ -50,33 +58,33 @@ export const toolbarConfigLogic = kea<toolbarConfigLogicType>([
// TRICKY: We cache a copy of the props. This allows us to connect the logic without passing the props in - only the top level caller has to do this.
props: [props],
accessToken: [
- props.accessToken || null,
+ asNonEmptyString(props.accessToken),
{
- setOAuthTokens: (_, { accessToken }) => accessToken,
+ setOAuthTokens: (_, { accessToken }) => asNonEmptyString(accessToken),
logout: () => null,
tokenExpired: () => null,
},
],
refreshToken: [
- props.refreshToken || null,
+ asNonEmptyString(props.refreshToken),
{
- setOAuthTokens: (_, { refreshToken }) => refreshToken,
+ setOAuthTokens: (_, { refreshToken }) => asNonEmptyString(refreshToken),
logout: () => null,
tokenExpired: () => null,
},
],
clientId: [
- props.clientId || null,
+ asNonEmptyString(props.clientId),
{
- setOAuthTokens: (_, { clientId }) => clientId,
+ setOAuthTokens: (_, { clientId }) => asNonEmptyString(clientId),
logout: () => null,
tokenExpired: () => null,
},
],
actionId: [props.actionId || null, { logout: () => null, clearUserIntent: () => null }],
experimentId: [props.experimentId || null, { logout: () => null, clearUserIntent: () => null }],
- productTourId: [props.productTourId || null, { logout: () => null, clearUserIntent: () => null }],
- userIntent: [props.userIntent || null, { logout: () => null, clearUserIntent: () => null }],
+ productTourId: [asNonEmptyString(props.productTourId), { logout: () => null, clearUserIntent: () => null }],
+ userIntent: [asUserIntent(props.userIntent), { logout: () => null, clearUserIntent: () => null }],
buttonVisible: [true, { showButton: () => true, hideButton: () => false, logout: () => false }],
authStatus: [
'idle' as 'idle' | 'checking' | 'authenticating' | 'error',
@@ -740,21 +748,24 @@ async function exchangeCodeForTokens(
body: body.toString(),
})
const data = await res.json()
- if (data.access_token && data.refresh_token) {
+ const access = asNonEmptyString(data?.access_token)
+ const refresh = asNonEmptyString(data?.refresh_token)
+ if (access && refresh) {
toolbarPosthogJS.capture('toolbar oauth exchange', {
status: 'success',
duration_ms: Math.round(performance.now() - startTime),
})
- actions.setOAuthTokens(data.access_token, data.refresh_token, clientId)
+ actions.setOAuthTokens(access, refresh, clientId)
return true
}
+ const errorString = asNonEmptyString(data?.error) ?? 'unknown'
toolbarPosthogJS.capture('toolbar oauth exchange', {
status: 'error',
- error: data.error || 'unknown',
+ error: errorString,
duration_ms: Math.round(performance.now() - startTime),
})
- toolbarLogger.error('auth', 'Token exchange failed', { error: data.error || data })
- captureToolbarException(new Error(`Token exchange failed: ${data.error || 'unknown'}`), 'token_exchange')
+ toolbarLogger.error('auth', 'Token exchange failed', { error: errorString })
+ captureToolbarException(new Error(`Token exchange failed: ${errorString}`), 'token_exchange')
lemonToast.error('Authentication failed. Please try again.')
return false
} catch (err) {
@@ -793,6 +804,34 @@ export async function toolbarFetch(
let fullUrl: string
if (urlConstruction === 'use-as-provided') {
+ // Pagination URLs come from response bodies — pin to uiHost (or apiHost, which
+ // is where Django's build_absolute_uri() sources its host) so they cannot
+ // redirect the Authorization header off-origin. Stub body matches the 401
+ // shape above so paginating callers fail gracefully on `results: []`.
+ const apiHost = logic?.values.apiHost
+ const allowedOrigins = [host, apiHost].filter(Boolean).map((h) => {
+ try {
+ return new URL(h as string).origin
+ } catch {
+ return null
+ }
+ })
+ if (allowedOrigins.length === 0) {
+ return new Response(JSON.stringify({ results: [], detail: 'no_uihost' }), { status: 400 })
+ }
+ let got: string
+ try {
+ got = new URL(url).origin
+ } catch {
+ return new Response(JSON.stringify({ results: [], detail: 'invalid_url' }), { status: 400 })
+ }
+ if (!allowedOrigins.includes(got)) {
+ toolbarLogger.warn('fetch', 'use-as-provided URL origin not in allowlist', {
+ allowed: allowedOrigins,
+ got,
+ })
+ return new Response(JSON.stringify({ results: [], detail: 'origin_mismatch' }), { status: 400 })
+ }
fullUrl = url
} else {
const { pathname, searchParams } = combineUrl(url)
diff --git a/frontend/src/toolbar/utils.test.ts b/frontend/src/toolbar/utils.test.ts
index 8bf1811dbb00..019a53966e1b 100644
--- a/frontend/src/toolbar/utils.test.ts
+++ b/frontend/src/toolbar/utils.test.ts
@@ -1,6 +1,25 @@
-import { joinWithUiHost, slashDotDataAttrUnescape } from './utils'
+import { asNonEmptyString, joinWithUiHost, slashDotDataAttrUnescape } from './utils'
describe('utils', () => {
+ describe('asNonEmptyString', () => {
+ const testCases: Array<{ input: unknown; expected: string | null }> = [
+ { input: 'hello', expected: 'hello' },
+ { input: '', expected: null },
+ { input: null, expected: null },
+ { input: undefined, expected: null },
+ { input: true, expected: null },
+ { input: false, expected: null },
+ { input: 0, expected: null },
+ { input: 1, expected: null },
+ { input: {}, expected: null },
+ { input: [], expected: null },
+ { input: ['a'], expected: null },
+ ]
+ it.each(testCases)('$input -> $expected', ({ input, expected }) => {
+ expect(asNonEmptyString(input)).toBe(expected)
+ })
+ })
+
describe('joinWithUiHost', () => {
const testCases: Array<{ uiHost: string; path: string; expected: string }> = [
{
diff --git a/frontend/src/toolbar/utils.ts b/frontend/src/toolbar/utils.ts
index 762d48823a81..32385ff210ee 100644
--- a/frontend/src/toolbar/utils.ts
+++ b/frontend/src/toolbar/utils.ts
@@ -15,6 +15,10 @@ import { ActionStepPropertyKey } from './actions/ActionStep'
export const TOOLBAR_ID = '__POSTHOG_TOOLBAR__'
+// Props arrive via the `__posthog=<base64>` URL fragment, so the static type is not
+// load-bearing at runtime — verify before storing strings that flow into auth headers.
+export const asNonEmptyString = (v: unknown): string | null => (typeof v === 'string' && v.length > 0 ? v : null)
+
const elementToQueryCache = new WeakMap<HTMLElement, string | undefined>()
export const TOOLBAR_CONTAINER_CLASS = 'toolbar-global-fade-container'
export const LOCALSTORAGE_KEY = '_postHogToolbarParams'
diff --git a/frontend/src/types.ts b/frontend/src/types.ts
index 0ee72f3ebaf7..8a9bf008eb7c 100644
--- a/frontend/src/types.ts
+++ b/frontend/src/types.ts
@@ -847,6 +847,8 @@ export interface ElementType {
text?: string
}
+// Keep the union literal so kea-typegen can inline its members; the runtime allowlist below
+// is asserted to satisfy the same members so TypeScript fails the build if either side drifts.
export type ToolbarUserIntent =
| 'add-action'
| 'edit-action'
@@ -856,6 +858,17 @@ export type ToolbarUserIntent =
| 'add-product-tour'
| 'edit-product-tour'
| 'preview-product-tour'
+
+export const TOOLBAR_USER_INTENTS = [
+ 'add-action',
+ 'edit-action',
+ 'heatmaps',
+ 'add-experiment',
+ 'edit-experiment',
+ 'add-product-tour',
+ 'edit-product-tour',
+ 'preview-product-tour',
+] as const satisfies readonly ToolbarUserIntent[]
export type ToolbarSource = 'url' | 'localstorage'
export type ToolbarVersion = 'toolbar'