fix:deadlock und doppelte Mails
CI / audit (push) Skipped
CI / checks (push) Failing after 3m21s
CI / image (push) Skipped

This commit is contained in:
marco.morath committed 2026-11-25 22:15:34 +01:00
1 parent b1531e41e1
commit 8b6f74f364
13 files changed
+69 -27

No files matched your search

+4 -1
View File
@@ -57,7 +57,10 @@ def _capacity(question: Question, option_id: str) -> int | None:
def _lock(db: Session, question: Question) -> None: def _lock(db: Session, question: Question) -> None:
db.execute(select(Question.id).where(Question.id == question.id).with_for_update()) # FOR NO KEY UPDATE: sperrt gleichzeitige Buchungen gegeneinander, aber nicht gegen
# Fremdschlüssel-Prüfungen (Antworten auf diese Frage); FOR UPDATE führte zu Deadlocks
db.execute(select(Question.id).where(Question.id == question.id)
.with_for_update(key_share=True))
def _counts(db: Session, question: Question) -> dict[tuple[str, str], int]: def _counts(db: Session, question: Question) -> dict[tuple[str, str], int]:
+4 -2
View File
@@ -737,8 +737,10 @@ def apply_proposals(
errors[question.id] = "proposal_invalid" errors[question.id] = "proposal_invalid"
continue continue
option = {"id": types.new_option_id(), "label": text} option = {"id": types.new_option_id(), "label": text}
# Frage sperren: gleichzeitige Vorschläge überschreiben sich nicht # Frage sperren: gleichzeitige Vorschläge überschreiben sich nicht (FOR NO KEY
db.execute(select(Question.id).where(Question.id == question.id).with_for_update()) # UPDATE, damit Fremdschlüssel-Prüfungen nicht blockieren, vgl. booking._lock)
db.execute(select(Question.id).where(Question.id == question.id)
.with_for_update(key_share=True))
db.refresh(question) db.refresh(question)
options = list(question.config.get("options") or []) options = list(question.config.get("options") or [])
if len(options) >= types.MAX_OPTIONS: if len(options) >= types.MAX_OPTIONS:
+4 -2
View File
@@ -91,8 +91,10 @@ def enqueue(
) )
if dedupe_key is not None: if dedupe_key is not None:
stmt = stmt.on_conflict_do_nothing(index_elements=[MailMessage.dedupe_key]) stmt = stmt.on_conflict_do_nothing(index_elements=[MailMessage.dedupe_key])
result = db.execute(stmt) # RETURNING statt rowcount: Bei Inserts über die ORM-Sitzung meldet SQLAlchemy 2.1
return bool(result.rowcount) # type: ignore[attr-defined] # die Zeilenzahl nicht zuverlässig (-1), dann käme jede Mail scheinbar neu hinzu
inserted = db.execute(stmt.returning(MailMessage.id)).first()
return inserted is not None
# -------------------------------------------------------------------------- # --------------------------------------------------------------------------
+13
View File
@@ -32,6 +32,8 @@ def db_settings(tmp_path, monkeypatch: pytest.MonkeyPatch): # type: ignore[no-u
from surveybox import settings as settings_mod from surveybox import settings as settings_mod
monkeypatch.setenv("SURVEYBOX_DATA_DIR", str(tmp_path / "data")) monkeypatch.setenv("SURVEYBOX_DATA_DIR", str(tmp_path / "data"))
# Tests prüfen englische Texte; ohne Kontosprache gilt die Standardsprache
monkeypatch.setenv("SURVEYBOX_DEFAULT_LANGUAGE", "en")
settings_mod.get_settings.cache_clear() settings_mod.get_settings.cache_clear()
db.get_engine.cache_clear() db.get_engine.cache_clear()
engine = db.get_engine() engine = db.get_engine()
@@ -60,3 +62,14 @@ def client(app): # type: ignore[no-untyped-def]
with new_client(app) as c: with new_client(app) as c:
yield c yield c
@pytest.fixture(autouse=True)
def _english_texts(): # type: ignore[no-untyped-def]
"""Texte außerhalb von Anfragen (Funktionen direkt aufgerufen) auf Englisch,
auch wenn in der CI die Übersetzungen kompiliert sind."""
from surveybox import i18n
token = i18n.set_language("en")
yield
i18n.reset_language(token)
+2 -1
View File
@@ -90,7 +90,8 @@ def test_deletion_needs_recent_sign_in(app: Any) -> None:
assert "sign in again" in page assert "sign in again" in page
assert post_delete(paul, "/account/delete", confirm="on").status_code == 403 assert post_delete(paul, "/account/delete", confirm="on").status_code == 403
assert user_by_email("paul@example.de") is not None assert user_by_email("paul@example.de") is not None
resp = post_delete(paul, "/logout", next="/account/delete") csrf = token_for(paul, "/account")
resp = paul.post("/logout", data={"csrf_token": csrf, "next": "/account/delete"})
assert resp.headers["location"] == "/login?next=/account/delete" assert resp.headers["location"] == "/login?next=/account/delete"
+1 -1
View File
@@ -52,7 +52,7 @@ def test_lists_filters_and_summary(app: Any) -> None:
# Teilnehmerliste: Früh mit Bernd, Carla auf der Warteliste; Spät mit Paul # Teilnehmerliste: Früh mit Bernd, Carla auf der Warteliste; Spät mit Paul
assert "Bernd Krause" in page and "Carla Kurz" in page and "Paul Peters" in page assert "Bernd Krause" in page and "Carla Kurz" in page and "Paul Peters" in page
filtered = carla.get(f"/forms/{pid}/responses?answer={slot_q}:{options[1]}").text filtered = carla.get(f"/forms/{pid}/responses?answer={slot_q}:{options[1]}").text
assert "1 of 3 answers match the filter" in filtered assert "1 of 3 answer matches the filter" in filtered
assert "Paul Peters" in filtered and "Bernd Krause" not in filtered assert "Paul Peters" in filtered and "Bernd Krause" not in filtered
tomorrow = (datetime.now(UTC) + timedelta(days=1)).date().isoformat() tomorrow = (datetime.now(UTC) + timedelta(days=1)).date().isoformat()
assert "0 of 3 answers" in carla.get(f"/forms/{pid}/responses?from={tomorrow}").text assert "0 of 3 answers" in carla.get(f"/forms/{pid}/responses?from={tomorrow}").text
+1 -1
View File
@@ -376,7 +376,7 @@ def test_closed_form(app: Any) -> None:
guest = new_client(app) guest = new_client(app)
page = guest.get(f"/f/{token}") page = guest.get(f"/f/{token}")
assert "This form is closed" in page.text assert "This form is closed" in page.text
csrf = token_for(guest, f"/f/{token}") csrf = token_for(guest, "/login") # die Seite des beendeten Formulars hat kein Formular
guest.post(f"/f/{token}", data={"csrf_token": csrf, f"q{q_name}": "Zu spät"}) guest.post(f"/f/{token}", data={"csrf_token": csrf, f"q{q_name}": "Zu spät"})
assert response_count(pid) == 0 assert response_count(pid) == 0
+2 -1
View File
@@ -42,7 +42,8 @@ def path_of(url: str) -> str:
def links_in(text: str, part: str) -> list[str]: def links_in(text: str, part: str) -> list[str]:
return [path_of(u) for u in re.findall(r"https?://\S+", text) if part in u] 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]]: def guest_form(app: Any, **settings: Any) -> tuple[str, int, list[str]]:
+6 -2
View File
@@ -4,6 +4,7 @@ Passwort vergessen, Einladungen, Benachrichtigungen, Abmelden (CI)."""
from __future__ import annotations from __future__ import annotations
import re
import smtplib import smtplib
from datetime import UTC, datetime, timedelta from datetime import UTC, datetime, timedelta
from email.message import EmailMessage from email.message import EmailMessage
@@ -179,8 +180,11 @@ def test_forgot_password_answers_the_same(app: Any) -> None:
known = forgot(new_client(app), "anna@example.de") known = forgot(new_client(app), "anna@example.de")
unknown = forgot(new_client(app), "nobody@example.de") unknown = forgot(new_client(app), "nobody@example.de")
assert known.status_code == unknown.status_code == 200 assert known.status_code == unknown.status_code == 200
assert known.text.replace(csrf_from(known.text), "") == unknown.text.replace( # Seiten gleich bis auf den CSRF-Wert (Meta-Feld, jeder Besucher hat seinen eigenen)
csrf_from(unknown.text), "") 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") (mail,) = messages("password_reset")
assert mail.recipient == "anna@example.de" and mail.status == "queued" assert mail.recipient == "anna@example.de" and mail.status == "queued"
text = content(mail)["text"] text = content(mail)["text"]
+1 -1
View File
@@ -52,7 +52,7 @@ def test_edit_preview_and_use_template(app: Any) -> None:
url = f"/admin/mail/templates/password_reset?lang={language}" url = f"/admin/mail/templates/password_reset?lang={language}"
root.post("/admin/mail/templates/password_reset/reset", root.post("/admin/mail/templates/password_reset/reset",
data={"csrf_token": token_for(root, url), "language": language}) data={"csrf_token": token_for(root, url), "language": language})
assert "own text" not in root.get("/admin/mail/templates").text assert "status-open" not in root.get("/admin/mail/templates").text
def test_unknown_kind_and_rights(app: Any) -> None: def test_unknown_kind_and_rights(app: Any) -> None:
+2 -1
View File
@@ -171,7 +171,8 @@ def test_poll_votes_proposal_results_and_calendar(app: Any) -> None:
options = options_of(qid) options = options_of(qid)
assert len(options) == 3 and options[-1]["proposed"] and options[-1]["date"] == "2026-07-15" assert len(options) == 3 and options[-1]["proposed"] and options[-1]["date"] == "2026-07-15"
thanks = guest.get(f"/f/{token}/thanks").text thanks = guest.get(f"/f/{token}/thanks").text
assert 'class="poll-result"' in thanks assert f"/f/{token}/results" in thanks
assert 'class="poll-result"' in guest.get(f"/f/{token}/results").text
other = new_client(app) other = new_client(app)
votes = {f"q{qid}_{o['id']}": "no" for o in options} votes = {f"q{qid}_{o['id']}": "no" for o in options}
+27 -13
View File
@@ -18,7 +18,6 @@ import pytest
pytest.importorskip("fastapi") pytest.importorskip("fastapi")
from fastapi.routing import APIRoute
from helpers import PASSWORD, login, new_client, token_for from helpers import PASSWORD, login, new_client, token_for
from test_forms import creator, participant, simple_form from test_forms import creator, participant, simple_form
from test_mail import admin from test_mail import admin
@@ -35,28 +34,43 @@ PROTECTED_PREFIXES = ("/admin", "/forms", "/account")
DUMMY_ID = "00000000-0000-0000-0000-000000000000" DUMMY_ID = "00000000-0000-0000-0000-000000000000"
def _routes(app: Any) -> list[APIRoute]: def _routes(app: Any) -> list[tuple[str, Any]]:
return [r for r in app.routes if isinstance(r, APIRoute)] """(voller Pfad, Endpunkt) für alle Endpunkte, auch in eingebundenen Routern."""
found: list[tuple[str, Any]] = []
def walk(routes: Any, prefix: str) -> None:
for route in routes:
path = getattr(route, "path", "") or ""
full = path if path.startswith(prefix) else prefix + path
sub = getattr(route, "routes", None)
if sub and not getattr(route, "methods", None):
walk(sub, full)
elif getattr(route, "methods", None) and getattr(route, "dependant", None):
found.append((full, route))
walk(app.routes, "")
return found
def _fill(route: APIRoute) -> str: def _fill(path: str, route: Any) -> str:
"""Pfad mit Platzhalter-Werten passenden Typs (Zahl oder UUID-Text).""" """Pfad mit Platzhalter-Werten passenden Typs (Zahl oder UUID-Text)."""
kinds = {p.name: p.field_info.annotation for p in route.dependant.path_params} kinds = {p.name: p.field_info.annotation for p in route.dependant.path_params}
return re.sub(r"\{([^}:]+)[^}]*\}", return re.sub(r"\{([^}:]+)[^}]*\}",
lambda m: "1" if kinds.get(m.group(1)) is int else DUMMY_ID, route.path) lambda m: "1" if kinds.get(m.group(1)) is int else DUMMY_ID, path)
def test_every_post_route_checks_csrf(app: Any) -> None: def test_every_post_route_checks_csrf(app: Any) -> None:
from surveybox.web.deps import verify_csrf from surveybox.web.deps import verify_csrf
missing = [] missing = []
for route in _routes(app): for full, route in _routes(app):
if not route.methods & {"POST", "PUT", "PATCH", "DELETE"}: if not set(route.methods) & {"POST", "PUT", "PATCH", "DELETE"}:
continue continue
deps = {d.call for d in route.dependant.dependencies} deps = {d.call for d in route.dependant.dependencies}
if verify_csrf not in deps and route.path not in CSRF_EXEMPT: if verify_csrf not in deps and full not in CSRF_EXEMPT:
missing.append(route.path) missing.append(full)
assert missing == [], f"POST ohne CSRF-Prüfung: {missing}" assert missing == [], f"POST ohne CSRF-Prüfung: {missing}"
assert sum(1 for _, r in _routes(app) if "POST" in r.methods) > 40 # wirklich erfasst
# Und wirklich: angemeldet, aber ohne Token wird abgewiesen # Und wirklich: angemeldet, aber ohne Token wird abgewiesen
root = admin(app) root = admin(app)
for path in ("/admin/appearance", "/forms", "/logout"): for path in ("/admin/appearance", "/forms", "/logout"):
@@ -67,15 +81,15 @@ def test_protected_pages_need_login_and_rights(app: Any) -> None:
guest = new_client(app) guest = new_client(app)
paul = participant(app) paul = participant(app)
checked = 0 checked = 0
for route in _routes(app): for full, route in _routes(app):
if "GET" not in route.methods or not route.path.startswith(PROTECTED_PREFIXES): if "GET" not in route.methods or not full.startswith(PROTECTED_PREFIXES):
continue continue
path = _fill(route) path = _fill(full, route)
resp = guest.get(path) resp = guest.get(path)
assert resp.status_code in (303, 401, 403, 404), (path, resp.status_code) assert resp.status_code in (303, 401, 403, 404), (path, resp.status_code)
if resp.status_code == 303: if resp.status_code == 303:
assert resp.headers["location"].startswith("/login"), path assert resp.headers["location"].startswith("/login"), path
if route.path.startswith("/admin"): if full.startswith("/admin"):
denied = paul.get(path) denied = paul.get(path)
assert denied.status_code in (303, 403, 404), path assert denied.status_code in (303, 403, 404), path
if denied.status_code == 303: if denied.status_code == 303:
+2 -1
View File
@@ -79,4 +79,5 @@ def test_language_cookie_and_safe_redirect(client: TestClient) -> None:
def test_unknown_language_sets_no_cookie(client: TestClient) -> None: def test_unknown_language_sets_no_cookie(client: TestClient) -> None:
resp = client.get("/language/xx", follow_redirects=False) resp = client.get("/language/xx", follow_redirects=False)
assert resp.status_code == 303 assert resp.status_code == 303
assert "set-cookie" not in resp.headers cookies = resp.headers.get_list("set-cookie")
assert not any(c.startswith("surveybox_lang=") for c in cookies)