hardening

This commit is contained in:
2026-05-16 10:44:20 +00:00
parent 52e3d680f7
commit cc26ed9b2c
18 changed files with 315 additions and 169 deletions
+15 -3
View File
@@ -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"}}
+14 -23
View File
@@ -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")
+26 -33
View File
@@ -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):