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.

Passwords and approvals need the person's API token, even on loopback (F-2)

Lin (kwant bot)bb8c3f76ab39
diff --git a/src/server/auth.rs b/src/server/auth.rs
index 6b56100a..e0e7aa75 100644
--- a/src/server/auth.rs
+++ b/src/server/auth.rs
@@ -183,6 +183,20 @@ fn exempt(path: &str) -> bool {
|| path == "/api/mcp/self"
}
+/// Routes only the person may call: saved passwords, answering an approval card, and the
+/// approvals switch. They need the token from this machine too, because a bot's shell runs on
+/// this machine and would otherwise reach them with a bare `curl`. Turn tokens are refused by the
+/// handlers themselves (403).
+pub fn person_only(method: &Method, path: &str) -> bool {
+ let segs: Vec<&str> = path.trim_end_matches('/').split('/').collect();
+ match segs.as_slice() {
+ ["", "api", "sandbox", _, "passwords", ..] => true,
+ ["", "api", "approvals", _, "resolve"] => *method == Method::POST,
+ ["", "api", "spaces" | "kwants", _, "approvals"] => *method != Method::GET && *method != Method::HEAD,
+ _ => false,
+ }
+}
+
fn header_str(headers: &HeaderMap, name: impl header::AsHeaderName) -> Option<&str> {
headers.get(name).and_then(|v| v.to_str().ok())
}
@@ -239,6 +253,15 @@ fn deny(status: StatusCode, msg: &str) -> Response {
(status, Json(json!({ "error": msg }))).into_response()
}
+/// 401 for a person-only route without the token: `{error, person_only: true}`.
+fn person_token_required() -> Response {
+ (
+ StatusCode::UNAUTHORIZED,
+ Json(json!({ "error": "this needs the API token: sign in with `kwnt token`", "person_only": true })),
+ )
+ .into_response()
+}
+
/// Origin check, CORS for allowed origins, and the token check, for every `/api` request.
pub async fn guard(State(state): State<AppState>, req: Request, next: Next) -> Response {
let path = req.uri().path().to_string();
@@ -268,6 +291,15 @@ pub async fn guard(State(state): State<AppState>, req: Request, next: Next) -> R
&& !presented_token_ok(&api, &headers)
{
deny(StatusCode::UNAUTHORIZED, "API token required")
+ } else if api.require != Require::Never && person_only(req.method(), &path) {
+ // A bot's turn token (or any bearer that isn't the API token) is a 403; no token a 401
+ if let Err(refused) = super::mcp_suggest::refuse_agent_tokens(&state, &headers, "only the person can do this").await {
+ refused
+ } else if !presented_token_ok(&api, &headers) {
+ person_token_required()
+ } else {
+ next.run(req).await
+ }
} else {
next.run(req).await
};
@@ -297,7 +329,8 @@ pub async fn guard(State(state): State<AppState>, req: Request, next: Next) -> R
resp
}
-/// `GET /api/auth/status`: `{auth_required, authenticated}` for this request.
+/// `GET /api/auth/status`: `{auth_required, authenticated, person_auth_required,
+/// person_authenticated}` for this request.
pub async fn status(State(state): State<AppState>, req: Request) -> Response {
let peer = req
.extensions()
@@ -305,8 +338,17 @@ pub async fn status(State(state): State<AppState>, req: Request) -> Response {
.map(|c| c.0.ip());
let headers = req.headers();
let required = needs_token(&state.api_token, headers, peer);
- let authenticated = !required || presented_token_ok(&state.api_token, headers);
- Json(json!({ "auth_required": required, "authenticated": authenticated })).into_response()
+ let has_token = presented_token_ok(&state.api_token, headers);
+ let authenticated = !required || has_token;
+ // Person-only actions (passwords, approvals) need the token even where the rest doesn't
+ let person_required = state.api_token.require != Require::Never;
+ Json(json!({
+ "auth_required": required,
+ "authenticated": authenticated,
+ "person_auth_required": person_required,
+ "person_authenticated": !person_required || has_token,
+ }))
+ .into_response()
}
#[derive(Deserialize)]
@@ -433,6 +475,21 @@ mod tests {
assert!(!format!("{api:?}").contains("abcdef"));
}
+ #[test]
+ fn person_only_routes() {
+ let (get, post, put, del) = (Method::GET, Method::POST, Method::PUT, Method::DELETE);
+ assert!(person_only(&get, "/api/sandbox/t1/passwords"));
+ assert!(person_only(&post, "/api/sandbox/t1/passwords/c1/reveal"));
+ assert!(person_only(&del, "/api/sandbox/t1/passwords/c1"));
+ assert!(person_only(&post, "/api/approvals/a1/resolve"));
+ assert!(person_only(&put, "/api/spaces/s1/approvals"));
+ assert!(person_only(&put, "/api/kwants/k1/approvals"));
+ assert!(!person_only(&get, "/api/kwants/k1/approvals"));
+ assert!(!person_only(&get, "/api/approvals"));
+ assert!(!person_only(&get, "/api/sandbox/t1/status"));
+ assert!(!person_only(&get, "/api/kwants"));
+ }
+
#[test]
fn token_file_is_private_and_stable() {
let dir = tempfile::tempdir().unwrap();
diff --git a/tests/approvals_off_test.rs b/tests/approvals_off_test.rs
index b4e0f3f2..10b40ea0 100644
--- a/tests/approvals_off_test.rs
+++ b/tests/approvals_off_test.rs
@@ -76,7 +76,7 @@ async fn get(e: &Env, uri: &str) -> Value {
}
async fn put(e: &Env, uri: &str, approvals: &str) -> Value {
- let (s, v) = call(&e.app, "PUT", uri, None, Some(json!({"approvals": approvals}))).await;
+ let (s, v) = call(&e.app, "PUT", uri, Some(e.state.api_token.reveal()), Some(json!({"approvals": approvals}))).await;
assert_eq!(s, StatusCode::OK, "{uri}: {v}");
v
}
@@ -275,15 +275,15 @@ async fn only_the_person_changes_approvals() {
#[tokio::test]
async fn bad_values_unknown_rows_and_other_spaces() {
let e = setup().await;
- let (s, _) = call(&e.app, "PUT", "/api/spaces/spc_default/approvals", None, Some(json!({"approvals": "never"}))).await;
+ let (s, _) = call(&e.app, "PUT", "/api/spaces/spc_default/approvals", Some(e.state.api_token.reveal()), Some(json!({"approvals": "never"}))).await;
assert_eq!(s, StatusCode::BAD_REQUEST);
- let (s, _) = call(&e.app, "PUT", "/api/spaces/spc_default/approvals", None, Some(json!({"approvals": "inherit"}))).await;
+ let (s, _) = call(&e.app, "PUT", "/api/spaces/spc_default/approvals", Some(e.state.api_token.reveal()), Some(json!({"approvals": "inherit"}))).await;
assert_eq!(s, StatusCode::BAD_REQUEST, "a space has no inherit");
- let (s, _) = call(&e.app, "PUT", &format!("/api/kwants/{}/approvals", e.bot.id), None, Some(json!({"approvals": "maybe"}))).await;
+ let (s, _) = call(&e.app, "PUT", &format!("/api/kwants/{}/approvals", e.bot.id), Some(e.state.api_token.reveal()), Some(json!({"approvals": "maybe"}))).await;
assert_eq!(s, StatusCode::BAD_REQUEST);
- let (s, _) = call(&e.app, "PUT", "/api/kwants/nope/approvals", None, Some(json!({"approvals": "off"}))).await;
+ let (s, _) = call(&e.app, "PUT", "/api/kwants/nope/approvals", Some(e.state.api_token.reveal()), Some(json!({"approvals": "off"}))).await;
assert_eq!(s, StatusCode::NOT_FOUND);
- let (s, _) = call(&e.app, "PUT", "/api/spaces/nope/approvals", None, Some(json!({"approvals": "off"}))).await;
+ let (s, _) = call(&e.app, "PUT", "/api/spaces/nope/approvals", Some(e.state.api_token.reveal()), Some(json!({"approvals": "off"}))).await;
assert_eq!(s, StatusCode::NOT_FOUND);
// Another space has its own switch, and its bots follow it
@@ -316,7 +316,7 @@ async fn bad_values_unknown_rows_and_other_spaces() {
assert_eq!(get(&e, &format!("/api/kwants/{}/approvals", lab_bot.id)).await["approvals_effective"], "off");
assert_eq!(get(&e, &format!("/api/kwants/{}/approvals", e.bot.id)).await["approvals_effective"], "ask");
// A bot named with the wrong space is not found there
- let (s, _) = call(&e.app, "PUT", &format!("/api/kwants/{}/approvals?space=spc_default", lab_bot.id), None, Some(json!({"approvals": "ask"}))).await;
+ let (s, _) = call(&e.app, "PUT", &format!("/api/kwants/{}/approvals?space=spc_default", lab_bot.id), Some(e.state.api_token.reveal()), Some(json!({"approvals": "ask"}))).await;
assert_eq!(s, StatusCode::NOT_FOUND);
// The record list stays in its space
assert_eq!(ask_bash(&e, &lab_bot, "touch x").await, Some(true));
diff --git a/tests/builtin_tools_test.rs b/tests/builtin_tools_test.rs
index 102b51b4..dce1988d 100644
--- a/tests/builtin_tools_test.rs
+++ b/tests/builtin_tools_test.rs
@@ -45,6 +45,19 @@ async fn post(app: &Router, uri: &str, body: Value) -> (StatusCode, Value) {
(status, serde_json::from_slice(&bytes).unwrap_or(Value::Null))
}
+/// A request only the person may make (answering a card): it carries the API token.
+async fn person_post(app: &Router, state: &AppState, uri: &str, body: Value) -> (StatusCode, Value) {
+ let req = Request::builder()
+ .method("POST")
+ .uri(uri)
+ .header("content-type", "application/json")
+ .header("authorization", format!("Bearer {}", state.api_token.reveal()));
+ let resp = app.clone().oneshot(req.body(Body::from(body.to_string())).unwrap()).await.unwrap();
+ let status = resp.status();
+ let bytes = to_bytes(resp.into_body(), usize::MAX).await.unwrap();
+ (status, serde_json::from_slice(&bytes).unwrap_or(Value::Null))
+}
+
/// What claude's `--permission-prompt-tool` asks kwnt before running a tool.
async fn claude_asks(app: &Router, token: &str, tool_name: &str, input: Value) -> Value {
let call = json!({"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {
@@ -101,7 +114,7 @@ async fn built_in_tools_follow_the_folder_policy() {
assert_eq!(details["tool"], "Write");
assert_eq!(details["outside_folder"], true);
assert_eq!(details["cwd"], real.display().to_string());
- let (status, _) = post(&app, &format!("/api/approvals/{id}/resolve"), json!({"decision": "deny"})).await;
+ let (status, _) = person_post(&app, &state, &format!("/api/approvals/{id}/resolve"), json!({"decision": "deny"})).await;
assert_eq!(status, StatusCode::OK);
assert_eq!(ask.await.unwrap()["behavior"], "deny");
}
@@ -118,7 +131,7 @@ async fn built_in_tools_follow_the_folder_policy() {
assert_eq!(details["outside_folder"], false);
assert_eq!(details["cwd"], real.display().to_string());
assert_eq!(details["kwant_name"], bot.name);
- post(&app, &format!("/api/approvals/{id}/resolve"), json!({"decision": "allow_once"})).await;
+ person_post(&app, &state, &format!("/api/approvals/{id}/resolve"), json!({"decision": "allow_once"})).await;
assert_eq!(ask.await.unwrap(), json!({"behavior": "allow", "updatedInput": bash("ls")}));
// Always this session: the next command runs without a card
@@ -127,7 +140,7 @@ async fn built_in_tools_follow_the_folder_policy() {
async move { claude_asks(&app, &token, "Bash", input).await }
});
let (id, _) = next_card(&mut events).await;
- post(&app, &format!("/api/approvals/{id}/resolve"), json!({"decision": "always_allow"})).await;
+ person_post(&app, &state, &format!("/api/approvals/{id}/resolve"), json!({"decision": "always_allow"})).await;
assert_eq!(ask.await.unwrap()["behavior"], "allow");
assert_eq!(claude_asks(&app, &token, "Bash", bash("ls -la")).await["behavior"], "allow");
assert!(state.broker.pending_ids().await.is_empty(), "always-this-session skips the card");
@@ -139,7 +152,7 @@ async fn built_in_tools_follow_the_folder_policy() {
});
let (id, details) = next_card(&mut events).await;
assert_eq!(details["tool"], "SomeNewTool");
- post(&app, &format!("/api/approvals/{id}/resolve"), json!({"decision": "deny"})).await;
+ person_post(&app, &state, &format!("/api/approvals/{id}/resolve"), json!({"decision": "deny"})).await;
assert_eq!(ask.await.unwrap()["behavior"], "deny");
for tool in ["mcp__other__echo", "mcp__kwnt__approve", ""] {
assert_eq!(claude_asks(&app, &token, tool, json!({})).await["behavior"], "deny", "{tool}");
@@ -196,7 +209,7 @@ async fn always_this_session_lasts_for_one_conversation() {
async move { claude_asks(&app, &token, "Bash", json!({"command": "touch x", "description": "Run it"})).await }
});
let (id, _) = next_card(&mut events).await;
- post(&app, &format!("/api/approvals/{id}/resolve"), json!({"decision": "always_allow"})).await;
+ person_post(&app, &state, &format!("/api/approvals/{id}/resolve"), json!({"decision": "always_allow"})).await;
assert_eq!(ask.await.unwrap()["behavior"], "allow");
mcp_runtime::finish_turn(&state, &a1).await;
state.turns.end_turn("turn-a1");
@@ -212,7 +225,7 @@ async fn always_this_session_lasts_for_one_conversation() {
});
let (id, details) = next_card(&mut events).await;
assert_eq!(details["tool"], "Write");
- post(&app, &format!("/api/approvals/{id}/resolve"), json!({"decision": "deny"})).await;
+ person_post(&app, &state, &format!("/api/approvals/{id}/resolve"), json!({"decision": "deny"})).await;
assert_eq!(ask.await.unwrap()["behavior"], "deny");
// Chat B with the same bot: asks again
@@ -223,7 +236,7 @@ async fn always_this_session_lasts_for_one_conversation() {
});
let (id, details) = next_card(&mut events).await;
assert_eq!(details["arguments"]["command"], "touch z");
- post(&app, &format!("/api/approvals/{id}/resolve"), json!({"decision": "deny"})).await;
+ person_post(&app, &state, &format!("/api/approvals/{id}/resolve"), json!({"decision": "deny"})).await;
assert_eq!(ask.await.unwrap()["behavior"], "deny");
// A turn kwnt isn't tracking is its own conversation
@@ -234,7 +247,7 @@ async fn always_this_session_lasts_for_one_conversation() {
async move { claude_asks(&app, &token, "Bash", json!({"command": "touch w", "description": "Run it"})).await }
});
let (id, _) = next_card(&mut events).await;
- post(&app, &format!("/api/approvals/{id}/resolve"), json!({"decision": "deny"})).await;
+ person_post(&app, &state, &format!("/api/approvals/{id}/resolve"), json!({"decision": "deny"})).await;
assert_eq!(ask.await.unwrap()["behavior"], "deny");
// A restart (a fresh broker) forgets every answer
diff --git a/tests/computer_mode_test.rs b/tests/computer_mode_test.rs
index aab158ca..82c65ee8 100644
--- a/tests/computer_mode_test.rs
+++ b/tests/computer_mode_test.rs
@@ -68,11 +68,12 @@ async fn next_approval(rx: &mut tokio::sync::broadcast::Receiver<RuntimeEvent>)
}
}
-async fn resolve(app: &axum::Router, id: &str, decision: &str) {
+async fn resolve(app: &axum::Router, token: &str, id: &str, decision: &str) {
let req = Request::builder()
.method("POST")
.uri(format!("/api/approvals/{id}/resolve"))
.header("content-type", "application/json")
+ .header("authorization", format!("Bearer {token}"))
.body(Body::from(json!({ "decision": decision }).to_string()))
.unwrap();
assert_eq!(
@@ -206,20 +207,20 @@ async fn computer_mode_api_and_local_shell_approval() {
let (id, details) = next_approval(&mut rx).await;
assert_eq!(details["source"], "local_shell");
assert_eq!(details["arguments"]["command"], "touch ran.txt");
- resolve(&app, &id, "deny").await;
+ resolve(&app, state.api_token.reveal(), &id, "deny").await;
assert!(denied.await.unwrap().is_err());
assert!(!marker.exists(), "a denied command must not run");
// "always allow" runs this command only; the next one asks again
let allowed = run("touch ran.txt && echo local-ok");
let (id, _) = next_approval(&mut rx).await;
- resolve(&app, &id, "always_allow").await;
+ resolve(&app, state.api_token.reveal(), &id, "always_allow").await;
let out = allowed.await.unwrap().unwrap();
assert!(out["stdout"].as_str().unwrap().contains("local-ok"));
assert!(marker.exists());
let again = run("echo again");
let (id, _) = next_approval(&mut rx).await;
- resolve(&app, &id, "allow_once").await;
+ resolve(&app, state.api_token.reveal(), &id, "allow_once").await;
assert!(again.await.unwrap().is_ok());
// switching back to vm takes effect without a restart
diff --git a/tests/mcp_gateway_test.rs b/tests/mcp_gateway_test.rs
index 9c69b535..d449ab44 100644
--- a/tests/mcp_gateway_test.rs
+++ b/tests/mcp_gateway_test.rs
@@ -290,6 +290,7 @@ async fn ending_the_turn_cancels_a_call_waiting_for_its_card() {
assert_eq!(withdrawn, ticket);
let late = reqwest::Client::new()
.post(format!("{base}/api/approvals/{ticket}/resolve"))
+ .bearer_auth(state.api_token.reveal())
.json(&json!({"decision": "allow_once"}))
.send()
.await
diff --git a/tests/profiles_api_test.rs b/tests/profiles_api_test.rs
index 7fd5a10b..5d43562b 100644
--- a/tests/profiles_api_test.rs
+++ b/tests/profiles_api_test.rs
@@ -485,7 +485,7 @@ async fn remote_requests_need_the_token() {
assert_eq!(s, StatusCode::OK);
assert_eq!(
serde_json::from_str::<Value>(&body).unwrap(),
- json!({"auth_required": true, "authenticated": false})
+ json!({"auth_required": true, "authenticated": false, "person_auth_required": true, "person_authenticated": false})
);
let bearer = format!("Bearer {TOKEN}");
@@ -585,6 +585,6 @@ async fn remote_requests_need_the_token() {
.await;
assert_eq!(
serde_json::from_str::<Value>(&body).unwrap(),
- json!({"auth_required": false, "authenticated": true})
+ json!({"auth_required": false, "authenticated": true, "person_auth_required": true, "person_authenticated": false})
);
}