Repository navigation
feat(serve): --api-keys, --cors-origins and x-request-id - #68
pawelkiszczak wants to merge 1 commit into
Conversation
Reviewer's GuideIntroduces opt-in API-key protection for HTTP and MCP endpoints, with live-reloaded SHA-256 key files and admin usage inspection, while adding configurable CORS and consistent request-ID response headers. Client libraries and the MCP stdio bridge can now send bearer credentials; defaults preserve existing response bodies and leave /health open. Sequence diagram for API-key authenticated requestssequenceDiagram
participant Client
participant Middleware
participant ApiKeys
participant Server
Client->>Middleware: HTTP request with Bearer API key
Middleware->>ApiKeys: check(secret)
ApiKeys-->>Middleware: key record or None
alt valid key
Middleware->>ApiKeys: touch(name)
Middleware->>Server: forward request
Server-->>Middleware: response
Middleware-->>Client: response with x-request-id and x-typesafe-request-id
else missing or invalid key
Middleware-->>Client: 401 UNAUTHORIZED
end
Sequence diagram for admin key usage inspectionsequenceDiagram
participant AdminClient
participant Middleware
participant ApiKeys
AdminClient->>Middleware: GET /v1/keys with API key
Middleware->>ApiKeys: check(secret)
ApiKeys-->>Middleware: key record
alt admin key
Middleware->>ApiKeys: usage()
ApiKeys-->>Middleware: key names and last_used
Middleware-->>AdminClient: 200 key usage
else non-admin key
Middleware-->>AdminClient: 403 FORBIDDEN
end
Flow diagram for request ID handlingflowchart TD
Request[HTTP request]
Validate{Valid X-Request-Id?}
Echo[Reuse supplied request ID]
Generate[Generate req_hex ID]
Response[Add x-request-id and x-typesafe-request-id]
Request --> Validate
Validate -->|yes| Echo
Validate -->|no| Generate
Echo --> Response
Generate --> Response
File-Level Changes
Assessment against linked issues
Possibly linked issues
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
There was a problem hiding this comment.
Hey - I've found 4 issues
Prompt for AI Agents
Please address the comments from this code review:
## Individual Comments
### Comment 1
<location path="basal/server.py" line_range="1700" />
<code_context>
- app = http_app(srv, a.mode, mcp)
+ from .auth import ApiKeys, protect, request_ids
+ origins = [origin.strip() for origin in a.cors_origins.split(",") if origin.strip()]
+ app = request_ids(protect(http_app(srv, a.mode, mcp), ApiKeys(a.api_keys) if a.api_keys else None, origins))
try: # uvloop + httptools when available (uvicorn[standard]); plain asyncio otherwise
import httptools # noqa: F401
</code_context>
<issue_to_address>
**Empty key path disables authentication**
When the server is launched with `--api-keys ""`, `a.api_keys` is an empty string, so the truthiness check passes `None` to `protect` and starts the server without authentication. An explicitly supplied but empty `--api-keys` value therefore leaves every protected route open.
Distinguish `None` from an empty path and reject an empty value instead of disabling authentication.
</issue_to_address>
### Comment 2
<location path="basal/auth.py" line_range="83" />
<code_context>
+ record = None
+ if not open_health and keys is not None:
+ headers = dict(scope.get("headers", ()))
+ authorization = headers.get(b"authorization", b"").decode("latin1")
+ secret = authorization[7:].strip() if authorization.lower().startswith("bearer ") else ""
+ secret = headers.get(b"x-api-key", b"").decode("latin1") or secret
</code_context>
<issue_to_address>
**Bearer keys travel in cleartext**
When a keyed client accesses the server remotely over an untrusted network without a TLS-terminating proxy, the server accepts bearer credentials over its plaintext HTTP listener, so a network observer can capture and replay a key to access protected inference and MCP routes.
Require TLS for remote authenticated traffic, or clearly require a TLS-terminating proxy and limit direct HTTP use to trusted or loopback networks.
Also at `docs/MCP.md:32`.
</issue_to_address>
### Comment 3
<location path="basal/auth.py" line_range="121" />
<code_context>
+ await app(scope, receive, send)
+ return
+ supplied = dict(scope.get("headers", ())).get(b"x-request-id", b"").decode("latin1")
+ request_id = supplied if re.fullmatch(r"[A-Za-z0-9._:-]{1,128}", supplied) else f"req_{uuid.uuid4().hex}"
+
+ async def send_with_id(message):
</code_context>
<issue_to_address>
**Request IDs cannot find server errors**
When an HTTP request produces a server-side error, `http_app.failed()` logs the exception without the request ID, and `request_ids()` neither adds the ID to the ASGI scope nor connects it to logging. A caller gets an ID in the response but cannot use it to locate the corresponding server-side error.
Make the request ID available to the request handler and include it in server-side error logs.
</issue_to_address>
### Comment 4
<location path="tests/test_http_status.py" line_range="114" />
<code_context>
+
+ decorated = asyncio.run(go())
+ assert decorated.content == b'{"ok":true}'
+ assert decorated.headers["x-request-id"].startswith("req_")
+ supplied = asyncio.run(on_app(AppServer(Engine()), lambda c: c.get("/health", headers={"X-Request-Id": "trace-1"}),
+ decorate=lambda app: request_ids(protect(app, None))))
</code_context>
<issue_to_address>
**Malformed request IDs pass**
When the implementation generates a non-hex ID such as `req_invalid`, `test_request_ids_preserve_unprotected_response_bytes` accepts any value starting with `req_`, so a generated ID such as `req_invalid` passes even though it does not have the documented hex suffix.
Assert that the generated ID matches the full `req_<hex>` format.
</issue_to_address>| app = http_app(srv, a.mode, mcp) | ||
| from .auth import ApiKeys, protect, request_ids | ||
| origins = [origin.strip() for origin in a.cors_origins.split(",") if origin.strip()] | ||
| app = request_ids(protect(http_app(srv, a.mode, mcp), ApiKeys(a.api_keys) if a.api_keys else None, origins)) |
There was a problem hiding this comment.
🟠 High · Empty key path disables authentication
When the server is launched with --api-keys "", a.api_keys is an empty string, so the truthiness check passes None to protect and starts the server without authentication. An explicitly supplied but empty --api-keys value therefore leaves every protected route open.
Distinguish None from an empty path and reject an empty value instead of disabling authentication.
Prompt for AI agents
In `basal/server.py` at line 1700:
**Empty key path disables authentication**
When the server is launched with `--api-keys ""`, `a.api_keys` is an empty string, so the truthiness check passes `None` to `protect` and starts the server without authentication. An explicitly supplied but empty `--api-keys` value therefore leaves every protected route open.
Distinguish `None` from an empty path and reject an empty value instead of disabling authentication.| record = None | ||
| if not open_health and keys is not None: | ||
| headers = dict(scope.get("headers", ())) | ||
| authorization = headers.get(b"authorization", b"").decode("latin1") |
There was a problem hiding this comment.
🟡 Medium · Bearer keys travel in cleartext
When a keyed client accesses the server remotely over an untrusted network without a TLS-terminating proxy, the server accepts bearer credentials over its plaintext HTTP listener, so a network observer can capture and replay a key to access protected inference and MCP routes.
Require TLS for remote authenticated traffic, or clearly require a TLS-terminating proxy and limit direct HTTP use to trusted or loopback networks.
Also at docs/MCP.md:32.
Prompt for AI agents
In `basal/auth.py` at line 83:
**Bearer keys travel in cleartext**
When a keyed client accesses the server remotely over an untrusted network without a TLS-terminating proxy, the server accepts bearer credentials over its plaintext HTTP listener, so a network observer can capture and replay a key to access protected inference and MCP routes.
Require TLS for remote authenticated traffic, or clearly require a TLS-terminating proxy and limit direct HTTP use to trusted or loopback networks.
Also at `docs/MCP.md:32`.| await app(scope, receive, send) | ||
| return | ||
| supplied = dict(scope.get("headers", ())).get(b"x-request-id", b"").decode("latin1") | ||
| request_id = supplied if re.fullmatch(r"[A-Za-z0-9._:-]{1,128}", supplied) else f"req_{uuid.uuid4().hex}" |
There was a problem hiding this comment.
🟡 Medium · Request IDs cannot find server errors
When an HTTP request produces a server-side error, http_app.failed() logs the exception without the request ID, and request_ids() neither adds the ID to the ASGI scope nor connects it to logging. A caller gets an ID in the response but cannot use it to locate the corresponding server-side error.
Make the request ID available to the request handler and include it in server-side error logs.
Prompt for AI agents
In `basal/auth.py` at line 121:
**Request IDs cannot find server errors**
When an HTTP request produces a server-side error, `http_app.failed()` logs the exception without the request ID, and `request_ids()` neither adds the ID to the ASGI scope nor connects it to logging. A caller gets an ID in the response but cannot use it to locate the corresponding server-side error.
Make the request ID available to the request handler and include it in server-side error logs.|
|
||
| decorated = asyncio.run(go()) | ||
| assert decorated.content == b'{"ok":true}' | ||
| assert decorated.headers["x-request-id"].startswith("req_") |
There was a problem hiding this comment.
🟡 Medium · Malformed request IDs pass
When the implementation generates a non-hex ID such as req_invalid, test_request_ids_preserve_unprotected_response_bytes accepts any value starting with req_, so a generated ID such as req_invalid passes even though it does not have the documented hex suffix.
Assert that the generated ID matches the full req_<hex> format.
Prompt for AI agents
In `tests/test_http_status.py` at line 114:
**Malformed request IDs pass**
When the implementation generates a non-hex ID such as `req_invalid`, `test_request_ids_preserve_unprotected_response_bytes` accepts any value starting with `req_`, so a generated ID such as `req_invalid` passes even though it does not have the documented hex suffix.
Assert that the generated ID matches the full `req_<hex>` format.|
Thank you, Paweł! Planned for basal 2.5, with one change: we will take it in as a single squash commit in which responses carry only the standard |
|
Thank you, Paweł: this PR ships in basal 2.5.0, squashed into one commit (d9d4ceb) with the review changes. Closing it as merged in 2.5.0. |
Squashed from #68 (Paweł Kiszczak, closes #67), with one request-id header (x-request-id). GET /v1/keys is served only with --api-keys (404 without, as before); --mcp's help keeps the bind advice for servers without keys; SERVING.md notes that basal-router does not forward keys yet. Merged with 2.5: basal-serve's app keeps --error-format, basal-mcp takes --model and --api-key, the client's api_key comes from 2.5's client; tests of both sides kept.
… version CONTRIBUTING.md credits the 2.5 pull requests as the release notes' community line lists them (Paweł Kiszczak #52, #62, #64, #66, #68, #71, #73, #75; Marcin Brzeżański #56; Grzegorz Brzezinka #76, #78) and adds Dariusz Koryto (#53, #58, #59, #60 and #55); the README's list names him too. docs/changes/README.md and the changelog.py help use 2.5.1, the next release, as the example.
Closes #67
What
Added optional SHA-256 digest API-key authentication with live reload, open
/health, admin-onlyGET /v1/keys, configurable CORS origins and request-ID response headers. Added bearer-key support to the MCP stdio bridge andBasalPython client.Why
Let basal-serve deployments protect the inference and MCP endpoints, serve browser clients from explicitly allowed origins, and correlate requests without requiring an external gateway.
Compatibility
With no flags, successful response bodies remain unchanged; every HTTP response now includes
x-request-idandx-typesafe-request-id(an accepted valid incomingX-Request-Idis echoed, otherwise areq_<hex>ID is generated). With API keys enabled, a missing or invalid key gets HTTP 401 with{"error":"missing or invalid API key","code":"UNAUTHORIZED"}; non-admin access toGET /v1/keysgets HTTP 403 with{"error":"admin key required","code":"FORBIDDEN"}.GET /healthremains unauthenticated.Tests run
uv run --no-sync pytest -q tests/test_auth.py tests/test_client.py tests/test_mcp.py tests/test_server.py tests/test_http_status.py— 98 passed.uv run --no-sync pytest -q -x— 774 passed, 53 skipped, 1 warning.uvx [email protected] check --select E9,F63,F7,F82 --target-version py310 .— failed on existingF821 Undefined name kposatbasal/gemma4.py:471; no changed file is named by the diagnostic.Summary by Sourcery
Enable optional API-key protection, browser CORS access, and request correlation for basal-serve and its clients.
New Features:
Enhancements:
Documentation:
Tests: