Skip to content

Commit 8a677df

Browse files
committed
add ability to import a policy from json
1 parent 66c2b26 commit 8a677df

File tree

2 files changed

+22
-2
lines changed

2 files changed

+22
-2
lines changed

lib/secure_headers/headers/content_security_policy.rb

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -169,7 +169,17 @@ def value
169169

170170
def to_json
171171
build_value
172-
@config.to_json
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
173183
end
174184

175185
private

spec/lib/secure_headers/headers/content_security_policy_spec.rb

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,17 @@ def request_for user_agent, request_uri=nil, options={:ssl => false}
5858

5959
it "exports a policy to JSON" do
6060
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:"]})
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'","https:","about:"],"img-src":["https:","data:"]})
68+
config = ContentSecurityPolicy.from_json(json1, json2)
69+
policy = ContentSecurityPolicy.new(config.merge(:disable_fill_missing => true))
70+
71+
expected = %({"default-src":["https:"],"script-src":["'unsafe-inline'","'unsafe-eval'","https:","data:"],"style-src":["'unsafe-inline'","https:","about:"],"img-src":["https:","data:"]})
6272
expect(policy.to_json).to eq(expected)
6373
end
6474

0 commit comments

Comments
 (0)