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 confirmation dialogs CSP was dropping (#101381)

Tom Piccirello00602c9ea56c
diff --git a/posthog/admin/admins/team_admin.py b/posthog/admin/admins/team_admin.py
index 7414131cb65f..97e2ab779a5c 100644
--- a/posthog/admin/admins/team_admin.py
+++ b/posthog/admin/admins/team_admin.py
@@ -22,7 +22,7 @@ from django.template.loader import render_to_string
from django.urls import NoReverseMatch, path, reverse
from django.utils import timezone
from django.utils.dateparse import parse_datetime
-from django.utils.html import escapejs, format_html, format_html_join
+from django.utils.html import format_html, format_html_join
from django.utils.safestring import mark_safe
from structlog import get_logger
@@ -625,7 +625,7 @@ class TeamAdmin(admin.ModelAdmin):
{
"view_url": reverse("admin:posthog_team_view_cache", args=[team.pk]),
"rebuild_url": reverse("admin:posthog_team_rebuild_cache", args=[team.pk]),
- "team_name_escaped": escapejs(team.name),
+ "team_name": team.name,
"cache_key": RemoteConfig.get_hypercache().get_cache_key(team.api_token),
},
)
@@ -934,10 +934,9 @@ class TeamAdmin(admin.ModelAdmin):
render_to_string(
"admin/posthog/team/email_sending_suspension_actions.html",
{
- "team": team,
"suspend_url": reverse("admin:posthog_team_suspend_email_sending", args=[team.pk]),
"unsuspend_url": reverse("admin:posthog_team_unsuspend_email_sending", args=[team.pk]),
- "team_name_escaped": escapejs(team.name),
+ "team_name": team.name,
"is_suspended": is_suspended,
},
)
@@ -999,7 +998,6 @@ class TeamAdmin(admin.ModelAdmin):
"set_tier_url": reverse("admin:posthog_team_set_email_sending_tier", args=[team.pk]),
"recompute_url": reverse("admin:posthog_team_recompute_email_sending_tier", args=[team.pk]),
},
- request=getattr(self, "_current_request", None),
)
)
@@ -1229,11 +1227,10 @@ class TeamAdmin(admin.ModelAdmin):
render_to_string(
"admin/posthog/team/ai_gateway_actions.html",
{
- "team": team,
"enable_url": reverse("admin:posthog_team_enable_ai_gateway", args=[team.pk]),
"revoke_url": reverse("admin:posthog_team_revoke_ai_gateway", args=[team.pk]),
"clear_revoke_url": reverse("admin:posthog_team_clear_ai_gateway_revoke", args=[team.pk]),
- "team_name_escaped": escapejs(team.name),
+ "team_name": team.name,
"is_enabled": team.llm_gateway_enabled_at is not None,
"is_revoked": team.llm_gateway_revoked_at is not None,
},
diff --git a/posthog/admin/test_team_admin.py b/posthog/admin/test_team_admin.py
index 3ed3761b7881..c805e749322a 100644
--- a/posthog/admin/test_team_admin.py
+++ b/posthog/admin/test_team_admin.py
@@ -701,21 +701,15 @@ class TestTeamAdminEmailSendingSuspension(BaseTest):
assert "Save tier" in html
assert "Recompute now" in html
- def test_tier_actions_use_a_nonce_script_not_inline_handlers(self) -> None:
+ def test_tier_actions_mark_the_confirm_instead_of_writing_an_inline_handler(self) -> None:
# Admin pages serve a CSP with no unsafe-inline/unsafe-hashes on script-src, so inline
- # onclick/onsubmit attributes are dropped. The recompute confirm must run from a nonce'd
- # script, which needs the request in the render context.
- request = self.factory.get(f"/admin/posthog/team/{self.team.pk}/change/")
- request.user = self.user
- request.csp_nonce = "test-nonce-value" # type: ignore[attr-defined]
- _attach_messages(request)
- self.admin._current_request = request
-
+ # onclick/onsubmit attributes are dropped. The recompute confirm must ride a data-confirm
+ # marker, which admin/base_site.html reads from its delegated listener.
html = self.admin.email_sending_tier_actions(self.team)
assert "onclick=" not in html
assert "onsubmit=" not in html
- assert 'nonce="test-nonce-value"' in html
+ assert 'data-confirm="Recompute' in html
def test_recompute_message_names_the_hold_reason(self) -> None:
# A held recompute used to report a canned guess ("pinned or does not meet the promotion
diff --git a/posthog/templates/admin/base_site.html b/posthog/templates/admin/base_site.html
index 43a0feb99014..96ab84d414cd 100644
--- a/posthog/templates/admin/base_site.html
+++ b/posthog/templates/admin/base_site.html
@@ -1,6 +1,52 @@
{% extends "admin/base_site.html" %}
{% block extrahead %}
<link rel="shortcut icon" href="/static/icons/favicon.ico?v=2023-07-07">
+ {% comment %}
+ Admin pages serve a CSP whose script-src carries no 'unsafe-inline' and no 'unsafe-hashes', so an
+ inline onclick or onsubmit attribute is dropped and the confirmation it holds never runs. Mark the
+ control with data-confirm, or the form with class="js-disable-on-submit", instead of writing a
+ handler on it. Both listeners are delegated from the document, so a control the admin injects into
+ a change form after load, such as a readonly-field widget rendered through render_to_string(), is
+ covered without a script, and therefore without a nonce, of its own.
+ {% endcomment %}
+ <script nonce="{{ request.csp_nonce }}">
+ document.addEventListener("click", function (event) {
+ var trigger = event.target.closest("[data-confirm]");
+ if (trigger && !window.confirm(trigger.dataset.confirm)) {
+ event.preventDefault();
+ event.stopPropagation();
+ }
+ }, true);
+
+ document.addEventListener("submit", function (event) {
+ if (!event.target.matches("form.js-disable-on-submit")) {
+ return;
+ }
+ var form = event.target;
+ // The form data set is built after the submit event finishes dispatching, so a control
+ // disabled inside this handler is left out of the POST body. Defer past that.
+ window.setTimeout(function () {
+ form.querySelectorAll("input[type=submit], button[type=submit]").forEach(function (control) {
+ control.disabled = true;
+ control.dataset.disabledOnSubmit = "1";
+ });
+ }, 0);
+ });
+
+ // Back/forward can restore this page from the bfcache with these controls still disabled,
+ // which leaves the operator on a page they cannot submit until they reload. A restore means
+ // the POST is done with. Only a control the handler above marked is released, so a control
+ // the template disabled on purpose stays disabled.
+ window.addEventListener("pageshow", function (event) {
+ if (!event.persisted) {
+ return;
+ }
+ document.querySelectorAll("[data-disabled-on-submit]").forEach(function (control) {
+ control.disabled = false;
+ control.removeAttribute("data-disabled-on-submit");
+ });
+ });
+ </script>
{% endblock %}
{% block extrastyle %}
{{ block.super }}
diff --git a/posthog/templates/admin/data_warehouse/externaldataschema/change_form.html b/posthog/templates/admin/data_warehouse/externaldataschema/change_form.html
index 39ffc0ab4a25..b36dbc11ea61 100644
--- a/posthog/templates/admin/data_warehouse/externaldataschema/change_form.html
+++ b/posthog/templates/admin/data_warehouse/externaldataschema/change_form.html
@@ -280,7 +280,7 @@
<button type="submit"
form="repartition-action-form"
class="default"
- onclick="return confirm('Repartition + reset resync (non-billable) for this schema?');">
+ data-confirm="Repartition + reset resync (non-billable) for this schema?">
Repartition &amp; resync
</button>
</div>
@@ -363,15 +363,11 @@
<button type="submit"
form="pause-schedule-action-form"
class="default"
- onclick="return confirm('Pause the Temporal schedule for this schema?');">
- Pause schedule
- </button>
+ data-confirm="Pause the Temporal schedule for this schema?">Pause schedule</button>
<button type="submit"
form="unpause-schedule-action-form"
class="default"
- onclick="return confirm('Unpause the Temporal schedule for this schema?');">
- Unpause schedule
- </button>
+ data-confirm="Unpause the Temporal schedule for this schema?">Unpause schedule</button>
</div>
<p class="help">
If the schedule is missing entirely (pause/unpause/sync fail with "workflow not found",
@@ -383,7 +379,7 @@
<button type="submit"
form="recreate-schedule-action-form"
class="default"
- onclick="return confirm('Recreate the Temporal schedule for this schema? No sync run is triggered.');">
+ data-confirm="Recreate the Temporal schedule for this schema? No sync run is triggered.">
Recreate schedule
</button>
</div>
@@ -408,7 +404,7 @@
<button type="submit"
form="trigger-sync-action-form"
class="default"
- onclick="return confirm('Trigger a sync for this schema?');">Trigger sync</button>
+ data-confirm="Trigger a sync for this schema?">Trigger sync</button>
</div>
</div>
</fieldset>
diff --git a/posthog/templates/admin/posthog/datadeletionrequest/change_form.html b/posthog/templates/admin/posthog/datadeletionrequest/change_form.html
index 809f8fc31ece..265fe0238b43 100644
--- a/posthog/templates/admin/posthog/datadeletionrequest/change_form.html
+++ b/posthog/templates/admin/posthog/datadeletionrequest/change_form.html
@@ -225,7 +225,7 @@
style="padding: 10px 15px;
background: #d9534f;
color: white"
- onclick="return confirm('Retry this failed request? It will be re-queued for execution.');">Retry execution</button>
+ data-confirm="Retry this failed request? It will be re-queued for execution.">Retry execution</button>
</div>
{% endif %}
{% if can_verify %}
@@ -253,7 +253,7 @@
style="padding: 10px 15px;
background: #417690;
color: white"
- onclick="return confirm('Verify this request against ClickHouse now?');">Verify deletion</button>
+ data-confirm="Verify this request against ClickHouse now?">Verify deletion</button>
</div>
{% endif %}
{% endblock %}
diff --git a/posthog/templates/admin/posthog/organization/send_ai_observability_usage_report.html b/posthog/templates/admin/posthog/organization/send_ai_observability_usage_report.html
index 6c8edaf4269c..2394fb4d0dce 100644
--- a/posthog/templates/admin/posthog/organization/send_ai_observability_usage_report.html
+++ b/posthog/templates/admin/posthog/organization/send_ai_observability_usage_report.html
@@ -2,8 +2,7 @@
{% load i18n admin_urls %}
{% block content %}
<div id="content-main">
- <form method="post"
- onsubmit="this.querySelector('input[name=_send_report]').disabled = true">
+ <form method="post" class="js-disable-on-submit">
<p>
The date is the day the report would have run; it reports AI observability usage for the <b>previous</b> day.
<br />
diff --git a/posthog/templates/admin/posthog/team/add_ai_gateway_credit_form.html b/posthog/templates/admin/posthog/team/add_ai_gateway_credit_form.html
index 160dd984405f..4536d6eb1b78 100644
--- a/posthog/templates/admin/posthog/team/add_ai_gateway_credit_form.html
+++ b/posthog/templates/admin/posthog/team/add_ai_gateway_credit_form.html
@@ -2,8 +2,7 @@
{% load i18n %}
{% block content %}
<p>Add prepaid credit to <strong>{{ team.name }}</strong>'s AI gateway wallet. This appends a top-up entry to the gateway ledger and increases the team's spendable balance immediately.</p>
- <form method="post"
- onsubmit="this.querySelector('input[type=submit]').disabled = true;">
+ <form method="post" class="js-disable-on-submit">
{% csrf_token %}
<input type="hidden" name="form_nonce" value="{{ form_nonce }}" />
<div style="margin: 20px 0;">
diff --git a/posthog/templates/admin/posthog/team/ai_gateway_actions.html b/posthog/templates/admin/posthog/team/ai_gateway_actions.html
index 064116de0272..bb272931baf3 100644
--- a/posthog/templates/admin/posthog/team/ai_gateway_actions.html
+++ b/posthog/templates/admin/posthog/team/ai_gateway_actions.html
@@ -5,7 +5,7 @@
formmethod="post"
formaction="{{ enable_url }}"
formnovalidate
- {% if is_enabled %}disabled title="Already enabled"{% else %}onclick="return confirm('Enable AI gateway access for {{ team_name_escaped }}?');"{% endif %}
+ {% if is_enabled %}disabled title="Already enabled"{% else %}data-confirm="Enable AI gateway access for {{ team_name }}?"{% endif %}
style="margin-right: 8px">Enable access</button>
<button type="submit"
name="_revoke_ai_gateway"
@@ -13,7 +13,7 @@
formmethod="post"
formaction="{{ revoke_url }}"
formnovalidate
- {% if is_revoked %}disabled title="Already revoked"{% else %}onclick="return confirm('Revoke AI gateway access for {{ team_name_escaped }}?');"{% endif %}
+ {% if is_revoked %}disabled title="Already revoked"{% else %}data-confirm="Revoke AI gateway access for {{ team_name }}?"{% endif %}
style="margin-right: 8px">Revoke access</button>
<button type="submit"
name="_clear_ai_gateway_revoke"
@@ -21,7 +21,7 @@
formmethod="post"
formaction="{{ clear_revoke_url }}"
formnovalidate
- {% if not is_revoked %}disabled title="Not revoked"{% else %}onclick="return confirm('Clear AI gateway revoke for {{ team_name_escaped }}?');"{% endif %}>
+ {% if not is_revoked %}disabled title="Not revoked"{% else %}data-confirm="Clear AI gateway revoke for {{ team_name }}?"{% endif %}>
Clear revoke
</button>
<p style="margin-top: 8px; color: #666; font-size: 12px;">
diff --git a/posthog/templates/admin/posthog/team/delete_recordings.html b/posthog/templates/admin/posthog/team/delete_recordings.html
index e4289abd4e67..8592883e821f 100644
--- a/posthog/templates/admin/posthog/team/delete_recordings.html
+++ b/posthog/templates/admin/posthog/team/delete_recordings.html
@@ -546,14 +546,15 @@
// Each POST mints a fresh Temporal workflow id server-side (team_admin.py), so a double submit
// starts a second, redundant deletion workflow. Lock the form once a submit is accepted.
- // Sibling admin templates do this with an inline `onsubmit=` attribute, which cannot work here:
- // the admin CSP has no 'unsafe-inline' for script-src, so attribute handlers are blocked.
+ // The shared `js-disable-on-submit` marker in admin/base_site.html does not fit: `inFlight` is
+ // page-global across the four forms here, and it must short-circuit before `shouldSubmit()`
+ // prompts, so that a second submit raises no dialog at all.
var inFlight = false;
function lock(form) {
- // Safe to do synchronously: the submit event has already committed the navigation, and these
- // controls have no `name`, so removing them cannot drop a field from the POST body. Deferring
- // it to a timeout does NOT work, because the pending navigation means the callback never runs.
+ // Safe to do synchronously: these controls have no `name`, so disabling them cannot drop a
+ // field from the POST body. The shared listener defers the same work because it cannot know
+ // that about an arbitrary form.
var controls = form.querySelectorAll('input[type="submit"], button[type="submit"]');
Array.prototype.forEach.call(controls, function(c) { c.disabled = true; });
}
diff --git a/posthog/templates/admin/posthog/team/email_sending_suspension_actions.html b/posthog/templates/admin/posthog/team/email_sending_suspension_actions.html
index 68275d4043b1..30a3f0301946 100644
--- a/posthog/templates/admin/posthog/team/email_sending_suspension_actions.html
+++ b/posthog/templates/admin/posthog/team/email_sending_suspension_actions.html
@@ -6,7 +6,7 @@
formmethod="post"
formaction="{{ unsuspend_url }}"
formnovalidate
- onclick="return confirm('Re-enable workflow email sending for {{ team_name_escaped }}? The team will be notified.');">
+ data-confirm="Re-enable workflow email sending for {{ team_name }}? The team will be notified.">
Re-enable email sending
</button>
{% else %}
diff --git a/posthog/templates/admin/posthog/team/email_sending_tier_actions.html b/posthog/templates/admin/posthog/team/email_sending_tier_actions.html
index 2268c9f8b41a..a288ee6df96e 100644
--- a/posthog/templates/admin/posthog/team/email_sending_tier_actions.html
+++ b/posthog/templates/admin/posthog/team/email_sending_tier_actions.html
@@ -1,44 +1,46 @@
{% comment %}
Rendered as a readonly field inside the admin's team change form, so the controls sit in that
outer form (no <form> of their own, which the browser would drop) and submit through formaction.
-Admin pages serve a CSP with no 'unsafe-inline'/'unsafe-hashes' on script-src, which silently
-drops inline onclick/onsubmit attributes, so the recompute confirmation lives in the nonce'd
-<script> block below. Include with request=request so {{ request.csp_nonce }} resolves.
{% endcomment %}
<div class="email-sending-tier-widget" style="margin: 10px 0;">
-<div style="display: flex; align-items: center; gap: 10px; flex-wrap: wrap;">
-<label for="email_sending_tier">Tier</label>
-<select id="email_sending_tier" name="tier">
-{% for option in tiers %}
-<option value="{{ option.tier }}" {% if option.selected %}selected{% endif %}>
-{{ option.tier }} — {{ option.per_hour }}/hour, {{ option.per_day }}/day
-</option>
-{% endfor %}
-</select>
-<label for="email_sending_tier_pinned">
-<input type="checkbox" id="email_sending_tier_pinned" name="pinned" {% if pinned %}checked{% endif %} />
-Pin (stops automatic promotion and demotion)
-</label>
-<button type="submit" class="default" formmethod="post" formaction="{{ set_tier_url }}" formnovalidate>Save tier</button>
+ <div style="display: flex;
+ align-items: center;
+ gap: 10px;
+ flex-wrap: wrap">
+ <label for="email_sending_tier">Tier</label>
+ <select id="email_sending_tier" name="tier">
+ {% for option in tiers %}
+ <option value="{{ option.tier }}" {% if option.selected %}selected{% endif %}>
+ {{ option.tier }} — {{ option.per_hour }}/hour, {{ option.per_day }}/day
+ </option>
+ {% endfor %}
+ </select>
+ <label for="email_sending_tier_pinned">
+ <input type="checkbox"
+ id="email_sending_tier_pinned"
+ name="pinned"
+ {% if pinned %}checked{% endif %} />
+ Pin (stops automatic promotion and demotion)
+ </label>
+ <button type="submit"
+ class="default"
+ formmethod="post"
+ formaction="{{ set_tier_url }}"
+ formnovalidate>Save tier</button>
+ </div>
+ <div style="margin-top: 8px;">
+ <button type="submit"
+ class="button"
+ formmethod="post"
+ formaction="{{ recompute_url }}"
+ formnovalidate
+ data-confirm="Recompute the email sending tier for this team from its recent sending history?">
+ Recompute now from sending history
+ </button>
+ </div>
+ <p style="margin-top: 8px; color: #666; font-size: 12px;">
+ Saving a tier writes <code>email_sending_tier</code> on the team's workflows config and stamps
+ <code>email_sending_tier_updated_at</code>, which restarts the clock the promotion bar measures.
+ Recomputing applies the same rules the daily sweep uses and moves the team at most one tier.
+ </p>
</div>
-<div style="margin-top: 8px;">
-<button type="submit" class="button recompute-tier-button" formmethod="post" formaction="{{ recompute_url }}" formnovalidate>
-Recompute now from sending history
-</button>
-</div>
-<p style="margin-top: 8px; color: #666; font-size: 12px;">
-Saving a tier writes <code>email_sending_tier</code> on the team's workflows config and stamps
-<code>email_sending_tier_updated_at</code>, which restarts the clock the promotion bar measures.
-Recomputing applies the same rules the daily sweep uses and moves the team at most one tier.
-</p>
-</div>
-<script nonce="{{ request.csp_nonce }}">
-(function () {
- var widget = document.currentScript.previousElementSibling;
- widget.querySelector(".recompute-tier-button").addEventListener("click", function (event) {
- if (!confirm("Recompute the email sending tier for this team from its recent sending history?")) {
- event.preventDefault();
- }
- });
-})();
-</script>
diff --git a/posthog/templates/admin/posthog/team/group_type_mapping_edit.html b/posthog/templates/admin/posthog/team/group_type_mapping_edit.html
index 9950a2884616..592f2ab9e574 100644
--- a/posthog/templates/admin/posthog/team/group_type_mapping_edit.html
+++ b/posthog/templates/admin/posthog/team/group_type_mapping_edit.html
@@ -12,8 +12,7 @@
<td style="padding: 4px 0;"><code>{{ mapping.group_type }}</code></td>
</tr>
</table>
- <form method="post"
- onsubmit="this.querySelector('input[type=submit]').disabled = true;">
+ <form method="post" class="js-disable-on-submit">
{% csrf_token %}
<div style="margin: 20px 0;">
<label for="name_singular"
diff --git a/posthog/templates/admin/posthog/team/remote_config_cache_actions.html b/posthog/templates/admin/posthog/team/remote_config_cache_actions.html
index 181807d1db11..9c75054ce70c 100644
--- a/posthog/templates/admin/posthog/team/remote_config_cache_actions.html
+++ b/posthog/templates/admin/posthog/team/remote_config_cache_actions.html
@@ -9,7 +9,7 @@
formmethod="post"
formaction="{{ rebuild_url }}"
formnovalidate
- onclick="return confirm('Rebuild cache for team {{ team_name_escaped }}?');">Rebuild cache</button>
+ data-confirm="Rebuild cache for team {{ team_name }}?">Rebuild cache</button>
<p style="margin-top: 8px; color: #666; font-size: 12px;">
Cache key: <code>{{ cache_key }}</code>
</p>
diff --git a/posthog/templates/admin/posthog/team/suspend_email_sending_form.html b/posthog/templates/admin/posthog/team/suspend_email_sending_form.html
index 4f70f602326d..48a6f682f4ab 100644
--- a/posthog/templates/admin/posthog/team/suspend_email_sending_form.html
+++ b/posthog/templates/admin/posthog/team/suspend_email_sending_form.html
@@ -2,8 +2,7 @@
{% load i18n %}
{% block content %}
<p>Suspend ALL workflow email sending for <strong>{{ team.name }}</strong>. The CDP email worker blocks every send for this team within a few minutes, and the team is notified by email and in-app. The reason below is shown to the customer.</p>
- <form method="post"
- onsubmit="this.querySelector('input[type=submit]').disabled = true;">
+ <form method="post" class="js-disable-on-submit">
{% csrf_token %}
<div style="margin: 20px 0;">
<label for="reason"