File: test_auth_methods.py

package info (click to toggle)
aiosmtplib 5.1.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 604 kB
  • sloc: python: 5,823; makefile: 20; sh: 6
file content (306 lines) | stat: -rw-r--r-- 10,530 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
"""
Tests for auth methods on the SMTP class.
"""

import asyncio
import base64

import pytest

from aiosmtplib import SMTP
from aiosmtplib.auth import (
    auth_crammd5_verify,
    auth_login_encode,
    auth_plain_encode,
    auth_xoauth2_encode,
)
from aiosmtplib.errors import SMTPAuthenticationError, SMTPException
from aiosmtplib.response import SMTPResponse
from aiosmtplib.typing import SMTPStatus

from .auth import DummySMTPAuth


SUCCESS_RESPONSE = SMTPResponse(SMTPStatus.auth_successful, "OK")
FAILURE_RESPONSE = SMTPResponse(SMTPStatus.auth_failed, "Nope")


async def test_login_without_extension_raises_error(mock_auth: DummySMTPAuth) -> None:
    mock_auth.esmtp_extensions = {}

    with pytest.raises(SMTPException) as excinfo:
        await mock_auth.login("username", "bogus")

    assert "Try connecting via TLS" not in excinfo.value.args[0]


async def test_login_unknown_method_raises_error(mock_auth: DummySMTPAuth) -> None:
    mock_auth.AUTH_METHODS = ("fakeauth",)
    mock_auth.server_auth_methods = ["fakeauth"]

    with pytest.raises(RuntimeError):
        await mock_auth.login("username", "bogus")


async def test_login_without_method_raises_error(mock_auth: DummySMTPAuth) -> None:
    mock_auth.server_auth_methods = []

    with pytest.raises(SMTPException):
        await mock_auth.login("username", "bogus")


async def test_login_tries_all_methods(mock_auth: DummySMTPAuth) -> None:
    responses = [
        FAILURE_RESPONSE,  # CRAM-MD5
        FAILURE_RESPONSE,  # PLAIN
        (SMTPStatus.auth_continue, "VXNlcm5hbWU6"),  # LOGIN continue
        SUCCESS_RESPONSE,  # LOGIN success
    ]
    mock_auth.responses.extend(responses)
    await mock_auth.login("username", "thirdtimelucky")


async def test_login_all_methods_fail_raises_error(mock_auth: DummySMTPAuth) -> None:
    responses = [
        FAILURE_RESPONSE,  # CRAM-MD5
        FAILURE_RESPONSE,  # PLAIN
        FAILURE_RESPONSE,  # LOGIN
    ]
    mock_auth.responses.extend(responses)
    with pytest.raises(SMTPAuthenticationError):
        await mock_auth.login("username", "bogus")


@pytest.mark.parametrize(
    "username,password",
    [("test", "test"), ("admin124", "$3cr3t$"), ("føø", "bär€")],
    ids=["test user", "admin user", "utf-8 user"],
)
async def test_auth_plain_success(
    mock_auth: DummySMTPAuth, username: str, password: str
) -> None:
    """
    Check that auth_plain base64 encodes the username/password given.
    """
    mock_auth.responses.append(SUCCESS_RESPONSE)
    await mock_auth.auth_plain(username, password)

    encoded = auth_plain_encode(username, password)
    assert mock_auth.received_commands == [b"AUTH PLAIN " + encoded]


async def test_auth_plain_success_bytes(mock_auth: DummySMTPAuth) -> None:
    """
    Check that auth_plain base64 encodes the username/password when given as bytes.
    """
    username = "ภาษา".encode("tis-620")
    password = "ไทย".encode("tis-620")
    mock_auth.responses.append(SUCCESS_RESPONSE)
    await mock_auth.auth_plain(username, password)

    encoded = auth_plain_encode(username, password)
    assert mock_auth.received_commands == [b"AUTH PLAIN " + encoded]


