Debian Codegraph @

tests/smtpd.py

raw
1 """
2 Implements handlers required on top of aiosmtpd for testing.
3 """
4
5 import asyncio
6 import logging
7 from email.errors import HeaderParseError
8 from email.message import EmailMessage, Message
9 from typing import Any, AnyStr
10
11 from aiosmtpd.handlers import Message as MessageHandler
12 from aiosmtpd.smtp import MISSING
13 from aiosmtpd.smtp import SMTP as SMTPD
14 from aiosmtpd.smtp import Envelope, Session, _Missing
15
16 from aiosmtplib import SMTPStatus
17
18
19 log = logging.getLogger("mail.log")
20
21
22 class RecordingHandler(MessageHandler):
23 def __init__(
24 self,
25 messages_list: list[EmailMessage | Message],
26 commands_list: list[tuple[str, tuple[Any, ...]]],
27 responses_list: list[str],
28 ) -> None:
29 self.messages = messages_list
30 self.commands = commands_list
31 self.responses = responses_list
32 super().__init__(message_class=EmailMessage)
33
34 def record_command(self, command: str, *args: Any) -> None:
35 self.commands.append((command, tuple(args)))
36
37 def record_server_response(self, status: str) -> None:
38 self.responses.append(status)
39
40 def handle_message(self, message: EmailMessage | Message) -> None:
41 self.messages.append(message)
42
43 async def handle_EHLO(
44 self,
45 server: SMTPD,
46 session: Session,
47 envelope: Envelope,
48 hostname: str,
49 responses: list[str],
50 ) -> list[str]:
51 """Advertise auth login support."""
52 session.host_name = hostname # type: ignore
53 if server._tls_protocol:
54 return ["250-AUTH LOGIN"] + responses
55 else:
56 return responses
57
58
59 class TestSMTPD(SMTPD):
60 transport: asyncio.BaseTransport | None # type: ignore
61
62 def _getaddr(self, arg: str) -> tuple[str | None, str | None]:
63 """
64 Don't raise an exception on unparsable email address
65 """
66 address: str | None = None
67 rest: str | None = ""
68 try:
69 address, rest = super()._getaddr(arg)
70 except HeaderParseError:
71 pass
72
73 return address, rest
74
75 async def _call_handler_hook(self, command: str, *args: Any) -> Any:
76 self.event_handler.record_command(command, *args)
77 return await super()._call_handler_hook(command, *args)
78
79 async def push(self, status: AnyStr) -> None:
80 await super().push(status)
81 self.event_handler.record_server_response(status)
82
83 async def smtp_EXPN(self, arg: str) -> None:
84 """
85 Pass EXPN to handler hook.
86 """
87 status = await self._call_handler_hook("EXPN")
88 await self.push(
89 "502 EXPN not implemented" if isinstance(status, _Missing) else status
90 )
91
92 async def smtp_HELP(self, arg: str) -> None:
93 """
94 Override help to pass to handler hook.
95 """
96 status = await self._call_handler_hook("HELP")
97 if status is MISSING:
98 await super().smtp_HELP(arg)
99 else:
100 await self.push(status)
101
102 async def smtp_STARTTLS(self, arg: str) -> None:
103 await super().smtp_STARTTLS(arg)
104 self.event_handler.record_command("STARTTLS", arg)
105
106
107 async def mock_response_delayed_ok(smtpd: SMTPD, *args: Any, **kwargs: Any) -> None:
108 await asyncio.sleep(1.0)
109 await smtpd.push("250 all done")
110
111
112 async def mock_response_delayed_read(smtpd: SMTPD, *args: Any, **kwargs: Any) -> None:
113 await smtpd.push("220-hi")
114 await asyncio.sleep(1.0)
115
116
117 async def mock_response_done(smtpd: SMTPD, *args: Any, **kwargs: Any) -> None:
118 if args and args[0]:
119 smtpd.session.host_name = args[0]
120 await smtpd.push("250 done")
121
122
123 async def mock_response_done_then_close(
124 smtpd: SMTPD, *args: Any, **kwargs: Any
125 ) -> None:
126 if args and args[0]:
127 smtpd.session.host_name = args[0]
128 await smtpd.push("250 done")
129 await smtpd.push("221 bye now")
130 smtpd.transport.close()
131
132
133 async def mock_response_delayed_close(smtpd: SMTPD, *args: Any, **kwargs: Any) -> None:
134 if args and args[0]:
135 smtpd.session.host_name = args[0]
136 await smtpd.push("250 done")
137
138 smtpd.loop.call_later(0.1, smtpd.transport.close)
139
140
141 async def mock_response_error_disconnect(
142 smtpd: SMTPD, *args: Any, **kwargs: Any
143 ) -> None:
144 await smtpd.push("501 error")
145 smtpd.transport.close()
146
147
148 async def mock_response_bad_data(smtpd: SMTPD, *args: Any, **kwargs: Any) -> None:
149 smtpd._writer.write(b"250 \xff\xff\xff\xff\r\n")
150 await smtpd._writer.drain()
151
152
153 async def mock_response_gibberish(smtpd: SMTPD, *args: Any, **kwargs: Any) -> None:
154 smtpd._writer.write("wefpPSwrsfa2sdfsdf")
155 await smtpd._writer.drain()
156
157
158 async def mock_response_expn(smtpd: SMTPD, *args: Any, **kwargs: Any) -> None:
159 await smtpd.push(
160 """250-Joseph Blow <[email protected]>
161 250 Alice Smith <[email protected]>"""
162 )
163
164
165 async def mock_response_ehlo_minimal(smtpd: SMTPD, *args: Any, **kwargs: Any) -> None:
166 if args and args[0]:
167 smtpd.session.host_name = args[0]
168
169 await smtpd.push("250 HELP")
170
171
172 async def mock_response_ehlo_full(smtpd: SMTPD, *args: Any, **kwargs: Any) -> None:
173 if args and args[0]:
174 smtpd.session.host_name = args[0]
175
176 await smtpd.push(
177 """250-localhost
178 250-PIPELINING
179 250-8BITMIME
180 250-SIZE 512000
181 250-DSN
182 250-ENHANCEDSTATUSCODES
183 250-EXPN
184 250-HELP
185 250-SAML
186 250-SEND
187 250-SOML
188 250-TURN
189 250-XADR
190 250-XSTA
191 250-ETRN
192 250 XGEN"""
193 )
194
195
196 async def mock_response_unavailable(smtpd: SMTPD, *args: Any, **kwargs: Any) -> None:
197 await smtpd.push("421 retry in 5 minutes")
198 smtpd.transport.close()
199
200
201 async def mock_response_tls_not_available(
202 smtpd: SMTPD, *args: Any, **kwargs: Any
203 ) -> None:
204 await smtpd.push("454 please login")
205
206
207 async def mock_response_tls_ready_disconnect(
208 smtpd: SMTPD, *args: Any, **kwargs: Any
209 ) -> None:
210 await smtpd.push("220 go for it")
211 smtpd.transport.close()
212
213
214 async def mock_response_start_data_disconnect(
215 smtpd: SMTPD, *args: Any, **kwargs: Any
216 ) -> None:
217 await smtpd.push("354 ok")
218 smtpd.transport.close()
219
220
221 async def mock_response_disconnect(smtpd: SMTPD, *args: Any, **kwargs: Any) -> None:
222 smtpd.transport.close()
223
224
225 async def mock_response_eof(smtpd: SMTPD, *args: Any, **kwargs: Any) -> None:
226 smtpd.transport.write_eof()
227
228
229 async def mock_response_mailbox_unavailable(
230 smtpd: SMTPD, *args: Any, **kwargs: Any
231 ) -> None:
232 await smtpd.push(f"{SMTPStatus.mailbox_unavailable} error")
233
234
235 async def mock_response_unrecognized_command(
236 smtpd: SMTPD, *args: Any, **kwargs: Any
237 ) -> None:
238 await smtpd.push(f"{SMTPStatus.unrecognized_command} error")
239
240
241 async def mock_response_bad_command_sequence(
242 smtpd: SMTPD, *args: Any, **kwargs: Any
243 ) -> None:
244 await smtpd.push(f"{SMTPStatus.bad_command_sequence} error")
245
246
247 async def mock_response_syntax_error(smtpd: SMTPD, *args: Any, **kwargs: Any) -> None:
248 await smtpd.push(f"{SMTPStatus.syntax_error} error")
249
250
251 async def mock_response_syntax_error_and_cleanup(
252 smtpd: SMTPD, *args: Any, **kwargs: Any
253 ) -> None:
254 await smtpd.push(f"{SMTPStatus.syntax_error} error")
255
256 if smtpd._handler_coroutine:
257 smtpd._handler_coroutine.cancel()
258 if smtpd.transport:
259 smtpd.transport.close()
260
261
262 async def mock_response_quit_error(smtpd: SMTPD, *args: Any, **kwargs: Any) -> None:
263 await smtpd.push("500 unexpected error")