From abd81c998bd929ec88017f2231053e5d89011cfc Mon Sep 17 00:00:00 2001 From: Diogo Biazus Date: Sat, 21 May 2016 13:18:45 -0400 Subject: [PATCH] jwtClaims should always return Left for invalid JWT --- src/PostgREST/Auth.hs | 26 ++++++++++++-------------- src/PostgREST/Middleware.hs | 5 +---- 2 files changed, 13 insertions(+), 18 deletions(-) diff --git a/src/PostgREST/Auth.hs b/src/PostgREST/Auth.hs index d422b4a7d..ed6591f4f 100644 --- a/src/PostgREST/Auth.hs +++ b/src/PostgREST/Auth.hs @@ -25,7 +25,7 @@ import Data.Aeson.Types (parseMaybe, emptyObject, emptyArray) import qualified Data.ByteString as BS import qualified Data.Vector as V import qualified Data.HashMap.Strict as M -import Data.Maybe (fromMaybe, maybeToList) +import Data.Maybe (fromMaybe, maybeToList, fromJust) import Data.Monoid ((<>)) import Data.String.Conversions (cs) import Data.Text (Text) @@ -52,22 +52,20 @@ claimsToSQL claims = roleStmts <> varStmts {-| Receives the JWT secret (from config) and a JWT and returns a map of JWT claims - In case there is any problem decoding the JWT it returns Nothing. + In case there is any problem decoding the JWT it returns an error Text -} - - jwtClaims :: JWT.Secret -> Text -> NominalDiffTime -> Either Text (M.HashMap Text Value) -jwtClaims secret input time = - case mClaims of - Nothing -> Right M.empty - Just claims -> do - let mExp = claims ^? key "exp" . _Integer - expired = fromMaybe False $ (<= time) . fromInteger <$> mExp - if expired - then Left "JWT expired" - else Right (value2map claims) +jwtClaims _ "" _ = Right M.empty +jwtClaims secret jwt time = + case isExpired <$> mClaims of + Just True -> Left "JWT expired" + Nothing -> Left "Invalid JWT" + Just False -> Right $ value2map $ fromJust mClaims where - mClaims = toJSON . JWT.claims <$> JWT.decodeAndVerifySignature secret input + isExpired claims = + let mExp = claims ^? key "exp" . _Integer + in fromMaybe False $ (<= time) . fromInteger <$> mExp + mClaims = toJSON . JWT.claims <$> JWT.decodeAndVerifySignature secret jwt value2map (Object o) = o value2map _ = M.empty diff --git a/src/PostgREST/Middleware.hs b/src/PostgREST/Middleware.hs index b1be406c4..969b20c09 100644 --- a/src/PostgREST/Middleware.hs +++ b/src/PostgREST/Middleware.hs @@ -30,10 +30,7 @@ runWithClaims :: AppConfig -> Either Text (M.HashMap Text Value) -> runWithClaims conf eClaims app req = case eClaims of Left e -> clientErr e - Right claims -> - if M.null claims && not (null $ iJWT req) - then clientErr "Invalid JWT" - else do + Right claims -> do -- role claim defaults to anon if not specified in jwt H.sql . mconcat . claimsToSQL $ M.union claims (M.singleton "role" anon) app req