async def test_auth_plain_error(mock_auth: DummySMTPAuth) -> None:
    mock_auth.responses.append(FAILURE_RESPONSE)

    with pytest.raises(SMTPAuthenticationError):
        await mock_auth.auth_plain("username", "bogus")


@pytest.mark.parametrize(
    "username,password",
    [("test", "test"), ("admin124", "$3cr3t$"), ("føø", "bär€")],
    ids=["test user", "admin user", "utf-8 user"],
)
async def test_auth_login_success(
    mock_auth: DummySMTPAuth, username: str, password: str
) -> None:
    continue_response = (SMTPStatus.auth_continue, "VXNlcm5hbWU6")
    mock_auth.responses.extend([continue_response, SUCCESS_RESPONSE])
    await mock_auth.auth_login(username, password)

    encoded_username, encoded_password = auth_login_encode(username, password)

    assert mock_auth.received_commands == [
        b"AUTH LOGIN " + encoded_username,
        encoded_password,
    ]


async def test_auth_login_success_bytes(mock_auth: DummySMTPAuth) -> None:
    continue_response = (SMTPStatus.auth_continue, "VXNlcm5hbWU6")
    mock_auth.responses.extend([continue_response, SUCCESS_RESPONSE])

    username = "ภาษา".encode("tis-620")
    password = "ไทย".encode("tis-620")
    await mock_auth.auth_login(username, password)

    encoded_username, encoded_password = auth_login_encode(username, password)

    assert mock_auth.received_commands == [
        b"AUTH LOGIN " + encoded_username,
        encoded_password,
    ]


async def test_auth_login_error(mock_auth: DummySMTPAuth) -> None:
    mock_auth.responses.append(FAILURE_RESPONSE)
    with pytest.raises(SMTPAuthenticationError):
        await mock_auth.auth_login("username", "bogus")


async def test_auth_plain_continue_error(mock_auth: DummySMTPAuth) -> None:
    continue_response = (SMTPStatus.auth_continue, "VXNlcm5hbWU6")
    mock_auth.responses.extend([continue_response, FAILURE_RESPONSE])

    with pytest.raises(SMTPAuthenticationError):
        await mock_auth.auth_login("username", "bogus")


@pytest.mark.parametrize(
    "username,password",
    [("test", "test"), ("admin124", "$3cr3t$"), ("føø", "bär€")],
    ids=["test user", "admin user", "utf-8 user"],
)
async def test_auth_crammd5_success(
    mock_auth: DummySMTPAuth, username: str, password: str
) -> None:
    continue_response = (
        SMTPStatus.auth_continue,
        base64.b64encode(b"secretteststring").decode("utf-8"),
    )
    mock_auth.responses.extend([continue_response, SUCCESS_RESPONSE])
    await mock_auth.auth_crammd5(username, password)

    password_bytes = password.encode("utf-8")
    username_bytes = username.encode("utf-8")
    response_bytes = continue_response[1].encode("utf-8")

    expected_command = auth_crammd5_verify(
        username_bytes, password_bytes, response_bytes
    )

    assert mock_auth.received_commands == [b"AUTH CRAM-MD5", expected_command]


async def test_auth_crammd5_success_bytes(mock_auth: DummySMTPAuth) -> None:
    continue_response = (
        SMTPStatus.auth_continue,
        base64.b64encode(b"secretteststring").decode("utf-8"),
    )
    mock_auth.responses.extend([continue_response, SUCCESS_RESPONSE])

    username = "ภาษา".encode("tis-620")
    password = "ไทย".encode("tis-620")
    await mock_auth.auth_crammd5(username, password)

    response_bytes = continue_response[1].encode("utf-8")

    expected_command = auth_crammd5_verify(username, password, response_bytes)

    assert mock_auth.received_commands == [b"AUTH CRAM-MD5", expected_command]


async def test_auth_crammd5_initial_error(mock_auth: DummySMTPAuth) -> None:
    mock_auth.responses.append(FAILURE_RESPONSE)

    with pytest.raises(SMTPAuthenticationError):
        await mock_auth.auth_crammd5("username", "bogus")


