Skip to content

A platform for community discussion. Free, open, simple.

DEV: Support passing relative URLs CSP builder (#19176)

David Taylor174a8b431bd2
diff --git a/lib/content_security_policy/builder.rb b/lib/content_security_policy/builder.rb
index af240829ba8..4f5dbfb9133 100644
--- a/lib/content_security_policy/builder.rb
+++ b/lib/content_security_policy/builder.rb
@@ -27,12 +27,13 @@ class ContentSecurityPolicy
def initialize(base_url:)
@directives = Default.new(base_url: base_url).directives
+ @base_url = base_url
end
def <<(extension)
return unless valid_extension?(extension)
- extension.each { |directive, sources| extend_directive(normalize(directive), sources) }
+ extension.each { |directive, sources| extend_directive(normalize_directive(directive), sources) }
end
def build
@@ -51,20 +52,27 @@ class ContentSecurityPolicy
private
- def normalize(directive)
+ def normalize_directive(directive)
directive.to_s.gsub('-', '_').to_sym
end
+ def normalize_source(source)
+ if source.starts_with?("/")
+ "#{@base_url}#{source}"
+ else
+ source
+ end
+ rescue URI::ParseError
+ source
+ 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
+ sources = Array(sources).map { |s| normalize_source(s) }
+ @directives[directive].concat(sources)
@directives[directive].delete(:none) if @directives[directive].count > 1
end
diff --git a/spec/fixtures/plugins/csp_extension/plugin.rb b/spec/fixtures/plugins/csp_extension/plugin.rb
index 71625d3b813..e694598c4a1 100644
--- a/spec/fixtures/plugins/csp_extension/plugin.rb
+++ b/spec/fixtures/plugins/csp_extension/plugin.rb
@@ -6,7 +6,7 @@
# authors: xrav3nz
extend_content_security_policy(
- script_src: ['https://from-plugin.com'],
+ script_src: ['https://from-plugin.com', '/local/path'],
object_src: ['https://test-stripping.com'],
frame_ancestors: ['https://frame-ancestors-plugin.ext'],
manifest_src: ['https://manifest-src.com']
diff --git a/spec/lib/content_security_policy_spec.rb b/spec/lib/content_security_policy_spec.rb
index 504b2cdf3d9..8fba63c1f74 100644
--- a/spec/lib/content_security_policy_spec.rb
+++ b/spec/lib/content_security_policy_spec.rb
@@ -222,6 +222,7 @@ RSpec.describe ContentSecurityPolicy do
plugin.enabled = true
expect(parse(policy)['script-src']).to include('https://from-plugin.com')
+ expect(parse(policy)['script-src']).to include('http://test.localhost/local/path')
expect(parse(policy)['object-src']).to include('https://test-stripping.com')
expect(parse(policy)['object-src']).to_not include("'none'")
expect(parse(policy)['manifest-src']).to include("'self'")