Skip to content

🛡️ Warracker is an open source, self-hostable warranty tracker to monitor expirations, store receipts, files. You own the data, your rules!

Security: persist the generated SECRET_KEY, fail closed without one, Secure session cookie on HTTPS (CFG-01c, CFG-02, CFG-03)

Omega (QA)2b3baec3cd5c
diff --git a/backend/config.py b/backend/config.py
index 220220a..27a35ab 100644
--- a/backend/config.py
+++ b/backend/config.py
@@ -6,22 +6,94 @@ from urllib.parse import unquote, urlparse
logger = logging.getLogger(__name__)
+def _secret_key_file_paths():
+ """Candidate locations for the persisted generated SECRET_KEY, best first.
+
+ The first path lives inside the uploads folder, the one directory the
+ shipped compose files and the Unraid template all mount as a volume,
+ so a generated key survives container recreation (CFG-02). The file
+ is a dotfile no warranty row references, and the file routes only
+ serve paths a warranty row references, so it is not downloadable.
+ The legacy bare `secret_key` file in the working directory stays as
+ a fallback so installs that already generated one keep using it.
+ SECRET_KEY_FILE overrides both locations.
+ """
+ override = os.environ.get('SECRET_KEY_FILE')
+ if override:
+ return [override]
+ upload_folder = os.environ.get('UPLOAD_FOLDER', '/data/uploads')
+ return [os.path.join(upload_folder, '.secret_key'), 'secret_key']
+
+
+def _migrate_secret_key_file(source, target):
+ """Copy a legacy key file to the persisted location, best effort.
+
+ Runs when the key was read from the legacy location and the
+ persisted location has no key yet, so the first start after an
+ upgrade keeps the existing key and future recreations keep it too.
+ """
+ if source == target or os.path.exists(target):
+ return
+ try:
+ with open(source, 'r') as f:
+ secret = f.read().strip()
+ if not secret:
+ return
+ parent = os.path.dirname(target)
+ if parent:
+ os.makedirs(parent, exist_ok=True)
+ with open(target, 'w') as f:
+ f.write(secret)
+ try:
+ os.chmod(target, 0o600)
+ except OSError:
+ pass
+ logger.info(f"Migrated SECRET_KEY file from {source} to {target}")
+ except OSError:
+ pass
+
+
def get_try_create_secret():
secret = os.environ.get('SECRET_KEY')
- if not secret:
- secret_file = 'secret_key'
- if os.path.exists(secret_file):
- secret = open(secret_file, 'r').read().strip()
- else:
+ if secret:
+ return secret
+ paths = _secret_key_file_paths()
+ for path in paths:
+ if os.path.exists(path):
try:
- import base64
- secret = base64.b64encode(os.urandom(32)).decode('ascii')
- with open(secret_file, 'w') as f:
- f.write(secret)
- logger.info(f"Generated new SECRET_KEY and saved to {secret_file}")
- except Exception:
- secret = 'your_default_secret_key_please_change_in_prod'
- return secret
+ with open(path, 'r') as f:
+ secret = f.read().strip()
+ if secret:
+ _migrate_secret_key_file(path, paths[0])
+ return secret
+ except OSError:
+ continue
+ # No usable key anywhere: generate one and persist it. If no key file
+ # location is writable, fail closed (CFG-03): there is no fallback to
+ # a known key, because a token forged with a public key would be
+ # accepted. The operator must set SECRET_KEY or fix the permissions.
+ import base64
+ secret = base64.b64encode(os.urandom(32)).decode('ascii')
+ for path in paths:
+ try:
+ parent = os.path.dirname(path)
+ if parent:
+ os.makedirs(parent, exist_ok=True)
+ with open(path, 'w') as f:
+ f.write(secret)
+ try:
+ os.chmod(path, 0o600)
+ except OSError:
+ pass
+ logger.info(f"Generated new SECRET_KEY and saved to {path}")
+ return secret
+ except OSError:
+ continue
+ raise RuntimeError(
+ "Could not persist a generated SECRET_KEY: none of the key file "
+ f"locations ({', '.join(paths)}) is writable. Set the SECRET_KEY "
+ "environment variable or make one of those locations writable."
+ )
class Config:
"""Base configuration class."""
@@ -30,12 +102,6 @@ class Config:
SECRET_KEY = get_try_create_secret()
JWT_EXPIRATION_DELTA = timedelta(hours=int(os.environ.get('JWT_EXPIRATION_HOURS', '24')))
- # Security Warning for Default Secret Key
- @staticmethod
- def _check_secret_key():
- if Config.SECRET_KEY == 'your_default_secret_key_please_change_in_prod':
- logger.warning("SECURITY WARNING: Using default SECRET_KEY. Please set a strong SECRET_KEY environment variable in production.")
-
# Database Configuration
DB_HOST = os.environ.get('DB_HOST', 'warrackerdb')
DB_NAME = os.environ.get('DB_NAME', 'warranty_db')
@@ -118,11 +184,31 @@ class Config:
"DB_ADMIN_PASSWORD in your environment or .env file."
)
+ @staticmethod
+ def _upgrade_session_cookie_secure(app):
+ """Emit the session cookie with Secure when the deployment serves HTTPS.
+
+ The default configuration is DevelopmentConfig, whose session
+ cookie has no Secure flag (CFG-01c). Flipping the default to the
+ production config would break plain-HTTP installs, whose browsers
+ would refuse to store a Secure cookie and break the OIDC login
+ flow state kept in the session. Instead, upgrade to Secure when
+ the deployment's own public URL uses https, which the operator
+ already configures for login redirects. This only ever adds the
+ flag, never removes a Secure setting the active config provides.
+ """
+ if app.config.get('SESSION_COOKIE_SECURE'):
+ return
+ base_url = os.environ.get('FRONTEND_URL') or os.environ.get('APP_BASE_URL') or ''
+ if urlparse(base_url).scheme == 'https':
+ app.config['SESSION_COOKIE_SECURE'] = True
+ logger.info("Session cookie Secure flag enabled (deployment URL uses https).")
+
@staticmethod
def init_app(app):
"""Initialize configuration-specific settings."""
Config._validate_db_vars(app)
- Config._check_secret_key()
+ Config._upgrade_session_cookie_secure(app)
if not os.path.exists(Config.UPLOAD_FOLDER):
try:
diff --git a/tests/test_secret_key_config.py b/tests/test_secret_key_config.py
new file mode 100644
index 0000000..65f90a7
--- /dev/null
+++ b/tests/test_secret_key_config.py
@@ -0,0 +1,135 @@
+"""SECRET_KEY generation, persistence, and fail-closed behavior.
+
+CFG-02: a generated key must survive container recreation, so it is
+persisted inside the uploads folder (the one directory every shipped
+topology mounts as a volume), with the legacy working-directory file
+kept as a fallback and migrated forward.
+
+CFG-03: when no key can be generated or persisted, startup must fail
+with a clear message. There is no fallback to a publicly known key.
+
+CFG-01c: the session cookie gains the Secure flag when the deployment
+serves HTTPS, without breaking plain-HTTP installs.
+"""
+import os
+
+import pytest
+from flask import Flask
+
+from backend.config import (
+ DevelopmentConfig,
+ ProductionConfig,
+ get_try_create_secret,
+)
+
+REPO_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+LITERAL_FALLBACK = "your_default_secret_key_please_change_in_prod"
+
+
+def test_env_secret_key_wins(monkeypatch, tmp_path):
+ monkeypatch.setenv("SECRET_KEY", "env-key-value")
+ monkeypatch.setenv("UPLOAD_FOLDER", str(tmp_path))
+ assert get_try_create_secret() == "env-key-value"
+ assert not os.path.exists(tmp_path / ".secret_key")
+
+
+def test_generated_key_persists_in_upload_folder(monkeypatch, tmp_path):
+ monkeypatch.delenv("SECRET_KEY", raising=False)
+ monkeypatch.delenv("SECRET_KEY_FILE", raising=False)
+ monkeypatch.setenv("UPLOAD_FOLDER", str(tmp_path))
+ monkeypatch.chdir(tmp_path)
+
+ secret = get_try_create_secret()
+ assert len(secret) == 44 # base64 of 32 random bytes
+
+ key_file = tmp_path / ".secret_key"
+ assert key_file.read_text() == secret
+ assert oct(os.stat(key_file).st_mode & 0o777) == "0o600"
+
+ # A second start reads the persisted key instead of minting a new one.
+ assert get_try_create_secret() == secret
+
+
+def test_legacy_key_file_is_read_and_migrated(monkeypatch, tmp_path):
+ workdir = tmp_path / "work"
+ uploads = tmp_path / "uploads"
+ workdir.mkdir()
+ uploads.mkdir()
+ (workdir / "secret_key").write_text("legacy-key-value")
+ monkeypatch.delenv("SECRET_KEY", raising=False)
+ monkeypatch.delenv("SECRET_KEY_FILE", raising=False)
+ monkeypatch.setenv("UPLOAD_FOLDER", str(uploads))
+ monkeypatch.chdir(workdir)
+
+ assert get_try_create_secret() == "legacy-key-value"
+ assert (uploads / ".secret_key").read_text() == "legacy-key-value"
+
+
+def test_secret_key_file_override(monkeypatch, tmp_path):
+ key_file = tmp_path / "custom" / "key.txt"
+ monkeypatch.delenv("SECRET_KEY", raising=False)
+ monkeypatch.setenv("SECRET_KEY_FILE", str(key_file))
+ monkeypatch.setenv("UPLOAD_FOLDER", str(tmp_path))
+ monkeypatch.chdir(tmp_path)
+
+ secret = get_try_create_secret()
+ assert key_file.read_text() == secret
+ assert get_try_create_secret() == secret
+
+
+def test_unwritable_key_locations_fail_closed(monkeypatch, tmp_path):
+ blocker = tmp_path / "blocker"
+ blocker.write_text("not a directory")
+ monkeypatch.delenv("SECRET_KEY", raising=False)
+ monkeypatch.setenv("SECRET_KEY_FILE", str(blocker / "key"))
+ monkeypatch.setenv("UPLOAD_FOLDER", str(tmp_path))
+ monkeypatch.chdir(tmp_path)
+
+ with pytest.raises(RuntimeError) as excinfo:
+ get_try_create_secret()
+ assert "SECRET_KEY" in str(excinfo.value)
+
+
+def test_no_literal_fallback_key_in_source():
+ with open(os.path.join(REPO_ROOT, "backend", "config.py")) as f:
+ assert LITERAL_FALLBACK not in f.read()
+
+
+def _app_with(config_class):
+ app = Flask(__name__)
+ app.config.from_object(config_class)
+ app.config["TESTING"] = True # skip DB validation for these tests
+ return app
+
+
+def test_session_cookie_secure_upgraded_for_https(monkeypatch):
+ monkeypatch.setenv("FRONTEND_URL", "https://warracker.example.com")
+ monkeypatch.delenv("APP_BASE_URL", raising=False)
+ app = _app_with(DevelopmentConfig)
+ assert app.config["SESSION_COOKIE_SECURE"] is False
+ DevelopmentConfig.init_app(app)
+ assert app.config["SESSION_COOKIE_SECURE"] is True
+
+
+def test_session_cookie_secure_stays_off_for_http(monkeypatch):
+ monkeypatch.setenv("FRONTEND_URL", "http://192.168.1.10:8005")
+ monkeypatch.delenv("APP_BASE_URL", raising=False)
+ app = _app_with(DevelopmentConfig)
+ DevelopmentConfig.init_app(app)
+ assert app.config["SESSION_COOKIE_SECURE"] is False
+
+
+def test_session_cookie_secure_uses_app_base_url(monkeypatch):
+ monkeypatch.delenv("FRONTEND_URL", raising=False)
+ monkeypatch.setenv("APP_BASE_URL", "https://warracker.example.com")
+ app = _app_with(DevelopmentConfig)
+ DevelopmentConfig.init_app(app)
+ assert app.config["SESSION_COOKIE_SECURE"] is True
+
+
+def test_production_config_never_downgraded(monkeypatch):
+ monkeypatch.setenv("FRONTEND_URL", "http://192.168.1.10:8005")
+ monkeypatch.delenv("APP_BASE_URL", raising=False)
+ app = _app_with(ProductionConfig)
+ ProductionConfig.init_app(app)
+ assert app.config["SESSION_COOKIE_SECURE"] is True