"""Tests for authentication API endpoints.""" import pytest from httpx import ASGITransport, AsyncClient from src.server.fastapi_app import app from src.server.services.auth_service import auth_service @pytest.fixture(autouse=True) def reset_auth_state(): """Reset auth service state before each test.""" # Clear any rate limiting state and password hash # Force clear all keys in _failed dict auth_service._failed.clear() auth_service._hash = None yield # Cleanup after test auth_service._failed.clear() auth_service._hash = None @pytest.mark.asyncio async def test_auth_flow_setup_login_status_logout(): """Test complete authentication flow.""" transport = ASGITransport(app=app) async with AsyncClient( transport=transport, base_url="http://test" ) as client: # Setup r = await client.post( "/api/auth/setup", json={"master_password": "Aa!strong1"} ) assert r.status_code == 201 # Bad login r = await client.post("/api/auth/login", json={"password": "wrong"}) assert r.status_code == 401 # Good login r = await client.post( "/api/auth/login", json={"password": "Aa!strong1"} ) assert r.status_code == 200 data = r.json() assert "access_token" in data token = data["access_token"] # Status unauthenticated when no auth header r = await client.get("/api/auth/status") assert r.status_code == 200 assert r.json()["configured"] is True # Status authenticated with header auth_header = {"Authorization": f"Bearer {token}"} r = await client.get("/api/auth/status", headers=auth_header) assert r.status_code == 200 assert r.json()["authenticated"] is True # Logout r = await client.post( "/api/auth/logout", headers=auth_header ) assert r.status_code == 200