Files
marco.morath f18298d07f
CI / audit (push) Skipped
CI / checks (push) Failing after 3m22s
CI / image (push) Skipped
fix:routen2
2026-11-25 22:32:38 +01:00

282 lines
12 KiB
Python

# SPDX-License-Identifier: AGPL-3.0-or-later
"""Phase 6b gegen PostgreSQL: Gäste, persönliche Links, Double-Opt-in,
Meine Links anfordern, Selbstregistrierung (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 (
add_question,
create_form,
creator,
fill,
form_row,
question_ids,
save_settings,
set_status,
)
from test_mail import admin, content, messages
from test_phase5 import bookings, slot_form
from surveybox import db
from surveybox.forms import guests
from surveybox.models import GuestContact, Response, UserAccount
from surveybox.settings import get_settings
pytestmark = pytest.mark.db
def path_of(url: str) -> str:
return url.replace(get_settings().public_origin, "")
def links_in(text: str, part: str) -> list[str]:
found = [path_of(u) for u in re.findall(r"https?://[^\s\"'<>]+", text) if part in u]
return list(dict.fromkeys(found)) # dieselbe Adresse als Link und als Text: einmal
def guest_form(app: Any, **settings: Any) -> tuple[str, int, list[str]]:
carla = creator(app)
_, token, qid, options = slot_form(carla, **{"guest_email": "optional", **settings})
return token, qid, options
def responses() -> list[Response]:
with Session(db.get_engine()) as s:
rows = list(s.scalars(select(Response).order_by(Response.id)))
for row in rows:
s.expunge(row)
return rows
def contact(email: str) -> GuestContact | None:
with Session(db.get_engine()) as s:
found = s.scalar(select(GuestContact).where(GuestContact.email == email))
if found is not None:
s.expunge(found)
return found
# --------------------------------------------------------------------------
# Persönlicher Link
# --------------------------------------------------------------------------
def test_guest_without_email_sees_link_once(app: Any) -> None:
token, qid, (early, _) = guest_form(app)
guest = new_client(app)
assert fill(guest, token, {f"q{qid}": early}).status_code == 303
(response,) = responses()
assert response.user_id is None and response.access_hash is not None
assert response.guest_contact_id is None
page = guest.get(f"/f/{token}/thanks").text
(link,) = links_in(page, "/r/")
assert "/r/" in link
# Nur einmal angezeigt
assert "/r/" not in guest.get(f"/f/{token}/thanks").text
view = new_client(app).get(link)
assert view.status_code == 200 and "Früh" in view.text
assert messages("guest_receipt") == [] # ohne Adresse keine Mail
def test_guest_with_email_gets_receipt_and_confirms(app: Any) -> None:
token, qid, (early, _) = guest_form(app)
guest = new_client(app)
resp = fill(guest, token, {f"q{qid}": early, "guest_email": "Gast@Example.de"})
assert resp.status_code == 303
(mail,) = messages("guest_receipt")
assert mail.recipient == "gast@example.de" and mail.user_id is None
text = content(mail)["text"]
(link,) = links_in(text, "/r/")
(confirm,) = links_in(text, "/g/confirm/")
found = contact("gast@example.de")
assert found is not None and found.confirmed_at is None
# Bestätigen: GET ändert nichts, erst der Knopf
other = new_client(app)
page = other.get(confirm)
assert page.status_code == 200
assert contact("gast@example.de").confirmed_at is None # type: ignore[union-attr]
csrf = re.search(r'name="csrf_token" value="([0-9a-f]+)"', page.text).group(1) # type: ignore[union-attr]
assert other.post(confirm, data={"csrf_token": csrf}).status_code == 200
assert contact("gast@example.de").confirmed_at is not None # type: ignore[union-attr]
assert new_client(app).get(confirm).status_code == 404 # nur einmal
assert new_client(app).get(link).status_code == 200
def test_address_from_email_question(app: Any) -> None:
carla = creator(app)
pid = create_form(carla)
add_question(carla, pid, "email", label="Ihre E-Mail-Adresse")
assert save_settings(carla, pid, access="link", guest_email="question").status_code == 303
assert set_status(carla, pid, "open").status_code == 303
(qid,) = question_ids(pid)
token = form_row(pid).share_token
page = new_client(app).get(f"/f/{token}").text
assert 'name="guest_email"' not in page and "personal link" in page
guest = new_client(app)
assert fill(guest, token, {f"q{qid}": "Gast@Example.de"}).status_code == 303
(mail,) = messages("guest_receipt")
assert mail.recipient == "gast@example.de"
link = links_in(content(mail)["text"], "/r/")[0]
# Neue Adresse über den persönlichen Link: neue Bestätigung an die neue Adresse
csrf = token_for(guest, f"{link}/edit")
guest.post(f"{link}/edit", data={"csrf_token": csrf, f"q{qid}": "neu@example.de"})
assert [m.recipient for m in messages("guest_receipt")] == ["gast@example.de",
"neu@example.de"]
assert "/g/confirm/" in content(messages("guest_receipt")[1])["text"]
def test_invalid_email_keeps_form(app: Any) -> None:
token, qid, (early, _) = guest_form(app, guest_email="required")
resp = fill(new_client(app), token, {f"q{qid}": early, "guest_email": "kaputt@"})
assert resp.status_code == 400
assert responses() == []
def test_edit_and_delete_with_personal_link(app: Any) -> None:
token, qid, (early, late) = guest_form(app, waitlist=True)
first, second = new_client(app), new_client(app)
fill(first, token, {f"q{qid}": early})
link = links_in(first.get(f"/f/{token}/thanks").text, "/r/")[0]
fill(second, token, {f"q{qid}": early})
assert [b[1] for b in bookings(qid)] == ["confirmed", "waiting"]
# Ändern über den Link: Platz wechseln, der Wartende rückt nach
csrf = token_for(first, f"{link}/edit")
resp = first.post(f"{link}/edit", data={"csrf_token": csrf, f"q{qid}": late})
assert resp.status_code == 303 and resp.headers["location"].endswith("?done=saved")
assert sorted(b[:2] for b in bookings(qid)) == sorted([(early, "confirmed"),
(late, "confirmed")])
# Löschen braucht die Bestätigung
csrf = token_for(first, link)
assert first.post(f"{link}/delete", data={"csrf_token": csrf}).status_code == 400
resp = first.post(f"{link}/delete", data={"csrf_token": csrf, "confirm": "on"})
assert resp.status_code == 200
assert len(responses()) == 1 and [b[0] for b in bookings(qid)] == [early]
assert new_client(app).get(link).status_code == 404
def test_guessing_links_is_limited(app: Any) -> None:
client = new_client(app)
codes = {client.get(f"/r/{'x' * 43}{i}").status_code for i in range(guests.LINK_GUESSES_PER_IP)}
assert codes == {404}
def test_confirmed_guest_is_notified_when_promoted(app: Any) -> None:
token, qid, (early, late) = guest_form(app, waitlist=True)
anna = new_client(app)
fill(anna, token, {f"q{qid}": early, "guest_email": "anna@gast.de"})
anna_link = links_in(anna.get(f"/f/{token}/thanks").text, "/r/")[0]
bert = new_client(app)
fill(bert, token, {f"q{qid}": early, "guest_email": "bert@gast.de"})
# Bert ist noch nicht bestätigt: keine Benachrichtigung
with Session(db.get_engine()) as s:
s.execute(update(GuestContact).where(GuestContact.email == "bert@gast.de")
.values(confirmed_at=datetime.now(UTC)))
s.commit()
csrf = token_for(anna, f"{anna_link}/edit")
anna.post(f"{anna_link}/edit", data={"csrf_token": csrf, f"q{qid}": late})
(mail,) = messages("promoted")
assert mail.recipient == "bert@gast.de"
data = content(mail)
assert "/links" in data["text"]
unsubscribe = path_of(data["headers"]["List-Unsubscribe"].strip("<>"))
one_click = TestClient(app).post(unsubscribe, data={"List-Unsubscribe": "One-Click"})
assert one_click.status_code == 200
assert contact("bert@gast.de").notify is False # type: ignore[union-attr]
def test_request_links_replaces_old_ones(app: Any) -> None:
token, qid, (early, _) = guest_form(app)
guest = new_client(app)
fill(guest, token, {f"q{qid}": early, "guest_email": "gast@example.de"})
old = links_in(guest.get(f"/f/{token}/thanks").text, "/r/")[0]
client = new_client(app)
for address in ("gast@example.de", "nobody@example.de"):
csrf = token_for(client, "/links")
page = client.post("/links", data={"csrf_token": csrf, "email": address})
assert page.status_code == 200 and "If we have answers for this address" in page.text
(mail,) = messages("guest_links")
(new,) = links_in(content(mail)["text"], "/r/")
assert new != old
assert new_client(app).get(old).status_code == 404
assert new_client(app).get(new).status_code == 200
def test_unconfirmed_addresses_are_purged(app: Any) -> None:
token, qid, (early, _) = guest_form(app)
fill(new_client(app), token, {f"q{qid}": early, "guest_email": "gast@example.de"})
with Session(db.get_engine()) as s:
assert guests.purge_unconfirmed(s, datetime.now(UTC)) == 0
assert guests.purge_unconfirmed(s, datetime.now(UTC) + timedelta(days=8)) == 1
s.commit()
(response,) = responses()
assert response.guest_contact_id is None and response.access_hash is not None
# --------------------------------------------------------------------------
# Selbstregistrierung
# --------------------------------------------------------------------------
def register(client: TestClient, email: str, name: str = "Gast Anna") -> Any:
csrf = token_for(client, "/register")
return client.post("/register", data={"csrf_token": csrf, "email": email, "name": name})
def test_registration_for_confirmed_guests(app: Any) -> None:
token, qid, (early, _) = guest_form(app)
guest = new_client(app)
fill(guest, token, {f"q{qid}": early, "guest_email": "anna@gast.de"})
client = new_client(app)
# Unbestätigt: gleiche Antwort, aber keine Mail
assert register(client, "anna@gast.de").status_code == 200
assert messages("register") == []
with Session(db.get_engine()) as s:
s.execute(update(GuestContact).values(confirmed_at=datetime.now(UTC)))
s.commit()
assert register(client, "anna@gast.de").status_code == 200
(mail,) = messages("register")
(link,) = links_in(content(mail)["text"], "/register/")
csrf = token_for(client, link)
resp = client.post(link, data={"csrf_token": csrf, "password": "ein langer und sicherer satz",
"password2": "ein langer und sicherer satz"})
assert resp.status_code == 303 and "registered" in resp.headers["location"]
with Session(db.get_engine()) as s:
user = s.scalar(select(UserAccount).where(UserAccount.email == "anna@gast.de"))
assert user is not None and user.role == "participant"
assert user.email_verified_at is not None
(response,) = s.scalars(select(Response)).all()
assert response.user_id == user.id and response.access_hash is None
assert contact("anna@gast.de") is None
# Zweites Mal: Konto existiert, also kein neuer Link
csrf = token_for(client, link)
again = client.post(link, data={"csrf_token": csrf, "password": "noch ein langer satz hier",
"password2": "noch ein langer satz hier"})
assert again.status_code == 400
register(new_client(app), "anna@gast.de")
assert len(messages("register_exists")) == 1
def test_registration_levels(app: Any) -> None:
client = admin(app)
for level, status in (("off", 404), ("open", 200)):
csrf = token_for(client, "/admin/settings")
client.post("/admin/settings/registration",
data={"csrf_token": csrf, "self_registration": level})
assert new_client(app).get("/register").status_code == status
# Offen: jede Adresse bekommt einen Link
register(new_client(app), "neu@example.de")
assert [m.recipient for m in messages("register")] == ["neu@example.de"]
assert "/register" in new_client(app).get("/login").text