Debian Codegraph @

tests/test_auth_methods.py

raw
1 """
2 Tests for auth methods on the SMTP class.
3 """
4
5 import asyncio
6 import base64
7
8 import pytest
9
10 from aiosmtplib import SMTP
11 from aiosmtplib.auth import (
12 auth_crammd5_verify,
13 auth_login_encode,
14 auth_plain_encode,
15 auth_xoauth2_encode,
16 )
17 from aiosmtplib.errors import SMTPAuthenticationError, SMTPException
18 from aiosmtplib.response import SMTPResponse
19 from aiosmtplib.typing import SMTPStatus
20
21 from .auth import DummySMTPAuth
22
23
24 SUCCESS_RESPONSE = SMTPResponse(SMTPStatus.auth_successful, "OK")
25 FAILURE_RESPONSE = SMTPResponse(SMTPStatus.auth_failed, "Nope")
26
27
28 async def test_login_without_extension_raises_error(mock_auth: DummySMTPAuth) -> None:
29 mock_auth.esmtp_extensions = {}
30
31 with pytest.raises(SMTPException) as excinfo:
32 await mock_auth.login("username", "bogus")
33
34 assert "Try connecting via TLS" not in excinfo.value.args[0]
35
36
37 async def test_login_unknown_method_raises_error(mock_auth: DummySMTPAuth) -> None:
38 mock_auth.AUTH_METHODS = ("fakeauth",)
39 mock_auth.server_auth_methods = ["fakeauth"]
40
41 with pytest.raises(RuntimeError):
42 await mock_auth.login("username", "bogus")
43
44
45 async def test_login_without_method_raises_error(mock_auth: DummySMTPAuth) -> None:
46 mock_auth.server_auth_methods = []
47
48 with pytest.raises(SMTPException):
49 await mock_auth.login("username", "bogus")
50
51
52 async def test_login_tries_all_methods(mock_auth: DummySMTPAuth) -> None:
53 responses = [
54 FAILURE_RESPONSE, # CRAM-MD5
55 FAILURE_RESPONSE, # PLAIN
56 (SMTPStatus.auth_continue, "VXNlcm5hbWU6"), # LOGIN continue
57 SUCCESS_RESPONSE, # LOGIN success
58 ]
59 mock_auth.responses.extend(responses)
60 await mock_auth.login("username", "thirdtimelucky")
61
62
63 async def test_login_all_methods_fail_raises_error(mock_auth: DummySMTPAuth) -> None:
64 responses = [
65 FAILURE_RESPONSE, # CRAM-MD5
66 FAILURE_RESPONSE, # PLAIN
67 FAILURE_RESPONSE, # LOGIN
68 ]
69 mock_auth.responses.extend(responses)
70 with pytest.raises(SMTPAuthenticationError):
71 await mock_auth.login("username", "bogus")
72
73
74 @pytest.mark.parametrize(
75 "username,password",
76 [("test", "test"), ("admin124", "$3cr3t$"), ("føø", "bär€")],
77 ids=["test user", "admin user", "utf-8 user"],
78 )
79 async def test_auth_plain_success(
80 mock_auth: DummySMTPAuth, username: str, password: str
81 ) -> None:
82 """
83 Check that auth_plain base64 encodes the username/password given.
84 """
85 mock_auth.responses.append(SUCCESS_RESPONSE)
86 await mock_auth.auth_plain(username, password)
87
88 encoded = auth_plain_encode(username, password)
89 assert mock_auth.received_commands == [b"AUTH PLAIN " + encoded]
90
91
92 async def test_auth_plain_success_bytes(mock_auth: DummySMTPAuth) -> None:
93 """
94 Check that auth_plain base64 encodes the username/password when given as bytes.
95 """
96 username = "ภาษา".encode("tis-620")
97 password = "ไทย".encode("tis-620")
98 mock_auth.responses.append(SUCCESS_RESPONSE)
99 await mock_auth.auth_plain(username, password)
100
101 encoded = auth_plain_encode(username, password)
102 assert mock_auth.received_commands == [b"AUTH PLAIN " + encoded]
103
104
105 async def test_auth_plain_error(mock_auth: DummySMTPAuth) -> None:
106 mock_auth.responses.append(FAILURE_RESPONSE)
107
108 with pytest.raises(SMTPAuthenticationError):
109 await mock_auth.auth_plain("username", "bogus")
110
111
112 @pytest.mark.parametrize(
113 "username,password",
114 [("test", "test"), ("admin124", "$3cr3t$"), ("føø", "bär€")],
115 ids=["test user", "admin user", "utf-8 user"],
116 )
117 async def test_auth_login_success(
118 mock_auth: DummySMTPAuth, username: str, password: str
119 ) -> None:
120 continue_response = (SMTPStatus.auth_continue, "VXNlcm5hbWU6")
121 mock_auth.responses.extend([continue_response, SUCCESS_RESPONSE])
122 await mock_auth.auth_login(username, password)
123
124 encoded_username, encoded_password = auth_login_encode(username, password)
125
126 assert mock_auth.received_commands == [
127 b"AUTH LOGIN " + encoded_username,
128 encoded_password,
129 ]
130
131
132 async def test_auth_login_success_bytes(mock_auth: DummySMTPAuth) -> None:
133 continue_response = (SMTPStatus.auth_continue, "VXNlcm5hbWU6")
134 mock_auth.responses.extend([continue_response, SUCCESS_RESPONSE])
135
136 username = "ภาษา".encode("tis-620")
137 password = "ไทย".encode("tis-620")
138 await mock_auth.auth_login(username, password)
139
140 encoded_username, encoded_password = auth_login_encode(username, password)
141
142 assert mock_auth.received_commands == [
143 b"AUTH LOGIN " + encoded_username,
144 encoded_password,
145 ]
146
147
148 async def test_auth_login_error(mock_auth: DummySMTPAuth) -> None:
149 mock_auth.responses.append(FAILURE_RESPONSE)
150 with pytest.raises(SMTPAuthenticationError):
151 await mock_auth.auth_login("username", "bogus")
152
153
154 async def test_auth_plain_continue_error(mock_auth: DummySMTPAuth) -> None:
155 continue_response = (SMTPStatus.auth_continue, "VXNlcm5hbWU6")
156 mock_auth.responses.extend([continue_response, FAILURE_RESPONSE])
157
158 with pytest.raises(SMTPAuthenticationError):
159 await mock_auth.auth_login("username", "bogus")
160
161
162 @pytest.mark.parametrize(
163 "username,password",
164 [("test", "test"), ("admin124", "$3cr3t$"), ("føø", "bär€")],
165 ids=["test user", "admin user", "utf-8 user"],
166 )
167 async def test_auth_crammd5_success(
168 mock_auth: DummySMTPAuth, username: str, password: str
169 ) -> None:
170 continue_response = (
171 SMTPStatus.auth_continue,
172 base64.b64encode(b"secretteststring").decode("utf-8"),
173 )
174 mock_auth.responses.extend([continue_response, SUCCESS_RESPONSE])
175 await mock_auth.auth_crammd5(username, password)
176
177 password_bytes = password.encode("utf-8")
178 username_bytes = username.encode("utf-8")
179 response_bytes = continue_response[1].encode("utf-8")
180
181 expected_command = auth_crammd5_verify(
182 username_bytes, password_bytes, response_bytes
183 )
184
185 assert mock_auth.received_commands == [b"AUTH CRAM-MD5", expected_command]
186
187
188 async def test_auth_crammd5_success_bytes(mock_auth: DummySMTPAuth) -> None:
189 continue_response = (
190 SMTPStatus.auth_continue,
191 base64.b64encode(b"secretteststring").decode("utf-8"),
192 )
193 mock_auth.responses.extend([continue_response, SUCCESS_RESPONSE])
194
195 username = "ภาษา".encode("tis-620")
196 password = "ไทย".encode("tis-620")
197 await mock_auth.auth_crammd5(username, password)
198
199 response_bytes = continue_response[1].encode("utf-8")
200
201 expected_command = auth_crammd5_verify(username, password, response_bytes)
202
203 assert mock_auth.received_commands == [b"AUTH CRAM-MD5", expected_command]
204
205
206 async def test_auth_crammd5_initial_error(mock_auth: DummySMTPAuth) -> None:
207 mock_auth.responses.append(FAILURE_RESPONSE)
208
209 with pytest.raises(SMTPAuthenticationError):
210 await mock_auth.auth_crammd5("username", "bogus")
211
212
213 async def test_auth_crammd5_continue_error(mock_auth: DummySMTPAuth) -> None:
214 continue_response = (SMTPStatus.auth_continue, "VXNlcm5hbWU6")
215 mock_auth.responses.extend([continue_response, FAILURE_RESPONSE])
216
217 with pytest.raises(SMTPAuthenticationError):
218 await mock_auth.auth_crammd5("username", "bogus")
219
220
221 async def test_auth_crammd5_invalid_challenge_raises_auth_error(
222 mock_auth: DummySMTPAuth,
223 ) -> None:
224 continue_response = (SMTPStatus.auth_continue, "not base64!!")
225 mock_auth.responses.append(continue_response)
226
227 with pytest.raises(SMTPAuthenticationError) as excinfo:
228 await mock_auth.auth_crammd5("username", "bogus")
229
230 assert excinfo.value.code == SMTPStatus.auth_continue
231 assert "CRAM-MD5" in excinfo.value.message
232 assert mock_auth.received_commands == [b"AUTH CRAM-MD5"]
233
234
235 async def test_login_falls_back_after_invalid_crammd5_challenge(
236 mock_auth: DummySMTPAuth,
237 ) -> None:
238 responses = [
239 (SMTPStatus.auth_continue, "not base64!!"), # CRAM-MD5 bad challenge
240 SUCCESS_RESPONSE, # PLAIN
241 ]
242 mock_auth.responses.extend(responses)
243 await mock_auth.login("username", "secondtimelucky")
244
245 assert mock_auth.received_commands[0] == b"AUTH CRAM-MD5"
246 assert mock_auth.received_commands[1].startswith(b"AUTH PLAIN")
247
248
249 async def test_login_without_starttls_exception(
250 smtp_client: SMTP,
251 smtpd_server: asyncio.AbstractServer,
252 auth_username: str,
253 auth_password: str,
254 ) -> None:
255 async with smtp_client:
256 with pytest.raises(SMTPException) as excinfo:
257 await smtp_client.login(auth_username, auth_password)
258
259 assert "Try connecting via TLS" in excinfo.value.args[0]
260
261
262 @pytest.mark.parametrize(
263 "username,token",
264 [
265 ("[email protected]", "ya29.token123"),
266 ("[email protected]", "access_token_here"),
267 ("føø@example.com", "bär€_token"),
268 ],
269 ids=["test user", "gmail user", "utf-8 user"],
270 )
271 async def test_auth_xoauth2_success(
272 mock_auth: DummySMTPAuth, username: str, token: str
273 ) -> None:
274 """Check that auth_xoauth2 base64 encodes the username/token correctly."""
275 mock_auth.responses.append(SUCCESS_RESPONSE)
276 await mock_auth.auth_xoauth2(username, token)
277
278 encoded = auth_xoauth2_encode(username, token)
279 assert mock_auth.received_commands == [b"AUTH XOAUTH2 " + encoded]
280
281
282 async def test_auth_xoauth2_success_bytes(mock_auth: DummySMTPAuth) -> None:
283 """Check that auth_xoauth2 works with bytes input."""
284 username = b"[email protected]"
285 token = b"access_token_bytes"
286 mock_auth.responses.append(SUCCESS_RESPONSE)
287 await mock_auth.auth_xoauth2(username, token)
288
289 encoded = auth_xoauth2_encode(username, token)
290 assert mock_auth.received_commands == [b"AUTH XOAUTH2 " + encoded]
291
292
293 async def test_auth_xoauth2_error(mock_auth: DummySMTPAuth) -> None:
294 """Check that auth_xoauth2 raises on failure response."""
295 mock_auth.responses.append(FAILURE_RESPONSE)
296
297 with pytest.raises(SMTPAuthenticationError):
298 await mock_auth.auth_xoauth2("[email protected]", "bad_token")
299
300
301 async def test_auth_xoauth2_challenge_error(mock_auth: DummySMTPAuth) -> None:
302 """
303 Check that auth_xoauth2 handles the error challenge flow.
304
305 On failure, server sends 334 with base64-encoded error JSON,
306 client sends empty response, then gets the final 535 error.
307 """
308 # Server sends error challenge (334), then final error (535)
309 challenge_response = (SMTPStatus.auth_continue, "eyJzdGF0dXMiOiI0MDAifQ==")
310 mock_auth.responses.extend([challenge_response, FAILURE_RESPONSE])
311
312 with pytest.raises(SMTPAuthenticationError):
313 await mock_auth.auth_xoauth2("[email protected]", "expired_token")
314
315 # Verify we sent the initial auth and then empty response
316 encoded = auth_xoauth2_encode("[email protected]", "expired_token")
317 assert mock_auth.received_commands == [b"AUTH XOAUTH2 " + encoded, b""]
318
319
320 async def test_maybe_login_with_oauth_token_generator(mock_auth: DummySMTPAuth) -> None:
321 """Test that _maybe_login_on_connect uses oauth_token_generator when provided."""
322 mock_auth.server_auth_methods = ["xoauth2", "plain", "login"]
323 mock_auth._login_username = "[email protected]"
324
325 async def get_token() -> str:
326 return "test_oauth_token"
327
328 mock_auth._oauth_token_generator = get_token
329 mock_auth.responses.append(SUCCESS_RESPONSE)
330
331 await mock_auth._maybe_login_on_connect()
332
333 encoded = auth_xoauth2_encode("[email protected]", "test_oauth_token")
334 assert mock_auth.received_commands == [b"AUTH XOAUTH2 " + encoded]
335
336
337 async def test_auth_crammd5_passes_timeout(mock_auth: DummySMTPAuth) -> None:
338 """
339 Test that auth_crammd5 passes timeout to the verification command.
340
341 Both execute_command calls in auth_crammd5 should receive the timeout parameter.
342 """
343 continue_response = (
344 SMTPStatus.auth_continue,
345 base64.b64encode(b"challenge").decode("utf-8"),
346 )
347 mock_auth.responses.extend([continue_response, SUCCESS_RESPONSE])
348 await mock_auth.auth_crammd5("user", "pass", timeout=5.0)
349
350 # Both commands should have received the timeout
351 assert len(mock_auth.received_kwargs) == 2
352 assert mock_auth.received_kwargs[0].get("timeout") == 5.0
353 assert mock_auth.received_kwargs[1].get("timeout") == 5.0