| 1 |
""" |
| 2 |
Protocol level tests. |
| 3 |
""" |
| 4 |
|
| 5 |
import asyncio |
| 6 |
import gc |
| 7 |
import os |
| 8 |
import socket |
| 9 |
import ssl |
| 10 |
|
| 11 |
import pytest |
| 12 |
|
| 13 |
from aiosmtplib import SMTPResponseException, SMTPServerDisconnected, SMTPTimeoutError |
| 14 |
from aiosmtplib.protocol import FlowControlMixin, SMTPProtocol |
| 15 |
|
| 16 |
from .compat import cleanup_server |
| 17 |
|
| 18 |
|
| 19 |
async def test_protocol_connect(hostname: str, echo_server_port: int) -> None: |
| 20 |
event_loop = asyncio.get_running_loop() |
| 21 |
connect_future = event_loop.create_connection( |
| 22 |
SMTPProtocol, host=hostname, port=echo_server_port |
| 23 |
) |
| 24 |
transport, protocol = await asyncio.wait_for(connect_future, timeout=1.0) |
| 25 |
|
| 26 |
assert getattr(protocol, "transport", None) is transport |
| 27 |
assert not transport.is_closing() |
| 28 |
|
| 29 |
transport.close() |
| 30 |
|
| 31 |
|
| 32 |
async def test_protocol_read_limit_overrun( |
| 33 |
bind_address: str, |
| 34 |
hostname: str, |
| 35 |
monkeypatch: pytest.MonkeyPatch, |
| 36 |
) -> None: |
| 37 |
event_loop = asyncio.get_running_loop() |
| 38 |
|
| 39 |
async def client_connected( |
| 40 |
reader: asyncio.StreamReader, writer: asyncio.StreamWriter |
| 41 |
) -> None: |
| 42 |
await reader.read(1000) |
| 43 |
long_response = ( |
| 44 |
b"220 At vero eos et accusamus et iusto odio dignissimos ducimus qui " |
| 45 |
b"blanditiis praesentium voluptatum deleniti atque corruptis qui " |
| 46 |
b"blanditiis praesentium voluptatum\n" |
| 47 |
) |
| 48 |
writer.write(long_response) |
| 49 |
await writer.drain() |
| 50 |
|
| 51 |
server = await asyncio.start_server( |
| 52 |
client_connected, host=bind_address, port=0, family=socket.AF_INET |
| 53 |
) |
| 54 |
server_port = server.sockets[0].getsockname()[1] if server.sockets else 0 |
| 55 |
connect_future = event_loop.create_connection( |
| 56 |
SMTPProtocol, host=hostname, port=server_port |
| 57 |
) |
| 58 |
|
| 59 |
_, protocol = await asyncio.wait_for(connect_future, timeout=1.0) |
| 60 |
|
| 61 |
monkeypatch.setattr("aiosmtplib.protocol.MAX_LINE_LENGTH", 128) |
| 62 |
|
| 63 |
with pytest.raises(SMTPResponseException) as exc_info: |
| 64 |
await protocol.execute_command(b"TEST", timeout=1.0) # type: ignore |
| 65 |
|
| 66 |
assert exc_info.value.code == -1 |
| 67 |
assert "Response too long" in exc_info.value.message |
| 68 |
|
| 69 |
server.close() |
| 70 |
await cleanup_server(server) |
| 71 |
|
| 72 |
|
| 73 |
async def test_protocol_response_no_newline_overrun( |
| 74 |
bind_address: str, |
| 75 |
hostname: str, |
| 76 |
monkeypatch: pytest.MonkeyPatch, |
| 77 |
) -> None: |
| 78 |
event_loop = asyncio.get_running_loop() |
| 79 |
|
| 80 |
async def client_connected( |
| 81 |
reader: asyncio.StreamReader, writer: asyncio.StreamWriter |
| 82 |
) -> None: |
| 83 |
await reader.read(1000) |
| 84 |
# No line ending at all, so the per-line cap is never reached. |
| 85 |
writer.write(b"2" * 500) |
| 86 |
await writer.drain() |
| 87 |
|
| 88 |
server = await asyncio.start_server( |
| 89 |
client_connected, host=bind_address, port=0, family=socket.AF_INET |
| 90 |
) |
| 91 |
server_port = server.sockets[0].getsockname()[1] if server.sockets else 0 |
| 92 |
connect_future = event_loop.create_connection( |
| 93 |
SMTPProtocol, host=hostname, port=server_port |
| 94 |
) |
| 95 |
|
| 96 |
_, protocol = await asyncio.wait_for(connect_future, timeout=1.0) |
| 97 |
|
| 98 |
monkeypatch.setattr("aiosmtplib.protocol.MAX_RESPONSE_LENGTH", 128) |
| 99 |
|
| 100 |
with pytest.raises(SMTPResponseException) as exc_info: |
| 101 |
await protocol.execute_command(b"TEST", timeout=1.0) # type: ignore |
| 102 |
|
| 103 |
assert exc_info.value.code == -1 |
| 104 |
assert "Response too long" in exc_info.value.message |
| 105 |
|
| 106 |
server.close() |
| 107 |
await cleanup_server(server) |
| 108 |
|
| 109 |
|
| 110 |
async def test_protocol_response_continuation_overrun( |
| 111 |
bind_address: str, |
| 112 |
hostname: str, |
| 113 |
monkeypatch: pytest.MonkeyPatch, |
| 114 |
) -> None: |
| 115 |
event_loop = asyncio.get_running_loop() |
| 116 |
|
| 117 |
async def client_connected( |
| 118 |
reader: asyncio.StreamReader, writer: asyncio.StreamWriter |
| 119 |
) -> None: |
| 120 |
await reader.read(1000) |
| 121 |
# Endless multiline continuation; each line is well under the per-line |
| 122 |
# cap, so only the total response cap can stop it. |
| 123 |
writer.write(b"250-spam\r\n" * 100) |
| 124 |
await writer.drain() |
| 125 |
|
| 126 |
server = await asyncio.start_server( |
| 127 |
client_connected, host=bind_address, port=0, family=socket.AF_INET |
| 128 |
) |
| 129 |
server_port = server.sockets[0].getsockname()[1] if server.sockets else 0 |
| 130 |
connect_future = event_loop.create_connection( |
| 131 |
SMTPProtocol, host=hostname, port=server_port |
| 132 |
) |
| 133 |
|
| 134 |
_, protocol = await asyncio.wait_for(connect_future, timeout=1.0) |
| 135 |
|
| 136 |
monkeypatch.setattr("aiosmtplib.protocol.MAX_RESPONSE_LENGTH", 128) |
| 137 |
|
| 138 |
with pytest.raises(SMTPResponseException) as exc_info: |
| 139 |
await protocol.execute_command(b"TEST", timeout=1.0) # type: ignore |
| 140 |
|
| 141 |
assert exc_info.value.code == -1 |
| 142 |
assert "Response too long" in exc_info.value.message |
| 143 |
|
| 144 |
server.close() |
| 145 |
await cleanup_server(server) |
| 146 |
|
| 147 |
|
| 148 |
async def test_protocol_connected_check_on_read_response( |
| 149 |
monkeypatch: pytest.MonkeyPatch, |
| 150 |
) -> None: |
| 151 |
protocol = SMTPProtocol() |
| 152 |
monkeypatch.setattr(protocol, "transport", None) |
| 153 |
|
| 154 |
with pytest.raises(SMTPServerDisconnected): |
| 155 |
await protocol.read_response(timeout=1.0) |
| 156 |
|
| 157 |
|
| 158 |
async def test_protocol_read_only_transport_error() -> None: |
| 159 |
event_loop = asyncio.get_running_loop() |
| 160 |
read_descriptor, _ = os.pipe() |
| 161 |
read_pipe = os.fdopen(read_descriptor, "rb", buffering=0) |
| 162 |
connect_future = event_loop.connect_read_pipe(SMTPProtocol, read_pipe) |
| 163 |
transport, protocol = await asyncio.wait_for(connect_future, timeout=1.0) |
| 164 |
|
| 165 |
assert getattr(protocol, "transport", None) is transport |
| 166 |
|
| 167 |
with pytest.raises(RuntimeError, match="does not support writing"): |
| 168 |
protocol.write(b"TEST\n") |
| 169 |
|
| 170 |
transport.close() |
| 171 |
|
| 172 |
|
| 173 |
async def test_protocol_connected_check_on_start_tls( |
| 174 |
client_tls_context: ssl.SSLContext, |
| 175 |
) -> None: |
| 176 |
smtp_protocol = SMTPProtocol() |
| 177 |
|
| 178 |
with pytest.raises(SMTPServerDisconnected): |
| 179 |
await smtp_protocol.start_tls(client_tls_context, timeout=1.0) |
| 180 |
|
| 181 |
|
| 182 |
async def test_protocol_already_over_tls_check_on_start_tls( |
| 183 |
client_tls_context: ssl.SSLContext, |
| 184 |
) -> None: |
| 185 |
smtp_protocol = SMTPProtocol() |
| 186 |
smtp_protocol._over_ssl = True |
| 187 |
|
| 188 |
with pytest.raises(RuntimeError, match="Already using TLS"): |
| 189 |
await smtp_protocol.start_tls(client_tls_context) |
| 190 |
|
| 191 |
|
| 192 |
async def test_protocol_connection_reset_on_starttls( |
| 193 |
hostname: str, |
| 194 |
smtpd_server_port: int, |
| 195 |
client_tls_context: ssl.SSLContext, |
| 196 |
monkeypatch: pytest.MonkeyPatch, |
| 197 |
) -> None: |
| 198 |
event_loop = asyncio.get_running_loop() |
| 199 |
|
| 200 |
connect_future = event_loop.create_connection( |
| 201 |
SMTPProtocol, host=hostname, port=smtpd_server_port |
| 202 |
) |
| 203 |
transport, protocol = await asyncio.wait_for(connect_future, timeout=1.0) |
| 204 |
|
| 205 |
def mock_start_tls(*args, **kwargs) -> None: |
| 206 |
raise ConnectionResetError("Connection was reset") |
| 207 |
|
| 208 |
monkeypatch.setattr(event_loop, "start_tls", mock_start_tls) |
| 209 |
|
| 210 |
with pytest.raises(SMTPServerDisconnected): |
| 211 |
await protocol.start_tls(client_tls_context) |
| 212 |
|
| 213 |
transport.close() |
| 214 |
|
| 215 |
|
| 216 |
async def test_protocol_timeout_on_starttls( |
| 217 |
hostname: str, |
| 218 |
smtpd_server_port: int, |
| 219 |
client_tls_context: ssl.SSLContext, |
| 220 |
monkeypatch: pytest.MonkeyPatch, |
| 221 |
) -> None: |
| 222 |
event_loop = asyncio.get_running_loop() |
| 223 |
|
| 224 |
connect_future = event_loop.create_connection( |
| 225 |
SMTPProtocol, host=hostname, port=smtpd_server_port |
| 226 |
) |
| 227 |
transport, protocol = await asyncio.wait_for(connect_future, timeout=1.0) |
| 228 |
|
| 229 |
def mock_start_tls(*args, **kwargs) -> None: |
| 230 |
raise TimeoutError("Timed out") |
| 231 |
|
| 232 |
monkeypatch.setattr(event_loop, "start_tls", mock_start_tls) |
| 233 |
|
| 234 |
with pytest.raises(SMTPTimeoutError, match="Timed out while upgrading transport"): |
| 235 |
await protocol.start_tls(client_tls_context) |
| 236 |
|
| 237 |
transport.close() |
| 238 |
|
| 239 |
|
| 240 |
async def test_protocol_discards_buffer_before_tls_handshake( |
| 241 |
bind_address: str, |
| 242 |
hostname: str, |
| 243 |
client_tls_context: ssl.SSLContext, |
| 244 |
monkeypatch: pytest.MonkeyPatch, |
| 245 |
) -> None: |
| 246 |
""" |
| 247 |
Bytes a MITM injects after the 220 STARTTLS reply must not survive into the |
| 248 |
encrypted session. |
| 249 |
""" |
| 250 |
event_loop = asyncio.get_running_loop() |
| 251 |
|
| 252 |
async def client_connected( |
| 253 |
reader: asyncio.StreamReader, writer: asyncio.StreamWriter |
| 254 |
) -> None: |
| 255 |
await reader.readuntil(b"\r\n") |
| 256 |
# 220 reply plus injected plaintext, in a single segment. |
| 257 |
writer.write(b"220 Go ahead\r\n250-mx.evil\r\n250 AUTH LOGIN\r\n") |
| 258 |
await writer.drain() |
| 259 |
await reader.read() # keep the connection open through start_tls |
| 260 |
|
| 261 |
server = await asyncio.start_server( |
| 262 |
client_connected, host=bind_address, port=0, family=socket.AF_INET |
| 263 |
) |
| 264 |
server_port = server.sockets[0].getsockname()[1] if server.sockets else 0 |
| 265 |
connect_future = event_loop.create_connection( |
| 266 |
SMTPProtocol, host=hostname, port=server_port |
| 267 |
) |
| 268 |
_, protocol = await asyncio.wait_for(connect_future, timeout=1.0) |
| 269 |
|
| 270 |
captured: dict[str, bytes] = {} |
| 271 |
|
| 272 |
async def mock_start_tls(transport, proto, *args, **kwargs): # type: ignore[no-untyped-def] |
| 273 |
captured["buffer"] = bytes(proto._buffer) |
| 274 |
return transport |
| 275 |
|
| 276 |
monkeypatch.setattr(event_loop, "start_tls", mock_start_tls) |
| 277 |
|
| 278 |
response = await protocol.start_tls(client_tls_context, timeout=1.0) # type: ignore[union-attr] |
| 279 |
|
| 280 |
assert response.code == 220 |
| 281 |
assert captured["buffer"] == b"" |
| 282 |
|
| 283 |
server.close() |
| 284 |
await cleanup_server(server) |
| 285 |
|
| 286 |
|
| 287 |
async def test_error_on_readline_with_partial_line( |
| 288 |
bind_address: str, hostname: str |
| 289 |
) -> None: |
| 290 |
event_loop = asyncio.get_running_loop() |
| 291 |
partial_response = b"499 incomplete response\\" |
| 292 |
|
| 293 |
async def client_connected( |
| 294 |
reader: asyncio.StreamReader, writer: asyncio.StreamWriter |
| 295 |
) -> None: |
| 296 |
writer.write(partial_response) |
| 297 |
writer.write_eof() |
| 298 |
await writer.drain() |
| 299 |
|
| 300 |
server = await asyncio.start_server( |
| 301 |
client_connected, host=bind_address, port=0, family=socket.AF_INET |
| 302 |
) |
| 303 |
server_port = server.sockets[0].getsockname()[1] if server.sockets else 0 |
| 304 |
|
| 305 |
connect_future = event_loop.create_connection( |
| 306 |
SMTPProtocol, host=hostname, port=server_port |
| 307 |
) |
| 308 |
|
| 309 |
_, protocol = await asyncio.wait_for(connect_future, timeout=1.0) |
| 310 |
|
| 311 |
with pytest.raises(SMTPServerDisconnected): |
| 312 |
await protocol.read_response(timeout=1.0) # type: ignore |
| 313 |
|
| 314 |
server.close() |
| 315 |
await cleanup_server(server) |
| 316 |
|
| 317 |
|
| 318 |
async def test_protocol_error_on_readline_with_malformed_response( |
| 319 |
bind_address: str, hostname: str |
| 320 |
) -> None: |
| 321 |
event_loop = asyncio.get_running_loop() |
| 322 |
response = b"ERROR\n" |
| 323 |
|
| 324 |
async def client_connected( |
| 325 |
reader: asyncio.StreamReader, writer: asyncio.StreamWriter |
| 326 |
) -> None: |
| 327 |
writer.write(response) |
| 328 |
writer.write_eof() |
| 329 |
await writer.drain() |
| 330 |
|
| 331 |
server = await asyncio.start_server( |
| 332 |
client_connected, host=bind_address, port=0, family=socket.AF_INET |
| 333 |
) |
| 334 |
server_port = server.sockets[0].getsockname()[1] if server.sockets else 0 |
| 335 |
|
| 336 |
connect_future = event_loop.create_connection( |
| 337 |
SMTPProtocol, host=hostname, port=server_port |
| 338 |
) |
| 339 |
|
| 340 |
_, protocol = await asyncio.wait_for(connect_future, timeout=1.0) |
| 341 |
|
| 342 |
with pytest.raises( |
| 343 |
SMTPResponseException, match="Malformed SMTP response line: ERROR" |
| 344 |
): |
| 345 |
await protocol.read_response(timeout=1.0) # type: ignore |
| 346 |
|
| 347 |
server.close() |
| 348 |
await cleanup_server(server) |
| 349 |
|
| 350 |
|
| 351 |
async def test_protocol_response_waiter_unset( |
| 352 |
bind_address: str, |
| 353 |
hostname: str, |
| 354 |
monkeypatch: pytest.MonkeyPatch, |
| 355 |
) -> None: |
| 356 |
event_loop = asyncio.get_running_loop() |
| 357 |
|
| 358 |
async def client_connected( |
| 359 |
reader: asyncio.StreamReader, writer: asyncio.StreamWriter |
| 360 |
) -> None: |
| 361 |
await reader.read(1000) |
| 362 |
writer.write(b"220 Hi\r\n") |
| 363 |
await writer.drain() |
| 364 |
|
| 365 |
server = await asyncio.start_server( |
| 366 |
client_connected, host=bind_address, port=0, family=socket.AF_INET |
| 367 |
) |
| 368 |
server_port = server.sockets[0].getsockname()[1] if server.sockets else 0 |
| 369 |
|
| 370 |
connect_future = event_loop.create_connection( |
| 371 |
SMTPProtocol, host=hostname, port=server_port |
| 372 |
) |
| 373 |
|
| 374 |
_, protocol = await asyncio.wait_for(connect_future, timeout=1.0) |
| 375 |
|
| 376 |
monkeypatch.setattr(protocol, "_response_waiter", None) |
| 377 |
|
| 378 |
with pytest.raises(SMTPServerDisconnected): |
| 379 |
await protocol.execute_command(b"TEST", timeout=1.0) # type: ignore |
| 380 |
|
| 381 |
server.close() |
| 382 |
await cleanup_server(server) |
| 383 |
|
| 384 |
|
| 385 |
async def test_protocol_data_received_called_twice( |
| 386 |
bind_address: str, |
| 387 |
hostname: str, |
| 388 |
) -> None: |
| 389 |
event_loop = asyncio.get_running_loop() |
| 390 |
|
| 391 |
async def client_connected( |
| 392 |
reader: asyncio.StreamReader, writer: asyncio.StreamWriter |
| 393 |
) -> None: |
| 394 |
await reader.read(1000) |
| 395 |
writer.write(b"220 Hi\r\n") |
| 396 |
await writer.drain() |
| 397 |
await asyncio.sleep(0) |
| 398 |
writer.write(b"221 Hi again!\r\n") |
| 399 |
await writer.drain() |
| 400 |
|
| 401 |
server = await asyncio.start_server( |
| 402 |
client_connected, host=bind_address, port=0, family=socket.AF_INET |
| 403 |
) |
| 404 |
server_port = server.sockets[0].getsockname()[1] if server.sockets else 0 |
| 405 |
|
| 406 |
connect_future = event_loop.create_connection( |
| 407 |
SMTPProtocol, host=hostname, port=server_port |
| 408 |
) |
| 409 |
|
| 410 |
_, protocol = await asyncio.wait_for(connect_future, timeout=1.0) |
| 411 |
|
| 412 |
response = await protocol.execute_command(b"TEST", timeout=1.0) # type: ignore |
| 413 |
|
| 414 |
assert response.code == 220 |
| 415 |
assert response.message == "Hi" |
| 416 |
|
| 417 |
server.close() |
| 418 |
await cleanup_server(server) |
| 419 |
|
| 420 |
|
| 421 |
async def test_protocol_eof_response(bind_address: str, hostname: str) -> None: |
| 422 |
event_loop = asyncio.get_running_loop() |
| 423 |
|
| 424 |
async def client_connected( |
| 425 |
reader: asyncio.StreamReader, writer: asyncio.StreamWriter |
| 426 |
) -> None: |
| 427 |
writer.transport.abort() # type: ignore |
| 428 |
|
| 429 |
server = await asyncio.start_server( |
| 430 |
client_connected, host=bind_address, port=0, family=socket.AF_INET |
| 431 |
) |
| 432 |
server_port = server.sockets[0].getsockname()[1] if server.sockets else 0 |
| 433 |
|
| 434 |
connect_future = event_loop.create_connection( |
| 435 |
SMTPProtocol, host=hostname, port=server_port |
| 436 |
) |
| 437 |
await asyncio.wait_for(connect_future, timeout=1.0) |
| 438 |
|
| 439 |
server.close() |
| 440 |
await cleanup_server(server) |
| 441 |
|
| 442 |
|
| 443 |
@pytest.mark.skip_if_uvloop(reason="flaky on uvloop") |
| 444 |
async def test_protocol_exception_cleanup_warning( |
| 445 |
caplog: pytest.LogCaptureFixture, |
| 446 |
debug_event_loop: asyncio.AbstractEventLoop, |
| 447 |
bind_address: str, |
| 448 |
hostname: str, |
| 449 |
) -> None: |
| 450 |
async def client_connected( |
| 451 |
reader: asyncio.StreamReader, writer: asyncio.StreamWriter |
| 452 |
) -> None: |
| 453 |
await reader.read(1000) |
| 454 |
writer.write(b"220 Hi\r\n") |
| 455 |
await writer.drain() |
| 456 |
|
| 457 |
await reader.read(1000) |
| 458 |
writer.write(b"221 Bye\r\n") |
| 459 |
await writer.drain() |
| 460 |
|
| 461 |
writer.transport.close() |
| 462 |
|
| 463 |
server = await asyncio.start_server( |
| 464 |
client_connected, host=bind_address, port=0, family=socket.AF_INET |
| 465 |
) |
| 466 |
server_port = server.sockets[0].getsockname()[1] if server.sockets else 0 |
| 467 |
|
| 468 |
connect_future = debug_event_loop.create_connection( |
| 469 |
SMTPProtocol, host=hostname, port=server_port |
| 470 |
) |
| 471 |
_, protocol = await asyncio.wait_for(connect_future, timeout=1.0) |
| 472 |
|
| 473 |
await protocol.execute_command(b"HELO", timeout=1.0) |
| 474 |
await protocol.execute_command(b"QUIT", timeout=1.0) |
| 475 |
|
| 476 |
del protocol |
| 477 |
# Force garbage collection |
| 478 |
gc.collect() |
| 479 |
|
| 480 |
server.close() |
| 481 |
await cleanup_server(server) |
| 482 |
|
| 483 |
assert "Future exception was never retrieved" not in caplog.text |
| 484 |
|
| 485 |
|
| 486 |
async def test_protocol_get_close_waiter() -> None: |
| 487 |
event_loop = asyncio.get_running_loop() |
| 488 |
protocol = SMTPProtocol(event_loop) |
| 489 |
|
| 490 |
close_waiter = protocol._get_close_waiter(None) # type: ignore |
| 491 |
assert close_waiter is not None |
| 492 |
|
| 493 |
|
| 494 |
async def test_protocol_missing_command_lock_disconnected() -> None: |
| 495 |
event_loop = asyncio.get_running_loop() |
| 496 |
protocol = SMTPProtocol(event_loop) |
| 497 |
|
| 498 |
with pytest.raises(SMTPServerDisconnected): |
| 499 |
await protocol.execute_command(b"TEST") |
| 500 |
|
| 501 |
with pytest.raises(SMTPServerDisconnected): |
| 502 |
await protocol.execute_data_command(b"TEST\n") |
| 503 |
|
| 504 |
|
| 505 |
async def test_flow_control_mixin_drain() -> None: |
| 506 |
event_loop = asyncio.get_running_loop() |
| 507 |
|
| 508 |
# Adapted from stdlib |
| 509 |
drained = 0 |
| 510 |
|
| 511 |
async def drainer(stream) -> None: |
| 512 |
nonlocal drained |
| 513 |
await stream._drain_helper() |
| 514 |
drained += 1 |
| 515 |
|
| 516 |
stream = FlowControlMixin(event_loop) |
| 517 |
stream.pause_writing() |
| 518 |
event_loop.call_later(0.1, stream.resume_writing) |
| 519 |
await asyncio.gather(*[drainer(stream) for _ in range(10)]) |
| 520 |
assert drained == 10 |
| 521 |
|
| 522 |
|
| 523 |
async def test_flow_control_mixin_drain_incomplete() -> None: |
| 524 |
event_loop = asyncio.get_running_loop() |
| 525 |
|
| 526 |
flow_control = FlowControlMixin(event_loop) |
| 527 |
flow_control.pause_writing() |
| 528 |
|
| 529 |
waiter = event_loop.create_future() |
| 530 |
flow_control._drain_waiters.append(waiter) |
| 531 |
|
| 532 |
waiter.set_result("test") |
| 533 |
flow_control.resume_writing() |
| 534 |
|
| 535 |
assert waiter.done() |
| 536 |
assert not waiter.cancelled() |
| 537 |
|
| 538 |
|
| 539 |
async def test_flow_control_mixin_connection_lost_exception() -> None: |
| 540 |
event_loop = asyncio.get_running_loop() |
| 541 |
|
| 542 |
flow_control = FlowControlMixin(event_loop) |
| 543 |
flow_control.pause_writing() |
| 544 |
waiter = event_loop.create_future() |
| 545 |
|
| 546 |
flow_control._drain_waiters.append(waiter) |
| 547 |
|
| 548 |
exc = ConnectionAbortedError("boom") |
| 549 |
flow_control.connection_lost(exc) |
| 550 |
|
| 551 |
assert waiter.done() |
| 552 |
assert not waiter.cancelled() |
| 553 |
assert waiter.exception() is exc |
| 554 |
|
| 555 |
|
| 556 |
async def test_flow_control_mixin_connection_lost_no_exception() -> None: |
| 557 |
event_loop = asyncio.get_running_loop() |
| 558 |
|
| 559 |
flow_control = FlowControlMixin(event_loop) |
| 560 |
flow_control.pause_writing() |
| 561 |
waiter = event_loop.create_future() |
| 562 |
|
| 563 |
flow_control._drain_waiters.append(waiter) |
| 564 |
|
| 565 |
flow_control.connection_lost(None) |
| 566 |
|
| 567 |
assert waiter.done() |
| 568 |
assert not waiter.cancelled() |
| 569 |
assert waiter.exception() is None |
| 570 |
|
| 571 |
|
| 572 |
async def test_flow_control_mixin_connection_lost_done() -> None: |
| 573 |
event_loop = asyncio.get_running_loop() |
| 574 |
|
| 575 |
flow_control = FlowControlMixin(event_loop) |
| 576 |
flow_control.pause_writing() |
| 577 |
waiter = event_loop.create_future() |
| 578 |
|
| 579 |
flow_control._drain_waiters.append(waiter) |
| 580 |
exc = ConnectionResetError("boom") |
| 581 |
waiter.set_exception(exc) |
| 582 |
|
| 583 |
flow_control.connection_lost(None) |
| 584 |
|
| 585 |
assert waiter.done() |
| 586 |
assert not waiter.cancelled() |
| 587 |
assert waiter.exception() is exc |
| 588 |
|
| 589 |
|
| 590 |
async def test_flow_control_mixin_drain_helper() -> None: |
| 591 |
loop = asyncio.get_running_loop() |
| 592 |
flow_control = FlowControlMixin(loop) |
| 593 |
|
| 594 |
await flow_control._drain_helper() |
| 595 |
|
| 596 |
|
| 597 |
async def test_flow_control_mixin_drain_helper_connection_lost() -> None: |
| 598 |
loop = asyncio.get_running_loop() |
| 599 |
flow_control = FlowControlMixin(loop) |
| 600 |
flow_control.pause_writing() |
| 601 |
flow_control.connection_lost(None) |
| 602 |
|
| 603 |
with pytest.raises(ConnectionResetError): |
| 604 |
await flow_control._drain_helper() |
| 605 |
|
| 606 |
|
| 607 |
class _FakeTransport(asyncio.Transport): |
| 608 |
"""Minimal transport stub for driving SMTPProtocol callbacks directly.""" |
| 609 |
|
| 610 |
def __init__(self) -> None: |
| 611 |
super().__init__() |
| 612 |
self._extra: dict[str, object] = {"sslcontext": object()} |
| 613 |
|
| 614 |
def get_extra_info(self, name: str, default: object = None) -> object: |
| 615 |
return self._extra.get(name, default) |
| 616 |
|
| 617 |
def is_closing(self) -> bool: |
| 618 |
return False |
| 619 |
|
| 620 |
|
| 621 |
async def test_protocol_connection_lost_after_quit_resolves_waiter() -> None: |
| 622 |
""" |
| 623 |
Regression test for https://github.com/cole/aiosmtplib/issues/345. |
| 624 |
|
| 625 |
When the peer drops the transport with an exception after ``QUIT\\r\\n`` |
| 626 |
has been written but before the 221 reply is parsed (e.g. AWS SES closes |
| 627 |
TLS without ``close_notify``, surfaced as ``connection_lost(SSLEOFError)``), |
| 628 |
the response waiter must be resolved so that ``SMTP.quit()`` returns |
| 629 |
promptly instead of blocking until the read timeout. |
| 630 |
""" |
| 631 |
protocol = SMTPProtocol() |
| 632 |
protocol.connection_made(_FakeTransport()) |
| 633 |
|
| 634 |
protocol._quit_sent = True |
| 635 |
waiter = protocol._response_waiter |
| 636 |
assert waiter is not None and not waiter.done() |
| 637 |
|
| 638 |
protocol.connection_lost(ssl.SSLEOFError("EOF occurred in violation of protocol")) |
| 639 |
|
| 640 |
assert waiter.done() |
| 641 |
assert waiter.exception() is None |
| 642 |
response = waiter.result() |
| 643 |
assert response.code == 221 |
| 644 |
|
| 645 |
|
| 646 |
async def test_protocol_connection_lost_without_quit_raises() -> None: |
| 647 |
""" |
| 648 |
Without an outstanding QUIT, ``connection_lost`` must continue to |
| 649 |
surface ``SMTPServerDisconnected`` on the response waiter. |
| 650 |
""" |
| 651 |
protocol = SMTPProtocol() |
| 652 |
protocol.connection_made(_FakeTransport()) |
| 653 |
|
| 654 |
waiter = protocol._response_waiter |
| 655 |
assert waiter is not None and not waiter.done() |
| 656 |
|
| 657 |
protocol.connection_lost(ConnectionResetError("boom")) |
| 658 |
|
| 659 |
assert waiter.done() |
| 660 |
exc = waiter.exception() |
| 661 |
assert isinstance(exc, SMTPServerDisconnected) |
| 662 |
|
| 663 |
|
| 664 |
class _WriteRecordingTransport(_FakeTransport): |
| 665 |
def __init__(self) -> None: |
| 666 |
super().__init__() |
| 667 |
self.writes: list[bytes] = [] |
| 668 |
|
| 669 |
def write(self, data: bytes) -> None: |
| 670 |
self.writes.append(data) |
| 671 |
|
| 672 |
|
| 673 |
@pytest.mark.parametrize( |
| 674 |
"arg", |
| 675 |
( |
| 676 |
b"FROM:<[email protected]\r\nRCPT TO:<[email protected]>", |
| 677 |
b"FROM:<[email protected]\rRCPT TO:<[email protected]>", |
| 678 |
b"FROM:<[email protected]\nRCPT TO:<[email protected]>", |
| 679 |
b"FROM:<[email protected]\x00>", |
| 680 |
b"FROM:<[email protected]\tEVIL>", |
| 681 |
b"FROM:<[email protected]\x7f>", |
| 682 |
), |
| 683 |
ids=("crlf", "cr", "lf", "nul", "tab", "del"), |
| 684 |
) |
| 685 |
async def test_protocol_execute_command_rejects_injected_args(arg: bytes) -> None: |
| 686 |
protocol = SMTPProtocol() |
| 687 |
transport = _WriteRecordingTransport() |
| 688 |
protocol.connection_made(transport) |
| 689 |
|
| 690 |
with pytest.raises(ValueError, match="prohibited"): |
| 691 |
await protocol.execute_command(b"MAIL", arg, timeout=1.0) |
| 692 |
|
| 693 |
assert transport.writes == [] |
| 694 |
|
| 695 |
|
| 696 |
async def test_protocol_execute_command_rejects_injected_option() -> None: |
| 697 |
protocol = SMTPProtocol() |
| 698 |
transport = _WriteRecordingTransport() |
| 699 |
protocol.connection_made(transport) |
| 700 |
|
| 701 |
with pytest.raises(ValueError, match="prohibited"): |
| 702 |
await protocol.execute_command( |
| 703 |
b"MAIL", b"FROM:<[email protected]>", b"BODY=8BITMIME\r\nDATA", timeout=1.0 |
| 704 |
) |
| 705 |
|
| 706 |
assert transport.writes == [] |
| 707 |
|
| 708 |
|
| 709 |
async def test_protocol_ignores_unsolicited_data_between_commands() -> None: |
| 710 |
""" |
| 711 |
Data received while no command is outstanding must be discarded, not stored |
| 712 |
on the next waiter. Otherwise a single unsolicited line permanently desyncs |
| 713 |
every subsequent command/response pair by one. |
| 714 |
""" |
| 715 |
protocol = SMTPProtocol() |
| 716 |
transport = _WriteRecordingTransport() |
| 717 |
protocol.connection_made(transport) |
| 718 |
|
| 719 |
# Greeting, consumed by a normal read. |
| 720 |
protocol.data_received(b"220 hi\r\n") |
| 721 |
greeting = await protocol.read_response(timeout=1.0) |
| 722 |
assert greeting.code == 220 |
| 723 |
|
| 724 |
# An unsolicited line arrives while the client is idle between commands. |
| 725 |
protocol.data_received(b"250 unsolicited\r\n") |
| 726 |
assert protocol._response_waiter is not None |
| 727 |
assert not protocol._response_waiter.done() |
| 728 |
assert protocol._buffer == bytearray() |
| 729 |
|
| 730 |
# The next command must receive its OWN response, not the stale line. |
| 731 |
task = asyncio.ensure_future(protocol.execute_command(b"NOOP", timeout=1.0)) |
| 732 |
await asyncio.sleep(0) # let the command write and start awaiting |
| 733 |
protocol.data_received(b"250 real noop reply\r\n") |
| 734 |
|
| 735 |
response = await task |
| 736 |
assert response.code == 250 |
| 737 |
assert response.message == "real noop reply" |
| 738 |
|
| 739 |
|
| 740 |
async def test_protocol_ignores_unsolicited_multiline_data() -> None: |
| 741 |
"""An unsolicited multiline response between commands must be discarded.""" |
| 742 |
protocol = SMTPProtocol() |
| 743 |
transport = _WriteRecordingTransport() |
| 744 |
protocol.connection_made(transport) |
| 745 |
|
| 746 |
protocol.data_received(b"220 hi\r\n") |
| 747 |
greeting = await protocol.read_response(timeout=1.0) |
| 748 |
assert greeting.code == 220 |
| 749 |
|
| 750 |
# A full multiline response arrives while no command is outstanding. |
| 751 |
protocol.data_received(b"250-foo\r\n250-bar\r\n250 baz\r\n") |
| 752 |
assert protocol._response_waiter is not None |
| 753 |
assert not protocol._response_waiter.done() |
| 754 |
assert protocol._buffer == bytearray() |
| 755 |
|
| 756 |
task = asyncio.ensure_future(protocol.execute_command(b"NOOP", timeout=1.0)) |
| 757 |
await asyncio.sleep(0) |
| 758 |
protocol.data_received(b"250 real\r\n") |
| 759 |
|
| 760 |
response = await task |
| 761 |
assert response.code == 250 |
| 762 |
assert response.message == "real" |
| 763 |
|
| 764 |
|
| 765 |
async def test_protocol_ignores_unsolicited_partial_data() -> None: |
| 766 |
""" |
| 767 |
Unsolicited data fragmented across data_received calls between commands |
| 768 |
must be discarded, not buffered for the next command. |
| 769 |
""" |
| 770 |
protocol = SMTPProtocol() |
| 771 |
transport = _WriteRecordingTransport() |
| 772 |
protocol.connection_made(transport) |
| 773 |
|
| 774 |
protocol.data_received(b"220 hi\r\n") |
| 775 |
greeting = await protocol.read_response(timeout=1.0) |
| 776 |
assert greeting.code == 220 |
| 777 |
|
| 778 |
# Unsolicited response trickling in across multiple chunks, including a |
| 779 |
# mid-line split, while no command is outstanding. |
| 780 |
protocol.data_received(b"250-foo\r\n") |
| 781 |
protocol.data_received(b"250 ba") |
| 782 |
protocol.data_received(b"r\r\n") |
| 783 |
assert protocol._response_waiter is not None |
| 784 |
assert not protocol._response_waiter.done() |
| 785 |
assert protocol._buffer == bytearray() |
| 786 |
|
| 787 |
task = asyncio.ensure_future(protocol.execute_command(b"NOOP", timeout=1.0)) |
| 788 |
await asyncio.sleep(0) |
| 789 |
protocol.data_received(b"250 real\r\n") |
| 790 |
|
| 791 |
response = await task |
| 792 |
assert response.code == 250 |
| 793 |
assert response.message == "real" |
| 794 |
|
| 795 |
|
| 796 |
async def test_protocol_data_received_without_response_waiter() -> None: |
| 797 |
""" |
| 798 |
Data can arrive after the connection is lost but before cleanup |
| 799 |
(e.g. a queued data_received callback); it should be dropped, not raise. |
| 800 |
""" |
| 801 |
protocol = SMTPProtocol(loop=asyncio.get_running_loop()) |
| 802 |
assert protocol._response_waiter is None |
| 803 |
|
| 804 |
protocol.data_received(b"421 Going away\r\n") |
| 805 |
|
| 806 |
assert not protocol._buffer |