Debian Codegraph @

tests/test_commands.py

raw
1 """
2 Lower level SMTP command tests.
3 """
4
5 import contextlib
6 import email.errors
7 import email.message
8 from typing import Any
9
10 import pytest
11
12 from aiosmtplib import (
13 SMTP,
14 SMTPDataError,
15 SMTPHeloError,
16 SMTPNotSupported,
17 SMTPResponseException,
18 SMTPServerDisconnected,
19 SMTPStatus,
20 )
21
22 from .smtpd import (
23 RecordingHandler,
24 mock_response_bad_command_sequence,
25 mock_response_bad_data,
26 mock_response_done,
27 mock_response_ehlo_full,
28 mock_response_expn,
29 mock_response_gibberish,
30 mock_response_syntax_error,
31 mock_response_syntax_error_and_cleanup,
32 mock_response_unavailable,
33 mock_response_unrecognized_command,
34 )
35
36
37 async def test_helo_ok(smtp_client: SMTP) -> None:
38 async with smtp_client:
39 response = await smtp_client.helo()
40
41 assert response.code == SMTPStatus.completed
42
43
44 async def test_helo_with_hostname(smtp_client: SMTP) -> None:
45 async with smtp_client:
46 response = await smtp_client.helo(hostname="example.com")
47
48 assert response.code == SMTPStatus.completed
49
50
51 async def test_helo_with_hostname_unset_after_connect(smtp_client: SMTP) -> None:
52 async with smtp_client:
53 smtp_client.local_hostname = None
54 response = await smtp_client.helo()
55
56 assert response.code == SMTPStatus.completed
57
58
59 @pytest.mark.parametrize(
60 "helo_hostname",
61 ["me.example.com XCLIENT ADDR=1.2.3.4", "me.example.com\r\nQUIT", ""],
62 ids=["space", "crlf", "empty"],
63 )
64 async def test_helo_with_hostname_injection_raises_error(
65 smtp_client: SMTP, helo_hostname: str
66 ) -> None:
67 async with smtp_client:
68 with pytest.raises(ValueError):
69 await smtp_client.helo(hostname=helo_hostname)
70
71
72 async def test_helo_with_hostname_strips_whitespace(smtp_client: SMTP) -> None:
73 async with smtp_client:
74 response = await smtp_client.helo(hostname=" example.com ")
75
76 assert response.code == SMTPStatus.completed
77
78
79 @pytest.mark.smtpd_mocks(smtp_HELO=mock_response_unrecognized_command)
80 async def test_helo_error(smtp_client: SMTP) -> None:
81 async with smtp_client:
82 with pytest.raises(SMTPHeloError) as exception_info:
83 await smtp_client.helo()
84 assert exception_info.value.code == SMTPStatus.unrecognized_command
85
86
87 async def test_ehlo_ok(smtp_client: SMTP) -> None:
88 async with smtp_client:
89 response = await smtp_client.ehlo()
90
91 assert response.code == SMTPStatus.completed
92
93
94 async def test_ehlo_with_hostname(smtp_client: SMTP) -> None:
95 async with smtp_client:
96 response = await smtp_client.ehlo(hostname="example.com")
97
98 assert response.code == SMTPStatus.completed
99
100
101 async def test_ehlo_with_hostname_unset_after_connect(smtp_client: SMTP) -> None:
102 async with smtp_client:
103 smtp_client.local_hostname = None
104 response = await smtp_client.ehlo()
105
106 assert response.code == SMTPStatus.completed
107
108
109 @pytest.mark.parametrize(
110 "helo_hostname",
111 ["me.example.com XCLIENT ADDR=1.2.3.4", "me.example.com\r\nQUIT", ""],
112 ids=["space", "crlf", "empty"],
113 )
114 async def test_ehlo_with_hostname_injection_raises_error(
115 smtp_client: SMTP, helo_hostname: str
116 ) -> None:
117 async with smtp_client:
118 with pytest.raises(ValueError):
119 await smtp_client.ehlo(hostname=helo_hostname)
120
121
122 async def test_ehlo_with_hostname_strips_whitespace(smtp_client: SMTP) -> None:
123 async with smtp_client:
124 response = await smtp_client.ehlo(hostname=" example.com ")
125
126 assert response.code == SMTPStatus.completed
127
128
129 @pytest.mark.smtpd_mocks(smtp_EHLO=mock_response_unrecognized_command)
130 async def test_ehlo_error(smtp_client: SMTP) -> None:
131 async with smtp_client:
132 with pytest.raises(SMTPHeloError) as exception_info:
133 await smtp_client.ehlo()
134 assert exception_info.value.code == SMTPStatus.unrecognized_command
135
136
137 @pytest.mark.smtpd_mocks(smtp_EHLO=mock_response_unrecognized_command)
138 async def test_ehlo_error_does_not_set_supports_esmtp(smtp_client: SMTP) -> None:
139 """
140 Test that a failed EHLO response does not set supports_esmtp to True.
141
142 The EHLO response should only be parsed for extensions after validating
143 that the response code indicates success.
144 """
145 async with smtp_client:
146 assert smtp_client.supports_esmtp is False
147
148 with pytest.raises(SMTPHeloError):
149 await smtp_client.ehlo()
150
151 assert smtp_client.supports_esmtp is False
152 assert smtp_client.last_ehlo_response is None
153 assert smtp_client.esmtp_extensions == {}
154
155
156 @pytest.mark.smtpd_mocks(smtp_EHLO=mock_response_ehlo_full)
157 async def test_ehlo_parses_esmtp_extensions(smtp_client: SMTP) -> None:
158 async with smtp_client:
159 await smtp_client.ehlo()
160
161 assert smtp_client.supports_extension("8bitmime")
162 assert smtp_client.supports_extension("size")
163 assert smtp_client.supports_extension("pipelining")
164 assert smtp_client.supports_extension("ENHANCEDSTATUSCODES")
165 assert not smtp_client.supports_extension("notreal")
166
167
168 @pytest.mark.smtpd_mocks(smtp_EHLO=mock_response_done)
169 async def test_ehlo_with_no_extensions(smtp_client: SMTP) -> None:
170 async with smtp_client:
171 await smtp_client.ehlo()
172
173 assert not smtp_client.supports_extension("size")
174
175
176 async def test_ehlo_or_helo_if_needed_ehlo_success(smtp_client: SMTP) -> None:
177 async with smtp_client:
178 assert smtp_client.is_ehlo_or_helo_needed is True
179
180 await smtp_client._ehlo_or_helo_if_needed()
181
182 assert smtp_client.is_ehlo_or_helo_needed is False
183
184
185 @pytest.mark.smtpd_mocks(smtp_EHLO=mock_response_unrecognized_command)
186 async def test_ehlo_or_helo_if_needed_helo_success(smtp_client: SMTP) -> None:
187 async with smtp_client:
188 assert smtp_client.is_ehlo_or_helo_needed is True
189
190 await smtp_client._ehlo_or_helo_if_needed()
191
192 assert smtp_client.is_ehlo_or_helo_needed is False
193
194
195 @pytest.mark.smtpd_mocks(
196 smtp_HELO=mock_response_unrecognized_command,
197 smtp_EHLO=mock_response_unrecognized_command,
198 )
199 async def test_ehlo_or_helo_if_needed_neither_succeeds(smtp_client: SMTP) -> None:
200 async with smtp_client:
201 assert smtp_client.is_ehlo_or_helo_needed is True
202
203 with pytest.raises(SMTPHeloError) as exception_info:
204 await smtp_client._ehlo_or_helo_if_needed()
205 assert exception_info.value.code == SMTPStatus.unrecognized_command
206
207
208 @pytest.mark.smtpd_mocks(smtp_EHLO=mock_response_unavailable)
209 async def test_ehlo_or_helo_if_needed_disconnect_after_ehlo(smtp_client: SMTP) -> None:
210 async with smtp_client:
211 with pytest.raises(SMTPHeloError):
212 await smtp_client._ehlo_or_helo_if_needed()
213
214
215 async def test_rset_ok(smtp_client: SMTP) -> None:
216 async with smtp_client:
217 response = await smtp_client.rset()
218
219 assert response.code == SMTPStatus.completed
220 assert response.message == "OK"
221
222
223 @pytest.mark.smtpd_mocks(smtp_RSET=mock_response_bad_command_sequence)
224 async def test_rset_error(smtp_client: SMTP) -> None:
225 async with smtp_client:
226 with pytest.raises(SMTPResponseException) as exception_info:
227 await smtp_client.rset()
228 assert exception_info.value.code == SMTPStatus.bad_command_sequence
229
230
231 async def test_noop_ok(smtp_client: SMTP) -> None:
232 async with smtp_client:
233 response = await smtp_client.noop()
234
235 assert response.code == SMTPStatus.completed
236 assert response.message == "OK"
237
238
239 @pytest.mark.smtpd_mocks(smtp_NOOP=mock_response_syntax_error)
240 async def test_noop_error(smtp_client: SMTP) -> None:
241 async with smtp_client:
242 with pytest.raises(SMTPResponseException) as exception_info:
243 await smtp_client.noop()
244 assert exception_info.value.code == SMTPStatus.syntax_error
245
246
247 async def test_vrfy_ok(smtp_client: SMTP) -> None:
248 nice_address = "[email protected]"
249 async with smtp_client:
250 response = await smtp_client.vrfy(nice_address)
251
252 assert response.code == SMTPStatus.cannot_vrfy
253
254
255 async def test_vrfy_with_blank_address(smtp_client: SMTP) -> None:
256 bad_address = ""
257 async with smtp_client:
258 with pytest.raises(SMTPResponseException):
259 await smtp_client.vrfy(bad_address)
260
261
262 @pytest.mark.smtpd_options(smtputf8=True)
263 async def test_vrfy_smtputf8_supported(smtp_client: SMTP) -> None:
264 async with smtp_client:
265 response = await smtp_client.vrfy("tést@exåmple.com", options=["SMTPUTF8"])
266
267 assert response.code == SMTPStatus.cannot_vrfy
268
269
270 @pytest.mark.smtpd_options(smtputf8=False)
271 async def test_vrfy_smtputf8_not_supported(smtp_client: SMTP) -> None:
272 async with smtp_client:
273 with pytest.raises(SMTPNotSupported):
274 await smtp_client.vrfy("tést@exåmple.com", options=["SMTPUTF8"])
275
276
277 @pytest.mark.smtpd_mocks(smtp_EXPN=mock_response_expn)
278 async def test_expn_ok(smtp_client: SMTP) -> None:
279 async with smtp_client:
280 response = await smtp_client.expn("listserv-members")
281 assert response.code == SMTPStatus.completed
282
283
284 async def test_expn_error(smtp_client: SMTP) -> None:
285 """
286 Since EXPN isn't implemented by aiosmtpd, it raises an exception by default.
287 """
288 async with smtp_client:
289 with pytest.raises(SMTPResponseException):
290 await smtp_client.expn("a-list")
291
292
293 @pytest.mark.smtpd_options(smtputf8=True)
294 @pytest.mark.smtpd_mocks(smtp_EXPN=mock_response_expn)
295 async def test_expn_smtputf8_supported(smtp_client: SMTP) -> None:
296 utf8_list = "tést-lïst"
297 async with smtp_client:
298 response = await smtp_client.expn(utf8_list, options=["SMTPUTF8"])
299
300 assert response.code == SMTPStatus.completed
301
302
303 @pytest.mark.smtpd_options(smtputf8=False)
304 async def test_expn_smtputf8_not_supported(smtp_client: SMTP) -> None:
305 utf8_list = "tést-lïst"
306 async with smtp_client:
307 with pytest.raises(SMTPNotSupported):
308 await smtp_client.expn(utf8_list, options=["SMTPUTF8"])
309
310
311 async def test_help_ok(smtp_client: SMTP) -> None:
312 async with smtp_client:
313 help_message = await smtp_client.help()
314
315 assert "Supported commands" in help_message
316
317
318 @pytest.mark.smtpd_mocks(smtp_HELP=mock_response_syntax_error)
319 async def test_help_error(smtp_client: SMTP) -> None:
320 async with smtp_client:
321 with pytest.raises(SMTPResponseException) as exception_info:
322 await smtp_client.help()
323 assert exception_info.value.code == SMTPStatus.syntax_error
324
325
326 @pytest.mark.smtpd_mocks(smtp_QUIT=mock_response_syntax_error_and_cleanup)
327 async def test_quit_error(smtp_client: SMTP) -> None:
328 async with smtp_client:
329 with pytest.raises(SMTPResponseException) as exception_info:
330 await smtp_client.quit()
331 assert exception_info.value.code == SMTPStatus.syntax_error
332
333
334 async def test_supported_methods(smtp_client: SMTP) -> None:
335 async with smtp_client:
336 response = await smtp_client.ehlo()
337
338 assert response.code == SMTPStatus.completed
339 assert smtp_client.supports_extension("size")
340 assert smtp_client.supports_extension("help")
341 assert not smtp_client.supports_extension("bogus")
342
343
344 async def test_mail_ok(smtp_client: SMTP) -> None:
345 async with smtp_client:
346 response = await smtp_client.mail("[email protected]")
347
348 assert response.code == SMTPStatus.completed
349 assert response.message == "OK"
350
351
352 @pytest.mark.smtpd_mocks(smtp_MAIL=mock_response_bad_command_sequence)
353 async def test_mail_error(smtp_client: SMTP) -> None:
354 async with smtp_client:
355 with pytest.raises(SMTPResponseException) as exception_info:
356 await smtp_client.mail("[email protected]")
357 assert exception_info.value.code == SMTPStatus.bad_command_sequence
358
359
360 async def test_mail_options_not_implemented(smtp_client: SMTP) -> None:
361 async with smtp_client:
362 with pytest.raises(SMTPResponseException):
363 await smtp_client.mail("[email protected]", options=["OPT=1"])
364
365
366 @pytest.mark.smtpd_options(smtputf8=True)
367 async def test_mail_smtputf8(smtp_client: SMTP) -> None:
368 async with smtp_client:
369 response = await smtp_client.mail(
370 "tést@exåmple.com", options=["SMTPUTF8"], encoding="utf-8"
371 )
372
373 assert response.code == SMTPStatus.completed
374
375
376 async def test_mail_default_encoding_utf8_encode_error(smtp_client: SMTP) -> None:
377 async with smtp_client:
378 with pytest.raises(UnicodeEncodeError):
379 await smtp_client.mail("tést@exåmple.com", options=["SMTPUTF8"])
380
381
382 async def test_rcpt_ok(smtp_client: SMTP) -> None:
383 async with smtp_client:
384 await smtp_client.mail("[email protected]")
385
386 response = await smtp_client.rcpt("[email protected]")
387
388 assert response.code == SMTPStatus.completed
389 assert response.message == "OK"
390
391
392 @pytest.mark.smtpd_mocks(smtp_RCPT=mock_response_done)
393 async def test_rcpt_options_ok(smtp_client: SMTP) -> None:
394 async with smtp_client:
395 await smtp_client.mail("[email protected]")
396
397 response = await smtp_client.rcpt(
398 "[email protected]", options=["NOTIFY=FAILURE,DELAY"]
399 )
400
401 assert response.code == SMTPStatus.completed
402
403
404 async def test_rcpt_options_not_implemented(smtp_client: SMTP) -> None:
405 # RCPT options are not implemented in aiosmtpd, so any option will return 555
406 async with smtp_client:
407 await smtp_client.mail("[email protected]")
408
409 with pytest.raises(SMTPResponseException) as err:
410 await smtp_client.rcpt("[email protected]", options=["OPT=1"])
411 assert err.value.code == SMTPStatus.syntax_error
412
413
414 @pytest.mark.smtpd_mocks(smtp_RCPT=mock_response_syntax_error)
415 async def test_rcpt_error(smtp_client: SMTP) -> None:
416 async with smtp_client:
417 await smtp_client.mail("[email protected]")
418
419 with pytest.raises(SMTPResponseException) as exception_info:
420 await smtp_client.rcpt("[email protected]")
421 assert exception_info.value.code == SMTPStatus.syntax_error
422
423
424 @pytest.mark.smtpd_options(smtputf8=True)
425 async def test_rcpt_smtputf8(smtp_client: SMTP) -> None:
426 async with smtp_client:
427 await smtp_client.mail("[email protected]", options=["SMTPUTF8"])
428 response = await smtp_client.rcpt("tést@exåmple.com", encoding="utf-8")
429
430 assert response.code == SMTPStatus.completed
431
432
433 async def test_rcpt_default_encoding_utf8_encode_error(smtp_client: SMTP) -> None:
434 async with smtp_client:
435 await smtp_client.mail("[email protected]")
436
437 with pytest.raises(UnicodeEncodeError):
438 await smtp_client.rcpt("tést@exåmple.com", options=["SMTPUTF8"])
439
440
441 async def test_data_ok(smtp_client: SMTP) -> None:
442 async with smtp_client:
443 await smtp_client.mail("[email protected]")
444 await smtp_client.rcpt("[email protected]")
445 response = await smtp_client.data("HELLO WORLD")
446
447 assert response.code == SMTPStatus.completed
448 assert response.message == "OK"
449
450
451 @pytest.mark.smtpd_mocks(smtp_DATA=mock_response_bad_command_sequence)
452 async def test_data_error_on_start_input(smtp_client: SMTP) -> None:
453 async with smtp_client:
454 await smtp_client.mail("[email protected]")
455 await smtp_client.rcpt("[email protected]")
456 with pytest.raises(SMTPDataError) as exception_info:
457 await smtp_client.data("TEST MESSAGE")
458 assert exception_info.value.code == SMTPStatus.bad_command_sequence
459
460
461 async def test_data_complete_error(
462 smtp_client: SMTP,
463 smtpd_handler: RecordingHandler,
464 monkeypatch: pytest.MonkeyPatch,
465 ) -> None:
466 monkeypatch.setattr(smtpd_handler, "handle_DATA", mock_response_syntax_error)
467
468 async with smtp_client:
469 await smtp_client.mail("[email protected]")
470 await smtp_client.rcpt("[email protected]")
471 with pytest.raises(SMTPDataError) as exception_info:
472 await smtp_client.data("TEST MESSAGE")
473 assert exception_info.value.code == SMTPStatus.syntax_error
474
475
476 async def test_data_error_when_disconnected() -> None:
477 client = SMTP()
478
479 with pytest.raises(SMTPServerDisconnected):
480 await client.data("HELLO WORLD")
481
482
483 @pytest.mark.smtpd_mocks(smtp_NOOP=mock_response_gibberish)
484 async def test_gibberish_raises_exception(smtp_client: SMTP) -> None:
485 async with smtp_client:
486 with pytest.raises(SMTPResponseException):
487 await smtp_client.noop()
488
489
490 @pytest.mark.smtpd_mocks(smtp_NOOP=mock_response_bad_data)
491 async def test_badly_encoded_text_response(smtp_client: SMTP) -> None:
492 async with smtp_client:
493 response = await smtp_client.noop()
494
495 assert response.code == SMTPStatus.completed
496
497
498 @pytest.mark.parametrize("command", ("mail", "rcpt", "vrfy", "expn"))
499 async def test_address_command_rejects_injection(
500 smtp_client: SMTP,
501 received_commands: list[tuple[str, tuple[Any, ...]]],
502 command: str,
503 ) -> None:
504 async with smtp_client:
505 await smtp_client.ehlo()
506 received_commands.clear()
507
508 method = getattr(smtp_client, command)
509 with pytest.raises(ValueError):
510 await method("[email protected]\r\nRCPT TO:<[email protected]>")
511
512 assert received_commands == []
513
514
515 @pytest.mark.parametrize("command", ("mail", "rcpt", "vrfy", "expn"))
516 @pytest.mark.parametrize(
517 "address",
518 (
519 "[email protected]> AUTH=<[email protected]",
520 "[email protected]> NOTIFY=SUCCESS,FAILURE ORCPT=rfc822;<[email protected]",
521 "[email protected]> SIZE=1",
522 ),
523 ids=("auth", "dsn", "size"),
524 )
525 async def test_address_command_rejects_parameter_injection(
526 smtp_client: SMTP,
527 received_commands: list[tuple[str, tuple[Any, ...]]],
528 command: str,
529 address: str,
530 ) -> None:
531 """
532 Addresses that would smuggle ESMTP parameters onto the command line
533 (without using control characters) must never be sent.
534 """
535 async with smtp_client:
536 await smtp_client.ehlo()
537 received_commands.clear()
538
539 method = getattr(smtp_client, command)
540 with pytest.raises(ValueError):
541 await method(address)
542
543 assert received_commands == []
544
545
546 async def test_sendmail_rejects_parameter_injection(
547 smtp_client: SMTP,
548 received_commands: list[tuple[str, tuple[Any, ...]]],
549 received_messages: list[email.message.EmailMessage],
550 ) -> None:
551 async with smtp_client:
552 await smtp_client.ehlo()
553 received_commands.clear()
554
555 with pytest.raises(ValueError):
556 await smtp_client.sendmail(
557 "[email protected]> AUTH=<[email protected]",
558 ["[email protected]"],
559 "Subject: legit\n\nhi",
560 )
561
562 with pytest.raises(ValueError):
563 await smtp_client.sendmail(
564 "[email protected]",
565 ["[email protected]> NOTIFY=SUCCESS,FAILURE"],
566 "Subject: legit\n\nhi",
567 )
568
569 assert received_commands == []
570 assert received_messages == []
571
572
573 async def test_sendmail_rejects_command_injection(
574 smtp_client: SMTP,
575 received_commands: list[tuple[str, tuple[Any, ...]]],
576 received_messages: list[email.message.EmailMessage],
577 ) -> None:
578 """
579 A complete transaction smuggled into the sender must never be sent.
580 """
581 injected_sender = (
582 "[email protected]>\r\n"
583 "MAIL FROM:<[email protected]>\r\n"
584 "RCPT TO:<[email protected]>\r\n"
585 "DATA\r\n"
586 "Subject: smuggled\r\n"
587 "\r\n"
588 "smuggled body\r\n"
589 ".\r\n"
590 "RSET\r\nMAIL FROM:<x"
591 )
592 async with smtp_client:
593 await smtp_client.ehlo()
594 received_commands.clear()
595
596 with pytest.raises(ValueError):
597 await smtp_client.sendmail(
598 injected_sender, ["[email protected]"], "Subject: legit\n\nhi"
599 )
600
601 assert received_commands == []
602 assert received_messages == []
603
604
605 async def test_send_message_compat32_does_not_smuggle_envelope_commands(
606 smtp_client: SMTP,
607 received_commands: list[tuple[str, tuple[Any, ...]]],
608 ) -> None:
609 message = email.message.Message()
610 message["From"] = "[email protected]\r\nRCPT TO:<[email protected]>"
611 message["To"] = "[email protected]"
612 message.set_payload("hello")
613
614 async with smtp_client:
615 # PyPy's BytesGenerator enforces verify_generated_headers and rejects the
616 # injected newline; CPython's BytesGenerator does not. Either way, no
617 # envelope command may be smuggled.
618 with contextlib.suppress(email.errors.HeaderWriteError):
619 await smtp_client.send_message(message)
620
621 for _, args in received_commands:
622 assert all("hijacker" not in str(arg) for arg in args)
623
624
625 @pytest.mark.smtpd_mocks(smtp_HELO=mock_response_unrecognized_command)
626 async def test_helo_error_does_not_set_last_helo_response(smtp_client: SMTP) -> None:
627 async with smtp_client:
628 with pytest.raises(SMTPHeloError):
629 await smtp_client.helo()
630
631 assert smtp_client.last_helo_response is None
632 assert smtp_client.is_ehlo_or_helo_needed