Skip to content

Commit 4121c1d

Browse files
ecthienderpranshi06
authored andcommitted
Revert "Feature/multiple jwt secrets"
PR-URL: hasura/graphql-engine-mono#3136 Co-authored-by: pranshi06 <85474619+pranshi06@users.noreply.github.com> GitOrigin-RevId: aa41817
1 parent 5726852 commit 4121c1d

13 files changed

Lines changed: 85 additions & 204 deletions

File tree

‎docs/graphql/cloud/security/index.rst‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,4 +31,3 @@ Features
3131
api-limits
3232
disable-graphql-introspection
3333
rotating-admin-secrets
34-
multiple-jwt-secrets

‎docs/graphql/cloud/security/mutiple-jwt-secrets.rst‎

Lines changed: 0 additions & 43 deletions
This file was deleted.

‎server/graphql-engine.cabal‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -156,7 +156,6 @@ library
156156
, mtl
157157
, openapi3
158158
, optparse-applicative
159-
, optparse-generic
160159
, parsec
161160
, pg-client
162161
, postgresql-binary

‎server/src-lib/Hasura/Prelude.hs‎

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,6 @@ module Hasura.Prelude
2121
liftEitherM,
2222
hoistMaybe,
2323
hoistEither,
24-
readJson,
2524
tshow,
2625

2726
-- * Trace debugging
@@ -268,9 +267,6 @@ hoistEither = ExceptT . pure
268267
tshow :: Show a => a -> Text
269268
tshow = T.pack . show
270269

271-
readJson :: (J.FromJSON a) => String -> Either String a
272-
readJson = J.eitherDecodeStrict . txtToBs . T.pack
273-
274270
-- | Customized 'J.Options' which apply "snake case" to Generic or Template
275271
-- Haskell JSON derivations.
276272
--

‎server/src-lib/Hasura/Server/API/Config.hs‎

Lines changed: 9 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@ module Hasura.Server.API.Config
77
where
88

99
import Data.Aeson.TH
10-
import Data.HashMap.Strict qualified as Map
1110
import Data.HashSet qualified as Set
1211
import Hasura.GraphQL.Execute.LiveQuery.Options qualified as LQ
1312
import Hasura.Prelude
@@ -36,7 +35,7 @@ data ServerConfig = ServerConfig
3635
scfgIsAdminSecretSet :: !Bool,
3736
scfgIsAuthHookSet :: !Bool,
3837
scfgIsJwtSet :: !Bool,
39-
scfgJwt :: !(Map.HashMap (Maybe StringOrURI) JWTInfo),
38+
scfgJwt :: !(Maybe JWTInfo),
4039
scfgIsAllowListEnabled :: !Bool,
4140
scfgLiveQueries :: !LQ.LiveQueriesOptions,
4241
scfgConsoleAssetsDir :: !(Maybe Text),
@@ -91,12 +90,11 @@ isJWTSet = \case
9190
AMAdminSecretAndJWT {} -> True
9291
_ -> False
9392

94-
getJWTInfo :: AuthMode -> Map.HashMap (Maybe StringOrURI) JWTInfo
95-
getJWTInfo (AMAdminSecretAndJWT _ jwtCtxs _) =
96-
let f jwtCtx = case jcxClaims jwtCtx of
97-
JCNamespace namespace claimsFormat ->
98-
JWTInfo namespace claimsFormat Nothing
99-
JCMap claimsMap ->
100-
JWTInfo (ClaimNs defaultClaimsNamespace) defaultClaimsFormat $ Just claimsMap
101-
in fmap f jwtCtxs
102-
getJWTInfo _ = mempty
93+
getJWTInfo :: AuthMode -> Maybe JWTInfo
94+
getJWTInfo (AMAdminSecretAndJWT _ jwtCtx _) =
95+
Just $ case jcxClaims jwtCtx of
96+
JCNamespace namespace claimsFormat ->
97+
JWTInfo namespace claimsFormat Nothing
98+
JCMap claimsMap ->
99+
JWTInfo (ClaimNs defaultClaimsNamespace) defaultClaimsFormat $ Just claimsMap
100+
getJWTInfo _ = Nothing

‎server/src-lib/Hasura/Server/Auth.hs‎

