Files
romm/backend/utils/validation.py
Marcello Pichini ff31cf9428 fix(validation): reject email addresses ending in a newline (#5593)
* fix(validation): reject email addresses ending in a newline

* fix(validation): reject usernames ending in a newline

The username pattern had the same trailing-newline gap as the email one.
Both patterns now rely on fullmatch, so their anchors are dropped.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(user): use the renamed bearer helper

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Georges-Antoine Assi <contact@me.gantoine.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 21:57:31 -05:00

201 lines
6.1 KiB
Python

import re
from typing import Annotated, Final
from pydantic import AfterValidator, Field
from logger.logger import log
from models.user import TEXT_FIELD_LENGTH
class ValidationError(Exception):
"""Custom exception for validation errors."""
def __init__(self, message: str, field_name: str = "field"):
self.message = message
self.field_name = field_name
super().__init__(self.message)
# Pre-compiled regex patterns for better performance
USERNAME_PATTERN = re.compile(r"[a-zA-Z0-9_-]+")
EMAIL_PATTERN = re.compile(r"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}")
# Upper bound on a `rom_ids` request scope, so one request maps to a bounded
# query and response. Documented so clients can batch a large library.
MAX_ROM_IDS_PER_QUERY: Final = 500
def dedupe_in_order[T](items: list[T] | None) -> list[T] | None:
return None if items is None else list(dict.fromkeys(items))
# Shared by every route that scopes a query to a set of ROMs, so the cap and
# the per-ID rule are declared once and every route rejects a bad scope alike.
RomIdScope = Annotated[
list[Annotated[int, Field(gt=0)]] | None,
Field(max_length=MAX_ROM_IDS_PER_QUERY),
AfterValidator(dedupe_in_order),
]
def narrow_rom_id_scope(
rom_id: int | None, rom_ids: list[int] | None
) -> list[int] | None:
"""Fold a route's single-ROM `rom_id` filter into its `rom_ids` scope.
Both filters apply together, so the result is their intersection. `None`
means no ROM scope at all, while an empty list is an explicit empty one.
"""
if rom_id is None:
return rom_ids
if rom_ids is None:
return [rom_id]
return [rom_id] if rom_id in rom_ids else []
def parse_comma_separated_ids(value: str, field_name: str = "ID") -> list[int]:
"""Parse a comma-separated list of integer IDs from a query parameter.
Raises:
ValidationError: If any entry is not an integer.
"""
try:
return [int(part) for part in value.split(",") if part.strip()]
except ValueError as exc:
raise ValidationError(
f"Invalid {field_name} format. Must be comma-separated integers.",
field_name,
) from exc
def validate_ascii_only(value: str, field_name: str = "field") -> None:
"""Validate that a string contains only ASCII characters.
Args:
value (str): The value to validate
field_name (str): The name of the field for error messages
Raises:
ValidationError: If the value contains non-ASCII characters
"""
if not value:
return
# Check if any character is outside ASCII range (0-127)
if any(ord(char) > 127 for char in value):
msg = f"{field_name} must contain only ASCII characters"
log.error(f"Validation failed: {msg}")
raise ValidationError(msg, field_name)
def validate_username(username: str) -> None:
"""Validate username format and content.
Args:
username (str): The username to validate
Raises:
ValidationError: If the username is invalid
"""
if not username or not username.strip():
msg = "Username cannot be empty"
log.error(msg)
raise ValidationError(msg, "Username")
validate_ascii_only(username, "Username")
if len(username) < 3:
msg = "Username must be at least 3 characters long"
log.error(msg)
raise ValidationError(msg, "Username")
if len(username) > TEXT_FIELD_LENGTH:
msg = "Username must be no more than 255 characters long"
log.error(msg)
raise ValidationError(msg, "Username")
if not USERNAME_PATTERN.fullmatch(username):
msg = "Username can only contain letters, numbers, underscores, and hyphens"
log.error(f"Validation failed: {msg} for username: {username}")
raise ValidationError(msg, "Username")
def sanitize_username(username: str, fallback: str = "user") -> str:
"""Coerce an externally supplied username into one `validate_username` accepts.
An identity provider is free to hand out names RomM's own rules reject
(`first.last`, an email address, non-ASCII), and an account carrying one
can't be edited afterwards.
Args:
username (str): The username as the provider sent it
fallback (str): Stem to use when nothing usable survives
Returns:
str: A username that satisfies `validate_username`
"""
sanitized = re.sub(r"[^a-zA-Z0-9_-]+", "-", username).strip("-")[:TEXT_FIELD_LENGTH]
# Same floor as `validate_username`, and a bare "a-" style remnant is no
# more recognizable than the fallback.
if len(sanitized) < 3:
sanitized = re.sub(r"[^a-zA-Z0-9_-]+", "-", fallback).strip("-")[
:TEXT_FIELD_LENGTH
]
if len(sanitized) < 3:
sanitized = "user"
return sanitized
def validate_password(password: str) -> None:
"""Validate password format and content.
Args:
password (str): The password to validate
Raises:
ValidationError: If the password is invalid
"""
if not password or not password.strip():
msg = "Password cannot be empty"
log.error(msg)
raise ValidationError(msg, "Password")
validate_ascii_only(password, "Password")
if len(password) < 6:
msg = "Password must be at least 6 characters long"
log.error(msg)
raise ValidationError(msg, "Password")
if len(password) > TEXT_FIELD_LENGTH:
msg = "Password must be no more than 255 characters long"
log.error(msg)
raise ValidationError(msg, "Password")
def validate_email(email: str) -> None:
"""Validate email format and content.
Args:
email (str): The email to validate
Raises:
ValidationError: If the email is invalid
"""
if not email:
return
validate_ascii_only(email, "Email")
if len(email) > TEXT_FIELD_LENGTH:
msg = f"Email must be no more than {TEXT_FIELD_LENGTH} characters long"
log.error(msg)
raise ValidationError(msg, "Email")
if not EMAIL_PATTERN.fullmatch(email):
msg = "Invalid email format"
log.error(f"Validation failed: {msg} for email: {email}")
raise ValidationError(msg, "Email")