Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions members_map/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,8 +59,8 @@ def pins():

@bp.post("/pins/<int:pin_id>")
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."
Expand Down
8 changes: 2 additions & 6 deletions members_map/checks.py
Original file line number Diff line number Diff line change
@@ -1,21 +1,17 @@
import re
import time
from collections.abc import Iterable

import click
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
Expand All @@ -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
Expand Down
60 changes: 53 additions & 7 deletions members_map/forms.py
Original file line number Diff line number Diff line change
@@ -1,24 +1,70 @@
import hmac
import re
import secrets
import unicodedata

from flask import abort, request, session

MAX_LOCATION_LENGTH = 200
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)
Expand Down
4 changes: 2 additions & 2 deletions members_map/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down
57 changes: 57 additions & 0 deletions tests/test_forms.py
Original file line number Diff line number Diff line change
@@ -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
)
4 changes: 3 additions & 1 deletion tests/test_views.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"),
],
)
Expand Down
Loading