Lines changed: 16 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,6 @@ import Control.Monad.Trans.Managed (ManagedT)
3333
import Crypto.Hash qualified as Crypto
3434
import Data.ByteArray qualified as BA
3535
import Data.ByteString (ByteString)
36-
import Data.HashMap.Strict qualified as Map
3736
import Data.HashSet qualified as Set
3837
import Data.Hashable qualified as Hash
3938
import Data.IORef (newIORef)
@@ -97,7 +96,7 @@ data AuthMode
9796
= AMNoAuth
9897
| AMAdminSecret !(Set.HashSet AdminSecretHash) !(Maybe RoleName)
9998
| AMAdminSecretAndHook !(Set.HashSet AdminSecretHash) !AuthHook
100-
| AMAdminSecretAndJWT !(Set.HashSet AdminSecretHash) !(Map.HashMap (Maybe StringOrURI) JWTCtx) !(Maybe RoleName)
99+
| AMAdminSecretAndJWT !(Set.HashSet AdminSecretHash) !JWTCtx !(Maybe RoleName)
101100
deriving (Show, Eq)
102101

103102
-- | Validate the user's requested authentication configuration, launching any
@@ -110,17 +109,17 @@ setupAuthMode ::
110109
) =>
111110
Set.HashSet AdminSecretHash ->
112111
Maybe AuthHook ->
113-
Map.HashMap (Maybe StringOrURI) JWTConfig ->
112+
Maybe JWTConfig ->
114113
Maybe RoleName ->
115114
H.Manager ->
116115
Logger Hasura ->
117116
ExceptT Text (ManagedT m) AuthMode
118-
setupAuthMode adminSecretHashSet mWebHook mJwtSecrets mUnAuthRole httpManager logger =
119-
case (not (Set.null adminSecretHashSet), mWebHook, not (Map.null mJwtSecrets)) of
120-
(True, Nothing, False) -> return $ AMAdminSecret adminSecretHashSet mUnAuthRole
121-
(True, Nothing, True) -> do
122-
jwtCtxs <- mkJwtCtxs mJwtSecrets
123-
pure $ AMAdminSecretAndJWT adminSecretHashSet jwtCtxs mUnAuthRole
117+
setupAuthMode adminSecretHashSet mWebHook mJwtSecret mUnAuthRole httpManager logger =
118+
case (not (Set.null adminSecretHashSet), mWebHook, mJwtSecret) of
119+
(True, Nothing, Nothing) -> return $ AMAdminSecret adminSecretHashSet mUnAuthRole
120+
(True, Nothing, Just jwtConf) -> do
121+
jwtCtx <- mkJwtCtx jwtConf
122+
return $ AMAdminSecretAndJWT adminSecretHashSet jwtCtx mUnAuthRole
124123
-- Nothing below this case uses unauth role. Throw a fatal error if we would otherwise ignore
125124
-- that parameter, lest users misunderstand their auth configuration:
126125
_
@@ -129,26 +128,18 @@ setupAuthMode adminSecretHashSet mWebHook mJwtSecrets mUnAuthRole httpManager lo
129128
"Fatal Error: --unauthorized-role (HASURA_GRAPHQL_UNAUTHORIZED_ROLE)"
130129
<> requiresAdminScrtMsg
131130
<> " and is not allowed when --auth-hook (HASURA_GRAPHQL_AUTH_HOOK) is set"
132-
(False, Nothing, False) -> return AMNoAuth
133-
(True, Just hook, False) -> return $ AMAdminSecretAndHook adminSecretHashSet hook
134-
(False, Just _, False) ->
131+
(False, Nothing, Nothing) -> return AMNoAuth
132+
(True, Just hook, Nothing) -> return $ AMAdminSecretAndHook adminSecretHashSet hook
133+
(False, Just _, Nothing) ->
135134
throwError $
136135
"Fatal Error : --auth-hook (HASURA_GRAPHQL_AUTH_HOOK)" <> requiresAdminScrtMsg
137-
(False, Nothing, True) ->
136+
(False, Nothing, Just _) ->
138137
throwError $
139138
"Fatal Error : --jwt-secret (HASURA_GRAPHQL_JWT_SECRET)" <> requiresAdminScrtMsg
140-
(_, Just _, True) ->
139+
(_, Just _, Just _) ->
141140
throwError
142141
"Fatal Error: Both webhook and JWT mode cannot be enabled at the same time"
143142
where
144-
mkJwtCtxs ::
145-
( ForkableMonadIO m,
146-
Tracing.HasReporter m
147-
) =>
148-
Map.HashMap (Maybe StringOrURI) JWTConfig ->
149-
ExceptT Text (ManagedT m) (Map.HashMap (Maybe StringOrURI) JWTCtx)
150-
mkJwtCtxs = traverse mkJwtCtx
151-
152143
requiresAdminScrtMsg =
153144
" requires --admin-secret (HASURA_GRAPHQL_ADMIN_SECRET) or "
154145
<> " --access-key (HASURA_GRAPHQL_ACCESS_KEY) to be set"
@@ -213,7 +204,7 @@ getUserInfoWithExpTime_ ::
213204
m (UserInfo, Maybe UTCTime, [N.Header])
214205
) ->
215206
-- | mock 'processJwt'
216-
(Map.HashMap (Maybe StringOrURI) JWTCtx -> [N.Header] -> Maybe RoleName -> m (UserInfo, Maybe UTCTime, [N.Header])) ->
207+
(JWTCtx -> [N.Header] -> Maybe RoleName -> m (UserInfo, Maybe UTCTime, [N.Header])) ->
217208
_Logger_Hasura ->
218209
_Manager ->
219210
[N.Header] ->
@@ -241,8 +232,8 @@ getUserInfoWithExpTime_ userInfoFromAuthHook_ processJwt_ logger manager rawHead
241232
-- this is the case that actually ends up consuming the request AST
242233
AMAdminSecretAndHook adminSecretHashSet hook ->
243234
checkingSecretIfSent adminSecretHashSet $ userInfoFromAuthHook_ logger manager hook rawHeaders reqs
244-
AMAdminSecretAndJWT adminSecretHashSet jwtSecrets unAuthRole ->
245-
checkingSecretIfSent adminSecretHashSet $ processJwt_ jwtSecrets rawHeaders unAuthRole
235+
AMAdminSecretAndJWT adminSecretHashSet jwtSecret unAuthRole ->
236+
checkingSecretIfSent adminSecretHashSet $ processJwt_ jwtSecret rawHeaders unAuthRole
246237
where
247238
-- CAREFUL!:
248239
mkUserInfoFallbackAdminRole adminSecretState =

