Skip to content

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

fix(csp): make four template scripts run under the strict csp (#104022)

Tom Piccirello108ca796190f
diff --git a/.semgrep/rules/devex/csp-inline-js-in-template.html b/.semgrep/rules/devex/csp-inline-js-in-template.html
new file mode 100644
index 000000000000..40695f581c8e
--- /dev/null
+++ b/.semgrep/rules/devex/csp-inline-js-in-template.html
@@ -0,0 +1,71 @@
+{% extends "admin/base_site.html" %}
+{% comment %}
+Fixture for csp-inline-js-in-template. Markup quoted in a comment never reaches the browser:
+<a href="javascript:void(0)">x</a> <button onclick="go()">x</button> <script>go()</script>
+{% endcomment %}
+{# <script>go()</script> <a href="javascript:go()">x</a> #}
+<!-- <button onclick="go()">x</button> <script>go()</script> -->
+{% block content %}
+ <!-- ruleid: csp-javascript-url-in-template -->
+ <a href="javascript:history.back()" class="button">Back</a>
+ <!-- ruleid: csp-javascript-url-in-template -->
+ <a href='javascript:void(0)'>Nothing</a>
+ <!-- ruleid: csp-javascript-url-in-template -->
+ <a HREF=" JavaScript:go()">Mixed case</a>
+ <!-- ruleid: csp-javascript-url-in-template -->
+ <form method="post" action="javascript:submitIt()">
+ <!-- ruleid: csp-javascript-url-in-template -->
+ <button type="submit" formaction="javascript:submitIt()">Save</button>
+ </form>
+ <!-- ok: csp-javascript-url-in-template -->
+ <a href="{{ settings_url }}" class="button">Settings</a>
+ <!-- ok: csp-javascript-url-in-template -->
+ <span data-href="javascript:go()">A script reads this attribute; the browser does not follow it.</span>
+ <!-- ok: csp-javascript-url-in-template -->
+ <p>Links that start with javascript: do not run under the policy.</p>
+ <!-- ok: csp-javascript-url-in-template -->
+ <p>Do not write <code>href="javascript:go()"</code> in a template.</p>
+
+ <!-- ruleid: csp-inline-event-handler-in-template -->
+ <button type="button" onclick="go()">Go</button>
+ <!-- ruleid: csp-inline-event-handler-in-template -->
+ <input type="text"
+ readonly
+ value="{{ value }}"
+ onclick="this.select()" />
+ <!-- ruleid: csp-inline-event-handler-in-template -->
+ <img src="{{ image_url }}" alt="" ONERROR='this.remove()'>
+ <!-- ruleid: csp-inline-event-handler-in-template -->
+ <select name="mode" class="x"onchange="this.form.submit()"></select>
+ <!-- ok: csp-inline-event-handler-in-template -->
+ <div data-onboarding="step-1" class="card">Onboarding</div>
+ <!-- ok: csp-inline-event-handler-in-template -->
+ <button type="button" x-on:click="open = true">Open</button>
+ <!-- ok: csp-inline-event-handler-in-template -->
+ <p>Turn the setting on = off to reset it.</p>
+
+ <!-- ruleid: csp-inline-script-without-nonce -->
+ <script>
+ document.addEventListener("click", function () {});
+ </script>
+ <!-- ruleid: csp-inline-script-without-nonce -->
+ <script type="module">import "/static/x.js"</script>
+ <!-- ruleid: csp-inline-script-without-nonce -->
+ <SCRIPT type="text/javascript">go()</SCRIPT>
+ <!-- ok: csp-inline-script-without-nonce -->
+ <script nonce="{{ request.csp_nonce }}">
+ var button = document.getElementById("go");
+ button.onclick = function () {};
+ for (var i = 0; i<n; i++) { button.onfocus = null; }
+ </script>
+ <!-- ok: csp-inline-script-without-nonce -->
+ <script
+ type="module"
+ nonce="{{ request.csp_nonce }}">go()</script>
+ <!-- ok: csp-inline-script-without-nonce -->
+ <script src="/static/admin/x.js"></script>
+ <!-- ok: csp-inline-script-without-nonce -->
+ <script type="application/json" id="config">{"a": 1}</script>
+ <!-- ok: csp-inline-script-without-nonce -->
+ <script type="text/template" id="row"><tr><td></td></tr></script>
+{% endblock %}
diff --git a/.semgrep/rules/devex/csp-inline-js-in-template.yaml b/.semgrep/rules/devex/csp-inline-js-in-template.yaml
new file mode 100644
index 000000000000..7f45ce0b6a03
--- /dev/null
+++ b/.semgrep/rules/devex/csp-inline-js-in-template.yaml
@@ -0,0 +1,102 @@
+rules:
+ - id: csp-javascript-url-in-template
+ message: |
+ This `javascript:` URL never runs for a viewer whose policy is enforced. The app and
+ admin policies in `CSPMiddleware` set `script-src` to a nonce with no `'unsafe-inline'`,
+ and a browser treats a `javascript:` URL as an inline script. The link does nothing, and
+ the user sees no error.
+
+ Make it a real link to a URL. If the action needs script, render a `<button type="button">`
+ and bind its handler with `addEventListener` inside `<script nonce="{{ request.csp_nonce }}">`.
+ `posthog/templates/admin/deletion_button.html` shows the pattern.
+
+ See "Content Security Policy" in `.agents/security.md`.
+ severity: ERROR
+ languages: [generic]
+ paths:
+ include:
+ - /posthog/**/templates/**/*.html
+ - /products/*/backend/templates/**/*.html
+ - /ee/**/templates/**/*.html
+ - /frontend/src/**/*.html
+ patterns:
+ # The match has to start inside a tag, so page text that shows `href="javascript:..."`
+ # does not match. `data-href="javascript:..."` is data for a script to read, not a URL
+ # the browser follows.
+ - pattern-regex: '(?i)<[a-z][a-z0-9-]*\b[^<>]*?(?<![\w-])(?:href|src|action|formaction|xlink:href)\s*=\s*["'']?\s*javascript:'
+ # Markup quoted in a template or HTML comment never reaches the browser as a tag.
+ - pattern-not-regex: '(?s)\{%\s*comment\s*%\}.*?\{%\s*endcomment\s*%\}|<!--.*?-->|\{#.*?#\}'
+ metadata:
+ category: correctness
+ technology:
+ - django
+ - html
+ references:
+ - https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/script-src#unsafe_inline_script
+
+ - id: csp-inline-event-handler-in-template
+ message: |
+ This inline event handler never runs for a viewer whose policy is enforced. The app and
+ admin policies in `CSPMiddleware` set `script-src` to a nonce with no `'unsafe-inline'`
+ and no `'unsafe-hashes'`. A nonce cannot cover an attribute, so no change to the policy
+ makes this work. The browser drops the handler, and the user sees no error.
+
+ Give the element an `id` or a class, and bind the handler with `addEventListener` inside
+ `<script nonce="{{ request.csp_nonce }}">`. `posthog/templates/admin/deletion_button.html`
+ shows the pattern.
+
+ See "Content Security Policy" in `.agents/security.md`.
+ severity: ERROR
+ languages: [generic]
+ paths:
+ include:
+ - /posthog/**/templates/**/*.html
+ - /products/*/backend/templates/**/*.html
+ - /ee/**/templates/**/*.html
+ - /frontend/src/**/*.html
+ patterns:
+ # The match has to start inside a tag. `[^<>]` stops it at the tag's end, so text and
+ # script bodies that merely contain `on...=` do not match. The character before `on` must
+ # be whitespace or a quote, which keeps `data-on...` and `x-on:` attributes out.
+ - pattern-regex: '(?i)<[a-z][a-z0-9-]*\b[^<>]*?[\s"'']on[a-z]+\s*='
+ # Markup quoted in a template or HTML comment never reaches the browser as a tag.
+ - pattern-not-regex: '(?s)\{%\s*comment\s*%\}.*?\{%\s*endcomment\s*%\}|<!--.*?-->|\{#.*?#\}'
+ metadata:
+ category: correctness
+ technology:
+ - django
+ - html
+ references:
+ - https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/script-src#unsafe_hashes
+
+ - id: csp-inline-script-without-nonce
+ message: |
+ This inline `<script>` has no nonce, so it never runs for a viewer whose policy is
+ enforced. The app and admin policies in `CSPMiddleware` allow an inline script only when
+ it carries the per-request nonce. The browser drops the script, and the user sees no error.
+
+ Add `nonce="{{ request.csp_nonce }}"` to the tag. The template needs `request` in its
+ context: `render()`, `render_template()`, and admin views pass it, and `render_to_string()`
+ passes it only when you give it `request=request`.
+
+ A `<script src=...>` from `'self'` needs no nonce, and a data block such as
+ `type="application/json"` never runs, so neither matches this rule.
+ severity: ERROR
+ languages: [generic]
+ paths:
+ include:
+ - /posthog/**/templates/**/*.html
+ - /products/*/backend/templates/**/*.html
+ - /ee/**/templates/**/*.html
+ - /frontend/src/**/*.html
+ patterns:
+ - pattern-regex: '(?i)<script\b(?![^>]*[\s"''](?:nonce|src)\s*=)(?![^>]*\btype\s*=\s*["'']?(?:application/(?:ld\+)?json|text/(?:template|x-template|html|plain|markdown)))[^>]*>'
+ # Markup quoted in a template or HTML comment never reaches the browser as a tag.
+ - pattern-not-regex: '(?s)\{%\s*comment\s*%\}.*?\{%\s*endcomment\s*%\}|<!--.*?-->|\{#.*?#\}'
+ metadata:
+ category: correctness
+ technology:
+ - django
+ - html
+ references:
+ - https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/script-src#unsafe_inline_script
diff --git a/.semgrep/rules/devex/csp-javascript-url-in-jsx.test.tsx b/.semgrep/rules/devex/csp-javascript-url-in-jsx.test.tsx
new file mode 100644
index 000000000000..dcf46a14afdc
--- /dev/null
+++ b/.semgrep/rules/devex/csp-javascript-url-in-jsx.test.tsx
@@ -0,0 +1,59 @@
+// @ts-nocheck
+// Test fixture for the csp-javascript-url-in-jsx rule.
+
+// ruleid: csp-javascript-url-in-jsx
+const Anchor = <a href="javascript:void(0)">Nothing</a>
+
+// ruleid: csp-javascript-url-in-jsx
+const MixedCaseInBraces = <a className="x" href={'JavaScript:go()'}>Mixed case</a>
+
+// ruleid: csp-javascript-url-in-jsx
+const TemplateLiteral = <a href={`javascript:${code}`}>Template</a>
+
+// ruleid: csp-javascript-url-in-jsx
+const Frame = <iframe src="javascript:''" sandbox="" />
+
+// ruleid: csp-javascript-url-in-jsx
+const FormAction = <form action="javascript:void(0)" />
+
+// ruleid: csp-javascript-url-in-jsx
+const SubmitterAction = <button formAction="javascript:go()">Save</button>
+
+// Link strips the scheme, which leaves a dead link, so the rule still reports it.
+// ruleid: csp-javascript-url-in-jsx
+const RouterLink = <Link to="javascript:void(0)">Link</Link>
+
+// ok: csp-javascript-url-in-jsx
+const External = <a href="https://posthog.com/docs">Docs</a>
+
+// ok: csp-javascript-url-in-jsx
+const Dynamic = <a href={url}>Dynamic</a>
+
+// ok: csp-javascript-url-in-jsx
+const Handler = <LemonButton onClick={() => window.history.back()}>Back</LemonButton>
+
+// ok: csp-javascript-url-in-jsx
+const OtherAttribute = <CodeSnippet language="javascript:">{label}</CodeSnippet>
+
+export function navigate(anchor: HTMLAnchorElement, url: string, code: string): void {
+ // ruleid: csp-javascript-url-in-jsx
+ anchor.href = 'javascript:void(0)'
+ // ruleid: csp-javascript-url-in-jsx
+ window.location = 'javascript:go()'
+ // ruleid: csp-javascript-url-in-jsx
+ location = 'javascript:go()'
+ // ruleid: csp-javascript-url-in-jsx
+ window.location.assign('javascript:go()')
+ // ruleid: csp-javascript-url-in-jsx
+ location.replace('javascript:go()')
+ // ruleid: csp-javascript-url-in-jsx
+ window.open(`javascript:${code}`, '_blank')
+ // ruleid: csp-javascript-url-in-jsx
+ open('javascript:go()')
+ // ok: csp-javascript-url-in-jsx
+ anchor.href = '/docs/javascript:intro'
+ // ok: csp-javascript-url-in-jsx
+ window.open(url, '_blank', 'noopener')
+ // ok: csp-javascript-url-in-jsx
+ const label = 'javascript: the language'
+}
diff --git a/.semgrep/rules/devex/csp-javascript-url-in-jsx.yaml b/.semgrep/rules/devex/csp-javascript-url-in-jsx.yaml
new file mode 100644
index 000000000000..c44882ea0859
--- /dev/null
+++ b/.semgrep/rules/devex/csp-javascript-url-in-jsx.yaml
@@ -0,0 +1,51 @@
+rules:
+ - id: csp-javascript-url-in-jsx
+ message: |
+ This `javascript:` URL never runs for a viewer whose app policy is enforced. The policy in
+ `CSPMiddleware` sets `script-src` to a nonce with no `'unsafe-inline'`, and a browser
+ treats a `javascript:` URL as an inline script. React 18 renders the URL and only warns in
+ development, so nothing stops it before the browser does. The link does nothing, and the
+ user sees no error.
+
+ Use an `onClick` handler on a `LemonButton`, or a real URL on a `Link`.
+ severity: ERROR
+ # First-party UI code is TypeScript. The only `.js` files under these paths are generated
+ # validators and test mocks, which render nothing.
+ languages: [typescript]
+ paths:
+ include:
+ - /frontend/src
+ - /products/*/frontend
+ exclude:
+ - '**/*.test.ts'
+ - '**/*.test.tsx'
+ - '**/*.stories.tsx'
+ patterns:
+ - pattern-either:
+ - patterns:
+ - pattern-either:
+ - pattern: <$EL ... $ATTR=$URL ... />
+ - pattern: <$EL ... $ATTR={$URL} ... />
+ - metavariable-regex:
+ metavariable: $ATTR
+ regex: ^(href|src|action|formAction|to|xlinkHref)$
+ - pattern: $OBJ.href = $URL
+ - pattern: $OBJ.location = $URL
+ - pattern: location = $URL
+ - pattern: location.assign($URL)
+ - pattern: location.replace($URL)
+ - pattern: $OBJ.location.assign($URL)
+ - pattern: $OBJ.location.replace($URL)
+ - pattern: window.open($URL, ...)
+ - pattern: open($URL, ...)
+ # Bind the whole literal and read the scheme off its source text, so a plain string and
+ # a template literal both match.
+ - metavariable-regex:
+ metavariable: $URL
+ regex: '^[''"`]\s*(?i:javascript):'
+ metadata:
+ category: correctness
+ technology:
+ - react
+ references:
+ - https://legacy.reactjs.org/blog/2019/08/08/react-v16.9.0.html#deprecating-javascript-urls
diff --git a/posthog/templates/admin/distinct_id_usage.html b/posthog/templates/admin/distinct_id_usage.html
index 08e75d0d1f43..6d3efb5b5506 100644
--- a/posthog/templates/admin/distinct_id_usage.html
+++ b/posthog/templates/admin/distinct_id_usage.html
@@ -32,7 +32,7 @@
}
.copy-feedback.visible { opacity: 1; }
</style>
- <script>
+ <script nonce="{{ request.csp_nonce }}">
document.addEventListener('click', function(e) {
var el = e.target.closest('.copyable');
if (!el) return;
diff --git a/posthog/templates/toolbar_oauth_error.html b/posthog/templates/toolbar_oauth_error.html
index 4f65750f29fc..a507bd018497 100644
--- a/posthog/templates/toolbar_oauth_error.html
+++ b/posthog/templates/toolbar_oauth_error.html
@@ -164,10 +164,15 @@
text-decoration: none;
transition: all 0.15s ease;
cursor: pointer;
+ font-family: inherit;
font-size: 0.875rem;
min-width: 200px;
}
+ .btn[hidden] {
+ display: none;
+ }
+
.btn-primary {
background: var(--ph-brand-blue);
color: white;
@@ -266,8 +271,22 @@
{% if settings_url %}
<a href="{{ settings_url }}" class="btn btn-primary">Go to project settings</a>
{% endif %}
- <a href="javascript:history.back()" class="btn btn-secondary">Go back</a>
+ <button type="button" id="go-back" class="btn btn-secondary" hidden>Go back</button>
</div>
</div>
+ <script nonce="{{ request.csp_nonce }}">
+ (function () {
+ // The app launches the toolbar in a new tab with noopener, and that tab has no
+ // previous page. history.back() does nothing there, so the button stays hidden.
+ if (window.history.length < 2) {
+ return;
+ }
+ var button = document.getElementById("go-back");
+ button.hidden = false;
+ button.addEventListener("click", function () {
+ window.history.back();
+ });
+ })();
+ </script>
</body>
</html>
diff --git a/products/experiments/backend/templates/admin/experiments/_recalculation_panel.html b/products/experiments/backend/templates/admin/experiments/_recalculation_panel.html
index fd83b71bd630..4a751b43957a 100644
--- a/products/experiments/backend/templates/admin/experiments/_recalculation_panel.html
+++ b/products/experiments/backend/templates/admin/experiments/_recalculation_panel.html
@@ -108,7 +108,7 @@
{% endif %}
{% endif %}
</fieldset>
-<script>
+<script nonce="{{ request.csp_nonce }}">
// These buttons live inside the admin change form, so the submit event bubbles up from it.
// Disabling the submitter after submit starts keeps the request but blocks a second click.
document.addEventListener("submit", function (event) {
diff --git a/products/managed_warehouse/backend/templates/admin/managed_warehouse/duckgres_server/provision_result.html b/products/managed_warehouse/backend/templates/admin/managed_warehouse/duckgres_server/provision_result.html
index e8e838704eef..877743d58638 100644
--- a/products/managed_warehouse/backend/templates/admin/managed_warehouse/duckgres_server/provision_result.html
+++ b/products/managed_warehouse/backend/templates/admin/managed_warehouse/duckgres_server/provision_result.html
@@ -38,13 +38,18 @@
{% if password %}
<p>Copy this now:</p>
<input type="text"
+ id="provisioned-password"
readonly
value="{{ password }}"
- onclick="this.select()"
style="width: 100%;
padding: 8px;
font-family: monospace;
font-size: 14px" />
+ <script nonce="{{ request.csp_nonce }}">
+ document.getElementById("provisioned-password").addEventListener("click", function (event) {
+ event.currentTarget.select();
+ });
+ </script>
{% else %}
<p>
<em>The control plane did not return a password in this response. Retrieve the credentials