|
| 1 | +# frozen_string_literal: true |
| 2 | + |
| 3 | +module Alchemy |
| 4 | + module Admin |
| 5 | + # The Content Security Policy Alchemy applies to its own admin responses. |
| 6 | + # |
| 7 | + # Configured by default. Set it to nil to send no policy at all: |
| 8 | + # |
| 9 | + # Alchemy.config.admin_content_security_policy = nil |
| 10 | + # |
| 11 | + # 'self' follows the origin the admin is served from, so mounting it under |
| 12 | + # its own subdomain through +Alchemy.admin_constraints+ needs no extra |
| 13 | + # configuration. The page preview is same origin as well, because it falls |
| 14 | + # back to an admin path, unless a preview host is configured, in which case |
| 15 | + # that host is added to +frame-src+. |
| 16 | + # |
| 17 | + # Assets your application adds through +admin_stylesheets+ or through |
| 18 | + # +Alchemy.importmap+ are picked up automatically, so a module pinned to a |
| 19 | + # CDN does not need any extra configuration. Subclass to allow anything |
| 20 | + # else, and configure the subclass instead: |
| 21 | + # |
| 22 | + # class AdminContentSecurityPolicy < Alchemy::Admin::ContentSecurityPolicy |
| 23 | + # def call |
| 24 | + # super.tap do |policy| |
| 25 | + # policy.connect_src(*policy.directives["connect-src"], "https://api.example.com") |
| 26 | + # end |
| 27 | + # end |
| 28 | + # end |
| 29 | + # |
| 30 | + class ContentSecurityPolicy |
| 31 | + class InvalidSourceError < StandardError; end |
| 32 | + |
| 33 | + # Rails calls an asset host proc with the asset source, so we need one to |
| 34 | + # evaluate it with. Any source resolves to the same origin unless the |
| 35 | + # host shards, which the %d form covers separately. |
| 36 | + ASSET_SOURCE = "/" |
| 37 | + |
| 38 | + def initialize(request = nil) |
| 39 | + @request = request |
| 40 | + end |
| 41 | + |
| 42 | + attr_reader :request |
| 43 | + # Send the policy as Content-Security-Policy-Report-Only, which reports |
| 44 | + # violations to the browser console and to +report_uri+ without blocking |
| 45 | + # anything. Worth running first, to find what a policy would break. |
| 46 | + def report_only? = false |
| 47 | + |
| 48 | + # Authorizes the inline scripts Alchemy renders. It has to be |
| 49 | + # unguessable, otherwise injected markup could carry a valid nonce. |
| 50 | + def nonce_generator = ->(_request) { SecureRandom.base64(16) } |
| 51 | + |
| 52 | + def call |
| 53 | + ActionDispatch::ContentSecurityPolicy.new do |policy| |
| 54 | + policy.default_src :self |
| 55 | + # script-src and style-src have to be named explicitly, because Rails |
| 56 | + # only appends the nonce to directives the policy actually declares. |
| 57 | + policy.script_src :self, *asset_hosts, *importmap_origins |
| 58 | + policy.style_src :self, *asset_hosts, *admin_stylesheet_origins |
| 59 | + # Inline style attributes cannot carry a nonce. Turbo sets them for |
| 60 | + # its progress bar, and so do several of our bundled dependencies. |
| 61 | + policy.style_src_attr :unsafe_inline |
| 62 | + policy.img_src :self, :data, :blob, *asset_hosts |
| 63 | + policy.font_src :self, :data, *asset_hosts |
| 64 | + policy.media_src :self, :blob, *asset_hosts |
| 65 | + policy.connect_src :self, *asset_hosts |
| 66 | + policy.frame_src :self, *preview_hosts |
| 67 | + policy.object_src :none |
| 68 | + policy.base_uri :self |
| 69 | + policy.form_action :self |
| 70 | + # An endpoint of your own that the browser POSTs a JSON report to |
| 71 | + # whenever it blocks something: |
| 72 | + # |
| 73 | + # policy.report_uri "/csp-violation-reports" |
| 74 | + end |
| 75 | + end |
| 76 | + |
| 77 | + private |
| 78 | + |
| 79 | + def asset_hosts |
| 80 | + host = ActionController::Base.asset_host |
| 81 | + return [] if host.blank? |
| 82 | + |
| 83 | + hosts = if host.respond_to?(:call) |
| 84 | + [call_asset_host(host)] |
| 85 | + elsif host.include?("%d") |
| 86 | + # Rails shards these over four hosts. |
| 87 | + 4.times.map { host % _1 } |
| 88 | + else |
| 89 | + [host] |
| 90 | + end |
| 91 | + hosts.filter_map { origin(_1) }.uniq |
| 92 | + end |
| 93 | + |
| 94 | + def call_asset_host(host) |
| 95 | + arity = host.respond_to?(:arity) ? host.arity : host.method(:call).arity |
| 96 | + args = [ASSET_SOURCE] |
| 97 | + args << request if request && (arity > 1 || arity < 0) |
| 98 | + host.call(*args) |
| 99 | + end |
| 100 | + |
| 101 | + # Modules can be pinned to a CDN, in which case the pin holds an absolute |
| 102 | + # URL instead of an asset name. |
| 103 | + def importmap_origins |
| 104 | + Alchemy.importmap.packages.values.filter_map { origin(_1.path) }.uniq |
| 105 | + end |
| 106 | + |
| 107 | + # Admin stylesheets are usually asset names, but an absolute URL is |
| 108 | + # allowed here too. |
| 109 | + def admin_stylesheet_origins |
| 110 | + Alchemy.config.admin_stylesheets.filter_map { origin(_1) }.uniq |
| 111 | + end |
| 112 | + |
| 113 | + # A CSP source is an origin, so anything with a host contributes one and |
| 114 | + # everything else (asset names, module specifiers) is same origin already. |
| 115 | + def origin(url) |
| 116 | + uri = URI.parse(url.to_s) |
| 117 | + return nil unless uri.host |
| 118 | + |
| 119 | + port = ":#{uri.port}" if uri.port && uri.port != uri.default_port |
| 120 | + "#{uri.scheme ? "#{uri.scheme}://" : "//"}#{uri.host}#{port}" |
| 121 | + rescue URI::InvalidURIError => error |
| 122 | + raise InvalidSourceError, "Cannot build a Content Security Policy source from " \ |
| 123 | + "#{url.inspect} (#{error.message}). It came from your asset host, your " \ |
| 124 | + "admin stylesheets, an importmap pin or a preview host." |
| 125 | + end |
| 126 | + |
| 127 | + # The page editor renders the frontend of the application in an iframe, |
| 128 | + # which is a different host whenever a preview host is configured. |
| 129 | + def preview_hosts |
| 130 | + preview = Alchemy.config.preview |
| 131 | + ([preview.host] + preview.per_site_configs.map(&:host)).filter_map { origin(_1) }.uniq |
| 132 | + end |
| 133 | + end |
| 134 | + end |
| 135 | +end |
0 commit comments