Skip to content

armgit / sie

Public Imported from GitHub
0

Open-source inference server and production cluster for all the models your agent needs.

feat(server): add opt-in token auth and warn about exposed servers (#751)

Krisztian Gajdar2d56a6619eb5
diff --git a/COMPATIBILITY.md b/COMPATIBILITY.md
index fb113b782..68f02f3dd 100644
--- a/COMPATIBILITY.md
+++ b/COMPATIBILITY.md
@@ -183,25 +183,39 @@ that will change logs a warning naming 0.13.0.
#### Release N: options and warnings
-Every new option keeps today's behaviour by default. The one exception is a
-security fix: `/ws/status` stops sending host identity at once, which changes
-the values of three response fields (see the `ServerInfo` item below). The
-fields keep their names and types, so clients that read them keep working.
+Nothing breaks. Every new option keeps today's behaviour by default. There are
+two exceptions, both security fixes:
+
+- `/ws/status` stops sending host identity at once, which changes the values of
+ three response fields (see the `ServerInfo` item below). The fields keep
+ their names and types, so clients that read them keep working.
+- `sie-server` stops at startup when `SIE_AUTH_TOKENS` or `SIE_AUTH_TOKEN` is
+ set but holds no token, as an unset variable passed through does, unless
+ `SIE_AUTH_MODE=none`. Without this, a server meant to require a token would
+ run without authentication.
+
+The changes:
- `sie-server serve`:
- `--host` also reads `SIE_SERVER_HOST`. The default stays `0.0.0.0`.
- Opt-in token authentication, with the gateway's variables:
`SIE_AUTH_MODE` (`none`, `token`, `auto`) and `SIE_AUTH_TOKENS` or
`SIE_AUTH_TOKEN`. A configured token turns it on. Clients send
- `Authorization: Bearer <token>` or `x-api-key: <token>`. `/healthz`,
+ `Authorization: Bearer <token>` or `x-api-key: <token>`; when a request
+ sends both, `Authorization` is used and `x-api-key` is ignored. `/healthz`,
`/livez` and `/readyz` stay open.
- - In token mode without a configured token, the server generates one, saves
- it with mode `0600` in `SIE_DATA_DIR`, and prints it once.
+ - In token mode without a configured token, the server generates one and
+ saves it with mode `0600` in `SIE_DATA_DIR`. It prints the token once when
+ stderr is a terminal, and otherwise only the file's path. A container with
+ a terminal counts as one, and its logs keep that print.
- `SIE_DATA_DIR` moves from `/tmp/sie-server` to a per-user directory,
`$XDG_DATA_HOME/sie` or `~/.local/share/sie`. Images set `/app/.cache/sie`;
mount a volume there to keep the token across containers.
- A server that listens beyond loopback without authentication logs a
warning on every start.
+ - A server bound to loopback without authentication logs a warning, once per
+ `Host`, for a request whose `Host` does not name this machine (`localhost`,
+ `127.0.0.1`, `[::1]` or the bind address). The request is still answered.
- `/ws/status` no longer sends the OS user, working directory or process id.
`ServerInfo.user`, `working_dir` and `pid` are always `""`, `""` and `0`,
and are deprecated. This is an exception to the rule that a changed
@@ -211,26 +225,34 @@ fields keep their names and types, so clients that read them keep working.
- Rust/Candle worker: logs a notice when it binds `0.0.0.0` only because
`SIE_SERVER_HOST` is unset.
- Gateway:
- - Accepts `x-api-key` alongside `Authorization`. A request that sends both
- must send the same token in each.
+ - Accepts `x-api-key` alongside `Authorization`. When a request sends both,
+ `Authorization` is used and `x-api-key` is ignored, so a request that
+ passes today still passes, including one where a proxy in front of the
+ gateway adds an `x-api-key` of its own. Repeated `x-api-key` values that
+ carry different tokens get `401`.
+ - A repeated `Authorization` header still uses its first value. When the
+ values carry different tokens, the gateway logs a warning once.
- `SIE_WORKER_AUTH_TOKEN` is the token the gateway presents to workers.
- Logs a warning when `SIE_AUTH_MODE` is unset on a non-loopback bind.
- Telemetry: `SIE_TELEMETRY_ENABLED=1` opts in explicitly. The default stays on,
with a notice at startup. Helm `telemetry.enabled: true` sets
`SIE_TELEMETRY_ENABLED=1`.
-- Helm: `gateway.auth.generateToken` and `workers.auth`, both off by default.
+- Helm, with the chart change that adds them: `gateway.auth.generateToken` and
+ `workers.auth`, both off by default.
#### 0.13.0: default changes (breaking)
| Surface | Until 0.13.0 | From 0.13.0 | To keep the old behaviour |
| --- | --- | --- | --- |
| `sie-server serve` bind | `0.0.0.0` | `127.0.0.1` | `--host 0.0.0.0` or `SIE_SERVER_HOST=0.0.0.0` |
-| `sie-server` beyond loopback | No authentication | A token is required. Without `SIE_AUTH_TOKEN`, one is generated and printed once | `SIE_AUTH_MODE=none` |
+| `sie-server` beyond loopback | No authentication | A token is required. Without `SIE_AUTH_TOKEN`, one is generated, and printed once on a terminal | `SIE_AUTH_MODE=none` |
+| `sie-server` on loopback without authentication | A request whose `Host` does not name this machine is answered, with a warning | It gets `400`. So does a request whose `Origin` names another site, at least for WebSocket upgrades and methods other than `GET` | Token authentication, or a setting for more allowed `Host` names, designed together with this change |
| Rust/Candle worker bind | `0.0.0.0` | `127.0.0.1` | `SIE_SERVER_HOST=0.0.0.0` (the image sets it) |
+| Gateway in token mode, repeated `Authorization` values that carry different tokens | The first value is used, with a warning | `401` | Send one `Authorization` header |
| Gateway binary beyond loopback with `SIE_AUTH_MODE` unset | Starts without authentication | Refuses to start | `SIE_AUTH_MODE=none`, or `token` with `SIE_AUTH_TOKENS` |
| Telemetry | On unless disabled | Off unless `SIE_TELEMETRY_ENABLED=1` | `SIE_TELEMETRY_ENABLED=1` |
-| Helm `gateway.auth.mode` | `none` | `token`, with a generated Secret | `gateway.auth.mode=none` |
-| Helm `workers.auth.enabled` | `false` | `true` | `workers.auth.enabled=false` |
+| Helm `gateway.auth.mode` | `none` | `token`, with a generated Secret (needs the chart change above) | `gateway.auth.mode=none` |
+| Helm `workers.auth.enabled` (with the chart change above) | `false` | `true` | `workers.auth.enabled=false` |
| Helm `workers.networkPolicy.enabled` | `false` | `true` | `workers.networkPolicy.enabled=false` |
| Helm `telemetry.enabled` | `true` | `false` | `telemetry.enabled=true` |
@@ -257,8 +279,9 @@ docker run -p 127.0.0.1:8080:8080 -e SIE_AUTH_TOKEN=$SIE_API_KEY \
curl -H "Authorization: Bearer $SIE_API_KEY" http://localhost:8080/v1/models
```
-Without `-e SIE_AUTH_TOKEN`, copy the generated token from `docker logs`. The
-SDKs read `SIE_API_KEY`.
+Without `-e SIE_AUTH_TOKEN`, read the generated token with
+`docker exec <container> cat /app/.cache/sie/auth-token`. The SDKs read
+`SIE_API_KEY`.
A server reached from another machine, before:
@@ -272,8 +295,9 @@ After:
SIE_AUTH_TOKEN=<token> sie-server serve --host 0.0.0.0
```
-Helm: upgrade worker authentication in two steps, so no worker rejects a
-gateway that has not rolled yet.
+Helm, with the chart change that adds `workers.auth`: upgrade worker
+authentication in two steps, so no worker rejects a gateway that has not rolled
+yet.
```bash
helm upgrade sie-cluster oci://ghcr.io/superlinked/charts/sie-cluster -f values.yaml \
diff --git a/SECURITY.md b/SECURITY.md
index b50fdbe5e..2804106ca 100644
--- a/SECURITY.md
+++ b/SECURITY.md
@@ -41,17 +41,33 @@ What a default install exposes, and how to close it.
requests without authentication. Anyone who can reach the port can run
inference, read `/ws/status`, and make the server load catalog models, which
costs compute, disk and network.
+- Turn on token authentication with `SIE_AUTH_MODE=token`, and set the token
+ with `SIE_AUTH_TOKEN` (or comma-separated `SIE_AUTH_TOKENS`). Without a
+ configured token, the server generates one and keeps it in `SIE_DATA_DIR`.
+ Clients send it as `Authorization: Bearer <token>` or `x-api-key: <token>`;
+ when both are sent, `Authorization` is used. `/healthz`, `/livez` and
+ `/readyz` stay open. Token authentication covers the HTTP port; the IPC
+ socket and the engines' ports listen on this machine only.
- Keep it on this machine with `--host 127.0.0.1`. In Docker, publish the port
on loopback only: `-p 127.0.0.1:8080:8080`.
+- A loopback server without a token is still exposed to a web page that uses
+ DNS rebinding. Until 0.13.0 the server only logs a warning for a `Host` that
+ does not name this machine. Set a token if a browser on this machine may
+ visit untrusted pages.
- Do not expose an unauthenticated server to a network you do not control.
- Expose it through an authenticating proxy, or through the gateway with token
- authentication enabled.
+ Turn on token authentication, or expose it through an authenticating proxy
+ or through the gateway with token authentication enabled.
### Gateway
- The gateway authenticates requests with static tokens: set
`SIE_AUTH_MODE=token` and `SIE_AUTH_TOKENS`. Mutations of pools, admin and
config routes also need `SIE_ADMIN_TOKEN`.
+- Clients send a token as `Authorization: Bearer <token>` or
+ `x-api-key: <token>`. When both are sent, `Authorization` is used and
+ `x-api-key` is ignored. Until 0.13.0, a repeated `Authorization` header uses
+ its first value and logs a warning; from 0.13.0, repeated values that carry
+ different tokens are refused.
- `/healthz`, `/readyz`, `/openapi.json` and `/docs` are always reachable.
`/`, `/health` and `/ws/*` require a token unless
`SIE_AUTH_EXEMPT_OPERATIONAL=true`.
diff --git a/examples/coding-agent-claude-code/README.md b/examples/coding-agent-claude-code/README.md
index 0f1a328b5..4519227c2 100644
--- a/examples/coding-agent-claude-code/README.md
+++ b/examples/coding-agent-claude-code/README.md
@@ -88,9 +88,10 @@ export API_TIMEOUT_MS=1800000
- `ANTHROPIC_BASE_URL` is the gateway without `/v1`. Claude Code appends
`/v1/messages`.
-- `ANTHROPIC_AUTH_TOKEN` arrives as `Authorization: Bearer ...`, which is
- where SIE reads the key. Claude Code sends `ANTHROPIC_API_KEY` as
- `x-api-key` instead, which SIE does not read.
+- `ANTHROPIC_AUTH_TOKEN` arrives as `Authorization: Bearer ...`, and
+ Claude Code sends `ANTHROPIC_API_KEY` as `x-api-key`. The gateway reads
+ either one; when a request carries both, it uses `Authorization` and
+ ignores `x-api-key`.
- The model id is sent byte for byte, slash and colon included. The four
model variables keep every request, background tasks and subagents
included, on the SIE model. A request that names a model the gateway does
diff --git a/packages/sie_gateway/README.md b/packages/sie_gateway/README.md
index a24c4a590..1ef849a45 100644
--- a/packages/sie_gateway/README.md
+++ b/packages/sie_gateway/README.md
@@ -92,11 +92,12 @@ Each `--flag` above has a matching `SIE_*` environment variable (see next sectio
| `SIE_NATS_URL` | | NATS server URL. The process can start without it, but inference requests will return `503` until a usable client exists. Credentials in the URL are not used; logs show the URL with any userinfo redacted |
| `SIE_NATS_USER` | | NATS user (Helm sets `sie-gateway`). Set together with `SIE_NATS_PASSWORD`; setting only one fails startup |
| `SIE_NATS_PASSWORD` | | NATS password of `SIE_NATS_USER`. Redacted in `Config` debug output |
-| `SIE_AUTH_MODE` | `none` | Auth mode for inbound requests: `none` disables, `token` (alias `static`) enforces. Unknown values fail-open-to-bypass; `main` logs a startup error naming the bad value |
-| `SIE_AUTH_TOKENS` | | CSV of valid bearer tokens for inference and pool/config read endpoints. If unset, the singular `SIE_AUTH_TOKEN` is used as a fallback. When auth is enabled and this list is empty, non-probe requests return `500` |
+| `SIE_AUTH_MODE` | `none` | Auth mode for inbound requests: `none` disables, `token` (alias `static`) enforces. Values are case-sensitive. An unknown value, including `sie-server`'s `auto`, refuses every request with `500` except the probes and the API description (`/healthz`, `/readyz`, `/openapi.json`, `/docs`), and `main` logs a startup error naming the bad value. While it is unset on a non-loopback bind and the configuration is otherwise valid, `main` logs a warning: from 0.13.0 the gateway refuses to start that way |
+| `SIE_AUTH_TOKENS` | | CSV of valid tokens for inference and pool/config read endpoints, presented as `Authorization: Bearer <token>` or `x-api-key: <token>` (when both are sent, `Authorization` is used and `x-api-key` is ignored). A repeated `Authorization` header uses its first value, as before, and logs a warning once; from 0.13.0 repeated values that carry different tokens get `401`. Repeated `x-api-key` values that carry different tokens get `401`. If unset, the singular `SIE_AUTH_TOKEN` is used as a fallback. When auth is enabled and this list is empty, non-probe requests return `500` |
| `SIE_AUTH_TOKEN` | | Singular alias for `SIE_AUTH_TOKENS` (fallback only; prefer the plural form) |
| `SIE_ADMIN_TOKEN` | | Admin bearer token the gateway requires inbound for admin-gated mutations: `POST/PUT/DELETE` on `/v1/configs/*`, `/v1/admin/*`, `/v1/pools/*`. If empty and an inbound request targets one of those paths, the middleware fails closed with `403`. Sent to `sie-config` only when `SIE_CONFIG_SERVICE_TOKEN` is unset (deprecated fallback) |
| `SIE_CONFIG_SERVICE_TOKEN` | | Bearer token the gateway presents **as a client** on its `sie-config` reads (`/v1/configs/bundles`, `/export`, `/epoch`): `sie-config`'s read-scoped `SIE_CONFIG_READ_TOKEN`. When set, it decides and a blank value sends no token; when unset, the gateway falls back to `SIE_ADMIN_TOKEN` and logs a deprecation warning |
+| `SIE_WORKER_AUTH_TOKEN` | | Token the gateway presents as `Authorization: Bearer` when it dials a worker's `/ws/status` (`ws` health mode). Set it to the workers' `SIE_AUTH_TOKEN` when workers require a token. The dial uses plain `ws://`, so the token crosses the network unencrypted: keep the gateway-to-worker network trusted. Startup fails when it is not a valid header value |
| `SIE_AUTH_EXEMPT_OPERATIONAL` | `false` | When `true`, `/`, `/health`, and `/ws/*` are exempt from auth (they expose worker URLs, queue depth, GPU inventory). `/healthz` and `/readyz` are always exempt (K8s probes carry no creds). Default is fail-closed |
| `SIE_NATS_CONFIG_TRUSTED_PRODUCERS` | `sie-config` | CSV allowlist of `producer_id` values trusted to publish on `sie.config.models._all`. Matches exact OR K8s pod-name prefix (`sie-config` also matches `sie-config-5f7b6d8c-kxwvr`). Untrusted notifications are dropped; the epoch poller still closes the gap |
| `SIE_NATS_CONFIG_TRUST_ANY_PRODUCER` | `false` | Disable producer validation entirely (dev/local only). `main` emits a startup audit warning when on |
diff --git a/packages/sie_gateway/docs/architecture-guide.md b/packages/sie_gateway/docs/architecture-guide.md
index 9f90b414a..e8e93f3fc 100644
--- a/packages/sie_gateway/docs/architecture-guide.md
+++ b/packages/sie_gateway/docs/architecture-guide.md
@@ -516,7 +516,7 @@ Gateway (`sie-gateway`):
- `SIE_CONFIG_SERVICE_TOKEN` — bearer token the gateway-as-client presents on its `sie-config` reads (`GET /v1/configs/bundles`, `/bundles/{id}`, `/export`, `/epoch`). It should be `sie-config`'s read-scoped token (`SIE_CONFIG_READ_TOKEN` there), which the chart generates and always wires in (empty when the chart runs no `sie-config`). When the variable is set it decides, and a blank value sends no `Authorization` header (so `sie-config` must either be unauthenticated or the gateway will fail with `401`/`403`). When it is unset, the gateway falls back to `SIE_ADMIN_TOKEN` and, when `SIE_CONFIG_SERVICE_URL` is set, logs a deprecation warning at startup; it logs the same warning when the two are equal. `sie-config` accepts one read token at a time and every component reads it at start, so a rotation restarts `sie-config` first and then the gateways and worker sidecars; until they restart, they receive `403` on config reads.
- `SIE_ADMIN_TOKEN` — the token that `AuthLayer` requires for admin-gated mutations on the gateway itself (`POST/PUT/DELETE` on `/v1/configs/*`, `/v1/admin/*`, `/v1/pools/*`). If empty and the matching inbound request targets an admin path, the middleware fails closed with `403`. It is not sent to `sie-config` unless `SIE_CONFIG_SERVICE_TOKEN` is unset (the deprecated fallback above). The chart wires it only from `gateway.auth.adminTokenSecretName`, never from the `sie-config` admin token.
- `SIE_AUTH_TOKEN` / `SIE_AUTH_TOKENS` — tokens accepted by the gateway's own inference API (`/v1/encode`, `/v1/score`, `/v1/extract`) and for read-side pool/config routes. Not used for outbound calls to `sie-config`. When `SIE_AUTH_MODE` enables auth but this list is empty, every non-probe request returns `500`.
-- `SIE_AUTH_MODE` — `token` (alias: `static`) enforces auth; `none` (default) disables it. Typos are fail-open-to-bypass by design; `audit_auth` logs a startup error naming the bad value so operators see it in `kubectl logs`.
+- `SIE_AUTH_MODE` — `token` (alias: `static`) enforces auth; `none` (default) disables it. A typo refuses every request with `500` except the probes and the API description (`/healthz`, `/readyz`, `/openapi.json`, `/docs`), and `audit_auth` logs a startup error naming the bad value so operators see it in `kubectl logs`. Requests present a token as `Authorization: Bearer` or `x-api-key`; when both are sent, `Authorization` is used and `x-api-key` is ignored. Only the first `Authorization` value is read; repeated values that disagree log a warning once and are refused from 0.13.0. Repeated `x-api-key` values that disagree are refused.
- `SIE_AUTH_EXEMPT_OPERATIONAL` — when `true`, `/`, `/health`, and `/ws/*` are exempt from auth (they expose worker URLs, bundle assignments, queue depth, GPU inventory — treat as sensitive). Default `false`. **`/healthz` and `/readyz` are always exempt from auth** so kubelet probes never fail with **`401`/`403`** because of a missing bearer token. `/readyz` reports only process readiness and, when `SIE_CONFIG_SERVICE_URL` is set, first-bootstrap completion; worker health remains visible through `/health` and inference responses.
- `SIE_NATS_CONFIG_TRUSTED_PRODUCERS` — comma-separated producer allowlist for `sie.config.models._all`. Binary default is `sie-config`; Helm sets the release-scoped config Deployment name. Matching is exact OR K8s pod-name prefix (see §4.3). Untrusted notifications are dropped; the `config_poller` still closes the gap.
- `SIE_NATS_CONFIG_TRUST_ANY_PRODUCER` — `true` disables producer validation entirely. Intended for local/dev. `main.rs` emits a startup warning when on.
diff --git a/packages/sie_gateway/openapi.json b/packages/sie_gateway/openapi.json
index 3c97fc552..d8646d7bd 100644
--- a/packages/sie_gateway/openapi.json
+++ b/packages/sie_gateway/openapi.json
@@ -4506,6 +4506,12 @@
}
},
"securitySchemes": {
+ "apiKeyAuth": {
+ "description": "The same SIE token as bearerAuth, sent in the x-api-key header. When a request sends both, the Authorization header is used and x-api-key is ignored.",
+ "in": "header",
+ "name": "x-api-key",
+ "type": "apiKey"
+ },
"bearerAuth": {
"bearerFormat": "opaque",
"description": "SIE bearer token. Mutating pool/config/admin routes require the configured admin token; other protected routes accept a normal gateway token.",
@@ -9080,6 +9086,9 @@
"security": [
{
"bearerAuth": []
+ },
+ {
+ "apiKeyAuth": []
}
],
"tags": [
diff --git a/packages/sie_gateway/src/config.rs b/packages/sie_gateway/src/config.rs
index 1aea1bd71..003c31079 100644
--- a/packages/sie_gateway/src/config.rs
+++ b/packages/sie_gateway/src/config.rs
@@ -2,6 +2,7 @@ use std::collections::{HashMap, HashSet};
use std::env;
use std::time::Duration;
+use axum::http::HeaderValue;
use serde::Deserialize;
use crate::state::demand_tracker::PhysicalLaneCatalog;
@@ -784,6 +785,43 @@ fn env_default(key: &str, fallback: &str) -> String {
}
}
+/// The `Authorization` value the gateway presents when it dials a worker's
+/// `/ws/status`, from `SIE_WORKER_AUTH_TOKEN`. `None` when it is unset or blank.
+pub fn worker_authorization_from_env() -> Result<Option<HeaderValue>, String> {
+ worker_authorization(env::var("SIE_WORKER_AUTH_TOKEN").unwrap_or_default().trim())
+}
+
+fn worker_authorization(token: &str) -> Result<Option<HeaderValue>, String> {
+ if token.is_empty() {
+ return Ok(None);
+ }
+ let mut value = HeaderValue::from_str(&format!("Bearer {token}"))
+ .map_err(|_| "SIE_WORKER_AUTH_TOKEN is not a valid HTTP header value".to_string())?;
+ value.set_sensitive(true);
+ Ok(Some(value))
+}
+
+/// Whether `SIE_AUTH_MODE` is set to a non-empty value.
+pub fn auth_mode_is_set() -> bool {
+ env::var("SIE_AUTH_MODE").is_ok_and(|value| !value.is_empty())
+}
+
+/// The startup warning for a gateway that serves other machines without
+/// authentication only because `SIE_AUTH_MODE` is unset. A configuration
+/// [`Config::auth_config_error`] refuses serves nobody, so it gets none.
+pub fn unset_auth_mode_warning(config: &Config, auth_mode_set: bool) -> Option<String> {
+ let host = config.host.as_str();
+ if auth_mode_set
+ || config.auth_config_error().is_some()
+ || host_is_loopback(host.trim_start_matches('[').trim_end_matches(']'))
+ {
+ return None;
+ }
+ Some(format!(
+ "SIE_AUTH_MODE is unset and the gateway listens on {host}, so every client that can reach it is served without authentication. From 0.13.0 the gateway refuses to start this way. Set SIE_AUTH_MODE=token with SIE_AUTH_TOKEN, or set SIE_AUTH_MODE=none to keep it open."
+ ))
+}
+
/// The bearer the gateway presents to `sie-config`. `SIE_CONFIG_SERVICE_TOKEN`
/// decides whenever it is set, and a blank value means no credential. Only an
/// unset `SIE_CONFIG_SERVICE_TOKEN` falls back to `SIE_ADMIN_TOKEN`, the
@@ -932,9 +970,9 @@ impl Config {
}
/// Report auth configuration soundness. Returns `(level, message)`
- /// pairs that callers log at startup. Catches fail-open
- /// misconfigurations (e.g. tokens set while `SIE_AUTH_MODE=none`),
- /// unknown modes, missing tokens, and explicit operational bypasses.
+ /// pairs that callers log at startup. Catches misconfigurations the
+ /// middleware refuses (e.g. tokens set while `SIE_AUTH_MODE=none`, or an
+ /// unknown mode), missing tokens, and explicit operational bypasses.
///
/// Does not mutate `self` and does not refuse startup; matches the
/// gateway's "log and continue" posture for config issues.
@@ -951,7 +989,7 @@ impl Config {
issues.push((
AuditLevel::Error,
format!(
- "SIE_AUTH_MODE='{}' is not recognized; expected 'none', 'static', or 'token'. Auth is currently DISABLED (fail-open) because of the unknown mode — fix SIE_AUTH_MODE.",
+ "SIE_AUTH_MODE='{}' is not recognized; expected 'none', 'static', or 'token'. Fix SIE_AUTH_MODE.",
mode
),
));
@@ -968,7 +1006,7 @@ impl Config {
if !is_enabled && has_tokens {
issues.push((
AuditLevel::Error,
- "SIE_AUTH_TOKEN(S) is set but SIE_AUTH_MODE is not 'static'/'token'. Auth is DISABLED; the tokens are dead configuration. Set SIE_AUTH_MODE=token to enforce auth.".to_string(),
+ "SIE_AUTH_TOKEN(S) is set but SIE_AUTH_MODE is not 'static'/'token', so the gateway refuses every request except the probes and the API description. Set SIE_AUTH_MODE=token to enforce the tokens, or remove them.".to_string(),
));
} else if !is_enabled && has_admin {
let usage = if admin_is_config_credential {
@@ -2201,9 +2239,8 @@ mod tests {
let cfg = cfg_with_auth("none", vec!["t1"], "admin", false);
let issues = cfg.audit_auth();
assert!(
- issues
- .iter()
- .any(|(lvl, msg)| *lvl == AuditLevel::Error && msg.contains("DISABLED")),
+ issues.iter().any(|(lvl, msg)| *lvl == AuditLevel::Error
+ && msg.contains("refuses every request except the probes")),
"expected error about tokens + disabled auth, got {:?}",
issues
);
@@ -2353,4 +2390,46 @@ mod tests {
},
);
}
+
+ #[test]
+ fn worker_authorization_is_a_sensitive_bearer_value() {
+ let value = worker_authorization("worker-secret").unwrap().unwrap();
+ assert_eq!(value.to_str().unwrap(), "Bearer worker-secret");
+ assert!(value.is_sensitive());
+ assert!(worker_authorization("").unwrap().is_none());
+ let error = worker_authorization("bad\ntoken").unwrap_err();
+ assert!(
+ !error.contains("bad"),
+ "the error must not echo the token: {error}"
+ );
+ }
+
+ fn cfg_on_host(host: &str, mode: &str, tokens: Vec<&str>) -> Config {
+ let mut cfg = cfg_with_auth(mode, tokens, "", false);
+ cfg.host = host.to_string();
+ cfg
+ }
+
+ #[test]
+ fn unset_auth_mode_warning_covers_only_an_exposed_unset_mode() {
+ let warning =
+ unset_auth_mode_warning(&cfg_on_host("0.0.0.0", "none", vec![]), false).unwrap();
+ assert!(warning.contains("0.13.0"), "{warning}");
+ assert!(unset_auth_mode_warning(&cfg_on_host("::", "none", vec![]), false).is_some());
+ assert!(unset_auth_mode_warning(&cfg_on_host("10.0.0.5", "none", vec![]), false).is_some());
+ assert!(unset_auth_mode_warning(&cfg_on_host("0.0.0.0", "none", vec![]), true).is_none());
+ for host in ["127.0.0.1", "::1", "[::1]", "localhost"] {
+ assert!(
+ unset_auth_mode_warning(&cfg_on_host(host, "none", vec![]), false).is_none(),
+ "{host}"
+ );
+ }
+ }
+
+ #[test]
+ fn unset_auth_mode_warning_stays_quiet_when_the_gateway_refuses_every_request() {
+ let refusing = cfg_on_host("0.0.0.0", "none", vec!["t1"]);
+ assert!(refusing.auth_config_error().is_some());
+ assert!(unset_auth_mode_warning(&refusing, false).is_none());
+ }
}
diff --git a/packages/sie_gateway/src/discovery/ws_health.rs b/packages/sie_gateway/src/discovery/ws_health.rs
index b2e5e5522..33cb08457 100644
--- a/packages/sie_gateway/src/discovery/ws_health.rs
+++ b/packages/sie_gateway/src/discovery/ws_health.rs
@@ -3,6 +3,9 @@ use std::collections::HashMap;
use std::sync::Arc;
use std::time::Duration;
use tokio::sync::Mutex;
+use tokio_tungstenite::tungstenite::client::IntoClientRequest;
+use tokio_tungstenite::tungstenite::handshake::client::Request;
+use tokio_tungstenite::tungstenite::http::header::{HeaderValue, AUTHORIZATION};
use tokio_tungstenite::tungstenite::Message;
use tracing::{info, warn};
@@ -11,13 +14,17 @@ use crate::types::WorkerStatusMessage;
pub struct WsHealthManager {
registry: Arc<WorkerRegistry>,
+ worker_authorization: Option<HeaderValue>,
cancels: Mutex<HashMap<String, tokio::sync::watch::Sender<()>>>,
}
impl WsHealthManager {
- pub fn new(registry: Arc<WorkerRegistry>) -> Self {
+ /// `worker_authorization` is the `Authorization` value presented on every
+ /// worker `/ws/status` dial.
+ pub fn new(registry: Arc<WorkerRegistry>, worker_authorization: Option<HeaderValue>) -> Self {
Self {
registry,
+ worker_authorization,
cancels: Mutex::new(HashMap::new()),
}
}
@@ -56,8 +63,9 @@ impl WsHealthManager {
cancels.insert(url.clone(), tx);
let registry = Arc::clone(&self.registry);
+ let authorization = self.worker_authorization.clone();
tokio::spawn(async move {
- connect_to_worker(registry, url, rx).await;
+ connect_to_worker(registry, url, authorization, rx).await;
});
}
@@ -83,6 +91,7 @@ impl WsHealthManager {
async fn connect_to_worker(
registry: Arc<WorkerRegistry>,
url: String,
+ authorization: Option<HeaderValue>,
mut cancel: tokio::sync::watch::Receiver<()>,
) {
let ws_url = url
@@ -99,7 +108,15 @@ async fn connect_to_worker(
}
}
- match run_ws_connection(&registry, &url, &ws_url, &mut cancel).await {
+ match run_ws_connection(
+ &registry,
+ &url,
+ &ws_url,
+ authorization.as_ref(),
+ &mut cancel,
+ )
+ .await
+ {
Ok(()) => return, // Cancelled
Err(e) => {
warn!(url = %ws_url, error = %e, "websocket error");
@@ -118,15 +135,28 @@ async fn connect_to_worker(
}
}
+fn status_request(
+ ws_url: &str,
+ authorization: Option<&HeaderValue>,
+) -> Result<Request, Box<dyn std::error::Error + Send + Sync>> {
+ let mut request = ws_url.into_client_request()?;
+ if let Some(value) = authorization {
+ request.headers_mut().insert(AUTHORIZATION, value.clone());
+ }
+ Ok(request)
+}
+
async fn run_ws_connection(
registry: &Arc<WorkerRegistry>,
http_url: &str,
ws_url: &str,
+ authorization: Option<&HeaderValue>,
cancel: &mut tokio::sync::watch::Receiver<()>,
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
info!(url = %ws_url, "connecting to worker");
- let (ws_stream, _) = tokio_tungstenite::connect_async(ws_url).await?;
+ let request = status_request(ws_url, authorization)?;
+ let (ws_stream, _) = tokio_tungstenite::connect_async(request).await?;
info!(url = %ws_url, "connected to worker");
let (_, mut read) = ws_stream.split();
@@ -178,3 +208,59 @@ async fn run_ws_connection(
}
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use tokio::net::TcpListener;
+ use tokio_tungstenite::tungstenite::handshake::server::{
+ Request as ServerRequest, Response as ServerResponse,
+ };
+
+ #[allow(clippy::result_large_err)]
+ async fn authorization_seen_by_worker(authorization: Option<HeaderValue>) -> Option<String> {
+ let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let addr = listener.local_addr().unwrap();
+ let registry = Arc::new(WorkerRegistry::new(Duration::from_secs(30), None));
+ let manager = WsHealthManager::new(registry, authorization);
+ manager.add_worker(format!("http://{addr}")).await;
+
+ let (stream, _) = tokio::time::timeout(Duration::from_secs(5), listener.accept())
+ .await
+ .unwrap()
+ .unwrap();
+ let (tx, rx) = std::sync::mpsc::channel();
+ let _socket = tokio_tungstenite::accept_hdr_async(
+ stream,
+ move |request: &ServerRequest, response: ServerResponse| {
+ let header = request
+ .headers()
+ .get(AUTHORIZATION)
+ .map(|value| value.to_str().unwrap().to_string());
+ tx.send((request.uri().path().to_string(), header)).unwrap();
+ Ok(response)
+ },
+ )
+ .await
+ .unwrap();
+ manager.stop().await;
+
+ let (path, header) = rx.recv().unwrap();
+ assert_eq!(path, "/ws/status");
+ header
+ }
+
+ #[tokio::test]
+ async fn worker_dial_presents_the_worker_token() {
+ let value = HeaderValue::from_static("Bearer worker-secret");
+ assert_eq!(
+ authorization_seen_by_worker(Some(value)).await.as_deref(),
+ Some("Bearer worker-secret")
+ );
+ }
+
+ #[tokio::test]
+ async fn worker_dial_without_a_token_sends_no_authorization() {
+ assert_eq!(authorization_seen_by_worker(None).await, None);
+ }
+}
diff --git a/packages/sie_gateway/src/handlers/proxy.rs b/packages/sie_gateway/src/handlers/proxy.rs
index 8342ee3f7..139634496 100644
--- a/packages/sie_gateway/src/handlers/proxy.rs
+++ b/packages/sie_gateway/src/handlers/proxy.rs
@@ -41,7 +41,7 @@ use crate::state::worker_registry::{QueueRoute, WorkerRegistry};
use crate::types::model::FallbackTrigger;
use crate::types::AuditEntry;
-use crate::middleware::auth::{extract_bearer_token, mask_token};
+use crate::middleware::auth::request_token_id;
use super::serving_disclosure::{
remote_forbidden, DeferredFallbackFinish, FallbackAttempt, ServingDisclosure,
@@ -3895,9 +3895,7 @@ async fn proxy_request_inner(
}
};
- let token_id = extract_bearer_token(req.headers())
- .map(|t| mask_token(&t))
- .unwrap_or_default();
+ let token_id = request_token_id(req.headers());
let content_length = req
.headers()
.get("content-length")
@@ -9256,9 +9254,7 @@ async fn resolve_generation_route(
}
}
- let token_id = extract_bearer_token(hdr)
- .map(|t| mask_token(&t))
- .unwrap_or_default();
+ let token_id = request_token_id(hdr);
let content_length = hdr
.get("content-length")
.and_then(|v| v.to_str().ok())
@@ -12245,6 +12241,7 @@ pub(crate) fn is_openai_compat_forwarded_header(name: &str) -> bool {
pub(crate) fn is_openai_compat_inner_request_header(name: &str) -> bool {
[
"authorization",
+ "x-api-key",
"x-sie-machine-profile",
"x-sie-pool",
"x-sie-engine",
@@ -23376,6 +23373,7 @@ mod tests {
// path — every other endpoint injects queue trace context).
for name in [
"authorization",
+ "x-api-key",
"x-sie-machine-profile",
"x-sie-pool",
"x-sie-engine",
diff --git a/packages/sie_gateway/src/main.rs b/packages/sie_gateway/src/main.rs
index 5345fb333..d3705413d 100644
--- a/packages/sie_gateway/src/main.rs
+++ b/packages/sie_gateway/src/main.rs
@@ -192,6 +192,10 @@ async fn run_server(cfg: Config) -> Result<(), Box<dyn std::error::Error>> {
crate::config::AuditLevel::Error => tracing::error!(audit = "auth", "{}", msg),
}
}
+ if let Some(msg) = config::unset_auth_mode_warning(&config, config::auth_mode_is_set()) {
+ tracing::warn!(audit = "auth", "{}", msg);
+ }
+ let worker_authorization = config::worker_authorization_from_env()?;
for (level, msg) in config.audit_nats_producer_trust() {
match level {
crate::config::AuditLevel::Warn => {
@@ -369,7 +373,10 @@ async fn run_server(cfg: Config) -> Result<(), Box<dyn std::error::Error>> {
}
if use_ws {
- let ws_mgr = Arc::new(WsHealthManager::new(Arc::clone(&registry)));
+ let ws_mgr = Arc::new(WsHealthManager::new(
+ Arc::clone(&registry),
+ worker_authorization,
+ ));
ws_mgr.start(discovery.get_worker_urls()).await;
ws_mgr.start_heartbeat_loop().await;
ws_manager = Some(ws_mgr);
diff --git a/packages/sie_gateway/src/middleware/audit.rs b/packages/sie_gateway/src/middleware/audit.rs
index 443b8db64..5f6d74424 100644
--- a/packages/sie_gateway/src/middleware/audit.rs
+++ b/packages/sie_gateway/src/middleware/audit.rs
@@ -23,7 +23,7 @@ use std::time::Instant;
use tower::{Layer, Service};
use tracing::info;
-use super::auth::mask_token;
+use super::auth::request_token_id;
use crate::observability::metrics::AdmissionOutcomeSlot;
#[derive(Clone)]
@@ -71,19 +71,7 @@ where
let method = req.method().to_string();
let path = req.uri().path().to_string();
- let token_id = req
- .headers()
- .get("authorization")
- .and_then(|v| v.to_str().ok())
- .map(|h| {
- let token = if h.to_lowercase().starts_with("bearer ") {
- h[7..].trim()
- } else {
- h.trim()
- };
- mask_token(token)
- })
- .unwrap_or_default();
+ let token_id = request_token_id(req.headers());
let content_length = req
.headers()
diff --git a/packages/sie_gateway/src/middleware/auth.rs b/packages/sie_gateway/src/middleware/auth.rs
index 7b99ad7b9..321151fb3 100644
--- a/packages/sie_gateway/src/middleware/auth.rs
+++ b/packages/sie_gateway/src/middleware/auth.rs
@@ -3,6 +3,7 @@ use axum::http::{Method, Request, StatusCode};
use axum::response::{IntoResponse, Response};
use std::future::Future;
use std::pin::Pin;
+use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::task::{Context, Poll};
use subtle::ConstantTimeEq;
@@ -46,6 +47,8 @@ pub struct AuthLayer {
/// interpretation, which this middleware serves as a refusal rather than
/// as "auth off" — see [`AuthMiddleware::call`].
misconfigured: Option<Arc<str>>,
+ /// Set once the warning about repeated `Authorization` values is logged.
+ repeated_authorization_warned: Arc<AtomicBool>,
}
impl AuthLayer {
@@ -60,6 +63,7 @@ impl AuthLayer {
Self {
config,
misconfigured,
+ repeated_authorization_warned: Arc::new(AtomicBool::new(false)),
}
}
}
@@ -72,6 +76,7 @@ impl<S> Layer<S> for AuthLayer {
inner,
config: Arc::clone(&self.config),
misconfigured: self.misconfigured.clone(),
+ repeated_authorization_warned: Arc::clone(&self.repeated_authorization_warned),
}
}
}
@@ -81,6 +86,7 @@ pub struct AuthMiddleware<S> {
inner: S,
config: Arc<Config>,
misconfigured: Option<Arc<str>>,
+ repeated_authorization_warned: Arc<AtomicBool>,
}
impl<S> Service<Request<Body>> for AuthMiddleware<S>
@@ -99,6 +105,7 @@ where
fn call(&mut self, req: Request<Body>) -> Self::Future {
let config = Arc::clone(&self.config);
let misconfigured = self.misconfigured.clone();
+ let repeated_authorization_warned = Arc::clone(&self.repeated_authorization_warned);
let mut inner = self.inner.clone();
Box::pin(async move {
@@ -141,14 +148,40 @@ where
return inner.call(req).await;
}
- let token = match extract_bearer_token(req.headers()) {
- Some(t) => t,
- None => {
+ let token = match extract_request_credential(req.headers()) {
+ RequestCredential::Token(t) => {
+ if authorization_values_disagree(req.headers())
+ && !repeated_authorization_warned.swap(true, Ordering::Relaxed)
+ {
+ tracing::warn!(
+ audit = "auth",
+ "A request repeated the Authorization header with different values. The gateway used the first value; from 0.13.0 it refuses such requests with 401. Send one Authorization header."
+ );
+ }
+ t
+ }
+ RequestCredential::Missing => {
+ record_admission_rejection(&req, AdmissionOutcome::Unauthenticated);
+ return Ok(error_response(
+ StatusCode::UNAUTHORIZED,
+ err_code::UNAUTHORIZED,
+ "Missing Authorization or x-api-key header",
+ ));
+ }
+ RequestCredential::Conflicting => {
record_admission_rejection(&req, AdmissionOutcome::Unauthenticated);
return Ok(error_response(
StatusCode::UNAUTHORIZED,
err_code::UNAUTHORIZED,
- "Missing Authorization header",
+ "Repeated x-api-key headers carry different tokens",
+ ));
+ }
+ RequestCredential::Unreadable => {
+ record_admission_rejection(&req, AdmissionOutcome::Unauthenticated);
+ return Ok(error_response(
+ StatusCode::UNAUTHORIZED,
+ err_code::UNAUTHORIZED,
+ "Invalid token",
));
}
};
@@ -227,27 +260,103 @@ fn is_admin_endpoint(method: &Method, path: &str) -> bool {
/// Extract the token from an `Authorization` header, accepting
/// `Bearer <token>` (case-insensitive prefix) or a raw token value.
///
-/// Canonical shared implementation: also consumed by `handlers::proxy`
-/// and downstream authentication layers.
+/// Exported through the crate's library target (`src/lib.rs`) for
+/// composition crates that read `Authorization` only. This gateway reads
+/// request credentials with [`extract_request_credential`].
+#[allow(dead_code)]
pub fn extract_bearer_token(headers: &axum::http::HeaderMap) -> Option<String> {
- let header = headers
- .get("authorization")?
- .to_str()
- .ok()?
- .trim()
- .to_string();
+ authorization_token(headers.get("authorization")?.to_str().ok()?)
+}
+
+fn authorization_token(header: &str) -> Option<String> {
+ let header = header.trim();
if header.is_empty() {
return None;
}
let token = if header.to_lowercase().starts_with("bearer ") {
- header[7..].trim().to_string()
+ header[7..].trim()
} else {
header
};
if token.is_empty() {
None
} else {
- Some(token)
+ Some(token.to_string())
+ }
+}
+
+/// The credential a request presents.
+#[derive(Debug, PartialEq, Eq)]
+pub enum RequestCredential {
+ Missing,
+ Token(String),
+ /// Repeated `x-api-key` values carry different tokens.
+ Conflicting,
+ /// A credential header whose value is not visible ASCII.
+ Unreadable,
+}
+
+/// Read the request's token. The first `Authorization` value (`Bearer
+/// <token>` or a raw value, as [`extract_bearer_token`]) decides when it
+/// carries a token, and `x-api-key` is then ignored. Otherwise `x-api-key`
+/// decides, and its repeated values must carry the same token. Later
+/// `Authorization` values are ignored, as they always were; see
+/// [`authorization_values_disagree`].
+pub fn extract_request_credential(headers: &axum::http::HeaderMap) -> RequestCredential {
+ let authorization = match headers.get("authorization").map(|value| value.to_str()) {
+ None => RequestCredential::Missing,
+ Some(Err(_)) => RequestCredential::Unreadable,
+ Some(Ok(raw)) => {
+ authorization_token(raw).map_or(RequestCredential::Missing, RequestCredential::Token)
+ }
+ };
+ match authorization {
+ RequestCredential::Missing => header_credential(headers.get_all("x-api-key"), |raw| {
+ let raw = raw.trim();
+ (!raw.is_empty()).then(|| raw.to_string())
+ }),
+ decided => decided,
+ }
+}
+
+fn header_credential<'a>(
+ values: impl IntoIterator<Item = &'a axum::http::HeaderValue>,
+ parse: impl Fn(&str) -> Option<String>,
+) -> RequestCredential {
+ let mut found: Option<String> = None;
+ for value in values {
+ let Ok(raw) = value.to_str() else {
+ return RequestCredential::Unreadable;
+ };
+ let Some(token) = parse(raw) else {
+ continue;
+ };
+ match &found {
+ None => found = Some(token),
+ Some(existing) if *existing == token => {}
+ Some(_) => return RequestCredential::Conflicting,
+ }
+ }
+ found.map_or(RequestCredential::Missing, RequestCredential::Token)
+}
+
+/// Whether the request repeats `Authorization` with values that carry
+/// different tokens, or one that cannot be read. Until 0.13.0 the gateway
+/// uses the first value; from 0.13.0 such a request is refused.
+pub fn authorization_values_disagree(headers: &axum::http::HeaderMap) -> bool {
+ headers.get_all("authorization").iter().nth(1).is_some()
+ && matches!(
+ header_credential(headers.get_all("authorization"), authorization_token),
+ RequestCredential::Conflicting | RequestCredential::Unreadable
+ )
+}
+
+/// The masked request token for audit records, empty when the request
+/// presents no single readable token.
+pub fn request_token_id(headers: &axum::http::HeaderMap) -> String {
+ match extract_request_credential(headers) {
+ RequestCredential::Token(token) => mask_token(&token),
+ _ => String::new(),
}
}
@@ -284,7 +393,14 @@ fn error_response(status: StatusCode, code: &'static str, message: &str) -> Resp
"message": message,
}
});
- (status, axum::Json(body)).into_response()
+ let mut response = (status, axum::Json(body)).into_response();
+ if status == StatusCode::UNAUTHORIZED {
+ response.headers_mut().insert(
+ axum::http::header::WWW_AUTHENTICATE,
+ axum::http::HeaderValue::from_static("Bearer"),
+ );
+ }
+ response
}
#[cfg(test)]
@@ -790,4 +906,418 @@ mod tests {
StatusCode::INTERNAL_SERVER_ERROR
);
}
+
+ fn headers(pairs: &[(&str, &str)]) -> axum::http::HeaderMap {
+ let mut map = axum::http::HeaderMap::new();
+ for (name, value) in pairs {
+ map.append(
+ axum::http::HeaderName::from_bytes(name.as_bytes()).unwrap(),
+ axum::http::HeaderValue::from_str(value).unwrap(),
+ );
+ }
+ map
+ }
+
+ #[test]
+ fn request_credential_reads_either_header() {
+ for pairs in [
+ vec![("authorization", "Bearer tok")],
+ vec![("authorization", "bearer tok")],
+ vec![("authorization", "tok")],
+ vec![("x-api-key", "tok")],
+ vec![("x-api-key", " tok ")],
+ vec![("authorization", "Bearer tok"), ("x-api-key", "tok")],
+ vec![("authorization", "Bearer tok"), ("x-api-key", "other")],
+ vec![("authorization", "Bearer tok"), ("authorization", "tok")],
+ vec![
+ ("authorization", "Bearer tok"),
+ ("authorization", "Bearer other"),
+ ],
+ vec![("authorization", ""), ("x-api-key", "tok")],
+ ] {
+ assert_eq!(
+ extract_request_credential(&headers(&pairs)),
+ RequestCredential::Token("tok".into()),
+ "{pairs:?}"
+ );
+ }
+ }
+
+ #[test]
+ fn request_credential_lets_authorization_decide() {
+ let unreadable_key = {
+ let mut map = headers(&[("authorization", "Bearer tok")]);
+ map.insert(
+ "x-api-key",
+ axum::http::HeaderValue::from_bytes(b"t\xffk").unwrap(),
+ );
+ map
+ };
+ assert_eq!(
+ extract_request_credential(&unreadable_key),
+ RequestCredential::Token("tok".into())
+ );
+ let unreadable_authorization = {
+ let mut map = headers(&[("x-api-key", "tok")]);
+ map.insert(
+ "authorization",
+ axum::http::HeaderValue::from_bytes(b"t\xffk").unwrap(),
+ );
+ map
+ };
+ assert_eq!(
+ extract_request_credential(&unreadable_authorization),
+ RequestCredential::Unreadable
+ );
+ }
+
+ fn with_unreadable(
+ mut map: axum::http::HeaderMap,
+ name: &'static str,
+ ) -> axum::http::HeaderMap {
+ map.append(
+ name,
+ axum::http::HeaderValue::from_bytes(b"t\xffk").unwrap(),
+ );
+ map
+ }
+
+ #[test]
+ fn request_credential_refuses_repeated_x_api_key_that_disagrees() {
+ assert_eq!(
+ extract_request_credential(&headers(&[("x-api-key", "tok"), ("x-api-key", "other")])),
+ RequestCredential::Conflicting
+ );
+ assert_eq!(
+ extract_request_credential(&with_unreadable(
+ headers(&[("x-api-key", "tok")]),
+ "x-api-key"
+ )),
+ RequestCredential::Unreadable
+ );
+ }
+
+ #[test]
+ fn request_credential_uses_the_first_authorization_value() {
+ assert_eq!(
+ extract_request_credential(&with_unreadable(
+ headers(&[("authorization", "Bearer tok")]),
+ "authorization"
+ )),
+ RequestCredential::Token("tok".into())
+ );
+ assert_eq!(
+ extract_request_credential(&headers(&[
+ ("authorization", ""),
+ ("authorization", "Bearer other")
+ ])),
+ RequestCredential::Missing
+ );
+ let mut unreadable_first = with_unreadable(axum::http::HeaderMap::new(), "authorization");
+ unreadable_first.append(
+ "authorization",
+ axum::http::HeaderValue::from_static("Bearer tok"),
+ );
+ assert_eq!(
+ extract_request_credential(&unreadable_first),
+ RequestCredential::Unreadable
+ );
+ }
+
+ #[test]
+ fn authorization_values_disagree_only_for_repeats_with_another_token() {
+ for pairs in [
+ vec![
+ ("authorization", "Bearer tok"),
+ ("authorization", "Bearer other"),
+ ],
+ vec![("authorization", "Bearer tok"), ("authorization", "other")],
+ ] {
+ assert!(authorization_values_disagree(&headers(&pairs)), "{pairs:?}");
+ }
+ assert!(authorization_values_disagree(&with_unreadable(
+ headers(&[("authorization", "Bearer tok")]),
+ "authorization"
+ )));
+ for pairs in [
+ vec![("authorization", "Bearer tok")],
+ vec![("authorization", "Bearer tok"), ("authorization", "tok")],
+ vec![("authorization", "Bearer tok"), ("authorization", "")],
+ vec![("x-api-key", "tok"), ("x-api-key", "other")],
+ ] {
+ assert!(
+ !authorization_values_disagree(&headers(&pairs)),
+ "{pairs:?}"
+ );
+ }
+ }
+
+ #[test]
+ fn request_credential_missing_and_unreadable() {
+ assert_eq!(
+ extract_request_credential(&headers(&[])),
+ RequestCredential::Missing
+ );
+ assert_eq!(
+ extract_request_credential(&headers(&[("authorization", ""), ("x-api-key", " ")])),
+ RequestCredential::Missing
+ );
+ let mut map = axum::http::HeaderMap::new();
+ map.insert(
+ "x-api-key",
+ axum::http::HeaderValue::from_bytes(b"t\xffk").unwrap(),
+ );
+ assert_eq!(
+ extract_request_credential(&map),
+ RequestCredential::Unreadable
+ );
+ }
+
+ #[test]
+ fn request_token_id_masks_either_header() {
+ assert_eq!(
+ request_token_id(&headers(&[("x-api-key", "secret-token-123")])),
+ "************-123"
+ );
+ assert_eq!(
+ request_token_id(&headers(&[("authorization", "Bearer secret-token-123")])),
+ "************-123"
+ );
+ assert_eq!(
+ request_token_id(&headers(&[
+ ("authorization", "Bearer secret-token-123"),
+ ("x-api-key", "other-token-456")
+ ])),
+ "************-123"
+ );
+ assert_eq!(
+ request_token_id(&headers(&[
+ ("authorization", "Bearer a-token-111"),
+ ("authorization", "Bearer b-token-222")
+ ])),
+ mask_token("a-token-111")
+ );
+ assert_eq!(
+ request_token_id(&headers(&[
+ ("x-api-key", "a-token-111"),
+ ("x-api-key", "b-token-222")
+ ])),
+ ""
+ );
+ }
+
+ async fn send_headers(
+ router: Router,
+ method: Method,
+ path: &str,
+ pairs: &[(&str, &str)],
+ ) -> StatusCode {
+ let mut req = HttpRequest::builder().method(method).uri(path);
+ for (name, value) in pairs {
+ req = req.header(*name, *value);
+ }
+ router
+ .oneshot(req.body(Body::empty()).unwrap())
+ .await
+ .unwrap()
+ .status()
+ }
+
+ #[tokio::test]
+ async fn middleware_401_names_the_bearer_scheme() {
+ let cfg = cfg_for_middleware("token", vec!["user"], "admin", false);
+ let response = test_router(cfg)
+ .oneshot(
+ HttpRequest::builder()
+ .method(Method::POST)
+ .uri("/v1/encode/any")
+ .body(Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
+ assert_eq!(response.headers()["www-authenticate"], "Bearer");
+ }
+
+ #[tokio::test]
+ async fn middleware_accepts_x_api_key() {
+ let cfg = cfg_for_middleware("token", vec!["user"], "admin", false);
+ let r = test_router(Arc::clone(&cfg));
+ assert_eq!(
+ send_headers(r, Method::POST, "/v1/encode/any", &[("x-api-key", "user")]).await,
+ StatusCode::OK
+ );
+ let r = test_router(Arc::clone(&cfg));
+ assert_eq!(
+ send_headers(r, Method::POST, "/v1/encode/any", &[("x-api-key", "bogus")]).await,
+ StatusCode::UNAUTHORIZED
+ );
+ let r = test_router(cfg);
+ assert_eq!(
+ send_headers(
+ r,
+ Method::POST,
+ "/v1/encode/any",
+ &[("authorization", "Bearer user"), ("x-api-key", "user")]
+ )
+ .await,
+ StatusCode::OK
+ );
+ }
+
+ #[tokio::test]
+ async fn middleware_lets_authorization_decide_over_x_api_key() {
+ let cfg = cfg_for_middleware("token", vec!["user"], "admin", false);
+ for (pairs, path, expected) in [
+ (
+ [("authorization", "Bearer user"), ("x-api-key", "bogus")],
+ "/v1/encode/any",
+ StatusCode::OK,
+ ),
+ (
+ [("authorization", "Bearer bogus"), ("x-api-key", "user")],
+ "/v1/encode/any",
+ StatusCode::UNAUTHORIZED,
+ ),
+ (
+ [("authorization", "Bearer admin"), ("x-api-key", "user")],
+ "/v1/pools",
+ StatusCode::OK,
+ ),
+ (
+ [("authorization", "Bearer user"), ("x-api-key", "admin")],
+ "/v1/pools",
+ StatusCode::FORBIDDEN,
+ ),
+ ] {
+ let r = test_router(Arc::clone(&cfg));
+ assert_eq!(
+ send_headers(r, Method::POST, path, &pairs).await,
+ expected,
+ "{pairs:?} {path}"
+ );
+ }
+ }
+
+ #[derive(Clone, Default)]
+ struct CapturedLog(Arc<std::sync::Mutex<Vec<u8>>>);
+
+ impl std::io::Write for CapturedLog {
+ fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
+ self.0.lock().unwrap().extend_from_slice(buf);
+ Ok(buf.len())
+ }
+
+ fn flush(&mut self) -> std::io::Result<()> {
+ Ok(())
+ }
+ }
+
+ impl<'a> tracing_subscriber::fmt::MakeWriter<'a> for CapturedLog {
+ type Writer = Self;
+
+ fn make_writer(&'a self) -> Self::Writer {
+ self.clone()
+ }
+ }
+
+ impl CapturedLog {
+ fn count(&self, needle: &str) -> usize {
+ String::from_utf8_lossy(&self.0.lock().unwrap())
+ .matches(needle)
+ .count()
+ }
+ }
+
+ #[tokio::test]
+ async fn middleware_uses_the_first_authorization_value_and_warns_once() {
+ use tracing::instrument::WithSubscriber;
+
+ let log = CapturedLog::default();
+ let dispatch = tracing::Dispatch::new(
+ tracing_subscriber::fmt()
+ .with_writer(log.clone())
+ .with_ansi(false)
+ .finish(),
+ );
+ let cfg = cfg_for_middleware("token", vec!["user"], "admin", false);
+ let router = test_router(cfg);
+ let repeated = || {
+ HttpRequest::builder()
+ .method(Method::POST)
+ .uri("/v1/encode/any")
+ .header("authorization", "Bearer user")
+ .header("authorization", "Bearer bogus")
+ };
+ let unreadable_repeat = HttpRequest::builder()
+ .method(Method::POST)
+ .uri("/v1/encode/any")
+ .header("authorization", "Bearer user")
+ .header(
+ "authorization",
+ axum::http::HeaderValue::from_bytes(b"t\xffk").unwrap(),
+ );
+ let bogus_first = HttpRequest::builder()
+ .method(Method::POST)
+ .uri("/v1/encode/any")
+ .header("authorization", "Bearer bogus")
+ .header("authorization", "Bearer user");
+ let user_first_admin_key = HttpRequest::builder()
+ .method(Method::POST)
+ .uri("/v1/pools")
+ .header("authorization", "Bearer user")
+ .header("authorization", "Bearer admin")
+ .header("x-api-key", "admin");
+
+ for (request, expected) in [
+ (repeated(), StatusCode::OK),
+ (repeated(), StatusCode::OK),
+ (unreadable_repeat, StatusCode::OK),
+ (bogus_first, StatusCode::UNAUTHORIZED),
+ (user_first_admin_key, StatusCode::FORBIDDEN),
+ ] {
+ let status = router
+ .clone()
+ .oneshot(request.body(Body::empty()).unwrap())
+ .with_subscriber(dispatch.clone())
+ .await
+ .unwrap()
+ .status();
+ assert_eq!(status, expected);
+ }
+ assert_eq!(log.count("repeated the Authorization header"), 1);
+ assert_eq!(log.count("from 0.13.0 it refuses such requests"), 1);
+ }
+
+ #[tokio::test]
+ async fn middleware_refuses_repeated_x_api_key_that_disagrees() {
+ let cfg = cfg_for_middleware("token", vec!["user", "other"], "admin", false);
+ let r = test_router(cfg);
+ assert_eq!(
+ send_headers(
+ r,
+ Method::POST,
+ "/v1/encode/any",
+ &[("x-api-key", "user"), ("x-api-key", "other")]
+ )
+ .await,
+ StatusCode::UNAUTHORIZED
+ );
+ }
+
+ #[tokio::test]
+ async fn middleware_admin_routes_accept_the_admin_token_in_x_api_key() {
+ let cfg = cfg_for_middleware("token", vec!["user"], "admin", false);
+ let r = test_router(Arc::clone(&cfg));
+ assert_eq!(
+ send_headers(r, Method::POST, "/v1/pools", &[("x-api-key", "admin")]).await,
+ StatusCode::OK
+ );
+ let r = test_router(cfg);
+ assert_eq!(
+ send_headers(r, Method::POST, "/v1/pools", &[("x-api-key", "user")]).await,
+ StatusCode::FORBIDDEN
+ );
+ }
}
diff --git a/packages/sie_gateway/src/openapi.rs b/packages/sie_gateway/src/openapi.rs
index 7527b8218..d3a2f49b0 100644
--- a/packages/sie_gateway/src/openapi.rs
+++ b/packages/sie_gateway/src/openapi.rs
@@ -275,7 +275,7 @@ fn apply_gateway_openapi_overrides(value: &mut Value) {
"name": "Apache-2.0",
"url": "https://www.apache.org/licenses/LICENSE-2.0.html"
});
- value["security"] = json!([{ "bearerAuth": [] }]);
+ value["security"] = json!([{ "bearerAuth": [] }, { "apiKeyAuth": [] }]);
let components = value
.as_object_mut()
@@ -288,6 +288,12 @@ fn apply_gateway_openapi_overrides(value: &mut Value) {
"scheme": "bearer",
"bearerFormat": "opaque",
"description": "SIE bearer token. Mutating pool/config/admin routes require the configured admin token; other protected routes accept a normal gateway token."
+ },
+ "apiKeyAuth": {
+ "type": "apiKey",
+ "in": "header",
+ "name": "x-api-key",
+ "description": "The same SIE token as bearerAuth, sent in the x-api-key header. When a request sends both, the Authorization header is used and x-api-key is ignored."
}
});
@@ -3477,7 +3483,19 @@ mod tests {
#[test]
fn openapi_json_documents_auth_and_exempt_routes() {
let spec: serde_json::Value = serde_json::from_str(&OPENAPI_JSON).unwrap();
- assert_eq!(spec["security"], json!([{ "bearerAuth": [] }]));
+ assert_eq!(
+ spec["security"],
+ json!([{ "bearerAuth": [] }, { "apiKeyAuth": [] }])
+ );
+ assert_eq!(
+ spec["components"]["securitySchemes"]["apiKeyAuth"],
+ json!({
+ "type": "apiKey",
+ "in": "header",
+ "name": "x-api-key",
+ "description": "The same SIE token as bearerAuth, sent in the x-api-key header. When a request sends both, the Authorization header is used and x-api-key is ignored."
+ })
+ );
assert_eq!(spec["paths"]["/healthz"]["get"]["security"], json!([]));
assert_eq!(spec["paths"]["/readyz"]["get"]["security"], json!([]));
assert!(spec["paths"]["/readyz"]["get"]["description"]
diff --git a/packages/sie_server/Dockerfile.cpu b/packages/sie_server/Dockerfile.cpu
index a6db66a2e..b60b5fd10 100644
--- a/packages/sie_server/Dockerfile.cpu
+++ b/packages/sie_server/Dockerfile.cpu
@@ -175,6 +175,7 @@ ENV DEBIAN_FRONTEND=noninteractive \
PYTHONUNBUFFERED=1 \
PYTHONDONTWRITEBYTECODE=1 \
HF_HOME=/app/.cache/huggingface \
+ SIE_DATA_DIR=/app/.cache/sie \
OMP_NUM_THREADS=4 \
MKL_NUM_THREADS=4
@@ -220,7 +221,8 @@ COPY --link --from=base --chown=1000:1000 /app/bundles /app/bundles
# Bundle-specific extras — last layer so shared layers above stay cached.
COPY --link --from=builder --chown=1000:1000 /app/bundle-libs /app/bundle-libs
-RUN mkdir -p /app/evals /app/.cache/huggingface && chown -R sie:sie /app/evals /app/.cache
+RUN mkdir -p /app/evals /app/.cache/huggingface /app/.cache/sie && chown -R sie:sie /app/evals /app/.cache \
+ && chmod 700 /app/.cache/sie
# Declare BUNDLE arg only here, where it is first used (LABEL + ENV),
# so every RUN/COPY layer above is bundle-agnostic in its cache key.
diff --git a/packages/sie_server/Dockerfile.cuda12 b/packages/sie_server/Dockerfile.cuda12
index ab46ac2da..1f58c81df 100644
--- a/packages/sie_server/Dockerfile.cuda12
+++ b/packages/sie_server/Dockerfile.cuda12
@@ -308,8 +308,9 @@ COPY --link --from=base --chown=1000:1000 /app/bundles /app/bundles
# A `.pth` file in the shared venv puts /app/bundle-libs at sys.path[0] at startup.
COPY --link --from=builder --chown=1000:1000 /app/bundle-libs /app/bundle-libs
-RUN mkdir -p /app/evals /app/.cache/huggingface /app/.cache/sie-kernels \
- && chown -R sie:sie /app/evals /app/.cache
+RUN mkdir -p /app/evals /app/.cache/huggingface /app/.cache/sie-kernels /app/.cache/sie \
+ && chown -R sie:sie /app/evals /app/.cache \
+ && chmod 700 /app/.cache/sie
# Declare the BUNDLE arg only here, where it is first used (LABEL + ENV),
# so every RUN/COPY layer above is bundle-agnostic in its cache key and the
@@ -324,6 +325,7 @@ ENV PATH="/app/.venv/bin:$PATH" \
PYTHONUNBUFFERED=1 \
PYTHONDONTWRITEBYTECODE=1 \
HF_HOME=/app/.cache/huggingface \
+ SIE_DATA_DIR=/app/.cache/sie \
SIE_SGLANG_KERNEL_CACHE_ROOT=/app/.cache/sie-kernels \
NVIDIA_VISIBLE_DEVICES=all \
NVIDIA_DRIVER_CAPABILITIES=compute,utility \
diff --git a/packages/sie_server/Dockerfile.cuda13 b/packages/sie_server/Dockerfile.cuda13
index e9d8d6b13..f885dfa88 100644
--- a/packages/sie_server/Dockerfile.cuda13
+++ b/packages/sie_server/Dockerfile.cuda13
@@ -273,8 +273,9 @@ COPY --link --from=base --chown=1000:1000 /app/bundles /app/bundles
# Bundle-specific extras — last layer so shared layers above stay cached.
COPY --link --from=builder --chown=1000:1000 /app/bundle-libs /app/bundle-libs
-RUN mkdir -p /app/evals /app/.cache/huggingface /app/.cache/sie-kernels \
- && chown -R sie:sie /app/evals /app/.cache
+RUN mkdir -p /app/evals /app/.cache/huggingface /app/.cache/sie-kernels /app/.cache/sie \
+ && chown -R sie:sie /app/evals /app/.cache \
+ && chmod 700 /app/.cache/sie
# Declare BUNDLE only here (LABEL + ENV) so layers above are bundle-agnostic.
ARG BUNDLE
@@ -288,6 +289,7 @@ ENV PATH="/app/bundle-libs/bin:/app/.venv/bin:$PATH" \
PYTHONUNBUFFERED=1 \
PYTHONDONTWRITEBYTECODE=1 \
HF_HOME=/app/.cache/huggingface \
+ SIE_DATA_DIR=/app/.cache/sie \
SIE_SGLANG_KERNEL_CACHE_ROOT=/app/.cache/sie-kernels \
NVIDIA_VISIBLE_DEVICES=all \
NVIDIA_DRIVER_CAPABILITIES=compute,utility \
diff --git a/packages/sie_server/README.md b/packages/sie_server/README.md
index b2afe2e03..9c878b864 100644
--- a/packages/sie_server/README.md
+++ b/packages/sie_server/README.md
@@ -1035,6 +1035,61 @@ as a profile an operator chooses.
`sie-server` reads its config from `SIE_*` environment variables (Pydantic
`BaseSettings`). Common knobs:
+### Authentication and exposure
+
+| Env var | Default | Effect |
+|--|--|--|
+| `SIE_SERVER_HOST` | `0.0.0.0` | Address `sie-server serve` binds, same as `--host`. `127.0.0.1` accepts connections from this machine only. The default becomes `127.0.0.1` in 0.13.0. |
+| `SIE_AUTH_MODE` | unset | `token` (alias `static`) requires a token on every route of the HTTP port except `/healthz`, `/livez` and `/readyz`, including `/ws/status`. `none` turns authentication off. `auto` requires a token when the bind address is not loopback; it is a `sie-server` value, which the gateway refuses. Unset behaves as `none`, or as `token` when a token is configured. Values are lowercase and case-sensitive, as on the gateway; any other value stops startup. |
+| `SIE_AUTH_TOKENS` | unset | Comma-separated accepted tokens. `SIE_AUTH_TOKEN` is read when it is unset. Setting a token with `SIE_AUTH_MODE=none` stops startup, and so does a token variable that is set but holds no token, unless `SIE_AUTH_MODE=none`. |
+| `SIE_DATA_DIR` | `$XDG_DATA_HOME/sie`, else `~/.local/share/sie` | Holds the generated token (`auth-token`, mode `0600`) and the telemetry worker id. Images set `/app/.cache/sie`. |
+
+Clients send the token as `Authorization: Bearer <token>` or `x-api-key: <token>`;
+when both are sent, `Authorization` is used and `x-api-key` is ignored, as on the
+gateway. The SDKs send `SIE_API_KEY`
+as a Bearer token.
+
+Token auth covers the HTTP port. The other listeners are local: the IPC socket
+that a worker sidecar uses (`SIE_IPC_SOCKET_PATH`, mode `0600`) and the
+loopback ports of the engines the server launches.
+
+When token auth is on and no token is configured, the server generates one on
+first start and saves it in `SIE_DATA_DIR`. When stderr is a terminal it prints
+the token once; otherwise, as in a container without a terminal or under a
+service manager whose output is kept in logs, it prints only the file's path
+and the command that reads it. Later starts reuse the token and print only its
+path. They only read it, so a read-only directory or volume works once it holds
+the token. A container started with a terminal (`docker run -t`, Compose
+`tty: true`, or a Kubernetes container with `tty: true`) counts as a terminal,
+and the container runtime keeps that one print in the container's logs. In
+containers, set `SIE_AUTH_TOKEN` yourself instead. The server refuses a token
+directory that another user owns or can write to, and a token file that is a
+symbolic link, not a regular file, hard-linked, owned by another user, or
+readable by others. To rotate a generated token, delete `auth-token` from
+`SIE_DATA_DIR` and restart the server. In Docker, keep the token across
+containers with a volume:
+
+```bash
+docker run -p 127.0.0.1:8080:8080 -e SIE_AUTH_MODE=token \
+ -v sie-data:/app/.cache/sie \
+ -v sie-hf-cache:/app/.cache/huggingface \
+ ghcr.io/superlinked/sie-server:latest-cpu-default
+```
+
+A server that listens beyond loopback without authentication logs a warning on
+every start. From 0.13.0 such a server requires a token unless
+`SIE_AUTH_MODE=none` is set explicitly.
+
+A server bound to loopback (`127.0.0.0/8`, `::1` or `localhost`) with
+authentication off checks that the `Host` header names this machine:
+`localhost`, `127.0.0.1`, `[::1]` or the bind address, with any port. A web
+page that rebinds its own domain to `127.0.0.1` sends another `Host`. Until
+0.13.0 such a request is still answered, and the server logs a warning once for
+each such `Host`. From 0.13.0 it gets `400`. That also affects a reverse proxy
+on the same machine that passes the client's `Host` on, and a container that
+reaches the server as `host.docker.internal`: have them send one of the names
+above, or turn on token authentication.
+
### Memory & OOM resilience
| Env var | Default | Effect |
diff --git a/packages/sie_server/src/sie_server/app/app_factory.py b/packages/sie_server/src/sie_server/app/app_factory.py
index 7086634b9..9f0f80d48 100644
--- a/packages/sie_server/src/sie_server/app/app_factory.py
+++ b/packages/sie_server/src/sie_server/app/app_factory.py
@@ -30,6 +30,13 @@ from sie_server.config.upstreams import install_upstreams, load_upstreams
from sie_server.core.memory import MemoryConfig
from sie_server.core.readiness import mark_not_ready, mark_ready, register_liveness_probe
from sie_server.core.registry import ModelRegistry
+from sie_server.core.server_auth import (
+ LoopbackHostMiddleware,
+ ServerAuthMiddleware,
+ is_loopback_host,
+ loopback_host_allowlist,
+ server_tokens,
+)
from sie_server.core.shutdown import ShutdownMiddleware, ShutdownState, setup_signal_handlers
from sie_server.ipc_server import IpcServer
from sie_server.observability.gpu import _init_nvml, shutdown_nvml
@@ -86,6 +93,10 @@ class AppFactory:
)
# Add graceful shutdown middleware (for spot instance preemption)
app.add_middleware(ShutdownMiddleware, shutdown_state=shutdown_state)
+ if config.auth_mode == "token":
+ app.add_middleware(ServerAuthMiddleware, tokens=server_tokens(os.environ))
+ elif config.bind_host and is_loopback_host(config.bind_host):
+ app.add_middleware(LoopbackHostMiddleware, allowed_hosts=loopback_host_allowlist(config.bind_host))
install_upstreams(
load_upstreams(config.upstreams_file) if config.upstreams_file else {},
diff --git a/packages/sie_server/src/sie_server/app/app_state_config.py b/packages/sie_server/src/sie_server/app/app_state_config.py
index f1d5615b4..ae9e76619 100644
--- a/packages/sie_server/src/sie_server/app/app_state_config.py
+++ b/packages/sie_server/src/sie_server/app/app_state_config.py
@@ -5,6 +5,14 @@ from dataclasses import dataclass
from pathlib import Path
from sie_server.config.upstreams import REMOTE_SERVING_ENV, UPSTREAMS_FILE_ENV, remote_serving_from_env
+from sie_server.core.server_auth import (
+ AUTH_MODE_ENV,
+ AuthMode,
+ configured_tokens,
+ declares_tokens,
+ requested_mode,
+ resolve_auth_mode,
+)
# Environment variable names for configuration
ENV_DEVICE = "SIE_DEVICE"
@@ -16,6 +24,8 @@ ENV_PINNED_MODELS = "SIE_PINNED_MODELS"
ENV_POOL = "SIE_POOL"
ENV_UPSTREAMS_FILE = UPSTREAMS_FILE_ENV
ENV_REMOTE_SERVING = REMOTE_SERVING_ENV
+ENV_AUTH_MODE = AUTH_MODE_ENV
+ENV_SERVER_HOST = "SIE_SERVER_HOST"
@dataclass
@@ -53,6 +63,12 @@ class AppStateConfig:
remote_serving: bool = True
"""Global switch. When False, every remote profile is refused and nothing is sent upstream."""
+ auth_mode: AuthMode = "none"
+ """Resolved auth mode. ``token`` requires a token on every route except the probes."""
+
+ bind_host: str | None = None
+ """Address the server binds. With auth off on a loopback bind, only loopback Host headers are answered."""
+
def __post_init__(self) -> None:
"""Keep scalar and concrete device settings in the same device family."""
if not self.devices:
@@ -123,6 +139,11 @@ class AppStateConfig:
del os.environ[ENV_UPSTREAMS_FILE]
os.environ[ENV_REMOTE_SERVING] = "1" if self.remote_serving else "0"
+ os.environ[ENV_AUTH_MODE] = self.auth_mode
+ if self.bind_host:
+ os.environ[ENV_SERVER_HOST] = self.bind_host
+ elif ENV_SERVER_HOST in os.environ:
+ del os.environ[ENV_SERVER_HOST]
@classmethod
def from_env_vars(cls) -> AppStateConfig:
@@ -143,6 +164,14 @@ class AppStateConfig:
pool_name = os.environ.get(ENV_POOL) or None
upstreams_file = os.environ.get(ENV_UPSTREAMS_FILE) or None
remote_serving = remote_serving_from_env(os.environ.get(ENV_REMOTE_SERVING))
+ # The bind address is not known here, so an unresolved ``auto`` requires a token.
+ auth_mode = resolve_auth_mode(
+ requested_mode(os.environ),
+ has_tokens=bool(configured_tokens(os.environ)),
+ exposed=True,
+ declares_tokens=declares_tokens(os.environ),
+ )
+ bind_host = os.environ.get(ENV_SERVER_HOST) or None
return cls(
models_dir=models_dir,
@@ -154,4 +183,6 @@ class AppStateConfig:
pool_name=pool_name,
upstreams_file=upstreams_file,
remote_serving=remote_serving,
+ auth_mode=auth_mode,
+ bind_host=bind_host,
)
diff --git a/packages/sie_server/src/sie_server/cli.py b/packages/sie_server/src/sie_server/cli.py
index 4d874f0e8..6e2156252 100644
--- a/packages/sie_server/src/sie_server/cli.py
+++ b/packages/sie_server/src/sie_server/cli.py
@@ -25,6 +25,7 @@ if sys.platform == "darwin":
import hashlib
import logging
+import shlex
from collections.abc import Iterable
from pathlib import Path
from typing import Annotated
@@ -58,10 +59,25 @@ from sie_server.config.upstreams import (
load_upstreams,
remote_serving_from_env,
)
+from sie_server.core.data_dir import DATA_DIR_ENV, resolve_data_dir
from sie_server.core.deps import collect_bundle_deps
from sie_server.core.loader import load_model_configs
from sie_server.core.logging import configure_logging, is_valid_log_level, valid_log_levels
from sie_server.core.model_suggestions import suggest_models
+from sie_server.core.server_auth import (
+ AUTH_MODE_ENV,
+ AUTH_TOKEN_ENV,
+ AuthConfigError,
+ AuthMode,
+ StoredToken,
+ TokenFileError,
+ configured_tokens,
+ declares_tokens,
+ is_loopback_host,
+ load_or_create_token,
+ requested_mode,
+ resolve_auth_mode,
+)
from sie_server.main import run_server
logger = logging.getLogger(__name__)
@@ -130,6 +146,105 @@ def _echo_suggestions(unknown: Iterable[str], known: Iterable[str]) -> None:
typer.echo(f" '{name}': did you mean {', '.join(suggestions)}?", err=True)
+_SECURE_DEFAULTS_RELEASE = "0.13.0"
+SERVER_HOST_ENV = "SIE_SERVER_HOST"
+
+
+def _stderr_is_terminal() -> bool:
+ return sys.stderr.isatty()
+
+
+def _echo_generated_token(stored: StoredToken, port: int) -> None:
+ rule = "=" * 72
+ if _stderr_is_terminal():
+ lines = [
+ f"sie-server generated an API token and saved it to {stored.path}.",
+ "It is shown only this once. Clients send it as 'Authorization: Bearer <token>'",
+ "or 'x-api-key: <token>':",
+ "",
+ f" export SIE_API_KEY={stored.token}",
+ ]
+ else:
+ lines = [
+ f"sie-server generated an API token and saved it to {stored.path}.",
+ "It is not printed because this output is not a terminal and may be kept in logs. Read it with:",
+ "",
+ f" export SIE_API_KEY=$(cat {shlex.quote(str(stored.path))})",
+ "",
+ f"In a container, run that through 'docker exec', or set {AUTH_TOKEN_ENV} yourself instead.",
+ "Clients send it as 'Authorization: Bearer <token>' or 'x-api-key: <token>'.",
+ ]
+ lines.append(f' curl -H "Authorization: Bearer $SIE_API_KEY" http://localhost:{port}/v1/models')
+ typer.echo("\n".join([rule, *lines, rule]), err=True)
+
+
+def _prepare_auth(*, host: str, port: int, host_is_default: bool) -> AuthMode:
+ """Resolve the server's auth mode, provision its token, and warn about exposure."""
+ exposed = not is_loopback_host(host)
+ requested = requested_mode(os.environ)
+ tokens = configured_tokens(os.environ)
+ try:
+ mode = resolve_auth_mode(
+ requested, has_tokens=bool(tokens), exposed=exposed, declares_tokens=declares_tokens(os.environ)
+ )
+ except AuthConfigError as exc:
+ typer.echo(f"Error: {exc}", err=True)
+ raise typer.Exit(1) from None
+
+ if mode == "token" and tokens:
+ typer.echo(f"Auth: every route except /healthz, /livez and /readyz requires one of {len(tokens)} token(s)")
+ elif mode == "token":
+ directory = resolve_data_dir()
+ if directory is None:
+ typer.echo(
+ f"Error: {AUTH_MODE_ENV} requires a token, but there is no home directory to keep a generated "
+ f"one in. Set {AUTH_TOKEN_ENV}, or set {DATA_DIR_ENV} to a private directory.",
+ err=True,
+ )
+ raise typer.Exit(1)
+ try:
+ stored = load_or_create_token(directory)
+ except TokenFileError as exc:
+ typer.echo(f"Error: {exc}", err=True)
+ raise typer.Exit(1) from None
+ if stored.created:
+ _echo_generated_token(stored, port)
+ else:
+ typer.echo(f"Auth: every route except /healthz, /livez and /readyz requires the token in {stored.path}")
+
+ if exposed and mode == "none":
+ if requested == "none":
+ typer.echo(
+ f"Warning: authentication is off ({AUTH_MODE_ENV}=none) and sie-server listens on "
+ f"{host}:{port}. Anyone who can reach that address can use this server.",
+ err=True,
+ )
+ else:
+ rule = "!" * 72
+ typer.echo(
+ "\n".join(
+ [
+ rule,
+ f"WARNING: sie-server listens on {host}:{port} without authentication.",
+ "Any machine that can reach that address can use this server.",
+ f"From {_SECURE_DEFAULTS_RELEASE}, an exposed sie-server requires a token. Set "
+ f"{AUTH_TOKEN_ENV} now, or set {AUTH_MODE_ENV}=token to have the server generate one.",
+ f"To keep it open, set {AUTH_MODE_ENV}=none.",
+ rule,
+ ]
+ ),
+ err=True,
+ )
+ if host_is_default and exposed:
+ typer.echo(
+ f"Notice: sie-server listens on {host} because neither --host nor {SERVER_HOST_ENV} is set. "
+ f"From {_SECURE_DEFAULTS_RELEASE} the default is 127.0.0.1. Pass --host {host} or set "
+ f"{SERVER_HOST_ENV}={host} to keep listening on every interface.",
+ err=True,
+ )
+ return mode
+
+
def _came_from_command_line(param: str) -> bool:
"""Whether ``param`` was typed on the command line rather than defaulted.
@@ -140,10 +255,14 @@ def _came_from_command_line(param: str) -> bool:
Returns ``False`` when there is no active Click context (direct calls in
tests), which keeps the lenient path — the strict one is opt-in.
"""
+ return _parameter_source(param) == ParameterSource.COMMANDLINE
+
+
+def _parameter_source(param: str) -> ParameterSource | None:
ctx = click.get_current_context(silent=True)
if ctx is None:
- return False
- return ctx.get_parameter_source(param) == ParameterSource.COMMANDLINE
+ return None
+ return ctx.get_parameter_source(param)
def _canonical_model_id(value: str) -> str:
@@ -326,7 +445,12 @@ def openapi_export(
@app.command()
def serve(
port: int = typer.Option(8080, "--port", "-p", help="Port to listen on"),
- host: str = typer.Option("0.0.0.0", "--host", help="Host to bind to"), # noqa: S104 — intentional bind to all interfaces for server
+ host: str = typer.Option(
+ "0.0.0.0", # noqa: S104 — intentional bind to all interfaces for server
+ "--host",
+ envvar=SERVER_HOST_ENV,
+ help="Address to bind to. Use 127.0.0.1 to accept connections from this machine only.",
+ ),
device: str = typer.Option("auto", "--device", "-d", help="Device to use (auto, cuda, mps, cpu)"),
models_dir: str = typer.Option(
DEFAULT_MODELS_DIR,
@@ -612,6 +736,12 @@ def serve(
typer.echo("Tracing enabled - exporting to localhost:4317")
typer.echo("Start Jaeger with: mise run jaeger")
+ auth_mode = _prepare_auth(
+ host=host,
+ port=port,
+ host_is_default=_parameter_source("host") in (None, ParameterSource.DEFAULT),
+ )
+
typer.echo(f"Starting SIE server on {host}:{port}")
typer.echo(f"Models directory: {models_dir_resolved}")
@@ -699,6 +829,8 @@ def serve(
pool_name=pool_name,
upstreams_file=upstreams_file,
remote_serving=remote_serving,
+ auth_mode=auth_mode,
+ bind_host=host,
)
if upstreams_file and not remote_serving:
typer.echo("Remote serving: off. Every remote profile is refused.")
diff --git a/packages/sie_server/src/sie_server/core/data_dir.py b/packages/sie_server/src/sie_server/core/data_dir.py
new file mode 100644
index 000000000..8a543af45
--- /dev/null
+++ b/packages/sie_server/src/sie_server/core/data_dir.py
@@ -0,0 +1,65 @@
+from __future__ import annotations
+
+import os
+import re
+import stat
+import time
+from collections.abc import Iterator
+from pathlib import Path
+
+DATA_DIR_ENV = "SIE_DATA_DIR"
+TEMPORARY_FILE_MAX_AGE_S = 60.0
+_DIR_NAME = "sie"
+
+
+def resolve_data_dir() -> Path | None:
+ """The directory that holds the server token and the telemetry worker id.
+
+ ``SIE_DATA_DIR`` wins. Otherwise it is a per-user directory:
+ ``$XDG_DATA_HOME/sie``, or ``~/.local/share/sie``. ``None`` when neither
+ ``SIE_DATA_DIR`` nor a home directory is available.
+ """
+ configured = os.environ.get(DATA_DIR_ENV, "").strip()
+ if configured:
+ return Path(configured).expanduser()
+ xdg_data_home = os.environ.get("XDG_DATA_HOME", "").strip()
+ if xdg_data_home and Path(xdg_data_home).is_absolute():
+ return Path(xdg_data_home) / _DIR_NAME
+ try:
+ return Path.home() / ".local" / "share" / _DIR_NAME
+ except RuntimeError:
+ return None
+
+
+def ensure_data_dir(path: Path) -> Path:
+ """Create ``path`` readable by its owner only, leaving an existing directory as it is."""
+ path.mkdir(mode=0o700, parents=True, exist_ok=True)
+ return path
+
+
+def owned_files(directory: Path, name: re.Pattern[str]) -> Iterator[tuple[Path, os.stat_result]]:
+ """Regular files in ``directory`` whose whole name matches ``name`` and that this user owns."""
+ for entry in directory.iterdir():
+ if not name.fullmatch(entry.name):
+ continue
+ try:
+ info = entry.lstat()
+ except FileNotFoundError:
+ continue
+ if stat.S_ISREG(info.st_mode) and info.st_uid == os.getuid():
+ yield entry, info
+
+
+def remove_stale_files(directory: Path, name: re.Pattern[str]) -> None:
+ """Remove the files ``owned_files`` finds that have one link and are too old to still be in use.
+
+ A file younger than ``TEMPORARY_FILE_MAX_AGE_S`` may belong to a start
+ that is still writing it, so it is left in place. Errors are ignored.
+ """
+ cutoff = time.time() - TEMPORARY_FILE_MAX_AGE_S
+ try:
+ for entry, info in owned_files(directory, name):
+ if info.st_nlink == 1 and info.st_mtime < cutoff:
+ entry.unlink(missing_ok=True)
+ except OSError:
+ return
diff --git a/packages/sie_server/src/sie_server/core/server_auth.py b/packages/sie_server/src/sie_server/core/server_auth.py
new file mode 100644
index 000000000..a00f0334d
--- /dev/null
+++ b/packages/sie_server/src/sie_server/core/server_auth.py
@@ -0,0 +1,434 @@
+"""Token authentication for ``sie-server``.
+
+One vocabulary with the gateway: ``SIE_AUTH_MODE`` selects the mode,
+``SIE_AUTH_TOKENS`` (or ``SIE_AUTH_TOKEN``) holds comma-separated tokens, and a
+request presents one in ``Authorization: Bearer`` or ``x-api-key``, with
+``Authorization`` taking precedence when both are sent.
+"""
+
+from __future__ import annotations
+
+import errno
+import hmac
+import ipaddress
+import logging
+import os
+import re
+import secrets
+import stat
+from collections.abc import Iterable, Mapping, Sequence
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Literal
+
+import orjson
+from starlette.types import ASGIApp, Receive, Scope, Send
+
+from sie_server.core.data_dir import ensure_data_dir, owned_files, remove_stale_files, resolve_data_dir
+
+logger = logging.getLogger(__name__)
+
+AUTH_MODE_ENV = "SIE_AUTH_MODE"
+AUTH_TOKENS_ENV = "SIE_AUTH_TOKENS"
+AUTH_TOKEN_ENV = "SIE_AUTH_TOKEN" # noqa: S105 - an environment variable name
+TOKEN_FILE_NAME = "auth-token" # noqa: S105 - a file name
+
+EXEMPT_PATHS = frozenset({"/healthz", "/livez", "/readyz"})
+LOOPBACK_HOST_NAMES = frozenset({"localhost", "127.0.0.1", "[::1]"})
+
+AuthMode = Literal["none", "token"]
+
+_TOKEN_MODES = frozenset({"token", "static"})
+_KNOWN_MODES = frozenset({"none", "auto"} | _TOKEN_MODES)
+_MAX_TOKEN_FILE_BYTES = 4096
+_GENERATED_TOKEN_BYTES = 32
+_O_NOFOLLOW = getattr(os, "O_NOFOLLOW", 0)
+_TEMP_PREFIX = f".{TOKEN_FILE_NAME}.sie-server-"
+_TEMP_NAME = re.compile(rf"{re.escape(_TEMP_PREFIX)}[0-9a-f]{{16}}")
+_READ_ONLY_ERRNOS = frozenset({errno.EACCES, errno.EROFS})
+_HOST_CHECK_RELEASE = "0.13.0"
+_MAX_WARNED_HOSTS = 64
+_MAX_LOGGED_HOST_CHARS = 100
+
+
+class AuthConfigError(ValueError):
+ """The auth environment has no valid interpretation."""
+
+
+class TokenFileError(RuntimeError):
+ """The persisted token cannot be created or trusted."""
+
+
+@dataclass(frozen=True)
+class StoredToken:
+ token: str
+ path: Path
+ created: bool
+
+
+def configured_tokens(env: Mapping[str, str]) -> tuple[str, ...]:
+ """Tokens from ``SIE_AUTH_TOKENS``, else ``SIE_AUTH_TOKEN``, as the gateway reads them."""
+ for name in (AUTH_TOKENS_ENV, AUTH_TOKEN_ENV):
+ tokens = tuple(part.strip() for part in env.get(name, "").split(",") if part.strip())
+ if tokens:
+ return tokens
+ return ()
+
+
+def requested_mode(env: Mapping[str, str]) -> str | None:
+ """``SIE_AUTH_MODE`` without surrounding whitespace, or ``None`` when it is unset or empty.
+
+ Values are case-sensitive, as the gateway reads them.
+ """
+ raw = env.get(AUTH_MODE_ENV, "").strip()
+ return raw or None
+
+
+def declares_tokens(env: Mapping[str, str]) -> bool:
+ """Whether ``SIE_AUTH_TOKENS`` or ``SIE_AUTH_TOKEN`` is present, even with a blank value."""
+ return AUTH_TOKENS_ENV in env or AUTH_TOKEN_ENV in env
+
+
+def resolve_auth_mode(
+ requested: str | None, *, has_tokens: bool, exposed: bool, declares_tokens: bool = False
+) -> AuthMode:
+ """Decide whether requests need a token.
+
+ A configured token is never dead configuration: it turns auth on unless
+ ``SIE_AUTH_MODE=none`` says otherwise, and that combination is refused.
+ A token variable that is present but holds no token is refused too, unless
+ the mode is ``none``, because it reads as an attempt to set a token.
+ ``auto`` also turns auth on for a bind that other machines can reach.
+ """
+ if requested is not None and requested not in _KNOWN_MODES:
+ raise AuthConfigError(f"{AUTH_MODE_ENV} must be one of none, token, static or auto (lowercase).")
+ if declares_tokens and not has_tokens and requested != "none":
+ raise AuthConfigError(
+ f"{AUTH_TOKENS_ENV} or {AUTH_TOKEN_ENV} is set but holds no token, for example an empty or unset "
+ f"variable passed through. Set it to a token, or remove it."
+ )
+ if requested in _TOKEN_MODES:
+ return "token"
+ if requested == "none":
+ if has_tokens:
+ raise AuthConfigError(
+ f"{AUTH_TOKENS_ENV} or {AUTH_TOKEN_ENV} is set but {AUTH_MODE_ENV}=none turns authentication "
+ f"off. Unset {AUTH_MODE_ENV} or set it to token to enforce the token, or remove the token."
+ )
+ return "none"
+ if has_tokens:
+ return "token"
+ if requested == "auto" and exposed:
+ return "token"
+ return "none"
+
+
+def is_loopback_host(host: str) -> bool:
+ """Whether a bind address is reachable only from this machine."""
+ candidate = host.strip().strip("[]")
+ if candidate.lower() == "localhost":
+ return True
+ try:
+ return ipaddress.ip_address(candidate).is_loopback
+ except ValueError:
+ return False
+
+
+def loopback_host_allowlist(bind_host: str) -> frozenset[str]:
+ """Host header values a loopback server answers: the loopback names plus its own bind address."""
+ candidate = bind_host.strip().lower().strip("[]")
+ if not candidate:
+ return LOOPBACK_HOST_NAMES
+ return LOOPBACK_HOST_NAMES | {f"[{candidate}]" if ":" in candidate else candidate}
+
+
+def request_host(headers: Iterable[tuple[bytes, bytes]]) -> str | None:
+ """The request's Host without its port, lowercased; ``None`` when absent or malformed."""
+ for name, value in headers:
+ if name != b"host":
+ continue
+ raw = value.decode("latin-1").strip().lower()
+ if raw.startswith("["):
+ host, bracket, rest = raw.partition("]")
+ host += bracket
+ else:
+ host, _, port = raw.partition(":")
+ rest = f":{port}" if port else ""
+ if not _bracket_ok(host) or (rest and not (rest.startswith(":") and rest[1:].isdigit())):
+ return None
+ return host
+ return None
+
+
+def _bracket_ok(host: str) -> bool:
+ return bool(host) and (not host.startswith("[") or host.endswith("]"))
+
+
+def token_path(directory: Path) -> Path:
+ return directory / TOKEN_FILE_NAME
+
+
+def load_or_create_token(directory: Path) -> StoredToken:
+ """Read the persisted token, generating it on first use.
+
+ An existing token is read without writing to the directory, so a read-only
+ directory or volume works once it holds the token. A new token appears at
+ its path complete or not at all: it is written to a private temporary file
+ and hard-linked into place, which fails if another process created the
+ token first.
+ """
+ path = token_path(directory)
+ try:
+ ensure_data_dir(directory)
+ except OSError as exc:
+ raise TokenFileError(f"Cannot create {directory}: {exc.strerror or exc}") from exc
+ check_private_directory(directory)
+ remove_stale_files(directory, _TEMP_NAME)
+ if os.path.lexists(path):
+ return StoredToken(token=read_stored_token(directory), path=path, created=False)
+ token = secrets.token_urlsafe(_GENERATED_TOKEN_BYTES)
+ staged = directory / f"{_TEMP_PREFIX}{secrets.token_hex(8)}"
+ try:
+ fd = os.open(staged, os.O_WRONLY | os.O_CREAT | os.O_EXCL | _O_NOFOLLOW, 0o600)
+ except OSError as exc:
+ if exc.errno in _READ_ONLY_ERRNOS and os.path.lexists(path):
+ return StoredToken(token=read_stored_token(directory), path=path, created=False)
+ raise TokenFileError(f"Cannot create {staged}: {exc.strerror or exc}") from exc
+ try:
+ try:
+ os.write(fd, f"{token}\n".encode())
+ os.fsync(fd)
+ finally:
+ os.close(fd)
+ os.link(staged, path)
+ except FileExistsError:
+ return StoredToken(token=read_stored_token(directory), path=path, created=False)
+ except OSError as exc:
+ raise TokenFileError(f"Cannot create {path} from {staged}: {exc.strerror or exc}") from exc
+ finally:
+ staged.unlink(missing_ok=True)
+ return StoredToken(token=token, path=path, created=True)
+
+
+def check_private_directory(directory: Path) -> None:
+ """Refuse a token directory that another user owns or can write to."""
+ try:
+ info = directory.stat()
+ except OSError as exc:
+ raise TokenFileError(f"Cannot read {directory}: {exc.strerror or exc}") from exc
+ if not stat.S_ISDIR(info.st_mode):
+ raise TokenFileError(f"{directory} must be a directory.")
+ if info.st_uid != os.getuid():
+ raise TokenFileError(f"{directory} must be owned by the user that runs sie-server.")
+ if stat.S_IMODE(info.st_mode) & 0o022:
+ raise TokenFileError(f"{directory} must not be writable by others (chmod 700 {directory}).")
+
+
+def read_stored_token(directory: Path) -> str:
+ """Read the persisted token, refusing a file that others could read or replace."""
+ check_private_directory(directory)
+ path = token_path(directory)
+ try:
+ fd = os.open(path, os.O_RDONLY | _O_NOFOLLOW | os.O_NONBLOCK)
+ except OSError as exc:
+ if exc.errno == errno.ELOOP:
+ raise TokenFileError(f"{path} is a symbolic link; it must be a regular file.") from exc
+ raise TokenFileError(f"Cannot read {path}: {exc.strerror or exc}") from exc
+ try:
+ info = os.fstat(fd)
+ if not stat.S_ISREG(info.st_mode):
+ raise TokenFileError(f"{path} must be a regular file.")
+ if info.st_nlink != 1 and not _drop_temporary_links(path, fd, info):
+ raise TokenFileError(
+ f"{path} must not have other hard links. Remove the other link, or delete {path} to have "
+ f"sie-server generate a new token."
+ )
+ if info.st_uid != os.getuid():
+ raise TokenFileError(f"{path} must be owned by the user that runs sie-server.")
+ if stat.S_IMODE(info.st_mode) & 0o077:
+ raise TokenFileError(f"{path} must not be readable or writable by others (chmod 600 {path}).")
+ raw = os.read(fd, _MAX_TOKEN_FILE_BYTES + 1)
+ finally:
+ os.close(fd)
+ if len(raw) > _MAX_TOKEN_FILE_BYTES:
+ raise TokenFileError(f"{path} is too large to be a token.")
+ token = raw.decode("ascii", errors="replace").strip()
+ if not token or any(not ("!" <= ch <= "~") or ch == "," for ch in token):
+ raise TokenFileError(
+ f"{path} must hold one token: printable ASCII without spaces or commas. "
+ f"Delete {path} to have sie-server generate a new token."
+ )
+ return token
+
+
+def _drop_temporary_links(path: Path, fd: int, token: os.stat_result) -> bool:
+ """Remove the temporary links a concurrent or interrupted first start left on the token.
+
+ True when every extra hard link of the token is such a file, even if a
+ read-only directory keeps them in place; any other link is left alone and
+ the token is refused. The link count is read again after the scan, so a
+ concurrent start that removes its own link meanwhile is not mistaken for a
+ foreign link.
+ """
+ try:
+ linked = [
+ entry
+ for entry, info in owned_files(path.parent, _TEMP_NAME)
+ if (info.st_dev, info.st_ino) == (token.st_dev, token.st_ino)
+ ]
+ except OSError:
+ return False
+ if os.fstat(fd).st_nlink not in (1, len(linked) + 1):
+ return False
+ for entry in linked:
+ try:
+ entry.unlink(missing_ok=True)
+ except OSError:
+ continue
+ return True
+
+
+def server_tokens(env: Mapping[str, str]) -> tuple[str, ...]:
+ """The tokens a server in ``token`` mode accepts: the configured ones, else the persisted one."""
+ tokens = configured_tokens(env)
+ if tokens:
+ return tokens
+ directory = resolve_data_dir()
+ if directory is None:
+ raise TokenFileError(f"No token is configured and there is no data directory; set {AUTH_TOKEN_ENV}.")
+ return (read_stored_token(directory),)
+
+
+def request_credentials(headers: Iterable[tuple[bytes, bytes]]) -> set[bytes]:
+ """The distinct tokens a request presents, as the gateway reads them.
+
+ ``Authorization`` (``Bearer <token>`` in any case, or the bare token) takes
+ precedence: when it carries a token, ``x-api-key`` is ignored. Otherwise the
+ ``x-api-key`` values count. Empty values are ignored. More than one distinct
+ token means repeated headers that disagree.
+ """
+ authorization: set[bytes] = set()
+ api_key: set[bytes] = set()
+ for name, value in headers:
+ if name == b"authorization":
+ credential = value.strip()
+ if credential[:7].lower() == b"bearer ":
+ credential = credential[7:].strip()
+ if credential:
+ authorization.add(credential)
+ elif name == b"x-api-key":
+ credential = value.strip()
+ if credential:
+ api_key.add(credential)
+ return authorization or api_key
+
+
+class ServerAuthMiddleware:
+ """Require a token on every HTTP and WebSocket route except the probes."""
+
+ def __init__(self, app: ASGIApp, tokens: Sequence[str]) -> None:
+ if not tokens:
+ raise ValueError("ServerAuthMiddleware needs at least one token")
+ self.app = app
+ self._tokens = tuple(token.encode() for token in tokens)
+
+ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
+ if scope["type"] not in ("http", "websocket") or scope["path"] in EXEMPT_PATHS:
+ await self.app(scope, receive, send)
+ return
+ rejection = self._rejection(request_credentials(scope["headers"]))
+ if rejection is None:
+ await self.app(scope, receive, send)
+ return
+ await _reject(scope, receive, send, _unauthorized(rejection))
+
+ def _rejection(self, presented: set[bytes]) -> str | None:
+ if not presented:
+ return "Missing credentials: send Authorization: Bearer <token> or x-api-key: <token>"
+ if len(presented) > 1:
+ return "Repeated credential headers carry different tokens"
+ (credential,) = presented
+ matches = [hmac.compare_digest(credential, token) for token in self._tokens]
+ if any(matches):
+ return None
+ return "Invalid token"
+
+
+def _describe_hosts(allowed: frozenset[str]) -> str:
+ names = ["localhost", "127.0.0.1", "[::1]", *sorted(allowed - LOOPBACK_HOST_NAMES)]
+ return f"{', '.join(names[:-1])} or {names[-1]}"
+
+
+class LoopbackHostMiddleware:
+ """Watch for Host headers that do not name this machine, which is what a DNS-rebinding page sends.
+
+ Until 0.13.0 such a request is answered, and a warning is logged once per
+ Host. With ``enforce`` it is refused with 400.
+ """
+
+ def __init__(self, app: ASGIApp, allowed_hosts: Iterable[str], *, enforce: bool = False) -> None:
+ self.app = app
+ self._allowed = frozenset(allowed_hosts)
+ self._enforce = enforce
+ self._hosts = _describe_hosts(self._allowed)
+ self._warned: set[str | None] = set()
+
+ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
+ if scope["type"] not in ("http", "websocket"):
+ await self.app(scope, receive, send)
+ return
+ host = request_host(scope["headers"])
+ if host in self._allowed:
+ await self.app(scope, receive, send)
+ return
+ if self._enforce:
+ message = f"This server listens on loopback and answers only requests addressed to {self._hosts}."
+ await _reject(scope, receive, send, _Rejection(400, "INVALID_INPUT", message))
+ return
+ self._warn(host)
+ await self.app(scope, receive, send)
+
+ def _warn(self, host: str | None) -> None:
+ key = None if host is None else host[:_MAX_LOGGED_HOST_CHARS]
+ if key in self._warned or len(self._warned) >= _MAX_WARNED_HOSTS:
+ return
+ self._warned.add(key)
+ shown = "(none)" if key is None else repr(key)
+ logger.warning(
+ "A request with Host %s reached this loopback server, which has authentication off. From %s "
+ "sie-server refuses such requests with 400, because a web page can send them through DNS "
+ "rebinding. Address the server as %s, or turn on token authentication.",
+ shown,
+ _HOST_CHECK_RELEASE,
+ self._hosts,
+ )
+
+
+@dataclass(frozen=True)
+class _Rejection:
+ status: int
+ code: str
+ message: str
+
+
+def _unauthorized(message: str) -> _Rejection:
+ return _Rejection(401, "UNAUTHORIZED", message)
+
+
+async def _reject(scope: Scope, receive: Receive, send: Send, rejection: _Rejection) -> None:
+ body = orjson.dumps({"detail": {"code": rejection.code, "message": rejection.message}})
+ headers = [(b"content-type", b"application/json"), (b"content-length", str(len(body)).encode())]
+ if rejection.status == 401:
+ headers.append((b"www-authenticate", b"Bearer"))
+ if scope["type"] == "http":
+ await send({"type": "http.response.start", "status": rejection.status, "headers": headers})
+ await send({"type": "http.response.body", "body": body})
+ return
+ connect = await receive()
+ if connect["type"] != "websocket.connect":
+ return
+ if "websocket.http.response" in (scope.get("extensions") or {}):
+ await send({"type": "websocket.http.response.start", "status": rejection.status, "headers": headers})
+ await send({"type": "websocket.http.response.body", "body": body})
+ return
+ await send({"type": "websocket.close", "code": 1008})
diff --git a/packages/sie_server/src/sie_server/observability/telemetry.py b/packages/sie_server/src/sie_server/observability/telemetry.py
index d771aff52..7e49df33f 100644
--- a/packages/sie_server/src/sie_server/observability/telemetry.py
+++ b/packages/sie_server/src/sie_server/observability/telemetry.py
@@ -4,6 +4,9 @@ import logging
import os
import platform
import random
+import re
+import secrets
+import stat
import uuid
from collections.abc import AsyncGenerator
from contextlib import asynccontextmanager
@@ -12,6 +15,7 @@ from pathlib import Path
import httpx
+from sie_server.core.data_dir import ensure_data_dir, remove_stale_files, resolve_data_dir
from sie_server.observability.gpu import get_gpu_metrics
logger = logging.getLogger(__name__)
@@ -26,6 +30,11 @@ _UPDATE_MIN_S = 55 * 60 # 55 minutes
_UPDATE_MAX_S = 65 * 60 # 65 minutes
_SEND_TIMEOUT_S = 10
+_WORKER_ID_FILE = "worker-id"
+_WORKER_ID_TEMP_PREFIX = f".{_WORKER_ID_FILE}.sie-server-"
+_WORKER_ID_TEMP_NAME = re.compile(rf"{re.escape(_WORKER_ID_TEMP_PREFIX)}[0-9a-f]{{16}}")
+_MAX_WORKER_ID_BYTES = 64
+_O_NOFOLLOW = getattr(os, "O_NOFOLLOW", 0)
_CONSECUTIVE_FAILURE_WARN_THRESHOLD = 3
_DEFAULT_ENABLED = True
@@ -73,30 +82,61 @@ def _warn_default_on_once() -> None:
logger.warning(_DEFAULT_ON_NOTICE)
-def _get_or_create_worker_id(data_dir: str | None = None) -> str:
- if data_dir is None:
- data_dir = os.environ.get("SIE_DATA_DIR", "/tmp/sie-server") # noqa: S108
-
- id_path = os.path.join(data_dir, "worker-id")
+def _read_worker_id(path: Path) -> str | None:
+ """The stored worker id; ``None`` when the file is missing, not a regular file, or not a UUID."""
+ try:
+ fd = os.open(path, os.O_RDONLY | _O_NOFOLLOW | os.O_NONBLOCK)
+ except OSError:
+ return None
+ try:
+ if not stat.S_ISREG(os.fstat(fd).st_mode):
+ return None
+ raw = os.read(fd, _MAX_WORKER_ID_BYTES + 1)
+ except OSError:
+ return None
+ finally:
+ os.close(fd)
+ existing = raw.decode("ascii", errors="replace").strip()
+ try:
+ uuid.UUID(existing)
+ except ValueError:
+ return None
+ return existing
- # Try to read existing ID
- id_file = Path(id_path)
- # Try to read existing ID
+def _store_worker_id(directory: Path, path: Path, worker_id: str) -> None:
+ """Replace whatever is at ``path`` with ``worker_id``, never writing through a link."""
+ staged = directory / f"{_WORKER_ID_TEMP_PREFIX}{secrets.token_hex(8)}"
+ fd = os.open(staged, os.O_WRONLY | os.O_CREAT | os.O_EXCL | _O_NOFOLLOW, 0o600)
try:
- existing = id_file.read_text().strip()
- uuid.UUID(existing) # validate
+ try:
+ os.write(fd, worker_id.encode())
+ finally:
+ os.close(fd)
+ staged.replace(path)
+ except OSError:
+ staged.unlink(missing_ok=True)
+ raise
+
+
+def _get_or_create_worker_id(data_dir: str | None = None) -> str:
+ if data_dir is None:
+ resolved = resolve_data_dir()
+ if resolved is None:
+ return str(uuid.uuid4())
+ data_dir = str(resolved)
+
+ directory = Path(data_dir)
+ id_path = directory / _WORKER_ID_FILE
+ remove_stale_files(directory, _WORKER_ID_TEMP_NAME)
+ existing = _read_worker_id(id_path)
+ if existing is not None:
return existing
- except (OSError, ValueError):
- pass
- # Generate new ID
new_id = str(uuid.uuid4())
-
- # Try to persist
try:
- Path(data_dir).mkdir(parents=True, exist_ok=True)
- id_file.write_text(new_id)
+ ensure_data_dir(directory)
+ _store_worker_id(directory, id_path, new_id)
except OSError:
logger.debug("Could not persist worker ID to %s, using ephemeral ID", id_path)
diff --git a/packages/sie_server/tests/core/test_server_auth.py b/packages/sie_server/tests/core/test_server_auth.py
new file mode 100644
index 000000000..3458507d0
--- /dev/null
+++ b/packages/sie_server/tests/core/test_server_auth.py
@@ -0,0 +1,831 @@
+"""Token authentication for sie-server: resolution, the persisted token, and the middleware."""
+
+from __future__ import annotations
+
+import asyncio
+import errno
+import logging
+import os
+import re
+import stat
+import subprocess
+import sys
+import threading
+import time
+from collections.abc import Callable, Iterator
+from pathlib import Path
+from typing import Any
+
+import pytest
+from fastapi import FastAPI, WebSocket
+from fastapi.testclient import TestClient
+from sie_server.app.app_factory import AppFactory
+from sie_server.app.app_state_config import AppStateConfig
+from sie_server.core.data_dir import resolve_data_dir
+from sie_server.core.server_auth import (
+ AuthConfigError,
+ LoopbackHostMiddleware,
+ ServerAuthMiddleware,
+ TokenFileError,
+ configured_tokens,
+ is_loopback_host,
+ load_or_create_token,
+ loopback_host_allowlist,
+ read_stored_token,
+ request_credentials,
+ request_host,
+ resolve_auth_mode,
+ server_tokens,
+ token_path,
+)
+from sie_server.observability.telemetry import _get_or_create_worker_id
+from starlette.testclient import WebSocketDenialResponse
+
+TOKEN = "s3cret-token-value" # noqa: S105 - test credential
+OTHER = "another-token-value"
+
+
[email protected](autouse=True)
+def _clean_auth_env(monkeypatch: pytest.MonkeyPatch) -> Iterator[None]:
+ saved = dict(os.environ)
+ for name in (
+ "SIE_AUTH_MODE",
+ "SIE_AUTH_TOKEN",
+ "SIE_AUTH_TOKENS",
+ "SIE_DATA_DIR",
+ "SIE_SERVER_HOST",
+ "XDG_DATA_HOME",
+ ):
+ monkeypatch.delenv(name, raising=False)
+ yield
+ os.environ.clear()
+ os.environ.update(saved)
+
+
+class TestResolveAuthMode:
+ @pytest.mark.parametrize(
+ ("requested", "has_tokens", "exposed", "expected"),
+ [
+ (None, False, False, "none"),
+ (None, False, True, "none"),
+ (None, True, False, "token"),
+ (None, True, True, "token"),
+ ("token", False, False, "token"),
+ ("static", False, True, "token"),
+ ("auto", False, False, "none"),
+ ("auto", False, True, "token"),
+ ("auto", True, False, "token"),
+ ("none", False, False, "none"),
+ ("none", False, True, "none"),
+ ],
+ )
+ def test_resolution(self, requested: str | None, has_tokens: bool, exposed: bool, expected: str) -> None:
+ assert resolve_auth_mode(requested, has_tokens=has_tokens, exposed=exposed) == expected
+
+ def test_a_token_with_auth_explicitly_off_is_refused(self) -> None:
+ with pytest.raises(AuthConfigError, match="SIE_AUTH_MODE=none"):
+ resolve_auth_mode("none", has_tokens=True, exposed=False)
+
+ def test_an_unknown_mode_is_refused(self) -> None:
+ with pytest.raises(AuthConfigError, match="none, token, static or auto"):
+ resolve_auth_mode("open", has_tokens=False, exposed=False)
+
+ @pytest.mark.parametrize("requested", ["TOKEN", "Token", "None", "AUTO"])
+ def test_modes_are_case_sensitive_as_on_the_gateway(self, requested: str) -> None:
+ with pytest.raises(AuthConfigError, match="lowercase"):
+ resolve_auth_mode(requested, has_tokens=False, exposed=False)
+
+ @pytest.mark.parametrize("requested", [None, "token", "static", "auto"])
+ def test_a_declared_but_blank_token_is_refused(self, requested: str | None) -> None:
+ with pytest.raises(AuthConfigError, match="holds no token"):
+ resolve_auth_mode(requested, has_tokens=False, exposed=True, declares_tokens=True)
+
+ def test_a_blank_token_with_auth_explicitly_off_is_harmless(self) -> None:
+ assert resolve_auth_mode("none", has_tokens=False, exposed=True, declares_tokens=True) == "none"
+
+
+class TestConfiguredTokens:
+ def test_tokens_variable_wins_over_token(self) -> None:
+ env = {"SIE_AUTH_TOKENS": " a , b,,", "SIE_AUTH_TOKEN": "c"}
+ assert configured_tokens(env) == ("a", "b")
+
+ def test_single_token_variable_is_comma_separated_too(self) -> None:
+ assert configured_tokens({"SIE_AUTH_TOKEN": "c,d"}) == ("c", "d")
+
+ def test_blank_values_configure_nothing(self) -> None:
+ assert configured_tokens({"SIE_AUTH_TOKENS": " , ", "SIE_AUTH_TOKEN": ""}) == ()
+
+
+class TestIsLoopbackHost:
+ @pytest.mark.parametrize("host", ["127.0.0.1", "127.8.9.10", "::1", "[::1]", "localhost", "LOCALHOST"])
+ def test_loopback(self, host: str) -> None:
+ assert is_loopback_host(host)
+
+ @pytest.mark.parametrize("host", ["0.0.0.0", "::", "192.168.1.20", "10.0.0.1", "example.com", ""]) # noqa: S104
+ def test_exposed(self, host: str) -> None:
+ assert not is_loopback_host(host)
+
+
+class TestDataDir:
+ def test_explicit_directory_wins(self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
+ monkeypatch.setenv("SIE_DATA_DIR", str(tmp_path / "data"))
+ monkeypatch.setenv("XDG_DATA_HOME", str(tmp_path / "xdg"))
+ assert resolve_data_dir() == tmp_path / "data"
+
+ def test_xdg_data_home(self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
+ monkeypatch.setenv("XDG_DATA_HOME", str(tmp_path))
+ assert resolve_data_dir() == tmp_path / "sie"
+
+ def test_relative_xdg_data_home_is_ignored(self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
+ monkeypatch.setenv("XDG_DATA_HOME", "relative")
+ monkeypatch.setenv("HOME", str(tmp_path))
+ assert resolve_data_dir() == tmp_path / ".local" / "share" / "sie"
+
+ def test_default_is_per_user(self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
+ monkeypatch.setenv("HOME", str(tmp_path))
+ assert resolve_data_dir() == tmp_path / ".local" / "share" / "sie"
+
+
+class TestPersistedToken:
+ def test_first_use_creates_a_private_token(self, tmp_path: Path) -> None:
+ directory = tmp_path / "sie"
+ stored = load_or_create_token(directory)
+
+ assert stored.created
+ assert stored.path == token_path(directory)
+ assert len(stored.token) >= 43
+ assert stat.S_IMODE(stored.path.stat().st_mode) == 0o600
+ assert stat.S_IMODE(directory.stat().st_mode) & 0o077 == 0
+ assert stored.path.read_text() == f"{stored.token}\n"
+
+ def test_later_use_reads_the_same_token(self, tmp_path: Path) -> None:
+ first = load_or_create_token(tmp_path)
+ second = load_or_create_token(tmp_path)
+
+ assert not second.created
+ assert second.token == first.token
+
+ def test_a_token_others_can_read_is_refused(self, tmp_path: Path) -> None:
+ stored = load_or_create_token(tmp_path)
+ stored.path.chmod(0o644)
+
+ with pytest.raises(TokenFileError, match="chmod 600"):
+ read_stored_token(tmp_path)
+
+ def test_concurrent_first_starts_agree_on_one_token(self, tmp_path: Path) -> None:
+ for trial in range(10):
+ directory = tmp_path / f"trial-{trial}"
+ starts = [
+ subprocess.Popen( # noqa: S603
+ [sys.executable, "-c", _FIRST_START_SCRIPT, str(directory)],
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE,
+ text=True,
+ )
+ for _ in range(6)
+ ]
+ results = [start.communicate(timeout=60) for start in starts]
+ assert [start.returncode for start in starts] == [0] * 6, results
+ assert len({out.strip() for out, _ in results}) == 1
+ assert [entry.name for entry in directory.iterdir()] == ["auth-token"]
+ assert token_path(directory).stat().st_nlink == 1
+
+ def test_an_empty_token_file_names_the_file_to_delete(self, tmp_path: Path) -> None:
+ path = token_path(tmp_path)
+ path.touch(mode=0o600)
+
+ with pytest.raises(TokenFileError, match=f"Delete {re.escape(str(path))}"):
+ load_or_create_token(tmp_path)
+
+ def test_a_fifo_is_refused_without_blocking(self, tmp_path: Path) -> None:
+ os.mkfifo(token_path(tmp_path), 0o600)
+ outcome: list[BaseException] = []
+ reader = threading.Thread(target=_capture, args=(lambda: read_stored_token(tmp_path), outcome), daemon=True)
+ reader.start()
+ reader.join(timeout=5)
+
+ assert not reader.is_alive(), "reading a FIFO token path blocked"
+ assert isinstance(outcome[0], TokenFileError)
+ assert "must be a regular file" in str(outcome[0])
+
+ def test_a_temporary_link_left_by_an_interrupted_start_is_dropped(self, tmp_path: Path) -> None:
+ stored = load_or_create_token(tmp_path)
+ staged = tmp_path / ".auth-token.sie-server-0123456789abcdef"
+ os.link(stored.path, staged)
+
+ assert read_stored_token(tmp_path) == stored.token
+ assert not staged.exists()
+ assert stored.path.stat().st_nlink == 1
+
+ def test_a_concurrent_start_that_removes_its_temporary_link_mid_read_is_accepted(
+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ stored = load_or_create_token(tmp_path)
+ staged = tmp_path / ".auth-token.sie-server-0123456789abcdef"
+ os.link(stored.path, staged)
+ real_fstat = os.fstat
+ seen: list[int] = []
+
+ def fstat_then_the_other_start_unlinks(fd: int) -> os.stat_result:
+ info = real_fstat(fd)
+ if not seen:
+ seen.append(info.st_nlink)
+ staged.unlink()
+ return info
+
+ monkeypatch.setattr(os, "fstat", fstat_then_the_other_start_unlinks)
+
+ assert read_stored_token(tmp_path) == stored.token
+ assert seen == [2]
+
+ def test_a_temporary_link_in_a_directory_without_write_permission_is_tolerated(self, tmp_path: Path) -> None:
+ directory = tmp_path / "sie"
+ stored = load_or_create_token(directory)
+ os.link(stored.path, directory / ".auth-token.sie-server-0123456789abcdef")
+ directory.chmod(0o500)
+ try:
+ assert read_stored_token(directory) == stored.token
+ finally:
+ directory.chmod(0o700)
+
+ @pytest.mark.parametrize("name", [".auth-token.bak", ".auth-token.0123456789abcdef"])
+ def test_a_users_link_named_like_a_temporary_file_is_kept_and_refused(self, tmp_path: Path, name: str) -> None:
+ stored = load_or_create_token(tmp_path)
+ backup = tmp_path / name
+ os.link(stored.path, backup)
+
+ with pytest.raises(TokenFileError, match="hard links"):
+ read_stored_token(tmp_path)
+ assert backup.exists()
+
+ def test_only_old_temporary_files_of_the_server_are_cleaned_up(self, tmp_path: Path) -> None:
+ old = time.time() - 600
+ orphan = tmp_path / ".auth-token.sie-server-00000000000000aa"
+ in_flight = tmp_path / ".auth-token.sie-server-00000000000000bb"
+ users = tmp_path / ".auth-token.backup"
+ for path in (orphan, in_flight, users):
+ path.write_text("unused\n")
+ path.chmod(0o600)
+ for path in (orphan, users):
+ os.utime(path, (old, old))
+
+ load_or_create_token(tmp_path)
+
+ assert not orphan.exists()
+ assert in_flight.exists()
+ assert users.exists()
+
+ def test_an_existing_token_in_a_directory_without_write_permission_is_read(self, tmp_path: Path) -> None:
+ directory = tmp_path / "sie"
+ stored = load_or_create_token(directory)
+ directory.chmod(0o500)
+ try:
+ again = load_or_create_token(directory)
+ finally:
+ directory.chmod(0o700)
+
+ assert not again.created
+ assert again.token == stored.token
+
+ def test_an_existing_token_is_read_without_creating_a_file(
+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ stored = load_or_create_token(tmp_path)
+ creates = _record_creates_in(tmp_path, monkeypatch)
+
+ assert load_or_create_token(tmp_path).token == stored.token
+ assert creates == []
+
+ @pytest.mark.parametrize("code", [errno.EACCES, errno.EROFS])
+ def test_a_token_that_appears_while_the_directory_refuses_writes_is_read(
+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, code: int
+ ) -> None:
+ def another_start_finished_first() -> None:
+ token_path(tmp_path).write_text(f"{TOKEN}\n")
+ token_path(tmp_path).chmod(0o600)
+
+ _refuse_creates_in(tmp_path, monkeypatch, code, before=another_start_finished_first)
+
+ stored = load_or_create_token(tmp_path)
+
+ assert not stored.created
+ assert stored.token == TOKEN
+
+ def test_a_read_only_volume_without_a_token_names_the_temporary_file(
+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ _refuse_creates_in(tmp_path, monkeypatch, errno.EROFS)
+
+ with pytest.raises(TokenFileError, match=r"Cannot create .*/\.auth-token\.sie-server-[0-9a-f]{16}: "):
+ load_or_create_token(tmp_path)
+
+ def test_a_hard_linked_token_is_refused(self, tmp_path: Path) -> None:
+ stored = load_or_create_token(tmp_path)
+ os.link(stored.path, tmp_path / "copy")
+
+ with pytest.raises(TokenFileError, match="hard links"):
+ read_stored_token(tmp_path)
+
+ @pytest.mark.parametrize("mode", [0o770, 0o707, 0o777])
+ def test_a_directory_others_can_write_is_refused(self, tmp_path: Path, mode: int) -> None:
+ directory = tmp_path / "shared"
+ directory.mkdir()
+ directory.chmod(mode)
+
+ with pytest.raises(TokenFileError, match="chmod 700"):
+ load_or_create_token(directory)
+ assert not token_path(directory).exists()
+
+ def test_a_directory_of_another_user_is_refused(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ load_or_create_token(tmp_path)
+ monkeypatch.setattr(os, "getuid", lambda: tmp_path.stat().st_uid + 1)
+
+ with pytest.raises(TokenFileError, match="must be owned by the user"):
+ read_stored_token(tmp_path)
+
+ def test_the_worker_id_is_never_written_through_a_symbolic_link(self, tmp_path: Path) -> None:
+ target = tmp_path / "elsewhere"
+ (tmp_path / "worker-id").symlink_to(target)
+
+ _get_or_create_worker_id(str(tmp_path))
+
+ assert not target.exists()
+
+ def test_a_symbolic_link_is_refused(self, tmp_path: Path) -> None:
+ target = tmp_path / "elsewhere"
+ target.write_text(f"{TOKEN}\n")
+ target.chmod(0o600)
+ token_path(tmp_path).symlink_to(target)
+
+ with pytest.raises(TokenFileError, match="symbolic link"):
+ load_or_create_token(tmp_path)
+
+ @pytest.mark.parametrize("content", ["", "\n", "two tokens\n", "a,b\n", "tokén\n"])
+ def test_malformed_content_is_refused(self, tmp_path: Path, content: str) -> None:
+ path = token_path(tmp_path)
+ path.write_text(content, encoding="utf-8")
+ path.chmod(0o600)
+
+ with pytest.raises(TokenFileError, match="must hold one token"):
+ read_stored_token(tmp_path)
+
+ def test_server_tokens_prefer_the_configured_ones(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setenv("SIE_DATA_DIR", str(tmp_path))
+ load_or_create_token(tmp_path)
+
+ assert server_tokens({"SIE_AUTH_TOKEN": TOKEN}) == (TOKEN,)
+
+ def test_server_tokens_fall_back_to_the_persisted_one(
+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ monkeypatch.setenv("SIE_DATA_DIR", str(tmp_path))
+ stored = load_or_create_token(tmp_path)
+
+ assert server_tokens(os.environ) == (stored.token,)
+
+ def test_server_tokens_never_generate_one(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setenv("SIE_DATA_DIR", str(tmp_path))
+
+ with pytest.raises(TokenFileError):
+ server_tokens(os.environ)
+ assert not token_path(tmp_path).exists()
+
+
+def _plain_app() -> FastAPI:
+ app = FastAPI()
+
+ @app.get("/healthz")
+ def healthz() -> str:
+ return "ok"
+
+ @app.get("/v1/thing")
+ def thing() -> dict[str, bool]:
+ return {"ok": True}
+
+ @app.websocket("/ws/status")
+ async def status(websocket: WebSocket) -> None:
+ await websocket.accept()
+ await websocket.send_json({"ready": True})
+ await websocket.close()
+
+ return app
+
+
+def _protected_app(tokens: tuple[str, ...] = (TOKEN, OTHER)) -> FastAPI:
+ app = _plain_app()
+ app.add_middleware(ServerAuthMiddleware, tokens=tokens)
+ return app
+
+
+class TestMiddleware:
+ @pytest.fixture
+ def client(self) -> TestClient:
+ return TestClient(_protected_app())
+
+ def test_probes_need_no_token(self, client: TestClient) -> None:
+ assert client.get("/healthz").status_code == 200
+
+ def test_a_trailing_slash_is_not_a_probe(self, client: TestClient) -> None:
+ assert client.get("/healthz/").status_code == 401
+
+ def test_missing_credentials(self, client: TestClient) -> None:
+ response = client.get("/v1/thing")
+
+ assert response.status_code == 401
+ assert response.headers["www-authenticate"] == "Bearer"
+ assert response.json()["detail"]["code"] == "UNAUTHORIZED"
+
+ @pytest.mark.parametrize(
+ "headers",
+ [
+ {"Authorization": f"Bearer {TOKEN}"},
+ {"Authorization": f"bearer {TOKEN}"},
+ {"Authorization": f" Bearer {TOKEN} "},
+ {"Authorization": TOKEN},
+ {"x-api-key": TOKEN},
+ {"X-API-Key": OTHER},
+ {"Authorization": f"Bearer {TOKEN}", "x-api-key": TOKEN},
+ {"Authorization": f"Bearer {TOKEN}", "x-api-key": OTHER},
+ {"Authorization": f"Bearer {TOKEN}", "x-api-key": "wrong"},
+ {"Authorization": "", "x-api-key": TOKEN},
+ ],
+ )
+ def test_accepted_credentials(self, client: TestClient, headers: dict[str, str]) -> None:
+ assert client.get("/v1/thing", headers=headers).status_code == 200
+
+ @pytest.mark.parametrize(
+ ("headers", "message"),
+ [
+ ({"Authorization": "Bearer wrong"}, "Invalid token"),
+ ({"x-api-key": "wrong"}, "Invalid token"),
+ ({"Authorization": f"Bearer {TOKEN[:-1]}"}, "Invalid token"),
+ ({"Authorization": f"Basic {TOKEN}"}, "Invalid token"),
+ ({"Authorization": "Bearer"}, "Invalid token"),
+ ({"Authorization": "", "x-api-key": ""}, "Missing credentials"),
+ ({"Authorization": "Bearer wrong", "x-api-key": TOKEN}, "Invalid token"),
+ ],
+ )
+ def test_refused_credentials(self, client: TestClient, headers: dict[str, str], message: str) -> None:
+ response = client.get("/v1/thing", headers=headers)
+
+ assert response.status_code == 401
+ assert message in response.json()["detail"]["message"]
+
+ @pytest.mark.parametrize(
+ "headers",
+ [
+ [("Authorization", f"Bearer {TOKEN}"), ("Authorization", f"Bearer {OTHER}")],
+ [("Authorization", f"Bearer {TOKEN}"), ("Authorization", "Bearer wrong"), ("x-api-key", TOKEN)],
+ [("x-api-key", TOKEN), ("x-api-key", OTHER)],
+ ],
+ )
+ def test_a_repeated_header_that_disagrees_is_refused(
+ self, client: TestClient, headers: list[tuple[str, str]]
+ ) -> None:
+ # One header repeated with two tokens is not the two-header case, so it stays a refusal.
+ response = client.get("/v1/thing", headers=headers)
+
+ assert response.status_code == 401
+ assert "Repeated credential headers carry different tokens" in response.json()["detail"]["message"]
+
+ def test_websocket_without_a_token_is_denied(self, client: TestClient) -> None:
+ with pytest.raises(WebSocketDenialResponse) as denied, client.websocket_connect("/ws/status"):
+ pass
+ assert denied.value.status_code == 401
+
+ def test_websocket_with_a_token_connects(self, client: TestClient) -> None:
+ with client.websocket_connect("/ws/status", headers={"Authorization": f"Bearer {TOKEN}"}) as websocket:
+ assert websocket.receive_json() == {"ready": True}
+
+ def test_a_middleware_without_tokens_cannot_be_built(self) -> None:
+ with pytest.raises(ValueError, match="at least one token"):
+ TestClient(_protected_app(tokens=())).get("/healthz")
+
+
+class TestRequestCredentials:
+ def test_authorization_decides_when_both_headers_are_sent(self) -> None:
+ headers = [(b"authorization", b"Bearer first"), (b"x-api-key", b"second")]
+ assert request_credentials(headers) == {b"first"}
+
+ def test_x_api_key_alone_decides(self) -> None:
+ assert request_credentials([(b"x-api-key", b" second ")]) == {b"second"}
+
+ def test_an_empty_authorization_leaves_x_api_key_to_decide(self) -> None:
+ assert request_credentials([(b"authorization", b""), (b"x-api-key", b"second")]) == {b"second"}
+
+
+class TestHostAllowlist:
+ @pytest.mark.parametrize(
+ ("host", "expected"),
+ [
+ ("localhost", "localhost"),
+ ("LOCALHOST:8080", "localhost"),
+ ("127.0.0.1:8080", "127.0.0.1"),
+ ("[::1]:8080", "[::1]"),
+ ("[::1]", "[::1]"),
+ ("evil.example", "evil.example"),
+ ("[::1", None),
+ ("localhost:80x", None),
+ ],
+ )
+ def test_request_host(self, host: str, expected: str | None) -> None:
+ assert request_host([(b"host", host.encode())]) == expected
+
+ def test_a_missing_host_matches_nothing(self) -> None:
+ assert request_host([(b"accept", b"*/*")]) is None
+
+ @pytest.mark.parametrize(
+ ("bind", "extra"), [("127.0.0.1", None), ("localhost", None), ("::1", None), ("127.0.0.2", "127.0.0.2")]
+ )
+ def test_allowlist_holds_the_loopback_names_and_the_bind_address(self, bind: str, extra: str | None) -> None:
+ allowed = loopback_host_allowlist(bind)
+ assert {"localhost", "127.0.0.1", "[::1]"} <= allowed
+ if extra:
+ assert extra in allowed
+
+
+def _loopback_client(bind_host: str, base_url: str = "http://localhost:8080", **config: object) -> TestClient:
+ return TestClient(AppFactory.create_app(AppStateConfig(bind_host=bind_host, **config)), base_url=base_url)
+
+
+class TestLoopbackServerApp:
+ @pytest.mark.parametrize("base_url", ["http://localhost:8080", "http://127.0.0.1:8080", "http://localhost"])
+ def test_loopback_clients_are_answered_without_a_warning(
+ self, base_url: str, caplog: pytest.LogCaptureFixture
+ ) -> None:
+ client = _loopback_client("127.0.0.1", base_url)
+
+ with caplog.at_level(logging.WARNING, logger=_AUTH_LOGGER):
+ assert client.get("/openapi.json").status_code == 200
+ assert client.get("/healthz").status_code == 200
+ assert _host_warnings(caplog) == []
+
+ def test_an_ipv6_loopback_host_is_answered(self, caplog: pytest.LogCaptureFixture) -> None:
+ client = _loopback_client("::1")
+
+ with caplog.at_level(logging.WARNING, logger=_AUTH_LOGGER):
+ assert client.get("/openapi.json", headers={"Host": "[::1]:8080"}).status_code == 200
+ assert _host_warnings(caplog) == []
+
+ @pytest.mark.parametrize(
+ "host", ["evil.example", "localhost.evil.example", "evil.example:8080", "0.0.0.0:8080", "host.docker.internal"]
+ )
+ def test_another_host_is_answered_with_one_warning(self, host: str, caplog: pytest.LogCaptureFixture) -> None:
+ client = _loopback_client("127.0.0.1")
+
+ with caplog.at_level(logging.WARNING, logger=_AUTH_LOGGER):
+ assert client.get("/openapi.json", headers={"Host": host}).status_code == 200
+ assert client.get("/healthz", headers={"Host": host}).status_code == 200
+
+ (warning,) = _host_warnings(caplog)
+ assert "0.13.0" in warning
+ assert repr(host.partition(":")[0]) in warning
+
+ def test_another_host_on_a_websocket_connects_with_a_warning(self, caplog: pytest.LogCaptureFixture) -> None:
+ app = _plain_app()
+ app.add_middleware(LoopbackHostMiddleware, allowed_hosts=loopback_host_allowlist("127.0.0.1"))
+ client = TestClient(app)
+
+ with (
+ caplog.at_level(logging.WARNING, logger=_AUTH_LOGGER),
+ client.websocket_connect("/ws/status", headers={"Host": "evil.example"}) as websocket,
+ ):
+ assert websocket.receive_json() == {"ready": True}
+ (warning,) = _host_warnings(caplog)
+ assert "0.13.0" in warning
+
+ def test_a_long_host_is_remembered_and_logged_by_its_first_characters(
+ self, caplog: pytest.LogCaptureFixture
+ ) -> None:
+ client = _loopback_client("127.0.0.1")
+ prefix = "a" * 100
+
+ with caplog.at_level(logging.WARNING, logger=_AUTH_LOGGER):
+ for tail in ("b" * 5000, "c" * 5000):
+ assert client.get("/healthz", headers={"Host": prefix + tail}).status_code == 200
+
+ (warning,) = _host_warnings(caplog)
+ assert repr(prefix) in warning
+ assert "a" * 101 not in warning
+ assert "bbbb" not in warning
+
+ def test_each_other_host_is_warned_about_once(self, caplog: pytest.LogCaptureFixture) -> None:
+ client = _loopback_client("127.0.0.1")
+
+ with caplog.at_level(logging.WARNING, logger=_AUTH_LOGGER):
+ for host in ("a.example", "b.example", "a.example", "b.example"):
+ assert client.get("/healthz", headers={"Host": host}).status_code == 200
+
+ assert len(_host_warnings(caplog)) == 2
+
+ def test_warnings_stop_after_many_hosts(self, caplog: pytest.LogCaptureFixture) -> None:
+ client = _loopback_client("127.0.0.1")
+
+ with caplog.at_level(logging.WARNING, logger=_AUTH_LOGGER):
+ for index in range(80):
+ client.get("/healthz", headers={"Host": f"host-{index}.example"})
+
+ assert len(_host_warnings(caplog)) == 64
+
+ def test_the_bind_address_is_answered(self, caplog: pytest.LogCaptureFixture) -> None:
+ client = _loopback_client("127.0.0.2", "http://127.0.0.2:8080")
+
+ with caplog.at_level(logging.WARNING, logger=_AUTH_LOGGER):
+ assert client.get("/openapi.json").status_code == 200
+ assert _host_warnings(caplog) == []
+
+ @pytest.mark.parametrize("bind_host", ["0.0.0.0", "192.168.1.20", None]) # noqa: S104
+ def test_an_exposed_or_unknown_bind_is_not_host_checked(
+ self, bind_host: str | None, caplog: pytest.LogCaptureFixture
+ ) -> None:
+ client = TestClient(AppFactory.create_app(AppStateConfig(bind_host=bind_host)))
+
+ with caplog.at_level(logging.WARNING, logger=_AUTH_LOGGER):
+ assert client.get("/openapi.json", headers={"Host": "evil.example"}).status_code == 200
+ assert _host_warnings(caplog) == []
+
+ def test_token_auth_replaces_the_host_check(
+ self, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
+ ) -> None:
+ monkeypatch.setenv("SIE_AUTH_TOKEN", TOKEN)
+ client = _loopback_client("127.0.0.1", auth_mode="token")
+
+ with caplog.at_level(logging.WARNING, logger=_AUTH_LOGGER):
+ response = client.get("/openapi.json", headers={"Host": "evil.example", "x-api-key": TOKEN})
+ assert response.status_code == 200
+ assert _host_warnings(caplog) == []
+
+
+class TestLoopbackHostEnforcement:
+ @pytest.fixture
+ def client(self) -> TestClient:
+ app = _plain_app()
+ app.add_middleware(LoopbackHostMiddleware, allowed_hosts=loopback_host_allowlist("127.0.0.2"), enforce=True)
+ return TestClient(app, base_url="http://127.0.0.2:8080")
+
+ def test_the_allowed_hosts_are_answered(self, client: TestClient) -> None:
+ for host in ("localhost", "127.0.0.1:8080", "[::1]", "127.0.0.2:8080"):
+ assert client.get("/v1/thing", headers={"Host": host}).status_code == 200
+
+ def test_another_host_is_refused_with_the_allowed_names(self, client: TestClient) -> None:
+ response = client.get("/v1/thing", headers={"Host": "evil.example"})
+
+ assert response.status_code == 400
+ assert response.json()["detail"] == {
+ "code": "INVALID_INPUT",
+ "message": "This server listens on loopback and answers only requests addressed to "
+ "localhost, 127.0.0.1, [::1] or 127.0.0.2.",
+ }
+
+ def test_another_host_on_a_websocket_is_refused(self, client: TestClient) -> None:
+ with (
+ pytest.raises(WebSocketDenialResponse) as denied,
+ client.websocket_connect("/ws/status", headers={"Host": "evil.example"}),
+ ):
+ pass
+ assert denied.value.status_code == 400
+
+
+class TestWebSocketCloseFallback:
+ """Without the ``websocket.http.response`` extension a refusal can only close the socket."""
+
+ @pytest.mark.parametrize(
+ "build",
+ [
+ lambda inner: ServerAuthMiddleware(inner, tokens=(TOKEN,)),
+ lambda inner: LoopbackHostMiddleware(inner, loopback_host_allowlist("127.0.0.1"), enforce=True),
+ ],
+ ids=["token", "host"],
+ )
+ @pytest.mark.parametrize("extensions", [None, {}], ids=["absent", "empty"])
+ def test_a_refused_websocket_is_closed_with_policy_violation(
+ self, build: Callable[[Any], Any], extensions: dict[str, Any] | None
+ ) -> None:
+ inner_calls: list[dict[str, Any]] = []
+
+ async def inner(scope: dict[str, Any], receive: Any, send: Any) -> None:
+ inner_calls.append(scope)
+
+ scope: dict[str, Any] = {"type": "websocket", "path": "/ws/status", "headers": [(b"host", b"evil.example")]}
+ if extensions is not None:
+ scope["extensions"] = extensions
+ sent: list[dict[str, Any]] = []
+
+ async def receive() -> dict[str, Any]:
+ return {"type": "websocket.connect"}
+
+ async def send(message: dict[str, Any]) -> None:
+ sent.append(message)
+
+ asyncio.run(build(inner)(scope, receive, send))
+
+ assert inner_calls == []
+ assert sent == [{"type": "websocket.close", "code": 1008}]
+
+
+class TestServerApp:
+ def test_token_mode_protects_the_real_app(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setenv("SIE_AUTH_TOKEN", TOKEN)
+ client = TestClient(AppFactory.create_app(AppStateConfig(auth_mode="token")))
+
+ assert client.get("/healthz").status_code == 200
+ assert client.get("/openapi.json").status_code == 401
+ assert client.get("/openapi.json", headers={"x-api-key": TOKEN}).status_code == 200
+ with pytest.raises(WebSocketDenialResponse), client.websocket_connect("/ws/status"):
+ pass
+
+ def test_default_mode_installs_no_auth(self) -> None:
+ client = TestClient(AppFactory.create_app(AppStateConfig()))
+
+ assert client.get("/openapi.json").status_code == 200
+
+ def test_token_mode_without_any_token_refuses_to_build(
+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ monkeypatch.setenv("SIE_DATA_DIR", str(tmp_path))
+
+ with pytest.raises(TokenFileError):
+ AppFactory.create_app(AppStateConfig(auth_mode="token"))
+
+
+class TestAppStateConfigRoundTrip:
+ def test_the_resolved_mode_survives_the_factory_boundary(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setenv("SIE_AUTH_TOKEN", TOKEN)
+ AppStateConfig(auth_mode="token").save_to_env_vars()
+
+ assert os.environ["SIE_AUTH_MODE"] == "token"
+ assert AppStateConfig.from_env_vars().auth_mode == "token"
+
+ def test_an_unresolved_auto_requires_a_token(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setenv("SIE_AUTH_MODE", "auto")
+
+ assert AppStateConfig.from_env_vars().auth_mode == "token"
+
+ def test_the_bind_address_survives_the_factory_boundary(self) -> None:
+ AppStateConfig(bind_host="127.0.0.1").save_to_env_vars()
+
+ assert AppStateConfig.from_env_vars().bind_host == "127.0.0.1"
+
+ def test_the_factory_refuses_a_blank_token(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setenv("SIE_AUTH_TOKEN", " , ")
+
+ with pytest.raises(AuthConfigError, match="holds no token"):
+ AppStateConfig.from_env_vars()
+
+
+_FIRST_START_SCRIPT = (
+ "import sys; from pathlib import Path; "
+ "from sie_server.core.server_auth import load_or_create_token; "
+ "print(load_or_create_token(Path(sys.argv[1])).token)"
+)
+
+
+_AUTH_LOGGER = "sie_server.core.server_auth"
+
+
+def _host_warnings(caplog: pytest.LogCaptureFixture) -> list[str]:
+ return [
+ record.getMessage()
+ for record in caplog.records
+ if record.name == _AUTH_LOGGER and record.levelno == logging.WARNING and "Host" in record.getMessage()
+ ]
+
+
+def _creates_in(directory: Path, path: Any, flags: int) -> bool:
+ return bool(flags & os.O_CREAT) and Path(os.fsdecode(path)).parent == directory
+
+
+def _record_creates_in(directory: Path, monkeypatch: pytest.MonkeyPatch) -> list[str]:
+ creates: list[str] = []
+ real_open = os.open
+
+ def recording_open(path: Any, flags: int, *args: Any, **kwargs: Any) -> int:
+ if _creates_in(directory, path, flags):
+ creates.append(os.fsdecode(path))
+ return real_open(path, flags, *args, **kwargs)
+
+ monkeypatch.setattr(os, "open", recording_open)
+ return creates
+
+
+def _refuse_creates_in(
+ directory: Path, monkeypatch: pytest.MonkeyPatch, code: int, before: Callable[[], None] | None = None
+) -> None:
+ """Make creating a file in ``directory`` fail as a read-only directory or volume does."""
+ real_open = os.open
+
+ def refusing_open(path: Any, flags: int, *args: Any, **kwargs: Any) -> int:
+ if _creates_in(directory, path, flags):
+ if before is not None:
+ before()
+ raise OSError(code, os.strerror(code), os.fsdecode(path))
+ return real_open(path, flags, *args, **kwargs)
+
+ monkeypatch.setattr(os, "open", refusing_open)
+
+
+def _capture(call: Callable[[], object], outcome: list[BaseException]) -> None:
+ try:
+ call()
+ except BaseException as exc: # noqa: BLE001
+ outcome.append(exc)
diff --git a/packages/sie_server/tests/observability/test_telemetry.py b/packages/sie_server/tests/observability/test_telemetry.py
index 11ef633d9..148447c04 100644
--- a/packages/sie_server/tests/observability/test_telemetry.py
+++ b/packages/sie_server/tests/observability/test_telemetry.py
@@ -1,6 +1,8 @@
import asyncio
import logging
import os
+import threading
+import time
import uuid
from collections.abc import Iterator
from contextlib import contextmanager
@@ -142,6 +144,79 @@ class TestGetOrCreateWorkerId:
uuid.UUID(worker_id) # valid UUID
assert worker_id != "not-a-uuid"
+ @pytest.mark.parametrize("content", ["not-a-uuid", "", "\n"])
+ def test_bad_content_is_repaired_once_and_then_stable(self, tmp_path: Path, content: str) -> None:
+ id_path = tmp_path / "worker-id"
+ id_path.write_text(content)
+
+ repaired = _get_or_create_worker_id(str(tmp_path))
+
+ uuid.UUID(repaired)
+ assert id_path.read_text() == repaired
+ assert _get_or_create_worker_id(str(tmp_path)) == repaired
+ assert [entry.name for entry in tmp_path.iterdir()] == ["worker-id"]
+
+ def test_a_fifo_does_not_block_and_is_replaced(self, tmp_path: Path) -> None:
+ id_path = tmp_path / "worker-id"
+ os.mkfifo(id_path, 0o600)
+ outcome: list[str] = []
+ reader = threading.Thread(target=lambda: outcome.append(_get_or_create_worker_id(str(tmp_path))), daemon=True)
+ reader.start()
+ reader.join(timeout=5)
+ try:
+ assert not reader.is_alive(), "reading a FIFO worker id blocked"
+ finally:
+ if reader.is_alive():
+ os.close(os.open(id_path, os.O_WRONLY | os.O_NONBLOCK))
+
+ uuid.UUID(outcome[0])
+ assert id_path.is_file()
+ assert _get_or_create_worker_id(str(tmp_path)) == outcome[0]
+
+ def test_a_fifo_is_never_read_as_the_worker_id(self, tmp_path: Path) -> None:
+ id_path = tmp_path / "worker-id"
+ os.mkfifo(id_path, 0o600)
+ planted = str(uuid.uuid4())
+ reader = os.open(id_path, os.O_RDONLY | os.O_NONBLOCK)
+ writer = os.open(id_path, os.O_WRONLY)
+ try:
+ os.write(writer, planted.encode())
+ worker_id = _get_or_create_worker_id(str(tmp_path))
+ finally:
+ os.close(writer)
+ os.close(reader)
+
+ assert worker_id != planted
+ assert id_path.is_file()
+ assert id_path.read_text() == worker_id
+
+ def test_only_old_temporary_files_of_the_server_are_cleaned_up(self, tmp_path: Path) -> None:
+ old = time.time() - 600
+ orphan = tmp_path / ".worker-id.sie-server-00000000000000aa"
+ in_flight = tmp_path / ".worker-id.sie-server-00000000000000bb"
+ users = tmp_path / ".worker-id.backup"
+ for path in (orphan, in_flight, users):
+ path.write_text(str(uuid.uuid4()))
+ for path in (orphan, users):
+ os.utime(path, (old, old))
+
+ _get_or_create_worker_id(str(tmp_path))
+
+ assert not orphan.exists()
+ assert in_flight.exists()
+ assert users.exists()
+
+ def test_temporary_files_of_another_user_are_kept(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ old = time.time() - 600
+ orphan = tmp_path / ".worker-id.sie-server-00000000000000aa"
+ orphan.write_text(str(uuid.uuid4()))
+ os.utime(orphan, (old, old))
+ monkeypatch.setattr(os, "getuid", lambda: orphan.stat().st_uid + 1)
+
+ _get_or_create_worker_id(str(tmp_path))
+
+ assert orphan.exists()
+
def test_readonly_dir_falls_back_to_ephemeral(self, tmp_path: Path) -> None:
nonexistent = os.path.join(str(tmp_path), "readonly", "nested", "deep")
# Make parent read-only
diff --git a/packages/sie_server/tests/test_cli_auth.py b/packages/sie_server/tests/test_cli_auth.py
new file mode 100644
index 000000000..cce53beec
--- /dev/null
+++ b/packages/sie_server/tests/test_cli_auth.py
@@ -0,0 +1,252 @@
+"""`sie-server serve`: bind address, token auth resolution and exposure warnings."""
+
+from __future__ import annotations
+
+import os
+from collections.abc import Iterator
+from pathlib import Path
+from typing import Any
+
+import pytest
+from sie_server import cli
+from sie_server.app.app_state_config import AppStateConfig
+from sie_server.core.server_auth import token_path
+from typer.testing import CliRunner
+
+TOKEN = "s3cret-token-value" # noqa: S105 - test credential
+
+
[email protected](autouse=True)
+def _restore_environment() -> Iterator[None]:
+ saved = dict(os.environ)
+ yield
+ os.environ.clear()
+ os.environ.update(saved)
+
+
+def started(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> dict[str, Any]:
+ calls: dict[str, Any] = {}
+
+ def fake_run_server(**kwargs: Any) -> None:
+ calls.update(kwargs)
+
+ monkeypatch.setattr(cli, "run_server", fake_run_server)
+ for name in (
+ "SIE_AUTH_MODE",
+ "SIE_AUTH_TOKEN",
+ "SIE_AUTH_TOKENS",
+ "SIE_SERVER_HOST",
+ "XDG_DATA_HOME",
+ "SIE_UPSTREAMS_FILE",
+ "SIE_REMOTE_SERVING",
+ "SIE_LOG_LEVEL",
+ "SIE_PRELOAD_MODELS",
+ "SIE_PINNED_MODELS",
+ "SIE_EXTRA_MODELS",
+ ):
+ monkeypatch.delenv(name, raising=False)
+ monkeypatch.setenv("SIE_DATA_DIR", str(tmp_path / "data"))
+ return calls
+
+
+def serve(*args: str) -> Any:
+ return CliRunner().invoke(cli.app, ["serve", *args])
+
+
+def resolved_mode(started: dict[str, Any]) -> str:
+ config: AppStateConfig = started["config"]
+ return config.auth_mode
+
+
+def test_default_bind_is_unchanged_and_warns(started: dict[str, Any]) -> None:
+ result = serve()
+
+ assert result.exit_code == 0, result.output
+ assert started["host"] == "0.0.0.0" # noqa: S104
+ assert resolved_mode(started) == "none"
+ assert "WARNING: sie-server listens on 0.0.0.0:8080 without authentication." in result.output
+ assert "From 0.13.0, an exposed sie-server requires a token." in result.output
+ assert "From 0.13.0 the default is 127.0.0.1." in result.output
+
+
+def test_loopback_bind_does_not_warn(started: dict[str, Any]) -> None:
+ result = serve("--host", "127.0.0.1")
+
+ assert result.exit_code == 0, result.output
+ assert started["host"] == "127.0.0.1"
+ assert "WARNING" not in result.output
+ assert "Notice" not in result.output
+
+
+def test_bind_address_from_the_environment(started: dict[str, Any], monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setenv("SIE_SERVER_HOST", "127.0.0.1")
+
+ result = serve()
+
+ assert result.exit_code == 0, result.output
+ assert started["host"] == "127.0.0.1"
+ assert "WARNING" not in result.output
+
+
+def test_an_explicit_exposed_bind_skips_the_default_notice(started: dict[str, Any]) -> None:
+ result = serve("--host", "0.0.0.0") # noqa: S104
+
+ assert result.exit_code == 0, result.output
+ assert "WARNING: sie-server listens on 0.0.0.0:8080 without authentication." in result.output
+ assert "Notice" not in result.output
+
+
+def test_explicitly_open_server_warns_without_the_deprecation(
+ started: dict[str, Any], monkeypatch: pytest.MonkeyPatch
+) -> None:
+ monkeypatch.setenv("SIE_AUTH_MODE", "none")
+
+ result = serve("--host", "0.0.0.0") # noqa: S104
+
+ assert result.exit_code == 0, result.output
+ assert resolved_mode(started) == "none"
+ assert "authentication is off (SIE_AUTH_MODE=none)" in result.output
+ assert "From 0.13.0" not in result.output
+
+
+def test_a_configured_token_turns_auth_on(started: dict[str, Any], monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setenv("SIE_AUTH_TOKEN", TOKEN)
+
+ result = serve("--host", "0.0.0.0") # noqa: S104
+
+ assert result.exit_code == 0, result.output
+ assert resolved_mode(started) == "token"
+ assert "WARNING" not in result.output
+ assert TOKEN not in result.output
+
+
+def test_token_mode_generates_and_prints_the_token_once(
+ started: dict[str, Any], monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ monkeypatch.setenv("SIE_AUTH_MODE", "token")
+ monkeypatch.setattr(cli, "_stderr_is_terminal", lambda: True)
+
+ first = serve("--port", "9090")
+
+ assert first.exit_code == 0, first.output
+ assert resolved_mode(started) == "token"
+ token = token_path(tmp_path / "data").read_text().strip()
+ assert f"export SIE_API_KEY={token}" in first.output
+ assert "http://localhost:9090/v1/models" in first.output
+
+ second = serve()
+
+ assert second.exit_code == 0, second.output
+ assert token not in second.output
+ assert str(token_path(tmp_path / "data")) in second.output
+
+
+def test_a_generated_token_is_not_printed_into_logs(
+ started: dict[str, Any], monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ data = tmp_path / "data $HOME"
+ monkeypatch.setenv("SIE_DATA_DIR", str(data))
+ monkeypatch.setenv("SIE_AUTH_MODE", "token")
+ monkeypatch.setattr(cli, "_stderr_is_terminal", lambda: False)
+
+ result = serve()
+
+ assert result.exit_code == 0, result.output
+ path = token_path(data)
+ assert path.read_text().strip() not in result.output
+ assert f"export SIE_API_KEY=$(cat '{path}')" in result.output
+ assert "set SIE_AUTH_TOKEN yourself" in result.output
+
+
[email protected]("value", [" ", ",", ""])
+def test_a_blank_token_stops_startup(started: dict[str, Any], monkeypatch: pytest.MonkeyPatch, value: str) -> None:
+ monkeypatch.setenv("SIE_AUTH_TOKEN", value)
+
+ result = serve("--host", "0.0.0.0") # noqa: S104
+
+ assert result.exit_code == 1
+ assert "holds no token" in result.output
+ assert not started
+
+
+def test_the_bind_address_reaches_the_app(started: dict[str, Any]) -> None:
+ result = serve("--host", "127.0.0.1")
+
+ assert result.exit_code == 0, result.output
+ config: AppStateConfig = started["config"]
+ assert config.bind_host == "127.0.0.1"
+
+
+def test_auto_leaves_a_loopback_server_open(started: dict[str, Any], monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setenv("SIE_AUTH_MODE", "auto")
+
+ result = serve("--host", "127.0.0.1")
+
+ assert result.exit_code == 0, result.output
+ assert resolved_mode(started) == "none"
+
+
+def test_auto_protects_an_exposed_server(
+ started: dict[str, Any], monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ monkeypatch.setenv("SIE_AUTH_MODE", "auto")
+
+ result = serve("--host", "0.0.0.0") # noqa: S104
+
+ assert result.exit_code == 0, result.output
+ assert resolved_mode(started) == "token"
+ assert token_path(tmp_path / "data").exists()
+ assert "WARNING" not in result.output
+
+
+def test_a_token_with_auth_off_stops_startup(started: dict[str, Any], monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setenv("SIE_AUTH_MODE", "none")
+ monkeypatch.setenv("SIE_AUTH_TOKEN", TOKEN)
+
+ result = serve()
+
+ assert result.exit_code == 1
+ assert "SIE_AUTH_MODE=none" in result.output
+ assert TOKEN not in result.output
+ assert not started
+
+
+def test_an_unknown_mode_stops_startup(started: dict[str, Any], monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setenv("SIE_AUTH_MODE", "open")
+
+ result = serve()
+
+ assert result.exit_code == 1
+ assert "none, token, static or auto" in result.output
+ assert not started
+
+
+def test_an_unsafe_token_file_stops_startup(
+ started: dict[str, Any], monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ monkeypatch.setenv("SIE_AUTH_MODE", "token")
+ directory = tmp_path / "data"
+ directory.mkdir()
+ token_path(directory).write_text(f"{TOKEN}\n")
+ token_path(directory).chmod(0o644)
+
+ result = serve()
+
+ assert result.exit_code == 1
+ assert "chmod 600" in result.output
+ assert TOKEN not in result.output
+ assert not started
+
+
[email protected]("value", ["TOKEN", "Token", "None"])
+def test_auth_modes_are_case_sensitive_as_on_the_gateway(
+ started: dict[str, Any], monkeypatch: pytest.MonkeyPatch, value: str
+) -> None:
+ monkeypatch.setenv("SIE_AUTH_MODE", value)
+
+ result = serve()
+
+ assert result.exit_code == 1
+ assert "lowercase" in result.output
+ assert not started
diff --git a/packages/sie_server_rust/src/main.rs b/packages/sie_server_rust/src/main.rs
index 3ec6d1974..0fe281d86 100644
--- a/packages/sie_server_rust/src/main.rs
+++ b/packages/sie_server_rust/src/main.rs
@@ -10,7 +10,7 @@ use sie_server_rust::ipc::{IpcServer, IpcServerConfig};
use sie_server_rust::ipc_types::SetPinnedModelsRequest;
use sie_server_rust::native_backend::NativeBackend;
use sie_server_rust::observability::{init_observability, shutdown_observability};
-use tracing::{error, info};
+use tracing::{error, info, warn};
#[derive(Debug, Parser)]
#[command(author, version, name = "sie-server-rust")]
@@ -43,8 +43,8 @@ struct Cli {
#[arg(long, env = "SIE_PINNED_MODELS")]
pinned_models: Option<String>,
- #[arg(long, env = "SIE_SERVER_HOST", default_value = "0.0.0.0")]
- host: String,
+ #[arg(long, env = "SIE_SERVER_HOST")]
+ host: Option<String>,
#[arg(long, env = "SIE_SERVER_PORT", default_value = "8080")]
port: u16,
@@ -94,13 +94,15 @@ async fn run() -> anyhow::Result<()> {
}
backend.start_idle_evictor();
+ let http_host = http_host(cli.host);
+
let shutdown_backend = backend.clone();
let server = IpcServer::new(
IpcServerConfig {
socket_path: cli.ipc_socket_path,
worker_id: cli.worker_id,
bundle: cli.bundle,
- http_host: cli.host,
+ http_host,
http_port: cli.port,
},
backend,
@@ -112,6 +114,15 @@ async fn run() -> anyhow::Result<()> {
result
}
+fn http_host(configured: Option<String>) -> String {
+ configured.unwrap_or_else(|| {
+ warn!(
+ "neither --host nor SIE_SERVER_HOST is set, so the health server listens on 0.0.0.0. From 0.13.0 the default is 127.0.0.1; set SIE_SERVER_HOST=0.0.0.0 to keep listening on every interface"
+ );
+ "0.0.0.0".to_string()
+ })
+}
+
fn csv_values(raw: &str) -> Vec<String> {
raw.split(',')
.map(str::trim)
@@ -148,6 +159,12 @@ fn idle_evict_duration(raw: Option<u64>) -> anyhow::Result<Option<Duration>> {
mod tests {
use super::*;
+ #[test]
+ fn http_host_keeps_every_interface_by_default() {
+ assert_eq!(http_host(None), "0.0.0.0");
+ assert_eq!(http_host(Some("127.0.0.1".to_string())), "127.0.0.1");
+ }
+
#[test]
fn idle_evict_duration_matches_python_bounds() {
assert_eq!(idle_evict_duration(None).unwrap(), None);