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(csp): clear the first-party loads the narrowed policy still reports (#104811)

Tom Piccirelloe088deb00efd
diff --git a/frontend/src/lib/logic/featureFlagLogic.test.ts b/frontend/src/lib/logic/featureFlagLogic.test.ts
index 8d6617fa5e7e..19faae006b10 100644
--- a/frontend/src/lib/logic/featureFlagLogic.test.ts
+++ b/frontend/src/lib/logic/featureFlagLogic.test.ts
@@ -1,13 +1,39 @@
-import { areClientFeatureFlagsHonored } from './featureFlagLogic'
-
-describe('areClientFeatureFlagsHonored', () => {
- it.each([
- [null, false],
- [{ cloud: false, is_debug: false }, false],
- [{ cloud: true, is_debug: false }, true],
- [{ cloud: false, is_debug: true }, true],
- [{ cloud: true, is_debug: true }, true],
- ])('preflight %s returns %s', (preflight, expected) => {
- expect(areClientFeatureFlagsHonored(preflight)).toBe(expected)
+import posthog from 'posthog-js'
+
+import { initKeaTests } from '~/test/init'
+
+import { areClientFeatureFlagsHonored, featureFlagLogic } from './featureFlagLogic'
+
+describe('featureFlagLogic', () => {
+ describe('areClientFeatureFlagsHonored', () => {
+ it.each([
+ [null, false],
+ [{ cloud: false, is_debug: false }, false],
+ [{ cloud: true, is_debug: false }, true],
+ [{ cloud: false, is_debug: true }, true],
+ [{ cloud: true, is_debug: true }, true],
+ ])('preflight %s returns %s', (preflight, expected) => {
+ expect(areClientFeatureFlagsHonored(preflight)).toBe(expected)
+ })
+ })
+
+ describe('receivedFeatureFlags', () => {
+ afterEach(() => {
+ delete (posthog as any).config
+ })
+
+ // The mocked onFeatureFlags never calls back, as posthog-js does not when flags are off.
+ it.each([
+ ['flags disabled', { advanced_disable_flags: true }, true],
+ ['flags enabled', { advanced_disable_flags: false }, false],
+ ])('with %s is %s before any flags arrive', (_name, config, expected) => {
+ ;(posthog as any).config = config
+ initKeaTests()
+
+ const logic = featureFlagLogic()
+ logic.mount()
+
+ expect(logic.values.receivedFeatureFlags).toBe(expected)
+ })
})
})
diff --git a/frontend/src/lib/logic/featureFlagLogic.ts b/frontend/src/lib/logic/featureFlagLogic.ts
index 56b073493702..822e9ee93a6f 100644
--- a/frontend/src/lib/logic/featureFlagLogic.ts
+++ b/frontend/src/lib/logic/featureFlagLogic.ts
@@ -142,5 +142,10 @@ export const featureFlagLogic = kea<featureFlagLogicType>([
}),
afterMount(({ actions }) => {
posthog.onFeatureFlags(actions.setFeatureFlags)
+ if (posthog.config?.advanced_disable_flags) {
+ // posthog-js never calls back when flags are off, and the app holds its first render
+ // until this arrives. A page with no project key has no flags to wait for.
+ actions.setFeatureFlags([], {})
+ }
}),
])
diff --git a/frontend/src/loadPostHogJS.test.ts b/frontend/src/loadPostHogJS.test.ts
index 12d3860c87a9..13ab6a273c2f 100644
--- a/frontend/src/loadPostHogJS.test.ts
+++ b/frontend/src/loadPostHogJS.test.ts
@@ -1,12 +1,28 @@
+import posthog from 'posthog-js'
import { sampleOnProperty } from 'posthog-js/lib/src/extensions/sampling'
-import { isInDeferredInitSample } from './loadPostHogJS'
+import { isInDeferredInitSample, loadPostHogJS } from './loadPostHogJS'
-describe('isInDeferredInitSample', () => {
- it.each(['', 'a', '0198f1e2-9c3b-7a1d-8f4e-2b6c9d0e1f23', 'session-one', 'session-two', 'session-three'])(
- 'keeps the posthog-js sampling verdict for session %p',
- (sessionId) => {
- expect(isInDeferredInitSample(sessionId)).toBe(sampleOnProperty(sessionId, 0.5))
- }
- )
+describe('loadPostHogJS', () => {
+ describe('isInDeferredInitSample', () => {
+ it.each(['', 'a', '0198f1e2-9c3b-7a1d-8f4e-2b6c9d0e1f23', 'session-one', 'session-two', 'session-three'])(
+ 'keeps the posthog-js sampling verdict for session %p',
+ (sessionId) => {
+ expect(isInDeferredInitSample(sessionId)).toBe(sampleOnProperty(sessionId, 0.5))
+ }
+ )
+ })
+
+ describe('without a project key', () => {
+ it('starts posthog-js with no request to PostHog', () => {
+ window.JS_POSTHOG_API_KEY = undefined
+
+ loadPostHogJS()
+
+ expect(posthog.init).toHaveBeenCalledWith(
+ 'fake_token',
+ expect.objectContaining({ advanced_disable_flags: true })
+ )
+ })
+ })
})
diff --git a/frontend/src/loadPostHogJS.tsx b/frontend/src/loadPostHogJS.tsx
index c5716a154b03..07dcaacd8382 100644
--- a/frontend/src/loadPostHogJS.tsx
+++ b/frontend/src/loadPostHogJS.tsx
@@ -190,6 +190,10 @@ export function loadPostHogJS(options: LoadPostHogJSOptions = {}): void {
} else {
posthog.init('fake_token', {
autocapture: false,
+ // Pages without a project key only need `posthog` calls to be safe no-ops. Without this,
+ // init() fetches remote config and flags for the placeholder token from PostHog Cloud
+ // before `loaded` can opt out.
+ advanced_disable_flags: true,
loaded: function (ph) {
ph.opt_out_capturing()
},
diff --git a/frontend/src/scenes/onboarding/legacy/sdks/hooks/useAdblockDetection.ts b/frontend/src/scenes/onboarding/legacy/sdks/hooks/useAdblockDetection.ts
index cbf8d060c972..b42773c245a2 100644
--- a/frontend/src/scenes/onboarding/legacy/sdks/hooks/useAdblockDetection.ts
+++ b/frontend/src/scenes/onboarding/legacy/sdks/hooks/useAdblockDetection.ts
@@ -1,6 +1,8 @@
import posthog from 'posthog-js'
import { useEffect, useRef, useState } from 'react'
+import { apiHostOrigin } from 'lib/utils/apiHost'
+
export type AdblockDetectionResult = 'unknown' | 'blocked' | 'ok'
/**
@@ -32,7 +34,7 @@ export function useAdblockDetection(delayMs: number = 20_000): AdblockDetectionR
// Check 2 – attempt a fetch to the ingestion endpoint
try {
- await fetch('https://us.i.posthog.com/decide/?v=3', {
+ await fetch(`${apiHostOrigin()}/decide/?v=3`, {
method: 'POST',
mode: 'no-cors',
body: JSON.stringify({}),
diff --git a/posthog/middleware.py b/posthog/middleware.py
index 2f984a617e62..3e953c17fe23 100644
--- a/posthog/middleware.py
+++ b/posthog/middleware.py
@@ -41,7 +41,7 @@ from statshog.defaults.django import statsd
from posthog.api.shared import UserBasicSerializer
from posthog.clickhouse.client.execute import clickhouse_query_counter
from posthog.clickhouse.query_tagging import QueryCounter, get_query_tag_value, reset_query_tags, tag_queries
-from posthog.cloud_utils import is_cloud, is_dev_mode
+from posthog.cloud_utils import get_api_host, is_cloud, is_dev_mode
from posthog.constants import AUTH_BACKEND_KEYS, POSTHOG_JS_CLOUD_HOST, POSTHOG_JS_CLOUD_TOKEN
from posthog.event_usage import get_event_source, get_mcp_properties, sanitize_header_value
from posthog.geoip import get_geoip_properties
@@ -1655,6 +1655,12 @@ class CSPMiddleware:
shadow_parts: list[str] = []
if report_uri and is_cloud() and resource_url == "https://*.posthog.com" and not settings.E2E_TESTING:
bundle = [bundle_origin] if bundle_origin else []
+ agent_proxy_url = settings.TASKS_AGENT_PROXY_PUBLIC_URL
+ agent_proxy = (
+ [urlsplit(agent_proxy_url)._replace(path="", query="", fragment="").geturl()]
+ if agent_proxy_url
+ else []
+ )
replacements = {
# posthog-js loads its extensions from /static/ and our project's remote config. The
# config path names our token because the same path serves every project's config.
@@ -1668,6 +1674,10 @@ class CSPMiddleware:
*bundle,
POSTHOG_JS_CLOUD_HOST,
f"https://live.{urlsplit(settings.SITE_URL).hostname}",
+ # The onboarding adblock check probes the region's ingestion host.
+ f"{get_api_host()}/decide/",
+ # A task run's live stream, when the server hands out the region's agent-proxy.
+ *agent_proxy,
],
}
shadow_uri = csp_report_endpoint(sample_rate=sample_rate, v=NARROWED_APP_POLICY_REPORT_VERSION)
diff --git a/posthog/test/test_middleware.py b/posthog/test/test_middleware.py
index 5d0b80a21a25..eefe1cf65b35 100644
--- a/posthog/test/test_middleware.py
+++ b/posthog/test/test_middleware.py
@@ -3,6 +3,7 @@ import json
import hashlib
from datetime import datetime, timedelta
from typing import Any, cast
+from urllib.parse import urlsplit
import pytest
import time_machine
@@ -2382,13 +2383,24 @@ class TestCSPMiddleware(APIBaseTest):
@parameterized.expand(
[
(
- "cloud",
+ "cloud_us",
{
"CLOUD_DEPLOYMENT": "US",
"SITE_URL": "https://us.posthog.com",
"JS_URL": "https://app-static-prod.posthog.com",
+ "TASKS_AGENT_PROXY_PUBLIC_URL": "https://agent-proxy.us.posthog.com",
+ },
+ ("us", "eu"),
+ ),
+ (
+ "cloud_eu",
+ {
+ "CLOUD_DEPLOYMENT": "EU",
+ "SITE_URL": "https://eu.posthog.com",
+ "JS_URL": "https://app-static.eu.posthog.com",
+ "TASKS_AGENT_PROXY_PUBLIC_URL": "https://agent-proxy.eu.posthog.com/",
},
- True,
+ ("eu", "us"),
),
# An operator can turn reporting on for their own install, but the shadow names PostHog
# Cloud's hosts and token, so its reports would tell that operator nothing they can act on.
@@ -2399,11 +2411,11 @@ class TestCSPMiddleware(APIBaseTest):
"SITE_URL": "https://posthog.example.com",
"CSP_REPORT_ENDPOINT": "https://posthog.example.com/report/?token=phc_test&v=2",
},
- False,
+ None,
),
]
)
- def test_only_cloud_pages_carry_a_report_only_shadow_without_the_wildcards(self, _name, overrides, expects_shadow):
+ def test_only_cloud_pages_carry_a_report_only_shadow_without_the_wildcards(self, _name, overrides, regions):
# The shadow is the evidence for dropping the wildcards, so it must report on its own version
# and must not quietly keep a wildcard.
with override_settings(TEST=False, DEBUG=False, **overrides):
@@ -2412,13 +2424,19 @@ class TestCSPMiddleware(APIBaseTest):
app_policy, *shadows = response["Content-Security-Policy-Report-Only"].split(", ")
assert "https://*.posthog.com" in app_policy
assert "&v=2&" in app_policy
- assert len(shadows) == (1 if expects_shadow else 0)
- if expects_shadow:
+ assert len(shadows) == (1 if regions else 0)
+ if regions:
+ region, other_region = regions
shadow = shadows[0]
assert "*.posthog.com" not in shadow
assert "https://internal-j.posthog.com/array/sTMFPsFhdP1Ssg/config.js" in shadow
- assert "https://live.us.posthog.com" in shadow
assert "&v=3&" in shadow
+ connect_src = next(part for part in shadow.split("; ") if part.startswith("connect-src ")).split()
+ assert f"https://live.{region}.posthog.com" in connect_src
+ assert f"https://{region}.i.posthog.com/decide/" in connect_src
+ assert f"https://agent-proxy.{region}.posthog.com" in connect_src
+ # Allowing the other region would hide a request that crossed regions by mistake.
+ assert not any(other_region in (urlsplit(source).hostname or "").split(".") for source in connect_src)
class TestSocialAuthExceptionMiddleware(APIBaseTest):