Initial Commit: Status Testing
CI / audit (push) Skipped
CI / checks (push) Failing after 37s
CI / image (push) Skipped

This commit is contained in:
marco.morath committed 2026-11-25 18:46:04 +01:00
1 parent 1eff675f05
commit 42dd1f2d4a
286 files changed
+64800 -369

No files matched your search

+62
View File
@@ -0,0 +1,62 @@
# SPDX-License-Identifier: AGPL-3.0-or-later
"""Gemeinsame Test-Hilfen.
Tests mit dem Marker `db` laufen nur, wenn SURVEYBOX_TEST_DB=1 gesetzt ist
und die SURVEYBOX_DB_*-Variablen auf eine Wegwerf-Datenbank zeigen (CI).
Die Datenbank wird dabei geleert!
"""
from __future__ import annotations
import os
import pytest
def pytest_collection_modifyitems(config: pytest.Config, items: list[pytest.Item]) -> None:
if os.environ.get("SURVEYBOX_TEST_DB") == "1":
return
skip = pytest.mark.skip(reason="SURVEYBOX_TEST_DB=1 nicht gesetzt")
for item in items:
if "db" in item.keywords:
item.add_marker(skip)
@pytest.fixture
def db_settings(tmp_path, monkeypatch: pytest.MonkeyPatch): # type: ignore[no-untyped-def]
"""Einstellungen mit leerem Datenverzeichnis und frischem Schema."""
pytest.importorskip("sqlalchemy")
from sqlalchemy import text
from surveybox import db
from surveybox import settings as settings_mod
monkeypatch.setenv("SURVEYBOX_DATA_DIR", str(tmp_path / "data"))
settings_mod.get_settings.cache_clear()
db.get_engine.cache_clear()
engine = db.get_engine()
with engine.begin() as conn:
conn.execute(text(f"DROP SCHEMA IF EXISTS {db.DB_SCHEMA} CASCADE"))
yield settings_mod.get_settings()
engine.dispose()
settings_mod.get_settings.cache_clear()
db.get_engine.cache_clear()
@pytest.fixture
def app(db_settings): # type: ignore[no-untyped-def]
"""Web-Anwendung auf frisch migrierter Datenbank."""
from surveybox import db
from surveybox.upgrade import run_upgrade
from surveybox.web.app import create_app
run_upgrade(db_settings, db.get_engine())
return create_app()
@pytest.fixture
def client(app): # type: ignore[no-untyped-def]
from helpers import new_client
with new_client(app) as c:
yield c
+175
View File
@@ -0,0 +1,175 @@
# SPDX-License-Identifier: AGPL-3.0-or-later
"""Gemeinsame Hilfen für die Web-Tests gegen PostgreSQL."""
from __future__ import annotations
import base64
import hashlib
import json
import os
import re
import struct
import time
from typing import Any
from fastapi.testclient import TestClient
from sqlalchemy.orm import Session
from surveybox import db
from surveybox.accounts import service
from surveybox.models import Role, UserAccount
from surveybox.security import totp
from surveybox.settings import get_settings
PASSWORD = "ein langer und sicherer satz"
ORIGIN = "http://localhost"
RP_ID = "localhost"
def new_client(app: Any) -> TestClient:
return TestClient(
app,
base_url=ORIGIN,
headers={"Origin": ORIGIN, "Accept-Language": "en"},
follow_redirects=False,
)
def csrf_from(html: str) -> str:
match = re.search(r'name="csrf_token" value="([0-9a-f]+)"', html)
assert match, "kein CSRF-Feld auf der Seite"
return match.group(1)
def token_for(client: TestClient, path: str) -> str:
resp = client.get(path)
assert resp.status_code == 200, resp.text
return csrf_from(resp.text)
def make_user(
role: Role = Role.PARTICIPANT, email: str = "anna@example.de", with_totp: bool = False
) -> tuple[UserAccount, str | None]:
settings = get_settings()
with Session(db.get_engine()) as s:
user = service.create_user(s, email, "Anna", role, None)
service.set_password(s, user, PASSWORD)
secret = None
if with_totp:
secret = totp.generate_secret()
code = totp.code_at_step(secret, totp.current_step(time.time()))
service.enable_totp(s, settings, user, secret, code)
s.commit()
s.refresh(user)
s.expunge(user)
return user, secret
def next_totp(secret: str) -> str:
return totp.code_at_step(secret, totp.current_step(time.time()) + 1)
def login(client: TestClient, email: str, password: str = PASSWORD) -> Any:
token = token_for(client, "/login")
return client.post(
"/login", data={"email": email, "password": password, "csrf_token": token, "next": "/"}
)
def post_json(client: TestClient, path: str, body: dict[str, Any], csrf: str) -> Any:
return client.post(path, json=body, headers={"X-CSRF-Token": csrf})
# ---------------------------------------------------------------------------
# Software-Authenticator: erzeugt Passkey-Antworten wie ein Browser
# ---------------------------------------------------------------------------
def b64u(data: bytes) -> str:
return base64.urlsafe_b64encode(data).rstrip(b"=").decode()
def unb64u(value: str) -> bytes:
return base64.urlsafe_b64decode(value + "=" * (-len(value) % 4))
class SoftAuthenticator:
"""ES256-Passkey mit Benutzerprüfung, Attestation "none"."""
def __init__(self, rp_id: str = RP_ID, origin: str = ORIGIN) -> None:
from cryptography.hazmat.primitives.asymmetric import ec
self.rp_id = rp_id
self.origin = origin
self.key = ec.generate_private_key(ec.SECP256R1())
self.credential_id = os.urandom(32)
self.user_handle: bytes | None = None
self.counter = 0
def _rp_hash(self) -> bytes:
return hashlib.sha256(self.rp_id.encode()).digest()
def _cose_key(self) -> bytes:
import cbor2
numbers = self.key.public_key().public_numbers()
return cbor2.dumps(
{1: 2, 3: -7, -1: 1, -2: numbers.x.to_bytes(32, "big"),
-3: numbers.y.to_bytes(32, "big")}
)
def _client_data(self, kind: str, challenge: str) -> bytes:
return json.dumps(
{"type": kind, "challenge": challenge, "origin": self.origin, "crossOrigin": False}
).encode()
def create(self, options: dict[str, Any]) -> dict[str, Any]:
import cbor2
self.user_handle = unb64u(options["user"]["id"])
client_data = self._client_data("webauthn.create", options["challenge"])
flags = 0x01 | 0x04 | 0x40 # Anwesenheit, Benutzerprüfung, Schlüsseldaten
auth_data = (
self._rp_hash()
+ bytes([flags])
+ struct.pack(">I", 0)
+ b"\x00" * 16
+ struct.pack(">H", len(self.credential_id))
+ self.credential_id
+ self._cose_key()
)
attestation = cbor2.dumps({"fmt": "none", "attStmt": {}, "authData": auth_data})
return {
"id": b64u(self.credential_id),
"rawId": b64u(self.credential_id),
"type": "public-key",
"response": {
"clientDataJSON": b64u(client_data),
"attestationObject": b64u(attestation),
"transports": ["internal"],
},
"clientExtensionResults": {},
}
def get(self, options: dict[str, Any]) -> dict[str, Any]:
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import ec
client_data = self._client_data("webauthn.get", options["challenge"])
self.counter += 1
auth_data = self._rp_hash() + bytes([0x01 | 0x04]) + struct.pack(">I", self.counter)
signature = self.key.sign(
auth_data + hashlib.sha256(client_data).digest(), ec.ECDSA(hashes.SHA256())
)
return {
"id": b64u(self.credential_id),
"rawId": b64u(self.credential_id),
"type": "public-key",
"response": {
"clientDataJSON": b64u(client_data),
"authenticatorData": b64u(auth_data),
"signature": b64u(signature),
"userHandle": b64u(self.user_handle) if self.user_handle else None,
},
"clientExtensionResults": {},
}
+224
View File
@@ -0,0 +1,224 @@
# SPDX-License-Identifier: AGPL-3.0-or-later
"""Anmeldung, zweiter Faktor, Verwaltung - durchgespielt gegen PostgreSQL (CI)."""
from __future__ import annotations
import re
import time
import pytest
pytest.importorskip("fastapi")
pytest.importorskip("httpx")
pytest.importorskip("argon2")
from fastapi.testclient import TestClient
from helpers import (
PASSWORD,
csrf_from,
login,
make_user,
new_client,
next_totp,
token_for,
)
from sqlalchemy import select
from sqlalchemy.orm import Session
from surveybox import db
from surveybox.accounts import service
from surveybox.models import AuditEvent, Role, UserAccount
from surveybox.security import totp
from surveybox.settings import Settings, get_settings
pytestmark = pytest.mark.db
# ---------------------------------------------------------------------------
def test_login_logout(client: TestClient) -> None:
make_user()
resp = login(client, "Anna@Example.de")
assert resp.status_code == 303 and resp.headers["location"] == "/"
assert "surveybox_session" in client.cookies
page = client.get("/account")
assert page.status_code == 200 and "anna@example.de" in page.text
out = client.post("/logout", data={"csrf_token": csrf_from(page.text)})
assert out.status_code == 303
after = client.get("/account")
assert after.status_code == 303
assert after.headers["location"].startswith("/login?next=%2Faccount")
def test_wrong_password_and_lockout(client: TestClient) -> None:
make_user()
for _ in range(5):
resp = login(client, "anna@example.de", "falsches passwort!!")
assert resp.status_code == 400
assert "Email or password is wrong" in resp.text
# Jetzt gesperrt: auch das richtige Passwort scheitert mit derselben Meldung
resp = login(client, "anna@example.de")
assert resp.status_code == 400
with Session(db.get_engine()) as s:
user = s.scalar(select(UserAccount).where(UserAccount.email == "anna@example.de"))
assert user is not None and user.locked_until is not None
def test_unknown_user_gets_same_answer(client: TestClient) -> None:
resp = login(client, "niemand@example.de")
assert resp.status_code == 400
assert "Email or password is wrong" in resp.text
def test_csrf_protection(client: TestClient, app) -> None: # type: ignore[no-untyped-def]
make_user()
data = {"email": "anna@example.de", "password": PASSWORD, "next": "/"}
client.get("/login")
assert client.post("/login", data=data).status_code == 403 # ohne Token
token = token_for(client, "/login")
evil = client.post("/login", data={**data, "csrf_token": token},
headers={"Origin": "https://evil.example"})
assert evil.status_code == 403
# Token eines anderen Besuchers passt nicht
with new_client(app) as other:
foreign = token_for(other, "/login")
assert client.post("/login", data={**data, "csrf_token": foreign}).status_code == 403
def test_admin_must_set_up_totp_then_login_with_second_factor(client: TestClient) -> None:
make_user(Role.ADMIN, "admin@example.de")
resp = login(client, "admin@example.de")
assert resp.headers["location"] == "/account?notice=mfa_required_admin"
assert client.get("/admin/users").headers["location"].startswith("/account")
setup = client.get("/account/totp")
assert setup.status_code == 200
sealed = re.search(r'name="sealed" value="([0-9a-f]+)"', setup.text)
secret_text = re.search(r'class="secret"><code>([A-Z2-7 ]+)</code>', setup.text)
assert sealed and secret_text
secret = secret_text.group(1).replace(" ", "")
code = totp.code_at_step(secret, totp.current_step(time.time()))
done = client.post(
"/account/totp",
data={
"sealed": sealed.group(1),
"code": code,
"current_password": PASSWORD,
"csrf_token": csrf_from(setup.text),
},
)
assert done.status_code == 200
codes = re.findall(r"<code>([A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{4})</code>", done.text)
assert len(codes) == 10
assert client.get("/admin/users").status_code == 200
# Abmelden, neu anmelden: jetzt mit zweitem Faktor
client.post("/logout", data={"csrf_token": csrf_from(done.text)})
resp = login(client, "admin@example.de")
assert resp.headers["location"].startswith("/login/mfa")
mfa_page = client.get("/login/mfa")
token = csrf_from(mfa_page.text)
wrong = client.post("/login/mfa", data={"code": "000000", "csrf_token": token, "next": "/"})
assert wrong.status_code == 400
# Derselbe TOTP-Code wie bei der Einrichtung zählt nicht ein zweites Mal
replay = client.post("/login/mfa", data={"code": code, "csrf_token": token, "next": "/"})
assert replay.status_code == 400
ok = client.post("/login/mfa", data={"code": codes[0], "csrf_token": token, "next": "/"})
assert ok.status_code == 303 and ok.headers["location"] == "/"
assert client.get("/admin/users").status_code == 200
# Ein Wiederherstellungscode funktioniert nur einmal
with Session(db.get_engine()) as s:
user = service.find_by_email(s, "admin@example.de")
assert user is not None
settings: Settings = get_settings()
assert service.verify_second_factor(s, settings, user, codes[0]) is None
assert service.verify_second_factor(s, settings, user, codes[1]) == "recovery"
def test_admin_invites_user_who_sets_password( # type: ignore[no-untyped-def]
client: TestClient, app
) -> None:
_, secret = make_user(Role.ADMIN, "admin@example.de", with_totp=True)
assert secret
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": "/"})
form = client.get("/admin/users/new")
assert form.status_code == 200
created = client.post(
"/admin/users/new",
data={"email": "Bob@Example.de", "display_name": "Bob", "role": "creator",
"csrf_token": csrf_from(form.text)},
)
assert created.status_code == 200
link = re.search(r"http://localhost/setup/([A-Za-z0-9_-]+)", created.text)
assert link
with new_client(app) as bob:
page = bob.get(f"/setup/{link.group(1)}")
assert page.status_code == 200
mismatch = bob.post(
f"/setup/{link.group(1)}",
data={"password": PASSWORD, "password2": PASSWORD + "x",
"csrf_token": csrf_from(page.text)},
)
assert mismatch.status_code == 400
done = bob.post(
f"/setup/{link.group(1)}",
data={"password": PASSWORD, "password2": PASSWORD,
"csrf_token": csrf_from(page.text)},
)
assert done.headers["location"] == "/login?notice=setup_done"
# Link ist verbraucht
assert bob.get(f"/setup/{link.group(1)}").status_code == 410
assert login(bob, "bob@example.de").status_code == 303
def test_participant_cannot_open_admin(client: TestClient) -> None:
make_user()
login(client, "anna@example.de")
assert client.get("/admin/users").status_code == 403
assert client.get("/admin/audit").status_code == 403
def test_last_admin_cannot_remove_own_rights(client: TestClient) -> None:
admin, secret = make_user(Role.ADMIN, "admin@example.de", with_totp=True)
assert secret
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": "/"})
page = client.get(f"/admin/users/{admin.public_id}")
resp = client.post(
f"/admin/users/{admin.public_id}",
data={"display_name": "Admin", "role": "participant", "is_active": "on",
"csrf_token": csrf_from(page.text)},
)
assert resp.status_code == 400
with Session(db.get_engine()) as s:
assert service.count_active_admins(s) == 1
def test_audit_log_contains_no_personal_data(client: TestClient) -> None:
make_user()
login(client, "anna@example.de", "falsches passwort!!")
login(client, "anna@example.de")
with Session(db.get_engine()) as s:
events = list(s.scalars(select(AuditEvent)))
assert {e.action for e in events} >= {"auth.login_failed", "auth.login"}
for e in events:
blob = f"{e.target_id} {e.details}"
assert "@" not in blob and "anna" not in blob.lower()
def test_security_headers_on_pages(client: TestClient) -> None:
resp = client.get("/login")
assert "default-src 'self'" in resp.headers["content-security-policy"]
assert resp.headers["x-frame-options"] == "DENY"
assert resp.headers["cache-control"] == "no-store"
assert "surveybox_csrf" in client.cookies
+105
View File
@@ -0,0 +1,105 @@
# SPDX-License-Identifier: AGPL-3.0-or-later
"""Einstellungen > Gestaltung über die Oberfläche (CI)."""
from __future__ import annotations
import io
from typing import Any
import pytest
pytest.importorskip("fastapi")
from helpers import new_client, token_for
from PIL import Image
from test_forms import participant
from test_mail import admin
pytestmark = pytest.mark.db
def png(color: tuple[int, int, int, int] = (31, 95, 174, 255)) -> bytes:
buf = io.BytesIO()
Image.new("RGBA", (300, 100), color).save(buf, "PNG")
return buf.getvalue()
def save(client: Any, **fields: str) -> Any:
data = {"name": "Feuerwehr Test", "mode": "auto", "primary": "#c00000",
"accent": "#ffcc00", "background": "#f6f7f9", "text": "#1c1e21",
"background_default": "on", "text_default": "on", **fields}
return client.post("/admin/appearance",
data={"csrf_token": token_for(client, "/admin/appearance"), **data})
def test_name_colours_and_footer(app: Any) -> None:
root = admin(app)
guest = new_client(app)
assert "/branding/theme.css" not in guest.get("/login").text
resp = save(root, imprint_url="https://fw.example/impressum",
privacy_url="https://fw.example/datenschutz", footer_text="Freiwillige <b>",
welcome="Hallo <i>Welt</i>")
assert resp.status_code == 303 and "settings_saved" in resp.headers["location"]
page = guest.get("/login").text
assert "Sign in · Feuerwehr Test" in page and "/branding/theme.css?v=" in page
assert 'href="https://fw.example/impressum"' in page and "Legal notice" in page
assert "Freiwillige &lt;b&gt;" in page
assert "Hallo &lt;i&gt;Welt&lt;/i&gt;" in guest.get("/").text
css = guest.get("/branding/theme.css")
assert css.status_code == 200 and css.headers["content-type"].startswith("text/css")
assert "--sb-primary:#c00000" in css.text and "--sb-accent:#ffcc00" in css.text
assert "--sb-bg:#f6f7f9" in css.text # Standard angehakt: unverändert
# Gelbe Akzentfarbe: zu wenig Kontrast, Warnung ohne Speicherverbot
assert "accent colour has too little contrast" in root.get("/admin/appearance").text
def test_invalid_input_is_not_saved(app: Any) -> None:
root = admin(app)
resp = save(root, name="", imprint_url="javascript:alert(1)")
assert resp.status_code == 400
assert "Please enter a name" in resp.text and "must start with https://" in resp.text
assert "/branding/theme.css" not in new_client(app).get("/login").text
def test_font_export_import_and_reset(app: Any) -> None:
root = admin(app)
save(root, mode="dark", css=".brand-name { letter-spacing: 1px }")
csrf = token_for(root, "/admin/appearance")
resp = root.post("/admin/appearance/font", data={"csrf_token": csrf},
files={"font": ("x.svg", b"<svg/>", "image/svg+xml")})
assert "error=font" in resp.headers["location"]
csrf = token_for(root, "/admin/appearance")
root.post("/admin/appearance/font", data={"csrf_token": csrf},
files={"font": ("a.woff2", b"wOF2" + b"\0" * 64, "font/woff2")})
guest = new_client(app)
css = guest.get("/branding/theme.css").text
assert "@font-face" in css and "color-scheme:dark" in css and "letter-spacing" in css
assert guest.get("/branding/font").headers["content-type"] == "font/woff2"
csrf = token_for(root, "/admin/settings")
root.post("/admin/settings/logo", data={"csrf_token": csrf},
files={"logo": ("logo.png", png(), "image/png")})
csrf = token_for(root, "/admin/appearance")
root.post("/admin/settings/logo", data={"csrf_token": csrf, "variant": "dark"},
files={"logo": ("dark.png", png((255, 255, 255, 255)), "image/png")})
assert "/branding/logo-dark.png?v=" in guest.get("/login").text
exported = root.get("/admin/appearance/export")
assert exported.status_code == 200 and "surveybox-appearance" in exported.text
# Zurücksetzen, dann Import stellt alles wieder her
csrf = token_for(root, "/admin/appearance")
root.post("/admin/appearance/reset", data={"csrf_token": csrf})
assert "color-scheme:dark" not in guest.get("/branding/theme.css").text
csrf = token_for(root, "/admin/appearance")
resp = root.post("/admin/appearance/import", data={"csrf_token": csrf},
files={"design": ("d.json", exported.content, "application/json")})
assert resp.status_code == 303 and "settings_saved" in resp.headers["location"]
assert "color-scheme:dark" in guest.get("/branding/theme.css").text
csrf = token_for(root, "/admin/appearance")
resp = root.post("/admin/appearance/import", data={"csrf_token": csrf},
files={"design": ("d.json", b'{"format": "x"}', "application/json")})
assert "error=import" in resp.headers["location"]
def test_only_admins(app: Any) -> None:
paul = participant(app)
assert paul.get("/admin/appearance").status_code in (303, 403)
assert new_client(app).get("/admin/appearance/export").status_code in (303, 401, 403)
+80
View File
@@ -0,0 +1,80 @@
# SPDX-License-Identifier: AGPL-3.0-or-later
"""Gestaltung ohne Datenbank: Eingaben prüfen, Kontrast, theme.css, Export und Import."""
from __future__ import annotations
import json
from dataclasses import replace
from pathlib import Path
import pytest
from surveybox import appearance as app
def test_parse_accepts_and_rejects() -> None:
look, errors = app.parse({
"name": " Feuerwehr\nTitisee ", "mode": "dark", "primary": "#C00000",
"imprint_url": "https://fw.example/impressum", "welcome": "Zeile 1\r\nZeile 2\x07",
"css": ".x { color: red }",
})
assert errors == []
assert look.name == "Feuerwehr Titisee" and look.mode == "dark"
assert look.primary == "#c00000" and look.welcome == "Zeile 1\nZeile 2"
bad, errors = app.parse({"name": "", "primary": "red", "privacy_url": "javascript:x",
"imprint_url": "https://x\" onmouseover=1", "mode": "neon",
"footer_text": "x" * 400})
assert errors == ["color", "name", "too_long", "url"]
assert bad.primary == "" and bad.privacy_url == "" and bad.imprint_url == ""
assert bad.mode == "auto" and len(bad.footer_text) == app.MAX_FOOTER
def test_contrast_and_palette() -> None:
assert round(app.contrast("#000000", "#ffffff"), 1) == 21.0
assert app.warnings(app.DEFAULT) == []
keys = [key for key, _ in app.warnings(app.Appearance(primary="#ffee00"))]
assert "button" in keys and "link" in keys
keys = [key for key, _ in app.warnings(app.Appearance(text="#cccccc"))]
assert keys == ["text"]
# Die dunkle Darstellung hellt eine dunkle Primärfarbe auf, bis sie lesbar ist
colors = app.palette(app.Appearance(primary="#202060"))
assert app.contrast(colors.dark["primary"], app.DARK["surface"]) >= 4.5
# Dunkler Hintergrund: Karten nicht weiß, Hinweise lesbar
colors = app.palette(app.Appearance(background="#101820", text="#f0f0f0"))
assert colors.light["surface"] != "#ffffff"
assert app.contrast(colors.light["muted"], colors.light["surface"]) >= 4.5
def test_theme_css_by_mode() -> None:
auto = app.theme_css(app.Appearance(primary="#c00000", css=".x{}"), None)
assert "--sb-primary:#c00000" in auto and "@media (prefers-color-scheme: dark)" in auto
assert auto.rstrip().endswith(".x{}")
light = app.theme_css(app.Appearance(mode="light"), None)
assert "color-scheme:light;" in light and "@media" not in light
dark = app.theme_css(app.Appearance(mode="dark", font_format="woff2"), "/branding/font?v=1")
assert "--sb-bg:#121417" in dark and 'format("woff2")' in dark and "SurveyboxCustom" in dark
def test_save_current_and_font(tmp_path: Path) -> None:
assert app.current(tmp_path) == app.DEFAULT
saved = app.save(tmp_path, app.Appearance(name="Test", primary="#123456"))
assert saved.name == "Test" and saved.version and saved.themed
assert app.font_format(b"wOF2" + b"\0" * 20) == "woff2"
assert app.font_format(b"<svg") is None
with pytest.raises(ValueError):
app.save_font(tmp_path, b"GIF89a")
look = app.save_font(tmp_path, b"wOFF" + b"\0" * 20)
assert look.font_format == "woff" and look.name == "Test"
assert app.remove_font(tmp_path).font_format == ""
def test_export_round_trip() -> None:
look = replace(app.Appearance(name="X", footer_text="F"), version="v9")
data = app.export(look, {"logo": b"\x89PNG", "font": b"wOF2"})
assert "version" not in data["appearance"]
values, files = app.read_export(json.dumps(data).encode())
assert app.parse(values)[0].name == "X" and files == {"logo": b"\x89PNG", "font": b"wOF2"}
for raw in (b"kein json", b"{}", json.dumps({"format": "x"}).encode(),
json.dumps({**data, "files": {"logo": "%%%"}}).encode()):
with pytest.raises(ValueError):
app.read_export(raw)
+83
View File
@@ -0,0 +1,83 @@
# SPDX-License-Identifier: AGPL-3.0-or-later
"""Jede Protokollaktion im Code ist erlaubt (audit.ACTIONS) und hat einen Namen
für die Protokollseite (routes/admin.py: ACTION_NAMES).
Eine nicht erlaubte Aktion löst zur Laufzeit einen Fehler aus (HTTP 500). Der
Test liest nur den Quelltext und braucht keine Datenbank.
"""
from __future__ import annotations
import ast
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent / "surveybox"
def _literal_set(path: Path, name: str) -> set[str]:
tree = ast.parse(path.read_text(encoding="utf-8"))
for node in ast.walk(tree):
targets: list[ast.expr] = []
value: ast.expr | None = None
if isinstance(node, ast.Assign):
targets, value = node.targets, node.value
elif isinstance(node, ast.AnnAssign) and node.value is not None:
targets, value = [node.target], node.value
if any(isinstance(t, ast.Name) and t.id == name for t in targets) and value is not None:
if isinstance(value, ast.Set):
return {e.value for e in value.elts if isinstance(e, ast.Constant)}
if isinstance(value, ast.Dict):
return {k.value for k in value.keys if isinstance(k, ast.Constant)}
raise AssertionError(f"{name} nicht gefunden in {path}")
def _used_actions() -> dict[str, str]:
"""Aktion -> Fundstelle für audit.record(db, "…") und action="…"."""
found: dict[str, str] = {}
for path in ROOT.rglob("*.py"):
tree = ast.parse(path.read_text(encoding="utf-8"))
for node in ast.walk(tree):
if not isinstance(node, ast.Call):
continue
func = node.func
is_record = isinstance(func, ast.Attribute) and func.attr == "record" and (
isinstance(func.value, ast.Name) and func.value.id == "audit"
)
if is_record and len(node.args) >= 2 and isinstance(node.args[1], ast.Constant):
found[str(node.args[1].value)] = f"{path.name}:{node.lineno}"
name = func.attr if isinstance(func, ast.Attribute) else getattr(func, "id", "")
if name not in ("record", "create_link"):
continue
for keyword in node.keywords:
if keyword.arg == "action" and isinstance(keyword.value, ast.Constant):
found[str(keyword.value.value)] = f"{path.name}:{node.lineno}"
# Standardwerte von Parametern namens "action"
for node in ast.walk(tree):
if isinstance(node, ast.FunctionDef):
args = node.args
defaults = dict(zip(
[a.arg for a in args.args][-len(args.defaults):] if args.defaults else [],
args.defaults, strict=False,
))
value = defaults.get("action")
if isinstance(value, ast.Constant):
found[str(value.value)] = f"{path.name}:{node.lineno}"
return found
def test_every_used_action_is_allowed_and_named() -> None:
allowed = _literal_set(ROOT / "accounts" / "audit.py", "ACTIONS")
named = _literal_set(ROOT / "web" / "routes" / "admin.py", "ACTION_NAMES")
used = _used_actions()
assert used, "keine Protokollaktionen gefunden - Test prüft nichts"
missing = {a: where for a, where in used.items() if a not in allowed}
assert not missing, f"nicht in audit.ACTIONS: {missing}"
unnamed = {a: where for a, where in used.items() if a not in named}
assert not unnamed, f"nicht in ACTION_NAMES: {unnamed}"
def test_found_the_new_actions() -> None:
used = _used_actions()
for action in ("admin.mail_settings_changed", "admin.mail_test",
"account.reset_requested", "account.notifications_changed"):
assert action in used
+237
View File
@@ -0,0 +1,237 @@
# SPDX-License-Identifier: AGPL-3.0-or-later
from __future__ import annotations
import os
import socket
import subprocess
from collections.abc import Iterator
from datetime import UTC, datetime
from pathlib import Path
import pytest
from surveybox import backup
# ---------------------------------------------------------------------------
# Reine Hilfsfunktionen
# ---------------------------------------------------------------------------
def _fake_pg_lib(root: Path, versions: list[int]) -> Path:
for v in versions:
bindir = root / str(v) / "bin"
bindir.mkdir(parents=True)
for tool in ("pg_dump", "pg_restore"):
(bindir / tool).write_text("#!/bin/sh\n")
(root / "notaversion").mkdir()
return root
@pytest.mark.parametrize(
("server", "expected"),
[(17, 17), (18, 18), (16, 17), (19, 19)],
)
def test_find_pg_tool_prefers_same_then_next_higher(
tmp_path: Path, server: int, expected: int
) -> None:
root = _fake_pg_lib(tmp_path, [17, 18, 19])
assert backup.find_pg_tool("pg_dump", server, root) == root / str(expected) / "bin/pg_dump"
def test_find_pg_tool_refuses_newer_server(tmp_path: Path) -> None:
root = _fake_pg_lib(tmp_path, [17, 18])
with pytest.raises(backup.BackupError, match="PostgreSQL 19"):
backup.find_pg_tool("pg_dump", 19, root)
def test_backup_filename_sorts_chronologically() -> None:
a = backup.backup_filename("daily", datetime(2026, 1, 2, 3, 4, 5, tzinfo=UTC))
b = backup.backup_filename("daily", datetime(2026, 11, 2, 3, 4, 5, tzinfo=UTC))
assert a == "surveybox-daily-20260102T030405Z.dump"
assert a < b
def test_backup_filename_with_revisions_is_safe() -> None:
name = backup.backup_filename(
"pre-upgrade", datetime(2026, 1, 1, tzinfo=UTC), "0001_initial", "../../evil rev"
)
assert "/" not in name and " " not in name
assert name.startswith("surveybox-pre-upgrade-20260101T000000Z-from-0001_initial-to-")
def test_apply_retention_keeps_newest(tmp_path: Path) -> None:
names = [
backup.backup_filename("daily", datetime(2026, 1, day, tzinfo=UTC)) for day in range(1, 6)
]
for n in names:
(tmp_path / n).write_bytes(b"x")
(tmp_path / "surveybox-daily-20260106T000000Z.dump.partial").write_bytes(b"x")
deleted = backup.apply_retention(tmp_path, keep=2)
assert [p.name for p in deleted] == names[:3]
remaining = sorted(p.name for p in tmp_path.iterdir())
assert names[3] in remaining and names[4] in remaining
assert any(n.endswith(".partial") for n in remaining) # unfertige bleiben unangetastet
def test_subprocess_env_does_not_leak_app_secrets(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setenv("SURVEYBOX_SECRET_KEY", "geheim")
env = backup._subprocess_env({"PGHOST": "db"})
assert "SURVEYBOX_SECRET_KEY" not in env
assert env["PGHOST"] == "db"
# ---------------------------------------------------------------------------
# Gegen ein echtes PostgreSQL (temporärer Cluster oder Test-Datenbank)
# ---------------------------------------------------------------------------
def _free_port() -> int:
with socket.socket() as s:
s.bind(("127.0.0.1", 0))
return int(s.getsockname()[1])
@pytest.fixture(scope="module")
def pg_cluster(tmp_path_factory: pytest.TempPathFactory) -> Iterator[tuple[dict[str, str], int]]:
"""Startet einen Wegwerf-Cluster mit den lokal installierten Werkzeugen."""
versions = backup.available_pg_versions()
initdb = [backup.PG_LIB_ROOT / str(v) / "bin/initdb" for v in versions]
initdb = [p for p in initdb if p.is_file()]
if not initdb:
pytest.skip("kein initdb vorhanden")
if os.geteuid() == 0:
pytest.skip("PostgreSQL startet nicht als root")
bindir = initdb[-1].parent
major = int(bindir.parent.name)
base = tmp_path_factory.mktemp("pg")
data, sock = base / "data", base / "sock"
sock.mkdir()
subprocess.run(
[str(bindir / "initdb"), "-D", str(data), "-U", "test", "--auth=trust", "-E", "UTF8"],
check=True, capture_output=True,
)
port = _free_port()
subprocess.run(
[str(bindir / "pg_ctl"), "-D", str(data), "-w", "-l", str(base / "log"),
"-o", f"-p {port} -k {sock} -c listen_addresses=''", "start"],
check=True, capture_output=True,
)
env = {"PGHOST": str(sock), "PGPORT": str(port), "PGUSER": "test", "PGDATABASE": "postgres"}
try:
yield env, major
finally:
subprocess.run([str(bindir / "pg_ctl"), "-D", str(data), "-m", "fast", "stop"],
check=False, capture_output=True)
def _psql(bindir: Path, env: dict[str, str], sql: str) -> str:
out = subprocess.run(
[str(bindir / "psql"), "-XAtq", "-v", "ON_ERROR_STOP=1", "-c", sql],
env={**os.environ, **env}, check=True, capture_output=True, text=True,
)
return out.stdout.strip()
def _tools(major: int) -> tuple[Path, Path, Path]:
return (
backup.find_pg_tool("pg_dump", major),
backup.find_pg_tool("pg_restore", major),
backup.find_pg_tool("psql", major),
)
def test_dump_verify_and_restore_roundtrip(
pg_cluster: tuple[dict[str, str], int], tmp_path: Path
) -> None:
env, major = pg_cluster
pg_dump, pg_restore, psql = _tools(major)
bindir = pg_dump.parent
_psql(bindir, env, "DROP SCHEMA IF EXISTS surveybox CASCADE; CREATE SCHEMA surveybox")
_psql(bindir, env, "CREATE TABLE surveybox.t (id int primary key, note text)")
_psql(bindir, env, "INSERT INTO surveybox.t VALUES (1, 'vorher')")
_psql(bindir, env, "CREATE TABLE public.fremd (x int); INSERT INTO public.fremd VALUES (7)")
target = tmp_path / "out" / "surveybox-manual-test.dump"
backup.dump_to_file(pg_dump, pg_restore, env, target)
assert target.is_file()
assert oct(target.stat().st_mode & 0o777) == "0o600"
assert not list(target.parent.glob("*.partial"))
# Ein "Update" nach der Sicherung: Daten geändert, neue Tabelle mit
# Fremdschlüssel auf eine alte Tabelle. Genau das ließe ein einfaches
# pg_restore --clean scheitern.
_psql(bindir, env, "UPDATE surveybox.t SET note = 'nachher'")
_psql(
bindir,
env,
"CREATE TABLE surveybox.neu (id int primary key, t_id int references surveybox.t(id))",
)
_psql(bindir, env, "INSERT INTO surveybox.neu VALUES (1, 1)")
_psql(bindir, env, "UPDATE public.fremd SET x = 8")
backup.restore_from_file(pg_restore, psql, env, target, tmp_path / "work")
assert _psql(bindir, env, "SELECT note FROM surveybox.t WHERE id = 1") == "vorher"
assert _psql(bindir, env, "SELECT to_regclass('surveybox.neu') IS NULL") == "t"
# Andere Schemata bleiben unberührt
assert _psql(bindir, env, "SELECT x FROM public.fremd") == "8"
assert not list((tmp_path / "work").glob(".restore-*"))
def test_failed_restore_keeps_current_state(
pg_cluster: tuple[dict[str, str], int], tmp_path: Path
) -> None:
"""Bricht das Einspielen ab, bleibt der bisherige Stand vollständig erhalten."""
env, major = pg_cluster
pg_dump, pg_restore, psql = _tools(major)
bindir = pg_dump.parent
_psql(bindir, env, "DROP SCHEMA IF EXISTS surveybox CASCADE; CREATE SCHEMA surveybox")
_psql(bindir, env, "CREATE TABLE surveybox.t (v text); INSERT INTO surveybox.t VALUES ('a')")
target = tmp_path / "surveybox-manual-t.dump"
backup.dump_to_file(pg_dump, pg_restore, env, target)
_psql(bindir, env, "UPDATE surveybox.t SET v = 'b'")
# Eine Rolle, die es beim Einspielen nicht gibt, lässt einen Befehl der
# Sicherung scheitern: Wir hängen ihn an das erzeugte Skript an, indem
# wir pg_restore durch einen Wrapper ersetzen.
wrapper = tmp_path / "pg_restore_wrapper.sh"
wrapper.write_text(
"#!/bin/sh\n"
f'"{pg_restore}" "$@" || exit $?\n'
'for a in "$@"; do case "$a" in --file=*) '
'echo "SELECT kaputt_absichtlich();" >> "${a#--file=}";; esac; done\n'
)
wrapper.chmod(0o755)
with pytest.raises(backup.BackupError, match="Einspielen"):
backup.restore_from_file(wrapper, psql, env, target, tmp_path / "work")
assert _psql(bindir, env, "SELECT v FROM surveybox.t") == "b"
def test_failed_dump_leaves_no_file(
pg_cluster: tuple[dict[str, str], int], tmp_path: Path
) -> None:
env, major = pg_cluster
pg_dump, pg_restore, _ = _tools(major)
target = tmp_path / "surveybox-manual-broken.dump"
with pytest.raises(backup.BackupError, match="pg_dump"):
backup.dump_to_file(pg_dump, pg_restore, {**env, "PGDATABASE": "gibtsnicht"}, target)
assert not target.exists()
assert not list(tmp_path.glob("*.partial"))
def test_restore_rejects_corrupt_file(
pg_cluster: tuple[dict[str, str], int], tmp_path: Path
) -> None:
env, major = pg_cluster
_, pg_restore, psql = _tools(major)
bad = tmp_path / "kaputt.dump"
bad.write_bytes(b"keine Sicherung")
with pytest.raises(backup.BackupError, match="Prüfung"):
backup.restore_from_file(pg_restore, psql, env, bad, tmp_path / "work")
def test_restore_rejects_bad_schema_name(tmp_path: Path) -> None:
f = tmp_path / "x.dump"
f.write_bytes(b"x")
with pytest.raises(backup.BackupError, match="Schemaname"):
backup.restore_from_file(f, f, {}, f, tmp_path, schema="x; DROP")
+54
View File
@@ -0,0 +1,54 @@
# SPDX-License-Identifier: AGPL-3.0-or-later
"""Eigenes Logo über die Admin-Einstellungen (CI)."""
from __future__ import annotations
import io
from typing import Any
import pytest
pytest.importorskip("fastapi")
from helpers import new_client, token_for
from PIL import Image
from test_mail import admin
pytestmark = pytest.mark.db
def png() -> bytes:
buf = io.BytesIO()
Image.new("RGBA", (300, 100), (31, 95, 174, 255)).save(buf, "PNG")
return buf.getvalue()
def test_upload_show_and_remove_logo(app: Any) -> None:
root = admin(app)
guest = new_client(app)
assert "img/logo.svg" in guest.get("/login").text
assert guest.get("/favicon.ico", follow_redirects=False).headers["location"].startswith(
"/static/img/")
csrf = token_for(root, "/admin/settings")
resp = root.post("/admin/settings/logo", data={"csrf_token": csrf},
files={"logo": ("logo.png", png(), "image/png")})
assert resp.status_code == 303 and "notice=settings_saved" in resp.headers["location"]
page = guest.get("/login").text
assert "/branding/logo.png?v=" in page and "/branding/favicon.png?v=" in page
logo = guest.get("/branding/logo.png")
assert logo.status_code == 200 and logo.headers["content-type"] == "image/png"
assert "immutable" in logo.headers["cache-control"]
assert guest.get("/favicon.ico", follow_redirects=False).headers["location"].startswith(
"/branding/favicon.png?v=")
assert guest.get("/branding/branding.json").status_code == 404
# SVG wird abgelehnt, das bisherige Logo bleibt
csrf = token_for(root, "/admin/settings")
resp = root.post("/admin/settings/logo", data={"csrf_token": csrf},
files={"logo": ("x.svg", b"<svg xmlns='http://www.w3.org/2000/svg'/>",
"image/svg+xml")})
assert "error=logo_invalid" in resp.headers["location"]
assert "/branding/logo.png?v=" in guest.get("/login").text
csrf = token_for(root, "/admin/settings")
root.post("/admin/settings/logo/remove", data={"csrf_token": csrf})
assert "img/logo.svg" in guest.get("/login").text
assert guest.get("/branding/logo.png").status_code == 404
+64
View File
@@ -0,0 +1,64 @@
# SPDX-License-Identifier: AGPL-3.0-or-later
"""Eigenes Logo: neu berechnet, drei Fassungen, nur bekannte Dateien (ohne Datenbank)."""
from __future__ import annotations
from pathlib import Path
import pytest
pytest.importorskip("PIL")
from PIL import Image, ImageDraw
from surveybox import branding
from surveybox.media import images
def logo_file(tmp_path: Path, size: tuple[int, int] = (1200, 300)) -> Path:
img = Image.new("RGBA", size, (0, 0, 0, 0))
ImageDraw.Draw(img).rectangle((100, 50, size[0] - 100, size[1] - 50), fill=(200, 30, 30, 255))
path = tmp_path / "in.png"
img.save(path)
return path
def test_default_until_a_logo_is_saved(tmp_path: Path) -> None:
assert branding.current(tmp_path) == branding.DEFAULT
assert branding.DEFAULT.url("logo") is None
brand = branding.save_logo(tmp_path, logo_file(tmp_path))
assert brand.custom and brand.url("favicon") == f"/branding/favicon.png?v={brand.version}"
sizes = {name: Image.open(tmp_path / "branding" / name).size
for name in branding.FILES.values() if name != "logo-dark.png"}
assert not brand.dark and brand.url("logo_dark") is None
assert sizes["favicon.png"] == (64, 64) and sizes["touch.png"] == (180, 180)
assert sizes["logo.png"][0] <= 800 and sizes["logo.png"][1] <= 240
# Leere Ränder sind abgeschnitten
width, height = sizes["logo.png"]
assert width == 800 and 158 <= height <= 162
branding.remove_logo(tmp_path)
assert branding.current(tmp_path) == branding.DEFAULT
def test_only_known_files_are_served(tmp_path: Path) -> None:
branding.save_logo(tmp_path, logo_file(tmp_path))
assert branding.file_path(tmp_path, "logo.png") is not None
assert branding.file_path(tmp_path, "branding.json") is None
assert branding.file_path(tmp_path, "../secret") is None
def test_svg_and_garbage_are_refused(tmp_path: Path) -> None:
svg = tmp_path / "x.svg"
svg.write_text('<svg xmlns="http://www.w3.org/2000/svg"><script>alert(1)</script></svg>')
with pytest.raises(images.ImageError):
branding.save_logo(tmp_path, svg)
assert branding.current(tmp_path) == branding.DEFAULT
def test_dark_logo(tmp_path: Path) -> None:
branding.save_logo(tmp_path, logo_file(tmp_path))
brand = branding.save_logo(tmp_path, logo_file(tmp_path), dark=True)
assert brand.dark and brand.url("logo_dark") == f"/branding/logo-dark.png?v={brand.version}"
branding.remove_dark_logo(tmp_path)
brand = branding.current(tmp_path)
assert brand.custom and not brand.dark
+50
View File
@@ -0,0 +1,50 @@
# SPDX-License-Identifier: AGPL-3.0-or-later
"""iCalendar-Ausgabe der bestätigten Termine (ohne Datenbank)."""
from __future__ import annotations
from datetime import UTC, datetime
from types import SimpleNamespace
from zoneinfo import ZoneInfo
from surveybox.forms import calendar
def poll(confirmed: list[str]) -> SimpleNamespace:
return SimpleNamespace(
id=7,
type="poll",
config={
"mode": "dates",
"confirmed": confirmed,
"options": [
{"id": "aaaa0001", "label": "", "date": "2026-07-01", "time": "18:30",
"duration": 90},
{"id": "aaaa0002", "label": "Ausweichtermin; mit Grill, bitte",
"date": "2026-07-08", "time": None, "duration": None},
{"id": "aaaa0003", "label": "", "date": "2026-07-15", "time": None,
"duration": None},
],
},
)
def test_only_confirmed_dates_with_utc_and_all_day() -> None:
events = calendar.confirmed_events([poll(["aaaa0001", "aaaa0002"])])
text = calendar.build(
title="Sommerfest", url="https://x/f/t", host="x", events=events,
tz=ZoneInfo("Europe/Berlin"), now=datetime(2026, 6, 1, tzinfo=UTC),
)
assert text.count("BEGIN:VEVENT") == 2
assert "DTSTART:20260701T163000Z" in text and "DTEND:20260701T180000Z" in text
assert "DTSTART;VALUE=DATE:20260708" in text and "DTEND;VALUE=DATE:20260709" in text
assert "SUMMARY:Sommerfest: Ausweichtermin\\; mit Grill\\, bitte" in text
assert "20260715" not in text
assert all(len(line.encode()) <= 75 for line in text.split("\r\n"))
def test_folding_keeps_utf8() -> None:
long = "Ä" * 60
folded = calendar._fold(f"SUMMARY:{long}")
assert "\r\n " in folded
assert folded.replace("\r\n ", "") == f"SUMMARY:{long}"
+176
View File
@@ -0,0 +1,176 @@
# SPDX-License-Identifier: AGPL-3.0-or-later
"""Bedingungen: Auswertung, Designer-Eingaben, Pflege (ohne Datenbank)."""
from __future__ import annotations
from dataclasses import dataclass, field
from typing import Any
import pytest
from surveybox.forms import conditions as c
@dataclass
class Q:
id: int
type: str
label: str = ""
config: dict[str, Any] = field(default_factory=dict)
position: int = 0
required: bool = False
def form() -> list[Q]:
qs = [
Q(1, "yes_no", "Kommen Sie?"),
Q(2, "number", "Wie viele?", {"decimals": 0}),
Q(3, "single_choice", "Essen", {"options": [{"id": "veg01", "label": "Vegetarisch"},
{"id": "mea01", "label": "Fleisch"}]}),
Q(4, "multiple_choice", "Extras", {"options": [{"id": "dri01", "label": "Getränke"},
{"id": "des01", "label": "Nachtisch"}]}),
Q(5, "short_text", "Unverträglichkeiten"),
Q(6, "page_break", "Seite 2"),
Q(7, "heading", "Übernachtung"),
Q(8, "date", "Anreise"),
Q(9, "file_upload", "Nachweis"),
]
for index, q in enumerate(qs):
q.position = index
return qs
def rule(q: int, op: str, value: str = "") -> dict[str, Any]:
return {"q": q, "op": op, "value": value}
def cond(*rules: dict[str, Any], action: str = "show", match: str = "all") -> dict[str, Any]:
return {"action": action, "match": match, "rules": list(rules)}
def test_show_when_yes_and_hidden_answers_count_as_empty() -> None:
qs = form()
qs[1].config["condition"] = cond(rule(1, "eq", "yes"))
qs[2].config["condition"] = cond(rule(2, "gt", "2"))
# Nein: Frage 2 aus, also gilt ihr Wert als leer, also auch Frage 3 aus
hidden = c.hidden_ids(qs, {"q1": ["no"], "q2": ["5"]})
assert {2, 3} <= hidden
hidden = c.hidden_ids(qs, {"q1": ["yes"], "q2": ["5"]})
assert not {2, 3} & hidden
hidden = c.hidden_ids(qs, {"q1": ["yes"], "q2": ["2"]})
assert 3 in hidden and 2 not in hidden
def test_page_and_section_conditions() -> None:
qs = form()
qs[5].config["condition"] = cond(rule(1, "eq", "yes")) # ganze Seite 2
qs[6].config["condition"] = cond(rule(4, "contains", "des01"), action="hide")
hidden = c.hidden_ids(qs, {"q1": ["no"]})
assert {6, 7, 8, 9} <= hidden
hidden = c.hidden_ids(qs, {"q1": ["yes"], "q4": ["dri01", "des01"]})
assert 6 not in hidden and {7, 8, 9} <= hidden
hidden = c.hidden_ids(qs, {"q1": ["yes"], "q4": ["dri01"]})
assert not {6, 7, 8, 9} & hidden
@pytest.mark.parametrize(
("question", "rule_", "fields", "expected"),
[
(5, rule(5, "contains", "NUSS"), {"q5": ["Haselnuss, Gluten"]}, True),
(5, rule(5, "eq", "gluten"), {"q5": [" Gluten "]}, True),
(5, rule(5, "not_contains", "nuss"), {"q5": [""]}, True),
(5, rule(5, "empty"), {"q5": [" "]}, True),
(2, rule(2, "lt", "3"), {"q2": ["2,0"]}, True),
(2, rule(2, "eq", "3"), {"q2": ["abc"]}, False),
(2, rule(2, "ne", "3"), {}, True),
(3, rule(3, "ne", "veg01"), {"q3": ["mea01"]}, True),
(4, rule(4, "not_contains", "des01"), {"q4": ["dri01"]}, True),
(8, rule(8, "gt", "2026-07-01"), {"q8": ["2026-07-02"]}, True),
(8, rule(8, "lt", "2026-07-01"), {"q8": [""]}, False),
],
)
def test_operators(question: int, rule_: dict[str, Any], fields: dict[str, list[str]],
expected: bool) -> None:
qs = form()
target = Q(99, "info", "Ziel", {"condition": cond(rule_)}, position=100)
assert (99 not in c.hidden_ids([*qs, target], fields)) is expected
def test_files_and_any_match() -> None:
qs = form()
target = Q(99, "info", "Ziel", {"condition": cond(rule(9, "not_empty"), rule(1, "eq", "no"),
match="any")}, position=100)
assert 99 in c.hidden_ids([*qs, target], {"q1": ["yes"]})
assert 99 not in c.hidden_ids([*qs, target], {"q1": ["yes"]}, with_files={9})
def test_parse_from_designer() -> None:
qs = form()
question = qs[7] # Anreise, Position 7
fields = {
"cond_action": ["show"],
"cond_match": ["any"],
"rule_q": ["1", "3", "2", ""],
"rule_op": ["eq", "ne", "gt", "eq"],
"rule_text": ["", "", "1,50", ""],
"rule_option": ["yes", "veg01", "", ""],
}
parsed = c.parse(question, fields, qs)
assert parsed == {
"action": "show",
"match": "any",
"rules": [rule(1, "eq", "yes"), rule(3, "ne", "veg01"), rule(2, "gt", "1.5")],
}
assert c.parse(question, {"rule_q": [""]}, qs) is None
@pytest.mark.parametrize(
("fields", "code"),
[
({"rule_q": ["9"], "rule_op": ["empty"]}, "condition_ref_invalid"), # spätere Frage
({"rule_q": ["7"], "rule_op": ["empty"]}, "condition_ref_invalid"), # keine Eingabe
({"rule_q": ["1"], "rule_op": ["gt"], "rule_option": ["yes"]}, "condition_op_invalid"),
({"rule_q": ["3"], "rule_op": ["eq"], "rule_option": ["xxx"]},
"condition_value_invalid"),
({"rule_q": ["2"], "rule_op": ["eq"], "rule_text": ["viele"]},
"condition_value_invalid"),
],
)
def test_parse_rejects(fields: dict[str, list[str]], code: str) -> None:
qs = form()
with pytest.raises(c.ConditionError) as exc:
c.parse(qs[7], fields, qs)
assert exc.value.code == code
def test_order_delete_and_copy_helpers() -> None:
qs = form()
qs[4].config["condition"] = cond(rule(1, "eq", "yes"), rule(3, "eq", "veg01"))
assert c.order_violations(qs) == []
reordered = [qs[4], *qs[:4], *qs[5:]]
assert c.order_violations(reordered) == [5]
cleaned = c.without_reference(qs[4].config, 3)
assert cleaned is not None and cleaned["condition"]["rules"] == [rule(1, "eq", "yes")]
assert c.without_reference(qs[4].config, 8) is None
assert "condition" not in c.remap(qs[4].config, {})
assert c.remap(qs[4].config, {1: 11, 3: 13})["condition"]["rules"][1]["q"] == 13
def test_layout() -> None:
pages = c.layout(form())
assert len(pages) == 2
assert [q.id for q in pages[0]["sections"][0]["items"]] == [1, 2, 3, 4, 5]
assert pages[1]["break"].id == 6
assert pages[1]["sections"][1]["heading"].id == 7
starts_with_break = [Q(1, "page_break"), Q(2, "short_text")]
assert len(c.layout(starts_with_break)) == 1
def test_poll_and_slots_in_conditions() -> None:
qs = [Q(1, "poll", config={"options": [{"id": "t1", "label": "A"}]}),
Q(2, "slots", config={"options": [{"id": "s1", "label": "Früh"}]}, position=1),
Q(3, "info", config={"condition": cond(rule(1, "not_empty"))}, position=2),
Q(4, "info", config={"condition": cond(rule(2, "contains", "s1"))}, position=3)]
assert c.hidden_ids(qs, {"q1_propose_text": ["x"]}) == {3, 4}
assert c.hidden_ids(qs, {"q1_t1": ["no"], "q2": ["s1"]}) == set()
+70
View File
@@ -0,0 +1,70 @@
# SPDX-License-Identifier: AGPL-3.0-or-later
"""Einbetten im Rahmen (Nextcloud "External sites") und kompakte Darstellung (CI)."""
from __future__ import annotations
from typing import Any
import pytest
pytest.importorskip("fastapi")
from helpers import new_client
pytestmark = pytest.mark.db
def test_embedding_forbidden_by_default(app: Any) -> None:
resp = new_client(app).get("/login")
assert resp.headers["X-Frame-Options"] == "DENY"
assert "frame-ancestors 'none'" in resp.headers["Content-Security-Policy"]
assert 'class="brand"' in resp.text
@pytest.fixture
def embed_app(db_settings: Any, monkeypatch: pytest.MonkeyPatch) -> Any:
from surveybox import db
from surveybox import settings as settings_mod
from surveybox.upgrade import run_upgrade
from surveybox.web.app import create_app
monkeypatch.setenv("SURVEYBOX_FRAME_ANCESTORS", "https://cloud.example.de")
settings_mod.get_settings.cache_clear()
settings = settings_mod.get_settings()
run_upgrade(settings, db.get_engine())
return create_app()
def test_allowed_ancestors_and_compact_mode(embed_app: Any) -> None:
client = new_client(embed_app)
resp = client.get("/login")
assert "X-Frame-Options" not in resp.headers
assert ("frame-ancestors 'self' https://cloud.example.de"
in resp.headers["Content-Security-Policy"])
assert 'class="brand"' in resp.text # außerhalb des Rahmens wie immer
# Im Rahmen: ohne Logo und Fußzeile, mit "Neuer Tab"
framed = client.get("/login", headers={"Sec-Fetch-Dest": "iframe"}).text
assert 'class="brand"' not in framed and "topbar compact" in framed and "?embed=0" in framed
# ?embed=1 merkt sich die Darstellung, ?embed=0 schaltet sie ab
client.get("/login?embed=1")
assert "topbar compact" in client.get("/login").text
client.get("/login?embed=0")
assert "topbar compact" not in client.get("/login").text
def test_invalid_ancestors_are_refused(monkeypatch: pytest.MonkeyPatch) -> None:
pytest.importorskip("pydantic_settings")
from pydantic import ValidationError
from surveybox.settings import Settings
monkeypatch.setenv("SURVEYBOX_PUBLIC_URL", "https://umfrage.example.de")
monkeypatch.setenv("SURVEYBOX_SECRET_KEY", "x" * 40)
monkeypatch.setenv("SURVEYBOX_DB_PASSWORD", "x")
for value in ("http://cloud.example.de", "*", "https://a.de/pfad", "'unsafe-inline'"):
monkeypatch.setenv("SURVEYBOX_FRAME_ANCESTORS", value)
with pytest.raises(ValidationError):
Settings()
monkeypatch.setenv("SURVEYBOX_FRAME_ANCESTORS", "https://Cloud.example.de/, https://b.de:8443")
settings = Settings()
assert settings.frame_ancestors_csp == "'self' https://cloud.example.de https://b.de:8443"
+196
View File
@@ -0,0 +1,196 @@
# 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) == []
+58
View File
@@ -0,0 +1,58 @@
# SPDX-License-Identifier: AGPL-3.0-or-later
"""Löschjournal ohne Datenbank: Einträge, Marke nach Wiederherstellung, Aufräumen."""
from __future__ import annotations
import uuid
from datetime import UTC, datetime, timedelta
from pathlib import Path
from types import SimpleNamespace
from typing import Any
import pytest
pytest.importorskip("pydantic_settings")
from surveybox import erasure_journal
from surveybox.backup import backup_time
def settings(tmp_path: Path) -> Any:
return SimpleNamespace(data_dir=tmp_path, backup_dir=tmp_path / "backups")
def test_record_read_and_prune(tmp_path: Path) -> None:
s = settings(tmp_path)
first = uuid.uuid4()
erasure_journal.record(s, "user", first, forms={"a": ""})
erasure_journal.record(s, "guest", uuid.uuid4())
with erasure_journal.journal_path(s).open("a", encoding="utf-8") as handle:
handle.write('{"at": "kaputt"') # angefangene Zeile nach einem Absturz
found = erasure_journal.entries(s)
assert [e.kind for e in found] == ["user", "guest"]
assert found[0].id == str(first) and found[0].extra == {"forms": {"a": ""}}
later = datetime.now(UTC) + timedelta(seconds=1)
assert erasure_journal.entries(s, later) == []
assert erasure_journal.prune(s, later) == 3
assert erasure_journal.entries(s) == []
with pytest.raises(ValueError):
erasure_journal.record(s, "unknown", first)
def test_restore_marker(tmp_path: Path) -> None:
s = settings(tmp_path)
assert erasure_journal.pending_since(s) is None
taken = datetime(2026, 11, 1, 3, 0, tzinfo=UTC)
erasure_journal.mark_restore(s, taken)
assert erasure_journal.pending_since(s) == taken
erasure_journal.clear_marker(s)
assert erasure_journal.pending_since(s) is None
def test_backup_time_from_name() -> None:
assert backup_time(Path("surveybox-daily-20261101T030000Z.dump")) == datetime(
2026, 11, 1, 3, 0, tzinfo=UTC)
assert backup_time(Path(
"surveybox-pre-upgrade-20261101T030000Z-from-0012-to-0013.dump"
)) == datetime(2026, 11, 1, 3, 0, tzinfo=UTC)
assert backup_time(Path("eigene.dump")) is None
+141
View File
@@ -0,0 +1,141 @@
# SPDX-License-Identifier: AGPL-3.0-or-later
"""Phase 8b gegen PostgreSQL: Filter, Teilnehmerlisten, Export, Löschen von Antworten (CI)."""
from __future__ import annotations
import csv
import io
import zipfile
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, creator, fill, form_row, participant, question_ids
from test_phase5 import slot_form
from surveybox import db
from surveybox.models import AuditEvent, Response
pytestmark = pytest.mark.db
def prepare(app: Any) -> tuple[TestClient, str, str, int, int, list[str]]:
carla = creator(app)
pid, token, slot_q, options = slot_form(carla, capacity="1", waitlist=True)
add_question(carla, pid, "participant_name", label="Name", email_mode="optional",
personal="on")
name_q = question_ids(pid)[-1]
fill(new_client(app), token, {f"q{slot_q}": options[0], f"q{name_q}_first": "Bernd",
f"q{name_q}_last": "Krause", f"q{name_q}_email": "=b@x.de"})
fill(new_client(app), token, {f"q{slot_q}": options[0], f"q{name_q}_first": "Carla",
f"q{name_q}_last": "Kurz"})
fill(participant(app), token, {f"q{slot_q}": options[1], f"q{name_q}_first": "Paul",
f"q{name_q}_last": "Peters"})
return carla, pid, token, slot_q, name_q, options
def export(client: TestClient, pid: str, **data: str) -> Any:
csrf = token_for(client, f"/forms/{pid}/responses")
return client.post(f"/forms/{pid}/responses/export", data={"csrf_token": csrf, **data})
def test_lists_filters_and_summary(app: Any) -> None:
carla, pid, _, slot_q, _, options = prepare(app)
page = carla.get(f"/forms/{pid}/responses").text
# 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 "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
# Unbekannter Filter wird ignoriert
assert "3 answers so far" in carla.get(f"/forms/{pid}/responses?answer=999:x").text
def test_csv_and_xlsx_export(app: Any) -> None:
carla, pid, _, _, _, _ = prepare(app)
resp = export(carla, pid, format="csv")
assert resp.status_code == 200 and "attachment" in resp.headers["content-disposition"]
text = resp.content.decode("utf-8-sig")
rows = list(csv.reader(io.StringIO(text), delimiter=";"))
assert rows[0][:4] == ["No.", "Submitted", "Changed", "Participant"]
assert "Name: First name" in rows[0] and "Name: Email address" in rows[0]
assert len(rows) == 4
assert any("'=b@x.de" in cell for cell in rows[1]) # Formel entschärft
assert any("(waiting list)" in cell for row in rows for cell in row)
# Ohne personenbezogene Daten: keine Namensspalten, kein Kontoname
lean = export(carla, pid, format="csv", personal="off").content.decode("utf-8-sig")
assert "Krause" not in lean and "Participant" not in lean.splitlines()[0]
# Gefiltert und als XLSX mit Info-Blatt und Logo
resp = export(carla, pid, format="xlsx", answer="")
with zipfile.ZipFile(io.BytesIO(resp.content)) as z:
assert "xl/worksheets/sheet2.xml" not in z.namelist()
assert any(n.startswith("xl/media/") for n in z.namelist())
assert "Krause" in z.read("xl/worksheets/sheet1.xml").decode()
with Session(db.get_engine()) as s:
details = [e.details for e in s.scalars(
select(AuditEvent).where(AuditEvent.action == "form.exported"))]
assert [d["format"] for d in details] == ["csv", "csv", "xlsx"] # type: ignore[index]
assert details[1]["personal"] is False # type: ignore[index]
def test_browse_and_delete_answer(app: Any) -> None:
carla, pid, _, _, _, _ = prepare(app)
with Session(db.get_engine()) as s:
first = s.scalar(select(Response).where(Response.form_id == form_row(pid).id)
.order_by(Response.submitted_at, Response.id))
assert first is not None
rid = first.public_id
s.execute(update(Response).where(Response.id == first.id).values(
submitted_at=datetime.now(UTC) - timedelta(hours=1)))
s.commit()
page = carla.get(f"/forms/{pid}/responses/{rid}").text
assert "Next" in page and "Delete answer" in page
csrf = token_for(carla, f"/forms/{pid}/responses/{rid}")
resp = carla.post(f"/forms/{pid}/responses/{rid}/delete",
data={"csrf_token": csrf, "confirm": "on"})
assert resp.status_code == 303 and "response_deleted" in resp.headers["location"]
page = carla.get(f"/forms/{pid}/responses").text
assert "Bernd Krause" not in page
# Carla rückt von der Warteliste nach
assert "2 answers so far" in page
def test_invited_people_without_response_are_listed(app: Any) -> None:
from helpers import login
from surveybox.models import Form, FormAccess, FormAccessEntry, UserAccount
carla = creator(app)
pid, token, slot_q, options = slot_form(carla, capacity="")
participant(app) # paul
participant(app, "olga@example.de")
with Session(db.get_engine()) as s:
form = s.get(Form, form_row(pid).id)
assert form is not None
users = {u.email: u.id for u in s.scalars(select(UserAccount))}
for email in ("paul@example.de", "olga@example.de"):
s.add(FormAccessEntry(form_id=form.id, user_id=users[email]))
form.access = FormAccess.RESTRICTED
s.commit()
paul = new_client(app)
login(paul, "paul@example.de")
assert fill(paul, token, {f"q{slot_q}": options[0]}).status_code == 303
page = carla.get(f"/forms/{pid}/responses").text
assert "1 invited person has not responded yet" in page
assert "no response yet" in page and "received" in page
missing = carla.get(f"/forms/{pid}/responses?missing=1").text
assert "no response yet" in missing and "received" not in missing
# Im Export ebenfalls, aber nicht ohne personenbezogene Daten
full = export(carla, pid, format="csv").content.decode("utf-8-sig")
assert "no response yet" in full
lean = export(carla, pid, format="csv", personal="off").content.decode("utf-8-sig")
assert "no response yet" not in lean
+343
View File
@@ -0,0 +1,343 @@
# SPDX-License-Identifier: AGPL-3.0-or-later
"""Phase 6c gegen PostgreSQL: Folge-Mails mit Dokumenten, gestrichene Einträge,
Erinnerungen, tägliche Zusammenfassung (CI)."""
from __future__ import annotations
import re
import uuid
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 content, messages
from test_phase5 import bookings, options_of, slot_form
from surveybox import db
from surveybox.forms import digest, followups, reminders
from surveybox.models import (
Followup,
FollowupDocument,
Form,
FormAccess,
FormAccessEntry,
UserAccount,
)
from surveybox.settings import get_settings
pytestmark = pytest.mark.db
PDF = b"%PDF-1.4\n1 0 obj<<>>endobj\ntrailer<<>>\n%%EOF\n"
def path_of(url: str) -> str:
return url.replace(get_settings().public_origin, "")
def create_followup(client: TestClient, pid: str, **fields: Any) -> str:
data = {"subject": "Unterlagen zu {form}", "body": "Hallo {name},\nanbei das Programm.",
"trigger": "manual", "link_days": "90", "catch_up": "no", **fields}
csrf = token_for(client, f"/forms/{pid}/followups/new")
resp = client.post(f"/forms/{pid}/followups/new", data={"csrf_token": csrf, **data})
assert resp.status_code == 303, resp.text
match = re.search(r"/followups/([0-9a-f-]{36})", resp.headers["location"])
assert match
return match.group(1)
def upload_pdf(client: TestClient, pid: str, fid: str) -> None:
url = f"/forms/{pid}/followups/{fid}"
csrf = token_for(client, url)
resp = client.post(f"{url}/documents", data={"csrf_token": csrf, "title": "Programm"},
files={"document": ("programm.pdf", PDF, "application/pdf")})
assert resp.status_code == 303, resp.text
def send_now(client: TestClient, pid: str, fid: str) -> Any:
url = f"/forms/{pid}/followups/{fid}"
csrf = token_for(client, url)
return client.post(f"{url}/send", data={"csrf_token": csrf, "confirm": "on"})
def downloads() -> list[int]:
with Session(db.get_engine()) as s:
return [d.downloads for d in s.scalars(select(FollowupDocument))]
def test_followup_on_submit_with_personal_document_link(app: Any) -> None:
carla = creator(app)
pid, token, qid, (early, _) = slot_form(carla)
fid = create_followup(carla, pid, trigger="submit")
upload_pdf(carla, pid, fid)
paul = participant(app)
assert fill(paul, token, {f"q{qid}": early}).status_code == 303
(mail,) = messages("followup")
assert mail.recipient == "paul@example.de"
data = content(mail)
assert data["subject"] == "Unterlagen zu Sommerfest"
assert data["text"].startswith("Hallo Anna,") # Testkonten heißen "Anna"
(link,) = [w for w in data["text"].split() if "/d/" in w]
# Persönlicher Link funktioniert ohne Anmeldung, zählt nur anonym
resp = new_client(app).get(path_of(link))
assert resp.status_code == 200 and resp.content == PDF
assert "attachment" in resp.headers["content-disposition"]
assert downloads() == [1]
# Die Bestätigungsseite zeigt das Dokument; nur der Empfänger kommt dran
page = paul.get(f"/f/{token}").text
assert "Programm" in page
doc_url = re.search(rf"/f/{token}/documents/[0-9a-f-]{{36}}", page).group(0) # type: ignore[union-attr]
assert paul.get(doc_url).status_code == 200
other = participant(app, "olga@example.de")
assert other.get(doc_url).status_code == 404
# Geänderte Antwort: keine zweite Mail
fill(paul, token, {f"q{qid}": early}, path="/edit")
assert len(messages("followup")) == 1
def test_manual_send_reaches_everyone_once(app: Any) -> None:
carla = creator(app)
pid, token, qid, (early, late) = slot_form(carla, capacity="")
fid = create_followup(carla, pid)
fill(participant(app), token, {f"q{qid}": early})
fill(participant(app, "olga@example.de"), token, {f"q{qid}": late})
page = carla.get(f"/forms/{pid}/followups/{fid}").text
assert "2 people who have not received it yet" in page
assert "Unterlagen zu Sommerfest" in page # Vorschau
resp = send_now(carla, pid, fid)
assert resp.status_code == 303 and "sent=2" in resp.headers["location"]
assert send_now(carla, pid, fid).headers["location"].count("sent=0") == 1
assert sorted(m.recipient for m in messages("followup")) == [
"olga@example.de", "paul@example.de"]
def test_only_confirmed_places(app: Any) -> None:
carla = creator(app)
pid, token, qid, (early, _) = slot_form(carla, waitlist=True)
fid = create_followup(carla, pid, only_confirmed="on")
fill(participant(app), token, {f"q{qid}": early})
fill(participant(app, "olga@example.de"), token, {f"q{qid}": early})
assert [b[1] for b in bookings(qid)] == ["confirmed", "waiting"]
send_now(carla, pid, fid)
assert [m.recipient for m in messages("followup")] == ["paul@example.de"]
def test_followup_when_form_closes(app: Any) -> None:
from test_forms import set_status
carla = creator(app)
pid, token, qid, (early, _) = slot_form(carla)
create_followup(carla, pid, trigger="close")
fill(participant(app), token, {f"q{qid}": early})
settings = get_settings()
with Session(db.get_engine()) as s:
assert followups.run_due(s, settings, datetime.now(UTC)) == 0
s.commit()
assert set_status(carla, pid, "closed").status_code == 303
with Session(db.get_engine()) as s:
assert followups.run_due(s, settings, datetime.now(UTC)) == 1
s.commit()
(item,) = s.scalars(select(Followup)).all()
assert item.sent_at is not None
assert followups.run_due(s, settings, datetime.now(UTC)) == 0
def test_removed_entry_notifies_and_frees_bookings(app: Any) -> None:
carla = creator(app)
pid, token, qid, (early, late) = slot_form(carla, capacity="")
fill(participant(app), token, {f"q{qid}": early})
labels = {o["id"]: o["label"] for o in options_of(qid)}
assert labels[early] == "Früh"
# "Früh" streichen
csrf = token_for(carla, f"/forms/{pid}/questions/{qid}")
resp = carla.post(f"/forms/{pid}/questions/{qid}", data={
"csrf_token": csrf, "label": "Schicht", "slot_mode": "list",
"option_id": [late], "option_label": ["Spät"], "option_capacity": [""]})
assert resp.status_code == 303
assert bookings(qid) == []
(mail,) = messages("changed")
assert mail.recipient == "paul@example.de" and "Früh" in content(mail)["text"]
def test_reminder_for_invited_people(app: Any) -> None:
carla = creator(app)
_, token, qid, (early, _) = slot_form(carla)
participant(app) # paul
participant(app, "olga@example.de")
with Session(db.get_engine()) as s:
form = s.scalar(select(Form).where(Form.share_token == token))
assert form is not None
users = {u.email: u.id for u in s.scalars(select(UserAccount))}
for email in ("paul@example.de", "olga@example.de"):
s.add(FormAccessEntry(form_id=form.id, user_id=users[email]))
s.execute(update(Form).where(Form.id == form.id).values(
access=FormAccess.RESTRICTED, closes_at=datetime.now(UTC) + timedelta(days=2),
reminder_days=3))
s.commit()
olga = new_client(app)
from helpers import login
login(olga, "olga@example.de")
assert fill(olga, token, {f"q{qid}": early}).status_code == 303
settings = get_settings()
with Session(db.get_engine()) as s:
assert reminders.run_due(s, settings, datetime.now(UTC)) == 1
s.commit()
assert reminders.run_due(s, settings, datetime.now(UTC)) == 0 # nur einmal
s.commit()
assert [m.recipient for m in messages("reminder")] == ["paul@example.de"]
def test_daily_digest_for_managers(app: Any) -> None:
carla = creator(app)
_, token, qid, (early, _) = slot_form(carla)
since = datetime.now(UTC) - timedelta(minutes=1)
fill(participant(app), token, {f"q{qid}": early})
with Session(db.get_engine()) as s:
assert digest.run(s, get_settings(), since, "2026-11-25") == 1
s.commit()
assert digest.run(s, get_settings(), since, "2026-11-25") == 0 # einmal je Tag
(mail,) = messages("digest")
assert mail.recipient == "carla@example.de"
assert "1 new answer" in content(mail)["text"]
def test_copy_keeps_followups_and_documents(app: Any) -> None:
carla = creator(app)
pid, _, _, _ = slot_form(carla)
fid = create_followup(carla, pid, trigger="submit")
upload_pdf(carla, pid, fid)
csrf = token_for(carla, f"/forms/{pid}")
resp = carla.post(f"/forms/{pid}/copy", data={"csrf_token": csrf})
assert resp.status_code == 303
with Session(db.get_engine()) as s:
assert len(s.scalars(select(Followup)).all()) == 2
assert len(s.scalars(select(FollowupDocument)).all()) == 2
assert form_row(pid) is not None
# --------------------------------------------------------------------------
# Empfängerübersicht und Hinweise an Gäste
# --------------------------------------------------------------------------
def recipients_page(client: TestClient, pid: str, fid: str) -> str:
resp = client.get(f"/forms/{pid}/followups/{fid}/recipients")
assert resp.status_code == 200
return str(resp.text)
def send_to(client: TestClient, pid: str, fid: str, key: str) -> Any:
url = f"/forms/{pid}/followups/{fid}/recipients"
csrf = token_for(client, url)
return client.post(f"{url}/send", data={"csrf_token": csrf, "recipient": key})
def test_guest_without_address_is_told_once(app: Any) -> None:
carla = creator(app)
pid, token, qid, (early, _) = slot_form(carla, capacity="", guest_email="optional")
guest = new_client(app)
# Ohne Folge-Mail: kein Hinweis
assert fill(guest, token, {f"q{qid}": early}).status_code == 303
create_followup(carla, pid)
guest = new_client(app)
form_page = guest.get(f"/f/{token}").text
assert "You only receive it if you enter your email address" in form_page
first = fill(guest, token, {f"q{qid}": early})
assert first.status_code == 200
assert "You have not entered an email address" in first.text
assert 'name="followup_ack" value="1"' in first.text
second = fill(guest, token, {f"q{qid}": early, "followup_ack": "1"})
assert second.status_code == 303 and second.headers["location"].endswith("?mail=none")
assert "without an email address" in guest.get(second.headers["location"]).text
# Mit Adresse: Hinweis in der Eingangsbestätigung und auf der Dankeseite
other = new_client(app)
resp = fill(other, token, {f"q{qid}": early, "guest_email": "gast@example.de"})
assert resp.headers["location"].endswith("?mail=confirm")
(mail,) = messages("guest_receipt")
assert "You only receive it if you confirm your email address" in content(mail)["text"]
def test_recipient_overview_and_sending_again(app: Any) -> None:
carla = creator(app)
pid, token, qid, (early, _) = slot_form(carla, capacity="", guest_email="optional")
fid = create_followup(carla, pid)
fill(participant(app), token, {f"q{qid}": early})
fill(new_client(app), token, {f"q{qid}": early, "guest_email": "gast@example.de"})
fill(new_client(app), token, {f"q{qid}": early, "followup_ack": "1"})
page = recipients_page(carla, pid, fid)
assert "Not sent yet" in page and "Address not confirmed" in page
assert "No email address" in page
assert "gast@example.de" not in page # Zusage an Gäste: Adresse bleibt verborgen
keys = re.findall(r'name="recipient" value="([^"]+)"', page)
assert len(keys) == 1 and keys[0].startswith("u:") # nur Paul kann eine Mail bekommen
resp = send_to(carla, pid, fid, keys[0])
assert resp.status_code == 303 and resp.headers["location"].endswith("result=sent")
page = recipients_page(carla, pid, fid)
assert "Received" in page and "Send again" in page and "waiting to be sent" in page
# Erneut senden: zweite Mail trotz Sperre gegen doppelte Einträge
assert send_to(carla, pid, fid, keys[0]).headers["location"].endswith("result=sent")
assert [m.recipient for m in messages("followup")] == ["paul@example.de"] * 2
# Kein Teilnehmer dieses Formulars, kein Versand
bad = send_to(carla, pid, fid, "u:00000000-0000-0000-0000-000000000000")
assert bad.headers["location"].endswith("result=failed")
# Der Gesamtversand bleibt bei "noch nicht erhalten": Paul ist erledigt
assert "sent=0" in send_now(carla, pid, fid).headers["location"]
def test_planned_ignores_finished_one_time_mails(app: Any) -> None:
carla = creator(app)
pid, _, _, _ = slot_form(carla)
with Session(db.get_engine()) as s:
form = s.get(Form, form_row(pid).id)
assert form is not None and not followups.planned(s, form)
fid = create_followup(carla, pid, trigger="close")
with Session(db.get_engine()) as s:
form = s.get(Form, form_row(pid).id)
assert form is not None and followups.planned(s, form)
s.execute(update(Followup).where(Followup.public_id == uuid.UUID(fid))
.values(sent_at=datetime.now(UTC)))
s.expire_all()
assert not followups.planned(s, form)
def test_catch_up_for_people_who_join_later(app: Any) -> None:
carla = creator(app)
pid, token, qid, (early, _) = slot_form(carla, capacity="", guest_email="optional")
# Die Frage nach dem Nachholen muss beantwortet werden
csrf = token_for(carla, f"/forms/{pid}/followups/new")
resp = carla.post(f"/forms/{pid}/followups/new", data={
"csrf_token": csrf, "subject": "S", "body": "B", "trigger": "manual", "link_days": "90"})
assert resp.status_code == 400 and "join later" in resp.text
auto = create_followup(carla, pid, subject="Automatisch", catch_up="yes")
by_hand = create_followup(carla, pid, subject="Von Hand", catch_up="no")
fill(participant(app), token, {f"q{qid}": early})
# Vor dem ersten Versand wird nichts nachgeholt
assert messages("followup") == []
send_now(carla, pid, auto)
send_now(carla, pid, by_hand)
assert len(messages("followup")) == 2
# Spätere Teilnahme: nur die Mail mit Nachholen kommt automatisch
fill(participant(app, "olga@example.de"), token, {f"q{qid}": early})
later = [content(m)["subject"] for m in messages("followup")
if m.recipient == "olga@example.de"]
assert later == ["Automatisch"]
# Gast bestätigt seine Adresse erst später
guest = new_client(app)
fill(guest, token, {f"q{qid}": early, "guest_email": "gast@example.de"})
(receipt,) = messages("guest_receipt")
(confirm,) = [w for w in content(receipt)["text"].split() if "/g/confirm/" in w]
other = new_client(app)
page = other.get(path_of(confirm))
csrf = re.search(r'name="csrf_token" value="([0-9a-f]+)"', page.text).group(1) # type: ignore[union-attr]
assert other.post(path_of(confirm), data={"csrf_token": csrf}).status_code == 200
guest_mails = [content(m)["subject"] for m in messages("followup")
if m.recipient == "gast@example.de"]
assert guest_mails == ["Automatisch"]
+57
View File
@@ -0,0 +1,57 @@
# SPDX-License-Identifier: AGPL-3.0-or-later
"""form_files muss die Dateien liefern, die request.form() erzeugt."""
from __future__ import annotations
import asyncio
import pytest
pytest.importorskip("sqlalchemy")
pytest.importorskip("multipart")
from starlette.requests import Request
from surveybox.web.deps import form_files
BOUNDARY = "sbtestboundary"
def _request(parts: list[tuple[str, str | None, bytes]]) -> Request:
body = b""
for name, filename, data in parts:
disposition = f'form-data; name="{name}"'
if filename is not None:
disposition += f'; filename="{filename}"'
body += f"--{BOUNDARY}\r\nContent-Disposition: {disposition}\r\n".encode()
if filename is not None:
body += b"Content-Type: application/pdf\r\n"
body += b"\r\n" + data + b"\r\n"
body += f"--{BOUNDARY}--\r\n".encode()
sent = False
async def receive() -> dict[str, object]:
nonlocal sent
if sent:
return {"type": "http.disconnect"}
sent = True
return {"type": "http.request", "body": body, "more_body": False}
scope = {
"type": "http",
"method": "POST",
"path": "/",
"headers": [(b"content-type", f"multipart/form-data; boundary={BOUNDARY}".encode())],
}
return Request(scope, receive)
def test_uploaded_file_is_found_and_empty_field_skipped() -> None:
request = _request([
("csrf_token", None, b"x"),
("document", "programm.pdf", b"%PDF-1.4 test"),
("other", "", b""),
])
files = asyncio.run(form_files(request))
assert list(files) == ["document"]
assert files["document"][0].filename == "programm.pdf"
+423
View File
@@ -0,0 +1,423 @@
# SPDX-License-Identifier: AGPL-3.0-or-later
"""Formulare: Anlegen, Ausfüllen, Zugriffsarten, Anonymität, Rechte (CI, PostgreSQL)."""
from __future__ import annotations
import uuid
from typing import Any
import pytest
pytest.importorskip("fastapi")
from fastapi.testclient import TestClient
from helpers import login, make_user, new_client, token_for
from sqlalchemy import func, select
from sqlalchemy.orm import Session
from surveybox import db
from surveybox.accounts import groups
from surveybox.models import (
Answer,
Form,
FormParticipation,
Response,
Role,
UserAccount,
)
pytestmark = pytest.mark.db
# ---------------------------------------------------------------------------
# Hilfen
# ---------------------------------------------------------------------------
def creator(app: Any, email: str = "carla@example.de") -> TestClient:
make_user(Role.CREATOR, email)
client = new_client(app)
assert login(client, email).status_code == 303
return client
def participant(app: Any, email: str = "paul@example.de") -> TestClient:
make_user(Role.PARTICIPANT, email)
client = new_client(app)
assert login(client, email).status_code == 303
return client
def create_form(client: TestClient, title: str = "Sommerfest") -> str:
csrf = token_for(client, "/forms")
resp = client.post("/forms", data={"title": title, "csrf_token": csrf})
assert resp.status_code == 303, resp.text
return resp.headers["location"].rsplit("/", 1)[-1]
def add_question(client: TestClient, pid: str, type_key: str, **fields: Any) -> None:
csrf = token_for(client, f"/forms/{pid}/questions/new?type={type_key}")
data = {"csrf_token": csrf, **fields}
resp = client.post(f"/forms/{pid}/questions/new?type={type_key}", data=data)
assert resp.status_code == 303, resp.text
def save_settings(client: TestClient, pid: str, **overrides: Any) -> Any:
csrf = token_for(client, f"/forms/{pid}/settings")
data: dict[str, Any] = {
"csrf_token": csrf,
"title": "Sommerfest",
"access": "users",
"allow_edit": "until_close",
"deletion_mode": "anonymize",
"guest_email": "none",
"results_visibility": "never",
}
data.update(overrides)
return client.post(f"/forms/{pid}/settings", data=data)
def set_status(client: TestClient, pid: str, status: str) -> Any:
csrf = token_for(client, f"/forms/{pid}")
return client.post(f"/forms/{pid}/status", data={"status": status, "csrf_token": csrf})
def form_row(pid: str) -> Form:
with Session(db.get_engine()) as s:
form = s.scalar(select(Form).where(Form.public_id == uuid.UUID(pid)))
assert form is not None
s.expunge(form)
return form
def question_ids(pid: str) -> list[int]:
with Session(db.get_engine()) as s:
form = s.scalar(select(Form).where(Form.public_id == uuid.UUID(pid)))
assert form is not None
return [q.id for q in form.questions]
def response_count(pid: str) -> int:
with Session(db.get_engine()) as s:
form = s.scalar(select(Form).where(Form.public_id == uuid.UUID(pid)))
assert form is not None
return s.scalar(select(func.count()).where(Response.form_id == form.id)) or 0
def simple_form(client: TestClient, **settings: Any) -> tuple[str, str, list[int]]:
"""Formular mit Pflicht-Textfrage und Einfachauswahl, veröffentlicht."""
pid = create_form(client)
add_question(client, pid, "short_text", label="Ihr Name", required="on", max_length="50")
add_question(
client, pid, "single_choice", label="Lieblingsessen",
option_id=["", "", ""], option_label=["Pizza", "Salat", ""], display="radio",
)
if settings:
assert save_settings(client, pid, **settings).status_code == 303
assert set_status(client, pid, "open").status_code == 303
return pid, form_row(pid).share_token, question_ids(pid)
def option_ids(pid: str, qid: int) -> list[str]:
with Session(db.get_engine()) as s:
form = s.scalar(select(Form).where(Form.public_id == uuid.UUID(pid)))
assert form is not None
question = next(q for q in form.questions if q.id == qid)
return [o["id"] for o in question.config["options"]]
def fill(client: TestClient, token: str, data: dict[str, Any], path: str = "") -> Any:
csrf = token_for(client, f"/f/{token}{path}")
return client.post(f"/f/{token}{path}", data={"csrf_token": csrf, **data})
# ---------------------------------------------------------------------------
# Tests
# ---------------------------------------------------------------------------
def test_create_form_and_questions(app: Any) -> None:
client = creator(app)
pid = create_form(client, " Umfrage Herbst ")
assert form_row(pid).title == "Umfrage Herbst"
add_question(client, pid, "heading", label="Teil 1")
add_question(client, pid, "rating", label="Wie war es?", scale_max="7")
add_question(
client, pid, "multiple_choice", label="Was?",
option_id=["", ""], option_label=["A", "B"], min_select="0", max_select="2",
)
page = client.get(f"/forms/{pid}")
assert page.status_code == 200
assert "Wie war es?" in page.text
ids = question_ids(pid)
assert len(ids) == 3
# Zu wenige Optionen werden abgelehnt
csrf = token_for(client, f"/forms/{pid}/questions/new?type=ranking")
resp = client.post(
f"/forms/{pid}/questions/new?type=ranking",
data={"csrf_token": csrf, "label": "Rang", "option_id": [""], "option_label": ["nur eine"]},
)
assert resp.status_code == 400
assert "at least two options" in resp.text
# Verschieben: die letzte Frage nach oben
csrf = token_for(client, f"/forms/{pid}")
resp = client.post(
f"/forms/{pid}/questions/{ids[2]}/move", data={"direction": "up", "csrf_token": csrf}
)
assert resp.status_code == 303
assert question_ids(pid) == [ids[0], ids[2], ids[1]]
# Vorschau rendert das Formular ohne Absende-Knopf
preview = client.get(f"/forms/{pid}/preview")
assert preview.status_code == 200
assert 'type="submit">Submit' not in preview.text
def test_publish_needs_input_question(app: Any) -> None:
client = creator(app)
pid = create_form(client)
add_question(client, pid, "info", label="Nur Text")
resp = set_status(client, pid, "open")
assert resp.status_code == 400
assert form_row(pid).status == "draft"
def test_draft_is_not_reachable(app: Any) -> None:
client = creator(app)
pid = create_form(client)
token = form_row(pid).share_token
guest = new_client(app)
assert guest.get(f"/f/{token}").status_code == 404
assert guest.get("/f/doesnotexist").status_code == 404
def test_fill_as_user_once_and_edit(app: Any) -> None:
owner = creator(app)
pid, token, (q_name, q_food) = simple_form(owner)
pizza = option_ids(pid, q_food)[0]
user = participant(app)
# Startseite zeigt das offene Formular
assert "Sommerfest" in user.get("/").text
resp = fill(user, token, {f"q{q_name}": "Paul", f"q{q_food}": pizza})
assert resp.status_code == 303
assert resp.headers["location"] == f"/f/{token}/thanks"
assert response_count(pid) == 1
# Zweiter Aufruf: bereits teilgenommen, Ändern möglich
again = user.get(f"/f/{token}")
assert "already filled in" in again.text
assert f"/f/{token}/edit" in again.text
# Doppeltes Absenden (z. B. altes Formular im Browser) legt nichts an
csrf = token_for(user, "/")
user.post(f"/f/{token}", data={"csrf_token": csrf, f"q{q_name}": "Paul"})
assert response_count(pid) == 1
# Ändern
edit = user.get(f"/f/{token}/edit")
assert edit.status_code == 200
assert 'value="Paul"' in edit.text
resp = fill(user, token, {f"q{q_name}": "Paul Neu"}, path="/edit")
assert resp.status_code == 303
with Session(db.get_engine()) as s:
texts = set(s.scalars(select(Answer.value_text).where(Answer.question_id == q_name)))
assert texts == {"Paul Neu"}
# Auswahl wurde entfernt, weil im neuen Absenden leer
assert s.scalar(select(func.count()).where(Answer.question_id == q_food)) == 0
def test_users_access_requires_login(app: Any) -> None:
owner = creator(app)
_, token, _ = simple_form(owner)
guest = new_client(app)
resp = guest.get(f"/f/{token}")
assert resp.status_code == 303
assert resp.headers["location"].startswith("/login")
def test_validation_errors_keep_input(app: Any) -> None:
owner = creator(app)
pid = create_form(owner)
add_question(owner, pid, "short_text", label="Name", required="on", max_length="50")
add_question(owner, pid, "number", label="Anzahl", min="1", max="10", decimals="0")
add_question(owner, pid, "email", label="Mail")
assert save_settings(owner, pid, access="link").status_code == 303
assert set_status(owner, pid, "open").status_code == 303
token = form_row(pid).share_token
q_name, q_num, q_mail = question_ids(pid)
guest = new_client(app)
resp = fill(guest, token, {f"q{q_name}": "", f"q{q_num}": "12", f"q{q_mail}": "kein@"})
assert resp.status_code == 400
assert "Please answer this question." in resp.text
assert "The number is too large." in resp.text
assert "Please enter a valid email address." in resp.text
assert 'value="12"' in resp.text
assert response_count(pid) == 0
resp = fill(guest, token, {f"q{q_name}": "Gast", f"q{q_num}": "3", f"q{q_mail}": ""})
assert resp.status_code == 303
with Session(db.get_engine()) as s:
response = s.scalar(select(Response))
assert response is not None
assert response.user_id is None
numbers = list(s.scalars(select(Answer.value_number).where(Answer.question_id == q_num)))
assert [float(n) for n in numbers] == [3.0]
def test_link_password(app: Any) -> None:
owner = creator(app)
pid, token, (q_name, _) = simple_form(owner, access="link_password", link_password="geheim1")
guest = new_client(app)
page = guest.get(f"/f/{token}")
assert page.status_code == 200
assert 'name="password"' in page.text
csrf = token_for(guest, f"/f/{token}")
wrong = guest.post(f"/f/{token}/password", data={"password": "falsch", "csrf_token": csrf})
assert wrong.status_code == 400
right = guest.post(f"/f/{token}/password", data={"password": "geheim1", "csrf_token": csrf})
assert right.status_code == 303
page = guest.get(f"/f/{token}")
assert f'name="q{q_name}"' in page.text
assert fill(guest, token, {f"q{q_name}": "Gast"}).status_code == 303
assert response_count(pid) == 1
# Neues Passwort macht alte Freischaltungen ungültig
changed = save_settings(owner, pid, access="link_password", link_password="anderes2")
assert changed.status_code == 303
assert 'name="password"' in guest.get(f"/f/{token}").text
def test_link_password_needs_password(app: Any) -> None:
owner = creator(app)
pid = create_form(owner)
resp = save_settings(owner, pid, access="link_password")
assert resp.status_code == 400
assert form_row(pid).access == "users"
def test_restricted_access_via_group(app: Any) -> None:
owner = creator(app)
pid, token, (q_name, _) = simple_form(owner)
member_client = participant(app, "mia@example.de")
outsider = participant(app, "otto@example.de")
with Session(db.get_engine()) as s:
member = s.scalar(select(UserAccount).where(UserAccount.email == "mia@example.de"))
assert member is not None
group = groups.create(s, "Festausschuss", "", actor_id=member.id)
groups.add_member(s, group, member, actor_id=member.id)
s.commit()
group_pid = str(group.public_id)
resp = save_settings(owner, pid, access="restricted")
assert resp.status_code == 303
assert resp.headers["location"] == f"/forms/{pid}/access"
csrf = token_for(owner, f"/forms/{pid}/access")
resp = owner.post(f"/forms/{pid}/access", data={"groups": [group_pid], "csrf_token": csrf})
assert resp.status_code == 303
assert outsider.get(f"/f/{token}").status_code == 403
assert "Sommerfest" not in outsider.get("/").text
assert member_client.get(f"/f/{token}").status_code == 200
assert fill(member_client, token, {f"q{q_name}": "Mia"}).status_code == 303
def test_anonymous_participation(app: Any) -> None:
owner = creator(app)
pid, token, (q_name, _) = simple_form(owner, anonymous="on")
user = participant(app)
assert fill(user, token, {f"q{q_name}": "geheim"}).status_code == 303
with Session(db.get_engine()) as s:
response = s.scalar(select(Response))
assert response is not None
assert response.user_id is None
assert s.scalar(select(func.count()).select_from(FormParticipation)) == 1
again = user.get(f"/f/{token}")
assert "already filled in" in again.text
assert "/edit" not in again.text
assert user.get(f"/f/{token}/edit").status_code == 303
# Anonymität lässt sich nach der ersten Antwort nicht mehr abschalten
resp = save_settings(owner, pid)
assert resp.status_code == 400
assert form_row(pid).anonymous is True
def test_consent_required(app: Any) -> None:
owner = creator(app)
_, token, (q_name, _) = simple_form(
owner, access="link", require_consent="on", consent_text="Ich willige ein."
)
guest = new_client(app)
resp = fill(guest, token, {f"q{q_name}": "Gast"})
assert resp.status_code == 400
assert "Please confirm the consent." in resp.text
assert fill(guest, token, {f"q{q_name}": "Gast", "consent": "on"}).status_code == 303
with Session(db.get_engine()) as s:
response = s.scalar(select(Response))
assert response is not None
assert response.consent_at is not None
def test_closed_form(app: Any) -> None:
owner = creator(app)
pid, token, (q_name, _) = simple_form(owner, access="link")
assert set_status(owner, pid, "closed").status_code == 303
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}")
guest.post(f"/f/{token}", data={"csrf_token": csrf, f"q{q_name}": "Zu spät"})
assert response_count(pid) == 0
def test_responses_view_and_permissions(app: Any) -> None:
owner = creator(app)
pid, token, (q_name, _) = simple_form(owner)
user = participant(app)
assert fill(user, token, {f"q{q_name}": "Antwort von Paul"}).status_code == 303
listing = owner.get(f"/forms/{pid}/responses")
assert listing.status_code == 200
with Session(db.get_engine()) as s:
response = s.scalar(select(Response))
assert response is not None
rid = str(response.public_id)
assert rid in listing.text
detail = owner.get(f"/forms/{pid}/responses/{rid}")
assert "Antwort von Paul" in detail.text
# Teilnehmende und fremde Ersteller sehen nichts
assert pid not in user.get("/forms").text
assert user.get(f"/forms/{pid}/responses").status_code == 403
other = creator(app, "olga@example.de")
assert other.get(f"/forms/{pid}").status_code == 403
assert other.get(f"/forms/{pid}/responses/{rid}").status_code == 403
assert pid not in other.get("/forms").text
def test_delete_form(app: Any) -> None:
owner = creator(app)
pid, token, (q_name, _) = simple_form(owner, access="link")
guest = new_client(app)
assert fill(guest, token, {f"q{q_name}": "Gast"}).status_code == 303
csrf = token_for(owner, f"/forms/{pid}/settings")
assert owner.post(f"/forms/{pid}/delete", data={"csrf_token": csrf}).status_code == 400
resp = owner.post(f"/forms/{pid}/delete", data={"csrf_token": csrf, "confirm": "on"})
assert resp.status_code == 303
with Session(db.get_engine()) as s:
assert s.scalar(select(func.count()).select_from(Form)) == 0
assert s.scalar(select(func.count()).select_from(Response)) == 0
assert s.scalar(select(func.count()).select_from(Answer)) == 0
assert guest.get(f"/f/{token}").status_code == 404
+222
View File
@@ -0,0 +1,222 @@
# SPDX-License-Identifier: AGPL-3.0-or-later
"""Gruppenadministratoren, Gruppenersteller, Hierarchie (CI, PostgreSQL)."""
from __future__ import annotations
from typing import Any
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 add_question, fill, form_row, set_status
from surveybox import db
from surveybox.models import (
Form,
FormAccessEntry,
GroupMember,
GroupRole,
Role,
UserAccount,
UserGroup,
)
pytestmark = pytest.mark.db
def build_tree() -> dict[str, int]:
"""Gesamtwehr > Nord > Jugend; Gesamtwehr > Süd."""
with Session(db.get_engine()) as s:
top = UserGroup(name="Gesamtwehr")
s.add(top)
s.flush()
north = UserGroup(name="Nord", parent_id=top.id)
south = UserGroup(name="Süd", parent_id=top.id)
s.add_all([north, south])
s.flush()
youth = UserGroup(name="Jugend", parent_id=north.id)
s.add(youth)
s.commit()
return {"top": top.id, "north": north.id, "south": south.id, "youth": youth.id}
def user_id(email: str) -> int:
with Session(db.get_engine()) as s:
uid = s.scalar(select(UserAccount.id).where(UserAccount.email == email))
assert uid is not None
return uid
def give(email: str, group: int, *, member: bool = True, role: str | None = None) -> None:
uid = user_id(email)
with Session(db.get_engine()) as s:
if member:
s.add(GroupMember(group_id=group, user_id=uid))
if role:
s.add(GroupRole(group_id=group, user_id=uid, role=role))
s.commit()
def public_id(group: int) -> str:
with Session(db.get_engine()) as s:
return str(s.get(UserGroup, group).public_id) # type: ignore[union-attr]
def signed_in(app: Any, email: str, secret: str | None = None) -> TestClient:
client = new_client(app)
login(client, email)
if secret:
mfa = client.get("/login/mfa")
client.post("/login/mfa", data={"code": next_totp(secret),
"csrf_token": csrf_from(mfa.text), "next": "/"})
return client
def test_group_admin_needs_second_factor(app: Any) -> None:
ids = build_tree()
make_user(Role.PARTICIPANT, "gina@example.de")
give("gina@example.de", ids["north"], role="admin")
client = signed_in(app, "gina@example.de")
resp = client.get("/admin/groups")
assert resp.status_code == 303
assert "mfa_required_admin" in resp.headers["location"]
def test_group_admin_scope(app: Any) -> None:
ids = build_tree()
_, secret = make_user(Role.PARTICIPANT, "gina@example.de", with_totp=True)
give("gina@example.de", ids["north"], role="admin")
make_user(Role.PARTICIPANT, "sven@example.de")
give("sven@example.de", ids["south"])
client = signed_in(app, "gina@example.de", secret)
listing = client.get("/admin/groups").text
assert "Nord" in listing and "Jugend" in listing
assert "Süd" not in listing and "Gesamtwehr" not in listing
assert client.get(f"/admin/groups/{public_id(ids['south'])}").status_code == 403
assert client.get("/admin/users").status_code == 403
# Neue Gruppe nur unterhalb der eigenen
csrf = token_for(client, "/admin/groups")
resp = client.post("/admin/groups", data={"name": "Oben", "csrf_token": csrf})
assert resp.status_code == 400
resp = client.post("/admin/groups", data={"name": "Kinder", "csrf_token": csrf,
"parent": public_id(ids["youth"])})
assert resp.status_code == 303
# Neues Konto direkt in der Jugend, als Teilnehmer
youth_page = f"/admin/groups/{public_id(ids['youth'])}"
csrf = token_for(client, youth_page)
resp = client.post(f"{youth_page}/new-member", data={
"csrf_token": csrf, "display_name": "Jana", "email": "jana@example.de"})
assert resp.status_code == 200 and "/setup/" in resp.text
with Session(db.get_engine()) as s:
jana = s.scalar(select(UserAccount).where(UserAccount.email == "jana@example.de"))
assert jana is not None and jana.role == Role.PARTICIPANT
assert s.get(GroupMember, (ids["youth"], jana.id)) is not None
sven_pid = str(s.scalar(select(UserAccount.public_id).where(
UserAccount.email == "sven@example.de")))
jana_pid = str(jana.public_id)
# Jana wird Gruppenerstellerin; Sven (Süd) kann nicht geholt werden
resp = client.post(f"{youth_page}/roles", data={"csrf_token": csrf, "user": jana_pid,
"role": "creator"})
assert resp.status_code == 303
resp = client.post(f"{youth_page}/members", data={"csrf_token": csrf, "user": sven_pid})
assert resp.status_code == 403
# Die eigene oberste Gruppe lässt sich nicht löschen, Untergruppen schon
north_page = f"/admin/groups/{public_id(ids['north'])}"
csrf = token_for(client, north_page)
assert client.post(f"{north_page}/delete",
data={"csrf_token": csrf, "confirm": "on"}).status_code == 403
def test_group_creator_forms_and_inheritance(app: Any) -> None:
ids = build_tree()
make_user(Role.PARTICIPANT, "carl@example.de")
give("carl@example.de", ids["north"], member=False, role="creator")
make_user(Role.PARTICIPANT, "jule@example.de")
give("jule@example.de", ids["youth"])
make_user(Role.PARTICIPANT, "sven@example.de")
give("sven@example.de", ids["south"])
carl = signed_in(app, "carl@example.de")
# Nur in eigenen Gruppen
csrf = token_for(carl, "/forms")
resp = carl.post("/forms", data={"csrf_token": csrf, "title": "Ausflug",
"group": public_id(ids["south"])})
assert resp.status_code == 400
resp = carl.post("/forms", data={"csrf_token": csrf, "title": "Ausflug"})
assert resp.status_code == 400
resp = carl.post("/forms", data={"csrf_token": csrf, "title": "Ausflug",
"group": public_id(ids["north"])})
assert resp.status_code == 303
pid = resp.headers["location"].rsplit("/", 1)[-1]
form = form_row(pid)
assert form.access == "restricted" and form.group_id == ids["north"]
with Session(db.get_engine()) as s:
entries = list(s.scalars(select(FormAccessEntry.group_id).where(
FormAccessEntry.form_id == form.id)))
assert entries == [ids["north"]]
# "Alle angemeldeten Benutzer" ist gesperrt
csrf = token_for(carl, f"/forms/{pid}/settings")
resp = carl.post(f"/forms/{pid}/settings", data={
"csrf_token": csrf, "title": "Ausflug", "access": "users", "allow_edit": "until_close",
"deletion_mode": "anonymize", "guest_email": "none", "results_visibility": "never",
"group": public_id(ids["north"])})
assert resp.status_code == 400
access_page = carl.get(f"/forms/{pid}/access").text
assert "Jugend" in access_page and "Süd" not in access_page
add_question(carl, pid, "short_text", label="Name")
assert set_status(carl, pid, "open").status_code == 303
token = form_row(pid).share_token
qid = _question_id(pid)
# Mitglied der Untergruppe Jugend darf, Süd nicht
jule = signed_in(app, "jule@example.de")
assert jule.get(f"/f/{token}").status_code == 200
assert "Ausflug" in jule.get("/").text
assert fill(jule, token, {f"q{qid}": "Jule"}).status_code == 303
sven = signed_in(app, "sven@example.de")
assert sven.get(f"/f/{token}").status_code == 403
def test_group_admin_manages_forms_below(app: Any) -> None:
ids = build_tree()
make_user(Role.PARTICIPANT, "carl@example.de")
give("carl@example.de", ids["youth"], member=False, role="creator")
_, secret = make_user(Role.PARTICIPANT, "gina@example.de", with_totp=True)
give("gina@example.de", ids["north"], member=False, role="admin")
_, secret_s = make_user(Role.PARTICIPANT, "sina@example.de", with_totp=True)
give("sina@example.de", ids["south"], member=False, role="admin")
carl = signed_in(app, "carl@example.de")
csrf = token_for(carl, "/forms")
resp = carl.post("/forms", data={"csrf_token": csrf, "title": "Zeltlager",
"group": public_id(ids["youth"])})
pid = resp.headers["location"].rsplit("/", 1)[-1]
gina = signed_in(app, "gina@example.de", secret)
assert gina.get(f"/forms/{pid}").status_code == 200
assert "Zeltlager" in gina.get("/forms").text
assert gina.get(f"/forms/{pid}/team").status_code == 200 # Verwaltung wie Eigentümer
sina = signed_in(app, "sina@example.de", secret_s)
assert sina.get(f"/forms/{pid}").status_code == 403
assert "Zeltlager" not in sina.get("/forms").text
def _question_id(pid: str) -> int:
import uuid
with Session(db.get_engine()) as s:
form = s.scalar(select(Form).where(Form.public_id == uuid.UUID(pid)))
assert form is not None
return form.questions[0].id
+264
View File
@@ -0,0 +1,264 @@
# SPDX-License-Identifier: AGPL-3.0-or-later
"""Fragengruppen und Teilnahme mit einem Eintrag (ohne Datenbank)."""
from __future__ import annotations
from dataclasses import dataclass, field
from decimal import Decimal
from typing import Any
from zoneinfo import ZoneInfo
import pytest
from surveybox.forms import conditions, groups, types
TZ = ZoneInfo("Europe/Berlin")
@dataclass
class Q:
id: int
type: str
label: str = ""
config: dict[str, Any] = field(default_factory=dict)
position: int = 0
required: bool = False
def slot(qid: int, label: str, capacity: int | None = None, **extra: Any) -> Q:
option: dict[str, Any] = {"id": types.SINGLE_SLOT, "label": label}
if capacity:
option["capacity"] = capacity
return Q(qid, "slots", label, {"single": True, "options": [option], **extra})
def numbered(qs: list[Q]) -> list[Q]:
for index, q in enumerate(qs):
q.position = index
return qs
def shifts() -> list[Q]:
return numbered([
Q(1, "yes_no", "Helfen Sie mit?"),
Q(2, groups.GROUP, "Schichten", {"member_type": "slots", "max_select": 2}),
slot(3, "Fr früh", 3),
slot(4, "Fr spät", 3),
slot(5, "Sa früh"),
Q(6, "short_text", "Bemerkung"),
slot(7, "Einzeln"), # nach einer anderen Frage: nicht mehr in der Gruppe
])
# --------------------------------------------------------------------------
# Zugehörigkeit
# --------------------------------------------------------------------------
def test_members_are_following_questions_of_the_type() -> None:
qs = shifts()
assert [m.id for m in groups.resolve(qs)[2]] == [3, 4, 5]
assert groups.member_of(qs) == {3: 2, 4: 2, 5: 2}
def test_heading_or_other_group_ends_a_group() -> None:
qs = numbered([
Q(1, groups.GROUP, "A", {"member_type": "yes_no"}),
Q(2, "yes_no", "a"),
Q(3, "heading", "H"),
Q(4, "yes_no", "b"),
Q(5, groups.GROUP, "B", {"member_type": "yes_no"}),
Q(6, groups.GROUP, "C", {"member_type": "yes_no"}),
Q(7, "yes_no", "c"),
])
found = groups.resolve(qs)
assert [m.id for m in found[1]] == [2]
assert found[5] == []
assert [m.id for m in found[6]] == [7]
def test_legacy_slot_lists_do_not_join_a_group() -> None:
legacy = Q(3, "slots", "Alt", {"options": [{"id": "aaaaaa", "label": "x"},
{"id": "bbbbbb", "label": "y"}]})
qs = numbered([Q(1, groups.GROUP, "G", {"member_type": "slots"}), slot(2, "neu"), legacy])
assert [m.id for m in groups.resolve(qs)[1]] == [2]
def test_members_must_match_the_first_one() -> None:
a = {"options": [{"id": "aaaaaa", "label": "Rot"}, {"id": "bbbbbb", "label": "Grün"}]}
b = {"options": [{"id": "cccccc", "label": "Rot"}, {"id": "dddddd", "label": "Grün"}]}
c = {"options": [{"id": "eeeeee", "label": "Blau"}, {"id": "ffffff", "label": "Grün"}]}
qs = numbered([
Q(1, groups.GROUP, "M", {"member_type": "single_choice"}),
Q(2, "single_choice", "x", a), Q(3, "single_choice", "y", b), Q(4, "single_choice", "z", c),
Q(5, groups.GROUP, "R", {"member_type": "rating"}),
Q(6, "rating", "r1", {"scale_max": 5}), Q(7, "rating", "r2", {"scale_max": 7}),
Q(8, groups.GROUP, "J", {"member_type": "yes_no"}),
Q(9, "yes_no", "j1"), Q(10, "yes_no", "j2", {"label_yes": "Gern"}),
])
found = groups.resolve(qs)
assert [m.id for m in found[1]] == [2, 3]
assert [m.id for m in found[5]] == [6]
assert [m.id for m in found[8]] == [9]
def test_choice_with_other_cannot_be_grouped() -> None:
cfg = {"allow_other": True, "options": [{"id": "aaaaaa", "label": "x"}]}
qs = numbered([Q(1, groups.GROUP, "M", {"member_type": "single_choice"}),
Q(2, "single_choice", "x", cfg)])
assert groups.resolve(qs)[1] == []
def test_max_select_only_for_counting_types() -> None:
def group(**cfg: Any) -> Q:
return Q(1, groups.GROUP, config=cfg)
assert groups.max_select(group(member_type="slots", max_select=2)) == 2
assert groups.max_select(group(member_type="rating", max_select=2)) == 0
assert groups.max_select(group(member_type="slots")) == 0
assert groups.min_select(group(member_type="yes_no", min_select=1)) == 1
assert groups.min_select(group(member_type="rating", min_select=1)) == 0
# --------------------------------------------------------------------------
# Höchstzahl
# --------------------------------------------------------------------------
def booked() -> dict[str, Any]:
return {"value_json": {"selected": [types.SINGLE_SLOT]}}
def test_too_many_counts_bookings() -> None:
qs = shifts()
check = groups.count_errors
assert check(qs, {3: booked(), 4: booked()}, set()) == {}
assert check(qs, {3: booked(), 4: booked(), 5: booked()}, set()) == {2: "group_too_many"}
# Ausgeblendete Fragen und Gruppen zählen nicht
assert check(qs, {3: booked(), 4: booked(), 5: booked()}, {5}) == {}
assert check(qs, {3: booked(), 4: booked(), 5: booked()}, {2}) == {}
# Fragen außerhalb der Gruppe zählen nicht
assert check(qs, {3: booked(), 4: booked(), 7: booked()}, set()) == {}
def test_too_many_counts_yes_only() -> None:
qs = numbered([Q(1, groups.GROUP, "J", {"member_type": "yes_no", "max_select": 1}),
Q(2, "yes_no", "a"), Q(3, "yes_no", "b")])
yes, no = {"value_bool": True}, {"value_bool": False}
assert groups.count_errors(qs, {2: yes, 3: no}, set()) == {}
assert groups.count_errors(qs, {2: yes, 3: yes}, set()) == {1: "group_too_many"}
def test_min_select() -> None:
qs = shifts()
qs[1].config.update(min_select=1, max_select=1)
assert groups.count_errors(qs, {}, set()) == {2: "group_too_few"}
assert groups.count_errors(qs, {4: booked()}, set()) == {}
# Weniger sichtbare Zeilen als die Mindestzahl: dann zählen alle sichtbaren
qs[1].config.update(min_select=3, max_select=0)
assert groups.count_errors(qs, {3: booked(), 4: booked()}, {5}) == {}
assert groups.count_errors(qs, {3: booked()}, {5}) == {2: "group_too_few"}
# Ausgeblendete Gruppe verlangt nichts
assert groups.count_errors(qs, {}, {2, 3, 4, 5}) == {}
def test_required_rows_in_slot_group_are_ruled_by_the_group() -> None:
qs = shifts()
for q in qs[2:5]:
q.required = True # drei Pflicht-Schichten, höchstens eine wählbar
ruled = groups.required_by_group(qs)
assert ruled == {3, 4, 5}
# Die einzelne Schicht ist dann keine Pflicht mehr
assert types.parse_answer(qs[2], {}, TZ, required=False).error is None
assert types.parse_answer(qs[2], {}, TZ).error == "required"
# Ja/Nein-Zeilen behalten ihre Pflicht
yn = numbered([Q(1, groups.GROUP, "J", {"member_type": "yes_no"}), Q(2, "yes_no", "a")])
assert groups.required_by_group(yn) == set()
# --------------------------------------------------------------------------
# Bedingungen und Aufbau der Seite
# --------------------------------------------------------------------------
def test_condition_on_group_hides_all_members() -> None:
qs = shifts()
qs[1].config["condition"] = {"action": "show", "match": "all",
"rules": [{"q": 1, "op": "eq", "value": "yes"}]}
assert conditions.hidden_ids(qs, {"q1": ["no"]}) == {2, 3, 4, 5}
assert conditions.hidden_ids(qs, {"q1": ["yes"]}) == set()
def test_member_keeps_its_own_condition() -> None:
qs = shifts()
qs[3].config["condition"] = {"action": "show", "match": "all",
"rules": [{"q": 3, "op": "contains", "value": "single"}]}
assert conditions.hidden_ids(qs, {}) == {4}
assert conditions.hidden_ids(qs, {"q3": ["single"]}) == set()
def test_layout_shows_group_instead_of_members() -> None:
qs = shifts()
items = conditions.layout(qs)[0]["sections"][0]["items"]
assert [q.id for q in items] == [1, 2, 6, 7]
def test_single_slot_rule_option_is_signed_up() -> None:
assert conditions.options_for_rules(slot(1, "x")) == [(types.SINGLE_SLOT, "signed up")]
# --------------------------------------------------------------------------
# Einstellungen und Antworten
# --------------------------------------------------------------------------
def test_group_config() -> None:
cfg = types.parse_config(groups.GROUP, {"member_type": ["slots"], "max_select": ["3"],
"min_select": ["1"]})
assert cfg == {"member_type": "slots", "min_select": 1, "max_select": 3}
cfg = types.parse_config(groups.GROUP, {"member_type": ["rating"], "max_select": ["3"]})
assert cfg == {"member_type": "rating", "min_select": 0, "max_select": 0}
with pytest.raises(types.ConfigError):
types.parse_config(groups.GROUP, {"member_type": ["slots"], "min_select": ["2"],
"max_select": ["1"]})
with pytest.raises(types.ConfigError):
types.parse_config(groups.GROUP, {"member_type": ["poll"]})
with pytest.raises(types.ConfigError):
types.parse_config(groups.GROUP, {"member_type": ["slots"], "max_select": ["-1"]})
def test_single_slot_config_keeps_option_id() -> None:
cfg = types.parse_config("slots", {"label": ["Fr früh"], "capacity": ["4"],
"waitlist": ["on"]})
assert cfg["single"] is True
assert cfg["options"] == [{"id": types.SINGLE_SLOT, "label": "Fr früh", "capacity": 4}]
assert cfg["waitlist"] is True
unlimited = types.parse_config("slots", {"label": ["x"], "capacity": [""]})
assert "capacity" not in unlimited["options"][0]
with pytest.raises(types.ConfigError):
types.parse_config("slots", {"label": ["x"], "capacity": ["0"]})
def test_slot_list_mode_still_works() -> None:
cfg = types.parse_config("slots", {"slot_mode": ["list"], "option_label": ["A", "B"],
"option_id": ["", ""], "option_capacity": ["2", ""]})
assert "single" not in cfg
assert [o["label"] for o in cfg["options"]] == ["A", "B"]
def test_single_slot_answer() -> None:
q = slot(5, "Fr früh", 2)
result = types.parse_answer(q, {"q5": ["single"]}, TZ)
assert result.stored == {"value_json": {"selected": ["single"]}}
assert types.parse_answer(q, {}, TZ).stored is None
assert types.parse_answer(q, {"q5": ["other"]}, TZ).error == "choice"
assert types.display_answer(q, result.stored or {}, TZ) == "signed up"
assert types.display_answer(q, {}, TZ) == ""
assert types.raw_from_answer(q, result.stored or {}, TZ) == {"q5": ["single"]}
def test_group_has_no_answer() -> None:
assert not types.TYPES[groups.GROUP].is_input
assert types.parse_answer(Q(1, groups.GROUP), {"q1": ["x"]}, TZ).stored is None
assert types.parse_answer(Q(2, "rating", config={"scale_max": 5}), {"q2": ["3"]},
TZ).stored == {"value_number": Decimal(3)}
+279
View File
@@ -0,0 +1,279 @@
# 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]:
return [path_of(u) for u in re.findall(r"https?://\S+", text) if part in u]
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)) == [(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
+123
View File
@@ -0,0 +1,123 @@
# SPDX-License-Identifier: AGPL-3.0-or-later
"""Gäste und Selbstregistrierung ohne Datenbank (braucht die Modelle)."""
from __future__ import annotations
import time
import uuid
from types import SimpleNamespace
import pytest
pytest.importorskip("sqlalchemy")
from surveybox.accounts import registration
from surveybox.forms import guests
from surveybox.mail import notify
SECRET = "s" * 48
def form(**kw: object) -> SimpleNamespace:
return SimpleNamespace(**{"anonymous": False, "guest_email": "optional", **kw})
def test_registration_token_roundtrip_and_expiry() -> None:
now = time.time()
token = registration.make_token(SECRET, "anna@example.de", "Anna Ä", "de", now)
pending = registration.parse_token(SECRET, token, now + 60)
assert pending == registration.Pending("anna@example.de", "Anna Ä", "de")
assert registration.parse_token(SECRET, token, now + 25 * 3600) is None
assert registration.parse_token("x" * 48, token, now) is None
raw, _, mac = token.partition(".")
other = registration.make_token(SECRET, "eve@example.de", "Eve", "de", now)
assert registration.parse_token(SECRET, other.partition(".")[0] + "." + mac, now) is None
assert registration.parse_token(SECRET, raw, now) is None
assert registration.parse_token(SECRET, "", now) is None
def test_parse_guest_email() -> None:
user = SimpleNamespace(id=1)
assert guests.parse_email(form(), user, "a@b.de").email is None # angemeldet
assert guests.parse_email(form(anonymous=True), None, "a@b.de").email is None
assert guests.parse_email(form(guest_email="none"), None, "a@b.de").email is None
assert guests.parse_email(form(), None, " Anna@Example.DE ").email == "anna@example.de"
assert guests.parse_email(form(), None, "").error is None
assert guests.parse_email(form(guest_email="required"), None, "").error == "required"
assert guests.parse_email(form(), None, "kein@").error == "email"
def test_wants_link() -> None:
assert guests.wants_link(form(), None)
assert not guests.wants_link(form(anonymous=True), None)
assert not guests.wants_link(form(), SimpleNamespace(id=1))
def test_guest_unsubscribe_token() -> None:
contact = SimpleNamespace(public_id=uuid.uuid4(), email="g@example.de", language="de",
confirmed_at=None, notify=True)
recipient = notify.for_guest(contact, SimpleNamespace(default_language="de")) # type: ignore[arg-type]
token = notify.unsubscribe_token(SECRET, recipient, "promoted")
found = notify.parse_unsubscribe(SECRET, token)
assert found is not None and found.kind == "guest" and found.public_id == contact.public_id
def test_guest_needs_confirmation_for_notifications() -> None:
contact = SimpleNamespace(public_id=uuid.uuid4(), email="g@example.de", language=None,
confirmed_at=None, notify=True)
settings = SimpleNamespace(default_language="fr")
recipient = notify.for_guest(contact, settings) # type: ignore[arg-type]
assert recipient.language == "fr"
assert not notify.allowed(None, recipient, "promoted", None) # type: ignore[arg-type]
contact.confirmed_at = 1
assert notify.allowed(None, recipient, "promoted", None) # type: ignore[arg-type]
assert not notify.allowed(None, recipient, "comment_new", None) # type: ignore[arg-type]
contact.notify = False
assert not notify.allowed(None, recipient, "promoted", None) # type: ignore[arg-type]
def test_email_from_answers() -> None:
questions = [SimpleNamespace(id=1, type="short_text"), SimpleNamespace(id=2, type="email"),
SimpleNamespace(id=3, type="email")]
stored = {2: {"value_text": " Anna@Example.DE "}, 3: {"value_text": "b@example.de"}}
assert guests.email_from_answers(
form(guest_email="question", questions=questions), stored, set()) == "anna@example.de"
# Ausgeblendete Frage zählt nicht, die nächste E-Mail-Frage schon
assert guests.email_from_answers(
form(guest_email="question", questions=questions), stored, {2}) == "b@example.de"
assert guests.email_from_answers(form(guest_email="optional", questions=questions),
stored, set()) is None
assert guests.email_from_answers(
form(guest_email="question", anonymous=True, questions=questions), stored, set()) is None
# Das eigene Feld gibt es dann nicht
assert guests.parse_email(form(guest_email="question"), None, "a@b.de").email is None
def test_followup_document_token() -> None:
from surveybox.forms import followups
doc = SimpleNamespace(public_id=uuid.uuid4())
now = time.time()
token = followups.document_token(SECRET, doc, "u:x", int(now + 60)) # type: ignore[arg-type]
assert followups.parse_document_token(SECRET, token, now) == doc.public_id
assert followups.parse_document_token(SECRET, token, now + 120) is None # abgelaufen
assert followups.parse_document_token("x" * 48, token, now) is None
raw, _, mac = token.partition(".")
assert followups.parse_document_token(SECRET, raw + "." + mac[::-1], now) is None
def test_followup_placeholders() -> None:
from surveybox.forms import followups
f = SimpleNamespace(title="Fest")
assert followups.personalize("Hallo {name}, zu {form}: {x} %s {}", "Anna", f) == ( # type: ignore[arg-type]
"Hallo Anna, zu Fest: {x} %s {}")
def test_removed_options() -> None:
from surveybox.forms import changes
before = [{"id": "a", "label": "A"}, {"id": "b", "label": "B"}]
after = [{"id": "b", "label": "B2"}]
assert changes.removed_options(before, after) == [{"id": "a", "label": "A"}]
assert changes.removed_options(before, before) == []
+105
View File
@@ -0,0 +1,105 @@
# SPDX-License-Identifier: AGPL-3.0-or-later
from __future__ import annotations
from pathlib import Path
import pytest
from babel.messages.mofile import write_mo
from babel.messages.pofile import read_po
from surveybox import i18n
SOURCE_LOCALE = Path(i18n.__file__).parent / "locale"
@pytest.fixture
def compiled_locale(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
for lang in i18n.SUPPORTED_LANGUAGES:
po = SOURCE_LOCALE / lang / "LC_MESSAGES" / "messages.po"
target = tmp_path / lang / "LC_MESSAGES"
target.mkdir(parents=True)
with po.open("rb") as fh:
catalog = read_po(fh, locale=lang)
with (target / "messages.mo").open("wb") as fh:
write_mo(fh, catalog)
monkeypatch.setattr(i18n, "LOCALE_DIR", tmp_path)
i18n.translations.cache_clear()
yield tmp_path
i18n.translations.cache_clear()
@pytest.mark.parametrize(
("cookie", "header", "expected"),
[
("fr", "de-DE,de;q=0.9", "fr"),
(None, "de-DE,de;q=0.9,en;q=0.8", "de"),
(None, "en-US,en;q=0.9", "en"),
(None, "it-IT,fr;q=0.5,en;q=0.7", "en"),
(None, "fr-CH, fr;q=0.9, en;q=0.8", "fr"),
(None, "es, *;q=0.5", "de"),
(None, None, "de"),
("xx", "en", "en"),
(None, "en;q=0, fr", "fr"),
(None, "de;q=abc, en", "en"),
],
)
def test_negotiate_language(cookie: str | None, header: str | None, expected: str) -> None:
assert i18n.negotiate_language(cookie, header, "de") == expected
def test_unknown_default_falls_back_to_german() -> None:
assert i18n.negotiate_language(None, None, "xx") == "de"
def test_catalogs_cover_the_same_messages() -> None:
ids: dict[str, set[str]] = {}
for lang in i18n.SUPPORTED_LANGUAGES:
with (SOURCE_LOCALE / lang / "LC_MESSAGES" / "messages.po").open("rb") as fh:
catalog = read_po(fh, locale=lang)
ids[lang] = {m.id for m in catalog if m.id}
missing = [m.id for m in catalog if m.id and not m.string]
assert not missing, f"{lang}: unübersetzt: {missing}"
assert ids["de"] == ids["en"] == ids["fr"]
def test_template_messages_are_in_catalog() -> None:
from babel.messages.extract import extract_from_dir
method_map = [("**/templates/**.html", "jinja2"), ("**.py", "python")]
options = {"**/templates/**.html": {"extensions": "jinja2.ext.i18n"}}
extracted = {
msg[2]
for msg in extract_from_dir(
str(SOURCE_LOCALE.parent), method_map=method_map, options_map=options
)
if isinstance(msg[2], str)
}
with (SOURCE_LOCALE / "de" / "LC_MESSAGES" / "messages.po").open("rb") as fh:
catalog_ids = {m.id for m in read_po(fh) if m.id}
assert extracted <= catalog_ids, f"Fehlen im Katalog: {extracted - catalog_ids}"
def test_gettext_follows_context_language(compiled_locale: Path) -> None:
token = i18n.set_language("de")
try:
assert i18n.gettext("Database") == "Datenbank"
finally:
i18n.reset_language(token)
token = i18n.set_language("fr")
try:
assert i18n.gettext("Database") == "Base de données"
finally:
i18n.reset_language(token)
token = i18n.set_language("en")
try:
assert i18n.gettext("Database") == "Database"
finally:
i18n.reset_language(token)
def test_unsupported_language_is_not_set() -> None:
token = i18n.set_language("xx")
try:
assert i18n.get_language() == "de"
finally:
i18n.reset_language(token)
+313
View File
@@ -0,0 +1,313 @@
# 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 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
assert known.text.replace(csrf_from(known.text), "") == unknown.text.replace(
csrf_from(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 <surveybox@example.org>"
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
+52
View File
@@ -0,0 +1,52 @@
# SPDX-License-Identifier: AGPL-3.0-or-later
"""Eigene Mail-Vorlagen ohne Datenbank: Platzhalter, Prüfung, Anwenden."""
from __future__ import annotations
from types import SimpleNamespace
from surveybox.mail import custom, render
def context(**extra: object) -> dict[str, object]:
return {"app_name": "Feuerwehr", "origin": "https://x", "name": "Erika",
"form": SimpleNamespace(title="Sommerfest"), "link": "https://x/f/abc",
"guest": False, "links_url": "https://x/links", "unsubscribe_url": None,
"settings_url": "https://x/s", **extra}
def test_placeholders_follow_the_template() -> None:
assert {"greeting", "details", "app", "title", "name", "link", "entry"} <= set(
custom.placeholders("promoted"))
assert "title" not in custom.placeholders("invite")
assert custom.required("invite") == ["link"]
assert custom.required("register_exists") == ["forgot_url", "login_url"]
def test_validate() -> None:
ok = custom.clean(" Platz für {name}\n ", "{greeting}\r\n\r\nSchön!\n\n{details}")
assert ok.subject == "Platz für {name}" and "\r" not in ok.body
assert custom.validate("promoted", ok) == []
errors = dict(custom.validate("promoted", custom.Custom("", "Hallo {nope} ohne Link")))
assert set(errors) == {"subject", "unknown", "missing"}
assert errors["unknown"] == "{nope}" and errors["missing"] == "{link}"
assert custom.validate("promoted", custom.Custom("x", "Hier: {link}")) == []
def test_render_with_custom_text() -> None:
own = custom.Custom("Platz frei bei {app}: {title}",
"{greeting}\n\nWir freuen uns!\n\n{details}\n\nEure Feuerwehr")
mail = render.render("promoted", "en", context(entry="Früh"), own)
assert mail.subject == "Platz frei bei Feuerwehr: Sommerfest"
assert mail.text.startswith("Hello Erika,\n\nWir freuen uns!\n\nA place")
assert "https://x/f/abc" in mail.text and "Eure Feuerwehr" in mail.text
assert mail.text.count("Hello Erika") == 1 # Anrede nicht doppelt
assert '<a href="https://x/f/abc">' in mail.html and "-- \n" in mail.text
# Ohne Namen: allgemeine Anrede
plain = render.render("promoted", "en", context(name="", entry="Früh"), own)
assert plain.text.startswith("Hello,\n\nWir")
def test_preview_with_missing_values() -> None:
mail = render.render("confirmed", "en", {"name": "A"}, strict=False)
assert mail.subject and mail.text
+61
View File
@@ -0,0 +1,61 @@
# SPDX-License-Identifier: AGPL-3.0-or-later
"""E-Mail-Vorlagen über die Oberfläche und beim Versand (CI)."""
from __future__ import annotations
from typing import Any
import pytest
pytest.importorskip("fastapi")
from helpers import make_user, new_client, token_for
from test_mail import admin, content, forgot, messages
from surveybox.models import Role
pytestmark = pytest.mark.db
def save(client: Any, kind: str, language: str, subject: str, body: str) -> Any:
url = f"/admin/mail/templates/{kind}?lang={language}"
return client.post(f"/admin/mail/templates/{kind}", data={
"csrf_token": token_for(client, url), "language": language, "subject": subject,
"body": body})
def test_edit_preview_and_use_template(app: Any) -> None:
root = admin(app)
page = root.get("/admin/mail/templates").text
assert "Reset password" in page and "standard" in page
edit = root.get("/admin/mail/templates/password_reset?lang=en").text
assert "{greeting}" in edit and "Standard text" in edit
# Ohne {details} und ohne {link} kommt die Mail ohne Link an: abgelehnt
resp = save(root, "password_reset", "en", "Neues Passwort", "Hallo {wer}")
assert resp.status_code == 400
assert "Unknown placeholders: {wer}" in resp.text and "{link}" in resp.text
for language in ("de", "en", "fr"):
resp = save(root, "password_reset", language, "Neues Passwort für {app}",
"{greeting}\n\nDein Zugang bei der Feuerwehr:\n{link}\n\nGruß <b>")
assert resp.status_code == 303
page = root.get("/admin/mail/templates/password_reset?lang=en").text
assert "Preview with sample data" in page and "Gruß &lt;b&gt;" in page
make_user(Role.PARTICIPANT, "anna@example.de")
forgot(new_client(app), "anna@example.de")
(mail,) = messages("password_reset")
found = content(mail)
assert found["subject"].startswith("Neues Passwort für ")
assert "Dein Zugang bei der Feuerwehr:" in found["text"] and "/setup/" in found["text"]
assert "Gruß &lt;b&gt;" in found["html"]
# Zurück zum Standard
for language in ("de", "en", "fr"):
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
def test_unknown_kind_and_rights(app: Any) -> None:
root = admin(app)
assert root.get("/admin/mail/templates/followup").status_code == 404
assert new_client(app).get("/admin/mail/templates").status_code in (303, 401, 403)
+261
View File
@@ -0,0 +1,261 @@
# SPDX-License-Identifier: AGPL-3.0-or-later
"""Mail ohne Datenbank: Einstellungen, Vorlagen, Aufbau der Nachricht, Abmeldelinks."""
from __future__ import annotations
import uuid
from email import message_from_bytes
from email.policy import default
from pathlib import Path
from types import SimpleNamespace
from typing import Any
import pytest
from surveybox.mail import config, render, smtp
from surveybox.mail.config import MailConfig, MailConfigError
SECRET = "s" * 48
TEMPLATES = Path(render.TEMPLATE_DIR)
def fields(**values: str) -> dict[str, list[str]]:
return {k: [v] for k, v in values.items()}
# --------------------------------------------------------------------------
# Einstellungen
# --------------------------------------------------------------------------
def test_parse_form_encrypts_password_and_keeps_it() -> None:
cfg = config.parse_form(
MailConfig(),
fields(host="SMTP.Example.org", port="587", security="starttls", username="relay",
password="geheim 123", from_address="sb@example.org", from_name="Sommerfest\nX",
reply_to="team@example.org"),
SECRET,
)
assert cfg.host == "smtp.example.org"
assert cfg.from_name == "Sommerfest X"
assert "geheim" not in cfg.password_enc
assert cfg.password(SECRET) == "geheim 123"
# Leeres Passwortfeld behält das gespeicherte
again = config.parse_form(cfg, fields(host="smtp.example.org", port="465", security="tls",
username="relay", from_address="sb@example.org"),
SECRET)
assert again.password(SECRET) == "geheim 123"
assert again.security == "tls"
removed = config.parse_form(cfg, fields(host="smtp.example.org", port="587",
security="starttls", username="relay",
from_address="sb@example.org", password_remove="on"),
SECRET)
assert not removed.has_password
assert "password_enc" not in config.summary(cfg)
@pytest.mark.parametrize(
("values", "code"),
[
({"host": "https://smtp.example.org"}, "mail_host_invalid"),
({"host": "smtp.example.org:587"}, "mail_host_invalid"),
({"port": "0"}, "mail_port_invalid"),
({"security": "none"}, "mail_security_invalid"),
({"from_address": "Anna <a@example.org>"}, "mail_address_invalid"),
({"reply_to": "a@example.org\r\nBcc: x@example.org"}, "mail_address_invalid"),
({"from_address": ""}, "mail_address_invalid"),
({"password": "a\nb"}, "mail_password_invalid"),
],
)
def test_parse_form_rejects(values: dict[str, str], code: str) -> None:
base = {"host": "smtp.example.org", "port": "587", "security": "starttls",
"username": "relay", "from_address": "sb@example.org"}
with pytest.raises(MailConfigError) as exc:
config.parse_form(MailConfig(), fields(**{**base, **values}), SECRET)
assert exc.value.code == code
def test_not_configured_without_host() -> None:
assert not MailConfig().configured
assert MailConfig(host="x.de", from_address="a@x.de").configured
assert config.from_dict({"port": "abc", "security": "plain"}) == MailConfig()
# --------------------------------------------------------------------------
# Vorlagen
# --------------------------------------------------------------------------
BASE: dict[str, Any] = {
"app_name": "Surveybox", "origin": "https://umfrage.example", "name": "Anna <b>",
"form": SimpleNamespace(title="Fest <script>"), "unsubscribe_url": None,
"settings_url": "https://umfrage.example/account/notifications",
"guest": False, "links_url": "https://umfrage.example/links",
}
CONTEXTS: dict[str, dict[str, Any]] = {
"test": {},
"invite": {"link": "https://umfrage.example/setup/abc"},
"password_reset": {"link": "https://umfrage.example/setup/abc"},
"participation": {"link": "https://umfrage.example/f/t"},
"promoted": {"entry": "Fr früh", "link": "https://umfrage.example/f/t"},
"confirmed": {"options": [{"id": "a", "date": "2026-07-01", "time": None,
"duration": None, "label": "Grill"}],
"link": "https://umfrage.example/f/t", "calendar": None},
"comment_new": {"pending": True, "link": "https://umfrage.example/forms/x/comments"},
"comment_published": {"link": "https://umfrage.example/f/t"},
"slot_full": {"entry": "Fr", "link": "https://umfrage.example/forms/x/responses"},
"deadline": {"responses": 2, "link": "https://umfrage.example/forms/x/responses"},
"guest_receipt": {"link": "https://umfrage.example/r/abc", "edited": False,
"can_edit": True, "confirm": "https://umfrage.example/g/confirm/x"},
"guest_erase": {"link": "https://umfrage.example/g/erase/abc.123.def"},
"guest_export": {"link": "https://umfrage.example/g/export/abc.123.def"},
"guest_links": {"links": [(SimpleNamespace(title="Fest <script>"),
"https://umfrage.example/r/abc")]},
"register": {"link": "https://umfrage.example/register/abc",
"login_url": "https://umfrage.example/login",
"forgot_url": "https://umfrage.example/forgot"},
"register_exists": {"link": None, "login_url": "https://umfrage.example/login",
"forgot_url": "https://umfrage.example/forgot"},
"followup": {"custom_subject": "Unterlagen <Fest>", "body": "Hallo Anna <b>,\n\nsiehe unten.",
"documents": [("Programm <pdf>", "https://umfrage.example/d/abc.def")],
"expires": "24. Februar 2027", "link": ""},
"reminder": {"link": "https://umfrage.example/f/t", "closes": "1. Juli 2026, 18:00"},
"retention_notice": {"mode": "anonymize", "date": "1. Juli 2026", "responses": 3,
"link": "https://umfrage.example/forms/x/responses",
"settings_link": "https://umfrage.example/forms/x/settings"},
"digest": {"items": [{"title": "Fest <script>", "new": 2, "changed": 1,
"link": "https://umfrage.example/forms/x/responses"}],
"link": ""},
"changed": {"question": "Termin", "options": [{"id": "a", "date": "2026-07-01",
"time": None, "duration": None,
"label": ""}],
"link": "https://umfrage.example/f/t"},
}
GUEST_TEMPLATES = {"guest_receipt", "guest_links", "guest_erase", "guest_export"}
def test_every_template_has_a_context() -> None:
assert {p.stem for p in TEMPLATES.glob("*.txt")} == set(CONTEXTS)
@pytest.mark.parametrize("name", sorted(CONTEXTS))
@pytest.mark.parametrize("language", ["de", "en", "fr"])
def test_templates_render(name: str, language: str) -> None:
rendered = render.render(name, language, {**BASE, **CONTEXTS[name]})
assert rendered.subject and "\n" not in rendered.subject
if name not in GUEST_TEMPLATES:
assert "Anna <b>" in rendered.text
# HTML ist escaped, Links sind klickbar
assert "<script>" not in rendered.html
assert "Anna &lt;b&gt;" in rendered.html or name in GUEST_TEMPLATES
assert 'href="https://umfrage.example' in rendered.html or name == "test"
def test_unsubscribe_link_in_footer() -> None:
url = "https://umfrage.example/mail/unsubscribe/abc.def"
rendered = render.render("promoted", "en", {**BASE, **CONTEXTS["promoted"],
"unsubscribe_url": url})
assert url in rendered.text
assert f'<a href="{url}">' in rendered.html
def test_linkify_keeps_only_https() -> None:
html = render.to_html('Siehe https://x.example/a?b=1&c=2. und javascript:alert(1) "x"')
assert '<a href="https://x.example/a?b=1&amp;c=2">' in html
assert "javascript:alert(1)" in html and 'href="javascript' not in html
# --------------------------------------------------------------------------
# Nachricht
# --------------------------------------------------------------------------
def test_build_message_headers() -> None:
cfg = MailConfig(host="smtp.example.org", from_address="sb@example.org",
from_name="Feuerwehr Titisee-Neustadt")
out = smtp.Outgoing(
recipient="anna@example.org", subject="Betreff\r\nBcc: evil@example.org",
text="Hallo", html="<p>Hallo</p>", reply_to="team@example.org",
headers={"List-Unsubscribe": "<https://x/mail/unsubscribe/t>",
"List-Unsubscribe-Post": "List-Unsubscribe=One-Click"},
)
raw = smtp.build(cfg, out, "umfrage.example").as_bytes()
parsed = message_from_bytes(raw, policy=default)
assert parsed["From"] == "Feuerwehr Titisee-Neustadt <sb@example.org>"
assert parsed["Reply-To"] == "team@example.org"
assert parsed["Subject"] == "Betreff Bcc: evil@example.org"
assert parsed["Bcc"] is None
assert parsed["Auto-Submitted"] == "auto-generated"
assert parsed["List-Unsubscribe-Post"] == "List-Unsubscribe=One-Click"
assert parsed["Message-ID"].endswith("@umfrage.example>")
assert parsed.get_body(("html",)) is not None
def test_send_now_reports_connection_errors() -> None:
cfg = MailConfig(host="127.0.0.1", port=1, from_address="sb@example.org")
error = smtp.send_now(cfg, "", smtp.Outgoing("a@example.org", "s", "t"), "x")
assert error and "Error" in error
# --------------------------------------------------------------------------
# Abmeldelinks (braucht die Modelle)
# --------------------------------------------------------------------------
def test_unsubscribe_token_roundtrip() -> None:
pytest.importorskip("sqlalchemy")
from surveybox.mail import notify
user = SimpleNamespace(public_id=uuid.uuid4())
form = SimpleNamespace(public_id=uuid.uuid4())
token = notify.unsubscribe_token(SECRET, user, "promoted", form) # type: ignore[arg-type]
found = notify.parse_unsubscribe(SECRET, token)
assert found is not None
assert (found.user_public_id, found.event, found.form_public_id) == (
user.public_id, "promoted", form.public_id)
assert notify.parse_unsubscribe("x" * 48, token) is None
raw, _, mac = token.partition(".")
assert notify.parse_unsubscribe(SECRET, raw + "." + mac[:-2] + "AA") is None
assert notify.parse_unsubscribe(SECRET, "garbage") is None
def test_preferences_default_on() -> None:
pytest.importorskip("sqlalchemy")
from surveybox.mail import notify
user = SimpleNamespace(is_active=True, notify_prefs={})
assert notify.wants(user, "promoted") # type: ignore[arg-type]
notify.turn_off(user, "promoted") # type: ignore[arg-type]
assert not notify.wants(user, "promoted") # type: ignore[arg-type]
notify.set_prefs(user, ["promoted"]) # type: ignore[arg-type]
assert notify.wants(user, "promoted") and not notify.wants(user, "deadline") # type: ignore[arg-type]
assert not notify.wants(SimpleNamespace(is_active=False, notify_prefs={}), "promoted") # type: ignore[arg-type]
def test_guest_variants() -> None:
# Ohne Namen: neutrale Anrede; Gäste bekommen den Hinweis auf "Meine Links"
ctx = {**BASE, **CONTEXTS["promoted"], "name": "", "guest": True}
text = render.render("promoted", "en", ctx).text
assert text.startswith("Hello,") and "https://umfrage.example/links" in text
receipt = render.render("guest_receipt", "en", {**BASE, **CONTEXTS["guest_receipt"],
"confirm": None, "edited": True})
assert "changed answer" in receipt.text and "confirm your address" not in receipt.text
assert receipt.subject.startswith("Your answer has been changed")
def test_guest_receipt_names_planned_followups() -> None:
ctx = {**BASE, **CONTEXTS["guest_receipt"]}
plain = render.render("guest_receipt", "en", ctx).text
assert "further information" not in plain and "confirm your address" in plain
planned = render.render("guest_receipt", "en", {**ctx, "followups_planned": True}).text
assert "You only receive it if you confirm your email address" in planned
assert "https://umfrage.example/g/confirm/x" in planned
def test_followup_mail_keeps_text_and_lists_links() -> None:
rendered = render.render("followup", "de", {**BASE, **CONTEXTS["followup"]})
assert rendered.subject == "Unterlagen <Fest>"
assert rendered.text.startswith("Hallo Anna <b>,")
assert "https://umfrage.example/d/abc.def" in rendered.text
assert "Unterlagen &lt;Fest&gt;" not in rendered.html # Betreff steht nicht im Text
assert '<a href="https://umfrage.example/d/abc.def">' in rendered.html
+437
View File
@@ -0,0 +1,437 @@
# SPDX-License-Identifier: AGPL-3.0-or-later
"""Phase 3b gegen PostgreSQL: Medien, Bildauswahl, Datei-Upload, Team, Vorlagen (CI)."""
from __future__ import annotations
import io
import uuid
from typing import Any
import pytest
pytest.importorskip("fastapi")
pytest.importorskip("PIL")
from fastapi.testclient import TestClient
from helpers import new_client, token_for
from sqlalchemy import func, select
from sqlalchemy.orm import Session
from test_forms import (
add_question,
create_form,
creator,
fill,
form_row,
participant,
question_ids,
save_settings,
set_status,
simple_form,
)
from surveybox import db
from surveybox.media import config as media_config
from surveybox.models import Answer, Form, MediaFile, Question, Response, UserAccount
pytestmark = pytest.mark.db
def jpeg_bytes(size: tuple[int, int] = (1200, 800)) -> bytes:
from PIL import Image
img = Image.new("RGB", size, (10, 120, 200))
exif = Image.Exif()
exif[0x010F] = "Kamerahersteller"
buffer = io.BytesIO()
img.save(buffer, "JPEG", exif=exif)
return buffer.getvalue()
FAKE_MP4 = b"\x00\x00\x00\x18ftypisom\x00\x00\x02\x00isomiso2" + b"\x00" * 5000
FAKE_PDF = b"%PDF-1.7\n" + b"0" * 2000
def post_files(client: TestClient, url: str, page: str, data: dict[str, Any], files: Any) -> Any:
csrf = token_for(client, page)
return client.post(url, data={"csrf_token": csrf, **data}, files=files)
def question(pid: str, qid: int) -> Question:
with Session(db.get_engine()) as s:
q = s.get(Question, qid)
assert q is not None
s.expunge(q)
return q
def media_rows() -> list[MediaFile]:
with Session(db.get_engine()) as s:
rows = list(s.scalars(select(MediaFile).order_by(MediaFile.id)))
for row in rows:
s.expunge(row)
return rows
def enable_youtube() -> None:
with Session(db.get_engine()) as s:
media_config.save(s, media_config.MediaConfig(embed_youtube=True))
s.commit()
# ---------------------------------------------------------------------------
# Bilder und Videos an Fragen
# ---------------------------------------------------------------------------
def test_image_gallery_and_participant_access(app: Any) -> None:
owner = creator(app)
pid, token, (q_name, _) = simple_form(owner, access="link")
page = f"/forms/{pid}/questions/{q_name}"
base = f"{page}/media"
# Ohne Beschreibung kein Bild
resp = post_files(owner, f"{base}/image", page, {"alt": ""}, {"image": ("a.jpg", jpeg_bytes())})
assert "media_error=alt_missing" in resp.headers["location"]
# Keine Bilddatei
resp = post_files(owner, f"{base}/image", page, {"alt": "x"}, {"image": ("a.jpg", FAKE_PDF)})
assert "media_error=image_type" in resp.headers["location"]
resp = post_files(
owner, f"{base}/image", page, {"alt": "Plakat"}, {"image": ("plakat.jpg", jpeg_bytes())}
)
assert resp.status_code == 303 and "media_error" not in resp.headers["location"]
media = question(pid, q_name).config["media"]
assert media["kind"] == "images" and media["items"][0]["alt"] == "Plakat"
image_id = media["items"][0]["id"]
# Verwaltende sehen das Bild, ohne Metadaten und als WebP
shown = owner.get(f"/forms/{pid}/media/{image_id}")
assert shown.status_code == 200
assert shown.headers["content-type"] == "image/webp"
assert b"Kamerahersteller" not in shown.content
assert owner.get(f"/forms/{pid}/media/{image_id}/thumb").status_code == 200
# Teilnehmende über den Link, mit Bild auf der Seite
guest = new_client(app)
assert f"/f/{token}/media/{image_id}" in guest.get(f"/f/{token}").text
assert guest.get(f"/f/{token}/media/{image_id}/thumb").status_code == 200
# Nicht über die Verwaltungsadresse
assert guest.get(f"/forms/{pid}/media/{image_id}").status_code in (303, 403)
# Nach dem Schließen nicht mehr
set_status(owner, pid, "closed")
assert guest.get(f"/f/{token}/media/{image_id}").status_code == 404
def test_video_upload_types_and_range(app: Any) -> None:
owner = creator(app)
pid = create_form(owner)
add_question(owner, pid, "info", label="Bitte ansehen")
(qid,) = question_ids(pid)
page = f"/forms/{pid}/questions/{qid}"
mov = b"\x00\x00\x00\x14ftypqt " + b"\x00" * 100
resp = post_files(owner, f"{page}/media/video", page, {}, {"video": ("film.mov", mov)})
assert "media_error=file_type" in resp.headers["location"]
resp = post_files(
owner, f"{page}/media/video", page, {"title": "Einweisung"},
{"video": ("film.mp4", FAKE_MP4), "captions": ("de.vtt", b"WEBVTT\n\n")},
)
assert "media_error" not in resp.headers["location"]
media = question(pid, qid).config["media"]
assert media["kind"] == "video" and media["captions"]
partial = owner.get(f"/forms/{pid}/media/{media['id']}", headers={"Range": "bytes=0-99"})
assert partial.status_code == 206
assert len(partial.content) == 100
# Ein Bild ersetzt das Video; die Datei des Videos verliert ihren Eintrag
post_files(
owner, f"{page}/media/image", page, {"alt": "Bild"}, {"image": ("a.jpg", jpeg_bytes())}
)
assert question(pid, qid).config["media"]["kind"] == "images"
assert {m.kind for m in media_rows()} == {"image"}
def test_external_video_needs_enabled_provider(app: Any) -> None:
owner = creator(app)
pid, token, (q_name, _) = simple_form(owner, access="link")
page = f"/forms/{pid}/questions/{q_name}"
url = "https://www.youtube.com/watch?v=dQw4w9WgXcQ"
resp = post_files(owner, f"{page}/media/embed", page, {"url": url}, None)
assert "media_error=embed_provider_disabled" in resp.headers["location"]
enable_youtube()
resp = post_files(owner, f"{page}/media/embed", page, {"url": url}, None)
assert "media_error" not in resp.headers["location"]
fill_page = new_client(app).get(f"/f/{token}")
assert "frame-src https://www.youtube-nocookie.com" in fill_page.headers[
"content-security-policy"
]
assert 'data-player="https://www.youtube-nocookie.com/embed/dQw4w9WgXcQ' in fill_page.text
assert "<iframe" not in fill_page.text # erst nach Klick
def test_option_images_for_picture_choice(app: Any) -> None:
owner = creator(app)
pid = create_form(owner)
csrf = token_for(owner, f"/forms/{pid}/questions/new?type=single_choice")
resp = owner.post(
f"/forms/{pid}/questions/new?type=single_choice",
data={
"csrf_token": csrf, "label": "Welches Motiv?", "display": "images",
"option_id": ["", "", ""], "option_label": ["Berg", "", "See"],
},
files={"option_image_2": ("see.jpg", jpeg_bytes())},
)
assert resp.status_code == 303
(qid,) = question_ids(pid)
options = question(pid, qid).config["options"]
assert [o["label"] for o in options] == ["Berg", "See"]
assert "image" not in options[0] and options[1]["image"]
# Speichern ohne neue Datei behält das Bild
csrf = token_for(owner, f"/forms/{pid}/questions/{qid}")
owner.post(
f"/forms/{pid}/questions/{qid}",
data={
"csrf_token": csrf, "label": "Welches Motiv?", "display": "images",
"option_id": [o["id"] for o in options], "option_label": ["Berg", "See"],
},
)
assert question(pid, qid).config["options"][1]["image"] == options[1]["image"]
# ---------------------------------------------------------------------------
# Datei-Upload beim Ausfüllen
# ---------------------------------------------------------------------------
def upload_form(owner: TestClient) -> tuple[str, str, int, int]:
pid = create_form(owner)
add_question(owner, pid, "short_text", label="Name", required="on")
add_question(
owner, pid, "file_upload", label="Unterlagen", required="on",
allow_pdf="on", max_files="2", max_mb="1",
)
assert save_settings(owner, pid, access="link").status_code == 303
assert set_status(owner, pid, "open").status_code == 303
q_name, q_file = question_ids(pid)
return pid, form_row(pid).share_token, q_name, q_file
def test_upload_kept_after_validation_error_and_downloadable(app: Any) -> None:
owner = creator(app)
pid, token, q_name, q_file = upload_form(owner)
guest = new_client(app)
# Falscher Typ
csrf = token_for(guest, f"/f/{token}")
resp = guest.post(
f"/f/{token}", data={"csrf_token": csrf, f"q{q_name}": "Gast"},
files={f"q{q_file}": ("bild.pdf", jpeg_bytes())},
)
assert resp.status_code == 400
assert "This file type is not allowed here." in resp.text
# Richtige Datei, aber Name fehlt: Datei bleibt erhalten
resp = guest.post(
f"/f/{token}", data={"csrf_token": csrf, f"q{q_name}": ""},
files={f"q{q_file}": ("anmeldung.pdf", FAKE_PDF)},
)
assert resp.status_code == 400
assert "anmeldung.pdf" in resp.text
keep = resp.text.split(f'name="q{q_file}_keep" value="', 1)[1].split('"', 1)[0]
# Manipulierte Kennung wird ignoriert, echte behalten
resp = guest.post(
f"/f/{token}",
data={"csrf_token": csrf, f"q{q_name}": "Gast",
f"q{q_file}_keep": [keep, keep.split(".")[0] + ".00ff"]},
)
assert resp.status_code == 303
with Session(db.get_engine()) as s:
answer = s.scalar(select(Answer).where(Answer.question_id == q_file))
assert answer is not None
files = answer.value_json["files"]
assert [f["name"] for f in files] == ["anmeldung.pdf"]
row = s.scalar(select(MediaFile).where(MediaFile.public_id == uuid.UUID(files[0]["id"])))
assert row is not None and row.response_id is not None and row.pending_until is None
download = owner.get(f"/forms/{pid}/media/{files[0]['id']}")
assert download.status_code == 200
assert download.headers["content-disposition"].startswith("attachment")
assert "sandbox" in download.headers["content-security-policy"]
# Teilnehmende kommen nie an hochgeladene Dateien
assert guest.get(f"/f/{token}/media/{files[0]['id']}").status_code == 404
def test_upload_required_and_too_large(app: Any) -> None:
owner = creator(app)
_, token, q_name, q_file = upload_form(owner)
guest = new_client(app)
resp = fill(guest, token, {f"q{q_name}": "Gast"})
assert resp.status_code == 400
assert "Please answer this question." in resp.text
csrf = token_for(guest, f"/f/{token}")
big = b"%PDF-1.7\n" + b"0" * (1024 * 1024 + 10)
resp = guest.post(
f"/f/{token}", data={"csrf_token": csrf, f"q{q_name}": "Gast"},
files={f"q{q_file}": ("gross.pdf", big)},
)
assert resp.status_code == 400
assert "The file is too large." in resp.text
def test_small_requests_are_limited(app: Any) -> None:
client = new_client(app)
resp = client.post("/login", content=b"a=" + b"x" * (3 * 1024 * 1024),
headers={"Content-Type": "application/x-www-form-urlencoded"})
assert resp.status_code == 413
# ---------------------------------------------------------------------------
# Team, Kopien, Vorlagen
# ---------------------------------------------------------------------------
def add_member(owner: TestClient, pid: str, email: str, role: str) -> None:
with Session(db.get_engine()) as s:
target = s.scalar(select(UserAccount.public_id).where(UserAccount.email == email))
csrf = token_for(owner, f"/forms/{pid}/team")
resp = owner.post(
f"/forms/{pid}/team", data={"csrf_token": csrf, "target": f"u:{target}", "role": role}
)
assert resp.status_code == 303
def test_team_roles(app: Any) -> None:
owner = creator(app)
pid, _, _ = simple_form(owner)
editor = participant(app, "erik@example.de")
evaluator = participant(app, "eva@example.de")
outsider = participant(app, "otto@example.de")
add_member(owner, pid, "erik@example.de", "editor")
add_member(owner, pid, "eva@example.de", "evaluator")
# Mitbearbeitende ändern Fragen, aber nicht das Team und löschen nicht
assert editor.get(f"/forms/{pid}").status_code == 200
add_question(editor, pid, "short_text", label="Von Erik")
assert editor.get(f"/forms/{pid}/team").status_code == 403
csrf = token_for(editor, f"/forms/{pid}")
assert editor.post(
f"/forms/{pid}/delete", data={"csrf_token": csrf, "confirm": "on"}
).status_code == 403
# Startseite zeigt das Formular
assert "Sommerfest" in editor.get("/").text
# Auswertende sehen nur Antworten
designer = evaluator.get(f"/forms/{pid}")
assert designer.status_code == 303 and designer.headers["location"].endswith("/responses")
assert evaluator.get(f"/forms/{pid}/responses").status_code == 200
assert evaluator.get(f"/forms/{pid}/settings").status_code == 403
assert outsider.get(f"/forms/{pid}/responses").status_code == 403
def test_copy_with_media_and_templates(app: Any) -> None:
owner = creator(app)
pid, _, (q_name, _) = simple_form(owner)
page = f"/forms/{pid}/questions/{q_name}"
post_files(
owner, f"{page}/media/image", page, {"alt": "Plakat"}, {"image": ("a.jpg", jpeg_bytes())}
)
csrf = token_for(owner, f"/forms/{pid}")
resp = owner.post(f"/forms/{pid}/copy", data={"csrf_token": csrf})
assert resp.status_code == 303
copy_pid = resp.headers["location"].split("/")[2].split("?")[0]
copy_form = form_row(copy_pid)
assert copy_form.status == "draft" and copy_form.title.startswith("Copy of")
copied_q = question(copy_pid, question_ids(copy_pid)[0])
original_item = question(pid, q_name).config["media"]["items"][0]
copied_item = copied_q.config["media"]["items"][0]
assert copied_item["id"] != original_item["id"]
rows = {str(m.public_id): m for m in media_rows()}
assert rows[copied_item["id"]].storage_key == rows[original_item["id"]].storage_key
assert owner.get(f"/forms/{copy_pid}/media/{copied_item['id']}").status_code == 200
# Vorlage: nicht veröffentlichbar, für andere erst nach Freigabe sichtbar
resp = owner.post(f"/forms/{pid}/save-template", data={"csrf_token": csrf})
template_pid = resp.headers["location"].split("/")[2].split("?")[0]
assert form_row(template_pid).is_template
assert set_status(owner, template_pid, "open").status_code == 400
other = creator(app, "olga@example.de")
csrf_other = token_for(other, "/forms")
assert other.post(
f"/forms/from-template/{template_pid}", data={"csrf_token": csrf_other}
).status_code == 403
csrf = token_for(owner, f"/forms/{template_pid}")
owner.post(f"/forms/{template_pid}/share-template", data={"csrf_token": csrf, "shared": "on"})
assert "Sommerfest" in other.get("/forms").text
resp = other.post(f"/forms/from-template/{template_pid}", data={"csrf_token": csrf_other})
assert resp.status_code == 303
with Session(db.get_engine()) as s:
owner_id = s.scalar(select(UserAccount.id).where(UserAccount.email == "olga@example.de"))
assert s.scalar(
select(func.count()).select_from(Form).where(Form.owner_id == owner_id)
) == 1
# ---------------------------------------------------------------------------
# Designer und Vorschau
# ---------------------------------------------------------------------------
def test_reorder_and_live_preview(app: Any) -> None:
owner = creator(app)
pid = create_form(owner)
for label in ("Eins", "Zwei", "Drei"):
add_question(owner, pid, "short_text", label=label)
first, second, third = question_ids(pid)
csrf = token_for(owner, f"/forms/{pid}")
version = owner.get(f"/forms/{pid}/preview/version").json()["version"]
bad = owner.post(f"/forms/{pid}/order", json={"order": [first, second]},
headers={"X-CSRF-Token": csrf})
assert bad.status_code == 409
no_csrf = owner.post(f"/forms/{pid}/order", json={"order": [third, first, second]})
assert no_csrf.status_code == 403
ok = owner.post(f"/forms/{pid}/order", json={"order": [third, first, second]},
headers={"X-CSRF-Token": csrf})
assert ok.status_code == 200
assert question_ids(pid) == [third, first, second]
assert owner.get(f"/forms/{pid}/preview/version").json()["version"] != version
frame = owner.get(f"/forms/{pid}/preview/frame")
assert frame.status_code == 200
assert frame.headers["x-frame-options"] == "SAMEORIGIN"
assert "frame-ancestors 'self'" in frame.headers["content-security-policy"]
# Alle anderen Seiten bleiben nicht einbettbar
assert owner.get(f"/forms/{pid}").headers["x-frame-options"] == "DENY"
def test_pending_uploads_are_purged(app: Any) -> None:
from datetime import UTC, datetime, timedelta
from surveybox.worker import Worker
owner = creator(app)
_, token, q_name, q_file = upload_form(owner)
guest = new_client(app)
csrf = token_for(guest, f"/f/{token}")
guest.post(
f"/f/{token}", data={"csrf_token": csrf, f"q{q_name}": ""},
files={f"q{q_file}": ("a.pdf", FAKE_PDF)},
)
assert len(media_rows()) == 1
with Session(db.get_engine()) as s:
for row in s.scalars(select(MediaFile)):
row.pending_until = datetime.now(UTC) - timedelta(minutes=1)
s.commit()
from surveybox.settings import get_settings
Worker(get_settings(), db.get_engine()).run_cleanup(datetime.now(UTC))
assert media_rows() == []
with Session(db.get_engine()) as s:
assert s.scalar(select(func.count()).select_from(Response)) == 0
+322
View File
@@ -0,0 +1,322 @@
# SPDX-License-Identifier: AGPL-3.0-or-later
"""Typprüfung, Bildverarbeitung, Einbettungen und Ablage (ohne Datenbank)."""
from __future__ import annotations
import io
import os
import time
import zipfile
from pathlib import Path
import pytest
from surveybox.media import embeds, sniff, storage
# ---------------------------------------------------------------------------
# Typprüfung
# ---------------------------------------------------------------------------
def _write(tmp_path: Path, name: str, data: bytes) -> Path:
path = tmp_path / name
path.write_bytes(data)
return path
@pytest.mark.parametrize(
("data", "name", "key"),
[
(b"\xff\xd8\xff\xe0" + b"0" * 20, "a.jpg", "jpeg"),
(b"\x89PNG\r\n\x1a\n" + b"0" * 20, "a.png", "png"),
(b"RIFF\x00\x00\x00\x00WEBPVP8 ", "a.webp", "webp"),
(b"\x00\x00\x00\x18ftypisom" + b"0" * 20, "a.mp4", "mp4"),
(b"\x1a\x45\xdf\xa3\x9f\x42\x86\x81\x01webm", "a.webm", "webm"),
(b"%PDF-1.7\n", "a.pdf", "pdf"),
(b"WEBVTT\n\n00:00.000 --> 00:01.000\nHallo\n", "a.vtt", "vtt"),
("Name;Ort\nÄrger;Köln\n".encode(), "liste.csv", "csv"),
(b"einfacher Text\n", "notiz", "txt"),
],
)
def test_detects_by_content(tmp_path: Path, data: bytes, name: str, key: str) -> None:
detected = sniff.detect_file(_write(tmp_path, name, data), name)
assert detected is not None
assert detected.key == key
def test_rejects_unknown_and_disguised(tmp_path: Path) -> None:
exe = _write(tmp_path, "bild.jpg", b"MZ\x90\x00" + b"\x00" * 50)
assert sniff.detect_file(exe, "bild.jpg") is None
mov = _write(tmp_path, "film.mp4", b"\x00\x00\x00\x14ftypqt " + b"0" * 20)
assert sniff.detect_file(mov, "film.mp4") is None
html = _write(tmp_path, "x.png", b"<html><script>alert(1)</script>")
assert sniff.detect_file(html, "x.png").key == "txt" # type: ignore[union-attr]
def _zip(tmp_path: Path, name: str, files: dict[str, bytes]) -> Path:
path = tmp_path / name
with zipfile.ZipFile(path, "w") as archive:
for inner, content in files.items():
archive.writestr(inner, content)
return path
def test_office_formats_from_archive(tmp_path: Path) -> None:
docx = _zip(tmp_path, "a.docx", {"[Content_Types].xml": b"<x/>", "word/document.xml": b""})
assert sniff.detect_file(docx).key == "docx" # type: ignore[union-attr]
ods = _zip(tmp_path, "a.ods", {"mimetype": b"application/vnd.oasis.opendocument.spreadsheet"})
assert sniff.detect_file(ods).key == "ods" # type: ignore[union-attr]
plain = _zip(tmp_path, "a.zip", {"readme.txt": b"hi"})
assert sniff.detect_file(plain).key == "zip" # type: ignore[union-attr]
def test_safe_filename() -> None:
assert sniff.safe_filename("C:\\Users\\x\\Bericht 2026.PDF", "pdf") == "Bericht 2026.pdf"
assert sniff.safe_filename('../../etc/pa"ss\x00wd', "txt") == "passwd.txt"
assert sniff.safe_filename("", "png") == "datei.png"
# ---------------------------------------------------------------------------
# Bilder
# ---------------------------------------------------------------------------
PIL = pytest.importorskip("PIL")
def _jpeg_with_gps(path: Path, size: tuple[int, int] = (3000, 2000)) -> None:
from PIL import Image
img = Image.new("RGB", size, (200, 30, 30))
exif = Image.Exif()
exif[0x010F] = "Kamerahersteller"
exif[0x0112] = 6 # um 90° gedreht
exif[0x8825] = {1: "N", 2: (47.0, 54.0, 0.0)}
img.save(path, "JPEG", exif=exif)
def test_image_is_rotated_resized_and_stripped(tmp_path: Path) -> None:
from PIL import Image
from surveybox.media import images
source = tmp_path / "foto.jpg"
_jpeg_with_gps(source)
full, thumb = tmp_path / "full", tmp_path / "thumb"
result = images.process(source, full, thumb)
# Ausrichtung angewandt (hochkant), auf 2560 begrenzt
assert (result.width, result.height) == (1707, 2560)
with Image.open(full) as out:
assert out.format == "WEBP"
assert not out.getexif()
assert "exif" not in out.info
with Image.open(thumb) as small:
assert max(small.size) == 640
def test_image_rejects_garbage_and_bombs(tmp_path: Path) -> None:
from PIL import Image
from surveybox.media import images
junk = _write(tmp_path, "x.png", b"\x89PNG\r\n\x1a\n" + os.urandom(200))
with pytest.raises(images.ImageError):
images.process(junk, tmp_path / "f", tmp_path / "t")
gif = tmp_path / "a.gif"
Image.new("RGB", (10, 10)).save(gif, "GIF")
with pytest.raises(images.ImageError):
images.process(gif, tmp_path / "f", tmp_path / "t")
bomb = tmp_path / "bomb.png"
Image.new("1", (9000, 9000)).save(bomb, "PNG")
with pytest.raises(images.ImageError):
images.process(bomb, tmp_path / "f", tmp_path / "t")
def test_transparent_png_keeps_alpha(tmp_path: Path) -> None:
from PIL import Image
from surveybox.media import images
source = tmp_path / "logo.png"
Image.new("RGBA", (100, 50), (0, 0, 0, 0)).save(source, "PNG")
images.process(source, tmp_path / "f", tmp_path / "t")
with Image.open(tmp_path / "f") as out:
assert out.mode == "RGBA"
# ---------------------------------------------------------------------------
# Externe Videos
# ---------------------------------------------------------------------------
ALL = embeds.EmbedPolicy(youtube=True, vimeo=True, peertube_hosts=("video.example.org",))
@pytest.mark.parametrize(
("url", "provider", "video"),
[
("https://www.youtube.com/watch?v=dQw4w9WgXcQ&t=10", "youtube", "dQw4w9WgXcQ"),
("https://youtu.be/dQw4w9WgXcQ?si=abc", "youtube", "dQw4w9WgXcQ"),
("https://www.youtube.com/shorts/dQw4w9WgXcQ", "youtube", "dQw4w9WgXcQ"),
("https://vimeo.com/76979871", "vimeo", "76979871"),
("https://player.vimeo.com/video/76979871?h=abc123def", "vimeo", "76979871"),
("https://video.example.org/w/9c9de5e8-0a1e-484a-b099-e80766180a6d", "peertube",
"9c9de5e8-0a1e-484a-b099-e80766180a6d"),
("https://video.example.org/videos/watch/kkGMgK9ZtnKfYAgnEtQxbv", "peertube",
"kkGMgK9ZtnKfYAgnEtQxbv"),
],
)
def test_parse_video_urls(url: str, provider: str, video: str) -> None:
embed = embeds.parse_url(url, ALL)
assert (embed.provider, embed.video) == (provider, video)
assert embeds.from_config(embed.to_config()) == embed
@pytest.mark.parametrize(
"url",
[
"javascript:alert(1)",
"https://www.youtube.com/watch?v=short",
"https://www.youtube.com/watch?v=dQw4w9WgXcQ\"><script>",
"https://evil.example/w/9c9de5e8-0a1e-484a-b099-e80766180a6d",
"https://vimeo.com/abc",
],
)
def test_rejects_bad_video_urls(url: str) -> None:
with pytest.raises(embeds.EmbedError):
embeds.parse_url(url, ALL)
def test_disabled_provider_and_player_urls() -> None:
with pytest.raises(embeds.EmbedError) as exc:
embeds.parse_url("https://youtu.be/dQw4w9WgXcQ", embeds.EmbedPolicy())
assert exc.value.code == "embed_provider_disabled"
yt = embeds.parse_url("https://youtu.be/dQw4w9WgXcQ", ALL)
assert embeds.player_url(yt).startswith("https://www.youtube-nocookie.com/embed/")
vimeo = embeds.parse_url("https://vimeo.com/76979871", ALL)
assert "dnt=1" in embeds.player_url(vimeo)
assert ALL.frame_sources() == [
"https://www.youtube-nocookie.com",
"https://player.vimeo.com",
"https://video.example.org",
]
# Manipulierte Konfiguration wird verworfen
assert embeds.from_config({"provider": "peertube", "video": "abcdefgh", "host": "a b"}) is None
def test_clean_host() -> None:
assert embeds.clean_host("https://Video.Example.org/") == "video.example.org"
assert embeds.clean_host("localhost") is None
assert embeds.clean_host("exa mple.org") is None
# ---------------------------------------------------------------------------
# Ablage
# ---------------------------------------------------------------------------
def test_receive_commit_and_sweep(tmp_path: Path) -> None:
root, tmp = tmp_path / "media", tmp_path / "tmp"
temp = storage.temp_path(tmp)
assert storage.receive(io.BytesIO(b"x" * 100), temp, 1000) == 100
key = storage.commit(root, temp)
assert storage.path_for(root, key).read_bytes() == b"x" * 100
big = storage.temp_path(tmp)
with pytest.raises(storage.TooLarge):
storage.receive(io.BytesIO(b"x" * 2000), big, 1000)
assert not big.exists()
with pytest.raises(ValueError):
storage.path_for(root, "../../etc/passwd")
orphan = storage.commit(root, _write(tmp, "o", b"o"))
# Frische verwaiste Dateien bleiben (Sicherungen), alte verschwinden
assert storage.sweep(root, {key}) == 0
old = time.time() - 2 * storage.ORPHAN_MIN_AGE
os.utime(storage.path_for(root, orphan), (old, old))
assert storage.sweep(root, {key}) == 1
assert set(storage.stored_keys(root)) == {key}
def test_backup_manifest_store_and_restore(tmp_path: Path) -> None:
from surveybox import backup
media, backups = tmp_path / "media", tmp_path / "backups"
store = backups / "media"
first = storage.commit(media, _write(tmp_path, "a", b"erste"))
second = storage.commit(media, _write(tmp_path, "b", b"zweite"))
(backups / "daily").mkdir(parents=True)
dump_old = backups / "daily" / "surveybox-daily-20260101T000000Z.dump"
dump_old.write_bytes(b"x")
assert backup.backup_media(media, store, dump_old) == 2
# Eine Datei verschwindet, eine neue kommt hinzu
storage.path_for(media, first).unlink()
third = storage.commit(media, _write(tmp_path, "c", b"dritte"))
dump_new = backups / "daily" / "surveybox-daily-20260102T000000Z.dump"
dump_new.write_bytes(b"x")
backup.backup_media(media, store, dump_new)
assert set(backup.read_manifest(backup.manifest_for(dump_new))) == {second, third}
# Alte Sicherung zurückspielen: die gelöschte Datei kommt wieder
assert backup.restore_media(media, store, dump_old) == 1
assert storage.path_for(media, first).read_bytes() == b"erste"
# Alte Sicherung weg: ihre Datei wird im Speicher nicht mehr gebraucht
dump_old.unlink()
backup.manifest_for(dump_old).unlink()
assert backup.prune_media_store(backups, store) == 1
assert set(storage.stored_keys(store)) == {second, third}
OWN = embeds.EmbedPolicy(
custom=(
embeds.Source("media.example.org", "mediacms", True),
embeds.Source("nas.example.org:5001", "file", False),
embeds.Source("192.168.10.5", "iframe", True),
)
)
def test_own_sources() -> None:
cms = embeds.parse_url("https://media.example.org/view?m=AbCdEf123", OWN)
assert embeds.player_url(cms) == "https://media.example.org/embed?m=AbCdEf123"
assert embeds.needs_consent(cms, OWN)
nas = embeds.parse_url("https://nas.example.org:5001/videos/Einweisung 2026.mp4", OWN)
assert nas.provider == "file"
assert embeds.player_url(nas) == "https://nas.example.org:5001/videos/Einweisung%202026.mp4"
assert not embeds.needs_consent(nas, OWN)
assert embeds.from_config(nas.to_config()) == nas
page = embeds.parse_url("https://192.168.10.5/player?id=7", OWN)
assert page.provider == "iframe"
assert embeds.csp_sources([cms, nas, page]) == (
["https://192.168.10.5", "https://media.example.org"],
["https://nas.example.org:5001"],
)
@pytest.mark.parametrize(
"url",
[
"http://nas.example.org:5001/a.mp4", # kein HTTPS
"https://nas.example.org/a.mp4", # falscher Port
"https://user:pw@nas.example.org:5001/a.mp4",
"https://media.example.org/view?m=x",
"https://other.example.org/a.mp4",
],
)
def test_own_sources_reject(url: str) -> None:
with pytest.raises(embeds.EmbedError):
embeds.parse_url(url, OWN)
def test_own_source_config_is_rechecked() -> None:
forged = {"provider": "file", "host": "nas.example.org:5001",
"url": "https://evil.example/x.mp4"}
assert embeds.from_config(forged) is None
quoted = embeds.from_config({"provider": "iframe", "host": "192.168.10.5",
"url": 'https://192.168.10.5/a"onload="x'})
assert quoted is not None and '"' not in embeds.player_url(quoted)
assert embeds.clean_source_host("NAS.example.org:5001") == "nas.example.org:5001"
assert embeds.clean_source_host("nas:99999") is None
+46
View File
@@ -0,0 +1,46 @@
# SPDX-License-Identifier: AGPL-3.0-or-later
"""Fragetyp "Teilnehmer-Name" ohne Datenbank."""
from __future__ import annotations
from types import SimpleNamespace
from typing import Any
from zoneinfo import ZoneInfo
from surveybox.forms import types
TZ = ZoneInfo("Europe/Berlin")
def question(email: str = "optional") -> Any:
return SimpleNamespace(id=7, type="participant_name", label="Name", required=True,
config=types.parse_config("participant_name", {"email_mode": [email]}))
def parse(q: Any, **values: str) -> types.AnswerResult:
return types.parse_answer(q, {f"q7_{k}": [v] for k, v in values.items()}, TZ)
def test_names_are_required_and_email_follows_the_setting() -> None:
q = question()
assert parse(q).error == "name_incomplete"
assert parse(q, first="Anna").error == "name_incomplete"
result = parse(q, first=" Anna ", last="Muster Frau")
assert result.error is None and result.stored == {
"value_text": "Anna Muster Frau", "value_json": {"first": "Anna", "last": "Muster Frau"}}
assert parse(q, first="A", last="B", email="kaputt").error == "email"
assert parse(question("required"), first="A", last="B").error == "name_email_missing"
off = parse(question("off"), first="A", last="B", email="a@b.de")
assert off.stored is not None and "email" not in off.stored["value_json"]
assert types.parse_config("participant_name", {"email_mode": ["egal"]}) == {"email": "optional"}
def test_display_and_back_into_the_form() -> None:
q = question()
stored = parse(q, first="Anna", last="Muster", email="anna@example.de").stored
assert stored is not None
assert types.display_answer(q, stored, TZ) == "Anna Muster <anna@example.de>"
assert types.raw_from_answer(q, stored, TZ) == {
"q7_first": ["Anna"], "q7_last": ["Muster"], "q7_email": ["anna@example.de"]}
assert types.short_name("Anna", "Muster") == "Anna M."
assert "participant_name" in types.PERSONAL_BY_DEFAULT
+216
View File
@@ -0,0 +1,216 @@
# SPDX-License-Identifier: AGPL-3.0-or-later
"""Passkeys und Gruppen - mit Software-Authenticator gegen PostgreSQL (CI)."""
from __future__ import annotations
import re
from typing import Any
import pytest
pytest.importorskip("fastapi")
pytest.importorskip("webauthn")
pytest.importorskip("cbor2")
from fastapi.testclient import TestClient
from helpers import (
PASSWORD,
SoftAuthenticator,
csrf_from,
login,
make_user,
new_client,
post_json,
token_for,
)
from sqlalchemy import func, select
from sqlalchemy.orm import Session
from surveybox import db
from surveybox.models import AuditEvent, GroupMember, Role, UserGroup, WebAuthnCredential
pytestmark = pytest.mark.db
def register_passkey(client: TestClient, auth: SoftAuthenticator, name: str = "Laptop") -> Any:
csrf = token_for(client, "/account")
options = post_json(client, "/account/passkeys/options", {"password": PASSWORD}, csrf)
assert options.status_code == 200, options.text
data = options.json()
return post_json(
client,
"/account/passkeys/register",
{"challengeId": data["challengeId"], "credential": auth.create(data["publicKey"]),
"name": name},
csrf,
)
def passkey_login(client: TestClient, auth: SoftAuthenticator, base: str = "/login/passkey",
page: str = "/login") -> Any:
csrf = token_for(client, page)
options = post_json(client, f"{base}/options", {}, csrf)
assert options.status_code == 200, options.text
data = options.json()
return post_json(
client,
f"{base}/verify",
{"challengeId": data["challengeId"], "credential": auth.get(data["publicKey"]),
"next": "/account"},
csrf,
)
def test_register_passkey_and_sign_in_without_password( # type: ignore[no-untyped-def]
client: TestClient, app
) -> None:
make_user()
login(client, "anna@example.de")
auth = SoftAuthenticator()
resp = register_passkey(client, auth)
assert resp.status_code == 200, resp.text
assert resp.json()["redirect"] == "/account?notice=passkey_added"
page = client.get("/account")
assert "Laptop" in page.text
with new_client(app) as fresh:
result = passkey_login(fresh, auth)
assert result.status_code == 200, result.text
assert result.json()["redirect"] == "/account"
assert fresh.get("/account").status_code == 200
with Session(db.get_engine()) as s:
row = s.scalar(select(WebAuthnCredential))
assert row is not None and row.sign_count == 1 and row.last_used_at is not None
assert row.transports == ["internal"]
def test_wrong_password_blocks_registration(client: TestClient) -> None:
make_user()
login(client, "anna@example.de")
csrf = token_for(client, "/account")
resp = post_json(client, "/account/passkeys/options", {"password": "falsch"}, csrf)
assert resp.status_code == 400
assert "current password is wrong" in resp.json()["error"]
def test_challenge_is_single_use(client: TestClient) -> None:
make_user()
login(client, "anna@example.de")
auth = SoftAuthenticator()
csrf = token_for(client, "/account")
data = post_json(client, "/account/passkeys/options", {"password": PASSWORD}, csrf).json()
body = {"challengeId": data["challengeId"], "credential": auth.create(data["publicKey"])}
assert post_json(client, "/account/passkeys/register", body, csrf).status_code == 200
again = post_json(client, "/account/passkeys/register", body, csrf)
assert again.status_code == 400
assert "expired" in again.json()["error"]
def test_unknown_passkey_is_rejected(client: TestClient) -> None:
make_user()
stranger = SoftAuthenticator()
stranger.user_handle = b"x" * 32
resp = passkey_login(client, stranger)
assert resp.status_code == 400
assert "not registered" in resp.json()["error"]
def test_json_endpoints_need_csrf_header(client: TestClient) -> None:
client.get("/login")
resp = client.post("/login/passkey/options", json={})
assert resp.status_code == 403
def test_passkey_as_second_factor_for_admin( # type: ignore[no-untyped-def]
client: TestClient, app
) -> None:
make_user(Role.ADMIN, "admin@example.de")
login(client, "admin@example.de")
# Admin ohne zweiten Faktor kommt nur auf die Kontoseite; dort legt er einen Passkey an
assert client.get("/admin/users").status_code == 303
auth = SoftAuthenticator()
assert register_passkey(client, auth).status_code == 200
assert client.get("/admin/users").status_code == 200
with new_client(app) as fresh:
resp = login(fresh, "admin@example.de")
assert resp.headers["location"].startswith("/login/mfa")
result = passkey_login(fresh, auth, base="/login/mfa/passkey", page="/login/mfa")
assert result.status_code == 200, result.text
assert fresh.get("/admin/users").status_code == 200
def test_admin_cannot_remove_last_second_factor(client: TestClient) -> None:
make_user(Role.ADMIN, "admin@example.de")
login(client, "admin@example.de")
register_passkey(client, SoftAuthenticator())
with Session(db.get_engine()) as s:
pk_id = s.scalar(select(WebAuthnCredential.id))
page = client.get("/account")
resp = client.post(
f"/account/passkeys/{pk_id}/delete",
data={"current_password": PASSWORD, "csrf_token": csrf_from(page.text)},
)
assert resp.status_code == 400
with Session(db.get_engine()) as s:
assert s.scalar(select(func.count()).select_from(WebAuthnCredential)) == 1
def test_participant_can_remove_passkey(client: TestClient) -> None:
make_user()
login(client, "anna@example.de")
register_passkey(client, SoftAuthenticator())
with Session(db.get_engine()) as s:
pk_id = s.scalar(select(WebAuthnCredential.id))
page = client.get("/account")
resp = client.post(
f"/account/passkeys/{pk_id}/delete",
data={"current_password": PASSWORD, "csrf_token": csrf_from(page.text)},
)
assert resp.headers["location"] == "/account?notice=passkey_removed"
def test_groups_lifecycle(client: TestClient) -> None:
make_user(Role.ADMIN, "admin@example.de")
member, _ = make_user(Role.PARTICIPANT, "bob@example.de")
login(client, "admin@example.de")
register_passkey(client, SoftAuthenticator())
page = client.get("/admin/groups")
created = client.post(
"/admin/groups",
data={"name": "Jugendfeuerwehr", "description": "Gruppenabende",
"csrf_token": csrf_from(page.text)},
)
assert created.status_code == 303
group_url = created.headers["location"].split("?")[0]
duplicate = client.post(
"/admin/groups",
data={"name": "jugendfeuerwehr", "csrf_token": csrf_from(page.text)},
)
assert duplicate.status_code == 400
edit = client.get(group_url)
assert "Jugendfeuerwehr" in edit.text and "bob@example.de" in edit.text
client.post(f"{group_url}/members",
data={"user": str(member.public_id), "csrf_token": csrf_from(edit.text)})
with Session(db.get_engine()) as s:
assert s.scalar(select(func.count()).select_from(GroupMember)) == 1
client.post(f"{group_url}/members/{member.public_id}/remove",
data={"csrf_token": csrf_from(edit.text)})
no_confirm = client.post(f"{group_url}/delete", data={"csrf_token": csrf_from(edit.text)})
assert no_confirm.status_code == 400
deleted = client.post(f"{group_url}/delete",
data={"confirm": "on", "csrf_token": csrf_from(edit.text)})
assert deleted.headers["location"] == "/admin/groups?notice=group_deleted"
with Session(db.get_engine()) as s:
assert s.scalar(select(func.count()).select_from(UserGroup)) == 0
actions = set(s.scalars(select(AuditEvent.action)))
assert {"admin.group_created", "admin.group_member_added", "admin.group_member_removed",
"admin.group_deleted", "account.passkey_added"} <= actions
audit = client.get("/admin/audit")
assert re.search(r"Group created", audit.text)
+208
View File
@@ -0,0 +1,208 @@
# SPDX-License-Identifier: AGPL-3.0-or-later
"""Phase 4 gegen PostgreSQL: Bedingungen, Seiten, Gruppen beim Anlegen, eigene Video-Quellen."""
from __future__ import annotations
from typing import Any
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 (
add_question,
create_form,
creator,
fill,
form_row,
question_ids,
save_settings,
set_status,
)
from surveybox import db
from surveybox.media import config as media_config
from surveybox.models import Answer, GroupMember, Question, Role, UserAccount, UserGroup
pytestmark = pytest.mark.db
def config_of(qid: int) -> dict[str, Any]:
with Session(db.get_engine()) as s:
q = s.get(Question, qid)
assert q is not None
return dict(q.config)
def rule_fields(ref: int, op: str, *, option: str = "", text: str = "",
action: str = "show") -> dict[str, Any]:
return {"cond_action": action, "cond_match": "all", "rule_q": [str(ref), ""],
"rule_op": [op, "eq"], "rule_option": [option, ""], "rule_text": [text, ""]}
def conditional_form(owner: TestClient) -> tuple[str, str, int, int, int]:
"""Ja/Nein, dann Pflicht-Zahl nur bei Ja, dann Seite 2 mit Bemerkung."""
pid = create_form(owner)
add_question(owner, pid, "yes_no", label="Kommen Sie?", required="on")
(q_yes,) = question_ids(pid)
add_question(owner, pid, "number", label="Wie viele?", required="on", decimals="0",
**rule_fields(q_yes, "eq", option="yes"))
add_question(owner, pid, "page_break", label="Seite 2")
add_question(owner, pid, "short_text", label="Bemerkung")
assert save_settings(owner, pid, access="link").status_code == 303
assert set_status(owner, pid, "open").status_code == 303
q_yes, q_count, _, q_note = question_ids(pid)
return pid, form_row(pid).share_token, q_yes, q_count, q_note
def test_condition_saved_and_summarised(app: Any) -> None:
owner = creator(app)
pid, _, q_yes, q_count, _ = conditional_form(owner)
condition = config_of(q_count)["condition"]
assert condition == {"action": "show", "match": "all",
"rules": [{"q": q_yes, "op": "eq", "value": "yes"}]}
designer = owner.get(f"/forms/{pid}").text
assert "Shown if all apply:" in designer
assert "controls 1 condition" in designer
def test_hidden_question_not_required_and_discarded(app: Any) -> None:
owner = creator(app)
_, token, q_yes, q_count, q_note = conditional_form(owner)
guest = new_client(app)
page = guest.get(f"/f/{token}").text
assert "data-cond=" in page and 'class="fill-page"' in page
# Ja ohne Zahl: Pflicht
resp = fill(guest, token, {f"q{q_yes}": "yes"})
assert resp.status_code == 400
# Nein und trotzdem eine Zahl geschickt (manipuliert): wird verworfen
resp = fill(guest, token, {f"q{q_yes}": "no", f"q{q_count}": "7", f"q{q_note}": "Gruß"})
assert resp.status_code == 303
with Session(db.get_engine()) as s:
stored = {a.question_id for a in s.scalars(select(Answer))}
assert stored == {q_yes, q_note}
def test_rules_only_on_earlier_questions(app: Any) -> None:
owner = creator(app)
pid, _, q_yes, q_count, q_note = conditional_form(owner)
# Erste Frage darf sich nicht auf eine spätere beziehen
csrf = token_for(owner, f"/forms/{pid}/questions/{q_yes}")
resp = owner.post(
f"/forms/{pid}/questions/{q_yes}",
data={"csrf_token": csrf, "label": "Kommen Sie?", **rule_fields(q_note, "empty")},
)
assert resp.status_code == 400
assert "earlier question" in resp.text
# Verschieben, das die Bedingung bricht, wird abgelehnt
csrf = token_for(owner, f"/forms/{pid}")
resp = owner.post(f"/forms/{pid}/questions/{q_count}/move",
data={"direction": "up", "csrf_token": csrf})
assert "problem=order_condition" in resp.headers["location"]
assert question_ids(pid)[:2] == [q_yes, q_count]
resp = owner.post(f"/forms/{pid}/order", json={"order": list(reversed(question_ids(pid)))},
headers={"X-CSRF-Token": csrf})
assert resp.status_code == 409
def test_delete_and_copy_keep_conditions_consistent(app: Any) -> None:
owner = creator(app)
pid, _, q_yes, q_count, _ = conditional_form(owner)
csrf = token_for(owner, f"/forms/{pid}")
resp = owner.post(f"/forms/{pid}/copy", data={"csrf_token": csrf})
copy_pid = resp.headers["location"].split("/")[2].split("?")[0]
copy_yes, copy_count, _, _ = question_ids(copy_pid)
assert config_of(copy_count)["condition"]["rules"][0]["q"] == copy_yes
resp = owner.post(f"/forms/{pid}/questions/{q_yes}/delete", data={"csrf_token": csrf})
assert "notice=condition_rules_removed" in resp.headers["location"]
assert "condition" not in config_of(q_count)
# ---------------------------------------------------------------------------
# Gruppen beim Anlegen eines Benutzers
# ---------------------------------------------------------------------------
def admin_client(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 test_groups_suitable_for_user_type(app: Any) -> None:
client = admin_client(app)
page = client.get("/admin/groups")
client.post("/admin/groups", data={"name": "Formularteam", "roles": ["creator"],
"csrf_token": csrf_from(page.text)})
client.post("/admin/groups", data={"name": "Alle", "roles": ["admin", "creator",
"participant"],
"csrf_token": csrf_from(page.text)})
with Session(db.get_engine()) as s:
team = s.scalar(select(UserGroup).where(UserGroup.name == "Formularteam"))
everyone = s.scalar(select(UserGroup).where(UserGroup.name == "Alle"))
assert team is not None and everyone is not None
assert team.roles == ["creator"] and everyone.roles is None
team_id, all_id = str(team.public_id), str(everyone.public_id)
form = client.get("/admin/users/new")
assert 'data-roles="creator"' in form.text
resp = client.post("/admin/users/new", data={
"email": "paula@example.de", "display_name": "Paula", "role": "participant",
"groups": [team_id, all_id], "csrf_token": csrf_from(form.text)})
assert resp.status_code == 400
resp = client.post("/admin/users/new", data={
"email": "carlo@example.de", "display_name": "Carlo", "role": "creator",
"groups": [team_id, all_id], "csrf_token": csrf_from(form.text)})
assert resp.status_code == 200
with Session(db.get_engine()) as s:
user = s.scalar(select(UserAccount).where(UserAccount.email == "carlo@example.de"))
assert user is not None
groups = set(s.scalars(select(GroupMember.group_id).where(GroupMember.user_id == user.id)))
assert len(groups) == 2
# ---------------------------------------------------------------------------
# Eigene Video-Quellen
# ---------------------------------------------------------------------------
def test_own_video_source_without_click(app: Any) -> None:
owner = creator(app)
_, token, q_yes, _, _ = conditional_form(owner)
with Session(db.get_engine()) as s:
media_config.save(s, media_config.MediaConfig(custom_sources=[
{"host": "nas.example.org:5001", "kind": "file", "ask": False}]))
s.commit()
pid = form_row_for_token(token)
page = f"/forms/{pid}/questions/{q_yes}"
csrf = token_for(owner, page)
resp = owner.post(f"{page}/media/embed", data={
"csrf_token": csrf, "url": "https://nas.example.org:5001/video/einweisung.mp4"})
assert "media_error" not in resp.headers["location"]
html = new_client(app).get(f"/f/{token}")
player = '<video controls preload="metadata" src="https://nas.example.org:5001/video/'
assert player in html.text
assert "media-src 'self' https://nas.example.org:5001" in html.headers[
"content-security-policy"
]
def form_row_for_token(token: str) -> str:
from surveybox.models import Form
with Session(db.get_engine()) as s:
pid = s.scalar(select(Form.public_id).where(Form.share_token == token))
return str(pid)
+263
View File
@@ -0,0 +1,263 @@
# SPDX-License-Identifier: AGPL-3.0-or-later
"""Phase 5 gegen PostgreSQL: Plätze, Warteliste, Abstimmung, Kalender, Kommentare (CI)."""
from __future__ import annotations
import uuid
from concurrent.futures import ThreadPoolExecutor
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
from sqlalchemy.orm import Session
from test_forms import (
add_question,
create_form,
creator,
fill,
form_row,
participant,
question_ids,
save_settings,
set_status,
)
from surveybox import db
from surveybox.models import Booking, Comment, Form, Question
pytestmark = pytest.mark.db
def options_of(qid: int) -> list[dict[str, Any]]:
with Session(db.get_engine()) as s:
q = s.get(Question, qid)
assert q is not None
return list(q.config["options"])
def bookings(qid: int) -> list[tuple[str, str, bool]]:
with Session(db.get_engine()) as s:
return [
(b.option_id, b.status, b.promoted_at is not None)
for b in s.scalars(select(Booking).where(Booking.question_id == qid)
.order_by(Booking.id))
]
def slot_form(owner: TestClient, capacity: str = "1", *, waitlist: bool = False,
multiple: bool = False, **settings: Any) -> tuple[str, str, int, list[str]]:
pid = create_form(owner)
fields: dict[str, Any] = {
"label": "Schicht", "slot_mode": "list", "option_id": ["", ""],
"option_label": ["Früh", "Spät"], "option_capacity": [capacity, ""],
}
if waitlist:
fields["waitlist"] = "on"
if multiple:
fields["multiple"] = "on"
add_question(owner, pid, "slots", **fields)
assert save_settings(owner, pid, access="link", **settings).status_code == 303
assert set_status(owner, pid, "open").status_code == 303
(qid,) = question_ids(pid)
return pid, form_row(pid).share_token, qid, [o["id"] for o in options_of(qid)]
def test_last_place_not_twice(app: Any) -> None:
owner = creator(app)
_, token, qid, (early, late) = slot_form(owner)
first, second = new_client(app), new_client(app)
assert fill(first, token, {f"q{qid}": early}).status_code == 303
resp = fill(second, token, {f"q{qid}": early})
assert resp.status_code == 409
assert "just been taken" in resp.text
assert f'value="{early}"' in resp.text # Formular bleibt ausgefüllt
assert fill(second, token, {f"q{qid}": late}).status_code == 303
assert sorted(bookings(qid)) == sorted([(early, "confirmed", False),
(late, "confirmed", False)])
places = first.get(f"/f/{token}/places").json()
assert places[str(qid)][early] == {"free": 0, "full": True}
assert places[str(qid)][late]["free"] is None
def test_concurrent_bookings(app: Any) -> None:
owner = creator(app)
_, token, qid, (early, _) = slot_form(owner)
clients = [new_client(app) for _ in range(4)]
tokens = [token_for(c, f"/f/{token}") for c in clients]
def submit(index: int) -> int:
resp = clients[index].post(f"/f/{token}", data={"csrf_token": tokens[index],
f"q{qid}": early})
return resp.status_code
with ThreadPoolExecutor(max_workers=4) as pool:
codes = list(pool.map(submit, range(4)))
assert codes.count(303) == 1 and codes.count(409) == 3
assert [b for b in bookings(qid) if b[1] == "confirmed"] == [(early, "confirmed", False)]
def test_waitlist_and_promotion(app: Any) -> None:
owner = creator(app)
pid, token, qid, (early, late) = slot_form(owner, 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 fill(bert, token, {f"q{qid}": early}).status_code == 303
assert [b[1] for b in bookings(qid)] == ["confirmed", "waiting"]
assert "waiting list" in bert.get(f"/f/{token}/edit").text
# Anna wechselt: Bert rückt nach
resp = fill(anna, token, {f"q{qid}": late}, path="/edit")
assert resp.status_code == 303
states = {(b[0], b[1], b[2]) for b in bookings(qid)}
assert (early, "confirmed", True) in states and (late, "confirmed", False) in states
# Mehr Plätze im Designer: weitere Wartende rücken nach
carl = participant(app, "carl2@example.de")
assert fill(carl, token, {f"q{qid}": early}).status_code == 303
csrf = token_for(owner, f"/forms/{pid}/questions/{qid}")
owner.post(f"/forms/{pid}/questions/{qid}", data={
"csrf_token": csrf, "label": "Schicht", "waitlist": "on", "slot_mode": "list",
"option_id": [early, late], "option_label": ["Früh", "Spät"],
"option_capacity": ["2", ""]})
assert all(b[1] == "confirmed" for b in bookings(qid))
def test_places_per_person(app: Any) -> None:
owner = creator(app)
_, token, qid, (early, late) = slot_form(owner, capacity="", multiple=True,
slots_max_per_person="1")
guest = new_client(app)
resp = fill(guest, token, {f"q{qid}": [early, late]})
assert resp.status_code == 400
assert "more places than allowed" in resp.text
# ---------------------------------------------------------------------------
# Abstimmung und Kalender
# ---------------------------------------------------------------------------
def poll_form(owner: TestClient) -> tuple[str, str, int]:
pid = create_form(owner)
add_question(owner, pid, "poll", label="Wann?", required="on", mode="dates", answers="ynm",
allow_proposals="on", date_option_id=["", ""],
option_date=["2026-07-01", "2026-07-08"], option_time=["18:30", ""],
option_duration=["90", ""], date_option_label=["", ""])
assert save_settings(owner, pid, access="link", calendar_mode="feed",
results_visibility="after_submit").status_code == 303
assert set_status(owner, pid, "open").status_code == 303
(qid,) = question_ids(pid)
return pid, form_row(pid).share_token, qid
def test_poll_votes_proposal_results_and_calendar(app: Any) -> None:
owner = creator(app)
pid, token, qid = poll_form(owner)
first, second = (o["id"] for o in options_of(qid))
guest = new_client(app)
resp = fill(guest, token, {f"q{qid}_{first}": "yes"})
assert resp.status_code == 400 and "Please answer every option." in resp.text
resp = fill(guest, token, {f"q{qid}_{first}": "yes", f"q{qid}_{second}": "maybe",
f"q{qid}_propose_date": "2026-07-15",
f"q{qid}_propose_time": "19:00"})
assert resp.status_code == 303
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
other = new_client(app)
votes = {f"q{qid}_{o['id']}": "no" for o in options}
votes[f"q{qid}_{first}"] = "yes"
assert fill(other, token, votes).status_code == 303
results = owner.get(f"/forms/{pid}/responses").text
assert '<tr class="best">' in results
csrf = token_for(owner, f"/forms/{pid}/responses")
owner.post(f"/forms/{pid}/questions/{qid}/confirm",
data={"csrf_token": csrf, "confirmed": [first]})
ics = guest.get(f"/f/{token}/calendar.ics")
assert ics.status_code == 200 and ics.headers["content-type"].startswith("text/calendar")
assert ics.text.count("BEGIN:VEVENT") == 1 and "DTSTART:20260701T163000Z" in ics.text
with Session(db.get_engine()) as s:
feed = s.scalar(select(Form.calendar_token).where(Form.public_id == uuid.UUID(pid)))
assert feed
anonymous = TestClient(app, base_url="http://localhost")
assert anonymous.get(f"/calendar/{feed}.ics").status_code == 200
assert anonymous.get("/calendar/falsch.ics").status_code == 404
owner.post(f"/forms/{pid}/calendar-token", data={"csrf_token": csrf})
assert anonymous.get(f"/calendar/{feed}.ics").status_code == 404
# ---------------------------------------------------------------------------
# Kommentare
# ---------------------------------------------------------------------------
def comment(client: TestClient, token: str, body: str, **extra: Any) -> Any:
csrf = token_for(client, f"/f/{token}")
return client.post(f"/f/{token}/comments", data={"csrf_token": csrf, "body": body, **extra})
def test_moderated_comments(app: Any) -> None:
owner = creator(app)
pid = create_form(owner)
add_question(owner, pid, "short_text", label="Name")
assert save_settings(owner, pid, access="link", comments_mode="moderated",
comments_anonymous="on").status_code == 303
assert set_status(owner, pid, "open").status_code == 303
token = form_row(pid).share_token
guest, other = new_client(app), new_client(app)
assert comment(guest, token, "Ohne Namen").headers["location"].endswith(
"comment_error=comment_name_missing#comments")
resp = comment(guest, token, "Gibt es Parkplätze? <b>x</b>", guest_name="Gerd")
assert resp.status_code == 303
assert "Gibt es Parkplätze?" in guest.get(f"/f/{token}").text # eigener, wartend
assert "Gibt es Parkplätze?" not in other.get(f"/f/{token}").text
moderation = owner.get(f"/forms/{pid}/comments").text
assert "Gerd" in moderation and "&lt;b&gt;" in moderation
with Session(db.get_engine()) as s:
cid = str(s.scalar(select(Comment.public_id)))
csrf = token_for(owner, f"/forms/{pid}/comments")
owner.post(f"/forms/{pid}/comments/{cid}/publish", data={"csrf_token": csrf})
page = other.get(f"/f/{token}").text
assert "Gibt es Parkplätze?" in page and "Gerd" not in page # anonym für andere
# Andere dürfen nicht ändern; der Autor schon, dann wieder zur Freigabe
csrf_other = token_for(other, f"/f/{token}")
resp = other.post(f"/f/{token}/comments/{cid}/edit",
data={"csrf_token": csrf_other, "body": "gekapert"})
assert "comment_error=comment_not_own" in resp.headers["location"]
csrf_guest = token_for(guest, f"/f/{token}")
guest.post(f"/f/{token}/comments/{cid}/edit",
data={"csrf_token": csrf_guest, "body": "Gibt es Fahrradständer?"})
assert "Fahrradständer" not in other.get(f"/f/{token}").text
# Begrenzung gegen Spam
for index in range(9):
comment(guest, token, f"Nachricht {index}", guest_name="Gerd")
resp = comment(guest, token, "zu viel", guest_name="Gerd")
assert "comment_error=comment_limit" in resp.headers["location"]
def test_comments_off(app: Any) -> None:
owner = creator(app)
pid = create_form(owner)
add_question(owner, pid, "short_text", label="Name")
assert save_settings(owner, pid, access="link", comments_mode="off").status_code == 303
assert set_status(owner, pid, "open").status_code == 303
token = form_row(pid).share_token
guest = new_client(app)
assert 'id="comments"' not in guest.get(f"/f/{token}").text
assert comment(guest, token, "Hallo", guest_name="G").status_code == 404
+226
View File
@@ -0,0 +1,226 @@
# SPDX-License-Identifier: AGPL-3.0-or-later
"""Phase 8c gegen PostgreSQL: Antworten ändern mit Vermerk, Ergebnisse für Teilnehmende,
Teilnehmerlisten als PDF (CI)."""
from __future__ import annotations
import io
import zipfile
from datetime import UTC, datetime
from typing import Any
from zoneinfo import ZoneInfo
import pytest
pytest.importorskip("fastapi")
from helpers import new_client, token_for
from sqlalchemy import select, update
from sqlalchemy.orm import Session
from test_evaluation import prepare
from test_forms import (
add_question,
create_form,
creator,
fill,
form_row,
participant,
question_ids,
)
from test_phase5 import slot_form
from surveybox import db
from surveybox.models import AuditEvent, Form, Response, ResponseNote
pytestmark = pytest.mark.db
def first_response(pid: str) -> Response:
with Session(db.get_engine()) as s:
found = s.scalar(select(Response).where(Response.form_id == form_row(pid).id)
.order_by(Response.submitted_at, Response.id))
assert found is not None
s.expunge(found)
return found
# --------------------------------------------------------------------------
# Antwort ändern mit Vermerk
# --------------------------------------------------------------------------
def test_manager_changes_answer_with_note(app: Any) -> None:
carla, pid, _, slot_q, name_q, options = prepare(app)
rid = first_response(pid).public_id # Bernd Krause, Früh
url = f"/forms/{pid}/responses/{rid}/edit"
page = carla.get(url).text
assert 'name="edit_note"' in page and "Bernd Krause" in page
data = {f"q{slot_q}": options[1], f"q{name_q}_first": "Bernd",
f"q{name_q}_last": "Krause-Neu", f"q{name_q}_email": "b@x.de"}
# Ohne Vermerk wird nichts gespeichert
resp = carla.post(url, data={"csrf_token": token_for(carla, url), **data})
assert resp.status_code == 400 and "Please describe why" in resp.text
assert "Krause-Neu" not in carla.get(f"/forms/{pid}/responses/{rid}").text
resp = carla.post(url, data={"csrf_token": token_for(carla, url), **data,
"edit_note": "Anruf am Montag: <b>Schicht tauschen</b>"})
assert resp.status_code == 303 and "response_edited" in resp.headers["location"]
view = carla.get(f"/forms/{pid}/responses/{rid}").text
assert "Krause-Neu" in view and "Anruf am Montag" in view and "&lt;b&gt;" in view
with Session(db.get_engine()) as s:
note = s.scalar(select(ResponseNote))
assert note is not None and set(note.changed) == {"Schicht", "Name"}
actions = list(s.scalars(select(AuditEvent.action)))
assert "response.edited" in actions
def test_note_in_subject_export_and_removed_when_anonymized(app: Any) -> None:
from surveybox.forms import retention, subject_export
carla, pid, _, slot_q, name_q, options = prepare(app)
response = first_response(pid)
url = f"/forms/{pid}/responses/{response.public_id}/edit"
carla.post(url, data={"csrf_token": token_for(carla, url), f"q{slot_q}": options[0],
f"q{name_q}_first": "Bernd", f"q{name_q}_last": "Krause",
"edit_note": "Nur geprüft"})
with Session(db.get_engine()) as s:
own = s.get(Response, response.id)
assert own is not None
data = subject_export.for_response(s, own, ZoneInfo("UTC"))
assert any(n["note"] == "Nur geprüft" for n in str_notes(data))
form = s.get(Form, own.form_id)
assert form is not None
retention.anonymize_responses(s, form, [own.id], datetime.now(UTC))
s.commit()
assert s.scalar(select(ResponseNote)) is None
def str_notes(data: Any) -> list[dict[str, Any]]:
"""Vermerke irgendwo in der Auskunft finden (Aufbau des Umschlags egal)."""
found: list[dict[str, Any]] = []
def walk(node: Any) -> None:
if isinstance(node, dict):
if isinstance(node.get("notes"), list):
found.extend(node["notes"])
for value in node.values():
walk(value)
elif isinstance(node, list):
for value in node:
walk(value)
walk(data)
return found
def test_evaluators_cannot_change_answers(app: Any) -> None:
_, pid, _, _, _, _ = prepare(app)
rid = first_response(pid).public_id
assert new_client(app).get(f"/forms/{pid}/responses/{rid}/edit").status_code == 303
olga = participant(app, "olga@example.de")
assert olga.get(f"/forms/{pid}/responses/{rid}/edit").status_code in (403, 404)
# --------------------------------------------------------------------------
# Ergebnisse für Teilnehmende
# --------------------------------------------------------------------------
def test_results_after_own_participation(app: Any) -> None:
owner = creator(app)
pid, token, slot_q, options = slot_form(owner, capacity="2",
results_visibility="after_submit")
add_question(owner, pid, "short_text", label="Bemerkung")
note_q = question_ids(pid)[-1]
other = new_client(app)
page = other.get(f"/f/{token}/results").text
assert "after you have taken part" in page
guest = new_client(app)
assert fill(guest, token, {f"q{slot_q}": options[0],
f"q{note_q}": "geheimer Freitext"}).status_code == 303
assert "/results" in guest.get(f"/f/{token}/thanks").text
page = guest.get(f"/f/{token}/results").text
assert "Results from 1 answer" in page and "Schicht" in page
assert "geheimer Freitext" not in page and "Bemerkung" not in page
# Wer nicht teilgenommen hat, sieht weiterhin nichts
assert "after you have taken part" in other.get(f"/f/{token}/results").text
def test_results_after_close_and_never(app: Any) -> None:
owner = creator(app)
pid, token, slot_q, options = slot_form(owner, capacity="2",
results_visibility="after_close")
assert fill(new_client(app), token, {f"q{slot_q}": options[0]}).status_code == 303
visitor = new_client(app)
assert "once the form has closed" in visitor.get(f"/f/{token}/results").text
with Session(db.get_engine()) as s:
s.execute(update(Form).where(Form.id == form_row(pid).id).values(
status="closed", closed_at=datetime.now(UTC)))
s.commit()
closed = visitor.get(f"/f/{token}").text
assert f"/f/{token}/results" in closed
assert "Results from 1 answer" in visitor.get(f"/f/{token}/results").text
with Session(db.get_engine()) as s:
s.execute(update(Form).where(Form.id == form_row(pid).id).values(
results_visibility="never"))
s.commit()
assert visitor.get(f"/f/{token}/results").status_code == 404
# --------------------------------------------------------------------------
# Teilnehmerlisten als PDF
# --------------------------------------------------------------------------
def test_participant_lists_pdf(app: Any) -> None:
pytest.importorskip("reportlab")
carla, pid, _, _, _, _ = prepare(app)
csrf = token_for(carla, f"/forms/{pid}/responses")
resp = carla.post(f"/forms/{pid}/responses/lists",
data={"csrf_token": csrf, "signature": "on"})
assert resp.status_code == 200 and resp.headers["content-type"] == "application/pdf"
assert resp.content.startswith(b"%PDF") and "attachment" in resp.headers[
"content-disposition"]
with Session(db.get_engine()) as s:
details = [e.details for e in s.scalars(
select(AuditEvent).where(AuditEvent.action == "form.exported"))]
assert details[-1]["format"] == "lists" # type: ignore[index]
def test_answers_as_pdf_and_ods(app: Any) -> None:
pytest.importorskip("reportlab")
carla, pid, _, _, _, _ = prepare(app)
for kind, start in (("pdf", b"%PDF"), ("ods", b"PK")):
csrf = token_for(carla, f"/forms/{pid}/responses")
resp = carla.post(f"/forms/{pid}/responses/export",
data={"csrf_token": csrf, "format": kind})
assert resp.status_code == 200 and resp.content.startswith(start)
assert resp.headers["content-disposition"].endswith(f'.{kind}"')
with zipfile.ZipFile(io.BytesIO(resp.content)) as z:
assert "Krause" in z.read("content.xml").decode()
csrf = token_for(carla, f"/forms/{pid}/responses")
assert carla.post(f"/forms/{pid}/responses/export",
data={"csrf_token": csrf, "format": "docx"}).status_code == 404
def test_no_participant_lists_without_slots(app: Any) -> None:
pytest.importorskip("reportlab")
owner = creator(app)
pid = create_form(owner)
add_question(owner, pid, "short_text", label="Was bringst du mit?")
page = owner.get(f"/forms/{pid}/responses").text
assert "Participant lists (PDF)" not in page and 'value="pdf"' in page
csrf = token_for(owner, f"/forms/{pid}/responses")
assert owner.post(f"/forms/{pid}/responses/lists",
data={"csrf_token": csrf}).status_code == 404
def test_no_participant_lists_for_anonymous_forms(app: Any) -> None:
pytest.importorskip("reportlab")
carla, pid, _, _, _, _ = prepare(app)
with Session(db.get_engine()) as s:
s.execute(update(Form).where(Form.id == form_row(pid).id).values(anonymous=True))
s.commit()
csrf = token_for(carla, f"/forms/{pid}/responses")
assert "Participant lists (PDF)" not in carla.get(f"/forms/{pid}/responses").text
resp = carla.post(f"/forms/{pid}/responses/lists", data={"csrf_token": csrf})
assert resp.status_code == 404
+114
View File
@@ -0,0 +1,114 @@
# SPDX-License-Identifier: AGPL-3.0-or-later
"""Phase 8c ohne Datenbank: PDF-Ausgaben, ODS, Vermerke, Ergebnis-Cookie."""
from __future__ import annotations
import io
import re
import zipfile
from decimal import Decimal
from pathlib import Path
from types import SimpleNamespace
from xml.etree import ElementTree
import pytest
LOGO = Path(__file__).parents[1] / "surveybox" / "web" / "static" / "img" / "logo-128.png"
def test_pdf_lists() -> None:
pytest.importorskip("reportlab")
from surveybox.forms import pdf_export as pdf
sections = [pdf.Section("Schicht", [
pdf.Entry("Früh", 3, ["Anna <b", "Jiří Novák & Şahin"], ["Wartend"]),
pdf.Entry("Spät", None, [f"Person {i}" for i in range(80)], []),
pdf.Entry("Leer", None, [], []),
])]
data = pdf.participant_lists("Fest <x>", sections, [("Stand", "25.11.2026")],
LOGO.read_bytes(), pdf.Options(signature=True,
page_per_entry=True))
assert data.startswith(b"%PDF")
pages = len(re.findall(rb"/Type /Page\b(?!s)", data))
assert pages >= 4 # jeder Eintrag beginnt auf einer neuen Seite, "Spät" braucht zwei
plain = pdf.participant_lists("Fest", [pdf.Section("", [pdf.Entry("Alle", None, ["A"])])],
[], None, pdf.Options())
assert len(re.findall(rb"/Type /Page\b(?!s)", plain)) == 1
def test_printable_falls_back_to_base_letters() -> None:
pytest.importorskip("reportlab")
from surveybox.forms.pdf_export import printable
assert printable("Jiří Őz\u0000\nŞahin") == "Jirí Oz Şahin" # í kennt die Schrift
assert printable("Anna") == "Anna"
def test_changed_labels_and_clean() -> None:
pytest.importorskip("sqlalchemy")
from surveybox.forms import notes
q1, q2, q3 = (SimpleNamespace(id=i, label=f"Frage {i}") for i in (1, 2, 3))
before = [(q1, "Ja", []), (q2, "", [{"id": "a"}]), (q3, "x", [])]
after = [(q1, "Ja", []), (q2, "", [{"id": "b"}]), (q3, "y", [])]
assert notes.changed_labels(before, after) == ["Frage 2", "Frage 3"]
assert notes.changed_labels(before, before) == []
assert notes.clean(" Zeile 1\r\nZeile 2\x07 ") == "Zeile 1\nZeile 2"
def test_results_cookie_and_visibility() -> None:
pytest.importorskip("sqlalchemy")
from surveybox.forms import public_results
form = SimpleNamespace(public_id="p1", share_token="tok" * 8, results_visibility="never")
value = public_results.cookie_value("geheim", form) # type: ignore[arg-type]
assert public_results.cookie_valid("geheim", form, value) # type: ignore[arg-type]
assert not public_results.cookie_valid("anders", form, value) # type: ignore[arg-type]
assert not public_results.cookie_valid("geheim", form, None) # type: ignore[arg-type]
assert not public_results.visible(form, True) # type: ignore[arg-type]
form.results_visibility = "after_submit"
assert public_results.visible(form, True) # type: ignore[arg-type]
assert not public_results.visible(form, False) # type: ignore[arg-type]
def test_pdf_answers_table_fits_page_width() -> None:
pytest.importorskip("reportlab")
from surveybox.forms import pdf_export as pdf
headers = ["Nr.", "Abgegeben", "Teilnehmer", "Was bringst du mit?", "E-Mail-Adresse"]
rows = [[1, "25.11.2026 11:34", "Gast", "Muffin <b>", None],
[2, "25.11.2026 11:36", "Gast", "Langer Text\nmit Umbruch " * 8, "a@b.de"]]
widths = pdf.column_widths(headers, rows, 770.0, 9.0)
assert widths is not None and abs(sum(widths) - 770.0) < 0.01
data = pdf.answers_table("Muster", headers, rows, [("Antworten", "2")], LOGO.read_bytes())
assert data.startswith(b"%PDF") and b"/MediaBox [ 0 0 841.8898 595.2756 ]" in data
# Sehr viele Spalten: passt trotzdem auf die Seitenbreite (kleinere Schrift)
wide = [f"Frage {i} mit langer Beschriftung" for i in range(30)]
assert pdf.answers_table("Muster", wide, [["x" * 40] * 30], [], None).startswith(b"%PDF")
def test_ods_document() -> None:
from surveybox.forms import ods
sheet = ods.Sheet("Antworten", [[], ["Titel"], ["Stand: heute"], []],
["Nr.", "Name", None], [[1, "=1+1", Decimal("2.5")], [2, "a\nb <&>", None]],
widths=[6, 20, 10], title_rows={1},
image=ods.Image(LOGO.read_bytes(), 1.27, 1.27),
page=ods.PageSetup(footer=("Seite ", " von ")))
data = ods.document(sheet, "Fest")
with zipfile.ZipFile(io.BytesIO(data)) as z:
first = z.infolist()[0]
assert first.filename == "mimetype" and first.compress_type == zipfile.ZIP_STORED
assert z.read("mimetype") == b"application/vnd.oasis.opendocument.spreadsheet"
for name in ("content.xml", "styles.xml", "meta.xml", "META-INF/manifest.xml"):
ElementTree.fromstring(z.read(name)) # noqa: S314 (selbst erzeugt)
content = z.read("content.xml").decode()
styles = z.read("styles.xml").decode()
assert "Pictures/logo.png" in z.namelist()
assert "table:formula" not in content and "<text:p>=1+1</text:p>" in content
assert "<text:p>a</text:p><text:p>b &lt;&amp;&gt;</text:p>" in content
assert 'office:value="2.5"' in content and "<table:table-header-rows>" in content
assert 'table:target-range-address="Antworten.A5:Antworten.C7"' in content
assert 'style:print-orientation="landscape"' in styles and 'style:scale-to-X="1"' in styles
assert "<text:page-number>" in styles and "<text:page-count>" in styles
assert 'fo:margin-top="2.0cm"' in styles
+134
View File
@@ -0,0 +1,134 @@
# SPDX-License-Identifier: AGPL-3.0-or-later
"""Fragengruppen gegen PostgreSQL: Einfügen, Tabelle, Höchstzahl, Buchung (CI)."""
from __future__ import annotations
from typing import Any
import pytest
pytest.importorskip("fastapi")
from fastapi.testclient import TestClient
from helpers import new_client, token_for
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_phase5 import bookings
from surveybox import db
from surveybox.models import Question
pytestmark = pytest.mark.db
def add_to_group(client: TestClient, pid: str, group: int, type_key: str, **fields: Any) -> None:
url = f"/forms/{pid}/questions/new?type={type_key}&group={group}"
csrf = token_for(client, url)
resp = client.post(url, data={"csrf_token": csrf, **fields})
assert resp.status_code == 303, resp.text
def types_in_order(pid: str) -> list[str]:
with Session(db.get_engine()) as s:
return [s.get(Question, qid).type for qid in question_ids(pid)] # type: ignore[union-attr]
def shift_form(owner: TestClient, max_select: str = "1") -> tuple[str, str, list[int]]:
pid = create_form(owner)
add_question(owner, pid, "question_group", label="Schichten", member_type="slots",
max_select=max_select)
add_question(owner, pid, "short_text", label="Bemerkung")
(group, _) = question_ids(pid)
# In die Gruppe einfügen: landet vor "Bemerkung", nicht am Ende
add_to_group(owner, pid, group, "slots", label="Freitag", capacity="1")
add_to_group(owner, pid, group, "slots", label="Samstag", capacity="5")
assert types_in_order(pid) == ["question_group", "slots", "slots", "short_text"]
assert save_settings(owner, pid, access="link").status_code == 303
assert set_status(owner, pid, "open").status_code == 303
return pid, form_row(pid).share_token, question_ids(pid)
def test_group_is_shown_as_table_and_indented(app: Any) -> None:
owner = creator(app)
pid, token, (group, fri, _sat, _) = shift_form(owner)
designer = owner.get(f"/forms/{pid}").text
assert designer.count("group-member") == 2
assert f"group={group}" in designer
page = new_client(app).get(f"/f/{token}").text
assert 'class="group-table group-slots"' in page
assert f'data-qid="{fri}" data-type="slots"' in page
assert 'value="single"' in page
assert 'data-max="1"' in page
def test_group_limit_and_booking(app: Any) -> None:
owner = creator(app)
_, token, (_group, fri, sat, _) = shift_form(owner)
guest = new_client(app)
resp = fill(guest, token, {f"q{fri}": "single", f"q{sat}": "single"})
assert resp.status_code == 400
assert "more entries than allowed" in resp.text
assert bookings(fri) == [] and bookings(sat) == []
assert fill(guest, token, {f"q{fri}": "single"}).status_code == 303
assert bookings(fri) == [("single", "confirmed", False)]
# Freitag hat nur einen Platz
other = new_client(app)
resp = fill(other, token, {f"q{fri}": "single"})
assert resp.status_code == 409
places = other.get(f"/f/{token}/places").json()
assert places[str(fri)]["single"] == {"free": 0, "full": True}
def test_required_rows_do_not_block_the_form(app: Any) -> None:
"""Drei Pflicht-Schichten bei höchstens einer: Die Gruppe regelt die Pflicht."""
owner = creator(app)
pid = create_form(owner)
add_question(owner, pid, "question_group", label="Schichten", member_type="slots",
min_select="1", max_select="1")
(group,) = question_ids(pid)
for label in ("Fr", "Sa", "So"):
add_to_group(owner, pid, group, "slots", label=label, required="on")
assert "A single entry cannot be required" in owner.get(
f"/forms/{pid}/questions/new?type=slots&group={group}").text
assert save_settings(owner, pid, access="link").status_code == 303
assert set_status(owner, pid, "open").status_code == 303
token = form_row(pid).share_token
(_, fri, _, _) = question_ids(pid)
guest = new_client(app)
resp = fill(guest, token, {})
assert resp.status_code == 400
assert "Please choose more entries in this group" in resp.text
assert "Please answer this question" not in resp.text
assert fill(guest, token, {f"q{fri}": "single"}).status_code == 303
def test_unlimited_group(app: Any) -> None:
owner = creator(app)
_, token, (_, fri, sat, _) = shift_form(owner, max_select="0")
resp = fill(new_client(app), token, {f"q{fri}": "single", f"q{sat}": "single"})
assert resp.status_code == 303
def test_capacity_edit_keeps_bookings(app: Any) -> None:
owner = creator(app)
pid, token, (_, fri, _, _) = shift_form(owner)
assert fill(new_client(app), token, {f"q{fri}": "single"}).status_code == 303
csrf = token_for(owner, f"/forms/{pid}/questions/{fri}")
resp = owner.post(f"/forms/{pid}/questions/{fri}", data={
"csrf_token": csrf, "label": "Freitag abend", "slot_mode": "single", "capacity": "3"})
assert resp.status_code == 303
assert bookings(fri) == [("single", "confirmed", False)]
with Session(db.get_engine()) as s:
q = s.get(Question, fri)
assert q is not None
assert q.config["options"] == [{"id": "single", "label": "Freitag abend", "capacity": 3}]
+245
View File
@@ -0,0 +1,245 @@
# SPDX-License-Identifier: AGPL-3.0-or-later
"""Fragetypen ohne Datenbank: Einstellungen, Prüfung, Anzeige, Rückweg ins Formular."""
from __future__ import annotations
from datetime import date, datetime, time
from decimal import Decimal
from types import SimpleNamespace
from typing import Any
from zoneinfo import ZoneInfo
import pytest
from surveybox.forms import types
from surveybox.forms.types import OTHER, ConfigError, parse_answer, parse_config
TZ = ZoneInfo("Europe/Berlin")
def q(type_: str, required: bool = False, **config: Any) -> SimpleNamespace:
return SimpleNamespace(id=7, type=type_, label="Frage", required=required, config=config)
OPTS = [{"id": "aaaaaa01", "label": "Rot"}, {"id": "bbbbbb02", "label": "Grün"},
{"id": "cccccc03", "label": "Blau"}]
def answer(question: SimpleNamespace, **fields: Any) -> types.AnswerResult:
data = {k: v if isinstance(v, list) else [v] for k, v in fields.items()}
return parse_answer(question, data, TZ)
# --- Einstellungen ----------------------------------------------------------
def test_options_keep_ids_and_skip_blank_rows() -> None:
cfg = parse_config(
"single_choice",
{
"option_id": ["aaaaaa01", "", "kaputt!", ""],
"option_label": ["Rot", " Grün ", "Blau", ""],
"display": ["dropdown"],
"allow_other": ["on"],
},
)
assert [o["label"] for o in cfg["options"]] == ["Rot", "Grün", "Blau"]
assert cfg["options"][0]["id"] == "aaaaaa01"
assert cfg["options"][2]["id"] != "kaputt!"
assert cfg["display"] == "dropdown" and cfg["allow_other"] is True
def test_options_need_two() -> None:
with pytest.raises(ConfigError, match="options_too_few"):
parse_config("ranking", {"option_label": ["nur eine"]})
def test_number_config_range() -> None:
cfg = parse_config("number", {"min": ["1,5"], "max": ["10"], "decimals": ["1"], "unit": ["kg"]})
assert cfg == {"min": "1.5", "max": "10", "decimals": 1, "unit": "kg"}
with pytest.raises(ConfigError):
parse_config("number", {"min": ["5"], "max": ["1"]})
with pytest.raises(ConfigError):
parse_config("number", {"decimals": ["9"]})
def test_unknown_type() -> None:
with pytest.raises(ConfigError):
parse_config("datei", {})
# --- Antworten ------------------------------------------------------------------
def test_required_and_empty() -> None:
assert answer(q("short_text", required=True), q7=" ").error == "required"
assert answer(q("short_text"), q7="").stored is None
def test_text_normalization_and_length() -> None:
assert answer(q("short_text", max_length=10), q7=" zu viel ").stored == {
"value_text": "zu viel"
}
assert answer(q("short_text", max_length=3), q7="abcd").error == "too_long"
long = answer(q("long_text"), q7="Zeile 1\r\nZeile 2\n").stored
assert long == {"value_text": "Zeile 1\nZeile 2"}
@pytest.mark.parametrize(
("value", "ok"),
[("anna@example.de", True), ("anna@", False), ("a b@example.de", False)],
)
def test_email(value: str, ok: bool) -> None:
assert (answer(q("email"), q7=value).error is None) is ok
@pytest.mark.parametrize(
("value", "ok"), [("+49 7651 1234", True), ("(07651) 12-34", True), ("12", False),
("abc", False)]
)
def test_phone(value: str, ok: bool) -> None:
assert (answer(q("phone"), q7=value).error is None) is ok
def test_number_rules() -> None:
question = q("number", min="0", max="100", decimals=1)
assert answer(question, q7="12,5").stored == {"value_number": Decimal("12.5")}
assert answer(question, q7="12.55").error == "number_decimals"
assert answer(question, q7="-1").error == "number_min"
assert answer(question, q7="101").error == "number_max"
assert answer(question, q7="zwölf").error == "number"
assert answer(q("number"), q7="1e20").error == "number"
assert answer(q("number"), q7="NaN").error == "number"
def test_date_time_datetime() -> None:
d = q("date", min_date="2026-01-01", max_date="2026-12-31")
assert answer(d, q7="2026-05-01").stored == {"value_date": date(2026, 5, 1)}
assert answer(d, q7="2025-12-31").error == "date_min"
assert answer(d, q7="31.05.2026").error == "date"
assert answer(q("time"), q7="18:30").stored == {"value_time": time(18, 30)}
dt = answer(q("datetime"), q7="2026-07-01T18:30").stored
assert dt is not None and dt["value_datetime"] == datetime(2026, 7, 1, 18, 30, tzinfo=TZ)
def test_yes_no() -> None:
assert answer(q("yes_no"), q7="yes").stored == {"value_bool": True}
assert answer(q("yes_no"), q7="no").stored == {"value_bool": False}
assert answer(q("yes_no"), q7="vielleicht").error == "choice"
def test_single_choice_with_other() -> None:
question = q("single_choice", options=OPTS, allow_other=True)
assert answer(question, q7="bbbbbb02").stored == {"value_text": "bbbbbb02"}
assert answer(question, q7="fremd").error == "choice"
assert answer(question, q7=OTHER).error == "other_missing"
assert answer(question, q7=OTHER, q7_other="Gelb").stored == {
"value_text": OTHER, "value_json": {"other": "Gelb"}
}
assert answer(q("single_choice", options=OPTS), q7=OTHER).error == "choice"
def test_multiple_choice_limits() -> None:
question = q("multiple_choice", options=OPTS, min_select=2, max_select=2, allow_other=True)
assert answer(question, q7=["aaaaaa01"]).error == "select_min"
assert answer(question, q7=["aaaaaa01", "bbbbbb02", "cccccc03"]).error == "select_max"
ok = answer(question, q7=["aaaaaa01", OTHER], q7_other="Gelb").stored
assert ok == {"value_json": {"selected": ["aaaaaa01"], "other": "Gelb"}}
assert answer(question, q7=["aaaaaa01", "boese"]).error == "choice"
def test_ranking() -> None:
question = q("ranking", options=OPTS)
full = {"q7_rank_aaaaaa01": "2", "q7_rank_bbbbbb02": "3", "q7_rank_cccccc03": "1"}
assert answer(question, **full).stored == {
"value_json": {"order": ["cccccc03", "aaaaaa01", "bbbbbb02"]}
}
assert answer(question, **{**full, "q7_rank_bbbbbb02": "2"}).error == "ranking"
assert answer(question, q7_rank_aaaaaa01="1").error == "ranking"
assert answer(question).stored is None
def test_rating() -> None:
question = q("rating", scale_max=5)
assert answer(question, q7="5").stored == {"value_number": Decimal(5)}
assert answer(question, q7="6").error == "rating"
assert answer(question, q7="0").error == "rating"
# --- Anzeige und Rückweg ----------------------------------------------------------
@pytest.mark.parametrize(
("question", "fields"),
[
(q("short_text"), {"q7": "Hallo"}),
(q("number", decimals=2, unit="€"), {"q7": "12.50"}),
(q("date"), {"q7": "2026-05-01"}),
(q("time"), {"q7": "08:15"}),
(q("datetime"), {"q7": "2026-07-01T18:30"}),
(q("yes_no"), {"q7": "no"}),
(q("single_choice", options=OPTS, allow_other=True), {"q7": OTHER, "q7_other": "Gelb"}),
(q("multiple_choice", options=OPTS, allow_other=True),
{"q7": ["bbbbbb02", OTHER], "q7_other": "Gelb"}),
(q("ranking", options=OPTS),
{"q7_rank_aaaaaa01": "2", "q7_rank_bbbbbb02": "1", "q7_rank_cccccc03": "3"}),
(q("rating", scale_max=7), {"q7": "4"}),
],
)
def test_roundtrip_stored_to_fields(question: SimpleNamespace, fields: dict[str, Any]) -> None:
first = answer(question, **fields).stored
assert first is not None
again = types.raw_from_answer(question, first, TZ)
assert parse_answer(question, again, TZ).stored == first
assert types.display_answer(question, first, TZ)
def test_display_marks_deleted_options() -> None:
question = q("multiple_choice", options=OPTS[:1])
text = types.display_answer(
question, {"value_json": {"selected": ["aaaaaa01", "weg00001"], "other": None}}, TZ
)
assert "Rot" in text and "(deleted option)" in text
def test_slots_and_poll_config_and_answers() -> None:
from types import SimpleNamespace
from surveybox.forms.types import ConfigError, parse_answer, parse_config
cfg = parse_config("slots", {
"slot_mode": ["list"],
"option_id": ["", "", ""], "option_label": ["Frühschicht", "", "Spätschicht"],
"option_capacity": ["5", "", ""], "multiple": ["on"], "waitlist": ["on"],
})
assert [o.get("capacity") for o in cfg["options"]] == [5, None]
assert cfg["multiple"] and cfg["waitlist"] and not cfg["hide_full"]
with pytest.raises(ConfigError):
parse_config("slots", {"slot_mode": ["list"], "option_label": ["A"],
"option_capacity": ["0"]})
dates = parse_config("poll", {
"mode": ["dates"], "answers": ["ynm"],
"date_option_id": ["", ""], "option_date": ["2026-07-08", "2026-07-01"],
"option_time": ["", "18:30"], "option_duration": ["", "90"],
"date_option_label": ["", "Grill"],
})
assert [o["date"] for o in dates["options"]] == ["2026-07-01", "2026-07-08"]
assert dates["options"][0]["time"] == "18:30" and dates["options"][0]["duration"] == 90
tz = ZoneInfo("Europe/Berlin")
poll = SimpleNamespace(id=4, type="poll", label="", required=True, config=dates)
first, second = (o["id"] for o in dates["options"])
assert parse_answer(poll, {f"q4_{first}": ["maybe"]}, tz).error == "poll_incomplete"
ok = parse_answer(poll, {f"q4_{first}": ["maybe"], f"q4_{second}": ["no"]}, tz)
assert ok.stored == {"value_json": {"votes": {first: "maybe", second: "no"}}}
yn = SimpleNamespace(id=4, type="poll", label="", required=False,
config={**dates, "answers": "yn"})
assert parse_answer(yn, {f"q4_{first}": ["maybe"]}, tz).error == "choice"
slots = SimpleNamespace(id=5, type="slots", label="", required=False,
config={**cfg, "multiple": False})
ids = [o["id"] for o in cfg["options"]]
assert parse_answer(slots, {"q5": ids}, tz).error == "choice"
assert parse_answer(slots, {"q5": [ids[0]]}, tz).stored == {
"value_json": {"selected": [ids[0]]}}
+143
View File
@@ -0,0 +1,143 @@
# SPDX-License-Identifier: AGPL-3.0-or-later
"""Phase 7a gegen PostgreSQL: Löschfristen, Hinweis an den Eigentümer (CI)."""
from __future__ import annotations
import re
from datetime import UTC, datetime, timedelta
from typing import Any
import pytest
pytest.importorskip("fastapi")
from helpers import new_client
from sqlalchemy import func, select, update
from sqlalchemy.orm import Session
from test_forms import (
creator,
fill,
form_row,
option_ids,
participant,
question_ids,
set_status,
simple_form,
)
from test_mail import content, messages
from surveybox import db
from surveybox.forms import retention
from surveybox.models import Answer, AuditEvent, Comment, Form, Question, Response
from surveybox.settings import get_settings
pytestmark = pytest.mark.db
def prepare(app: Any, mode: str = "anonymize") -> tuple[str, str, list[int], Any]:
"""Formular mit personenbezogener Namensfrage, zwei Antworten, geschlossen."""
carla = creator(app)
pid, token, (name_q, food_q) = simple_form(
carla, access="link", guest_email="optional", deletion_mode=mode)
with Session(db.get_engine()) as s:
s.execute(update(Question).where(Question.id == name_q).values(personal=True))
s.commit()
options = option_ids(pid, food_q)
assert fill(participant(app), token, {f"q{name_q}": "Paul", f"q{food_q}": options[0]}
).status_code == 303
guest = new_client(app)
resp = fill(guest, token, {f"q{name_q}": "Gast", f"q{food_q}": options[1],
"guest_email": "gast@example.de"})
assert resp.status_code == 303
assert set_status(carla, pid, "closed").status_code == 303
assert form_row(pid).closed_at is not None
return pid, token, [name_q, food_q], carla
def run(now: datetime) -> tuple[int, int]:
with Session(db.get_engine()) as s:
result = retention.run_due(s, get_settings(), now)
s.commit()
return result
def shift_end(pid: str, days_ago: int, retention_days: int) -> None:
with Session(db.get_engine()) as s:
s.execute(update(Form).where(Form.id == form_row(pid).id).values(
closed_at=datetime.now(UTC) - timedelta(days=days_ago),
retention_days=retention_days))
s.commit()
def responses(pid: str) -> list[Response]:
with Session(db.get_engine()) as s:
rows = list(s.scalars(select(Response).where(Response.form_id == form_row(pid).id)))
for row in rows:
s.expunge(row)
return rows
def test_anonymize_after_notice_and_grace(app: Any) -> None:
pid, _, (name_q, food_q), carla = prepare(app)
(receipt,) = messages("guest_receipt")
personal_link = re.search(r"https?://\S+/r/\S+", content(receipt)["text"]).group(0) # type: ignore[union-attr]
# Frist abgelaufen, aber noch kein Hinweis: erst Hinweis, keine Löschung
shift_end(pid, days_ago=40, retention_days=30)
now = datetime.now(UTC)
assert run(now) == (1, 0)
(notice,) = messages("retention_notice")
assert notice.recipient == "carla@example.de"
assert "will be anonymized" in content(notice)["text"]
assert all(r.anonymized_at is None for r in responses(pid))
assert run(now + timedelta(days=6)) == (0, 0) # Karenz nach dem Hinweis
# Nach sieben Tagen: anonymisiert
assert run(now + timedelta(days=8)) == (0, 2)
rows = responses(pid)
assert len(rows) == 2
assert all(r.user_id is None and r.guest_contact_id is None and r.access_hash is None
and r.anonymized_at is not None for r in rows)
with Session(db.get_engine()) as s:
kept = set(s.scalars(select(Answer.question_id).where(
Answer.response_id.in_([r.id for r in rows]))))
assert kept == {food_q} # Name (personenbezogen) gelöscht, Auswahl bleibt
actions = list(s.scalars(select(AuditEvent.action)))
assert "form.retention_applied" in actions
# Persönlicher Link des Gasts ist ungültig, Ergebnis bleibt sichtbar
path = personal_link.replace(get_settings().public_origin, "")
assert new_client(app).get(path).status_code in (404, 410)
assert "Pizza" in carla.get(f"/forms/{pid}/responses").text
assert run(now + timedelta(days=9)) == (0, 0) # nichts mehr zu tun
assert question_ids(pid) == [name_q, food_q]
def test_delete_mode_removes_answers_and_comments(app: Any) -> None:
pid, _, _, _ = prepare(app, mode="delete")
with Session(db.get_engine()) as s:
s.add(Comment(form_id=form_row(pid).id, guest_name="Gast", body="Hallo",
status="published"))
s.commit()
shift_end(pid, days_ago=400, retention_days=30)
now = datetime.now(UTC)
run(now)
assert "will be deleted completely" in content(messages("retention_notice")[0])["text"]
assert run(now + timedelta(days=8)) == (0, 2)
assert responses(pid) == []
with Session(db.get_engine()) as s:
assert s.scalar(select(func.count()).select_from(Comment)) == 0
def test_open_form_and_reopened_form_are_left_alone(app: Any) -> None:
pid, _, _, carla = prepare(app)
shift_end(pid, days_ago=400, retention_days=1)
assert set_status(carla, pid, "open").status_code == 303
assert form_row(pid).closed_at is None
assert run(datetime.now(UTC) + timedelta(days=30)) == (0, 0)
assert messages("retention_notice") == []
def test_settings_show_planned_date(app: Any) -> None:
pid, _, _, carla = prepare(app)
page = carla.get(f"/forms/{pid}/settings").text
assert "The answers will be anonymized on" in page
assert "default of this installation (730 days)" in page
assert "The retention period ends" in carla.get(f"/forms/{pid}/responses").text
+62
View File
@@ -0,0 +1,62 @@
# SPDX-License-Identifier: AGPL-3.0-or-later
"""Löschfristen: Ende des Formulars und Zeitpunkt der Löschung (ohne Datenbank)."""
from __future__ import annotations
from datetime import UTC, datetime, timedelta
from types import SimpleNamespace
from typing import Any
import pytest
pytest.importorskip("sqlalchemy")
from surveybox.forms import retention
NOW = datetime(2026, 11, 25, 12, 0, tzinfo=UTC)
def form(**kw: Any) -> Any:
base = {"is_template": False, "status": "closed", "closed_at": NOW - timedelta(days=10),
"closes_at": None, "updated_at": NOW - timedelta(days=20),
"retention_days": 30, "deletion_mode": "anonymize", "retention_notified_at": None}
return SimpleNamespace(**{**base, **kw})
class NoSettings:
def get(self, *_: Any) -> None:
return None
def test_end_of_form() -> None:
assert retention.ended_at(form(), NOW) == NOW - timedelta(days=10)
past = NOW - timedelta(days=3)
assert retention.ended_at(form(status="open", closes_at=past), NOW) == past
assert retention.ended_at(form(status="open", closes_at=NOW + timedelta(days=1)), NOW) is None
assert retention.ended_at(form(status="draft"), NOW) is None
assert retention.ended_at(form(is_template=True), NOW) is None
# Geschlossen ohne Zeitpunkt (ältere Daten): Enddatum, sonst letzte Änderung
assert retention.ended_at(form(closed_at=None), NOW) == NOW - timedelta(days=20)
def test_deletion_waits_for_the_notice() -> None:
plan = retention.schedule(NoSettings(), form(), NOW) # type: ignore[arg-type]
assert plan is not None and plan.due == NOW + timedelta(days=20)
assert plan.effective(None) is None
assert plan.effective(NOW - timedelta(days=11)) is None # Hinweis vor dem Ende zählt nicht
on_time = plan.due - retention.NOTICE_BEFORE
assert plan.effective(on_time) == plan.due
late = plan.due - timedelta(days=1)
assert plan.effective(late) == late + retention.GRACE_AFTER_NOTICE
def test_default_period_and_planned_date() -> None:
db: Any = NoSettings()
assert retention.days_for(db, form(retention_days=None)) == retention.DEFAULT_DAYS
# Kurze Frist ohne Hinweis: frühestens sieben Tage nach dem nächsten Lauf
short = form(retention_days=1)
assert retention.planned_date(db, short, NOW) == NOW + retention.GRACE_AFTER_NOTICE
# Lange Frist: genau zum Fristende
long = form(retention_days=400)
assert retention.planned_date(db, long, NOW) == NOW - timedelta(days=10) + timedelta(days=400)
assert retention.planned_date(db, form(status="draft"), NOW) is None
+51
View File
@@ -0,0 +1,51 @@
# SPDX-License-Identifier: AGPL-3.0-or-later
"""Gruppenhierarchie ohne Datenbank: Vererbung nach unten und oben, Kreise."""
from __future__ import annotations
import pytest
pytest.importorskip("sqlalchemy")
from surveybox.accounts import scope
# 1 Gesamtwehr
# 2 Abteilung Nord
# 4 Jugendfeuerwehr
# 3 Abteilung Süd
# 5 Förderverein
TREE = {1: None, 2: 1, 3: 1, 4: 2, 5: None}
NAMES = {1: "Gesamtwehr", 2: "Abteilung Nord", 3: "Abteilung Süd", 4: "Jugendfeuerwehr",
5: "Förderverein"}
def test_descendants_and_ancestors() -> None:
assert scope.descendants(TREE, [2]) == {2, 4}
assert scope.descendants(TREE, [1]) == {1, 2, 3, 4}
assert scope.ancestors(TREE, [4]) == {4, 2, 1}
assert scope.ancestors(TREE, [5, 3]) == {5, 3, 1}
assert scope.descendants(TREE, [99]) == set()
def test_cycles_are_detected() -> None:
assert scope.would_cycle(TREE, 1, 4)
assert scope.would_cycle(TREE, 2, 2)
assert not scope.would_cycle(TREE, 4, 3)
assert not scope.would_cycle(TREE, 4, None)
def test_tree_order_with_and_without_selection() -> None:
assert scope.depth_order(TREE, NAMES) == [(5, 0), (1, 0), (2, 1), (4, 2), (3, 1)]
# Nur ein Teilbaum sichtbar: er beginnt bei Tiefe 0
assert scope.depth_order(TREE, NAMES, {2, 4}) == [(2, 0), (4, 1)]
def test_scope_flags() -> None:
group_admin = scope.Scope(user_id=1, instance_admin=False, global_creator=False,
managed=frozenset({2, 4}), creating=frozenset({2, 4}))
assert group_admin.can_manage_groups and group_admin.can_create_forms
assert group_admin.manages(4) and not group_admin.manages(3)
assert group_admin.may_create_in(4) and not group_admin.may_create_in(None)
creator = scope.Scope(user_id=2, instance_admin=False, global_creator=True)
assert creator.may_create_in(None) and creator.may_create_in(3)
assert not creator.can_manage_groups
+136
View File
@@ -0,0 +1,136 @@
# SPDX-License-Identifier: AGPL-3.0-or-later
"""Abnahme, Sicherheit: Prüfungen über alle Routen statt einzelner Seiten (CI).
- Jede ändernde Anfrage (POST) hat die CSRF-Prüfung; Ausnahmen sind benannt.
- Jede Seite unter /admin, /forms und /account verlangt eine Anmeldung;
/admin zusätzlich Administratorrechte.
- Sicherheits-Header auf allen Arten von Antworten.
- Keine Weiterleitung nach außen, Cookies mit HttpOnly und SameSite.
- Teilnehmer-Seite unter 100 KB ohne Bilder und ohne externe Ressourcen.
"""
from __future__ import annotations
import re
from typing import Any
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
pytestmark = pytest.mark.db
# POST ohne CSRF-Prüfung, jeweils mit Grund
CSRF_EXEMPT = {
# Abmelden per Klick im Mailprogramm (RFC 8058): kommt ohne Cookies; der
# signierte Schlüssel im Link ist die Berechtigung
"/mail/unsubscribe/{token}",
}
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 _fill(route: APIRoute) -> 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)
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"}:
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)
assert missing == [], f"POST ohne CSRF-Prüfung: {missing}"
# Und wirklich: angemeldet, aber ohne Token wird abgewiesen
root = admin(app)
for path in ("/admin/appearance", "/forms", "/logout"):
assert root.post(path, data={"x": "1"}).status_code == 403, path
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):
continue
path = _fill(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"):
denied = paul.get(path)
assert denied.status_code in (303, 403, 404), path
if denied.status_code == 303:
assert not denied.headers["location"].startswith(path), path
checked += 1
assert checked > 40 # die Prüfung erfasst die Routen wirklich
def test_security_headers_on_all_kinds_of_responses(app: Any) -> None:
client = new_client(app)
for path in ("/login", "/static/css/app.css", "/gibt-es-nicht", "/favicon.ico",
"/f/unbekannt"):
resp = client.get(path)
headers = resp.headers
assert headers["X-Content-Type-Options"] == "nosniff", path
assert "default-src 'self'" in headers["Content-Security-Policy"], path
assert "script-src 'self'" in headers["Content-Security-Policy"], path
assert headers["Referrer-Policy"] == "same-origin", path
assert "server" not in headers, path
if not path.startswith("/static/"):
assert headers["Cache-Control"] == "no-store", path
html = client.get("/login").text
assert "<script>" not in html and " style=" not in html and "onclick" not in html
def test_no_open_redirects_and_cookie_flags(app: Any) -> None:
root = admin(app) # legt den Admin an und meldet ihn an
paul = participant(app)
client = new_client(app)
token = token_for(client, "/login")
resp = client.post("/login", data={"email": "paul@example.de", "password": PASSWORD,
"csrf_token": token, "next": "//evil.example/"})
assert resp.status_code == 303
assert resp.headers["location"].startswith("/") and "evil" not in resp.headers["location"]
for target in ("//evil.example/", "https://evil.example/", "/\\evil.example"):
location = root.get(f"/language/de?next={target}").headers.get("location", "/")
assert location.startswith("/") and not location.startswith(("//", "/\\")), target
assert paul.get("/").status_code == 200
resp = login(new_client(app), "paul@example.de")
cookies = [v for k, v in resp.headers.multi_items() if k.lower() == "set-cookie"]
session = next(c for c in cookies if "surveybox_session" in c)
assert "HttpOnly" in session and "SameSite=lax" in session.replace("Lax", "lax")
def test_participant_page_is_small_and_self_contained(app: Any) -> None:
owner = creator(app)
_, token, _ = simple_form(owner, access="link")
guest = new_client(app)
page = guest.get(f"/f/{token}")
assert page.status_code == 200
html = page.text
assets = re.findall(r'<(?:script|link)[^>]+(?:src|href)="([^"]+)"', html)
assert all(a.startswith("/") and not a.startswith("//") for a in assets), assets
total = len(page.content)
for asset in assets:
if asset.endswith((".css", ".js")) or "theme.css" in asset:
total += len(guest.get(asset.split("?")[0]).content)
assert total < 100_000, total
+187
View File
@@ -0,0 +1,187 @@
# SPDX-License-Identifier: AGPL-3.0-or-later
"""Sicherheitsbausteine ohne Datenbank."""
from __future__ import annotations
import base64
from ipaddress import ip_network
import pytest
from surveybox.security import csrf, recovery, totp
from surveybox.security.client_ip import client_ip, ip_key
from surveybox.security.headers import security_headers
from surveybox.security.tokens import derive_key, new_token, token_hash
# --- TOTP: Testvektoren aus RFC 6238, Anhang B (SHA-1, letzte 6 Ziffern) -------
RFC_SECRET = base64.b32encode(b"12345678901234567890").decode().rstrip("=")
@pytest.mark.parametrize(
("unix_time", "expected"),
[(59, "287082"), (1111111109, "081804"), (1111111111, "050471"), (1234567890, "005924"),
(2000000000, "279037"), (20000000000, "353130")],
)
def test_totp_rfc6238_vectors(unix_time: int, expected: str) -> None:
assert totp.code_at_step(RFC_SECRET, totp.current_step(unix_time)) == expected
def test_totp_accepts_neighbour_steps_and_rejects_replay() -> None:
secret = totp.generate_secret()
t = 1_700_000_000
step = totp.current_step(t)
previous = totp.code_at_step(secret, step - 1)
assert totp.verify(secret, previous, t, None) == step - 1
assert totp.verify(secret, previous, t, last_step=step - 1) is None # schon benutzt
far = totp.code_at_step(secret, step - 3)
assert totp.verify(secret, far, t, None) is None
def test_totp_normalizes_input() -> None:
secret = totp.generate_secret()
t = 1_700_000_000
code = totp.code_at_step(secret, totp.current_step(t))
assert totp.verify(secret, f"{code[:3]} {code[3:]}", t, None) is not None
assert totp.verify(secret, "12345", t, None) is None
def test_provisioning_uri_is_escaped() -> None:
uri = totp.provisioning_uri("ABC", "a b@example.de", "Survey box")
assert uri.startswith("otpauth://totp/Survey%20box%3Aa%20b%40example.de?")
assert "issuer=Survey%20box" in uri
# --- CSRF ---------------------------------------------------------------------
def test_csrf_token_roundtrip() -> None:
cookie = new_token(24)
token = csrf.form_token("k" * 40, cookie)
assert csrf.token_valid("k" * 40, cookie, token)
assert not csrf.token_valid("k" * 40, new_token(24), token)
assert not csrf.token_valid("x" * 40, cookie, token)
assert not csrf.token_valid("k" * 40, None, token)
assert not csrf.token_valid("k" * 40, cookie, None)
@pytest.mark.parametrize(
("origin", "referer", "ok"),
[
("https://umfrage.example", None, True),
("https://UMFRAGE.example", None, True),
("https://evil.example", None, False),
("null", "https://umfrage.example/login", True),
(None, "https://umfrage.example/account?x=1", True),
(None, "https://umfrage.example.evil.example/", False),
(None, None, False),
("http://umfrage.example", None, False),
],
)
def test_origin_check(origin: str | None, referer: str | None, ok: bool) -> None:
assert csrf.origin_allowed("https://umfrage.example", origin, referer) is ok
# --- Header -------------------------------------------------------------------
def test_security_headers() -> None:
h = security_headers(https=True)
assert "script-src 'self'" in h["Content-Security-Policy"]
assert "unsafe-inline" not in h["Content-Security-Policy"]
assert "frame-ancestors 'none'" in h["Content-Security-Policy"]
assert h["Strict-Transport-Security"].startswith("max-age=")
assert "Strict-Transport-Security" not in security_headers(https=False)
# Mit "no-referrer" schicken Browser bei Formularen "Origin: null"; dann
# scheitert jede Anmeldung an der CSRF-Prüfung (Fehler in Phase 2a).
assert h["Referrer-Policy"] == "same-origin"
assert h["X-Frame-Options"] == "DENY"
def test_frame_ancestors_allow_embedding() -> None:
h = security_headers(https=True, frame_ancestors="'self' https://cloud.example.de")
assert "frame-ancestors 'self' https://cloud.example.de" in h["Content-Security-Policy"]
# X-Frame-Options kennt nur eine Adresse und würde den Rahmen verbieten
assert "X-Frame-Options" not in h
# --- Client-IP ----------------------------------------------------------------
PROXIES = [ip_network("172.30.40.0/24"), ip_network("10.0.0.5/32")]
@pytest.mark.parametrize(
("peer", "xff", "expected"),
[
("203.0.113.9", None, "203.0.113.9"),
("203.0.113.9", "1.2.3.4", "203.0.113.9"), # kein vertrauter Proxy: Header ignorieren
("172.30.40.1", "198.51.100.7", "198.51.100.7"),
("172.30.40.1", "6.6.6.6, 198.51.100.7", "198.51.100.7"), # gefälschter Eintrag links
("172.30.40.1", "198.51.100.7, 10.0.0.5", "198.51.100.7"), # Proxykette
("172.30.40.1", "kaputt", "172.30.40.1"),
(None, None, "unknown"),
],
)
def test_client_ip(peer: str | None, xff: str | None, expected: str) -> None:
assert client_ip(peer, xff, PROXIES) == expected
def test_ip_key_is_pseudonymous() -> None:
key = ip_key("s" * 40, "198.51.100.7")
assert "198" not in key and len(key) == 32
assert key == ip_key("s" * 40, "198.51.100.7")
assert key != ip_key("t" * 40, "198.51.100.7")
# --- Tokens, Schlüssel, Wiederherstellungscodes -------------------------------
def test_derived_keys_differ_by_purpose() -> None:
a = derive_key("s" * 40, "csrf")
assert len(a) == 32
assert a != derive_key("s" * 40, "totp")
assert a == derive_key("s" * 40, "csrf")
assert len(derive_key("s" * 40, "x", length=80)) == 80
def test_token_hash_is_stable() -> None:
t = new_token()
assert len(t) >= 40
assert token_hash(t) == token_hash(t) and len(token_hash(t)) == 32
def test_recovery_codes() -> None:
codes = recovery.generate_codes()
assert len(codes) == 10 and len(set(codes)) == 10
assert all(len(c) == 14 and c.count("-") == 2 for c in codes)
code = codes[0]
h = recovery.code_hash("s" * 40, code)
assert recovery.code_hash("s" * 40, code.lower().replace("-", " ")) == h
assert recovery.code_hash("s" * 40, codes[1]) != h
def test_secretbox_roundtrip_and_context() -> None:
pytest.importorskip("cryptography")
from surveybox.security import secretbox
blob = secretbox.encrypt("s" * 40, "totp", b"GEHEIM", b"user:1")
assert b"GEHEIM" not in blob
assert secretbox.decrypt("s" * 40, "totp", blob, b"user:1") == b"GEHEIM"
with pytest.raises(secretbox.DecryptionError):
secretbox.decrypt("s" * 40, "totp", blob, b"user:2") # anderes Konto
with pytest.raises(secretbox.DecryptionError):
secretbox.decrypt("t" * 40, "totp", blob, b"user:1") # anderer Schlüssel
def test_password_rules() -> None:
pytest.importorskip("argon2")
from surveybox.security import passwords
assert passwords.password_problems("kurz") == ["too_short"]
assert "equals_email" in passwords.password_problems("anna@example.de", "Anna@Example.de")
assert "too_simple" in passwords.password_problems("aaaaaaaaaaaaaaa")
assert passwords.password_problems("ein langer satz mit wörtern") == []
h = passwords.hash_password("ein langer satz mit wörtern")
assert h.startswith("$argon2id$")
assert passwords.verify_password(h, "ein langer satz mit wörtern") == (True, False)
assert passwords.verify_password(h, "falsch")[0] is False
assert passwords.verify_password(None, "egal") == (False, False)
+51
View File
@@ -0,0 +1,51 @@
# SPDX-License-Identifier: AGPL-3.0-or-later
"""Teilnehmer-Name und Namen der Eingetragenen bei Teilnahme-Feldern (CI)."""
from __future__ import annotations
from typing import Any
import pytest
pytest.importorskip("fastapi")
from helpers import new_client
from test_forms import add_question, creator, fill, participant, question_ids, save_settings
from test_phase5 import slot_form
pytestmark = pytest.mark.db
def setup_form(app: Any, names: str) -> tuple[Any, str, str, int, int, str]:
carla = creator(app)
pid, token, slot_q, (early, _) = slot_form(carla, capacity="", slot_names=names)
add_question(carla, pid, "participant_name", label="Ihr Name", email_mode="optional",
personal="on")
name_q = question_ids(pid)[-1]
return carla, pid, token, slot_q, name_q, early
def test_names_of_others_are_shown_when_the_form_says_so(app: Any) -> None:
carla, pid, token, slot_q, name_q, early = setup_form(app, "short")
guest = new_client(app)
missing = fill(guest, token, {f"q{slot_q}": early})
assert missing.status_code == 400 and "first and last name" in missing.text
assert fill(guest, token, {f"q{slot_q}": early, f"q{name_q}_first": "Bernd",
f"q{name_q}_last": "Krause"}).status_code == 303
# Angemeldete ohne Namensfeld-Antwort erscheinen mit dem Kontonamen
paul = participant(app)
page = paul.get(f"/f/{token}").text
assert "Bernd K." in page and "Krause" not in page
assert "sees who has already signed up" in page
# Das Namensfeld ist aus dem Konto vorbelegt
assert 'autocomplete="email" value="paul@example.de"' in page
assert save_settings(carla, pid, access="link", slot_names="full").status_code == 303
assert "Bernd Krause" in new_client(app).get(f"/f/{token}").text
def test_names_stay_hidden_by_default(app: Any) -> None:
_, _, token, slot_q, name_q, early = setup_form(app, "off")
fill(new_client(app), token, {f"q{slot_q}": early, f"q{name_q}_first": "Bernd",
f"q{name_q}_last": "Krause"})
page = new_client(app).get(f"/f/{token}").text
assert "Bernd" not in page and "sees who has already signed up" not in page
+99
View File
@@ -0,0 +1,99 @@
# SPDX-License-Identifier: AGPL-3.0-or-later
"""Phase 7c gegen PostgreSQL: Datenexport für Betroffene (CI)."""
from __future__ import annotations
import json
import re
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
from sqlalchemy.orm import Session
from test_forms import creator, fill, participant
from test_mail import admin, content, messages
from test_phase5 import slot_form
from surveybox import db
from surveybox.models import AuditEvent, UserAccount
from surveybox.settings import get_settings
pytestmark = pytest.mark.db
def download(client: TestClient, page: str, action: str, **data: Any) -> dict[str, Any]:
csrf = token_for(client, page)
resp = client.post(action, data={"csrf_token": csrf, **data})
assert resp.status_code == 200, resp.text
assert resp.headers["content-type"].startswith("application/json")
assert "attachment" in resp.headers["content-disposition"]
assert resp.headers["cache-control"] == "no-store"
return dict(json.loads(resp.content))
def actions() -> list[str]:
with Session(db.get_engine()) as s:
return list(s.scalars(select(AuditEvent.action)))
def test_user_downloads_own_data(app: Any) -> None:
carla = creator(app)
_, token, qid, (early, _) = slot_form(carla)
paul = participant(app)
fill(paul, token, {f"q{qid}": early})
data = download(paul, "/account", "/account/export")
assert data["format"] == "surveybox-subject-export"
assert data["account"]["email"] == "paul@example.de"
(response,) = data["responses"]
assert response["form"]["title"] == "Sommerfest"
assert response["answers"][0]["answer"]
assert response["places"][0]["status"] == "confirmed"
assert "sessions" in data and "email_log" in data
assert "account.exported" in actions()
def test_guest_downloads_data_by_mail_and_by_personal_link(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/export", data={"csrf_token": csrf, "email": "gast@example.de"})
assert "sent a link to download it" in resp.text
(mail,) = messages("guest_export")
link = re.search(r"https?://\S+/g/export/\S+", content(mail)["text"]).group(0) # type: ignore[union-attr]
path = link.replace(get_settings().public_origin, "")
data = download(guest, path, path)
assert data["guest"]["email"] == "gast@example.de"
assert len(data["responses"]) == 1
assert "guest.exported" in actions()
# Gast ohne Adresse: über den persönlichen Link
other = new_client(app)
fill(other, token, {f"q{qid}": early})
personal = re.search(r"/r/[A-Za-z0-9_-]+", other.get(f"/f/{token}/thanks").text).group(0) # type: ignore[union-attr]
single = download(other, personal, f"{personal}/export")
assert len(single["responses"]) == 1 and "guest" not in single
# Falscher Link
assert new_client(app).get("/g/export/abc.123.def").status_code == 404
def test_admin_exports_user_and_guest(app: Any) -> None:
root = admin(app)
paul = participant(app)
del paul
with Session(db.get_engine()) as s:
target = s.scalar(select(UserAccount).where(UserAccount.email == "paul@example.de"))
assert target is not None
pid = target.public_id
data = download(root, f"/admin/users/{pid}", f"/admin/users/{pid}/export")
assert data["account"]["email"] == "paul@example.de"
csrf = token_for(root, "/admin/users")
resp = root.post("/admin/guests/export",
data={"csrf_token": csrf, "email": "niemand@example.de"})
assert resp.status_code == 303 and "guest_unknown" in resp.headers["location"]
assert "admin.user_exported" in actions()
+168
View File
@@ -0,0 +1,168 @@
# SPDX-License-Identifier: AGPL-3.0-or-later
"""Update-Ablauf gegen eine echte PostgreSQL-Datenbank (nur in der CI)."""
from __future__ import annotations
import shutil
from pathlib import Path
import pytest
pytest.importorskip("alembic")
from sqlalchemy import text
from surveybox import db
from surveybox.settings import Settings
from surveybox.upgrade import (
MIGRATION_LOCK_KEY,
MIGRATIONS_DIR,
UpgradeError,
current_revision,
head_revision,
run_upgrade,
)
pytestmark = pytest.mark.db
MIGRATION_OK = '''
import sqlalchemy as sa
from alembic import op
revision = "9001_test_ok"
down_revision = "{down}"
branch_labels = None
depends_on = None
def upgrade() -> None:
op.create_table("test_ok", sa.Column("id", sa.Integer(), primary_key=True))
op.execute("INSERT INTO test_ok (id) VALUES (1)")
def downgrade() -> None:
op.drop_table("test_ok")
'''
MIGRATION_BROKEN = '''
import sqlalchemy as sa
from alembic import op
revision = "9002_test_broken"
down_revision = "9001_test_ok"
branch_labels = None
depends_on = None
def upgrade() -> None:
op.create_table("test_half", sa.Column("id", sa.Integer(), primary_key=True))
op.add_column("test_ok", sa.Column("extra", sa.Text()))
op.execute("SELECT * FROM gibt_es_nicht") # schlägt fehl
def downgrade() -> None:
pass
'''
def _script_dir(tmp_path: Path, *extra: str) -> Path:
target = tmp_path / "migrations"
shutil.copytree(MIGRATIONS_DIR, target, ignore=shutil.ignore_patterns("__pycache__"))
real_head = head_revision()
for i, body in enumerate(extra):
(target / "versions" / f"9{i:03d}_test.py").write_text(body.replace("{down}", real_head))
return target
def _table_exists(name: str) -> bool:
with db.get_engine().connect() as conn:
return bool(conn.execute(text("SELECT to_regclass(:n) IS NOT NULL"), {"n": name}).scalar())
def test_fresh_install_then_current(db_settings: Settings) -> None:
engine = db.get_engine()
first = run_upgrade(db_settings, engine)
assert first.action == "installed"
assert first.backup_file is None
assert _table_exists("app_setting") and _table_exists("job_state")
second = run_upgrade(db_settings, engine)
assert second.action == "current"
def test_upgrade_makes_backup_and_failed_upgrade_changes_nothing(
db_settings: Settings, tmp_path: Path
) -> None:
engine = db.get_engine()
run_upgrade(db_settings, engine)
ok_dir = _script_dir(tmp_path / "a", MIGRATION_OK)
result = run_upgrade(db_settings, engine, ok_dir)
assert result.action == "upgraded"
assert result.backup_file is not None and result.backup_file.is_file()
assert "pre-upgrade" in result.backup_file.name
broken_dir = _script_dir(tmp_path / "b", MIGRATION_OK, MIGRATION_BROKEN)
with pytest.raises(UpgradeError, match="zurückgerollt"):
run_upgrade(db_settings, engine, broken_dir)
assert not _table_exists("test_half")
with engine.connect() as conn:
assert current_revision(conn) == "9001_test_ok"
columns = conn.execute(
text(
"SELECT column_name FROM information_schema.columns "
"WHERE table_schema = 'surveybox' AND table_name = 'test_ok'"
)
).scalars().all()
assert "extra" not in columns
def test_refuses_newer_database(db_settings: Settings) -> None:
engine = db.get_engine()
run_upgrade(db_settings, engine)
with engine.begin() as conn:
conn.execute(text("UPDATE alembic_version SET version_num = '9999_from_the_future'"))
with pytest.raises(UpgradeError, match="nicht kennt"):
run_upgrade(db_settings, engine)
def test_refuses_foreign_tables(db_settings: Settings) -> None:
engine = db.get_engine()
with engine.begin() as conn:
conn.execute(text(f"CREATE SCHEMA {db.DB_SCHEMA}"))
conn.execute(text(f"CREATE TABLE {db.DB_SCHEMA}.fremd (x int)"))
with pytest.raises(UpgradeError, match="keine Versionsangabe"):
run_upgrade(db_settings, engine)
def test_waits_for_migration_lock(db_settings: Settings) -> None:
engine = db.get_engine()
impatient = db_settings.model_copy(update={"migration_lock_timeout": 1})
with engine.connect() as holder:
holder.execute(text("SELECT pg_advisory_lock(:k)"), {"k": MIGRATION_LOCK_KEY})
with pytest.raises(UpgradeError, match="Migrationssperre"):
run_upgrade(impatient, engine)
holder.execute(text("SELECT pg_advisory_unlock(:k)"), {"k": MIGRATION_LOCK_KEY})
assert run_upgrade(db_settings, engine).action == "installed"
def test_migrations_match_models(db_settings: Settings) -> None:
"""Die Migrationen erzeugen genau das Schema, das die Modelle beschreiben."""
from alembic.autogenerate import compare_metadata
from alembic.migration import MigrationContext
from surveybox.models import Base
engine = db.get_engine()
run_upgrade(db_settings, engine)
with engine.connect() as conn:
context = MigrationContext.configure(
conn,
opts={
"include_schemas": False,
"compare_type": True,
"compare_server_default": False,
},
)
diff = compare_metadata(context, Base.metadata)
assert diff == [], diff
+82
View File
@@ -0,0 +1,82 @@
# SPDX-License-Identifier: AGPL-3.0-or-later
from __future__ import annotations
import pytest
pytest.importorskip("fastapi")
pytest.importorskip("httpx")
from fastapi.testclient import TestClient
from surveybox import db
from surveybox.settings import Settings
from surveybox.upgrade import run_upgrade
from surveybox.web.routes.pages import safe_next
@pytest.mark.parametrize(
("value", "expected"),
[
(None, "/"),
("", "/"),
("/", "/"),
("/forms/1?x=2", "/forms/1?x=2"),
("https://evil.example", "/"),
("//evil.example", "/"),
("/\\evil.example", "/"),
("/ok\r\nSet-Cookie: x=1", "/"),
("relative", "/"),
],
)
def test_safe_next(value: str | None, expected: str) -> None:
assert safe_next(value) == expected
@pytest.fixture
def client(db_settings: Settings) -> TestClient:
run_upgrade(db_settings, db.get_engine())
from surveybox.web.app import create_app
return TestClient(create_app())
@pytest.mark.db
def test_health(client: TestClient) -> None:
assert client.get("/health/live").json() == {"status": "ok"}
ready = client.get("/health/ready")
assert ready.status_code == 200
assert ready.headers["cache-control"] == "no-store"
@pytest.mark.db
@pytest.mark.parametrize(
("accept", "text"),
[
("de-DE,de;q=0.9", "Formulare und Abstimmungen, selbst gehostet."),
("fr", "Formulaires et sondages, auto-hébergés."),
("en-GB", "Forms and polls, self-hosted."),
],
)
def test_index_in_three_languages(client: TestClient, accept: str, text: str) -> None:
resp = client.get("/", headers={"Accept-Language": accept})
assert resp.status_code == 200
assert text in resp.text
assert "http://testserver" not in resp.text # nur relative Links
@pytest.mark.db
def test_language_cookie_and_safe_redirect(client: TestClient) -> None:
resp = client.get("/language/fr?next=//evil.example", follow_redirects=False)
assert resp.status_code == 303
assert resp.headers["location"] == "/"
assert "surveybox_lang=fr" in resp.headers["set-cookie"]
assert "httponly" in resp.headers["set-cookie"].lower()
page = client.get("/", headers={"Accept-Language": "de"})
assert "Formulaires et sondages, auto-hébergés." in page.text
@pytest.mark.db
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
+73
View File
@@ -0,0 +1,73 @@
# SPDX-License-Identifier: AGPL-3.0-or-later
"""XLSX-Schreiber: gültiges Paket, Texte ohne Formeln, Bild auf dem Info-Blatt."""
from __future__ import annotations
import io
import zipfile
from decimal import Decimal
from xml.etree import ElementTree
import pytest
from surveybox.forms import xlsx
PNG = (b"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00\x00\x01\x08\x06\x00\x00"
b"\x00\x1f\x15\xc4\x89\x00\x00\x00\rIDATx\x9cc\xf8\x0f\x00\x00\x01\x01\x00\x05\x18\xd8"
b"\xa9\x00\x00\x00\x00IEND\xaeB`\x82")
def book() -> bytes:
return xlsx.workbook([
xlsx.Sheet("Antworten", [["Nr.", "Name", "Zahl"], [1, "Anna <&> \x01", "=1+1"],
[2, None, Decimal("3.5")]], header=True, widths=[6, 20, 10]),
xlsx.Sheet("Info: [x]", [["Formular", "Fest"]], image=xlsx.Image(PNG, 48, 48),
first_row=5),
])
def test_package_is_well_formed() -> None:
with zipfile.ZipFile(io.BytesIO(book())) as z:
names = set(z.namelist())
assert {"[Content_Types].xml", "xl/workbook.xml", "xl/worksheets/sheet1.xml",
"xl/drawings/drawing2.xml", "xl/media/image2.png"} <= names
for name in names:
if name.endswith((".xml", ".rels")):
ElementTree.fromstring(z.read(name)) # noqa: S314 (selbst erzeugt)
sheet = z.read("xl/worksheets/sheet1.xml").decode()
assert "<f>" not in sheet and "=1+1" in sheet # Text, keine Formel
assert "\x01" not in sheet and "Anna &lt;&amp;&gt;" in sheet
assert 'ySplit="1"' in sheet and '<autoFilter ref="A1:C3"/>' in sheet
assert 'name="Info x"' in z.read("xl/workbook.xml").decode() # : [ ] ersetzt
def test_column_names() -> None:
assert [xlsx.column_name(i) for i in (0, 25, 26, 701, 702)] == ["A", "Z", "AA", "ZZ", "AAA"]
def test_readable_by_openpyxl() -> None:
openpyxl = pytest.importorskip("openpyxl")
wb = openpyxl.load_workbook(io.BytesIO(book()))
first = wb.worksheets[0]
assert [c.value for c in first[2]] == [1, "Anna <&> ", "=1+1"]
assert first.freeze_panes == "A2"
def test_page_setup_and_print_titles() -> None:
page = xlsx.PageSetup(landscape=True, margins=(1.0, 1.0, 2.0, 1.2), fit_width=True,
footer="&CSeite &P von &N")
data = xlsx.workbook([xlsx.Sheet("Antworten", [["Titel"], [], ["Nr.", "Name"], [1, "Anna"]],
header=True, header_row=2, freeze=False, page=page)])
with zipfile.ZipFile(io.BytesIO(data)) as z:
sheet = z.read("xl/worksheets/sheet1.xml").decode()
book_xml = z.read("xl/workbook.xml").decode()
styles = z.read("xl/styles.xml").decode()
assert 'orientation="landscape"' in sheet
assert 'fitToWidth="1"' in sheet and 'fitToHeight="0"' in sheet
assert '<pageSetUpPr fitToPage="1"/>' in sheet
assert 'top="0.7874' in sheet and 'left="0.3937' in sheet
assert "Seite &amp;P von &amp;N" in sheet
assert '<autoFilter ref="A3:B4"/>' in sheet and "ySplit" not in sheet
assert "_xlnm.Print_Titles" in book_xml and "$3:$3" in book_xml
assert "_xlnm._FilterDatabase" in book_xml
assert "FFCCCCCC" in styles