import pytest from fastapi.testclient import TestClient from starlette.websockets import WebSocketDisconnect from app.api import ws as ws_module from app.models import Role from tests.conftest import PASSWORD, login ORIGIN = {"Origin": "https://testserver"} def connect(c: TestClient, headers=ORIGIN): # TestClient always uses ws:// and therefore drops Secure cookies; browsers use wss:// cookie = "; ".join(f"{name}={value}" for name, value in c.cookies.items()) return c.websocket_connect("/api/ws", headers={**headers, "Cookie": cookie}) def expect_close(c: TestClient, code: int, headers=ORIGIN) -> None: with pytest.raises(WebSocketDisconnect) as exc, connect(c, headers) as ws: ws.receive_json() ws.receive_json() assert exc.value.code == code @pytest.fixture def anna(client, make_user): make_user("anna") login(client, "anna") return client @pytest.fixture def second_client(client): def _make(username: str, password: str = PASSWORD) -> TestClient: other = TestClient(client.app, base_url="https://testserver") login(other, username, password) return other return _make # --- Handshake ------------------------------------------------------------------ def test_connect_with_session(anna): with connect(anna) as ws: assert ws.receive_json() == {"type": "hello"} def test_connect_without_session_is_closed_4401(client): expect_close(client, 4401) def test_foreign_origin_is_rejected(anna): expect_close(anna, 4403, {"Origin": "https://evil.example"}) def test_missing_origin_is_rejected(anna): expect_close(anna, 4403, {}) def test_connection_limit(anna, monkeypatch): monkeypatch.setattr(ws_module, "MAX_CONNECTIONS_PER_USER", 2) with connect(anna) as ws1, connect(anna) as ws2: ws1.receive_json() ws2.receive_json() expect_close(anna, 4429) # --- Clip events ---------------------------------------------------------------- def test_clip_events_reach_all_devices_of_user(anna, second_client): phone = second_client("anna") with connect(anna) as laptop_ws, connect(phone) as phone_ws: laptop_ws.receive_json() phone_ws.receive_json() clip = phone.post("/api/clips", json={"content": "from phone"}).json() for ws in (laptop_ws, phone_ws): event = ws.receive_json() assert event["type"] == "clip.created" assert event["data"]["id"] == clip["id"] assert event["data"]["content"] == "from phone" phone.patch(f"/api/clips/{clip['id']}", json={"content": "edited"}) event = laptop_ws.receive_json() assert event["type"] == "clip.updated" assert event["data"]["content"] == "edited" assert event["data"]["version"] == 2 phone_ws.receive_json() phone.delete(f"/api/clips/{clip['id']}") assert laptop_ws.receive_json() == {"type": "clip.deleted", "data": {"id": clip["id"]}} def test_no_event_on_conflict(anna): clip = anna.post("/api/clips", json={"content": "x"}).json() with connect(anna) as ws: ws.receive_json() assert ( anna.patch(f"/api/clips/{clip['id']}", json={"content": "y", "version": 99}).status_code == 409 ) anna.post("/api/clips", json={"content": "marker"}) # The next event is the marker, so the conflict produced none assert ws.receive_json()["data"]["content"] == "marker" def test_events_are_not_sent_to_other_users(anna, make_user, second_client): make_user("bert") bert = second_client("bert") with connect(bert) as bert_ws: bert_ws.receive_json() anna.post("/api/clips", json={"content": "anna's secret"}) bert.post("/api/clips", json={"content": "marker"}) event = bert_ws.receive_json() assert event["data"]["content"] == "marker" # --- Session end closes sockets ------------------------------------------------- def test_logout_closes_socket(anna): with pytest.raises(WebSocketDisconnect) as exc, connect(anna) as ws: ws.receive_json() anna.post("/api/auth/logout") ws.receive_json() assert exc.value.code == 4401 def test_revoking_session_closes_its_socket_only(anna, second_client): phone = second_client("anna") sessions = anna.get("/api/auth/sessions").json() phone_session = next(s for s in sessions if not s["current"]) with connect(anna) as laptop_ws: laptop_ws.receive_json() with pytest.raises(WebSocketDisconnect) as exc, connect(phone) as phone_ws: phone_ws.receive_json() anna.delete(f"/api/auth/sessions/{phone_session['id']}") phone_ws.receive_json() assert exc.value.code == 4401 anna.post("/api/clips", json={"content": "still live"}) assert laptop_ws.receive_json()["type"] == "clip.created" def test_revoke_other_sessions_closes_their_sockets(anna, second_client): phone = second_client("anna") with connect(anna) as laptop_ws: laptop_ws.receive_json() with pytest.raises(WebSocketDisconnect), connect(phone) as phone_ws: phone_ws.receive_json() anna.delete("/api/auth/sessions") phone_ws.receive_json() anna.post("/api/clips", json={"content": "still live"}) assert laptop_ws.receive_json()["type"] == "clip.created" def test_password_change_closes_other_sockets(anna, second_client): phone = second_client("anna") with pytest.raises(WebSocketDisconnect) as exc, connect(phone) as phone_ws: phone_ws.receive_json() anna.post( "/api/auth/password", json={"current_password": PASSWORD, "new_password": "brand new password"}, ) phone_ws.receive_json() assert exc.value.code == 4401 @pytest.mark.parametrize( ("method", "body"), [("patch", {"is_active": False}), ("patch", {"password": "reset by admin!"}), ("delete", None)], ) def test_admin_actions_close_user_sockets(client, make_user, second_client, method, body): make_user("boss", Role.ADMIN) anna_id = make_user("anna").id login(client, "boss") anna = second_client("anna") with pytest.raises(WebSocketDisconnect) as exc, connect(anna) as ws: ws.receive_json() if method == "patch": client.patch(f"/api/admin/users/{anna_id}", json=body) else: client.delete(f"/api/admin/users/{anna_id}") ws.receive_json() assert exc.value.code == 4401 def test_heartbeat_and_revalidation(anna, db, monkeypatch): from app.models import UserSession monkeypatch.setattr(ws_module, "PING_INTERVAL_SECONDS", 0.05) monkeypatch.setattr(ws_module, "REVALIDATE_INTERVAL_SECONDS", 0) with pytest.raises(WebSocketDisconnect) as exc, connect(anna) as ws: assert ws.receive_json() == {"type": "hello"} assert ws.receive_json() == {"type": "ping"} # Session disappears behind the socket's back (e.g. CLI password reset) db.query(UserSession).delete() db.commit() while True: assert ws.receive_json() == {"type": "ping"} assert exc.value.code == 4401