Docs restructure, code review, gatherer reliability, JWT key fail-closed
Documentation - Three levels: DOCS/General (overview, configuration), DOCS/Deployment (choose a method, first steps), details per method in Containers/ and System_Services/; new root README and DOCS/README map. - Remove superseded pages (Deployment.md, Deployment_Docker/Native.md, Index.md); split the two scenario guides by section. - Isolate the Timeweb/Hysteria2 records in DEPLOYMENTS/timeweb-hysteria2/ (not linked from DOCS, listed in .graphifyignore). - Add DOCS/code_review/ with a time-stamped analysis of the code base. Gatherer (BUG-02, BUG-03) - Session key (CN, address, connected_since_ts), baseline from the active_sessions snapshot, grace period for sessions missing from the status. - Status file integrity (TITLE/TIME/END) and freshness; a torn read skips the tick. - Cache applied after commit; main loop survives exceptions, backs off, and stops cleanly on SIGTERM/SIGINT; new client rows start with the first frame's totals; five tests. JWT signing key (SEC-01) - No built-in default: Core and Profiler refuse to start with a missing, placeholder or short (< 32) key; shipped config.ini has an empty value. - Same rule in install.sh, update.sh (issues a new key when missing or weak), docker lib/entrypoint; five tests, conftest.py for the test key. Each change has a plan and a summary under DOCS/Changes/. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
f95a0b63e6
commit
ad6995bb63
85 files changed
+2805
-1280
No files matched your search
@@ -19,6 +19,9 @@ python3 -m venv venv
|
||||
source venv/bin/activate
|
||||
pip install -r requirements.txt
|
||||
|
||||
# JWT key (required, no built-in default; at least 32 characters). Must be the same value as for APP_CORE
|
||||
export OVPMON_API_SECRET_KEY=$(openssl rand -hex 32)
|
||||
|
||||
# Run
|
||||
python3 main.py
|
||||
# Swagger UI available at http://localhost:8000/docs
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
[api]
|
||||
# Secret key for JWT token verification.
|
||||
# MUST match the key in APP_CORE/config.ini if not overridden by ENV.
|
||||
secret_key = ovpmon-secret-change-me
|
||||
# Secret key for JWT token verification.
|
||||
# MUST match the key of APP_CORE (same OVPMON_API_SECRET_KEY or the same value in its config.ini).
|
||||
# Set OVPMON_API_SECRET_KEY or this value; at least 32 characters, random (openssl rand -hex 32). There is no built-in default.
|
||||
secret_key =
|
||||
|
||||
[profiler]
|
||||
# Path to the profiler database relative to component root
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
import os
|
||||
|
||||
# utils.auth refuses to import without a strong JWT key (no built-in default), and tests import
|
||||
# main: give them a throwaway key before anything is imported. A real key in the environment is
|
||||
# left untouched.
|
||||
os.environ.setdefault("OVPMON_API_SECRET_KEY", "x" * 64)
|
||||
@@ -0,0 +1,45 @@
|
||||
import importlib
|
||||
import sys
|
||||
|
||||
import pytest
|
||||
|
||||
from utils.secret_key import resolve_secret_key, SecretKeyError
|
||||
|
||||
GOOD = "0123456789abcdef" * 4 # 64 hex characters
|
||||
|
||||
|
||||
def test_weak_or_missing_key_is_refused():
|
||||
for bad in (None, "", " ", "ovpmon-secret-change-me", "Change-Me-Please", "k" * 31):
|
||||
with pytest.raises(SecretKeyError) as exc:
|
||||
resolve_secret_key(bad, None)
|
||||
assert "openssl rand -hex 32" in str(exc.value)
|
||||
if bad and bad.strip():
|
||||
assert bad not in str(exc.value) # the key value is never part of the message
|
||||
# the same checks apply to the config.ini value
|
||||
with pytest.raises(SecretKeyError):
|
||||
resolve_secret_key(None, "ovpmon-secret-change-me")
|
||||
# legacy variable name is called out explicitly
|
||||
with pytest.raises(SecretKeyError) as exc:
|
||||
resolve_secret_key(None, "", legacy_env=GOOD)
|
||||
assert "OVPMON_SECRET_KEY" in str(exc.value) and "OVPMON_API_SECRET_KEY" in str(exc.value)
|
||||
assert GOOD not in str(exc.value)
|
||||
|
||||
|
||||
def test_good_key_and_priority():
|
||||
assert resolve_secret_key(GOOD, None) == (GOOD, "environment")
|
||||
assert resolve_secret_key(None, GOOD) == (GOOD, "config.ini")
|
||||
# environment wins over config.ini, even when the config.ini value is the old default
|
||||
assert resolve_secret_key(GOOD, "ovpmon-secret-change-me") == (GOOD, "environment")
|
||||
|
||||
|
||||
def test_auth_import_fails_closed(monkeypatch):
|
||||
# Fresh import each time; the original module is restored in sys.modules after the test
|
||||
monkeypatch.delitem(sys.modules, "utils.auth", raising=False)
|
||||
monkeypatch.setenv("OVPMON_API_SECRET_KEY", "ovpmon-secret-change-me")
|
||||
with pytest.raises(SystemExit) as exc:
|
||||
importlib.import_module("utils.auth")
|
||||
assert exc.value.code == 1
|
||||
|
||||
monkeypatch.delitem(sys.modules, "utils.auth", raising=False)
|
||||
monkeypatch.setenv("OVPMON_API_SECRET_KEY", GOOD)
|
||||
assert importlib.import_module("utils.auth").SECRET_KEY == GOOD
|
||||
+18
-16
@@ -1,29 +1,31 @@
|
||||
import jwt
|
||||
import configparser
|
||||
import logging
|
||||
import os
|
||||
from fastapi import Header, HTTPException, status
|
||||
from pathlib import Path
|
||||
|
||||
from .config import get_config_value
|
||||
from .secret_key import resolve_secret_key, SecretKeyError
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def get_secret_key():
|
||||
# Use consistent OVPMON_API_SECRET_KEY as primary source
|
||||
key = get_config_value('api', 'secret_key', fallback='ovpmon-secret-change-me')
|
||||
|
||||
if key == 'ovpmon-secret-change-me':
|
||||
print("[AUTH] WARNING: Using default fallback SECRET_KEY")
|
||||
else:
|
||||
# Check if it was from env (get_config_value prioritizes env)
|
||||
import os
|
||||
if os.getenv('OVPMON_API_SECRET_KEY'):
|
||||
print("[AUTH] Using SECRET_KEY from OVPMON_API_SECRET_KEY environment variable")
|
||||
elif os.getenv('OVPMON_SECRET_KEY'):
|
||||
print("[AUTH] Using SECRET_KEY from OVPMON_SECRET_KEY environment variable")
|
||||
else:
|
||||
print("[AUTH] SECRET_KEY loaded (config.ini or fallback)")
|
||||
|
||||
"""JWT signing key: OVPMON_API_SECRET_KEY, else [api] secret_key of config.ini. No built-in default."""
|
||||
try:
|
||||
# get_config_value returns the environment value first, then the config.ini value
|
||||
key, source = resolve_secret_key(
|
||||
os.getenv('OVPMON_API_SECRET_KEY'),
|
||||
get_config_value('api', 'secret_key'),
|
||||
os.getenv('OVPMON_SECRET_KEY'))
|
||||
except SecretKeyError as e:
|
||||
logger.critical(f"Refusing to start: {e}")
|
||||
raise SystemExit(1)
|
||||
logger.info(f"JWT secret key loaded from {source}")
|
||||
return key
|
||||
|
||||
|
||||
# Fails the import (and so the uvicorn start, exit code 1) when the key is missing or weak
|
||||
SECRET_KEY = get_secret_key()
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
"""JWT signing key rule (fail closed). Identical copy lives in APP_CORE/secret_key.py."""
|
||||
|
||||
ENV_NAME = "OVPMON_API_SECRET_KEY"
|
||||
LEGACY_ENV_NAME = "OVPMON_SECRET_KEY"
|
||||
DEFAULT_KEY = "ovpmon-secret-change-me"
|
||||
MIN_LENGTH = 32
|
||||
|
||||
HOW_TO_FIX = f"Generate one with: openssl rand -hex 32, and set it in {ENV_NAME} (or [api] secret_key in config.ini)."
|
||||
|
||||
|
||||
class SecretKeyError(Exception):
|
||||
"""The signing key is missing or weak. The message never contains the key value."""
|
||||
|
||||
|
||||
def resolve_secret_key(env, ini_value, legacy_env=None):
|
||||
"""Return (key, source) where source is "environment" or "config.ini".
|
||||
|
||||
env: value of OVPMON_API_SECRET_KEY (or None); ini_value: [api] secret_key (or None);
|
||||
legacy_env: value of OVPMON_SECRET_KEY (not used by the application, only for the hint).
|
||||
Priority: environment > config.ini. Raises SecretKeyError; does not log or exit.
|
||||
"""
|
||||
if env is not None:
|
||||
key, source = env, f"environment variable {ENV_NAME}"
|
||||
result_source = "environment"
|
||||
else:
|
||||
key, source = ini_value, "[api] secret_key in config.ini"
|
||||
result_source = "config.ini"
|
||||
|
||||
if key is None or not key.strip():
|
||||
msg = f"JWT secret key is not set (checked {ENV_NAME} and [api] secret_key in config.ini)."
|
||||
if legacy_env is not None and legacy_env.strip():
|
||||
msg += (f" {LEGACY_ENV_NAME} is set but is not used by the application: "
|
||||
f"rename it to {ENV_NAME}.")
|
||||
raise SecretKeyError(f"{msg} {HOW_TO_FIX}")
|
||||
|
||||
lowered = key.strip().lower()
|
||||
if lowered == DEFAULT_KEY or "change-me" in lowered or "changeme" in lowered:
|
||||
raise SecretKeyError(f"JWT secret key from {source} is a placeholder/default value. {HOW_TO_FIX}")
|
||||
if len(key) < MIN_LENGTH:
|
||||
raise SecretKeyError(f"JWT secret key from {source} is too short "
|
||||
f"({len(key)} characters, at least {MIN_LENGTH} required). {HOW_TO_FIX}")
|
||||
return key, result_source
|
||||
Reference in new issue
Block a user