feat(api): require api_key when binding to all interfaces (parity with WS gateway)

The OpenAI-compatible API server had no authentication option, unlike the
WebSocket gateway which already refuses wildcard binds without a token.
When bound to 0.0.0.0, any caller who could reach the port could drive
the agent with its default tool posture.

- Add api_key field to ApiConfig (schema.py).
- Add wildcard_host_requires_auth validator that rejects wildcard binds
  without api_key, mirroring the WS gateway pattern.
- Add Bearer-token auth middleware to the API server (server.py).
  /health remains unauthenticated.
- Replace the wildcard-host CLI warning with a hard error when api_key
  is unset, and pass api_key to create_app.

Fixes #4490
@
This commit is contained in:
dajiaohuang
2026-07-01 13:09:49 +08:00
committed by Xubin Ren
parent 21aa900d64
commit 56443ac6e2
3 changed files with 52 additions and 4 deletions
+12
View File
@@ -307,6 +307,18 @@ class ApiConfig(Base):
host: str = "127.0.0.1" # Safer default: local-only bind.
port: int = 8900
timeout: float = 120.0 # Per-request timeout in seconds.
api_key: str = Field(default="", repr=False)
@model_validator(mode="after")
def wildcard_host_requires_auth(self) -> "ApiConfig":
if self.host not in ("0.0.0.0", "::"):
return self
if self.api_key.strip():
return self
raise ValueError(
"host is 0.0.0.0 (all interfaces) but api_key is not set "
"- set api.api_key to prevent unauthenticated access"
)
class GatewayConfig(Base):