You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

61 lines
2.4 KiB

  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, 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.child_src :self, :blob, assets_host
  29. p.worker_src :self, :blob, assets_host
  30. else
  31. p.connect_src :self, :data, :blob, assets_host, media_host, Rails.configuration.x.streaming_api_base_url
  32. p.script_src :self, assets_host
  33. p.child_src :self, :blob, assets_host
  34. p.worker_src :self, :blob, assets_host
  35. end
  36. end
  37. # Report CSP violations to a specified URI
  38. # For further information see the following documentation:
  39. # https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy-Report-Only
  40. # Rails.application.config.content_security_policy_report_only = true
  41. Rails.application.config.content_security_policy_nonce_generator = -> request { SecureRandom.base64(16) }
  42. Rails.application.config.content_security_policy_nonce_directives = %w(style-src)
  43. PgHero::HomeController.content_security_policy do |p|
  44. p.script_src :self, :unsafe_inline, assets_host
  45. p.style_src :self, :unsafe_inline, assets_host
  46. end
  47. PgHero::HomeController.after_action do
  48. request.content_security_policy_nonce_generator = nil
  49. end