Skip to content

armgit / kwant

Public Imported from GitHub
0

Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.

server: one error shape for every /api error (14d) (#638)

Oleksandr Ivanchenko7ea46a7acabb
diff --git a/docs/teams-api.md b/docs/teams-api.md
index 10f61385..2d21a119 100644
--- a/docs/teams-api.md
+++ b/docs/teams-api.md
@@ -402,3 +402,32 @@ Every window a test has to cross reads "now" from **`kwnt::clock::now()`**. Nobo
| Clash code (test plan T-A5, T-W9, Q-API1) | 409 `clash` with `clashes[]` | 409 `name_taken` / `handle_taken` (`name_taken` is what imports already answer) **plus** `clashes[]` with every clash | one code family across kwant; the list is what the sheet needs |
| Idempotency (test plan §0.5, T-W9) | `idempotency_key` in the body, required | optional `Idempotency-Key` header; 400 `bad_request` when sent empty or over 200 characters | a header keeps the body strict (`unknown_field`), and an older client without a key still works; the sheet always sends one |
| Templates source | templates-copy.md | `templates.json` embedded byte for byte from `design/templates.js` | no hand copying |
+
+## 9. Errors, everywhere in the HTTP API (14d)
+
+Every refusal under `/api/` (any 4xx or 5xx) answers in one JSON shape:
+
+```json
+{ "error": "<a plain sentence>", "code": "<snake_case>", "detail": "<optional>" }
+```
+
+- A route's own `code` always wins (`bad_name`, `exists`, `too_large`, `archived`, ...), and so do its other fields
+ (`field`, `suggestion`, `max_bytes`, `person_only`, ...).
+- A route that sends no `code` gets one from the status: `bad_request` (400 and any other 4xx), `unauthorized`
+ (401), `forbidden` (403), `not_found` (404), `method_not_allowed` (405), `conflict` (409), `too_large` (413),
+ `unsupported_media` (415), `unprocessable` (422), `rate_limited` (429), `server_error` (5xx).
+- A request kwant can't parse (a query, path or JSON body in the wrong form) gets a plain sentence, one of the codes
+ `bad_request`, `bad_json` (the body isn't valid JSON), `unsupported_media` (not sent as `application/json`),
+ `too_large` or `unprocessable` (valid JSON with the wrong fields or types), and the parser's own words in `detail`
+ (at most 300 characters). For example `GET /api/spaces/spc_default/docs/page?file=faq.md&page=abc`:
+ `400 {"error": "That request wasn't in the form kwant expected.", "code": "bad_request", "detail": "Failed to deserialize query string: invalid digit found in string"}`.
+- A 409 that found a thing in another state names that state in both `status` and `code` (a fact `accepted`, a
+ proposal `stale`, a suggestion `dismissed`).
+- Successful answers, downloads, streams (SSE, WebSocket), and error bodies over 64 KB or of unknown length are sent
+ as the route wrote them. JSON-RPC answers (`/api/mcp/...`) keep their own `error` object.
+- The MCP transport endpoints (`/api/mcp/agents`, `/api/mcp/gateway`, `/api/mcp/gateway/grok`,
+ `/api/mcp/permission/:token`, `/api/mcp/self`) are left alone entirely: MCP clients call them, and an unknown or
+ revoked bearer there is still a bare `401` with an empty body. The management routes under `/api/mcp/` (servers,
+ OAuth, registry, suggestions) get the shape like any other route.
+
+The layer is `src/server/error_shape.rs`, the outermost layer of the router.
diff --git a/frontend/src/spaceDocs.ts b/frontend/src/spaceDocs.ts
index 846b0274..1f0e3aa9 100644
--- a/frontend/src/spaceDocs.ts
+++ b/frontend/src/spaceDocs.ts
@@ -279,12 +279,14 @@ const ADD_CODES: Record<string, AddProblem> = {
no_text: 'no_text',
unreadable: 'unreadable',
person_only: 'person_only',
+ archived: 'archived',
};
/**
* Maps an add's answer (Vega's route) to what the row says. The error's `code` decides, never the status or the
- * words: two 409s and two 422s mean different things, and the words carry the file's own name. Without a code,
- * only a proxy's bare 413 and the archived space's 409 (the one 409 without a code) are told apart.
+ * words: two 409s and two 422s mean different things, and the words carry the file's own name. The archived space's
+ * 409 has the code `archived` since 14d; without a code (an older server, or a proxy), a bare 413 and a 409 are still
+ * told apart.
*/
export function addResultOf(status: number, code: string, error = ''): Exclude<AddResult, { ok: true }> {
const kind = ADD_CODES[code];
diff --git a/frontend/tests/spaceDocs.test.mjs b/frontend/tests/spaceDocs.test.mjs
index dc1ae523..d9aecfa9 100644
--- a/frontend/tests/spaceDocs.test.mjs
+++ b/frontend/tests/spaceDocs.test.mjs
@@ -148,6 +148,10 @@ test('add: the error code decides the row, never the status or the words', () =>
[409, 'full', 'this space has 200 documents, the most kwant reads', 'limit'],
[409, 'docs_link', 'the space’s docs isn’t a plain folder', 'docs_link'],
[409, '', 'this space is archived; restore it first', 'archived'],
+ [409, 'archived', 'this space is archived; restore it first', 'archived'],
+ [409, 'conflict', 'something else changed', 'failed'],
+ [413, 'too_large', '', 'too_large'],
+ [500, 'server_error', 'Something went wrong inside kwant.', 'failed'],
[403, 'person_only', 'only the person', 'person_only'],
[400, 'interrupted', 'The upload was interrupted.', 'failed'],
[422, 'something_new', 'already exists', 'failed'],
diff --git a/src/server/error_shape.rs b/src/server/error_shape.rs
new file mode 100644
index 00000000..ebc681f1
--- /dev/null
+++ b/src/server/error_shape.rs
@@ -0,0 +1,408 @@
+//! One shape for every refusal under `/api/` (roadmap 14d): `{error, code[, detail]}`.
+//!
+//! Handlers keep their own messages and codes; this layer only fills the gaps, on 4xx/5xx
+//! responses to `/api/` paths:
+//! - **axum's own extractor rejections** (`Query`, `Json`, `Path`, body limits), which axum
+//! answers in plain text ("Failed to deserialize query string"), become a plain sentence with a
+//! code (`bad_request`, `bad_json`, `unsupported_media`, `too_large`, `unprocessable`); the
+//! parser's text is kept in `detail`, cut to [`DETAIL_CHARS`] characters.
+//! - **another plain-text or empty body** (a handler's own `(StatusCode, String)`) keeps its text
+//! as `error` (the status's sentence when empty) and gets the status's code.
+//! - **a JSON body with a string `error` and no `code`** (the per-module `error()` helpers) gets
+//! the status's code ([`status_code`]); every other field stays as it is.
+//!
+//! Everything else passes through untouched: the MCP transport endpoints ([`mcp_transport`]:
+//! `/api/mcp/agents`, `/api/mcp/gateway…`, `/api/mcp/permission/…`, `/api/mcp/self`, whose
+//! unauthenticated answer is a bare 401), success responses, bodies that already have a
+//! `code`, JSON that isn't `{error: "…"}` (JSON-RPC answers included), any other content type
+//! (downloads, HTML, event streams), and bodies that may be larger than [`MAX_BODY`] or have no
+//! known length (a stream is never buffered).
+
+use axum::{
+ body::{to_bytes, Body, HttpBody},
+ extract::Request,
+ http::{header, HeaderValue, StatusCode},
+ middleware::Next,
+ response::Response,
+};
+use serde_json::{json, Map, Value};
+
+/// Error bodies at most this large are read; a larger or unknown-length one passes untouched.
+pub const MAX_BODY: u64 = 64 * 1024;
+/// The parser's own text is kept in `detail` up to this many characters.
+pub const DETAIL_CHARS: usize = 300;
+
+/// The texts axum answers its extractor rejections with (axum 0.7 / axum-core 0.4), by prefix.
+const REJECTION_PREFIXES: [&str; 16] = [
+ "Failed to deserialize",
+ "Failed to parse the request body as JSON",
+ "Failed to buffer the request body",
+ "Expected request with `Content-Type: application/json`",
+ "Form requests must have `Content-Type",
+ "Request body didn't contain valid UTF-8",
+ "Invalid URL",
+ "Wrong number of path arguments",
+ "No paths parameters found",
+ "Missing request extension",
+ "No host found in request",
+ "No matched path found",
+ "The matched route is not nested",
+ "Connection header did not include",
+ "`Upgrade` header did not include",
+ "`Sec-WebSocket-",
+];
+
+/// The code a status gives an error body that has none.
+pub fn status_code(status: StatusCode) -> &'static str {
+ match status.as_u16() {
+ 400 => "bad_request",
+ 401 => "unauthorized",
+ 403 => "forbidden",
+ 404 => "not_found",
+ 405 => "method_not_allowed",
+ 409 => "conflict",
+ 413 => "too_large",
+ 415 => "unsupported_media",
+ 422 => "unprocessable",
+ 429 => "rate_limited",
+ 500..=599 => "server_error",
+ _ => "bad_request",
+ }
+}
+
+/// A plain sentence for a status, when the body says nothing a person can read.
+fn status_sentence(status: StatusCode) -> &'static str {
+ match status.as_u16() {
+ 401 => "kwant needs a valid sign-in for that.",
+ 403 => "That isn't allowed.",
+ 404 => "kwant couldn't find that.",
+ 405 => "That action isn't available here.",
+ 409 => "That clashes with how things are now.",
+ 413 => "That's too large for kwant to accept.",
+ 415 => "kwant can't read that kind of request.",
+ 422 => "That request's values weren't what kwant expected.",
+ 429 => "Too many requests at once. Try again in a moment.",
+ 500..=599 => "Something went wrong inside kwant.",
+ _ => "That request wasn't in the form kwant expected.",
+ }
+}
+
+/// An axum rejection's code and sentence, by its status and text.
+fn rejection(status: StatusCode, text: &str) -> (&'static str, &'static str) {
+ match status.as_u16() {
+ 413 => ("too_large", status_sentence(status)),
+ 415 => ("unsupported_media", "kwant expected this request as JSON (Content-Type: application/json)."),
+ 422 => ("unprocessable", status_sentence(status)),
+ 400 if text.starts_with("Failed to parse the request body as JSON") => {
+ ("bad_json", "That request's body isn't valid JSON.")
+ }
+ 500..=599 => ("server_error", status_sentence(status)),
+ _ => ("bad_request", "That request wasn't in the form kwant expected."),
+ }
+}
+
+fn is_rejection(text: &str) -> bool {
+ REJECTION_PREFIXES.iter().any(|p| text.starts_with(p))
+}
+
+fn cut(text: &str, max: usize) -> String {
+ match text.char_indices().nth(max) {
+ Some((i, _)) => format!("{}…", &text[..i]),
+ None => text.to_string(),
+ }
+}
+
+enum Kind {
+ Json,
+ Text,
+ Empty,
+}
+
+/// What the layer may rewrite, judged from the headers alone (the body is read only after).
+fn kind(resp: &Response) -> Option<Kind> {
+ let status = resp.status();
+ if !(status.is_client_error() || status.is_server_error()) {
+ return None;
+ }
+ let declared = resp.headers().get(header::CONTENT_LENGTH).and_then(|v| v.to_str().ok()?.parse::<u64>().ok());
+ let known = declared.or_else(|| resp.body().size_hint().exact()).or_else(|| resp.body().size_hint().upper());
+ match known {
+ Some(n) if n <= MAX_BODY => {}
+ _ => return None,
+ }
+ let ct = resp.headers().get(header::CONTENT_TYPE).and_then(|v| v.to_str().ok()).map(|s| s.to_ascii_lowercase());
+ match ct.as_deref() {
+ None if known == Some(0) => Some(Kind::Empty),
+ None => None,
+ Some(ct) => {
+ let mime = ct.split(';').next().unwrap_or("").trim();
+ if mime == "application/json" || mime.ends_with("+json") {
+ Some(Kind::Json)
+ } else if mime == "text/plain" {
+ Some(Kind::Text)
+ } else {
+ None
+ }
+ }
+ }
+}
+
+/// The new body for `bytes`, or `None` to send the original as it was.
+fn reshape(status: StatusCode, kind: &Kind, bytes: &[u8]) -> Option<Value> {
+ match kind {
+ Kind::Json => {
+ let Ok(Value::Object(mut obj)) = serde_json::from_slice::<Value>(bytes) else { return None };
+ if obj.contains_key("code") || obj.contains_key("jsonrpc") || !obj.get("error").is_some_and(Value::is_string) {
+ return None;
+ }
+ obj.insert("code".into(), Value::from(status_code(status)));
+ Some(Value::Object(obj))
+ }
+ Kind::Text | Kind::Empty => {
+ let text = String::from_utf8_lossy(bytes);
+ let text = text.trim();
+ if text.is_empty() {
+ return Some(json!({ "error": status_sentence(status), "code": status_code(status) }));
+ }
+ if is_rejection(text) {
+ let (code, sentence) = rejection(status, text);
+ return Some(json!({ "error": sentence, "code": code, "detail": cut(text, DETAIL_CHARS) }));
+ }
+ let mut obj = Map::new();
+ obj.insert("error".into(), Value::from(text));
+ obj.insert("code".into(), Value::from(status_code(status)));
+ Some(Value::Object(obj))
+ }
+ }
+}
+
+/// The MCP transport endpoints MCP clients and engines call (JSON-RPC over HTTP). Their refusals
+/// belong to the MCP side, not kwant's API: an unknown or revoked bearer is a bare 401 there
+/// (docs/agents-connect contract), so the layer leaves them alone. The management routes under
+/// `/api/mcp/` (servers, OAuth, registry, suggestions) are ordinary API and keep the shape.
+fn mcp_transport(path: &str) -> bool {
+ path == super::agents_connect::ENDPOINT
+ || path.starts_with("/api/mcp/gateway")
+ || path.starts_with("/api/mcp/permission/")
+ || path == "/api/mcp/self"
+}
+
+/// The layer: see the module docs.
+pub async fn layer(req: Request, next: Next) -> Response {
+ let path = req.uri().path();
+ let api = path.starts_with("/api/") && !mcp_transport(path);
+ let resp = next.run(req).await;
+ if !api {
+ return resp;
+ }
+ shape(resp).await
+}
+
+/// Gives one response the `{error, code}` shape if it needs it (public for the tests).
+pub async fn shape(resp: Response) -> Response {
+ let Some(kind) = kind(&resp) else { return resp };
+ let (mut parts, body) = resp.into_parts();
+ let bytes = match to_bytes(body, MAX_BODY as usize).await {
+ Ok(b) => b,
+ Err(e) => {
+ // The body broke while it was read: the original can't be sent any more
+ tracing::warn!(error = %e, "error body could not be read");
+ parts.headers.remove(header::CONTENT_LENGTH);
+ let v = json!({ "error": status_sentence(parts.status), "code": status_code(parts.status) });
+ return json_response(parts, &v);
+ }
+ };
+ match reshape(parts.status, &kind, &bytes) {
+ Some(v) => json_response(parts, &v),
+ None => Response::from_parts(parts, Body::from(bytes)),
+ }
+}
+
+fn json_response(mut parts: axum::http::response::Parts, v: &Value) -> Response {
+ let body = serde_json::to_vec(v).unwrap_or_default();
+ parts.headers.insert(header::CONTENT_TYPE, HeaderValue::from_static("application/json"));
+ parts.headers.insert(header::CONTENT_LENGTH, HeaderValue::from(body.len()));
+ Response::from_parts(parts, Body::from(body))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use axum::{
+ extract::Query,
+ routing::{get, post},
+ Json, Router,
+ };
+ use serde::Deserialize;
+ use tower::ServiceExt;
+
+ #[derive(Deserialize)]
+ #[allow(dead_code)]
+ struct Q {
+ page: usize,
+ }
+
+ #[derive(Deserialize)]
+ #[allow(dead_code)]
+ struct B {
+ name: String,
+ }
+
+ fn app() -> Router {
+ Router::new()
+ .route("/api/q", get(|Query(_q): Query<Q>| async { "ok" }))
+ .route("/api/j", post(|Json(_b): Json<B>| async { "ok" }))
+ .route("/api/no-code", get(|| async { (StatusCode::NOT_FOUND, Json(json!({"error": "bot not found", "n": 2}))) }))
+ .route(
+ "/api/has-code",
+ get(|| async { (StatusCode::CONFLICT, Json(json!({"error": "already there", "code": "exists"}))) }),
+ )
+ .route("/api/ok", get(|| async { Json(json!({"error": "a field called error on a 200"})) }))
+ .route("/api/own-text", get(|| async { (StatusCode::FORBIDDEN, "Ana isn't in this chat.".to_string()) }))
+ .route("/api/empty", get(|| async { StatusCode::METHOD_NOT_ALLOWED }))
+ .route("/api/big", get(|| async { (StatusCode::BAD_REQUEST, "x".repeat(MAX_BODY as usize + 1)) }))
+ .route(
+ "/api/stream",
+ get(|| async {
+ let chunks = futures::stream::iter([Ok::<_, std::io::Error>("Failed to deserialize")]);
+ (StatusCode::BAD_REQUEST, [(header::CONTENT_TYPE, "text/plain")], Body::from_stream(chunks))
+ }),
+ )
+ .route(
+ "/api/download",
+ get(|| async { (StatusCode::NOT_FOUND, [(header::CONTENT_TYPE, "text/html")], "<p>nope</p>") }),
+ )
+ .route("/api/rpc", get(|| async { (StatusCode::BAD_REQUEST, Json(json!({"jsonrpc": "2.0", "error": "x"}))) }))
+ .route("/plain", get(|| async { (StatusCode::NOT_FOUND, "404 Not Found") }))
+ .route("/api/mcp/agents", post(|| async { StatusCode::UNAUTHORIZED }))
+ .route("/api/mcp/gateway", post(|| async { StatusCode::UNAUTHORIZED }))
+ .route("/api/mcp/self", post(|| async { StatusCode::UNAUTHORIZED }))
+ .route("/api/mcp/servers", post(|| async { StatusCode::UNAUTHORIZED }))
+ .layer(axum::middleware::from_fn(layer))
+ }
+
+ async fn call(method: &str, uri: &str, ct: Option<&str>, body: &str) -> (StatusCode, Option<String>, Vec<u8>) {
+ let mut req = axum::http::Request::builder().method(method).uri(uri);
+ if let Some(ct) = ct {
+ req = req.header(header::CONTENT_TYPE, ct);
+ }
+ let resp = app().oneshot(req.body(Body::from(body.to_string())).unwrap()).await.unwrap();
+ let status = resp.status();
+ let ct = resp.headers().get(header::CONTENT_TYPE).map(|v| v.to_str().unwrap().to_string());
+ let bytes = to_bytes(resp.into_body(), usize::MAX).await.unwrap().to_vec();
+ (status, ct, bytes)
+ }
+
+ fn json_of(b: &[u8]) -> Value {
+ serde_json::from_slice(b).unwrap_or_else(|_| panic!("not JSON: {}", String::from_utf8_lossy(b)))
+ }
+
+ #[tokio::test]
+ async fn a_plain_text_query_rejection_becomes_a_sentence_with_a_code() {
+ let (s, ct, b) = call("GET", "/api/q?page=abc", None, "").await;
+ assert_eq!((s, ct.as_deref()), (StatusCode::BAD_REQUEST, Some("application/json")));
+ let v = json_of(&b);
+ assert_eq!(v["code"], "bad_request");
+ assert_eq!(v["error"], "That request wasn't in the form kwant expected.");
+ assert!(v["detail"].as_str().unwrap().starts_with("Failed to deserialize query string"), "{v}");
+ }
+
+ #[tokio::test]
+ async fn json_body_rejections_get_their_own_codes() {
+ let (s, _, b) = call("POST", "/api/j", Some("application/json"), "{not json").await;
+ let v = json_of(&b);
+ assert_eq!((s, v["code"].as_str()), (StatusCode::BAD_REQUEST, Some("bad_json")), "{v}");
+ assert!(v["detail"].as_str().unwrap().starts_with("Failed to parse the request body as JSON"), "{v}");
+
+ let (s, _, b) = call("POST", "/api/j", Some("application/json"), r#"{"name": 3}"#).await;
+ let v = json_of(&b);
+ assert_eq!((s, v["code"].as_str()), (StatusCode::UNPROCESSABLE_ENTITY, Some("unprocessable")), "{v}");
+
+ let (s, _, b) = call("POST", "/api/j", Some("text/plain"), r#"{"name": "a"}"#).await;
+ let v = json_of(&b);
+ assert_eq!((s, v["code"].as_str()), (StatusCode::UNSUPPORTED_MEDIA_TYPE, Some("unsupported_media")), "{v}");
+ }
+
+ #[tokio::test]
+ async fn a_long_parser_text_is_cut_in_detail() {
+ let v = reshape(StatusCode::BAD_REQUEST, &Kind::Text, format!("Failed to deserialize {}", "é".repeat(500)).as_bytes()).unwrap();
+ assert_eq!(v["detail"].as_str().unwrap().chars().count(), DETAIL_CHARS + 1);
+ assert!(v["detail"].as_str().unwrap().ends_with('…'));
+ }
+
+ #[tokio::test]
+ async fn json_without_a_code_gets_the_status_code_and_keeps_every_field() {
+ let (s, ct, b) = call("GET", "/api/no-code", None, "").await;
+ assert_eq!((s, ct.as_deref()), (StatusCode::NOT_FOUND, Some("application/json")));
+ assert_eq!(json_of(&b), json!({"error": "bot not found", "n": 2, "code": "not_found"}));
+ }
+
+ #[tokio::test]
+ async fn json_with_a_code_is_sent_byte_for_byte() {
+ let (s, _, b) = call("GET", "/api/has-code", None, "").await;
+ assert_eq!(s, StatusCode::CONFLICT);
+ assert_eq!(b, serde_json::to_vec(&json!({"error": "already there", "code": "exists"})).unwrap());
+ }
+
+ #[tokio::test]
+ async fn success_is_untouched() {
+ let (s, _, b) = call("GET", "/api/ok", None, "").await;
+ assert_eq!(s, StatusCode::OK);
+ assert_eq!(json_of(&b), json!({"error": "a field called error on a 200"}));
+ }
+
+ #[tokio::test]
+ async fn a_handlers_own_text_stays_the_error_and_empty_bodies_get_a_sentence() {
+ let (_, _, b) = call("GET", "/api/own-text", None, "").await;
+ assert_eq!(json_of(&b), json!({"error": "Ana isn't in this chat.", "code": "forbidden"}));
+ let (s, _, b) = call("GET", "/api/empty", None, "").await;
+ assert_eq!(s, StatusCode::METHOD_NOT_ALLOWED);
+ assert_eq!(json_of(&b), json!({"error": "That action isn't available here.", "code": "method_not_allowed"}));
+ }
+
+ #[tokio::test]
+ async fn large_streamed_and_other_bodies_pass_through() {
+ let (s, ct, b) = call("GET", "/api/big", None, "").await;
+ assert_eq!((s, ct.as_deref(), b.len()), (StatusCode::BAD_REQUEST, Some("text/plain; charset=utf-8"), MAX_BODY as usize + 1));
+ let (s, ct, b) = call("GET", "/api/stream", None, "").await;
+ assert_eq!((s, ct.as_deref(), b.as_slice()), (StatusCode::BAD_REQUEST, Some("text/plain"), b"Failed to deserialize".as_slice()));
+ let (_, ct, b) = call("GET", "/api/download", None, "").await;
+ assert_eq!((ct.as_deref(), b.as_slice()), (Some("text/html"), b"<p>nope</p>".as_slice()));
+ let (_, _, b) = call("GET", "/api/rpc", None, "").await;
+ assert_eq!(json_of(&b), json!({"jsonrpc": "2.0", "error": "x"}));
+ // Outside /api/ nothing changes
+ let (_, _, b) = call("GET", "/plain", None, "").await;
+ assert_eq!(b, b"404 Not Found");
+ }
+
+ /// CI 43615734542: an MCP client's unauthenticated call is a bare 401, as agents-connect promises;
+ /// kwant's own `/api/mcp/servers` management route still gets the shape.
+ #[tokio::test]
+ async fn mcp_transport_endpoints_keep_their_bare_401() {
+ for uri in ["/api/mcp/agents", "/api/mcp/gateway", "/api/mcp/self"] {
+ let (s, _, b) = call("POST", uri, None, "").await;
+ assert_eq!((s, b.len()), (StatusCode::UNAUTHORIZED, 0), "{uri}");
+ }
+ let (s, _, b) = call("POST", "/api/mcp/servers", None, "").await;
+ assert_eq!(s, StatusCode::UNAUTHORIZED);
+ assert_eq!(json_of(&b), json!({"error": "kwant needs a valid sign-in for that.", "code": "unauthorized"}));
+ }
+
+ #[test]
+ fn every_status_has_a_code() {
+ for (s, c) in [
+ (400, "bad_request"),
+ (401, "unauthorized"),
+ (403, "forbidden"),
+ (404, "not_found"),
+ (409, "conflict"),
+ (413, "too_large"),
+ (429, "rate_limited"),
+ (500, "server_error"),
+ (503, "server_error"),
+ (418, "bad_request"),
+ ] {
+ assert_eq!(status_code(StatusCode::from_u16(s).unwrap()), c, "{s}");
+ }
+ }
+}
diff --git a/src/server/missions/discovery.rs b/src/server/missions/discovery.rs
index 956e7055..26cbbdec 100644
--- a/src/server/missions/discovery.rs
+++ b/src/server/missions/discovery.rs
@@ -507,7 +507,7 @@ async fn load(state: &AppState, query: Option<&str>, id: &str) -> Result<Suggest
}
fn not_offered(s: &SuggestionRow) -> Response {
- (StatusCode::CONFLICT, Json(json!({ "error": format!("this suggestion was already {}", s.status), "status": s.status, "routine_id": s.routine_id }))).into_response()
+ (StatusCode::CONFLICT, Json(json!({ "error": format!("this suggestion was already {}", s.status), "status": s.status, "code": s.status, "routine_id": s.routine_id }))).into_response()
}
/// The routine Accept makes from `s` with the person's overrides `b`, built and checked like any
diff --git a/src/server/missions/flight_school.rs b/src/server/missions/flight_school.rs
index eef55559..73f170b2 100644
--- a/src/server/missions/flight_school.rs
+++ b/src/server/missions/flight_school.rs
@@ -765,7 +765,7 @@ fn not_open(status: &str, why: Option<&str>) -> Response {
("stale", Some(w)) => format!("this proposal is stale: {w}"),
_ => format!("this proposal is already {status}"),
};
- (StatusCode::CONFLICT, Json(json!({"error": error, "status": status}))).into_response()
+ (StatusCode::CONFLICT, Json(json!({"error": error, "status": status, "code": status}))).into_response()
}
#[derive(Deserialize, Default)]
diff --git a/src/server/missions/truth_ledger.rs b/src/server/missions/truth_ledger.rs
index 3890396b..9b779b57 100644
--- a/src/server/missions/truth_ledger.rs
+++ b/src/server/missions/truth_ledger.rs
@@ -257,7 +257,7 @@ async fn decide(State(state): State<AppState>, RawQuery(q): RawQuery, headers: H
},
Ok(Decision::NotProposed(status)) => Err((
StatusCode::CONFLICT,
- Json(json!({ "error": format!("this fact is already {status}"), "status": status })),
+ Json(json!({ "error": format!("this fact is already {status}"), "status": status, "code": status })),
)
.into_response()),
Ok(Decision::NotFound) => Err(not_found("fact")),
@@ -975,7 +975,8 @@ pub async fn needs_you(state: &AppState, task: &super::Task) -> Vec<Value> {
// C2: person routes (all person only through the `/api/facts` prefix, `auth::person_only`)
fn conflict_body(error: String, status: Option<&str>) -> Response {
- (StatusCode::CONFLICT, Json(json!({ "error": error, "status": status }))).into_response()
+ // The code is the state found (the UI reads it), or `conflict` when there is none
+ (StatusCode::CONFLICT, Json(json!({ "error": error, "status": status, "code": status.unwrap_or("conflict") }))).into_response()
}
async fn on_or_409(state: &AppState) -> Option<Response> {
diff --git a/src/server/mod.rs b/src/server/mod.rs
index 6d9c5cf4..eecbfc7e 100644
--- a/src/server/mod.rs
+++ b/src/server/mod.rs
@@ -1,5 +1,6 @@
pub mod discussion;
pub mod routes;
+pub mod error_shape;
pub mod delivery_plan;
pub mod sse;
pub mod browser_input;
@@ -625,5 +626,7 @@ pub fn create_router(state: AppState) -> Router {
.fallback(crate::embedded::static_handler)
.layer(axum::middleware::from_fn_with_state(state.clone(), spaces::row_guard))
.layer(axum::middleware::from_fn_with_state(state.clone(), auth::guard))
+ // Outermost, so the guard's own refusals get a code too (roadmap 14d)
+ .layer(axum::middleware::from_fn(error_shape::layer))
.with_state(state)
}
diff --git a/src/server/space_docs.rs b/src/server/space_docs.rs
index e12c72f1..77a1d19b 100644
--- a/src/server/space_docs.rs
+++ b/src/server/space_docs.rs
@@ -93,13 +93,15 @@ fn plain_name_problem(name: &str) -> Option<&'static str> {
}
}
-/// Why a new document can't be called `name`: 400 `bad_name` (not a plain one-line name, or too
-/// long), 415 `wrong_kind` (a kind kwant doesn't read).
+/// Why a new document can't be called `name`: 400 `bad_name` (not a plain one-line name, too
+/// long, or holding a control or bidi mark), 415 `wrong_kind` (a kind kwant doesn't read).
pub fn upload_name_problem(name: &str) -> Option<(StatusCode, &'static str, &'static str)> {
if let Some(why) = plain_name_problem(name) {
Some((StatusCode::BAD_REQUEST, "bad_name", why))
} else if name.len() > MAX_NAME_BYTES || name.chars().any(char::is_control) {
Some((StatusCode::BAD_REQUEST, "bad_name", "a document's name is one line of at most 200 bytes"))
+ } else if name.chars().any(is_bidi_control) {
+ Some((StatusCode::BAD_REQUEST, "bad_name", "a document's name can't hold invisible direction marks (they can make it read differently)"))
} else if kind_of(name).is_none() {
Some((StatusCode::UNSUPPORTED_MEDIA_TYPE, "wrong_kind", WRONG_KIND))
} else {
@@ -107,6 +109,12 @@ pub fn upload_name_problem(name: &str) -> Option<(StatusCode, &'static str, &'st
}
}
+/// The invisible marks that change which way text runs (U+200E/F, U+202A–U+202E, U+2066–U+2069):
+/// in a name they can make `invoice.md\u{202E}fdp.exe` look like another file.
+fn is_bidi_control(c: char) -> bool {
+ matches!(c, '\u{200E}' | '\u{200F}' | '\u{202A}'..='\u{202E}' | '\u{2066}'..='\u{2069}')
+}
+
fn kind_of(name: &str) -> Option<&'static str> {
let ext = name.rsplit_once('.')?.1.to_ascii_lowercase();
KINDS.iter().copied().find(|k| *k == ext)
@@ -920,6 +928,15 @@ mod tests {
("", Some((StatusCode::BAD_REQUEST, "bad_name"))),
("faq.md ", Some((StatusCode::BAD_REQUEST, "bad_name"))),
("a\nb.md", Some((StatusCode::BAD_REQUEST, "bad_name"))),
+ ("a\u{7F}b.md", Some((StatusCode::BAD_REQUEST, "bad_name"))),
+ ("a\u{1F}b.md", Some((StatusCode::BAD_REQUEST, "bad_name"))),
+ ("faq\u{202E}dm.txt", Some((StatusCode::BAD_REQUEST, "bad_name"))),
+ ("faq\u{200E}.md", Some((StatusCode::BAD_REQUEST, "bad_name"))),
+ ("faq\u{200F}.md", Some((StatusCode::BAD_REQUEST, "bad_name"))),
+ ("\u{202A}faq.md", Some((StatusCode::BAD_REQUEST, "bad_name"))),
+ ("faq\u{2066}x\u{2069}.md", Some((StatusCode::BAD_REQUEST, "bad_name"))),
+ ("Préférences – 2026.md", None),
+ ("سياسة.md", None),
(long.as_str(), Some((StatusCode::BAD_REQUEST, "bad_name"))),
("photo.png", Some((StatusCode::UNSUPPORTED_MEDIA_TYPE, "wrong_kind"))),
("faq", Some((StatusCode::UNSUPPORTED_MEDIA_TYPE, "wrong_kind"))),
@@ -1139,6 +1156,7 @@ mod tests {
("sub%2Fescape.md", b"x".to_vec(), StatusCode::BAD_REQUEST, "bad_name"),
("%2Ehidden.md", b"x".to_vec(), StatusCode::BAD_REQUEST, "bad_name"),
("a%0Ab.md", b"x".to_vec(), StatusCode::BAD_REQUEST, "bad_name"),
+ ("invoice%E2%80%AEdm.txt", b"x".to_vec(), StatusCode::BAD_REQUEST, "bad_name"),
("", b"x".to_vec(), StatusCode::BAD_REQUEST, "bad_name"),
("photo.png", b"x".to_vec(), StatusCode::UNSUPPORTED_MEDIA_TYPE, "wrong_kind"),
("readme", b"x".to_vec(), StatusCode::UNSUPPORTED_MEDIA_TYPE, "wrong_kind"),
@@ -1311,5 +1329,35 @@ mod tests {
assert!(v["error"].as_str().is_some_and(|m| !m.is_empty()), "{uri}: {v}");
}
}
+
+ /// space-docs qa-2 item 3: a page that isn't a number was axum's plain-text "Failed to
+ /// deserialize query string"; it is JSON with a code now (roadmap 14d).
+ #[tokio::test]
+ async fn a_page_that_isnt_a_number_is_a_json_bad_request() {
+ let e = setup().await;
+ add(&e, "faq.md", b"words").await;
+ let req = Request::builder()
+ .uri(format!("{BASE}/page?file=faq.md&page=abc"))
+ .header("authorization", format!("Bearer {}", person(&e)))
+ .body(Body::empty())
+ .unwrap();
+ let resp = e.app.clone().oneshot(req).await.unwrap();
+ assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
+ assert_eq!(resp.headers()[header::CONTENT_TYPE], "application/json");
+ let v: Value = serde_json::from_slice(&to_bytes(resp.into_body(), usize::MAX).await.unwrap()).unwrap();
+ assert_eq!((v["code"].as_str(), v["error"].as_str()), (Some("bad_request"), Some("That request wasn't in the form kwant expected.")), "{v}");
+ assert!(v["detail"].as_str().unwrap().starts_with("Failed to deserialize query string"), "{v}");
+ }
+
+ /// space-docs qa-2 item 4: a name with a right-to-left override can pass for another file.
+ #[tokio::test]
+ async fn a_name_with_a_bidi_mark_is_refused_and_nothing_is_written() {
+ let e = setup().await;
+ for name in ["invoice%E2%80%AEdm.txt", "faq%E2%80%8E.md", "a%E2%81%A6b%E2%81%A9.md", "a%7Fb.md"] {
+ let (s, v) = add(&e, name, b"x").await;
+ assert_eq!((s, v["code"].as_str()), (StatusCode::BAD_REQUEST, Some("bad_name")), "{name}: {v}");
+ }
+ assert!(!docs(&e).exists() || std::fs::read_dir(docs(&e)).unwrap().next().is_none());
+ }
}
}
diff --git a/src/server/spaces.rs b/src/server/spaces.rs
index 8ee874a1..8a0c0af9 100644
--- a/src/server/spaces.rs
+++ b/src/server/spaces.rs
@@ -215,7 +215,7 @@ pub async fn ids_guard(state: &AppState, query: Option<&str>, rows: &[(RowKind,
}
fn archived() -> Response {
- error(StatusCode::CONFLICT, "this space is archived; restore it first")
+ (StatusCode::CONFLICT, Json(json!({ "error": "this space is archived; restore it first", "code": "archived" }))).into_response()
}
/// One space as the API shows it, with what the space switcher needs.
diff --git a/tests/browser_recovery_test.rs b/tests/browser_recovery_test.rs
index 57fe44c2..7a76c5ad 100644
--- a/tests/browser_recovery_test.rs
+++ b/tests/browser_recovery_test.rs
@@ -163,7 +163,8 @@ async fn a_browser_that_is_not_there_gets_the_docker_text_at_once() {
assert_eq!(status, 503);
let error = body["error"].as_str().unwrap();
assert_ne!(error, BROWSER_BUSY);
- assert!(body.get("code").is_none() && body.get("retryable").is_none(), "{body}");
+ // No route code: only the status's own (14d), and nothing says retry
+ assert!(body["code"] == "server_error" && body.get("retryable").is_none(), "{body}");
assert!(started.elapsed() < Duration::from_secs(5), "a refused connection isn't retried for 45 s");
app_task.abort();
diff --git a/tests/mcp_oauth_test.rs b/tests/mcp_oauth_test.rs
index a805af5c..ba5150b5 100644
--- a/tests/mcp_oauth_test.rs
+++ b/tests/mcp_oauth_test.rs
@@ -570,10 +570,10 @@ async fn no_way_to_register_is_a_clear_error() {
.unwrap()
.is_none());
- // Other failures carry no code (Retry may help)
+ // Other failures carry no dead-end code, only the status's own (14d): Retry may help
let e = env(oauth_mock::MockOptions { refuse_registration: true, ..Default::default() }).await;
let id = create_http_server(&e).await;
let (status, body) = call(&e.app, "POST", &format!("/api/mcp/servers/{id}/oauth/start"), Some(json!({"origin": ORIGIN}))).await;
assert_eq!(status, StatusCode::BAD_GATEWAY);
- assert!(body.get("code").is_none(), "{body}");
+ assert_eq!(body["code"], "server_error", "{body}");
}
diff --git a/tests/tool_notes_test.rs b/tests/tool_notes_test.rs
index 68130046..320a4d53 100644
--- a/tests/tool_notes_test.rs
+++ b/tests/tool_notes_test.rs
@@ -231,7 +231,7 @@ async fn patch(env: &Env, id: &str, body: Value) -> (StatusCode, Value) {
#[tokio::test]
async fn an_edit_into_an_open_duplicate_is_409_and_changes_nothing() {
let env = setup().await;
- let conflict = |existing: &str| json!({"error": "There's already an open note for this tool of that kind.", "existing_id": existing});
+ let conflict = |existing: &str| json!({"error": "There's already an open note for this tool of that kind.", "code": "conflict", "existing_id": existing});
// D2: a tip, fixed; the same tip again; reopening the first
let first = add(&env, "bash", "tip", "Quote paths").await;