Skip to content

Commit dee8645

Browse files
pranshi06hasura-bot
authored andcommitted
server: fallback to unauthorised role when JWT is not found in cookie
PR-URL: hasura/graphql-engine-mono#2882 GitOrigin-RevId: ad03fbd
1 parent d7ac98d commit dee8645

9 files changed

Lines changed: 139 additions & 33 deletions

File tree

‎.circleci/server-test-names.txt‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ jwt-claims-map-with-json-path-values
1313
jwt-claims-map-with-literal-values
1414
jwt-with-expiry-time-leeway
1515
jwt-cookie
16+
jwt-cookie-unauthorized-role
1617
cors-domains
1718
auth-webhook-cookie
1819
ws-init-cookie-read-cors-enabled

‎.circleci/test-server.sh‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -554,6 +554,35 @@ case "$SERVER_TEST_TO_RUN" in
554554
unset HASURA_GRAPHQL_JWT_SECRET
555555
;;
556556

557+
jwt-cookie-unauthorized-role)
558+
echo -e "\n$(time_elapsed): <########## TEST GRAPHQL-ENGINE WITH JWT (in cookie mode) AND UNAUTHORIZED ROLE #####################################>\n"
559+
TEST_TYPE="jwt-cookie-unauthorized-role"
560+
561+
init_jwt
562+
563+
export HASURA_GRAPHQL_JWT_SECRET="$(jq -n --arg key "$(cat $OUTPUT_FOLDER/ssl/jwt_public.key)" '{ type: "RS512", key: $key , header: {"type": "Cookie", "name": "hasura_user"}}')"
564+
export HASURA_GRAPHQL_ADMIN_SECRET="HGE$RANDOM$RANDOM"
565+
export HASURA_GRAPHQL_UNAUTHORIZED_ROLE="anonymous"
566+
567+
run_hge_with_args serve
568+
569+
wait_for_port 8080
570+
pytest -n 1 --hge-urls "$HGE_URL" --pg-urls "$HASURA_GRAPHQL_DATABASE_URL" --hge-key="$HASURA_GRAPHQL_ADMIN_SECRET" --hge-jwt-key-file="$OUTPUT_FOLDER/ssl/jwt_private.key" --hge-jwt-conf="$HASURA_GRAPHQL_JWT_SECRET" --test-unauthorized-role test_graphql_queries.py::TestFallbackUnauthorizedRoleCookie
571+
572+
kill_hge_servers
573+
574+
unset HASURA_GRAPHQL_UNAUTHORIZED_ROLE
575+
576+
run_hge_with_args serve
577+
578+
wait_for_port 8080
579+
pytest -n 1 --hge-urls "$HGE_URL" --pg-urls "$HASURA_GRAPHQL_DATABASE_URL" --hge-key="$HASURA_GRAPHQL_ADMIN_SECRET" --hge-jwt-key-file="$OUTPUT_FOLDER/ssl/jwt_private.key" --hge-jwt-conf="$HASURA_GRAPHQL_JWT_SECRET" --test-no-cookie-and-unauth-role test_graphql_queries.py::TestMissingUnauthorizedRoleAndCookie
580+
581+
kill_hge_servers
582+
583+
unset HASURA_GRAPHQL_JWT_SECRET
584+
;;
585+
557586
# test with CORS modes
558587
cors-domains)
559588
echo -e "\n$(time_elapsed): <########## TEST GRAPHQL-ENGINE WITH CORS DOMAINS ########>\n"

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
- server: support database-to-database joins with BigQuery
1818
- server: improved startup time when using large remote schemas
1919
- server: fix rest-endpoints bug allow list arguments (fix #7135)
20+
- server: fallback to unauthorized role when JWT is not found in cookie (fix #7272)
2021
- console: add comments to tracked functions
2122
- console: add select all columns option while selecting the columns in event triggers
2223
- console: add request transforms for events

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

Lines changed: 38 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -417,7 +417,7 @@ processJwt = processJwt_ processAuthZOrCookieHeader jcxHeader
417417
processJwt_ ::
418418
(MonadError QErr m) =>
419419
-- | mock 'processAuthZOrCookieHeader'
420-
(_JWTCtx -> BLC.ByteString -> m (ClaimsMap, Maybe UTCTime)) ->
420+
(_JWTCtx -> BLC.ByteString -> m (Maybe (ClaimsMap, Maybe UTCTime))) ->
421421
(_JWTCtx -> JWTHeader) ->
422422
Map.HashMap (Maybe StringOrURI) _JWTCtx ->
423423
HTTP.RequestHeaders ->
@@ -450,26 +450,30 @@ processJwt_ processAuthZOrCookieHeader_ fGetHeaderType jwtCtxs headers mUnAuthRo
450450
JHCookie _ -> CI.mk "Cookie"
451451

452452
withAuthZHeader authzHeader jwtCtx = do
453-
(claimsMap, expTimeM) <- processAuthZOrCookieHeader_ jwtCtx $ BL.fromStrict authzHeader
454-
455-
HasuraClaims allowedRoles defaultRole <- parseHasuraClaims claimsMap
456-
-- see if there is a x-hasura-role header, or else pick the default role.
457-
-- The role returned is unauthenticated at this point:
458-
let requestedRole =
459-
fromMaybe defaultRole $
460-
getRequestHeader userRoleHeader headers >>= mkRoleName . bsToTxt
461-
462-
when (requestedRole `notElem` allowedRoles) $
463-
throw400 AccessDenied "Your requested role is not in allowed roles"
464-
let finalClaims =
465-
Map.delete defaultRoleClaim . Map.delete allowedRolesClaim $ claimsMap
466-
467-
let finalClaimsObject = mapKeys sessionVariableToText finalClaims
468-
metadata <- parseJwtClaim (J.Object $ finalClaimsObject) "x-hasura-* claims"
469-
userInfo <-
470-
mkUserInfo (URBPreDetermined requestedRole) UAdminSecretNotSent $
471-
mkSessionVariablesText metadata
472-
pure (userInfo, expTimeM, [])
453+
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)
456+
case claimsMapTuple of
457+
Nothing -> withoutAuthZHeader
458+
Just (claimsMap, expTimeM) -> do
459+
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
465+
466+
when (requestedRole `notElem` allowedRoles) $
467+
throw400 AccessDenied "Your requested role is not in allowed roles"
468+
let finalClaims =
469+
Map.delete defaultRoleClaim . Map.delete allowedRolesClaim $ claimsMap
470+
471+
let finalClaimsObject = mapKeys sessionVariableToText finalClaims
472+
metadata <- parseJwtClaim (J.Object $ finalClaimsObject) "x-hasura-* claims"
473+
userInfo <-
474+
mkUserInfo (URBPreDetermined requestedRole) UAdminSecretNotSent $
475+
mkSessionVariablesText metadata
476+
pure (userInfo, expTimeM, [])
473477

474478
withoutAuthZHeader = do
475479
unAuthRole <- onNothing mUnAuthRole missingAuthzHeader
@@ -483,33 +487,38 @@ processJwt_ processAuthZOrCookieHeader_ fGetHeaderType jwtCtxs headers mUnAuthRo
483487
"Missing 'Authorization' or 'Cookie' header in JWT authentication mode"
484488

485489
-- | Parse and verify the 'Authorization' or 'Cookie' header (depending upon
486-
-- the `jcHeader` value of the `JWTConfig`), returning the raw claims
490+
-- the `jcHeader` value of the `JWTConfig`), returning either Nothing or the raw claims
487491
-- object, and the expiration, if any.
488492
processAuthZOrCookieHeader ::
489493
( MonadIO m,
490494
MonadError QErr m
491495
) =>
492496
JWTCtx ->
493497
BLC.ByteString ->
494-
m (ClaimsMap, Maybe UTCTime)
498+
-- The "Maybe" in "m (Maybe (...))" covers the case where the
499+
-- requested Cookie name is not present (returns "m Nothing")
500+
m (Maybe (ClaimsMap, Maybe UTCTime))
495501
processAuthZOrCookieHeader jwtCtx authzHeader = do
496502
--iss <- _ <$> Jose.decodeCompact (BL.fromStrict token)
497503
--let ctx = M.lookup iss jwtCtx
498504

