Skip to content

Commit

Permalink
Add parse function
Browse files Browse the repository at this point in the history
  • Loading branch information
egs33 committed Dec 18, 2020
1 parent d76f48f commit b9154be
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 0 deletions.
19 changes: 19 additions & 0 deletions src/ring_middleware_csp/core.clj
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,25 @@
(map (fn [[d v]] (str (name d) " " (value->str v nonce))))
(str/join ";"))))

(defn parse
"Make policy map from CSP header string value"
[policy-str]
(->> (str/split policy-str #";")
(map (fn [v]
(let [[name & values] (str/split v #" +")
values (map #(cond
(str/starts-with? % "'nonce-")
:nonce

(str/starts-with? % "'")
(keyword (subs % 1 (dec (count %))))

:else
%)
values)]
[(keyword name) values])))
(into {})))

(def ^:private make-template
(memoize (fn [policy]
(let [nonce-placeholder ";%NONCE%;"
Expand Down
20 changes: 20 additions & 0 deletions test/ring_middleware_csp/core_test.clj
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,26 @@
:style-src :nonce}
"abcdefg")))))

(deftest parse-test
(testing "without nonce"
(is (= {:default-src [:self]} (parse "default-src 'self'")))
(is (= {:default-src [:self]} (parse "default-src 'self'")))
(is (= {:default-src [:self "https://example.com"]
:connect-src [:none]
:script-src [:self "https://script.example.com"]
:style-src [:unsafe-inline "https://style.example.com"]}
(parse "default-src 'self' https://example.com;connect-src 'none';script-src 'self' https://script.example.com;style-src 'unsafe-inline' https://style.example.com")))
(is (= {:script-src [:self]
:report-uri ["/csp-report-path"]
:report-to ["csp-endpoint"]}
(parse "script-src 'self';report-uri /csp-report-path;report-to csp-endpoint"))))
(testing "with nonce"
(is (= {:script-src [:self :nonce]}
(parse "script-src 'self' 'nonce-abcdefg'")))
(is (= {:script-src [:self :nonce]
:style-src [:nonce]}
(parse "script-src 'self' 'nonce-abcdefg';style-src 'nonce-abcdefg'")))))

(deftest wrap-csp-test
(let [handler (constantly {:status 200 :headers {} :body ""})]
(is (= "default-src 'self'"
Expand Down

0 comments on commit b9154be

Please sign in to comment.