senbei (empty) → 1.0.0
raw patch · 12 files changed
+834/−0 lines, 12 filesdep +QuickCheckdep +basedep +bytestring
Dependencies added: QuickCheck, base, bytestring, hspec, senbei, text, time
Files
- .editorconfig +3/−0
- .envrc +1/−0
- .gitignore +13/−0
- CHANGELOG.md +12/−0
- LICENSE.md +21/−0
- README.md +14/−0
- flake.lock +61/−0
- flake.nix +28/−0
- fourmolu.yaml +80/−0
- senbei.cabal +54/−0
- src/Senbei.hs +319/−0
- test/tests.hs +228/−0
+ .editorconfig view
@@ -0,0 +1,3 @@+[*]+indent_style = space+indent_size = 2
+ .envrc view
@@ -0,0 +1,1 @@+use flake
+ .gitignore view
@@ -0,0 +1,13 @@+.build-cache+.cache+.direnv/+.ghcid+*.dylib+*.dyn_hi+*.dyn_o+*.hi+*.o+*.swp+dist*+dist/+.DS_Store
+ CHANGELOG.md view
@@ -0,0 +1,12 @@+# Changelog++All notable changes to this project will be documented in this file.++The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).+As this project is a Haskell Cabal project, it follows the [Package Versioning Policy](https://pvp.haskell.org/).++## [1.0.0] - 2026-11-24++### Added++- Initial release.
+ LICENSE.md view
@@ -0,0 +1,21 @@+MIT License++Copyright (c) 2026 ix (https://github.com/ix | rose@empty.town)++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.
+ README.md view
@@ -0,0 +1,14 @@+Senbei+------++Senbei is a lightweight HTTP cookie library which provides serialization+and deserialization of HTTP Set-Cookie and Cookie headers.++It utilizes strong typing to make illegal states unrepresentable and+to conform to appropriate RFCs in terms of runtime data validation.++Users of libraries such as Aeson will find its interface familiar.++## Contributing++PRs are expected to update changelog.md and the version number.
+ flake.lock view
@@ -0,0 +1,61 @@+{+ "nodes": {+ "flake-utils": {+ "inputs": {+ "systems": "systems"+ },+ "locked": {+ "lastModified": 1794427683,+ "narHash": "sha256-o7ey9gEilsxaifqJWnBDlYSKbNWYQYtKwDyXeZU2kaU=",+ "owner": "numtide",+ "repo": "flake-utils",+ "rev": "cd489559845d81f673a12885576016c65cbe9363",+ "type": "github"+ },+ "original": {+ "owner": "numtide",+ "repo": "flake-utils",+ "type": "github"+ }+ },+ "nixpkgs": {+ "locked": {+ "lastModified": 1795370043,+ "narHash": "sha256-s/0jq8usZtLVOolYBwmyUmd3JsfAu7w3FU+a0dgMqSY=",+ "owner": "nixos",+ "repo": "nixpkgs",+ "rev": "0dc498bfe49baeb18b0f9891e800b53bb2603193",+ "type": "github"+ },+ "original": {+ "owner": "nixos",+ "ref": "nixos-26.05",+ "repo": "nixpkgs",+ "type": "github"+ }+ },+ "root": {+ "inputs": {+ "flake-utils": "flake-utils",+ "nixpkgs": "nixpkgs"+ }+ },+ "systems": {+ "locked": {+ "lastModified": 1791244623,+ "narHash": "sha256-uuanbkFk8a313Zfrxdcz8Us/yQtaxNnKJtX8v0ZPpd8=",+ "owner": "nix-systems",+ "repo": "default",+ "rev": "d36eeed142f88b5a636f2e3856a53c61654cf29b",+ "type": "github"+ },+ "original": {+ "owner": "nix-systems",+ "repo": "default",+ "type": "github"+ }+ }+ },+ "root": "root",+ "version": 7+}
+ flake.nix view
@@ -0,0 +1,28 @@+{+ inputs = {+ nixpkgs.url = "github:nixos/nixpkgs/nixos-26.05";+ flake-utils.url = "github:numtide/flake-utils";+ };++ outputs = { self, nixpkgs, flake-utils }:+ flake-utils.lib.eachDefaultSystem (system:+ let+ pkgs = nixpkgs.legacyPackages.${system};+ packageName = "senbei";+ in {+ packages.${packageName} =+ pkgs.haskellPackages.callCabal2nix packageName self {};++ packages.default = self.packages.${system}.${packageName};++ devShells.default = pkgs.haskellPackages.shellFor {+ packages = ps: [ self.packages.${system}.${packageName} ];+ nativeBuildInputs = with pkgs; [+ haskellPackages.haskell-language-server+ ghcid+ cabal-install+ fourmolu+ ];+ };+ });+}
+ fourmolu.yaml view
@@ -0,0 +1,80 @@+# Number of spaces per indentation step+indentation: 2++# Max line length for automatic line breaking+column-limit: 80++# Styling of arrows in type signatures (choices: trailing, leading, or leading-args)+function-arrows: leading-args++# How to place commas in multi-line lists, records, etc. (choices: leading or trailing)+comma-style: leading++record-style: aligned++# Styling of import/export lists (choices: leading, trailing, or diff-friendly)+import-export-style: leading++# Rules for grouping import declarations+import-grouping: by-qualified++# Whether to full-indent or half-indent 'where' bindings past the preceding body+indent-wheres: false++# Whether to leave a space before an opening record brace+record-brace-space: true++# Number of spaces between top-level declarations+newlines-between-decls: 1++# How to print Haddock comments (choices: single-line, multi-line, or multi-line-compact)+haddock-style: single-line++# How to print module docstring+haddock-style-module: single-line++# Where to put docstring comments in function signatures (choices: auto, leading, or trailing)+haddock-location-signature: leading++# Styling of let blocks (choices: auto, inline, newline, or mixed)+let-style: inline++# How to align the 'in' keyword with respect to the 'let' keyword (choices: left-align, right-align, or no-space)+in-style: no-space++# Styling of if-statements (choices: indented or hanging)+if-style: hanging++# Whether to put parentheses around a single constraint (choices: auto, always, or never)+single-constraint-parens: never++# Whether to put parentheses around a single deriving class (choices: auto, always, or never)+single-deriving-parens: never++# Whether to sort constraints+sort-constraints: true++# Whether to sort derived classes+sort-derived-classes: true++# Whether to sort deriving clauses+sort-deriving-clauses: true++# Whether to place section operators (those that are infixr 0, such as $) in trailing position, continuing the expression indented below+trailing-section-operators: false++# Output Unicode syntax (choices: detect, always, or never)+unicode: never++# Give the programmer more choice on where to insert blank lines+respectful: false++# Fixity information for operators+fixities: []++# Module reexports Fourmolu should know about+reexports: []++# Modules defined by the current Cabal package for import grouping+local-modules: []+
+ senbei.cabal view
@@ -0,0 +1,54 @@+cabal-version: 3.8+name: senbei+version: 1.0.0+build-type: Simple+extra-source-files: README.md+category: Web+author: rose@empty.town+maintainer: rose@empty.town+extra-doc-files: CHANGELOG.md, README.md+synopsis: A safe HTTP cookie library.+license: MIT+license-file: LICENSE.md+description: A lightweight HTTP cookie library providing serialization and deserialization of HTTP Set-Cookie and Cookie headers. It uses strong typing to make illegal states unrepresentable and attempts to conform to appropriate RFCs.++source-repository head+ type: git+ location: https://github.com/ix/senbei++common ghc-flags+ ghc-options: -Wall++common extensions+ default-extensions:+ PatternSynonyms+ RecordWildCards+ StrictData+ TypeFamilies+ ViewPatterns++library+ import: ghc-flags, extensions+ default-language: GHC2024+ hs-source-dirs: src++ exposed-modules:+ Senbei++ build-depends:+ , base >= 4.20.2 && < 4.21+ , bytestring >= 0.12.2 && < 0.13+ , text >= 2.1.3 && < 2.2+ , time >= 1.12.2 && < 1.13++test-suite test+ import: ghc-flags, extensions+ default-language: GHC2024+ main-is: test/tests.hs+ build-depends:+ , base+ , hspec+ , senbei+ , text+ , time+ , QuickCheck
+ src/Senbei.hs view
@@ -0,0 +1,319 @@+{-# LANGUAGE OverloadedStrings #-}++-- |+-- Module: Senbei+-- Description: A safe HTTP cookie library.+-- Copyright: (c) ix, 2026+-- Maintainer: rose@empty.town+-- Stability: Stable+-- License: MIT+module Senbei+ ( CookieDomain+ , CookieName+ , CookieOctet+ , CookiePath+ , CookieSettings (..)+ , defaultCookieSettings+ , DictFor+ , ExpiryError (..)+ , Expiry (Expires, Session)+ , mkMaxAge+ , HasCookie (..)+ , NonEmptyRestrictedText+ , mkNonEmptyRestrictedText+ , fromNonEmptyRestrictedText+ , Partitioning (..)+ , RestrictedText+ , mkRestrictedText+ , fromRestrictedText+ , RestrictedTextError (..)+ , SameSite (..)+ , Security (..)+ , FindCookieError (..)+ , findCookieByName+ , toSetCookie+ , toSetCookieWithDefaults+ , simpleSetCookie+ , simpleSetCookieWithDefaults+ , SerializeCookieError (..)+ )+where++import Data.Bifunctor (first)+import Data.Bool+import Data.List+import Data.Maybe+import Data.Proxy+import Data.Text (Text)+import Data.Time+import GHC.TypeLits++import Data.ByteString qualified as BS+import Data.Text qualified as T+import Data.Text.Encoding qualified as T++{-# INLINEABLE MAX_COOKIE_LENGTH_BYTES #-}+pattern MAX_COOKIE_LENGTH_BYTES :: Int+pattern MAX_COOKIE_LENGTH_BYTES = 4096++-- | RestrictedText, which is some Text tied to a phantom dictionary+-- type denoting the characters allowable within.+newtype RestrictedText (dict :: Symbol)+ = MkRestrictedText {unRestrictedText :: Text}+ deriving newtype (Eq, Show)++-- | Deconstruct RestrictedText, producing a plain Text.+fromRestrictedText :: RestrictedText dict -> Text+fromRestrictedText = unRestrictedText++-- | A variant of RestrictedText which must be non-empty at construction.+newtype NonEmptyRestrictedText (dict :: Symbol)+ = MkNonEmptyRestrictedText {unNonEmptyRestrictedText :: RestrictedText dict}+ deriving newtype (Eq, Show)++-- | Deconstruct NonEmptyRestrictedText, producing a plain Text.+fromNonEmptyRestrictedText :: NonEmptyRestrictedText dict -> Text+fromNonEmptyRestrictedText = unRestrictedText . unNonEmptyRestrictedText++-- | Errors that arise when constructing RestrictedText or NonEmptyRestrictedText.+data RestrictedTextError = Empty | InvalidChar Char+ deriving (Eq, Show)++-- | Attempt to construct a NonEmptyRestrictedText from some Text.+-- If the string is empty or contains a character disallowed by the dictionary,+-- then a RestrictedTextError will be returned as the Left variant of Either.+mkNonEmptyRestrictedText ::+ forall dict.+ KnownSymbol dict =>+ Text+ -> Either RestrictedTextError (NonEmptyRestrictedText dict)+mkNonEmptyRestrictedText t+ | T.null t = Left Empty+ | otherwise = MkNonEmptyRestrictedText <$> mkRestrictedText t++-- | Attempt to construct a RestrictedText from some Text.+-- If the string contains a character disallowed by the dictionary,+-- then a RestrictedTextError will be returned as the Left variant of Either.+{-# INLINEABLE mkRestrictedText #-}+mkRestrictedText ::+ forall dict.+ KnownSymbol dict =>+ Text+ -> Either RestrictedTextError (RestrictedText dict)+mkRestrictedText t = case T.find (not . isAccepted) t of+ Nothing -> Right $ MkRestrictedText t+ Just unacceptable -> Left $ InvalidChar unacceptable+ where+ dictionary :: [Char]+ dictionary = symbolVal (Proxy @dict)++ isAccepted :: Char -> Bool+ isAccepted = (`elem` dictionary)++-- | Errors that arise while serializing a value as a cookie.+data SerializeCookieError = SizeLimitExceeded | InvalidValue RestrictedTextError+ deriving (Eq, Show)++-- | Errors that arise while trying to locate a cookie in a cookie string.+data FindCookieError = CookieMissing | CookieUnparseable Text+ deriving (Eq, Show)++-- | Errors that arise when attempting to construct an Expiry value.+data ExpiryError = NegativeMaxAge Integer+ deriving (Eq, Show)++-- | Values for the Expiry and MaxAge attributes of a cookie.+data Expiry = Expires UTCTime | MaxAge Integer | Session+ deriving (Eq, Show)++-- | Max-Age must be >= 0, so this smart constructor is used to construct it.+mkMaxAge :: Integer -> Either ExpiryError Expiry+mkMaxAge delta+ | delta < 0 = Left $ NegativeMaxAge delta+ | otherwise = Right $ MaxAge delta++-- | The Secure attribute, or lack of it.+data Security = Secure | Insecure+ deriving (Eq, Show)++-- | The Partitioned attribute, or lack of it.+-- Practically speaking, this is set only on cookies SameSite=None.+-- Since Secure is forced on SameSite=None cookies, that will be present too.+data Partitioning = Partitioned | Unpartitioned+ deriving (Eq, Show)++-- | The SameSite attribute.+-- 'None' must be used with the 'Secure' attribute, so it's set automatically.+data SameSite = Lax Security | Strict Security | None Partitioning+ deriving (Eq, Show)++type CookieOctetDict =+ "!#$%&'()*+-./0123456789:<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[]^_`abcdefghijklmnopqrstuvwxyz{|}~"++-- | An abstraction over Text for handling cookie values, or octets.+-- See [RFC6265](https://www.rfc-editor.org/info/rfc6265/#page-9).+type CookieOctet = RestrictedText CookieOctetDict++type CookiePathDict =+ "!\"#$%&'()*+,-./0123456789:<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~"++-- | An abstraction over Text for handling the Path attribute.+-- See [RFC6265](https://www.rfc-editor.org/info/rfc6265/#page-9).+type CookiePath = NonEmptyRestrictedText CookiePathDict++type CookieNameDict =+ "!#$%&'*+-.^_`|~0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"++-- | An abstraction over Text for handling cookie names.+-- See [RFC9110](https://www.rfc-editor.org/info/rfc9110/#section-5.6.2).+type CookieName = NonEmptyRestrictedText CookieNameDict++type CookieDomainDict =+ "-.0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"++-- | An abstraction over Text for handling cookie Domain attributes.+-- See [RFC1034](https://www.rfc-editor.org/info/rfc1034/#page-11).+type CookieDomain = NonEmptyRestrictedText CookieDomainDict++-- | An open type family that associates types with their dictionary symbols.+type family DictFor t :: Symbol++type instance DictFor CookieDomain = CookieDomainDict++type instance DictFor CookieName = CookieNameDict++type instance DictFor CookieOctet = CookieOctetDict++type instance DictFor CookiePath = CookiePathDict++-- | Settings (attributes) to be used when serializing a cookie.+data CookieSettings = MkCookieSettings+ { cookieDomain :: Maybe CookieDomain+ -- ^ The domain to which the cookie applies.+ , cookiePath :: Maybe CookiePath+ -- ^ The path to which the cookie applies.+ , cookieExpiry :: Expiry+ -- ^ The expiry - or max age - of the cookie.+ , cookieHttpOnly :: Bool+ -- ^ Whether JavaScript is able to access the cookie.+ , cookieSameSite :: SameSite+ -- ^ The SameSite policy for the cookie.+ }+ deriving (Eq, Show)++-- | Sensible defaults for CookieSettings.+defaultCookieSettings :: CookieSettings+defaultCookieSettings =+ MkCookieSettings+ { cookieDomain = Nothing+ , cookiePath = Nothing+ , cookieExpiry = Session+ , cookieHttpOnly = True+ , cookieSameSite = Lax Secure+ }++-- | A class encoding how to serialize and deserialize a type as a cookie value.+class HasCookie t where+ toCookieValue :: t -> Text+ fromCookieValue :: Text -> Either Text t++-- | The time format used in Expiry attributes.+-- [MDN source](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Date).+cookieTimeFormat :: String+cookieTimeFormat = "%a, %d %b %0Y %H:%M:%S GMT"++-- | Given CookieSettings, attempt to serialize a type t to a cookie.+-- If this fails, then SerializeCookieError is returned.+--+-- This is the verbose form of this function, it expects the user to+-- provide explicit settings and a validated CookieName.+--+-- For a more friendly alternative, consider simpleSetCookie or simpleSetCookieWithDefaults.+toSetCookie ::+ HasCookie t =>+ CookieSettings -> CookieName -> t -> Either SerializeCookieError Text+toSetCookie MkCookieSettings {..} name value = do+ octet <-+ first InvalidValue $ mkRestrictedText @CookieOctetDict (toCookieValue value)++ let expiry = case cookieExpiry of+ MaxAge d -> Just $ mconcat ["Max-Age=", T.show d]+ Expires t ->+ Just+ $ mconcat ["Expires=", T.pack $ formatTime defaultTimeLocale cookieTimeFormat t]+ Session -> Nothing++ sameSite =+ Just+ $ mconcat+ [ "SameSite="+ , case cookieSameSite of+ Strict _ -> "Strict"+ Lax _ -> "Lax"+ None _ -> "None"+ ]++ secure = case cookieSameSite of+ Lax Secure -> Just "Secure"+ Strict Secure -> Just "Secure"+ None _ -> Just "Secure"+ _ -> Nothing++ partitioned = case cookieSameSite of+ None Partitioned -> Just "Partitioned"+ _ -> Nothing++ let serialized =+ T.intercalate "; "+ $ catMaybes+ [ Just $ mconcat [fromNonEmptyRestrictedText name, "=", fromRestrictedText octet]+ , fmap+ (\domain -> mconcat ["Domain=", fromNonEmptyRestrictedText domain])+ cookieDomain+ , fmap (\path -> mconcat ["Path=", fromNonEmptyRestrictedText path]) cookiePath+ , expiry+ , bool Nothing (Just "HttpOnly") cookieHttpOnly+ , sameSite+ , secure+ , partitioned+ ]++ if BS.length (T.encodeUtf8 serialized) > MAX_COOKIE_LENGTH_BYTES then+ Left SizeLimitExceeded+ else+ Right serialized++-- | A variant of toSetCookie that uses defaultCookieSettings.+toSetCookieWithDefaults ::+ HasCookie t => CookieName -> t -> Either SerializeCookieError Text+toSetCookieWithDefaults = toSetCookie defaultCookieSettings++-- | A variant of toSetCookie that accepts CookieSettings but performs validation of the Text+-- given to it as a cookie name as opposed to expecting it to be done beforehand.+simpleSetCookie ::+ HasCookie t => CookieSettings -> Text -> t -> Either SerializeCookieError Text+simpleSetCookie settings rawName value =+ either (Left . InvalidValue) (\name -> toSetCookie settings name value)+ $ mkNonEmptyRestrictedText rawName++-- | A variant of toSetCookie that is the most permissive. It uses defaultCookieSettings+-- and accepts Text as the cookie name instead of requiring it to be validated upfront.+simpleSetCookieWithDefaults ::+ HasCookie t => Text -> t -> Either SerializeCookieError Text+simpleSetCookieWithDefaults = simpleSetCookie defaultCookieSettings++-- | Attempt to parse out a type t from a cookie string (by name).+findCookieByName ::+ HasCookie t => CookieName -> Text -> Either FindCookieError t+findCookieByName (fromNonEmptyRestrictedText -> name) cookies =+ case find ((== name) . fst) pairs of+ Nothing -> Left CookieMissing+ Just (_, v) -> first CookieUnparseable $ fromCookieValue v+ where+ sanitize :: (Text, Text) -> (Text, Text)+ sanitize (k, v) = (T.strip k, T.strip $ T.drop 1 v)++ pairs :: [(Text, Text)]+ pairs =+ map (sanitize . T.span (/= '='))+ $ T.splitOn ";" cookies
+ test/tests.hs view
@@ -0,0 +1,228 @@+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE UndecidableInstances #-}+{-# OPTIONS_GHC -Wno-orphans #-}++module Main where++import Control.Monad+import Data.Either+import Data.Proxy+import Data.Text (Text)+import Data.Time+import GHC.TypeLits+import Senbei+import Test.Hspec+import Test.QuickCheck++import Data.Text qualified as T++pattern STRING_SIZE :: Int+pattern STRING_SIZE = 24++instance HasCookie Text where+ toCookieValue = id+ fromCookieValue = Right++newtype Bad t = MkBad Text+ deriving newtype Show++newtype Good t = MkGood Text+ deriving newtype Show++instance KnownSymbol (DictFor t) => Arbitrary (Bad t) where+ arbitrary =+ MkBad . T.pack+ <$> ( vectorOf STRING_SIZE+ $ (arbitrary `suchThat` (not . (`elem` (symbolVal (Proxy @(DictFor t))))))+ )++instance KnownSymbol (DictFor t) => Arbitrary (Good t) where+ arbitrary =+ MkGood . T.pack+ <$> (vectorOf STRING_SIZE $ elements $ symbolVal $ Proxy @(DictFor t))++mkUnsafeNERT ::+ forall dict. KnownSymbol dict => Text -> NonEmptyRestrictedText dict+mkUnsafeNERT =+ either (error "NonEmptyRestrictedText construction failed") id+ . mkNonEmptyRestrictedText++main :: IO ()+main = hspec $ do+ describe "CookieDomain" $ do+ it "prohibits an empty value"+ $ mkNonEmptyRestrictedText @(DictFor CookieDomain) ""+ `shouldBe` Left Empty++ it "allows characters defined in the dictionary"+ $ property+ $ \((MkGood t :: Good CookieDomain)) ->+ mkNonEmptyRestrictedText @(DictFor CookieDomain) t `shouldSatisfy` \case+ Right (fromNonEmptyRestrictedText -> t') -> t' == t+ _ -> False++ it "disallows characters not defined in the dictionary"+ $ property+ $ \((MkBad t :: Bad CookieDomain)) ->+ mkNonEmptyRestrictedText @(DictFor CookieDomain) t `shouldSatisfy` \case+ Left (InvalidChar _) -> True+ _ -> False++ describe "CookieName" $ do+ it "prohibits an empty value"+ $ mkNonEmptyRestrictedText @(DictFor CookieName) ""+ `shouldBe` Left Empty++ it "allows characters defined in the dictionary"+ $ property+ $ \((MkGood t :: Good CookieName)) ->+ mkNonEmptyRestrictedText @(DictFor CookieName) t `shouldSatisfy` \case+ Right (fromNonEmptyRestrictedText -> t') -> t' == t+ _ -> False++ it "disallows characters not defined in the dictionary"+ $ property+ $ \((MkBad t :: Bad CookieName)) ->+ mkNonEmptyRestrictedText @(DictFor CookieName) t `shouldSatisfy` \case+ Left (InvalidChar _) -> True+ _ -> False++ describe "CookieOctet" $ do+ it "permits an empty value"+ $ mkRestrictedText @(DictFor CookieOctet) "" `shouldSatisfy` \case+ Right (fromRestrictedText -> "") -> True+ _ -> False++ it "allows characters defined in the dictionary"+ $ property+ $ \((MkGood t :: Good CookieOctet)) ->+ mkRestrictedText @(DictFor CookieOctet) t `shouldSatisfy` \case+ Right (fromRestrictedText -> t') -> t' == t+ _ -> False++ it "disallows characters not defined in the dictionary"+ $ property+ $ \((MkBad t :: Bad CookieOctet)) ->+ mkRestrictedText @(DictFor CookieOctet) t `shouldSatisfy` \case+ Left (InvalidChar _) -> True+ _ -> False++ describe "CookiePath" $ do+ it "prohibits an empty value"+ $ mkNonEmptyRestrictedText @(DictFor CookiePath) ""+ `shouldBe` Left Empty++ it "allows characters defined in the dictionary"+ $ property+ $ \((MkGood t :: Good CookiePath)) ->+ mkNonEmptyRestrictedText @(DictFor CookiePath) t `shouldSatisfy` \case+ Right (fromNonEmptyRestrictedText -> t') -> t' == t+ _ -> False++ it "disallows characters not defined in the dictionary"+ $ property+ $ \((MkBad t :: Bad CookiePath)) ->+ mkNonEmptyRestrictedText @(DictFor CookiePath) t `shouldSatisfy` \case+ Left (InvalidChar _) -> True+ _ -> False++ describe "CookieSettings"+ $ it "produces a valid cookie with defaults"+ $ simpleSetCookieWithDefaults "cookie" ("hi" :: Text)+ `shouldBe` Right "cookie=hi; HttpOnly; SameSite=Lax; Secure"++ describe "findCookieByName" $ do+ it "locates a cookie by CookieName" $ do+ forM_ ["cookie=example;", "cookie=example"] $ \cookieString ->+ findCookieByName (mkUnsafeNERT "cookie" :: CookieName) cookieString+ `shouldBe` (Right "example" :: Either FindCookieError Text)++ it "fails to locate a cookie not present in the cookie string" $ do+ findCookieByName (mkUnsafeNERT "abcdefg" :: CookieName) "cookie=example;"+ `shouldBe` (Left CookieMissing :: Either FindCookieError Text)++ it "permits an empty CookieOctet"+ $ findCookieByName (mkUnsafeNERT "name" :: CookieName) "name="+ `shouldBe` (Right "" :: Either FindCookieError Text)++ describe+ "toSetCookie / toSetCookieWithDefaults / simpleSetCookie / simpleSetCookieWithDefaults"+ $ do+ it "fails to produce a valid cookie when the value is invalid"+ $ simpleSetCookieWithDefaults "example" ("spaces aren't allowed" :: Text)+ `shouldBe` Left (InvalidValue $ InvalidChar ' ')++ it "fails to produce a valid cookie when the serialized size exceeds 4096 bytes" $ do+ let veryLongCookieName = T.replicate 1024 "name"+ veryLongCookieValue = T.replicate 1024 "value"+ simpleSetCookieWithDefaults+ veryLongCookieName+ ("value" :: Text)+ `shouldBe` Left SizeLimitExceeded+ simpleSetCookieWithDefaults veryLongCookieName veryLongCookieValue+ `shouldBe` Left SizeLimitExceeded++ it "handles the relationship between SameSite / Secure / Partitioned" $ do+ simpleSetCookie+ (defaultCookieSettings {cookieSameSite = Lax Insecure})+ "cookie"+ ("value" :: Text)+ `shouldBe` Right "cookie=value; HttpOnly; SameSite=Lax"+ simpleSetCookie+ (defaultCookieSettings {cookieSameSite = Lax Secure})+ "cookie"+ ("value" :: Text)+ `shouldBe` Right "cookie=value; HttpOnly; SameSite=Lax; Secure"+ simpleSetCookie+ (defaultCookieSettings {cookieSameSite = Strict Insecure})+ "cookie"+ ("value" :: Text)+ `shouldBe` Right "cookie=value; HttpOnly; SameSite=Strict"+ simpleSetCookie+ (defaultCookieSettings {cookieSameSite = Strict Secure})+ "cookie"+ ("value" :: Text)+ `shouldBe` Right "cookie=value; HttpOnly; SameSite=Strict; Secure"+ simpleSetCookie+ (defaultCookieSettings {cookieSameSite = None Partitioned})+ "cookie"+ ("value" :: Text)+ `shouldBe` Right "cookie=value; HttpOnly; SameSite=None; Secure; Partitioned"+ simpleSetCookie+ (defaultCookieSettings {cookieSameSite = None Unpartitioned})+ "cookie"+ ("value" :: Text)+ `shouldBe` Right "cookie=value; HttpOnly; SameSite=None; Secure"++ describe "Expiry" $ do+ it "is serialized correctly" $ do+ let expirySettings =+ defaultCookieSettings+ { cookieExpiry = Expires $ UTCTime (fromGregorian 2000 1 1) 0+ }+ maxAgeSettings =+ defaultCookieSettings+ { cookieExpiry = either (error . show) id $ mkMaxAge 1000+ }+ simpleSetCookie expirySettings "mycookie" ("" :: Text)+ `shouldBe` Right+ "mycookie=; Expires=Sat, 01 Jan 2000 00:00:00 GMT; HttpOnly; SameSite=Lax; Secure"+ simpleSetCookie+ (expirySettings {cookieExpiry = Expires $ UTCTime (fromGregorian 999 1 1) 0})+ "mycookie"+ ("" :: Text)+ `shouldBe` Right+ "mycookie=; Expires=Tue, 01 Jan 0999 00:00:00 GMT; HttpOnly; SameSite=Lax; Secure"+ simpleSetCookie maxAgeSettings "mycookie" ("" :: Text)+ `shouldBe` Right "mycookie=; Max-Age=1000; HttpOnly; SameSite=Lax; Secure"++ it "serializes a Max-Age of 0"+ $ simpleSetCookie+ (defaultCookieSettings {cookieExpiry = either (error . show) id $ mkMaxAge 0})+ "mycookie"+ ("" :: Text)+ `shouldBe` Right "mycookie=; Max-Age=0; HttpOnly; SameSite=Lax; Secure"++ it "has a smart constructor for Max-Age which fails on a negative value" $ do+ mkMaxAge 1000 `shouldSatisfy` isRight+ mkMaxAge (-1000) `shouldBe` Left (NegativeMaxAge (-1000))