Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(canvas): mount single-quoted entries and remove csp warnings (#91518)

Peter Kirkhamfdea110b8003
diff --git a/docs/internal/canvas-collaboration.md b/docs/internal/canvas-collaboration.md
index ee042ed3951b..237c584b4b3e 100644
--- a/docs/internal/canvas-collaboration.md
+++ b/docs/internal/canvas-collaboration.md
@@ -19,6 +19,15 @@ off the live canvas. A publish creates a source version and queues its build.
The live artifact changes only after a successful build. A failed build leaves
the last successful artifact available.
+For a component entry at `/src/canvas.tsx`, the builder adds the React mount code.
+The script's `src` attribute can use single or double quotes, with spaces around `=`.
+Builder fixes apply to new builds, not existing artifacts.
+Republish an affected canvas after the builder fix is deployed to replace a blank artifact.
+
+Canvas artifact responses use their enforced CSP without the application-wide report-only policy.
+Only the artifact response helper sets this exception; a CSP header alone does not enable it.
+Admin policy enforcement and reporting on other pages remain unchanged.
+
Use `expected_current_version_id` when publishing. A stale version returns HTTP 409.
Read the current source, apply the change again, and retry against that version.
Use version history to inspect earlier source and revert an unwanted change.
diff --git a/posthog/middleware.py b/posthog/middleware.py
index 937ce4ccb5e9..57cf2715a110 100644
--- a/posthog/middleware.py
+++ b/posthog/middleware.py
@@ -1240,6 +1240,8 @@ class CSPMiddleware:
f'posthog="{admin_report_endpoint}", default="{admin_report_endpoint}"'
)
response.headers["Content-Security-Policy"] = "; ".join(csp_parts)
+ elif getattr(response, "_posthog_canvas_artifact", False) and "Content-Security-Policy" in response.headers:
+ return response
else:
resource_url = "https://*.posthog.com"
if settings.DEBUG or settings.TEST:
diff --git a/posthog/test/test_middleware.py b/posthog/test/test_middleware.py
index d6fdb5d01a04..eaf3006d50f7 100644
--- a/posthog/test/test_middleware.py
+++ b/posthog/test/test_middleware.py
@@ -9,7 +9,7 @@ from unittest.mock import MagicMock, patch
from django.conf import settings
from django.core.cache import cache
-from django.http import HttpResponse, HttpResponseRedirect
+from django.http import HttpRequest, HttpResponse, HttpResponseRedirect
from django.test import (
Client as DjangoClient,
RequestFactory,
@@ -25,13 +25,14 @@ from social_core.exceptions import AuthCanceled, AuthFailed, AuthMissingParamete
from posthog.api.test.test_organization import create_organization
from posthog.api.test.test_team import create_team
-from posthog.middleware import per_request_logging_context_middleware
+from posthog.middleware import CSPMiddleware, per_request_logging_context_middleware
from posthog.models.organization import Organization
from posthog.models.team import Team
from posthog.models.user import User
from posthog.settings import SITE_URL
from products.actions.backend.models.action import Action
+from products.canvas.backend.artifacts import CANVAS_ARTIFACT_RESPONSE_MARKER
from products.cohorts.backend.models.cohort import Cohort
from products.dashboards.backend.models.dashboard import Dashboard
from products.feature_flags.backend.models.feature_flag import FeatureFlag
@@ -1939,6 +1940,39 @@ class TestCSPMiddleware(APIBaseTest):
assert "Content-Security-Policy-Report-Only" in response
assert "Content-Security-Policy" not in response
+ @parameterized.expand(
+ [
+ ("custom_policy", "/", False, "default-src 'self'", True),
+ ("canvas", "/", True, "sandbox allow-scripts; default-src 'none'", False),
+ ("custom_admin", "/admin/", False, "default-src *", True),
+ ("marked_admin", "/admin/", True, "default-src *", True),
+ ("marker_without_policy", "/", True, None, True),
+ ]
+ )
+ @override_settings(CLOUD_DEPLOYMENT="US")
+ def test_html_response_with_view_managed_csp(
+ self, _name: str, path: str, canvas_artifact: 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
+ if canvas_artifact:
+ setattr(response, CANVAS_ARTIFACT_RESPONSE_MARKER, True)
+ return response
+
+ response = CSPMiddleware(view)(RequestFactory().get(path))
+
+ 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 "Content-Security-Policy" not in response
+ assert ("Content-Security-Policy-Report-Only" in response) == (expects_reporting and path != "/admin/")
+ assert ("Reporting-Endpoints" in response) == expects_reporting
+
@override_settings(CLOUD_DEPLOYMENT="US") # As PostHog Cloud
def test_html_response_declares_default_reporting_endpoint_with_distinct_id(self):
# Browsers only deliver crash reports to the endpoint named `default`, so dropping or
diff --git a/products/canvas/backend/artifacts.py b/products/canvas/backend/artifacts.py
index 2d8cf77a2dc1..bc893fab9cdb 100644
--- a/products/canvas/backend/artifacts.py
+++ b/products/canvas/backend/artifacts.py
@@ -27,6 +27,7 @@ from posthog.storage import object_storage
from products.canvas.backend.contract import artifact_csp
from products.canvas.backend.models import CanvasBuild
+CANVAS_ARTIFACT_RESPONSE_MARKER = "_posthog_canvas_artifact"
ARTIFACT_TOKEN_SALT = "posthog.canvas.artifact.v1"
# Tokens embed a coarse time bucket instead of a per-second timestamp, so the
# artifact URL for a build is stable within a bucket (the iframe src doesn't
@@ -172,5 +173,6 @@ def _with_artifact_headers(response: HttpResponse, etag: str, manifest: dict) ->
response["X-Content-Type-Options"] = "nosniff"
network_origins = ((manifest.get("capabilities") or {}).get("network") or {}).get("origins") or []
response["Content-Security-Policy"] = artifact_csp(network_origins)
+ setattr(response, CANVAS_ARTIFACT_RESPONSE_MARKER, True)
response["Permissions-Policy"] = "camera=(), microphone=(), geolocation=(), payment=(), usb=()"
return response
diff --git a/products/canvas/backend/tests/test_artifacts.py b/products/canvas/backend/tests/test_artifacts.py
index c36b03100e82..08aca141fe18 100644
--- a/products/canvas/backend/tests/test_artifacts.py
+++ b/products/canvas/backend/tests/test_artifacts.py
@@ -1,7 +1,7 @@
import time
import hashlib
-from posthog.test.base import APIBaseTest
+from posthog.test.base import APIBaseTest, override_settings
from unittest.mock import patch
from posthog.models.scoping import team_scope
@@ -55,9 +55,12 @@ class TestCanvasArtifacts(APIBaseTest):
assert url is not None
return url.replace("http://localhost:8010", "")
+ @override_settings(CLOUD_DEPLOYMENT="US")
def test_serves_artifact_with_etag_and_csp(self):
response = self.client.get(self._url())
assert response.status_code == 200
+ assert "Content-Security-Policy-Report-Only" not in response
+ assert "Reporting-Endpoints" not in response
assert response.content == CONTENT
assert response["ETag"] == f'"{self.content_hash}"'
assert response["Content-Security-Policy"].startswith(
@@ -76,10 +79,13 @@ class TestCanvasArtifacts(APIBaseTest):
# white-screens.
assert response["Access-Control-Allow-Origin"] == "*"
+ @override_settings(CLOUD_DEPLOYMENT="US")
def test_revalidation_returns_304_without_reading_storage(self):
url = self._url()
response = self.client.get(url, HTTP_IF_NONE_MATCH=f'"{self.content_hash}"')
assert response.status_code == 304
+ assert "Content-Security-Policy-Report-Only" not in response
+ assert "Reporting-Endpoints" not in response
assert response["Content-Type"] == "text/html; charset=utf-8"
assert "script-src 'self'" in response["Content-Security-Policy"]
self.read_bytes.assert_not_called()
diff --git a/products/canvas/backend/tests/test_cloud_builder.py b/products/canvas/backend/tests/test_cloud_builder.py
index b91e4a2172c8..871ed5a6e6f8 100644
--- a/products/canvas/backend/tests/test_cloud_builder.py
+++ b/products/canvas/backend/tests/test_cloud_builder.py
@@ -19,10 +19,26 @@ from products.canvas.backend.source import _PLATFORM_ELEMENT_TOKENS, synthetic_s
class TestCanvasCloudBuilder(SimpleTestCase):
- def test_legacy_canvas_build_mounts_react_and_injects_the_runtime_bridge(self) -> None:
+ @parameterized.expand(
+ [
+ ("double_quotes", 'src="/src/canvas.tsx"'),
+ ("single_quotes", "src='/src/canvas.tsx'"),
+ ("attribute_whitespace", "src = '/src/canvas.tsx'"),
+ ("data_src_before_src", 'data-src="/src/canvas.tsx" src="/src/canvas.tsx"'),
+ ("quoted_src_before_src", 'data-config="mode src=\'/src/canvas.tsx\'" src="/src/canvas.tsx"'),
+ ("quoted_generated_entry", 'data-config="mode src=\'/src/canvas-entry.tsx\'" src="/src/canvas.tsx"'),
+ ("quoted_greater_than", 'data-config="> src=\'/src/canvas.tsx\'" src="/src/canvas.tsx"'),
+ ]
+ )
+ def test_legacy_canvas_build_mounts_react_and_injects_the_runtime_bridge(
+ self, _name: str, source_attribute: str
+ ) -> None:
payload = synthetic_source_project(
'import React from "react"; export default function Canvas() { return <div>Hello</div> }'
)
+ payload["files"]["index.html"] = payload["files"]["index.html"].replace(
+ 'src="/src/canvas.tsx"', source_attribute
+ )
result = run_cloud_builder(payload)
@@ -32,6 +48,11 @@ class TestCanvasCloudBuilder(SimpleTestCase):
html = next(file["content"] for file in result["files"] if file["path"] == "index.html")
self.assertIn("createRoot", javascript)
self.assertIn("canvas-runtime", html)
+ if config_attribute := re.search(r'data-config="[^"]*"', source_attribute):
+ self.assertIn(config_attribute.group(0), html)
+ meta_csp = html.split('content="', 1)[1].split('"', 1)[0]
+ self.assertNotIn("sandbox", meta_csp.split(";")[0])
+ self.assertIn("default-src 'none'", meta_csp)
def test_legacy_canvas_build_compiles_tailwind_and_quill_styles(self) -> None:
payload = synthetic_source_project(
@@ -186,13 +207,22 @@ class TestCanvasCloudBuilder(SimpleTestCase):
self.assertEqual(process.returncode, 0, process.stderr or process.stdout)
def test_builds_vanilla_typescript_with_the_shared_contract(self) -> None:
- result = run_cloud_builder(self._project('document.querySelector("#root")!.textContent = "Hello"'))
+ project = self._project('document.querySelector("#root")!.textContent = "Hello"')
+ project["files"]["src/canvas.tsx"] = "export default function Canvas() { return null }"
+ config_attribute = "data-config=\"mode src='/src/canvas.tsx'; module='/src/main.ts'\""
+ project["files"]["index.html"] = project["files"]["index.html"].replace(
+ "<script ", f"<script {config_attribute} "
+ )
+ result = run_cloud_builder(project)
files, manifest, diagnostics = validate_builder_output(result)
self.assertEqual(diagnostics, [])
self.assertEqual(manifest["entryHtml"], "index.html")
self.assertFalse(manifest["capabilities"]["posthog"]["inlineQueries"])
self.assertTrue(any(file["path"].endswith(".js") for file in files))
+ self.assertNotIn("legacyComponentPath", manifest)
+ html = next(file["content"] for file in files if file["path"] == "index.html")
+ self.assertIn(config_attribute, html)
def test_bundles_every_allowlisted_platform_library(self) -> None:
# Transitive versions are not pinned, so a caret range can drift onto a
diff --git a/products/canvas/packages/canvas_builder/build.mjs b/products/canvas/packages/canvas_builder/build.mjs
index b00c83013071..37729f2843e0 100644
--- a/products/canvas/packages/canvas_builder/build.mjs
+++ b/products/canvas/packages/canvas_builder/build.mjs
@@ -22,7 +22,7 @@ const canvasSdkSpecifier = '@posthog/canvas-sdk'
const canvasSdkModule = readFileSync(new URL('./canvas-sdk.mjs', import.meta.url), 'utf8')
const builderDirectory = path.dirname(fileURLToPath(import.meta.url))
const builderRequire = createRequire(import.meta.url)
-const htmlTag = /<(script|link)\b[^>]*>/gi
+const htmlTag = /<(script|link)\b(?:[^>"']|"[^"]*"|'[^']*')*>/gi
const htmlAttribute = /([a-zA-Z][\w-]*)\s*=\s*(?:"([^"]*)"|'([^']*)')/g
const forbiddenHtml = /(?:src|href)\s*=\s*["']\s*(javascript|data:text\/html|vbscript)/i
const extensions = ['', '.ts', '.tsx', '.js', '.jsx', '.css', '.json', '.svg', '.txt']
@@ -248,25 +248,45 @@ function entryReferences(html) {
for (const tag of html.matchAll(htmlTag)) {
const attributes = {}
for (const attribute of tag[0].matchAll(htmlAttribute)) {
- attributes[attribute[1].toLowerCase()] = attribute[2] ?? attribute[3] ?? ''
+ const quote = attribute[2] !== undefined ? '"' : "'"
+ attributes[attribute[1].toLowerCase()] = {
+ value: attribute[2] ?? attribute[3] ?? '',
+ valueStart: tag.index + attribute.index + attribute[0].indexOf(quote) + 1,
+ }
}
- if (tag[1].toLowerCase() === 'script' && attributes.type === 'module' && attributes.src) {
- references.push([attributes.src, 'js'])
+ let entry
+ let kind
+ if (tag[1].toLowerCase() === 'script' && attributes.type?.value === 'module' && attributes.src?.value) {
+ entry = attributes.src
+ kind = 'js'
} else if (
tag[1].toLowerCase() === 'link' &&
- attributes.rel === 'stylesheet' &&
- attributes.href &&
- !/^https:\/\//i.test(attributes.href)
+ attributes.rel?.value === 'stylesheet' &&
+ attributes.href?.value &&
+ !/^https:\/\//i.test(attributes.href.value)
) {
// A remote HTTPS stylesheet is not a local build entry, so it stays
// in the emitted HTML and loads at runtime under the declared-origin
// style-src CSP. Only local stylesheets are bundled here.
- references.push([attributes.href, 'css'])
+ entry = attributes.href
+ kind = 'css'
+ } else {
+ continue
}
+ references.push({ reference: entry.value, kind, valueStart: entry.valueStart })
}
return references
}
+function rewriteEntryReferences(html, reference, replacement, kind) {
+ for (const entry of entryReferences(html).reverse()) {
+ if (entry.reference === reference && entry.kind === kind) {
+ html = html.slice(0, entry.valueStart) + replacement + html.slice(entry.valueStart + reference.length)
+ }
+ }
+ return html
+}
+
function diagnostic(code, message, file, line) {
return {
severity: 'error',
@@ -480,11 +500,14 @@ async function buildCanvas(project) {
project = { ...project, files: { ...project.files }, dependencies: { ...project.dependencies } }
let html = project.files[project.entryHtml]
let legacy = null
- if (project.files['src/canvas.tsx'] && html.includes('src="/src/canvas.tsx"')) {
+ if (
+ project.files['src/canvas.tsx'] &&
+ entryReferences(html).some(({ reference, kind }) => reference === '/src/canvas.tsx' && kind === 'js')
+ ) {
legacy = { legacyComponentPath: 'src/canvas.tsx', legacyCode: project.files['src/canvas.tsx'] }
project.files['src/canvas-entry.tsx'] =
'import React from "react"; import { createRoot } from "react-dom/client"; import Canvas from "./canvas"; const root = document.getElementById("root"); if (root) createRoot(root).render(React.createElement(Canvas));'
- html = html.replace('src="/src/canvas.tsx"', 'src="/src/canvas-entry.tsx"')
+ html = rewriteEntryReferences(html, '/src/canvas.tsx', '/src/canvas-entry.tsx', 'js')
project.files[project.entryHtml] = html
// The injected mount is platform code, not the author's — admit the react/
// react-dom it needs even when the source only declared react.
@@ -509,7 +532,7 @@ async function buildCanvas(project) {
const files = []
let platformCss = ''
try {
- for (const [reference, kind] of refs) {
+ for (const { reference, kind } of refs) {
const entry = normalize(reference)
if (!(entry in project.files)) {
return {
@@ -529,7 +552,7 @@ async function buildCanvas(project) {
const content = kind === 'css' ? css : javascript
const emitted = `assets/${path.posix.basename(entry).replace(/\.[^.]+$/, '')}-${sha256(content).slice(0, 10)}.${kind}`
files.push(artifact(emitted, content))
- html = html.split(`"${reference}"`).join(`"./${emitted}"`).split(`'${reference}'`).join(`'./${emitted}'`)
+ html = rewriteEntryReferences(html, reference, `./${emitted}`, kind)
if (kind === 'js' && css) {
const cssPath = `assets/${path.posix.basename(entry).replace(/\.[^.]+$/, '')}-${sha256(css).slice(0, 10)}.css`
files.push(artifact(cssPath, css))
@@ -580,7 +603,10 @@ async function buildCanvas(project) {
.replace("media-src 'self' data: blob:", `media-src 'self' data: blob: ${externalSources}`)
.replace("frame-src 'none'", `frame-src ${externalSources}`)
: csp
- const head = `<meta http-equiv="Content-Security-Policy" content="${projectCsp}" /><link rel="stylesheet" href="./${cssPath}" /><script src="./${runtimePath}"></script>`
+ // `sandbox` is ignored in a <meta> policy and logs a console warning on every
+ // artifact load; the artifact origin delivers it via the response header.
+ const metaCsp = projectCsp.replace(/^sandbox[^;]*;\s*/, '')
+ const head = `<meta http-equiv="Content-Security-Policy" content="${metaCsp}" /><link rel="stylesheet" href="./${cssPath}" /><script src="./${runtimePath}"></script>`
html = html.includes('<head>') ? html.replace('<head>', `<head>${head}`) : `${head}${html}`
files.unshift(artifact(project.entryHtml, html))
const manifest = {