diff --git a/members_map/admin.py b/members_map/admin.py index d4e35ca..99ea3d5 100644 --- a/members_map/admin.py +++ b/members_map/admin.py @@ -59,8 +59,8 @@ def pins(): @bp.post("/pins/") def update_pin(pin_id: int): - location = request.form.get("location", "").strip() - nickname = forms.clean_nickname(request.form.get("nickname")) + location = forms.clean_text(request.form.get("location")) + nickname = forms.clean_text(request.form.get("nickname")) or None error = forms.validation_error(location, nickname) if not location: error = "Location can't be empty." diff --git a/members_map/checks.py b/members_map/checks.py index ca35f84..c6e4361 100644 --- a/members_map/checks.py +++ b/members_map/checks.py @@ -1,4 +1,3 @@ -import re import time from collections.abc import Iterable @@ -6,16 +5,13 @@ from flask import Flask from flask.cli import with_appcontext -from members_map import db, geo +from members_map import db, forms, geo NOT_IN_COUNTRY = "not in a country" DUPLICATE = "duplicate" LINK = "contains a link" FLAGS = (NOT_IN_COUNTRY, DUPLICATE, LINK) -LINK_PATTERN = re.compile( - r"https?://|www\.|\.(com|net|org|io|ru|xyz|info|biz)\b", re.IGNORECASE -) # Nominatim allows at most one request per second NOMINATIM_DELAY = 1.1 @@ -37,7 +33,7 @@ def flag_pins(pins: Iterable[db.Pin]) -> dict[int, list[str]]: if key in seen: reasons.append(DUPLICATE) seen.add(key) - if LINK_PATTERN.search(f"{pin.location} {pin.nickname or ''}"): + if forms.LINK_PATTERN.search(f"{pin.location} {pin.nickname or ''}"): reasons.append(LINK) if reasons: flags[pin.id] = reasons diff --git a/members_map/forms.py b/members_map/forms.py index a127ead..3e62211 100644 --- a/members_map/forms.py +++ b/members_map/forms.py @@ -1,5 +1,7 @@ import hmac +import re import secrets +import unicodedata from flask import abort, request, session @@ -7,18 +9,62 @@ MAX_NICKNAME_LENGTH = 50 -def clean_nickname(raw: str | None) -> str | None: - return (raw or "").strip() or None +LINK_PATTERN = re.compile( + r"https?://|www\.|\.(com|net|org|io|ru|xyz|info|biz)\b", re.IGNORECASE +) +EMAIL_PATTERN = re.compile(r"\S+@\S+\.\w{2,}") +# Stacked accents ("Zalgo text"). Real scripts rarely need more than three +# combining marks on one letter. +MAX_COMBINING_RUN = 3 +ZERO_WIDTH_JOINER = "\u200d" # Keeps emoji like 👩‍💻 in one piece -def validation_error(location: str, nickname: str | None) -> str | None: - if len(location) > MAX_LOCATION_LENGTH: - return "That location is too long." - if nickname and len(nickname) > MAX_NICKNAME_LENGTH: - return f"Nicknames can be at most {MAX_NICKNAME_LENGTH} characters." +def clean_text(raw: str | None) -> str: + """Normalize Unicode, drop invisible characters, collapse whitespace.""" + text = unicodedata.normalize("NFKC", raw or "") + text = "".join( + ch + for ch in text + if ch == ZERO_WIDTH_JOINER + or ch.isspace() + or not unicodedata.category(ch).startswith("C") + ) + return " ".join(text.split()) + + +def _too_many_combining_marks(text: str) -> bool: + run = 0 + for ch in text: + run = run + 1 if unicodedata.category(ch).startswith("M") else 0 + if run > MAX_COMBINING_RUN: + return True + return False + + +def _text_error(text: str, field: str, max_length: int) -> str | None: + if len(text) > max_length: + return f"{field} can be at most {max_length} characters." + if EMAIL_PATTERN.search(text): + return ( + f"{field} can't contain an email address, because the map is " + "public." + ) + if LINK_PATTERN.search(text): + return f"{field} can't contain links." + if _too_many_combining_marks(text): + return f"{field} has too many stacked accent marks." + if text and not any(ch.isalnum() for ch in text): + return f"{field} needs at least one letter or number." return None +def validation_error(location: str, nickname: str | None) -> str | None: + """Expects text that already went through clean_text.""" + return _text_error( + location, "Location", MAX_LOCATION_LENGTH + ) or _text_error(nickname or "", "Nickname", MAX_NICKNAME_LENGTH) + + def csrf_token() -> str: if "csrf" not in session: session["csrf"] = secrets.token_urlsafe(32) diff --git a/members_map/views.py b/members_map/views.py index 43292ac..3d6fe2a 100644 --- a/members_map/views.py +++ b/members_map/views.py @@ -67,8 +67,8 @@ def add_location(): flash("Your location was added to the map.", "success") return redirect(url_for("map.index")) - location = request.form.get("location", "").strip() - nickname = forms.clean_nickname(request.form.get("nickname")) + location = forms.clean_text(request.form.get("location")) + nickname = forms.clean_text(request.form.get("nickname")) or None if error := forms.validation_error(location, nickname): flash(error, "error") diff --git a/tests/test_forms.py b/tests/test_forms.py new file mode 100644 index 0000000..4af7ec2 --- /dev/null +++ b/tests/test_forms.py @@ -0,0 +1,57 @@ +import pytest + +from members_map.forms import clean_text, validation_error + + +@pytest.mark.parametrize( + ("raw", "expected"), + [ + (None, ""), + (" Vancouver,\t\n Canada ", "Vancouver, Canada"), + ("Dan", "Dan"), # fullwidth letters + ("Da​n", "Dan"), # zero-width space + ("‮evil", "evil"), # right-to-left override + ("bell\x07", "bell"), + ("Zoë", "Zoë"), + ("José", "José"), # decomposed e + accent becomes one character + ("👩‍💻 coder", "👩‍💻 coder"), + ("北京, 中国", "北京, 中国"), + ], +) +def test_clean_text(raw, expected): + assert clean_text(raw) == expected + + +@pytest.mark.parametrize( + "nickname", + [None, "Ada", "Zoë", "李雷", "Đặng Thị", "👩‍💻 Ada", "@ada_codes"], +) +def test_reasonable_nicknames_are_accepted(nickname): + assert validation_error("Berlin, Germany", nickname) is None + + +@pytest.mark.parametrize( + ("nickname", "message"), + [ + ("n" * 51, "at most 50 characters"), + ("http://spam.example", "can't contain links"), + ("www.spam.example", "can't contain links"), + ("buy-pills.com", "can't contain links"), + ("me@example.org", "email address"), + ("Z͓͔͑͒a", "stacked accent marks"), + ("!!!***", "at least one letter or number"), + ("🔥🔥🔥", "at least one letter or number"), + ], +) +def test_bad_nicknames_are_rejected(nickname, message): + error = validation_error("Berlin, Germany", nickname) + + assert error is not None + assert error.startswith("Nickname") + assert message in error + + +def test_bad_locations_are_rejected(): + assert "Location can't contain links" in validation_error( + "visit https://spam.example", None + ) diff --git a/tests/test_views.py b/tests/test_views.py index 8a76fc4..28002a7 100644 --- a/tests/test_views.py +++ b/tests/test_views.py @@ -141,7 +141,9 @@ def test_geocoder_down(app, client, geocode): ("data", "message"), [ ({"location": ""}, "Please enter a city and country"), - ({"location": "x" * 201}, "That location is too long"), + ({"location": "x" * 201}, "Location can be at most 200"), + ({"location": "Oslo", "nickname": "see www.spam.example"}, "links"), + ({"location": "Oslo", "nickname": "a@b.example"}, "email address"), ({"location": "Oslo", "nickname": "n" * 51}, "at most 50"), ], )