class CspBuilder
Content Security Policy builder class. This class provides a lot of methods for making it easier to compose Content Security Policies for your web applications.
@example Creating a CSP string
csp = CspBuilder.new. script_src("https://*.cloudfront.net", :self). style_src("https://*.cloudfront.net"). img_src('*'). frame_ancestors(:self). upgrade_insecure_requests # Get the compiled CSP string: # "script-src https://*.cloudfront.net 'self'; style-src https://*.cloudfront.net; img-src *; frame-ancestors 'self'; upgrade-insecure-requests" csp.compile!
Constants
- FETCH_DIRECTIVES
Fetch directive define the locations where various resource types can be loaded from. These directive all end in with “-src”
- META_DIRECTIVES
Meta directives do not require a value and can be used in a <meta> tag in the document's <head>
- VALUE_DIRECTIVES
Value directives are either document, navigation, reporting or other type of directives that require a value
- VERSION
Attributes
Final result string. This is set by compile!
Public Class Methods
Returns a new instance of CspBuilder
# File lib/csp_builder.rb, line 24 def initialize @directives = {} @result = nil end
Public Instance Methods
Compile Content Security Policy with all of the defined directives @return [String] compiled CSP string
# File lib/csp_builder.rb, line 37 def compile! @directives.freeze unless @directives.frozen? @result ||= compile.freeze end
Returns whether the result has been compiled or not @return [Boolean]
# File lib/csp_builder.rb, line 31 def compiled? !@result.nil? end
Protected Instance Methods
# File lib/csp_builder.rb, line 120 def reset! @directives = @directives.dup @result = nil end
Private Instance Methods
@private
# File lib/csp_builder.rb, line 132 def compile @directives.map { |key, val| META_DIRECTIVES.include?(key) ? key.to_s : "#{key} #{val}" }.join('; ') end
# File lib/csp_builder.rb, line 127 def initialize_dup(source) super.reset! end
@private
# File lib/csp_builder.rb, line 139 def set_directive!(key, value) if Symbol === value value = "'#{value}'" else value = value.to_s.dup end if @directives.has_key? key @directives[key] << " " @directives[key] << value else @directives[key] = value end end