content_security_policy.rb 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. # Define an application-wide content security policy
  2. # For further information see the following documentation
  3. # https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy
  4. def host_to_url(str)
  5. "http#{Rails.configuration.x.use_https ? 's' : ''}://#{str}" unless str.blank?
  6. end
  7. base_host = Rails.configuration.x.web_domain
  8. assets_host = Rails.configuration.action_controller.asset_host
  9. assets_host ||= host_to_url(base_host)
  10. media_host = host_to_url(ENV['S3_ALIAS_HOST'])
  11. media_host ||= host_to_url(ENV['S3_CLOUDFRONT_HOST'])
  12. media_host ||= host_to_url(ENV['S3_HOSTNAME']) if ENV['S3_ENABLED'] == 'true'
  13. media_host ||= assets_host
  14. Rails.application.config.content_security_policy do |p|
  15. p.base_uri :none
  16. p.default_src :none
  17. p.frame_ancestors :none
  18. p.font_src :self, assets_host
  19. p.img_src :self, :https, :data, :blob, assets_host
  20. p.style_src :self, :unsafe_inline, assets_host
  21. p.media_src :self, :https, :data, assets_host
  22. p.frame_src :self, :https
  23. p.manifest_src :self, assets_host
  24. if Rails.env.development?
  25. webpacker_urls = %w(ws http).map { |protocol| "#{protocol}#{Webpacker.dev_server.https? ? 's' : ''}://#{Webpacker.dev_server.host_with_port}" }
  26. p.connect_src :self, :data, :blob, assets_host, media_host, Rails.configuration.x.streaming_api_base_url, *webpacker_urls
  27. p.script_src :self, :unsafe_inline, :unsafe_eval, assets_host
  28. p.worker_src :self, :blob, assets_host
  29. else
  30. p.connect_src :self, :data, :blob, assets_host, media_host, Rails.configuration.x.streaming_api_base_url
  31. p.script_src :self, assets_host
  32. p.worker_src :self, :blob, assets_host
  33. end
  34. end
  35. # Report CSP violations to a specified URI
  36. # For further information see the following documentation:
  37. # https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy-Report-Only
  38. # Rails.application.config.content_security_policy_report_only = true