mirror of
https://github.com/unshackle-dl/unshackle.git
synced 2026-11-18 06:55:07 +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:
@@ -71,13 +71,13 @@ def free_port() -> int:
|
||||
return s.getsockname()[1]
|
||||
|
||||
|
||||
def wait_for_health(url: str, timeout: float = 60.0) -> bool:
|
||||
def wait_for_health(url: str, secret_key: str, timeout: float = 60.0) -> bool:
|
||||
import requests
|
||||
|
||||
deadline = time.monotonic() + timeout
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
r = requests.get(f"{url}/api/health", timeout=2)
|
||||
r = requests.get(f"{url}/api/health", headers={"X-Secret-Key": secret_key}, timeout=2)
|
||||
if r.status_code == 200:
|
||||
return True
|
||||
except requests.RequestException:
|
||||
@@ -112,6 +112,7 @@ def server_url(request: pytest.FixtureRequest):
|
||||
explicit = str(cfg.getoption("--server-url")).rstrip("/")
|
||||
mode = cfg.getoption("--spawn-serve")
|
||||
is_live = cfg.getoption("--live")
|
||||
key = str(cfg.getoption("--secret-key"))
|
||||
|
||||
if not is_live:
|
||||
yield explicit or "http://localhost:8786"
|
||||
@@ -120,13 +121,13 @@ def server_url(request: pytest.FixtureRequest):
|
||||
if mode == "never":
|
||||
if not explicit:
|
||||
pytest.fail("--spawn-serve=never requires --server-url")
|
||||
if not wait_for_health(explicit, timeout=10):
|
||||
if not wait_for_health(explicit, key, timeout=10):
|
||||
pytest.fail(f"External serve not reachable at {explicit}")
|
||||
yield explicit
|
||||
return
|
||||
|
||||
if mode == "auto" and explicit:
|
||||
if not wait_for_health(explicit, timeout=10):
|
||||
if not wait_for_health(explicit, key, timeout=10):
|
||||
pytest.fail(f"External serve not reachable at {explicit}")
|
||||
yield explicit
|
||||
return
|
||||
@@ -153,7 +154,7 @@ def server_url(request: pytest.FixtureRequest):
|
||||
)
|
||||
url = f"http://127.0.0.1:{port}"
|
||||
try:
|
||||
if not wait_for_health(url, timeout=60):
|
||||
if not wait_for_health(url, key, timeout=60):
|
||||
proc.terminate()
|
||||
pytest.fail(f"Spawned serve at {url} did not become healthy within 60s")
|
||||
yield url
|
||||
|
||||
@@ -24,12 +24,12 @@ def test_services_endpoint(http_session, server_url: str) -> None:
|
||||
assert isinstance(body["services"], list)
|
||||
|
||||
|
||||
def test_health_does_not_require_secret_key(server_url: str) -> None:
|
||||
"""Health bypasses auth even when the server runs with a key."""
|
||||
def test_health_requires_secret_key(server_url: str, secret_key: str) -> None:
|
||||
"""Health needs the API key like every other route."""
|
||||
import requests
|
||||
|
||||
r = requests.get(f"{server_url}/api/health", timeout=10)
|
||||
assert r.status_code == 200
|
||||
assert r.status_code == (401 if secret_key else 200)
|
||||
|
||||
|
||||
def test_unknown_route_returns_404(http_session, server_url: str) -> None:
|
||||
|
||||
@@ -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