webauthn-client-0.1.0.0: src/WebAuthn/Client/Http.hs
{-# LANGUAGE OverloadedStrings #-}
-- | Driving a WebAuthn ceremony over the JSON/HTTP conventions that most
-- relying parties use: ask for options, sign them, post the response back.
--
-- The endpoints and the session-cookie name are configuration, because there
-- is no standard for them. 'exampleEndpoints' is the one concrete adapter this
-- package ships, and doubles as an example.
module WebAuthn.Client.Http
( Endpoints (..)
, exampleEndpoints
, enroll
, authenticate
, authenticateWithStore
, sessionToken
) where
import Control.Exception (SomeException, try)
import Data.Aeson (Value (..), object)
import Data.Aeson qualified as A
import Data.Aeson.Key qualified as Key
import Data.Aeson.KeyMap qualified as KeyMap
import Data.ByteString (ByteString)
import Data.ByteString qualified as BS
import Data.ByteString.Lazy qualified as BL
import Data.Maybe (listToMaybe)
import Data.Text (Text)
import Data.Text qualified as T
import Data.Text.Encoding qualified as TE
import Network.HTTP.Client
( Manager, RequestBody (..), Response, httpLbs, newManager, parseRequest
, requestBody, requestHeaders, responseBody, responseHeaders, responseStatus )
import Network.HTTP.Client.TLS (tlsManagerSettings)
import Network.HTTP.Types.Header (Header, HeaderName, hContentType, hSetCookie)
import Network.HTTP.Types.Status (statusCode, statusIsSuccessful)
import WebAuthn.Client
( AuthenticationOptions (..), Credential (..), RegistrationOptions (..)
, createAssertion, createRegistration, parseAuthenticationOptions
, parseRegistrationOptions )
-- | Where a relying party's WebAuthn JSON endpoints live.
data Endpoints = Endpoints
{ endpointBaseUrl :: !Text
-- ^ Scheme, host and port, e.g. @https:\/\/gateway.example:9090@.
, endpointOrigin :: !Text
-- ^ The origin recorded in @clientDataJSON@, which a reverse proxy may make
-- different from 'endpointBaseUrl'. Use 'exampleEndpoints' when they match.
, endpointRegisterOptions :: !Text
-- ^ Path returning @PublicKeyCredentialCreationOptions@.
, endpointRegisterVerify :: !Text
-- ^ Path accepting the registration response.
, endpointLoginOptions :: !Text
-- ^ Path returning @PublicKeyCredentialRequestOptions@.
, endpointLoginVerify :: !Text
-- ^ Path accepting the assertion response and setting a session cookie.
, endpointSessionCookie :: !Text
-- ^ Name of the cookie that carries the resulting session token.
} deriving stock (Eq, Show)
-- | The auth API used by the shipped adapter.
exampleEndpoints :: Text -> Endpoints
exampleEndpoints baseUrl = Endpoints
{ endpointBaseUrl = baseUrl
, endpointOrigin = stripTrailingSlash baseUrl
, endpointRegisterOptions = "/api/auth/register/options"
, endpointRegisterVerify = "/api/auth/register/verify"
, endpointLoginOptions = "/api/auth/login/options"
, endpointLoginVerify = "/api/auth/login/verify"
, endpointSessionCookie = "session"
}
-- | Enroll a new credential. The extra headers are sent on both the options and
-- the verify request; some relying parties use them for a one-time enrollment
-- token.
enroll :: Endpoints -> [(HeaderName, ByteString)] -> IO (Either Text Credential)
enroll endpoints extraHeaders = do
mgr <- newManager tlsManagerSettings
options <- postJson mgr (url endpoints (endpointRegisterOptions endpoints))
extraHeaders (object [])
case options of
Left err -> pure (Left ("registration options request: " <> err))
Right (value, _) ->
case parseRegistrationOptions value of
Left err -> pure (Left ("registration options: " <> err))
Right ro -> do
(cred, response) <-
createRegistration (originOf endpoints) (roRpId ro) (roChallenge ro)
verified <- postJson mgr (url endpoints (endpointRegisterVerify endpoints))
extraHeaders response
pure $ case verified of
Left err -> Left ("registration verify request: " <> err)
Right _ -> Right cred
-- | Log in with an enrolled credential and return the session token and the
-- credential with its advanced sign counter. The caller must persist the
-- returned credential; use 'authenticateWithStore' to make that happen before
-- the assertion is sent.
authenticate :: Endpoints -> Credential -> IO (Either Text (Text, Credential))
authenticate endpoints = authenticateWithStore endpoints (\_ -> pure (Right ()))
-- | 'authenticate' with a persistence hook. The store is called with the
-- incremented credential /before/ the verify request is sent, so a lost
-- response can never make the next attempt replay an older counter.
authenticateWithStore
:: Endpoints
-> (Credential -> IO (Either Text ()))
-> Credential
-> IO (Either Text (Text, Credential))
authenticateWithStore endpoints store cred = do
mgr <- newManager tlsManagerSettings
options <- postJson mgr (url endpoints (endpointLoginOptions endpoints)) []
(object [])
case options of
Left err -> pure (Left ("login options request: " <> err))
Right (value, _) ->
case parseAuthenticationOptions value of
Left err -> pure (Left ("login options: " <> err))
Right ao -> do
(cred', response) <- createAssertion cred (aoChallenge ao)
saved <- store cred'
case saved of
Left err -> pure (Left ("could not persist the sign counter: " <> err))
Right () -> do
verified <- postJson mgr (url endpoints (endpointLoginVerify endpoints))
[] response
pure $ case verified of
Left err -> Left ("login verify request: " <> err)
Right (_, headers) ->
case sessionToken (endpointSessionCookie endpoints) headers of
Just token -> Right (token, cred')
Nothing -> Left
"the relying party accepted the assertion but set no session cookie"
-- | The value of @cookieName@ in a @Set-Cookie@ response, if present.
sessionToken :: Text -> [Header] -> Maybe Text
sessionToken cookieName headers = listToMaybe
[ T.takeWhile (/= ';') rest
| (name, value) <- headers
, name == hSetCookie
, let text = TE.decodeUtf8Lenient value
, Just rest <- [T.stripPrefix (cookieName <> "=") text]
, not (T.null rest)
]
-- ---------------------------------------------------------------------------
-- HTTP plumbing
-- ---------------------------------------------------------------------------
url :: Endpoints -> Text -> String
url endpoints path =
T.unpack (stripTrailingSlash (endpointBaseUrl endpoints) <> path)
originOf :: Endpoints -> Text
originOf = stripTrailingSlash . endpointOrigin
stripTrailingSlash :: Text -> Text
stripTrailingSlash = T.dropWhileEnd (== '/')
postJson
:: Manager -> String -> [(HeaderName, ByteString)] -> Value
-> IO (Either Text (Value, [Header]))
postJson mgr target extra body = do
req0 <- parseRequest ("POST " <> target)
let req = req0
{ requestHeaders = (hContentType, "application/json") : extra
, requestBody = RequestBodyLBS (A.encode body)
}
result <- try (httpLbs req mgr)
pure $ case result of
Left (e :: SomeException) ->
Left (T.pack target <> ": " <> T.pack (show e))
Right resp
| not (statusIsSuccessful (responseStatus resp)) ->
Left (responseError resp)
| otherwise ->
case A.decode (responseBody resp) of
Just value -> Right (value, responseHeaders resp)
Nothing -> Left (T.pack target <> ": response was not JSON")
responseError :: Response BL.ByteString -> Text
responseError resp =
let code = statusCode (responseStatus resp)
raw = BL.toStrict (responseBody resp)
detail = case A.decodeStrict' raw of
Just (Object o) ->
case (lookupString "error" o, lookupString "code" o) of
(Just msg, Just tag) -> msg <> " (" <> tag <> ")"
(Just msg, Nothing) -> msg
_ -> ""
_ -> ""
bodyText = T.strip (TE.decodeUtf8Lenient (BS.take 300 raw))
in "HTTP " <> T.pack (show code)
<> (if T.null detail
then if T.null bodyText then "" else ": " <> bodyText
else ": " <> detail)
lookupString :: Text -> A.Object -> Maybe Text
lookupString key o = case KeyMap.lookup (Key.fromText key) o of
Just (String s) -> Just s
_ -> Nothing