Skip to content

Commit a2664d3

Browse files
committed
Merge pull request #163 from twitter/json-csp
JSON representation of content security policies
2 parents 7b42451 + 8a77f47 commit a2664d3

File tree

3 files changed

+33
-1
lines changed

3 files changed

+33
-1
lines changed

.travis.yml

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@ rvm:
44
- "2.1"
55
- "2.0.0"
66
- "1.9.3"
7-
- "1.8.7"
87
- "jruby-19mode"
98

109
sudo: false

lib/secure_headers/headers/content_security_policy.rb

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
require 'base64'
33
require 'securerandom'
44
require 'user_agent_parser'
5+
require 'json'
56

67
module SecureHeaders
78
class ContentSecurityPolicyBuildError < StandardError; end
@@ -166,6 +167,21 @@ def value
166167
end
167168
end
168169

170+
def to_json
171+
build_value
172+
@config.to_json.gsub(/(\w+)_src/, "\\1-src")
173+
end
174+
175+
def self.from_json(*json_configs)
176+
json_configs.inject({}) do |combined_config, one_config|
177+
one_config = one_config.gsub(/(\w+)-src/, "\\1_src")
178+
config = JSON.parse(one_config, :symbolize_names => true)
179+
combined_config.merge(config) do |_, lhs, rhs|
180+
lhs | rhs
181+
end
182+
end
183+
end
184+
169185
private
170186

171187
def add_script_hashes

spec/lib/secure_headers/headers/content_security_policy_spec.rb

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,23 @@ def request_for user_agent, request_uri=nil, options={:ssl => false}
5656
end
5757
end
5858

59+
it "exports a policy to JSON" do
60+
policy = ContentSecurityPolicy.new(default_opts)
61+
expected = %({"default-src":["https:"],"script-src":["'unsafe-inline'","'unsafe-eval'","https:","data:"],"style-src":["'unsafe-inline'","https:","about:"],"img-src":["https:","data:"]})
62+
expect(policy.to_json).to eq(expected)
63+
end
64+
65+
it "imports JSON to build a policy" do
66+
json1 = %({"default-src":["https:"],"script-src":["'unsafe-inline'","'unsafe-eval'","https:","data:"]})
67+
json2 = %({"style-src":["'unsafe-inline'"],"img-src":["https:","data:"]})
68+
json3 = %({"style-src":["https:","about:"]})
69+
config = ContentSecurityPolicy.from_json(json1, json2, json3)
70+
policy = ContentSecurityPolicy.new(config.merge(:disable_fill_missing => true))
71+
72+
expected = %({"default-src":["https:"],"script-src":["'unsafe-inline'","'unsafe-eval'","https:","data:"],"style-src":["'unsafe-inline'","https:","about:"],"img-src":["https:","data:"]})
73+
expect(policy.to_json).to eq(expected)
74+
end
75+
5976
context "when using hash sources" do
6077
it "adds hashes and unsafe-inline to the script-src" do
6178
policy = ContentSecurityPolicy.new(default_opts.merge(:script_hashes => ['sha256-abc123']))

0 commit comments

Comments
 (0)