| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
"""Unit tests for the asynceapi._auth module.""" |
| 5 |
|
| 6 |
from __future__ import annotations |
| 7 |
|
| 8 |
import asyncio |
| 9 |
import logging |
| 10 |
|
| 11 |
import httpx |
| 12 |
import pytest |
| 13 |
|
| 14 |
from asynceapi._auth import EapiSessionAuth, _cookie_fingerprint |
| 15 |
from asynceapi.errors import EapiAsyncOnlyError, EapiAuthenticationError |
| 16 |
|
| 17 |
_HOST = "192.0.2.1" |
| 18 |
_USERNAME = "admin" |
| 19 |
_PASSWORD = "test1234" |
| 20 |
|
| 21 |
_LOGIN_URL = f"https://{_HOST}:443/login" |
| 22 |
_COMMAND_URL = f"https://{_HOST}:443/command-api" |
| 23 |
|
| 24 |
_SESSION_COOKIE = "aabbccdd11223344" |
| 25 |
|
| 26 |
|
| 27 |
@pytest.fixture(name="session_auth") |
| 28 |
def _session_auth_fixture() -> EapiSessionAuth: |
| 29 |
"""Return a fresh EapiSessionAuth with known credentials.""" |
| 30 |
return EapiSessionAuth(host=_HOST, username=_USERNAME, password=_PASSWORD, login_url=_LOGIN_URL) |
| 31 |
|
| 32 |
|
| 33 |
def test_eapi_session_auth_initial_state(session_auth: EapiSessionAuth) -> None: |
| 34 |
"""Test that fresh EapiSessionAuth starts logged out with no cookie.""" |
| 35 |
assert session_auth.logged_in is False |
| 36 |
assert session_auth.session_cookie is None |
| 37 |
|
| 38 |
|
| 39 |
def test_eapi_session_auth_repr_masks_credentials(session_auth: EapiSessionAuth) -> None: |
| 40 |
"""Test that repr includes the host but masks username and password.""" |
| 41 |
auth_repr = repr(session_auth) |
| 42 |
assert _HOST in auth_repr |
| 43 |
assert _USERNAME not in auth_repr |
| 44 |
assert _PASSWORD not in auth_repr |
| 45 |
|
| 46 |
|
| 47 |
def test_eapi_session_auth_sync_auth_flow_raises(session_auth: EapiSessionAuth) -> None: |
| 48 |
"""Test that sync_auth_flow raises EapiAsyncOnlyError.""" |
| 49 |
with pytest.raises(EapiAsyncOnlyError): |
| 50 |
session_auth.sync_auth_flow(httpx.Request("POST", _COMMAND_URL)) |
| 51 |
|
| 52 |
|
| 53 |
async def test_eapi_session_auth_reset_clears_state(session_auth: EapiSessionAuth) -> None: |
| 54 |
"""Test that reset() clears logged_in and session_cookie.""" |
| 55 |
session_auth.session_cookie = _SESSION_COOKIE |
| 56 |
await session_auth.reset() |
| 57 |
assert session_auth.logged_in is False |
| 58 |
assert session_auth.session_cookie is None |
| 59 |
|
| 60 |
|
| 61 |
async def test_eapi_session_auth_reset_serialized_with_login(session_auth: EapiSessionAuth) -> None: |
| 62 |
"""Test that reset() waits for an in-progress login to finish before clearing state.""" |
| 63 |
gen = session_auth.async_auth_flow(request=httpx.Request("POST", _COMMAND_URL)) |
| 64 |
login_req = await anext(gen) |
| 65 |
|
| 66 |
reset_task = asyncio.create_task(session_auth.reset()) |
| 67 |
await asyncio.sleep(0) ck |
| 68 |
|
| 69 |
login_response = httpx.Response(200, headers={"Set-Cookie": f"Session={_SESSION_COOKIE}; Path=/"}, request=login_req) |
| 70 |
await gen.asend(login_response) |
| 71 |
await reset_task |
| 72 |
|
| 73 |
assert session_auth.logged_in is False |
| 74 |
assert session_auth.session_cookie is None |
| 75 |
await gen.aclose() |
| 76 |
|
| 77 |
|
| 78 |
async def test_auth_flow_login_success(session_auth: EapiSessionAuth) -> None: |
| 79 |
"""Test that a successful login routes through /login, attaches the cookie on the command request, and updates internal state.""" |
| 80 |
gen = session_auth.async_auth_flow(request=httpx.Request("POST", _COMMAND_URL)) |
| 81 |
|
| 82 |
login_req = await anext(gen) |
| 83 |
assert login_req.url.path == "/login" |
| 84 |
|
| 85 |
login_response = httpx.Response(200, headers={"Set-Cookie": f"Session={_SESSION_COOKIE}; Path=/"}, request=login_req) |
| 86 |
cmd_req = await gen.asend(login_response) |
| 87 |
assert cmd_req.url.path == "/command-api" |
| 88 |
assert cmd_req.headers.get("Cookie") == f"Session={_SESSION_COOKIE}" |
| 89 |
assert session_auth.logged_in is True |
| 90 |
assert session_auth.session_cookie == _SESSION_COOKIE |
| 91 |
await gen.aclose() |
| 92 |
|
| 93 |
|
| 94 |
async def test_auth_flow_login_success_logs_cookie_fingerprint(session_auth: EapiSessionAuth, caplog: pytest.LogCaptureFixture) -> None: |
| 95 |
"""Test that a successful login logs the cookie fingerprint.""" |
| 96 |
caplog.set_level(logging.DEBUG, logger="asynceapi._auth") |
| 97 |
gen = session_auth.async_auth_flow(request=httpx.Request("POST", _COMMAND_URL)) |
| 98 |
|
| 99 |
login_req = await anext(gen) |
| 100 |
await gen.asend(httpx.Response(200, headers={"Set-Cookie": f"Session={_SESSION_COOKIE}; Path=/"}, request=login_req)) |
| 101 |
|
| 102 |
assert _cookie_fingerprint(_SESSION_COOKIE) in caplog.text |
| 103 |
await gen.aclose() |
| 104 |
|
| 105 |
|
| 106 |
async def test_auth_flow_skips_login_when_already_logged_in(session_auth: EapiSessionAuth) -> None: |
| 107 |
"""Test that an already-logged-in session skips login and attaches the cookie directly.""" |
| 108 |
session_auth.session_cookie = _SESSION_COOKIE |
| 109 |
|
| 110 |
gen = session_auth.async_auth_flow(request=httpx.Request("POST", _COMMAND_URL)) |
| 111 |
cmd_req = await anext(gen) |
| 112 |
assert cmd_req.url.path == "/command-api" |
| 113 |
assert cmd_req.headers.get("Cookie") == f"Session={_SESSION_COOKIE}" |
| 114 |
|
| 115 |
with pytest.raises(StopAsyncIteration): |
| 116 |
await gen.asend(httpx.Response(200, request=cmd_req)) |
| 117 |
|
| 118 |
|
| 119 |
async def test_auth_flow_waiting_request_skips_login_after_concurrent_login(session_auth: EapiSessionAuth) -> None: |
| 120 |
"""Test that a request waiting on login skips its own login after the first login completes.""" |
| 121 |
first_gen = session_auth.async_auth_flow(request=httpx.Request("POST", _COMMAND_URL)) |
| 122 |
|
| 123 |
first_login_req = await anext(first_gen) |
| 124 |
assert first_login_req.url.path == "/login" |
| 125 |
|
| 126 |
second_gen = session_auth.async_auth_flow(request=httpx.Request("POST", _COMMAND_URL)) |
| 127 |
|
| 128 |
second_request_task = asyncio.create_task(anext(second_gen)) |
| 129 |
await asyncio.sleep(0) |
| 130 |
|
| 131 |
|
| 132 |
first_cmd_req = await first_gen.asend(httpx.Response(200, headers={"Set-Cookie": f"Session={_SESSION_COOKIE}; Path=/"}, request=first_login_req)) |
| 133 |
second_cmd_req = await second_request_task |
| 134 |
|
| 135 |
assert first_cmd_req.url.path == "/command-api" |
| 136 |
assert second_cmd_req.url.path == "/command-api" |
| 137 |
assert first_cmd_req.headers.get("Cookie") == f"Session={_SESSION_COOKIE}" |
| 138 |
assert second_cmd_req.headers.get("Cookie") == f"Session={_SESSION_COOKIE}" |
| 139 |
|
| 140 |
await first_gen.aclose() |
| 141 |
await second_gen.aclose() |
| 142 |
|
| 143 |
|
| 144 |
async def test_auth_flow_waiting_request_logs_existing_cookie_fingerprint(session_auth: EapiSessionAuth, caplog: pytest.LogCaptureFixture) -> None: |
| 145 |
"""Test that a request waiting on another login logs the existing cookie fingerprint.""" |
| 146 |
caplog.set_level(logging.DEBUG, logger="asynceapi._auth") |
| 147 |
first_gen = session_auth.async_auth_flow(request=httpx.Request("POST", _COMMAND_URL)) |
| 148 |
first_login_req = await anext(first_gen) |
| 149 |
|
| 150 |
second_gen = session_auth.async_auth_flow(request=httpx.Request("POST", _COMMAND_URL)) |
| 151 |
second_request_task = asyncio.create_task(anext(second_gen)) |
| 152 |
await asyncio.sleep(0) |
| 153 |
|
| 154 |
await first_gen.asend(httpx.Response(200, headers={"Set-Cookie": f"Session={_SESSION_COOKIE}; Path=/"}, request=first_login_req)) |
| 155 |
await second_request_task |
| 156 |
|
| 157 |
assert _cookie_fingerprint(_SESSION_COOKIE) in caplog.text |
| 158 |
await first_gen.aclose() |
| 159 |
await second_gen.aclose() |
| 160 |
|
| 161 |
|
| 162 |
@pytest.mark.parametrize( |
| 163 |
("status_code", "expected_exc"), |
| 164 |
[ |
| 165 |
(401, EapiAuthenticationError), |
| 166 |
(500, httpx.HTTPStatusError), |
| 167 |
(200, RuntimeError), |
| 168 |
], |
| 169 |
ids=["401_auth_error", "500_http_error", "200_no_cookie"], |
| 170 |
) |
| 171 |
async def test_auth_flow_login_failure_raises( |
| 172 |
session_auth: EapiSessionAuth, |
| 173 |
status_code: int, |
| 174 |
expected_exc: type[Exception], |
| 175 |
) -> None: |
| 176 |
"""Test that a failed login raises the correct exception and leaves state clean.""" |
| 177 |
gen = session_auth.async_auth_flow(request=httpx.Request("POST", _COMMAND_URL)) |
| 178 |
login_req = await anext(gen) |
| 179 |
|
| 180 |
with pytest.raises(expected_exc): |
| 181 |
await gen.asend(httpx.Response(status_code, request=login_req)) |
| 182 |
assert session_auth.logged_in is False |
| 183 |
assert session_auth.session_cookie is None |
| 184 |
|
| 185 |
|
| 186 |
async def test_auth_flow_401_clears_matching_cookie(session_auth: EapiSessionAuth) -> None: |
| 187 |
"""Test that a 401 on the command request clears the cookie when it matches the one used.""" |
| 188 |
session_auth.session_cookie = _SESSION_COOKIE |
| 189 |
|
| 190 |
gen = session_auth.async_auth_flow(request=httpx.Request("POST", _COMMAND_URL)) |
| 191 |
cmd_req = await anext(gen) |
| 192 |
|
| 193 |
with pytest.raises(EapiAuthenticationError): |
| 194 |
await gen.asend(httpx.Response(401, request=cmd_req)) |
| 195 |
|
| 196 |
assert session_auth.logged_in is False |
| 197 |
assert session_auth.session_cookie is None |
| 198 |
|
| 199 |
|
| 200 |
async def test_auth_flow_401_preserves_new_cookie(session_auth: EapiSessionAuth) -> None: |
| 201 |
"""Test that a 401 does not clear a cookie that was replaced by a concurrent re-login.""" |
| 202 |
session_auth.session_cookie = _SESSION_COOKIE |
| 203 |
|
| 204 |
gen = session_auth.async_auth_flow(request=httpx.Request("POST", _COMMAND_URL)) |
| 205 |
cmd_req = await anext(gen) |
| 206 |
|
| 207 |
new_cookie = "freshcookie99887766" |
| 208 |
session_auth.session_cookie = new_cookie |
| 209 |
|
| 210 |
with pytest.raises(EapiAuthenticationError): |
| 211 |
await gen.asend(httpx.Response(401, request=cmd_req)) |
| 212 |
|
| 213 |
assert session_auth.session_cookie == new_cookie |
| 214 |
|
| 215 |
|
| 216 |
async def test_auth_flow_login_401_includes_response_text(session_auth: EapiSessionAuth) -> None: |
| 217 |
"""Test that a 401 on login includes the response body in the exception.""" |
| 218 |
gen = session_auth.async_auth_flow(request=httpx.Request("POST", _COMMAND_URL)) |
| 219 |
login_req = await anext(gen) |
| 220 |
|
| 221 |
with pytest.raises(EapiAuthenticationError) as exc_info: |
| 222 |
await gen.asend(httpx.Response(401, text="Unauthorized", request=login_req)) |
| 223 |
|
| 224 |
assert exc_info.value.response_text == "Unauthorized" |
| 225 |
|
| 226 |
|
| 227 |
async def test_auth_flow_session_expired_includes_response_text(session_auth: EapiSessionAuth) -> None: |
| 228 |
"""Test that a 401 on the command request includes the response body in the exception.""" |
| 229 |
session_auth.session_cookie = _SESSION_COOKIE |
| 230 |
|
| 231 |
gen = session_auth.async_auth_flow(request=httpx.Request("POST", _COMMAND_URL)) |
| 232 |
cmd_req = await anext(gen) |
| 233 |
|
| 234 |
with pytest.raises(EapiAuthenticationError) as exc_info: |
| 235 |
await gen.asend(httpx.Response(401, text="Session expired", request=cmd_req)) |
| 236 |
|
| 237 |
assert exc_info.value.response_text == "Session expired" |