From 1b40b95d1906069f0d908b1a74f4896ba52296fb Mon Sep 17 00:00:00 2001 From: "Maxime Alves LIRMM@home" Date: Thu, 27 Aug 2020 18:09:48 +0200 Subject: [PATCH] [auth] fix bug when "debug flag" = False in token --- halfapi/lib/jwt_middleware.py | 4 +-- tests/test_jwt_middleware.py | 52 +++++++++++++++++++++++++++++++++++ 2 files changed, 54 insertions(+), 2 deletions(-) diff --git a/halfapi/lib/jwt_middleware.py b/halfapi/lib/jwt_middleware.py index 1d8d91c..ecbf319 100644 --- a/halfapi/lib/jwt_middleware.py +++ b/halfapi/lib/jwt_middleware.py @@ -46,7 +46,7 @@ try: except ImportError: logger.warning('Could not import PRODUCTION variable from conf module,'\ ' using HALFAPI_PROD environment variable') - PRODUCTION = environ.get('HALFAPI_PROD') or False + PRODUCTION = bool(environ.get('HALFAPI_PROD', False)) try: from ..conf import SECRET @@ -106,7 +106,7 @@ class JWTAuthenticationBackend(AuthenticationBackend): algorithms=self.algorithm, verify=True) - if PRODUCTION and 'debug' in payload.keys(): + if PRODUCTION and 'debug' in payload.keys() and payload['debug']: raise AuthenticationError( 'Trying to connect using *DEBUG* token in *PRODUCTION* mode') diff --git a/tests/test_jwt_middleware.py b/tests/test_jwt_middleware.py index ac70551..b5f81ee 100644 --- a/tests/test_jwt_middleware.py +++ b/tests/test_jwt_middleware.py @@ -58,6 +58,27 @@ def token_builder(): key=SECRET ) +@pytest.fixture +def token_debug_false_builder(): + yield jwt.encode({ + 'name':'xxx', + 'id': str(uuid4()), + 'debug': False}, + key=SECRET + ) + + +@pytest.fixture +def token_debug_true_builder(): + yield jwt.encode({ + 'name':'xxx', + 'id': str(uuid4()), + 'debug': True}, + key=SECRET + ) + + + @pytest.fixture def token_dirser(): @@ -142,3 +163,34 @@ async def test_JWTAuthenticationBackend(token_builder): credentials, user = await backend.authenticate(req) assert type(user) == JWTUser assert type(credentials) == AuthCredentials + + +@pytest.mark.asyncio +async def test_JWTAuthenticationBackend_DebugFalse(token_debug_false_builder): + backend = JWTAuthenticationBackend() + assert backend.secret_key == SECRET + + req = Request( + headers={ + 'Authorization': token_debug_false_builder + }) + + credentials, user = await backend.authenticate(req) + assert type(user) == JWTUser + assert type(credentials) == AuthCredentials + + +@pytest.mark.asyncio +async def test_JWTAuthenticationBackend_DebugTrue(token_debug_true_builder): + backend = JWTAuthenticationBackend() + assert backend.secret_key == SECRET + + req = Request( + headers={ + 'Authorization': token_debug_true_builder + }) + + try: + await backend.authenticate(req) + except Exception as e: + assert type(e) == AuthenticationError