"""Phase 2 Auth unit tests: opaque cookies, stored hashes, CSRF, Origin, and endpoints.""" from datetime import datetime, timezone, timedelta from unittest.mock import MagicMock from uuid import uuid4 import pytest from argon2 import PasswordHasher from fastapi.testclient import TestClient from app.main import app from app.modules.auth.service import ( AuthService, COOKIE_NAME, UserContext, check_origin, generate_csrf_token, verify_csrf_token, hash_token, ) from app.api.v1.dependencies import get_auth_service class DummyMapping: def __init__(self, data): self._data = data def mappings(self): return self def first(self): return self._data def all(self): return [self._data] if self._data else [] class DummyConn: def __init__(self, query_results=None): self.query_results = query_results or [] self.executed = [] def execute(self, statement, params=None): self.executed.append((str(statement), params)) sql = str(statement).strip() if sql.startswith('SET ') or sql.startswith('SELECT organization_id FROM organization_settings'): return DummyMapping(None) if sql.startswith('SELECT u.id,u.organization_id'): return DummyMapping(getattr(self, '_last', None)) if self.query_results: res = self.query_results.pop(0) self._last = res return DummyMapping(res) return DummyMapping(None) class DummyEngine: def __init__(self, conn): self.conn = conn def begin(self): from contextlib import contextmanager @contextmanager def ctx(): yield self.conn return ctx() def test_csrf_generation_and_verification(): raw_token = "a" * 64 csrf = generate_csrf_token(raw_token) assert csrf and isinstance(csrf, str) assert verify_csrf_token(raw_token, csrf) is True # Tampered csrf assert verify_csrf_token(raw_token, "wrong-csrf-token") is False # Different token assert verify_csrf_token("different-token-1234", csrf) is False def test_check_origin(): # Valid matching origins assert check_origin("https://api.example.com", "api.example.com", ["https://api.example.com"], ["api.example.com"]) is True assert check_origin("http://localhost:8000", "localhost:8000") is True assert check_origin("http://127.0.0.1:8000/docs", "127.0.0.1:8000") is False # Untrusted origin assert check_origin("https://evil.com", "api.example.com") is False assert check_origin("https://api.example.com.evil.com", "api.example.com") is False # Missing origin/referer allowed (same-origin browser GET / native curl) assert check_origin(None, "localhost:8000") is True def test_auth_service_login_and_validation(): user_id = uuid4() org_id = uuid4() hasher = PasswordHasher() hashed_pwd = hasher.hash("secretpass") # Mock user row in DB user_row = { "id": user_id, "organization_id": org_id, "username": "testuser", "password_hash": hashed_pwd, "role": "user", "is_enabled": True, "access_epoch": 1, } conn = DummyConn(query_results=[user_row]) engine = DummyEngine(conn) auth = AuthService(engine, session_ttl=timedelta(hours=1)) # 1. Successful login user_dict, raw_token, csrf, expires = auth.login("testuser", "secretpass") assert user_dict["username"] == "testuser" assert user_dict["role"] == "user" assert len(raw_token) == 64 assert verify_csrf_token(raw_token, csrf) is True # 2. Invalid password conn_bad = DummyConn(query_results=[user_row]) auth_bad = AuthService(DummyEngine(conn_bad)) with pytest.raises(ValueError, match="INVALID_CREDENTIALS"): auth_bad.login("testuser", "wrongpassword") # 3. Disabled account disabled_row = dict(user_row, is_enabled=False) conn_dis = DummyConn(query_results=[disabled_row]) auth_dis = AuthService(DummyEngine(conn_dis)) with pytest.raises(ValueError, match="ACCOUNT_DISABLED"): auth_dis.login("testuser", "secretpass") # 4. Unknown user conn_none = DummyConn(query_results=[None]) auth_none = AuthService(DummyEngine(conn_none)) with pytest.raises(ValueError, match="INVALID_CREDENTIALS"): auth_none.login("nobody", "secretpass") def test_auth_service_session_verification(): user_id = uuid4() org_id = uuid4() session_id = uuid4() now = datetime.now(timezone.utc) # Active session row session_row = { "id": session_id, "user_id": user_id, "organization_id": org_id, "username": "alice", "role": "admin", "is_enabled": True, "access_epoch": 2, "expires_at": now + timedelta(hours=2), "revoked_at": None, } conn = DummyConn(query_results=[session_row]) auth = AuthService(DummyEngine(conn)) raw_token = "b" * 64 user_ctx = auth.get_current_user(raw_token) assert user_ctx.id == user_id assert user_ctx.username == "alice" assert user_ctx.role == "admin" assert user_ctx.access_epoch == 2 assert user_ctx.auth_session_id == session_id # Expired session expired_row = dict(session_row, expires_at=now - timedelta(seconds=1)) conn_exp = DummyConn(query_results=[expired_row]) auth_exp = AuthService(DummyEngine(conn_exp)) with pytest.raises(ValueError, match="SESSION_EXPIRED"): auth_exp.get_current_user(raw_token) # Revoked session revoked_row = dict(session_row, revoked_at=now - timedelta(seconds=1)) conn_rev = DummyConn(query_results=[revoked_row]) auth_rev = AuthService(DummyEngine(conn_rev)) with pytest.raises(ValueError, match="SESSION_REVOKED"): auth_rev.get_current_user(raw_token) @pytest.mark.parametrize('token', [None,'','é'*64,'a'*65,'a'*63,'G'*64,'\ud800'*64]) def test_malformed_session_and_csrf_rejected(token): assert not verify_csrf_token(token,'b'*64) assert not verify_csrf_token('b'*64,token) with pytest.raises(ValueError,match='AUTH_REQUIRED'): hash_token(token) @pytest.mark.parametrize('origin,host', [('http://evil:8000','localhost:8000'),('http://localhost:9999','localhost:8000'),('http://localhost:8000','evil'),('http://localhost:bad','localhost:8000'),('http://localhost:8000/','localhost:8000'),(None,'evil')]) def test_exact_origin_and_host(origin,host): assert not check_origin(origin,host)