diff --git a/surveybox/forms/booking.py b/surveybox/forms/booking.py index 322bcae..c204aa6 100644 --- a/surveybox/forms/booking.py +++ b/surveybox/forms/booking.py @@ -57,7 +57,10 @@ def _capacity(question: Question, option_id: str) -> int | 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]: diff --git a/surveybox/forms/service.py b/surveybox/forms/service.py index d028687..525eed9 100644 --- a/surveybox/forms/service.py +++ b/surveybox/forms/service.py @@ -737,8 +737,10 @@ def apply_proposals( errors[question.id] = "proposal_invalid" continue option = {"id": types.new_option_id(), "label": text} - # Frage sperren: gleichzeitige Vorschläge überschreiben sich nicht - db.execute(select(Question.id).where(Question.id == question.id).with_for_update()) + # Frage sperren: gleichzeitige Vorschläge überschreiben sich nicht (FOR NO KEY + # 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) options = list(question.config.get("options") or []) if len(options) >= types.MAX_OPTIONS: diff --git a/surveybox/mail/outbox.py b/surveybox/mail/outbox.py index 878256a..3bbe216 100644 --- a/surveybox/mail/outbox.py +++ b/surveybox/mail/outbox.py @@ -91,8 +91,10 @@ def enqueue( ) if dedupe_key is not None: stmt = stmt.on_conflict_do_nothing(index_elements=[MailMessage.dedupe_key]) - result = db.execute(stmt) - return bool(result.rowcount) # type: ignore[attr-defined] + # RETURNING statt rowcount: Bei Inserts über die ORM-Sitzung meldet SQLAlchemy 2.1 + # 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 # -------------------------------------------------------------------------- diff --git a/tests/conftest.py b/tests/conftest.py index 5663a01..5717df9 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -32,6 +32,8 @@ def db_settings(tmp_path, monkeypatch: pytest.MonkeyPatch): # type: ignore[no-u from surveybox import settings as settings_mod 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() db.get_engine.cache_clear() engine = db.get_engine() @@ -60,3 +62,14 @@ def client(app): # type: ignore[no-untyped-def] with new_client(app) as 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) diff --git a/tests/test_erasure.py b/tests/test_erasure.py index 37c3b01..50e7028 100644 --- a/tests/test_erasure.py +++ b/tests/test_erasure.py @@ -90,7 +90,8 @@ def test_deletion_needs_recent_sign_in(app: Any) -> None: 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") + csrf = token_for(paul, "/account") + resp = paul.post("/logout", data={"csrf_token": csrf, "next": "/account/delete"}) assert resp.headers["location"] == "/login?next=/account/delete" diff --git a/tests/test_evaluation.py b/tests/test_evaluation.py index 909f066..e16ac05 100644 --- a/tests/test_evaluation.py +++ b/tests/test_evaluation.py @@ -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 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 - 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 tomorrow = (datetime.now(UTC) + timedelta(days=1)).date().isoformat() assert "0 of 3 answers" in carla.get(f"/forms/{pid}/responses?from={tomorrow}").text diff --git a/tests/test_forms.py b/tests/test_forms.py index e8db1ce..50ee78b 100644 --- a/tests/test_forms.py +++ b/tests/test_forms.py @@ -376,7 +376,7 @@ def test_closed_form(app: Any) -> None: guest = new_client(app) page = guest.get(f"/f/{token}") 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"}) assert response_count(pid) == 0 diff --git a/tests/test_guests.py b/tests/test_guests.py index aa46f1d..32704d3 100644 --- a/tests/test_guests.py +++ b/tests/test_guests.py @@ -42,7 +42,8 @@ def path_of(url: str) -> 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]]: diff --git a/tests/test_mail.py b/tests/test_mail.py index 19e1f20..08a58dc 100644 --- a/tests/test_mail.py +++ b/tests/test_mail.py @@ -4,6 +4,7 @@ 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 @@ -179,8 +180,11 @@ def test_forgot_password_answers_the_same(app: Any) -> None: known = forgot(new_client(app), "anna@example.de") unknown = forgot(new_client(app), "nobody@example.de") assert known.status_code == unknown.status_code == 200 - assert known.text.replace(csrf_from(known.text), "") == unknown.text.replace( - csrf_from(unknown.text), "") + # 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"] diff --git a/tests/test_mail_templates.py b/tests/test_mail_templates.py index 9d90aa0..a5eda32 100644 --- a/tests/test_mail_templates.py +++ b/tests/test_mail_templates.py @@ -52,7 +52,7 @@ def test_edit_preview_and_use_template(app: Any) -> None: url = f"/admin/mail/templates/password_reset?lang={language}" root.post("/admin/mail/templates/password_reset/reset", 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: diff --git a/tests/test_phase5.py b/tests/test_phase5.py index 2763faa..8eba508 100644 --- a/tests/test_phase5.py +++ b/tests/test_phase5.py @@ -171,7 +171,8 @@ def test_poll_votes_proposal_results_and_calendar(app: Any) -> None: options = options_of(qid) assert len(options) == 3 and options[-1]["proposed"] and options[-1]["date"] == "2026-07-15" 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) votes = {f"q{qid}_{o['id']}": "no" for o in options} diff --git a/tests/test_security_matrix.py b/tests/test_security_matrix.py index 5c54329..2ea17ba 100644 --- a/tests/test_security_matrix.py +++ b/tests/test_security_matrix.py @@ -18,7 +18,6 @@ import pytest pytest.importorskip("fastapi") -from fastapi.routing import APIRoute from helpers import PASSWORD, login, new_client, token_for from test_forms import creator, participant, simple_form from test_mail import admin @@ -35,28 +34,43 @@ PROTECTED_PREFIXES = ("/admin", "/forms", "/account") DUMMY_ID = "00000000-0000-0000-0000-000000000000" -def _routes(app: Any) -> list[APIRoute]: - return [r for r in app.routes if isinstance(r, APIRoute)] +def _routes(app: Any) -> list[tuple[str, Any]]: + """(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).""" kinds = {p.name: p.field_info.annotation for p in route.dependant.path_params} 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: from surveybox.web.deps import verify_csrf missing = [] - for route in _routes(app): - if not route.methods & {"POST", "PUT", "PATCH", "DELETE"}: + for full, route in _routes(app): + if not set(route.methods) & {"POST", "PUT", "PATCH", "DELETE"}: continue deps = {d.call for d in route.dependant.dependencies} - if verify_csrf not in deps and route.path not in CSRF_EXEMPT: - missing.append(route.path) + if verify_csrf not in deps and full not in CSRF_EXEMPT: + missing.append(full) 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 root = admin(app) 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) paul = participant(app) checked = 0 - for route in _routes(app): - if "GET" not in route.methods or not route.path.startswith(PROTECTED_PREFIXES): + for full, route in _routes(app): + if "GET" not in route.methods or not full.startswith(PROTECTED_PREFIXES): continue - path = _fill(route) + path = _fill(full, route) resp = guest.get(path) assert resp.status_code in (303, 401, 403, 404), (path, resp.status_code) if resp.status_code == 303: assert resp.headers["location"].startswith("/login"), path - if route.path.startswith("/admin"): + if full.startswith("/admin"): denied = paul.get(path) assert denied.status_code in (303, 403, 404), path if denied.status_code == 303: diff --git a/tests/test_web.py b/tests/test_web.py index 49cb7cf..eb9410f 100644 --- a/tests/test_web.py +++ b/tests/test_web.py @@ -79,4 +79,5 @@ def test_language_cookie_and_safe_redirect(client: TestClient) -> None: def test_unknown_language_sets_no_cookie(client: TestClient) -> None: resp = client.get("/language/xx", follow_redirects=False) 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)