aboutsummaryrefslogtreecommitdiff
path: root/webmentions_ssg/auth.py
blob: ac1f4e792619ee9d29985c915e0f550a70032cca (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
98
99
100
101
102
103
104
105
106
107
108
109
110
# 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 functools import cache
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 werkzeug.security import generate_password_hash

from .extensions import db
from .models.user import User
from .validation import is_control_character

login_manager = LoginManager()

login_manager.login_view = "webmentions.login"  # pyright: ignore[reportAttributeAccessIssue]

MIN_PASSWORD_LENGTH = 8


@cache
def dummy_password_hash() -> str:
    """Lazily generate a reusable hash for unknown login usernames.

    The hash is calculated once and reused so missing accounts follow a comparable
    password-check path.

    :returns: Reusable password hash for timing-safe unknown-user authentication.
    """
    return generate_password_hash(secrets.token_urlsafe())


def validate_new_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.

    :param password: Proposed new password to validate.
    :raises ValueError: If the password is empty, too short, or contains 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(is_control_character(char) for char in password):
        raise ValueError("Password must not contain control characters.")


@login_manager.user_loader
def load_user_from_session_id(session_id: object) -> User | None:
    """Load a user from the database by identifier.

    :param session_id: Database ID and password-hash fingerprint stored in the session.
    :returns: Matching user, or ``None`` if no user exists with the identifier.
    """
    if not isinstance(session_id, str):
        return None

    user_id, _, _ = session_id.partition(":")
    if not (user_id.isascii() and user_id.isdecimal() and len(user_id) <= 19):
        return None

    user = db.session.get(User, int(user_id))
    if user is None or not compare_digest(session_id.encode(), user.get_id().encode()):
        return None
    return user


def login_username_rate_limit_key() -> str:
    """Group usernames across IPs without exposing plaintext to rate-limit storage.

    :returns: Hashed username rate-limit key, or an IP-specific key if no username was
              submitted.
    """
    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.

    :param next_url: Requested post-login redirect path.
    :returns: ``True`` if the redirect is a safe site-local path.
    """
    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.netloc
        and target.path.startswith("/")
        and not target.path.startswith("//")
    )