d131ba461c
Lint & Test / test (push) Successful in 20s
Security - Default scripts_management, callbacks_management, links_management, and media_folders_management to False so a leaked token cannot escalate to RCE through admin CRUD endpoints. - TokenSpec + scope hierarchy (read | control | admin); legacy bare-string api_tokens entries promote to admin for back-compat. Management endpoints now require admin scope. - WebSocket subprotocol auth (Sec-WebSocket-Protocol: media-server.token.<T>) preferred over ?token= query so the token no longer lands in URL/history/ Referer; query fallback retained for HA integration back-compat. - Origin allow-list check on the WS endpoint (CSWSH defence). - In-process token-bucket rate limiter: 5/min for failed auths, 10/min for /api/scripts/execute and /api/callbacks/execute. - shell=False subprocess path (shlex.split) + per-parameter regex `pattern` in ScriptParameterConfig to harden shell=true scripts against parameter injection (Windows cmd.exe env-var expansion). - CSP gains form-action, worker-src, manifest-src directives. - Refuse cors_origins=["*"] at startup; strip token=... from uvicorn access logs; validate Gitea release tag against strict SemVer regex. - noopener noreferrer + no-referrer referrerpolicy on every outbound link. - icacls hardening of config.yaml on Windows (current user + SYSTEM + Administrators only); 0600 still enforced on POSIX. - WS volume handler clamps input and never drops the socket on bad messages. Performance - Album-art read in windows_media gated by track key — was decoding the WinRT thumbnail twice per second regardless of track changes. - /api/media/artwork returns content-derived ETag + Cache-Control so the browser sends If-None-Match and gets 304s on track repeats. - Foreground-service ctypes argtypes hoisted to one-time module init (was re-declaring ~14 prototypes per probe). - display_service _static_cache keyed by (edid_hash, ...) tuple with eviction of disappeared monitors — fixes stale capabilities on hot-plug swaps where the new topology has the same monitor count. - Visualizer rAF loop paused on document.hidden, resumed on visible. Reliability / bug fixes - Lifespan rewritten as try/yield/finally so a partial-startup failure cannot orphan background tasks or executors. - _run_callback in routes/media.py keeps a strong task ref (GC-safe) and uses the dedicated callback executor instead of the default pool. - macos_media.set_volume() no longer always returns True. - TrayManager._restart_requested initialised in __init__; set before signalling exit so the main thread observes it correctly. - Missing static_dir now logs a WARNING instead of silent UI disable. UX / accessibility / PWA - manifest.json theme_color and background_color match the Studio Reference base (#0E0D0B); added id and scope for PWA installability. - ARIA on mini-player icon buttons; inner SVGs marked aria-hidden. - OS mediaSession API wired so headset / lockscreen / Bluetooth buttons drive play/pause/next/prev/seek and show track metadata + artwork. Observability - X-Request-ID middleware (accept upstream id if it matches a safe regex, otherwise UUID4); request_id_var added to ContextVars and included in every log line alongside the token label. - Audit log (append-only JSONL) for every script + callback execution, including the on_play/on_pause/etc. event callbacks. Background-thread writer; queue capped; flushed in lifespan teardown. Deployment - proxy_headers + forwarded_allow_ips plumbed through Settings → uvicorn.Config for reverse-proxy installs. - HTTPS support via ssl_certfile + ssl_keyfile (+ optional password); startup refuses to launch with only one of the pair set. - Thumbnail cache moved from project-root .cache to %LOCALAPPDATA%/media-server/cache (Windows) and $XDG_CACHE_HOME/media-server/thumbnails (POSIX). Tests - 35 new tests across auth scopes, rate limiter, browser path traversal (../ NUL UNC absolute), script-param validation incl. regex, Gitea tag whitelist, config atomic write + POSIX perms. 47 passed / 4 skipped.
85 lines
2.9 KiB
Python
85 lines
2.9 KiB
Python
"""Path traversal defence for BrowserService.validate_path.
|
|
|
|
The browser endpoint is the single most security-critical filesystem entry
|
|
point in the app: it serves file contents and folder listings to the WebUI.
|
|
A bypass here = arbitrary read of any file the server process can see.
|
|
|
|
The current implementation signals rejection by *raising* (ValueError for
|
|
traversal/NUL/unknown folder, FileNotFoundError for non-existent absolute
|
|
paths). Either rejection mode is acceptable — these tests assert that the
|
|
adversarial input never returns a path *inside* the configured base.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import tempfile
|
|
from pathlib import Path
|
|
from unittest.mock import patch
|
|
|
|
import pytest
|
|
|
|
from media_server.services.browser_service import BrowserService
|
|
|
|
|
|
@pytest.fixture
|
|
def tmp_media_folder():
|
|
"""A real temp dir registered as a media folder for the test duration."""
|
|
with tempfile.TemporaryDirectory() as tmp:
|
|
base = Path(tmp).resolve()
|
|
(base / "ok.mp3").write_bytes(b"id3")
|
|
(base / "sub").mkdir()
|
|
(base / "sub" / "nested.mp3").write_bytes(b"id3")
|
|
|
|
from media_server.config import MediaFolderConfig
|
|
folders = {"test": MediaFolderConfig(path=str(base), label="Test", enabled=True)}
|
|
with patch("media_server.services.browser_service.settings.media_folders", folders):
|
|
yield base
|
|
|
|
|
|
def _is_rejected(folder_id: str, rel: str) -> bool:
|
|
"""Helper: True iff validate_path either raises or returns None."""
|
|
try:
|
|
result = BrowserService.validate_path(folder_id, rel)
|
|
except (ValueError, FileNotFoundError, OSError):
|
|
return True
|
|
return result is None
|
|
|
|
|
|
def test_validate_path_accepts_a_real_file(tmp_media_folder: Path):
|
|
p = BrowserService.validate_path("test", "ok.mp3")
|
|
assert p is not None
|
|
assert p.is_file()
|
|
# Defence-in-depth: resolved path must live inside the base.
|
|
assert tmp_media_folder in p.resolve().parents or p.resolve().parent == tmp_media_folder
|
|
|
|
|
|
def test_validate_path_accepts_nested(tmp_media_folder: Path):
|
|
p = BrowserService.validate_path("test", "sub/nested.mp3")
|
|
assert p is not None
|
|
|
|
|
|
def test_unknown_folder_rejected(tmp_media_folder: Path):
|
|
assert _is_rejected("ghost", "ok.mp3")
|
|
|
|
|
|
def test_dotdot_traversal_rejected(tmp_media_folder: Path):
|
|
assert _is_rejected("test", "../etc/passwd")
|
|
assert _is_rejected("test", "..\\..\\Windows\\System32")
|
|
assert _is_rejected("test", "sub/../../etc/passwd")
|
|
|
|
|
|
def test_absolute_path_rejected(tmp_media_folder: Path):
|
|
assert _is_rejected("test", "/etc/passwd")
|
|
assert _is_rejected("test", "C:\\Windows\\System32")
|
|
assert _is_rejected("test", "C:/Windows")
|
|
|
|
|
|
def test_unc_path_rejected(tmp_media_folder: Path):
|
|
assert _is_rejected("test", "\\\\server\\share")
|
|
assert _is_rejected("test", "//server/share")
|
|
|
|
|
|
def test_null_byte_rejected(tmp_media_folder: Path):
|
|
assert _is_rejected("test", "ok.mp3\x00.png")
|
|
assert _is_rejected("test", "sub\x00/nested.mp3")
|