Speakr is a personal, self-hosted web application designed for transcribing audio recordings
Python
Refuse the insecure default SECRET_KEY and auto-generate/persist a strong per-deployment key when unset, preventing session and password-reset-token forgery
Murtaza Nasirb3b7ad0237f8
diff --git a/src/app.py b/src/app.pyindex fc79cd4c..4211ccf3 100644--- a/src/app.py+++ b/src/app.py@@ -371,8 +371,40 @@ if 'sqlite' in app.config['SQLALCHEMY_DATABASE_URI']:'pool_pre_ping': True # Verify connections before use}# MAX_CONTENT_LENGTH will be set dynamically after database initialization-# Set a secret key for session management and CSRF protection-app.config['SECRET_KEY'] = os.environ.get('SECRET_KEY', 'default-dev-key-change-in-production')+# Set a secret key for session management and CSRF protection.++# The old code fell back to a hardcoded constant when SECRET_KEY was unset.+# That key signs the session cookie AND itsdangerous password-reset tokens,+# so a publicly-known value lets anyone forge a session cookie for any+# user_id (instant admin takeover) and mint valid reset tokens. resolve_secret_key+# refuses the known-bad default and, when nothing is configured, auto-generates+# a strong per-deployment key and persists it — so a self-hoster who never sets+# the env var is secure by default instead of silently exploitable. (The key+# only signs sessions/tokens; it does not encrypt stored data, so a lost key+# means a one-time re-login, never data loss.)+from src.utils.security import resolve_secret_key as _resolve_secret_key++try:+ _secret_key, _secret_key_action = _resolve_secret_key(+ os.environ.get('SECRET_KEY'),+ app.config['SQLALCHEMY_DATABASE_URI'],+ key_file=os.environ.get('SECRET_KEY_FILE') or None,+ )+except ValueError as _sk_exc:+ raise RuntimeError(str(_sk_exc))+app.config['SECRET_KEY'] = _secret_key+if _secret_key_action == 'generated':+ app.logger.warning(+ "SECRET_KEY was not set; generated a strong random key and persisted "+ "it under the instance directory. It is included in a normal data-volume "+ "backup; set SECRET_KEY explicitly for multi-host or key-rotation setups."+ )+elif _secret_key_action == 'ephemeral':+ app.logger.error(+ "SECRET_KEY not set and an auto-generated key could not be persisted. "+ "Using an ephemeral key: sessions will not survive a restart. Set "+ "SECRET_KEY to fix this."+ )# Apply ProxyFix to handle headers from a reverse proxy (like Nginx or Caddy)# This is crucial for request.is_secure to work correctly behind an SSL-terminating proxy.diff --git a/src/utils/security.py b/src/utils/security.pyindex 573b05e7..cb1acecb 100644--- a/src/utils/security.py+++ b/src/utils/security.py@@ -4,11 +4,92 @@ Security utilities for password validation and other security functions.This module provides security-related utility functions for the application."""+import osimport re+import secretsfrom wtforms.validators import ValidationErrorfrom urllib.parse import urlparse+# The value the app historically fell back to when SECRET_KEY was unset. It is+# a public constant in the source, so it must never be accepted at runtime.+INSECURE_SECRET_KEY = 'default-dev-key-change-in-production'+++def resolve_secret_key(env_key, db_uri, key_file=None,+ instance_dir_fallback='/data/instance',+ token_factory=None):+ """Resolve a Flask SECRET_KEY without any Flask/logging dependency.++ This key signs the session cookie and the itsdangerous email/password-reset+ tokens, so a known value allows session and reset-token forgery. Resolution:++ 1. A real ``env_key`` (not the insecure default) is used as-is.+ 2. The insecure built-in default is refused (raises ``ValueError``).+ 3. Otherwise a strong key is generated once and persisted next to the+ instance data (``key_file``, or ``<instance_dir>/secret_key``) so it is+ stable across restarts and captured by a normal data-volume backup.++ Returns ``(key, action)`` with action in+ {'env', 'persisted', 'generated', 'ephemeral'}. Pure and unit-testable;+ ``token_factory`` defaults to a 256-bit hex token and is injectable.+ """+ if token_factory is None:+ token_factory = lambda: secrets.token_hex(32)++ env_key = (env_key or '').strip()+ if env_key and env_key != INSECURE_SECRET_KEY:+ return env_key, 'env'+ if env_key == INSECURE_SECRET_KEY:+ raise ValueError(+ "SECRET_KEY is set to the insecure built-in default "+ f"('{INSECURE_SECRET_KEY}'). This key signs session cookies and "+ "password-reset tokens; a known value lets anyone forge an admin "+ "session. Set SECRET_KEY to a strong random value, e.g. "+ "`python -c \"import secrets; print(secrets.token_hex(32))\"`."+ )++ if not key_file:+ if db_uri and db_uri.startswith('sqlite'):+ db_path = db_uri.split('sqlite:///', 1)[-1]+ instance_dir = os.path.dirname(db_path) or '.'+ else:+ instance_dir = instance_dir_fallback+ key_file = os.path.join(instance_dir, 'secret_key')++ # Reuse a previously-persisted key if present.+ try:+ with open(key_file, 'r') as fh:+ existing = fh.read().strip()+ if existing:+ return existing, 'persisted'+ except OSError:+ pass++ new_key = token_factory()+ try:+ os.makedirs(os.path.dirname(key_file) or '.', exist_ok=True)+ # O_EXCL so concurrent workers don't clobber each other.+ fd = os.open(key_file, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)+ try:+ os.write(fd, new_key.encode())+ finally:+ os.close(fd)+ return new_key, 'generated'+ except FileExistsError:+ # Lost the create race to another worker — use the key it wrote.+ try:+ with open(key_file, 'r') as fh:+ persisted = fh.read().strip()+ if persisted:+ return persisted, 'persisted'+ except OSError:+ pass+ return new_key, 'ephemeral'+ except OSError:+ return new_key, 'ephemeral'++def password_check(form, field):"""Custom WTForms validator for password strength.diff --git a/tests/test_secret_key_resolution.py b/tests/test_secret_key_resolution.pynew file mode 100644index 00000000..ac015809--- /dev/null+++ b/tests/test_secret_key_resolution.py@@ -0,0 +1,88 @@+"""Unit tests for SECRET_KEY resolution (security hardening).++The app used to fall back to a hardcoded constant when SECRET_KEY was unset.+That constant signs session cookies and password-reset tokens, so a known+value lets anyone forge an admin session. resolve_secret_key refuses the+default, uses a real env key as-is, and otherwise generates+persists a strong+per-deployment key.+"""++import os+import sys+import tempfile++import pytest++sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))++from src.utils.security import resolve_secret_key, INSECURE_SECRET_KEY+++def test_real_env_key_is_used_verbatim():+ key, action = resolve_secret_key('a-real-strong-key', 'sqlite:////tmp/x.db')+ assert key == 'a-real-strong-key'+ assert action == 'env'+++def test_insecure_default_is_refused():+ with pytest.raises(ValueError) as exc:+ resolve_secret_key(INSECURE_SECRET_KEY, 'sqlite:////tmp/x.db')+ assert 'insecure' in str(exc.value).lower()+++def test_unset_generates_and_persists_key(tmp_path):+ key_file = str(tmp_path / 'secret_key')+ key, action = resolve_secret_key('', 'sqlite:////ignored.db', key_file=key_file)+ assert action == 'generated'+ assert len(key) >= 32+ # Persisted with the exact value and owner-only permissions.+ assert os.path.exists(key_file)+ with open(key_file) as fh:+ assert fh.read().strip() == key+ assert (os.stat(key_file).st_mode & 0o777) == 0o600+++def test_second_call_reads_the_persisted_key(tmp_path):+ key_file = str(tmp_path / 'secret_key')+ first, a1 = resolve_secret_key(None, 'sqlite:///x.db', key_file=key_file)+ second, a2 = resolve_secret_key(None, 'sqlite:///x.db', key_file=key_file)+ assert a1 == 'generated'+ assert a2 == 'persisted'+ assert first == second # stable across restarts+++def test_none_env_var_is_treated_as_unset(tmp_path):+ key, action = resolve_secret_key(None, 'sqlite:///x.db',+ key_file=str(tmp_path / 'k'))+ assert action == 'generated'+ assert key+++def test_key_file_derived_from_sqlite_instance_dir(tmp_path):+ # No explicit key_file: it should land next to the sqlite database.+ db = tmp_path / 'instance' / 'transcriptions.db'+ db.parent.mkdir(parents=True)+ key, action = resolve_secret_key('', f'sqlite:////{db}')+ assert action == 'generated'+ assert (tmp_path / 'instance' / 'secret_key').exists()+++def test_ephemeral_when_persistence_fails(tmp_path):+ # key_file points into a path that cannot be created (a file as a dir).+ blocker = tmp_path / 'blocker'+ blocker.write_text('x')+ key, action = resolve_secret_key('', 'sqlite:///x.db',+ key_file=str(blocker / 'sub' / 'secret_key'))+ assert action == 'ephemeral'+ assert key # still returns a usable key, never the insecure default+ assert key != INSECURE_SECRET_KEY+++def test_generated_keys_are_unique():+ seen = set()+ for _ in range(5):+ with tempfile.TemporaryDirectory() as d:+ key, _ = resolve_secret_key('', 'sqlite:///x.db',+ key_file=os.path.join(d, 'k'))+ seen.add(key)+ assert len(seen) == 5