From 538569f5895834a9f7b8d4dcfd543be6fbfca37e Mon Sep 17 00:00:00 2001 From: Bastian Raschke Date: Thu, 28 Jan 2021 22:05:39 +0100 Subject: [PATCH] Catch `UnicodeDecodeError` when passing malformed data in authorization header (Fixes #122) --- flask_httpauth.py | 14 ++++++++++---- tests/test_basic_verify_password.py | 7 +++++++ 2 files changed, 17 insertions(+), 4 deletions(-) diff --git a/flask_httpauth.py b/flask_httpauth.py index 2c2d185..a1ff75b 100644 --- a/flask_httpauth.py +++ b/flask_httpauth.py @@ -169,9 +169,10 @@ def decorated(*args, **kwargs): return login_required_internal def username(self): - if not request.authorization: + auth = self.get_auth() + if not auth: return "" - return request.authorization.username + return auth.username def current_user(self): if hasattr(g, 'flask_httpauth_user'): @@ -205,9 +206,14 @@ def get_auth(self): username, password = b64decode(credentials).split(b':', 1) except (ValueError, TypeError): return None + try: + username = username.decode('utf-8') + password = password.decode('utf-8') + except UnicodeDecodeError: + username = None + password = None return Authorization( - scheme, {'username': username.decode('utf-8'), - 'password': password.decode('utf-8')}) + scheme, {'username': username, 'password': password}) def authenticate(self, auth, stored_password): if auth: diff --git a/tests/test_basic_verify_password.py b/tests/test_basic_verify_password.py index b552ecb..4f383ab 100644 --- a/tests/test_basic_verify_password.py +++ b/tests/test_basic_verify_password.py @@ -75,6 +75,13 @@ def test_verify_auth_login_invalid(self): self.assertEqual(response.status_code, 403) self.assertTrue('WWW-Authenticate' in response.headers) + def test_verify_auth_login_malformed_password(self): + creds = 'eyJhbGciOieyJp==' + response = self.client.get('/basic-verify', + headers={'Authorization': 'Basic ' + creds}) + self.assertEqual(response.status_code, 403) + self.assertTrue('WWW-Authenticate' in response.headers) + class HTTPAuthTestCaseOldStyle(HTTPAuthTestCase): use_old_style_callback = True