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>
85 lines
3.2 KiB
Python
85 lines
3.2 KiB
Python
import jwt
|
|
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():
|
|
"""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()
|
|
|
|
|
|
async def verify_token(authorization: str = Header(None)):
|
|
if not authorization or not authorization.startswith("Bearer "):
|
|
print(f"[AUTH] Missing or invalid Authorization header: {authorization[:20] if authorization else 'None'}")
|
|
raise HTTPException(
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
detail="Token is missing or invalid",
|
|
headers={"WWW-Authenticate": "Bearer"},
|
|
)
|
|
|
|
token = authorization.split(" ")[1]
|
|
|
|
try:
|
|
# Debug: Log a few chars of the key and token (safely)
|
|
# print(f"[AUTH] Decoding token with SECRET_KEY starting with: {SECRET_KEY[:3]}...")
|
|
|
|
payload = jwt.decode(token, SECRET_KEY, algorithms=["HS256"])
|
|
if payload.get("is_2fa_pending"):
|
|
raise HTTPException(
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
detail="2FA verification required",
|
|
headers={"WWW-Authenticate": "Bearer"},
|
|
)
|
|
return payload
|
|
except HTTPException:
|
|
raise
|
|
except Exception as e:
|
|
error_type = type(e).__name__
|
|
error_detail = str(e)
|
|
print(f"[AUTH] JWT Decode Failed. Type: {error_type}, Detail: {error_detail}")
|
|
|
|
# Handling exceptions dynamically to avoid AttributeError
|
|
if error_type == "ExpiredSignatureError":
|
|
raise HTTPException(
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
detail="Token has expired",
|
|
headers={"WWW-Authenticate": "Bearer"},
|
|
)
|
|
elif error_type in ["InvalidTokenError", "DecodeError"]:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
detail="Token is invalid",
|
|
headers={"WWW-Authenticate": "Bearer"},
|
|
)
|
|
else:
|
|
# Check if it's a TypeError (e.g. wrong arguments for decode)
|
|
if error_type == "TypeError":
|
|
print("[AUTH] Critical: jwt.decode failed with TypeError. This likely means 'jwt' package is installed instead of 'PyJWT'.")
|
|
|
|
raise HTTPException(
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
detail=f"Authentication error: {error_type}",
|
|
headers={"WWW-Authenticate": "Bearer"},
|
|
)
|