Buckets:
AnonymousSpottedToad/candidate_bucket / codebase /python /SHAdd0WTAka_Zen-Ai-Pentest /tests /unit /test_api_auth.py
| """ | |
| Comprehensive unit tests for api/auth.py | |
| Coverage targets: | |
| - Password hashing and verification (legacy + new auth) | |
| - JWT token creation and decoding (legacy + new auth) | |
| - FastAPI dependency functions (verify_token, get_current_user, require_admin, require_operator) | |
| - Role-based permission checking | |
| - AuthService (authenticate_user, create_user) | |
| - Legacy API key management | |
| - Module-level legacy wrappers | |
| """ | |
| import os | |
| import sys | |
| from datetime import datetime, timedelta, timezone | |
| from unittest.mock import MagicMock, patch | |
| import jwt | |
| import pytest | |
| from fastapi import HTTPException, status | |
| from fastapi.security import HTTPAuthorizationCredentials | |
| # Ensure project root is in path | |
| sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))) | |
| from api import auth as auth_module | |
| # ============================================================================= | |
| # Fixtures | |
| # ============================================================================= | |
| def clear_api_keys(): | |
| """Clear legacy API keys before and after each test.""" | |
| auth_module.API_KEYS.clear() | |
| auth_module._api_key_counter = 0 | |
| yield | |
| auth_module.API_KEYS.clear() | |
| auth_module._api_key_counter = 0 | |
| def reset_singletons(): | |
| """Reset JWT handler and password hasher singletons between tests.""" | |
| auth_module._jwt_handler = None | |
| auth_module._password_hasher = None | |
| yield | |
| auth_module._jwt_handler = None | |
| auth_module._password_hasher = None | |
| def sample_user_data(): | |
| """Sample user payload for legacy token creation.""" | |
| return { | |
| "sub": "testuser", | |
| "username": "testuser", | |
| "role": "admin", | |
| "user_id": 1, | |
| } | |
| def valid_legacy_token(sample_user_data): | |
| """Create a valid legacy JWT token.""" | |
| return auth_module.create_access_token(sample_user_data) | |
| def expired_legacy_token(sample_user_data): | |
| """Create an expired legacy JWT token.""" | |
| return auth_module.create_access_token(sample_user_data, expires_delta=timedelta(minutes=-1)) | |
| def mock_credentials(): | |
| """Create mock HTTPAuthorizationCredentials with a dummy token.""" | |
| return HTTPAuthorizationCredentials(scheme="Bearer", credentials="dummy-token") | |
| # ============================================================================= | |
| # Singleton Getters | |
| # ============================================================================= | |
| class TestSingletonGetters: | |
| """Tests for get_jwt_handler, get_password_hasher, get_auth_service.""" | |
| def test_get_jwt_handler_singleton(self): | |
| """get_jwt_handler should return the same instance on subsequent calls.""" | |
| handler1 = auth_module.get_jwt_handler() | |
| handler2 = auth_module.get_jwt_handler() | |
| assert handler1 is handler2 | |
| assert isinstance(handler1, auth_module.JWTHandler) | |
| def test_get_password_hasher_singleton(self): | |
| """get_password_hasher should return the same instance on subsequent calls.""" | |
| hasher1 = auth_module.get_password_hasher() | |
| hasher2 = auth_module.get_password_hasher() | |
| assert hasher1 is hasher2 | |
| assert isinstance(hasher1, auth_module.PasswordHasher) | |
| def test_get_auth_service_returns_instance(self): | |
| """get_auth_service should return an AuthService instance.""" | |
| svc = auth_module.get_auth_service() | |
| assert isinstance(svc, auth_module.AuthService) | |
| # ============================================================================= | |
| # Password Functions | |
| # ============================================================================= | |
| class TestPrehashPassword: | |
| """Tests for _prehash_password.""" | |
| def test_short_password_returns_encoded_bytes(self): | |
| """Passwords under 72 bytes should be returned as UTF-8 encoded bytes.""" | |
| password = "short" | |
| result = auth_module._prehash_password(password) | |
| assert result == password.encode("utf-8") | |
| def test_long_password_returns_sha256_digest(self): | |
| """Passwords over 72 bytes should be SHA256 digested.""" | |
| password = "a" * 100 | |
| result = auth_module._prehash_password(password) | |
| assert isinstance(result, bytes) | |
| assert len(result) == 32 # SHA256 digest length | |
| class TestPasswordHashAndVerify: | |
| """Tests for get_password_hash and verify_password.""" | |
| def test_get_password_hash_legacy(self): | |
| """get_password_hash should return a bcrypt hash when NEW_AUTH_AVAILABLE is False.""" | |
| with patch.object(auth_module, "NEW_AUTH_AVAILABLE", False): | |
| hashed = auth_module.get_password_hash("my-password") | |
| assert hashed.startswith("$2") | |
| def test_verify_password_legacy_success(self): | |
| """verify_password should return True for matching password (legacy).""" | |
| with patch.object(auth_module, "NEW_AUTH_AVAILABLE", False): | |
| hashed = auth_module.get_password_hash("my-password") | |
| assert auth_module.verify_password("my-password", hashed) is True | |
| def test_verify_password_legacy_failure(self): | |
| """verify_password should return False for non-matching password (legacy).""" | |
| with patch.object(auth_module, "NEW_AUTH_AVAILABLE", False): | |
| hashed = auth_module.get_password_hash("my-password") | |
| assert auth_module.verify_password("wrong-password", hashed) is False | |
| def test_get_password_hash_new_auth(self): | |
| """get_password_hash should delegate to PasswordHasher when NEW_AUTH_AVAILABLE is True.""" | |
| mock_hasher = MagicMock() | |
| mock_hasher.hash.return_value = "mocked-hash" | |
| with patch.object(auth_module, "NEW_AUTH_AVAILABLE", True): | |
| with patch.object(auth_module, "get_password_hasher", return_value=mock_hasher): | |
| result = auth_module.get_password_hash("my-password") | |
| assert result == "mocked-hash" | |
| mock_hasher.hash.assert_called_once_with("my-password") | |
| def test_verify_password_new_auth(self): | |
| """verify_password should delegate to PasswordHasher when NEW_AUTH_AVAILABLE is True.""" | |
| mock_hasher = MagicMock() | |
| mock_hasher.verify.return_value = True | |
| with patch.object(auth_module, "NEW_AUTH_AVAILABLE", True): | |
| with patch.object(auth_module, "get_password_hasher", return_value=mock_hasher): | |
| result = auth_module.verify_password("my-password", "mocked-hash") | |
| assert result is True | |
| mock_hasher.verify.assert_called_once_with("my-password", "mocked-hash") | |
| # ============================================================================= | |
| # JWT Token Functions | |
| # ============================================================================= | |
| class TestCreateAccessToken: | |
| """Tests for create_access_token.""" | |
| def test_legacy_dict_arg(self, sample_user_data): | |
| """create_access_token(data_dict) should return a valid JWT string.""" | |
| token = auth_module.create_access_token(sample_user_data) | |
| payload = jwt.decode(token, auth_module.SECRET_KEY, algorithms=[auth_module.ALGORITHM]) | |
| assert payload["sub"] == "testuser" | |
| assert payload["role"] == "admin" | |
| def test_legacy_kwarg_data(self, sample_user_data): | |
| """create_access_token(data={...}) should return a valid JWT string.""" | |
| token = auth_module.create_access_token(data=sample_user_data) | |
| payload = jwt.decode(token, auth_module.SECRET_KEY, algorithms=[auth_module.ALGORITHM]) | |
| assert payload["sub"] == "testuser" | |
| def test_legacy_with_expires_delta(self, sample_user_data): | |
| """create_access_token with expires_delta should set custom expiration.""" | |
| delta = timedelta(minutes=5) | |
| token = auth_module.create_access_token(sample_user_data, expires_delta=delta) | |
| payload = jwt.decode(token, auth_module.SECRET_KEY, algorithms=[auth_module.ALGORITHM]) | |
| exp = datetime.fromtimestamp(payload["exp"], tz=timezone.utc) | |
| assert (exp - datetime.now(timezone.utc)) <= timedelta(minutes=6) | |
| def test_new_signature_success(self): | |
| """create_access_token(user_id, username, role) should use JWTHandler.""" | |
| mock_handler = MagicMock() | |
| mock_handler.create_access_token.return_value = "new-token" | |
| mock_config = MagicMock() | |
| mock_config.jwt.access_token_expire_minutes = 30 | |
| with patch.object(auth_module, "get_jwt_handler", return_value=mock_handler): | |
| with patch("auth.config.get_config", return_value=mock_config): | |
| token = auth_module.create_access_token(user_id="1", username="test", role="admin") | |
| assert token == "new-token" | |
| mock_handler.create_access_token.assert_called_once() | |
| call_kwargs = mock_handler.create_access_token.call_args.kwargs | |
| assert call_kwargs["user_id"] == "1" | |
| assert call_kwargs["roles"] == ["admin"] | |
| assert call_kwargs["permissions"] == auth_module._get_permissions_for_role("admin") | |
| def test_new_signature_missing_args_raises(self): | |
| """create_access_token without required kwargs should raise ValueError.""" | |
| with pytest.raises(ValueError, match="user_id, username, and role are required"): | |
| auth_module.create_access_token(user_id="1", username="test") | |
| def test_new_signature_with_positional_args(self): | |
| """create_access_token with positional args should work.""" | |
| mock_handler = MagicMock() | |
| mock_handler.create_access_token.return_value = "new-token" | |
| mock_config = MagicMock() | |
| mock_config.jwt.access_token_expire_minutes = 30 | |
| with patch.object(auth_module, "get_jwt_handler", return_value=mock_handler): | |
| with patch("auth.config.get_config", return_value=mock_config): | |
| token = auth_module.create_access_token("1", "test", "admin") | |
| assert token == "new-token" | |
| class TestCreateTokenPair: | |
| """Tests for create_token_pair.""" | |
| def test_create_token_pair(self): | |
| """create_token_pair should delegate to JWTHandler.""" | |
| mock_handler = MagicMock() | |
| mock_handler.create_token_pair.return_value = { | |
| "access_token": "at", | |
| "refresh_token": "rt", | |
| "token_type": "bearer", | |
| "expires_in": 1800, | |
| } | |
| with patch.object(auth_module, "get_jwt_handler", return_value=mock_handler): | |
| result = auth_module.create_token_pair("1", "test", "admin") | |
| assert result["access_token"] == "at" | |
| mock_handler.create_token_pair.assert_called_once() | |
| call_kwargs = mock_handler.create_token_pair.call_args.kwargs | |
| assert call_kwargs["user_id"] == "1" | |
| assert call_kwargs["roles"] == ["admin"] | |
| class TestDecodeToken: | |
| """Tests for decode_token.""" | |
| def test_decode_valid_legacy_token(self, valid_legacy_token, sample_user_data): | |
| """decode_token should return payload for a valid legacy token.""" | |
| payload = auth_module.decode_token(valid_legacy_token) | |
| assert payload is not None | |
| assert payload["sub"] == sample_user_data["sub"] | |
| assert payload["role"] == sample_user_data["role"] | |
| def test_decode_expired_token_returns_none(self, expired_legacy_token): | |
| """decode_token should return None for an expired token.""" | |
| assert auth_module.decode_token(expired_legacy_token) is None | |
| def test_decode_invalid_token_returns_none(self): | |
| """decode_token should return None for an invalid token string.""" | |
| assert auth_module.decode_token("not-a-valid-token") is None | |
| def test_decode_invalid_token_with_new_auth_available(self): | |
| """decode_token should fallback to handler when NEW_AUTH_AVAILABLE is True.""" | |
| mock_handler = MagicMock() | |
| mock_payload = MagicMock() | |
| mock_payload.sub = "user1" | |
| mock_payload.roles = ["admin"] | |
| mock_payload.permissions = ["*"] | |
| mock_payload.exp = datetime.now(timezone.utc) + timedelta(minutes=30) | |
| mock_payload.jti = "jti-123" | |
| mock_handler.decode_token.return_value = mock_payload | |
| with patch.object(auth_module, "NEW_AUTH_AVAILABLE", True): | |
| with patch.object(auth_module, "get_jwt_handler", return_value=mock_handler): | |
| result = auth_module.decode_token("some-token") | |
| assert result is not None | |
| assert result["sub"] == "user1" | |
| assert result["role"] == "admin" | |
| assert result["user_id"] == "user1" | |
| assert result["username"] == "user1" | |
| def test_decode_token_new_auth_expired(self): | |
| """decode_token should return None when handler raises TokenExpiredError.""" | |
| TokenExpiredError = type("TokenExpiredError", (Exception,), {}) | |
| TokenInvalidError = type("TokenInvalidError", (Exception,), {}) | |
| mock_handler = MagicMock() | |
| mock_handler.decode_token.side_effect = TokenExpiredError("expired") | |
| with patch.object(auth_module, "NEW_AUTH_AVAILABLE", True): | |
| with patch.object(auth_module, "get_jwt_handler", return_value=mock_handler): | |
| with patch.object(auth_module, "TokenExpiredError", TokenExpiredError, create=True): | |
| with patch.object(auth_module, "TokenInvalidError", TokenInvalidError, create=True): | |
| result = auth_module.decode_token("expired-token") | |
| assert result is None | |
| def test_decode_token_new_auth_invalid(self): | |
| """decode_token should return None when handler raises TokenInvalidError.""" | |
| TokenExpiredError = type("TokenExpiredError", (Exception,), {}) | |
| TokenInvalidError = type("TokenInvalidError", (Exception,), {}) | |
| mock_handler = MagicMock() | |
| mock_handler.decode_token.side_effect = TokenInvalidError("invalid") | |
| with patch.object(auth_module, "NEW_AUTH_AVAILABLE", True): | |
| with patch.object(auth_module, "get_jwt_handler", return_value=mock_handler): | |
| with patch.object(auth_module, "TokenExpiredError", TokenExpiredError, create=True): | |
| with patch.object(auth_module, "TokenInvalidError", TokenInvalidError, create=True): | |
| result = auth_module.decode_token("bad-token") | |
| assert result is None | |
| def test_decode_legacy_token_default_role(self, sample_user_data): | |
| """decode_token should default role to viewer if missing.""" | |
| data = {"sub": "user"} # no role | |
| token = auth_module.create_access_token(data) | |
| payload = auth_module.decode_token(token) | |
| assert payload["role"] == "viewer" | |
| class TestGetPermissionsForRole: | |
| """Tests for _get_permissions_for_role.""" | |
| def test_permissions_for_role(self, role, expected): | |
| """_get_permissions_for_role should return correct permissions.""" | |
| assert auth_module._get_permissions_for_role(role) == expected | |
| # ============================================================================= | |
| # FastAPI Dependencies | |
| # ============================================================================= | |
| class TestVerifyToken: | |
| """Tests for verify_token dependency.""" | |
| async def test_verify_token_valid(self, mock_credentials): | |
| """verify_token should return payload for valid credentials.""" | |
| token = auth_module.create_access_token({"sub": "user", "role": "admin"}) | |
| creds = HTTPAuthorizationCredentials(scheme="Bearer", credentials=token) | |
| payload = await auth_module.verify_token(creds) | |
| assert payload["sub"] == "user" | |
| async def test_verify_token_invalid_raises_401(self, mock_credentials): | |
| """verify_token should raise HTTPException 401 for invalid token.""" | |
| with pytest.raises(HTTPException) as exc_info: | |
| await auth_module.verify_token(mock_credentials) | |
| assert exc_info.value.status_code == status.HTTP_401_UNAUTHORIZED | |
| assert "Invalid or expired token" in exc_info.value.detail | |
| async def test_verify_token_expired_raises_401(self, expired_legacy_token): | |
| """verify_token should raise HTTPException 401 for expired token.""" | |
| creds = HTTPAuthorizationCredentials(scheme="Bearer", credentials=expired_legacy_token) | |
| with pytest.raises(HTTPException) as exc_info: | |
| await auth_module.verify_token(creds) | |
| assert exc_info.value.status_code == status.HTTP_401_UNAUTHORIZED | |
| class TestGetCurrentUser: | |
| """Tests for get_current_user dependency.""" | |
| async def test_get_current_user_returns_payload(self): | |
| """get_current_user should return the decoded token payload.""" | |
| token = auth_module.create_access_token({"sub": "user", "role": "admin"}) | |
| creds = HTTPAuthorizationCredentials(scheme="Bearer", credentials=token) | |
| payload = await auth_module.get_current_user(creds) | |
| assert payload["sub"] == "user" | |
| class TestRequireAdmin: | |
| """Tests for require_admin dependency.""" | |
| async def test_require_admin_success(self): | |
| """require_admin should return user when role is admin.""" | |
| token = auth_module.create_access_token({"sub": "admin", "role": "admin"}) | |
| creds = HTTPAuthorizationCredentials(scheme="Bearer", credentials=token) | |
| user = await auth_module.require_admin(creds) | |
| assert user["sub"] == "admin" | |
| async def test_require_admin_forbidden(self): | |
| """require_admin should raise 403 for non-admin users.""" | |
| token = auth_module.create_access_token({"sub": "user", "role": "viewer"}) | |
| creds = HTTPAuthorizationCredentials(scheme="Bearer", credentials=token) | |
| with pytest.raises(HTTPException) as exc_info: | |
| await auth_module.require_admin(creds) | |
| assert exc_info.value.status_code == status.HTTP_403_FORBIDDEN | |
| assert "Admin privileges required" in exc_info.value.detail | |
| class TestRequireOperator: | |
| """Tests for require_operator dependency.""" | |
| async def test_require_operator_analyst_success(self): | |
| """require_operator should return user for security_analyst.""" | |
| token = auth_module.create_access_token({"sub": "analyst", "role": "security_analyst"}) | |
| creds = HTTPAuthorizationCredentials(scheme="Bearer", credentials=token) | |
| user = await auth_module.require_operator(creds) | |
| assert user["sub"] == "analyst" | |
| async def test_require_operator_admin_success(self): | |
| """require_operator should return user for admin (higher privilege).""" | |
| token = auth_module.create_access_token({"sub": "admin", "role": "admin"}) | |
| creds = HTTPAuthorizationCredentials(scheme="Bearer", credentials=token) | |
| user = await auth_module.require_operator(creds) | |
| assert user["sub"] == "admin" | |
| async def test_require_operator_forbidden(self): | |
| """require_operator should raise 403 for viewer.""" | |
| token = auth_module.create_access_token({"sub": "viewer", "role": "viewer"}) | |
| creds = HTTPAuthorizationCredentials(scheme="Bearer", credentials=token) | |
| with pytest.raises(HTTPException) as exc_info: | |
| await auth_module.require_operator(creds) | |
| assert exc_info.value.status_code == status.HTTP_403_FORBIDDEN | |
| assert "Security analyst privileges required" in exc_info.value.detail | |
| # ============================================================================= | |
| # Permission Checking | |
| # ============================================================================= | |
| class TestCheckPermissions: | |
| """Tests for check_permissions.""" | |
| def test_check_permissions_single_role(self, user_role, required, expected): | |
| """check_permissions should correctly evaluate role hierarchy.""" | |
| user = {"role": user_role} | |
| assert auth_module.check_permissions(user, required) == expected | |
| def test_check_permissions_with_roles_list(self): | |
| """check_permissions should support roles list.""" | |
| user = {"roles": ["user", "admin"]} | |
| assert auth_module.check_permissions(user, "admin") is True | |
| def test_check_permissions_no_roles_defaults_viewer(self): | |
| """check_permissions should default to viewer level if no roles/role present.""" | |
| user = {} | |
| assert auth_module.check_permissions(user, "viewer") is True | |
| assert auth_module.check_permissions(user, "user") is False | |
| def test_check_permissions_unknown_role(self): | |
| """check_permissions should treat unknown roles as level 0.""" | |
| user = {"role": "unknown"} | |
| assert auth_module.check_permissions(user, "viewer") is False | |
| assert auth_module.check_permissions(user, "user") is False | |
| # ============================================================================= | |
| # AuthService | |
| # ============================================================================= | |
| class TestAuthServiceAuthenticateUser: | |
| """Tests for AuthService.authenticate_user.""" | |
| def test_authenticate_user_not_found(self): | |
| """authenticate_user should return None when user is not found.""" | |
| mock_db = MagicMock() | |
| mock_db.query.return_value.filter.return_value.first.return_value = None | |
| svc = auth_module.AuthService() | |
| result = svc.authenticate_user(mock_db, "nouser", "password") | |
| assert result is None | |
| def test_authenticate_user_inactive(self): | |
| """authenticate_user should return None when user is inactive.""" | |
| mock_user = MagicMock() | |
| mock_user.is_active = False | |
| mock_db = MagicMock() | |
| mock_db.query.return_value.filter.return_value.first.return_value = mock_user | |
| svc = auth_module.AuthService() | |
| result = svc.authenticate_user(mock_db, "user", "password") | |
| assert result is None | |
| def test_authenticate_user_wrong_password(self): | |
| """authenticate_user should return None when password is wrong.""" | |
| mock_user = MagicMock() | |
| mock_user.is_active = True | |
| mock_user.hashed_password = "hashed" | |
| mock_db = MagicMock() | |
| mock_db.query.return_value.filter.return_value.first.return_value = mock_user | |
| svc = auth_module.AuthService() | |
| with patch.object(svc.password_hasher, "verify", return_value=False): | |
| result = svc.authenticate_user(mock_db, "user", "wrongpass") | |
| assert result is None | |
| def test_authenticate_user_success(self): | |
| """authenticate_user should return user dict on success.""" | |
| mock_user = MagicMock() | |
| mock_user.is_active = True | |
| mock_user.id = 1 | |
| mock_user.username = "testuser" | |
| mock_user.email = "test@example.com" | |
| mock_user.role = MagicMock() | |
| mock_user.role.value = "admin" | |
| mock_user.hashed_password = "hashed" | |
| mock_db = MagicMock() | |
| mock_db.query.return_value.filter.return_value.first.return_value = mock_user | |
| svc = auth_module.AuthService() | |
| with patch.object(svc.password_hasher, "verify", return_value=True): | |
| result = svc.authenticate_user(mock_db, "testuser", "password") | |
| assert result is not None | |
| assert result["id"] == 1 | |
| assert result["username"] == "testuser" | |
| assert result["email"] == "test@example.com" | |
| assert result["role"] == "admin" | |
| assert result["is_active"] is True | |
| class TestAuthServiceCreateUser: | |
| """Tests for AuthService.create_user.""" | |
| def test_create_user_already_exists(self): | |
| """create_user should raise ValueError when username/email exists.""" | |
| mock_db = MagicMock() | |
| mock_db.query.return_value.filter.return_value.first.return_value = MagicMock() | |
| svc = auth_module.AuthService() | |
| with pytest.raises(ValueError, match="Username or email already exists"): | |
| svc.create_user(mock_db, "user", "user@example.com", "Password123!") | |
| def test_create_user_weak_password(self): | |
| """create_user should raise ValueError when password is too weak.""" | |
| mock_db = MagicMock() | |
| mock_db.query.return_value.filter.return_value.first.return_value = None | |
| svc = auth_module.AuthService() | |
| with patch.object(svc.password_hasher, "validate_strength", return_value=(False, "too weak")): | |
| with pytest.raises(ValueError, match="Password too weak"): | |
| svc.create_user(mock_db, "user", "user@example.com", "weak") | |
| def test_create_user_success(self): | |
| """create_user should create and return user dict.""" | |
| mock_db = MagicMock() | |
| mock_db.query.return_value.filter.return_value.first.return_value = None | |
| mock_user = MagicMock() | |
| mock_user.id = 1 | |
| mock_user.username = "newuser" | |
| mock_user.email = "new@example.com" | |
| mock_user.role = MagicMock() | |
| mock_user.role.value = "user" | |
| mock_user.is_active = True | |
| mock_user.created_at = datetime.now(timezone.utc) | |
| mock_db.add.return_value = None | |
| mock_db.commit.return_value = None | |
| mock_db.refresh.return_value = None | |
| svc = auth_module.AuthService() | |
| with patch.object(svc.password_hasher, "validate_strength", return_value=(True, None)): | |
| with patch.object(svc.password_hasher, "hash", return_value="hashed_pw"): | |
| with patch("database.auth_models.User", return_value=mock_user): | |
| with patch("database.auth_models.UserRole"): | |
| result = svc.create_user(mock_db, "newuser", "new@example.com", "StrongPass123!") | |
| assert result["id"] == 1 | |
| assert result["username"] == "newuser" | |
| assert result["role"] == "user" | |
| mock_db.add.assert_called_once() | |
| mock_db.commit.assert_called_once() | |
| mock_db.refresh.assert_called_once() | |
| def test_create_user_invalid_role_fallback(self): | |
| """create_user should fallback to USER role for invalid role strings.""" | |
| mock_db = MagicMock() | |
| mock_db.query.return_value.filter.return_value.first.return_value = None | |
| mock_user = MagicMock() | |
| mock_user.id = 2 | |
| mock_user.username = "user" | |
| mock_user.email = "u@example.com" | |
| mock_user.role = MagicMock() | |
| mock_user.role.value = "user" | |
| mock_user.is_active = True | |
| mock_user.created_at = None | |
| svc = auth_module.AuthService() | |
| with patch.object(svc.password_hasher, "validate_strength", return_value=(True, None)): | |
| with patch.object(svc.password_hasher, "hash", return_value="hashed_pw"): | |
| with patch("database.auth_models.User", return_value=mock_user): | |
| with patch("database.auth_models.UserRole", side_effect=[ValueError, mock_user.role]): | |
| result = svc.create_user(mock_db, "user", "u@example.com", "StrongPass123!", role="badrole") | |
| assert result["role"] == "user" | |
| # ============================================================================= | |
| # Legacy API Key Management | |
| # ============================================================================= | |
| class TestAPIKeyManagement: | |
| """Tests for create_api_key, revoke_api_key, verify_api_key.""" | |
| def test_create_api_key_format(self): | |
| """create_api_key should return a string with expected prefix.""" | |
| key = auth_module.create_api_key(1, "my-key") | |
| assert key.startswith("zen_1_my-key_") | |
| assert key in auth_module.API_KEYS | |
| assert auth_module.API_KEYS[key]["user_id"] == 1 | |
| assert auth_module.API_KEYS[key]["name"] == "my-key" | |
| def test_create_api_key_counter_increments(self): | |
| """create_api_key should increment counter for each call.""" | |
| key1 = auth_module.create_api_key(1, "key1") | |
| key2 = auth_module.create_api_key(1, "key2") | |
| assert "_1_" in key1 | |
| assert "_2_" in key2 | |
| def test_revoke_api_key_success(self): | |
| """revoke_api_key should return True and remove key.""" | |
| key = auth_module.create_api_key(1, "to-revoke") | |
| assert auth_module.revoke_api_key(key) is True | |
| assert key not in auth_module.API_KEYS | |
| def test_revoke_api_key_failure(self): | |
| """revoke_api_key should return False for unknown key.""" | |
| assert auth_module.revoke_api_key("nonexistent") is False | |
| def test_verify_api_key_found(self): | |
| """verify_api_key should return key data for valid key.""" | |
| key = auth_module.create_api_key(2, "test") | |
| data = auth_module.verify_api_key(key) | |
| assert data is not None | |
| assert data["user_id"] == 2 | |
| def test_verify_api_key_not_found(self): | |
| """verify_api_key should return None for invalid key.""" | |
| assert auth_module.verify_api_key("invalid-key") is None | |
| # ============================================================================= | |
| # Legacy Module-Level Wrappers | |
| # ============================================================================= | |
| class TestLegacyWrappers: | |
| """Tests for module-level authenticate_user and create_user wrappers.""" | |
| def test_module_authenticate_user_delegates(self): | |
| """Module-level authenticate_user should delegate to AuthService.""" | |
| mock_db = MagicMock() | |
| with patch.object(auth_module, "get_auth_service") as mock_get_svc: | |
| mock_svc = MagicMock() | |
| mock_svc.authenticate_user.return_value = {"id": 1} | |
| mock_get_svc.return_value = mock_svc | |
| result = auth_module.authenticate_user(mock_db, "user", "pass") | |
| assert result == {"id": 1} | |
| mock_svc.authenticate_user.assert_called_once_with(mock_db, "user", "pass") | |
| def test_module_create_user_delegates(self): | |
| """Module-level create_user should delegate to AuthService.""" | |
| mock_db = MagicMock() | |
| with patch.object(auth_module, "get_auth_service") as mock_get_svc: | |
| mock_svc = MagicMock() | |
| mock_svc.create_user.return_value = {"id": 2} | |
| mock_get_svc.return_value = mock_svc | |
| result = auth_module.create_user(mock_db, "user", "u@e.com", "pass", "admin") | |
| assert result == {"id": 2} | |
| mock_svc.create_user.assert_called_once_with(mock_db, "user", "u@e.com", "pass", "admin") | |
Xet Storage Details
- Size:
- 31.6 kB
- Xet hash:
- c1989f9d03151b2d5c49ae66d1c5331b27b49d15d510e17886b8b1a023a55850
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.