async def test_auth_crammd5_continue_error(mock_auth: DummySMTPAuth) -> None:
    continue_response = (SMTPStatus.auth_continue, "VXNlcm5hbWU6")
    mock_auth.responses.extend([continue_response, FAILURE_RESPONSE])

    with pytest.raises(SMTPAuthenticationError):
        await mock_auth.auth_crammd5("username", "bogus")


async def test_login_without_starttls_exception(
    smtp_client: SMTP,
    smtpd_server: asyncio.AbstractServer,
    auth_username: str,
    auth_password: str,
) -> None:
    async with smtp_client:
        with pytest.raises(SMTPException) as excinfo:
            await smtp_client.login(auth_username, auth_password)

        assert "Try connecting via TLS" in excinfo.value.args[0]


@pytest.mark.parametrize(
    "username,token",
    [
        ("test@example.com", "ya29.token123"),
        ("user@gmail.com", "access_token_here"),
        ("føø@example.com", "bär€_token"),
    ],
    ids=["test user", "gmail user", "utf-8 user"],
)
async def test_auth_xoauth2_success(
    mock_auth: DummySMTPAuth, username: str, token: str
) -> None:
    """Check that auth_xoauth2 base64 encodes the username/token correctly."""
    mock_auth.responses.append(SUCCESS_RESPONSE)
    await mock_auth.auth_xoauth2(username, token)

    encoded = auth_xoauth2_encode(username, token)
    assert mock_auth.received_commands == [b"AUTH XOAUTH2 " + encoded]


async def test_auth_xoauth2_success_bytes(mock_auth: DummySMTPAuth) -> None:
    """Check that auth_xoauth2 works with bytes input."""
    username = b"user@example.com"
    token = b"access_token_bytes"
    mock_auth.responses.append(SUCCESS_RESPONSE)
    await mock_auth.auth_xoauth2(username, token)

    encoded = auth_xoauth2_encode(username, token)
    assert mock_auth.received_commands == [b"AUTH XOAUTH2 " + encoded]


async def test_auth_xoauth2_error(mock_auth: DummySMTPAuth) -> None:
    """Check that auth_xoauth2 raises on failure response."""
    mock_auth.responses.append(FAILURE_RESPONSE)

    with pytest.raises(SMTPAuthenticationError):
        await mock_auth.auth_xoauth2("user@example.com", "bad_token")


async def test_auth_xoauth2_challenge_error(mock_auth: DummySMTPAuth) -> None:
    """
    Check that auth_xoauth2 handles the error challenge flow.

    On failure, server sends 334 with base64-encoded error JSON,
    client sends empty response, then gets the final 535 error.
    """
    # Server sends error challenge (334), then final error (535)
    challenge_response = (SMTPStatus.auth_continue, "eyJzdGF0dXMiOiI0MDAifQ==")
    mock_auth.responses.extend([challenge_response, FAILURE_RESPONSE])

    with pytest.raises(SMTPAuthenticationError):
        await mock_auth.auth_xoauth2("user@example.com", "expired_token")

    # Verify we sent the initial auth and then empty response
    encoded = auth_xoauth2_encode("user@example.com", "expired_token")
    assert mock_auth.received_commands == [b"AUTH XOAUTH2 " + encoded, b""]


async def test_maybe_login_with_oauth_token_generator(mock_auth: DummySMTPAuth) -> None:
    """Test that _maybe_login_on_connect uses oauth_token_generator when provided."""
    mock_auth.server_auth_methods = ["xoauth2", "plain", "login"]
    mock_auth._login_username = "user@example.com"

    async def get_token() -> str:
        return "test_oauth_token"

    mock_auth._oauth_token_generator = get_token
    mock_auth.responses.append(SUCCESS_RESPONSE)

    await mock_auth._maybe_login_on_connect()

    encoded = auth_xoauth2_encode("user@example.com", "test_oauth_token")
    assert mock_auth.received_commands == [b"AUTH XOAUTH2 " + encoded]