11module Hasura.Server.Auth.JWT
22 ( processJwt ,
33 RawJWT ,
4- StringOrURI (.. ),
54 JWTConfig (.. ),
65 JWTCtx (.. ),
76 Jose. JWKSet (.. ),
@@ -38,13 +37,10 @@ import Data.Aeson qualified as J
3837import Data.Aeson.Casing qualified as J
3938import Data.Aeson.Internal (JSONPath )
4039import Data.Aeson.TH qualified as J
41- import Data.ByteArray.Encoding qualified as BAE
42- import Data.ByteString.Internal qualified as B
4340import Data.ByteString.Lazy qualified as BL
4441import Data.ByteString.Lazy.Char8 qualified as BLC
4542import Data.CaseInsensitive qualified as CI
4643import Data.HashMap.Strict qualified as Map
47- import Data.Hashable
4844import Data.IORef (IORef , readIORef , writeIORef )
4945import Data.Parser.CacheControl
5046import Data.Parser.Expires
@@ -220,21 +216,6 @@ data JWTClaims
220216 | JCMap ! JWTCustomClaimsMap
221217 deriving (Show , Eq )
222218
223- -- | Hashable Wrapper for constructing a HashMap of JWTConfigs
224- newtype StringOrURI = StringOrURI { unStringOrURI :: Jose. StringOrURI}
225- deriving newtype (Show , Eq , J.ToJSON , J.FromJSON )
226-
227- instance J. ToJSONKey StringOrURI
228-
229- instance J. FromJSONKey StringOrURI
230-
231- instance J. ToJSONKey (Maybe StringOrURI )
232-
233- instance J. FromJSONKey (Maybe StringOrURI )
234-
235- instance Hashable StringOrURI where
236- hashWithSalt i = hashWithSalt i . J. encode
237-
238219-- | The JWT configuration we got from the user.
239220data JWTConfig = JWTConfig
240221 { jcKeyOrUrl :: ! (Either Jose. JWK URI ),
@@ -376,21 +357,6 @@ updateJwkRef (Logger logger) manager url jwkRef = do
376357
377358type ClaimsMap = Map. HashMap SessionVariable J. Value
378359
379- -- | Decode a Jose ClaimsSet without verifying the signature
380- decodeClaimsSet :: RawJWT -> Maybe Jose. ClaimsSet
381- decodeClaimsSet (RawJWT jwt) = do
382- (_, c, _) <- extractElems $ BL. splitWith (== B. c2w ' .' ) jwt
383- case BAE. convertFromBase BAE. Base64URLUnpadded $ BL. toStrict c of
384- Left _ -> Nothing
385- Right s -> J. decode $ BL. fromStrict s
386- where
387- extractElems (h : c : s : _) = Just (h, c, s)
388- extractElems _ = Nothing
389-
390- -- | Extract the issuer from a bearer tokena _without_ verifying it.
391- tokenIssuer :: RawJWT -> Maybe StringOrURI
392- tokenIssuer = coerce <$> (decodeClaimsSet >=> view Jose. claimIss)
393-
394360-- | Process the request headers to verify the JWT and extract UserInfo from it
395361-- From the JWT config, we check which header to expect, it can be the "Authorization"
396362-- or "Cookie" header
@@ -407,7 +373,7 @@ processJwt ::
407373 ( MonadIO m ,
408374 MonadError QErr m
409375 ) =>
410- Map. HashMap ( Maybe StringOrURI ) JWTCtx ->
376+ JWTCtx ->
411377 HTTP. RequestHeaders ->
412378 Maybe RoleName ->
413379 m (UserInfo , Maybe UTCTime , [N. Header ])
@@ -419,49 +385,29 @@ processJwt_ ::
419385 -- | mock 'processAuthZOrCookieHeader'
420386 (_JWTCtx -> BLC. ByteString -> m (Maybe (ClaimsMap , Maybe UTCTime ))) ->
421387 (_JWTCtx -> JWTHeader ) ->
422- Map. HashMap ( Maybe StringOrURI ) _JWTCtx ->
388+ _JWTCtx ->
423389 HTTP. RequestHeaders ->
424390 Maybe RoleName ->
425391 m (UserInfo , Maybe UTCTime , [N. Header ])
426- processJwt_ processAuthZOrCookieHeader_ fGetHeaderType jwtCtxs headers mUnAuthRole =
427- case find (liftA2 (||) (== CI. mk " Cookie" ) (== CI. mk " Authorization" ) . fst ) headers of
428- Nothing -> withoutAuthZHeader
429- Just (key, val) ->
430- let issuer = tokenIssuer (RawJWT $ BLC. fromStrict val)
431- in case (Map. size jwtCtxs, Map. elems jwtCtxs, Map. lookup issuer jwtCtxs) of
432- -- Note: In 2.1 prior to this commit, if the JWTCtx has
433- -- an Issuer specified, then a token with a matching or
434- -- absent issuer will validate, but a different issuer
435- -- will fail. We special case that by checking if the
436- -- size of the HashMap is 1:
437- (1 , [jwtCtx], Nothing ) -> withAuthZHeader val jwtCtx
438- (_, _, Nothing ) ->
439- case Map. lookup Nothing jwtCtxs of
440- Just jwtCtx -> withAuthZHeader val jwtCtx
441- Nothing -> throw400 InvalidHeaders " Could not verify JWT: Invalid Issuer"
442- (_, _, Just jwtCtx)
443- | key /= expectedHeader jwtCtx ->
444- throw400 InvalidHeaders $ " Missing " <> T. decodeUtf8 (CI. foldedCase $ expectedHeader jwtCtx) <> " header in JWT authentication mode"
445- (_, _, Just jwtCtx) -> withAuthZHeader val jwtCtx
392+ processJwt_ processAuthZOrCookieHeader_ fGetHeaderType jwtCtx headers mUnAuthRole =
393+ maybe withoutAuthZHeader withAuthZHeader mAuthZHeader
446394 where
447- expectedHeader jwtCtx =
395+ expectedHeader =
448396 case fGetHeaderType jwtCtx of
449- JHAuthorization -> CI. mk " Authorization"
450- JHCookie _ -> CI. mk " Cookie"
397+ JHAuthorization -> " Authorization"
398+ JHCookie _ -> " Cookie"
451399
452- withAuthZHeader authzHeader jwtCtx = do
400+ mAuthZHeader =
401+ find (\ (headerName, _) -> headerName == CI. mk expectedHeader) headers
402+
403+ withAuthZHeader (_, authzHeader) = do
453404 claimsMapTuple <- processAuthZOrCookieHeader_ jwtCtx (BL. fromStrict authzHeader)
454- -- if the requested cookie name is not present among the cookies available,
455- -- then fall back to unauthorized-role (if present)
405+
456406 case claimsMapTuple of
457407 Nothing -> withoutAuthZHeader
458408 Just (claimsMap, expTimeM) -> do
459409 HasuraClaims allowedRoles defaultRole <- parseHasuraClaims claimsMap
460- -- see if there is a x-hasura-role header, or else pick the default role.
461- -- The role returned is unauthenticated at this point:
462- let requestedRole =
463- fromMaybe defaultRole $
464- getRequestHeader userRoleHeader headers >>= mkRoleName . bsToTxt
410+ let requestedRole = fromMaybe defaultRole $ getRequestHeader userRoleHeader headers >>= mkRoleName . bsToTxt
465411
466412 when (requestedRole `notElem` allowedRoles) $
467413 throw400 AccessDenied " Your requested role is not in allowed roles"
@@ -484,7 +430,7 @@ processJwt_ processAuthZOrCookieHeader_ fGetHeaderType jwtCtxs headers mUnAuthRo
484430 where
485431 missingAuthzHeader =
486432 throw400 InvalidHeaders $
487- " Missing 'Authorization' or 'Cookie' header in JWT authentication mode"
433+ " Missing " <> bsToTxt expectedHeader <> " header in JWT authentication mode"
488434
489435-- | Parse and verify the 'Authorization' or 'Cookie' header (depending upon
490436-- the `jcHeader` value of the `JWTConfig`), returning either Nothing or the raw claims
@@ -499,9 +445,6 @@ processAuthZOrCookieHeader ::
499445 -- requested Cookie name is not present (returns "m Nothing")
500446 m (Maybe (ClaimsMap , Maybe UTCTime ))
501447processAuthZOrCookieHeader jwtCtx authzHeader = do
502- -- iss <- _ <$> Jose.decodeCompact (BL.fromStrict token)
503- -- let ctx = M.lookup iss jwtCtx
504-
505448 -- try to parse JWT token from Authorization or Cookie header
506449 jwt <-
507450 case jcxHeader jwtCtx of
0 commit comments