How to Set Up API Key Authentication for the OpenSandbox Server
OpenSandbox secures its Lifecycle API through a FastAPI middleware that validates the OPEN-SANDBOX-API‑KEY request header against a secret configured in ~/.sandbox.toml, returning 401 errors for missing or invalid credentials while exempting health checks and documentation endpoints.
OpenSandbox implements API key authentication to protect its sandbox management endpoints. The system uses a pluggable AuthMiddleware class that integrates with the FastAPI application lifecycle to intercept requests before they reach route handlers. This guide covers the complete configuration and usage based on the actual implementation in the alibaba/OpenSandbox repository.
Configure the API Key in ServerConfig
Authentication is controlled by the api_key field inside the server configuration section. In src/config.py, the ServerConfig dataclass defines this field at lines 80-84, which is parsed from a TOML configuration file.
Create or edit ~/.sandbox.toml (the default path, overridable via the SANDBOX_CONFIG_PATH environment variable):
[server]
host = "0.0.0.0"
port = 8080
log_level = "INFO"
# Enable API key authentication
api_key = "my-secret-12345"
The api_key value can be any opaque string. For production deployments, inject this value via environment variables or a secrets manager rather than committing it to version control.
How AuthMiddleware Enforces Authentication
The AuthMiddleware class in src/middleware/auth.py implements the actual security checks. When the FastAPI application starts in src/main.py (lines 35-38), the middleware is registered via app.add_middleware(AuthMiddleware, config=app_config).
During initialization, the middleware calls _load_api_keys() to extract the key from the AppConfig object. For every incoming request, the dispatch method performs the following logic:
- Path exemption check: Requests to
/health,/docs,/redoc,/openapi.json, and proxy routes matching/sandboxes/{id}/proxy/{port}/…bypass authentication entirely. - Configuration check: If
self.valid_api_keysis empty (no key configured), the middleware allows all requests. - Header validation: The middleware looks for the
OPEN-SANDBOX-API-KEYheader.- Missing header → Returns 401 Unauthorized with code
MISSING_API_KEY. - Invalid key → Returns 401 Unauthorized with code
INVALID_API_KEY. - Valid key → Proceeds to the route handler.
- Missing header → Returns 401 Unauthorized with code
Error responses follow the standard schema defined in src/main.py, returning JSON objects with code and message fields.
Starting the Server with Authentication
After configuring the TOML file, start the server from the repository root:
cd server
uv run python -m src.main
# Alternative: uvicorn src.main:app --host 0.0.0.0 --port 8080
The startup sequence loads the configuration via load_config(), initializes AuthMiddleware with the extracted secret, and mounts the middleware onto the FastAPI app. The server will now reject unauthenticated requests to protected endpoints.
Making Authenticated API Requests
Clients must include the OPEN-SANDBOX-API-KEY header in all requests to protected endpoints. For example, to list sandboxes:
curl -H "OPEN-SANDBOX-API-KEY: my-secret-12345" \
http://localhost:8080/v1/sandboxes
If authentication fails, the server returns structured error responses:
{
"code": "MISSING_API_KEY",
"message": "Authentication credentials are missing. Provide API key via OPEN-SANDBOX-API-KEY header."
}
Or for incorrect values:
{
"code": "INVALID_API_KEY",
"message": "Authentication credentials are invalid. Check your API key and try again."
}
Bypassing Authentication for Local Development
To disable authentication for local testing, either omit the api_key field or set it to an empty string in ~/.sandbox.toml:
[server]
api_key = ""
When AuthMiddleware detects an empty valid_api_keys set during initialization, it skips all header checks and allows unrestricted access. This is useful for development environments where credential management is unnecessary.
Summary
- Configuration: Set
server.api_keyin~/.sandbox.toml(parsed bysrc/config.py) to define the required secret. - Middleware:
AuthMiddlewareinsrc/middleware/auth.pyenforces checks on every request except exempt paths like/healthand/docs. - Registration: The middleware attaches to the FastAPI app in
src/main.pyviaapp.add_middleware(). - Client Usage: Send the key in the
OPEN-SANDBOX-API-KEYheader; missing or invalid keys trigger 401 responses with specific error codes. - Local Testing: Leave
api_keyempty to bypass authentication entirely.
Frequently Asked Questions
What file paths does the authentication middleware ignore?
The AuthMiddleware in src/middleware/auth.py maintains an internal list of exempt paths including /health, /docs, /redoc, and /openapi.json. Additionally, proxy routes matching /sandboxes/{id}/proxy/{port}/… are exempt to prevent accidental credential leakage through proxied connections.
Can I configure multiple valid API keys for the OpenSandbox server?
The current implementation in src/middleware/auth.py supports a single API key via ServerConfig.api_key. However, the middleware stores keys in a set (self.valid_api_keys), suggesting the underlying structure could be extended to support multiple secrets if the configuration parsing logic in src/config.py were modified to accept a list.
Why am I getting a 401 error when accessing the Swagger UI?
If you configured an API key but receive MISSING_API_KEY when visiting /docs, verify that the Swagger documentation endpoint is not in your exemption list. By default, /docs, /redoc, and /openapi.json are exempt from authentication. If these are protected in your deployment, you must add the OPEN-SANDBOX-API-KEY header to your browser requests or configure your reverse proxy to inject it.
How does the server handle API key validation errors?
When the AuthMiddleware.dispatch method detects a missing or invalid header, it returns a 401 Unauthorized response with a JSON body containing an error code field (MISSING_API_KEY or INVALID_API_KEY) and a descriptive message. This schema is consistent with the global error handling defined in src/main.py.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →