packages feed

wai-csrf (empty) → 0.1

raw patch · 6 files changed

+741/−0 lines, 6 filesdep +basedep +bytestringdep +case-insensitive

Dependencies added: base, bytestring, case-insensitive, cookie, crypton, http-types, memory, time, wai, wai-csrf, wai-extra

Files

+ CHANGELOG.md view
@@ -0,0 +1,3 @@+# Version 0.1++* Initial version.
+ LICENSE view
@@ -0,0 +1,219 @@+Copyright 2025, Renzo Carbonara.++Except where otherwise explicitly mentioned, all of contents of the+"wai-csrf" project are licensed under the Apache License,+Version 2.0 (the "License"); you may not use this file except in+compliance with the License. You may obtain a copy of the License at the+end of this file or at http://www.apache.org/licenses/LICENSE-2.0++Unless required by applicable law or agreed to in writing, software+distributed under the License is distributed on an "AS IS" BASIS,+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+See the License for the specific language governing permissions and+limitations under the License.+++-------------------------------------------------------------------------------+++                                 Apache License+                           Version 2.0, January 2004+                        http://www.apache.org/licenses/++   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION++   1. Definitions.++      "License" shall mean the terms and conditions for use, reproduction,+      and distribution as defined by Sections 1 through 9 of this document.++      "Licensor" shall mean the copyright owner or entity authorized by+      the copyright owner that is granting the License.++      "Legal Entity" shall mean the union of the acting entity and all+      other entities that control, are controlled by, or are under common+      control with that entity. For the purposes of this definition,+      "control" means (i) the power, direct or indirect, to cause the+      direction or management of such entity, whether by contract or+      otherwise, or (ii) ownership of fifty percent (50%) or more of the+      outstanding shares, or (iii) beneficial ownership of such entity.++      "You" (or "Your") shall mean an individual or Legal Entity+      exercising permissions granted by this License.++      "Source" form shall mean the preferred form for making modifications,+      including but not limited to software source code, documentation+      source, and configuration files.++      "Object" form shall mean any form resulting from mechanical+      transformation or translation of a Source form, including but+      not limited to compiled object code, generated documentation,+      and conversions to other media types.++      "Work" shall mean the work of authorship, whether in Source or+      Object form, made available under the License, as indicated by a+      copyright notice that is included in or attached to the work+      (an example is provided in the Appendix below).++      "Derivative Works" shall mean any work, whether in Source or Object+      form, that is based on (or derived from) the Work and for which the+      editorial revisions, annotations, elaborations, or other modifications+      represent, as a whole, an original work of authorship. For the purposes+      of this License, Derivative Works shall not include works that remain+      separable from, or merely link (or bind by name) to the interfaces of,+      the Work and Derivative Works thereof.++      "Contribution" shall mean any work of authorship, including+      the original version of the Work and any modifications or additions+      to that Work or Derivative Works thereof, that is intentionally+      submitted to Licensor for inclusion in the Work by the copyright owner+      or by an individual or Legal Entity authorized to submit on behalf of+      the copyright owner. For the purposes of this definition, "submitted"+      means any form of electronic, verbal, or written communication sent+      to the Licensor or its representatives, including but not limited to+      communication on electronic mailing lists, source code control systems,+      and issue tracking systems that are managed by, or on behalf of, the+      Licensor for the purpose of discussing and improving the Work, but+      excluding communication that is conspicuously marked or otherwise+      designated in writing by the copyright owner as "Not a Contribution."++      "Contributor" shall mean Licensor and any individual or Legal Entity+      on behalf of whom a Contribution has been received by Licensor and+      subsequently incorporated within the Work.++   2. Grant of Copyright License. Subject to the terms and conditions of+      this License, each Contributor hereby grants to You a perpetual,+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable+      copyright license to reproduce, prepare Derivative Works of,+      publicly display, publicly perform, sublicense, and distribute the+      Work and such Derivative Works in Source or Object form.++   3. Grant of Patent License. Subject to the terms and conditions of+      this License, each Contributor hereby grants to You a perpetual,+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable+      (except as stated in this section) patent license to make, have made,+      use, offer to sell, sell, import, and otherwise transfer the Work,+      where such license applies only to those patent claims licensable+      by such Contributor that are necessarily infringed by their+      Contribution(s) alone or by combination of their Contribution(s)+      with the Work to which such Contribution(s) was submitted. If You+      institute patent litigation against any entity (including a+      cross-claim or counterclaim in a lawsuit) alleging that the Work+      or a Contribution incorporated within the Work constitutes direct+      or contributory patent infringement, then any patent licenses+      granted to You under this License for that Work shall terminate+      as of the date such litigation is filed.++   4. Redistribution. You may reproduce and distribute copies of the+      Work or Derivative Works thereof in any medium, with or without+      modifications, and in Source or Object form, provided that You+      meet the following conditions:++      (a) You must give any other recipients of the Work or+          Derivative Works a copy of this License; and++      (b) You must cause any modified files to carry prominent notices+          stating that You changed the files; and++      (c) You must retain, in the Source form of any Derivative Works+          that You distribute, all copyright, patent, trademark, and+          attribution notices from the Source form of the Work,+          excluding those notices that do not pertain to any part of+          the Derivative Works; and++      (d) If the Work includes a "NOTICE" text file as part of its+          distribution, then any Derivative Works that You distribute must+          include a readable copy of the attribution notices contained+          within such NOTICE file, excluding those notices that do not+          pertain to any part of the Derivative Works, in at least one+          of the following places: within a NOTICE text file distributed+          as part of the Derivative Works; within the Source form or+          documentation, if provided along with the Derivative Works; or,+          within a display generated by the Derivative Works, if and+          wherever such third-party notices normally appear. The contents+          of the NOTICE file are for informational purposes only and+          do not modify the License. You may add Your own attribution+          notices within Derivative Works that You distribute, alongside+          or as an addendum to the NOTICE text from the Work, provided+          that such additional attribution notices cannot be construed+          as modifying the License.++      You may add Your own copyright statement to Your modifications and+      may provide additional or different license terms and conditions+      for use, reproduction, or distribution of Your modifications, or+      for any such Derivative Works as a whole, provided Your use,+      reproduction, and distribution of the Work otherwise complies with+      the conditions stated in this License.++   5. Submission of Contributions. Unless You explicitly state otherwise,+      any Contribution intentionally submitted for inclusion in the Work+      by You to the Licensor shall be under the terms and conditions of+      this License, without any additional terms or conditions.+      Notwithstanding the above, nothing herein shall supersede or modify+      the terms of any separate license agreement you may have executed+      with Licensor regarding such Contributions.++   6. Trademarks. This License does not grant permission to use the trade+      names, trademarks, service marks, or product names of the Licensor,+      except as required for reasonable and customary use in describing the+      origin of the Work and reproducing the content of the NOTICE file.++   7. Disclaimer of Warranty. Unless required by applicable law or+      agreed to in writing, Licensor provides the Work (and each+      Contributor provides its Contributions) on an "AS IS" BASIS,+      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or+      implied, including, without limitation, any warranties or conditions+      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A+      PARTICULAR PURPOSE. You are solely responsible for determining the+      appropriateness of using or redistributing the Work and assume any+      risks associated with Your exercise of permissions under this License.++   8. Limitation of Liability. In no event and under no legal theory,+      whether in tort (including negligence), contract, or otherwise,+      unless required by applicable law (such as deliberate and grossly+      negligent acts) or agreed to in writing, shall any Contributor be+      liable to You for damages, including any direct, indirect, special,+      incidental, or consequential damages of any character arising as a+      result of this License or out of the use or inability to use the+      Work (including but not limited to damages for loss of goodwill,+      work stoppage, computer failure or malfunction, or any and all+      other commercial damages or losses), even if such Contributor+      has been advised of the possibility of such damages.++   9. Accepting Warranty or Additional Liability. While redistributing+      the Work or Derivative Works thereof, You may choose to offer,+      and charge a fee for, acceptance of support, warranty, indemnity,+      or other liability obligations and/or rights consistent with this+      License. However, in accepting such obligations, You may act only+      on Your own behalf and on Your sole responsibility, not on behalf+      of any other Contributor, and only if You agree to indemnify,+      defend, and hold each Contributor harmless for any liability+      incurred by, or claims asserted against, such Contributor by reason+      of your accepting any such warranty or additional liability.++   END OF TERMS AND CONDITIONS++   APPENDIX: How to apply the Apache License to your work.++      To apply the Apache License to your work, attach the following+      boilerplate notice, with the fields enclosed by brackets "[]"+      replaced with your own identifying information. (Don't include+      the brackets!)  The text should be enclosed in the appropriate+      comment syntax for the file format. We also recommend that a+      file or class name and description of purpose be included on the+      same "printed page" as the copyright notice for easier+      identification within third-party archives.++   Copyright [yyyy] [name of copyright owner]++   Licensed under the Apache License, Version 2.0 (the "License");+   you may not use this file except in compliance with the License.+   You may obtain a copy of the License at++       http://www.apache.org/licenses/LICENSE-2.0++   Unless required by applicable law or agreed to in writing, software+   distributed under the License is distributed on an "AS IS" BASIS,+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+   See the License for the specific language governing permissions and+   limitations under the License.
+ README.md view
@@ -0,0 +1,8 @@+# wai-csrf++Cross-Site Request Forgery protection for Haskell WAI++* Copyright © Renzo Carbonara, 2025.++* Licensing terms in `LICENSE` file (`Apache-2.0`).+
+ lib/Wai/CSRF.hs view
@@ -0,0 +1,280 @@+-- | This module exports tool to prevent cross-site request forgeries in+-- "Network.Wai". Consider using it in combination with "Wai.CryptoCookie".+module Wai.CSRF+   ( Config (..)+   , defaultConfig+   , tokenFromRequestHeader+   , tokenFromRequestCookie+   , setCookie+   , expireCookie+   , middleware++    -- * Token+   , Token (..)+   , randomToken+   , tokenToBase64UU+   , tokenFromBase64UU++    -- * Masked token+   , MaskedToken (..)+   , maskedTokenToBase64UU+   , maskedTokenFromBase64UU+   , randomMaskToken+   , unmaskToken+   ) where++import Crypto.Random qualified as C+import Data.ByteArray qualified as BA+import Data.ByteArray.Encoding qualified as BA+import Data.ByteArray.Sized qualified as BAS+import Data.ByteString qualified as B+import Data.CaseInsensitive qualified as CI+import Data.Time.Clock.POSIX qualified as Time+import Network.HTTP.Types qualified as H+import Network.Wai qualified as Wai+import Web.Cookie qualified as C++--------------------------------------------------------------------------------++-- | CSRF token.+--+-- * It is safe to send and receive the 'Token' through HTTP cookies and+-- headers.+--+-- * If you need to send or receive the 'Token' as part of the request or+-- response body, use 'MaskedToken' instead.+newtype Token = Token (BAS.SizedByteArray 32 B.ByteString)++instance Show Token where+   showsPrec n (Token s) = showsPrec n $ BAS.unSizedByteArray s++instance Eq Token where+   Token a == Token b = BA.constEq a b++-- | A CSRF token is just random 32 bytes. Its meaning and validity depends on+-- how and whether you tie it to a user session.+randomToken :: (C.MonadRandom m) => m Token+randomToken = fmap (Token . BAS.unsafeSizedByteArray) (C.getRandomBytes 32)++-- | @'tokenFromBase64UU' . 'tokenToBase64UU'  ==  'Just'@+tokenToBase64UU :: Token -> B.ByteString+tokenToBase64UU (Token t) =+   BA.convertToBase BA.Base64URLUnpadded t++-- | @'tokenFromBase64UU' . 'tokenToBase64UU'  ==  'Just'@+tokenFromBase64UU :: B.ByteString -> Maybe Token+tokenFromBase64UU b =+   case BA.convertFromBase BA.Base64URLUnpadded b of+      Right (x :: BA.Bytes) -> Token <$> BAS.fromByteArrayAccess x+      _ -> Nothing++--------------------------------------------------------------------------------++-- | If you embed a 'Token' as is in a response body when HTTP body compression+-- is enabled, it is possible for a malicious actor to recover the 'Token'+-- through a /BREACH/ attack or similar. In order to prevent that, send a+-- different 'MaskedToken' (generated with 'randomMaskToken') each time+-- instead.+newtype MaskedToken = MaskedToken (BAS.SizedByteArray 64 BA.Bytes)++instance Show MaskedToken where+   showsPrec n (MaskedToken s) = showsPrec n $ BAS.unSizedByteArray s++instance Eq MaskedToken where+   MaskedToken a == MaskedToken b = BA.constEq a b++toMaskedToken :: Mask -> Token -> MaskedToken+toMaskedToken (Mask m) (Token s) =+   let x = BAS.xor m s+   in  MaskedToken $! BAS.append m (x `asTypeOf` m)++fromMaskedToken :: MaskedToken -> (Mask, Token)+fromMaskedToken (MaskedToken t) =+   let (m, x) = BAS.splitAt t+   in  (Mask m, Token $! BAS.xor m (x `asTypeOf` m))++-- | @'maskedTokenFromBase64UU' . 'maskedTokenToBase64UU'  ==  'Just'@+maskedTokenToBase64UU :: MaskedToken -> B.ByteString+maskedTokenToBase64UU (MaskedToken t) = BA.convertToBase BA.Base64URLUnpadded t++-- | @'maskedTokenFromBase64UU' . 'maskedTokenToBase64UU'  ==  'Just'@+maskedTokenFromBase64UU :: B.ByteString -> Maybe MaskedToken+maskedTokenFromBase64UU b = case BA.convertFromBase BA.Base64URLUnpadded b of+   Right (x :: BA.Bytes) -> MaskedToken <$> BAS.fromByteArrayAccess x+   _ -> Nothing++-- | See 'MaskedToken'.+newtype Mask = Mask (BAS.SizedByteArray 32 BA.Bytes)++instance Show Mask where+   showsPrec n (Mask s) = showsPrec n $ BAS.unSizedByteArray s++instance Eq Mask where+   Mask a == Mask b = BA.constEq a b++randomMask :: (C.MonadRandom m) => m Mask+randomMask = fmap (Mask . BAS.unsafeSizedByteArray) (C.getRandomBytes 32)++-- | @'unmaskToken' '<$>' 'randomMaskToken' tok@ and @'pure' tok@ produce+-- the same output @tok@.+randomMaskToken :: (C.MonadRandom m) => Token -> m MaskedToken+randomMaskToken t = flip toMaskedToken t <$> randomMask++-- | @'unmaskToken' '<$>' 'randomMaskToken' tok@ and @'pure' tok@ produce+-- the same output @tok@.+unmaskToken :: MaskedToken -> Token+unmaskToken = snd . fromMaskedToken++--------------------------------------------------------------------------------++-- | Config common to 'middleware', 'tokenFromRequestHeader' and+-- 'tokenFromRequestCookie'.+--+-- Consider using 'defaultConfig' and updating desired fields only.+data Config = Config+   { cookieName :: B.ByteString+   -- ^ Used by 'tokenFromRequestCookie', 'setCookie', 'expireCookie' and+   -- 'middleware'.+   , headerName :: B.ByteString+   -- ^ Used by 'tokenFromRequestHeader' and 'middleware'.+   , reject :: Wai.Request -> Maybe (Token, Bool) -> Maybe Wai.Response+   -- ^ Used by 'middleware'. Decide whether the incoming 'Wai.Request' should+   -- be rejected with a given 'Wai.Response'. Takes the 'Token' that came in+   -- through a cookie (see 'Config'\'s @cookieName@), if any, as well as a+   -- 'Bool' which is 'True' if there is a matching 'Token' that came in+   -- through a header (see 'Config'\'s @headerName@).+   --+   -- If the token comes through the request body (see 'MaskedToken'), then+   -- it is sometimes best not to reject the request here, and instead check+   -- and potentially reject the request downstream, so as to preserve the+   -- streaming nature of processing the request body.+   --+   -- Notice that nothing in @'Maybe' ('Token', 'Bool')@ has been evaluated+   -- by the time @reject@ is called, so unless you force their evaluation,+   -- using 'middleware' is essentially free.+   }++-- | Default CSRF settings.+--+-- * Cookie name is @CSRF-TOKEN@.+--+-- * Header name is @X-CSRF-TOKEN@.+--+-- * Reject with 'H.forbidden403' all request who are neither @GET@, @HEAD@,+-- @OPTIONS@ nor @TRACE@, unless the 'Token' is present in both cookie and+-- header and they are equal.+defaultConfig :: Config+defaultConfig =+   Config+      { cookieName = "CSRF-TOKEN"+      , headerName = "X-CSRF-TOKEN"+      , reject = \req yteq ->+         if+            | Wai.requestMethod req == H.methodGet -> Nothing+            | Wai.requestMethod req == H.methodHead -> Nothing+            | Wai.requestMethod req == H.methodOptions -> Nothing+            | Wai.requestMethod req == H.methodTrace -> Nothing+            | Just (_, eq) <- yteq, eq -> Nothing+            | otherwise -> Just $ Wai.responseLBS H.forbidden403 [] "CSRF"+      }++-- | Obtain the 'Token' from the 'Wai.Request' headers.+--+-- You don't need to use this if you are using 'middleware'.+tokenFromRequestHeader :: Config -> Wai.Request -> Maybe Token+tokenFromRequestHeader c = \r -> do+   [t64] <- pure $ lookupMany n $ Wai.requestHeaders r+   tokenFromBase64UU t64+  where+   n = CI.mk c.headerName++-- | Obtain the 'Token' from the 'Wai.Request' cookies.+--+-- You don't need to use this if you are using 'middleware'.+tokenFromRequestCookie :: Config -> Wai.Request -> Maybe Token+tokenFromRequestCookie c r = do+   [t64] <- pure $ lookupMany c.cookieName $ requestCookies r+   tokenFromBase64UU t64++-- | Construct a 'C.SetCookie' to set the CSRF 'Token'.+--+-- The 'C.SetCookie' has these settings, some of which could be overriden.+--+--      * Cookie name is 'Config'\'s @cookieName@.+--+--      * @HttpOnly@: No, and you shouldn't change this.+--+--      * @Max-Age@ and @Expires@: This cookie never expires. We recommend+--      relying on server-side expiration instead, as the lifetime of the+--      cookie could easily be extended by a legitimate but malicious client.+--      It is recommended that you rotate the 'Token' each time a new user+--      session is established.+--+--      * @Path@: @\/@+--+--      * @SameSite@: @Lax@.+--+--      * @Secure@: Yes.+--+--      * @Domain@: Not set.+setCookie :: Config -> Token -> C.SetCookie+setCookie c tok =+   (expireCookie c)+      { C.setCookieValue = tokenToBase64UU tok+      , C.setCookieExpires = Nothing+      , C.setCookieMaxAge = Nothing+      }++-- | Construct a 'C.SetCookie' expiring the cookie named 'Config'\'s+-- @cookieName@.+expireCookie :: Config -> C.SetCookie+expireCookie c =+   C.defaultSetCookie+      { C.setCookieName = c.cookieName+      , C.setCookieValue = ""+      , C.setCookieDomain = Nothing+      , C.setCookieExpires = Just (Time.posixSecondsToUTCTime 0)+      , C.setCookieHttpOnly = False+      , C.setCookieMaxAge = Just (negate 1)+      , C.setCookiePath = Just "/"+      , C.setCookieSameSite = Just C.sameSiteLax+      , C.setCookieSecure = True+      }++-- | Construct a 'Wai.Middleware' (almost) that does the following:+--+-- 1. Try to find the CSRF 'Token' among the incoming 'Wai.Request' cookies+-- (see 'Config'\'s @cookieName@).+--+-- 2. Use 'Config'\'s @reject@ to decide if the incoming 'Wai.Request'+-- should be rejected.+--+-- 3. If the 'Wai.Request' wasn't rejected, we pass the 'Token' found in the+-- cookie, if any, to the underlying 'Wai.Application'.+--+-- Important: This doesn't set any cookie. You must explicitly add+-- 'setCookie' to a 'Wai.Response' yourself.+middleware+   :: Config+   -> (Maybe Token -> Wai.Application)+   -> Wai.Application+middleware c = \fapp req respond -> do+   let yct = fyct req+       yte = liftA2 (\ct ht -> (ct, ct == ht)) yct (fyht req)+   case c.reject req yte of+      Nothing -> fapp yct req respond+      Just res -> respond res+  where+   fyct = tokenFromRequestCookie c+   fyht = tokenFromRequestHeader c++--------------------------------------------------------------------------------++requestCookies :: Wai.Request -> [(B.ByteString, B.ByteString)]+requestCookies r = C.parseCookies =<< lookupMany "Cookie" (Wai.requestHeaders r)++lookupMany :: (Eq k) => k -> [(k, v)] -> [v]+lookupMany k = findMany (== k)++findMany :: (Eq k) => (k -> Bool) -> [(k, v)] -> [v]+findMany f = map snd . filter (\(a, _) -> f a)
+ test/Main.hs view
@@ -0,0 +1,168 @@+{-# LANGUAGE RecordWildCards #-}++module Main (main) where++import Control.Exception qualified as Ex+import Control.Monad+import Control.Monad.IO.Class+import Data.ByteString qualified as B+import Data.Maybe+import Data.String+import Network.HTTP.Types qualified as HT+import Network.Wai qualified as W+import Network.Wai.Test qualified as WT+import Web.Cookie qualified as WC++import Wai.CSRF qualified as WCC++main :: IO ()+main = do+   testToken+   testCookies+   testReject+   putStrLn "TESTS OK"++testReject :: IO ()+testReject = do+   tok1 <- WCC.randomToken+   let sc1 = WCC.setCookie WCC.defaultConfig tok1+       app = WCC.middleware WCC.defaultConfig \yt _ respond ->+         respond $+            W.responseLBS HT.status200 [] $+               fromString (show (yt == Just tok1))++   tok2 <- WCC.randomToken+   let sc2 = WCC.setCookie WCC.defaultConfig tok2++   WT.withSession app do+      -- Make sure the cookie is set+      WT.assertNoClientCookieExists "t0-a" "CSRF-TOKEN"+      WT.setClientCookie sc1++      -- Request succeeds because it is GET+      sres1 <- WT.request WT.defaultRequest+      WT.assertStatus 200 sres1+      WT.assertBody "True" sres1+      WT.assertClientCookieExists "t0-b" "CSRF-TOKEN"++      -- Request fails because it is POST and there is no CSRF header+      sres2 <- WT.request WT.defaultRequest{W.requestMethod = HT.methodPost}+      WT.assertStatus 403 sres2+      WT.assertBody "CSRF" sres2++      -- Request succeeds because it is POST and there is matching CSRF header+      sres3 <-+         WT.request+            WT.defaultRequest+               { W.requestMethod = HT.methodPost+               , W.requestHeaders = [("X-CSRF-TOKEN", WC.setCookieValue sc1)]+               }+      WT.assertStatus 200 sres3+      WT.assertBody "True" sres3++      -- Request succeeds because it is GET. The request header doesn't match,+      -- but it doesn't matter.+      sres4 <- do+         WT.request+            WT.defaultRequest+               { W.requestHeaders = [("X-CSRF-TOKEN", WC.setCookieValue sc2)]+               }+      WT.assertStatus 200 sres4+      WT.assertBody "True" sres4++      -- Request fails because it is POST, but there is no matching request header+      sres5 <- do+         WT.request+            WT.defaultRequest+               { W.requestMethod = HT.methodPost+               , W.requestHeaders = [("X-CSRF-TOKEN", WC.setCookieValue sc2)]+               }+      WT.assertStatus 403 sres5+      WT.assertBody "CSRF" sres5++testToken :: IO ()+testToken = do+   t0 <- WCC.randomToken+   t1 <- WCC.randomToken+   when (t0 == t1) $ fail "e0"++   mt0 <- WCC.randomMaskToken t0+   mt1 <- WCC.randomMaskToken t0+   when (mt0 == mt1) $ fail "e1"++   when (WCC.unmaskToken mt0 /= t0) $ fail "e3"++   let mt064 = WCC.maskedTokenToBase64UU mt0+   when (WCC.maskedTokenFromBase64UU mt064 /= Just mt0) $ fail "e4"++testCookies :: IO ()+testCookies = do+   let c = WCC.defaultConfig++   let fapp1 :: (Maybe WCC.Token -> Maybe (Maybe WCC.Token)) -> W.Application+       fapp1 = \g -> WCC.middleware c (app1 c g)++   -- keeping cookies untouched+   WT.withSession (fapp1 \_ -> Nothing) do+      WT.assertNoClientCookieExists "t0-a" "CSRF-TOKEN"+      sres1 <- WT.request WT.defaultRequest+      WT.assertBody "Nothing" sres1+      WT.assertNoClientCookieExists "t0-b" "CSRF-TOKEN"+      sres1 <- WT.request WT.defaultRequest+      WT.assertBody "Nothing" sres1+      WT.assertNoClientCookieExists "t0-c" "CSRF-TOKEN"++   -- explicitly deleting cookie+   WT.withSession (fapp1 \_ -> Just Nothing) do+      WT.assertNoClientCookieExists "t1-a" "CSRF-TOKEN"+      sres1 <- WT.request WT.defaultRequest+      WT.assertBody "Nothing" sres1+      WT.assertClientCookieExists "t1-b" "CSRF-TOKEN"+      sres1 <- WT.request WT.defaultRequest+      WT.assertBody "Nothing" sres1+      WT.assertClientCookieExists "t1-c" "CSRF-TOKEN"++   -- explicitely setting cookie+   tok1 <- WCC.randomToken+   ck0 <- WT.withSession (fapp1 \_ -> Just (Just tok1)) do+      WT.assertNoClientCookieExists "t2-a" "CSRF-TOKEN"+      sres1 <- WT.request WT.defaultRequest+      WT.assertBody "Nothing" sres1+      WT.assertClientCookieExists "t2-b" "CSRF-TOKEN"+      sres2 <- WT.request WT.defaultRequest+      WT.assertBody (fromString (show (Just tok1))) sres2+      WT.assertClientCookieExists "t2-c" "CSRF-TOKEN"+      WT.getClientCookies++   -- modify and explicitly delete+   WT.withSession (fapp1 \_ -> Just Nothing) do+      WT.assertNoClientCookieExists "t3-a" "CSRF-TOKEN"+      WT.modifyClientCookies \_ -> ck0+      WT.assertClientCookieExists "t3-b" "CSRF-TOKEN"+      sres1 <- WT.request WT.defaultRequest+      WT.assertBody (fromString (show (Just tok1))) sres1+      WT.assertClientCookieExists "t3-c" "CSRF-TOKEN"+      sres2 <- WT.request WT.defaultRequest+      WT.assertBody "Nothing" sres2+      WT.assertClientCookieExists "t3-d" "CSRF-TOKEN"+      WT.assertClientCookieValue "t3-e" "CSRF-TOKEN" ""++app1+   :: WCC.Config+   -> (Maybe WCC.Token -> Maybe (Maybe WCC.Token))+   -> Maybe WCC.Token+   -> W.Application+app1 c g yold = \req respond -> do+   let ysc :: Maybe WC.SetCookie =+         case g yold of+            Nothing -> Nothing+            Just Nothing -> Just $ WCC.expireCookie c+            Just (Just new) -> Just $ WCC.setCookie c new+   respond+      $ W.responseLBS+         HT.status200+         ( fmap+            (\sc -> ("Set-Cookie", WC.renderSetCookieBS sc))+            (maybeToList ysc)+         )+      $ fromString (show yold)
+ wai-csrf.cabal view
@@ -0,0 +1,63 @@+cabal-version: 2.4+name: wai-csrf+version: 0.1+license: Apache-2.0+license-file: LICENSE+extra-source-files: README.md CHANGELOG.md+author: Renzo Carbonara+maintainer: renλren.zone+copyright: Renzo Carbonara, 2025+category: Web+build-type: Simple+synopsis: Cross-site request forgery protection for WAI+description: Cross-site request forgery protection for WAI+homepage: https://github.com/k0001/hs-wai-csrf+bug-reports: https://github.com/k0001/hs-wai-csrf/issues+tested-with: GHC == 9.8.1++common basic+  default-language: GHC2021+  build-depends: base == 4.*+  default-extensions:+    BlockArguments+    DataKinds+    DerivingStrategies+    DuplicateRecordFields+    LambdaCase+    MultiWayIf+    OverloadedRecordDot+    OverloadedStrings+    TypeFamilies+    ViewPatterns+++library+  import: basic+  ghc-options: -O2 -Wall+  hs-source-dirs: lib+  exposed-modules:+    Wai.CSRF+  build-depends:+    bytestring,+    case-insensitive,+    cookie,+    crypton,+    http-types,+    memory,+    time,+    wai,++test-suite test+  import: basic+  type: exitcode-stdio-1.0+  hs-source-dirs: test+  main-is: Main.hs+  ghc-options: -threaded -with-rtsopts=-N+  build-depends:+    bytestring,+    cookie,+    http-types,+    wai,+    wai-csrf,+    wai-extra,+