class Hanami::Config::Actions::ContentSecurityPolicy

Config for Content Security Policy in Hanami apps

@since 2.0.0

Public Class Methods

new(&blk) click to toggle source

@since 2.0.0 @api private

# File lib/hanami/config/actions/content_security_policy.rb, line 12
def initialize(&blk)
  @policy = {
    base_uri: "'self'",
    child_src: "'self'",
    connect_src: "'self'",
    default_src: "'none'",
    font_src: "'self'",
    form_action: "'self'",
    frame_ancestors: "'self'",
    frame_src: "'self'",
    img_src: "'self' https: data:",
    media_src: "'self'",
    object_src: "'none'",
    script_src: "'self'",
    style_src: "'self' 'unsafe-inline' https:"
  }

  blk&.(self)
end

Public Instance Methods

[](key) click to toggle source

Get a CSP setting

@param key [Symbol] the underscored name of the CPS setting @return [String,NilClass] the CSP setting, if any

@since 2.0.0 @api public

@example

module MyApp
  class App < Hanami::App
    config.actions.content_security_policy[:base_uri] # => "'self'"
  end
end
# File lib/hanami/config/actions/content_security_policy.rb, line 53
def [](key)
  @policy[key]
end
[]=(key, value) click to toggle source

Set a CSP setting

@param key [Symbol] the underscored name of the CPS setting @param value [String] the CSP setting value

@since 2.0.0 @api public

@example Replace a default value

module MyApp
  class App < Hanami::App
    config.actions.content_security_policy[:plugin_types] = nil
  end
end

@example Append to a default value

module MyApp
  class App < Hanami::App
    config.actions.content_security_policy[:script_src] += " https://my.cdn.test"
  end
end
# File lib/hanami/config/actions/content_security_policy.rb, line 78
def []=(key, value)
  @policy[key] = value
end
delete(key) click to toggle source

Deletes a CSP key

@param key [Symbol] the underscored name of the CPS setting

@since 2.0.0 @api public

@example

module MyApp
  class App < Hanami::App
    config.actions.content_security_policy.delete(:object_src)
  end
end
# File lib/hanami/config/actions/content_security_policy.rb, line 95
def delete(key)
  @policy.delete(key)
end
initialize_copy(original_object) click to toggle source

@since 2.0.0 @api private

Calls superclass method
# File lib/hanami/config/actions/content_security_policy.rb, line 34
def initialize_copy(original_object)
  @policy = original_object.instance_variable_get(:@policy).dup
  super
end
to_s() click to toggle source

@since 2.0.0 @api private

# File lib/hanami/config/actions/content_security_policy.rb, line 101
def to_s
  @policy.map do |key, value|
    "#{dasherize(key)} #{value}"
  end.join(";")
end

Private Instance Methods

dasherize(key) click to toggle source

@since 2.0.0 @api private

# File lib/hanami/config/actions/content_security_policy.rb, line 111
def dasherize(key)
  key.to_s.gsub("_", "-")
end