packages feed

senbei-1.0.0: test/tests.hs

{-# 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))