Skip to content

Commit

Permalink
Add logging and exception for access token failure
Browse files Browse the repository at this point in the history
  • Loading branch information
kevincarrogan committed Aug 27, 2024
1 parent cde2e62 commit 1c32c9e
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 1 deletion.
8 changes: 8 additions & 0 deletions mail/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,10 @@
logger = logging.getLogger(__name__)


class AuthenticationError(Exception):
pass


class Authenticator(Protocol):
user: str

Expand Down Expand Up @@ -66,6 +70,10 @@ def _get_access_token(self):
logger.info("Token not found in cache")
result = self.app.acquire_token_for_client(scopes=scopes)

if "access_token" not in result:
logger.info(result)
raise AuthenticationError("No access token found")

return result["access_token"]

def _encode_access_string(self, username, access_token):
Expand Down
45 changes: 44 additions & 1 deletion mail/tests/test_auth.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,15 @@
import base64
import uuid
from poplib import POP3_SSL
from unittest.mock import MagicMock, call, patch

from django.test import SimpleTestCase

from mail.auth import BasicAuthentication, ModernAuthentication
from mail.auth import (
AuthenticationError,
BasicAuthentication,
ModernAuthentication,
)


class BasicAuthenticationTests(SimpleTestCase):
Expand Down Expand Up @@ -128,6 +133,44 @@ def test_authenticates_connection_without_silent_acquisition(self):
]
)

def test_error_acquiring_access_token(self):
pop3conn = MagicMock(spec=POP3_SSL)
mock_conn = pop3conn()

username = "username"
client_id = "client_id"
client_secret = "client_secret" # nosec
tenant_id = "tenant_id"

mock_failed_result = {
'error': 'invalid_client',
'error_description': "AAZZZZ1234567: There was an error",
'error_codes': [1234567],
'timestamp': '2024-08-27 08:59:54Z',
'trace_id': str(uuid.uuid4()),
'correlation_id': str(uuid.uuid4()),
'error_uri': 'https://login.microsoftonline.com/error?code=1234567',
}

with patch("mail.auth.msal") as mock_msal:
mock_ConfidentialClientApplication = mock_msal.ConfidentialClientApplication()
mock_acquire_token_silent = mock_ConfidentialClientApplication.acquire_token_silent
mock_acquire_token_silent.return_value = mock_failed_result

auth = ModernAuthentication(
username,
client_id,
client_secret,
tenant_id,
)
with self.assertRaises(AuthenticationError), self.assertLogs(logger='mail.auth', level='INFO') as cm:
auth.authenticate(mock_conn)

self.assertIn(
f"INFO:mail.auth:{mock_failed_result}",
cm.output,
)

def test_equal(self):
username = "username"
client_id = "client_id"
Expand Down

0 comments on commit 1c32c9e

Please sign in to comment.