499505
-- try to parse JWT token from Authorization or Cookie header
500506
jwt <-
501507
case jcxHeader jwtCtx of
502-
JHAuthorization -> parseAuthzHeader
508+
JHAuthorization -> Just <$> parseAuthzHeader
503509
JHCookie cName -> parseCookieHeader cName
504510

505511
-- verify the JWT
506-
claims <- liftJWTError invalidJWTError $ verifyJwt jwtCtx $ RawJWT jwt
512+
case jwt of
513+
Nothing -> pure Nothing
514+
Just jwt' -> do
515+
claims <- liftJWTError invalidJWTError $ verifyJwt jwtCtx $ RawJWT jwt'
507516

508-
let expTimeM = fmap (\(Jose.NumericDate t) -> t) $ claims ^. Jose.claimExp
517+
let expTimeM = fmap (\(Jose.NumericDate t) -> t) $ claims ^. Jose.claimExp
509518

510-
claimsObject <- parseClaimsMap claims claimsConfig
519+
claimsObject <- parseClaimsMap claims claimsConfig
511520

512-
pure $ (claimsObject, expTimeM)
521+
pure $ Just (claimsObject, expTimeM)
513522
where
514523
claimsConfig = jcxClaims jwtCtx
515524
parseAuthzHeader = do
@@ -521,7 +530,7 @@ processAuthZOrCookieHeader jwtCtx authzHeader = do
521530
parseCookieHeader cName = do
522531
let cookies = Spock.parseCookies $ BL.toStrict authzHeader
523532
jwtCookie = snd <$> find (\(hn, _) -> hn == cName) cookies
524-
BL.fromStrict . txtToBs <$> (onNothing jwtCookie (malformedCookieHeader cName))
533+
pure $ BL.fromStrict . txtToBs <$> jwtCookie
525534

