Module: CSPMaker

Defined in:
lib/csp_maker/csp.rb,
lib/csp_maker.rb,
lib/csp_maker/rack.rb,
lib/csp_maker/version.rb

Overview

Configures the HTTP Content-Security-Policy response header to help protect against XSS and injection attacks.

Example global policy:

CSPMaker.build_policy do |policy|
  policy.default_src :self, :https
  policy.font_src    :self, :https, :data
  policy.img_src     :self, :https, :data
  policy.object_src  :none
  policy.script_src  :self, :https
  policy.style_src   :self, :https

  # Specify URI for violation reports
  policy.report_uri "/csp-violation-report-endpoint"
end

Defined Under Namespace

Classes: ContentSecurityPolicy, InvalidDirectiveError, Middleware

Constant Summary collapse

VERSION =
'0.1.0'

Class Attribute Summary collapse

Class Method Summary collapse

Class Attribute Details

.nonce_directivesObject

Returns the value of attribute nonce_directives.



10
11
12
# File 'lib/csp_maker.rb', line 10

def nonce_directives
  @nonce_directives
end

.nonce_generatorObject

Returns the value of attribute nonce_generator.



10
11
12
# File 'lib/csp_maker.rb', line 10

def nonce_generator
  @nonce_generator
end

.report_onlyObject

Returns the value of attribute report_only.



10
11
12
# File 'lib/csp_maker.rb', line 10

def report_only
  @report_only
end

Class Method Details

.build_policy(context = nil, &block) ⇒ Object

Raises:

  • (ArgumentError)


12
13
14
15
16
17
# File 'lib/csp_maker.rb', line 12

def build_policy(context = nil, &block)
  raise ArgumentError, "block required" unless block_given?

  policy = define_policy(&block)
  policy.build(context)
end

.default_generatorObject



33
34
35
# File 'lib/csp_maker.rb', line 33

def default_generator
  proc { SecureRandom.base64(16) }
end

.define_policy(&block) ⇒ Object

Raises:

  • (ArgumentError)


19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/csp_maker.rb', line 19

def define_policy(&block)
  raise ArgumentError, "block required" unless block_given?

  policy = ContentSecurityPolicy.new

  if block.parameters.empty?
    policy.instance_eval(&block)
  else
    block.call(policy)
  end

  policy
end

.make_nonceObject



37
38
39
# File 'lib/csp_maker.rb', line 37

def make_nonce
  nonce_generator.call
end