# SPDX-License-Identifier: AGPL-3.0-or-later """Phase 7b gegen PostgreSQL: Konten und Gast-Adressen löschen, Löschjournal (CI).""" from __future__ import annotations import re from datetime import UTC, datetime, timedelta from typing import Any import pytest pytest.importorskip("fastapi") from fastapi.testclient import TestClient from helpers import new_client, token_for from sqlalchemy import select, update from sqlalchemy.orm import Session from test_forms import creator, fill, form_row, participant from test_mail import admin, content, messages from test_phase5 import bookings, slot_form from surveybox import db, erasure_journal from surveybox.models import ( AuditEvent, Comment, Form, FormMember, GuestContact, MailMessage, Response, UserAccount, UserSession, ) from surveybox.settings import get_settings pytestmark = pytest.mark.db def user_by_email(email: str) -> UserAccount | None: with Session(db.get_engine()) as s: found = s.scalar(select(UserAccount).where(UserAccount.email == email)) if found is not None: s.expunge(found) return found def post_delete(client: TestClient, path: str, **data: Any) -> Any: csrf = token_for(client, path) return client.post(path, data={"csrf_token": csrf, **data}) def audit_actions() -> list[str]: with Session(db.get_engine()) as s: return list(s.scalars(select(AuditEvent.action))) def test_self_deletion_releases_place_and_is_journaled(app: Any) -> None: carla = creator(app) pid, token, qid, (early, _) = slot_form(carla, waitlist=True) paul = participant(app) assert fill(paul, token, {f"q{qid}": early}).status_code == 303 assert fill(participant(app, "olga@example.de"), token, {f"q{qid}": early}).status_code == 303 assert [b[1] for b in bookings(qid)] == ["confirmed", "waiting"] page = paul.get("/account/delete").text assert "1 answer is anonymized" in page and "waiting list move up" in page # Ohne Bestätigung passiert nichts assert post_delete(paul, "/account/delete").status_code == 400 assert user_by_email("paul@example.de") is not None resp = post_delete(paul, "/account/delete", confirm="on") assert resp.status_code == 200 and "has been deleted" in resp.text assert user_by_email("paul@example.de") is None # Olga rückt nach; Pauls Antwort bleibt anonym ohne Platz (Formular läuft noch) assert [b[1:] for b in bookings(qid)] == [("confirmed", True)] with Session(db.get_engine()) as s: rows = list(s.scalars(select(Response).where(Response.form_id == form_row(pid).id))) assert sum(1 for r in rows if r.user_id is None and r.anonymized_at is not None) == 1 assert "account.deleted" in audit_actions() entries = erasure_journal.entries(get_settings()) assert [e.kind for e in entries] == ["user"] # Sitzung ist weg assert paul.get("/account").status_code in (303, 401, 403) def test_deletion_needs_recent_sign_in(app: Any) -> None: paul = participant(app) with Session(db.get_engine()) as s: s.execute(update(UserSession).values(reauth_at=datetime.now(UTC) - timedelta(hours=1))) s.commit() page = paul.get("/account/delete").text assert "sign in again" in page assert post_delete(paul, "/account/delete", confirm="on").status_code == 403 assert user_by_email("paul@example.de") is not None resp = post_delete(paul, "/logout", next="/account/delete") assert resp.headers["location"] == "/login?next=/account/delete" def test_forms_are_handed_over_or_deleted(app: Any) -> None: carla = creator(app) kept, _, _, _ = slot_form(carla) dropped, _, _, _ = slot_form(carla) creator(app, "bea@example.de") bea = user_by_email("bea@example.de") assert bea is not None with Session(db.get_engine()) as s: s.add(FormMember(form_id=form_row(kept).id, user_id=bea.id, role="editor")) s.add(Comment(form_id=form_row(kept).id, user_id=user_by_email("carla@example.de").id, # type: ignore[union-attr] body="Hallo", status="published")) s.commit() page = carla.get("/account/delete").text assert "Hand over to" in page resp = post_delete(carla, "/account/delete", confirm="on", **{f"form_{kept}": str(bea.public_id), f"form_{dropped}": "delete"}) assert resp.status_code == 200 with Session(db.get_engine()) as s: forms = {str(f.public_id): f.owner_id for f in s.scalars(select(Form))} comment = s.scalar(select(Comment)) assert comment is not None and comment.author_deleted and comment.user_id is None assert forms == {kept: bea.id} (entry,) = erasure_journal.entries(get_settings()) assert entry.extra["forms"] == {kept: str(bea.public_id), dropped: ""} def test_admin_deletes_user_and_last_admin_is_protected(app: Any) -> None: root = admin(app) carla = creator(app) pid, _, _, _ = slot_form(carla) target = user_by_email("carla@example.de") me = user_by_email("admin@example.de") assert target is not None and me is not None path = f"/admin/users/{target.public_id}/delete" assert "Forms of this user" in root.get(path).text resp = post_delete(root, path, confirm="on", forms_to=str(me.public_id)) assert resp.headers["location"] == "/admin/users?notice=user_deleted" assert user_by_email("carla@example.de") is None assert form_row(pid).owner_id == me.id # Der einzige Administrator kann sich nicht selbst löschen assert root.get(f"/admin/users/{me.public_id}/delete").headers["location"] == "/account/delete" resp = post_delete(root, "/account/delete", confirm="on") assert resp.status_code == 400 and "last administrator" in resp.text def test_guest_deletes_all_data_by_mail(app: Any) -> None: carla = creator(app) _, token, qid, (early, _) = slot_form(carla, capacity="", guest_email="optional") fill(new_client(app), token, {f"q{qid}": early, "guest_email": "gast@example.de"}) guest = new_client(app) csrf = token_for(guest, "/links") resp = guest.post("/links/erase", data={"csrf_token": csrf, "email": "gast@example.de"}) assert "sent a link to delete it" in resp.text (mail,) = messages("guest_erase") link = re.search(r"https?://\S+/g/erase/\S+", content(mail)["text"]).group(0) # type: ignore[union-attr] path = link.replace(get_settings().public_origin, "") page = guest.get(path) assert page.status_code == 200 and "1 answer is anonymized" in page.text csrf = re.search(r'name="csrf_token" value="([0-9a-f]+)"', page.text).group(1) # type: ignore[union-attr] done = guest.post(path, data={"csrf_token": csrf, "confirm": "on"}) assert done.status_code == 200 and "has been deleted" in done.text with Session(db.get_engine()) as s: assert s.scalar(select(GuestContact)) is None assert list(s.scalars(select(MailMessage).where( MailMessage.recipient == "gast@example.de"))) == [] (response,) = s.scalars(select(Response)) assert response.guest_contact_id is None and response.anonymized_at is not None assert guest.get(path).status_code == 404 # Link ist verbraucht assert "guest.deleted" in audit_actions() def test_unknown_address_gets_same_answer(app: Any) -> None: guest = new_client(app) csrf = token_for(guest, "/links") resp = guest.post("/links/erase", data={"csrf_token": csrf, "email": "niemand@example.de"}) assert "sent a link to delete it" in resp.text assert messages("guest_erase") == [] def test_journal_is_replayed_after_restore(app: Any) -> None: carla = creator(app) _, token, qid, (early, _) = slot_form(carla, capacity="", guest_email="optional") fill(new_client(app), token, {f"q{qid}": early, "guest_email": "gast@example.de"}) settings = get_settings() with Session(db.get_engine()) as s: contact = s.scalar(select(GuestContact)) assert contact is not None pid = contact.public_id # Als wäre die Adresse nach der Sicherung gelöscht und die Sicherung dann zurückgespielt erasure_journal.record(settings, "guest", pid) erasure_journal.mark_restore(settings, datetime.now(UTC) - timedelta(minutes=5)) from surveybox.worker import Worker assert Worker(settings).replay_erasures() == 1 assert erasure_journal.pending_since(settings) is None with Session(db.get_engine()) as s: assert s.scalar(select(GuestContact)) is None # Ältere Einträge fallen beim Aufräumen weg assert erasure_journal.prune(settings, datetime.now(UTC) + timedelta(seconds=1)) == 1 assert erasure_journal.entries(settings) == []