Files
surveybox/tests/test_mail_units.py
T
marco.morath 94466378c7
CI / audit (push) Skipped
CI / checks (push) Successful in 4m13s
CI / image (push) Successful in 1m16s
fix:Umfrageergebnisse und Archivierung
2026-11-26 15:19:43 +01:00

274 lines
13 KiB
Python

# 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,
"votes": [{"text": "1. Juli <b>", "vote": "yes", "confirmed": True,
"counts": {"yes": 3, "maybe": 1, "no": 0}},
{"text": "8. Juli", "vote": "", "confirmed": False,
"counts": None}],
"show_counts": True, "maybe": True,
"feed": "https://umfrage.example/calendar/abc.ics"},
"proposed": {"options": [{"id": "b", "date": "2026-07-02", "time": "18:30",
"duration": None, "label": "", "proposed": True}],
"link": "https://umfrage.example/f/t"},
"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"},
"invitation": {"link": "https://umfrage.example/i/abc.def", "closes": "1. Juli 2026, 18:00",
"invited_guest": True,
"stop_link": "https://umfrage.example/mail/invitation/abc.def"},
"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