"""A socket whose credential ends is closed: by the route that ended it, or by the sweep when it expired. uv run pytest auth/tests/test_sockets.py -q The door is checked at the handshake only, so before this a signed-out tab, a revoked token or an expired session kept its socket streaming until the tab reconnected. Every socket here is opened on the client the route is called on: a client that is not entered runs its requests on an event loop of their own, and the route's background task could not close a socket living there. """ from __future__ import annotations import asyncio import contextlib import logging import sqlite3 from contextlib import closing from pathlib import Path from typing import Any import pytest from fastapi.testclient import TestClient from starlette.websockets import WebSocketDisconnect import auth.middleware from auth import AuthConfig, close_ended_sockets, sweep_ended_sockets from auth.tests import PASSWORD from auth.tests.harness import build #: The cookie a login over plain http sets. COOKIE = AuthConfig().cookie LONG_AGO = "2000-01-01T00:00:00+00:00" def closed_with(ws: Any) -> int: """Read frames until the server closes the socket; the close code. Blocks on a socket the server left open, since the test client's receive has no timeout, so each test asks the bus first, which does not block.""" for _ in range(50): try: ws.receive_json() except WebSocketDisconnect as closed: return closed.code raise AssertionError("the socket stayed open") def sweep_now(client: TestClient) -> int: """`close_ended_sockets` on the loop the client's sockets live on.""" assert client.portal is not None return client.portal.call(close_ended_sockets, client.app) def expire(client: TestClient, table: str) -> None: with closing(sqlite3.connect(client.app.state.auth.path)) as conn, conn: conn.execute(f"UPDATE {table} SET expires_at=?", (LONG_AGO,)) # --------------------------------------------------------------- the routes def test_signing_out_closes_the_socket_the_session_opened(signed_in: TestClient): with signed_in.websocket_connect("/ws/jobs") as ws: assert ws.receive_json()["type"] == "jobs" assert signed_in.post("/logout").status_code == 200 assert signed_in.app.state.bus.sockets == () assert closed_with(ws) == 1008 def test_revoking_a_token_closes_its_socket(signed_in: TestClient): """The cookie is taken out so the bearer header is what opens the socket; with the cookie in, the session would be what it stands on.""" made = signed_in.post("/api/account/tokens", json={"current": PASSWORD, "label": "cron"}).json() here = signed_in.cookies[COOKIE] signed_in.cookies.clear() with signed_in.websocket_connect( "/ws/jobs", headers={"authorization": f"Bearer {made['token']}"}) as ws: assert ws.receive_json()["type"] == "jobs" signed_in.cookies.set(COOKIE, here) assert signed_in.delete(f"/api/account/tokens/{made['id']}").status_code == 200 assert signed_in.app.state.bus.sockets == () assert closed_with(ws) == 1008 def test_closing_the_others_closes_their_sockets_and_keeps_this_one( signed_in: TestClient): here = signed_in.cookies[COOKIE] there = signed_in.app.state.auth.open_session("phone", 1) def as_(token: str) -> None: signed_in.cookies.clear() signed_in.cookies.set(COOKIE, token) as_(there) with signed_in.websocket_connect("/ws/jobs") as theirs: assert theirs.receive_json()["type"] == "jobs" as_(here) with signed_in.websocket_connect("/ws/jobs") as mine: assert mine.receive_json()["type"] == "jobs" closed = signed_in.post("/api/account/sessions/close") assert closed.json() == {"signed_out": 1} assert len(signed_in.app.state.bus.sockets) == 1, "this tab's is open" assert closed_with(theirs) == 1008 # ---------------------------------------------------------------- expiry def test_an_expired_session_loses_its_socket(signed_in: TestClient): """Expiry ends no request, so no route sees it; the sweep's call does.""" with signed_in.websocket_connect("/ws/jobs") as ws: assert ws.receive_json()["type"] == "jobs" assert sweep_now(signed_in) == 0, "a live session keeps its socket" expire(signed_in, "auth_sessions") assert sweep_now(signed_in) == 1 assert closed_with(ws) == 1008 def test_nothing_is_closed_on_an_unlocked_app_or_one_without_a_bus( open_app: TestClient, signed_in: TestClient): with open_app.websocket_connect("/ws/jobs", headers={"host": "127.0.0.1"}) as ws: assert ws.receive_json()["type"] == "jobs" assert sweep_now(open_app) == 0 del signed_in.app.state.bus expire(signed_in, "auth_sessions") assert sweep_now(signed_in) == 0 def test_the_sweep_runs_on_its_clock_and_survives_a_failure( monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture): calls: list[object] = [] async def counted(app: object) -> int: calls.append(app) if len(calls) == 1: raise sqlite3.OperationalError("database is locked") return 0 monkeypatch.setattr(auth.middleware, "close_ended_sockets", counted) async def run() -> asyncio.Task[None]: task = asyncio.create_task(sweep_ended_sockets("the app", every=0.01)) for _ in range(200): if len(calls) >= 2: break await asyncio.sleep(0.01) task.cancel() with contextlib.suppress(asyncio.CancelledError): await task return task with caplog.at_level(logging.WARNING): task = asyncio.run(run()) assert len(calls) >= 2 and calls[0] == "the app" assert "the socket sweep failed" in caplog.text assert task.cancelled() def test_a_locked_app_sweeps_while_it_is_up(tmp_path: Path): app = build(tmp_path / "a.db", enabled="always") assert app.state.auth_sweep is None with TestClient(app): sweep = app.state.auth_sweep assert isinstance(sweep, asyncio.Task) and not sweep.done() assert sweep.done() and sweep.cancelled() def test_an_unlocked_app_has_no_sweep(open_app: TestClient): assert open_app.app.state.auth_sweep is None