mirror of
https://github.com/unshackle-dl/unshackle.git
synced 2026-11-16 14:05:10 +00:00
fix(api)!: key the health route and keep server internals from user keys
/api/health needs X-Secret-Key but stays outside the rate limit. Only the admin key gets load_errors from /api/services, default error details no longer name the exception class, and a prepare signal replaces aiohttp's Server banner on every response while the CDM routes keep their own.
This commit is contained in:
@@ -249,7 +249,7 @@ async def test_since_cursor_and_dashboard_key(aiohttp_client, serve_app) -> None
|
||||
assert (await client.get("/api/dashboard/cdm-logs")).status == 401
|
||||
assert (await client.get("/api/dashboard/cdm-logs", headers=USER)).status == 401
|
||||
# Only the device routes are CDM calls: not the API, not the ping, not this route.
|
||||
await client.get("/api/health")
|
||||
await client.get("/api/health", headers=USER)
|
||||
await client.get("/", headers=USER)
|
||||
|
||||
page = await cdm_log(client, since=1)
|
||||
|
||||
@@ -255,6 +255,8 @@ async def test_rate_limited_request_returns_429(aiohttp_client, monkeypatch) ->
|
||||
assert (await client.get("/api/services", headers={"X-Secret-Key": "tier-key"})).status == 200
|
||||
resp = await client.get("/api/services", headers={"X-Secret-Key": "tier-key"})
|
||||
assert resp.status == 429 and int(resp.headers["Retry-After"]) > 0
|
||||
assert (await client.get("/api/health", headers={"X-Secret-Key": "tier-key"})).status == 200
|
||||
assert (await client.get("/api/health")).status == 401
|
||||
# The dashboard key leaves the middleware before the limit check, so it always answers.
|
||||
assert (await client.get("/api/dashboard/status", headers={"X-Secret-Key": "dash-secret"})).status == 200
|
||||
|
||||
@@ -400,7 +402,7 @@ async def test_dashboard_health(aiohttp_client, dashboard_cfg, monkeypatch) -> N
|
||||
|
||||
|
||||
async def test_unknown_key_on_open_route_does_not_grow_key_stats(aiohttp_client, monkeypatch) -> None:
|
||||
"""/api/health answers 200 to any header, so counters keyed by the raw header are a memory leak."""
|
||||
"""Counters keyed by the raw header of an unknown key would grow without bound."""
|
||||
monkeypatch.setitem(config.serve, "users", {"real": {}})
|
||||
stats.keys.clear()
|
||||
client = await aiohttp_client(make_app())
|
||||
|
||||
@@ -95,6 +95,12 @@ def test_build_error_response_from_generic_exception() -> None:
|
||||
assert body["message"] == f"oops (ref {body['ref']})"
|
||||
|
||||
|
||||
def test_categorize_fallback_names_no_exception_class() -> None:
|
||||
err = categorize_exception(RuntimeError("oops"), context={"op": "x"})
|
||||
assert err.error_code == APIErrorCode.INTERNAL_ERROR
|
||||
assert err.details == {"op": "x"}
|
||||
|
||||
|
||||
def test_build_error_response_debug_mode_includes_traceback() -> None:
|
||||
try:
|
||||
raise ValueError("kaboom")
|
||||
|
||||
@@ -40,13 +40,10 @@ def make_app():
|
||||
|
||||
|
||||
def no_key_required_auth():
|
||||
"""Mirror serve.py's api_key_authentication middleware: required X-Secret-Key
|
||||
on every endpoint except /api/health."""
|
||||
"""Mirror serve.py's api_key_authentication middleware: a required X-Secret-Key on every endpoint."""
|
||||
|
||||
@web.middleware
|
||||
async def mw(request, handler):
|
||||
if request.path == "/api/health":
|
||||
return await handler(request)
|
||||
secret = request.headers.get("X-Secret-Key")
|
||||
if not secret:
|
||||
return web.json_response({"status": 401, "message": "Secret Key is Empty."}, status=401)
|
||||
@@ -307,11 +304,44 @@ async def test_health_endpoint_responds_ok(make_app, aiohttp_client) -> None:
|
||||
assert "version" in body
|
||||
|
||||
|
||||
async def test_health_bypasses_api_key_auth_middleware(make_app, aiohttp_client) -> None:
|
||||
app = make_app(remote_only=True, with_auth_middleware=True)
|
||||
async def test_every_response_carries_a_generic_server_header(make_app, aiohttp_client) -> None:
|
||||
"""Returned, raised (404, 405) and streamed responses all lose aiohttp's version banner."""
|
||||
|
||||
async def stream(request: web.Request) -> web.StreamResponse:
|
||||
response = web.StreamResponse()
|
||||
await response.prepare(request)
|
||||
await response.write(b"x")
|
||||
return response
|
||||
|
||||
app = make_app(remote_only=True)
|
||||
app.router.add_get("/stream", stream)
|
||||
client = await aiohttp_client(app)
|
||||
resp = await client.get("/api/health")
|
||||
assert resp.status == 200 # health bypasses auth
|
||||
for method, path in [("GET", "/api/health"), ("DELETE", "/api/health"), ("GET", "/api/nope"), ("GET", "/stream")]:
|
||||
resp = await client.request(method, path)
|
||||
assert resp.headers["Server"] == "unshackle", (method, path, resp.status)
|
||||
|
||||
|
||||
async def test_services_load_errors_go_to_the_admin_key_only(
|
||||
make_app, aiohttp_client, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
from unshackle.core import services as services_module
|
||||
from unshackle.core.config import config
|
||||
|
||||
monkeypatch.setattr(services_module, "LOAD_ERRORS", ["BAD: failed to import - ImportError: boom"])
|
||||
monkeypatch.setattr(config, "serve", {"api_secret": "admin", "users": {"user": {"services": ["EXAMPLE"]}}})
|
||||
client = await aiohttp_client(make_app(remote_only=True))
|
||||
user = await (await client.get("/api/services", headers={"X-Secret-Key": "user"})).json()
|
||||
admin = await (await client.get("/api/services", headers={"X-Secret-Key": "admin"})).json()
|
||||
assert user["load_errors"] == []
|
||||
assert admin["load_errors"] == ["BAD: failed to import - ImportError: boom"]
|
||||
|
||||
|
||||
async def test_health_needs_an_api_key(make_app, aiohttp_client) -> None:
|
||||
app = make_app(remote_only=True, with_auth_middleware=True)
|
||||
app["config"]["users"]["good-key"] = {}
|
||||
client = await aiohttp_client(app)
|
||||
assert (await client.get("/api/health")).status == 401
|
||||
assert (await client.get("/api/health", headers={"X-Secret-Key": "good-key"})).status == 200
|
||||
|
||||
|
||||
async def test_auth_middleware_rejects_missing_key(make_app, aiohttp_client) -> None:
|
||||
|
||||
Reference in New Issue
Block a user