Class: CSPMaker::Middleware

Inherits:
Object
  • Object
show all
Defined in:
lib/csp_maker/rack.rb

Constant Summary collapse

CONTENT_SECURITY_POLICY =
"content-security-policy"
CONTENT_SECURITY_POLICY_REPORT_ONLY =
"content-security-policy-report-only"
NONCE_ENV_KEY =
"csp_maker.nonce"

Instance Method Summary collapse

Constructor Details

#initialize(app, policy, report_only: CSPMaker.report_only, nonce_generator: CSPMaker.nonce_generator, nonce_directives: CSPMaker.nonce_directives) ⇒ Middleware

Returns a new instance of Middleware.



10
11
12
13
14
15
16
17
18
19
20
# File 'lib/csp_maker/rack.rb', line 10

def initialize(app, policy,
  report_only: CSPMaker.report_only,
  nonce_generator: CSPMaker.nonce_generator,
  nonce_directives: CSPMaker.nonce_directives)

  @app = app
  @policy = policy
  @report_only = report_only
  @nonce_generator = nonce_generator
  @nonce_directives = nonce_directives
end

Instance Method Details

#call(env) ⇒ Object



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/csp_maker/rack.rb', line 22

def call(env)
  nonce = make_nonce(env) if @nonce_generator
  
  status, headers, _ = response = @app.call(env)

  # Returning CSP headers with a 304 Not Modified is harmful, since nonces in the
  # new CSP headers might not match nonces in the cached HTML.
  return response if status == 304

  return response if policy_present?(headers)

  request = Rack::Request.new(env)
  headers[header_name] = @policy.build(request, nonce, @nonce_directives)

  response
end