"""Kontoverwaltung: Einmal-Passwort, Deaktivieren, Betreiberrolle, Sitzungen, Login-Begrenzung.""" from __future__ import annotations import pytest from fastapi.testclient import TestClient from app.auth.accounts import create_account from tests.support import ORIGIN, PASSWORD, Actor NEW_PASSWORD = "Neues-Passwort-2026" def register(conn, email: str, name: str, *, superadmin: bool = False): """Accounts of the operator kind, because the account list hides fixture accounts.""" account = create_account(conn, email, name, PASSWORD, is_superadmin=superadmin) conn.commit() return account @pytest.fixture def operator(client, db) -> Actor: actor = Actor(client, "betreiber-admin@example.test", "Betreiber Admin") register(db, actor.email, actor.name, superadmin=True) actor.login() return actor def _user(client, db, email: str = "nutzer-admin@example.test", name: str = "Nutzer Admin") -> Actor: actor = Actor(client, email, name) register(db, actor.email, actor.name) return actor def _second_client(): from app.main import app return TestClient(app) def test_operator_creates_an_account_with_a_one_time_password(client, operator): created = operator.request( "POST", "/api/v1/accounts", json={"email": "neu@example.test", "display_name": "Neu"}, status=201, ) temporary = created["temporary_password"] assert len(temporary) >= 10 assert created["must_change_password"] is True fresh = Actor(client, "neu@example.test", "Neu") fresh.password = temporary body = fresh.login() assert body["account"]["must_change_password"] is True refused = fresh.request("GET", "/api/v1/cases", status=403) assert refused["code"] == "password_change_required" fresh.request("GET", "/api/v1/auth/session") fresh.request( "POST", "/api/v1/auth/password", json={"current_password": "falsch-falsch-1", "new_password": NEW_PASSWORD}, status=422, ) fresh.request("POST", "/api/v1/auth/password", json={"current_password": temporary, "new_password": temporary}, status=422) fresh.request("POST", "/api/v1/auth/password", json={"current_password": temporary, "new_password": "kurz"}, status=422) fresh.request( "POST", "/api/v1/auth/password", json={"current_password": temporary, "new_password": NEW_PASSWORD}, status=204, ) fresh.request("GET", "/api/v1/cases") assert fresh.request("GET", "/api/v1/auth/session")["account"]["must_change_password"] is False again = Actor(client, "neu@example.test", "Neu") again.password = NEW_PASSWORD again.login() old = client.post( "/api/v1/auth/login", json={"email": "neu@example.test", "password": temporary}, headers={"Origin": ORIGIN}, ) assert old.status_code == 401 def test_only_the_operator_manages_accounts(client, db, operator): user = _user(client, db) target = operator.request("GET", "/api/v1/accounts")["items"][0]["id"] user.login() user.request("GET", "/api/v1/accounts", status=403) user.request("GET", f"/api/v1/accounts/{target}", status=403) user.request("PATCH", f"/api/v1/accounts/{target}", json={"status": "disabled"}, status=403) user.request("POST", f"/api/v1/accounts/{target}/password-reset", status=403) user.request("POST", f"/api/v1/accounts/{target}/sessions/revoke", status=403) user.request("POST", "/api/v1/accounts", json={"email": "x@example.test", "display_name": "X"}, status=403) def test_a_disabled_account_cannot_sign_in_and_its_sessions_end(client, db, operator): user = _user(client, db) other = _second_client() victim = Actor(other, user.email, user.name) victim.login() victim.request("GET", "/api/v1/cases") operator.request("PATCH", f"/api/v1/accounts/{_id(operator, user.email)}", json={"status": "disabled"}) victim.request("GET", "/api/v1/cases", status=401) refused = client.post( "/api/v1/auth/login", json={"email": user.email, "password": PASSWORD}, headers={"Origin": ORIGIN}, ) assert refused.status_code == 401 listed = operator.request("GET", "/api/v1/accounts", params={"status": "disabled"}) assert [item["email"] for item in listed["items"]] == [user.email] operator.request("PATCH", f"/api/v1/accounts/{_id(operator, user.email)}", json={"status": "active"}) Actor(client, user.email, user.name).login() def test_the_last_operator_and_the_own_account_are_protected(client, db, operator): me = _id(operator, operator.email) operator.request("PATCH", f"/api/v1/accounts/{me}", json={"status": "disabled"}, status=422) operator.request("PATCH", f"/api/v1/accounts/{me}", json={"is_operator": False}, status=422) user = _user(client, db) other = _id(operator, user.email) operator.request("PATCH", f"/api/v1/accounts/{other}", json={"is_operator": True}) # A second operator exists now, so the first may step down. operator.request("PATCH", f"/api/v1/accounts/{me}", json={"is_operator": False}) promoted = Actor(client, user.email, user.name) promoted.login() promoted.request("PATCH", f"/api/v1/accounts/{promoted_id(promoted)}", json={"status": "disabled"}, status=422) promoted.request("PATCH", f"/api/v1/accounts/{promoted_id(promoted)}", json={"is_operator": False}, status=422) def test_granting_the_operator_role_ends_the_target_sessions(client, db, operator): user = _user(client, db) other = _second_client() target = Actor(other, user.email, user.name) target.login() target.request("GET", "/api/v1/cases") operator.request("PATCH", f"/api/v1/accounts/{_id(operator, user.email)}", json={"is_operator": True}) target.request("GET", "/api/v1/cases", status=401) fresh = Actor(other, user.email, user.name) assert fresh.login()["account"]["is_superadmin"] is True def test_password_reset_sets_a_one_time_password_and_ends_sessions(client, db, operator): user = _user(client, db) other = _second_client() target = Actor(other, user.email, user.name) target.login() account_id = _id(operator, user.email) operator.request("POST", f"/api/v1/accounts/{operator_id(operator)}/password-reset", status=422) reset = operator.request("POST", f"/api/v1/accounts/{account_id}/password-reset") target.request("GET", "/api/v1/cases", status=401) renewed = Actor(other, user.email, user.name) renewed.password = reset["temporary_password"] assert renewed.login()["account"]["must_change_password"] is True renewed.request("GET", "/api/v1/cases", status=403) detail = operator.request("GET", f"/api/v1/accounts/{account_id}") assert detail["must_change_password"] is True assert detail["active_sessions"] == 1 revoked = operator.request("POST", f"/api/v1/accounts/{account_id}/sessions/revoke") assert revoked["revoked"] == 1 renewed.request("GET", "/api/v1/auth/session", status=401) def test_own_sessions_can_be_listed_and_ended(client, db): user = _user(client, db) user.login() other = _second_client() second = Actor(other, user.email, user.name) second.login() items = user.request("GET", "/api/v1/auth/sessions")["items"] assert len(items) == 2 assert sum(1 for item in items if item["current"]) == 1 current = next(item for item in items if item["current"]) foreign = next(item for item in items if not item["current"]) user.request("DELETE", f"/api/v1/auth/sessions/{current['id']}", status=422) user.request("DELETE", f"/api/v1/auth/sessions/{foreign['id']}", status=204) second.request("GET", "/api/v1/cases", status=401) third = Actor(other, user.email, user.name) third.login() assert user.request("POST", "/api/v1/auth/sessions/revoke-others")["revoked"] == 1 third.request("GET", "/api/v1/cases", status=401) user.request("GET", "/api/v1/cases") def test_login_attempts_are_counted_in_the_database_without_the_address(client, db): user = _user(client, db) for _ in range(8): response = client.post( "/api/v1/auth/login", json={"email": user.email, "password": "falsch-falsch-1"}, headers={"Origin": ORIGIN}, ) assert response.status_code == 401 blocked = client.post( "/api/v1/auth/login", json={"email": user.email, "password": PASSWORD}, headers={"Origin": ORIGIN}, ) assert blocked.status_code == 429 rows = db.execute("SELECT bucket FROM auth_login_attempts").fetchall() assert len(rows) == 8 assert all(user.email not in row["bucket"] and len(row["bucket"]) == 64 for row in rows) db.rollback() # Another address is a separate bucket and still works. other = _user(client, db, "andere-adresse@example.test", "Andere") Actor(client, other.email, other.name).login() def test_unknown_and_wrong_password_answer_alike(client, db): user = _user(client, db) wrong = client.post( "/api/v1/auth/login", json={"email": user.email, "password": "falsch-falsch-1"}, headers={"Origin": ORIGIN}, ) unknown = client.post( "/api/v1/auth/login", json={"email": "gibt-es-nicht@example.test", "password": "falsch-falsch-1"}, headers={"Origin": ORIGIN}, ) assert wrong.status_code == unknown.status_code == 401 assert wrong.json()["detail"] == unknown.json()["detail"] def test_admin_actions_are_audited_without_secrets(client, db, operator): created = operator.request( "POST", "/api/v1/accounts", json={"email": "audit-ziel@example.test", "display_name": "Audit Ziel"}, status=201, ) account_id = created["id"] operator.request("POST", f"/api/v1/accounts/{account_id}/password-reset") operator.request("PATCH", f"/api/v1/accounts/{account_id}", json={"status": "disabled"}) rows = db.execute( "SELECT action, detail FROM domain_events WHERE resource_kind = 'account' AND resource_id = %s ORDER BY occurred_at", (account_id,), ).fetchall() assert [row["action"] for row in rows] == ["account_created", "password_reset", "account_disabled"] text = str(rows) + str(db.execute("SELECT * FROM domain_events").fetchall()) assert "audit-ziel@example.test" not in text assert created["temporary_password"] not in text def _id(actor: Actor, email: str) -> str: items = actor.request("GET", "/api/v1/accounts")["items"] return next(item["id"] for item in items if item["email"] == email) def operator_id(actor: Actor) -> str: return _id(actor, actor.email) def promoted_id(actor: Actor) -> str: return _id(actor, actor.email)