Skip to content

Commit eadd493

Browse files
committed
Add async support to wrap-xss-protection
1 parent b89ef9a commit eadd493

2 files changed

Lines changed: 35 additions & 6 deletions

File tree

src/ring/middleware/x_headers.clj

Lines changed: 16 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,9 @@
1313
(str "ALLOW-FROM " (:allow-from frame-options))
1414
(str/upper-case (name frame-options))))
1515

16+
(defn- format-xss-protection [enable? options]
17+
(str (if enable? "1" "0") (if options "; mode=block")))
18+
1619
(defn- wrap-x-header [handler header-name header-value]
1720
(fn
1821
([request]
@@ -66,6 +69,14 @@
6669
{:pre [(= content-type-options :nosniff)]}
6770
(wrap-x-header handler "X-Content-Type-Options" (name content-type-options)))
6871

72+
(defn xss-protection-response
73+
"Add the X-XSS-Protection header to the response. See: wrap-xss-protection."
74+
([response enable?]
75+
(xss-protection-response response enable? nil))
76+
([response enable? options]
77+
(some-> response
78+
(resp/header "X-XSS-Protection" (format-xss-protection enable? options)))))
79+
6980
(defn wrap-xss-protection
7081
"Middleware that adds the X-XSS-Protection header to the response. This header
7182
enables a heuristic filter in browsers for detecting cross-site scripting
@@ -77,9 +88,8 @@
7788
:mode - currently accepts only :block
7889
7990
See: http://msdn.microsoft.com/en-us/library/dd565647(v=vs.85).aspx"
80-
[handler enable? & [options]]
81-
{:pre [(or (nil? options) (= options {:mode :block}))]}
82-
(let [header-value (str (if enable? "1" "0") (if options "; mode=block"))]
83-
(fn [request]
84-
(if-let [response (handler request)]
85-
(resp/header response "X-XSS-Protection" header-value)))))
91+
([handler enable?]
92+
(wrap-xss-protection handler enable? nil))
93+
([handler enable? options]
94+
{:pre [(or (nil? options) (= options {:mode :block}))]}
95+
(wrap-x-header handler "X-XSS-Protection" (format-xss-protection enable? options))))

test/ring/middleware/x_headers_test.clj

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -130,3 +130,22 @@
130130
(testing "nil response"
131131
(let [handler (wrap-xss-protection (constantly nil) true)]
132132
(is (nil? (handler (request :get "/"))))))))
133+
134+
(deftest test-wrap-xss-protection-cps
135+
(testing "nosniff"
136+
(let [handler (-> (fn [_ respond _] (respond (response "hello")))
137+
(wrap-xss-protection true))
138+
resp (promise)
139+
ex (promise)]
140+
(handler (request :get "/") resp ex)
141+
(is (not (realized? ex)))
142+
(is (= (:headers @resp) {"X-XSS-Protection" "1"}))))
143+
144+
(testing "nil response"
145+
(let [handler (-> (fn [_ respond _] (respond nil))
146+
(wrap-xss-protection true))
147+
resp (promise)
148+
ex (promise)]
149+
(handler (request :get "/") resp ex)
150+
(is (not (realized? ex)))
151+
(is (nil? @resp)))))

0 commit comments

Comments
 (0)