aboutsummaryrefslogtreecommitdiff
path: root/webmentions_ssg
diff options
context:
space:
mode:
Diffstat (limited to '')
-rw-r--r--webmentions_ssg/__init__.py11
-rw-r--r--webmentions_ssg/auth.py27
-rw-r--r--webmentions_ssg/cli/users.py15
-rw-r--r--webmentions_ssg/config.py6
-rw-r--r--webmentions_ssg/models.py11
-rw-r--r--webmentions_ssg/security.py51
6 files changed, 111 insertions, 10 deletions
diff --git a/webmentions_ssg/__init__.py b/webmentions_ssg/__init__.py
index 518add0..51635ef 100644
--- a/webmentions_ssg/__init__.py
+++ b/webmentions_ssg/__init__.py
@@ -27,6 +27,7 @@ from webmentions_ssg.config import (
normalize_allowed_hostnames,
)
+from .security import validate_secret_key
from .tasks import Huey
from .url_security import is_http_url
@@ -82,6 +83,16 @@ def create_app(config_class: type[DefaultConfig] | None = None) -> Flask:
app.config.from_prefixed_env(prefix="FLASK")
app.config.from_prefixed_env(prefix="WEBMENTIONS_SSG")
+ # A fixed key is convenient only for local debugging. All other
+ # deployments must supply their own persistent, random signing key.
+ using_local_dev_key = (
+ issubclass(config_class, DevelopmentConfig)
+ and app.debug
+ and app.config.get("SECRET_KEY") == DevelopmentConfig.SECRET_KEY
+ )
+ if not app.testing and not using_local_dev_key:
+ validate_secret_key(app.config.get("SECRET_KEY"))
+
app.config["ALLOWED_HOSTNAMES"] = normalize_allowed_hostnames(
app.config["ALLOWED_HOSTNAMES"]
)
diff --git a/webmentions_ssg/auth.py b/webmentions_ssg/auth.py
index 48a95b7..147220e 100644
--- a/webmentions_ssg/auth.py
+++ b/webmentions_ssg/auth.py
@@ -4,6 +4,8 @@
"""Configure user authentication and session loading."""
+from hmac import compare_digest
+
from flask_login import LoginManager
from . import DATABASE as db
@@ -15,11 +17,30 @@ AUTH.login_view = "root.login" # pyright: ignore[reportAttributeAccessIssue]
@AUTH.user_loader
-def load_user(id: int) -> User | None:
+def load_user(session_id: str) -> User | None:
"""
Load a user from the database by identifier.
- :param id: User identifier stored in the login session.
+ :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.
"""
- return db.session.get(User, int(id))
+ 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
diff --git a/webmentions_ssg/cli/users.py b/webmentions_ssg/cli/users.py
index 7c6afde..a48fc71 100644
--- a/webmentions_ssg/cli/users.py
+++ b/webmentions_ssg/cli/users.py
@@ -10,6 +10,7 @@ from flask.cli import AppGroup
from sqlalchemy.exc import IntegrityError
from .. import DATABASE
+from ..security import validate_password
USERS_CLI = AppGroup("users", help="Manage users.")
@@ -41,8 +42,10 @@ def create_user(username: str, password: str) -> None:
if not username:
raise click.ClickException("Username must not be empty.")
- if not password:
- raise click.ClickException("Password must not be empty.")
+ try:
+ validate_password(password)
+ except ValueError as exc:
+ raise click.ClickException(str(exc)) from exc
if DATABASE.session.scalar(sa.select(User).where(User.username == username)):
raise click.ClickException(f"User {username!r} already exists.")
@@ -81,10 +84,12 @@ def set_user_password(username: str, password: str) -> None:
:param username: Username of the account to update.
:param password: New plain-text password to hash and store.
- :raises click.ClickException: If the account is missing or the password is empty.
+ :raises click.ClickException: If the account is missing or the password is invalid.
"""
- if not password:
- raise click.ClickException("Password must not be empty.")
+ try:
+ validate_password(password)
+ except ValueError as exc:
+ raise click.ClickException(str(exc)) from exc
user = _require_user(username)
user.password = password
diff --git a/webmentions_ssg/config.py b/webmentions_ssg/config.py
index 1c7d44e..28cea64 100644
--- a/webmentions_ssg/config.py
+++ b/webmentions_ssg/config.py
@@ -5,7 +5,6 @@
"""Define application settings for production, development, and testing."""
import logging
-import secrets
def normalize_allowed_hostnames(value: object) -> set[str]:
@@ -26,7 +25,8 @@ def normalize_allowed_hostnames(value: object) -> set[str]:
class DefaultConfig:
TESTING = False
DEBUG = False
- SECRET_KEY = secrets.token_urlsafe()
+ # Production must provide a persistent, random key through configuration.
+ SECRET_KEY = None
BOOTSTRAP_SERVE_LOCAL = True
# BOOTSTRAP_BOOTSWATCH_THEME = "Materia"
# Secure by default; deployment configuration can override these values.
@@ -82,6 +82,8 @@ class DefaultConfig:
class DevelopmentConfig(DefaultConfig):
DEBUG = True
+ # Only for local debug use; production rejects this as an insecure value.
+ SECRET_KEY = "INSECURE_DEVELOPMENT_ONLY_SECRET_KEY"
SESSION_COOKIE_SECURE = False
LOG_FILE = "testing/webmentions-ssg.log"
LOG_LEVEL = logging.DEBUG
diff --git a/webmentions_ssg/models.py b/webmentions_ssg/models.py
index 58f95bc..7cab879 100644
--- a/webmentions_ssg/models.py
+++ b/webmentions_ssg/models.py
@@ -9,6 +9,7 @@ from __future__ import annotations
import uuid
from datetime import UTC, datetime
from enum import StrEnum
+from hashlib import sha256
from typing import Never
from flask_login import UserMixin
@@ -77,6 +78,16 @@ class User(UserMixin, Base):
"""
self.password_hash = generate_password_hash(password)
+ def get_id(self) -> str:
+ """Bind the login session to the current stored password hash.
+
+ Only a one-way fingerprint is placed in Flask's signed cookie, never
+ the password hash itself. Rehashing the password invalidates all
+ previously issued session identifiers without a schema change.
+ """
+ fingerprint = sha256(self.password_hash.encode("utf-8")).hexdigest()
+ return f"{self.id}:{fingerprint}"
+
def check_password(self, password: str) -> bool:
"""
Check a plain-text password against the stored password hash.
diff --git a/webmentions_ssg/security.py b/webmentions_ssg/security.py
new file mode 100644
index 0000000..f4841a4
--- /dev/null
+++ b/webmentions_ssg/security.py
@@ -0,0 +1,51 @@
+# SPDX-FileCopyrightText: 2026 Dennis Fink <me+coding@dennisfink.me>
+#
+# SPDX-License-Identifier: BSD-3-Clause
+
+"""Validate persistent signing keys and administrator passwords."""
+
+MIN_PASSWORD_LENGTH = 8
+MIN_SECRET_KEY_LENGTH = 32
+
+
+def validate_secret_key(value: object) -> None:
+ """Require a non-placeholder, sufficiently long deployment signing key."""
+ if not isinstance(value, (str, bytes)):
+ raise TypeError(
+ "Configure a persistent SECRET_KEY of at least 32 random bytes "
+ "before starting."
+ )
+
+ # Flask accepts either text or bytes as its signing key. Reject common
+ # example/development values even when their lengths look sufficient.
+ key = value.encode("utf-8") if isinstance(value, str) else value
+ if len(key) < MIN_SECRET_KEY_LENGTH or not key.strip():
+ raise RuntimeError(
+ "Configure a persistent SECRET_KEY of at least 32 random bytes "
+ "before starting."
+ )
+
+ normalized = key.strip().lower()
+ if normalized.startswith(
+ (b"replace_with", b"changeme", b"change_me", b"your_", b"insecure_")
+ ):
+ raise RuntimeError(
+ "SECRET_KEY is an example/development placeholder; "
+ "generate and configure a real random key."
+ )
+
+
+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.")