Class: Rack::ContentSecurityPolicy

Inherits:
Object
  • Object
show all
Includes:
Contracts::Builtin, Contracts::Core
Defined in:
lib/rack/content_security_policy.rb,
lib/rack/content_security_policy/version.rb,
lib/rack/content_security_policy/contracts.rb

Defined Under Namespace

Classes: DirectiveKey, DirectiveVal, Directives, RackResponse

Constant Summary collapse

CSP_HEADER =
'Content-Security-Policy'.freeze
CSP_REPORT_ONLY_HEADER =
'Content-Security-Policy-Report-Only'.freeze
NO_ARG_DIRECTIVES =
['block-all-mixed-content',
'disown-opener',
'upgrade-insecure-requests'].freeze
VERSION =
'0.1.2'.freeze

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(app, directives: {}, report_only: false) ⇒ ContentSecurityPolicy

Returns a new instance of ContentSecurityPolicy.



16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/rack/content_security_policy.rb', line 16

def initialize(app, directives: {}, report_only: false)
  @app = app

  class_dirs = Rack::ContentSecurityPolicy.directives
  if directives.empty? && class_dirs.empty?
    raise ArgumentError, 'no directives provided'
  end
  @directives = class_dirs.merge(directives)

  class_report_only = Rack::ContentSecurityPolicy.report_only
  @report_only = report_only || class_report_only ? true : false
end

Class Method Details

.[]=(name, value) ⇒ Object



88
89
90
# File 'lib/rack/content_security_policy.rb', line 88

def self.[]=(name, value)
  @directives[name] = value
end

.configure {|_self| ... } ⇒ Object

Yields:

  • (_self)

Yield Parameters:



82
83
84
85
# File 'lib/rack/content_security_policy.rb', line 82

def self.configure
  @directives ||= {}
  yield(self)
end

.directivesObject



77
78
79
# File 'lib/rack/content_security_policy.rb', line 77

def self.directives
  @directives
end

.report_onlyObject



72
73
74
# File 'lib/rack/content_security_policy.rb', line 72

def self.report_only
  @report_only
end

.report_only=(ro) ⇒ Object



67
68
69
# File 'lib/rack/content_security_policy.rb', line 67

def self.report_only=(ro)
  @report_only = ro
end

Instance Method Details

#_call(env) ⇒ Object



45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/rack/content_security_policy.rb', line 45

def _call(env)
  status, headers, response = @app.call(env)

  directives = @directives.sort.map do |d|
    if NO_ARG_DIRECTIVES.include?(d[0])
      d[0]
    else
      "#{d[0]} #{d[1]}"
    end
  end.join('; ')

  csp_hdr = @report_only ? CSP_REPORT_ONLY_HEADER : CSP_HEADER
  headers[csp_hdr] = directives

  [status, headers, response]
end

#call(env) ⇒ Object



40
41
42
# File 'lib/rack/content_security_policy.rb', line 40

def call(env)
  dup._call(env)
end

#directivesObject



35
36
37
# File 'lib/rack/content_security_policy.rb', line 35

def directives
  @directives
end

#report_onlyObject



30
31
32
# File 'lib/rack/content_security_policy.rb', line 30

def report_only
  @report_only
end