hardening
This commit is contained in:
@@ -8,10 +8,10 @@ class Settings(BaseSettings):
|
||||
app_name: str = "Magent"
|
||||
cors_allow_origin: str = "http://localhost:3000"
|
||||
sqlite_path: str = Field(default="data/magent.db", validation_alias=AliasChoices("SQLITE_PATH"))
|
||||
jwt_secret: str = Field(default="change-me", validation_alias=AliasChoices("JWT_SECRET"))
|
||||
jwt_secret: Optional[str] = Field(default=None, validation_alias=AliasChoices("JWT_SECRET"))
|
||||
jwt_exp_minutes: int = Field(default=720, validation_alias=AliasChoices("JWT_EXP_MINUTES"))
|
||||
admin_username: str = Field(default="admin", validation_alias=AliasChoices("ADMIN_USERNAME"))
|
||||
admin_password: str = Field(default="adminadmin", validation_alias=AliasChoices("ADMIN_PASSWORD"))
|
||||
admin_username: Optional[str] = Field(default=None, validation_alias=AliasChoices("ADMIN_USERNAME"))
|
||||
admin_password: Optional[str] = Field(default=None, validation_alias=AliasChoices("ADMIN_PASSWORD"))
|
||||
log_level: str = Field(default="INFO", validation_alias=AliasChoices("LOG_LEVEL"))
|
||||
log_file: str = Field(default="data/magent.log", validation_alias=AliasChoices("LOG_FILE"))
|
||||
requests_sync_ttl_minutes: int = Field(
|
||||
@@ -102,7 +102,7 @@ class Settings(BaseSettings):
|
||||
)
|
||||
|
||||
discord_webhook_url: Optional[str] = Field(
|
||||
default="https://discord.com/api/webhooks/1464141924775629033/O_rvCAmIKowR04tyAN54IuMPcQFEiT-ustU3udDaMTlF62PmoI6w4-52H3ZQcjgHQOgt",
|
||||
default=None,
|
||||
validation_alias=AliasChoices("DISCORD_WEBHOOK_URL"),
|
||||
)
|
||||
|
||||
|
||||
@@ -331,6 +331,8 @@ def verify_user_password(username: str, password: str) -> Optional[Dict[str, Any
|
||||
user = get_user_by_username(username)
|
||||
if not user:
|
||||
return None
|
||||
if user.get("auth_provider") != "local":
|
||||
return None
|
||||
if not verify_password(password, user["password_hash"]):
|
||||
return None
|
||||
return user
|
||||
|
||||
+43
-12
@@ -1,4 +1,5 @@
|
||||
import asyncio
|
||||
from contextlib import asynccontextmanager
|
||||
|
||||
from fastapi import FastAPI
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
@@ -22,7 +23,48 @@ from .services.jellyfin_sync import run_daily_jellyfin_sync
|
||||
from .logging_config import configure_logging
|
||||
from .runtime import get_runtime_settings
|
||||
|
||||
app = FastAPI(title=settings.app_name)
|
||||
|
||||
def validate_security_settings() -> None:
|
||||
issues = []
|
||||
jwt_secret = (settings.jwt_secret or "").strip()
|
||||
admin_username = (settings.admin_username or "").strip()
|
||||
admin_password = (settings.admin_password or "").strip()
|
||||
if not jwt_secret:
|
||||
issues.append("JWT_SECRET is required")
|
||||
if not admin_username:
|
||||
issues.append("ADMIN_USERNAME is required")
|
||||
if not admin_password:
|
||||
issues.append("ADMIN_PASSWORD is required")
|
||||
if jwt_secret == "change-me":
|
||||
issues.append("JWT_SECRET must not use the default placeholder")
|
||||
if admin_password == "adminadmin":
|
||||
issues.append("ADMIN_PASSWORD must not use the default placeholder")
|
||||
if issues:
|
||||
raise RuntimeError("Unsafe Magent security configuration: " + "; ".join(issues))
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(_: FastAPI):
|
||||
validate_security_settings()
|
||||
init_db()
|
||||
runtime = get_runtime_settings()
|
||||
configure_logging(runtime.log_level, runtime.log_file)
|
||||
background_tasks = [
|
||||
asyncio.create_task(run_daily_jellyfin_sync(), name="daily-jellyfin-sync"),
|
||||
asyncio.create_task(startup_warmup_requests_cache(), name="startup-warmup-requests-cache"),
|
||||
asyncio.create_task(run_requests_delta_loop(), name="requests-delta-loop"),
|
||||
asyncio.create_task(run_daily_requests_full_sync(), name="daily-requests-full-sync"),
|
||||
asyncio.create_task(run_daily_db_cleanup(), name="daily-db-cleanup"),
|
||||
]
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
for task in background_tasks:
|
||||
task.cancel()
|
||||
await asyncio.gather(*background_tasks, return_exceptions=True)
|
||||
|
||||
|
||||
app = FastAPI(title=settings.app_name, lifespan=lifespan)
|
||||
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
@@ -37,17 +79,6 @@ app.add_middleware(
|
||||
async def health() -> dict:
|
||||
return {"status": "ok"}
|
||||
|
||||
@app.on_event("startup")
|
||||
async def startup() -> None:
|
||||
init_db()
|
||||
runtime = get_runtime_settings()
|
||||
configure_logging(runtime.log_level, runtime.log_file)
|
||||
asyncio.create_task(run_daily_jellyfin_sync())
|
||||
asyncio.create_task(startup_warmup_requests_cache())
|
||||
asyncio.create_task(run_requests_delta_loop())
|
||||
asyncio.create_task(run_daily_requests_full_sync())
|
||||
asyncio.create_task(run_daily_db_cleanup())
|
||||
|
||||
|
||||
app.include_router(requests_router)
|
||||
app.include_router(auth_router)
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
from secrets import token_urlsafe
|
||||
|
||||
from fastapi import APIRouter, HTTPException, status, Depends
|
||||
from fastapi.security import OAuth2PasswordRequestForm
|
||||
|
||||
@@ -21,6 +23,12 @@ router = APIRouter(prefix="/auth", tags=["auth"])
|
||||
async def login(form_data: OAuth2PasswordRequestForm = Depends()) -> dict:
|
||||
user = verify_user_password(form_data.username, form_data.password)
|
||||
if not user:
|
||||
existing = get_user_by_username(form_data.username)
|
||||
if existing and existing.get("auth_provider") != "local":
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail=f"Use the {existing.get('auth_provider')} sign-in flow for this account",
|
||||
)
|
||||
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid credentials")
|
||||
if user.get("is_blocked"):
|
||||
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="User is blocked")
|
||||
@@ -45,10 +53,12 @@ async def jellyfin_login(form_data: OAuth2PasswordRequestForm = Depends()) -> di
|
||||
raise HTTPException(status_code=status.HTTP_502_BAD_GATEWAY, detail=str(exc)) from exc
|
||||
if not isinstance(response, dict) or not response.get("User"):
|
||||
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid Jellyfin credentials")
|
||||
create_user_if_missing(form_data.username, "jellyfin-user", role="user", auth_provider="jellyfin")
|
||||
create_user_if_missing(form_data.username, token_urlsafe(32), role="user", auth_provider="jellyfin")
|
||||
user = get_user_by_username(form_data.username)
|
||||
if user and user.get("is_blocked"):
|
||||
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="User is blocked")
|
||||
if user and user.get("auth_provider") == "jellyfin":
|
||||
set_user_password(form_data.username, token_urlsafe(32))
|
||||
try:
|
||||
users = await client.get_users()
|
||||
if isinstance(users, list):
|
||||
@@ -57,7 +67,7 @@ async def jellyfin_login(form_data: OAuth2PasswordRequestForm = Depends()) -> di
|
||||
continue
|
||||
name = user.get("Name")
|
||||
if isinstance(name, str) and name:
|
||||
create_user_if_missing(name, "jellyfin-user", role="user", auth_provider="jellyfin")
|
||||
create_user_if_missing(name, token_urlsafe(32), role="user", auth_provider="jellyfin")
|
||||
except Exception:
|
||||
pass
|
||||
token = create_access_token(form_data.username, "user")
|
||||
@@ -78,10 +88,12 @@ async def jellyseerr_login(form_data: OAuth2PasswordRequestForm = Depends()) ->
|
||||
raise HTTPException(status_code=status.HTTP_502_BAD_GATEWAY, detail=str(exc)) from exc
|
||||
if not isinstance(response, dict):
|
||||
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid Jellyseerr credentials")
|
||||
create_user_if_missing(form_data.username, "jellyseerr-user", role="user", auth_provider="jellyseerr")
|
||||
create_user_if_missing(form_data.username, token_urlsafe(32), role="user", auth_provider="jellyseerr")
|
||||
user = get_user_by_username(form_data.username)
|
||||
if user and user.get("is_blocked"):
|
||||
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="User is blocked")
|
||||
if user and user.get("auth_provider") == "jellyseerr":
|
||||
set_user_password(form_data.username, token_urlsafe(32))
|
||||
token = create_access_token(form_data.username, "user")
|
||||
set_last_login(form_data.username)
|
||||
return {"access_token": token, "token_type": "bearer", "user": {"username": form_data.username, "role": "user"}}
|
||||
|
||||
@@ -939,15 +939,15 @@ async def _ensure_request_access(
|
||||
) -> None:
|
||||
if user.get("role") == "admin":
|
||||
return
|
||||
runtime = get_runtime_settings()
|
||||
mode = (runtime.requests_data_source or "prefer_cache").lower()
|
||||
cached = get_request_cache_payload(request_id)
|
||||
if mode != "always_js" and cached is not None:
|
||||
logger.debug("access cache hit: request_id=%s mode=%s", request_id, mode)
|
||||
if cached is not None:
|
||||
logger.debug("access cache hit: request_id=%s", request_id)
|
||||
if _request_matches_user(cached, user.get("username", "")):
|
||||
return
|
||||
raise HTTPException(status_code=403, detail="Request not accessible for this user")
|
||||
logger.debug("access cache miss: request_id=%s mode=%s", request_id, mode)
|
||||
if not client.configured():
|
||||
raise HTTPException(status_code=403, detail="Request access cannot be verified")
|
||||
logger.debug("access cache miss: request_id=%s", request_id)
|
||||
details = await _get_request_details(client, request_id)
|
||||
if details is None or not _request_matches_user(details, user.get("username", "")):
|
||||
raise HTTPException(status_code=403, detail="Request not accessible for this user")
|
||||
@@ -1067,8 +1067,7 @@ async def _resolve_root_folder_path(client: Any, root_folder: str, service_name:
|
||||
async def get_snapshot(request_id: str, user: Dict[str, str] = Depends(get_current_user)) -> Snapshot:
|
||||
runtime = get_runtime_settings()
|
||||
client = JellyseerrClient(runtime.jellyseerr_base_url, runtime.jellyseerr_api_key)
|
||||
if client.configured():
|
||||
await _ensure_request_access(client, int(request_id), user)
|
||||
await _ensure_request_access(client, int(request_id), user)
|
||||
return await build_snapshot(request_id)
|
||||
|
||||
|
||||
@@ -1327,8 +1326,7 @@ async def search_requests(
|
||||
async def ai_triage(request_id: str, user: Dict[str, str] = Depends(get_current_user)) -> TriageResult:
|
||||
runtime = get_runtime_settings()
|
||||
client = JellyseerrClient(runtime.jellyseerr_base_url, runtime.jellyseerr_api_key)
|
||||
if client.configured():
|
||||
await _ensure_request_access(client, int(request_id), user)
|
||||
await _ensure_request_access(client, int(request_id), user)
|
||||
snapshot = await build_snapshot(request_id)
|
||||
return triage_snapshot(snapshot)
|
||||
|
||||
@@ -1337,8 +1335,7 @@ async def ai_triage(request_id: str, user: Dict[str, str] = Depends(get_current_
|
||||
async def action_search(request_id: str, user: Dict[str, str] = Depends(get_current_user)) -> dict:
|
||||
runtime = get_runtime_settings()
|
||||
client = JellyseerrClient(runtime.jellyseerr_base_url, runtime.jellyseerr_api_key)
|
||||
if client.configured():
|
||||
await _ensure_request_access(client, int(request_id), user)
|
||||
await _ensure_request_access(client, int(request_id), user)
|
||||
snapshot = await build_snapshot(request_id)
|
||||
prowlarr_results: List[Dict[str, Any]] = []
|
||||
prowlarr = ProwlarrClient(runtime.prowlarr_base_url, runtime.prowlarr_api_key)
|
||||
@@ -1368,8 +1365,7 @@ async def action_search(request_id: str, user: Dict[str, str] = Depends(get_curr
|
||||
async def action_search_auto(request_id: str, user: Dict[str, str] = Depends(get_current_user)) -> dict:
|
||||
runtime = get_runtime_settings()
|
||||
client = JellyseerrClient(runtime.jellyseerr_base_url, runtime.jellyseerr_api_key)
|
||||
if client.configured():
|
||||
await _ensure_request_access(client, int(request_id), user)
|
||||
await _ensure_request_access(client, int(request_id), user)
|
||||
snapshot = await build_snapshot(request_id)
|
||||
arr_item = snapshot.raw.get("arr", {}).get("item")
|
||||
if not isinstance(arr_item, dict):
|
||||
@@ -1418,8 +1414,7 @@ async def action_search_auto(request_id: str, user: Dict[str, str] = Depends(get
|
||||
async def action_resume(request_id: str, user: Dict[str, str] = Depends(get_current_user)) -> dict:
|
||||
runtime = get_runtime_settings()
|
||||
client = JellyseerrClient(runtime.jellyseerr_base_url, runtime.jellyseerr_api_key)
|
||||
if client.configured():
|
||||
await _ensure_request_access(client, int(request_id), user)
|
||||
await _ensure_request_access(client, int(request_id), user)
|
||||
snapshot = await build_snapshot(request_id)
|
||||
queue = snapshot.raw.get("arr", {}).get("queue")
|
||||
download_ids = _download_ids(_queue_records(queue))
|
||||
@@ -1465,8 +1460,7 @@ async def action_resume(request_id: str, user: Dict[str, str] = Depends(get_curr
|
||||
async def action_readd(request_id: str, user: Dict[str, str] = Depends(get_current_user)) -> dict:
|
||||
runtime = get_runtime_settings()
|
||||
client = JellyseerrClient(runtime.jellyseerr_base_url, runtime.jellyseerr_api_key)
|
||||
if client.configured():
|
||||
await _ensure_request_access(client, int(request_id), user)
|
||||
await _ensure_request_access(client, int(request_id), user)
|
||||
snapshot = await build_snapshot(request_id)
|
||||
jelly = snapshot.raw.get("jellyseerr") or {}
|
||||
media = jelly.get("media") or {}
|
||||
@@ -1578,8 +1572,7 @@ async def request_history(
|
||||
) -> dict:
|
||||
runtime = get_runtime_settings()
|
||||
client = JellyseerrClient(runtime.jellyseerr_base_url, runtime.jellyseerr_api_key)
|
||||
if client.configured():
|
||||
await _ensure_request_access(client, int(request_id), user)
|
||||
await _ensure_request_access(client, int(request_id), user)
|
||||
snapshots = await asyncio.to_thread(get_recent_snapshots, request_id, limit)
|
||||
return {"snapshots": snapshots}
|
||||
|
||||
@@ -1590,8 +1583,7 @@ async def request_actions(
|
||||
) -> dict:
|
||||
runtime = get_runtime_settings()
|
||||
client = JellyseerrClient(runtime.jellyseerr_base_url, runtime.jellyseerr_api_key)
|
||||
if client.configured():
|
||||
await _ensure_request_access(client, int(request_id), user)
|
||||
await _ensure_request_access(client, int(request_id), user)
|
||||
actions = await asyncio.to_thread(get_recent_actions, request_id, limit)
|
||||
return {"actions": actions}
|
||||
|
||||
@@ -1602,8 +1594,7 @@ async def action_grab(
|
||||
) -> dict:
|
||||
runtime = get_runtime_settings()
|
||||
client = JellyseerrClient(runtime.jellyseerr_base_url, runtime.jellyseerr_api_key)
|
||||
if client.configured():
|
||||
await _ensure_request_access(client, int(request_id), user)
|
||||
await _ensure_request_access(client, int(request_id), user)
|
||||
snapshot = await build_snapshot(request_id)
|
||||
guid = payload.get("guid")
|
||||
indexer_id = payload.get("indexerId")
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import asyncio
|
||||
from typing import Any, Dict
|
||||
import httpx
|
||||
from fastapi import APIRouter, Depends
|
||||
@@ -38,53 +39,45 @@ async def services_status() -> Dict[str, Any]:
|
||||
)
|
||||
jellyfin = JellyfinClient(runtime.jellyfin_base_url, runtime.jellyfin_api_key)
|
||||
|
||||
services = []
|
||||
services.append(
|
||||
await _check(
|
||||
checks = [
|
||||
_check(
|
||||
"Jellyseerr",
|
||||
jellyseerr.configured(),
|
||||
lambda: jellyseerr.get_recent_requests(take=1, skip=0),
|
||||
)
|
||||
)
|
||||
services.append(
|
||||
await _check(
|
||||
),
|
||||
_check(
|
||||
"Sonarr",
|
||||
sonarr.configured(),
|
||||
sonarr.get_system_status,
|
||||
)
|
||||
)
|
||||
services.append(
|
||||
await _check(
|
||||
),
|
||||
_check(
|
||||
"Radarr",
|
||||
radarr.configured(),
|
||||
radarr.get_system_status,
|
||||
)
|
||||
)
|
||||
prowlarr_status = await _check(
|
||||
"Prowlarr",
|
||||
prowlarr.configured(),
|
||||
prowlarr.get_health,
|
||||
)
|
||||
),
|
||||
_check(
|
||||
"Prowlarr",
|
||||
prowlarr.configured(),
|
||||
prowlarr.get_health,
|
||||
),
|
||||
_check(
|
||||
"qBittorrent",
|
||||
qbittorrent.configured(),
|
||||
qbittorrent.get_app_version,
|
||||
),
|
||||
_check(
|
||||
"Jellyfin",
|
||||
jellyfin.configured(),
|
||||
jellyfin.get_system_info,
|
||||
),
|
||||
]
|
||||
services = await asyncio.gather(*checks)
|
||||
prowlarr_status = next(service for service in services if service["name"] == "Prowlarr")
|
||||
if prowlarr_status.get("status") == "up":
|
||||
health = prowlarr_status.get("detail")
|
||||
if isinstance(health, list) and health:
|
||||
prowlarr_status["status"] = "degraded"
|
||||
prowlarr_status["message"] = "Health warnings"
|
||||
services.append(prowlarr_status)
|
||||
services.append(
|
||||
await _check(
|
||||
"qBittorrent",
|
||||
qbittorrent.configured(),
|
||||
qbittorrent.get_app_version,
|
||||
)
|
||||
)
|
||||
services.append(
|
||||
await _check(
|
||||
"Jellyfin",
|
||||
jellyfin.configured(),
|
||||
jellyfin.get_system_info,
|
||||
)
|
||||
)
|
||||
|
||||
overall = "up"
|
||||
if any(s.get("status") == "down" for s in services):
|
||||
|
||||
@@ -19,6 +19,8 @@ def verify_password(plain_password: str, hashed_password: str) -> bool:
|
||||
|
||||
|
||||
def create_access_token(subject: str, role: str, expires_minutes: Optional[int] = None) -> str:
|
||||
if not settings.jwt_secret:
|
||||
raise ValueError("JWT_SECRET is not configured")
|
||||
minutes = expires_minutes or settings.jwt_exp_minutes
|
||||
expires = datetime.now(timezone.utc) + timedelta(minutes=minutes)
|
||||
payload: Dict[str, Any] = {"sub": subject, "role": role, "exp": expires}
|
||||
@@ -26,6 +28,8 @@ def create_access_token(subject: str, role: str, expires_minutes: Optional[int]
|
||||
|
||||
|
||||
def decode_token(token: str) -> Dict[str, Any]:
|
||||
if not settings.jwt_secret:
|
||||
raise ValueError("JWT_SECRET is not configured")
|
||||
return jwt.decode(token, settings.jwt_secret, algorithms=[_ALGORITHM])
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user