526535
liftJWTError :: (MonadError e' m) => (e -> e') -> ExceptT e m a -> m a
527536
liftJWTError ef action = do
@@ -534,9 +543,6 @@ processAuthZOrCookieHeader jwtCtx authzHeader = do
534543
malformedAuthzHeader =
535544
throw400 InvalidHeaders "Malformed Authorization header"
536545

537-
malformedCookieHeader c =
538-
throw400 InvalidHeaders $ "Could not find " <> c <> " in Cookie header"
539-
540546
-- | parse the claims map from the JWT token or custom claims from the JWT config
541547
parseClaimsMap ::
542548
MonadError QErr m =>

‎server/src-test/Hasura/Server/AuthSpec.hs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,7 @@ getUserInfoWithExpTimeTests = describe "getUserInfo" $ do
6767
(mkSessionVariablesHeaders mempty)
6868

6969
processAuthZHeader _jwtCtx _authzHeader =
70-
return (mapKeys mkSessionVariable claims, Nothing)
70+
return $ Just (mapKeys mkSessionVariable claims, Nothing)
7171

7272
processJwt = processJwt_ processAuthZHeader (const JHAuthorization)
7373

‎server/tests-py/conftest.py‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -155,6 +155,12 @@ def pytest_addoption(parser):
155155
help="Run testcases for unauthorized role",
156156
)
157157

158+
parser.addoption(
159+
"--test-no-cookie-and-unauth-role",
160+
action="store_true",
161+
help="Run testcases for no unauthorized role and no cookie jwt header set (cookie auth is set as part of jwt config upon engine startup)",
162+
)
163+
158164
parser.addoption(
159165
"--enable-remote-schema-permissions",
160166
action="store_true",
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
description: Make request with role header not set (no unAuthorized role either) and cookie JWT header not set
2+
url: /v1/graphql
3+
status: 200
4+
# set a random cookie so that header length is not 0
5+
headers:
6+
Cookie: 'refresh_token=john_doe'
7+
response:
8+
errors:
9+
- extensions:
10+
path: $
11+
code: invalid-headers
12+
message: Missing 'Authorization' or 'Cookie' header in JWT authentication mode
13+
query:
14+
query: |
15+
query {
16+
user{
17+
id
18+
}
19+
}
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
description: Make request with role header value as anonymous and cookie JWT header not set
2+
url: /v1/graphql
3+
status: 200
4+
headers:
5+
X-Hasura-Role: 'anonymous'
6+
response:
7+
data:
8+
user:
9+
- id: 3
10+
query:
11+
query: |
12+
query {
13+
user{
14+
id
15+
}
16+
}

‎server/tests-py/test_graphql_queries.py‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1211,6 +1211,34 @@ def dir(cls):
12111211
def test_unauth_role(self, hge_ctx, transport):
12121212
check_query_f(hge_ctx, self.dir() + '/unauthorized_role.yaml', transport, False)
12131213

1214+
@pytest.mark.skipif(
1215+
not PytestConf.config.getoption("--test-unauthorized-role"),
1216+
reason="--test-unauthorized-role missing"
1217+
)
1218+
@pytest.mark.parametrize('transport', ['http'])
1219+
@usefixtures('per_class_tests_db_state')
1220+
class TestFallbackUnauthorizedRoleCookie:
1221+
@classmethod
1222+
def dir(cls):
1223+
return 'queries/unauthorized_role'
1224+
1225+
def test_fallback_unauth_role_jwt_cookie_not_set(self, hge_ctx, transport):
1226+
check_query_f(hge_ctx, self.dir() + '/cookie_header_absent_unauth_role_set.yaml', transport, add_auth=False)
1227+
1228+
@pytest.mark.skipif(
1229+
not PytestConf.config.getoption("--test-no-cookie-and-unauth-role"),
1230+
reason="--test-no-cookie-and-unauth-role missing"
1231+
)
1232+
@pytest.mark.parametrize('transport', ['http'])
1233+
@usefixtures('per_class_tests_db_state')
1234+
class TestMissingUnauthorizedRoleAndCookie:
1235+
@classmethod
1236+
def dir(cls):
1237+
return 'queries/unauthorized_role'
1238+
1239+
def test_error_unauth_role_not_set_jwt_cookie_not_set(self, hge_ctx, transport):
1240+
check_query_f(hge_ctx, self.dir() + '/cookie_header_absent_unauth_role_not_set.yaml', transport, add_auth=False)
1241+
12141242
@usefixtures('per_class_tests_db_state')
12151243
class TestGraphQLExplain:
12161244
@classmethod

0 commit comments

Comments
 (0)