diff options
| author | Dennis Fink | 2026-10-31 16:42:44 +0100 |
|---|---|---|
| committer | Dennis Fink | 2026-10-31 16:42:44 +0100 |
| commit | 3494eab1208dc18478485e02c61e292556502fa6 (patch) | |
| tree | 5d9e95d709b119a0245d0294837f9b6a7e38bff1 | |
| parent | fdb1762715658eae987dd104a0e6d3cb92a4a8d7 (diff) | |
| download | webmentions-ssg-3494eab1208dc18478485e02c61e292556502fa6.tar.gz webmentions-ssg-3494eab1208dc18478485e02c61e292556502fa6.zip | |
fix(core): harden session and credential security
Require persistent non-placeholder signing keys outside local
development and bind login sessions to the current password hash so
password changes revoke existing cookies.
Enforce a minimal password policy for user administration while
preserving long Unicode passphrases without arbitrary composition
limits.
Diffstat (limited to '')
| -rw-r--r-- | contrib/webmentions-ssg.example.cfg | 4 | ||||
| -rw-r--r-- | tests/cli/test_users.py | 110 | ||||
| -rw-r--r-- | tests/test_auth.py | 67 | ||||
| -rw-r--r-- | tests/test_config.py | 88 | ||||
| -rw-r--r-- | tests/test_models.py | 16 | ||||
| -rw-r--r-- | tests/test_views.py | 8 | ||||
| -rw-r--r-- | webmentions_ssg/__init__.py | 11 | ||||
| -rw-r--r-- | webmentions_ssg/auth.py | 27 | ||||
| -rw-r--r-- | webmentions_ssg/cli/users.py | 15 | ||||
| -rw-r--r-- | webmentions_ssg/config.py | 6 | ||||
| -rw-r--r-- | webmentions_ssg/models.py | 11 | ||||
| -rw-r--r-- | webmentions_ssg/security.py | 51 |
12 files changed, 382 insertions, 32 deletions
diff --git a/contrib/webmentions-ssg.example.cfg b/contrib/webmentions-ssg.example.cfg index 22fcf72..2b7b115 100644 --- a/contrib/webmentions-ssg.example.cfg +++ b/contrib/webmentions-ssg.example.cfg @@ -20,6 +20,10 @@ BOOTSTRAP_SERVE_LOCAL = True # Generate a persistent random key, e.g.: # python -c 'import secrets; print(secrets.token_urlsafe(32))' # Never commit your real key or SMTP password to version control. +# Production refuses to start without a real, persistent key (>=32 random bytes); +# set the same SECRET_KEY in the web process and every worker. +# Changing this key invalidates all existing signed login sessions. +# Upgrading to password-bound sessions also requires users to sign in again once. SECRET_KEY = "REPLACE_WITH_A_LONG_RANDOM_SECRET" # --------------------------------------------------------------------------- diff --git a/tests/cli/test_users.py b/tests/cli/test_users.py index 6538b27..4764c85 100644 --- a/tests/cli/test_users.py +++ b/tests/cli/test_users.py @@ -35,22 +35,23 @@ def test_users_cli_help_lists_management_commands(app: Flask) -> None: def test_users_cli_create_with_prompts_hashes_password(app: Flask) -> None: result = app.test_cli_runner().invoke( - args=["users", "create"], input="alice\nnew-secret\nnew-secret\n" + args=["users", "create"], + input="alice\nmy new secret passphrase\nmy new secret passphrase\n", ) assert result.exit_code == 0, result.output assert "Created user 'alice'." in result.output - assert "new-secret" not in result.output + assert "my new secret passphrase" not in result.output user = _get_user(app, "alice") assert user is not None - assert user.check_password("new-secret") - assert user.password_hash != "new-secret" + assert user.check_password("my new secret passphrase") + assert user.password_hash != "my new secret passphrase" def test_users_cli_create_with_username_option(app: Flask) -> None: result = app.test_cli_runner().invoke( args=["users", "create", "--username", "alice"], - input="new-secret\nnew-secret\n", + input="my new secret passphrase\nmy new secret passphrase\n", ) assert result.exit_code == 0, result.output @@ -61,7 +62,14 @@ def test_users_cli_create_rejects_duplicate(app: Flask) -> None: _add_user(app, "alice") result = app.test_cli_runner().invoke( - args=["users", "create", "--username", "alice", "--password", "other"] + args=[ + "users", + "create", + "--username", + "alice", + "--password", + "a stronger duplicate password", + ] ) assert result.exit_code != 0 @@ -74,7 +82,14 @@ def test_users_cli_create_rejects_duplicate(app: Flask) -> None: @pytest.mark.parametrize("username", ["", " "]) def test_users_cli_create_rejects_invalid_username(app: Flask, username: str) -> None: result = app.test_cli_runner().invoke( - args=["users", "create", "--username", username, "--password", "valid"] + args=[ + "users", + "create", + "--username", + username, + "--password", + "a strong password for testing", + ] ) assert result.exit_code != 0 @@ -117,22 +132,29 @@ def test_users_cli_set_password_updates_hash(app: Flask) -> None: old_hash = _get_user(app, "alice").password_hash # type: ignore[union-attr] result = app.test_cli_runner().invoke( - args=["users", "set-password", "alice"], input="replacement\nreplacement\n" + args=["users", "set-password", "alice"], + input="a long replacement passphrase\na long replacement passphrase\n", ) assert result.exit_code == 0, result.output assert "Updated password for user 'alice'." in result.output - assert "replacement" not in result.output + assert "a long replacement passphrase" not in result.output user = _get_user(app, "alice") assert user is not None assert user.password_hash != old_hash assert not user.check_password("original") - assert user.check_password("replacement") + assert user.check_password("a long replacement passphrase") def test_users_cli_set_password_missing_user(app: Flask) -> None: result = app.test_cli_runner().invoke( - args=["users", "set-password", "missing", "--password", "replacement"] + args=[ + "users", + "set-password", + "missing", + "--password", + "a long replacement passphrase", + ] ) assert result.exit_code != 0 @@ -208,13 +230,19 @@ def test_users_cli_can_manage_legacy_whitespace_username(app: Flask) -> None: _add_user(app, " alice ") reset = app.test_cli_runner().invoke( - args=["users", "set-password", " alice ", "--password", "replacement"] + args=[ + "users", + "set-password", + " alice ", + "--password", + "a long replacement passphrase", + ] ) assert reset.exit_code == 0, reset.output user = _get_user(app, " alice ") assert user is not None - assert user.check_password("replacement") + assert user.check_password("a long replacement passphrase") deleted = app.test_cli_runner().invoke(args=["users", "delete", " alice ", "--yes"]) assert deleted.exit_code == 0, deleted.output @@ -230,9 +258,63 @@ def test_users_cli_create_rolls_back_on_duplicate_race(app: Flask) -> None: patch.object(DATABASE.session, "rollback") as rollback, ): result = app.test_cli_runner().invoke( - args=["users", "create", "--username", "alice", "--password", "secret"] + args=[ + "users", + "create", + "--username", + "alice", + "--password", + "a long secret for testing", + ] ) rollback.assert_called_once() assert result.exit_code != 0 assert "User 'alice' already exists." in result.output + + +@pytest.mark.parametrize( + ("password", "error"), + [ + ("short", "at least 8 characters"), + ("good passphrase with\tab", "control characters"), + ], +) +@pytest.mark.parametrize("operation", ["create", "set-password"]) +def test_users_cli_enforces_password_policy( + app: Flask, password: str, error: str, operation: str +) -> None: + _add_user(app, "existing") + if operation == "create": + command = ["users", "create", "--username", "new"] + else: + command = ["users", "set-password", "existing"] + + result = app.test_cli_runner().invoke(args=[*command, "--password", password]) + assert result.exit_code != 0 + assert error in result.output + assert _get_user(app, "new") is None + existing = _get_user(app, "existing") + assert existing is not None and existing.check_password("original") + + +def test_users_cli_accepts_long_unicode_passphrase(app: Flask) -> None: + passphrase = "🦊 several words of my passphrase 🪁" + result = app.test_cli_runner().invoke( + args=["users", "create", "--username", "alice", "--password", passphrase] + ) + assert result.exit_code == 0, result.output + user = _get_user(app, "alice") + assert user is not None and user.check_password(passphrase) + + +@pytest.mark.parametrize("passphrase", ["12345678", " " * 8, "🦊" + "a" * 1025]) +def test_users_cli_accepts_minimum_whitespace_and_unbounded_passwords( + app: Flask, passphrase: str +) -> None: + result = app.test_cli_runner().invoke( + args=["users", "create", "--username", "alice", "--password", passphrase] + ) + assert result.exit_code == 0, result.output + user = _get_user(app, "alice") + assert user is not None and user.check_password(passphrase) diff --git a/tests/test_auth.py b/tests/test_auth.py index e0416b0..a6117b2 100644 --- a/tests/test_auth.py +++ b/tests/test_auth.py @@ -20,9 +20,72 @@ def test_load_user_returns_matching_user(app: Flask) -> None: user = User(username="account", password="secret") db.session.add(user) db.session.commit() - assert load_user(user.id) is user + assert load_user(user.get_id()) is user def test_load_user_returns_none_for_unknown_id(app: Flask) -> None: with app.app_context(): - assert load_user(99_999) is None + assert load_user("99999:" + "a" * 64) is None + + +def test_load_user_rejects_legacy_and_malformed_sessions(app: Flask) -> None: + with app.app_context(): + user = User(username="account", password="secret") + db.session.add(user) + db.session.commit() + + for identifier in ( + str(user.id), # Old ID-only sessions must not bypass revocation. + "", + "not-an-id:" + "a" * 64, + f"{user.id}:invalid", + f"{user.id}:" + "é" * 64, + f"{user.id}:" + "z" * 64, + f"{user.id}:" + "0" * 64, + f"{user.id}:" + "0" * 64 + ":trailing", + "-1:" + "0" * 64, + ): + assert load_user(identifier) is None + + +def test_password_change_invalidates_existing_session(app: Flask) -> None: + old_password = "a long original passphrase" + new_password = "a different long passphrase" + + with app.app_context(): + user = User(username="account", password=old_password) + db.session.add(user) + db.session.commit() + old_identifier = user.get_id() + + client = app.test_client() + response = client.post( + "/login", data={"username": "account", "password": old_password} + ) + assert response.status_code == 302 + assert client.get("/received").status_code == 200 + + with client.session_transaction() as session: + assert session["_user_id"] == old_identifier + + result = app.test_cli_runner().invoke( + args=["users", "set-password", "account", "--password", new_password] + ) + assert result.exit_code == 0, result.output + + with app.app_context(): + user = db.session.get(User, int(old_identifier.split(":", 1)[0])) + assert user is not None + assert user.get_id() != old_identifier + assert load_user(old_identifier) is None + assert load_user(user.get_id()) is user + + # A pre-existing, validly signed cookie no longer authenticates. + assert client.get("/received").status_code == 302 + + # Logging in with the newly chosen password still works. + response = client.post( + "/login", data={"username": "account", "password": new_password} + ) + assert response.status_code == 302 + assert client.get("/received").status_code == 200 diff --git a/tests/test_config.py b/tests/test_config.py index 1b45946..dd02c01 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -10,7 +10,7 @@ import pytest from wtforms import Field, ValidationError from wtforms.form import BaseForm -from webmentions_ssg import create_app +from webmentions_ssg import LIMITER, create_app from webmentions_ssg.config import ( DefaultConfig, DevelopmentConfig, @@ -126,7 +126,10 @@ def test_invalid_allowed_hostnames_fail_at_startup( def test_production_requires_nonempty_allowed_hostnames(tmp_path: Path) -> None: config_path = tmp_path / "production.cfg" - config_path.write_text('RATELIMIT_STORAGE_URI = "redis://localhost:6379"\n') + config_path.write_text( + 'RATELIMIT_STORAGE_URI = "redis://localhost:6379"\n' + 'SECRET_KEY = "the-production-secret-key-for-this-test"\n' + ) class EmptyHostnamesConfig(ProductionConfig): CONFIG_FILE = str(config_path) @@ -148,3 +151,84 @@ def test_environment_allowed_hostnames_override_config_file( app = create_app(LocalDevelopmentConfig) assert app.config["ALLOWED_HOSTNAMES"] == {"second.example"} + + +@pytest.mark.parametrize( + ("secret", "expected_exception"), + [ + (None, TypeError), + ("", RuntimeError), + ("short", RuntimeError), + ("REPLACE_WITH_A_LONG_RANDOM_SECRET", RuntimeError), + ("INSECURE_DEVELOPMENT_ONLY_SECRET_KEY", RuntimeError), + ("change_me_to_a_new_strong_secret_key", RuntimeError), + (123, TypeError), + ], +) +def test_production_refuses_missing_weak_or_example_secret_key( + tmp_path: Path, secret: object, expected_exception: type[Exception] +) -> None: + config_file = tmp_path / "production.cfg" + config_file.write_text("# This file intentionally has no signing key.\n") + + class SecretKeyConfig(ProductionConfig): + CONFIG_FILE = str(config_file) + LOG_FILE = str(tmp_path / "production.log") + ALLOWED_HOSTNAMES = {"example.com"} + RATELIMIT_STORAGE_URI = "redis://localhost:6379" + SECRET_KEY = secret + + with pytest.raises(expected_exception, match="SECRET_KEY"): + create_app(SecretKeyConfig) + + +def test_production_uses_persistent_configured_secret( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + # The test concerns secret-key persistence, not Redis initialization. + monkeypatch.setattr(LIMITER, "init_app", lambda app: None) + config_file = tmp_path / "production.cfg" + key = "a-fixed-key-with-32-plus-random-characters" + config_file.write_text(f"SECRET_KEY = {key!r}\n") + + class ConfiguredProduction(ProductionConfig): + CONFIG_FILE = str(config_file) + LOG_FILE = str(tmp_path / "production.log") + ALLOWED_HOSTNAMES = {"example.com"} + RATELIMIT_STORAGE_URI = "redis://localhost:6379" + + first = create_app(ConfiguredProduction) + second = create_app(ConfiguredProduction) + assert first.secret_key == key == second.secret_key + + +def test_production_accepts_environment_secret_override( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + config_file = tmp_path / "production.cfg" + config_file.write_text('SECRET_KEY = "REPLACE_WITH_A_LONG_RANDOM_SECRET"\n') + key = "another-long-persistent-secret-for-a-deployment" + monkeypatch.setenv("WEBMENTIONS_SSG_SECRET_KEY", key) + # Avoid requiring the optional Redis dependency for this configuration test. + monkeypatch.setattr(LIMITER, "init_app", lambda app: None) + + class EnvConfiguredProduction(ProductionConfig): + CONFIG_FILE = str(config_file) + LOG_FILE = str(tmp_path / "production.log") + ALLOWED_HOSTNAMES = {"example.com"} + RATELIMIT_STORAGE_URI = "redis://localhost:6379" + + app = create_app(EnvConfiguredProduction) + assert app.secret_key == key + + +def test_development_rejects_placeholder_even_with_debug(tmp_path: Path) -> None: + config_file = tmp_path / "development.cfg" + config_file.write_text('SECRET_KEY = "REPLACE_WITH_A_LONG_RANDOM_SECRET"\n') + + class LocalDevelopment(DevelopmentConfig): + CONFIG_FILE = str(config_file) + LOG_FILE = str(tmp_path / "development.log") + + with pytest.raises(RuntimeError, match="SECRET_KEY"): + create_app(LocalDevelopment) diff --git a/tests/test_models.py b/tests/test_models.py index 2fa2cb8..392b246 100644 --- a/tests/test_models.py +++ b/tests/test_models.py @@ -146,3 +146,19 @@ def test_source_repr() -> None: def test_sent_webmention_repr() -> None: webmention = SentWebmention(target="https://example.com/post", desired_revision=1) assert repr(webmention) == "<SentWebmention 'https://example.com/post'>" + + +def test_user_session_id_changes_when_password_hash_changes() -> None: + user = User(username="admin", password="a strong passphrase", id=42) + original_hash = user.password_hash + original_id = user.get_id() + + assert original_id.startswith("42:") + assert original_hash not in original_id + assert len(original_id.split(":", 1)[1]) == 64 + + # Even a reset to the same password rehashes with a new salt, revoking + # any old session token. + user.password = "a strong passphrase" + assert user.password_hash != original_hash + assert user.get_id() != original_id diff --git a/tests/test_views.py b/tests/test_views.py index fb12b8b..21a33bf 100644 --- a/tests/test_views.py +++ b/tests/test_views.py @@ -60,7 +60,7 @@ def log_in(app: Flask, client: FlaskClient) -> None: db.session.add(user) db.session.commit() - user_id = user.id + user_id = user.get_id() with client.session_transaction() as session: session["_user_id"] = str(user_id) @@ -422,7 +422,7 @@ def test_login_redirects_to_local_next_page( user = User(username="admin", password="test") db.session.add(user) db.session.commit() - user_id = user.id + user_id = user.get_id() mock_login_form(views_module, monkeypatch, valid=True) @@ -463,7 +463,7 @@ def test_login_rejects_unsafe_next_page( user = User(username="admin", password="test") db.session.add(user) db.session.commit() - user_id = user.id + user_id = user.get_id() mock_login_form(views_module, monkeypatch, valid=True) @@ -1173,7 +1173,7 @@ def test_admin_only_links_safe_existing_status_urls( user = User(username="admin", password="test") db.session.add(user) db.session.commit() - user_id = user.id + user_id = user.get_id() with client.session_transaction() as session: session["_user_id"] = str(user_id) 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.") |
