Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
fix(keyproxy): security hardening from review (3 blockers + 4 majors)
Ruben Lütke97adb70ecfd2
diff --git a/keyproxy/README.md b/keyproxy/README.mdindex 0a1ded9dcf..5205a7fcf3 100644--- a/keyproxy/README.md+++ b/keyproxy/README.md@@ -122,8 +122,13 @@ curl -s -X POST https://keys.example.com/admin/tokens \curl -s https://keys.example.com/admin/tokens -H "authorization: Bearer $KEYPROXY_ADMIN_KEY"curl -s -X DELETE https://keys.example.com/admin/tokens/<id> -H "authorization: Bearer $KEYPROXY_ADMIN_KEY"curl -s "https://keys.example.com/admin/usage?token_id=<id>" -H "authorization: Bearer $KEYPROXY_ADMIN_KEY"+# which providers have a real key loaded (admin-only — never on /healthz)+curl -s https://keys.example.com/admin/providers -H "authorization: Bearer $KEYPROXY_ADMIN_KEY"```+`GET /healthz` is the only unauthenticated endpoint; it returns exactly+`{"status": "ok"}` and reveals nothing about which providers or keys are loaded.+### CLI```bashdiff --git a/keyproxy/admin.py b/keyproxy/admin.pyindex 859ff99d0d..246ab90d76 100644--- a/keyproxy/admin.py+++ b/keyproxy/admin.py@@ -52,10 +52,11 @@ class UsageReportRow(BaseModel):def _require_admin(request: Request) -> None:- admin_key = request.app.state.config.admin_key- if not admin_key:- # No admin key configured -> admin surface is disabled (fail closed).- raise HTTPException(status_code=503, detail="admin disabled (no KEYPROXY_ADMIN_KEY)")+ # Always answer with 401 — never reveal whether KEYPROXY_ADMIN_KEY is set.+ # An unset admin key resolves to the empty string, and+ # ``compare_digest("", presented)`` is False for any non-empty bearer, so+ # admin stays fail-closed without a distinguishable 503.+ admin_key = request.app.state.config.admin_key or ""header = request.headers.get("authorization", "")prefix = "bearer "presented = header[len(prefix):].strip() if header.lower().startswith(prefix) else ""@@ -71,6 +72,12 @@ def _require_admin(request: Request) -> None:def build_admin_router() -> APIRouter:router = APIRouter(prefix="/admin", dependencies=[Depends(_require_admin)])+ @router.get("/providers", response_model=list[str])+ def list_providers(request: Request) -> list[str]:+ # Provider enumeration is admin-only — it reveals which real keys are+ # loaded, so it must never sit on the unauthenticated /healthz probe.+ return request.app.state.config.configured_providers()+@router.post("/tokens", response_model=IssueTokenResponse)def issue_token(body: IssueTokenRequest, request: Request) -> IssueTokenResponse:tokens: TokenStore = request.app.state.tokensdiff --git a/keyproxy/app.py b/keyproxy/app.pyindex 2bd97d4ec7..e1aaec960d 100644--- a/keyproxy/app.py+++ b/keyproxy/app.py@@ -61,10 +61,10 @@ def create_app(@app.get("/healthz")def healthz() -> dict[str, object]:- return {- "status": "ok",- "providers": config.configured_providers(),- }+ # Unauthenticated liveness probe — MUST NOT reveal which providers /+ # real keys are loaded. Provider enumeration lives behind the admin+ # bearer at GET /admin/providers.+ return {"status": "ok"}app.include_router(build_admin_router())diff --git a/keyproxy/passthrough.py b/keyproxy/passthrough.pyindex e38311b0e9..45a1b23d73 100644--- a/keyproxy/passthrough.py+++ b/keyproxy/passthrough.py@@ -21,6 +21,7 @@ plus the token / usage / config dependencies.from __future__ import annotations+import loggingfrom typing import Anyimport httpx@@ -32,6 +33,8 @@ from .config import ProxyConfigfrom .tokens import TokenStorefrom .usage import UsageStore+_log = logging.getLogger("keyproxy.passthrough")+# Hop-by-hop headers (RFC 7230 §6.1) must not be forwarded by a proxy. Plus any# inbound auth header — the proxy sets the real credential itself._HOP_BY_HOP = frozenset(@@ -127,11 +130,13 @@ async def handle_passthrough(status_code=401,)- # 3. Provider lookup — 404 if unknown OR known-but-unkeyed.+ # 3. Provider lookup — 404 with ONE generic message whether the provider is+ # unknown OR known-but-unkeyed, so an authenticated client cannot enumerate+ # which known providers have a real key loaded.looked = config.lookup(provider_id)if looked is None:return JSONResponse(- {"error": "unknown_provider", "detail": f"provider '{provider_id}' is not configured"},+ {"error": "provider_not_available", "detail": "provider not available"},status_code=404,)vendor, real_base, real_key = looked@@ -162,8 +167,18 @@ async def handle_passthrough(except httpx.HTTPError as exc:# The upstream/proxy could not be reached — honest 502 (distinct from a# 401 bad-key or a 429 rate-limit, which pass through with their status).+ # The exception string can carry the real vendor base URL, so it is+ # logged server-side ONLY; the client gets a static message.+ _log.warning(+ "upstream unreachable for provider %s: %s",+ provider_id,+ exc.__class__.__name__,+ )return JSONResponse(- {"error": "upstream_unreachable", "detail": str(exc)},+ {+ "error": "upstream_unreachable",+ "detail": "upstream vendor could not be reached",+ },status_code=502,)@@ -176,16 +191,24 @@ async def handle_passthrough(usage_buffer.extend(chunk[: _USAGE_BUFFER_CAP - len(usage_buffer)])yield chunkfinally:- await upstream_response.aclose()+ # Both the close and the metering are best-effort cleanup that runs+ # after the body has streamed; neither may surface as a stream error.+ try:+ await upstream_response.aclose()+ except Exception: # noqa: BLE001 — close failure must not break the stream+ _log.debug("upstream response close failed", exc_info=True)# 6. Best-effort metering — never fails the response (we are past# the point where the body is already streamed).- _record_usage(- usage,- token_id=token_id,- provider_id=provider_id,- vendor=vendor,- body=bytes(usage_buffer),- )+ try:+ _record_usage(+ usage,+ token_id=token_id,+ provider_id=provider_id,+ vendor=vendor,+ body=bytes(usage_buffer),+ )+ except Exception: # noqa: BLE001 — metering must never break the stream+ _log.debug("usage recording failed", exc_info=True)response_headers = _safe_response_headers(upstream_response.headers)return StreamingResponse(diff --git a/keyproxy/tests/test_admin.py b/keyproxy/tests/test_admin.pyindex 5dd5d6fb5f..3d9f928796 100644--- a/keyproxy/tests/test_admin.py+++ b/keyproxy/tests/test_admin.py@@ -130,9 +130,50 @@ async def test_usage_report() -> None:@pytest.mark.anyio-async def test_healthz_is_open() -> None:+async def test_healthz_is_open_and_reveals_nothing() -> None:app, _tokens, _usage = build_app()async with client_for(app) as c:r = await c.get("/healthz")assert r.status_code == 200- assert r.json()["status"] == "ok"+ # Liveness only — must NOT enumerate providers / loaded keys.+ assert r.json() == {"status": "ok"}+++async def test_admin_providers_requires_auth() -> None:+ app, _tokens, _usage = build_app()+ async with client_for(app) as c:+ r = await c.get("/admin/providers")+ assert r.status_code == 401+++async def test_admin_providers_lists_configured() -> None:+ app, _tokens, _usage = build_app()+ async with client_for(app) as c:+ r = await c.get("/admin/providers", headers=auth())+ assert r.status_code == 200+ assert r.json() == ["openai"]+++async def test_admin_returns_401_not_503_when_no_admin_key() -> None:+ # When KEYPROXY_ADMIN_KEY is unset the admin surface must still answer 401+ # (never a 503 that reveals the key is absent).+ store = Store(":memory:")+ tokens = TokenStore(store)+ usage = UsageStore(store)+ cfg = ProxyConfig(providers={}, admin_key=None, allow_insecure=True)++ def upstream_handler(_req: httpx.Request) -> httpx.Response:+ return httpx.Response(200, json={"ok": True})++ upstream = httpx.AsyncClient(transport=httpx.MockTransport(upstream_handler))+ app = create_app(config=cfg, tokens=tokens, usage=usage, upstream=upstream)+ async with client_for(app) as c:+ no_auth = await c.get("/admin/tokens")+ with_bearer = await c.get(+ "/admin/tokens", headers={"authorization": "Bearer anything"}+ )+ assert no_auth.status_code == 401+ assert with_bearer.status_code == 401diff --git a/keyproxy/tests/test_config.py b/keyproxy/tests/test_config.pyindex 0ae6b71015..8e36356210 100644--- a/keyproxy/tests/test_config.py+++ b/keyproxy/tests/test_config.py@@ -99,9 +99,11 @@ def test_real_keys_not_in_repr(monkeypatch: pytest.MonkeyPatch) -> None:monkeypatch.setenv("KEYPROXY_OPENAI_KEY", "sk-super-secret-value")monkeypatch.setenv("KEYPROXY_ADMIN_KEY", "admin-secret-value")cfg = load_config()- text = repr(cfg)- assert "sk-super-secret-value" not in text- assert "admin-secret-value" not in text+ # Neither repr() nor str() may contain a real key or the admin key — the+ # object must be safe to log.+ for text in (repr(cfg), str(cfg)):+ assert "sk-super-secret-value" not in text+ assert "admin-secret-value" not in textdef test_provider_id_upper_mapping() -> None:diff --git a/keyproxy/tests/test_passthrough.py b/keyproxy/tests/test_passthrough.pyindex 8327971858..a36a261916 100644--- a/keyproxy/tests/test_passthrough.py+++ b/keyproxy/tests/test_passthrough.py@@ -139,6 +139,55 @@ async def test_unknown_provider_is_404() -> None:json={"x": 1},)assert r.status_code == 404+ assert r.json()["detail"] == "provider not available"+++async def test_known_but_unkeyed_provider_404_is_indistinguishable() -> None:+ # grok is in the wire contract but NOT keyed in this harness -> same generic+ # 404 + message as a totally unknown provider, so probing can't enumerate+ # known-but-unkeyed providers.+ def upstream(_req: httpx.Request) -> httpx.Response:+ return _json_stream(200, {"ok": True})++ app, tokens, _usage = build_harness(upstream)+ issued = tokens.issue("alice")+ async with client_for(app) as c:+ unkeyed = await c.post(+ "/p/grok/v1/chat/completions",+ headers={"authorization": f"Bearer {issued.plaintext}"},+ json={"x": 1},+ )+ unknown = await c.post(+ "/p/no-such-provider/x",+ headers={"authorization": f"Bearer {issued.plaintext}"},+ json={"x": 1},+ )+ assert unkeyed.status_code == unknown.status_code == 404+ assert unkeyed.json() == unknown.json()+++async def test_upstream_unreachable_is_502_without_leaking_url() -> None:+ real_base = "https://api.openai.com/v1"++ def upstream(_req: httpx.Request) -> httpx.Response:+ raise httpx.ConnectError("Failed to connect to " + real_base)++ app, tokens, _usage = build_harness(upstream)+ issued = tokens.issue("alice")+ async with client_for(app) as c:+ r = await c.post(+ "/p/openai/chat/completions",+ headers={"authorization": f"Bearer {issued.plaintext}"},+ json={"model": "gpt-4o-mini"},+ )+ assert r.status_code == 502+ body = r.text+ # The static message is returned; the real vendor URL never leaks.+ assert r.json()["detail"] == "upstream vendor could not be reached"+ assert real_base not in body+ assert "api.openai.com" not in body# --------------------------------------------------------------------------diff --git a/keyproxy/tests/test_vendors.py b/keyproxy/tests/test_vendors.pyindex 202cfec13b..90ff866e54 100644--- a/keyproxy/tests/test_vendors.py+++ b/keyproxy/tests/test_vendors.py@@ -50,6 +50,16 @@ def test_extract_openai_compatible_missing() -> None:)+def test_extract_openai_compatible_requires_bearer_scheme() -> None:+ # A raw Authorization value without the "Bearer " scheme is NOT a token —+ # it must fail closed (None -> 401), never be treated as a bare token.+ headers = {"authorization": "kp_inbound_token"}+ assert (+ vendors.extract_inbound_token("openai_compatible", headers, query={})+ is None+ )++def test_extract_anthropic_x_api_key() -> None:headers = {"x-api-key": "kp_inbound_token"}token = vendors.extract_inbound_token("anthropic", headers, query={})diff --git a/keyproxy/tokens.py b/keyproxy/tokens.pyindex 9bda971ac4..7578be4525 100644--- a/keyproxy/tokens.py+++ b/keyproxy/tokens.py@@ -60,15 +60,18 @@ class TokenStore:return IssuedToken(id=token_id, label=label, plaintext=plaintext)# ------------------------------------------------------------------- # Verify (constant-time, fail-closed)+ # Verify (fail-closed)# ------------------------------------------------------------------def verify(self, plaintext: str | None) -> str | None:"""Return the token id for a valid, non-revoked token, else ``None``.- Constant-time comparison on the SHA-256 hex. Looks the candidate up by- its hash (an indexed equality match) and then constant-time-compares to- guard against any storage-layer timing leak.+ The lookup is by the SHA-256 hash of the presented token, so the real+ timing surface is the indexed DB equality match — not constant-time on+ its own. We hash the token (the secret) before it touches the query, so+ the comparison is over hash digests, not the raw secret. The+ :func:`hmac.compare_digest` below is a belt-and-suspenders check on the+ returned hash, NOT a standalone timing-attack guarantee."""if not plaintext:return Nonediff --git a/keyproxy/vendors.py b/keyproxy/vendors.pyindex 35b6436d09..5bcc5f13fa 100644--- a/keyproxy/vendors.py+++ b/keyproxy/vendors.py@@ -51,13 +51,18 @@ def resolve_provider(provider_id: str) -> tuple[str, str] | None:def _bearer(value: str | None) -> str | None:+ """Extract the token from an ``Authorization: Bearer <token>`` header.++ The ``Bearer`` scheme is REQUIRED: a header without it returns ``None`` so+ the caller fails closed (401). A bare header value is never treated as a+ token.+ """if not value:return Noneprefix = "bearer "if value.lower().startswith(prefix):return value[len(prefix):].strip() or None- # Some clients send the raw token in Authorization without the scheme.- return value.strip() or None+ return Nonedef extract_inbound_token(