Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

security: enable a nonce-based CSP and a restrictive Permissions-Policy (#3246)

GFRfefce9b496c7
diff --git a/.env.example b/.env.example
index eb4dc7ab9b..6606a66e44 100644
--- a/.env.example
+++ b/.env.example
@@ -262,6 +262,10 @@ BRAND_NAME=
POSTHOG_KEY=
POSTHOG_HOST=
+# Content Security Policy: true only reports violations in the browser console
+# instead of blocking them (see docs/hosting/content-security-policy.md)
+# CSP_REPORT_ONLY=false
+
# Disable enforcing SSL connections
# DISABLE_SSL=true
diff --git a/app/components/provider_logo.html.erb b/app/components/provider_logo.html.erb
index 02efd980a7..6177133012 100644
--- a/app/components/provider_logo.html.erb
+++ b/app/components/provider_logo.html.erb
@@ -10,6 +10,6 @@
) %>
<% end %>
<% if (url = brand_url) %>
- <%= helpers.image_tag url, class: "absolute inset-0 w-full h-full bg-container", alt: "", loading: "lazy", onerror: ProviderLogo::REMOVE_ON_ERROR %>
+ <%= helpers.image_tag url, class: "absolute inset-0 w-full h-full bg-container", alt: "", loading: "lazy", data: ProviderLogo::REMOVE_ON_ERROR %>
<% end %>
<% end %>
diff --git a/app/components/provider_logo.rb b/app/components/provider_logo.rb
index da2bed6352..ebc5994ba2 100644
--- a/app/components/provider_logo.rb
+++ b/app/components/provider_logo.rb
@@ -8,7 +8,8 @@
# when it doesn't know the brand, and a failed image removes itself to reveal
# the fallback.
class ProviderLogo < ApplicationComponent
- REMOVE_ON_ERROR = "this.remove()".freeze
+ # An inline onerror handler would be blocked by the Content-Security-Policy.
+ REMOVE_ON_ERROR = { controller: "image-fallback", action: "error->image-fallback#remove" }.freeze
def initialize(provider_key:, class_name: "w-8 h-8 rounded-full")
@provider_key = provider_key
diff --git a/app/helpers/accounts_helper.rb b/app/helpers/accounts_helper.rb
index 80d224878c..8ec8a90140 100644
--- a/app/helpers/accounts_helper.rb
+++ b/app/helpers/accounts_helper.rb
@@ -97,7 +97,7 @@ module AccountsHelper
.pick(Arel.sql("count(*)"), Arel.sql("max(account_providers.updated_at)"))
[
- family.build_cache_key("account_sidebar_tabs_v10", invalidate_on_data_updates: true),
+ family.build_cache_key("account_sidebar_tabs_v12", invalidate_on_data_updates: true),
Current.user&.id,
shares_version,
providers_version,
diff --git a/app/javascript/controllers/history_back_controller.js b/app/javascript/controllers/history_back_controller.js
new file mode 100644
index 0000000000..16afbce79c
--- /dev/null
+++ b/app/javascript/controllers/history_back_controller.js
@@ -0,0 +1,11 @@
+import { Controller } from "@hotwired/stimulus";
+
+// Navigates back in browser history. A strict script-src CSP blocks
+// `javascript:` URLs (they're treated as inline script, same as
+// onclick="..."), so this replaces any `href="javascript:history.back()"`.
+export default class extends Controller {
+ back(event) {
+ event.preventDefault();
+ window.history.back();
+ }
+}
diff --git a/app/javascript/controllers/image_fallback_controller.js b/app/javascript/controllers/image_fallback_controller.js
new file mode 100644
index 0000000000..11dfa63598
--- /dev/null
+++ b/app/javascript/controllers/image_fallback_controller.js
@@ -0,0 +1,47 @@
+import { Controller } from "@hotwired/stimulus";
+
+// Removes an <img> the browser cannot load, revealing the fallback rendered
+// underneath it. This replaces an inline onerror handler, which the
+// Content-Security-Policy blocks.
+export default class extends Controller {
+ static values = { retry: Boolean, releasePermanent: Boolean };
+
+ connect() {
+ // The image may have failed before Stimulus connected, in which case its
+ // error event is already gone. decode() rejects for a broken image and
+ // resolves for one that loaded (including SVGs without a natural size).
+ if (this.element.complete) {
+ this.element.decode().catch(() => this.remove());
+ }
+ }
+
+ remove() {
+ if (this.retryValue && this.#retryOnce()) return;
+
+ // A logo in a wrapper Turbo carries across visits must not be carried as
+ // its initials, so the wrapper drops its permanence and the next page
+ // tries the image again.
+ if (this.releasePermanentValue) {
+ this.element
+ .closest("[data-turbo-permanent]")
+ ?.removeAttribute("data-turbo-permanent");
+ }
+ this.element.remove();
+ }
+
+ // iOS Safari can fail an image it only revalidated (its cached redirect,
+ // then 304 Not Modified, with the cached copy already dropped). A fresh URL
+ // makes it fetch a same-origin image again rather than give up on it.
+ #retryOnce() {
+ const image = this.element;
+ if (image.dataset.retried) return false;
+
+ const url = new URL(image.src);
+ if (url.origin !== window.location.origin) return false;
+
+ image.dataset.retried = "1";
+ url.searchParams.set("retry", Date.now());
+ image.src = url.toString();
+ return true;
+ }
+}
diff --git a/app/javascript/controllers/page_reload_controller.js b/app/javascript/controllers/page_reload_controller.js
new file mode 100644
index 0000000000..f9946221c2
--- /dev/null
+++ b/app/javascript/controllers/page_reload_controller.js
@@ -0,0 +1,11 @@
+import { Controller } from "@hotwired/stimulus";
+
+// Full page reload (not a Turbo morph refresh) for the rare cases where the
+// page needs a genuinely fresh load — e.g. after fixing an infra
+// misconfiguration (Redis) that may also be breaking the Turbo/Action Cable
+// connection itself, where a client-side morph can't be trusted to work.
+export default class extends Controller {
+ reload() {
+ window.location.reload();
+ }
+}
diff --git a/app/javascript/controllers/stop_propagation_controller.js b/app/javascript/controllers/stop_propagation_controller.js
new file mode 100644
index 0000000000..a9a1ddaae6
--- /dev/null
+++ b/app/javascript/controllers/stop_propagation_controller.js
@@ -0,0 +1,11 @@
+import { Controller } from "@hotwired/stimulus";
+
+// Generic click-guard for elements nested inside a larger clickable/label
+// area (e.g. a date input inside an account row that toggles selection on
+// click). A strict script-src CSP blocks inline onclick="..." handlers, so
+// this replaces every such handler in the app.
+export default class extends Controller {
+ stop(event) {
+ event.stopPropagation();
+ }
+}
diff --git a/app/javascript/controllers/submit_form_controller.js b/app/javascript/controllers/submit_form_controller.js
new file mode 100644
index 0000000000..fe57fcd01b
--- /dev/null
+++ b/app/javascript/controllers/submit_form_controller.js
@@ -0,0 +1,16 @@
+import { Controller } from "@hotwired/stimulus";
+
+// Submits an arbitrary <form> looked up by DOM id on change/click. Exists
+// for elements associated with a form via the HTML form="..." attribute
+// instead of DOM nesting (e.g. a popover panel rendered outside the <form>
+// it logically belongs to), where auto-submit-form's target-scoping
+// (app/javascript/controllers/auto_submit_form_controller.js) can't reach
+// them. Prefer auto-submit-form when the element is actually nested inside
+// the form it submits.
+export default class extends Controller {
+ static values = { formId: String };
+
+ submit() {
+ document.getElementById(this.formIdValue)?.requestSubmit();
+ }
+}
diff --git a/app/views/accounts/_account_sidebar_tabs.html.erb b/app/views/accounts/_account_sidebar_tabs.html.erb
index 02addb92f4..ceae54e70f 100644
--- a/app/views/accounts/_account_sidebar_tabs.html.erb
+++ b/app/views/accounts/_account_sidebar_tabs.html.erb
@@ -4,7 +4,7 @@
ERB dependency tracker mis-parses as a bogus "Ds/D" template dependency
and then logs "Couldn't find template for digesting: Ds/D" on every cache
miss. The cache key is already manually versioned via
- account_sidebar_tabs_cache_key ("account_sidebar_tabs_v10",
+ account_sidebar_tabs_cache_key ("account_sidebar_tabs_v12",
invalidate_on_data_updates: true), so we opt out of automatic template
digesting. Bump that version suffix when changing this template or its
sidebar dependencies. %>
@@ -128,6 +128,9 @@
<% end %>
<% end %>
<% end %>
+<% end %>
+<%# Outside the cache block: the nonce is per session, so a cached script
+ would carry another session's nonce and the CSP would block it. %>
<script nonce="<%= content_security_policy_nonce %>">
// Expand/Collapse all for the account sidebar. Event-delegated on document
// so it works for both the desktop and mobile sidebar instances and survives
@@ -192,4 +195,3 @@
});
})();
</script>
-<% end %>
diff --git a/app/views/accounts/_logo.html.erb b/app/views/accounts/_logo.html.erb
index 4fed309861..7404287777 100644
--- a/app/views/accounts/_logo.html.erb
+++ b/app/views/accounts/_logo.html.erb
@@ -15,16 +15,10 @@
rounded: true
} %>
-<%# A sidebar logo sits in a wrapper Turbo carries across visits; a failed
- image must not be carried as its initials, so it drops the permanence
- and the next page tries the image again. %>
-<%# Before that, a same-origin image retries once at a fresh URL: iOS Safari
- can fail an image it only revalidated (its cached redirect, then 304 Not
- Modified, with the cached copy already dropped), and a new URL makes it
- fetch the image again rather than give up on a logo that is there.
- window.URL: in an inline handler a bare URL is document.URL, a string. %>
-<% retry_once = "if (!this.dataset.retried && new window.URL(this.src).origin === location.origin) { this.dataset.retried = '1'; const url = new window.URL(this.src); url.searchParams.set('retry', Date.now()); this.src = url; return; }" %>
-<% on_error = "#{retry_once} this.closest('[data-turbo-permanent]')?.removeAttribute('data-turbo-permanent'); #{ProviderLogo::REMOVE_ON_ERROR}" %>
+<%# A sidebar logo sits in a wrapper Turbo carries across visits. A failed
+ same-origin image is fetched once more at a fresh URL, then drops that
+ permanence before it removes itself (see image_fallback_controller.js). %>
+<% fallback = ProviderLogo::REMOVE_ON_ERROR.merge(image_fallback_retry_value: true, image_fallback_release_permanent_value: true) %>
<div class="relative shrink-0">
<% if url.present? %>
<%# The ProviderLogo recipe: the initials sit under the image, and a logo the
@@ -36,7 +30,7 @@
class: "absolute inset-0 w-full h-full rounded-full object-contain bg-container",
alt: "",
loading: "lazy",
- onerror: on_error %>
+ data: fallback %>
<% end %>
<% else %>
<%= render DS::FilledIcon.new(**initials) %>
diff --git a/app/views/doorkeeper/applications/_delete_form.html.erb b/app/views/doorkeeper/applications/_delete_form.html.erb
index bf7a0d0dfb..67901c9a86 100644
--- a/app/views/doorkeeper/applications/_delete_form.html.erb
+++ b/app/views/doorkeeper/applications/_delete_form.html.erb
@@ -1,6 +1,4 @@
<%- submit_btn_css ||= "btn btn-link" %>
-<%= form_tag oauth_application_path(application), method: :delete do %>
- <%= submit_tag t("doorkeeper.applications.buttons.destroy"),
- onclick: "return confirm('#{ t('doorkeeper.applications.confirmations.destroy') }')",
- class: submit_btn_css %>
+<%= form_tag oauth_application_path(application), method: :delete, data: { turbo_confirm: t("doorkeeper.applications.confirmations.destroy") } do %>
+ <%= submit_tag t("doorkeeper.applications.buttons.destroy"), class: submit_btn_css %>
<% end %>
diff --git a/app/views/doorkeeper/authorizations/error.html.erb b/app/views/doorkeeper/authorizations/error.html.erb
index 0334300308..e5a2c775aa 100644
--- a/app/views/doorkeeper/authorizations/error.html.erb
+++ b/app/views/doorkeeper/authorizations/error.html.erb
@@ -13,10 +13,10 @@
</div>
<div class="text-center">
- <%= render DS::Link.new(
+ <%= render DS::Button.new(
text: t("doorkeeper.authorizations.error.go_back"),
- href: "javascript:history.back()",
- variant: :secondary
+ variant: :secondary,
+ data: { controller: "history-back", action: "click->history-back#back" }
) %>
</div>
</div>
diff --git a/app/views/doorkeeper/authorizations/form_post.html.erb b/app/views/doorkeeper/authorizations/form_post.html.erb
index 3caec37e05..cc2085d278 100644
--- a/app/views/doorkeeper/authorizations/form_post.html.erb
+++ b/app/views/doorkeeper/authorizations/form_post.html.erb
@@ -15,7 +15,7 @@
<% end %>
<% end %>
-<script>
+<script nonce="<%= content_security_policy_nonce %>">
window.onload = function () {
document.forms['redirect_form'].submit();
};
diff --git a/app/views/doorkeeper/authorized_applications/_delete_form.html.erb b/app/views/doorkeeper/authorized_applications/_delete_form.html.erb
index 7668b39713..8ef74b6d83 100644
--- a/app/views/doorkeeper/authorized_applications/_delete_form.html.erb
+++ b/app/views/doorkeeper/authorized_applications/_delete_form.html.erb
@@ -1,4 +1,4 @@
<%- submit_btn_css ||= "btn btn-link" %>
-<%= form_tag oauth_authorized_application_path(application), method: :delete do %>
- <%= submit_tag t("doorkeeper.authorized_applications.buttons.revoke"), onclick: "return confirm('#{ t('doorkeeper.authorized_applications.confirmations.revoke') }')", class: submit_btn_css %>
+<%= form_tag oauth_authorized_application_path(application), method: :delete, data: { turbo_confirm: t("doorkeeper.authorized_applications.confirmations.revoke") } do %>
+ <%= submit_tag t("doorkeeper.authorized_applications.buttons.revoke"), class: submit_btn_css %>
<% end %>
diff --git a/app/views/imports/new.html.erb b/app/views/imports/new.html.erb
index 687d6d6ba2..205bde2bba 100644
--- a/app/views/imports/new.html.erb
+++ b/app/views/imports/new.html.erb
@@ -65,7 +65,7 @@
<% if (params[:type].nil? || params[:type] == "SureImport") && !Current.user&.guest? %>
<li>
- <%= styled_form_with url: imports_path, scope: :import, multipart: true, class: "w-full", data: { turbo_frame: "_top" } do |form| %>
+ <%= styled_form_with url: imports_path, scope: :import, multipart: true, class: "w-full", data: { turbo_frame: "_top", controller: "auto-submit-form" } do |form| %>
<%= form.hidden_field :type, value: "SureImport" %>
<label class="flex items-center justify-between p-4 group cursor-pointer w-full">
<div class="flex items-center gap-2">
@@ -84,7 +84,7 @@
</div>
</div>
<%= icon("chevron-right") %>
- <%= form.file_field :import_file, accept: ".ndjson,.json", class: "hidden", onchange: "this.form.requestSubmit()" %>
+ <%= form.file_field :import_file, accept: ".ndjson,.json", class: "hidden", data: { auto_submit_form_target: "auto", autosubmit_trigger_event: "change" } %>
</label>
<% end %>
@@ -138,7 +138,7 @@
<% if (params[:type].nil? || params[:type].in?(%w[DocumentImport PdfImport])) && @document_upload_extensions.any? %>
<li>
- <%= styled_form_with url: imports_path, scope: :import, multipart: true, class: "w-full", data: { turbo_frame: "_top" } do |form| %>
+ <%= styled_form_with url: imports_path, scope: :import, multipart: true, class: "w-full", data: { turbo_frame: "_top", controller: "auto-submit-form" } do |form| %>
<%= form.hidden_field :type, value: "DocumentImport" %>
<label class="flex items-center justify-between p-4 group cursor-pointer w-full">
<div class="flex items-center gap-2">
@@ -157,7 +157,7 @@
</div>
</div>
<%= icon("chevron-right") %>
- <%= form.file_field :import_file, accept: @document_upload_extensions.join(","), class: "hidden", onchange: "this.form.requestSubmit()" %>
+ <%= form.file_field :import_file, accept: @document_upload_extensions.join(","), class: "hidden", data: { auto_submit_form_target: "auto", autosubmit_trigger_event: "change" } %>
</label>
<% end %>
diff --git a/app/views/indexa_capital_items/setup_accounts.html.erb b/app/views/indexa_capital_items/setup_accounts.html.erb
index fb16386c31..dbdd019214 100644
--- a/app/views/indexa_capital_items/setup_accounts.html.erb
+++ b/app/views/indexa_capital_items/setup_accounts.html.erb
@@ -61,7 +61,7 @@
<% end %>
</label>
</div>
- <div class="mt-3 pl-7" onclick="event.stopPropagation();">
+ <div class="mt-3 pl-7" data-controller="stop-propagation" data-action="click->stop-propagation#stop">
<label for="sync_start_<%= indexa_capital_account.id %>" class="block text-xs text-secondary mb-1">
<%= t("indexa_capital_items.setup_accounts.sync_start_date_label") %>
</label>
@@ -69,7 +69,7 @@
id="sync_start_<%= indexa_capital_account.id %>"
name="sync_start_dates[<%= indexa_capital_account.id %>]"
value="<%= indexa_capital_account.sync_start_date %>"
- onclick="event.stopPropagation();"
+ data-action="click->stop-propagation#stop"
autocomplete="off"
class="bg-container border border-primary rounded px-2 py-1 text-sm text-primary">
<p class="text-xs text-secondary mt-1">
diff --git a/app/views/layouts/_dark_mode_check.html.erb b/app/views/layouts/_dark_mode_check.html.erb
index 949891f2b0..d95db5b151 100644
--- a/app/views/layouts/_dark_mode_check.html.erb
+++ b/app/views/layouts/_dark_mode_check.html.erb
@@ -1,4 +1,4 @@
-<script>
+<script nonce="<%= content_security_policy_nonce %>">
if (localStorage.theme === 'dark' || (!('theme' in localStorage) && window.matchMedia('(prefers-color-scheme: dark)').matches)) {
document.documentElement.setAttribute("data-theme", "dark");
}
diff --git a/app/views/layouts/_privacy_mode_check.html.erb b/app/views/layouts/_privacy_mode_check.html.erb
index 6e92999014..de364f115a 100644
--- a/app/views/layouts/_privacy_mode_check.html.erb
+++ b/app/views/layouts/_privacy_mode_check.html.erb
@@ -1,4 +1,4 @@
-<script>
+<script nonce="<%= content_security_policy_nonce %>">
if (localStorage.getItem('privacyMode') === 'true') {
document.documentElement.classList.add('privacy-mode');
}
diff --git a/app/views/layouts/print.html.erb b/app/views/layouts/print.html.erb
index b11b75c96f..7342ac2718 100644
--- a/app/views/layouts/print.html.erb
+++ b/app/views/layouts/print.html.erb
@@ -15,7 +15,7 @@
<%= yield %>
</div>
- <script>
+ <script nonce="<%= content_security_policy_nonce %>">
// Auto-trigger print dialog when page loads
window.onload = function() {
// Small delay to ensure styles are loaded
diff --git a/app/views/layouts/shared/_head.html.erb b/app/views/layouts/shared/_head.html.erb
index 8e906f72fd..ef6da1e62c 100644
--- a/app/views/layouts/shared/_head.html.erb
+++ b/app/views/layouts/shared/_head.html.erb
@@ -82,7 +82,7 @@
<link rel="apple-touch-icon" sizes="512x512" href="/logo-pwa.png">
<link rel="icon" sizes="192x192" type="image/png" href="/android-chrome-192x192.png">
- <% if posthog_enabled? && (posthog_config = Rails.configuration.x.posthog).try(:api_key).present? %>
+ <% if posthog_enabled? && (posthog_config = Rails.configuration.x.posthog).try(:enabled) %>
<%= render "shared/posthog", posthog_api_key: posthog_config.api_key, posthog_host: posthog_config.host %>
<% end %>
diff --git a/app/views/pages/redis_configuration_error.html.erb b/app/views/pages/redis_configuration_error.html.erb
index 7ed0fb2e76..80e3f7c606 100644
--- a/app/views/pages/redis_configuration_error.html.erb
+++ b/app/views/pages/redis_configuration_error.html.erb
@@ -44,7 +44,7 @@
icon: "refresh-cw",
type: "button",
full_width: true,
- onclick: "window.location.reload()"
+ data: { controller: "page-reload", action: "click->page-reload#reload" }
) %>
</div>
</div>
diff --git a/app/views/sessions/mobile_sso_start.html.erb b/app/views/sessions/mobile_sso_start.html.erb
index 123aca3a74..4e80e99542 100644
--- a/app/views/sessions/mobile_sso_start.html.erb
+++ b/app/views/sessions/mobile_sso_start.html.erb
@@ -3,6 +3,6 @@
<form id="sso_form" action="/auth/<%= ERB::Util.html_escape(@provider) %>" method="post">
<input type="hidden" name="authenticity_token" value="<%= form_authenticity_token %>">
</form>
- <script>document.getElementById('sso_form').submit();</script>
+ <script nonce="<%= content_security_policy_nonce %>">document.getElementById('sso_form').submit();</script>
<noscript><p><%= t("sessions.mobile_sso_start.redirecting_html", url: "/auth/#{ERB::Util.html_escape(@provider)}") %></p></noscript>
</body></html>
diff --git a/app/views/settings/providers/_sync_button.html.erb b/app/views/settings/providers/_sync_button.html.erb
index 6e3df16aea..97beb71d35 100644
--- a/app/views/settings/providers/_sync_button.html.erb
+++ b/app/views/settings/providers/_sync_button.html.erb
@@ -11,5 +11,5 @@
title: button_label,
aria: { label: button_label },
class: "disabled:opacity-40 disabled:cursor-not-allowed",
- form: { onclick: "event.stopPropagation()", class: "inline-flex" }
+ form: { data: { controller: "stop-propagation", action: "click->stop-propagation#stop" }, class: "inline-flex" }
) %>
diff --git a/app/views/snaptrade_items/setup_accounts.html.erb b/app/views/snaptrade_items/setup_accounts.html.erb
index 1410356a3d..652a9a984a 100644
--- a/app/views/snaptrade_items/setup_accounts.html.erb
+++ b/app/views/snaptrade_items/setup_accounts.html.erb
@@ -139,7 +139,7 @@
<% end %>
</label>
</div>
- <div class="mt-3 pl-7" onclick="event.stopPropagation();">
+ <div class="mt-3 pl-7" data-controller="stop-propagation" data-action="click->stop-propagation#stop">
<%= render DS::Select.new(
form: form,
method: "account_types[#{snaptrade_account.id}]",
@@ -154,7 +154,7 @@
id="sync_start_<%= snaptrade_account.id %>"
name="sync_start_dates[<%= snaptrade_account.id %>]"
value="<%= snaptrade_account.sync_start_date %>"
- onclick="event.stopPropagation();"
+ data-action="click->stop-propagation#stop"
autocomplete="off"
class="bg-container border border-primary rounded px-2 py-1 text-sm text-primary">
<p class="text-xs text-secondary mt-1">
diff --git a/config/initializers/posthog.rb b/config/initializers/00_posthog.rb
similarity index 56%
rename from config/initializers/posthog.rb
rename to config/initializers/00_posthog.rb
index 125853e07f..c33b3e949f 100644
--- a/config/initializers/posthog.rb
+++ b/config/initializers/00_posthog.rb
@@ -9,7 +9,9 @@ def (Rails.configuration.x.posthog).browser_enabled?
end
Rails.configuration.x.posthog.api_key = ENV["POSTHOG_KEY"].presence
-Rails.configuration.x.posthog.host = ENV.fetch("POSTHOG_HOST", "https://us.i.posthog.com")
+# .presence (not .fetch) so an explicitly-blank POSTHOG_HOST="" still falls
+# back to the default instead of reaching PostHog::Client as an empty string.
+Rails.configuration.x.posthog.host = ENV["POSTHOG_HOST"].presence || "https://us.i.posthog.com"
Rails.configuration.x.posthog.feedback_enabled = ActiveModel::Type::Boolean.new.cast(ENV.fetch("POSTHOG_FEEDBACK_ENABLED", "true"))
# Public client configuration for shared feedback, including self-hosted Sankey.
# This write-only project token is safe to distribute; it is not an admin key.
@@ -27,10 +29,34 @@ Rails.configuration.x.posthog.feedback_surveys = {
}.freeze
}.freeze
-if (api_key = Rails.configuration.x.posthog.api_key).present?
+# Both the server client below AND the browser snippet
+# (app/views/shared/_posthog.html.erb, rendered from _head.html.erb) AND
+# the CSP script-src/connect-src allowlist (content_security_policy.rb)
+# send data to this host — posthog-ruby sends the API key in the request
+# body and silently skips TLS when the scheme isn't https, and the browser
+# integration would ship analytics/session data in cleartext the same way.
+# A single `enabled` method gates all three integration points so a bad
+# POSTHOG_HOST disables PostHog everywhere instead of only wherever a
+# reviewer happened to look first. Defined as a method (not a value computed
+# once at boot) so it re-evaluates against api_key/host, which tests stub.
+Rails.configuration.x.posthog.define_singleton_method(:enabled) do
+ next false unless api_key.present?
+ scheme = begin
+ URI.parse(host).scheme
+ rescue URI::InvalidURIError
+ nil
+ end
+ scheme == "https"
+end
+
+if Rails.configuration.x.posthog.api_key.present? && !Rails.configuration.x.posthog.enabled
+ Rails.logger.error("[PostHog] POSTHOG_HOST (#{Rails.configuration.x.posthog.host}) is not HTTPS — refusing to enable PostHog (server client, browser snippet, and CSP allowlist) to avoid sending the API key/analytics data in cleartext.")
+end
+
+if Rails.configuration.x.posthog.enabled
# Initialize PostHog client
$posthog = PostHog::Client.new({
- api_key: api_key,
+ api_key: Rails.configuration.x.posthog.api_key,
host: Rails.configuration.x.posthog.host,
on_error: Proc.new { |status, msg| puts "PostHog error: #{status} - #{msg}" }
})
diff --git a/config/initializers/content_security_policy.rb b/config/initializers/content_security_policy.rb
index 834aa21186..f05071b343 100644
--- a/config/initializers/content_security_policy.rb
+++ b/config/initializers/content_security_policy.rb
@@ -1,26 +1,143 @@
# Be sure to restart your server when you modify this file.
-
-# Define an application-wide content security policy.
+#
# See the Securing Rails Applications Guide for more information:
# https://guides.rubyonrails.org/security.html#content-security-policy-header
-
-# Rails.application.configure do
-# config.content_security_policy do |policy|
-# policy.default_src :self, :https
-# policy.font_src :self, :https, :data
-# policy.img_src :self, :https, :data
-# policy.object_src :none
-# policy.script_src :self, :https
-# policy.script_src :self, :https, 'https://us.i.posthog.com'
-# policy.style_src :self, :https
-# # Specify URI for violation reports
-# # policy.report_uri "/csp-violation-report-endpoint"
-# end
#
-# # Generate session nonces for permitted importmap, inline scripts, and inline styles.
-# config.content_security_policy_nonce_generator = ->(request) { request.session.id.to_s }
-# config.content_security_policy_nonce_directives = %w(script-src style-src)
-#
-# # Report violations without enforcing the policy.
-# # config.content_security_policy_report_only = true
-# end
+# Deliberately excluded directives:
+# - form-action: the OAuth authorization consent form
+# (app/views/doorkeeper/authorizations/new.html.erb) and the redirect pages
+# in app/views/doorkeeper/authorizations/form_post.html.erb /
+# app/views/sessions/mobile_sso_start.html.erb submit to a caller-registered
+# redirect_uri or custom URL scheme (e.g. "sureapp://") that isn't known
+# ahead of time, so a static allowlist can't cover it without breaking
+# every third-party OAuth client and the mobile app's SSO flow.
+# - report-uri: no violation-collection endpoint exists yet; add one before
+# relying on this for detection rather than just enforcement.
+# A CSP source with a path matches only that path, so external URLs are
+# reduced to their origin (scheme, host and a non-default port).
+csp_origin = lambda do |url|
+ uri = URI.parse(url.to_s.strip)
+ next unless %w[http https].include?(uri.scheme) && uri.host.present?
+
+ port = uri.port == uri.default_port ? "" : ":#{uri.port}"
+ "#{uri.scheme}://#{uri.host}#{port}"
+rescue URI::InvalidURIError
+ nil
+end
+
+Rails.application.configure do
+ config.content_security_policy do |policy|
+ policy.default_src :self
+ policy.font_src :self, :https, :data
+ # blob: is required for the profile-picture upload preview
+ # (app/javascript/controllers/profile_image_preview_controller.js uses
+ # URL.createObjectURL(file) to show the selected file before it's saved).
+ #
+ # A generic_s3 endpoint can be plain http (e.g. a local MinIO), which
+ # :https does not cover, so its origin is allowed explicitly. Without
+ # path-style URLs the bucket is a subdomain of the endpoint host.
+ s3_image_origins = lambda do
+ s3_origin = csp_origin.call(ENV["GENERIC_S3_ENDPOINT"])
+ next [] unless s3_origin
+
+ bucket = ENV["GENERIC_S3_BUCKET"].to_s.strip
+ path_style = ActiveModel::Type::Boolean.new.cast(ENV.fetch("GENERIC_S3_FORCE_PATH_STYLE", "false"))
+ origins = [ s3_origin ]
+ origins << s3_origin.sub("://", "://#{bucket}.") if bucket.match?(/\A[a-z0-9.-]+\z/i) && !path_style
+ origins
+ end
+ policy.img_src :self, :https, :data, :blob, s3_image_origins
+
+ # Plaid Link (app/javascript/controllers/plaid_controller.js) loads its
+ # widget script from cdn.plaid.com at runtime via a dynamically inserted
+ # <script> tag — that bypasses the nonce entirely (nonces only apply to
+ # markup the server itself rendered), so the origin must be allowlisted
+ # directly. The widget then opens an iframe from the same cdn.plaid.com
+ # host and talks to the Plaid API host of the active environment. That
+ # environment is not known at boot: Settings > Providers can override
+ # PLAID_ENV (config_value(:environment) in
+ # app/models/provider/plaid_adapter.rb wins over the env var), and Plaid
+ # EU reads PLAID_EU_ENV instead, so a US and an EU family on the same
+ # install can use different environments. Allowlist every Plaid API host
+ # rather than tracking one env var, or bank-linking breaks silently
+ # whenever the effective environment differs from it. Always included
+ # (not gated on Plaid being actively configured) since Plaid is a core,
+ # always-available connection method, not an opt-in add-on like PostHog
+ # below.
+ plaid_api_hosts = %w[sandbox development production].map { |env| "https://#{env}.plaid.com" }
+ plaid_cdn_host = "https://cdn.plaid.com"
+ policy.frame_src :self, plaid_cdn_host
+
+ # PostHog dynamically inserts a plain <script src> for its recorder
+ # bundle (_posthog_bootstrap.html.erb loads <host>-assets/static/array.js)
+ # and long-polls its ingestion endpoint — neither goes through importmap,
+ # so both need explicit script-src/connect-src entries. Two independent
+ # integrations load it, each with its own host:
+ # - analytics (layouts/shared/_head.html.erb) on POSTHOG_HOST, only when
+ # POSTHOG_KEY is set;
+ # - the self-hosted feedback survey (FeedbackHelper#feedback_config) on
+ # the shared public project, without POSTHOG_KEY, unless
+ # POSTHOG_FEEDBACK_ENABLED=false.
+ # Hosts are added only when the matching integration renders, using the
+ # same gates as the views, so the default policy stays as tight as
+ # possible. Resolved per request (Rails instance_execs the proc in the
+ # controller) so the gates are read the same way the views read them.
+ # config/initializers/00_posthog.rb sets Rails.configuration.x.posthog —
+ # the "00_" prefix forces it to load before this file (plain alphabetical
+ # order would put "content_security_policy.rb" first and crash boot with
+ # NoMethodError on nil).
+ posthog_hosts = lambda do
+ config = Rails.configuration.x.posthog
+ # Same gate as FeedbackHelper#posthog_enabled?, which the head partial
+ # and the feedback survey both check before rendering.
+ next [] unless Rails.env.production? || (Rails.env.development? && config.development_enabled)
+
+ hosts = []
+ hosts << config.host if config.enabled
+ if config.feedback_enabled && Rails.application.config.app_mode.self_hosted?
+ hosts << config.self_hosted_feedback_project[:host]
+ end
+ # POSTHOG_HOST may carry a reverse-proxy path (e.g. https://example.com/ingest).
+ hosts.filter_map { |host| csp_origin.call(host) }.uniq
+ .flat_map { |host| [ host, host.sub(".i.posthog.com", "-assets.i.posthog.com") ] }.uniq
+ end
+ policy.script_src :self, plaid_cdn_host, posthog_hosts
+ policy.connect_src :self, *plaid_api_hosts, posthog_hosts
+ # unsafe-inline is scoped to styles only, never scripts. Category/tag
+ # colors are the only user-influenced values rendered into style="..."
+ # attributes, and Category#color / Tag#color are validated server-side
+ # against /\A#[0-9A-Fa-f]{6}\z/ (see app/models/category.rb,
+ # app/models/tag.rb), so this can't be used to inject arbitrary CSS —
+ # nonces don't cover inline style *attributes* (only <style> elements),
+ # and this app relies on inline styles too heavily (D3 charts, dynamic
+ # widget sizing) to refactor them all away in this change.
+ policy.style_src :self, :unsafe_inline
+ policy.object_src :none
+ # Blocks a classic CSP bypass: an attacker-injected <base href="...">
+ # tag would otherwise silently redirect every relative script/asset URL
+ # (including importmap-resolved module specifiers) to an attacker origin.
+ policy.base_uri :self
+ # CSP's modern replacement for X-Frame-Options; kept even though Rails
+ # already sends X-Frame-Options: SAMEORIGIN by default, since
+ # frame-ancestors is what's actually enforced by current browsers and
+ # supports non-SAMEORIGIN cases X-Frame-Options can't express.
+ policy.frame_ancestors :self
+ end
+
+ # Every <script> element must carry this nonce to execute — an attacker
+ # who injects a script tag via an XSS payload has no way to predict or
+ # read it (Rails ties it to the session id; browsers also hide nonce
+ # attributes from generic DOM access), so injected markup without the
+ # nonce is simply not executed. Deliberately NOT applied to style-src:
+ # nonces only cover <style> elements, not inline style="..." attributes,
+ # so it would give no benefit there and just make it look like inline
+ # styles need per-element upkeep they don't.
+ config.content_security_policy_nonce_generator = ->(request) { request.session.id.to_s }
+ config.content_security_policy_nonce_directives = %w[script-src]
+
+ # CSP_REPORT_ONLY=true sends the same policy as
+ # Content-Security-Policy-Report-Only: the browser reports violations in
+ # its console but blocks nothing. An escape hatch for self-hosted setups
+ # that inject their own scripts (see docs/hosting/content-security-policy.md).
+ config.content_security_policy_report_only = ActiveModel::Type::Boolean.new.cast(ENV.fetch("CSP_REPORT_ONLY", "false"))
+end
diff --git a/config/initializers/permissions_policy.rb b/config/initializers/permissions_policy.rb
index 7db3b9577e..c38bad12ea 100644
--- a/config/initializers/permissions_policy.rb
+++ b/config/initializers/permissions_policy.rb
@@ -1,13 +1,28 @@
# Be sure to restart your server when you modify this file.
-
+#
# Define an application-wide HTTP permissions policy. For further
# information see: https://developers.google.com/web/updates/2018/06/feature-policy
+#
+# This app never uses camera/microphone/usb/geolocation/payment/fullscreen
+# APIs (verified by grepping app/javascript for their JS entry points), so
+# those are locked to :none.
+#
+# WebAuthn/passkeys (app/javascript/controllers/webauthn_*_controller.js) are
+# deliberately NOT restricted here: this Rails version's PermissionsPolicy
+# DIRECTIVES list (action_dispatch/http/permissions_policy.rb) doesn't include
+# publickey-credentials-get/-create, so there's no directive to set — leaving
+# it unlisted keeps the browser default (allowed), which is what passkey
+# login/registration needs. Do not add those directive names here; Rails
+# raises NoMethodError for any symbol outside its fixed DIRECTIVES map.
+#
+# Rails only sends this policy as the legacy Feature-Policy header, which
+# Firefox and Safari ignore, so the same list also goes out as
+# Permissions-Policy (each feature disabled with an empty allowlist).
+disabled_features = %i[camera microphone geolocation usb payment fullscreen]
+
+Rails.application.config.permissions_policy do |policy|
+ disabled_features.each { |feature| policy.public_send(feature, :none) }
+end
-# Rails.application.config.permissions_policy do |policy|
-# policy.camera :none
-# policy.gyroscope :none
-# policy.microphone :none
-# policy.usb :none
-# policy.fullscreen :self
-# policy.payment :self, "https://secure.example.com"
-# end
+Rails.application.config.action_dispatch.default_headers["Permissions-Policy"] =
+ disabled_features.map { |feature| "#{feature}=()" }.join(", ")
diff --git a/config/initializers/rswag.rb b/config/initializers/rswag.rb
index 5bef48784c..7348cdcd8f 100644
--- a/config/initializers/rswag.rb
+++ b/config/initializers/rswag.rb
@@ -9,3 +9,19 @@ if defined?(Rswag::Api) && Rails.env.development?
c.openapi_root = Rails.root.join("docs", "api").to_s
end
end
+
+# Rswag's UI middleware returns its own CSP (which allows the inline Swagger UI
+# bootstrap script) under a mixed-case header name. Rails' CSP middleware looks
+# for the lowercase Rack 3 name, misses it and adds the app policy as a second
+# header, which blocks that script and leaves /api-docs blank. Normalizing the
+# header names lets Rails see the existing policy and keep it.
+if defined?(Rswag::Ui) && Rails.env.development?
+ require "rswag/ui/middleware"
+
+ Rswag::Ui::Middleware.prepend(Module.new do
+ def call(env)
+ status, headers, body = super
+ [ status, Rack::Headers.new.merge!(headers), body ]
+ end
+ end)
+end
diff --git a/docs/hosting/content-security-policy.md b/docs/hosting/content-security-policy.md
new file mode 100644
index 0000000000..5758d80b39
--- /dev/null
+++ b/docs/hosting/content-security-policy.md
@@ -0,0 +1,26 @@
+# Content Security Policy
+
+Sure sends a Content-Security-Policy (CSP) header with every page. The browser then runs only the scripts that Sure itself renders, so injected markup cannot run JavaScript. The policy lives in `config/initializers/content_security_policy.rb`.
+
+## What it allows out of the box
+
+- Scripts, styles, fonts and connections from Sure's own origin.
+- Plaid Link, so bank connections keep working.
+- PostHog, but only when analytics or the feedback survey are turned on. If `POSTHOG_HOST` contains a path (for example a reverse proxy at `https://example.com/ingest`), only its origin is allowed, so every path on that host works.
+- Images from any `https:` URL. If you use `generic_s3` storage with a plain `http://` `GENERIC_S3_ENDPOINT` (for example a local MinIO), that endpoint's origin is allowed too. Without `GENERIC_S3_FORCE_PATH_STYLE=true` the bucket subdomain of that endpoint is allowed as well.
+
+## When something breaks
+
+Some proxies and CDNs inject their own scripts into every page. Sure's policy blocks those scripts, because they do not carry its nonce. Known examples are Cloudflare Web Analytics, Rocket Loader and the email obfuscation in Scrape Shield. Turn those features off for your Sure host if you can.
+
+If you cannot, or you need time to find out what is blocked, set:
+
+```bash
+CSP_REPORT_ONLY=true
+```
+
+Sure then sends the same policy as `Content-Security-Policy-Report-Only`. The browser blocks nothing and only lists each violation in its developer console. Restart the app after changing the variable. Use this as a temporary escape hatch: while it is set, the policy no longer protects against injected scripts.
+
+## Permissions Policy
+
+Sure also disables browser features it never uses (camera, microphone, geolocation, USB, payment and fullscreen). It sends this list both as `Permissions-Policy` and as the older `Feature-Policy` header. The list lives in `config/initializers/permissions_policy.rb`.
diff --git a/docs/llm-guides/feedback-surveys.md b/docs/llm-guides/feedback-surveys.md
index 422c4e81d5..4288c268d5 100644
--- a/docs/llm-guides/feedback-surveys.md
+++ b/docs/llm-guides/feedback-surveys.md
@@ -5,7 +5,7 @@ deployment behavior, privacy boundaries, and the first implementation's event
catalog and counting rules.
Use `feedback_config(:feature_name)` from `FeedbackHelper` to select a survey.
-Project routing belongs in this helper and `config/initializers/posthog.rb`;
+Project routing belongs in this helper and `config/initializers/00_posthog.rb`;
question wording, response mapping, UI, and events belong to the feature.
## Configuration
@@ -34,6 +34,12 @@ client configuration; operators need no account or key setup. It must never be a
PostHog personal or project secret key. An operator's own analytics configuration
must not change this destination.
+The browser loads the survey script from this host's `-assets` counterpart and
+sends responses to the host itself, so `config/initializers/content_security_policy.rb`
+allowlists both in `script-src` and `connect-src` under the same gates. If the
+destination host changes, the policy follows it automatically; a new destination
+outside `self_hosted_feedback_project` must be added there too.
+
Unknown features, blank survey IDs, or a missing ID for the selected destination
return `{}`. There is no fallback to another feature's survey or another project.
Self-hosted configuration also returns `{}` outside production (unless development explicitly opts in with
diff --git a/test/architecture/ai_agreement_test.rb b/test/architecture/ai_agreement_test.rb
index 13731f9d56..8e7f316c1f 100644
--- a/test/architecture/ai_agreement_test.rb
+++ b/test/architecture/ai_agreement_test.rb
@@ -65,7 +65,7 @@ class AiAgreementTest < ActionDispatch::IntegrationTest
enhance_shown = response.body.include?(enhance_family_merchants_path)
get new_import_path
- document_upload_shown = css_select("form[data-turbo-frame=_top] input[type=file][onchange='this.form.requestSubmit()']").size > 1
+ document_upload_shown = css_select("form[data-turbo-frame=_top][data-controller~=auto-submit-form] input[type=file][data-auto-submit-form-target=auto]").size > 1
offered = Rule::Registry::TransactionResource.new(Rule.new(family: @family, resource_type: "transaction")).action_executors.map(&:key)
tools = Assistant.function_classes(@user)
diff --git a/test/architecture/csp_inline_script_test.rb b/test/architecture/csp_inline_script_test.rb
new file mode 100644
index 0000000000..7a8f6fb878
--- /dev/null
+++ b/test/architecture/csp_inline_script_test.rb
@@ -0,0 +1,78 @@
+# frozen_string_literal: true
+
+require "test_helper"
+
+# The Content-Security-Policy (config/initializers/content_security_policy.rb)
+# only runs inline scripts that carry the request nonce. Inline event handlers
+# and javascript: URLs can never carry one, so the browser silently drops them.
+# This test catches them before they ship.
+class CspInlineScriptTest < ActiveSupport::TestCase
+ TEMPLATE_GLOBS = %w[app/views/**/*.erb app/components/**/*.erb app/components/**/*.rb app/helpers/**/*.rb].freeze
+
+ EVENTS = %w[
+ abort animationend beforeunload blur change click contextmenu copy cut dblclick drag dragend dragover
+ dragstart drop error focus focusin focusout input invalid keydown keypress keyup load mousedown
+ mouseenter mouseleave mousemove mouseout mouseover mouseup paste pointerdown pointerup reset resize
+ scroll select submit toggle touchend touchmove touchstart transitionend unload wheel
+ ].freeze
+ EVENT = "on(?:#{EVENTS.join("|")})"
+
+ # onclick="…" in markup, or onclick: … / "onclick" => … in tag helpers.
+ INLINE_HANDLER = /(?:\s#{EVENT}\s*=\s*["']|["']?\b#{EVENT}["']?\s*(?::(?!:)|=>))/i
+ JAVASCRIPT_URL = /["']\s*javascript:/i
+ SCRIPT_TAG = /<script\b([^>]*)>.*?<\/script>/mi
+ DATA_SCRIPT_TYPE = /type\s*=\s*["']application\/(?:ld\+)?json["']/i
+
+ test "templates have no inline event handlers" do
+ assert_no_offenses(INLINE_HANDLER, "inline event handler (use a Stimulus action instead)")
+ end
+
+ test "templates have no javascript: URLs" do
+ assert_no_offenses(JAVASCRIPT_URL, "javascript: URL (use a Stimulus action instead)")
+ end
+
+ test "inline script tags carry the CSP nonce" do
+ offenses = template_sources.flat_map do |path, source|
+ source.to_enum(:scan, SCRIPT_TAG).filter_map do
+ attributes = Regexp.last_match(1)
+ next if attributes.match?(/\b(?:nonce|src)\s*=/i) || attributes.match?(DATA_SCRIPT_TYPE)
+
+ "#{path}:#{line_of(source, Regexp.last_match.begin(0))}"
+ end
+ end
+
+ assert_empty offenses, "inline <script> without nonce=\"<%= content_security_policy_nonce %>\":\n#{offenses.join("\n")}"
+ end
+
+ test "the checks catch what they are meant to catch" do
+ assert_match INLINE_HANDLER, %(<img src="x" onerror="this.remove()">)
+ assert_match INLINE_HANDLER, %(image_tag url, onerror: "this.remove()")
+ assert_match INLINE_HANDLER, %(image_tag url, onerror: on_error)
+ assert_match INLINE_HANDLER, %(tag.button "Go", "onclick" => "go()")
+ assert_no_match INLINE_HANDLER, %(data: { action: "click->menu#toggle" }, onboarding: "x")
+ assert_match JAVASCRIPT_URL, %(<a href="javascript:void(0)">)
+ assert_match SCRIPT_TAG, %(<script>alert(1)</script>)
+ end
+
+ private
+ def assert_no_offenses(pattern, description)
+ offenses = template_sources.flat_map do |path, source|
+ source.each_line.with_index(1).filter_map { |line, number| "#{path}:#{number}" if line.match?(pattern) }
+ end
+
+ assert_empty offenses, "#{description}:\n#{offenses.join("\n")}"
+ end
+
+ # ERB and HTML comments are dropped (kept as blank lines so line numbers
+ # stay right); they may mention <script> or onerror in prose.
+ def template_sources
+ @template_sources ||= TEMPLATE_GLOBS.flat_map { |glob| Dir[Rails.root.join(glob)] }.sort.to_h do |file|
+ source = File.read(file).gsub(/<%#.*?%>|<!--.*?-->/m) { |comment| "\n" * comment.count("\n") }
+ [ Pathname(file).relative_path_from(Rails.root).to_s, source ]
+ end
+ end
+
+ def line_of(source, offset)
+ source[0...offset].count("\n") + 1
+ end
+end
diff --git a/test/components/provider_logo_test.rb b/test/components/provider_logo_test.rb
index 9e7be0a0c1..191f5ebe62 100644
--- a/test/components/provider_logo_test.rb
+++ b/test/components/provider_logo_test.rb
@@ -12,7 +12,8 @@ class ProviderLogoTest < ViewComponent::TestCase
render_inline(ProviderLogo.new(provider_key: :example))
assert_selector "img[src='https://cdn.brandfetch.io/example.com/icon/fallback/404/w/40/h/40?c=test-client-id']"
- assert_selector "img[onerror='#{ProviderLogo::REMOVE_ON_ERROR}']"
+ assert_selector "img[data-controller='image-fallback'][data-action='error->image-fallback#remove']"
+ assert_no_selector "img[onerror]"
assert_selector "span[aria-hidden='true'] + img"
end
diff --git a/test/controllers/imports_controller_test.rb b/test/controllers/imports_controller_test.rb
index 3f752dc919..021ac0f8e5 100644
--- a/test/controllers/imports_controller_test.rb
+++ b/test/controllers/imports_controller_test.rb
@@ -29,7 +29,10 @@ class ImportsControllerTest < ActionDispatch::IntegrationTest
assert_response :success
assert_select "turbo-frame#modal"
- assert_select "form[data-turbo-frame=_top] input[type=file][onchange='this.form.requestSubmit()']", count: 2
+ # The file inputs submit through the auto-submit-form controller rather
+ # than an inline onchange handler, which the Content Security Policy blocks.
+ assert_select "form[data-turbo-frame=_top][data-controller~=auto-submit-form] input[type=file][data-auto-submit-form-target=auto]", count: 2
+ assert_select "input[type=file][onchange]", count: 0
end
# DS::Button with an href renders button_to, which POSTs unless given a
diff --git a/test/initializers/posthog_test.rb b/test/initializers/posthog_test.rb
index 414f76d1da..bdb0865eed 100644
--- a/test/initializers/posthog_test.rb
+++ b/test/initializers/posthog_test.rb
@@ -70,7 +70,7 @@ class PosthogTest < ActiveSupport::TestCase
def load_initializer(**overrides)
with_env_overrides({ POSTHOG_KEY: nil, POSTHOG_HOST: nil, POSTHOG_FEEDBACK_ENABLED: "true",
POSTHOG_DEVELOPMENT_ENABLED: "false" }.merge(overrides)) do
- load Rails.root.join("config/initializers/posthog.rb")
+ load Rails.root.join("config/initializers/00_posthog.rb")
end
end
end
diff --git a/test/integration/content_security_policy_test.rb b/test/integration/content_security_policy_test.rb
new file mode 100644
index 0000000000..39510969a3
--- /dev/null
+++ b/test/integration/content_security_policy_test.rb
@@ -0,0 +1,174 @@
+require "test_helper"
+
+class ContentSecurityPolicyTest < ActionDispatch::IntegrationTest
+ test "sends a nonce-based CSP header that forbids unsafe-inline scripts" do
+ get new_session_url
+
+ csp = response.headers["Content-Security-Policy"]
+ assert csp.present?, "Content-Security-Policy header must be set"
+
+ script_src = csp[/script-src ([^;]+)/, 1]
+ assert_includes script_src, "'self'"
+ assert_match(/'nonce-[0-9a-f]+'/, script_src)
+ assert_not_includes script_src, "'unsafe-inline'", "script-src must never allow unsafe-inline"
+ assert_not_includes script_src, "'unsafe-eval'", "script-src must never allow unsafe-eval"
+
+ assert_includes csp, "object-src 'none'"
+ assert_includes csp, "base-uri 'self'"
+ assert_includes csp, "frame-ancestors 'self'"
+ end
+
+ test "the CSP nonce sent in the header matches the nonce rendered on inline scripts" do
+ get new_session_url
+
+ csp = response.headers["Content-Security-Policy"]
+ nonce = csp[/'nonce-([0-9a-f]+)'/, 1]
+ assert nonce.present?
+
+ inline_scripts = assert_select "script:not([src])"
+ assert_select "script:not([src])[nonce=?]", nonce, count: inline_scripts.size
+ end
+
+ test "the cached account sidebar still runs its script in a new session" do
+ store = ActiveSupport::Cache::MemoryStore.new
+ original = [ ActionController::Base.perform_caching, ActionController::Base.cache_store ]
+ ActionController::Base.perform_caching = true
+ ActionController::Base.cache_store = store
+
+ nonces = 2.times.map do
+ reset!
+ sign_in users(:family_admin)
+ get root_path
+
+ nonce = response.headers["Content-Security-Policy"][/'nonce-([0-9a-f]+)'/, 1]
+ sidebar_script = css_select("script").find { |script| script.text.include?("__sidebarExpandAllBound") }
+ assert sidebar_script, "the account sidebar script is rendered"
+ assert_equal nonce, sidebar_script["nonce"]
+ nonce
+ end
+
+ assert_not_equal nonces.first, nonces.last, "each session gets its own nonce"
+ ensure
+ ActionController::Base.perform_caching, ActionController::Base.cache_store = original
+ end
+
+ test "allows every Plaid API host whatever environment PLAID_ENV names" do
+ # The effective Plaid environment can come from Settings > Providers or
+ # PLAID_EU_ENV, so the policy must not depend on PLAID_ENV alone.
+ get new_session_url
+
+ connect_src = csp_directive("connect-src")
+ %w[sandbox development production].each do |env|
+ assert_includes connect_src, "https://#{env}.plaid.com"
+ end
+ assert_includes csp_directive("script-src"), "https://cdn.plaid.com"
+ assert_includes csp_directive("frame-src"), "https://cdn.plaid.com"
+ end
+
+ test "allows the self-hosted feedback survey's PostHog hosts without POSTHOG_KEY" do
+ user = users(:family_admin)
+ user.update!(preferences: user.preferences.merge("preview_features_enabled" => true, "cashflow_preview_enabled" => true))
+ sign_in user
+ config = Rails.configuration.x.posthog
+ config.stubs(:api_key).returns(nil)
+ config.stubs(:feedback_enabled).returns(true)
+ config.stubs(:development_enabled).returns(false)
+ Rails.env.stubs(:production?).returns(true)
+
+ with_self_hosting do
+ get root_path
+ assert_select "#cashflow-preview[data-sankey-preview-feedback-host-value='https://us.i.posthog.com']"
+ [ "script-src", "connect-src" ].each do |directive|
+ assert_includes csp_directive(directive), "https://us.i.posthog.com"
+ assert_includes csp_directive(directive), "https://us-assets.i.posthog.com"
+ end
+
+ config.stubs(:feedback_enabled).returns(false)
+ get root_path
+ assert_select "#cashflow-preview[data-sankey-preview-feedback-host-value='']"
+ assert_not_includes response.headers["Content-Security-Policy"], "posthog.com"
+ end
+ end
+
+ test "allows the analytics PostHog host only when analytics are enabled" do
+ config = Rails.configuration.x.posthog
+ config.stubs(:feedback_enabled).returns(false)
+ config.stubs(:host).returns("https://eu.i.posthog.com")
+ Rails.env.stubs(:production?).returns(true)
+
+ config.stubs(:api_key).returns(nil)
+ get new_session_url
+ assert_not_includes response.headers["Content-Security-Policy"], "posthog.com"
+
+ config.stubs(:api_key).returns("operator-owned-project")
+ get new_session_url
+ [ "script-src", "connect-src" ].each do |directive|
+ assert_includes csp_directive(directive), "https://eu.i.posthog.com"
+ assert_includes csp_directive(directive), "https://eu-assets.i.posthog.com"
+ end
+ end
+
+ test "adds no PostHog hosts outside production unless development opts in" do
+ config = Rails.configuration.x.posthog
+ config.stubs(:api_key).returns("operator-owned-project")
+ config.stubs(:feedback_enabled).returns(true)
+ config.stubs(:development_enabled).returns(false)
+
+ with_self_hosting do
+ get new_session_url
+ assert_not_includes response.headers["Content-Security-Policy"], "posthog.com"
+ end
+ end
+
+ test "sends the permissions policy as Permissions-Policy as well as Feature-Policy" do
+ get new_session_url
+
+ assert_includes response.headers["Feature-Policy"], "camera 'none'"
+ permissions = response.headers["Permissions-Policy"].split(", ")
+ %w[camera microphone geolocation usb payment fullscreen].each do |feature|
+ assert_includes permissions, "#{feature}=()"
+ end
+ end
+
+ test "allows a plain-http generic S3 endpoint for images" do
+ with_env_overrides(GENERIC_S3_ENDPOINT: "http://minio.local:9000", GENERIC_S3_BUCKET: "sure", GENERIC_S3_FORCE_PATH_STYLE: "true") do
+ get new_session_url
+ assert_includes csp_directive("img-src"), "http://minio.local:9000"
+ assert_not_includes csp_directive("img-src"), "http://sure.minio.local:9000"
+ end
+
+ with_env_overrides(GENERIC_S3_ENDPOINT: "http://minio.local:9000/", GENERIC_S3_BUCKET: "sure", GENERIC_S3_FORCE_PATH_STYLE: "false") do
+ get new_session_url
+ assert_includes csp_directive("img-src"), "http://minio.local:9000"
+ assert_includes csp_directive("img-src"), "http://sure.minio.local:9000"
+ end
+ end
+
+ test "adds no S3 image origin without a usable endpoint" do
+ [ nil, "", "minio.local" ].each do |endpoint|
+ with_env_overrides(GENERIC_S3_ENDPOINT: endpoint) do
+ get new_session_url
+ assert_equal %w['self' https: data: blob:], csp_directive("img-src")
+ end
+ end
+ end
+
+ test "reduces a PostHog host behind a reverse-proxy path to its origin" do
+ config = Rails.configuration.x.posthog
+ config.stubs(:feedback_enabled).returns(false)
+ config.stubs(:api_key).returns("operator-owned-project")
+ config.stubs(:host).returns("https://analytics.example.com/ingest")
+ Rails.env.stubs(:production?).returns(true)
+
+ get new_session_url
+ [ "script-src", "connect-src" ].each do |directive|
+ assert_includes csp_directive(directive), "https://analytics.example.com"
+ assert_not_includes response.headers["Content-Security-Policy"], "/ingest"
+ end
+ end
+
+ private
+ def csp_directive(name)
+ response.headers["Content-Security-Policy"][/#{name} ([^;]+)/, 1].to_s.split
+ end
+end
diff --git a/test/views/accounts/logo_view_test.rb b/test/views/accounts/logo_view_test.rb
index 02647f4dcb..d405d7aab3 100644
--- a/test/views/accounts/logo_view_test.rb
+++ b/test/views/accounts/logo_view_test.rb
@@ -10,11 +10,9 @@ class AccountsLogoViewTest < ActionView::TestCase
assert_select "span.relative" do
assert_select "div", text: @account.name.first
- assert_select "img[src='https://example.com/logo.png']" do |images|
- on_error = images.first["onerror"]
- assert on_error.end_with?(ProviderLogo::REMOVE_ON_ERROR), "the image removes itself"
- assert_includes on_error, "removeAttribute('data-turbo-permanent')", "a kept sidebar wrapper stops being kept"
- end
+ assert_select "img[src='https://example.com/logo.png'][data-controller='image-fallback'][data-action='error->image-fallback#remove']" \
+ "[data-image-fallback-retry-value='true'][data-image-fallback-release-permanent-value='true']"
+ assert_select "img[onerror]", count: 0
end
end