fix(serve): close the developer dashboard when a config reload removes its key

This commit is contained in:
imSp4rky
2026-11-26 13:40:04 -07:00
parent 34ce5e5ae8
commit 7bba51910d
5 changed files with 55 additions and 8 deletions
+3
View File
@@ -20,6 +20,9 @@ serve:
``` ```
Without `dashboard.key` the server does not register the routes, and they answer `404`. Without `dashboard.key` the server does not register the routes, and they answer `404`.
A config reload that removes the dashboard key closes the dashboard: the routes answer `404` and
an open `/api/dashboard/events` connection ends. To add a dashboard key to a server that started
without one, restart it.
`serve --no-key` turns off user authentication only; the dashboard key stays required. `serve --no-key` turns off user authentication only; the dashboard key stays required.
Once the dashboard key is set, every `/api/dashboard/` request must carry it in Once the dashboard key is set, every `/api/dashboard/` request must carry it in
`X-Secret-Key`. `X-Secret-Key`.
+5 -3
View File
@@ -161,7 +161,7 @@ is the [REST API](../../dev/rest-api/index.md) section. These are the config key
| `tiers` | dict | `{}` | Named settings that `users` entries reference by name (see below). | | `tiers` | dict | `{}` | Named settings that `users` entries reference by name (see below). |
| `services` | list | *(unset)* | Global service allowlist. Omit to allow all. | | `services` | list | *(unset)* | Global service allowlist. Omit to allow all. |
| `remote_only` | bool | `false` | Expose only the remote service session endpoints (health, services, search, session) and disable the rest of the REST API. | | `remote_only` | bool | `false` | Expose only the remote service session endpoints (health, services, search, session) and disable the rest of the REST API. |
| `dashboard` | dict | *(unset)* | Developer dashboard: `key` is the API key for the read-only `/api/dashboard/` endpoints (status, remote sessions, remote session logs, jobs, keys, services, health, logs, SSE events). Unset leaves those routes unregistered. See [dashboard endpoints](../../dev/rest-api/dashboard.md). | | `dashboard` | dict | *(unset)* | Developer dashboard: `key` is the API key for the read-only `/api/dashboard/` endpoints (status, remote sessions, remote session logs, jobs, keys, services, health, logs, SSE events). Unset leaves those routes unregistered, and a reload that removes the key makes them answer `404`. See [dashboard endpoints](../../dev/rest-api/dashboard.md). |
| `session_ttl` | int (s) | `300` | Seconds a remote session can stay idle before it expires. A remote client sends keep-alive requests to its remote session during a download, so the remote session does not expire during a long download. | | `session_ttl` | int (s) | `300` | Seconds a remote session can stay idle before it expires. A remote client sends keep-alive requests to its remote session during a download, so the remote session does not expire during a long download. |
| `max_sessions` | int or null | `100` | Maximum concurrent remote sessions; at the cap the server evicts the oldest remote session of the API key that holds the most. Set it to `null` or `0` for no limit, which is also what `/api/dashboard/status` then reports, so a dashboard can tell "no cap" from a cap that happens to sit at the default. | | `max_sessions` | int or null | `100` | Maximum concurrent remote sessions; at the cap the server evicts the oldest remote session of the API key that holds the most. Set it to `null` or `0` for no limit, which is also what `/api/dashboard/status` then reports, so a dashboard can tell "no cap" from a cap that happens to sit at the default. |
| `history_limit` | int | `100` | How many finished jobs to retain in history. | | `history_limit` | int | `100` | How many finished jobs to retain in history. |
@@ -188,8 +188,10 @@ list.
`tiers`, `services` and device lists in one step. Open CDM sessions and remote sessions `tiers`, `services` and device lists in one step. Open CDM sessions and remote sessions
continue; an API key you removed gets `401` on its next request. A file that does not parse continue; an API key you removed gets `401` on its next request. A file that does not parse
or validate keeps the running settings and logs the reason. A change to `remote_only`, or validate keeps the running settings and logs the reason. A change to `remote_only`,
`services_refresh_interval`, the first PlayReady device, or any command-line flag needs `services_refresh_interval`, the first PlayReady device, a `dashboard.key` on a server that
a restart, and the log says so. A new `global_speed_limit` applies to jobs that start after the started without one, or any command-line flag needs a restart, and the log says so. A reload
that removes `dashboard.key` closes the dashboard: its routes answer `404` and an open
`/api/dashboard/events` connection ends. A new `global_speed_limit` applies to jobs that start after the
reload; running jobs keep their share. Windows has no `SIGHUP`: restart the server there. reload; running jobs keep their share. Windows has no `SIGHUP`: restart the server there.
`server_cdm` decides whether the server runs the CDM licensing for that API key. Set it to `server_cdm` decides whether the server runs the CDM licensing for that API key. Set it to
+37
View File
@@ -2,6 +2,7 @@
from __future__ import annotations from __future__ import annotations
import asyncio
import logging import logging
from pathlib import Path from pathlib import Path
@@ -11,6 +12,9 @@ from aiohttp import web
from unshackle.commands import serve as serve_cmd from unshackle.commands import serve as serve_cmd
from unshackle.core import config as config_module from unshackle.core import config as config_module
from unshackle.core.api.events import bus
from unshackle.core.api.handlers import dashboard_authentication
from unshackle.core.api.routes import setup_routes
from unshackle.core.config import config from unshackle.core.config import config
pytestmark = pytest.mark.unit pytestmark = pytest.mark.unit
@@ -79,3 +83,36 @@ def test_restart_only_change_is_reported_not_applied(
assert _reload(app) is False assert _reload(app) is False
assert "restart" in caplog.text and "remote_only" in caplog.text assert "restart" in caplog.text and "remote_only" in caplog.text
assert set(app["config"]["users"]) == {"old", "api"} assert set(app["config"]["users"]) == {"old", "api"}
async def test_reload_that_drops_the_dashboard_key_closes_its_routes(
running: tuple[web.Application, Path], aiohttp_client
) -> None:
app, path = running
config.serve["dashboard"] = {"key": "dash"}
app.middlewares.append(dashboard_authentication)
app["debug_api"] = False
setup_routes(app, remote_only=True, dashboard=True)
client = await aiohttp_client(app)
assert (await client.get("/api/dashboard/status", headers={"X-Secret-Key": "dash"})).status == 200
stream = await client.get("/api/dashboard/events", headers={"X-Secret-Key": "dash"})
assert b"event: stats" in await stream.content.readuntil(b"\n\n")
_write(path, users={"old": {"devices": ["dev"]}})
assert _reload(app) is True
assert (await client.get("/api/dashboard/status")).status == 404
assert (await client.get("/api/dashboard/status", headers={"X-Secret-Key": "dash"})).status == 404
bus.publish("job", {"after": "reload"})
assert b"after" not in await asyncio.wait_for(stream.content.read(), 2)
def test_reload_that_adds_a_dashboard_key_needs_a_restart(
running: tuple[web.Application, Path], caplog: pytest.LogCaptureFixture
) -> None:
app, path = running
_write(path, users={"new": {"devices": ["dev"]}}, dashboard={"key": "dash"})
with caplog.at_level(logging.WARNING, logger=LOG.name):
assert _reload(app) is False
assert "restart" in caplog.text and "dashboard.key" in caplog.text
assert "dashboard" not in config.serve
+2
View File
@@ -262,6 +262,8 @@ def reload_config(app: web.Application, *, no_key: bool, serve_widevine: bool, s
changed = [k for k in RESTART_KEYS if serve.get(k) != config.serve.get(k)] changed = [k for k in RESTART_KEYS if serve.get(k) != config.serve.get(k)]
if serve_playready and bool(serve.get("playready_devices")) != ("playready_app" in app): if serve_playready and bool(serve.get("playready_devices")) != ("playready_app" in app):
changed.append("playready_devices (first device added or last removed)") changed.append("playready_devices (first device added or last removed)")
if dashboard_key(serve) and not any(r.canonical.startswith(DASHBOARD_PREFIX) for r in app.router.resources()):
changed.append("dashboard.key (dashboard off at startup)")
if changed: if changed:
log.warning(f"Config reload skipped, restart to apply: {', '.join(changed)}") log.warning(f"Config reload skipped, restart to apply: {', '.join(changed)}")
return False return False
+8 -5
View File
@@ -1128,16 +1128,16 @@ def request_secret_key(request: web.Request) -> str | None:
return key return key
def dashboard_key() -> str | None: def dashboard_key(serve: dict | None = None) -> str | None:
"""The developer dashboard key from serve.dashboard.key, or None when the dashboard is off.""" """The developer dashboard key from serve.dashboard.key (of *serve*, else the live config), or None when off."""
dashboard = (config.serve or {}).get("dashboard") dashboard = ((config.serve if serve is None else serve) or {}).get("dashboard")
key = dashboard.get("key") if isinstance(dashboard, dict) else None key = dashboard.get("key") if isinstance(dashboard, dict) else None
return str(key) if key else None return str(key) if key else None
@web.middleware @web.middleware
async def dashboard_authentication(request: web.Request, handler: Any) -> web.StreamResponse: async def dashboard_authentication(request: web.Request, handler: Any) -> web.StreamResponse:
"""Gate /api/dashboard/ behind serve.dashboard.key only; user and tier keys never pass. """Gate /api/dashboard/ behind serve.dashboard.key only; user and tier keys never pass, and with no dashboard key set it answers 404.
This middleware runs before the user-key middleware, so it answers the dashboard routes This middleware runs before the user-key middleware, so it answers the dashboard routes
first and no other route ever accepts the dashboard key. first and no other route ever accepts the dashboard key.
@@ -1148,7 +1148,7 @@ async def dashboard_authentication(request: web.Request, handler: Any) -> web.St
return await handler(request) return await handler(request)
expected = dashboard_key() expected = dashboard_key()
if not expected: if not expected:
return await handler(request) # routes are unregistered, so this 404s raise web.HTTPNotFound()
provided = request_secret_key(request) provided = request_secret_key(request)
if not provided or not hmac.compare_digest(provided, expected): if not provided or not hmac.compare_digest(provided, expected):
return web.json_response({"status": 401, "message": "Dashboard key is invalid."}, status=401) return web.json_response({"status": 401, "message": "Dashboard key is invalid."}, status=401)
@@ -2199,6 +2199,7 @@ async def dashboard_events_handler(request: web.Request) -> web.StreamResponse:
async def send_stats() -> None: async def send_stats() -> None:
await send("stats", dashboard_status()) await send("stats", dashboard_status())
opened_with = dashboard_key()
queue = bus.subscribe() queue = bus.subscribe()
get_task: asyncio.Task | None = None get_task: asyncio.Task | None = None
loop = asyncio.get_running_loop() loop = asyncio.get_running_loop()
@@ -2215,6 +2216,8 @@ async def dashboard_events_handler(request: web.Request) -> web.StreamResponse:
if get_task is None: if get_task is None:
get_task = asyncio.create_task(queue.get()) get_task = asyncio.create_task(queue.get())
done, _ = await asyncio.wait({get_task}, timeout=max(0.0, next_stats - loop.time())) done, _ = await asyncio.wait({get_task}, timeout=max(0.0, next_stats - loop.time()))
if dashboard_key() != opened_with:
break
if not done: if not done:
await send_stats() await send_stats()
next_stats = loop.time() + 5 next_stats = loop.time() + 5