Open-source inference server and production cluster for all the models your agent needs.
Python bgecolbertdata-pipelinedeep-learningembeddingsinferenceinference-serverinformation-retrievalllmmlmlopsnatural-language-processingnlppythonrerankingretrievalretrieval-augmented-generationsemantic-searchspladevector-search
fix(gateway): answer OpenAI-compatible routes in the OpenAI error envelope (#1024)
Krisztian Gajdarb6abf94331fa
diff --git a/packages/sie_gateway/docs/architecture-guide.md b/packages/sie_gateway/docs/architecture-guide.mdindex 0f6e9b0a5..c77976ed4 100644--- a/packages/sie_gateway/docs/architecture-guide.md+++ b/packages/sie_gateway/docs/architecture-guide.md@@ -78,6 +78,8 @@ before the gateway publishes the worker item, preserving the worker-side typedGateway-generated **JSON error** bodies (validation, routing, auth, config read, pools) use a FastAPI-like envelope **`{"detail":{"code":"<STABLE_CODE>","message":"…", …}}`**. Extra diagnostic keys (e.g. `compatible_bundles`, `gpu`, `model`) live **inside** `detail` when present. This is intentionally **not** the same shape as SDK retry contracts, which remain **`{"error":{"code","message"}}`** for **503** retryable worker signals, SIE-native provisioning, and **`502`** **`MODEL_LOAD_FAILED`**. OpenAI-compatible provisioning uses the OpenAI error envelope. **200** success payloads keep their existing top-level shapes.+On the OpenAI-compatible routes (`/v1/chat/completions`, `/v1/completions`, `/v1/responses`, `/v1/embeddings`, `/v1/models`, `/v1/audio/transcriptions`, `/v1/moderations`, and every path below them) every error answer uses the OpenAI envelope **`{"error":{"message","type","param","code"}}`**. The handlers build it themselves; refusals made outside them, such as the auth middleware's `401` and `500 GATEWAY_AUTH_MISCONFIGURED`, are re-rendered by the outer middleware `http_error::openai_error_envelope`, the twin of `anthropic_error_envelope` on `/v1/messages`. It turns a 4xx or 5xx JSON `detail` body into the OpenAI envelope: `message` is `detail.message` (or the `detail` string), `code` is `detail.code` verbatim (a string `detail` gets its status's SIE code: `UNAUTHORIZED`, `FORBIDDEN`, `NOT_FOUND`, `PAYLOAD_TOO_LARGE`, `RATE_LIMIT`, `INVALID_REQUEST` or `INTERNAL_SERVER_ERROR`), `type` follows the status (`authentication_error` for 401, `permission_error` for 403, `rate_limit_error` for 429, `invalid_request_error` for other 4xx, `server_error` for 5xx), `param` is `detail.param` when it is a string and otherwise `null`, and every other `detail` field stays in `error`. The status, the headers (`WWW-Authenticate`, `Retry-After`, `X-SIE-Error-Code`, `X-SIE-RateLimit-*`) and the response extensions are kept. Bodies already in the OpenAI envelope, non-JSON bodies and successes pass through, and the SIE-native routes keep `detail`. A composition that adds admission layers around the gateway's routes applies both envelope layers outermost so its refusals take the same shapes; the two never apply to the same path, and applying one twice changes nothing.+## 3. Configuration Write PathAll config mutations go to `sie-config`. The gateway has no write handler.@@ -569,7 +571,7 @@ Config (read-side only):Pools and operator:- `GET /v1/pools`, `POST /v1/pools`, `GET /v1/pools/{name}`, `POST /v1/pools/{name}/renew`, `DELETE /v1/pools/{name}`-- `GET /v1/models`, `GET /v1/models/{*model}` — model catalogue. JSON objects mirror `sie_server` **`ModelInfo`** shape (including `inputs`, `outputs`, `dims`, `profiles`, worker-derived `loaded` / `state`, optional `last_error`, …). `context_length` and `max_output_tokens` are the limits the route admits, and `capabilities.reasoning` lists the `reasoning_effort` values it accepts and, as `grammar_effort`, the value a grammar-constrained request (a `response_format` other than `text`) runs at when it names none, read from the same model config the chat gate checks. The worker runs such a request that names no value at `grammar_effort`, and one that names an accepted value at that value. An unknown `model` id returns **`404`** with **`{"detail":{"code":"MODEL_NOT_FOUND",...}}`** (same envelope style as FastAPI validation errors on `sie_server`).+- `GET /v1/models`, `GET /v1/models/{*model}` — model catalogue. JSON objects mirror `sie_server` **`ModelInfo`** shape (including `inputs`, `outputs`, `dims`, `profiles`, worker-derived `loaded` / `state`, optional `last_error`, …). `context_length` and `max_output_tokens` are the limits the route admits, and `capabilities.reasoning` lists the `reasoning_effort` values it accepts and, as `grammar_effort`, the value a grammar-constrained request (a `response_format` other than `text`) runs at when it names none, read from the same model config the chat gate checks. The worker runs such a request that names no value at `grammar_effort`, and one that names an accepted value at that value. An unknown `model` id returns **`404`** with **`{"error":{"message":"…","type":"invalid_request_error","param":null,"code":"MODEL_NOT_FOUND"}}`**, the OpenAI envelope of the OpenAI-compatible routes.- `GET /healthz`, `GET /readyz`, `GET /health`- `GET /ws/cluster-status`- `GET /` — HTML status page (operator-facing, not a programmatic API).diff --git a/packages/sie_gateway/openapi.json b/packages/sie_gateway/openapi.jsonindex be4539dc2..d0bb05b4f 100644--- a/packages/sie_gateway/openapi.json+++ b/packages/sie_gateway/openapi.json@@ -2891,32 +2891,6 @@],"type": "object"},- "ModelNotFoundDetail": {- "properties": {- "code": {- "type": "string"- },- "message": {- "type": "string"- }- },- "required": [- "code",- "message"- ],- "type": "object"- },- "ModelNotFoundResponse": {- "properties": {- "detail": {- "$ref": "#/components/schemas/ModelNotFoundDetail"- }- },- "required": [- "detail"- ],- "type": "object"- },"ModelReasoningWire": {"description": "``capabilities.reasoning`` on a ``GET /v1/models`` entry.","properties": {@@ -5323,7 +5297,7 @@"content": {"application/json": {"schema": {- "$ref": "#/components/schemas/StandardApiError"+ "$ref": "#/components/schemas/OpenAIErrorEnvelope"}}},@@ -5353,14 +5327,7 @@"content": {"application/json": {"schema": {- "oneOf": [- {- "$ref": "#/components/schemas/OpenAIErrorEnvelope"- },- {- "$ref": "#/components/schemas/StandardApiError"- }- ]+ "$ref": "#/components/schemas/OpenAIErrorEnvelope"}}},@@ -5632,7 +5599,7 @@"content": {"application/json": {"schema": {- "$ref": "#/components/schemas/StandardApiError"+ "$ref": "#/components/schemas/OpenAIErrorEnvelope"}}},@@ -5662,14 +5629,7 @@"content": {"application/json": {"schema": {- "oneOf": [- {- "$ref": "#/components/schemas/OpenAIErrorEnvelope"- },- {- "$ref": "#/components/schemas/StandardApiError"- }- ]+ "$ref": "#/components/schemas/OpenAIErrorEnvelope"}}},@@ -5852,7 +5812,7 @@"content": {"application/json": {"schema": {- "$ref": "#/components/schemas/StandardApiError"+ "$ref": "#/components/schemas/OpenAIErrorEnvelope"}}},@@ -5872,14 +5832,7 @@"content": {"application/json": {"schema": {- "oneOf": [- {- "$ref": "#/components/schemas/OpenAIErrorEnvelope"- },- {- "$ref": "#/components/schemas/StandardApiError"- }- ]+ "$ref": "#/components/schemas/OpenAIErrorEnvelope"}}},@@ -6748,7 +6701,7 @@"content": {"application/json": {"schema": {- "$ref": "#/components/schemas/StandardApiError"+ "$ref": "#/components/schemas/OpenAIErrorEnvelope"}}},@@ -6788,14 +6741,7 @@"content": {"application/json": {"schema": {- "oneOf": [- {- "$ref": "#/components/schemas/OpenAIErrorEnvelope"- },- {- "$ref": "#/components/schemas/StandardApiError"- }- ]+ "$ref": "#/components/schemas/OpenAIErrorEnvelope"}}},@@ -8284,7 +8230,7 @@"content": {"application/json": {"schema": {- "$ref": "#/components/schemas/StandardApiError"+ "$ref": "#/components/schemas/OpenAIErrorEnvelope"}}},@@ -8294,7 +8240,7 @@"content": {"application/json": {"schema": {- "$ref": "#/components/schemas/StandardApiError"+ "$ref": "#/components/schemas/OpenAIErrorEnvelope"}}},@@ -8335,7 +8281,7 @@"content": {"application/json": {"schema": {- "$ref": "#/components/schemas/StandardApiError"+ "$ref": "#/components/schemas/OpenAIErrorEnvelope"}}},@@ -8345,7 +8291,7 @@"content": {"application/json": {"schema": {- "$ref": "#/components/schemas/ModelNotFoundResponse"+ "$ref": "#/components/schemas/OpenAIErrorEnvelope"}}},@@ -8355,7 +8301,7 @@"content": {"application/json": {"schema": {- "$ref": "#/components/schemas/StandardApiError"+ "$ref": "#/components/schemas/OpenAIErrorEnvelope"}}},@@ -8378,7 +8324,7 @@"content": {"application/json": {"schema": {- "$ref": "#/components/schemas/StandardApiError"+ "$ref": "#/components/schemas/OpenAIErrorEnvelope"}}},@@ -8388,7 +8334,7 @@"content": {"application/json": {"schema": {- "$ref": "#/components/schemas/StandardApiError"+ "$ref": "#/components/schemas/OpenAIErrorEnvelope"}}},@@ -9068,7 +9014,7 @@"content": {"application/json": {"schema": {- "$ref": "#/components/schemas/StandardApiError"+ "$ref": "#/components/schemas/OpenAIErrorEnvelope"}}},@@ -9098,14 +9044,7 @@"content": {"application/json": {"schema": {- "oneOf": [- {- "$ref": "#/components/schemas/OpenAIErrorEnvelope"- },- {- "$ref": "#/components/schemas/StandardApiError"- }- ]+ "$ref": "#/components/schemas/OpenAIErrorEnvelope"}}},diff --git a/packages/sie_gateway/src/handlers/audio.rs b/packages/sie_gateway/src/handlers/audio.rsindex 3627008cf..58c8c1ffb 100644--- a/packages/sie_gateway/src/handlers/audio.rs+++ b/packages/sie_gateway/src/handlers/audio.rs@@ -574,7 +574,7 @@ fn copy_native_response_headers(from: &HeaderMap, to: &mut HeaderMap) {responses((status = 200, description = "OpenAI-compatible transcription response", body = crate::openapi::OpenAITranscriptionResponse),(status = 400, description = "Invalid or unsupported field", body = crate::openapi::OpenAIErrorEnvelope),- (status = 401, description = "Missing or invalid bearer token", body = crate::openapi::StandardApiError),+ (status = 401, description = "Missing or invalid bearer token", body = crate::openapi::OpenAIErrorEnvelope),(status = 404, description = "Model not found", body = crate::openapi::OpenAIErrorEnvelope),(status = 413, description = "Multipart body or audio file too large", body = crate::openapi::OpenAIErrorEnvelope),(status = 500, description = "Malformed worker response or gateway internal error", body = crate::openapi::OpenAIErrorEnvelope),diff --git a/packages/sie_gateway/src/handlers/models.rs b/packages/sie_gateway/src/handlers/models.rsindex 33595fe1f..5cb109425 100644--- a/packages/sie_gateway/src/handlers/models.rs+++ b/packages/sie_gateway/src/handlers/models.rs@@ -172,7 +172,7 @@ fn leave_out_profile(body: &mut Value, profile: &str) {params(("model" = String, Path, description = "Model id; percent-encode slashes when using OpenAPI-generated clients")),responses((status = 200, description = "Model detail", body = crate::openapi::ModelInfoWire),- (status = 404, description = "Model not found", body = crate::openapi::ModelNotFoundResponse)+ (status = 404, description = "Model not found", body = crate::openapi::OpenAIErrorEnvelope)))]pub async fn get_model(@@ -1251,8 +1251,9 @@ mod route_tests {assert_eq!(response.status(), StatusCode::NOT_FOUND);let body = body_json(response).await;- assert_eq!(body["detail"]["code"], "MODEL_NOT_FOUND");- assert!(body["detail"]["message"]+ assert_eq!(body["error"]["code"], "MODEL_NOT_FOUND");+ assert_eq!(body["error"]["type"], "invalid_request_error");+ assert!(body["error"]["message"].as_str().unwrap().contains("does/not/exist"));@@ -1337,8 +1338,9 @@ mod route_tests {assert_eq!(response.status(), StatusCode::NOT_FOUND);let body = body_json(response).await;- assert_eq!(body["detail"]["code"], "MODEL_NOT_FOUND");- assert!(body["detail"]["message"]+ assert_eq!(body["error"]["code"], "MODEL_NOT_FOUND");+ assert_eq!(body["error"]["type"], "invalid_request_error");+ assert!(body["error"]["message"].as_str().unwrap().contains("anything"));diff --git a/packages/sie_gateway/src/handlers/proxy.rs b/packages/sie_gateway/src/handlers/proxy.rsindex 36bd0086f..320cb8031 100644--- a/packages/sie_gateway/src/handlers/proxy.rs+++ b/packages/sie_gateway/src/handlers/proxy.rs@@ -15151,7 +15151,7 @@ fn openai_embedding_items_to_data(responses((status = 200, description = "OpenAI-compatible embeddings response", body = crate::openapi::OpenAIEmbeddingsListResponse),(status = 400, description = "Invalid request", body = crate::openapi::OpenAIErrorEnvelope),- (status = 401, description = "Missing or invalid bearer token", body = crate::openapi::StandardApiError),+ (status = 401, description = "Missing or invalid bearer token", body = crate::openapi::OpenAIErrorEnvelope),(status = 404, description = "Model not found", body = crate::openapi::OpenAIErrorEnvelope),(status = 409, description = "Bundle override conflicts with model routing", body = crate::openapi::OpenAIErrorEnvelope),(status = 413, description = "Request body too large", body = crate::openapi::OpenAIErrorEnvelope),diff --git a/packages/sie_gateway/src/http_error.rs b/packages/sie_gateway/src/http_error.rsindex c3deece71..cb00dc3d5 100644--- a/packages/sie_gateway/src/http_error.rs+++ b/packages/sie_gateway/src/http_error.rs@@ -7,8 +7,15 @@//! endpoints build that envelope directly. ``/v1/embeddings`` calls the SIE-native//! encode path internally and translates non-200 responses back into the OpenAI//! envelope. Native encode/score/extract endpoints keep ``json_detail`` to preserve-//! existing SDK error-handling contracts.+//! existing SDK error-handling contracts. [`openai_error_envelope`] re-renders the+//! ``detail`` refusals that reach an OpenAI-compatible route from outside its+//! handler, such as the auth middleware's.+use axum::body::{to_bytes, Body, HttpBody};+use axum::extract::Request;+use axum::http::{header, HeaderMap, HeaderValue, StatusCode};+use axum::middleware::Next;+use axum::response::Response;use serde_json::{json, Map, Value};/// Response-extension marker: this error response is a fault the GATEWAY owns,@@ -50,7 +57,7 @@ impl GatewayOwnedFault {/// that constructs a fresh `Response` from a status and body, rather than/// re-using the original's parts, silently discards it. A layer that must/// rebuild has to copy the extensions across explicitly.- pub fn mark(self, mut response: axum::response::Response) -> axum::response::Response {+ pub fn mark(self, mut response: Response) -> Response {response.extensions_mut().insert(self);response}@@ -72,6 +79,8 @@ pub mod code {pub const SERIALIZATION_ERROR: &str = "SERIALIZATION_ERROR";pub const UNAUTHORIZED: &str = "UNAUTHORIZED";pub const FORBIDDEN: &str = "FORBIDDEN";+ pub const NOT_FOUND: &str = "NOT_FOUND";+ pub const RATE_LIMIT: &str = "RATE_LIMIT";pub const GATEWAY_AUTH_MISCONFIGURED: &str = "GATEWAY_AUTH_MISCONFIGURED";pub const DEFAULT_POOL_DELETE_FORBIDDEN: &str = "DEFAULT_POOL_DELETE_FORBIDDEN";pub const POOL_OPERATION_FORBIDDEN: &str = "POOL_OPERATION_FORBIDDEN";@@ -114,6 +123,8 @@ pub mod openai_type {/// the whole pool).pub const RATE_LIMIT: &str = "rate_limit_error";pub const SERVER_ERROR: &str = "server_error";+ pub const AUTHENTICATION: &str = "authentication_error";+ pub const PERMISSION: &str = "permission_error";}/// Stable ``error.code`` values paired with the types above. These are@@ -224,6 +235,169 @@ pub fn embeddings_error(sie_code: &str, param: Option<&str>, message: impl Into<json_openai_error(message, err_type, param, err_code)}+const OPENAI_COMPATIBLE_PATHS: [&str; 7] = [+ "/v1/chat/completions",+ "/v1/completions",+ "/v1/responses",+ "/v1/embeddings",+ "/v1/models",+ "/v1/audio/transcriptions",+ "/v1/moderations",+];++const MAX_ERROR_BODY: usize = 1024 * 1024;++/// Whether a path is one of the gateway's OpenAI-compatible routes or below+/// one: `/v1/chat/completions`, `/v1/completions`, `/v1/responses`,+/// `/v1/embeddings`, `/v1/models`, `/v1/audio/transcriptions` and+/// `/v1/moderations`. `/v1/messages` and the SIE-native routes are not.+pub fn is_openai_path(path: &str) -> bool {+ OPENAI_COMPATIBLE_PATHS.iter().any(|base| {+ path.strip_prefix(base)+ .is_some_and(|rest| rest.is_empty() || rest.starts_with('/'))+ })+}++/// The ``error.type`` an outer refusal on an OpenAI-compatible route gets.+fn openai_type_for_status(status: StatusCode) -> &'static str {+ match status.as_u16() {+ 401 => openai_type::AUTHENTICATION,+ 403 => openai_type::PERMISSION,+ 429 => openai_type::RATE_LIMIT,+ 400..=499 => openai_type::INVALID_REQUEST,+ _ => openai_type::SERVER_ERROR,+ }+}++fn code_for_status(status: StatusCode) -> &'static str {+ match status.as_u16() {+ 401 => code::UNAUTHORIZED,+ 403 => code::FORBIDDEN,+ 404 => code::NOT_FOUND,+ 413 => code::PAYLOAD_TOO_LARGE,+ 429 => code::RATE_LIMIT,+ 400..=499 => code::INVALID_REQUEST,+ _ => code::INTERNAL_ERROR,+ }+}++/// The OpenAI envelope for a ``{"detail": ...}`` error body, or `None` when+/// the body is not that envelope (already OpenAI-shaped, or anything else).+fn openai_error_from_detail_body(status: StatusCode, body: &Value) -> Option<Value> {+ let body = body.as_object()?;+ if body.get("error").is_some_and(Value::is_object) {+ return None;+ }+ let mut error = Map::new();+ match body.get("detail")? {+ Value::String(message) => {+ error.insert("message".to_string(), json!(message));+ error.insert("type".to_string(), json!(openai_type_for_status(status)));+ error.insert("param".to_string(), Value::Null);+ error.insert("code".to_string(), json!(code_for_status(status)));+ }+ Value::Object(detail) => {+ let message = detail+ .get("message")+ .and_then(Value::as_str)+ .or_else(|| status.canonical_reason())+ .unwrap_or_default();+ let code = detail+ .get("code")+ .and_then(Value::as_str)+ .unwrap_or_else(|| code_for_status(status));+ let param = detail+ .get("param")+ .filter(|param| param.is_string())+ .cloned()+ .unwrap_or(Value::Null);+ error.insert("message".to_string(), json!(message));+ error.insert("type".to_string(), json!(openai_type_for_status(status)));+ error.insert("param".to_string(), param);+ error.insert("code".to_string(), json!(code));+ for (key, value) in detail {+ if !matches!(key.as_str(), "message" | "type" | "param" | "code") {+ error.insert(key.clone(), value.clone());+ }+ }+ }+ _ => return None,+ }+ Some(json!({ "error": error }))+}++fn is_json(headers: &HeaderMap) -> bool {+ headers+ .get(header::CONTENT_TYPE)+ .and_then(|value| value.to_str().ok())+ .and_then(|value| value.split(';').next())+ .map(|mime| mime.trim().to_ascii_lowercase())+ .is_some_and(|mime| mime == "application/json" || mime.ends_with("+json"))+}++async fn openai_error_response(response: Response) -> Response {+ let fits = response+ .body()+ .size_hint()+ .upper()+ .is_some_and(|len| len <= MAX_ERROR_BODY as u64);+ if !fits || !is_json(response.headers()) {+ return response;+ }+ let (mut parts, body) = response.into_parts();+ let Ok(bytes) = to_bytes(body, MAX_ERROR_BODY).await else {+ parts.headers.remove(header::CONTENT_LENGTH);+ return Response::from_parts(parts, Body::empty());+ };+ let rendered = serde_json::from_slice::<Value>(&bytes)+ .ok()+ .and_then(|body| openai_error_from_detail_body(parts.status, &body))+ .and_then(|envelope| serde_json::to_vec(&envelope).ok());+ let Some(rendered) = rendered else {+ return Response::from_parts(parts, Body::from(bytes));+ };+ parts+ .headers+ .insert(header::CONTENT_LENGTH, HeaderValue::from(rendered.len()));+ Response::from_parts(parts, Body::from(rendered))+}++/// Middleware that gives every error answer on the OpenAI-compatible routes+/// ([`is_openai_path`]) the OpenAI envelope.+///+/// Compositions that add admission layers around the gateway's routes apply+/// it outermost (`axum::middleware::from_fn(openai_error_envelope)`), so+/// their refusals take the same shape. A 4xx or 5xx JSON answer whose body is+/// ``{"detail": {...}}`` or ``{"detail": "..."}`` becomes+/// ``{"error": {"message", "type", "param", "code", ...}}``:+///+/// - `message` is `detail.message`, or `detail` when it is a string.+/// - `code` is `detail.code` verbatim, so clients keep branching on SIE+/// codes such as `UNAUTHORIZED`. A string `detail` gets the SIE code of its+/// status: `UNAUTHORIZED` (401), `FORBIDDEN` (403), `NOT_FOUND` (404),+/// `PAYLOAD_TOO_LARGE` (413), `RATE_LIMIT` (429), `INVALID_REQUEST` (other+/// 4xx), `INTERNAL_SERVER_ERROR` (5xx).+/// - `type` follows the status: `authentication_error` (401),+/// `permission_error` (403), `rate_limit_error` (429),+/// `invalid_request_error` (other 4xx), `server_error` (5xx).+/// - `param` is `detail.param` when it is a string, otherwise `null`.+/// - Every other `detail` field, such as `key_region`, is kept in `error`.+///+/// The status, the response extensions and every header are kept, with+/// `Content-Length` set to the new body. Answers that are already in the+/// OpenAI envelope, are not JSON, or are not errors pass through untouched,+/// and so does every answer on another path: `/v1/messages` belongs to+/// `anthropic_error_envelope`, and the SIE-native routes keep `detail`.+pub async fn openai_error_envelope(request: Request, next: Next) -> Response {+ let applies = is_openai_path(request.uri().path());+ let response = next.run(request).await;+ let status = response.status();+ if !applies || !(status.is_client_error() || status.is_server_error()) {+ return response;+ }+ openai_error_response(response).await+}+#[cfg(test)]mod tests {use super::*;@@ -322,4 +496,350 @@ mod tests {assert_eq!(err["code"], "transport_failure");assert!(err["param"].is_null());}++ mod openai_envelope {+ use super::*;+ use axum::http::HeaderName;+ use axum::response::IntoResponse;+ use axum::Router;+ use tower::ServiceExt;++ const OPENAI_PATHS: [&str; 11] = [+ "/v1/chat/completions",+ "/v1/completions",+ "/v1/responses",+ "/v1/responses/resp_1",+ "/v1/embeddings",+ "/v1/models",+ "/v1/models/BAAI/bge-m3",+ "/v1/audio/transcriptions",+ "/v1/moderations",+ "/v1/chat/completions/chatcmpl_1",+ "/v1/completions/",+ ];++ const OTHER_PATHS: [&str; 13] = [+ "/v1/messages",+ "/v1/messages/count_tokens",+ "/v1/encode/BAAI/bge-m3",+ "/v1/score/m",+ "/v1/extract/m",+ "/v1/generate/m",+ "/v1/rerank",+ "/v1/systemone",+ "/v1/decisions",+ "/v1/pools",+ "/v1/modelsx",+ "/v1/completionsx",+ "/health",+ ];++ type MakeResponse = fn() -> Response;++ async fn through(path: &str, make: MakeResponse) -> Response {+ serve(path, make, true).await+ }++ async fn serve(path: &str, make: MakeResponse, envelope: bool) -> Response {+ let router = Router::new().fallback(move || async move { make() });+ let router = if envelope {+ router.layer(axum::middleware::from_fn(openai_error_envelope))+ } else {+ router+ };+ router+ .oneshot(+ Request::builder()+ .uri(path)+ .body(Body::empty())+ .expect("request"),+ )+ .await+ .expect("response")+ }++ async fn bytes(response: Response) -> Vec<u8> {+ to_bytes(response.into_body(), usize::MAX)+ .await+ .expect("body")+ .to_vec()+ }++ fn missing_token() -> Response {+ let mut response = (+ StatusCode::UNAUTHORIZED,+ axum::Json(json_detail(+ code::UNAUTHORIZED,+ "Missing Authorization or x-api-key header",+ )),+ )+ .into_response();+ response+ .headers_mut()+ .insert(header::WWW_AUTHENTICATE, HeaderValue::from_static("Bearer"));+ response+ }++ fn region_refusal() -> Response {+ let mut extra = Map::new();+ extra.insert("key_region".to_string(), json!("eu"));+ extra.insert(+ "region_endpoint".to_string(),+ json!("https://eu.example.test"),+ );+ extra.insert("epoch".to_string(), json!(7));+ extra.insert("param".to_string(), json!("model"));+ let mut response = (+ StatusCode::FORBIDDEN,+ [+ (header::RETRY_AFTER, "30"),+ (HeaderName::from_static("x-sie-error-code"), "KEY_REGION"),+ (HeaderName::from_static("x-sie-ratelimit-rps"), "5"),+ (HeaderName::from_static("x-sie-ratelimit-scope"), "key"),+ ],+ axum::Json(json_detail_merge(+ "KEY_REGION",+ "this key belongs to another region",+ extra,+ )),+ )+ .into_response();+ response+ .extensions_mut()+ .insert(GatewayOwnedFault::new("test"));+ response+ }++ fn string_detail() -> Response {+ (+ StatusCode::NOT_FOUND,+ axum::Json(json!({"detail": "Not Found"})),+ )+ .into_response()+ }++ #[test]+ fn openai_paths_cover_the_routes_and_the_paths_below_them() {+ for path in OPENAI_PATHS {+ assert!(is_openai_path(path), "{path}");+ }+ for path in OTHER_PATHS {+ assert!(!is_openai_path(path), "{path}");+ }+ }++ #[tokio::test]+ async fn the_anthropic_and_openai_layers_never_both_apply() {+ for (path, anthropic) in [+ ("/v1/messages", true),+ ("/v1/messages/count_tokens", true),+ ("/v1/chat/completions", false),+ ("/v1/responses", false),+ ("/v1/models/m", false),+ ] {+ let response = Router::new()+ .fallback(|| async { missing_token() })+ .layer(axum::middleware::from_fn(+ crate::handlers::messages::anthropic_error_envelope,+ ))+ .layer(axum::middleware::from_fn(openai_error_envelope))+ .oneshot(+ Request::builder()+ .uri(path)+ .body(Body::empty())+ .expect("request"),+ )+ .await+ .expect("response");+ assert_eq!(response.status(), StatusCode::UNAUTHORIZED, "{path}");+ let body: Value = serde_json::from_slice(&bytes(response).await).expect("json");+ assert_eq!(body["error"]["type"], "authentication_error", "{path}");+ assert_eq!(+ body.get("type") == Some(&json!("error")),+ anthropic,+ "{path}"+ );+ assert_eq!(body["error"].get("code").is_some(), !anthropic, "{path}");+ }+ }++ #[test]+ fn the_type_follows_the_status() {+ for (status, want_type, want_code) in [+ (400, "invalid_request_error", "INVALID_REQUEST"),+ (401, "authentication_error", "UNAUTHORIZED"),+ (402, "invalid_request_error", "INVALID_REQUEST"),+ (403, "permission_error", "FORBIDDEN"),+ (404, "invalid_request_error", "NOT_FOUND"),+ (405, "invalid_request_error", "INVALID_REQUEST"),+ (413, "invalid_request_error", "PAYLOAD_TOO_LARGE"),+ (429, "rate_limit_error", "RATE_LIMIT"),+ (500, "server_error", "INTERNAL_SERVER_ERROR"),+ (502, "server_error", "INTERNAL_SERVER_ERROR"),+ (503, "server_error", "INTERNAL_SERVER_ERROR"),+ (504, "server_error", "INTERNAL_SERVER_ERROR"),+ ] {+ let status = StatusCode::from_u16(status).expect("status");+ let body = openai_error_from_detail_body(status, &json!({"detail": "refused"}))+ .expect("envelope");+ assert_eq!(body["error"]["type"], want_type, "{status}");+ assert_eq!(body["error"]["code"], want_code, "{status}");+ let body = openai_error_from_detail_body(+ status,+ &json!({"detail": {"code": "SOME_SIE_CODE", "message": "refused"}}),+ )+ .expect("envelope");+ assert_eq!(body["error"]["type"], want_type, "{status}");+ assert_eq!(body["error"]["code"], "SOME_SIE_CODE", "{status}");+ }+ }++ #[tokio::test]+ async fn a_detail_refusal_becomes_the_openai_envelope_on_every_openai_path() {+ for path in OPENAI_PATHS {+ let response = through(path, missing_token).await;+ assert_eq!(response.status(), StatusCode::UNAUTHORIZED, "{path}");+ assert_eq!(response.headers()["www-authenticate"], "Bearer", "{path}");+ assert_eq!(+ response.headers()["content-type"],+ "application/json",+ "{path}"+ );+ let length = response.headers()[header::CONTENT_LENGTH].clone();+ let body = bytes(response).await;+ assert_eq!(length, body.len().to_string().as_str(), "{path}");+ let body: Value = serde_json::from_slice(&body).expect("json");+ assert_eq!(+ body,+ json!({"error": {+ "message": "Missing Authorization or x-api-key header",+ "type": "authentication_error",+ "param": null,+ "code": "UNAUTHORIZED",+ }}),+ "{path}"+ );+ }+ }++ #[tokio::test]+ async fn a_string_detail_gets_the_code_of_its_status() {+ let response = through("/v1/responses/resp_1", string_detail).await;+ assert_eq!(response.status(), StatusCode::NOT_FOUND);+ let body: Value = serde_json::from_slice(&bytes(response).await).expect("json");+ assert_eq!(+ body,+ json!({"error": {+ "message": "Not Found",+ "type": "invalid_request_error",+ "param": null,+ "code": "NOT_FOUND",+ }})+ );+ }++ #[tokio::test]+ async fn detail_fields_headers_and_extensions_survive() {+ let response = through("/v1/chat/completions", region_refusal).await;+ assert_eq!(response.status(), StatusCode::FORBIDDEN);+ let headers = response.headers();+ assert_eq!(headers["retry-after"], "30");+ assert_eq!(headers["x-sie-error-code"], "KEY_REGION");+ assert_eq!(headers["x-sie-ratelimit-rps"], "5");+ assert_eq!(headers["x-sie-ratelimit-scope"], "key");+ assert_eq!(+ response.extensions().get::<GatewayOwnedFault>(),+ Some(&GatewayOwnedFault::new("test"))+ );+ let body: Value = serde_json::from_slice(&bytes(response).await).expect("json");+ assert_eq!(+ body,+ json!({"error": {+ "message": "this key belongs to another region",+ "type": "permission_error",+ "param": "model",+ "code": "KEY_REGION",+ "key_region": "eu",+ "region_endpoint": "https://eu.example.test",+ "epoch": 7,+ }})+ );+ }++ #[tokio::test]+ async fn other_answers_pass_through_untouched() {+ fn openai_body() -> Response {+ (+ StatusCode::BAD_REQUEST,+ [(header::CONTENT_TYPE, "application/json")],+ r#"{"error": {"code": "unsupported_field", "message": "no", "type": "invalid_request_error", "param": "tools"}, "detail": {"code": "X"}}"#,+ )+ .into_response()+ }+ fn plain_text() -> Response {+ (+ StatusCode::UNAUTHORIZED,+ [(header::CONTENT_TYPE, "text/plain")],+ r#"{"detail": {"code": "UNAUTHORIZED", "message": "no"}}"#,+ )+ .into_response()+ }+ fn success() -> Response {+ (+ StatusCode::OK,+ axum::Json(json!({"detail": {"code": "OK", "message": "fine"}})),+ )+ .into_response()+ }+ fn validation_list() -> Response {+ (+ StatusCode::UNPROCESSABLE_ENTITY,+ axum::Json(json!({"detail": [{"loc": ["body"], "msg": "required"}]})),+ )+ .into_response()+ }+ fn empty() -> Response {+ StatusCode::METHOD_NOT_ALLOWED.into_response()+ }+ fn not_json() -> Response {+ (+ StatusCode::BAD_GATEWAY,+ [(header::CONTENT_TYPE, "application/json")],+ "{\"detail\": ",+ )+ .into_response()+ }++ let cases: [(&str, MakeResponse); 6] = [+ ("openai", openai_body),+ ("plain text", plain_text),+ ("success", success),+ ("validation list", validation_list),+ ("empty", empty),+ ("not json", not_json),+ ];+ for (case, make) in cases {+ assert_untouched("/v1/chat/completions", make, case).await;+ }+ }++ async fn assert_untouched(path: &str, make: MakeResponse, case: &str) {+ let expected = serve(path, make, false).await;+ let response = through(path, make).await;+ assert_eq!(response.status(), expected.status(), "{case} {path}");+ assert_eq!(response.headers(), expected.headers(), "{case} {path}");+ assert_eq!(+ bytes(response).await,+ bytes(expected).await,+ "{case} {path}"+ );+ }++ #[tokio::test]+ async fn other_paths_keep_the_detail_envelope() {+ for path in OTHER_PATHS {+ assert_untouched(path, missing_token, "missing token").await;+ }+ }+ }}diff --git a/packages/sie_gateway/src/openapi.rs b/packages/sie_gateway/src/openapi.rsindex ba61bb3b6..a0c960d5f 100644--- a/packages/sie_gateway/src/openapi.rs+++ b/packages/sie_gateway/src/openapi.rs@@ -116,8 +116,6 @@ static OPENAPI_JSON: LazyLock<String> = LazyLock::new(|| {ModelRoutingWire,ModelsResponse,OpenAiModelObject,- ModelNotFoundDetail,- ModelNotFoundResponse,ProfileInfoWire,crate::types::worker::ModelInfo,MultiVector,@@ -1360,36 +1358,39 @@ fn inject_inference_response_headers(paths: &mut serde_json::Map<String, Value>)}/// Add documented auth responses for bearer-protected operations (spec completeness).+///+/// The OpenAI-compatible routes document the OpenAI envelope, which+/// `http_error::openai_error_envelope` gives the auth middleware's refusals+/// there; every other route documents `StandardApiError`.fn inject_bearer_auth_error_responses(paths: &mut serde_json::Map<String, Value>) {- let unauthorized = json!({- "description": "Missing or invalid bearer token (inference token)",- "content": {- "application/json": {- "schema": { "$ref": "#/components/schemas/StandardApiError" }- }- }- });- let forbidden = json!({- "description": "Valid bearer token but admin token required for this mutation (or admin token not configured)",- "content": {- "application/json": {- "schema": { "$ref": "#/components/schemas/StandardApiError" }- }- }- });- let auth_misconfigured = json!({- "description": "Gateway auth enabled but no tokens configured",- "content": {- "application/json": {- "schema": { "$ref": "#/components/schemas/StandardApiError" }+ let error_response = |description: &str, schema: &Value| {+ json!({+ "description": description,+ "content": {+ "application/json": {+ "schema": schema+ }}- }- });+ })+ };for (path, path_item) in paths.iter_mut() {let Some(path_item) = path_item.as_object_mut() else {continue;};+ let error_schema = auth_error_schema(path);+ let unauthorized = error_response(+ "Missing or invalid bearer token (inference token)",+ &error_schema,+ );+ let forbidden = error_response(+ "Valid bearer token but admin token required for this mutation (or admin token not configured)",+ &error_schema,+ );+ let auth_misconfigured = error_response(+ "Gateway auth enabled but no tokens configured",+ &error_schema,+ );for (method, op) in path_item.iter_mut() {if !matches!(method.as_str(), "get" | "post" | "put" | "delete" | "patch") {continue;@@ -1411,7 +1412,7 @@ fn inject_bearer_auth_error_responses(paths: &mut serde_json::Map<String, Value>responses.entry("401".to_string()).or_insert(unauthorized.clone());- merge_auth_misconfigured_response(responses, &auth_misconfigured);+ merge_auth_misconfigured_response(responses, &auth_misconfigured, &error_schema);if admin_mutation(method.as_str(), path) {responses@@ -1422,24 +1423,29 @@ fn inject_bearer_auth_error_responses(paths: &mut serde_json::Map<String, Value>}}-fn standard_api_error_schema() -> Value {- json!({ "$ref": "#/components/schemas/StandardApiError" })+fn auth_error_schema(path: &str) -> Value {+ if crate::http_error::is_openai_path(path) {+ json!({ "$ref": "#/components/schemas/OpenAIErrorEnvelope" })+ } else {+ json!({ "$ref": "#/components/schemas/StandardApiError" })+ }}-fn schema_allows_standard_api_error(schema: &Value) -> bool {- if schema == &standard_api_error_schema() {+fn schema_allows(schema: &Value, wanted: &Value) -> bool {+ if schema == wanted {return true;}schema.get("oneOf").and_then(|one_of| one_of.as_array())- .map(|schemas| schemas.iter().any(schema_allows_standard_api_error))+ .map(|schemas| schemas.iter().any(|schema| schema_allows(schema, wanted))).unwrap_or(false)}fn merge_auth_misconfigured_response(responses: &mut serde_json::Map<String, Value>,auth_misconfigured: &Value,+ error_schema: &Value,) {let Some(existing) = responses.get_mut("500") else {responses.insert("500".to_string(), auth_misconfigured.clone());@@ -1472,13 +1478,13 @@ fn merge_auth_misconfigured_response(.expect("OpenAPI application/json response should be an object");let schema = json_content.entry("schema").or_insert_with(|| json!(null));if schema.is_null() {- *schema = standard_api_error_schema();- } else if !schema_allows_standard_api_error(schema) {+ *schema = error_schema.clone();+ } else if !schema_allows(schema, error_schema) {let old_schema = schema.clone();*schema = json!({"oneOf": [old_schema,- standard_api_error_schema()+ error_schema]});}@@ -2696,17 +2702,6 @@ pub struct ModelsResponse {pub models: Vec<ModelInfoWire>,}-#[derive(Debug, Serialize, Deserialize, ToSchema)]-pub struct ModelNotFoundResponse {- pub detail: ModelNotFoundDetail,-}--#[derive(Debug, Serialize, Deserialize, ToSchema)]-pub struct ModelNotFoundDetail {- pub code: String,- pub message: String,-}-#[derive(Debug, Serialize, Deserialize, ToSchema)]pub struct PoolListResponse {pub pools: Vec<crate::types::pool::Pool>,@@ -3999,15 +3994,13 @@ mod tests {);}- // `/v1/embeddings` is OpenAI-compatible: every handler-generated error- // path documents the OpenAI `{error:{…}}` envelope so an `openai`- // client's error handling works unchanged. (401 is emitted upstream by- // the auth middleware and stays on the SIE-native shape.)- // (In the raw document each error is a direct `$ref`; the export step- // later merges the auth-misconfigured `StandardApiError` into the 500- // as a `oneOf` — see `openapi_export_*` tests.)+ // `/v1/embeddings` is OpenAI-compatible: every error path, including+ // the auth middleware's 401, documents the OpenAI `{error:{…}}`+ // envelope so an `openai` client's error handling works unchanged.let emb = &spec["paths"]["/v1/embeddings"]["post"]["responses"];- for status in ["400", "404", "409", "413", "500", "502", "503", "504"] {+ for status in [+ "400", "401", "404", "409", "413", "500", "502", "503", "504",+ ] {assert_eq!(emb[status]["content"]["application/json"]["schema"]["$ref"],"#/components/schemas/OpenAIErrorEnvelope",@@ -4016,6 +4009,46 @@ mod tests {}}+ #[test]+ fn openapi_export_documents_the_openai_envelope_on_openai_routes() {+ let spec: serde_json::Value = serde_json::from_str(&OPENAPI_JSON).unwrap();+ let openai = json!({"$ref": "#/components/schemas/OpenAIErrorEnvelope"});+ let standard = json!({"$ref": "#/components/schemas/StandardApiError"});+ let schema = |path: &str, method: &str, status: &str| {+ spec["paths"][path][method]["responses"][status]["content"]["application/json"]+ ["schema"]+ .clone()+ };+ let mut seen = 0;+ for (path, item) in spec["paths"].as_object().unwrap() {+ if !crate::http_error::is_openai_path(path) {+ continue;+ }+ for method in item.as_object().unwrap().keys() {+ seen += 1;+ assert_eq!(schema(path, method, "401"), openai, "{method} {path} 401");+ let internal = schema(path, method, "500");+ assert!(+ schema_allows(&internal, &openai) && !schema_allows(&internal, &standard),+ "{method} {path} 500: {internal}"+ );+ }+ }+ assert_eq!(seen, 8);+ assert_eq!(schema("/v1/models/{model}", "get", "404"), openai);+ for (path, method) in [+ ("/v1/encode/{model}", "post"),+ ("/v1/generate/{model}", "post"),+ ("/v1/pools", "post"),+ ] {+ assert_eq!(schema(path, method, "401"), standard, "{method} {path} 401");+ }+ assert_eq!(+ schema("/v1/messages", "post", "401"),+ json!({"$ref": "#/components/schemas/AnthropicErrorEnvelope"})+ );+ }+#[test]fn openapi_export_adds_msgpack_content_and_unauthorized_responses() {let spec: serde_json::Value = serde_json::from_str(&OPENAPI_JSON).unwrap();diff --git a/packages/sie_gateway/src/server.rs b/packages/sie_gateway/src/server.rsindex 39e1b6f77..34b17b5b5 100644--- a/packages/sie_gateway/src/server.rs+++ b/packages/sie_gateway/src/server.rs@@ -666,6 +666,9 @@ pub fn create_router_core(.layer(axum::middleware::from_fn(messages::anthropic_error_envelope,))+ .layer(axum::middleware::from_fn(+ crate::http_error::openai_error_envelope,+ )).with_state(state)}@@ -1301,12 +1304,20 @@ mod flat_404_tests {// Returned tempdirs must outlive the router so they drop after the test.fn build_router() -> (Router, tempfile::TempDir, tempfile::TempDir) {+ build_router_with(|_| {})+ }++ pub(super) fn build_router_with(+ configure: impl FnOnce(&mut Config),+ ) -> (Router, tempfile::TempDir, tempfile::TempDir) {let bundles_dir = tempfile::TempDir::new().unwrap();let models_dir = tempfile::TempDir::new().unwrap();- let config = Arc::new(test_config(+ let mut config = test_config(bundles_dir.path().to_str().unwrap(),models_dir.path().to_str().unwrap(),- ));+ );+ configure(&mut config);+ let config = Arc::new(config);let state = Arc::new(AppState {registry: Arc::new(WorkerRegistry::new(Duration::from_secs(30), None)),config: Arc::clone(&config),@@ -1465,3 +1476,98 @@ mod flat_404_tests {.await;}}++#[cfg(test)]+mod openai_error_envelope_tests {+ use axum::body::{to_bytes, Body};+ use axum::http::{Method, Request, StatusCode};+ use axum::Router;+ use serde_json::{json, Value};+ use tower::ServiceExt;++ use super::flat_404_tests::build_router_with;++ async fn refuse(app: &Router, method: Method, uri: &str) -> (StatusCode, String, Value) {+ let response = app+ .clone()+ .oneshot(+ Request::builder()+ .method(method)+ .uri(uri)+ .header("content-type", "application/json")+ .body(Body::from("{}"))+ .unwrap(),+ )+ .await+ .unwrap();+ let status = response.status();+ let challenge = response+ .headers()+ .get("www-authenticate")+ .map(|value| value.to_str().unwrap().to_string())+ .unwrap_or_default();+ let bytes = to_bytes(response.into_body(), usize::MAX).await.unwrap();+ (status, challenge, serde_json::from_slice(&bytes).unwrap())+ }++ #[tokio::test]+ async fn a_missing_token_on_an_openai_route_gets_the_openai_envelope() {+ let (app, _bundles_dir, _models_dir) = build_router_with(|config| {+ config.auth_mode = "token".to_string();+ config.auth_tokens = vec!["secret".to_string()];+ });+ for (method, uri) in [+ (Method::POST, "/v1/chat/completions"),+ (Method::POST, "/v1/completions"),+ (Method::POST, "/v1/responses"),+ (Method::POST, "/v1/embeddings"),+ (Method::GET, "/v1/models"),+ (Method::GET, "/v1/models/BAAI/bge-m3"),+ (Method::POST, "/v1/moderations"),+ ] {+ let (status, challenge, body) = refuse(&app, method, uri).await;+ assert_eq!(status, StatusCode::UNAUTHORIZED, "{uri}");+ assert_eq!(challenge, "Bearer", "{uri}");+ assert_eq!(+ body,+ json!({"error": {+ "message": "Missing Authorization or x-api-key header",+ "type": "authentication_error",+ "param": null,+ "code": "UNAUTHORIZED",+ }}),+ "{uri}"+ );+ }++ let (status, challenge, body) = refuse(&app, Method::POST, "/v1/encode/BAAI/bge-m3").await;+ assert_eq!(status, StatusCode::UNAUTHORIZED);+ assert_eq!(challenge, "Bearer");+ assert_eq!(+ body,+ json!({"detail": {+ "code": "UNAUTHORIZED",+ "message": "Missing Authorization or x-api-key header",+ }})+ );++ let (status, _, body) = refuse(&app, Method::POST, "/v1/messages").await;+ assert_eq!(status, StatusCode::UNAUTHORIZED);+ assert_eq!(body["type"], "error");+ assert_eq!(body["error"]["type"], "authentication_error");+ }++ #[tokio::test]+ async fn a_misconfigured_gateway_refuses_openai_routes_in_the_openai_envelope() {+ let (app, _bundles_dir, _models_dir) = build_router_with(|config| {+ config.auth_mode = "tokens".to_string();+ });+ let (status, _, body) = refuse(&app, Method::POST, "/v1/chat/completions").await;+ assert_eq!(status, StatusCode::INTERNAL_SERVER_ERROR);+ assert_eq!(body["error"]["type"], "server_error");+ assert_eq!(body["error"]["code"], "GATEWAY_AUTH_MISCONFIGURED");+ let (status, _, body) = refuse(&app, Method::POST, "/v1/score/m").await;+ assert_eq!(status, StatusCode::INTERNAL_SERVER_ERROR);+ assert_eq!(body["detail"]["code"], "GATEWAY_AUTH_MISCONFIGURED");+ }+}diff --git a/packages/sie_sdk/tests/client/test_auth_refusal_envelope.py b/packages/sie_sdk/tests/client/test_auth_refusal_envelope.pynew file mode 100644index 000000000..ca53b4ab2--- /dev/null+++ b/packages/sie_sdk/tests/client/test_auth_refusal_envelope.py@@ -0,0 +1,56 @@+"""An auth refusal raises the same SDK error in the SIE and the OpenAI error envelope.++The gateway and ``sie-server`` answer a missing or invalid token on the+OpenAI-compatible routes (``/v1/chat/completions``, ``/v1/responses``, ...) in+the OpenAI ``{"error": {...}}`` envelope, and on the SIE-native routes in+``{"detail": {...}}``. Both carry the same status, ``code`` and ``message``.+"""++from __future__ import annotations++import json+from collections.abc import Callable+from typing import Any+from unittest.mock import MagicMock, patch++import pytest+from sie_sdk import SIEClient+from sie_sdk.client.errors import RequestError++MESSAGE = "Missing Authorization or x-api-key header"+DETAIL = {"detail": {"code": "UNAUTHORIZED", "message": MESSAGE}}+OPENAI = {"error": {"message": MESSAGE, "type": "authentication_error", "param": None, "code": "UNAUTHORIZED"}}+++def _refusal(body: dict[str, Any]) -> MagicMock:+ response = MagicMock()+ response.status_code = 401+ response.headers = {"content-type": "application/json", "www-authenticate": "Bearer"}+ response.content = json.dumps(body).encode()+ response.text = json.dumps(body)+ response.json.return_value = body+ return response+++CALLS: dict[str, Callable[[SIEClient], object]] = {+ "chat_completions": lambda client: client.chat_completions("m", [{"role": "user", "content": "hi"}]),+ "responses": lambda client: client.responses("m", "hi"),+}++[email protected]("body", [DETAIL, OPENAI], ids=["detail", "openai"])[email protected]("call", sorted(CALLS))+def test_an_auth_refusal_raises_request_error_in_either_envelope(body: dict[str, Any], call: str) -> None:+ with patch("sie_sdk.client.sync.httpx.Client") as client_cls:+ client_cls.return_value.post.return_value = _refusal(body)+ client = SIEClient("http://localhost:8080")++ with pytest.raises(RequestError) as raised:+ CALLS[call](client)++ assert type(raised.value) is RequestError+ assert raised.value.status_code == 401+ assert raised.value.code == "UNAUTHORIZED"+ assert str(raised.value) == MESSAGE+ assert client_cls.return_value.post.call_count == 1+ client.close()diff --git a/packages/sie_server/README.md b/packages/sie_server/README.mdindex f3d5c76ee..62102749f 100644--- a/packages/sie_server/README.md+++ b/packages/sie_server/README.md@@ -1125,6 +1125,15 @@ server reads every value of a repeated header, skips empty ones, and refusesvalues that carry different tokens, while the gateway reads only the first`Authorization` value and uses `x-api-key` when that value is empty or blank.+A refused request gets `401` with `WWW-Authenticate: Bearer` and the code+`UNAUTHORIZED`, on the server and the gateway alike. On the OpenAI-compatible+routes (`/v1/chat/completions`, `/v1/completions`, `/v1/responses`,+`/v1/embeddings`, `/v1/audio/transcriptions`, and on the gateway also+`/v1/models` and `/v1/moderations`) the body is the OpenAI error envelope,+`{"error": {"message", "type": "authentication_error", "param": null, "code"}}`,+so OpenAI clients read it; `/v1/messages` answers in the Anthropic envelope and+the other routes in `{"detail": {"code", "message"}}`.+Token auth covers the HTTP port. The other listeners are local: the IPC socketthat a worker sidecar uses (`SIE_IPC_SOCKET_PATH`, mode `0600`) and theloopback ports of the engines the server launches. On macOS a socket candiff --git a/packages/sie_server/src/sie_server/api/openai_errors.py b/packages/sie_server/src/sie_server/api/openai_errors.pynew file mode 100644index 000000000..8bceb2311--- /dev/null+++ b/packages/sie_server/src/sie_server/api/openai_errors.py@@ -0,0 +1,180 @@+"""The OpenAI error envelope for every error answer on the OpenAI-compatible routes.++The routes' handlers answer in the OpenAI envelope. Refusals made outside them,+such as token authentication's, use the SIE ``{"detail": ...}`` envelope, which+OpenAI clients cannot read. :class:`OpenAIErrorEnvelopeMiddleware` re-renders+those on ``/v1/chat/completions``, ``/v1/completions``, ``/v1/responses``,+``/v1/embeddings`` and ``/v1/audio/transcriptions`` with the rule the gateway's+``openai_error_envelope`` applies.+"""++from __future__ import annotations++from http import HTTPStatus+from typing import Any++import orjson+from starlette.types import ASGIApp, Message, Receive, Scope, Send++OPENAI_PATHS = (+ "/v1/chat/completions",+ "/v1/completions",+ "/v1/responses",+ "/v1/embeddings",+ "/v1/audio/transcriptions",+)+_MAX_ERROR_BODY_BYTES = 1024 * 1024+_ENVELOPE_FIELDS = frozenset({"message", "type", "param", "code"})+_STATUS_TYPES: dict[int, str] = {+ HTTPStatus.UNAUTHORIZED: "authentication_error",+ HTTPStatus.FORBIDDEN: "permission_error",+ HTTPStatus.TOO_MANY_REQUESTS: "rate_limit_error",+}+_STATUS_CODES: dict[int, str] = {+ HTTPStatus.UNAUTHORIZED: "UNAUTHORIZED",+ HTTPStatus.FORBIDDEN: "FORBIDDEN",+ HTTPStatus.NOT_FOUND: "NOT_FOUND",+ HTTPStatus.REQUEST_ENTITY_TOO_LARGE: "PAYLOAD_TOO_LARGE",+ HTTPStatus.TOO_MANY_REQUESTS: "RATE_LIMIT",+}+++def is_openai_path(path: str) -> bool:+ """Whether a path is one of this server's OpenAI-compatible routes or below one."""+ return any(path == base or path.startswith(f"{base}/") for base in OPENAI_PATHS)+++def _client_error(status: int) -> bool:+ return HTTPStatus.BAD_REQUEST <= status < HTTPStatus.INTERNAL_SERVER_ERROR+++def openai_type_for_status(status: int) -> str:+ """The ``error.type`` of a re-rendered refusal: by status, as on the gateway."""+ if status in _STATUS_TYPES:+ return _STATUS_TYPES[status]+ return "invalid_request_error" if _client_error(status) else "server_error"+++def _code_for_status(status: int) -> str:+ if status in _STATUS_CODES:+ return _STATUS_CODES[status]+ return "INVALID_REQUEST" if _client_error(status) else "INTERNAL_SERVER_ERROR"+++def _reason(status: int) -> str:+ try:+ return HTTPStatus(status).phrase+ except ValueError:+ return ""+++def openai_error_from_detail(status: int, body: Any) -> dict[str, Any] | None:+ """The OpenAI envelope for a ``{"detail": ...}`` body, or ``None`` for any other body.++ ``detail.code`` is kept verbatim and a string ``detail`` gets the SIE code of+ its status; ``param`` is ``detail.param`` when it is a string; every other+ ``detail`` field is kept in ``error``.+ """+ if not isinstance(body, dict) or isinstance(body.get("error"), dict):+ return None+ detail = body.get("detail")+ error_type = openai_type_for_status(status)+ if isinstance(detail, str):+ return {"error": {"message": detail, "type": error_type, "param": None, "code": _code_for_status(status)}}+ if not isinstance(detail, dict):+ return None+ message = detail.get("message")+ param = detail.get("param")+ code = detail.get("code")+ error: dict[str, Any] = {+ "message": message if isinstance(message, str) else _reason(status),+ "type": error_type,+ "param": param if isinstance(param, str) else None,+ "code": code if isinstance(code, str) else _code_for_status(status),+ }+ error.update((key, value) for key, value in detail.items() if key not in _ENVELOPE_FIELDS)+ return {"error": error}+++def _rewritable(headers: list[tuple[bytes, bytes]]) -> bool:+ """Whether a response start declares a JSON body of at most 1 MiB."""+ mime: str | None = None+ length: bytes | None = None+ for name, value in headers:+ lowered = name.lower()+ if lowered == b"content-type" and mime is None:+ mime = value.decode("latin-1").split(";", 1)[0].strip().lower()+ elif lowered == b"content-length" and length is None:+ length = value.strip()+ if mime is None or not (mime == "application/json" or mime.endswith("+json")):+ return False+ return length is not None and length.isdigit() and int(length) <= _MAX_ERROR_BODY_BYTES+++def _render(status: int, body: bytes) -> bytes | None:+ try:+ parsed = orjson.loads(body)+ except orjson.JSONDecodeError:+ return None+ envelope = openai_error_from_detail(status, parsed)+ return None if envelope is None else orjson.dumps(envelope)+++class OpenAIErrorEnvelopeMiddleware:+ """Give every error answer on the OpenAI-compatible routes and the paths below them the OpenAI envelope.++ Added outside the server's other middleware, so their refusals on these+ paths, such as a missing credential, take the shape OpenAI clients read. A+ 4xx or 5xx JSON answer whose body is ``{"detail": {...}}`` or+ ``{"detail": "..."}`` becomes ``{"error": {"message", "type", "param",+ "code", ...}}`` with its status and headers, and a recomputed+ ``Content-Length``. ``type`` follows the status: ``authentication_error``+ (401), ``permission_error`` (403), ``rate_limit_error`` (429),+ ``invalid_request_error`` (other 4xx) and ``server_error`` (5xx). Answers+ already in the OpenAI envelope, answers that are not JSON or do not declare+ a ``Content-Length`` of at most 1 MiB, and successes pass through untouched.+ """++ def __init__(self, app: ASGIApp) -> None:+ self.app = app++ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:+ if scope["type"] != "http" or not is_openai_path(scope["path"]):+ await self.app(scope, receive, send)+ return+ held: Message | None = None+ body = bytearray()++ async def respond(message: Message) -> None:+ nonlocal held+ if message["type"] == "http.response.start":+ if message["status"] >= HTTPStatus.BAD_REQUEST and _rewritable(message.get("headers", [])):+ held = message+ return+ await send(message)+ return+ if held is None or message["type"] != "http.response.body":+ await send(message)+ return+ body.extend(message.get("body", b""))+ more_body = message.get("more_body", False)+ start = held+ if len(body) > _MAX_ERROR_BODY_BYTES:+ held = None+ await send(start)+ await send({"type": "http.response.body", "body": bytes(body), "more_body": more_body})+ return+ if more_body:+ return+ held = None+ rendered = _render(start["status"], bytes(body))+ if rendered is None:+ await send(start)+ await send({"type": "http.response.body", "body": bytes(body)})+ return+ headers = [(name, value) for name, value in start.get("headers", []) if name.lower() != b"content-length"]+ headers.append((b"content-length", str(len(rendered)).encode()))+ await send({**start, "headers": headers})+ await send({"type": "http.response.body", "body": rendered})++ await self.app(scope, receive, respond)diff --git a/packages/sie_server/src/sie_server/app/app_factory.py b/packages/sie_server/src/sie_server/app/app_factory.pyindex e6a39e3d8..1c80a95b7 100644--- a/packages/sie_server/src/sie_server/app/app_factory.py+++ b/packages/sie_server/src/sie_server/app/app_factory.py@@ -20,6 +20,7 @@ from sie_server.api.models import router as models_routerfrom sie_server.api.openai_audio import router as openai_audio_routerfrom sie_server.api.openai_compat import router as openai_routerfrom sie_server.api.openai_completions import router as openai_completions_router+from sie_server.api.openai_errors import OpenAIErrorEnvelopeMiddlewarefrom sie_server.api.openai_local import router as openai_local_routerfrom sie_server.api.openai_responses import router as openai_responses_routerfrom sie_server.api.openapi import setup_custom_openapi_schema@@ -102,6 +103,7 @@ class AppFactory:elif config.bind_host and is_loopback_host(config.bind_host):app.add_middleware(LoopbackHostMiddleware, allowed_hosts=loopback_host_allowlist(config.bind_host))app.add_middleware(AnthropicErrorEnvelopeMiddleware)+ app.add_middleware(OpenAIErrorEnvelopeMiddleware)install_upstreams(load_upstreams(config.upstreams_file) if config.upstreams_file else {},diff --git a/packages/sie_server/tests/api/test_anthropic_messages_route.py b/packages/sie_server/tests/api/test_anthropic_messages_route.pyindex fb09646d2..7d0dfabe8 100644--- a/packages/sie_server/tests/api/test_anthropic_messages_route.py+++ b/packages/sie_server/tests/api/test_anthropic_messages_route.py@@ -420,7 +420,7 @@ def test_token_auth_takes_either_header_and_refuses_in_the_anthropic_envelope(assert missing.headers["www-authenticate"] == "Bearer"assert missing.headers["x-sie-error-code"] == "UNAUTHORIZED"assert chat_missing.status_code == 401- assert chat_missing.json()["detail"]["code"] == "UNAUTHORIZED"+ assert chat_missing.json()["error"]["code"] == "UNAUTHORIZED"for credentials in ({"x-api-key": TOKEN},{"authorization": f"Bearer {TOKEN}"},diff --git a/packages/sie_server/tests/api/test_openai_error_envelope.py b/packages/sie_server/tests/api/test_openai_error_envelope.pynew file mode 100644index 000000000..93b3cbe26--- /dev/null+++ b/packages/sie_server/tests/api/test_openai_error_envelope.py@@ -0,0 +1,267 @@+"""Every error answer on the server's OpenAI-compatible routes uses the OpenAI envelope."""++from __future__ import annotations++from typing import Any++import pytest+from fastapi.testclient import TestClient+from sie_server.api.openai_errors import OpenAIErrorEnvelopeMiddleware, is_openai_path, openai_error_from_detail+from sie_server.app.app_factory import AppFactory+from sie_server.app.app_state_config import AppStateConfig+from starlette.applications import Starlette+from starlette.requests import Request+from starlette.responses import JSONResponse, PlainTextResponse, Response, StreamingResponse+from starlette.routing import Route++TOKEN = "openai-envelope-token" # noqa: S105 - a test credential+OPENAI_PATHS = [+ "/v1/chat/completions",+ "/v1/completions",+ "/v1/responses",+ "/v1/responses/resp_1",+ "/v1/embeddings",+ "/v1/audio/transcriptions",+]+OTHER_PATHS = [+ "/v1/messages",+ "/v1/encode/m",+ "/v1/score/m",+ "/v1/extract/m",+ "/v1/generate/m",+ "/v1/models",+ "/v1/models/m",+ "/v1/rerank",+ "/v1/systemone",+ "/v1/decisions",+ "/v1/completionsx",+ "/healthz",+]+MISSING = "Missing credentials: send Authorization: Bearer <token> or x-api-key: <token>"++[email protected]("path", OPENAI_PATHS)+def test_openai_paths_cover_the_routes_and_the_paths_below_them(path: str) -> None:+ assert is_openai_path(path)++[email protected]("path", OTHER_PATHS)+def test_other_paths_are_not_openai_paths(path: str) -> None:+ assert not is_openai_path(path)+++ ("status", "error_type", "code"),+ [+ (400, "invalid_request_error", "INVALID_REQUEST"),+ (401, "authentication_error", "UNAUTHORIZED"),+ (402, "invalid_request_error", "INVALID_REQUEST"),+ (403, "permission_error", "FORBIDDEN"),+ (404, "invalid_request_error", "NOT_FOUND"),+ (405, "invalid_request_error", "INVALID_REQUEST"),+ (413, "invalid_request_error", "PAYLOAD_TOO_LARGE"),+ (429, "rate_limit_error", "RATE_LIMIT"),+ (500, "server_error", "INTERNAL_SERVER_ERROR"),+ (503, "server_error", "INTERNAL_SERVER_ERROR"),+ ],+)+def test_the_type_follows_the_status(status: int, error_type: str, code: str) -> None:+ assert openai_error_from_detail(status, {"detail": "refused"}) == {+ "error": {"message": "refused", "type": error_type, "param": None, "code": code}+ }+ envelope = openai_error_from_detail(status, {"detail": {"code": "SOME_SIE_CODE", "message": "refused"}})+ assert envelope is not None+ assert envelope["error"]["type"] == error_type+ assert envelope["error"]["code"] == "SOME_SIE_CODE"+++def test_detail_fields_are_kept() -> None:+ detail = {+ "code": "KEY_REGION",+ "message": "this key belongs to another region",+ "param": "model",+ "key_region": "eu",+ "region_endpoint": "https://eu.example.test",+ "epoch": 7,+ }++ assert openai_error_from_detail(403, {"detail": detail}) == {+ "error": {+ "message": "this key belongs to another region",+ "type": "permission_error",+ "param": "model",+ "code": "KEY_REGION",+ "key_region": "eu",+ "region_endpoint": "https://eu.example.test",+ "epoch": 7,+ }+ }+++ "body",+ [+ {"error": {"message": "no", "type": "invalid_request_error", "param": None, "code": "unsupported_field"}},+ {"detail": [{"loc": ["body"], "msg": "required"}]},+ {"message": "no"},+ ["detail"],+ "detail",+ ],+)+def test_other_bodies_are_not_rewritten(body: Any) -> None:+ assert openai_error_from_detail(400, body) is None+++def _refusal(request: Request) -> Response:+ return JSONResponse(+ {"detail": {"code": "UNAUTHORIZED", "message": "no token"}},+ status_code=401,+ headers={+ "WWW-Authenticate": "Bearer",+ "Retry-After": "30",+ "X-SIE-Error-Code": "UNAUTHORIZED",+ "X-SIE-RateLimit-Rps": "5",+ },+ )+++async def _chunks() -> Any:+ yield b'{"detail": "Not '+ yield b'Found"}'+++def _chunked(request: Request) -> Response:+ return StreamingResponse(_chunks(), status_code=404, media_type="application/json")+++def _chunked_with_length(request: Request) -> Response:+ return StreamingResponse(+ _chunks(), status_code=404, media_type="application/json", headers={"content-length": "23"}+ )+++def _oversized(request: Request) -> Response:+ return JSONResponse({"detail": "x" * (1024 * 1024 + 1)}, status_code=400)+++def _plain(request: Request) -> Response:+ return PlainTextResponse('{"detail": "no"}', status_code=401)+++def _success(request: Request) -> Response:+ return JSONResponse({"detail": {"code": "OK", "message": "fine"}})+++def _openai(request: Request) -> Response:+ return Response(+ b'{"error":{"message":"no","type":"x","param":null,"code":"y"}}', 400, media_type="application/json"+ )+++def _app() -> TestClient:+ handlers = {+ "refusal": _refusal,+ "chunked": _chunked,+ "chunked_with_length": _chunked_with_length,+ "oversized": _oversized,+ "plain": _plain,+ "success": _success,+ "openai": _openai,+ }+ routes = [+ Route(f"{base}/{name}", handler)+ for base in ("/v1/chat/completions", "/v1/encode", "/v1/messages")+ for name, handler in handlers.items()+ ]+ app = Starlette(routes=routes)+ app.add_middleware(OpenAIErrorEnvelopeMiddleware)+ return TestClient(app)+++def test_a_detail_refusal_keeps_its_status_and_headers() -> None:+ response = _app().get("/v1/chat/completions/refusal")++ assert response.status_code == 401+ assert response.headers["www-authenticate"] == "Bearer"+ assert response.headers["retry-after"] == "30"+ assert response.headers["x-sie-error-code"] == "UNAUTHORIZED"+ assert response.headers["x-sie-ratelimit-rps"] == "5"+ assert response.headers["content-length"] == str(len(response.content))+ assert response.json() == {+ "error": {"message": "no token", "type": "authentication_error", "param": None, "code": "UNAUTHORIZED"}+ }+++def test_a_declared_length_body_sent_in_chunks_is_rewritten() -> None:+ response = _app().get("/v1/chat/completions/chunked_with_length")++ assert response.status_code == 404+ assert response.headers["content-length"] == str(len(response.content))+ assert response.json() == {+ "error": {"message": "Not Found", "type": "invalid_request_error", "param": None, "code": "NOT_FOUND"}+ }++[email protected]("name", ["chunked", "oversized", "plain", "success", "openai"])+def test_other_answers_pass_through(name: str) -> None:+ client = _app()+ expected = client.get(f"/v1/encode/{name}")+ response = client.get(f"/v1/chat/completions/{name}")++ assert response.status_code == expected.status_code+ assert response.content == expected.content+ assert response.headers.get("content-type") == expected.headers.get("content-type")++[email protected]("base", ["/v1/encode", "/v1/messages"])+def test_other_paths_keep_the_detail_envelope(base: str) -> None:+ response = _app().get(f"{base}/refusal")++ assert response.status_code == 401+ assert response.json() == {"detail": {"code": "UNAUTHORIZED", "message": "no token"}}+++def served(monkeypatch: pytest.MonkeyPatch) -> TestClient:+ monkeypatch.setenv("SIE_AUTH_TOKEN", TOKEN)+ return TestClient(AppFactory.create_app(AppStateConfig(auth_mode="token")))+++ "path",+ ["/v1/chat/completions", "/v1/completions", "/v1/responses", "/v1/embeddings", "/v1/audio/transcriptions"],+)+def test_a_missing_token_on_an_openai_route_gets_the_openai_envelope(served: TestClient, path: str) -> None:+ response = served.post(path, json={})++ assert response.status_code == 401+ assert response.headers["www-authenticate"] == "Bearer"+ assert response.json() == {+ "error": {"message": MISSING, "type": "authentication_error", "param": None, "code": "UNAUTHORIZED"}+ }+++def test_native_routes_and_messages_keep_their_envelopes(served: TestClient) -> None:+ for path in ("/v1/encode/m", "/v1/models"):+ response = served.post(path, json={}) if path.startswith("/v1/encode") else served.get(path)+ assert response.status_code == 401, path+ assert response.json() == {"detail": {"code": "UNAUTHORIZED", "message": MISSING}}, path++ messages = served.post("/v1/messages", json={})+ assert messages.status_code == 401+ assert messages.json()["type"] == "error"+ assert messages.json()["error"]["type"] == "authentication_error"+++def test_routing_refusals_on_openai_paths_get_the_openai_envelope(served: TestClient) -> None:+ headers = {"Authorization": f"Bearer {TOKEN}"}+ unknown = served.post("/v1/responses/resp_1", json={}, headers=headers)+ wrong_method = served.get("/v1/chat/completions", headers=headers)++ assert unknown.status_code == 404+ assert unknown.json() == {+ "error": {"message": "Not Found", "type": "invalid_request_error", "param": None, "code": "NOT_FOUND"}+ }+ assert wrong_method.status_code == 405+ assert wrong_method.json()["error"]["code"] == "INVALID_REQUEST"+ assert wrong_method.headers["allow"] == "POST"diff --git a/packages/sie_ts_sdk/tests/chat.test.ts b/packages/sie_ts_sdk/tests/chat.test.tsindex dbeacf490..3257fa42a 100644--- a/packages/sie_ts_sdk/tests/chat.test.ts+++ b/packages/sie_ts_sdk/tests/chat.test.ts@@ -147,6 +147,40 @@ describe("SIEClient.chatCompletions", () => {);});+ it.each([+ [+ "detail",+ {+ detail: { code: "UNAUTHORIZED", message: "Missing Authorization or x-api-key header" },+ },+ ],+ [+ "openai",+ {+ error: {+ message: "Missing Authorization or x-api-key header",+ type: "authentication_error",+ param: null,+ code: "UNAUTHORIZED",+ },+ },+ ],+ ])("throws the same RequestError for a 401 in the %s envelope", async (_envelope, body) => {+ mockFetch.mockResolvedValueOnce(jsonResponse(body, 401, { "WWW-Authenticate": "Bearer" }));++ const client = new SIEClient("http://localhost:8080");+ const error = await client+ .chatCompletions({ model: "m", messages: [{ role: "user", content: "hi" }] })+ .catch((caught: unknown) => caught);++ expect(error).toBeInstanceOf(RequestError);+ expect((error as RequestError).constructor).toBe(RequestError);+ expect((error as RequestError).statusCode).toBe(401);+ expect((error as RequestError).code).toBe("UNAUTHORIZED");+ expect((error as RequestError).message).toBe("Missing Authorization or x-api-key header");+ expect(mockFetch).toHaveBeenCalledTimes(1);+ });+it("throws ServerError on 500", async () => {mockFetch.mockResolvedValueOnce(jsonResponse({ error: { message: "boom", type: "server_error", code: "internal" } }, 500),diff --git a/packages/sie_ts_sdk/tests/responses.test.ts b/packages/sie_ts_sdk/tests/responses.test.tsindex 569e6df74..8ccb69324 100644--- a/packages/sie_ts_sdk/tests/responses.test.ts+++ b/packages/sie_ts_sdk/tests/responses.test.ts@@ -340,6 +340,40 @@ describe("SIEClient.responses", () => {expect(mockFetch).toHaveBeenCalledOnce();});+ it.each([+ [+ "detail",+ {+ detail: { code: "UNAUTHORIZED", message: "Missing Authorization or x-api-key header" },+ },+ ],+ [+ "openai",+ {+ error: {+ message: "Missing Authorization or x-api-key header",+ type: "authentication_error",+ param: null,+ code: "UNAUTHORIZED",+ },+ },+ ],+ ])("throws the same RequestError for a 401 in the %s envelope", async (_envelope, body) => {+ mockFetch.mockResolvedValueOnce(jsonResponse(body, 401, { "WWW-Authenticate": "Bearer" }));++ const client = new SIEClient("http://localhost:8080");+ const error = await client+ .responses({ model: "m", input: "Hi" })+ .catch((caught: unknown) => caught);++ expect(error).toBeInstanceOf(RequestError);+ expect((error as RequestError).constructor).toBe(RequestError);+ expect((error as RequestError).statusCode).toBe(401);+ expect((error as RequestError).code).toBe("UNAUTHORIZED");+ expect((error as RequestError).message).toBe("Missing Authorization or x-api-key header");+ expect(mockFetch).toHaveBeenCalledOnce();+ });+it("retries 503 MODEL_LOADING then returns the result", async () => {vi.useFakeTimers();try {