Skip to content

Commit

Permalink
Test for fetch POST request with CSRF. Fixes #33
Browse files Browse the repository at this point in the history
  • Loading branch information
chr15m committed Feb 21, 2024
1 parent 0d2a33f commit e929a95
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 5 deletions.
15 changes: 11 additions & 4 deletions examples/form-validation/webserver.cljs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,15 @@
:date "You must enter a valid date in YYYY-MM-DD format."
:count "You must enter a quantity between 5 and 10."})

(def button-script
(str
"token=document.cookie.split('; ')
.find((row)=>row.startsWith('XSRF-TOKEN='))?.split('=')[1];
ajax.onclick=()=>{fetch('/ajax',
{'method':'POST','body':'received!',
'headers':{'Content-Type':'text/plain','XSRF-Token':token}})
.then(r=>r.text()).then(d=>{ajaxresult.innerHTML=d})}"))

(defn view:form [csrf-token data validation-errors]
(let [ve (or validation-errors #js {})
data (or data #js {})]
Expand All @@ -42,9 +51,7 @@
[:div#ajaxresult]
[:button#ajax "Send fetch request"]
[:script {:dangerouslySetInnerHTML
{:__html
"ajax.onclick=()=>{fetch('/ajax',{'method':'POST','data':'hello','headers':{'Content-Type':'text/plain'}})
.then(r=>r.text()).then(d=>{ajaxresult.innerHTML=d})}"}}]]))
{:__html button-script}}]]))

(defn view:thank-you []
[:div
Expand Down Expand Up @@ -90,7 +97,7 @@
(web/reset-routes app)
(web/static-folder app "/css" "node_modules/minimal-stylesheet/")
(.use app handle-csrf-error)
(.post app "/ajax" (fn [req res] (.send res (aget req "body"))))
(.post app "/ajax" (fn [req res] (js/console.log (aget req "body")) (.send res (aget req "body"))))
(.use app "/" serve-form))

(defonce serve
Expand Down
14 changes: 13 additions & 1 deletion src/sitefoxtest/e2etests.cljs
Original file line number Diff line number Diff line change
Expand Up @@ -331,7 +331,18 @@
; then reload the first page to get a new token
(.goto page (str base-url "?hello=1"))
; check the second tab can still successfully submit
(check-form-submit page2))
(check-form-submit page2)
; close the page2 tab
(.close page2))

; Check that fetch requests still work with CSRF protection in place
(p/all [; click the ajax POST submit button
(-> page (.locator "button#ajax") .click)
; wait for waitForResponse fetch request loading to complete
(.waitForResponse page #(.includes (.url %) "/ajax"))])
(check-for-text
page "received!"
"The POST fetch request failed.")

(log "Closing resources.")
(j/call server :kill)
Expand All @@ -340,4 +351,5 @@
(done))
#(catch-fail % done server browser))))))

; (t/run-test sitefoxtest.e2etests/nbb-forms)
(t/run-tests *ns*)

0 comments on commit e929a95

Please sign in to comment.