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(admin): restore the array field preview CSP was dropping (#101384)

Tom Piccirelloefcd3cf81b71
diff --git a/posthog/admin/admins/data_deletion_request_admin.py b/posthog/admin/admins/data_deletion_request_admin.py
index 005d01cf9dc0..76eb3c0d5510 100644
--- a/posthog/admin/admins/data_deletion_request_admin.py
+++ b/posthog/admin/admins/data_deletion_request_admin.py
@@ -94,64 +94,12 @@ def dagster_run_url(run_id: str) -> str | None:
# Custom widget + field for ArrayField editing
# ---------------------------------------------------------------------------
-# JS template for the live preview/normalizer. All literal `{`/`}` are doubled because
-# we render via format_html(), which uses str.format() semantics. `{id}` is the only
-# substitution slot and gets the widget element id.
-_WIDGET_TEMPLATE = """{html}<div id="{id}_preview" style="margin-top:6px"></div>
-<script>
-(function() {{
- var ta = document.getElementById('{id}');
- if (!ta) return;
- var preview = document.getElementById('{id}_preview');
-
- function parse(text) {{
- text = text.trim();
- if (!text) return [];
- if (text.startsWith('[')) {{
- // Try JSON as-is, then with single→double quote swap (Python-style arrays).
- // Safe here because event/property names don't contain single quotes.
- var candidates = [text, text.replace(/'/g, '"')];
- for (var i = 0; i < candidates.length; i++) {{
- try {{
- var arr = JSON.parse(candidates[i]);
- if (Array.isArray(arr)) {{
- return arr.map(function(s){{return String(s).trim()}}).filter(Boolean);
- }}
- }} catch(e) {{}}
- }}
- }}
- return text.split('\\n').map(function(s){{return s.trim()}}).filter(Boolean);
- }}
-
- function render() {{
- var items = parse(ta.value);
- if (items.length === 0) {{
- preview.innerHTML = '<em style="color:#999">No items</em>';
- return;
- }}
- preview.innerHTML = '<strong>' + items.length + ' item(s):</strong> ' +
- items.map(function(s){{return '<code style="background:#e8e8e8;padding:2px 6px;border-radius:3px;margin:2px">' + s.replace(/</g,'&lt;') + '</code>'}}).join(' ');
- }}
-
- function normalizeIfArray() {{
- // If the current text is an array literal, rewrite it to one-per-line.
- // Only called on paste/blur to avoid clobbering live editing.
- var text = ta.value.trim();
- if (!text.startsWith('[')) return;
- var items = parse(text);
- if (items.length > 0) {{
- ta.value = items.join('\\n');
- render();
- }}
- }}
-
- ta.addEventListener('input', render);
- ta.addEventListener('blur', normalizeIfArray);
- ta.addEventListener('paste', function() {{ setTimeout(normalizeIfArray, 0); }});
- render();
-}})();
-</script>
-"""
+# The widget renders markup only. Its behaviour lives in a nonce'd block in
+# admin/posthog/datadeletionrequest/change_form.html, because a widget's render() receives no
+# request and so cannot reach {{ request.csp_nonce }}. Admin pages serve a policy whose script-src
+# carries no 'unsafe-inline', so an un-nonced inline script here is refused and the preview never
+# runs. Keeping the script in the template also emits it once rather than once per field.
+_WIDGET_TEMPLATE = '{html}<div class="array-textarea-preview" data-textarea-id="{id}" style="margin-top:6px"></div>'
class ArrayTextareaWidget(forms.Textarea):
diff --git a/posthog/admin/test_data_deletion_request_admin.py b/posthog/admin/test_data_deletion_request_admin.py
index d751c4bf2677..6044e5f3d364 100644
--- a/posthog/admin/test_data_deletion_request_admin.py
+++ b/posthog/admin/test_data_deletion_request_admin.py
@@ -1,3 +1,4 @@
+import re
from datetime import datetime, timedelta
import time_machine
@@ -11,6 +12,7 @@ from django.contrib.messages.storage.fallback import FallbackStorage
from django.test import RequestFactory, SimpleTestCase, override_settings
from django.utils import timezone
+from bs4 import BeautifulSoup
from parameterized import parameterized
from posthog.admin.admins.data_deletion_request_admin import EDITABLE_FIELDS, DataDeletionRequestAdmin, dagster_run_url
@@ -755,6 +757,48 @@ class TestDataDeletionRequestAdminChangeViewStatsAndLock(BaseTest):
self.assertTrue(ctx.get("show_save", True))
+@time_machine.travel("2025-01-15 12:00:00", tick=False)
+@override_settings(STORAGES={"staticfiles": {"BACKEND": "django.contrib.staticfiles.storage.StaticFilesStorage"}})
+class TestDataDeletionRequestAdminChangeFormScripts(BaseTest):
+ def setUp(self):
+ super().setUp()
+ self.user.is_staff = True
+ self.user.save()
+ self.client.force_login(self.user)
+
+ def test_array_previews_are_wired_by_a_script_carrying_the_page_nonce(self):
+ request = DataDeletionRequest.objects.create(
+ team_id=self.team.id,
+ request_type=RequestType.EVENT_REMOVAL,
+ events=["$pageview"],
+ start_time=datetime.now() - timedelta(days=7),
+ end_time=datetime.now(),
+ status=RequestStatus.DRAFT,
+ )
+
+ response = self.client.get(f"/admin/posthog/datadeletionrequest/{request.pk}/change/")
+
+ self.assertEqual(response.status_code, 200)
+ nonce = re.search(r"'nonce-([^']+)'", response["Content-Security-Policy"])
+ assert nonce is not None
+ soup = BeautifulSoup(response.content, "html.parser")
+ inline_scripts = soup.select("script:not([src])")
+ self.assertEqual({script.get("nonce") for script in inline_scripts}, {nonce.group(1)})
+ self.assertTrue(
+ any(
+ "array-textarea-preview" in script.get_text() and "textareaId" in script.get_text()
+ for script in inline_scripts
+ )
+ )
+ self.assertEqual(
+ {preview.get("data-textarea-id") for preview in soup.select("div.array-textarea-preview")},
+ {
+ soup.select_one(f"textarea[name={field}]").get("id")
+ for field in ("events", "properties", "person_properties")
+ },
+ )
+
+
@override_settings(STORAGES={"staticfiles": {"BACKEND": "django.contrib.staticfiles.storage.StaticFilesStorage"}})
class TestDataDeletionRequestAdminStatsViewRedirects(BaseTest):
def setUp(self):
diff --git a/posthog/templates/admin/posthog/datadeletionrequest/change_form.html b/posthog/templates/admin/posthog/datadeletionrequest/change_form.html
index 265fe0238b43..8cec7550f7b2 100644
--- a/posthog/templates/admin/posthog/datadeletionrequest/change_form.html
+++ b/posthog/templates/admin/posthog/datadeletionrequest/change_form.html
@@ -256,4 +256,86 @@
data-confirm="Verify this request against ClickHouse now?">Verify deletion</button>
</div>
{% endif %}
+ {% comment %}
+ Behaviour for ArrayTextareaWidget. It lives here rather than in the widget because a widget's
+ render() gets no request, so it cannot reach the nonce this policy requires, and because one
+ block covers every field instead of one copy per field.
+ {% endcomment %}
+ <script nonce="{{ request.csp_nonce }}">
+ (function () {
+ function parse(text) {
+ text = text.trim();
+ if (!text) {
+ return [];
+ }
+ if (text.startsWith("[")) {
+ // Python prints a list of strings with single quotes, so retry with them swapped
+ // for double quotes. Skip the swap when the text holds an escaped apostrophe (\'),
+ // because the swap turns it into an escaped double quote and changes the value.
+ // ArrayTextareaField.clean still parses that input with ast.literal_eval on submit.
+ var candidates = [text];
+ if (!text.includes("\\'")) {
+ candidates.push(text.replace(/'/g, '"'));
+ }
+ for (var i = 0; i < candidates.length; i++) {
+ try {
+ var arr = JSON.parse(candidates[i]);
+ if (Array.isArray(arr)) {
+ return arr.map(function (s) { return String(s).trim(); }).filter(Boolean);
+ }
+ } catch (e) {}
+ }
+ }
+ return text.split("\n").map(function (s) { return s.trim(); }).filter(Boolean);
+ }
+
+ document.querySelectorAll(".array-textarea-preview").forEach(function (preview) {
+ var textarea = document.getElementById(preview.dataset.textareaId);
+ if (!textarea) {
+ return;
+ }
+
+ function render() {
+ var items = parse(textarea.value);
+ preview.replaceChildren();
+ if (items.length === 0) {
+ var empty = document.createElement("em");
+ empty.style.color = "#999";
+ empty.textContent = "No items";
+ preview.appendChild(empty);
+ return;
+ }
+ var label = document.createElement("strong");
+ label.textContent = items.length + " item(s):";
+ preview.appendChild(label);
+ items.forEach(function (item) {
+ var code = document.createElement("code");
+ code.style.cssText = "background:#e8e8e8;padding:2px 6px;border-radius:3px;margin:2px";
+ // textContent, so a value containing markup is shown rather than parsed.
+ code.textContent = item;
+ preview.appendChild(document.createTextNode(" "));
+ preview.appendChild(code);
+ });
+ }
+
+ function normalizeIfArray() {
+ // Rewrite an array literal to one per line. Only on paste and blur, so live
+ // editing is not clobbered.
+ if (!textarea.value.trim().startsWith("[")) {
+ return;
+ }
+ var items = parse(textarea.value);
+ if (items.length > 0) {
+ textarea.value = items.join("\n");
+ render();
+ }
+ }
+
+ textarea.addEventListener("input", render);
+ textarea.addEventListener("blur", normalizeIfArray);
+ textarea.addEventListener("paste", function () { window.setTimeout(normalizeIfArray, 0); });
+ render();
+ });
+ })();
+ </script>
{% endblock %}