packages feed

webauthn-client-0.1.0.0: test/WebAuthn/ClientSpec.hs

{-# LANGUAGE OverloadedStrings #-}

module WebAuthn.ClientSpec (spec) where

import Crypto.Hash (SHA256 (..))
import Crypto.PubKey.ECC.ECDSA (PrivateKey (..), verify)
import Crypto.PubKey.ECC.Generate (generate)
import Crypto.PubKey.ECC.Types (CurveName (SEC_p256r1), getCurveByName)
import Data.Aeson qualified as A
import Data.Aeson.Key qualified as Key
import Data.Aeson.KeyMap qualified as KeyMap
import Data.ByteString qualified as BS
import Data.Text (Text)
import Data.Text qualified as T
import System.FilePath ((</>))
import System.IO.Temp (withSystemTempDirectory)
import Test.Hspec

import WebAuthn.Client

spec :: Spec
spec = describe "WebAuthn.Client" $ do
  describe "base64url" $ do
    it "round-trips arbitrary bytes without padding" $ do
      let raw = BS.pack [0, 1, 2, 250, 251, 252, 253, 254, 255]
      unb64url (b64url raw) `shouldBe` Right raw
      b64url raw `shouldNotSatisfy` T.isInfixOf "="

  describe "options parsing" $ do
    it "reads the registration challenge and rp id" $
      parseRegistrationOptions
        (A.object ["challenge" A..= ("c" :: Text), "rp" A..= A.object ["id" A..= ("example.com" :: Text)]])
        `shouldBe` Right (RegistrationOptions "c" "example.com")

    it "reads the authentication challenge and rp id" $
      parseAuthenticationOptions
        (A.object ["challenge" A..= ("c" :: Text), "rpId" A..= ("example.com" :: Text)])
        `shouldBe` Right (AuthenticationOptions "c" "example.com")

    it "rejects a missing challenge" $
      parseAuthenticationOptions (A.object ["rpId" A..= ("example.com" :: Text)])
        `shouldSatisfy` isLeft

  describe "assertion" $ do
    it "signs authData || SHA-256(clientDataJSON) with ES256" $ do
      (pub, priv) <- generate (getCurveByName SEC_p256r1)
      (clientData, authData, sig) <- assertionParts testOrigin testRpId challenge 7 priv
      verify SHA256 pub sig (authData <> sha256Raw clientData)
        `shouldBe` True

    it "does not verify against a different key" $ do
      (_, priv) <- generate (getCurveByName SEC_p256r1)
      (otherPub, _) <- generate (getCurveByName SEC_p256r1)
      (clientData, authData, sig) <- assertionParts testOrigin testRpId challenge 7 priv
      verify SHA256 otherPub sig (authData <> sha256Raw clientData)
        `shouldBe` False

    it "puts the ceremony, challenge and origin in clientDataJSON" $ do
      (_, priv) <- generate (getCurveByName SEC_p256r1)
      (clientData, _, _) <- assertionParts testOrigin testRpId challenge 1 priv
      let fields = A.decodeStrict clientData :: Maybe A.Value
      (fields >>= \v -> jsonString v "type") `shouldBe` Just "webauthn.get"
      (fields >>= \v -> jsonString v "challenge") `shouldBe` Just challenge
      (fields >>= \v -> jsonString v "origin") `shouldBe` Just testOrigin

    it "increments the sign counter" $ do
      (_, priv) <- generate (getCurveByName SEC_p256r1)
      let PrivateKey _ d = priv
          cred = Credential
            { credentialId = BS.pack [1 .. 16]
            , privateKey = d
            , rpId = testRpId
            , origin = testOrigin
            , signCount = 41
            }
      (cred', response) <- createAssertion cred challenge
      signCount cred' `shouldBe` 42
      case jsonString response "authenticatorData" >>= either (const Nothing) Just . unb64url of
        Nothing -> expectationFailure "authenticatorData is not base64url"
        Just authData -> BS.drop 33 authData `shouldBe` BS.pack [0, 0, 0, 42]

  describe "registration" $ do
    it "returns a credential and a none attestation for it" $ do
      (cred, body) <- createRegistration testOrigin testRpId challenge
      signCount cred `shouldBe` 0
      jsonString body "rawId" `shouldBe` Just (b64url (credentialId cred))
      case jsonString body "attestationObject" >>= either (const Nothing) Just . unb64url of
        Nothing -> expectationFailure "attestationObject is not base64url"
        Just attestation -> do
          BS.take 1 attestation `shouldBe` BS.pack [0xa3]
          attestation `shouldSatisfy` BS.isInfixOf "fmt"
          attestation `shouldSatisfy` BS.isInfixOf "none"

  describe "credential file" $ do
    it "round-trips through JSON" $ do
      let cred = Credential
            { credentialId = BS.pack [9, 8, 7]
            , privateKey = 12345678901234567890
            , rpId = testRpId
            , origin = testOrigin
            , signCount = 3
            }
      (A.decode (A.encode cred) :: Maybe Credential) `shouldBe` Just cred

    it "loads what it saved, and reports a missing file as Nothing" $
      withSystemTempDirectory "webauthn-client" $ \dir -> do
        let path = dir </> "credential.json"
            cred = Credential (BS.pack [1, 2, 3]) 99 testRpId testOrigin 0
        loadCredentialFile path `shouldReturn` Right Nothing
        saveCredentialFile path cred `shouldReturn` Right ()
        loadCredentialFile path `shouldReturn` Right (Just cred)

testOrigin :: Text
testOrigin = "https://gateway.example.com:9090"

testRpId :: Text
testRpId = "gateway.example.com"

challenge :: Text
challenge = "AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8"

jsonString :: A.Value -> Text -> Maybe Text
jsonString (A.Object o) key =
  case KeyMap.lookup (Key.fromText key) o of
    Just (A.String s) -> Just s
    _                 -> Nothing
jsonString _ _ = Nothing

isLeft :: Either a b -> Bool
isLeft (Left _) = True
isLeft (Right _) = False