-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsecure_headers.rb
More file actions
57 lines (46 loc) · 1.43 KB
/
secure_headers.rb
File metadata and controls
57 lines (46 loc) · 1.43 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# frozen_string_literal: true
# https://github.com/frodsan/rack-secure_headers
require "rack"
module Rack
class SecureHeaders
DEFAULTS = {
hsts: { max_age: "31536000", include_subdomains: true },
x_content_type_options: "nosniff",
x_frame_options: "SAMEORIGIN",
x_permitted_cross_domain_policies: "none",
x_xss_protection: "1; mode=block",
}.freeze
def initialize(app, options = {})
options = DEFAULTS.merge(options)
@app = app
@headers = base_headers(options)
if options[:hsts]
@headers["Strict-Transport-Security"] = hsts_header(options[:hsts])
end
end
def call(env)
@app.call(env).tap do |_, headers, _|
@headers.each do |key, value|
headers[key] ||= value
end
end
end
private
def base_headers(options)
headers = {
"X-Content-Type-Options" => options[:x_content_type_options],
"X-Frame-Options" => options[:x_frame_options],
"X-Permitted-Cross-Domain-Policies" => options[:x_permitted_cross_domain_policies],
"X-XSS-Protection" => options[:x_xss_protection],
}
headers.reject! { |_, v| v.nil? }
headers
end
def hsts_header(options)
header = sprintf("max-age=%s", options.fetch(:max_age))
header << "; includeSubdomains" if options[:include_subdomains]
header << "; preload" if options[:preload]
header
end
end
end