From 5f4643b895191ecc8ad8136008e0a0b33f88851c Mon Sep 17 00:00:00 2001 From: Claire Date: Fri, 5 Jan 2024 11:45:36 +0100 Subject: [PATCH] Add `PAPERCLIP_ROOT_URL` to Content-Security-Policy when used (#28561) --- app/lib/content_security_policy.rb | 11 ++++++++++- spec/lib/content_security_policy_spec.rb | 12 ++++++++++++ 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/app/lib/content_security_policy.rb b/app/lib/content_security_policy.rb index 966e41f03b..210f37cea0 100644 --- a/app/lib/content_security_policy.rb +++ b/app/lib/content_security_policy.rb @@ -10,7 +10,7 @@ class ContentSecurityPolicy end def media_hosts - [assets_host, cdn_host_value].compact + [assets_host, cdn_host_value, paperclip_root_url].compact end private @@ -23,6 +23,15 @@ class ContentSecurityPolicy s3_alias_host || s3_cloudfront_host || azure_alias_host || s3_hostname_host end + def paperclip_root_url + root_url = ENV.fetch('PAPERCLIP_ROOT_URL', nil) + return if root_url.blank? + + (Addressable::URI.parse(assets_host) + root_url).tap do |uri| + uri.path += '/' unless uri.path.blank? || uri.path.end_with?('/') + end.to_s + end + def url_from_base_host host_to_url(base_host) end diff --git a/spec/lib/content_security_policy_spec.rb b/spec/lib/content_security_policy_spec.rb index 4286f14980..27a3e80257 100644 --- a/spec/lib/content_security_policy_spec.rb +++ b/spec/lib/content_security_policy_spec.rb @@ -125,5 +125,17 @@ describe ContentSecurityPolicy do expect(subject.media_hosts).to contain_exactly(subject.assets_host, 'https://asset-host.s3.example') end end + + context 'when PAPERCLIP_ROOT_URL is configured' do + around do |example| + ClimateControl.modify PAPERCLIP_ROOT_URL: 'https://paperclip-host.example' do + example.run + end + end + + it 'uses the provided URL in the content security policy' do + expect(subject.media_hosts).to contain_exactly(subject.assets_host, 'https://paperclip-host.example') + end + end end end