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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Comprehensive Tests for Auth Router
|
| 3 |
+
|
| 4 |
+
Tests cover:
|
| 5 |
+
1. POST /auth/check-registration endpoint
|
| 6 |
+
2. POST /auth/google endpoint (Google Sign-In)
|
| 7 |
+
3. GET /auth/me endpoint (Get current user info)
|
| 8 |
+
4. POST /auth/refresh endpoint (Token refresh)
|
| 9 |
+
5. POST /auth/logout endpoint (User logout)
|
| 10 |
+
|
| 11 |
+
Uses mocked Google Auth service and database.
|
| 12 |
+
"""
|
| 13 |
+
import pytest
|
| 14 |
+
from datetime import datetime
|
| 15 |
+
from unittest.mock import patch, MagicMock, AsyncMock
|
| 16 |
+
from fastapi.testclient import TestClient
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
# ============================================================================
|
| 20 |
+
# 1. POST /auth/check-registration Tests
|
| 21 |
+
# ============================================================================
|
| 22 |
+
|
| 23 |
+
class TestCheckRegistration:
|
| 24 |
+
"""Test POST /auth/check-registration endpoint."""
|
| 25 |
+
|
| 26 |
+
def test_check_registration_not_registered(self):
|
| 27 |
+
"""Unregistered temp user returns is_registered=False."""
|
| 28 |
+
from routers.auth import router
|
| 29 |
+
from fastapi import FastAPI
|
| 30 |
+
from core.database import get_db
|
| 31 |
+
|
| 32 |
+
app = FastAPI()
|
| 33 |
+
|
| 34 |
+
async def mock_get_db():
|
| 35 |
+
mock_db = AsyncMock()
|
| 36 |
+
mock_result = MagicMock()
|
| 37 |
+
mock_result.scalar_one_or_none.return_value = None # No ClientUser found
|
| 38 |
+
mock_db.execute.return_value = mock_result
|
| 39 |
+
yield mock_db
|
| 40 |
+
|
| 41 |
+
app.dependency_overrides[get_db] = mock_get_db
|
| 42 |
+
app.include_router(router)
|
| 43 |
+
client = TestClient(app)
|
| 44 |
+
|
| 45 |
+
with patch('routers.auth.check_rate_limit', return_value=True):
|
| 46 |
+
response = client.post(
|
| 47 |
+
"/auth/check-registration",
|
| 48 |
+
json={"user_id": "temp_user_123"}
|
| 49 |
+
)
|
| 50 |
+
|
| 51 |
+
assert response.status_code == 200
|
| 52 |
+
assert response.json()["is_registered"] == False
|
| 53 |
+
|
| 54 |
+
def test_check_registration_is_registered(self):
|
| 55 |
+
"""Registered temp user returns is_registered=True."""
|
| 56 |
+
from routers.auth import router
|
| 57 |
+
from fastapi import FastAPI
|
| 58 |
+
from core.database import get_db
|
| 59 |
+
|
| 60 |
+
app = FastAPI()
|
| 61 |
+
|
| 62 |
+
async def mock_get_db():
|
| 63 |
+
mock_db = AsyncMock()
|
| 64 |
+
mock_result = MagicMock()
|
| 65 |
+
# Mock ClientUser exists
|
| 66 |
+
mock_client_user = MagicMock()
|
| 67 |
+
mock_result.scalar_one_or_none.return_value = mock_client_user
|
| 68 |
+
mock_db.execute.return_value = mock_result
|
| 69 |
+
yield mock_db
|
| 70 |
+
|
| 71 |
+
app.dependency_overrides[get_db] = mock_get_db
|
| 72 |
+
app.include_router(router)
|
| 73 |
+
client = TestClient(app)
|
| 74 |
+
|
| 75 |
+
with patch('routers.auth.check_rate_limit', return_value=True):
|
| 76 |
+
response = client.post(
|
| 77 |
+
"/auth/check-registration",
|
| 78 |
+
json={"user_id": "temp_user_123"}
|
| 79 |
+
)
|
| 80 |
+
|
| 81 |
+
assert response.status_code == 200
|
| 82 |
+
assert response.json()["is_registered"] == True
|
| 83 |
+
|
| 84 |
+
def test_check_registration_rate_limited(self):
|
| 85 |
+
"""Rate limit blocks excessive requests."""
|
| 86 |
+
from routers.auth import router
|
| 87 |
+
from fastapi import FastAPI
|
| 88 |
+
from core.database import get_db
|
| 89 |
+
|
| 90 |
+
app = FastAPI()
|
| 91 |
+
|
| 92 |
+
async def mock_get_db():
|
| 93 |
+
yield AsyncMock()
|
| 94 |
+
|
| 95 |
+
app.dependency_overrides[get_db] = mock_get_db
|
| 96 |
+
app.include_router(router)
|
| 97 |
+
client = TestClient(app)
|
| 98 |
+
|
| 99 |
+
with patch('routers.auth.check_rate_limit', return_value=False):
|
| 100 |
+
response = client.post(
|
| 101 |
+
"/auth/check-registration",
|
| 102 |
+
json={"user_id": "temp_user_123"}
|
| 103 |
+
)
|
| 104 |
+
|
| 105 |
+
assert response.status_code == 429
|
| 106 |
+
assert "too many" in response.json()["detail"].lower()
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
# ============================================================================
|
| 110 |
+
# 2. POST /auth/google Tests
|
| 111 |
+
# ============================================================================
|
| 112 |
+
|
| 113 |
+
class TestGoogleAuth:
|
| 114 |
+
"""Test POST /auth/google endpoint."""
|
| 115 |
+
|
| 116 |
+
def test_google_auth_new_user(self):
|
| 117 |
+
"""New user sign-in creates user account."""
|
| 118 |
+
from routers.auth import router
|
| 119 |
+
from fastapi import FastAPI
|
| 120 |
+
from core.database import get_db
|
| 121 |
+
from core.models import User
|
| 122 |
+
|
| 123 |
+
app = FastAPI()
|
| 124 |
+
|
| 125 |
+
# Mock Google user info
|
| 126 |
+
mock_google_user = MagicMock()
|
| 127 |
+
mock_google_user.google_id = "123456"
|
| 128 |
+
mock_google_user.email = "newuser@example.com"
|
| 129 |
+
mock_google_user.name = "New User"
|
| 130 |
+
mock_google_user.picture = "https://example.com/pic.jpg"
|
| 131 |
+
|
| 132 |
+
async def mock_get_db():
|
| 133 |
+
mock_db = AsyncMock()
|
| 134 |
+
# First query: user doesn't exist
|
| 135 |
+
mock_result = MagicMock()
|
| 136 |
+
mock_result.scalar_one_or_none.return_value = None
|
| 137 |
+
mock_db.execute.return_value = mock_result
|
| 138 |
+
yield mock_db
|
| 139 |
+
|
| 140 |
+
app.dependency_overrides[get_db] = mock_get_db
|
| 141 |
+
app.include_router(router)
|
| 142 |
+
client = TestClient(app)
|
| 143 |
+
|
| 144 |
+
with patch('routers.auth.get_google_auth_service') as mock_service, \
|
| 145 |
+
patch('routers.auth.check_rate_limit', return_value=True), \
|
| 146 |
+
patch('routers.auth.AuditService.log_event', return_value=AsyncMock()), \
|
| 147 |
+
patch('services.backup_service.get_backup_service'):
|
| 148 |
+
|
| 149 |
+
mock_service.return_value.verify_token.return_value = mock_google_user
|
| 150 |
+
|
| 151 |
+
response = client.post(
|
| 152 |
+
"/auth/google",
|
| 153 |
+
json={"id_token": "fake-google-token"}
|
| 154 |
+
)
|
| 155 |
+
|
| 156 |
+
assert response.status_code == 200
|
| 157 |
+
data = response.json()
|
| 158 |
+
assert data["success"] == True
|
| 159 |
+
assert "access_token" in data
|
| 160 |
+
assert data["email"] == "newuser@example.com"
|
| 161 |
+
assert data["is_new_user"] == True
|
| 162 |
+
|
| 163 |
+
def test_google_auth_existing_user(self):
|
| 164 |
+
"""Existing user sign-in returns user data."""
|
| 165 |
+
from routers.auth import router
|
| 166 |
+
from fastapi import FastAPI
|
| 167 |
+
from core.database import get_db
|
| 168 |
+
from core.models import User
|
| 169 |
+
|
| 170 |
+
app = FastAPI()
|
| 171 |
+
|
| 172 |
+
# Mock existing user
|
| 173 |
+
mock_user = MagicMock(spec=User)
|
| 174 |
+
mock_user.id = 1
|
| 175 |
+
mock_user.user_id = "usr_existing"
|
| 176 |
+
mock_user.email = "existing@example.com"
|
| 177 |
+
mock_user.google_id = "123456"
|
| 178 |
+
mock_user.name = "Existing User"
|
| 179 |
+
mock_user.credits = 100
|
| 180 |
+
mock_user.token_version = 1
|
| 181 |
+
mock_user.profile_picture = "https://example.com/pic.jpg"
|
| 182 |
+
|
| 183 |
+
# Mock Google user info
|
| 184 |
+
mock_google_user = MagicMock()
|
| 185 |
+
mock_google_user.google_id = "123456"
|
| 186 |
+
mock_google_user.email = "existing@example.com"
|
| 187 |
+
mock_google_user.name = "Existing User"
|
| 188 |
+
mock_google_user.picture = "https://example.com/pic.jpg"
|
| 189 |
+
|
| 190 |
+
async def mock_get_db():
|
| 191 |
+
mock_db = AsyncMock()
|
| 192 |
+
mock_result = MagicMock()
|
| 193 |
+
mock_result.scalar_one_or_none.return_value = mock_user
|
| 194 |
+
mock_db.execute.return_value = mock_result
|
| 195 |
+
yield mock_db
|
| 196 |
+
|
| 197 |
+
app.dependency_overrides[get_db] = mock_get_db
|
| 198 |
+
app.include_router(router)
|
| 199 |
+
client = TestClient(app)
|
| 200 |
+
|
| 201 |
+
with patch('routers.auth.get_google_auth_service') as mock_service, \
|
| 202 |
+
patch('routers.auth.check_rate_limit', return_value=True), \
|
| 203 |
+
patch('routers.auth.AuditService.log_event', return_value=AsyncMock()), \
|
| 204 |
+
patch('services.backup_service.get_backup_service'):
|
| 205 |
+
|
| 206 |
+
mock_service.return_value.verify_token.return_value = mock_google_user
|
| 207 |
+
|
| 208 |
+
response = client.post(
|
| 209 |
+
"/auth/google",
|
| 210 |
+
json={"id_token": "fake-google-token"}
|
| 211 |
+
)
|
| 212 |
+
|
| 213 |
+
assert response.status_code == 200
|
| 214 |
+
data = response.json()
|
| 215 |
+
assert data["success"] == True
|
| 216 |
+
assert data["user_id"] == "usr_existing"
|
| 217 |
+
assert data["is_new_user"] == False
|
| 218 |
+
assert data["credits"] == 100
|
| 219 |
+
|
| 220 |
+
def test_google_auth_web_client_cookie(self):
|
| 221 |
+
"""Web client receives refresh token as HttpOnly cookie."""
|
| 222 |
+
from routers.auth import router
|
| 223 |
+
from fastapi import FastAPI
|
| 224 |
+
from core.database import get_db
|
| 225 |
+
from core.models import User
|
| 226 |
+
|
| 227 |
+
app = FastAPI()
|
| 228 |
+
|
| 229 |
+
mock_user = MagicMock(spec=User)
|
| 230 |
+
mock_user.id = 1
|
| 231 |
+
mock_user.user_id = "usr_web"
|
| 232 |
+
mock_user.email = "web@example.com"
|
| 233 |
+
mock_user.name = "Web User"
|
| 234 |
+
mock_user.credits = 50
|
| 235 |
+
mock_user.token_version = 1
|
| 236 |
+
|
| 237 |
+
mock_google_user = MagicMock()
|
| 238 |
+
mock_google_user.google_id = "web123"
|
| 239 |
+
mock_google_user.email = "web@example.com"
|
| 240 |
+
mock_google_user.name = "Web User"
|
| 241 |
+
|
| 242 |
+
async def mock_get_db():
|
| 243 |
+
mock_db = AsyncMock()
|
| 244 |
+
mock_result = MagicMock()
|
| 245 |
+
mock_result.scalar_one_or_none.return_value = mock_user
|
| 246 |
+
mock_db.execute.return_value = mock_result
|
| 247 |
+
yield mock_db
|
| 248 |
+
|
| 249 |
+
app.dependency_overrides[get_db] = mock_get_db
|
| 250 |
+
app.include_router(router)
|
| 251 |
+
client = TestClient(app)
|
| 252 |
+
|
| 253 |
+
with patch('routers.auth.get_google_auth_service') as mock_service, \
|
| 254 |
+
patch('routers.auth.check_rate_limit', return_value=True), \
|
| 255 |
+
patch('routers.auth.AuditService.log_event', return_value=AsyncMock()), \
|
| 256 |
+
patch('services.backup_service.get_backup_service'), \
|
| 257 |
+
patch('routers.auth.detect_client_type', return_value="web"):
|
| 258 |
+
|
| 259 |
+
mock_service.return_value.verify_token.return_value = mock_google_user
|
| 260 |
+
|
| 261 |
+
response = client.post(
|
| 262 |
+
"/auth/google",
|
| 263 |
+
json={"id_token": "fake-google-token"},
|
| 264 |
+
headers={"User-Agent": "Mozilla/5.0"}
|
| 265 |
+
)
|
| 266 |
+
|
| 267 |
+
assert response.status_code == 200
|
| 268 |
+
# Check cookie was set
|
| 269 |
+
assert "refresh_token" in response.cookies
|
| 270 |
+
# Refresh token should NOT be in JSON body for web
|
| 271 |
+
data = response.json()
|
| 272 |
+
assert "refresh_token" not in data
|
| 273 |
+
|
| 274 |
+
def test_google_auth_mobile_client_json(self):
|
| 275 |
+
"""Mobile client receives refresh token in JSON body."""
|
| 276 |
+
from routers.auth import router
|
| 277 |
+
from fastapi import FastAPI
|
| 278 |
+
from core.database import get_db
|
| 279 |
+
from core.models import User
|
| 280 |
+
|
| 281 |
+
app = FastAPI()
|
| 282 |
+
|
| 283 |
+
mock_user = MagicMock(spec=User)
|
| 284 |
+
mock_user.id = 1
|
| 285 |
+
mock_user.user_id = "usr_mobile"
|
| 286 |
+
mock_user.email = "mobile@example.com"
|
| 287 |
+
mock_user.name = "Mobile User"
|
| 288 |
+
mock_user.credits = 50
|
| 289 |
+
mock_user.token_version = 1
|
| 290 |
+
|
| 291 |
+
mock_google_user = MagicMock()
|
| 292 |
+
mock_google_user.google_id = "mobile123"
|
| 293 |
+
mock_google_user.email = "mobile@example.com"
|
| 294 |
+
mock_google_user.name = "Mobile User"
|
| 295 |
+
|
| 296 |
+
async def mock_get_db():
|
| 297 |
+
mock_db = AsyncMock()
|
| 298 |
+
mock_result = MagicMock()
|
| 299 |
+
mock_result.scalar_one_or_none.return_value = mock_user
|
| 300 |
+
mock_db.execute.return_value = mock_result
|
| 301 |
+
yield mock_db
|
| 302 |
+
|
| 303 |
+
app.dependency_overrides[get_db] = mock_get_db
|
| 304 |
+
app.include_router(router)
|
| 305 |
+
client = TestClient(app)
|
| 306 |
+
|
| 307 |
+
with patch('routers.auth.get_google_auth_service') as mock_service, \
|
| 308 |
+
patch('routers.auth.check_rate_limit', return_value=True), \
|
| 309 |
+
patch('routers.auth.AuditService.log_event', return_value=AsyncMock()), \
|
| 310 |
+
patch('services.backup_service.get_backup_service'), \
|
| 311 |
+
patch('routers.auth.detect_client_type', return_value="mobile"):
|
| 312 |
+
|
| 313 |
+
mock_service.return_value.verify_token.return_value = mock_google_user
|
| 314 |
+
|
| 315 |
+
response = client.post(
|
| 316 |
+
"/auth/google",
|
| 317 |
+
json={"id_token": "fake-google-token"},
|
| 318 |
+
headers={"User-Agent": "MyApp/1.0"}
|
| 319 |
+
)
|
| 320 |
+
|
| 321 |
+
assert response.status_code == 200
|
| 322 |
+
data = response.json()
|
| 323 |
+
# Refresh token SHOULD be in JSON body for mobile
|
| 324 |
+
assert "refresh_token" in data
|
| 325 |
+
|
| 326 |
+
def test_google_auth_invalid_token(self):
|
| 327 |
+
"""Invalid Google token returns 401."""
|
| 328 |
+
from routers.auth import router
|
| 329 |
+
from fastapi import FastAPI
|
| 330 |
+
from core.database import get_db
|
| 331 |
+
from services.auth_service.google_provider import InvalidTokenError
|
| 332 |
+
|
| 333 |
+
app = FastAPI()
|
| 334 |
+
|
| 335 |
+
async def mock_get_db():
|
| 336 |
+
yield AsyncMock()
|
| 337 |
+
|
| 338 |
+
app.dependency_overrides[get_db] = mock_get_db
|
| 339 |
+
app.include_router(router)
|
| 340 |
+
client = TestClient(app)
|
| 341 |
+
|
| 342 |
+
with patch('routers.auth.get_google_auth_service') as mock_service, \
|
| 343 |
+
patch('routers.auth.check_rate_limit', return_value=True):
|
| 344 |
+
|
| 345 |
+
mock_service.return_value.verify_token.side_effect = InvalidTokenError("Invalid token")
|
| 346 |
+
|
| 347 |
+
response = client.post(
|
| 348 |
+
"/auth/google",
|
| 349 |
+
json={"id_token": "invalid-token"}
|
| 350 |
+
)
|
| 351 |
+
|
| 352 |
+
assert response.status_code == 401
|
| 353 |
+
assert "invalid" in response.json()["detail"].lower()
|
| 354 |
+
|
| 355 |
+
def test_google_auth_rate_limited(self):
|
| 356 |
+
"""Rate limit blocks excessive requests."""
|
| 357 |
+
from routers.auth import router
|
| 358 |
+
from fastapi import FastAPI
|
| 359 |
+
from core.database import get_db
|
| 360 |
+
|
| 361 |
+
app = FastAPI()
|
| 362 |
+
|
| 363 |
+
async def mock_get_db():
|
| 364 |
+
yield AsyncMock()
|
| 365 |
+
|
| 366 |
+
app.dependency_overrides[get_db] = mock_get_db
|
| 367 |
+
app.include_router(router)
|
| 368 |
+
client = TestClient(app)
|
| 369 |
+
|
| 370 |
+
with patch('routers.auth.check_rate_limit', return_value=False):
|
| 371 |
+
response = client.post(
|
| 372 |
+
"/auth/google",
|
| 373 |
+
json={"id_token": "any-token"}
|
| 374 |
+
)
|
| 375 |
+
|
| 376 |
+
assert response.status_code == 429
|
| 377 |
+
|
| 378 |
+
|
| 379 |
+
# ============================================================================
|
| 380 |
+
# 3. GET /auth/me Tests
|
| 381 |
+
# ============================================================================
|
| 382 |
+
|
| 383 |
+
class TestGetCurrentUserInfo:
|
| 384 |
+
"""Test GET /auth/me endpoint."""
|
| 385 |
+
|
| 386 |
+
def test_get_me_requires_auth(self):
|
| 387 |
+
"""GET /me requires authentication."""
|
| 388 |
+
from routers.auth import router
|
| 389 |
+
from fastapi import FastAPI
|
| 390 |
+
|
| 391 |
+
app = FastAPI()
|
| 392 |
+
app.include_router(router)
|
| 393 |
+
client = TestClient(app)
|
| 394 |
+
|
| 395 |
+
response = client.get("/auth/me")
|
| 396 |
+
|
| 397 |
+
# Should fail with auth error
|
| 398 |
+
assert response.status_code in [401, 403, 422]
|
| 399 |
+
|
| 400 |
+
def test_get_me_returns_user_info(self):
|
| 401 |
+
"""GET /me returns authenticated user info."""
|
| 402 |
+
from routers.auth import router
|
| 403 |
+
from fastapi import FastAPI
|
| 404 |
+
from dependencies import get_current_user
|
| 405 |
+
from core.models import User
|
| 406 |
+
|
| 407 |
+
app = FastAPI()
|
| 408 |
+
|
| 409 |
+
# Mock authenticated user
|
| 410 |
+
mock_user = MagicMock(spec=User)
|
| 411 |
+
mock_user.user_id = "usr_123"
|
| 412 |
+
mock_user.email = "user@example.com"
|
| 413 |
+
mock_user.name = "Test User"
|
| 414 |
+
mock_user.credits = 75
|
| 415 |
+
mock_user.profile_picture = "https://example.com/pic.jpg"
|
| 416 |
+
|
| 417 |
+
app.dependency_overrides[get_current_user] = lambda: mock_user
|
| 418 |
+
app.include_router(router)
|
| 419 |
+
client = TestClient(app)
|
| 420 |
+
|
| 421 |
+
response = client.get("/auth/me")
|
| 422 |
+
|
| 423 |
+
assert response.status_code == 200
|
| 424 |
+
data = response.json()
|
| 425 |
+
assert data["user_id"] == "usr_123"
|
| 426 |
+
assert data["email"] == "user@example.com"
|
| 427 |
+
assert data["name"] == "Test User"
|
| 428 |
+
assert data["credits"] == 75
|
| 429 |
+
|
| 430 |
+
|
| 431 |
+
# ============================================================================
|
| 432 |
+
# 4. POST /auth/refresh Tests
|
| 433 |
+
# ============================================================================
|
| 434 |
+
|
| 435 |
+
class TestTokenRefresh:
|
| 436 |
+
"""Test POST /auth/refresh endpoint."""
|
| 437 |
+
|
| 438 |
+
def test_refresh_with_valid_token_in_body(self):
|
| 439 |
+
"""Refresh with valid token in body returns new tokens."""
|
| 440 |
+
from routers.auth import router
|
| 441 |
+
from fastapi import FastAPI
|
| 442 |
+
from core.database import get_db
|
| 443 |
+
from core.models import User
|
| 444 |
+
from services.auth_service.jwt_provider import create_refresh_token
|
| 445 |
+
|
| 446 |
+
app = FastAPI()
|
| 447 |
+
|
| 448 |
+
# Create a valid refresh token
|
| 449 |
+
refresh_token = create_refresh_token("usr_123", "user@example.com", token_version=1)
|
| 450 |
+
|
| 451 |
+
mock_user = MagicMock(spec=User)
|
| 452 |
+
mock_user.user_id = "usr_123"
|
| 453 |
+
mock_user.email = "user@example.com"
|
| 454 |
+
mock_user.token_version = 1
|
| 455 |
+
|
| 456 |
+
async def mock_get_db():
|
| 457 |
+
mock_db = AsyncMock()
|
| 458 |
+
mock_result = MagicMock()
|
| 459 |
+
mock_result.scalar_one_or_none.return_value = mock_user
|
| 460 |
+
mock_db.execute.return_value = mock_result
|
| 461 |
+
yield mock_db
|
| 462 |
+
|
| 463 |
+
app.dependency_overrides[get_db] = mock_get_db
|
| 464 |
+
app.include_router(router)
|
| 465 |
+
client = TestClient(app)
|
| 466 |
+
|
| 467 |
+
with patch('routers.auth.check_rate_limit', return_value=True):
|
| 468 |
+
response = client.post(
|
| 469 |
+
"/auth/refresh",
|
| 470 |
+
json={"token": refresh_token}
|
| 471 |
+
)
|
| 472 |
+
|
| 473 |
+
assert response.status_code == 200
|
| 474 |
+
data = response.json()
|
| 475 |
+
assert data["success"] == True
|
| 476 |
+
assert "access_token" in data
|
| 477 |
+
assert "refresh_token" in data # New refresh token (rotation)
|
| 478 |
+
|
| 479 |
+
def test_refresh_with_cookie(self):
|
| 480 |
+
"""Refresh with cookie returns new tokens and rotates cookie."""
|
| 481 |
+
from routers.auth import router
|
| 482 |
+
from fastapi import FastAPI
|
| 483 |
+
from core.database import get_db
|
| 484 |
+
from core.models import User
|
| 485 |
+
from services.auth_service.jwt_provider import create_refresh_token
|
| 486 |
+
|
| 487 |
+
app = FastAPI()
|
| 488 |
+
|
| 489 |
+
refresh_token = create_refresh_token("usr_456", "user2@example.com", token_version=1)
|
| 490 |
+
|
| 491 |
+
mock_user = MagicMock(spec=User)
|
| 492 |
+
mock_user.user_id = "usr_456"
|
| 493 |
+
mock_user.email = "user2@example.com"
|
| 494 |
+
mock_user.token_version = 1
|
| 495 |
+
|
| 496 |
+
async def mock_get_db():
|
| 497 |
+
mock_db = AsyncMock()
|
| 498 |
+
mock_result = MagicMock()
|
| 499 |
+
mock_result.scalar_one_or_none.return_value = mock_user
|
| 500 |
+
mock_db.execute.return_value = mock_result
|
| 501 |
+
yield mock_db
|
| 502 |
+
|
| 503 |
+
app.dependency_overrides[get_db] = mock_get_db
|
| 504 |
+
app.include_router(router)
|
| 505 |
+
client = TestClient(app)
|
| 506 |
+
|
| 507 |
+
with patch('routers.auth.check_rate_limit', return_value=True):
|
| 508 |
+
# Set refresh token in cookie
|
| 509 |
+
client.cookies.set("refresh_token", refresh_token)
|
| 510 |
+
|
| 511 |
+
response = client.post(
|
| 512 |
+
"/auth/refresh",
|
| 513 |
+
json={} # Empty body, token from cookie
|
| 514 |
+
)
|
| 515 |
+
|
| 516 |
+
assert response.status_code == 200
|
| 517 |
+
# Cookie should be rotated
|
| 518 |
+
assert "refresh_token" in response.cookies
|
| 519 |
+
|
| 520 |
+
def test_refresh_missing_token(self):
|
| 521 |
+
"""Refresh without token returns 401."""
|
| 522 |
+
from routers.auth import router
|
| 523 |
+
from fastapi import FastAPI
|
| 524 |
+
from core.database import get_db
|
| 525 |
+
|
| 526 |
+
app = FastAPI()
|
| 527 |
+
|
| 528 |
+
async def mock_get_db():
|
| 529 |
+
yield AsyncMock()
|
| 530 |
+
|
| 531 |
+
app.dependency_overrides[get_db] = mock_get_db
|
| 532 |
+
app.include_router(router)
|
| 533 |
+
client = TestClient(app)
|
| 534 |
+
|
| 535 |
+
with patch('routers.auth.check_rate_limit', return_value=True):
|
| 536 |
+
response = client.post(
|
| 537 |
+
"/auth/refresh",
|
| 538 |
+
json={} # No token
|
| 539 |
+
)
|
| 540 |
+
|
| 541 |
+
assert response.status_code == 401
|
| 542 |
+
assert "missing" in response.json()["detail"].lower()
|
| 543 |
+
|
| 544 |
+
def test_refresh_wrong_token_type(self):
|
| 545 |
+
"""Refresh with access token (not refresh) returns 401."""
|
| 546 |
+
from routers.auth import router
|
| 547 |
+
from fastapi import FastAPI
|
| 548 |
+
from core.database import get_db
|
| 549 |
+
from services.auth_service.jwt_provider import create_access_token
|
| 550 |
+
|
| 551 |
+
app = FastAPI()
|
| 552 |
+
|
| 553 |
+
# Create access token instead of refresh
|
| 554 |
+
access_token = create_access_token("usr_123", "user@example.com")
|
| 555 |
+
|
| 556 |
+
async def mock_get_db():
|
| 557 |
+
yield AsyncMock()
|
| 558 |
+
|
| 559 |
+
app.dependency_overrides[get_db] = mock_get_db
|
| 560 |
+
app.include_router(router)
|
| 561 |
+
client = TestClient(app)
|
| 562 |
+
|
| 563 |
+
with patch('routers.auth.check_rate_limit', return_value=True):
|
| 564 |
+
response = client.post(
|
| 565 |
+
"/auth/refresh",
|
| 566 |
+
json={"token": access_token}
|
| 567 |
+
)
|
| 568 |
+
|
| 569 |
+
assert response.status_code == 401
|
| 570 |
+
assert "invalid token type" in response.json()["detail"].lower()
|
| 571 |
+
|
| 572 |
+
def test_refresh_invalidated_token(self):
|
| 573 |
+
"""Refresh with old token version returns 401."""
|
| 574 |
+
from routers.auth import router
|
| 575 |
+
from fastapi import FastAPI
|
| 576 |
+
from core.database import get_db
|
| 577 |
+
from core.models import User
|
| 578 |
+
from services.auth_service.jwt_provider import create_refresh_token
|
| 579 |
+
|
| 580 |
+
app = FastAPI()
|
| 581 |
+
|
| 582 |
+
# Create token with version 1
|
| 583 |
+
refresh_token = create_refresh_token("usr_123", "user@example.com", token_version=1)
|
| 584 |
+
|
| 585 |
+
# Mock user with version 2 (token was invalidated)
|
| 586 |
+
mock_user = MagicMock(spec=User)
|
| 587 |
+
mock_user.user_id = "usr_123"
|
| 588 |
+
mock_user.token_version = 2 # Higher version
|
| 589 |
+
|
| 590 |
+
async def mock_get_db():
|
| 591 |
+
mock_db = AsyncMock()
|
| 592 |
+
mock_result = MagicMock()
|
| 593 |
+
mock_result.scalar_one_or_none.return_value = mock_user
|
| 594 |
+
mock_db.execute.return_value = mock_result
|
| 595 |
+
yield mock_db
|
| 596 |
+
|
| 597 |
+
app.dependency_overrides[get_db] = mock_get_db
|
| 598 |
+
app.include_router(router)
|
| 599 |
+
client = TestClient(app)
|
| 600 |
+
|
| 601 |
+
with patch('routers.auth.check_rate_limit', return_value=True):
|
| 602 |
+
response = client.post(
|
| 603 |
+
"/auth/refresh",
|
| 604 |
+
json={"token": refresh_token}
|
| 605 |
+
)
|
| 606 |
+
|
| 607 |
+
assert response.status_code == 401
|
| 608 |
+
assert "invalidated" in response.json()["detail"].lower()
|
| 609 |
+
|
| 610 |
+
def test_refresh_rate_limited(self):
|
| 611 |
+
"""Rate limit blocks excessive refresh attempts."""
|
| 612 |
+
from routers.auth import router
|
| 613 |
+
from fastapi import FastAPI
|
| 614 |
+
from core.database import get_db
|
| 615 |
+
|
| 616 |
+
app = FastAPI()
|
| 617 |
+
|
| 618 |
+
async def mock_get_db():
|
| 619 |
+
yield AsyncMock()
|
| 620 |
+
|
| 621 |
+
app.dependency_overrides[get_db] = mock_get_db
|
| 622 |
+
app.include_router(router)
|
| 623 |
+
client = TestClient(app)
|
| 624 |
+
|
| 625 |
+
with patch('routers.auth.check_rate_limit', return_value=False):
|
| 626 |
+
response = client.post(
|
| 627 |
+
"/auth/refresh",
|
| 628 |
+
json={"token": "any-token"}
|
| 629 |
+
)
|
| 630 |
+
|
| 631 |
+
assert response.status_code == 429
|
| 632 |
+
|
| 633 |
+
|
| 634 |
+
# ============================================================================
|
| 635 |
+
# 5. POST /auth/logout Tests
|
| 636 |
+
# ============================================================================
|
| 637 |
+
|
| 638 |
+
class TestLogout:
|
| 639 |
+
"""Test POST /auth/logout endpoint."""
|
| 640 |
+
|
| 641 |
+
def test_logout_requires_auth(self):
|
| 642 |
+
"""Logout requires authentication."""
|
| 643 |
+
from routers.auth import router
|
| 644 |
+
from fastapi import FastAPI
|
| 645 |
+
|
| 646 |
+
app = FastAPI()
|
| 647 |
+
app.include_router(router)
|
| 648 |
+
client = TestClient(app)
|
| 649 |
+
|
| 650 |
+
response = client.post("/auth/logout")
|
| 651 |
+
|
| 652 |
+
assert response.status_code in [401, 403, 422]
|
| 653 |
+
|
| 654 |
+
def test_logout_increments_token_version(self):
|
| 655 |
+
"""Logout increments user's token version."""
|
| 656 |
+
from routers.auth import router
|
| 657 |
+
from fastapi import FastAPI
|
| 658 |
+
from dependencies import get_current_user
|
| 659 |
+
from core.database import get_db
|
| 660 |
+
from core.models import User
|
| 661 |
+
|
| 662 |
+
app = FastAPI()
|
| 663 |
+
|
| 664 |
+
mock_user = MagicMock(spec=User)
|
| 665 |
+
mock_user.id = 1
|
| 666 |
+
mock_user.user_id = "usr_123"
|
| 667 |
+
mock_user.token_version = 1
|
| 668 |
+
|
| 669 |
+
async def mock_get_db():
|
| 670 |
+
mock_db = AsyncMock()
|
| 671 |
+
yield mock_db
|
| 672 |
+
|
| 673 |
+
app.dependency_overrides[get_current_user] = lambda: mock_user
|
| 674 |
+
app.dependency_overrides[get_db] = mock_get_db
|
| 675 |
+
app.include_router(router)
|
| 676 |
+
client = TestClient(app)
|
| 677 |
+
|
| 678 |
+
with patch('routers.auth.AuditService.log_event', return_value=AsyncMock()), \
|
| 679 |
+
patch('services.backup_service.get_backup_service'):
|
| 680 |
+
|
| 681 |
+
response = client.post("/auth/logout")
|
| 682 |
+
|
| 683 |
+
assert response.status_code == 200
|
| 684 |
+
# Token version should be incremented
|
| 685 |
+
assert mock_user.token_version == 2
|
| 686 |
+
|
| 687 |
+
def test_logout_deletes_cookie(self):
|
| 688 |
+
"""Logout deletes refresh token cookie."""
|
| 689 |
+
from routers.auth import router
|
| 690 |
+
from fastapi import FastAPI
|
| 691 |
+
from dependencies import get_current_user
|
| 692 |
+
from core.database import get_db
|
| 693 |
+
from core.models import User
|
| 694 |
+
|
| 695 |
+
app = FastAPI()
|
| 696 |
+
|
| 697 |
+
mock_user = MagicMock(spec=User)
|
| 698 |
+
mock_user.id = 1
|
| 699 |
+
mock_user.user_id = "usr_123"
|
| 700 |
+
mock_user.token_version = 1
|
| 701 |
+
|
| 702 |
+
async def mock_get_db():
|
| 703 |
+
yield AsyncMock()
|
| 704 |
+
|
| 705 |
+
app.dependency_overrides[get_current_user] = lambda: mock_user
|
| 706 |
+
app.dependency_overrides[get_db] = mock_get_db
|
| 707 |
+
app.include_router(router)
|
| 708 |
+
client = TestClient(app)
|
| 709 |
+
|
| 710 |
+
with patch('routers.auth.AuditService.log_event', return_value=AsyncMock()), \
|
| 711 |
+
patch('services.backup_service.get_backup_service'):
|
| 712 |
+
|
| 713 |
+
response = client.post("/auth/logout")
|
| 714 |
+
|
| 715 |
+
assert response.status_code == 200
|
| 716 |
+
data = response.json()
|
| 717 |
+
assert data["success"] == True
|
| 718 |
+
assert "logged out" in data["message"].lower()
|
| 719 |
+
|
| 720 |
+
|
| 721 |
+
# ============================================================================
|
| 722 |
+
# Helper Function Tests
|
| 723 |
+
# ============================================================================
|
| 724 |
+
|
| 725 |
+
class TestHelperFunctions:
|
| 726 |
+
"""Test helper functions in auth router."""
|
| 727 |
+
|
| 728 |
+
def test_detect_client_type_web(self):
|
| 729 |
+
"""detect_client_type identifies web browsers."""
|
| 730 |
+
from routers.auth import detect_client_type
|
| 731 |
+
from fastapi import Request
|
| 732 |
+
|
| 733 |
+
mock_request = MagicMock(spec=Request)
|
| 734 |
+
mock_request.headers.get.return_value = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/91.0"
|
| 735 |
+
|
| 736 |
+
client_type = detect_client_type(mock_request)
|
| 737 |
+
|
| 738 |
+
assert client_type == "web"
|
| 739 |
+
|
| 740 |
+
def test_detect_client_type_mobile(self):
|
| 741 |
+
"""detect_client_type identifies mobile apps."""
|
| 742 |
+
from routers.auth import detect_client_type
|
| 743 |
+
from fastapi import Request
|
| 744 |
+
|
| 745 |
+
mock_request = MagicMock(spec=Request)
|
| 746 |
+
mock_request.headers.get.return_value = "MyApp/1.0 iOS"
|
| 747 |
+
|
| 748 |
+
client_type = detect_client_type(mock_request)
|
| 749 |
+
|
| 750 |
+
assert client_type == "mobile"
|
| 751 |
+
|
| 752 |
+
|
| 753 |
+
if __name__ == "__main__":
|
| 754 |
+
pytest.main([__file__, "-v"])
|