aboutsummaryrefslogtreecommitdiff
path: root/webmentions_ssg/auth.py
blob: 633aa820938c7bbe3a53aed0442ed48039b04730 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
# SPDX-FileCopyrightText: 2026 Dennis Fink <me+coding@dennisfink.me>
#
# SPDX-License-Identifier: BSD-3-Clause

"""Configure user authentication and session loading."""

import hashlib
import secrets
from hmac import compare_digest
from urllib.parse import urlsplit

from flask import request
from flask_limiter.util import get_remote_address
from flask_login import LoginManager

from .extensions import DATABASE as db
from .models import User

AUTH = LoginManager()

AUTH.login_view = "root.login"  # pyright: ignore[reportAttributeAccessIssue]

MIN_PASSWORD_LENGTH = 8

DUMMY_USER = User(username=secrets.token_urlsafe())
DUMMY_USER.password = secrets.token_urlsafe()


def validate_password(password: str) -> None:
    """Validate newly chosen passwords without arbitrary composition rules.

    Allow Unicode, whitespace-only passwords, and arbitrarily long passphrases,
    but reject empty passwords and control characters.
    """
    if not password:
        raise ValueError("Password must not be empty.")
    if len(password) < MIN_PASSWORD_LENGTH:
        raise ValueError(
            f"Password must be at least {MIN_PASSWORD_LENGTH} characters long."
        )
    if any(ord(char) < 32 or ord(char) == 127 for char in password):
        raise ValueError("Password must not contain control characters.")


@AUTH.user_loader
def load_user(session_id: str) -> User | None:
    """
    Load a user from the database by identifier.

    :param session_id: Database ID and password-hash fingerprint stored in the session.
    :return: Matching user, or ``None`` if no user exists with the identifier.
    """
    try:
        user_id, fingerprint = session_id.split(":", 1)
        if (
            not user_id.isascii()
            or not user_id.isdecimal()
            or len(user_id) > 19
            or len(fingerprint) != 64
            or any(char not in "0123456789abcdef" for char in fingerprint)
        ):
            return None
        user = db.session.get(User, int(user_id))
    except AttributeError, TypeError, ValueError:
        return None

    if user is None:
        return None

    if not compare_digest(session_id, user.get_id()):
        return None
    return user


def login_username_limit_key() -> str:
    """Group usernames across IPs without exposing plaintext to rate-limit storage."""
    username = request.form.get("username", "").strip().casefold()
    if not username:
        return f"missing-username:{get_remote_address()}"
    digest = hashlib.sha256(username.encode("utf-8")).hexdigest()
    return f"username:{digest}"


def is_safe_next_url(next_url: str) -> bool:
    """Allow redirects only to paths on this site."""
    if "\\" in next_url or not next_url.startswith("/") or next_url.startswith("//"):
        return False
    try:
        target = urlsplit(next_url)
    except ValueError:
        return False
    return (
        not target.scheme
        and not target.netloc
        and target.path.startswith("/")
        and not target.path.startswith("//")
    )