‎server/src-lib/Hasura/Server/Auth/JWT.hs‎

Lines changed: 14 additions & 71 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
module 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
3837
import Data.Aeson.Casing qualified as J
3938
import Data.Aeson.Internal (JSONPath)
4039
import Data.Aeson.TH qualified as J
41-
import Data.ByteArray.Encoding qualified as BAE
42-
import Data.ByteString.Internal qualified as B
4340
import Data.ByteString.Lazy qualified as BL
4441
import Data.ByteString.Lazy.Char8 qualified as BLC
4542
import Data.CaseInsensitive qualified as CI
4643
import Data.HashMap.Strict qualified as Map
47-
import Data.Hashable
4844
import Data.IORef (IORef, readIORef, writeIORef)
4945
import Data.Parser.CacheControl
5046
import 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.
239220
data JWTConfig = JWTConfig
240221
{ jcKeyOrUrl :: !(Either Jose.JWK URI),
@@ -376,21 +357,6 @@ updateJwkRef (Logger logger) manager url jwkRef = do
376357

377358
type 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))
501447
processAuthZOrCookieHeader 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

‎server/src-lib/Hasura/Server/Init.hs‎

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,6 @@ import Data.Aeson qualified as J
1313
import Data.Aeson.TH qualified as J
1414
import Data.ByteString.Char8 (pack, unpack)
1515
import Data.FileEmbed (embedStringFile, makeRelativeToProject)
16-
import Data.HashMap.Strict qualified as Map
1716
import Data.HashSet qualified as Set
1817
import Data.String qualified as DataString
1918
import Data.Text qualified as T
@@ -30,7 +29,6 @@ import Hasura.Logging qualified as L
3029
import Hasura.Prelude
3130
import Hasura.RQL.Types
3231
import Hasura.Server.Auth
33-
import Hasura.Server.Auth.JWT
3432
import Hasura.Server.Cors
3533
import Hasura.Server.Init.Config
3634
import Hasura.Server.Logging
@@ -189,8 +187,7 @@ mkServeOptions rso = do
189187
txIso <- fromMaybe Q.ReadCommitted <$> withEnv (rsoTxIso rso) (fst txIsoEnv)
190188
adminScrt <- fmap (maybe mempty Set.singleton) $ withEnvs (rsoAdminSecret rso) $ map fst [adminSecretEnv, accessKeyEnv]
191189
authHook <- mkAuthHook $ rsoAuthHook rso
192-
jwtSecret' <- withEnvJwtConf (rsoJwtSecret rso) $ fst jwtSecretEnv
193-
let jwtSecret = maybe mempty (uncurry Map.singleton) $ ((coerce . jcIssuer) &&& id) <$> jwtSecret'
190+
jwtSecret <- withEnvJwtConf (rsoJwtSecret rso) $ fst jwtSecretEnv
194191
unAuthRole <- withEnv (rsoUnAuthRole rso) $ fst unAuthRoleEnv
195192
corsCfg <- mkCorsConfig $ rsoCorsConfig rso
196193
enableConsole <-

0 commit comments

Comments
 (0)