Skip to content

feat(serve): --api-keys, --cors-origins and x-request-id - #68

Closed
pawelkiszczak wants to merge 1 commit into
rkinas:mainfrom
pawelkiszczak:pr/serve-api-keys
Closed

pawelkiszczak wants to merge 1 commit into
rkinas:mainfrom
pawelkiszczak:pr/serve-api-keys

Conversation

@pawelkiszczak

@pawelkiszczak pawelkiszczak commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor

Closes #67

What

Added optional SHA-256 digest API-key authentication with live reload, open /health, admin-only GET /v1/keys, configurable CORS origins and request-ID response headers. Added bearer-key support to the MCP stdio bridge and Basal Python 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-id and x-typesafe-request-id (an accepted valid incoming X-Request-Id is echoed, otherwise a req_<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 to GET /v1/keys gets HTTP 403 with {"error":"admin key required","code":"FORBIDDEN"}. GET /health remains 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 existing F821 Undefined name kpos at basal/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:

  • Add optional SHA-256 API-key authentication for HTTP and MCP endpoints, including live key-file reloads and admin-only key usage reporting.
  • Add configurable CORS origins and request ID headers to served HTTP responses.
  • Support bearer API keys in the Basal Python client and MCP stdio bridge.

Enhancements:

  • Keep health checks unauthenticated while protecting other routes when API-key authentication is enabled.

Documentation:

  • Document API-key authentication, CORS configuration, request IDs, and MCP bearer-key usage.

Tests:

  • Add coverage for authentication, key reload and revocation, admin access, CORS, request IDs, and client/MCP key propagation.

@sourcery-ai

sourcery-ai Bot commented Oct 28, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

Introduces 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 requests

sequenceDiagram
    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
Loading

Sequence diagram for admin key usage inspection

sequenceDiagram
    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
Loading

Flow diagram for request ID handling

flowchart 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
Loading

File-Level Changes

Change Details Files
Added optional API-key authentication with file-backed SHA-256 digests, live reload, usage tracking, and admin-only key inspection.
  • Accept Bearer and X-API-Key credentials and fail closed on missing, invalid, or malformed key files.
  • Keep GET /health unauthenticated while protecting HTTP and MCP routes when configured.
  • Add admin-gated GET /v1/keys with in-memory last-used timestamps.
  • Expose --api-keys and document key-file format and behavior.
basal/auth.py
basal/server.py
README.md
docs/SERVING.md
docs/MCP.md
docs/WHATS_NEW.md
tests/test_auth.py
tests/test_http_status.py
tests/test_server.py
Added configurable CORS handling and response request identifiers at the ASGI layer.
  • Allow comma-separated origins through --cors-origins with explicit methods, headers, and exposed request-ID headers.
  • Echo valid incoming X-Request-Id values or generate req_ identifiers.
  • Attach both x-request-id and x-typesafe-request-id to every HTTP response, including authentication and preflight responses.
  • Preserve response bodies and support streaming responses through middleware.
basal/auth.py
basal/server.py
docs/SERVING.md
tests/test_auth.py
tests/test_http_status.py
Propagated optional bearer API keys to Python and MCP clients.
  • Add api_key to Basal and configure its shared HTTP client Authorization header.
  • Add --api-key to the MCP stdio bridge and pass credentials to remote inference and model-name requests.
  • Cover client and bridge header propagation with tests.
basal/client.py
basal/mcp_server.py
tests/test_client.py
tests/test_mcp.py

Assessment against linked issues

Issue Objective Addressed Explanation
#67 Add opt-in API-key authentication for basal-serve HTTP and MCP endpoints using a SHA-256 digest file with live reload, while leaving GET /health open and accepting bearer or X-API-Key credentials. ✅
#67 Add configurable CORS origins for browser clients and attach x-request-id and x-typesafe-request-id response headers, echoing valid incoming request IDs or generating new ones. ✅
#67 Support bearer API-key authentication in the basal-mcp stdio bridge and the Python client, while preserving existing behavior when authentication is not configured. ✅

Possibly linked issues


Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨

Comment thread basal/server.py
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))

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟠 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.

Comment thread basal/auth.py
record = None
if not open_health and keys is not None:
headers = dict(scope.get("headers", ()))
authorization = headers.get(b"authorization", b"").decode("latin1")

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 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`.

Comment thread basal/auth.py
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}"

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 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.

Comment thread tests/test_http_status.py

decorated = asyncio.run(go())
assert decorated.content == b'{"ok":true}'
assert decorated.headers["x-request-id"].startswith("req_")

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 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.

@rkinas

rkinas commented Oct 28, 2026

Copy link
Copy Markdown
Owner

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 x-request-id header (the second request-id header is dropped, since it is not a project name). Please keep that name out of future PRs. We are also reviewing the key handling before the merge. The PR will close when 2.5 is published on main.

@rkinas

rkinas commented Nov 2, 2026

Copy link
Copy Markdown
Owner

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.

@rkinas rkinas closed this Nov 2, 2026
rkinas pushed a commit that referenced this pull request Nov 2, 2026
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.
rkinas added a commit that referenced this pull request Nov 2, 2026
… 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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Add optional API-key authentication, CORS and request IDs to basal-serve

2 participants