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.
Rust ai-agentsai-assistantai-botautomationbotbots-teamchatbotclaude-duetgrokgrok-botgrok-bot-alternativeharnessllmmulti-agentopenai-dotsopenbotpersonal-agentrustself-hostedselfhosted-ai
Person-only deletes: bots, teams and undo of bot actions and imports (audit F-13)
Lin (kwant bot)41a31ef9ff17
diff --git a/docs/bot-actions.md b/docs/bot-actions.mdindex 416d0b08..1ae0bc67 100644--- a/docs/bot-actions.md+++ b/docs/bot-actions.md@@ -120,6 +120,7 @@ Suggested buttons:- 409 if it isn't applied, if a newer applied change to the same target exists ("undo the newer change first: …"), or if it can't be put back safely (for example, a bot that already has history, or a channel with messages).- `POST /api/bot-actions/:id/confirm` and `POST /api/bot-actions/:id/decline`: only for pending actions; 409 otherwise.- All three return **403** for a turn token (self tools or MCP session) or any non-API bearer.+- Undo also needs the API token from this machine (401 `{person_only:true}` without it), because undoing a bot or channel deletes its saved passwords. The same holds for `POST /api/imports/:id/undo`, `DELETE /api/kwants/:id` and `DELETE /api/teams/:id`.- After a change, the card's meta is updated and SSE sends `bot_action_updated { action }`. That event is routed to the space and the chat context (channel, direct chat or thread).## Hiringdiff --git a/docs/saved-passwords.md b/docs/saved-passwords.mdindex a885b705..64f902f1 100644--- a/docs/saved-passwords.md+++ b/docs/saved-passwords.md@@ -37,7 +37,7 @@ With Bitwarden, the API token alone doesn't show a password: that needs the mast- the UI shows "Locked" until the person unlocks it again.- Only items in the `kwnt` folder, named `kwnt · <host>` and carrying the custom field `kwnt-owner`, are used. Organisation items, trashed items and items in other folders are never read.- Showing a password needs the master password, not only the API token. The token sits in kwnt's data folder, where a bot with approvals off can read it. Five wrong master passwords in a row lock the vault.-- Every vault route is person-only. A bot's turn token gets 403; no token gets 401.+- Every vault route is person-only. A bot's turn token gets 403; no token gets 401. Deleting a bot or team and undoing a bot action or import are person-only too, since they delete saved passwords.**Known gap (open, accepted 2026-10-20):** autofill stays on while approvals are off; Oleks decided this. Chrome's DevTools port listens on loopback without authentication, so with approvals off a bot with a shell can attach to it and read a field kwnt has just filled. This holds for both the built-in store and Bitwarden, because the leak is in the browser, not the store. Planned fix, on its own branch: start Chrome with `--remote-debugging-pipe` so there is no port to attach to.diff --git a/src/server/auth.rs b/src/server/auth.rsindex f0bb5358..a148fa27 100644--- a/src/server/auth.rs+++ b/src/server/auth.rs@@ -183,8 +183,8 @@ fn exempt(path: &str) -> bool {|| path == "/api/mcp/self"}-/// Routes only the person may call: saved passwords and the password vault (Bitwarden), answering an approval card, and the-/// approvals switch. They need the token from this machine too, because a bot's shell runs on+/// Routes only the person may call: saved passwords and the password vault (Bitwarden), answering an approval card, the+/// approvals switch, and deleting a bot or team or undoing a bot action or import (those delete saved passwords too). 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 {@@ -194,6 +194,8 @@ pub fn person_only(method: &Method, path: &str) -> bool {["", "api", "passwords", ..] => true,["", "api", "approvals", _, "resolve"] => *method == Method::POST,["", "api", "spaces" | "kwants", _, "approvals"] => *method != Method::GET && *method != Method::HEAD,+ ["", "api", "kwants" | "teams", _] => *method == Method::DELETE,+ ["", "api", "bot-actions" | "imports", _, "undo"] => *method == Method::POST,_ => false,}}@@ -493,6 +495,13 @@ mod tests {assert!(!person_only(&get, "/api/approvals"));assert!(!person_only(&get, "/api/sandbox/t1/status"));assert!(!person_only(&get, "/api/kwants"));+ assert!(person_only(&del, "/api/kwants/k1"));+ assert!(person_only(&del, "/api/teams/t1/"));+ assert!(person_only(&post, "/api/bot-actions/b1/undo"));+ assert!(person_only(&post, "/api/imports/i1/undo"));+ assert!(!person_only(&put, "/api/kwants/k1"));+ assert!(!person_only(&get, "/api/teams/t1"));+ assert!(!person_only(&post, "/api/bot-actions/b1/confirm"));}#[test]diff --git a/tests/bot_actions_test.rs b/tests/bot_actions_test.rsindex 2268fbbb..679a8dfe 100644--- a/tests/bot_actions_test.rs+++ b/tests/bot_actions_test.rs@@ -206,7 +206,7 @@ async fn routine_is_created_in_this_chat_as_this_bot_with_a_card_and_managed_throk(&e, &token, "routine_delete", json!({"routine": routine_id})).await;assert!(routines(&e).await.is_empty());let del = last_action(&e).await;- let (status, v) = call(&e.app, "POST", &format!("/api/bot-actions/{}/undo", del["id"].as_str().unwrap()), None, None).await;+ let (status, v) = call(&e.app, "POST", &format!("/api/bot-actions/{}/undo", del["id"].as_str().unwrap()), Some(e.state.api_token.reveal()), None).await;assert_eq!(status, StatusCode::OK, "{v}");assert_eq!(v["status"], "undone");assert_eq!(v["card"]["status"], "undone");@@ -220,7 +220,7 @@ async fn routine_is_created_in_this_chat_as_this_bot_with_a_card_and_managed_thr// Undoing the create removes itlet create = actions(&e).await.into_iter().find(|a| a["action"] == "routine_create").unwrap();- let (status, v) = call(&e.app, "POST", &format!("/api/bot-actions/{}/undo", create["id"].as_str().unwrap()), None, None).await;+ let (status, v) = call(&e.app, "POST", &format!("/api/bot-actions/{}/undo", create["id"].as_str().unwrap()), Some(e.state.api_token.reveal()), None).await;// The routine it made was deleted and recreated, so that row is gone: a conflict, not a crashassert_eq!(status, StatusCode::CONFLICT, "{v}");}@@ -297,7 +297,7 @@ async fn bots_are_created_and_updated_and_the_person_undoes_it() {let update = last_action(&e).await;// Undoing the create while a newer change is applied: 409, undo that first- let (status, v) = call(&e.app, "POST", &format!("/api/bot-actions/{}/undo", create["id"].as_str().unwrap()), None, None).await;+ let (status, v) = call(&e.app, "POST", &format!("/api/bot-actions/{}/undo", create["id"].as_str().unwrap()), Some(e.state.api_token.reveal()), None).await;assert_eq!(status, StatusCode::CONFLICT, "{v}");assert!(v["error"].as_str().unwrap().contains("newer"), "{v}");@@ -306,7 +306,7 @@ async fn bots_are_created_and_updated_and_the_person_undoes_it() {let (status, _) = call(&e.app, "POST", &format!("/api/bot-actions/{}/undo", update["id"].as_str().unwrap()), Some(bearer), None).await;assert_eq!(status, StatusCode::FORBIDDEN);}- let (status, v) = call(&e.app, "POST", &format!("/api/bot-actions/{}/undo", update["id"].as_str().unwrap()), None, None).await;+ let (status, v) = call(&e.app, "POST", &format!("/api/bot-actions/{}/undo", update["id"].as_str().unwrap()), Some(e.state.api_token.reveal()), None).await;assert_eq!(status, StatusCode::OK, "{v}");let chef_back = e.state.db.get_kwant(&chef.id).await.unwrap().unwrap();assert_eq!(chef_back.title, "Recipe helper");@@ -314,11 +314,11 @@ async fn bots_are_created_and_updated_and_the_person_undoes_it() {let (status, _) = call(&e.app, "POST", &format!("/api/bot-actions/{}/undo", create["id"].as_str().unwrap()), Some(&token), None).await;assert_eq!(status, StatusCode::FORBIDDEN);- let (status, v) = call(&e.app, "POST", &format!("/api/bot-actions/{}/undo", create["id"].as_str().unwrap()), None, None).await;+ let (status, v) = call(&e.app, "POST", &format!("/api/bot-actions/{}/undo", create["id"].as_str().unwrap()), Some(e.state.api_token.reveal()), None).await;assert_eq!(status, StatusCode::OK, "{v}");assert!(e.state.db.get_kwant(&chef.id).await.unwrap().is_none(), "undo removed Chef");// Twice is a conflict- let (status, _) = call(&e.app, "POST", &format!("/api/bot-actions/{}/undo", create["id"].as_str().unwrap()), None, None).await;+ let (status, _) = call(&e.app, "POST", &format!("/api/bot-actions/{}/undo", create["id"].as_str().unwrap()), Some(e.state.api_token.reveal()), None).await;assert_eq!(status, StatusCode::CONFLICT);}@@ -372,7 +372,7 @@ async fn non_secret_settings_change_and_undo() {assert!(text.contains("max_turns_global"), "{text}");let a = last_action(&e).await;- let (status, v) = call(&e.app, "POST", &format!("/api/bot-actions/{}/undo", a["id"].as_str().unwrap()), None, None).await;+ let (status, v) = call(&e.app, "POST", &format!("/api/bot-actions/{}/undo", a["id"].as_str().unwrap()), Some(e.state.api_token.reveal()), None).await;assert_eq!(status, StatusCode::OK, "{v}");let (_, s) = call(&e.app, "GET", "/api/settings", None, None).await;assert_eq!(s["timezone"], "", "undo clears the time zone it set");@@ -461,7 +461,7 @@ async fn other_spaces_are_out_of_reach() {// A new space can be created, but undo archives it againok(&e, &token, "space_create", json!({"name": "Side project"})).await;let a = last_action(&e).await;- let (status, _) = call(&e.app, "POST", &format!("/api/bot-actions/{}/undo", a["id"].as_str().unwrap()), None, None).await;+ let (status, _) = call(&e.app, "POST", &format!("/api/bot-actions/{}/undo", a["id"].as_str().unwrap()), Some(e.state.api_token.reveal()), None).await;assert_eq!(status, StatusCode::OK);let made = e.state.db.get_space(&SpaceId::new(a["target_id"].as_str().unwrap())).await.unwrap().unwrap();assert!(made.archived_at.is_some());@@ -504,7 +504,7 @@ async fn card_text_follows_the_decision_and_monthly_schedules_read_naturally() {assert_eq!(meta(&card)["details"]["schedule_text"], "monthly on the 1st and last day at 09:00 Europe/Kyiv");// After Undo the message itself says so, not only its meta (history, notifications, bots)- let (status, v) = call(&e.app, "POST", &format!("/api/bot-actions/{}/undo", create["id"].as_str().unwrap()), None, None).await;+ let (status, v) = call(&e.app, "POST", &format!("/api/bot-actions/{}/undo", create["id"].as_str().unwrap()), Some(e.state.api_token.reveal()), None).await;assert_eq!(status, StatusCode::OK, "{v}");let card = find(messages(&e, &e.general.id).await, card_of(&create));assert!(card.text.starts_with("Undone: Created routine 'Budget review'"), "{}", card.text);diff --git a/tests/hires_test.rs b/tests/hires_test.rsindex 9f4ddf8b..c3f095c8 100644--- a/tests/hires_test.rs+++ b/tests/hires_test.rs@@ -280,7 +280,7 @@ async fn only_the_person_decides_and_accept_once_creates_the_bot_in_the_team() {// Undo through the bot action removes the hired bot and the card says solet action = card["action_id"].as_str().unwrap();- let (status, v) = call(&e.app, "POST", &format!("/api/bot-actions/{action}/undo"), None, None).await;+ let (status, v) = call(&e.app, "POST", &format!("/api/bot-actions/{action}/undo"), Some(e.state.api_token.reveal()), None).await;assert_eq!(status, StatusCode::OK, "{v}");assert!(bot_named(&e, "spc_default", "Chef").await.is_none());let team = e.state.db.get_team_by_name(&SpaceId::default_space(), "core-engineering").await.unwrap().unwrap();@@ -332,7 +332,7 @@ async fn always_accept_hires_at_once_with_undo_up_to_the_daily_cap() {// Undo an automatic hirelet auto = hires(&e, "spc_default").await.into_iter().find(|h| h["name"] == "Coach").unwrap();let action = auto["action_id"].as_str().unwrap();- let (status, v) = call(&e.app, "POST", &format!("/api/bot-actions/{action}/undo"), None, None).await;+ let (status, v) = call(&e.app, "POST", &format!("/api/bot-actions/{action}/undo"), Some(e.state.api_token.reveal()), None).await;assert_eq!(status, StatusCode::OK, "{v}");assert!(bot_named(&e, "spc_default", "Coach").await.is_none());@@ -506,7 +506,7 @@ async fn a_team_is_one_proposal_on_one_card() {// Undo removes the whole team: bots, team and channellet action = card["action_id"].as_str().unwrap();- let (status, v) = call(&e.app, "POST", &format!("/api/bot-actions/{action}/undo"), None, None).await;+ let (status, v) = call(&e.app, "POST", &format!("/api/bot-actions/{action}/undo"), Some(e.state.api_token.reveal()), None).await;assert_eq!(status, StatusCode::OK, "{v}");for n in ["Quant", "Gopher", "Tester"] {assert!(bot_named(&e, "spc_default", n).await.is_none(), "{n} removed");diff --git a/tests/import_test.rs b/tests/import_test.rsindex c1f9e33b..fca7909f 100644--- a/tests/import_test.rs+++ b/tests/import_test.rs@@ -59,6 +59,21 @@ async fn send(app: &Router, method: &str, uri: &str, content_type: &str, body: V(status, serde_json::from_slice(&bytes).unwrap_or(Value::Null))}+/// Undoing an import is person-only: it carries the API token.+async fn undo_call(e: &Env, uri: &str, body: Value) -> (StatusCode, Value) {+ let req = Request::builder()+ .method("POST")+ .uri(uri)+ .header("content-type", "application/json")+ .header("authorization", format!("Bearer {}", e.state.api_token.reveal()))+ .body(Body::from(body.to_string()))+ .unwrap();+ let resp = e.app.clone().oneshot(req).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))+}+async fn json_call(app: &Router, method: &str, uri: &str, body: Value) -> (StatusCode, Value) {send(app, method, uri, "application/json", body.to_string().into_bytes()).await}@@ -191,7 +206,7 @@ async fn apply_creates_bots_without_tools_pending_skills_and_paused_routines_theassert_eq!(status, StatusCode::OK);assert_eq!(list[0]["id"], import_id.as_str());- let (status, undone) = json_call(&e.app, "POST", &format!("/api/imports/{import_id}/undo"), Value::Null).await;+ let (status, undone) = undo_call(&e, &format!("/api/imports/{import_id}/undo"), Value::Null).await;assert_eq!(status, StatusCode::OK, "{undone}");assert_eq!(undone["status"], "undone");let mut after = row_counts(&e.tmp).await;@@ -200,7 +215,7 @@ async fn apply_creates_bots_without_tools_pending_skills_and_paused_routines_theexpected.retain(|(t, _)| t != "imports");assert_eq!(after, expected, "undo removes everything the import created");- let (status, again) = json_call(&e.app, "POST", &format!("/api/imports/{import_id}/undo"), json!({})).await;+ let (status, again) = undo_call(&e, &format!("/api/imports/{import_id}/undo"), json!({})).await;assert_eq!((status, again["code"].as_str()), (StatusCode::CONFLICT, Some("already_undone")));}@@ -249,9 +264,9 @@ async fn package_with_team_lands_in_a_new_space_and_undo_removes_team_channels_a// Undo needs the right space.let id = applied["import"]["id"].as_str().unwrap();- let (status, _) = json_call(&e.app, "POST", &format!("/api/imports/{id}/undo"), Value::Null).await;+ let (status, _) = undo_call(&e, &format!("/api/imports/{id}/undo"), Value::Null).await;assert_eq!(status, StatusCode::NOT_FOUND, "an import in another space isn't visible from Default");- let (status, v) = json_call(&e.app, "POST", &format!("/api/imports/{id}/undo?space={space}"), Value::Null).await;+ let (status, v) = undo_call(&e, &format!("/api/imports/{id}/undo?space={space}"), Value::Null).await;assert_eq!(status, StatusCode::OK, "{v}");assert!(e.state.db.list_kwants(&sid).await.unwrap().is_empty());assert!(e.state.db.list_teams(&sid).await.unwrap().is_empty());@@ -287,7 +302,7 @@ async fn undo_is_refused_once_a_bot_is_used_and_needs_force_once_edited() {).await;assert_eq!(status, StatusCode::OK, "{v}");- let (status, v) = json_call(&e.app, "POST", &format!("/api/imports/{id}/undo"), Value::Null).await;+ let (status, v) = undo_call(&e, &format!("/api/imports/{id}/undo"), Value::Null).await;assert_eq!((status, v["code"].as_str()), (StatusCode::CONFLICT, Some("edited")), "{v}");assert_eq!(v["edited"][0], "Helper");@@ -306,7 +321,7 @@ async fn undo_is_refused_once_a_bot_is_used_and_needs_force_once_edited() {}).await.unwrap();- let (status, v) = json_call(&e.app, "POST", &format!("/api/imports/{id}/undo"), json!({ "force": true })).await;+ let (status, v) = undo_call(&e, &format!("/api/imports/{id}/undo"), json!({ "force": true })).await;assert_eq!((status, v["code"].as_str()), (StatusCode::CONFLICT, Some("in_use")), "{v}");assert!(e.state.db.get_kwant(&bot_id).await.unwrap().is_some());}@@ -326,7 +341,7 @@ async fn forced_undo_removes_an_edited_bot() {).await;assert_eq!(status, StatusCode::OK);- let (status, v) = json_call(&e.app, "POST", &format!("/api/imports/{id}/undo"), json!({ "force": true })).await;+ let (status, v) = undo_call(&e, &format!("/api/imports/{id}/undo"), json!({ "force": true })).await;assert_eq!(status, StatusCode::OK, "{v}");assert!(e.state.db.get_kwant(&bot_id).await.unwrap().is_none());}diff --git a/tests/initiative_test.rs b/tests/initiative_test.rsindex 9fbac4d2..0828dddf 100644--- a/tests/initiative_test.rs+++ b/tests/initiative_test.rs@@ -231,7 +231,7 @@ async fn a_follow_up_comes_back_to_the_same_chat_as_the_same_bot_and_can_be_undolet a = last_action(&e).await;assert_eq!((a["action"].as_str(), a["status"].as_str()), (Some("routine_create"), Some("applied")));assert!(a["summary"].as_str().unwrap().contains("follow-up"), "{a}");- let (status, v) = call(&e.app, "POST", &format!("/api/bot-actions/{}/undo", a["id"].as_str().unwrap()), None, None).await;+ let (status, v) = call(&e.app, "POST", &format!("/api/bot-actions/{}/undo", a["id"].as_str().unwrap()), Some(e.state.api_token.reveal()), None).await;assert_eq!(status, StatusCode::OK, "{v}");assert!(routines(&e).await.is_empty());diff --git a/tests/kwant_delete_test.rs b/tests/kwant_delete_test.rsindex 9dd00cd2..e1f200e5 100644--- a/tests/kwant_delete_test.rs+++ b/tests/kwant_delete_test.rs@@ -34,7 +34,15 @@ async fn setup() -> (Router, AppState, TempDir) {}async fn call(app: &Router, method: &str, uri: &str, body: Option<Value>) -> (StatusCode, Value) {- let req = Request::builder().method(method).uri(uri).header("content-type", "application/json");+ call_as(app, method, uri, None, body).await+}++/// With the person's API token (deleting a bot is person-only).+async fn call_as(app: &Router, method: &str, uri: &str, token: Option<&str>, body: Option<Value>) -> (StatusCode, Value) {+ let mut req = Request::builder().method(method).uri(uri).header("content-type", "application/json");+ if let Some(t) = token {+ req = req.header("authorization", format!("Bearer {t}"));+ }let body = body.map(|b| Body::from(b.to_string())).unwrap_or_else(Body::empty);let resp = app.clone().oneshot(req.body(body).unwrap()).await.unwrap();let status = resp.status();@@ -95,7 +103,7 @@ async fn the_person_deletes_any_bot_with_its_history() {state: "running".into(),since: chrono::Utc::now(),});- let (s, v) = call(&app, "DELETE", &format!("/api/kwants/{}", bot.id), None).await;+ let (s, v) = call_as(&app, "DELETE", &format!("/api/kwants/{}", bot.id), Some(state.api_token.reveal()), None).await;assert_eq!(s, StatusCode::CONFLICT);assert_eq!(v["error"], "running");assert!(v["message"].as_str().unwrap().contains("working"));@@ -114,7 +122,7 @@ async fn the_person_deletes_any_bot_with_its_history() {assert!(s == StatusCode::FORBIDDEN || s == StatusCode::UNAUTHORIZED, "{s}");// Deleted, with everything it owned- let (s, v) = call(&app, "DELETE", &format!("/api/kwants/{}", bot.id), None).await;+ let (s, v) = call_as(&app, "DELETE", &format!("/api/kwants/{}", bot.id), Some(state.api_token.reveal()), None).await;assert_eq!(s, StatusCode::OK, "{v}");assert_eq!(v["deleted"], json!(bot.id));assert_eq!(v["status"], json!("deleted"));@@ -135,16 +143,16 @@ async fn the_person_deletes_any_bot_with_its_history() {assert_ne!(t.lead_kwant_id, bot.id);assert!(!t.member_kwants.contains(&bot.id));}- let (s, _) = call(&app, "DELETE", &format!("/api/kwants/{}", bot.id), None).await;+ let (s, _) = call_as(&app, "DELETE", &format!("/api/kwants/{}", bot.id), Some(state.api_token.reveal()), None).await;assert_eq!(s, StatusCode::NOT_FOUND);// A space's only bot stayslet rest = state.db.list_kwants(&space).await.unwrap();for k in &rest[1..] {- let (s, v) = call(&app, "DELETE", &format!("/api/kwants/{}", k.id), None).await;+ let (s, v) = call_as(&app, "DELETE", &format!("/api/kwants/{}", k.id), Some(state.api_token.reveal()), None).await;assert_eq!(s, StatusCode::OK, "{v}");}- let (s, v) = call(&app, "DELETE", &format!("/api/kwants/{}", rest[0].id), None).await;+ let (s, v) = call_as(&app, "DELETE", &format!("/api/kwants/{}", rest[0].id), Some(state.api_token.reveal()), None).await;assert_eq!(s, StatusCode::CONFLICT);assert_eq!(v["error"], "last_bot");}diff --git a/tests/person_only_deletes_test.rs b/tests/person_only_deletes_test.rsnew file mode 100644index 00000000..d4a2fdd1--- /dev/null+++ b/tests/person_only_deletes_test.rs@@ -0,0 +1,151 @@+//! Deleting a bot or team, and undoing a bot action or an import, are person-only (audit+//! 2026-10-20, F-13). Since F-11 they delete saved passwords too, so a bare `curl` from a bot's+//! shell could wipe another bot's logins: no token is a 401 `{person_only:true}`, a bot's turn+//! token or a wrong token a 403, and nothing is deleted. The person's token goes through.++use axum::{+ body::{to_bytes, Body},+ http::{Request, StatusCode},+ Router,+};+use kwnt::{+ broker::PermissionBroker,+ config::Config,+ db::{models::NewTeam, spaces::SpaceId, Database},+ router::LayaRouter,+ sandbox::credentials::VAULT_DIR,+ server::{continuity::SelfScope, create_router, mcp_runtime, AppState},+ tools::ToolRunner,+};+use serde_json::{json, Value};+use std::path::{Path, PathBuf};+use tempfile::{tempdir, TempDir};+use tower::ServiceExt;++struct Env {+ app: Router,+ state: AppState,+ vault: PathBuf,+ _tmp: TempDir,+}++async fn setup() -> Env {+ let tmp = tempdir().unwrap();+ let data = tmp.path().join("data");+ let db = Database::init(&data).await.unwrap();+ let config = Config { data_dir: data.clone(), browser_cdp_url: Some("http://127.0.0.1:9".into()), ..Config::default() };+ let state = AppState::new(+ config.clone(),+ db,+ ToolRunner::new(data.join("workspace")),+ PermissionBroker::new(),+ LayaRouter::new(config.laya_url.clone()),+ );+ Env { app: create_router(state.clone()), state, vault: data.join(VAULT_DIR), _tmp: tmp }+}++/// A request from this machine (no remote peer), with an optional bearer.+async fn call(app: &Router, method: &str, uri: &str, bearer: Option<&str>) -> (StatusCode, Value) {+ let mut req = Request::builder().method(method).uri(uri).header("content-type", "application/json");+ if let Some(t) = bearer {+ req = req.header("authorization", format!("Bearer {t}"));+ }+ let resp = app.clone().oneshot(req.body(Body::empty()).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))+}++impl Env {+ fn token(&self) -> &str {+ self.state.api_token.reveal()+ }+ async fn bots(&self) -> Vec<kwnt::db::models::Kwant> {+ self.state.db.list_kwants(&SpaceId::default_space()).await.unwrap()+ }+ async fn save_for(&self, owner: &str) {+ let req = Request::builder()+ .method("POST")+ .uri(format!("/api/sandbox/{owner}/passwords"))+ .header("content-type", "application/json")+ .header("authorization", format!("Bearer {}", self.token()));+ let body = json!({"origin": "https://keep.test", "username": "ku", "password": "DUMMY-PW-KEEP"});+ let resp = self.app.clone().oneshot(req.body(Body::from(body.to_string())).unwrap()).await.unwrap();+ assert_eq!(resp.status(), StatusCode::OK);+ }+ fn file(&self, owner: &str) -> PathBuf {+ self.vault.join(format!("{owner}.bin"))+ }+ /// A live turn of `bot`; returns its turn token.+ async fn turn_token(&self, bot: &kwnt::db::models::Kwant, folder: &Path) -> String {+ let scope = SelfScope { kwant_id: bot.id.clone(), kwant_name: bot.name.clone(), ..Default::default() };+ let (_, token) = mcp_runtime::prepare_turn_with_self(&self.state, bot, None, Some(folder.to_path_buf()), Some(scope))+ .await+ .unwrap();+ token+ }+}++#[tokio::test]+async fn deletes_and_undos_refuse_no_token_and_bot_tokens() {+ let e = setup().await;+ let bots = e.bots().await;+ let (attacker, victim) = (&bots[0], &bots[1]);+ let team = NewTeam {+ name: "t".into(),+ description: None,+ icon: None,+ lead_kwant_id: victim.id.clone(),+ member_kwants: vec![victim.id.clone()],+ workspace_path: None,+ repo_url: None,+ };+ let team = e.state.db.create_team(&SpaceId::default_space(), &team).await.unwrap().id;+ e.save_for(&victim.id).await;+ e.save_for(&team).await;++ let folder = tempdir().unwrap();+ let turn = e.turn_token(attacker, folder.path()).await;+ let routes = [+ ("DELETE", format!("/api/kwants/{}", victim.id)),+ ("DELETE", format!("/api/teams/{team}")),+ ("POST", "/api/bot-actions/some-action/undo".to_string()),+ ("POST", "/api/imports/some-import/undo".to_string()),+ ];+ for (method, uri) in &routes {+ let (s, v) = call(&e.app, method, uri, None).await;+ assert_eq!(s, StatusCode::UNAUTHORIZED, "{method} {uri} without a token: {v}");+ assert_eq!(v["person_only"], true, "{v}");+ let (s, v) = call(&e.app, method, uri, Some(&turn)).await;+ assert_eq!(s, StatusCode::FORBIDDEN, "{method} {uri} with a bot's turn token: {v}");+ let (s, _) = call(&e.app, method, uri, Some("not-the-token")).await;+ assert_eq!(s, StatusCode::FORBIDDEN, "{method} {uri} with a wrong token");+ }+ // Nothing was deleted+ assert!(e.bots().await.iter().any(|b| b.id == victim.id));+ assert!(e.state.db.get_team(&team).await.unwrap().is_some());+ assert!(e.file(&victim.id).exists() && e.file(&team).exists());++ // The person's token goes through to the handlers+ let (s, v) = call(&e.app, "DELETE", &format!("/api/teams/{team}"), Some(e.token())).await;+ assert_eq!(s, StatusCode::OK, "{v}");+ assert!(!e.file(&team).exists());+ let (s, v) = call(&e.app, "DELETE", &format!("/api/kwants/{}", victim.id), Some(e.token())).await;+ assert_eq!(s, StatusCode::OK, "{v}");+ assert!(!e.file(&victim.id).exists());+ for uri in ["/api/bot-actions/some-action/undo", "/api/imports/some-import/undo"] {+ let (s, v) = call(&e.app, "POST", uri, Some(e.token())).await;+ assert_eq!(s, StatusCode::NOT_FOUND, "{uri} reaches the handler: {v}");+ }+}++/// Reading and editing stay open on this machine, as before.+#[tokio::test]+async fn reads_and_edits_stay_open_locally() {+ let e = setup().await;+ let bot = e.bots().await.remove(0);+ for uri in ["/api/kwants".to_string(), "/api/teams".to_string(), "/api/bot-actions".to_string(), format!("/api/kwants/{}/usage", bot.id)] {+ let (s, v) = call(&e.app, "GET", &uri, None).await;+ assert_eq!(s, StatusCode::OK, "GET {uri}: {v}");+ }+}diff --git a/tests/server_test.rs b/tests/server_test.rsindex 324947f8..73e06f27 100644--- a/tests/server_test.rs+++ b/tests/server_test.rs@@ -69,7 +69,7 @@ async fn test_teams_api_endpoints() {let router = LayaRouter::new(config.laya_url.clone());let state = AppState::new(config, db.clone(), tools, broker, router);- let app = create_router(state);+ let app = create_router(state.clone());// 1. GET /api/teams - Should return seeded teamlet req = Request::builder()@@ -137,6 +137,7 @@ async fn test_teams_api_endpoints() {let req = Request::builder().method("DELETE").uri(format!("/api/teams/{}", created_team.id))+ .header("authorization", format!("Bearer {}", state.api_token.reveal())).body(Body::empty()).unwrap();let resp = app.clone().oneshot(req).await.unwrap();diff --git a/tests/spaces_s2_fixes_test.rs b/tests/spaces_s2_fixes_test.rsindex 001bbfd4..e995754c 100644--- a/tests/spaces_s2_fixes_test.rs+++ b/tests/spaces_s2_fixes_test.rs@@ -92,6 +92,20 @@ async fn call(app: &Router, method: &str, uri: &str, body: Option<Value>) -> (St(s, serde_json::from_slice(&bytes).unwrap_or_else(|_| Value::String(String::from_utf8_lossy(&bytes).into())))}+async fn call_as(app: &Router, method: &str, uri: &str, token: &str, body: Option<Value>) -> (StatusCode, Value) {+ let req = Request::builder()+ .method(method)+ .uri(uri)+ .header("content-type", "application/json")+ .header("authorization", format!("Bearer {token}"))+ .body(body.map(|v| Body::from(v.to_string())).unwrap_or_else(Body::empty))+ .unwrap();+ let resp = app.clone().oneshot(req).await.unwrap();+ let s = resp.status();+ let bytes = to_bytes(resp.into_body(), usize::MAX).await.unwrap();+ (s, serde_json::from_slice(&bytes).unwrap_or_else(|_| Value::String(String::from_utf8_lossy(&bytes).into())))+}+async fn ok(app: &Router, method: &str, uri: &str, body: Option<Value>) -> Value {let (s, v) = call(app, method, uri, body).await;assert!(s.is_success(), "{method} {uri}: {s} {v}");@@ -552,7 +566,12 @@ async fn writes_on_an_archived_spaces_rows_are_refused() {("POST", "/api/skills".to_string(), Some(skill("late", Some(&bea)))),];for (method, path, body) in writes {- let (s, v) = call(app, method, &path, body).await;+ // Deleting a team is person-only, so that row carries the API token+ let (s, v) = if method == "DELETE" && path.starts_with("/api/teams/") {+ call_as(app, method, &path, env.state.api_token.reveal(), body).await+ } else {+ call(app, method, &path, body).await+ };assert_eq!(s, StatusCode::CONFLICT, "{method} {path}: {v}");}// Reads still work, and nothing changed