Class: Hanami::Middleware::ContentSecurityPolicyNonce Private

Inherits:
Object
  • Object
show all
Defined in:
lib/hanami/middleware/content_security_policy_nonce.rb

Overview

This class is part of a private API. You should avoid using this class if possible, as it may be removed or be changed in the future.

Generates a random per request nonce value like ‘mSMnSwfVZVe+LyQy1SPCGw==`, stores it as `“hanami.content_security_policy_nonce”` in the Rack environment, and replaces all occurrences of `’nonce’‘ in the `Content-Security-Policy header with the actual nonce value for the request, e.g. `’nonce-mSMnSwfVZVe+LyQy1SPCGw==‘`.

See Also:

Since:

  • 2.3.0

Instance Method Summary collapse

Constructor Details

#initialize(app) ⇒ ContentSecurityPolicyNonce

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Returns a new instance of ContentSecurityPolicyNonce.

Since:

  • 2.3.0



21
22
23
# File 'lib/hanami/middleware/content_security_policy_nonce.rb', line 21

def initialize(app)
  @app = app
end

Instance Method Details

#call(env) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Since:

  • 2.3.0



27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/hanami/middleware/content_security_policy_nonce.rb', line 27

def call(env)
  return @app.call(env) unless Hanami.app.config.actions.content_security_policy?

  args = nonce_generator.arity == 1 ? [Rack::Request.new(env)] : []
  request_nonce = nonce_generator.call(*args)

  env[CONTENT_SECURITY_POLICY_NONCE_REQUEST_KEY] = request_nonce

  _, headers, _ = response = @app.call(env)

  headers["Content-Security-Policy"] = sub_nonce(headers["Content-Security-Policy"], request_nonce)

  response
end