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
Saved passwords: count and delete deleted owners' files (audit F-11)
Lin (kwant bot)a2394d8926e7
diff --git a/docs/saved-passwords.md b/docs/saved-passwords.mdindex 48088585..a885b705 100644--- a/docs/saved-passwords.md+++ b/docs/saved-passwords.md@@ -17,6 +17,7 @@ Since 2026-10-20, approvals off and passwords in the built-in store are not allo- While any space or bot has approvals off, saving into the built-in store (`POST …/passwords` or `…/passwords/pending`) returns 409 `{error, needs_bitwarden: true}`. A captured login keeps waiting.- While any space or bot has approvals off, going back from Bitwarden to the built-in store (`DELETE /api/passwords/bitwarden`) returns 409 `{error, needs_bitwarden: true, local_count}`, unless the built-in store is empty.- A space that is off counts even if every bot in it overrides to `ask`, because a new bot there would inherit `off`.+- `local_count` counts every file in `<data>/kwnt-vault/`, including those of deleted teams, channels and bots (audit F-11). A file that won't open counts as one. Deleting a bot, team or channel now deletes its file. Leftovers from before this change are kept, because they are the person's data. They still count, and `POST /api/passwords/migrate` moves them to Bitwarden too. Spaces are only archived, so their bots' passwords keep counting. Deleting an owner never deletes items in Bitwarden.- An install that was already in this state keeps its approvals as they are. `GET /api/passwords/store` shows `exposed: true`, and kwnt logs one warning at start (a count, no secrets). Moving the passwords to Bitwarden or turning approvals back on clears it.With Bitwarden, the API token alone doesn't show a password: that needs the master password. The DevTools gap below still applies in Bitwarden mode.diff --git a/src/sandbox/credentials.rs b/src/sandbox/credentials.rsindex d6b015b0..3155670c 100644--- a/src/sandbox/credentials.rs+++ b/src/sandbox/credentials.rs@@ -72,6 +72,11 @@ pub trait CredentialStore: Send + Sync {/// Adds a credential, or replaces the password of the same origin + username.async fn save(&self, owner: &str, origin: &str, username: &str, password: &str) -> Result<CredentialMeta, StoreError>;async fn delete(&self, owner: &str, id: &str) -> Result<bool, StoreError>;+ /// Removes everything kept for `owner` once its team, channel or bot is deleted. Only the+ /// built-in store keeps per-owner files; other stores keep nothing to remove.+ async fn forget_owner(&self, _owner: &str) -> Result<(), StoreError> {+ Ok(())+ }}/// `scheme://host[:port]` of an http(s) URL, or of a bare host (taken as https).@@ -185,6 +190,19 @@ fn load_or_create_key(path: &Path, rng: &SystemRandom) -> Result<[u8; 32], StoreOk(key)}+/// The owner each `*.bin` file in `dir` is named after, live or not: every file the built-in+/// store holds. A hashed name (`h-…`) can't be opened by its stem, so it is counted, not moved.+pub fn stored_owners(dir: &Path) -> Vec<String> {+ let Ok(entries) = std::fs::read_dir(dir) else { return Vec::new() };+ let mut owners: Vec<String> = entries+ .flatten()+ .filter_map(|e| e.file_name().to_str().and_then(|n| n.strip_suffix(".bin")).map(str::to_string))+ .filter(|o| !o.is_empty())+ .collect();+ owners.sort();+ owners+}+/// A file name for an owner id; ids are uuids, anything else is hashed.fn owner_file(owner: &str) -> String {let plain = !owner.is_empty() && owner.len() <= 64 && owner.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_');@@ -314,6 +332,14 @@ impl CredentialStore for EncryptedFileStore {self.write(owner, &creds)?;Ok(true)}++ async fn forget_owner(&self, owner: &str) -> Result<(), StoreError> {+ let _g = self.guard();+ match std::fs::remove_file(self.path(owner)) {+ Err(e) if e.kind() != std::io::ErrorKind::NotFound => Err(e.into()),+ _ => Ok(()),+ }+ }}/// Stands in when the store can't be opened (an unreadable key): every call fails, nothing is@@ -446,6 +472,21 @@ mod tests {assert!(matches!(store.list("b").await, Err(StoreError::Crypto)));}+ #[tokio::test]+ async fn every_file_is_listed_and_forgetting_an_owner_removes_its_file() {+ let dir = tempfile::tempdir().unwrap();+ let store = EncryptedFileStore::open(dir.path()).unwrap();+ store.save("a", "https://example.com", "u", "DUMMY").await.unwrap();+ store.save("b", "https://example.com", "u", "DUMMY").await.unwrap();+ let v = dir.path().join(VAULT_DIR);+ std::fs::write(v.join("bitwarden.json"), b"{}").unwrap();+ assert_eq!(stored_owners(&v), vec!["a".to_string(), "b".to_string()]);+ store.forget_owner("a").await.unwrap();+ store.forget_owner("never-saved").await.unwrap();+ assert!(!v.join("a.bin").exists());+ assert_eq!(stored_owners(&v), vec!["b".to_string()]);+ }+#[test]fn secret_mentions() {assert!(mentions_kwnt_secrets("cat ~/.kwnt/kwnt-vault.key"));diff --git a/src/sandbox/vault.rs b/src/sandbox/vault.rsindex 5e0d65c8..8b760066 100644--- a/src/sandbox/vault.rs+++ b/src/sandbox/vault.rs@@ -4,13 +4,15 @@//! unlocks it again. Forgetting Bitwarden goes back to the built-in store.use super::bitwarden::BitwardenStore;-use super::credentials::{open_store, Credential, CredentialMeta, CredentialStore, StoreError, VAULT_DIR};-use std::path::Path;+use super::credentials::{open_store, stored_owners, Credential, CredentialMeta, CredentialStore, StoreError, VAULT_DIR};+use std::path::{Path, PathBuf};use std::sync::Arc;pub struct PasswordVault {local: Arc<dyn CredentialStore>,bitwarden: BitwardenStore,+ /// `<data_dir>/kwnt-vault`, where the built-in store keeps one file per owner.+ dir: PathBuf,}impl std::fmt::Debug for PasswordVault {@@ -33,7 +35,8 @@ impl PasswordVault {}pub fn new(local: Arc<dyn CredentialStore>, data_dir: &Path) -> Self {- Self { local, bitwarden: BitwardenStore::open(&data_dir.join(VAULT_DIR)) }+ let dir = data_dir.join(VAULT_DIR);+ Self { local, bitwarden: BitwardenStore::open(&dir), dir }}pub fn bitwarden(&self) -> &BitwardenStore {@@ -66,24 +69,27 @@ impl PasswordVault {}}- /// Moves every built-in saved password of `owners` into the unlocked Bitwarden vault. Each is- /// deleted locally only after Bitwarden has it; one that fails stays where it was.- pub async fn move_local_to_bitwarden(&self, owners: &[String]) -> Result<Migration, StoreError> {+ /// Moves every password the built-in store holds into the unlocked Bitwarden vault, including+ /// those of deleted teams, channels and bots (audit F-11). Each is deleted locally only after+ /// Bitwarden has it; one that fails stays where it was, and a file no owner opens counts as+ /// one failure.+ pub async fn move_local_to_bitwarden(&self) -> Result<Migration, StoreError> {if !self.bitwarden.is_unlocked().await {return Err(StoreError::Locked);}let mut done = Migration::default();- for owner in owners {- let Ok(list) = self.local.list(owner).await else {+ for owner in stored_owners(&self.dir) {+ let Ok(list) = self.local.list(&owner).await else {+ done.failed += 1;continue;};for meta in list {- let Ok(Some(c)) = self.local.get(owner, &meta.id).await else {+ let Ok(Some(c)) = self.local.get(&owner, &meta.id).await else {done.failed += 1;continue;};- match self.bitwarden.save(owner, &c.meta.origin, &c.meta.username, &c.password).await {- Ok(_) if self.local.delete(owner, &meta.id).await.is_ok() => done.moved += 1,+ match self.bitwarden.save(&owner, &c.meta.origin, &c.meta.username, &c.password).await {+ Ok(_) if self.local.delete(&owner, &meta.id).await.is_ok() => done.moved += 1,Ok(_) => done.failed += 1,Err(StoreError::Locked) => return Err(StoreError::Locked),Err(e) => {@@ -96,14 +102,21 @@ impl PasswordVault {Ok(done)}- /// How many passwords the built-in store holds for `owners`.- pub async fn local_count(&self, owners: &[String]) -> usize {+ /// How many passwords the built-in store holds: every file in it, including those of deleted+ /// owners (audit F-11). A file that doesn't open counts as one, since a bot with the key might.+ pub async fn local_count(&self) -> usize {let mut n = 0;- for owner in owners {- n += self.local.list(owner).await.map(|l| l.len()).unwrap_or(0);+ for owner in stored_owners(&self.dir) {+ n += self.local.list(&owner).await.map(|l| l.len()).unwrap_or(1);}n}++ /// Deletes the built-in store's file for a team, channel or bot that was deleted. Bitwarden+ /// items are the person's own and stay.+ pub async fn forget_local_owner(&self, owner: &str) -> Result<(), StoreError> {+ self.local.forget_owner(owner).await+ }}#[async_trait::async_trait]@@ -157,7 +170,7 @@ mod tests {assert!(vault.for_origin("team-1", "https://example.com").await.unwrap().is_none());assert!(matches!(vault.list("team-1").await, Err(StoreError::Locked)));assert!(matches!(vault.save("team-1", "https://example.com", "u", "p").await, Err(StoreError::Locked)));- assert!(matches!(vault.move_local_to_bitwarden(&["team-1".into()]).await, Err(StoreError::Locked)));- assert_eq!(vault.local_count(&["team-1".into()]).await, 1, "the local copy stays until moved");+ assert!(matches!(vault.move_local_to_bitwarden().await, Err(StoreError::Locked)));+ assert_eq!(vault.local_count().await, 1, "the local copy stays until moved");}}diff --git a/src/server/bot_actions.rs b/src/server/bot_actions.rsindex 28fc87c6..4926d4fa 100644--- a/src/server/bot_actions.rs+++ b/src/server/bot_actions.rs@@ -1680,6 +1680,7 @@ async fn delete_unused_bot(state: &AppState, id: &str) -> Result<(), Response> {}match state.db.delete_unused_kwant(id).await {Ok(true) => {+ super::passwords::forget_deleted_owners(state, &[id]).await;state.scheduler_wake.notify_one();Ok(())}@@ -1782,7 +1783,7 @@ async fn undo_action(state: &AppState, a: &BotAction) -> Result<Option<String>,.await?;}"channel_create" => match state.db.delete_empty_channel(&target).await {- Ok(true) => {}+ Ok(true) => super::passwords::forget_deleted_owners(state, &[&target]).await,Ok(false) => return Err(error(StatusCode::CONFLICT, "the channel already has messages, so it is kept")),Err(_) => return Err(StatusCode::INTERNAL_SERVER_ERROR.into_response()),},diff --git a/src/server/hires.rs b/src/server/hires.rsindex f82d36a2..52a6daa2 100644--- a/src/server/hires.rs+++ b/src/server/hires.rs@@ -746,6 +746,12 @@ pub(super) async fn remove_made(state: &AppState, ids: &[String], made_team: Optfor id in ids {let _ = state.db.delete_unused_kwant(id).await;}+ // Only what is really gone loses its saved passwords+ let mut gone: Vec<&str> = ids.iter().map(String::as_str).collect();+ if let Some(t) = made_team {+ gone.extend(["channel_id", "id"].iter().filter_map(|k| t[*k].as_str()));+ }+ super::passwords::forget_deleted_owners(state, &gone).await;state.scheduler_wake.notify_one();Ok(())}diff --git a/src/server/import_routes.rs b/src/server/import_routes.rsindex 30bf6955..50e71ebc 100644--- a/src/server/import_routes.rs+++ b/src/server/import_routes.rs@@ -236,6 +236,10 @@ pub async fn undo(State(state): State<AppState>, Scope(space): Scope, Path(id):};match state.db.undo_import(&id, req.force).await {Ok(r) => {+ let c = &r.created;+ let gone: Vec<&str> =+ c.kwants.iter().map(|k| k.id.as_str()).chain(c.teams.iter().chain(&c.channels).map(String::as_str)).collect();+ super::passwords::forget_deleted_owners(&state, &gone).await;tracing::info!(import_id = %id, space = %space, "import undone");Json(r).into_response()}diff --git a/src/server/passwords.rs b/src/server/passwords.rsindex 7e0b5150..ed94c6c3 100644--- a/src/server/passwords.rs+++ b/src/server/passwords.rs@@ -39,6 +39,8 @@//!//! and switching approvals off answers 409 while the built-in store holds any password (see//! [`refuse_approvals_off`]). An install already in that state is reported as `exposed: true`.+//! `local_count` counts every file in the built-in store, those of deleted teams, channels and+//! bots included, and deleting one removes its file (audit F-11).use super::AppState;use crate::db::spaces::SpaceId;@@ -346,10 +348,24 @@ async fn store_json(state: &AppState) -> Value {})}-/// How many passwords the built-in store holds. In Bitwarden mode these are leftovers that were-/// never moved, still readable with the built-in key.+/// How many passwords the built-in store holds, deleted owners' files included (audit F-11). In+/// Bitwarden mode these are leftovers that were never moved, still readable with the built-in key.pub async fn local_count(state: &AppState) -> usize {- state.credentials.local_count(&all_owners(state).await).await+ state.credentials.local_count().await+}++/// After a team, channel or bot is deleted: removes its file from the built-in store, so no+/// password outlives its owner unseen (audit F-11). An id that still exists is left alone.+pub async fn forget_deleted_owners(state: &AppState, ids: &[&str]) {+ if ids.is_empty() {+ return;+ }+ let live = all_owners(state).await;+ for id in ids.iter().filter(|id| !live.iter().any(|l| l == *id)) {+ if let Err(e) = state.credentials.forget_local_owner(id).await {+ tracing::warn!(error = %e, owner = %id, "could not delete a deleted owner's saved passwords");+ }+ }}/// Whether any space or bot has approvals off. A failed read counts as off.@@ -490,8 +506,7 @@ pub async fn migrate_to_bitwarden(State(state): State<AppState>, headers: Headerif let Err(r) = person(&state, &headers).await {return r;}- let owners = all_owners(&state).await;- match state.credentials.move_local_to_bitwarden(&owners).await {+ match state.credentials.move_local_to_bitwarden().await {Ok(done) => {tracing::info!(moved = done.moved, failed = done.failed, "the person moved saved passwords to Bitwarden");Json(json!(done)).into_response()diff --git a/src/server/routes.rs b/src/server/routes.rsindex 9e5b2a48..8764d361 100644--- a/src/server/routes.rs+++ b/src/server/routes.rs@@ -350,6 +350,7 @@ pub async fn delete_kwant(State(state): State<AppState>, headers: axum::http::HeErr(e) => return db_error(&e, ""),}state.broker.forget_kwant(&id).await;+ super::passwords::forget_deleted_owners(&state, &[&id]).await;state.scheduler_wake.notify_one();tracing::info!(kwant_id = %id, name = %bot.name, "the person deleted a bot");let folder = crate::db::spaces::space_data_dir(&state.config.data_dir, &space).join("bot-workspaces").join(&id);@@ -518,7 +519,10 @@ pub async fn delete_team(Path(id): Path<String>,) -> Result<Json<serde_json::Value>, StatusCode> {match state.db.delete_team(&id).await {- Ok(true) => Ok(Json(json!({ "status": "deleted" }))),+ Ok(true) => {+ super::passwords::forget_deleted_owners(&state, &[&id]).await;+ Ok(Json(json!({ "status": "deleted" })))+ }Ok(false) => Err(StatusCode::NOT_FOUND),Err(_) => Err(StatusCode::INTERNAL_SERVER_ERROR),}diff --git a/tests/bitwarden_test.rs b/tests/bitwarden_test.rsindex 2db80a73..27b7b265 100644--- a/tests/bitwarden_test.rs+++ b/tests/bitwarden_test.rs@@ -187,6 +187,8 @@ async fn bitwarden_end_to_end() {.person("POST", &format!("/api/sandbox/{team}/passwords"), Some(json!({"origin": "https://old.example.com", "username": "olduser", "password": "DUMMY-LOCAL-PW"}))).await;assert_eq!(s, StatusCode::OK);+ // and one a deleted bot left behind (audit F-11): counted, and moved too+ e.state.credentials.local().save("0b5e1e7e-dead-4bad-8bad-000000000011", "https://orphan.example.com", "ou", "DUMMY-ORPHAN-PW").await.unwrap();// Wrong master passwordlet unlock = |pw: &str| json!({"server_url": server, "email": email, "master_password": pw});@@ -202,7 +204,7 @@ async fn bitwarden_end_to_end() {assert_eq!(v["bitwarden"]["email"], email);assert_eq!(v["bitwarden"]["unlocked"], true);assert_eq!(v["bitwarden"]["login"], "password");- assert_eq!(v["local_count"], 1);+ assert_eq!(v["local_count"], 2);// Another account can't replace it without forgetting this onelet (s, _) = e@@ -213,8 +215,14 @@ async fn bitwarden_end_to_end() {// Move the local one overlet (s, v) = e.person("POST", "/api/passwords/migrate", None).await;assert_eq!(s, StatusCode::OK, "{v}");- assert_eq!(v, json!({"moved": 1, "failed": 0}));- assert_eq!(e.state.credentials.local_count(std::slice::from_ref(&team)).await, 0);+ assert_eq!(v, json!({"moved": 2, "failed": 0}));+ assert_eq!(e.state.credentials.local_count().await, 0);+ let left: Vec<_> = std::fs::read_dir(e.data.join("kwnt-vault"))+ .unwrap()+ .flatten()+ .filter(|f| f.file_name().to_string_lossy().ends_with(".bin"))+ .collect();+ assert!(left.is_empty(), "Move to Bitwarden leaves no built-in file: {left:?}");// Save one through the API and one the browser capturedlet uri = format!("/api/sandbox/{team}/passwords");@@ -303,7 +311,7 @@ async fn bitwarden_end_to_end() {// Unlock again (the saved server and email are reused) and the items are backlet (s, v) = e.person("POST", "/api/passwords/bitwarden/unlock", Some(json!({"master_password": MASTER}))).await;assert_eq!(s, StatusCode::OK, "{v}");- assert_eq!(v["bitwarden"]["item_count"], 3);+ assert_eq!(v["bitwarden"]["item_count"], 4, "the 3 saved here and the moved leftover");assert_eq!(vault.for_origin(&team, "https://login.example.com").await.unwrap().unwrap().password, "DUMMY-BW-PW-1b");// Delete moves it to Bitwarden's trash and kwnt stops using itdiff --git a/tests/orphan_passwords_test.rs b/tests/orphan_passwords_test.rsnew file mode 100644index 00000000..286a0d3d--- /dev/null+++ b/tests/orphan_passwords_test.rs@@ -0,0 +1,231 @@+//! Saved passwords don't outlive their owner unseen (audit 2026-10-20, F-11). Deleting a bot left+//! its `kwnt-vault/<id>.bin` behind, and `local_count` only counted live owners, so approvals+//! could go off while a bot could still decrypt that file with the built-in key.+//!+//! - Deleting a bot, team or channel deletes its file in the built-in store.+//! - `local_count` (and with it `exposed` and every approvals-off check) counts every file in the+//! built-in store, so a leftover from an older install blocks approvals off.+//! - An archived space keeps its bots, and their passwords keep counting.++use axum::{+ body::{to_bytes, Body},+ http::{Request, StatusCode},+ Router,+};+use kwnt::{+ broker::PermissionBroker,+ config::Config,+ db::{+ models::{NewChannel, NewKwant, NewTeam},+ spaces::SpaceId,+ Database,+ },+ router::LayaRouter,+ sandbox::credentials::VAULT_DIR,+ server::{create_router, passwords::forget_deleted_owners, AppState},+ tools::ToolRunner,+};+use serde_json::{json, Value};+use std::path::PathBuf;+use tempfile::{tempdir, TempDir};+use tower::ServiceExt;++/// An owner id that is not a team, channel or bot: a leftover from before deletes removed files.+const GONE: &str = "0b5e1e7e-dead-4bad-8bad-000000000011";++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()),+ );+ assert_eq!(state.credentials.store_name(), "local");+ Env { app: create_router(state.clone()), state, vault: data.join(VAULT_DIR), _tmp: tmp }+}++impl Env {+ async fn person(&self, method: &str, uri: &str, body: Option<Value>) -> (StatusCode, Value) {+ let req = Request::builder()+ .method(method)+ .uri(uri)+ .header("content-type", "application/json")+ .header("authorization", format!("Bearer {}", self.state.api_token.reveal()));+ let body = body.map(|b| Body::from(b.to_string())).unwrap_or_else(Body::empty);+ let resp = self.app.clone().oneshot(req.body(body).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))+ }+ async fn bots(&self) -> Vec<String> {+ self.state.db.list_kwants(&SpaceId::default_space()).await.unwrap().into_iter().map(|k| k.id).collect()+ }+ async fn save_for(&self, owner: &str) {+ let body = json!({"origin": "https://orphan.test", "username": "ou", "password": "DUMMY-PW-ORPHAN"});+ let (s, v) = self.person("POST", &format!("/api/sandbox/{owner}/passwords"), Some(body)).await;+ assert_eq!(s, StatusCode::OK, "{v}");+ }+ fn file(&self, owner: &str) -> PathBuf {+ self.vault.join(format!("{owner}.bin"))+ }+ async fn local_count(&self) -> Value {+ self.person("GET", "/api/passwords/store", None).await.1["local_count"].clone()+ }+ async fn bot_off(&self, bot: &str) -> (StatusCode, Value) {+ self.person("PUT", &format!("/api/kwants/{bot}/approvals"), Some(json!({"approvals": "off"}))).await+ }+ async fn space_off(&self) -> (StatusCode, Value) {+ let uri = format!("/api/spaces/{}/approvals", SpaceId::default_space().as_str());+ self.person("PUT", &uri, Some(json!({"approvals": "off"}))).await+ }+}++fn assert_refused(s: StatusCode, v: &Value, count: u64) {+ assert_eq!(s, StatusCode::CONFLICT, "{v}");+ assert_eq!(v["needs_bitwarden"], true, "{v}");+ assert_eq!(v["local_count"], count, "{v}");+}++/// Rigel's repro: save for a bot, delete the bot. Its file goes with it, so nothing is left for a+/// bot to decrypt, and approvals may go off.+#[tokio::test]+async fn deleting_a_bot_deletes_its_saved_passwords() {+ let e = setup().await;+ let bots = e.bots().await;+ let (doomed, other) = (&bots[0], &bots[1]);+ e.save_for(doomed).await;+ assert!(e.file(doomed).exists());+ assert_eq!(e.local_count().await, 1);++ let (s, v) = e.person("DELETE", &format!("/api/kwants/{doomed}"), None).await;+ assert_eq!(s, StatusCode::OK, "{v}");+ assert!(!e.file(doomed).exists(), "the deleted bot's file is removed");+ assert_eq!(e.local_count().await, 0);+ let (s, v) = e.bot_off(other).await;+ assert_eq!(s, StatusCode::OK, "nothing is left to read: {v}");+}++/// A leftover file whose owner no longer exists (an older install) counts: approvals off is+/// refused for a bot and for the space, `exposed` shows, and saving is refused once off.+#[tokio::test]+async fn a_leftover_file_of_a_deleted_owner_counts() {+ let e = setup().await;+ e.state.credentials.local().save(GONE, "https://orphan.test", "ou", "DUMMY-PW-ORPHAN").await.unwrap();+ assert!(e.file(GONE).exists());+ assert_eq!(e.local_count().await, 1, "a deleted owner's file counts");++ let bot = e.bots().await.remove(0);+ let (s, v) = e.bot_off(&bot).await;+ assert_refused(s, &v, 1);+ let (s, v) = e.space_off().await;+ assert_refused(s, &v, 1);++ // An install already in that state is reported, not changed+ e.state.db.set_space_approvals(&SpaceId::default_space(), "off").await.unwrap();+ let (_, store) = e.person("GET", "/api/passwords/store", None).await;+ assert_eq!(store["exposed"], true, "{store}");+ assert!(e.file(GONE).exists(), "an existing leftover is the person's data: never deleted on its own");+}++/// A file that doesn't open (a hashed name, a damaged file) still counts, as one.+#[tokio::test]+async fn a_file_that_does_not_open_counts_as_one() {+ let e = setup().await;+ std::fs::write(e.vault.join("h-00112233445566778899aabbccddeeff.bin"), b"not a vault file").unwrap();+ std::fs::write(e.vault.join("bitwarden.tmp-1"), b"ignored").unwrap();+ assert_eq!(e.local_count().await, 1);+ let bot = e.bots().await.remove(0);+ let (s, v) = e.bot_off(&bot).await;+ assert_refused(s, &v, 1);+}++#[tokio::test]+async fn deleting_a_team_deletes_its_saved_passwords() {+ let e = setup().await;+ let bot = e.bots().await.remove(0);+ let team = NewTeam {+ name: "t".into(),+ description: None,+ icon: None,+ lead_kwant_id: bot.clone(),+ member_kwants: vec![bot.clone()],+ workspace_path: None,+ repo_url: None,+ };+ let team = e.state.db.create_team(&SpaceId::default_space(), &team).await.unwrap().id;+ e.save_for(&team).await;+ e.save_for(&bot).await;+ assert_eq!(e.local_count().await, 2);++ let (s, v) = e.person("DELETE", &format!("/api/teams/{team}"), None).await;+ assert_eq!(s, StatusCode::OK, "{v}");+ assert!(!e.file(&team).exists(), "the deleted team's file is removed");+ assert!(e.file(&bot).exists(), "its lead bot's own passwords stay");+ assert_eq!(e.local_count().await, 1);+ let (s, v) = e.bot_off(&bot).await;+ assert_refused(s, &v, 1);+}++/// Channels go through the same clean-up, and an id that still exists is never wiped.+#[tokio::test]+async fn deleting_a_channel_deletes_its_saved_passwords_and_live_owners_are_kept() {+ let e = setup().await;+ let bot = e.bots().await.remove(0);+ let channel = NewChannel {+ name: "ops".into(),+ description: None,+ lead_kwant_id: bot.clone(),+ member_kwants: vec![bot.clone()],+ routing_mode: "auto".into(),+ };+ let channel = e.state.db.create_channel(&SpaceId::default_space(), &channel).await.unwrap().id;+ e.save_for(&channel).await;+ e.save_for(&bot).await;++ // Asked to forget owners that still exist: nothing happens+ forget_deleted_owners(&e.state, &[&channel, &bot]).await;+ assert!(e.file(&channel).exists() && e.file(&bot).exists());++ assert!(e.state.db.delete_empty_channel(&channel).await.unwrap());+ forget_deleted_owners(&e.state, &[&channel]).await;+ assert!(!e.file(&channel).exists(), "the deleted channel's file is removed");+ assert!(e.file(&bot).exists());+ assert_eq!(e.local_count().await, 1);+}++/// Spaces are archived, never deleted: their bots keep existing, and so does the count.+#[tokio::test]+async fn an_archived_space_keeps_counting() {+ let e = setup().await;+ let (s, v) = e.person("POST", "/api/spaces", Some(json!({"name": "Side"}))).await;+ assert_eq!(s, StatusCode::CREATED, "{v}");+ let space = SpaceId::new(v["id"].as_str().unwrap());+ let new_bot = NewKwant {+ name: "Sidey".into(),+ title: "t".into(),+ persona_prompt: "p".into(),+ soul: String::new(),+ avatar_sprite: "architect".into(),+ driver_type: "api".into(),+ preferred_model: "auto".into(),+ };+ let bot = e.state.db.create_kwant(&space, &new_bot).await.unwrap().id;+ e.save_for(&bot).await;+ e.state.db.archive_space(&space).await.unwrap();+ assert_eq!(e.local_count().await, 1);+ let other = e.bots().await.remove(0);+ let (s, v) = e.bot_off(&other).await;+ assert_refused(s, &v, 1);+}