# SPDX-License-Identifier: AGPL-3.0-or-later """Phase 6a gegen PostgreSQL: Mail-Einstellungen, Warteschlange, Versand, Passwort vergessen, Einladungen, Benachrichtigungen, Abmelden (CI).""" from __future__ import annotations import re import smtplib from datetime import UTC, datetime, timedelta from email.message import EmailMessage from typing import Any, ClassVar import pytest pytest.importorskip("fastapi") from fastapi.testclient import TestClient from helpers import csrf_from, login, make_user, new_client, next_totp, token_for from sqlalchemy import select from sqlalchemy.orm import Session from test_forms import creator, fill, participant from test_phase5 import slot_form from surveybox import db from surveybox.mail import config as mail_config from surveybox.mail import outbox, smtp from surveybox.models import AppSetting, AuditEvent, MailMessage, Role, UserAccount from surveybox.settings import get_settings pytestmark = pytest.mark.db RELAY = { "host": "smtp.example.org", "port": "587", "security": "starttls", "username": "relay", "password": "relay-geheim", "from_address": "surveybox@example.org", "from_name": "Surveybox Test", "reply_to": "team@example.org", } def admin(app: Any) -> TestClient: _, secret = make_user(Role.ADMIN, "admin@example.de", with_totp=True) assert secret client = new_client(app) login(client, "admin@example.de") mfa = client.get("/login/mfa") client.post("/login/mfa", data={"code": next_totp(secret), "csrf_token": csrf_from(mfa.text), "next": "/"}) return client def configure(client: TestClient) -> None: csrf = token_for(client, "/admin/mail") resp = client.post("/admin/mail", data={"csrf_token": csrf, **RELAY}) assert resp.status_code == 303, resp.text def messages(kind: str | None = None) -> list[MailMessage]: with Session(db.get_engine()) as s: stmt = select(MailMessage).order_by(MailMessage.id) if kind: stmt = stmt.where(MailMessage.kind == kind) rows = list(s.scalars(stmt)) for row in rows: s.expunge(row) return rows def content(row: MailMessage) -> dict[str, Any]: found = outbox.content_of(get_settings().secret_key.get_secret_value(), row) assert found is not None return dict(found) class FakeRelay: """Ersetzt smtp.Connection; merkt sich, was gesendet wurde.""" sent: ClassVar[list[EmailMessage]] = [] fail_connect: ClassVar[Exception | None] = None fail_send: ClassVar[Exception | None] = None def __init__(self, cfg: Any, password: str) -> None: self.password = password def __enter__(self) -> FakeRelay: if FakeRelay.fail_connect is not None: raise FakeRelay.fail_connect return self def send(self, msg: EmailMessage) -> None: if FakeRelay.fail_send is not None: raise FakeRelay.fail_send FakeRelay.sent.append(msg) def __exit__(self, *args: object) -> None: return None @pytest.fixture def relay(monkeypatch: pytest.MonkeyPatch) -> type[FakeRelay]: FakeRelay.sent = [] FakeRelay.fail_connect = None FakeRelay.fail_send = None monkeypatch.setattr(smtp, "Connection", FakeRelay) return FakeRelay def run_queue(at: datetime | None = None) -> int: settings = get_settings() return outbox.process_due(db.get_engine(), settings.secret_key.get_secret_value(), settings.public_host, at or datetime.now(UTC) + timedelta(seconds=1)) # -------------------------------------------------------------------------- # Einstellungen # -------------------------------------------------------------------------- def test_settings_store_password_encrypted(app: Any) -> None: client = admin(app) page = client.get("/admin/mail").text assert "No SMTP relay is set up yet" in page configure(client) with Session(db.get_engine()) as s: row = s.get(AppSetting, "mail") assert row is not None assert "relay-geheim" not in str(row.value) cfg = mail_config.load(s) assert cfg.password(get_settings().secret_key.get_secret_value()) == "relay-geheim" events = list(s.scalars(select(AuditEvent).where( AuditEvent.action == "admin.mail_settings_changed"))) assert events and "relay-geheim" not in str(events[0].details) assert "@" not in str(events[0].details) # keine Adressen im Protokoll page = client.get("/admin/mail").text assert "relay-geheim" not in page and "No SMTP relay" not in page # Ohne neues Passwort bleibt das alte csrf = token_for(client, "/admin/mail") client.post("/admin/mail", data={"csrf_token": csrf, **RELAY, "password": ""}) with Session(db.get_engine()) as s: assert mail_config.load(s).has_password def test_invalid_settings_are_refused(app: Any) -> None: client = admin(app) csrf = token_for(client, "/admin/mail") resp = client.post("/admin/mail", data={"csrf_token": csrf, **RELAY, "from_address": "x@y\r\nBcc: z@example.org"}) assert resp.status_code == 400 def test_test_mail_reports_errors(app: Any, relay: type[FakeRelay]) -> None: client = admin(app) configure(client) csrf = token_for(client, "/admin/mail") # send_now baut seine eigene Verbindung über smtp.Connection (hier: FakeRelay) resp = client.post("/admin/mail/test", data={"csrf_token": csrf, "to": ""}) assert resp.status_code == 200 assert "has been sent to admin@example.de" in resp.text assert relay.sent and relay.sent[0]["To"] == "admin@example.de" assert relay.sent[0]["Reply-To"] == "team@example.org" relay.fail_connect = smtplib.SMTPAuthenticationError(535, b"auth failed") csrf = token_for(client, "/admin/mail") resp = client.post("/admin/mail/test", data={"csrf_token": csrf, "to": ""}) assert "535 auth failed" in resp.text with Session(db.get_engine()) as s: tests = list(s.scalars(select(AuditEvent).where(AuditEvent.action == "admin.mail_test"))) assert [e.details for e in tests] == [{"ok": True}, {"ok": False}] # -------------------------------------------------------------------------- # Warteschlange und Versand # -------------------------------------------------------------------------- def forgot(client: TestClient, email: str) -> Any: csrf = token_for(client, "/forgot") return client.post("/forgot", data={"csrf_token": csrf, "email": email}) def test_forgot_password_answers_the_same(app: Any) -> None: make_user(Role.PARTICIPANT, "anna@example.de") known = forgot(new_client(app), "anna@example.de") unknown = forgot(new_client(app), "nobody@example.de") assert known.status_code == unknown.status_code == 200 # Seiten gleich bis auf den CSRF-Wert (Meta-Feld, jeder Besucher hat seinen eigenen) def without_token(html: str) -> str: return re.sub(r"[0-9a-f]{40,}", "", html) assert without_token(known.text) == without_token(unknown.text) (mail,) = messages("password_reset") assert mail.recipient == "anna@example.de" and mail.status == "queued" text = content(mail)["text"] link = next(w for w in text.split() if "/setup/" in w) assert new_client(app).get(link.replace(get_settings().public_origin, "")).status_code == 200 # Inhalt liegt nur verschlüsselt in der Datenbank assert mail.content_enc is not None and b"/setup/" not in mail.content_enc def test_forgot_password_is_rate_limited(app: Any) -> None: make_user(Role.PARTICIPANT, "anna@example.de") for _ in range(5): forgot(new_client(app), "anna@example.de") assert len(messages("password_reset")) == 3 def test_queue_waits_without_relay_and_sends_later(app: Any, relay: type[FakeRelay]) -> None: make_user(Role.PARTICIPANT, "anna@example.de") forgot(new_client(app), "anna@example.de") assert run_queue() == 0 and messages()[0].status == "queued" configure(admin(app)) assert run_queue() == 1 (mail,) = messages("password_reset") assert mail.status == "sent" and mail.content_enc is None and mail.sent_at is not None sent = relay.sent[0] assert sent["To"] == "anna@example.de" assert sent["From"] == "Surveybox Test " assert "/setup/" in sent.get_body(("plain",)).get_content() def test_retry_and_permanent_failure(app: Any, relay: type[FakeRelay]) -> None: configure(admin(app)) make_user(Role.PARTICIPANT, "anna@example.de") forgot(new_client(app), "anna@example.de") relay.fail_connect = smtplib.SMTPServerDisconnected("gone") now = datetime.now(UTC) + timedelta(seconds=1) assert run_queue(now) == 0 (mail,) = messages("password_reset") assert mail.status == "queued" and mail.attempts == 1 and "gone" in (mail.last_error or "") assert mail.next_attempt_at > now # Vor der nächsten Fälligkeit passiert nichts relay.fail_connect = None assert run_queue(now) == 0 relay.fail_send = smtp.PermanentError("550 no such user") assert run_queue(now + timedelta(minutes=2)) == 0 (mail,) = messages("password_reset") assert mail.status == "failed" and mail.content_enc is None def test_invite_by_mail(app: Any) -> None: client = admin(app) csrf = token_for(client, "/admin/users/new") resp = client.post("/admin/users/new", data={ "csrf_token": csrf, "email": "neu@example.de", "display_name": "Neu", "role": "participant", "send_mail": "on"}) assert resp.status_code == 303 and "invite_sent" in resp.headers["location"] (mail,) = messages("invite") assert mail.recipient == "neu@example.de" assert "/setup/" in content(mail)["text"] # -------------------------------------------------------------------------- # Benachrichtigungen # -------------------------------------------------------------------------- def comment(client: TestClient, token: str, body: str) -> Any: csrf = token_for(client, f"/f/{token}") return client.post(f"/f/{token}/comments", data={"csrf_token": csrf, "body": body}) def test_comment_notifies_owner_and_one_click_unsubscribe(app: Any) -> None: carla = creator(app) _, token, _, _ = slot_form(carla, comments_notify="on") paul = participant(app) assert comment(paul, token, "Gibt es Parkplätze?").status_code == 303 (mail,) = messages("comment_new") assert mail.recipient == "carla@example.de" data = content(mail) assert "Parkplätze" not in data["text"] # nur Links, keine Inhalte unsubscribe = data["headers"]["List-Unsubscribe"].strip("<>") assert data["headers"]["List-Unsubscribe-Post"] == "List-Unsubscribe=One-Click" # Ein-Klick-Abmeldung des Mailprogramms: ohne Cookies und ohne CSRF-Feld path = unsubscribe.replace(get_settings().public_origin, "") assert new_client(app).get(path).status_code == 200 # GET ändert nichts resp = TestClient(app).post(path, data={"List-Unsubscribe": "One-Click"}) assert resp.status_code == 200 with Session(db.get_engine()) as s: user = s.scalar(select(UserAccount).where(UserAccount.email == "carla@example.de")) assert user is not None and user.notify_prefs.get("comment_new") is False comment(paul, token, "Und Getränke?") assert len(messages("comment_new")) == 1 def test_waitlist_promotion_and_booked_up_mails(app: Any) -> None: carla = creator(app) _, token, qid, (early, late) = slot_form(carla, waitlist=True) anna = participant(app, "anna2@example.de") bert = participant(app, "bert@example.de") assert fill(anna, token, {f"q{qid}": early}).status_code == 303 assert [m.recipient for m in messages("slot_full")] == ["carla@example.de"] assert [m.recipient for m in messages("participation")] == ["anna2@example.de"] assert fill(bert, token, {f"q{qid}": early}).status_code == 303 assert messages("promoted") == [] # Anna wechselt: Bert rückt nach und bekommt genau eine Mail assert fill(anna, token, {f"q{qid}": late}, path="/edit").status_code == 303 (mail,) = messages("promoted") assert mail.recipient == "bert@example.de" assert "Früh" in content(mail)["text"] def test_no_participant_mails_for_anonymous_forms(app: Any) -> None: carla = creator(app) _, token, qid, (early, _) = slot_form(carla, anonymous="on") paul = participant(app) assert fill(paul, token, {f"q{qid}": early}).status_code == 303 assert messages("participation") == [] def test_notification_settings_page(app: Any) -> None: paul = participant(app) csrf = token_for(paul, "/account/notifications") resp = paul.post("/account/notifications", data={"csrf_token": csrf, "event_promoted": "on"}) assert resp.status_code == 303 with Session(db.get_engine()) as s: user = s.scalar(select(UserAccount).where(UserAccount.email == "paul@example.de")) assert user is not None assert user.notify_prefs["promoted"] is True assert user.notify_prefs["participation"] is False