Skip to content

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.

feat(keyproxy): passthrough core + admin surface + app factory + CLI

Ruben Lütke21d0f5f46f59
diff --git a/keyproxy/admin.py b/keyproxy/admin.py
new file mode 100644
index 0000000000..859ff99d0d
--- /dev/null
+++ b/keyproxy/admin.py
@@ -0,0 +1,126 @@
+"""Admin surface — token issue/list/revoke + a usage report.
+
+All endpoints are guarded by the ``KEYPROXY_ADMIN_KEY`` bearer
+(``Authorization: Bearer <admin_key>``), compared in constant time. The router
+is mounted by :func:`keyproxy.app.create_app` under ``/admin``.
+"""
+
+from __future__ import annotations
+
+import hmac
+
+from fastapi import APIRouter, Depends, HTTPException, Query, Request
+from pydantic import BaseModel, Field
+
+from .tokens import TokenStore
+from .usage import UsageStore
+
+# --------------------------------------------------------------------------
+# Request / response models
+# --------------------------------------------------------------------------
+
+
+class IssueTokenRequest(BaseModel):
+ label: str = Field(min_length=1, max_length=200)
+
+
+class IssueTokenResponse(BaseModel):
+ id: str
+ label: str
+ token: str # plaintext — returned exactly once, never persisted
+
+
+class TokenInfo(BaseModel):
+ id: str
+ label: str
+ created_at: int
+ revoked_at: int | None
+
+
+class UsageReportRow(BaseModel):
+ token_id: str | None
+ calls: int
+ prompt_tokens: int
+ completion_tokens: int
+ total_tokens: int
+ est_cost: float
+
+
+# --------------------------------------------------------------------------
+# Auth dependency
+# --------------------------------------------------------------------------
+
+
+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)")
+ header = request.headers.get("authorization", "")
+ prefix = "bearer "
+ presented = header[len(prefix):].strip() if header.lower().startswith(prefix) else ""
+ if not presented or not hmac.compare_digest(presented, admin_key):
+ raise HTTPException(status_code=401, detail="admin auth required")
+
+
+# --------------------------------------------------------------------------
+# Router
+# --------------------------------------------------------------------------
+
+
+def build_admin_router() -> APIRouter:
+ router = APIRouter(prefix="/admin", dependencies=[Depends(_require_admin)])
+
+ @router.post("/tokens", response_model=IssueTokenResponse)
+ def issue_token(body: IssueTokenRequest, request: Request) -> IssueTokenResponse:
+ tokens: TokenStore = request.app.state.tokens
+ issued = tokens.issue(body.label)
+ return IssueTokenResponse(
+ id=issued.id, label=issued.label, token=issued.plaintext
+ )
+
+ @router.get("/tokens", response_model=list[TokenInfo])
+ def list_tokens(request: Request) -> list[TokenInfo]:
+ tokens: TokenStore = request.app.state.tokens
+ return [
+ TokenInfo(
+ id=str(r["id"]),
+ label=str(r["label"]),
+ created_at=int(r["created_at"]),
+ revoked_at=(
+ int(r["revoked_at"]) if r["revoked_at"] is not None else None
+ ),
+ )
+ for r in tokens.list()
+ ]
+
+ @router.delete("/tokens/{token_id}")
+ def revoke_token(token_id: str, request: Request) -> dict[str, object]:
+ tokens: TokenStore = request.app.state.tokens
+ ok = tokens.revoke(token_id)
+ if not ok:
+ raise HTTPException(status_code=404, detail="unknown token id")
+ return {"revoked": True, "id": token_id}
+
+ @router.get("/usage", response_model=list[UsageReportRow])
+ def usage_report(
+ request: Request,
+ token_id: str | None = Query(default=None),
+ since: int | None = Query(default=None),
+ until: int | None = Query(default=None),
+ ) -> list[UsageReportRow]:
+ usage: UsageStore = request.app.state.usage
+ rows = usage.report(token_id=token_id, since=since, until=until)
+ return [
+ UsageReportRow(
+ token_id=r["token_id"],
+ calls=int(r["calls"]),
+ prompt_tokens=int(r["prompt_tokens"]),
+ completion_tokens=int(r["completion_tokens"]),
+ total_tokens=int(r["total_tokens"]),
+ est_cost=float(r["est_cost"]),
+ )
+ for r in rows
+ ]
+
+ return router
diff --git a/keyproxy/app.py b/keyproxy/app.py
new file mode 100644
index 0000000000..2bd97d4ec7
--- /dev/null
+++ b/keyproxy/app.py
@@ -0,0 +1,125 @@
+"""FastAPI application factory for the keyproxy service.
+
+:func:`create_app` builds the app, wiring the config / token store / usage store
+/ outbound httpx client onto ``app.state`` (all injectable so tests can supply
+an in-memory store and a fake upstream). It mounts:
+
+ - ``GET /healthz`` — open liveness probe.
+ - ``/admin/*`` — bearer-guarded admin surface.
+ - ``/p/{provider_id}/{path:path}`` — the generic streaming passthrough
+ (all HTTP methods).
+
+Boot-time HTTPS posture (§6): the proxy authenticates clients with bearer
+tokens, which must not travel over plaintext HTTP. Since TLS is terminated by
+the platform/reverse-proxy (not by this process), the operator asserts that with
+``KEYPROXY_TLS_TERMINATED=1``. If neither that nor ``KEYPROXY_ALLOW_INSECURE=1``
+is set, :func:`build_app_from_env` refuses to start.
+"""
+
+from __future__ import annotations
+
+import os
+from collections.abc import AsyncIterator
+from contextlib import asynccontextmanager
+
+import httpx
+from fastapi import FastAPI, Request, Response
+
+from .admin import build_admin_router
+from .config import ProxyConfig, load_config
+from .passthrough import handle_passthrough
+from .store import Store, default_db_path
+from .tokens import TokenStore
+from .usage import UsageStore
+
+_ALL_METHODS = ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS", "HEAD"]
+
+
+class InsecureStartupError(RuntimeError):
+ """Raised when token auth would run over plaintext HTTP without an opt-out."""
+
+
+def create_app(
+ *,
+ config: ProxyConfig,
+ tokens: TokenStore,
+ usage: UsageStore,
+ upstream: httpx.AsyncClient,
+) -> FastAPI:
+ """Build the app from explicit dependencies (the test + composition seam)."""
+
+ @asynccontextmanager
+ async def lifespan(app: FastAPI) -> AsyncIterator[None]:
+ yield
+ await app.state.upstream.aclose()
+
+ app = FastAPI(title="keyproxy", version="0.1.0", lifespan=lifespan)
+ app.state.config = config
+ app.state.tokens = tokens
+ app.state.usage = usage
+ app.state.upstream = upstream
+
+ @app.get("/healthz")
+ def healthz() -> dict[str, object]:
+ return {
+ "status": "ok",
+ "providers": config.configured_providers(),
+ }
+
+ app.include_router(build_admin_router())
+
+ # One generic handler for every method on the passthrough path. Registered
+ # explicitly per-method so OPTIONS/HEAD also route here.
+ async def _passthrough(request: Request, provider_id: str, path: str) -> Response:
+ return await handle_passthrough(request, provider_id, path)
+
+ app.add_api_route(
+ "/p/{provider_id}/{path:path}",
+ _passthrough,
+ methods=_ALL_METHODS,
+ include_in_schema=False,
+ )
+
+ return app
+
+
+def _https_posture_ok(cfg: ProxyConfig, env: dict[str, str]) -> bool:
+ """True when it is safe to serve token auth (TLS in front, or dev opt-out)."""
+ if cfg.allow_insecure:
+ return True
+ flag = (env.get("KEYPROXY_TLS_TERMINATED") or "").strip().lower()
+ return flag in {"1", "true", "yes", "on"}
+
+
+def build_app_from_env(env: dict[str, str] | None = None) -> FastAPI:
+ """Production entry point — load config from ENV and refuse insecure boot."""
+ src = os.environ if env is None else env
+ cfg = load_config(src)
+
+ if not _https_posture_ok(cfg, src):
+ raise InsecureStartupError(
+ "Refusing to start: token auth requires TLS in front of the proxy. "
+ "Set KEYPROXY_TLS_TERMINATED=1 once TLS is terminated by your "
+ "platform/reverse-proxy, or KEYPROXY_ALLOW_INSECURE=1 for local dev."
+ )
+
+ db_path = (src.get("KEYPROXY_DB_PATH") or "").strip() or str(default_db_path())
+ store = Store(db_path)
+ tokens = TokenStore(store)
+ usage = UsageStore(store)
+ upstream = httpx.AsyncClient(timeout=httpx.Timeout(300.0, connect=10.0))
+ return create_app(config=cfg, tokens=tokens, usage=usage, upstream=upstream)
+
+
+# Module-level ASGI app for ``uvicorn keyproxy.app:app``. Built lazily so that
+# importing the module (e.g. for tests) never triggers the insecure-boot guard.
+_app: FastAPI | None = None
+
+
+def __getattr__(name: str) -> object:
+ if name == "app":
+ global _app
+ if _app is None:
+ _app = build_app_from_env()
+ return _app
+ raise AttributeError(name)
diff --git a/keyproxy/cli.py b/keyproxy/cli.py
new file mode 100644
index 0000000000..6c59fd0500
--- /dev/null
+++ b/keyproxy/cli.py
@@ -0,0 +1,147 @@
+"""Admin CLI — issue-token / list-tokens / revoke / usage.
+
+Operates directly on the SQLite store (no HTTP), for on-box administration:
+
+ python -m keyproxy.cli issue-token --label alice
+ python -m keyproxy.cli list-tokens
+ python -m keyproxy.cli revoke <token-id>
+ python -m keyproxy.cli usage [--token <id>] [--since <unix>] [--until <unix>]
+
+The DB path comes from ``--db`` or ``KEYPROXY_DB_PATH`` (default
+``~/.keyproxy/keyproxy.sqlite``). The plaintext token is printed ONCE by
+``issue-token`` and is unrecoverable afterwards.
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import os
+import sys
+from collections.abc import Sequence
+
+from .store import Store, default_db_path
+from .tokens import TokenStore
+from .usage import UsageStore
+
+
+def _resolve_db_path(arg_db: str | None) -> str:
+ if arg_db:
+ return arg_db
+ env = (os.environ.get("KEYPROXY_DB_PATH") or "").strip()
+ return env or str(default_db_path())
+
+
+def _build_parser() -> argparse.ArgumentParser:
+ parser = argparse.ArgumentParser(
+ prog="keyproxy", description="keyproxy admin CLI"
+ )
+ parser.add_argument(
+ "--db",
+ default=None,
+ help="SQLite path (default: $KEYPROXY_DB_PATH or ~/.keyproxy/keyproxy.sqlite)",
+ )
+ parser.add_argument(
+ "--json", action="store_true", help="emit machine-readable JSON"
+ )
+ sub = parser.add_subparsers(dest="command", required=True)
+
+ issue = sub.add_parser("issue-token", help="issue a new per-user token")
+ issue.add_argument("--label", required=True, help="human label for the token")
+
+ sub.add_parser("list-tokens", help="list all tokens (active + revoked)")
+
+ revoke = sub.add_parser("revoke", help="revoke a token by id")
+ revoke.add_argument("token_id", help="the token id to revoke")
+
+ usage = sub.add_parser("usage", help="per-token usage report")
+ usage.add_argument("--token", default=None, help="filter by token id")
+ usage.add_argument("--since", type=int, default=None, help="unix seconds lower bound")
+ usage.add_argument("--until", type=int, default=None, help="unix seconds upper bound")
+
+ return parser
+
+
+def main(argv: Sequence[str] | None = None) -> int:
+ # Windows cp1252 stdout safety for non-ASCII labels.
+ try:
+ sys.stdout.reconfigure(encoding="utf-8") # type: ignore[union-attr]
+ except (AttributeError, ValueError): # pragma: no cover - non-reconfigurable stream
+ pass
+
+ parser = _build_parser()
+ args = parser.parse_args(argv)
+ as_json = bool(args.json)
+
+ store = Store(_resolve_db_path(args.db))
+ try:
+ tokens = TokenStore(store)
+ usage = UsageStore(store)
+
+ if args.command == "issue-token":
+ issued = tokens.issue(args.label)
+ if as_json:
+ print(json.dumps({
+ "id": issued.id,
+ "label": issued.label,
+ "token": issued.plaintext,
+ }))
+ else:
+ print(f"id: {issued.id}")
+ print(f"label: {issued.label}")
+ print(f"token: {issued.plaintext}")
+ print("(store this token now — it cannot be shown again)")
+ return 0
+
+ if args.command == "list-tokens":
+ rows = [
+ {
+ "id": r["id"],
+ "label": r["label"],
+ "created_at": r["created_at"],
+ "revoked_at": r["revoked_at"],
+ }
+ for r in tokens.list()
+ ]
+ if as_json:
+ print(json.dumps(rows))
+ elif not rows:
+ print("(no tokens)")
+ else:
+ for r in rows:
+ state = "revoked" if r["revoked_at"] else "active"
+ print(f"{r['id']} {state:<7} {r['label']}")
+ return 0
+
+ if args.command == "revoke":
+ ok = tokens.revoke(args.token_id)
+ if as_json:
+ print(json.dumps({"revoked": ok, "id": args.token_id}))
+ else:
+ print("revoked" if ok else "unknown token id")
+ return 0 if ok else 1
+
+ if args.command == "usage":
+ rows = usage.report(
+ token_id=args.token, since=args.since, until=args.until
+ )
+ if as_json:
+ print(json.dumps(rows))
+ elif not rows:
+ print("(no usage)")
+ else:
+ for r in rows:
+ print(
+ f"{r['token_id'] or '(untracked)'} "
+ f"calls={r['calls']} total_tokens={r['total_tokens']} "
+ f"est_cost=${r['est_cost']:.6f}"
+ )
+ return 0
+ finally:
+ store.close()
+
+ return 2 # pragma: no cover - argparse enforces a valid subcommand
+
+
+if __name__ == "__main__": # pragma: no cover
+ raise SystemExit(main())
diff --git a/keyproxy/passthrough.py b/keyproxy/passthrough.py
new file mode 100644
index 0000000000..e38311b0e9
--- /dev/null
+++ b/keyproxy/passthrough.py
@@ -0,0 +1,212 @@
+"""The generic streaming reverse-proxy core.
+
+One handler serves ``/p/{provider_id}/{path:path}`` for every HTTP method:
+
+1. Extract the inbound per-user token per the vendor's credential rule.
+2. ``tokens.verify(token)`` — fail-closed 401 if missing / unknown / revoked.
+3. ``config.lookup(provider_id)`` -> (vendor, real_base, real_key); 404 if
+ unknown.
+4. Build the upstream request: target ``real_base.rstrip('/') + '/' + path``,
+ copy method / query (minus the gemini ``key``) / body, forward only an
+ allowlist of safe headers (hop-by-hop + inbound auth stripped), then set the
+ real credential per the vendor rule.
+5. Stream the upstream response back unchanged (status, headers, body).
+6. Best-effort ``usage.record(...)`` — a parse miss records null counts and
+ NEVER fails the response; metering does not block or alter the response.
+
+The handler is wired into the app by :func:`keyproxy.app.create_app`, which
+injects the outbound ``httpx.AsyncClient`` (so tests can supply a fake upstream)
+plus the token / usage / config dependencies.
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+import httpx
+from fastapi import Request, Response
+from fastapi.responses import JSONResponse, StreamingResponse
+
+from . import vendors
+from .config import ProxyConfig
+from .tokens import TokenStore
+from .usage import UsageStore
+
+# 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(
+ {
+ "connection",
+ "keep-alive",
+ "proxy-authenticate",
+ "proxy-authorization",
+ "te",
+ "trailer",
+ "transfer-encoding",
+ "upgrade",
+ }
+)
+_INBOUND_AUTH = frozenset({"authorization", "x-api-key", "x-goog-api-key"})
+# Never copy the inbound Host (it is the proxy host, not the vendor's) or the
+# request's content-length (httpx recomputes it for the new body).
+_DROP_REQUEST_HEADERS = _HOP_BY_HOP | _INBOUND_AUTH | {"host", "content-length"}
+# Hop-by-hop response headers + ones httpx/Starlette will set themselves.
+_DROP_RESPONSE_HEADERS = _HOP_BY_HOP | {"content-length", "content-encoding"}
+
+# Cap on the buffered body we keep for usage parsing; the streamed response to
+# the client is never capped. A response larger than this still streams fully;
+# we just stop accumulating the metering buffer.
+_USAGE_BUFFER_CAP = 1_000_000 # 1 MB
+
+
+def _safe_request_headers(headers: httpx.Headers | dict[str, str]) -> dict[str, str]:
+ out: dict[str, str] = {}
+ items = headers.items() if hasattr(headers, "items") else headers.items()
+ for key, value in items:
+ if key.lower() in _DROP_REQUEST_HEADERS:
+ continue
+ out[key] = value
+ return out
+
+
+def _safe_response_headers(headers: httpx.Headers) -> dict[str, str]:
+ out: dict[str, str] = {}
+ for key, value in headers.items():
+ if key.lower() in _DROP_RESPONSE_HEADERS:
+ continue
+ out[key] = value
+ return out
+
+
+async def handle_passthrough(
+ request: Request,
+ provider_id: str,
+ path: str,
+) -> Response:
+ config: ProxyConfig = request.app.state.config
+ tokens: TokenStore = request.app.state.tokens
+ usage: UsageStore = request.app.state.usage
+ upstream: httpx.AsyncClient = request.app.state.upstream
+
+ # We need the vendor before token extraction (extraction is vendor-shaped),
+ # but we must not reveal whether a provider exists before auth. Resolve the
+ # vendor from the wire contract first (this is public, non-secret info).
+ contract = vendors.resolve_provider(provider_id)
+
+ # Lower-case the inbound headers once for vendor extraction.
+ lower_headers = {k.lower(): v for k, v in request.headers.items()}
+ query_params = dict(request.query_params)
+
+ # If the provider is not in the wire contract at all, we cannot know which
+ # credential slot to read. Try every inbound slot so a valid token still
+ # authenticates (then we 404 the unknown provider).
+ if contract is not None:
+ vendor = contract[0]
+ token = vendors.extract_inbound_token(
+ vendor, lower_headers, query=query_params
+ )
+ else:
+ vendor = None
+ token = (
+ vendors.extract_inbound_token(
+ "openai_compatible", lower_headers, query=query_params
+ )
+ or vendors.extract_inbound_token(
+ "anthropic", lower_headers, query=query_params
+ )
+ or vendors.extract_inbound_token(
+ "gemini", lower_headers, query=query_params
+ )
+ )
+
+ # 2. Auth — fail closed.
+ token_id = tokens.verify(token)
+ if token_id is None:
+ return JSONResponse(
+ {"error": "invalid_token", "detail": "missing, unknown, or revoked token"},
+ status_code=401,
+ )
+
+ # 3. Provider lookup — 404 if unknown OR known-but-unkeyed.
+ looked = config.lookup(provider_id)
+ if looked is None:
+ return JSONResponse(
+ {"error": "unknown_provider", "detail": f"provider '{provider_id}' is not configured"},
+ status_code=404,
+ )
+ vendor, real_base, real_key = looked
+
+ # 4. Build the upstream request.
+ body = await request.body()
+ out_headers = _safe_request_headers(request.headers)
+ out_query = dict(query_params)
+ # Strip the inbound gemini ?key= before placement (defence in depth — the
+ # placement function also pops it).
+ out_headers, out_query = vendors.place_outbound_credential(
+ vendor, headers=out_headers, query=out_query, real_key=real_key
+ )
+
+ target_url = real_base.rstrip("/") + "/" + path.lstrip("/")
+
+ upstream_request = upstream.build_request(
+ request.method,
+ target_url,
+ params=out_query or None,
+ headers=out_headers,
+ content=body if body else None,
+ )
+
+ # 5. Stream the upstream response back.
+ try:
+ upstream_response = await upstream.send(upstream_request, stream=True)
+ 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).
+ return JSONResponse(
+ {"error": "upstream_unreachable", "detail": str(exc)},
+ status_code=502,
+ )
+
+ usage_buffer = bytearray()
+
+ async def body_iterator():
+ try:
+ async for chunk in upstream_response.aiter_raw():
+ if len(usage_buffer) < _USAGE_BUFFER_CAP:
+ usage_buffer.extend(chunk[: _USAGE_BUFFER_CAP - len(usage_buffer)])
+ yield chunk
+ finally:
+ await upstream_response.aclose()
+ # 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),
+ )
+
+ response_headers = _safe_response_headers(upstream_response.headers)
+ return StreamingResponse(
+ body_iterator(),
+ status_code=upstream_response.status_code,
+ headers=response_headers,
+ media_type=upstream_response.headers.get("content-type"),
+ )
+
+
+def _record_usage(
+ usage: UsageStore,
+ *,
+ token_id: str,
+ provider_id: str,
+ vendor: str,
+ body: bytes,
+) -> None:
+ parsed: Any = None
+ try:
+ parsed = vendors.parse_usage(vendor, body)
+ except Exception: # noqa: BLE001 — metering must never raise
+ parsed = None
+ usage.record(token_id=token_id, provider_id=provider_id, parsed=parsed)
diff --git a/keyproxy/store.py b/keyproxy/store.py
index 10c6ed6702..c6e1d4357c 100644
--- a/keyproxy/store.py
+++ b/keyproxy/store.py
@@ -52,7 +52,7 @@ class Store:
with self._lock:
self._conn.close()
- def __enter__(self) -> "Store":
+ def __enter__(self) -> Store:
return self
def __exit__(self, *_: Any) -> None:
diff --git a/keyproxy/tests/conftest.py b/keyproxy/tests/conftest.py
index 2412540ad7..c3f3edbec7 100644
--- a/keyproxy/tests/conftest.py
+++ b/keyproxy/tests/conftest.py
@@ -9,8 +9,55 @@ its own Dockerfile via the working directory). When the tests are invoked as
from __future__ import annotations
import sys
+from collections.abc import AsyncIterator
from pathlib import Path
+import httpx
+import pytest
+
_REPO_ROOT = Path(__file__).resolve().parents[2]
if str(_REPO_ROOT) not in sys.path:
sys.path.insert(0, str(_REPO_ROOT))
+
+
+def anyio_backend() -> str:
+ """Pin the ``@pytest.mark.anyio`` tests to asyncio (no trio dependency)."""
+ return "asyncio"
+
+
+class _AsyncByteStream(httpx.AsyncByteStream):
+ """A minimal real async stream so MockTransport responses are streamable.
+
+ ``httpx.Response(content=...)`` produces an already-consumed buffered stream,
+ which raises ``StreamConsumed`` under ``aiter_raw()``. A real vendor returns
+ a streaming body; this mirrors that so the proxy's streaming path is
+ exercised exactly as in production.
+ """
+
+ def __init__(self, chunks: list[bytes]) -> None:
+ self._chunks = chunks
+
+ async def __aiter__(self) -> AsyncIterator[bytes]:
+ for chunk in self._chunks:
+ yield chunk
+
+ async def aclose(self) -> None: # pragma: no cover - trivial
+ return None
+
+
+def stream_response(
+ status: int,
+ body: bytes,
+ *,
+ headers: dict[str, str] | None = None,
+ chunk_size: int = 0,
+) -> httpx.Response:
+ """Build a streamable ``httpx.Response`` for a MockTransport upstream."""
+ if chunk_size and chunk_size > 0:
+ chunks = [body[i : i + chunk_size] for i in range(0, len(body), chunk_size)]
+ else:
+ chunks = [body] if body else []
+ return httpx.Response(
+ status, stream=_AsyncByteStream(chunks), headers=headers or {}
+ )
diff --git a/keyproxy/tests/test_admin.py b/keyproxy/tests/test_admin.py
new file mode 100644
index 0000000000..5dd5d6fb5f
--- /dev/null
+++ b/keyproxy/tests/test_admin.py
@@ -0,0 +1,138 @@
+"""Admin endpoints — issue/list/revoke tokens + usage report, bearer-guarded."""
+
+from __future__ import annotations
+
+import httpx
+import pytest
+
+from keyproxy.app import create_app
+from keyproxy.config import ProxyConfig
+from keyproxy.store import Store
+from keyproxy.tokens import TokenStore
+from keyproxy.usage import UsageStore
+from keyproxy.vendors import ParsedUsage
+
+ADMIN = "admin-secret"
+
+
+def build_app():
+ store = Store(":memory:")
+ tokens = TokenStore(store)
+ usage = UsageStore(store)
+ cfg = ProxyConfig(
+ providers={
+ "openai": ("openai_compatible", "https://api.openai.com/v1", "sk-REAL"),
+ },
+ admin_key=ADMIN,
+ 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)
+ return app, tokens, usage
+
+
+def client_for(app) -> httpx.AsyncClient:
+ return httpx.AsyncClient(
+ transport=httpx.ASGITransport(app=app), base_url="http://proxy"
+ )
+
+
+def auth() -> dict[str, str]:
+ return {"authorization": f"Bearer {ADMIN}"}
+
+
+async def test_issue_token_returns_plaintext_once() -> None:
+ app, _tokens, _usage = build_app()
+ async with client_for(app) as c:
+ r = await c.post("/admin/tokens", headers=auth(), json={"label": "alice"})
+ assert r.status_code == 200
+ data = r.json()
+ assert data["label"] == "alice"
+ assert data["token"].startswith("kp_")
+ assert data["id"]
+
+
+async def test_admin_requires_bearer() -> None:
+ app, _tokens, _usage = build_app()
+ async with client_for(app) as c:
+ r = await c.post("/admin/tokens", json={"label": "alice"})
+ assert r.status_code == 401
+
+
+async def test_admin_rejects_wrong_bearer() -> None:
+ app, _tokens, _usage = build_app()
+ async with client_for(app) as c:
+ r = await c.get(
+ "/admin/tokens", headers={"authorization": "Bearer wrong"}
+ )
+ assert r.status_code == 401
+
+
+async def test_list_tokens_has_no_plaintext_or_hash() -> None:
+ app, tokens, _usage = build_app()
+ issued = tokens.issue("alice")
+ async with client_for(app) as c:
+ r = await c.get("/admin/tokens", headers=auth())
+ assert r.status_code == 200
+ rows = r.json()
+ assert len(rows) == 1
+ body = r.text
+ # Neither the plaintext nor the sha256 is exposed via the admin list.
+ assert issued.plaintext not in body
+ assert "token_sha256" not in body
+ assert rows[0]["id"] == issued.id
+
+
+async def test_revoke_token() -> None:
+ app, tokens, _usage = build_app()
+ issued = tokens.issue("alice")
+ async with client_for(app) as c:
+ r = await c.delete(f"/admin/tokens/{issued.id}", headers=auth())
+ assert r.status_code == 200
+ assert r.json()["revoked"] is True
+ assert tokens.verify(issued.plaintext) is None
+
+
+async def test_revoke_unknown_404() -> None:
+ app, _tokens, _usage = build_app()
+ async with client_for(app) as c:
+ r = await c.delete("/admin/tokens/nope", headers=auth())
+ assert r.status_code == 404
+
+
+async def test_usage_report() -> None:
+ app, tokens, usage = build_app()
+ issued = tokens.issue("alice")
+ usage.record(
+ token_id=issued.id,
+ provider_id="openai",
+ parsed=ParsedUsage("gpt-4o-mini", 10, 20, 30),
+ )
+ async with client_for(app) as c:
+ r = await c.get("/admin/usage", headers=auth())
+ assert r.status_code == 200
+ rows = r.json()
+ assert len(rows) == 1
+ assert rows[0]["token_id"] == issued.id
+ assert rows[0]["calls"] == 1
+ assert rows[0]["total_tokens"] == 30
+
+
+async def test_healthz_is_open() -> 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"
diff --git a/keyproxy/tests/test_app_boot.py b/keyproxy/tests/test_app_boot.py
new file mode 100644
index 0000000000..df50a8af1a
--- /dev/null
+++ b/keyproxy/tests/test_app_boot.py
@@ -0,0 +1,47 @@
+"""Boot-time HTTPS posture + ENV-driven app construction."""
+
+from __future__ import annotations
+
+import pytest
+
+from keyproxy.app import (
+ InsecureStartupError,
+ _https_posture_ok,
+ build_app_from_env,
+)
+from keyproxy.config import load_config
+
+
+def _base_env() -> dict[str, str]:
+ return {
+ "KEYPROXY_ADMIN_KEY": "admin",
+ "KEYPROXY_OPENAI_KEY": "sk-real",
+ "KEYPROXY_DB_PATH": ":memory:",
+ }
+
+
+def test_refuses_insecure_boot_without_optout() -> None:
+ env = _base_env() # no TLS_TERMINATED, no ALLOW_INSECURE
+ with pytest.raises(InsecureStartupError):
+ build_app_from_env(env)
+
+
+def test_allows_boot_with_tls_terminated() -> None:
+ env = _base_env() | {"KEYPROXY_TLS_TERMINATED": "1"}
+ app = build_app_from_env(env)
+ assert app is not None
+
+
+def test_allows_boot_with_allow_insecure() -> None:
+ env = _base_env() | {"KEYPROXY_ALLOW_INSECURE": "1"}
+ app = build_app_from_env(env)
+ assert app is not None
+
+
+def test_https_posture_helper() -> None:
+ cfg = load_config(_base_env())
+ assert _https_posture_ok(cfg, _base_env()) is False
+ assert _https_posture_ok(cfg, {"KEYPROXY_TLS_TERMINATED": "true"}) is True
+
+ insecure_cfg = load_config(_base_env() | {"KEYPROXY_ALLOW_INSECURE": "1"})
+ assert _https_posture_ok(insecure_cfg, {}) is True
diff --git a/keyproxy/tests/test_cli.py b/keyproxy/tests/test_cli.py
new file mode 100644
index 0000000000..c88a59c301
--- /dev/null
+++ b/keyproxy/tests/test_cli.py
@@ -0,0 +1,60 @@
+"""CLI smoke tests against a temp-file DB (the CLI opens its own store)."""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+import pytest
+
+from keyproxy import cli
+
+
+def db(tmp_path: Path) -> str:
+ return str(tmp_path / "keyproxy.sqlite")
+
+
+def test_issue_then_list_then_revoke(db: str, capsys: pytest.CaptureFixture) -> None:
+ rc = cli.main(["--db", db, "--json", "issue-token", "--label", "alice"])
+ assert rc == 0
+ issued = json.loads(capsys.readouterr().out)
+ assert issued["label"] == "alice"
+ assert issued["token"].startswith("kp_")
+ token_id = issued["id"]
+
+ rc = cli.main(["--db", db, "--json", "list-tokens"])
+ assert rc == 0
+ rows = json.loads(capsys.readouterr().out)
+ assert len(rows) == 1
+ assert rows[0]["id"] == token_id
+ assert rows[0]["revoked_at"] is None
+
+ rc = cli.main(["--db", db, "--json", "revoke", token_id])
+ assert rc == 0
+ assert json.loads(capsys.readouterr().out)["revoked"] is True
+
+ # After revoke it still lists, now with a revoked_at timestamp.
+ cli.main(["--db", db, "--json", "list-tokens"])
+ rows = json.loads(capsys.readouterr().out)
+ assert rows[0]["revoked_at"] is not None
+
+
+def test_revoke_unknown_returns_nonzero(db: str, capsys: pytest.CaptureFixture) -> None:
+ rc = cli.main(["--db", db, "--json", "revoke", "no-such-id"])
+ assert rc == 1
+ assert json.loads(capsys.readouterr().out)["revoked"] is False
+
+
+def test_usage_report_empty(db: str, capsys: pytest.CaptureFixture) -> None:
+ rc = cli.main(["--db", db, "--json", "usage"])
+ assert rc == 0
+ assert json.loads(capsys.readouterr().out) == []
+
+
+def test_human_readable_issue(db: str, capsys: pytest.CaptureFixture) -> None:
+ rc = cli.main(["--db", db, "issue-token", "--label", "bob"])
+ assert rc == 0
+ out = capsys.readouterr().out
+ assert "token: kp_" in out
+ assert "cannot be shown again" in out
diff --git a/keyproxy/tests/test_parity.py b/keyproxy/tests/test_parity.py
new file mode 100644
index 0000000000..6ed438133e
--- /dev/null
+++ b/keyproxy/tests/test_parity.py
@@ -0,0 +1,65 @@
+"""Anti-drift parity (§7) for the provider->vendor wire contract.
+
+``PROVIDER_VENDORS`` is a wire-format vocabulary shared across the client config,
+the proxy, the usage rows, and the UI. This freezes the canonical expectation so
+any drift in the proxy's table (a provider added/removed/re-vendored, or a base
+URL changed) fails loudly here — the proxy-side half of the five-layer parity
+pattern. The client side carries the mirror of this same EXPECTED table.
+"""
+
+from __future__ import annotations
+
+from keyproxy import vendors
+
+# The canonical wire contract — must match the client side EXACTLY.
+EXPECTED_PROVIDER_VENDORS: dict[str, tuple[str, str]] = {
+ "claude-api": ("anthropic", "https://api.anthropic.com"),
+ "openai": ("openai_compatible", "https://api.openai.com/v1"),
+ "openrouter": ("openai_compatible", "https://openrouter.ai/api/v1"),
+ "grok": ("openai_compatible", "https://api.x.ai/v1"),
+ "gemini": ("gemini", "https://generativelanguage.googleapis.com"),
+ "groq-api": ("openai_compatible", "https://api.groq.com/openai/v1"),
+}
+
+
+def test_provider_vendor_map_matches_wire_contract() -> None:
+ assert vendors.PROVIDER_VENDORS == EXPECTED_PROVIDER_VENDORS
+
+
+def test_every_provider_vendor_is_known() -> None:
+ used = {vendor for vendor, _base in vendors.PROVIDER_VENDORS.values()}
+ assert used <= vendors.KNOWN_VENDORS
+
+
+def test_every_known_vendor_handles_all_three_concerns() -> None:
+ """extract / place / parse must each understand every known vendor."""
+ for vendor in vendors.KNOWN_VENDORS:
+ # extraction: an inbound credential slot exists for the vendor.
+ extracted = (
+ vendors.extract_inbound_token(
+ vendor, {"authorization": "Bearer t"}, query={}
+ )
+ or vendors.extract_inbound_token(vendor, {"x-api-key": "t"}, query={})
+ or vendors.extract_inbound_token(
+ vendor, {"x-goog-api-key": "t"}, query={}
+ )
+ )
+ assert extracted == "t", f"no inbound extraction for vendor {vendor!r}"
+
+ # placement: the real key lands somewhere on the outbound request.
+ headers, query = vendors.place_outbound_credential(
+ vendor, headers={}, query={}, real_key="REAL"
+ )
+ placed = any("REAL" in v for v in headers.values()) or any(
+ "REAL" in v for v in query.values()
+ )
+ assert placed, f"no outbound placement for vendor {vendor!r}"
+
+ # parse: a parse miss returns None (not an exception) for the vendor.
+ assert vendors.parse_usage(vendor, b"") is None
+
+
+def test_no_unexpected_providers_present() -> None:
+ # Guards against a provider being added to the proxy without updating the
+ # client mirror (and this expectation).
+ assert set(vendors.PROVIDER_VENDORS) == set(EXPECTED_PROVIDER_VENDORS)
diff --git a/keyproxy/tests/test_passthrough.py b/keyproxy/tests/test_passthrough.py
new file mode 100644
index 0000000000..8327971858
--- /dev/null
+++ b/keyproxy/tests/test_passthrough.py
@@ -0,0 +1,353 @@
+"""End-to-end passthrough behaviour against a FAKE upstream.
+
+The app's outbound ``httpx.AsyncClient`` is injected with an
+``httpx.MockTransport`` so no real vendor is contacted. We drive the app itself
+via ``httpx.ASGITransport``.
+"""
+
+from __future__ import annotations
+
+import json
+
+import httpx
+import pytest
+
+from keyproxy.app import create_app
+from keyproxy.config import ProxyConfig
+from keyproxy.store import Store
+from keyproxy.tokens import TokenStore
+from keyproxy.usage import UsageStore
+
+from .conftest import stream_response
+
+
+def _json_stream(status: int, obj: dict, **kw) -> httpx.Response:
+ return stream_response(
+ status,
+ json.dumps(obj).encode(),
+ headers={"content-type": "application/json"},
+ **kw,
+ )
+
+
+# --------------------------------------------------------------------------
+# Test harness: an app wired to an in-memory store + a programmable upstream.
+# --------------------------------------------------------------------------
+
+
+def build_harness(upstream_handler, *, providers=None, allow_insecure=True):
+ """Return (app, token_store, usage_store, captured) wired to a fake upstream.
+
+ ``captured`` is a list the upstream handler appends each received request to,
+ so a test can assert on the outbound request the proxy built.
+ """
+ store = Store(":memory:")
+ tokens = TokenStore(store)
+ usage = UsageStore(store)
+ cfg = ProxyConfig(
+ providers=providers
+ or {
+ "openai": (
+ "openai_compatible",
+ "https://api.openai.com/v1",
+ "sk-REAL-OPENAI",
+ ),
+ "claude-api": (
+ "anthropic",
+ "https://api.anthropic.com",
+ "sk-ant-REAL",
+ ),
+ "gemini": (
+ "gemini",
+ "https://generativelanguage.googleapis.com",
+ "REAL-GEMINI",
+ ),
+ },
+ admin_key="admin-secret",
+ allow_insecure=allow_insecure,
+ )
+ upstream = httpx.AsyncClient(transport=httpx.MockTransport(upstream_handler))
+ app = create_app(config=cfg, tokens=tokens, usage=usage, upstream=upstream)
+ return app, tokens, usage
+
+
+def client_for(app) -> httpx.AsyncClient:
+ return httpx.AsyncClient(
+ transport=httpx.ASGITransport(app=app), base_url="http://proxy"
+ )
+
+
+# --------------------------------------------------------------------------
+# Fail-closed auth / provider
+# --------------------------------------------------------------------------
+
+
+async def test_missing_token_is_401() -> None:
+ def upstream(_req: httpx.Request) -> httpx.Response:
+ return _json_stream(200, {"ok": True})
+
+ app, _tokens, _usage = build_harness(upstream)
+ async with client_for(app) as c:
+ r = await c.post("/p/openai/chat/completions", json={"x": 1})
+ assert r.status_code == 401
+
+
+async def test_bad_token_is_401() -> None:
+ def upstream(_req: httpx.Request) -> httpx.Response:
+ return _json_stream(200, {"ok": True})
+
+ app, _tokens, _usage = build_harness(upstream)
+ async with client_for(app) as c:
+ r = await c.post(
+ "/p/openai/chat/completions",
+ headers={"authorization": "Bearer kp_not_real"},
+ json={"x": 1},
+ )
+ assert r.status_code == 401
+
+
+async def test_revoked_token_is_401() -> None:
+ def upstream(_req: httpx.Request) -> httpx.Response:
+ return _json_stream(200, {"ok": True})
+
+ app, tokens, _usage = build_harness(upstream)
+ issued = tokens.issue("alice")
+ tokens.revoke(issued.id)
+ async with client_for(app) as c:
+ r = await c.post(
+ "/p/openai/chat/completions",
+ headers={"authorization": f"Bearer {issued.plaintext}"},
+ json={"x": 1},
+ )
+ assert r.status_code == 401
+
+
+async def test_unknown_provider_is_404() -> None:
+ 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:
+ r = await c.post(
+ "/p/no-such-provider/x",
+ headers={"authorization": f"Bearer {issued.plaintext}"},
+ json={"x": 1},
+ )
+ assert r.status_code == 404
+
+
+# --------------------------------------------------------------------------
+# Credential swap + header hygiene (openai_compatible)
+# --------------------------------------------------------------------------
+
+
+async def test_real_key_swapped_and_inbound_token_stripped() -> None:
+ captured: list[httpx.Request] = []
+
+ def upstream(req: httpx.Request) -> httpx.Response:
+ captured.append(req)
+ return _json_stream(200, {"ok": True})
+
+ 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 == 200
+ assert len(captured) == 1
+ out = captured[0]
+ # Real key is set; the inbound proxy token is gone.
+ assert out.headers["authorization"] == "Bearer sk-REAL-OPENAI"
+ assert issued.plaintext not in out.headers["authorization"]
+ # Target URL is real_base + "/" + path.
+ assert str(out.url) == "https://api.openai.com/v1/chat/completions"
+ # Body is forwarded unchanged.
+ assert json.loads(out.content) == {"model": "gpt-4o-mini"}
+
+
+async def test_hop_by_hop_headers_dropped() -> None:
+ captured: list[httpx.Request] = []
+
+ def upstream(req: httpx.Request) -> httpx.Response:
+ captured.append(req)
+ return _json_stream(200, {"ok": True})
+
+ app, tokens, _usage = build_harness(upstream)
+ issued = tokens.issue("alice")
+ async with client_for(app) as c:
+ await c.post(
+ "/p/openai/chat/completions",
+ headers={
+ "authorization": f"Bearer {issued.plaintext}",
+ # ``te`` is a hop-by-hop header that httpx does NOT re-add on the
+ # outbound connection, so its absence proves our stripping.
+ "te": "trailers",
+ "x-custom-app-header": "keep-me",
+ },
+ json={"model": "gpt-4o-mini"},
+ )
+ out = captured[0]
+ lower = {k.lower() for k in out.headers}
+ assert "te" not in lower
+ # The inbound auth header must never reach the upstream verbatim.
+ assert out.headers.get("authorization") == "Bearer sk-REAL-OPENAI"
+ # A non-hop-by-hop custom header is allowed through.
+ assert out.headers.get("x-custom-app-header") == "keep-me"
+
+
+# --------------------------------------------------------------------------
+# anthropic + gemini credential placement
+# --------------------------------------------------------------------------
+
+
+async def test_anthropic_x_api_key_swap() -> None:
+ captured: list[httpx.Request] = []
+
+ def upstream(req: httpx.Request) -> httpx.Response:
+ captured.append(req)
+ return _json_stream(200, {"ok": True})
+
+ app, tokens, _usage = build_harness(upstream)
+ issued = tokens.issue("alice")
+ async with client_for(app) as c:
+ await c.post(
+ "/p/claude-api/v1/messages",
+ headers={"x-api-key": issued.plaintext},
+ json={"model": "claude-3-5-sonnet"},
+ )
+ out = captured[0]
+ assert out.headers["x-api-key"] == "sk-ant-REAL"
+ assert str(out.url) == "https://api.anthropic.com/v1/messages"
+
+
+async def test_gemini_query_key_swapped_to_header() -> None:
+ captured: list[httpx.Request] = []
+
+ def upstream(req: httpx.Request) -> httpx.Response:
+ captured.append(req)
+ return _json_stream(200, {"ok": True})
+
+ app, tokens, _usage = build_harness(upstream)
+ issued = tokens.issue("alice")
+ async with client_for(app) as c:
+ await c.post(
+ f"/p/gemini/v1beta/models/gemini-2.0-flash:generateContent?key={issued.plaintext}",
+ json={"contents": []},
+ )
+ out = captured[0]
+ # The inbound ?key= (the proxy token) must NOT reach Google.
+ assert "key" not in dict(out.url.params)
+ assert out.headers["x-goog-api-key"] == "REAL-GEMINI"
+
+
+# --------------------------------------------------------------------------
+# Streaming round-trip + usage row
+# --------------------------------------------------------------------------
+
+
+async def test_streamed_completion_round_trips_and_records_usage() -> None:
+ sse = (
+ b'data: {"model":"gpt-4o-mini","choices":[{"delta":{"content":"hi"}}]}\n\n'
+ b'data: {"model":"gpt-4o-mini","usage":{"prompt_tokens":5,'
+ b'"completion_tokens":7,"total_tokens":12}}\n\n'
+ b"data: [DONE]\n\n"
+ )
+
+ def upstream(_req: httpx.Request) -> httpx.Response:
+ # chunk_size forces a multi-chunk body so the streaming path (not a
+ # single buffered write) is exercised.
+ return stream_response(
+ 200,
+ sse,
+ headers={"content-type": "text/event-stream"},
+ chunk_size=16,
+ )
+
+ 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", "stream": True},
+ )
+ assert r.status_code == 200
+ assert r.content == sse # body round-trips unchanged
+ assert r.headers["content-type"] == "text/event-stream"
+
+ rows = usage.recent()
+ assert len(rows) == 1
+ assert rows[0]["token_id"] == issued.id
+ assert rows[0]["provider_id"] == "openai"
+ assert rows[0]["prompt_tokens"] == 5
+ assert rows[0]["completion_tokens"] == 7
+ assert rows[0]["total_tokens"] == 12
+
+
+async def test_upstream_error_status_passes_through() -> None:
+ def upstream(_req: httpx.Request) -> httpx.Response:
+ return _json_stream(429, {"error": "rate limited"})
+
+ 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 == 429
+ assert r.json() == {"error": "rate limited"}
+
+
+async def test_usage_parse_miss_still_records_row() -> None:
+ def upstream(_req: httpx.Request) -> httpx.Response:
+ return stream_response(200, b"not parseable")
+
+ 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 == 200
+ rows = usage.recent()
+ assert len(rows) == 1
+ assert rows[0]["prompt_tokens"] is None
+
+
+async def test_get_method_round_trips() -> None:
+ captured: list[httpx.Request] = []
+
+ def upstream(req: httpx.Request) -> httpx.Response:
+ captured.append(req)
+ return _json_stream(200, {"data": ["model-a"]})
+
+ app, tokens, _usage = build_harness(upstream)
+ issued = tokens.issue("alice")
+ async with client_for(app) as c:
+ r = await c.get(
+ "/p/openai/models",
+ headers={"authorization": f"Bearer {issued.plaintext}"},
+ )
+ assert r.status_code == 200
+ assert captured[0].method == "GET"
+ assert str(captured[0].url) == "https://api.openai.com/v1/models"
diff --git a/keyproxy/tests/test_usage.py b/keyproxy/tests/test_usage.py
index a772c49cd5..516d37c416 100644
--- a/keyproxy/tests/test_usage.py
+++ b/keyproxy/tests/test_usage.py
@@ -1,5 +1,6 @@
"""usage.py — record best-effort usage rows + per-token/period report."""
+# ruff: noqa: S105, S106 — fixture "token_id" values are opaque ids, not secrets
from __future__ import annotations
import time
diff --git a/keyproxy/tests/test_vendors.py b/keyproxy/tests/test_vendors.py
index 53dc08c443..202cfec13b 100644
--- a/keyproxy/tests/test_vendors.py
+++ b/keyproxy/tests/test_vendors.py
@@ -1,14 +1,12 @@
"""vendors.py — provider->vendor map + credential extraction/placement + usage."""
+# ruff: noqa: S105 — fixture "token" values are fake inbound tokens, not secrets
from __future__ import annotations
import json
-import pytest
-
from keyproxy import vendors
-
# --------------------------------------------------------------------------
# provider_id -> vendor wire contract (must match the client side exactly)
# --------------------------------------------------------------------------
diff --git a/keyproxy/tokens.py b/keyproxy/tokens.py
index d412850c8a..9bda971ac4 100644
--- a/keyproxy/tokens.py
+++ b/keyproxy/tokens.py
@@ -23,7 +23,7 @@ from .store import Store
# Issued plaintext tokens carry a recognizable, non-secret prefix so they can
# be spotted in client config; the entropy lives in the random suffix.
-_TOKEN_PREFIX = "kp_"
+_TOKEN_PREFIX = "kp_" # noqa: S105 — a public label prefix, not a secret
_TOKEN_ENTROPY_BYTES = 32 # 256 bits
diff --git a/keyproxy/usage.py b/keyproxy/usage.py
index 9dc8442f39..5c5e458992 100644
--- a/keyproxy/usage.py
+++ b/keyproxy/usage.py
@@ -101,7 +101,7 @@ class UsageStore:
ts if ts is not None else int(time.time()),
),
)
- except Exception: # noqa: BLE001 — metering must never fail the request
+ except Exception: # noqa: BLE001, S110 — metering must never fail the request
pass
# ------------------------------------------------------------------
@@ -136,15 +136,15 @@ class UsageStore:
params.append(until)
clause = (" WHERE " + " AND ".join(where)) if where else ""
# ``clause`` is built only from static literal fragments; all values are
- # bound parameters.
+ # bound parameters, so this is not an injection vector.
sql = (
- "SELECT token_id, COUNT(*) AS calls, "
+ "SELECT token_id, COUNT(*) AS calls, " # noqa: S608
"COALESCE(SUM(prompt_tokens), 0) AS prompt_tokens, "
"COALESCE(SUM(completion_tokens), 0) AS completion_tokens, "
"COALESCE(SUM(total_tokens), 0) AS total_tokens, "
"COALESCE(SUM(est_cost), 0.0) AS est_cost "
f"FROM usage{clause} "
- "GROUP BY token_id ORDER BY total_tokens DESC" # noqa: S608
+ "GROUP BY token_id ORDER BY total_tokens DESC"
)
rows = self._store.query_all(sql, tuple(params))
return [dict(r) for r in rows]