2018-11-30 22:51:45 +08:00
|
|
|
# frozen_string_literal: true
|
2022-03-21 22:28:52 +08:00
|
|
|
require 'content_security_policy/default'
|
2018-11-30 22:51:45 +08:00
|
|
|
|
|
|
|
class ContentSecurityPolicy
|
|
|
|
class Builder
|
|
|
|
EXTENDABLE_DIRECTIVES = %i[
|
2019-01-10 04:33:42 +08:00
|
|
|
base_uri
|
2021-06-08 02:59:15 +08:00
|
|
|
frame_ancestors
|
2021-06-08 21:32:31 +08:00
|
|
|
manifest_src
|
2019-01-10 04:33:42 +08:00
|
|
|
object_src
|
2018-11-30 22:51:45 +08:00
|
|
|
script_src
|
|
|
|
worker_src
|
|
|
|
].freeze
|
|
|
|
|
|
|
|
# Make extending these directives no-op, until core includes them in default CSP
|
|
|
|
TO_BE_EXTENDABLE = %i[
|
|
|
|
connect_src
|
|
|
|
default_src
|
|
|
|
font_src
|
|
|
|
form_action
|
|
|
|
frame_src
|
|
|
|
img_src
|
|
|
|
media_src
|
|
|
|
prefetch_src
|
|
|
|
style_src
|
|
|
|
].freeze
|
|
|
|
|
2020-03-20 03:54:42 +08:00
|
|
|
def initialize(base_url:)
|
|
|
|
@directives = Default.new(base_url: base_url).directives
|
2018-11-30 22:51:45 +08:00
|
|
|
end
|
|
|
|
|
|
|
|
def <<(extension)
|
|
|
|
return unless valid_extension?(extension)
|
|
|
|
|
|
|
|
extension.each { |directive, sources| extend_directive(normalize(directive), sources) }
|
|
|
|
end
|
|
|
|
|
|
|
|
def build
|
|
|
|
policy = ActionDispatch::ContentSecurityPolicy.new
|
|
|
|
|
|
|
|
@directives.each do |directive, sources|
|
|
|
|
if sources.is_a?(Array)
|
|
|
|
policy.public_send(directive, *sources)
|
|
|
|
else
|
|
|
|
policy.public_send(directive, sources)
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
policy.build
|
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
|
|
|
|
def normalize(directive)
|
|
|
|
directive.to_s.gsub('-', '_').to_sym
|
|
|
|
end
|
|
|
|
|
|
|
|
def extend_directive(directive, sources)
|
|
|
|
return unless extendable?(directive)
|
|
|
|
|
|
|
|
@directives[directive] ||= []
|
|
|
|
|
|
|
|
if sources.is_a?(Array)
|
|
|
|
@directives[directive].concat(sources)
|
|
|
|
else
|
|
|
|
@directives[directive] << sources
|
|
|
|
end
|
2019-01-10 04:33:42 +08:00
|
|
|
|
|
|
|
@directives[directive].delete(:none) if @directives[directive].count > 1
|
2018-11-30 22:51:45 +08:00
|
|
|
end
|
|
|
|
|
|
|
|
def extendable?(directive)
|
|
|
|
EXTENDABLE_DIRECTIVES.include?(directive)
|
|
|
|
end
|
|
|
|
|
|
|
|
def valid_extension?(extension)
|
|
|
|
extension.is_a?(Hash)
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|