: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
chore(csp): give the content security policy its own file (#105569)
Tom Piccirello2b045f20731c
diff --git a/.agents/security.md b/.agents/security.mdindex e7a7259f57e7..7ab7df099c18 100644--- a/.agents/security.md+++ b/.agents/security.md@@ -160,8 +160,9 @@ docker run --rm -v "${PWD}:/src" semgrep/semgrep semgrep --test /src/.semgrep/ru## Content Security Policy-`CSPMiddleware` in `posthog/middleware.py` attaches a policy to every HTML response.+`CSPMiddleware` in `posthog/csp_middleware.py` attaches a policy to every HTML response.Treat it as enforced.+team-security owns that file in `.github/CODEOWNERS`, so every policy change needs their approval.A refused resource produces no user-visible error, so the feature simply does not work, and the only signal is a `$csp_violation` event in project 2.Three policies exist, and a change lands in whichever one covers the page:@@ -194,6 +195,8 @@ Add the source to the policy that covers the document, which is not always `CSPMAn app or admin page takes the matching list in `CSPMiddleware`.A canvas artifact takes `artifact_csp()` in `products/canvas/backend/contract.py`, and a workflow message asset takes the header its endpoint sets in `products/workflows/backend/api/hog_flow.py`.`CSPMiddleware` returns a view-set header untouched, so widening the app policy does nothing for those two.-Say why the source is needed in a comment either way, then run `posthog/test/test_middleware.py::TestCSPMiddleware`.+Say why the source is needed in a comment either way, then run `posthog/test/test_csp_middleware.py`.+The `csp-header-outside-csp-middleware` semgrep rule blocks a `Content-Security-Policy` header set anywhere else.+A new document that must carry its own policy needs team-security to add it to that rule's exceptions.To see what the policy currently blocks, query `$csp_violation` events in project 2.Filter to the current policy text and exclude browser extensions on both the source file and the blocked URL, or the result is mostly noise.diff --git a/.github/CODEOWNERS b/.github/CODEOWNERSindex c1d520e22a1f..934933f5b2e7 100644--- a/.github/CODEOWNERS+++ b/.github/CODEOWNERS@@ -57,6 +57,16 @@ posthog/api/authentication.py @PostHog/team-securityposthog/auth.py @PostHog/team-securityee/api/scim/auth.py @PostHog/team-security+# The Content Security Policy every app and admin page carries. A browser refuses a resource the+# policy does not name and shows the user no error, so a policy mistake breaks a feature with no+# signal, and a widened directive removes a control the same way. Neither shows up in a test or a+# stack trace, which is why review is the control. The semgrep rule stops a view from setting the+# header outside this file, and each exception it carries names the policy it allows, so a fourth+# document needs this team too.+posthog/csp_middleware.py @PostHog/team-security+posthog/test/test_csp_middleware.py @PostHog/team-security+.semgrep/rules/security/csp-header-outside-csp-middleware.* @PostHog/team-security+# Dev sandbox provides important protection in local devbin/dev-sandbox* @PostHog/team-securitydiff --git a/.semgrep/rules/security/csp-header-outside-csp-middleware.py b/.semgrep/rules/security/csp-header-outside-csp-middleware.pynew file mode 100644index 000000000000..2522c3dc7c6c--- /dev/null+++ b/.semgrep/rules/security/csp-header-outside-csp-middleware.py@@ -0,0 +1,98 @@+# Test cases for csp-header-outside-csp-middleware rule+# ruff: noqa: F821, F841, E501 — assignments exist solely to give semgrep something to match++from django.http import HttpResponse+++def flag_subscript_assignment(response):+ # ruleid: csp-header-outside-csp-middleware+ response["Content-Security-Policy"] = "default-src 'none'"+++def flag_headers_assignment(response):+ # ruleid: csp-header-outside-csp-middleware+ response.headers["Content-Security-Policy"] = "default-src 'self'"+++def flag_report_only_header(response):+ # ruleid: csp-header-outside-csp-middleware+ response.headers["Content-Security-Policy-Report-Only"] = "default-src 'self'"+++def flag_lowercase_header(response):+ # ruleid: csp-header-outside-csp-middleware+ response["content-security-policy"] = "default-src 'none'"+++def flag_setdefault(response):+ # ruleid: csp-header-outside-csp-middleware+ response.headers.setdefault("Content-Security-Policy", "default-src 'none'")+++def flag_headers_update(response):+ # ruleid: csp-header-outside-csp-middleware+ response.headers.update({"X-Frame-Options": "DENY", "Content-Security-Policy": "sandbox"})+++def flag_response_constructor():+ # ruleid: csp-header-outside-csp-middleware+ return HttpResponse("<p>hi</p>", headers={"Content-Security-Policy": "sandbox"})+++def ok_canvas_artifact_policy(response, network_origins):+ # ok: csp-header-outside-csp-middleware+ response["Content-Security-Policy"] = artifact_csp(network_origins)+++def ok_public_survey_policy(request, response):+ # ok: csp-header-outside-csp-middleware+ response["Content-Security-Policy"] = _public_survey_csp(request)+++def ok_workflow_asset_policy(response):+ # ok: csp-header-outside-csp-middleware+ response["Content-Security-Policy"] = (+ "sandbox; default-src 'none'; img-src https: data:; style-src 'unsafe-inline'"+ )+++def flag_report_only_canvas_artifact_policy(response, network_origins):+ # ruleid: csp-header-outside-csp-middleware+ response["Content-Security-Policy-Report-Only"] = artifact_csp(network_origins)+++def flag_report_only_public_survey_policy(request, response):+ # ruleid: csp-header-outside-csp-middleware+ response["Content-Security-Policy-Report-Only"] = _public_survey_csp(request)+++def flag_report_only_workflow_asset_policy(response):+ # ruleid: csp-header-outside-csp-middleware+ response["Content-Security-Policy-Report-Only"] = (+ "sandbox; default-src 'none'; img-src https: data:; style-src 'unsafe-inline'"+ )+++def flag_changed_workflow_asset_policy(response):+ # ruleid: csp-header-outside-csp-middleware+ response["Content-Security-Policy"] = "sandbox; default-src 'none'; img-src https: data:; script-src 'self'"+++def flag_second_policy_in_an_excepted_file(response):+ # ruleid: csp-header-outside-csp-middleware+ response["Content-Security-Policy"] = "default-src 'none'; frame-ancestors *"+++def ok_other_security_header(response):+ # ok: csp-header-outside-csp-middleware+ response["X-Content-Type-Options"] = "nosniff"+++def ok_reads_the_header(response):+ # ok: csp-header-outside-csp-middleware+ return "Content-Security-Policy" in response.headers+++def ok_reporting_endpoints_header(response):+ # ok: csp-header-outside-csp-middleware+ response.headers["Reporting-Endpoints"] = 'posthog="https://example.com/report/"'diff --git a/.semgrep/rules/security/csp-header-outside-csp-middleware.yaml b/.semgrep/rules/security/csp-header-outside-csp-middleware.yamlnew file mode 100644index 000000000000..07db21d8d662--- /dev/null+++ b/.semgrep/rules/security/csp-header-outside-csp-middleware.yaml@@ -0,0 +1,43 @@+rules:+ - id: csp-header-outside-csp-middleware+ message: >-+ Do not set a `Content-Security-Policy` header here. The policy the app serves lives in+ `posthog/csp_middleware.py`, which team-security owns in `.github/CODEOWNERS`, so a+ policy change gets a security review. A header set on a view escapes that review, and+ `CSPMiddleware` returns a response that already carries one unchanged, so it also drops+ the app policy for that document. Widen the matching list in `posthog/csp_middleware.py`+ instead. A document that must carry its own sandbox, such as untrusted HTML, needs+ team-security to add the path to this rule's `paths.exclude`.+ severity: ERROR+ languages: [python]+ patterns:+ - pattern-either:+ - pattern: $RESPONSE[$HEADER] = $POLICY+ - pattern: $RESPONSE.headers[$HEADER] = $POLICY+ - pattern: $RESPONSE.setdefault($HEADER, $POLICY)+ - pattern: $RESPONSE.headers.setdefault($HEADER, $POLICY)+ - pattern: '$RESPONSE.headers.update({..., $HEADER: $POLICY, ...})'+ - pattern: '$RESPONSE_CLASS(..., headers={..., $HEADER: $POLICY, ...})'+ - metavariable-regex:+ metavariable: $HEADER+ regex: (?i)^["']?content-security-policy(-report-only)?["']?$+ # Three documents sandbox untrusted HTML, so each carries a policy of its own rather than+ # the app policy. Each exception names the policy it allows, not the file, so a fourth+ # document in the same file trips the rule, and a change to one of these three policies+ # trips it too. Each exception also pins the enforced header name, because the `sandbox`+ # directive these three documents rely on has no effect when a browser gets the policy as+ # `Content-Security-Policy-Report-Only`. Adding an exception needs a team-security review.+ - pattern-not: $RESPONSE["Content-Security-Policy"] = artifact_csp(...)+ - pattern-not: $RESPONSE["Content-Security-Policy"] = _public_survey_csp(...)+ - pattern-not: >-+ $RESPONSE["Content-Security-Policy"] = "sandbox; default-src 'none'; img-src https:+ data:; style-src 'unsafe-inline'"+ paths:+ exclude:+ # The app and admin policies, and the middleware that attaches them.+ - /posthog/csp_middleware.py+ # Rule fixtures and tests set the header on purpose.+ - '**/.semgrep/**'+ - '**/test/**'+ - '**/tests/**'+ - '**/test_*.py'diff --git a/posthog/csp_middleware.py b/posthog/csp_middleware.pynew file mode 100644index 000000000000..8867e82771ea--- /dev/null+++ b/posthog/csp_middleware.py@@ -0,0 +1,460 @@+"""The Content Security Policy PostHog serves, and the middleware that attaches it.++The policy lives apart from the other middleware so that team-security owns the file in+`.github/CODEOWNERS` and reviews every change to it.+"""++import uuid+from urllib.parse import parse_qsl, urlencode, urlsplit++from django.conf import settings+from django.http import HttpRequest++import structlog+import posthoganalytics++from posthog.cloud_utils import get_api_host, is_cloud+from posthog.constants import POSTHOG_JS_CLOUD_HOST, POSTHOG_JS_CLOUD_TOKEN+from posthog.models.utils import generate_random_token+from posthog.ph_client import PH_US_API_KEY, PH_US_HOST++logger = structlog.get_logger(__name__)+++_POSTHOG_CSP_REPORT_ENDPOINT = f"{PH_US_HOST}/report/?token={PH_US_API_KEY}&v=2"+++def csp_report_endpoint(**params: str) -> str:+ """The URL browsers report CSP violations and crashes to, or "" when reporting is turned off."""+ endpoint = settings.CSP_REPORT_ENDPOINT+ if endpoint is None:+ # Only deployments PostHog runs report to PostHog. Violations from an instance we do not+ # run tell us nothing we can act on, and reporting sends that instance's document URLs to a+ # destination its operator never chose. The gate is cloud rather than hobby because a+ # self-hosted install with DEBUG set runs in the local mode, not the hobby one.+ endpoint = _POSTHOG_CSP_REPORT_ENDPOINT if is_cloud() else ""+ if not endpoint or not params:+ return endpoint+ # The endpoint carries the destination's project token and report version, so a param the caller+ # passes replaces the one already there rather than repeating it.+ parts = urlsplit(endpoint)+ query = dict(parse_qsl(parts.query, keep_blank_values=True))+ query.update(params)+ return parts._replace(query=urlencode(query)).geturl()+++# The full path, matched exactly. Django sends every unmatched path to the app catch-all, so a+# prefix match would also hand the app document this policy and stop it from starting.+REPLAY_PLAYER_FRAME_PATH = "/replay_player_frame/index.html"++# The app policy names only PostHog origins in `frame-ancestors`. Enforcing it on these paths stops+# every embedded dashboard, shared link and survey from rendering on a customer's site.+#+# The list follows `posthog/urls.py`. The Contour ingress keeps a similar list in+# `charts/argocd/contour-ingress/values/values.{dev,prod-us,prod-eu}.yaml`, which omits+# `/interview/` and the bare `/exporter`. Sync to the URL patterns, not to that list.+EMBEDDABLE_PATH_PREFIXES = (+ "/shared_dashboard/",+ "/shared/",+ "/embedded/",+ "/interview/",+ "/exporter/",+ "/external_surveys/",+)+EMBEDDABLE_PATHS = frozenset({"/render_query", "/exporter"})+++def is_embeddable_document(path: str) -> bool:+ return path in EMBEDDABLE_PATHS or path.startswith(EMBEDDABLE_PATH_PREFIXES)+++CSP_ENFORCE_APP_POLICY_FLAG = "csp-enforce-app-policy"+CSP_ENFORCE_SIGNED_OUT_PAGES_FLAG = "csp-enforce-signed-out-pages"++# The pages that take a password or a one-time code. Other signed-out pages keep the report-only header.+SIGNED_OUT_ENFORCEABLE_PATH_PREFIXES = ("/login", "/signup", "/reset", "/reset_2fa", "/verify_email")+++def is_signed_out_enforceable_path(path: str) -> bool:+ return any(path == prefix or path.startswith(prefix + "/") for prefix in SIGNED_OUT_ENFORCEABLE_PATH_PREFIXES)+++def signed_out_csp_enforcement_enabled() -> bool:+ try:+ # A signed-out visitor has no person to bucket, so each document draws a random id. The+ # flag's rollout percentage then applies per document.+ #+ # A condition on a person property cannot resolve for a random id, so it evaluates to None+ # and enforces nothing. Flag events stay off, because each document would add a new+ # distinct id to the project.+ return bool(+ posthoganalytics.feature_enabled(+ CSP_ENFORCE_SIGNED_OUT_PAGES_FLAG,+ str(uuid.uuid4()),+ only_evaluate_locally=True,+ send_feature_flag_events=False,+ )+ )+ except Exception:+ logger.warning("csp.signed_out_enforcement_flag_check_failed_defaulting_off", exc_info=True)+ return False+++def csp_enforcement_enabled(request: HttpRequest) -> bool:+ user = getattr(request, "user", None)+ if user is None:+ return False+ if not user.is_authenticated:+ # The document keeps the policy it loads with. A visitor who signs in on login goes on to+ # the app inside the same document, so the draw here also covers that visit.+ return is_signed_out_enforceable_path(request.path) and signed_out_csp_enforcement_enabled()+ distinct_id = getattr(user, "distinct_id", None)+ if not distinct_id:+ return False+ try:+ # Local evaluation only. A network call here would sit in the path of every HTML response,+ # and an unevaluable flag returns None, which leaves the policy report-only.+ #+ # Local evaluation holds the flag's conditions but not the person's properties, so a+ # condition on `email` cannot resolve unless the caller supplies it. Without this the+ # staff-only rollout every other flag here uses would return None and enforce nothing.+ return bool(+ posthoganalytics.feature_enabled(+ CSP_ENFORCE_APP_POLICY_FLAG,+ distinct_id,+ person_properties={"email": user.email} if user.email else {},+ only_evaluate_locally=True,+ )+ )+ except Exception:+ # A failed lookup and a deliberate opt-out both leave the policy report-only. The rollout+ # needs to tell them apart.+ logger.warning("csp.enforcement_flag_check_failed_defaulting_off", exc_info=True)+ return False+++def app_csp_header_name(request: HttpRequest) -> str:+ if is_embeddable_document(request.path):+ return "Content-Security-Policy-Report-Only"+ if csp_enforcement_enabled(request):+ return "Content-Security-Policy"+ return "Content-Security-Policy-Report-Only"+++# The app policy reports as v=2 through the endpoint above, and the shadow policy below as v=3.+NARROWED_APP_POLICY_REPORT_VERSION = "3"+_WILDCARD_SOURCES = frozenset({"https://*.posthog.com", "https://*.i.posthog.com"})+++def narrowed_app_policy(csp_parts: list[str], replacements: dict[str, list[str]]) -> list[str]:+ """The app policy's directives named in `replacements`, with their wildcard hosts swapped for+ the sources given there.++ Sent report-only beside the app policy, it reports each load the wildcards admit and the named+ sources do not, which is the evidence for dropping the wildcards. worker-src comes along because+ workers fall back to script-src without it. The shadow names no other directive, so nothing else+ is restricted in it.+ """+ narrowed = []+ for part in csp_parts:+ name, *sources = part.split()+ if name in replacements:+ narrowed.append(" ".join([name, *(s for s in sources if s not in _WILDCARD_SOURCES), *replacements[name]]))+ elif name == "worker-src":+ narrowed.append(part)+ return narrowed+++class CSPMiddleware:+ def __init__(self, get_response):+ self.get_response = get_response++ def __call__(self, request):+ nonce = generate_random_token(16)+ request.csp_nonce = nonce++ # nonce must be added to request (above) before generating response+ response = self.get_response(request)++ content_type = response.get("Content-Type", "")+ # csp headers only matter on html documents, so for defense in depth, add strong csp to all other requests+ if "text/html" not in content_type:+ response.headers["Content-Security-Policy"] = "default-src 'none'"+ return response++ if request.path == REPLAY_PLAYER_FRAME_PATH:+ # rrweb's own iframe is on about:blank, and a frame on a local scheme inherits its+ # parent's policy wholesale. Mounting rrweb inside this document rather than the app's+ # makes this policy the one a recorded page is judged against.+ #+ # Recorded pages load whatever they loaded when recorded, so the media directives are+ # open on purpose. Scripts are the exception: rrweb sandboxes its frame without+ # allow-scripts, so nothing recorded ever executes, and 'none' states that rather than+ # leaving it to the sandbox attribute alone.+ #+ # No report-uri: violations here describe a customer's site, not ours.+ #+ # frame-ancestors stays open because shared and embedded recordings put the app itself+ # in a customer's page, which makes this frame's ancestor chain cross-origin. The+ # document holds no data and cannot be scripted into cross-origin, so framing it+ # elsewhere yields a blank page.+ response.headers["Content-Security-Policy"] = "; ".join(+ [+ "default-src 'none'",+ "script-src 'none'",+ "style-src * 'unsafe-inline' data: blob:",+ "img-src * data: blob:",+ "font-src * data: blob:",+ "media-src * data: blob:",+ "connect-src *",+ "frame-src *",+ "child-src *",+ "form-action 'none'",+ "base-uri 'none'",+ "frame-ancestors *",+ ]+ )+ return response++ # With the admin portal off, Django admin is not mounted and `/admin/` reaches the app catch-all.+ # Choosing the admin policy by path alone would then enforce it on the app, and it has no+ # connect-src, so the app's own analytics and feature flag requests are refused.+ is_admin_view = getattr(settings, "ADMIN_PORTAL_ENABLED", False) and request.path.startswith("/admin/")+ if is_admin_view:+ django_loginas_inline_script_hash = "sha256-2bSkJXtgXFhxZUhgXzWsEsKImxJEQsqjns0vi3KiSrI="+ csp_parts = [+ "default-src 'self'",+ "style-src 'self' 'unsafe-inline'",+ f"script-src 'self' 'nonce-{nonce}' '{django_loginas_inline_script_hash}'",+ "font-src data: https://fonts.gstatic.com",+ # Without this the directive falls back to `default-src 'self'`, which drops the+ # `data:` icons Django admin and our own admin pages render, and the `blob:` images+ # the admin tools build client-side. Neither can execute, and this policy is+ # enforced for every staff member rather than flag-gated, so the fallback was+ # breaking admin pages outright.+ "img-src 'self' data: blob:",+ "worker-src 'none'",+ "child-src 'none'",+ "object-src 'none'",+ "frame-ancestors 'none'",+ "manifest-src 'none'",+ # used by the error page+ "frame-src https://posthog.com",+ "base-uri 'self'",+ ]++ admin_report_endpoint = csp_report_endpoint()+ if admin_report_endpoint:+ # Without a distinct_id the report endpoint mints a new one for every report, so a+ # single staff session reads as a crowd of users.+ user = getattr(request, "user", None)+ distinct_id = getattr(user, "distinct_id", None) if user is not None and user.is_authenticated else None+ reporting_endpoint = (+ csp_report_endpoint(distinct_id=distinct_id) if distinct_id else admin_report_endpoint+ )+ # The policy has no `report-to` directive. The app policy below gives the reason.+ csp_parts.append(f"report-uri {reporting_endpoint}")+ # Browsers only deliver crash reports to the endpoint named `default`.+ response.headers["Reporting-Endpoints"] = f'default="{reporting_endpoint}"'+ response.headers["Content-Security-Policy"] = "; ".join(csp_parts)+ elif "Content-Security-Policy" in response.headers:+ # The view picked this policy for this document: a canvas artifact runs untrusted code,+ # and the workflow asset endpoint sandboxes captured email HTML. The app policy would+ # drop that sandbox and impose a frame-ancestors list the app's own origin does not+ # match. Adding it report-only is no better, because these documents never aim to+ # satisfy it, so each load would report a violation of a policy we chose not to apply.+ return response+ else:+ resource_url = "https://*.posthog.com"+ # Enforced for every viewer, flag or not, because this directive is what admits these+ # origins: a frame-ancestors directive makes browsers ignore X-Frame-Options, which+ # names only our own origin.+ frame_ancestors = "frame-ancestors https://posthog.com https://preview.posthog.com"+ if settings.DEBUG or settings.TEST:+ resource_url = "http://localhost:8234"+ elif settings.SITE_URL.endswith(".dev.posthog.dev"):+ resource_url = "https://*.dev.posthog.dev"+ # The posthog.com dev server frames the dev app.+ frame_ancestors += " http://localhost:8001"++ connect_debug_url = "ws://localhost:8234" if settings.DEBUG or settings.TEST else ""+ js_url = urlsplit(settings.JS_URL)+ bundle_origin = f"{js_url.scheme}://{js_url.netloc}" if js_url.scheme and js_url.netloc else ""+ csp_parts = [+ # Firefox checks <link rel="modulepreload"> against default-src instead of script-src,+ # so without the bundle host it refuses the preloads index.html emits for the boot+ # chain. Every preload href starts with JS_URL, so its origin is the one host needed.+ # The fetch directives below each set their own sources, so only a load a browser+ # cannot map to one of them falls back to this list.+ f"default-src 'self' {bundle_origin}".rstrip(),+ f"style-src 'self' 'unsafe-inline' {resource_url} https://fonts.googleapis.com",+ # 'wasm-unsafe-eval' permits WebAssembly compilation and nothing else. It is not+ # 'unsafe-eval': it does not permit eval() or the Function constructor. Compiling a+ # module still requires calling WebAssembly.instantiate from JavaScript, so it grants+ # nothing to an attacker who cannot already run script, and nothing further to one who+ # can. Session replay decompresses snapshots with snappy-wasm and the HogQL editor+ # parses with a WebAssembly build, so both break without it.+ #+ # Stripe, Turnstile and Unlayer are the scripts we cannot serve ourselves: each vendor+ # requires the file to load from their own origin, so the flag-font trick of shipping+ # a copy does not apply. `loadStripe` injects js.stripe.com for the payment entry+ # modal, the signup captcha loads the Turnstile API, and `react-email-editor` injects+ # editor.unlayer.com/embed.js for the email templater. `frame-src 'self' https:`+ # already admits the iframes each one opens, and none produced a connect-src+ # violation while this policy was report-only, so their API calls run inside those+ # frames rather than from our page. Unlayer bears that out: embed.js is the only+ # unlayer URL this policy has ever reported, because the editor itself runs in a+ # frame that carries its own policy rather than ours.+ #+ # Unlayer is pinned to a path rather than the host, because react-email-editor+ # hardcodes that one URL and we do not pass its `scriptUrl` prop. A source path is+ # matched against the URL path alone, so the `?2` the library appends does not+ # defeat it. The cost is that a version bump which moves the file needs this line+ # updated, or the editor stops loading.+ f"script-src 'self' 'nonce-{nonce}' 'wasm-unsafe-eval' {resource_url} https://*.i.posthog.com https://js.stripe.com https://challenges.cloudflare.com https://editor.unlayer.com/embed.js",+ # A data: font cannot execute script, and this directive governs font loading only,+ # so the token widens nothing else. It also carries nothing out: a data: URL makes+ # no request, which is what the CSS-injection attacks on this directive need. The+ # `data:` refusal in the worker-src note below is a different case, because a+ # worker body is code.+ f"font-src 'self' data: {resource_url} https://app-static.eu.posthog.com https://app-static-prod.posthog.com https://fonts.gstatic.com",+ # `blob:` grants nothing to an attacker who cannot already run script, because only+ # script can mint a blob URL, and a worker started from one inherits this policy+ # rather than escaping it. The ServiceWorker spec rejects `blob:` on its own, so+ # this cannot register a persistent worker either.+ #+ # The reasoning holds only while every blob worker body is a compile-time constant.+ # `no-dynamic-worker-body` in .semgrep/rules/security checks first-party code for+ # that. It follows an object URL or a `data:` URL into a worker constructor through+ # the assignments in one function, so it catches the shapes we write rather than+ # every possible one.+ #+ # posthog-js builds its rrweb recorder worker from a blob, and PixiJS builds two+ # ImageBitmap workers the same way. Do not add `data:`: the recorder falls back to a+ # data URL only when blob fails, so allowing blob stops those attempts.+ "worker-src 'self' blob:",+ "child-src 'none'",+ "object-src 'none'",+ # `'self'` carries the PostHog AI onboarding videos under /static/. Max hands-free+ # needs the other two: it primes playback with a silent `data:` clip, then plays+ # the TTS response from a blob URL. None of the three can execute, because+ # media-src governs <audio> and <video> only.+ "media-src 'self' data: blob: https://res.cloudinary.com",+ # `https:` is here for the OAuth authorize page, which renders an application's icon+ # from a URL its registrant supplied. There is no allowlist that covers those, so+ # until we serve them ourselves the directive has to accept any host.+ #+ # The named origins below are the set we actually load images from, and `https:`+ # makes them redundant. They stay so that removing `https:` is a one-line change+ # rather than an archaeology exercise.+ #+ # Do not promote this to an enforced header as-is. An open `img-src` is an+ # exfiltration channel: an attacker who injects markup but cannot run script still+ # gets a beacon out through an image URL.+ # `blob:` is not part of that exfiltration surface: only script already running on+ # the page can mint a blob URL, and an image cannot execute, so it grants strictly+ # less than the `worker-src blob:` note below. Image upload previews, replay and the+ # SQL editor all render blob URLs, so they lose their images without it.+ f"img-src 'self' data: blob: https: {resource_url} https://posthog.com https://www.gravatar.com https://res.cloudinary.com https://platform.slack-edge.com https://raw.githubusercontent.com",+ frame_ancestors,+ # The live debugger's repo browser reads PostHog/posthog from the GitHub API. The path keeps+ # the rest of the API, and every other repository, out of reach of injected script.+ f"connect-src 'self' https://www.posthogstatus.com {resource_url} {connect_debug_url} https://api.github.com/repos/PostHog/posthog/ https://raw.githubusercontent.com/PostHog/terminal-assets/",+ # https: lets heatmaps frame a customer's site. 'self' is for the replay player+ # frame, whose document is same-origin: an http origin does not match https:.+ "frame-src 'self' https:",+ "manifest-src 'self'",+ "base-uri 'self'",+ # form-action has no default-src fallback, so leaving it unset lets an injected+ # form post anywhere. Every form we serve targets a same-origin path, but Chromium+ # judges each hop of the redirect chain too, and reports the original action rather+ # than the hop that failed. Exiting impersonation posts to /logout, which redirects+ # into /admin/, and AdminOAuth2Middleware sends that on to Google because+ # restore_original_login() flushes the session holding the admin verification. So+ # without this origin a staff logout is cancelled with nothing shown to the user.+ "form-action 'self' https://accounts.google.com",+ ]++ # Both values are read inside one narrowed block, so nothing below re-checks `user`.+ user = getattr(request, "user", None)+ if user is not None and user.is_authenticated:+ is_staff = bool(getattr(user, "is_staff", False))+ distinct_id = getattr(user, "distinct_id", None)+ else:+ is_staff = False+ distinct_id = None++ # Staff get the policy enforced ahead of everyone else, so each violation they report is+ # something already broken for a colleague rather than one sample of a trend. At 0.1 we+ # would see one breakage in ten, which is the opposite of what the staff rollout is for.+ # The endpoint does the sampling, so browsers already send every report and taking staff+ # to 1 costs ingestion rather than client traffic.+ #+ # This keys on is_staff rather than on the enforcement flag, which would otherwise track+ # the enforced population exactly. The flag widens until it covers everyone, and would+ # silently take the whole fleet to unsampled reporting; staff stays bounded.+ sample_rate = "1" if is_staff else "0.1"++ report_uri = csp_report_endpoint(sample_rate=sample_rate)+ 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.+ "script-src": [+ *bundle,+ f"{POSTHOG_JS_CLOUD_HOST}/static/",+ f"{POSTHOG_JS_CLOUD_HOST}/array/{POSTHOG_JS_CLOUD_TOKEN}/config.js",+ ],+ # liveEventsHostOrigin() in the frontend streams from live.<region host>.+ "connect-src": [+ *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)+ shadow_parts = [*narrowed_app_policy(csp_parts, replacements), f"report-uri {shadow_uri}"]+ if report_uri:+ report_endpoint = report_uri+ if distinct_id:+ # A report body never names the person, and a crash report arrives after the tab+ # already died, so only the URL can carry the distinct_id. Without it, the report+ # endpoint mints a random id for every report.+ report_endpoint = csp_report_endpoint(sample_rate=sample_rate, distinct_id=distinct_id)+ # The policy has no `report-to` directive, even though CSP3 marks `report-uri` as+ # deprecated. While a policy names `report-to`, browsers ignore its `report-uri` and+ # send reports only through the Reporting API. That API drops violations raised in+ # about:blank and srcdoc frames, because those documents inherit this policy but not+ # the Reporting-Endpoints header. Without `report-to`, browsers send those violations+ # to `report-uri`.+ csp_parts.append(f"report-uri {report_endpoint}")+ # Browsers only deliver crash reports to the endpoint named `default`.+ response.headers["Reporting-Endpoints"] = f'default="{report_endpoint}"'+ header_name = app_csp_header_name(request)+ response.headers[header_name] = "; ".join(csp_parts)+ if shadow_parts:+ # One header can carry several policies separated by commas, and the browser checks+ # each on its own.+ shadow = "; ".join(shadow_parts)+ reported = response.headers.get("Content-Security-Policy-Report-Only")+ response.headers["Content-Security-Policy-Report-Only"] = (+ f"{reported}, {shadow}" if reported else shadow+ )+ if header_name == "Content-Security-Policy-Report-Only" and not is_embeddable_document(request.path):+ # Django owns this header. A responseHeadersPolicy on the Contour ingress replaces+ # it, and with it the enforced app policy above, so the ingress must not set one.+ response.headers["Content-Security-Policy"] = frame_ancestors++ return responsediff --git a/posthog/middleware.py b/posthog/middleware.pyindex 014dea037081..67df848f7482 100644--- a/posthog/middleware.py+++ b/posthog/middleware.py@@ -10,7 +10,7 @@ from datetime import UTC, datetime, timedeltafrom enum import StrEnumfrom ipaddress import ip_address, ip_networkfrom typing import Optional, cast-from urllib.parse import parse_qsl, urlencode, urlsplit+from urllib.parse import urlencodefrom django.conf import settingsfrom django.contrib.auth import BACKEND_SESSION_KEY, logout@@ -30,7 +30,6 @@ from django.utils.deprecation import MiddlewareMixinfrom django.utils.http import http_date, url_has_allowed_host_and_schemeimport structlog-import posthoganalyticsfrom django_prometheus.middleware import Metricsfrom loginas.utils import is_impersonated_session, restore_original_loginfrom opentelemetry import trace@@ -42,8 +41,8 @@ from statshog.defaults.django import statsdfrom posthog.api.shared import UserBasicSerializerfrom posthog.clickhouse.client.execute import clickhouse_query_counterfrom posthog.clickhouse.query_tagging import QueryCounter, get_query_tag_value, reset_query_tags, tag_queries-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.cloud_utils import is_cloud, is_dev_mode+from posthog.constants import AUTH_BACKEND_KEYSfrom posthog.event_usage import get_event_source, get_mcp_properties, sanitize_header_valuefrom posthog.geoip import get_geoip_propertiesfrom posthog.helpers.impersonation import get_original_user_from_session@@ -57,8 +56,6 @@ from posthog.models.activity_logging.utils import (client_from_header,record_agent_intent,)-from posthog.models.utils import generate_random_token-from posthog.ph_client import PH_US_API_KEY, PH_US_HOSTfrom posthog.settings import PROJECT_SWITCHING_TOKEN_ALLOWLIST, SITE_URLfrom posthog.user_permissions import UserPermissionsfrom posthog.utils import get_ip_address, get_trusted_client_ip@@ -1299,445 +1296,6 @@ class ActivityLoggingMiddleware:return response-_POSTHOG_CSP_REPORT_ENDPOINT = f"{PH_US_HOST}/report/?token={PH_US_API_KEY}&v=2"---def csp_report_endpoint(**params: str) -> str:- """The URL browsers report CSP violations and crashes to, or "" when reporting is turned off."""- endpoint = settings.CSP_REPORT_ENDPOINT- if endpoint is None:- # Only deployments PostHog runs report to PostHog. Violations from an instance we do not- # run tell us nothing we can act on, and reporting sends that instance's document URLs to a- # destination its operator never chose. The gate is cloud rather than hobby because a- # self-hosted install with DEBUG set runs in the local mode, not the hobby one.- endpoint = _POSTHOG_CSP_REPORT_ENDPOINT if is_cloud() else ""- if not endpoint or not params:- return endpoint- # The endpoint carries the destination's project token and report version, so a param the caller- # passes replaces the one already there rather than repeating it.- parts = urlsplit(endpoint)- query = dict(parse_qsl(parts.query, keep_blank_values=True))- query.update(params)- return parts._replace(query=urlencode(query)).geturl()---# The full path, matched exactly. Django sends every unmatched path to the app catch-all, so a-# prefix match would also hand the app document this policy and stop it from starting.-REPLAY_PLAYER_FRAME_PATH = "/replay_player_frame/index.html"--# The app policy names only PostHog origins in `frame-ancestors`. Enforcing it on these paths stops-# every embedded dashboard, shared link and survey from rendering on a customer's site.-#-# The list follows `posthog/urls.py`. The Contour ingress keeps a similar list in-# `charts/argocd/contour-ingress/values/values.{dev,prod-us,prod-eu}.yaml`, which omits-# `/interview/` and the bare `/exporter`. Sync to the URL patterns, not to that list.-EMBEDDABLE_PATH_PREFIXES = (- "/shared_dashboard/",- "/shared/",- "/embedded/",- "/interview/",- "/exporter/",- "/external_surveys/",-)-EMBEDDABLE_PATHS = frozenset({"/render_query", "/exporter"})---def is_embeddable_document(path: str) -> bool:- return path in EMBEDDABLE_PATHS or path.startswith(EMBEDDABLE_PATH_PREFIXES)---CSP_ENFORCE_APP_POLICY_FLAG = "csp-enforce-app-policy"-CSP_ENFORCE_SIGNED_OUT_PAGES_FLAG = "csp-enforce-signed-out-pages"--# The pages that take a password or a one-time code. Other signed-out pages keep the report-only header.-SIGNED_OUT_ENFORCEABLE_PATH_PREFIXES = ("/login", "/signup", "/reset", "/reset_2fa", "/verify_email")---def is_signed_out_enforceable_path(path: str) -> bool:- return any(path == prefix or path.startswith(prefix + "/") for prefix in SIGNED_OUT_ENFORCEABLE_PATH_PREFIXES)---def signed_out_csp_enforcement_enabled() -> bool:- try:- # A signed-out visitor has no person to bucket, so each document draws a random id. The- # flag's rollout percentage then applies per document.- #- # A condition on a person property cannot resolve for a random id, so it evaluates to None- # and enforces nothing. Flag events stay off, because each document would add a new- # distinct id to the project.- return bool(- posthoganalytics.feature_enabled(- CSP_ENFORCE_SIGNED_OUT_PAGES_FLAG,- str(uuid.uuid4()),- only_evaluate_locally=True,- send_feature_flag_events=False,- )- )- except Exception:- logger.warning("csp.signed_out_enforcement_flag_check_failed_defaulting_off", exc_info=True)- return False---def csp_enforcement_enabled(request: HttpRequest) -> bool:- user = getattr(request, "user", None)- if user is None:- return False- if not user.is_authenticated:- # The document keeps the policy it loads with. A visitor who signs in on login goes on to- # the app inside the same document, so the draw here also covers that visit.- return is_signed_out_enforceable_path(request.path) and signed_out_csp_enforcement_enabled()- distinct_id = getattr(user, "distinct_id", None)- if not distinct_id:- return False- try:- # Local evaluation only. A network call here would sit in the path of every HTML response,- # and an unevaluable flag returns None, which leaves the policy report-only.- #- # Local evaluation holds the flag's conditions but not the person's properties, so a- # condition on `email` cannot resolve unless the caller supplies it. Without this the- # staff-only rollout every other flag here uses would return None and enforce nothing.- return bool(- posthoganalytics.feature_enabled(- CSP_ENFORCE_APP_POLICY_FLAG,- distinct_id,- person_properties={"email": user.email} if user.email else {},- only_evaluate_locally=True,- )- )- except Exception:- # A failed lookup and a deliberate opt-out both leave the policy report-only. The rollout- # needs to tell them apart.- logger.warning("csp.enforcement_flag_check_failed_defaulting_off", exc_info=True)- return False---def app_csp_header_name(request: HttpRequest) -> str:- if is_embeddable_document(request.path):- return "Content-Security-Policy-Report-Only"- if csp_enforcement_enabled(request):- return "Content-Security-Policy"- return "Content-Security-Policy-Report-Only"---# The app policy reports as v=2 through the endpoint above, and the shadow policy below as v=3.-NARROWED_APP_POLICY_REPORT_VERSION = "3"-_WILDCARD_SOURCES = frozenset({"https://*.posthog.com", "https://*.i.posthog.com"})---def narrowed_app_policy(csp_parts: list[str], replacements: dict[str, list[str]]) -> list[str]:- """The app policy's directives named in `replacements`, with their wildcard hosts swapped for- the sources given there.-- Sent report-only beside the app policy, it reports each load the wildcards admit and the named- sources do not, which is the evidence for dropping the wildcards. worker-src comes along because- workers fall back to script-src without it. The shadow names no other directive, so nothing else- is restricted in it.- """- narrowed = []- for part in csp_parts:- name, *sources = part.split()- if name in replacements:- narrowed.append(" ".join([name, *(s for s in sources if s not in _WILDCARD_SOURCES), *replacements[name]]))- elif name == "worker-src":- narrowed.append(part)- return narrowed---class CSPMiddleware:- def __init__(self, get_response):- self.get_response = get_response-- def __call__(self, request):- nonce = generate_random_token(16)- request.csp_nonce = nonce-- # nonce must be added to request (above) before generating response- response = self.get_response(request)-- content_type = response.get("Content-Type", "")- # csp headers only matter on html documents, so for defense in depth, add strong csp to all other requests- if "text/html" not in content_type:- response.headers["Content-Security-Policy"] = "default-src 'none'"- return response-- if request.path == REPLAY_PLAYER_FRAME_PATH:- # rrweb's own iframe is on about:blank, and a frame on a local scheme inherits its- # parent's policy wholesale. Mounting rrweb inside this document rather than the app's- # makes this policy the one a recorded page is judged against.- #- # Recorded pages load whatever they loaded when recorded, so the media directives are- # open on purpose. Scripts are the exception: rrweb sandboxes its frame without- # allow-scripts, so nothing recorded ever executes, and 'none' states that rather than- # leaving it to the sandbox attribute alone.- #- # No report-uri: violations here describe a customer's site, not ours.- #- # frame-ancestors stays open because shared and embedded recordings put the app itself- # in a customer's page, which makes this frame's ancestor chain cross-origin. The- # document holds no data and cannot be scripted into cross-origin, so framing it- # elsewhere yields a blank page.- response.headers["Content-Security-Policy"] = "; ".join(- [- "default-src 'none'",- "script-src 'none'",- "style-src * 'unsafe-inline' data: blob:",- "img-src * data: blob:",- "font-src * data: blob:",- "media-src * data: blob:",- "connect-src *",- "frame-src *",- "child-src *",- "form-action 'none'",- "base-uri 'none'",- "frame-ancestors *",- ]- )- return response-- # With the admin portal off, Django admin is not mounted and `/admin/` reaches the app catch-all.- # Choosing the admin policy by path alone would then enforce it on the app, and it has no- # connect-src, so the app's own analytics and feature flag requests are refused.- is_admin_view = getattr(settings, "ADMIN_PORTAL_ENABLED", False) and request.path.startswith("/admin/")- if is_admin_view:- django_loginas_inline_script_hash = "sha256-2bSkJXtgXFhxZUhgXzWsEsKImxJEQsqjns0vi3KiSrI="- csp_parts = [- "default-src 'self'",- "style-src 'self' 'unsafe-inline'",- f"script-src 'self' 'nonce-{nonce}' '{django_loginas_inline_script_hash}'",- "font-src data: https://fonts.gstatic.com",- # Without this the directive falls back to `default-src 'self'`, which drops the- # `data:` icons Django admin and our own admin pages render, and the `blob:` images- # the admin tools build client-side. Neither can execute, and this policy is- # enforced for every staff member rather than flag-gated, so the fallback was- # breaking admin pages outright.- "img-src 'self' data: blob:",- "worker-src 'none'",- "child-src 'none'",- "object-src 'none'",- "frame-ancestors 'none'",- "manifest-src 'none'",- # used by the error page- "frame-src https://posthog.com",- "base-uri 'self'",- ]-- admin_report_endpoint = csp_report_endpoint()- if admin_report_endpoint:- # Without a distinct_id the report endpoint mints a new one for every report, so a- # single staff session reads as a crowd of users.- user = getattr(request, "user", None)- distinct_id = getattr(user, "distinct_id", None) if user is not None and user.is_authenticated else None- reporting_endpoint = (- csp_report_endpoint(distinct_id=distinct_id) if distinct_id else admin_report_endpoint- )- # The policy has no `report-to` directive. The app policy below gives the reason.- csp_parts.append(f"report-uri {reporting_endpoint}")- # Browsers only deliver crash reports to the endpoint named `default`.- response.headers["Reporting-Endpoints"] = f'default="{reporting_endpoint}"'- response.headers["Content-Security-Policy"] = "; ".join(csp_parts)- elif "Content-Security-Policy" in response.headers:- # The view picked this policy for this document: a canvas artifact runs untrusted code,- # and the workflow asset endpoint sandboxes captured email HTML. The app policy would- # drop that sandbox and impose a frame-ancestors list the app's own origin does not- # match. Adding it report-only is no better, because these documents never aim to- # satisfy it, so each load would report a violation of a policy we chose not to apply.- return response- else:- resource_url = "https://*.posthog.com"- # Enforced for every viewer, flag or not, because this directive is what admits these- # origins: a frame-ancestors directive makes browsers ignore X-Frame-Options, which- # names only our own origin.- frame_ancestors = "frame-ancestors https://posthog.com https://preview.posthog.com"- if settings.DEBUG or settings.TEST:- resource_url = "http://localhost:8234"- elif settings.SITE_URL.endswith(".dev.posthog.dev"):- resource_url = "https://*.dev.posthog.dev"- # The posthog.com dev server frames the dev app.- frame_ancestors += " http://localhost:8001"-- connect_debug_url = "ws://localhost:8234" if settings.DEBUG or settings.TEST else ""- js_url = urlsplit(settings.JS_URL)- bundle_origin = f"{js_url.scheme}://{js_url.netloc}" if js_url.scheme and js_url.netloc else ""- csp_parts = [- # Firefox checks <link rel="modulepreload"> against default-src instead of script-src,- # so without the bundle host it refuses the preloads index.html emits for the boot- # chain. Every preload href starts with JS_URL, so its origin is the one host needed.- # The fetch directives below each set their own sources, so only a load a browser- # cannot map to one of them falls back to this list.- f"default-src 'self' {bundle_origin}".rstrip(),- f"style-src 'self' 'unsafe-inline' {resource_url} https://fonts.googleapis.com",- # 'wasm-unsafe-eval' permits WebAssembly compilation and nothing else. It is not- # 'unsafe-eval': it does not permit eval() or the Function constructor. Compiling a- # module still requires calling WebAssembly.instantiate from JavaScript, so it grants- # nothing to an attacker who cannot already run script, and nothing further to one who- # can. Session replay decompresses snapshots with snappy-wasm and the HogQL editor- # parses with a WebAssembly build, so both break without it.- #- # Stripe, Turnstile and Unlayer are the scripts we cannot serve ourselves: each vendor- # requires the file to load from their own origin, so the flag-font trick of shipping- # a copy does not apply. `loadStripe` injects js.stripe.com for the payment entry- # modal, the signup captcha loads the Turnstile API, and `react-email-editor` injects- # editor.unlayer.com/embed.js for the email templater. `frame-src 'self' https:`- # already admits the iframes each one opens, and none produced a connect-src- # violation while this policy was report-only, so their API calls run inside those- # frames rather than from our page. Unlayer bears that out: embed.js is the only- # unlayer URL this policy has ever reported, because the editor itself runs in a- # frame that carries its own policy rather than ours.- #- # Unlayer is pinned to a path rather than the host, because react-email-editor- # hardcodes that one URL and we do not pass its `scriptUrl` prop. A source path is- # matched against the URL path alone, so the `?2` the library appends does not- # defeat it. The cost is that a version bump which moves the file needs this line- # updated, or the editor stops loading.- f"script-src 'self' 'nonce-{nonce}' 'wasm-unsafe-eval' {resource_url} https://*.i.posthog.com https://js.stripe.com https://challenges.cloudflare.com https://editor.unlayer.com/embed.js",- # A data: font cannot execute script, and this directive governs font loading only,- # so the token widens nothing else. It also carries nothing out: a data: URL makes- # no request, which is what the CSS-injection attacks on this directive need. The- # `data:` refusal in the worker-src note below is a different case, because a- # worker body is code.- f"font-src 'self' data: {resource_url} https://app-static.eu.posthog.com https://app-static-prod.posthog.com https://fonts.gstatic.com",- # `blob:` grants nothing to an attacker who cannot already run script, because only- # script can mint a blob URL, and a worker started from one inherits this policy- # rather than escaping it. The ServiceWorker spec rejects `blob:` on its own, so- # this cannot register a persistent worker either.- #- # The reasoning holds only while every blob worker body is a compile-time constant.- # `no-dynamic-worker-body` in .semgrep/rules/security checks first-party code for- # that. It follows an object URL or a `data:` URL into a worker constructor through- # the assignments in one function, so it catches the shapes we write rather than- # every possible one.- #- # posthog-js builds its rrweb recorder worker from a blob, and PixiJS builds two- # ImageBitmap workers the same way. Do not add `data:`: the recorder falls back to a- # data URL only when blob fails, so allowing blob stops those attempts.- "worker-src 'self' blob:",- "child-src 'none'",- "object-src 'none'",- # `'self'` carries the PostHog AI onboarding videos under /static/. Max hands-free- # needs the other two: it primes playback with a silent `data:` clip, then plays- # the TTS response from a blob URL. None of the three can execute, because- # media-src governs <audio> and <video> only.- "media-src 'self' data: blob: https://res.cloudinary.com",- # `https:` is here for the OAuth authorize page, which renders an application's icon- # from a URL its registrant supplied. There is no allowlist that covers those, so- # until we serve them ourselves the directive has to accept any host.- #- # The named origins below are the set we actually load images from, and `https:`- # makes them redundant. They stay so that removing `https:` is a one-line change- # rather than an archaeology exercise.- #- # Do not promote this to an enforced header as-is. An open `img-src` is an- # exfiltration channel: an attacker who injects markup but cannot run script still- # gets a beacon out through an image URL.- # `blob:` is not part of that exfiltration surface: only script already running on- # the page can mint a blob URL, and an image cannot execute, so it grants strictly- # less than the `worker-src blob:` note below. Image upload previews, replay and the- # SQL editor all render blob URLs, so they lose their images without it.- f"img-src 'self' data: blob: https: {resource_url} https://posthog.com https://www.gravatar.com https://res.cloudinary.com https://platform.slack-edge.com https://raw.githubusercontent.com",- frame_ancestors,- # The live debugger's repo browser reads PostHog/posthog from the GitHub API. The path keeps- # the rest of the API, and every other repository, out of reach of injected script.- f"connect-src 'self' https://www.posthogstatus.com {resource_url} {connect_debug_url} https://api.github.com/repos/PostHog/posthog/ https://raw.githubusercontent.com/PostHog/terminal-assets/",- # https: lets heatmaps frame a customer's site. 'self' is for the replay player- # frame, whose document is same-origin: an http origin does not match https:.- "frame-src 'self' https:",- "manifest-src 'self'",- "base-uri 'self'",- # form-action has no default-src fallback, so leaving it unset lets an injected- # form post anywhere. Every form we serve targets a same-origin path, but Chromium- # judges each hop of the redirect chain too, and reports the original action rather- # than the hop that failed. Exiting impersonation posts to /logout, which redirects- # into /admin/, and AdminOAuth2Middleware sends that on to Google because- # restore_original_login() flushes the session holding the admin verification. So- # without this origin a staff logout is cancelled with nothing shown to the user.- "form-action 'self' https://accounts.google.com",- ]-- # Both values are read inside one narrowed block, so nothing below re-checks `user`.- user = getattr(request, "user", None)- if user is not None and user.is_authenticated:- is_staff = bool(getattr(user, "is_staff", False))- distinct_id = getattr(user, "distinct_id", None)- else:- is_staff = False- distinct_id = None-- # Staff get the policy enforced ahead of everyone else, so each violation they report is- # something already broken for a colleague rather than one sample of a trend. At 0.1 we- # would see one breakage in ten, which is the opposite of what the staff rollout is for.- # The endpoint does the sampling, so browsers already send every report and taking staff- # to 1 costs ingestion rather than client traffic.- #- # This keys on is_staff rather than on the enforcement flag, which would otherwise track- # the enforced population exactly. The flag widens until it covers everyone, and would- # silently take the whole fleet to unsampled reporting; staff stays bounded.- sample_rate = "1" if is_staff else "0.1"-- report_uri = csp_report_endpoint(sample_rate=sample_rate)- 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.- "script-src": [- *bundle,- f"{POSTHOG_JS_CLOUD_HOST}/static/",- f"{POSTHOG_JS_CLOUD_HOST}/array/{POSTHOG_JS_CLOUD_TOKEN}/config.js",- ],- # liveEventsHostOrigin() in the frontend streams from live.<region host>.- "connect-src": [- *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)- shadow_parts = [*narrowed_app_policy(csp_parts, replacements), f"report-uri {shadow_uri}"]- if report_uri:- report_endpoint = report_uri- if distinct_id:- # A report body never names the person, and a crash report arrives after the tab- # already died, so only the URL can carry the distinct_id. Without it, the report- # endpoint mints a random id for every report.- report_endpoint = csp_report_endpoint(sample_rate=sample_rate, distinct_id=distinct_id)- # The policy has no `report-to` directive, even though CSP3 marks `report-uri` as- # deprecated. While a policy names `report-to`, browsers ignore its `report-uri` and- # send reports only through the Reporting API. That API drops violations raised in- # about:blank and srcdoc frames, because those documents inherit this policy but not- # the Reporting-Endpoints header. Without `report-to`, browsers send those violations- # to `report-uri`.- csp_parts.append(f"report-uri {report_endpoint}")- # Browsers only deliver crash reports to the endpoint named `default`.- response.headers["Reporting-Endpoints"] = f'default="{report_endpoint}"'- header_name = app_csp_header_name(request)- response.headers[header_name] = "; ".join(csp_parts)- if shadow_parts:- # One header can carry several policies separated by commas, and the browser checks- # each on its own.- shadow = "; ".join(shadow_parts)- reported = response.headers.get("Content-Security-Policy-Report-Only")- response.headers["Content-Security-Policy-Report-Only"] = (- f"{reported}, {shadow}" if reported else shadow- )- if header_name == "Content-Security-Policy-Report-Only" and not is_embeddable_document(request.path):- # Django owns this header. A responseHeadersPolicy on the Contour ingress replaces- # it, and with it the enforced app policy above, so the ingress must not set one.- response.headers["Content-Security-Policy"] = frame_ancestors-- return response--class SocialAuthExceptionMiddleware:"""Middleware to handle custom social auth exceptions.diff --git a/posthog/owners.yaml b/posthog/owners.yamlindex 0edc9a45f0ce..2fabf2becbb0 100644--- a/posthog/owners.yaml+++ b/posthog/owners.yaml@@ -7,6 +7,10 @@ rules:owners: team-workflows- match: '/clickhouse/hcl/'owners: clickhouse+ - match:+ - '/csp_middleware.py'+ - '/test/test_csp_middleware.py'+ owners: team-security- match: '/data_freshness.py'owners: team-platform-features- match: '/egress/'diff --git a/posthog/settings/web.py b/posthog/settings/web.pyindex 96aaf0789cb7..ddd5dccb5c9e 100644--- a/posthog/settings/web.py+++ b/posthog/settings/web.py@@ -183,7 +183,7 @@ MIDDLEWARE = ["django.contrib.sessions.middleware.SessionMiddleware","posthog.middleware.OAuthCorsPreflightMiddleware", # Must precede CorsMiddleware — echoes custom headers on OAuth preflights"corsheaders.middleware.CorsMiddleware",- "posthog.middleware.CSPMiddleware",+ "posthog.csp_middleware.CSPMiddleware","django.middleware.common.CommonMiddleware",# Below CorsMiddleware so responses get CORS headers; above auth/CSRF and URL# resolution so the /api/environments → /api/projects rewrite is in place before thediff --git a/posthog/test/test_csp_middleware.py b/posthog/test/test_csp_middleware.pynew file mode 100644index 000000000000..742e4f084c15--- /dev/null+++ b/posthog/test/test_csp_middleware.py@@ -0,0 +1,493 @@+from urllib.parse import urlsplit++from posthog.test.base import APIBaseTest, override_settings+from unittest.mock import MagicMock, patch++from django.http import HttpRequest, HttpResponse+from django.test import RequestFactory, SimpleTestCase++from parameterized import parameterized++from posthog.csp_middleware import (+ CSP_ENFORCE_APP_POLICY_FLAG,+ CSP_ENFORCE_SIGNED_OUT_PAGES_FLAG,+ CSPMiddleware,+ app_csp_header_name,+ narrowed_app_policy,+)+++class TestCSPMiddleware(APIBaseTest):+ def test_replay_player_frame_carries_its_own_policy_and_reports_nothing(self):+ # The frame exists so a recorded page stops being judged against the app policy. If the+ # middleware branch goes, it silently inherits that policy again, along with its report-uri,+ # and every replayed page resumes reporting a customer's site to our project.+ response = self.client.get("/replay_player_frame/index.html")+ assert response.status_code == 200+ policy = response["Content-Security-Policy"]+ assert "script-src 'none'" in policy+ assert "img-src * data: blob:" in policy+ assert "report-uri" not in policy+ assert "Content-Security-Policy-Report-Only" not in response+ assert "Reporting-Endpoints" not in response++ def test_app_policy_allows_framing_the_replay_player_frame(self):+ # The player frame is same-origin, and an http origin does not match the https: source+ # that heatmaps need.+ response = self.client.get("/")+ assert "frame-src 'self' https:" in response["Content-Security-Policy-Report-Only"]++ @parameterized.expand(+ [+ ("local", {}, "default-src 'self' http://localhost:8234;"),+ # The bundle host alone. The rest of the policy names every PostHog subdomain, and a+ # fallback that broad admits whatever a new directive forgets to restrict.+ (+ "cloud",+ {+ "TEST": False,+ "DEBUG": False,+ "CLOUD_DEPLOYMENT": "US",+ "SITE_URL": "https://us.posthog.com",+ "JS_URL": "https://app-static-prod.posthog.com",+ },+ "default-src 'self' https://app-static-prod.posthog.com;",+ ),+ ]+ )+ def test_app_policy_lets_firefox_preload_the_app_bundle(self, _name, overrides, expected):+ # Firefox judges <link rel="modulepreload"> by default-src, not script-src. A default-src of+ # 'self' alone refuses every preload index.html emits for the boot chain.+ with override_settings(**overrides):+ response = self.client.get("/")+ assert expected in response["Content-Security-Policy-Report-Only"]++ def test_replay_player_frame_serves_the_mount_node_without_a_session(self):+ # Shared recordings render the player for logged-out viewers.+ self.client.logout()+ response = self.client.get("/replay_player_frame/index.html")+ assert response.status_code == 200+ # PlayerFrame.tsx looks the mount node up by this id. A rename here makes every player show its load error.+ assert 'id="player-frame-content"' in response.content.decode()++ def test_non_html_response_gets_strict_csp(self):+ response = self.client.get("/api/users/@me/")+ assert response.status_code == 200+ assert response["Content-Security-Policy"] == "default-src 'none'"+ assert "Content-Security-Policy-Report-Only" not in response++ @parameterized.expand(+ [+ ("app_root", "/", True),+ # No route serves this path, so the app catch-all answers it. It must keep the app+ # policy, because the frame policy is enforced and its script-src 'none' stops the app+ # from starting.+ ("path_under_the_replay_frame_prefix", "/replay_player_frame", True),+ # A customer's page frames this document, and the enforced list names only PostHog+ # origins.+ ("embeddable_document", "/shared/notarealtoken", False),+ ]+ )+ def test_html_response_without_the_flag_enforces_only_frame_ancestors(self, _name, path, enforces_frame_ancestors):+ response = self.client.get(path)+ reported = response["Content-Security-Policy-Report-Only"]+ assert "default-src 'self'" in reported+ if not enforces_frame_ancestors:+ assert "Content-Security-Policy" not in response+ return+ # Framing is enforced ahead of the flag because it is what lets posthog.com frame the app.+ # The enforced list has to be the one the reported policy names, or the two drift apart.+ enforced = response["Content-Security-Policy"]+ assert enforced.startswith("frame-ancestors https://posthog.com")+ assert "default-src" not in enforced+ assert enforced in reported++ @patch("posthog.csp_middleware.posthoganalytics.feature_enabled", return_value=True)+ def test_enforcement_reaches_an_app_page_but_not_an_embeddable_one(self, _mock_flag):+ # The wiring guard for app_csp_header_name. The matrix of paths lives in+ # TestAppCspHeaderName, which needs no database.+ enforced = self.client.get("/")+ assert "default-src 'self'" in enforced["Content-Security-Policy"]+ assert "Content-Security-Policy-Report-Only" not in enforced++ embedded = self.client.get("/shared/notarealtoken")+ assert "Content-Security-Policy" not in embedded+ assert "frame-ancestors" in embedded["Content-Security-Policy-Report-Only"]++ @override_settings(CLOUD_DEPLOYMENT="US") # As PostHog Cloud+ def test_html_response_declares_default_reporting_endpoint_with_distinct_id(self):+ response = self.client.get("/")+ policy = response["Content-Security-Policy-Report-Only"]+ # A `report-to` directive makes browsers ignore `report-uri` and report through the+ # Reporting API, which drops violations raised in about:blank and srcdoc frames.+ assert "report-to" not in policy+ _, report_endpoint = next(part for part in policy.split("; ") if part.startswith("report-uri ")).split()+ assert report_endpoint.startswith("https://us.i.posthog.com/report/")+ assert f"distinct_id={self.user.distinct_id}" in report_endpoint+ # Browsers only deliver crash reports to the endpoint named `default`, so dropping or+ # renaming it silently stops crash ingestion.+ assert response["Reporting-Endpoints"] == f'default="{report_endpoint}"'++ @override_settings(CLOUD_DEPLOYMENT="US") # As PostHog Cloud+ def test_reporting_endpoints_omit_distinct_id_when_logged_out(self):+ self.client.logout()+ response = self.client.get("/login")+ policy = response["Content-Security-Policy-Report-Only"]+ assert "report-uri https://us.i.posthog.com/report/" in policy+ assert "distinct_id" not in policy+ header = response["Reporting-Endpoints"]+ assert 'default="https://us.i.posthog.com/report/' in header+ assert "distinct_id" not in header++ @parameterized.expand(+ [+ ("self_hosted_by_default", {"CLOUD_DEPLOYMENT": None, "DEBUG": False}),+ # DEBUG puts an install in the local run mode rather than the hobby one, and nothing+ # stops a self-hoster deploying that way, so it must report nowhere as well.+ ("self_hosted_with_debug", {"CLOUD_DEPLOYMENT": None, "DEBUG": True}),+ # Cloud would otherwise report, so this case proves the empty value turns it off.+ ("explicitly_disabled", {"CLOUD_DEPLOYMENT": "US", "CSP_REPORT_ENDPOINT": ""}),+ ]+ )+ def test_no_endpoint_still_sends_the_policy_but_asks_for_no_reports(self, _name, overrides):+ # A self-hosted install must not report to PostHog, and the policy itself must survive, so+ # dropping it here would silently remove a security control.+ with override_settings(**{"CSP_REPORT_ENDPOINT": None, **overrides}):+ response = self.client.get("/")+ policy = response["Content-Security-Policy-Report-Only"]+ assert "default-src 'self'" in policy+ assert "report-uri" not in policy+ assert "report-to" not in policy+ assert "Reporting-Endpoints" not in response++ @override_settings(CSP_REPORT_ENDPOINT="https://posthog.example.com/report/")+ def test_report_endpoint_is_configurable(self):+ # An operator can point reporting at their own install, so nothing may hardcode ours.+ response = self.client.get("/")+ policy = response["Content-Security-Policy-Report-Only"]+ assert "report-uri https://posthog.example.com/report/?sample_rate=0.1" in policy+ header = response["Reporting-Endpoints"]+ assert "us.i.posthog.com" not in header+ assert f"distinct_id={self.user.distinct_id}" in header++ @parameterized.expand(+ [+ ("staff", True, "1", "0.1"),+ ("not_staff", False, "0.1", "1"),+ ]+ )+ @override_settings(CSP_REPORT_ENDPOINT="https://posthog.example.com/report/")+ def test_staff_report_every_violation_while_everyone_else_is_sampled(+ self, _name, is_staff, expected_rate, other_rate+ ):+ # Staff get the policy enforced ahead of everyone else, so a violation of theirs is+ # something already broken for a colleague rather than one sample of a trend. At 0.1 nine+ # in ten of those never arrive, which defeats the point of rolling out to staff first.+ self.user.is_staff = is_staff+ self.user.save()++ response = self.client.get("/")++ policy = response["Content-Security-Policy-Report-Only"]+ assert f"report-uri https://posthog.example.com/report/?sample_rate={expected_rate}" in policy+ assert f"sample_rate={expected_rate}&distinct_id={self.user.distinct_id}" in policy+ assert f"sample_rate={other_rate}" not in policy++ @parameterized.expand(+ [+ ("cloud", {"CLOUD_DEPLOYMENT": "US"}, True),+ ("self_hosted", {"CLOUD_DEPLOYMENT": None, "DEBUG": False}, False),+ ]+ )+ def test_admin_pages_enforce_the_policy_and_follow_the_reporting_default(self, _name, overrides, expects_reporting):+ # The admin policy is enforced, not report-only, and builds its own Reporting-Endpoints+ # header, so it can drift from the app policy unnoticed. A non-staff request redirects but+ # still carries that policy, because the middleware picks its branch by path once the portal is on.+ with override_settings(CSP_REPORT_ENDPOINT=None, ADMIN_PORTAL_ENABLED=True, **overrides):+ response = self.client.get("/admin/")+ policy = response["Content-Security-Policy"]+ # Only the admin policy forbids framing outright; the non-HTML fallback is default-src alone.+ assert "frame-ancestors 'none'" in policy+ assert "Content-Security-Policy-Report-Only" not in response+ assert "report-to" not in policy++ if expects_reporting:+ assert "report-uri https://us.i.posthog.com/report/" in policy+ # Sampling the admin policy too would silently drop violations, so the branches diverge.+ assert "sample_rate" not in policy+ # Without it every admin report arrives under a freshly minted id, so one staff session+ # counts as many users.+ assert f"distinct_id={self.user.distinct_id}" in policy+ _, report_endpoint = next(part for part in policy.split("; ") if part.startswith("report-uri ")).split()+ assert response["Reporting-Endpoints"] == f'default="{report_endpoint}"'+ else:+ assert "report-uri" not in policy+ assert "Reporting-Endpoints" not in response++ @override_settings(ADMIN_PORTAL_ENABLED=False)+ def test_admin_path_gets_the_app_policy_when_the_portal_is_off(self):+ # Without the portal, `/admin/` is an app page, and the app keeps running in that document+ # after it navigates away. The admin policy there would refuse every request the app makes+ # to another origin.+ response = self.client.get("/admin/")+ assert "frame-ancestors 'none'" not in response["Content-Security-Policy"]+ assert "connect-src 'self'" in response["Content-Security-Policy-Report-Only"]++ @parameterized.expand(+ [+ (+ "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/",+ },+ ("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.+ (+ "self_hosted_with_reporting_on",+ {+ "CLOUD_DEPLOYMENT": None,+ "SITE_URL": "https://posthog.example.com",+ "CSP_REPORT_ENDPOINT": "https://posthog.example.com/report/?token=phc_test&v=2",+ },+ None,+ ),+ ]+ )+ 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):+ response = self.client.get("/")++ 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 regions else 0)+ if regions:+ region, other_region = regions+ shadow = shadows[0]+ assert "*.posthog.com" not in shadow+ assert "https://internal-cf.posthog.com/array/sTMFPsFhdP1Ssg/config.js" 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 TestAppCspHeaderName(SimpleTestCase):+ def _request(+ self, path: str, *, distinct_id: str | None = "abc", email: str = "[email protected]"+ ) -> HttpRequest:+ request = RequestFactory().get(path)+ request.user = MagicMock(is_authenticated=distinct_id is not None, distinct_id=distinct_id, email=email)+ return request++ @parameterized.expand(+ [+ ("shared_dashboard", "/shared_dashboard/abc123"),+ ("shared", "/shared/abc123"),+ ("embedded", "/embedded/abc123"),+ ("interview", "/interview/abc123"),+ ("exporter_with_token", "/exporter/abc123"),+ ("exporter_render", "/exporter"),+ ("render_query", "/render_query"),+ ("external_survey", "/external_surveys/019efb7e-0672-0000-729b-e234586f6177"),+ ]+ )+ @patch("posthog.csp_middleware.posthoganalytics.feature_enabled", return_value=True)+ def test_embeddable_document_stays_report_only_under_enforcement(self, _name, path, _mock_flag):+ # A customer's site frames each of these. The app policy names only PostHog origins in+ # frame-ancestors, so enforcing it here stops the document rendering on their page.+ assert app_csp_header_name(self._request(path)) == "Content-Security-Policy-Report-Only"+ assert app_csp_header_name(self._request(path, distinct_id=None)) == "Content-Security-Policy-Report-Only"++ @parameterized.expand(+ [+ ("app_root", "/"),+ ("project_page", "/project/2/dashboard"),+ # Neither prefix owns these. A shorter prefix match would hand the app catch-all the+ # carve-out and quietly exempt an ordinary page from enforcement.+ ("shared_prefix_without_separator", "/sharedthing"),+ ("exporter_prefix_without_separator", "/exporterthing"),+ ]+ )+ @patch("posthog.csp_middleware.posthoganalytics.feature_enabled", return_value=True)+ def test_ordinary_page_is_enforced_for_a_flagged_user(self, _name, path, _mock_flag):+ assert app_csp_header_name(self._request(path)) == "Content-Security-Policy"++ @patch("posthog.csp_middleware.posthoganalytics.feature_enabled", return_value=False)+ def test_ordinary_page_stays_report_only_without_the_flag(self, _mock_flag):+ assert app_csp_header_name(self._request("/")) == "Content-Security-Policy-Report-Only"++ @patch("posthog.csp_middleware.posthoganalytics.feature_enabled", return_value=True)+ def test_the_flag_lookup_carries_the_email_for_local_evaluation(self, mock_flag):+ # Local evaluation cannot resolve a condition on email unless the caller supplies it, so a+ # staff-only rollout would enforce nothing.+ app_csp_header_name(self._request("/", email="[email protected]"))+ assert mock_flag.call_args.kwargs["person_properties"] == {"email": "[email protected]"}+ # Local evaluation keeps a flag network call out of every HTML response.+ assert mock_flag.call_args.kwargs["only_evaluate_locally"] is True++ @parameterized.expand(+ [+ ("login", "/login", None, CSP_ENFORCE_SIGNED_OUT_PAGES_FLAG, "Content-Security-Policy"),+ ("signup", "/signup", None, CSP_ENFORCE_SIGNED_OUT_PAGES_FLAG, "Content-Security-Policy"),+ ("reset_link", "/reset/abc/def", None, CSP_ENFORCE_SIGNED_OUT_PAGES_FLAG, "Content-Security-Policy"),+ (+ "reset_2fa_link",+ "/reset_2fa/abc/def",+ None,+ CSP_ENFORCE_SIGNED_OUT_PAGES_FLAG,+ "Content-Security-Policy",+ ),+ (+ "verify_email_link",+ "/verify_email/abc/def",+ None,+ CSP_ENFORCE_SIGNED_OUT_PAGES_FLAG,+ "Content-Security-Policy",+ ),+ ("login_without_a_flag", "/login", None, None, "Content-Security-Policy-Report-Only"),+ (+ "login_with_the_app_flag",+ "/login",+ None,+ CSP_ENFORCE_APP_POLICY_FLAG,+ "Content-Security-Policy-Report-Only",+ ),+ ("signed_in", "/login", "abc", CSP_ENFORCE_SIGNED_OUT_PAGES_FLAG, "Content-Security-Policy-Report-Only"),+ (+ "other_signed_out_page",+ "/messaging-preferences/abc",+ None,+ CSP_ENFORCE_SIGNED_OUT_PAGES_FLAG,+ "Content-Security-Policy-Report-Only",+ ),+ (+ "login_prefix_without_separator",+ "/loginfoo",+ None,+ CSP_ENFORCE_SIGNED_OUT_PAGES_FLAG,+ "Content-Security-Policy-Report-Only",+ ),+ ]+ )+ @patch("posthog.csp_middleware.posthoganalytics.feature_enabled")+ def test_each_flag_enforces_only_its_own_pages(+ self,+ _name: str,+ path: str,+ distinct_id: str | None,+ enabled_flag: str | None,+ expected: str,+ mock_flag: MagicMock,+ ) -> None:+ mock_flag.side_effect = lambda key, *args, **kwargs: key == enabled_flag+ assert app_csp_header_name(self._request(path, distinct_id=distinct_id)) == expected++ @patch("posthog.csp_middleware.posthoganalytics.feature_enabled", return_value=True)+ def test_each_signed_out_document_draws_its_own_bucket(self, mock_flag: MagicMock) -> None:+ app_csp_header_name(self._request("/login", distinct_id=None))+ app_csp_header_name(self._request("/login", distinct_id=None))+ # A fixed id would put every signed-out visitor in one bucket, so a rollout percentage+ # would enforce for everyone or nobody.+ first, second = (call.args[1] for call in mock_flag.call_args_list)+ assert first != second+ assert mock_flag.call_args.kwargs["only_evaluate_locally"] is True+ assert mock_flag.call_args.kwargs["send_feature_flag_events"] is False++ @parameterized.expand([("signed_in", "abc"), ("signed_out", None)])+ @patch("posthog.csp_middleware.posthoganalytics.feature_enabled", side_effect=Exception("flags unavailable"))+ def test_a_failing_flag_lookup_leaves_the_policy_report_only(+ self, _name: str, distinct_id: str | None, _mock_flag: MagicMock+ ) -> None:+ # Fail safe: an enforced policy that nobody meant to turn on breaks the page.+ assert (+ app_csp_header_name(self._request("/login", distinct_id=distinct_id))+ == "Content-Security-Policy-Report-Only"+ )+++class TestNarrowedAppPolicy(SimpleTestCase):+ def test_swaps_the_wildcards_and_keeps_every_other_source(self) -> None:+ app_policy = [+ "default-src 'self'",+ "script-src 'self' 'nonce-abc' 'wasm-unsafe-eval' https://*.posthog.com https://*.i.posthog.com https://js.stripe.com",+ "worker-src 'self' blob:",+ "img-src 'self' data: https://*.posthog.com",+ "connect-src 'self' https://api.github.com https://*.posthog.com",+ ]++ narrowed = narrowed_app_policy(+ app_policy,+ {+ "script-src": ["https://app-static-prod.posthog.com"],+ "connect-src": ["https://internal-j.posthog.com"],+ },+ )++ # A source the shadow dropped besides the wildcards would report loads the app policy allows,+ # and a directive it was not asked about would restrict what the shadow does not measure.+ assert narrowed == [+ "script-src 'self' 'nonce-abc' 'wasm-unsafe-eval' https://js.stripe.com https://app-static-prod.posthog.com",+ # Without it, workers fall back to script-src and the shadow reports the app's blob: workers.+ "worker-src 'self' blob:",+ "connect-src 'self' https://api.github.com https://internal-j.posthog.com",+ ]+++class TestViewManagedCsp(SimpleTestCase):+ @parameterized.expand(+ [+ ("custom_policy", "/", False, "default-src 'self'", False),+ # The workflow asset endpoint sandboxes captured email HTML and leaves frame-ancestors+ # open so the app can frame it. Enforcement must not replace that policy, because the+ # app policy drops the sandbox and names a frame-ancestors list the app origin does not+ # match, which blanks the viewer.+ ("custom_policy_under_enforcement", "/", True, "sandbox; default-src 'none'", False),+ ("custom_admin", "/admin/", False, "default-src *", True),+ ("no_policy", "/", False, None, True),+ ]+ )+ @override_settings(CLOUD_DEPLOYMENT="US")+ def test_html_response_with_view_managed_csp(+ self, _name: str, path: str, enforced: bool, policy: str | None, expects_reporting: bool+ ) -> None:+ def view(_request: HttpRequest) -> HttpResponse:+ response = HttpResponse("<html><body>artifact</body></html>", content_type="text/html; charset=utf-8")+ if policy is not None:+ response["Content-Security-Policy"] = policy+ return response++ request = RequestFactory().get(path)+ request.user = MagicMock(is_authenticated=True, distinct_id="abc", email="[email protected]")+ with patch("posthog.csp_middleware.posthoganalytics.feature_enabled", return_value=enforced):+ response = CSPMiddleware(view)(request)++ if path == "/admin/":+ assert "frame-ancestors 'none'" in response["Content-Security-Policy"]+ assert "default-src *" not in response["Content-Security-Policy"]+ elif policy is not None:+ assert response["Content-Security-Policy"] == policy+ else:+ assert response["Content-Security-Policy"].startswith("frame-ancestors ")+ assert ("Content-Security-Policy-Report-Only" in response) == (expects_reporting and path != "/admin/")+ assert ("Reporting-Endpoints" in response) == expects_reportingdiff --git a/posthog/test/test_middleware.py b/posthog/test/test_middleware.pyindex 8a5129f1b27c..93ec156c03df 100644--- a/posthog/test/test_middleware.py+++ b/posthog/test/test_middleware.py@@ -3,7 +3,6 @@ import jsonimport hashlibfrom datetime import datetime, timedeltafrom typing import Any, cast-from urllib.parse import urlsplitimport pytestimport time_machine@@ -31,13 +30,8 @@ from social_core.exceptions import AuthCanceled, AuthFailed, AuthMissingParametefrom posthog.api.test.test_organization import create_organizationfrom posthog.api.test.test_team import create_teamfrom posthog.middleware import (- CSP_ENFORCE_APP_POLICY_FLAG,- CSP_ENFORCE_SIGNED_OUT_PAGES_FLAG,- CSPMiddleware,ManagedProxyClientIPMiddleware,ManagedProxyClientIPOutcome,- app_csp_header_name,- narrowed_app_policy,per_request_logging_context_middleware,)from posthog.models.organization import Organization@@ -2171,281 +2165,6 @@ class TestActivityLoggingMiddleware(APIBaseTest):self.assertIsNone(self.captured["ip_address"])-class TestCSPMiddleware(APIBaseTest):- def test_replay_player_frame_carries_its_own_policy_and_reports_nothing(self):- # The frame exists so a recorded page stops being judged against the app policy. If the- # middleware branch goes, it silently inherits that policy again, along with its report-uri,- # and every replayed page resumes reporting a customer's site to our project.- response = self.client.get("/replay_player_frame/index.html")- assert response.status_code == 200- policy = response["Content-Security-Policy"]- assert "script-src 'none'" in policy- assert "img-src * data: blob:" in policy- assert "report-uri" not in policy- assert "Content-Security-Policy-Report-Only" not in response- assert "Reporting-Endpoints" not in response-- def test_app_policy_allows_framing_the_replay_player_frame(self):- # The player frame is same-origin, and an http origin does not match the https: source- # that heatmaps need.- response = self.client.get("/")- assert "frame-src 'self' https:" in response["Content-Security-Policy-Report-Only"]-- @parameterized.expand(- [- ("local", {}, "default-src 'self' http://localhost:8234;"),- # The bundle host alone. The rest of the policy names every PostHog subdomain, and a- # fallback that broad admits whatever a new directive forgets to restrict.- (- "cloud",- {- "TEST": False,- "DEBUG": False,- "CLOUD_DEPLOYMENT": "US",- "SITE_URL": "https://us.posthog.com",- "JS_URL": "https://app-static-prod.posthog.com",- },- "default-src 'self' https://app-static-prod.posthog.com;",- ),- ]- )- def test_app_policy_lets_firefox_preload_the_app_bundle(self, _name, overrides, expected):- # Firefox judges <link rel="modulepreload"> by default-src, not script-src. A default-src of- # 'self' alone refuses every preload index.html emits for the boot chain.- with override_settings(**overrides):- response = self.client.get("/")- assert expected in response["Content-Security-Policy-Report-Only"]-- def test_replay_player_frame_serves_the_mount_node_without_a_session(self):- # Shared recordings render the player for logged-out viewers.- self.client.logout()- response = self.client.get("/replay_player_frame/index.html")- assert response.status_code == 200- # PlayerFrame.tsx looks the mount node up by this id. A rename here makes every player show its load error.- assert 'id="player-frame-content"' in response.content.decode()-- def test_non_html_response_gets_strict_csp(self):- response = self.client.get("/api/users/@me/")- assert response.status_code == 200- assert response["Content-Security-Policy"] == "default-src 'none'"- assert "Content-Security-Policy-Report-Only" not in response-- @parameterized.expand(- [- ("app_root", "/", True),- # No route serves this path, so the app catch-all answers it. It must keep the app- # policy, because the frame policy is enforced and its script-src 'none' stops the app- # from starting.- ("path_under_the_replay_frame_prefix", "/replay_player_frame", True),- # A customer's page frames this document, and the enforced list names only PostHog- # origins.- ("embeddable_document", "/shared/notarealtoken", False),- ]- )- def test_html_response_without_the_flag_enforces_only_frame_ancestors(self, _name, path, enforces_frame_ancestors):- response = self.client.get(path)- reported = response["Content-Security-Policy-Report-Only"]- assert "default-src 'self'" in reported- if not enforces_frame_ancestors:- assert "Content-Security-Policy" not in response- return- # Framing is enforced ahead of the flag because it is what lets posthog.com frame the app.- # The enforced list has to be the one the reported policy names, or the two drift apart.- enforced = response["Content-Security-Policy"]- assert enforced.startswith("frame-ancestors https://posthog.com")- assert "default-src" not in enforced- assert enforced in reported-- @patch("posthog.middleware.posthoganalytics.feature_enabled", return_value=True)- def test_enforcement_reaches_an_app_page_but_not_an_embeddable_one(self, _mock_flag):- # The wiring guard for app_csp_header_name. The matrix of paths lives in- # TestAppCspHeaderName, which needs no database.- enforced = self.client.get("/")- assert "default-src 'self'" in enforced["Content-Security-Policy"]- assert "Content-Security-Policy-Report-Only" not in enforced-- embedded = self.client.get("/shared/notarealtoken")- assert "Content-Security-Policy" not in embedded- assert "frame-ancestors" in embedded["Content-Security-Policy-Report-Only"]-- @override_settings(CLOUD_DEPLOYMENT="US") # As PostHog Cloud- def test_html_response_declares_default_reporting_endpoint_with_distinct_id(self):- response = self.client.get("/")- policy = response["Content-Security-Policy-Report-Only"]- # A `report-to` directive makes browsers ignore `report-uri` and report through the- # Reporting API, which drops violations raised in about:blank and srcdoc frames.- assert "report-to" not in policy- _, report_endpoint = next(part for part in policy.split("; ") if part.startswith("report-uri ")).split()- assert report_endpoint.startswith("https://us.i.posthog.com/report/")- assert f"distinct_id={self.user.distinct_id}" in report_endpoint- # Browsers only deliver crash reports to the endpoint named `default`, so dropping or- # renaming it silently stops crash ingestion.- assert response["Reporting-Endpoints"] == f'default="{report_endpoint}"'-- @override_settings(CLOUD_DEPLOYMENT="US") # As PostHog Cloud- def test_reporting_endpoints_omit_distinct_id_when_logged_out(self):- self.client.logout()- response = self.client.get("/login")- policy = response["Content-Security-Policy-Report-Only"]- assert "report-uri https://us.i.posthog.com/report/" in policy- assert "distinct_id" not in policy- header = response["Reporting-Endpoints"]- assert 'default="https://us.i.posthog.com/report/' in header- assert "distinct_id" not in header-- @parameterized.expand(- [- ("self_hosted_by_default", {"CLOUD_DEPLOYMENT": None, "DEBUG": False}),- # DEBUG puts an install in the local run mode rather than the hobby one, and nothing- # stops a self-hoster deploying that way, so it must report nowhere as well.- ("self_hosted_with_debug", {"CLOUD_DEPLOYMENT": None, "DEBUG": True}),- # Cloud would otherwise report, so this case proves the empty value turns it off.- ("explicitly_disabled", {"CLOUD_DEPLOYMENT": "US", "CSP_REPORT_ENDPOINT": ""}),- ]- )- def test_no_endpoint_still_sends_the_policy_but_asks_for_no_reports(self, _name, overrides):- # A self-hosted install must not report to PostHog, and the policy itself must survive, so- # dropping it here would silently remove a security control.- with override_settings(**{"CSP_REPORT_ENDPOINT": None, **overrides}):- response = self.client.get("/")- policy = response["Content-Security-Policy-Report-Only"]- assert "default-src 'self'" in policy- assert "report-uri" not in policy- assert "report-to" not in policy- assert "Reporting-Endpoints" not in response-- @override_settings(CSP_REPORT_ENDPOINT="https://posthog.example.com/report/")- def test_report_endpoint_is_configurable(self):- # An operator can point reporting at their own install, so nothing may hardcode ours.- response = self.client.get("/")- policy = response["Content-Security-Policy-Report-Only"]- assert "report-uri https://posthog.example.com/report/?sample_rate=0.1" in policy- header = response["Reporting-Endpoints"]- assert "us.i.posthog.com" not in header- assert f"distinct_id={self.user.distinct_id}" in header-- @parameterized.expand(- [- ("staff", True, "1", "0.1"),- ("not_staff", False, "0.1", "1"),- ]- )- @override_settings(CSP_REPORT_ENDPOINT="https://posthog.example.com/report/")- def test_staff_report_every_violation_while_everyone_else_is_sampled(- self, _name, is_staff, expected_rate, other_rate- ):- # Staff get the policy enforced ahead of everyone else, so a violation of theirs is- # something already broken for a colleague rather than one sample of a trend. At 0.1 nine- # in ten of those never arrive, which defeats the point of rolling out to staff first.- self.user.is_staff = is_staff- self.user.save()-- response = self.client.get("/")-- policy = response["Content-Security-Policy-Report-Only"]- assert f"report-uri https://posthog.example.com/report/?sample_rate={expected_rate}" in policy- assert f"sample_rate={expected_rate}&distinct_id={self.user.distinct_id}" in policy- assert f"sample_rate={other_rate}" not in policy-- @parameterized.expand(- [- ("cloud", {"CLOUD_DEPLOYMENT": "US"}, True),- ("self_hosted", {"CLOUD_DEPLOYMENT": None, "DEBUG": False}, False),- ]- )- def test_admin_pages_enforce_the_policy_and_follow_the_reporting_default(self, _name, overrides, expects_reporting):- # The admin policy is enforced, not report-only, and builds its own Reporting-Endpoints- # header, so it can drift from the app policy unnoticed. A non-staff request redirects but- # still carries that policy, because the middleware picks its branch by path once the portal is on.- with override_settings(CSP_REPORT_ENDPOINT=None, ADMIN_PORTAL_ENABLED=True, **overrides):- response = self.client.get("/admin/")- policy = response["Content-Security-Policy"]- # Only the admin policy forbids framing outright; the non-HTML fallback is default-src alone.- assert "frame-ancestors 'none'" in policy- assert "Content-Security-Policy-Report-Only" not in response- assert "report-to" not in policy-- if expects_reporting:- assert "report-uri https://us.i.posthog.com/report/" in policy- # Sampling the admin policy too would silently drop violations, so the branches diverge.- assert "sample_rate" not in policy- # Without it every admin report arrives under a freshly minted id, so one staff session- # counts as many users.- assert f"distinct_id={self.user.distinct_id}" in policy- _, report_endpoint = next(part for part in policy.split("; ") if part.startswith("report-uri ")).split()- assert response["Reporting-Endpoints"] == f'default="{report_endpoint}"'- else:- assert "report-uri" not in policy- assert "Reporting-Endpoints" not in response-- @override_settings(ADMIN_PORTAL_ENABLED=False)- def test_admin_path_gets_the_app_policy_when_the_portal_is_off(self):- # Without the portal, `/admin/` is an app page, and the app keeps running in that document- # after it navigates away. The admin policy there would refuse every request the app makes- # to another origin.- response = self.client.get("/admin/")- assert "frame-ancestors 'none'" not in response["Content-Security-Policy"]- assert "connect-src 'self'" in response["Content-Security-Policy-Report-Only"]-- @parameterized.expand(- [- (- "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/",- },- ("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.- (- "self_hosted_with_reporting_on",- {- "CLOUD_DEPLOYMENT": None,- "SITE_URL": "https://posthog.example.com",- "CSP_REPORT_ENDPOINT": "https://posthog.example.com/report/?token=phc_test&v=2",- },- None,- ),- ]- )- 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):- response = self.client.get("/")-- 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 regions else 0)- if regions:- region, other_region = regions- shadow = shadows[0]- assert "*.posthog.com" not in shadow- assert "https://internal-cf.posthog.com/array/sTMFPsFhdP1Ssg/config.js" 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):CONFIG_AUTO_LOGIN = False@@ -2938,204 +2657,3 @@ class TestPerRequestLoggingContextMiddlewareMcpHeaders(APIBaseTest):assert "mcp_session_id" not in ctxassert "mcp_conversation_id" not in ctxspan.set_attribute.assert_not_called()---class TestAppCspHeaderName(SimpleTestCase):- def _request(- self, path: str, *, distinct_id: str | None = "abc", email: str = "[email protected]"- ) -> HttpRequest:- request = RequestFactory().get(path)- request.user = MagicMock(is_authenticated=distinct_id is not None, distinct_id=distinct_id, email=email)- return request-- @parameterized.expand(- [- ("shared_dashboard", "/shared_dashboard/abc123"),- ("shared", "/shared/abc123"),- ("embedded", "/embedded/abc123"),- ("interview", "/interview/abc123"),- ("exporter_with_token", "/exporter/abc123"),- ("exporter_render", "/exporter"),- ("render_query", "/render_query"),- ("external_survey", "/external_surveys/019efb7e-0672-0000-729b-e234586f6177"),- ]- )- @patch("posthog.middleware.posthoganalytics.feature_enabled", return_value=True)- def test_embeddable_document_stays_report_only_under_enforcement(self, _name, path, _mock_flag):- # A customer's site frames each of these. The app policy names only PostHog origins in- # frame-ancestors, so enforcing it here stops the document rendering on their page.- assert app_csp_header_name(self._request(path)) == "Content-Security-Policy-Report-Only"- assert app_csp_header_name(self._request(path, distinct_id=None)) == "Content-Security-Policy-Report-Only"-- @parameterized.expand(- [- ("app_root", "/"),- ("project_page", "/project/2/dashboard"),- # Neither prefix owns these. A shorter prefix match would hand the app catch-all the- # carve-out and quietly exempt an ordinary page from enforcement.- ("shared_prefix_without_separator", "/sharedthing"),- ("exporter_prefix_without_separator", "/exporterthing"),- ]- )- @patch("posthog.middleware.posthoganalytics.feature_enabled", return_value=True)- def test_ordinary_page_is_enforced_for_a_flagged_user(self, _name, path, _mock_flag):- assert app_csp_header_name(self._request(path)) == "Content-Security-Policy"-- @patch("posthog.middleware.posthoganalytics.feature_enabled", return_value=False)- def test_ordinary_page_stays_report_only_without_the_flag(self, _mock_flag):- assert app_csp_header_name(self._request("/")) == "Content-Security-Policy-Report-Only"-- @patch("posthog.middleware.posthoganalytics.feature_enabled", return_value=True)- def test_the_flag_lookup_carries_the_email_for_local_evaluation(self, mock_flag):- # Local evaluation cannot resolve a condition on email unless the caller supplies it, so a- # staff-only rollout would enforce nothing.- app_csp_header_name(self._request("/", email="[email protected]"))- assert mock_flag.call_args.kwargs["person_properties"] == {"email": "[email protected]"}- # Local evaluation keeps a flag network call out of every HTML response.- assert mock_flag.call_args.kwargs["only_evaluate_locally"] is True-- @parameterized.expand(- [- ("login", "/login", None, CSP_ENFORCE_SIGNED_OUT_PAGES_FLAG, "Content-Security-Policy"),- ("signup", "/signup", None, CSP_ENFORCE_SIGNED_OUT_PAGES_FLAG, "Content-Security-Policy"),- ("reset_link", "/reset/abc/def", None, CSP_ENFORCE_SIGNED_OUT_PAGES_FLAG, "Content-Security-Policy"),- (- "reset_2fa_link",- "/reset_2fa/abc/def",- None,- CSP_ENFORCE_SIGNED_OUT_PAGES_FLAG,- "Content-Security-Policy",- ),- (- "verify_email_link",- "/verify_email/abc/def",- None,- CSP_ENFORCE_SIGNED_OUT_PAGES_FLAG,- "Content-Security-Policy",- ),- ("login_without_a_flag", "/login", None, None, "Content-Security-Policy-Report-Only"),- (- "login_with_the_app_flag",- "/login",- None,- CSP_ENFORCE_APP_POLICY_FLAG,- "Content-Security-Policy-Report-Only",- ),- ("signed_in", "/login", "abc", CSP_ENFORCE_SIGNED_OUT_PAGES_FLAG, "Content-Security-Policy-Report-Only"),- (- "other_signed_out_page",- "/messaging-preferences/abc",- None,- CSP_ENFORCE_SIGNED_OUT_PAGES_FLAG,- "Content-Security-Policy-Report-Only",- ),- (- "login_prefix_without_separator",- "/loginfoo",- None,- CSP_ENFORCE_SIGNED_OUT_PAGES_FLAG,- "Content-Security-Policy-Report-Only",- ),- ]- )- @patch("posthog.middleware.posthoganalytics.feature_enabled")- def test_each_flag_enforces_only_its_own_pages(- self,- _name: str,- path: str,- distinct_id: str | None,- enabled_flag: str | None,- expected: str,- mock_flag: MagicMock,- ) -> None:- mock_flag.side_effect = lambda key, *args, **kwargs: key == enabled_flag- assert app_csp_header_name(self._request(path, distinct_id=distinct_id)) == expected-- @patch("posthog.middleware.posthoganalytics.feature_enabled", return_value=True)- def test_each_signed_out_document_draws_its_own_bucket(self, mock_flag: MagicMock) -> None:- app_csp_header_name(self._request("/login", distinct_id=None))- app_csp_header_name(self._request("/login", distinct_id=None))- # A fixed id would put every signed-out visitor in one bucket, so a rollout percentage- # would enforce for everyone or nobody.- first, second = (call.args[1] for call in mock_flag.call_args_list)- assert first != second- assert mock_flag.call_args.kwargs["only_evaluate_locally"] is True- assert mock_flag.call_args.kwargs["send_feature_flag_events"] is False-- @parameterized.expand([("signed_in", "abc"), ("signed_out", None)])- @patch("posthog.middleware.posthoganalytics.feature_enabled", side_effect=Exception("flags unavailable"))- def test_a_failing_flag_lookup_leaves_the_policy_report_only(- self, _name: str, distinct_id: str | None, _mock_flag: MagicMock- ) -> None:- # Fail safe: an enforced policy that nobody meant to turn on breaks the page.- assert (- app_csp_header_name(self._request("/login", distinct_id=distinct_id))- == "Content-Security-Policy-Report-Only"- )---class TestNarrowedAppPolicy(SimpleTestCase):- def test_swaps_the_wildcards_and_keeps_every_other_source(self) -> None:- app_policy = [- "default-src 'self'",- "script-src 'self' 'nonce-abc' 'wasm-unsafe-eval' https://*.posthog.com https://*.i.posthog.com https://js.stripe.com",- "worker-src 'self' blob:",- "img-src 'self' data: https://*.posthog.com",- "connect-src 'self' https://api.github.com https://*.posthog.com",- ]-- narrowed = narrowed_app_policy(- app_policy,- {- "script-src": ["https://app-static-prod.posthog.com"],- "connect-src": ["https://internal-j.posthog.com"],- },- )-- # A source the shadow dropped besides the wildcards would report loads the app policy allows,- # and a directive it was not asked about would restrict what the shadow does not measure.- assert narrowed == [- "script-src 'self' 'nonce-abc' 'wasm-unsafe-eval' https://js.stripe.com https://app-static-prod.posthog.com",- # Without it, workers fall back to script-src and the shadow reports the app's blob: workers.- "worker-src 'self' blob:",- "connect-src 'self' https://api.github.com https://internal-j.posthog.com",- ]---class TestViewManagedCsp(SimpleTestCase):- @parameterized.expand(- [- ("custom_policy", "/", False, "default-src 'self'", False),- # The workflow asset endpoint sandboxes captured email HTML and leaves frame-ancestors- # open so the app can frame it. Enforcement must not replace that policy, because the- # app policy drops the sandbox and names a frame-ancestors list the app origin does not- # match, which blanks the viewer.- ("custom_policy_under_enforcement", "/", True, "sandbox; default-src 'none'", False),- ("custom_admin", "/admin/", False, "default-src *", True),- ("no_policy", "/", False, None, True),- ]- )- @override_settings(CLOUD_DEPLOYMENT="US")- def test_html_response_with_view_managed_csp(- self, _name: str, path: str, enforced: bool, policy: str | None, expects_reporting: bool- ) -> None:- def view(_request: HttpRequest) -> HttpResponse:- response = HttpResponse("<html><body>artifact</body></html>", content_type="text/html; charset=utf-8")- if policy is not None:- response["Content-Security-Policy"] = policy- return response-- request = RequestFactory().get(path)- request.user = MagicMock(is_authenticated=True, distinct_id="abc", email="[email protected]")- with patch("posthog.middleware.posthoganalytics.feature_enabled", return_value=enforced):- response = CSPMiddleware(view)(request)-- if path == "/admin/":- assert "frame-ancestors 'none'" in response["Content-Security-Policy"]- assert "default-src *" not in response["Content-Security-Policy"]- elif policy is not None:- assert response["Content-Security-Policy"] == policy- else:- assert response["Content-Security-Policy"].startswith("frame-ancestors ")- assert ("Content-Security-Policy-Report-Only" in response) == (expects_reporting and path != "/admin/")- assert ("Reporting-Endpoints" in response) == expects_reporting