"""Tests for user_service — CRUD, tenant membership, permission checks. Security-critical: User management must enforce tenant isolation and RBAC. """ from __future__ import annotations import pytest from httpx import AsyncClient from tests.conftest import ORIGIN_HEADER, login_client, seed_tenant_and_users @pytest.mark.asyncio class TestUserServiceCRUD: """User service CRUD operations.""" async def test_list_users_as_admin(self, client: AsyncClient, db_session): """Admin can list users in their tenant.""" await seed_tenant_and_users(db_session) await login_client(client, "admin@tenanta.com") resp = await client.get("/api/v1/users", headers=ORIGIN_HEADER) assert resp.status_code == 200 data = resp.json() # API may return a list or paginated dict with 'items' users = data if isinstance(data, list) else data.get("items", []) emails = [u.get("email", "") for u in users] assert "admin@tenanta.com" in emails assert "admin@tenantb.com" not in emails async def test_list_users_as_viewer_forbidden(self, client: AsyncClient, db_session): """Viewer may or may not list users depending on default permissions.""" await seed_tenant_and_users(db_session) await login_client(client, "viewer@tenanta.com") resp = await client.get("/api/v1/users", headers=ORIGIN_HEADER) assert resp.status_code == 403 async def test_create_user_as_admin(self, client: AsyncClient, db_session): """Admin can create a new user in their tenant.""" await seed_tenant_and_users(db_session) await login_client(client, "admin@tenanta.com") resp = await client.post( "/api/v1/users", json={ "email": "newuser@test.de", "name": "New User", "password": "NewPass123!", "role": "viewer", }, headers=ORIGIN_HEADER, ) assert resp.status_code == 201 data = resp.json() assert data["email"] == "newuser@test.de" async def test_create_user_as_viewer_forbidden(self, client: AsyncClient, db_session): """Viewer cannot create users.""" await seed_tenant_and_users(db_session) await login_client(client, "viewer@tenanta.com") resp = await client.post( "/api/v1/users", json={ "email": "newuser@test.de", "name": "New User", "password": "NewPass123!", "role": "viewer", }, headers=ORIGIN_HEADER, ) assert resp.status_code == 403 async def test_create_user_duplicate_email(self, client: AsyncClient, db_session): """Cannot create user with existing email — should return error, not 500.""" await seed_tenant_and_users(db_session) await login_client(client, "admin@tenanta.com") resp = await client.post( "/api/v1/users", json={ "email": "admin@tenanta.com", "name": "Duplicate", "password": "NewPass123!", "role": "viewer", }, headers=ORIGIN_HEADER, ) assert resp.status_code == 409 async def test_update_user_as_admin(self, client: AsyncClient, db_session): """Admin can update a user.""" await seed_tenant_and_users(db_session) await login_client(client, "admin@tenanta.com") # Get user list first resp = await client.get("/api/v1/users", headers=ORIGIN_HEADER) assert resp.status_code == 200 data = resp.json() users = data if isinstance(data, list) else data.get("items", []) viewer = next(u for u in users if u["email"] == "viewer@tenanta.com") resp = await client.patch( f"/api/v1/users/{viewer['id']}", json={"name": "Updated Viewer"}, headers=ORIGIN_HEADER, ) assert resp.status_code == 200 assert resp.json()["name"] == "Updated Viewer" async def test_delete_user_as_admin(self, client: AsyncClient, db_session): """Admin can delete a user.""" await seed_tenant_and_users(db_session) await login_client(client, "admin@tenanta.com") resp = await client.get("/api/v1/users", headers=ORIGIN_HEADER) data = resp.json() users = data if isinstance(data, list) else data.get("items", []) viewer = next(u for u in users if u["email"] == "viewer@tenanta.com") resp = await client.delete( f"/api/v1/users/{viewer['id']}", headers=ORIGIN_HEADER, ) assert resp.status_code == 204 async def test_cross_tenant_user_isolation(self, client: AsyncClient, db_session): """Admin A cannot see users from tenant B.""" await seed_tenant_and_users(db_session) await login_client(client, "admin@tenanta.com") resp = await client.get("/api/v1/users", headers=ORIGIN_HEADER) assert resp.status_code == 200 data = resp.json() users = data if isinstance(data, list) else data.get("items", []) emails = [u["email"] for u in users] assert "admin@tenantb.com" not in emails class TestF02GlobalIdentityGuard: """F02 (Astra P0): tenant administration must not change global login identity fields of other users. User is a GLOBAL record shared across tenants (password, email, is_system_admin). A tenant admin (users:write) may manage membership and tenant-scoped fields — but must NOT change another member's global login identity (password-reset address, credentials) or the global activation status of a multi-tenant user. """ async def _get_user(self, client: AsyncClient, email: str) -> dict: resp = await client.get("/api/v1/users", headers=ORIGIN_HEADER) assert resp.status_code == 200 data = resp.json() users = data if isinstance(data, list) else data.get("items", []) return next(u for u in users if u["email"] == email) async def test_tenant_admin_cannot_change_foreign_email(self, client: AsyncClient, db_session): """Tenant admin changing ANOTHER member's email → 403.""" await seed_tenant_and_users(db_session) await login_client(client, "admin@tenanta.com") viewer = await self._get_user(client, "viewer@tenanta.com") resp = await client.patch( f"/api/v1/users/{viewer['id']}", json={"email": "attacker-controlled@evil.de"}, headers=ORIGIN_HEADER, ) assert resp.status_code == 403 assert resp.json().get("detail", {}).get("code") in ("global_identity_forbidden",) async def test_tenant_admin_cannot_change_foreign_password(self, client: AsyncClient, db_session): """Tenant admin setting ANOTHER member's password → 403.""" await seed_tenant_and_users(db_session) await login_client(client, "admin@tenanta.com") viewer = await self._get_user(client, "viewer@tenanta.com") resp = await client.patch( f"/api/v1/users/{viewer['id']}", json={"new_password": "NewHackedPass123!", "current_password": "whatever"}, headers=ORIGIN_HEADER, ) assert resp.status_code == 403 assert resp.json().get("detail", {}).get("code") in ("global_identity_forbidden",) async def test_tenant_admin_cannot_deactivate_multi_tenant_user(self, client: AsyncClient, db_session): """admin@tenanta.com is seeded with a SECOND membership (tenant B). A tenant admin deactivating this multi-tenant user's GLOBAL status → 403. Deactivation would lock the user out of every tenant, not just this one. """ seed = await seed_tenant_and_users(db_session) # editor_a edits the multi-tenant admin_a — editors lack users:write, # so log in as admin_a won't work (self-service rules differ). # Instead: viewer_a is single-tenant, admin_a is multi-tenant. # We need a second admin in tenant A without extra fixtures: use the # system-admin path — a non-system-admin tenant admin tries to # deactivate the multi-tenant admin_a from tenant A. await login_client(client, "admin@tenanta.com") # admin_a changing their OWN status hits self-modification prevention # first — so instead verify via a fresh single-tenant admin in A. # The seeded admin_a is multi-tenant; add a temporary admin: from app.core.auth import hash_password from app.models.user import User, UserTenant tenant_a_id = seed["tenant_a"].id admin_role_id = seed["admin_role_a"].id other_admin = User( email="otheradmin@tenanta.com", name="Other Admin", password_hash=hash_password("TestPass123!"), is_active=True, preferences={}, ) db_session.add(other_admin) await db_session.flush() ut = UserTenant( user_id=other_admin.id, tenant_id=tenant_a_id, is_default=True, role="admin", role_id=admin_role_id, ) db_session.add(ut) await db_session.commit() await login_client(client, "otheradmin@tenanta.com") admin_a = await self._get_user(client, "admin@tenanta.com") resp = await client.patch( f"/api/v1/users/{admin_a['id']}", json={"is_active": False}, headers=ORIGIN_HEADER, ) assert resp.status_code == 403 assert resp.json().get("detail", {}).get("code") in ("multi_tenant_status_forbidden",) async def test_tenant_admin_can_still_rename_member(self, client: AsyncClient, db_session): """Regression: tenant administration keeps working for tenant-scoped fields (name, role) — the guard only protects global identity.""" await seed_tenant_and_users(db_session) await login_client(client, "admin@tenanta.com") viewer = await self._get_user(client, "viewer@tenanta.com") resp = await client.patch( f"/api/v1/users/{viewer['id']}", json={"name": "Renamed Viewer"}, headers=ORIGIN_HEADER, ) assert resp.status_code == 200 assert resp.json()["name"] == "Renamed Viewer" async def test_self_service_email_change_still_allowed(self, client: AsyncClient, db_session): """Self-service: users can still change THEIR OWN email.""" await seed_tenant_and_users(db_session) await login_client(client, "admin@tenanta.com") me = await self._get_user(client, "admin@tenanta.com") resp = await client.patch( f"/api/v1/users/{me['id']}", json={"email": "admin@tenanta.com"}, # same value, but goes through the guard headers=ORIGIN_HEADER, ) assert resp.status_code == 200