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 can live in the person's Bitwarden, safe with approvals off (option 2)
Lin (kwant bot)8c1ed4850cfb
diff --git a/Cargo.lock b/Cargo.lockindex 8853d159..28828e18 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -102,6 +102,18 @@ dependencies = ["windows-sys 0.61.2",]+[[package]]+name = "argon2"+version = "0.5.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3c3610892ee6e0cbce8ae2700349fcf8f98adb0dbfbee85aec3c9179d29cc072"+dependencies = [+ "base64ct",+ "blake2",+ "cpufeatures 0.2.17",+ "password-hash",+]+[[package]]name = "async-trait"version = "0.1.92"@@ -231,6 +243,15 @@ dependencies = ["serde_core",]+[[package]]+name = "blake2"+version = "0.10.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "46502ad458c9a52b69d4d4d32775c788b7a1b85e8bc9d482d92250fc0e3f8efe"+dependencies = [+ "digest 0.10.7",+]+[[package]]name = "block-buffer"version = "0.10.4"@@ -1278,9 +1299,12 @@ dependencies = [name = "kwnt"version = "0.1.0"dependencies = [+ "aes",+ "argon2","async-trait","axum","base64 0.22.1",+ "cbc","chrono","clap","dirs",@@ -1311,6 +1335,7 @@ dependencies = ["tz-rs","url","uuid",+ "zeroize","zip",]@@ -1668,6 +1693,17 @@ dependencies = ["windows-link",]+[[package]]+name = "password-hash"+version = "0.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "346f04948ba92c43e8469c1ee6736c7563d71012b17d40745260fe106aac2166"+dependencies = [+ "base64ct",+ "rand_core 0.6.4",+ "subtle",+]+[[package]]name = "pdf-extract"version = "0.12.1"diff --git a/Cargo.toml b/Cargo.tomlindex f7c7a6de..62c4e1a4 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -45,6 +45,11 @@ percent-encoding = "2"zip = { version = "9", default-features = false, features = ["deflate"] }serde_norway = "0.9"pdf-extract = "0.12"+# Bitwarden vault crypto (AES-256-CBC + HMAC, Argon2id KDF), done in process; see sandbox::bitwarden+aes = "0.8"+cbc = { version = "0.1", features = ["alloc"] }+argon2 = "0.5"+zeroize = "1"[target.'cfg(unix)'.dependencies]libc = "0.2"diff --git a/docs/saved-passwords.md b/docs/saved-passwords.mdnew file mode 100644index 00000000..614769cc--- /dev/null+++ b/docs/saved-passwords.md@@ -0,0 +1,79 @@+# Saved passwords++Kwnt can fill website logins in a team's, channel's or bot's browser. The passwords live in one of two stores:++| Store | Where | Default |+|---|---|---|+| Built-in | encrypted files in `<data>/kwnt-vault/`, with the key next to them | yes |+| Bitwarden | the person's own Bitwarden (or Vaultwarden) account, folder `kwnt` | after the person unlocks it once |++The built-in store protects against copies of the data folder. It does **not** protect against a bot that runs as the same Linux user with approvals off. That bot can read the key file. Use Bitwarden when bots run with approvals off.++## Bitwarden: what holds and what doesn't++- Kwnt talks to Bitwarden itself (an in-process Rust client), not through the `bw` CLI and not through `bw serve`.+ - The CLI puts `BW_SESSION` in a child's environment and leaves the protected key in `data.json`. In the spike, another process run as the same user recovered a password from them.+ - `bw serve` is an unauthenticated local listener.+- The master password, the session token and the decrypted vault key exist only in kwnt's memory. Nothing secret is written to disk, put in a child's env or argv, or logged.+ - `<data>/kwnt-vault/bitwarden.json` holds only the server URL, email, device id and optional API-key client id.+ - Key buffers are zeroed on drop.+- Kwnt calls `prctl(PR_SET_DUMPABLE, 0)` at start. This makes `/proc/<kwnt>/{environ,mem,maps,…}` root-owned, so a same-user process can't read kwnt's memory or attach with ptrace. Children (Chrome, CLIs) get the normal setting back on exec.+- After a restart the vault is **locked**:+ - nothing is filled;+ - the per-owner password routes answer 423;+ - 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.++**Known gap (open):** Chrome's DevTools port listens on loopback without authentication. A bot with a shell can attach to it and read a field kwnt has filled. Bitwarden can't close this. Closing it needs either `--remote-debugging-pipe` or no autofill while approvals are off.++## HTTP API (person only)++Per owner (`:id` is a team, channel or bot id):++- `GET /api/sandbox/:id/passwords` returns `{passwords: [{id, origin, domain, username, created_at, last_used}], pending: null | {origin, username, captured_at}}`.+- `POST /api/sandbox/:id/passwords {origin | domain, username, password}` returns `{status: "saved", credential}`.+- `POST /api/sandbox/:id/passwords/:cid/reveal` returns `{password}`.+ - In Bitwarden mode the body must be `{master_password}`.+ - A wrong one returns 401 `{wrong_password: true}`.+- `DELETE /api/sandbox/:id/passwords/:cid` returns `{status: "deleted" | "not_found"}`.+- `POST|DELETE /api/sandbox/:id/passwords/pending` saves or discards the captured login.+- While Bitwarden is locked, each of these returns 423 `{error, locked: true}`.++Vault:++- `GET /api/passwords/store` returns:++ ```json+ {"store": "local" | "bitwarden", "locked": bool, "local_count": n,+ "bitwarden": {"server_url", "email", "login": "password" | "api_key", "client_id",+ "unlocked", "unlocked_at", "item_count", "last_sync"} | null}+ ```++- `POST /api/passwords/bitwarden/unlock` returns the store status.+ - Body: `{server_url?, email?, master_password, client_id?, client_secret?, two_factor_provider?, two_factor_token?, new_device_otp?}`.+ - `server_url` and `email` are needed only the first time. That first unlock also makes Bitwarden the store.+ - `server_url` must be https; plain http is accepted only for loopback.+ - Errors:+ - 401 `{wrong_password: true}`+ - 401 `{needs: "two_factor", providers}`+ - 401 `{needs: "new_device_otp"}`+ - 409 when another account is already set up+ - 400 for bad input+ - 502 when Bitwarden is unreachable or refuses+- `POST /api/passwords/bitwarden/lock` returns the store status.+- `DELETE /api/passwords/bitwarden {master_password}` goes back to the built-in store. The vault must be unlocked, and the items stay in Bitwarden.+- `POST /api/passwords/migrate` returns `{moved, failed}`. It runs once, when the person triggers it. Each built-in password is deleted locally only after Bitwarden has it.++## Tests++- `cargo test bitwarden` runs the unit tests and route checks, with known-answer vectors for the key derivation and the cipher format.+- The end-to-end tests run against a throwaway Vaultwarden:++```sh+docker run -d --rm --name kwnt-bwtest -p 127.0.0.1:18990:80 \+ -e SIGNUPS_ALLOWED=true -e SIGNUPS_VERIFY=false vaultwarden/server:latest+KWNT_TEST_VAULTWARDEN=http://127.0.0.1:18990 cargo test --test bitwarden_test+docker rm -f kwnt-bwtest+```diff --git a/src/lib.rs b/src/lib.rsindex 727296d9..75c9236f 100644--- a/src/lib.rs+++ b/src/lib.rs@@ -26,3 +26,19 @@ pub use sandbox::{};pub use server::{create_router, AppState};pub use tools::{ToolError, ToolRunner};++/// Makes kwnt's own process non-dumpable, so another process of the same OS user (a bot's shell+/// with approvals off) can't read its memory through `/proc/<pid>/mem`, attach a debugger, or+/// read `/proc/<pid>/environ`: those files become root's. kwnt holds the unlocked Bitwarden+/// keys in memory only (see `sandbox::bitwarden`). Children kwnt starts get the default back at+/// `execve`, so nothing they do changes. Linux only; elsewhere a no-op.+pub fn harden_process() {+ #[cfg(target_os = "linux")]+ {+ // SAFETY: prctl(PR_SET_DUMPABLE) takes plain integers and touches no memory of ours+ let rc = unsafe { libc::prctl(libc::PR_SET_DUMPABLE, 0, 0, 0, 0) };+ if rc != 0 {+ eprintln!("kwnt: could not make the process non-dumpable: {}", std::io::Error::last_os_error());+ }+ }+}diff --git a/src/main.rs b/src/main.rsindex 252ef3a8..629633d2 100644--- a/src/main.rs+++ b/src/main.rs@@ -81,9 +81,11 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {let cli = Cli::parse();// Before logging starts: stdout carries the MCP protocolif matches!(cli.command, Some(Commands::McpEchoServer)) {+ // A test helper that holds nothing: left dumpable so tests can find it by its environmentkwnt::mcp::echo_server::run_stdio().await?;return Ok(());}+ kwnt::harden_process();tracing_subscriber::fmt::init();if let Some(Commands::McpOauthMockServer { host, port, expires_in }) = &cli.command {let listener = tokio::net::TcpListener::bind((host.as_str(), *port)).await?;diff --git a/src/sandbox/bitwarden.rs b/src/sandbox/bitwarden.rsnew file mode 100644index 00000000..859d0f75--- /dev/null+++ b/src/sandbox/bitwarden.rs@@ -0,0 +1,1164 @@+//! Saved passwords in the person's Bitwarden vault (bitwarden.com, bitwarden.eu, or a+//! self-hosted Bitwarden or Vaultwarden), through Bitwarden's HTTP API with its crypto done+//! here, in kwnt's own process.+//!+//! Why not the `bw` CLI: it keeps its unlock secret (`BW_SESSION`) in the environment or on the+//! command line of every `bw` process, both readable through `/proc` by any process of the same+//! user, and the protected user key in its `data.json`; with both a bot reads every password.+//! `bw serve` and `rbw`'s agent hand passwords to any same-user client of a socket.+//!+//! Here nothing that unlocks the vault leaves kwnt's memory: the person sends the master+//! password once (a person-only route), kwnt derives the keys and keeps the user key and+//! tokens in memory only (kwnt is non-dumpable, see [`crate::harden_process`]), and forgets them+//! on lock or restart. Only non-secret settings (server, email, device id, API client id) are+//! saved, in `<data_dir>/kwnt-vault/bitwarden.json`.+//!+//! kwnt only uses login items in a folder named `kwnt` that carry a hidden `kwnt-owner` field+//! naming the team, channel or bot. Other items' passwords are never decrypted. Organization+//! items are ignored.++use super::credentials::{normalize_origin, private_dir, write_private, Credential, CredentialMeta, CredentialStore, StoreError};+use aes::cipher::{block_padding::Pkcs7, BlockDecryptMut, BlockEncryptMut, KeyIvInit};+use base64::{+ engine::general_purpose::{STANDARD as B64, URL_SAFE_NO_PAD},+ Engine,+};+use ring::rand::{SecureRandom, SystemRandom};+use ring::{hkdf, hmac, pbkdf2};+use serde::{Deserialize, Serialize};+use serde_json::{json, Value};+use std::num::NonZeroU32;+use std::path::{Path, PathBuf};+use std::time::{Duration, Instant};+use zeroize::{Zeroize, Zeroizing};++pub const CONFIG_FILE: &str = "bitwarden.json";+pub const FOLDER_NAME: &str = "kwnt";+pub const OWNER_FIELD: &str = "kwnt-owner";+const CLIENT_NAME: &str = "cli";+const CLIENT_VERSION: &str = "2026.10.0";+#[cfg(target_os = "macos")]+const DEVICE_TYPE: &str = "24"; // MacOsCLI+#[cfg(not(target_os = "macos"))]+const DEVICE_TYPE: &str = "25"; // LinuxCLI+/// The cached vault is fetched again when older than this.+const RESYNC: Duration = Duration::from_secs(300);+/// Wrong master passwords in a row (on reveal or forget) before kwnt locks the vault.+pub const MAX_WRONG_PASSWORDS: u32 = 5;++#[derive(Debug, thiserror::Error)]+pub enum UnlockError {+ #[error("wrong email or master password")]+ Wrong,+ #[error("Bitwarden asks for a two-step login code")]+ TwoFactor(Vec<String>),+ #[error("Bitwarden emailed a code to confirm this new device")]+ NewDeviceOtp,+ #[error("another Bitwarden account is set up; forget it first")]+ OtherAccount,+ #[error("{0}")]+ Invalid(String),+ #[error("Bitwarden could not be reached: {0}")]+ Unreachable(String),+ #[error("Bitwarden refused: {0}")]+ Server(String),+ #[error("this vault uses something kwnt does not support yet: {0}")]+ Unsupported(String),+}++#[derive(Debug)]+struct CryptoFail;++impl From<CryptoFail> for StoreError {+ fn from(_: CryptoFail) -> Self {+ StoreError::Crypto+ }+}++struct Len(usize);++impl hkdf::KeyType for Len {+ fn len(&self) -> usize {+ self.0+ }+}++/// A Bitwarden symmetric key: 32 bytes for AES-256-CBC, then 32 for HMAC-SHA256.+pub struct SymKey(Zeroizing<[u8; 64]>);++impl SymKey {+ pub fn from_slice(bytes: &[u8]) -> Option<Self> {+ let mut key = Zeroizing::new([0u8; 64]);+ (bytes.len() == 64).then(|| {+ key.copy_from_slice(bytes);+ SymKey(key)+ })+ }++ /// The key a master key unlocks the account key with (HKDF-Expand "enc" and "mac").+ pub fn stretch(master: &[u8; 32]) -> Self {+ let prk = hkdf::Prk::new_less_safe(hkdf::HKDF_SHA256, master);+ let mut key = Zeroizing::new([0u8; 64]);+ for (info, out) in [(b"enc", 0..32), (b"mac", 32..64)] {+ let info: [&[u8]; 1] = [info];+ prk.expand(&info, Len(32))+ .and_then(|okm| okm.fill(&mut key[out]))+ .expect("32 bytes is a valid HKDF-SHA256 length");+ }+ SymKey(key)+ }++ fn enc(&self) -> &[u8] {+ &self.0[..32]+ }++ fn mac(&self) -> hmac::Key {+ hmac::Key::new(hmac::HMAC_SHA256, &self.0[32..])+ }++ /// Opens a type-2 EncString (`2.iv|data|mac`, AES-256-CBC + HMAC-SHA256).+ pub fn decrypt(&self, enc_string: &str) -> Result<Zeroizing<Vec<u8>>, StoreError> {+ let rest = enc_string.strip_prefix("2.").ok_or(StoreError::Crypto)?;+ let mut parts = rest.split('|');+ let mut next = || parts.next().and_then(|p| B64.decode(p).ok()).ok_or(CryptoFail);+ let (iv, data, tag) = (next()?, next()?, next()?);+ if iv.len() != 16 {+ return Err(StoreError::Crypto);+ }+ let mut signed = iv.clone();+ signed.extend_from_slice(&data);+ hmac::verify(&self.mac(), &signed, &tag).map_err(|_| CryptoFail)?;+ let dec = cbc::Decryptor::<aes::Aes256>::new_from_slices(self.enc(), &iv).map_err(|_| CryptoFail)?;+ dec.decrypt_padded_vec_mut::<Pkcs7>(&data).map(Zeroizing::new).map_err(|_| StoreError::Crypto)+ }++ pub fn decrypt_string(&self, enc_string: &str) -> Result<Zeroizing<String>, StoreError> {+ let bytes = self.decrypt(enc_string)?;+ std::str::from_utf8(&bytes).map(|s| Zeroizing::new(s.to_string())).map_err(|_| StoreError::Crypto)+ }++ pub fn encrypt(&self, plain: &[u8], rng: &SystemRandom) -> Result<String, StoreError> {+ let mut iv = [0u8; 16];+ rng.fill(&mut iv).map_err(|_| CryptoFail)?;+ let enc = cbc::Encryptor::<aes::Aes256>::new_from_slices(self.enc(), &iv).map_err(|_| CryptoFail)?;+ let data = enc.encrypt_padded_vec_mut::<Pkcs7>(plain);+ let mut signed = iv.to_vec();+ signed.extend_from_slice(&data);+ let tag = hmac::sign(&self.mac(), &signed);+ Ok(format!("2.{}|{}|{}", B64.encode(iv), B64.encode(&data), B64.encode(tag.as_ref())))+ }+}++/// How an account turns its master password into the master key.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum Kdf {+ Pbkdf2 { iterations: u32 },+ Argon2id { iterations: u32, memory_mib: u32, parallelism: u32 },+}++impl Kdf {+ /// From a prelogin or token response, within limits that keep a hostile server from making+ /// kwnt spend minutes or gigabytes on one unlock.+ pub fn from_json(v: &Value) -> Result<Self, UnlockError> {+ let num = |name: &str| field(v, name).and_then(Value::as_u64).map(|n| n.min(u32::MAX as u64) as u32);+ let iterations = num("kdfIterations").ok_or_else(|| UnlockError::Server("no KDF settings".into()))?;+ let kdf = match num("kdf").unwrap_or(0) {+ 0 => Kdf::Pbkdf2 { iterations },+ 1 => Kdf::Argon2id {+ iterations,+ memory_mib: num("kdfMemory").unwrap_or(64),+ parallelism: num("kdfParallelism").unwrap_or(4),+ },+ other => return Err(UnlockError::Unsupported(format!("KDF type {other}"))),+ };+ let ok = match kdf {+ Kdf::Pbkdf2 { iterations } => (5_000..=10_000_000).contains(&iterations),+ Kdf::Argon2id { iterations, memory_mib, parallelism } => {+ (1..=20).contains(&iterations) && (15..=1024).contains(&memory_mib) && (1..=16).contains(¶llelism)+ }+ };+ if ok {+ Ok(kdf)+ } else {+ Err(UnlockError::Unsupported(format!("KDF settings out of range: {kdf:?}")))+ }+ }+}++/// The account's master key from its master password and email.+pub fn master_key(password: &str, email: &str, kdf: Kdf) -> Result<Zeroizing<[u8; 32]>, UnlockError> {+ let salt = email.trim().to_lowercase();+ let mut key = Zeroizing::new([0u8; 32]);+ match kdf {+ Kdf::Pbkdf2 { iterations } => {+ let n = NonZeroU32::new(iterations).ok_or_else(|| UnlockError::Unsupported("0 iterations".into()))?;+ pbkdf2::derive(pbkdf2::PBKDF2_HMAC_SHA256, n, salt.as_bytes(), password.as_bytes(), &mut key[..]);+ }+ Kdf::Argon2id { iterations, memory_mib, parallelism } => {+ use sha2::{Digest, Sha256};+ let salt = Sha256::digest(salt.as_bytes());+ let params = argon2::Params::new(memory_mib * 1024, iterations, parallelism, Some(32))+ .map_err(|e| UnlockError::Unsupported(e.to_string()))?;+ argon2::Argon2::new(argon2::Algorithm::Argon2id, argon2::Version::V0x13, params)+ .hash_password_into(password.as_bytes(), &salt, &mut key[..])+ .map_err(|e| UnlockError::Unsupported(e.to_string()))?;+ }+ }+ Ok(key)+}++/// What the server checks at login: PBKDF2(master key, salt = master password, 1 round).+pub fn auth_hash(master: &[u8; 32], password: &str) -> Zeroizing<String> {+ let mut out = Zeroizing::new([0u8; 32]);+ pbkdf2::derive(pbkdf2::PBKDF2_HMAC_SHA256, NonZeroU32::MIN, password.as_bytes(), master, &mut out[..]);+ Zeroizing::new(B64.encode(&out[..]))+}++/// Compares two secrets in time that depends only on their lengths.+fn same_secret(a: &[u8], b: &[u8]) -> bool {+ a.len() == b.len() && a.iter().zip(b).fold(0u8, |acc, (x, y)| acc | (x ^ y)) == 0+}++/// A JSON member by name, ignoring case (Bitwarden answers in camelCase, older servers in+/// PascalCase).+fn field<'a>(v: &'a Value, name: &str) -> Option<&'a Value> {+ let obj = v.as_object()?;+ obj.get(name)+ .or_else(|| obj.iter().find(|(k, _)| k.eq_ignore_ascii_case(name)).map(|(_, v)| v))+ .filter(|v| !v.is_null())+}++fn field_str<'a>(v: &'a Value, name: &str) -> Option<&'a str> {+ field(v, name).and_then(Value::as_str)+}++#[derive(Debug, Clone, PartialEq, Eq)]+pub struct Endpoints {+ pub api: String,+ pub identity: String,+}++/// The server's base address as saved, and its API and identity endpoints. bitwarden.com and+/// bitwarden.eu use their own API hosts; anything else is self-hosted (`<base>/api`,+/// `<base>/identity`). Plain http only for this machine.+pub fn endpoints(server: &str) -> Result<(String, Endpoints), UnlockError> {+ let raw = server.trim();+ let raw = if raw.is_empty() { "https://vault.bitwarden.com" } else { raw };+ let with_scheme = if raw.contains("://") { raw.to_string() } else { format!("https://{raw}") };+ let bad = || UnlockError::Invalid("the Bitwarden server must be an https address".into());+ let url = url::Url::parse(&with_scheme).map_err(|_| bad())?;+ let host = url.host_str().ok_or_else(bad)?.to_ascii_lowercase();+ let loopback = host == "localhost" || host.parse::<std::net::IpAddr>().is_ok_and(|ip| ip.is_loopback())+ || host.trim_matches(['[', ']']).parse::<std::net::IpAddr>().is_ok_and(|ip| ip.is_loopback());+ match url.scheme() {+ "https" => {}+ "http" if loopback => {}+ _ => return Err(bad()),+ }+ if url.query().is_some() || url.fragment().is_some() || !url.username().is_empty() || url.password().is_some() {+ return Err(bad());+ }+ for cloud in ["bitwarden.com", "bitwarden.eu"] {+ if host == cloud || host == format!("vault.{cloud}") || host == format!("api.{cloud}") || host == format!("identity.{cloud}") {+ return Ok((+ format!("https://vault.{cloud}"),+ Endpoints { api: format!("https://api.{cloud}"), identity: format!("https://identity.{cloud}") },+ ));+ }+ }+ let base = url.as_str().trim_end_matches('/').to_string();+ Ok((base.clone(), Endpoints { api: format!("{base}/api"), identity: format!("{base}/identity") }))+}++/// The settings kwnt keeps on disk. Nothing here unlocks anything.+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]+pub struct BitwardenConfig {+ pub server_url: String,+ pub email: String,+ /// The personal API key's client id (`user.…`), when the person logs in with it.+ #[serde(default)]+ pub client_id: Option<String>,+ pub device_id: String,+}++/// The person's unlock request. Not `Debug`: it holds the master password.+#[derive(Deserialize, Default)]+pub struct UnlockRequest {+ #[serde(default)]+ pub server_url: Option<String>,+ #[serde(default)]+ pub email: Option<String>,+ pub master_password: String,+ #[serde(default)]+ pub client_id: Option<String>,+ #[serde(default)]+ pub client_secret: Option<String>,+ #[serde(default)]+ pub two_factor_provider: Option<u32>,+ #[serde(default)]+ pub two_factor_token: Option<String>,+ #[serde(default)]+ pub new_device_otp: Option<String>,+}++impl Drop for UnlockRequest {+ fn drop(&mut self) {+ self.master_password.zeroize();+ if let Some(s) = self.client_secret.as_mut() {+ s.zeroize();+ }+ }+}++#[derive(Debug, Clone, Serialize, PartialEq)]+pub struct BitwardenStatus {+ pub server_url: String,+ pub email: String,+ /// `"password"` or `"api_key"`.+ pub login: &'static str,+ pub client_id: Option<String>,+ pub unlocked: bool,+ pub unlocked_at: Option<String>,+ pub item_count: Option<usize>,+ pub last_sync: Option<String>,+}++/// One kwnt login item from the vault, decrypted. Its password is wiped when dropped.+struct Item {+ owner: String,+ cred: Credential,+ /// The item's own key as stored (encrypted with the user key), if it has one.+ key_enc: Option<String>,+ key: Option<SymKey>,+}++impl Drop for Item {+ fn drop(&mut self) {+ self.cred.password.zeroize();+ }+}++struct Session {+ cfg: BitwardenConfig,+ ep: Endpoints,+ access: Zeroizing<String>,+ refresh: Option<Zeroizing<String>>,+ client_secret: Option<Zeroizing<String>>,+ expires: Instant,+ user_key: SymKey,+ kdf: Kdf,+ auth_hash: Zeroizing<String>,+ folder_id: Option<String>,+ /// The account's id, which new items name as `encryptedFor`.+ user_id: Option<String>,+ items: Vec<Item>,+ synced: Instant,+ synced_at: String,+ unlocked_at: String,+ wrong_passwords: u32,+}++pub struct BitwardenStore {+ config_path: PathBuf,+ config: std::sync::RwLock<Option<BitwardenConfig>>,+ session: tokio::sync::Mutex<Option<Session>>,+ http: reqwest::Client,+ rng: SystemRandom,+}++impl std::fmt::Debug for BitwardenStore {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ f.debug_struct("BitwardenStore").field("config", &self.config()).finish_non_exhaustive()+ }+}++/// Errors from an authenticated API call.+enum ApiError {+ /// The session is no longer valid: lock.+ Auth,+ Other(String),+}++impl From<ApiError> for StoreError {+ fn from(e: ApiError) -> Self {+ match e {+ ApiError::Auth => StoreError::Locked,+ ApiError::Other(m) => StoreError::Remote(m),+ }+ }+}++fn short(s: &str) -> String {+ s.chars().take(200).collect()+}++impl BitwardenStore {+ /// The store with its saved settings from `vault_dir`, locked.+ pub fn open(vault_dir: &Path) -> Self {+ let config_path = vault_dir.join(CONFIG_FILE);+ let config = std::fs::read(&config_path).ok().and_then(|b| serde_json::from_slice(&b).ok());+ Self {+ config_path,+ config: std::sync::RwLock::new(config),+ session: tokio::sync::Mutex::new(None),+ http: reqwest::Client::builder()+ .timeout(Duration::from_secs(30))+ .redirect(reqwest::redirect::Policy::none())+ .build()+ .unwrap_or_default(),+ rng: SystemRandom::new(),+ }+ }++ pub fn config(&self) -> Option<BitwardenConfig> {+ self.config.read().unwrap_or_else(|e| e.into_inner()).clone()+ }++ pub fn is_configured(&self) -> bool {+ self.config().is_some()+ }++ pub async fn is_unlocked(&self) -> bool {+ self.session.lock().await.is_some()+ }++ pub async fn status(&self) -> Option<BitwardenStatus> {+ let cfg = self.config()?;+ let session = self.session.lock().await;+ Some(BitwardenStatus {+ server_url: cfg.server_url.clone(),+ email: cfg.email.clone(),+ login: if cfg.client_id.is_some() { "api_key" } else { "password" },+ client_id: cfg.client_id.clone(),+ unlocked: session.is_some(),+ unlocked_at: session.as_ref().map(|s| s.unlocked_at.clone()),+ item_count: session.as_ref().map(|s| s.items.len()),+ last_sync: session.as_ref().map(|s| s.synced_at.clone()),+ })+ }++ /// Forgets the unlocked vault (keys, tokens, decrypted items). Saved settings stay.+ pub async fn lock(&self) {+ *self.session.lock().await = None;+ }++ /// Logs in to Bitwarden and unlocks the vault. The first unlock sets the account up; after+ /// that only the same server and email are accepted (see [`Self::forget`]).+ pub async fn unlock(&self, req: UnlockRequest) -> Result<BitwardenStatus, UnlockError> {+ let existing = self.config();+ let server = req.server_url.clone().filter(|s| !s.trim().is_empty())+ .or_else(|| existing.as_ref().map(|c| c.server_url.clone()))+ .unwrap_or_default();+ let (base, ep) = endpoints(&server)?;+ let email = req.email.clone().filter(|s| !s.trim().is_empty())+ .or_else(|| existing.as_ref().map(|c| c.email.clone()))+ .unwrap_or_default()+ .trim()+ .to_lowercase();+ if !email.contains('@') || email.len() > 320 {+ return Err(UnlockError::Invalid("the Bitwarden account email is missing".into()));+ }+ if req.master_password.is_empty() {+ return Err(UnlockError::Invalid("the master password is missing".into()));+ }+ if let Some(cfg) = &existing {+ if cfg.server_url != base || cfg.email != email {+ return Err(UnlockError::OtherAccount);+ }+ }+ let client_id = req.client_id.clone().map(|c| c.trim().to_string()).filter(|c| !c.is_empty())+ .or_else(|| existing.as_ref().and_then(|c| c.client_id.clone()));+ let client_secret = req.client_secret.clone().filter(|c| !c.trim().is_empty()).map(Zeroizing::new);+ if client_id.is_some() && client_secret.is_none() {+ return Err(UnlockError::Invalid("the API key's client secret is missing".into()));+ }+ let cfg = BitwardenConfig {+ server_url: base,+ email: email.clone(),+ client_id: client_id.clone(),+ device_id: existing.as_ref().map(|c| c.device_id.clone()).unwrap_or_else(|| uuid::Uuid::new_v4().to_string()),+ };++ let kdf = self.prelogin(&ep, &email).await?;+ let password = Zeroizing::new(req.master_password.clone());+ let (mk, hash) = {+ let (password, email) = (password.clone(), email.clone());+ tokio::task::spawn_blocking(move || {+ let mk = master_key(&password, &email, kdf)?;+ let hash = auth_hash(&mk, &password);+ Ok::<_, UnlockError>((mk, hash))+ })+ .await+ .map_err(|e| UnlockError::Server(e.to_string()))??+ };++ let mut form: Vec<(&str, String)> = self.device_form(&cfg);+ match (&client_id, &client_secret) {+ (Some(id), Some(secret)) => {+ form.extend([+ ("grant_type", "client_credentials".into()),+ ("client_id", id.clone()),+ ("client_secret", secret.to_string()),+ ("scope", "api".into()),+ ]);+ }+ _ => {+ form.extend([+ ("grant_type", "password".into()),+ ("username", email.clone()),+ ("password", hash.to_string()),+ ("scope", "api offline_access".into()),+ ("client_id", CLIENT_NAME.into()),+ ]);+ if let (Some(p), Some(t)) = (req.two_factor_provider, req.two_factor_token.as_deref()) {+ form.extend([+ ("twoFactorProvider", p.to_string()),+ ("twoFactorToken", t.trim().to_string()),+ ("twoFactorRemember", "0".into()),+ ]);+ }+ if let Some(otp) = req.new_device_otp.as_deref().filter(|o| !o.trim().is_empty()) {+ form.push(("newDeviceOtp", otp.trim().to_string()));+ }+ }+ }+ let token = self.token_request(&ep, &email, form).await?;++ let protected = field_str(&token, "Key").ok_or_else(|| UnlockError::Unsupported("the account has no key".into()))?;+ // With an API key the server never saw the master password: a MAC failure here is a wrong one+ let user_key = SymKey::stretch(&mk)+ .decrypt(protected)+ .map_err(|_| if protected.starts_with("2.") { UnlockError::Wrong } else { UnlockError::Unsupported("account key type".into()) })?;+ let user_key = SymKey::from_slice(&user_key).ok_or_else(|| UnlockError::Unsupported("account key size".into()))?;+ let access = field_str(&token, "access_token").ok_or_else(|| UnlockError::Server("no access token".into()))?;+ let expires_in = field(&token, "expires_in").and_then(Value::as_u64).unwrap_or(3600);+ let now = chrono::Utc::now().to_rfc3339();+ let mut session = Session {+ cfg: cfg.clone(),+ ep,+ access: Zeroizing::new(access.to_string()),+ refresh: field_str(&token, "refresh_token").map(|s| Zeroizing::new(s.to_string())),+ client_secret,+ expires: Instant::now() + Duration::from_secs(expires_in),+ user_key,+ kdf,+ auth_hash: hash,+ folder_id: None,+ user_id: None,+ items: Vec::new(),+ synced: Instant::now(),+ synced_at: now.clone(),+ unlocked_at: now,+ wrong_passwords: 0,+ };+ self.sync(&mut session).await.map_err(|e| match e {+ ApiError::Auth => UnlockError::Server("the new session was refused".into()),+ ApiError::Other(m) => UnlockError::Unreachable(m),+ })?;+ if existing.as_ref() != Some(&cfg) {+ self.save_config(&cfg).map_err(|e| UnlockError::Server(format!("could not save the settings: {e}")))?;+ }+ *self.session.lock().await = Some(session);+ tracing::info!(server = %cfg.server_url, "the person unlocked Bitwarden");+ Ok(self.status().await.expect("configured"))+ }++ /// Checks the master password against the unlocked vault. After+ /// [`MAX_WRONG_PASSWORDS`] wrong ones in a row the vault locks.+ pub async fn verify_master_password(&self, password: &str) -> Result<bool, StoreError> {+ let (email, kdf, expected) = {+ let guard = self.session.lock().await;+ let s = guard.as_ref().ok_or(StoreError::Locked)?;+ (s.cfg.email.clone(), s.kdf, s.auth_hash.clone())+ };+ let password = Zeroizing::new(password.to_string());+ let ok = tokio::task::spawn_blocking(move || {+ master_key(&password, &email, kdf)+ .map(|mk| same_secret(auth_hash(&mk, &password).as_bytes(), expected.as_bytes()))+ .unwrap_or(false)+ })+ .await+ .unwrap_or(false);+ let mut guard = self.session.lock().await;+ let s = guard.as_mut().ok_or(StoreError::Locked)?;+ if ok {+ s.wrong_passwords = 0;+ return Ok(true);+ }+ s.wrong_passwords += 1;+ if s.wrong_passwords >= MAX_WRONG_PASSWORDS {+ *guard = None;+ tracing::warn!("Bitwarden locked after {MAX_WRONG_PASSWORDS} wrong master passwords");+ return Err(StoreError::Locked);+ }+ Ok(false)+ }++ /// Stops using Bitwarden: forgets the session and the saved settings. The route checks the+ /// master password first ([`Self::verify_master_password`]), so whoever holds only the API+ /// token can't point kwnt at another vault. The items stay in the person's vault.+ pub async fn forget(&self) -> Result<(), StoreError> {+ let mut session = self.session.lock().await;+ match std::fs::remove_file(&self.config_path) {+ Err(e) if e.kind() != std::io::ErrorKind::NotFound => return Err(e.into()),+ _ => {}+ }+ *session = None;+ *self.config.write().unwrap_or_else(|e| e.into_inner()) = None;+ tracing::info!("the person stopped using Bitwarden for saved passwords");+ Ok(())+ }++ fn save_config(&self, cfg: &BitwardenConfig) -> std::io::Result<()> {+ if let Some(dir) = self.config_path.parent() {+ private_dir(dir)?;+ }+ write_private(&self.config_path, &serde_json::to_vec_pretty(cfg).unwrap_or_default())?;+ *self.config.write().unwrap_or_else(|e| e.into_inner()) = Some(cfg.clone());+ Ok(())+ }++ fn device_form(&self, cfg: &BitwardenConfig) -> Vec<(&'static str, String)> {+ vec![+ ("deviceType", DEVICE_TYPE.into()),+ ("deviceIdentifier", cfg.device_id.clone()),+ ("deviceName", "kwnt".into()),+ ("devicePushToken", String::new()),+ ]+ }++ fn client_headers(rb: reqwest::RequestBuilder) -> reqwest::RequestBuilder {+ rb.header("Device-Type", DEVICE_TYPE)+ .header("Bitwarden-Client-Name", CLIENT_NAME)+ .header("Bitwarden-Client-Version", CLIENT_VERSION)+ }++ async fn prelogin(&self, ep: &Endpoints, email: &str) -> Result<Kdf, UnlockError> {+ let mut last = String::new();+ for url in [format!("{}/accounts/prelogin", ep.identity), format!("{}/accounts/prelogin", ep.api)] {+ let resp = Self::client_headers(self.http.post(&url))+ .json(&json!({ "email": email }))+ .send()+ .await+ .map_err(|e| UnlockError::Unreachable(short(&e.without_url().to_string())))?;+ if resp.status().is_success() {+ let v: Value = resp.json().await.map_err(|_| UnlockError::Server("unreadable KDF settings".into()))?;+ return Kdf::from_json(&v);+ }+ last = resp.status().to_string();+ }+ Err(UnlockError::Server(format!("prelogin failed: {last}")))+ }++ async fn token_request(&self, ep: &Endpoints, email: &str, form: Vec<(&str, String)>) -> Result<Value, UnlockError> {+ let mut rb = Self::client_headers(self.http.post(format!("{}/connect/token", ep.identity))).form(&form);+ if form.iter().any(|(k, v)| *k == "grant_type" && v == "password") {+ rb = rb.header("Auth-Email", URL_SAFE_NO_PAD.encode(email));+ }+ drop(form);+ let resp = rb.send().await.map_err(|e| UnlockError::Unreachable(short(&e.without_url().to_string())))?;+ let status = resp.status();+ let body: Value = resp.json().await.unwrap_or(Value::Null);+ if status.is_success() {+ return Ok(body);+ }+ if let Some(p) = field(&body, "TwoFactorProviders2").and_then(Value::as_object) {+ return Err(UnlockError::TwoFactor(p.keys().cloned().collect()));+ }+ if let Some(p) = field(&body, "TwoFactorProviders").and_then(Value::as_array) {+ return Err(UnlockError::TwoFactor(p.iter().map(|v| v.as_str().map(str::to_string).unwrap_or_else(|| v.to_string())).collect()));+ }+ let message = [+ field_str(&body, "error_description"),+ field(&body, "ErrorModel").and_then(|m| field_str(m, "Message")),+ field_str(&body, "message"),+ ]+ .into_iter()+ .flatten()+ .find(|m| !m.trim().is_empty())+ .unwrap_or_default()+ .to_string();+ if message.to_lowercase().contains("new device") {+ return Err(UnlockError::NewDeviceOtp);+ }+ let error = field_str(&body, "error").unwrap_or_default();+ let lower = message.to_lowercase();+ if matches!(error, "invalid_grant" | "invalid_client")+ || status == reqwest::StatusCode::UNAUTHORIZED+ || lower.contains("password is incorrect")+ || lower.contains("invalid_username_or_password")+ {+ return Err(UnlockError::Wrong);+ }+ Err(UnlockError::Server(short(&format!("{status} {message}"))))+ }++ /// A fresh access token, from the refresh token or (API key login) the client secret.+ async fn renew(&self, s: &mut Session) -> Result<(), ApiError> {+ let mut form = self.device_form(&s.cfg);+ if let Some(refresh) = &s.refresh {+ form.extend([("grant_type", "refresh_token".into()), ("client_id", CLIENT_NAME.into()), ("refresh_token", refresh.to_string())]);+ } else if let (Some(id), Some(secret)) = (&s.cfg.client_id, &s.client_secret) {+ form.extend([+ ("grant_type", "client_credentials".into()),+ ("client_id", id.clone()),+ ("client_secret", secret.to_string()),+ ("scope", "api".into()),+ ]);+ } else {+ return Err(ApiError::Auth);+ }+ let token = self.token_request(&s.ep, &s.cfg.email, form).await.map_err(|e| match e {+ UnlockError::Unreachable(m) => ApiError::Other(m),+ _ => ApiError::Auth,+ })?;+ let access = field_str(&token, "access_token").ok_or(ApiError::Auth)?;+ s.access = Zeroizing::new(access.to_string());+ if let Some(r) = field_str(&token, "refresh_token") {+ s.refresh = Some(Zeroizing::new(r.to_string()));+ }+ s.expires = Instant::now() + Duration::from_secs(field(&token, "expires_in").and_then(Value::as_u64).unwrap_or(3600));+ Ok(())+ }++ async fn api(&self, s: &mut Session, method: reqwest::Method, path: &str, body: Option<&Value>) -> Result<Value, ApiError> {+ if Instant::now() + Duration::from_secs(60) >= s.expires {+ self.renew(s).await?;+ }+ for attempt in 0..2 {+ let mut rb = Self::client_headers(self.http.request(method.clone(), format!("{}{path}", s.ep.api)))+ .bearer_auth(s.access.as_str());+ if let Some(b) = body {+ rb = rb.json(b);+ }+ let resp = rb.send().await.map_err(|e| ApiError::Other(short(&e.without_url().to_string())))?;+ let status = resp.status();+ if status == reqwest::StatusCode::UNAUTHORIZED && attempt == 0 {+ self.renew(s).await?;+ continue;+ }+ if status == reqwest::StatusCode::UNAUTHORIZED {+ return Err(ApiError::Auth);+ }+ let v: Value = resp.json().await.unwrap_or(Value::Null);+ if !status.is_success() {+ let message = field(&v, "message").or_else(|| field(&v, "ErrorModel")).map(|m| m.to_string()).unwrap_or_default();+ return Err(ApiError::Other(short(&format!("{status} {message}"))));+ }+ return Ok(v);+ }+ Err(ApiError::Auth)+ }++ /// Fetches the vault and keeps kwnt's own items, decrypted, in the session.+ async fn sync(&self, s: &mut Session) -> Result<(), ApiError> {+ let v = self.api(s, reqwest::Method::GET, "/sync?excludeDomains=true", None).await?;+ let (folder_id, items) = parse_sync(&s.user_key, &v);+ s.folder_id = folder_id;+ s.user_id = field(&v, "profile").and_then(|p| field_str(p, "id")).map(str::to_string);+ s.items = items;+ s.synced = Instant::now();+ s.synced_at = chrono::Utc::now().to_rfc3339();+ Ok(())+ }++ /// The unlocked session, synced if stale. A refused session locks the vault.+ async fn fresh(&self) -> Result<tokio::sync::MutexGuard<'_, Option<Session>>, StoreError> {+ let mut guard = self.session.lock().await;+ let s = guard.as_mut().ok_or(StoreError::Locked)?;+ if s.synced.elapsed() >= RESYNC {+ match self.sync(s).await {+ Ok(()) => {}+ Err(ApiError::Auth) => {+ *guard = None;+ tracing::warn!("Bitwarden refused the session; the vault is locked");+ return Err(StoreError::Locked);+ }+ // Offline: keep serving what was fetched+ Err(ApiError::Other(m)) => tracing::warn!(error = %m, "could not refresh the Bitwarden vault"),+ }+ }+ Ok(guard)+ }++ async fn ensure_folder(&self, s: &mut Session) -> Result<String, StoreError> {+ if let Some(id) = &s.folder_id {+ return Ok(id.clone());+ }+ let name = s.user_key.encrypt(FOLDER_NAME.as_bytes(), &self.rng)?;+ let v = self.api(s, reqwest::Method::POST, "/folders", Some(&json!({ "name": name }))).await?;+ let id = field_str(&v, "id").ok_or_else(|| StoreError::Remote("the new folder has no id".into()))?.to_string();+ s.folder_id = Some(id.clone());+ Ok(id)+ }++ #[allow(clippy::too_many_arguments)]+ fn cipher_body(&self, s: &Session, item_key: Option<(&SymKey, &str)>, folder: &str, owner: &str, origin: &str, username: &str, password: &str) -> Result<Value, StoreError> {+ let k = item_key.map(|(k, _)| k).unwrap_or(&s.user_key);+ let enc = |t: &str| k.encrypt(t.as_bytes(), &self.rng);+ let host = url::Url::parse(origin).ok().and_then(|u| u.host_str().map(str::to_string)).unwrap_or_else(|| origin.to_string());+ Ok(json!({+ "type": 1,+ "organizationId": null,+ "encryptedFor": s.user_id,+ "folderId": folder,+ "key": item_key.map(|(_, e)| e),+ "name": enc(&format!("kwnt · {host}"))?,+ "notes": null,+ "favorite": false,+ "reprompt": 0,+ "login": {+ "username": if username.is_empty() { Value::Null } else { Value::String(enc(username)?) },+ "password": enc(password)?,+ "uris": [{ "uri": enc(origin)?, "match": null }],+ "totp": null,+ },+ "fields": [{ "type": 1, "name": enc(OWNER_FIELD)?, "value": enc(owner)?, "linkedId": null }],+ }))+ }++ fn meta_of(s: &Session, owner: &str, pred: impl Fn(&Item) -> bool) -> Option<CredentialMeta> {+ s.items.iter().find(|i| i.owner == owner && pred(i)).map(|i| i.cred.meta.clone())+ }+}++/// kwnt's items from a `/sync` response: login items in the `kwnt` folder with a `kwnt-owner`+/// field. Items that fail to decrypt are skipped.+fn parse_sync(user_key: &SymKey, v: &Value) -> (Option<String>, Vec<Item>) {+ let folder_id = field(v, "folders").and_then(Value::as_array).and_then(|folders| {+ folders.iter().find_map(|f| {+ let name = user_key.decrypt_string(field_str(f, "name")?).ok()?;+ (name.as_str() == FOLDER_NAME).then(|| field_str(f, "id").map(str::to_string)).flatten()+ })+ });+ let Some(folder) = folder_id.clone() else { return (None, Vec::new()) };+ let mut items = Vec::new();+ for c in field(v, "ciphers").and_then(Value::as_array).into_iter().flatten() {+ if field(c, "type").and_then(Value::as_u64) != Some(1)+ || field(c, "organizationId").is_some()+ || field(c, "deletedDate").is_some()+ || field_str(c, "folderId") != Some(folder.as_str())+ {+ continue;+ }+ let Some(id) = field_str(c, "id") else { continue };+ match parse_item(user_key, c, id) {+ Some(item) => items.push(item),+ None => tracing::warn!(item = %id, "skipped a Bitwarden item kwnt could not read"),+ }+ }+ (folder_id, items)+}++fn parse_item(user_key: &SymKey, c: &Value, id: &str) -> Option<Item> {+ let key_enc = field_str(c, "key").map(str::to_string);+ let key = match &key_enc {+ Some(e) => Some(SymKey::from_slice(&user_key.decrypt(e).ok()?)?),+ None => None,+ };+ let k = key.as_ref().unwrap_or(user_key);+ let owner = field(c, "fields").and_then(Value::as_array)?.iter().find_map(|f| {+ let name = k.decrypt_string(field_str(f, "name")?).ok()?;+ (name.as_str() == OWNER_FIELD).then(|| k.decrypt_string(field_str(f, "value")?).ok()).flatten()+ })?;+ let login = field(c, "login")?;+ let password = k.decrypt_string(field_str(login, "password")?).ok()?;+ let username = match field_str(login, "username") {+ Some(u) => k.decrypt_string(u).ok()?.to_string(),+ None => String::new(),+ };+ let uri = field(login, "uris").and_then(Value::as_array)?.iter().find_map(|u| field_str(u, "uri"))?;+ let origin = normalize_origin(&k.decrypt_string(uri).ok()?).ok()?;+ let created = field_str(c, "creationDate").unwrap_or_default().to_string();+ let revised = field_str(c, "revisionDate").unwrap_or_default().to_string();+ Some(Item {+ owner: owner.to_string(),+ cred: Credential {+ meta: CredentialMeta { id: id.to_string(), origin, username, created_at: created, last_used: revised },+ password: password.to_string(),+ },+ key_enc,+ key,+ })+}++#[async_trait::async_trait]+impl CredentialStore for BitwardenStore {+ async fn list(&self, owner: &str) -> Result<Vec<CredentialMeta>, StoreError> {+ let guard = self.fresh().await?;+ let s = guard.as_ref().ok_or(StoreError::Locked)?;+ Ok(s.items.iter().filter(|i| i.owner == owner).map(|i| i.cred.meta.clone()).collect())+ }++ async fn get(&self, owner: &str, id: &str) -> Result<Option<Credential>, StoreError> {+ let guard = self.fresh().await?;+ let s = guard.as_ref().ok_or(StoreError::Locked)?;+ Ok(s.items.iter().find(|i| i.owner == owner && i.cred.meta.id == id).map(|i| i.cred.clone()))+ }++ /// Locked: nothing to fill (never an error, so a page just loads unfilled).+ async fn for_origin(&self, owner: &str, origin: &str) -> Result<Option<Credential>, StoreError> {+ let Ok(origin) = normalize_origin(origin) else { return Ok(None) };+ let guard = match self.fresh().await {+ Ok(g) => g,+ Err(StoreError::Locked) => return Ok(None),+ Err(e) => return Err(e),+ };+ Ok(guard+ .as_ref()+ .and_then(|s| s.items.iter().find(|i| i.owner == owner && i.cred.meta.origin == origin))+ .map(|i| i.cred.clone()))+ }++ async fn save(&self, owner: &str, origin: &str, username: &str, password: &str) -> Result<CredentialMeta, StoreError> {+ let origin = normalize_origin(origin)?;+ let mut guard = self.fresh().await?;+ let s = guard.as_mut().ok_or(StoreError::Locked)?;+ let existing = s.items.iter().position(|i| i.owner == owner && i.cred.meta.origin == origin && i.cred.meta.username == username);+ let folder = self.ensure_folder(s).await?;+ let result = match existing {+ Some(pos) => {+ let item = &s.items[pos];+ let id = item.cred.meta.id.clone();+ let item_key = match (&item.key, &item.key_enc) {+ (Some(k), Some(e)) => Some((k, e.as_str())),+ _ => None,+ };+ let body = self.cipher_body(s, item_key, &folder, owner, &origin, username, password)?;+ self.api(s, reqwest::Method::PUT, &format!("/ciphers/{id}"), Some(&body)).await+ }+ None => {+ let body = self.cipher_body(s, None, &folder, owner, &origin, username, password)?;+ self.api(s, reqwest::Method::POST, "/ciphers", Some(&body)).await+ }+ };+ if let Err(ApiError::Auth) = result {+ *guard = None;+ return Err(StoreError::Locked);+ }+ result?;+ self.sync(s).await?;+ Self::meta_of(s, owner, |i| i.cred.meta.origin == origin && i.cred.meta.username == username)+ .ok_or_else(|| StoreError::Remote("the saved item did not come back from Bitwarden".into()))+ }++ /// Moves the item to the vault's trash, where the person can still restore it.+ async fn delete(&self, owner: &str, id: &str) -> Result<bool, StoreError> {+ let mut guard = self.fresh().await?;+ let s = guard.as_mut().ok_or(StoreError::Locked)?;+ if !s.items.iter().any(|i| i.owner == owner && i.cred.meta.id == id) {+ return Ok(false);+ }+ let path = format!("/ciphers/{}/delete", percent_encoding::utf8_percent_encode(id, percent_encoding::NON_ALPHANUMERIC));+ if let Err(e) = self.api(s, reqwest::Method::PUT, &path, None).await {+ if matches!(e, ApiError::Auth) {+ *guard = None;+ }+ return Err(e.into());+ }+ self.sync(s).await?;+ Ok(true)+ }+}++/// Registers an account on a Vaultwarden server with signups open, for tests against a+/// throwaway server only.+#[doc(hidden)]+pub async fn register_test_account(server: &str, email: &str, password: &str, iterations: u32) -> Result<(), String> {+ let (_, ep) = endpoints(server).map_err(|e| e.to_string())?;+ let http = reqwest::Client::new();+ let mk = master_key(password, email, Kdf::Pbkdf2 { iterations }).map_err(|e| e.to_string())?;+ let rng = SystemRandom::new();+ let mut user_key = [0u8; 64];+ rng.fill(&mut user_key).map_err(|_| "rng")?;+ let key = SymKey::stretch(&mk).encrypt(&user_key, &rng).map_err(|e| e.to_string())?;+ let token = http+ .post(format!("{}/accounts/register/send-verification-email", ep.identity))+ .json(&json!({ "email": email, "name": "kwnt test", "receiveMarketingEmails": false }))+ .send()+ .await+ .map_err(|e| e.to_string())?+ .text()+ .await+ .map_err(|e| e.to_string())?;+ let resp = http+ .post(format!("{}/accounts/register/finish", ep.identity))+ .json(&json!({+ "email": email,+ "emailVerificationToken": token.trim().trim_matches('"'),+ "masterPasswordHash": auth_hash(&mk, password).as_str(),+ "masterPasswordHint": null,+ "key": key,+ "kdf": 0,+ "kdfIterations": iterations,+ }))+ .send()+ .await+ .map_err(|e| e.to_string())?;+ if resp.status().is_success() {+ Ok(())+ } else {+ Err(format!("{} {}", resp.status(), resp.text().await.unwrap_or_default().chars().take(200).collect::<String>()))+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ // Computed by an independent implementation (Node's crypto) for password+ // "DUMMY-master-pw-1", email "[email protected]", PBKDF2 600000.+ const KAT_MASTER_KEY_B64: &str = "CvEI1eQwuZ8tFkKq6EBO4FhDkorFZCPtQWMf4y12pSI=";+ const KAT_AUTH_HASH: &str = "3z9m+sVXUmr2sAFZOh3Thweu9CdxKlBc676HEYlvIwQ=";+ const KAT_STRETCHED_B64: &str = "5CEqupEYQ+Tepc8DaJw/rHJA2Kp2iJSaLR7Voz0W65xSWSU0ErWp9xOtmT8PaZVbkzafVQji/sCyHAZXPkYsZA==";+ const KAT_ENC_STRING: &str = "2.AwMDAwMDAwMDAwMDAwMDAw==|sFVXIU/i9DZag+EJ0B9FzQ50pfSZZg1UqPOraR6668E=|wqpcki+XtofSJgGFdHsAmbCgtWmQL9BKvZn2IuM5pYA=";++ #[test]+ fn matches_an_independent_implementation() {+ let mk = master_key("DUMMY-master-pw-1", " [email protected] ", Kdf::Pbkdf2 { iterations: 600_000 }).unwrap();+ assert_eq!(B64.encode(&mk[..]), KAT_MASTER_KEY_B64);+ assert_eq!(auth_hash(&mk, "DUMMY-master-pw-1").as_str(), KAT_AUTH_HASH);+ let stretched = SymKey::stretch(&mk);+ assert_eq!(B64.encode(&stretched.0[..]), KAT_STRETCHED_B64);+ assert_eq!(stretched.decrypt_string(KAT_ENC_STRING).unwrap().as_str(), "DUMMY-KAT-plaintext");+ }++ #[test]+ fn enc_strings_round_trip_and_reject_tampering() {+ let rng = SystemRandom::new();+ let key = SymKey::from_slice(&[7u8; 64]).unwrap();+ let e = key.encrypt(b"DUMMY-PW", &rng).unwrap();+ assert!(e.starts_with("2."));+ assert_eq!(key.decrypt(&e).unwrap().as_slice(), b"DUMMY-PW");+ let other = SymKey::from_slice(&[8u8; 64]).unwrap();+ assert!(other.decrypt(&e).is_err(), "another key's MAC fails");+ let mut parts: Vec<String> = e.split('|').map(str::to_string).collect();+ parts[1] = B64.encode([0u8; 16]);+ assert!(key.decrypt(&parts.join("|")).is_err(), "changed data fails the MAC");+ assert!(key.decrypt("0.abc|def").is_err());+ assert!(SymKey::from_slice(&[0u8; 32]).is_none());+ }++ #[test]+ fn argon2id_and_kdf_limits() {+ let kdf = Kdf::from_json(&json!({"kdf": 1, "kdfIterations": 3, "kdfMemory": 16, "kdfParallelism": 1})).unwrap();+ let a = master_key("pw", "[email protected]", kdf).unwrap();+ let b = master_key("pw", "[email protected]", kdf).unwrap();+ assert_eq!(a[..], b[..], "the email salt ignores case");+ assert!(Kdf::from_json(&json!({"Kdf": 0, "KdfIterations": 600000})).is_ok(), "PascalCase too");+ assert!(Kdf::from_json(&json!({"kdf": 0, "kdfIterations": 1_000_000_000u64})).is_err());+ assert!(Kdf::from_json(&json!({"kdf": 1, "kdfIterations": 3, "kdfMemory": 100000, "kdfParallelism": 4})).is_err());+ assert!(Kdf::from_json(&json!({"kdf": 9, "kdfIterations": 3})).is_err());+ }++ #[test]+ fn server_addresses() {+ let (base, ep) = endpoints("").unwrap();+ assert_eq!(base, "https://vault.bitwarden.com");+ assert_eq!(ep.api, "https://api.bitwarden.com");+ assert_eq!(endpoints("vault.bitwarden.eu").unwrap().1.identity, "https://identity.bitwarden.eu");+ let (base, ep) = endpoints("https://pw.example.org/vw/").unwrap();+ assert_eq!(base, "https://pw.example.org/vw");+ assert_eq!(ep.api, "https://pw.example.org/vw/api");+ assert!(endpoints("http://127.0.0.1:18990").is_ok(), "plain http on this machine");+ assert!(endpoints("http://pw.example.org").is_err(), "never plain http elsewhere");+ assert!(endpoints("https://u:[email protected]").is_err());+ assert!(endpoints("ftp://pw.example.org").is_err());+ }++ fn sample_vault(user_key: &SymKey, rng: &SystemRandom) -> Value {+ let e = |t: &str| user_key.encrypt(t.as_bytes(), rng).unwrap();+ let item_key_raw = [9u8; 64];+ let item_key = SymKey::from_slice(&item_key_raw).unwrap();+ let ie = |t: &str| item_key.encrypt(t.as_bytes(), rng).unwrap();+ let owner_field = |owner: &str| json!([{"type": 1, "name": e(OWNER_FIELD), "value": e(owner)}]);+ json!({+ "folders": [{"id": "f-other", "name": e("Personal")}, {"id": "f-kwnt", "name": e("kwnt")}],+ "ciphers": [+ {"id": "c1", "type": 1, "folderId": "f-kwnt", "fields": owner_field("team-1"),+ "login": {"username": e("alice"), "password": e("DUMMY-1"), "uris": [{"uri": e("https://example.com/login")}]}},+ // not in the kwnt folder: never used, even with the owner field+ {"id": "c2", "type": 1, "folderId": "f-other", "fields": owner_field("team-1"),+ "login": {"username": e("bob"), "password": e("DUMMY-2"), "uris": [{"uri": e("https://example.com")}]}},+ // in the folder but no owner field+ {"id": "c3", "type": 1, "folderId": "f-kwnt",+ "login": {"username": e("carol"), "password": e("DUMMY-3"), "uris": [{"uri": e("https://example.com")}]}},+ // trashed+ {"id": "c4", "type": 1, "folderId": "f-kwnt", "deletedDate": "2026-01-01T00:00:00Z", "fields": owner_field("team-1"),+ "login": {"username": e("dave"), "password": e("DUMMY-4"), "uris": [{"uri": e("https://example.com")}]}},+ // an organization item+ {"id": "c5", "type": 1, "folderId": "f-kwnt", "organizationId": "o1", "fields": owner_field("team-1"),+ "login": {"username": e("erin"), "password": e("DUMMY-5"), "uris": [{"uri": e("https://example.com")}]}},+ // its own item key, PascalCase like older servers+ {"Id": "c6", "Type": 1, "FolderId": "f-kwnt", "Key": e_bytes(user_key, &item_key_raw, rng),+ "Fields": [{"Type": 1, "Name": ie(OWNER_FIELD), "Value": ie("bot-9")}],+ "Login": {"Username": ie("frank"), "Password": ie("DUMMY-6"), "Uris": [{"Uri": ie("http://127.0.0.1:8080/x")}]}},+ ],+ })+ }++ fn e_bytes(k: &SymKey, b: &[u8], rng: &SystemRandom) -> String {+ k.encrypt(b, rng).unwrap()+ }++ #[test]+ fn only_kwnt_items_in_the_kwnt_folder_are_used() {+ let rng = SystemRandom::new();+ let user_key = SymKey::from_slice(&[5u8; 64]).unwrap();+ let (folder, items) = parse_sync(&user_key, &sample_vault(&user_key, &rng));+ assert_eq!(folder.as_deref(), Some("f-kwnt"));+ let got: Vec<(&str, &str, &str, &str)> = items+ .iter()+ .map(|i| (i.cred.meta.id.as_str(), i.owner.as_str(), i.cred.meta.origin.as_str(), i.cred.password.as_str()))+ .collect();+ assert_eq!(got, vec![("c1", "team-1", "https://example.com", "DUMMY-1"), ("c6", "bot-9", "http://127.0.0.1:8080", "DUMMY-6")]);+ assert!(items[1].key.is_some() && items[1].key_enc.is_some());+ }++ #[tokio::test]+ async fn a_locked_store_fills_nothing_and_lists_nothing() {+ let dir = tempfile::tempdir().unwrap();+ std::fs::write(+ dir.path().join(CONFIG_FILE),+ serde_json::to_vec(&BitwardenConfig {+ server_url: "https://vault.bitwarden.com".into(),+ email: "[email protected]".into(),+ client_id: None,+ device_id: "d".into(),+ })+ .unwrap(),+ )+ .unwrap();+ let store = BitwardenStore::open(dir.path());+ assert!(store.is_configured());+ assert!(!store.is_unlocked().await);+ assert!(store.for_origin("team-1", "https://example.com").await.unwrap().is_none());+ assert!(matches!(store.list("team-1").await, Err(StoreError::Locked)));+ assert!(matches!(store.save("team-1", "https://example.com", "u", "p").await, Err(StoreError::Locked)));+ assert!(matches!(store.verify_master_password("x").await, Err(StoreError::Locked)));+ let status = store.status().await.unwrap();+ assert!(!status.unlocked && status.item_count.is_none());+ }++ #[tokio::test]+ async fn another_account_needs_forget_first() {+ let dir = tempfile::tempdir().unwrap();+ std::fs::write(+ dir.path().join(CONFIG_FILE),+ serde_json::to_vec(&BitwardenConfig {+ server_url: "https://vault.bitwarden.com".into(),+ email: "[email protected]".into(),+ client_id: None,+ device_id: "d".into(),+ })+ .unwrap(),+ )+ .unwrap();+ let store = BitwardenStore::open(dir.path());+ let mut req = UnlockRequest::default();+ req.server_url = Some("https://pw.attacker.test".into());+ req.email = Some("[email protected]".into());+ req.master_password = "DUMMY".into();+ assert!(matches!(store.unlock(req).await, Err(UnlockError::OtherAccount)));+ }+}diff --git a/src/sandbox/browser.rs b/src/sandbox/browser.rsindex a5377f7c..81a2e757 100644--- a/src/sandbox/browser.rs+++ b/src/sandbox/browser.rs@@ -457,7 +457,7 @@ impl BrowserController {.await?;let Some(context) = world["executionContextId"].as_i64() else { return Ok(()) };*self.capture_world.lock().await = Some(context);- let fill = match vault.store.for_origin(&vault.owner, &origin) {+ let fill = match vault.store.for_origin(&vault.owner, &origin).await {Ok(Some(c)) => json!({"origin": origin, "username": c.meta.username, "password": c.password}),_ => Value::Null,};@@ -498,7 +498,7 @@ impl BrowserController {return None;}if let Some(vault) = self.vault().await {- if let Ok(Some(saved)) = vault.store.for_origin(&vault.owner, &origin) {+ if let Ok(Some(saved)) = vault.store.for_origin(&vault.owner, &origin).await {if saved.meta.username == username && saved.password == password {return None;}diff --git a/src/sandbox/credentials.rs b/src/sandbox/credentials.rsindex 954d7590..d6b015b0 100644--- a/src/sandbox/credentials.rs+++ b/src/sandbox/credentials.rs@@ -2,12 +2,13 @@//! each file AES-256-GCM encrypted with the key in `<data_dir>/kwnt-vault.key` (both owner-only,//! 0600 files in 0700 folders). An owner is the team, channel or bot whose browser uses them.//!-//! [`CredentialStore`] is the seam for an external password manager (Proton Pass, Bitwarden,-//! 1Password CLI) later; [`EncryptedFileStore`] is the built-in one.+//! [`CredentialStore`] is the seam for where passwords live: [`EncryptedFileStore`] is the+//! built-in one, [`super::bitwarden::BitwardenStore`] the person's Bitwarden vault, and+//! [`super::vault::PasswordVault`] picks between them.//!//! A bot running as the same OS user could still read both files with approvals off; kwnt//! refuses tool calls that name them ([`mentions_kwnt_secrets`]), which raises the bar but is-//! not a wall. Only another OS user (or a container) is.+//! not a wall. Bitwarden is: its keys only ever live in kwnt's memory.use ring::aead::{Aad, LessSafeKey, Nonce, UnboundKey, AES_256_GCM, NONCE_LEN};use ring::rand::{SecureRandom, SystemRandom};@@ -27,6 +28,10 @@ pub enum StoreError {Crypto,#[error("invalid origin: {0}")]Origin(String),+ #[error("the password vault is locked")]+ Locked,+ #[error("the password manager failed: {0}")]+ Remote(String),}/// What the app may see about a saved password: never the password itself.@@ -58,14 +63,15 @@ impl std::fmt::Debug for Credential {}/// Where saved passwords live. Every call names its owner (team, channel or bot id).+#[async_trait::async_trait]pub trait CredentialStore: Send + Sync {- fn list(&self, owner: &str) -> Result<Vec<CredentialMeta>, StoreError>;- fn get(&self, owner: &str, id: &str) -> Result<Option<Credential>, StoreError>;+ async fn list(&self, owner: &str) -> Result<Vec<CredentialMeta>, StoreError>;+ async fn get(&self, owner: &str, id: &str) -> Result<Option<Credential>, StoreError>;/// The credential to fill on a page whose origin is exactly `origin`.- fn for_origin(&self, owner: &str, origin: &str) -> Result<Option<Credential>, StoreError>;+ async fn for_origin(&self, owner: &str, origin: &str) -> Result<Option<Credential>, StoreError>;/// Adds a credential, or replaces the password of the same origin + username.- fn save(&self, owner: &str, origin: &str, username: &str, password: &str) -> Result<CredentialMeta, StoreError>;- fn delete(&self, owner: &str, id: &str) -> Result<bool, StoreError>;+ 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>;}/// `scheme://host[:port]` of an http(s) URL, or of a bare host (taken as https).@@ -126,19 +132,19 @@ impl std::fmt::Debug for EncryptedFileStore {}#[cfg(unix)]-fn private_dir(path: &Path) -> std::io::Result<()> {+pub(crate) fn private_dir(path: &Path) -> std::io::Result<()> {use std::os::unix::fs::PermissionsExt;std::fs::create_dir_all(path)?;std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o700))}#[cfg(not(unix))]-fn private_dir(path: &Path) -> std::io::Result<()> {+pub(crate) fn private_dir(path: &Path) -> std::io::Result<()> {std::fs::create_dir_all(path)}/// Writes `bytes` to `path` as a new 0600 file, via a temp file and a rename.-fn write_private(path: &Path, bytes: &[u8]) -> std::io::Result<()> {+pub(crate) fn write_private(path: &Path, bytes: &[u8]) -> std::io::Result<()> {use std::io::Write;let tmp = path.with_extension(format!("tmp-{}", uuid::Uuid::new_v4().simple()));let mut opts = std::fs::OpenOptions::new();@@ -252,24 +258,25 @@ impl EncryptedFileStore {}}+#[async_trait::async_trait]impl CredentialStore for EncryptedFileStore {- fn list(&self, owner: &str) -> Result<Vec<CredentialMeta>, StoreError> {+ async fn list(&self, owner: &str) -> Result<Vec<CredentialMeta>, StoreError> {let _g = self.guard();Ok(self.read(owner)?.into_iter().map(|c| c.meta).collect())}- fn get(&self, owner: &str, id: &str) -> Result<Option<Credential>, StoreError> {+ async fn get(&self, owner: &str, id: &str) -> Result<Option<Credential>, StoreError> {let _g = self.guard();Ok(self.read(owner)?.into_iter().find(|c| c.meta.id == id))}- fn for_origin(&self, owner: &str, origin: &str) -> Result<Option<Credential>, StoreError> {+ async fn for_origin(&self, owner: &str, origin: &str) -> Result<Option<Credential>, StoreError> {let Ok(origin) = normalize_origin(origin) else { return Ok(None) };let _g = self.guard();Ok(self.read(owner)?.into_iter().find(|c| c.meta.origin == origin))}- fn save(&self, owner: &str, origin: &str, username: &str, password: &str) -> Result<CredentialMeta, StoreError> {+ async fn save(&self, owner: &str, origin: &str, username: &str, password: &str) -> Result<CredentialMeta, StoreError> {let origin = normalize_origin(origin)?;let _g = self.guard();let mut creds = self.read(owner)?;@@ -296,7 +303,7 @@ impl CredentialStore for EncryptedFileStore {Ok(meta)}- fn delete(&self, owner: &str, id: &str) -> Result<bool, StoreError> {+ async fn delete(&self, owner: &str, id: &str) -> Result<bool, StoreError> {let _g = self.guard();let mut creds = self.read(owner)?;let before = creds.len();@@ -314,20 +321,21 @@ impl CredentialStore for EncryptedFileStore {#[derive(Debug)]pub struct UnavailableStore;+#[async_trait::async_trait]impl CredentialStore for UnavailableStore {- fn list(&self, _: &str) -> Result<Vec<CredentialMeta>, StoreError> {+ async fn list(&self, _: &str) -> Result<Vec<CredentialMeta>, StoreError> {Err(StoreError::Crypto)}- fn get(&self, _: &str, _: &str) -> Result<Option<Credential>, StoreError> {+ async fn get(&self, _: &str, _: &str) -> Result<Option<Credential>, StoreError> {Err(StoreError::Crypto)}- fn for_origin(&self, _: &str, _: &str) -> Result<Option<Credential>, StoreError> {+ async fn for_origin(&self, _: &str, _: &str) -> Result<Option<Credential>, StoreError> {Err(StoreError::Crypto)}- fn save(&self, _: &str, _: &str, _: &str, _: &str) -> Result<CredentialMeta, StoreError> {+ async fn save(&self, _: &str, _: &str, _: &str, _: &str) -> Result<CredentialMeta, StoreError> {Err(StoreError::Crypto)}- fn delete(&self, _: &str, _: &str) -> Result<bool, StoreError> {+ async fn delete(&self, _: &str, _: &str) -> Result<bool, StoreError> {Err(StoreError::Crypto)}}@@ -358,7 +366,7 @@ struct LegacyCredential {/// Moves `<folder>/.saved_passwords.json` into the store for each of `owners`, then deletes the/// file. Returns how many credentials were moved. A file that can't be parsed is left in place.-pub fn migrate_legacy(store: &dyn CredentialStore, folder: &Path, owners: &[&str]) -> Result<usize, StoreError> {+pub async fn migrate_legacy(store: &dyn CredentialStore, folder: &Path, owners: &[&str]) -> Result<usize, StoreError> {let file = folder.join(LEGACY_FILE);let content = match std::fs::read_to_string(&file) {Ok(c) => c,@@ -377,7 +385,7 @@ pub fn migrate_legacy(store: &dyn CredentialStore, folder: &Path, owners: &[&strlet source = if c.origin.is_empty() { c.domain.as_str() } else { c.origin.as_str() };let Ok(origin) = normalize_origin(source) else { continue };for owner in owners {- store.save(owner, &origin, &c.username, &c.password)?;+ store.save(owner, &origin, &c.username, &c.password).await?;}moved += 1;}@@ -398,24 +406,24 @@ mod tests {assert!(normalize_origin("javascript:alert(1)").is_err());}- #[test]- fn encrypted_round_trip_and_private_files() {+ #[tokio::test]+ async fn encrypted_round_trip_and_private_files() {let dir = tempfile::tempdir().unwrap();let store = EncryptedFileStore::open(dir.path()).unwrap();- let meta = store.save("team-1", "https://example.com/login", "alice", "DUMMY-PW-1").unwrap();+ let meta = store.save("team-1", "https://example.com/login", "alice", "DUMMY-PW-1").await.unwrap();assert_eq!(meta.origin, "https://example.com");let raw = std::fs::read(dir.path().join(VAULT_DIR).join("team-1.bin")).unwrap();assert!(!String::from_utf8_lossy(&raw).contains("DUMMY-PW-1"));assert!(!String::from_utf8_lossy(&raw).contains("alice"));- assert_eq!(store.get("team-1", &meta.id).unwrap().unwrap().password, "DUMMY-PW-1");- assert!(store.list("team-2").unwrap().is_empty());- assert!(!format!("{:?}", store.get("team-1", &meta.id).unwrap()).contains("DUMMY"));+ assert_eq!(store.get("team-1", &meta.id).await.unwrap().unwrap().password, "DUMMY-PW-1");+ assert!(store.list("team-2").await.unwrap().is_empty());+ assert!(!format!("{:?}", store.get("team-1", &meta.id).await.unwrap()).contains("DUMMY"));// same origin + username replaces- store.save("team-1", "https://example.com", "alice", "DUMMY-PW-2").unwrap();- assert_eq!(store.list("team-1").unwrap().len(), 1);+ store.save("team-1", "https://example.com", "alice", "DUMMY-PW-2").await.unwrap();+ assert_eq!(store.list("team-1").await.unwrap().len(), 1);// reopen with the same keylet again = EncryptedFileStore::open(dir.path()).unwrap();- assert_eq!(again.get("team-1", &meta.id).unwrap().unwrap().password, "DUMMY-PW-2");+ assert_eq!(again.get("team-1", &meta.id).await.unwrap().unwrap().password, "DUMMY-PW-2");#[cfg(unix)]{use std::os::unix::fs::PermissionsExt;@@ -424,18 +432,18 @@ mod tests {assert_eq!(mode(dir.path().join(VAULT_DIR)), 0o700);assert_eq!(mode(dir.path().join(VAULT_DIR).join("team-1.bin")), 0o600);}- assert!(store.delete("team-1", &meta.id).unwrap());+ assert!(store.delete("team-1", &meta.id).await.unwrap());assert!(!dir.path().join(VAULT_DIR).join("team-1.bin").exists());}- #[test]- fn a_file_moved_to_another_owner_does_not_open() {+ #[tokio::test]+ async fn a_file_moved_to_another_owner_does_not_open() {let dir = tempfile::tempdir().unwrap();let store = EncryptedFileStore::open(dir.path()).unwrap();- store.save("a", "https://example.com", "u", "DUMMY").unwrap();+ store.save("a", "https://example.com", "u", "DUMMY").await.unwrap();let v = dir.path().join(VAULT_DIR);std::fs::copy(v.join("a.bin"), v.join("b.bin")).unwrap();- assert!(matches!(store.list("b"), Err(StoreError::Crypto)));+ assert!(matches!(store.list("b").await, Err(StoreError::Crypto)));}#[test]diff --git a/src/sandbox/mod.rs b/src/sandbox/mod.rsindex 3d97bf9c..9946ef3c 100644--- a/src/sandbox/mod.rs+++ b/src/sandbox/mod.rs@@ -1,8 +1,10 @@+pub mod bitwarden;pub mod browser;pub mod computer;pub mod credentials;pub mod manager;pub mod service;+pub mod vault;pub use browser::{detect_bot_wall, BrowserController, BrowserError, NavigationResult, PendingCapture};pub use credentials::{Credential, CredentialMeta, CredentialStore, EncryptedFileStore};diff --git a/src/sandbox/vault.rs b/src/sandbox/vault.rsnew file mode 100644index 00000000..5e0d65c8--- /dev/null+++ b/src/sandbox/vault.rs@@ -0,0 +1,163 @@+//! Which store saved passwords live in: the built-in encrypted files by default, or the person's+//! Bitwarden vault once they unlock one ([`BitwardenStore`]). While Bitwarden is set up it is the+//! only store used; locked, nothing is filled and nothing can be read or saved until the person+//! 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 std::sync::Arc;++pub struct PasswordVault {+ local: Arc<dyn CredentialStore>,+ bitwarden: BitwardenStore,+}++impl std::fmt::Debug for PasswordVault {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ f.debug_struct("PasswordVault").field("bitwarden", &self.bitwarden).finish_non_exhaustive()+ }+}++/// What a move from the built-in store to Bitwarden did.+#[derive(Debug, Default, Clone, serde::Serialize, PartialEq)]+pub struct Migration {+ pub moved: usize,+ pub failed: usize,+}++impl PasswordVault {+ /// The vault under `data_dir`: the built-in store and the saved Bitwarden settings, locked.+ pub fn open(data_dir: &Path) -> Self {+ Self::new(open_store(data_dir), data_dir)+ }++ pub fn new(local: Arc<dyn CredentialStore>, data_dir: &Path) -> Self {+ Self { local, bitwarden: BitwardenStore::open(&data_dir.join(VAULT_DIR)) }+ }++ pub fn bitwarden(&self) -> &BitwardenStore {+ &self.bitwarden+ }++ pub fn local(&self) -> &dyn CredentialStore {+ self.local.as_ref()+ }++ /// `"bitwarden"` once the person set Bitwarden up, else `"local"`.+ pub fn store_name(&self) -> &'static str {+ if self.bitwarden.is_configured() {+ "bitwarden"+ } else {+ "local"+ }+ }++ /// Whether saved passwords can't be used until the person unlocks Bitwarden.+ pub async fn is_locked(&self) -> bool {+ self.bitwarden.is_configured() && !self.bitwarden.is_unlocked().await+ }++ fn active(&self) -> &dyn CredentialStore {+ if self.bitwarden.is_configured() {+ &self.bitwarden+ } else {+ self.local.as_ref()+ }+ }++ /// 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> {+ 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 {+ continue;+ };+ for meta in list {+ 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,+ Ok(_) => done.failed += 1,+ Err(StoreError::Locked) => return Err(StoreError::Locked),+ Err(e) => {+ tracing::warn!(error = %e, "a saved password could not be moved to Bitwarden");+ done.failed += 1;+ }+ }+ }+ }+ Ok(done)+ }++ /// How many passwords the built-in store holds for `owners`.+ pub async fn local_count(&self, owners: &[String]) -> usize {+ let mut n = 0;+ for owner in owners {+ n += self.local.list(owner).await.map(|l| l.len()).unwrap_or(0);+ }+ n+ }+}++#[async_trait::async_trait]+impl CredentialStore for PasswordVault {+ async fn list(&self, owner: &str) -> Result<Vec<CredentialMeta>, StoreError> {+ self.active().list(owner).await+ }+ async fn get(&self, owner: &str, id: &str) -> Result<Option<Credential>, StoreError> {+ self.active().get(owner, id).await+ }+ async fn for_origin(&self, owner: &str, origin: &str) -> Result<Option<Credential>, StoreError> {+ self.active().for_origin(owner, origin).await+ }+ async fn save(&self, owner: &str, origin: &str, username: &str, password: &str) -> Result<CredentialMeta, StoreError> {+ self.active().save(owner, origin, username, password).await+ }+ async fn delete(&self, owner: &str, id: &str) -> Result<bool, StoreError> {+ self.active().delete(owner, id).await+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::sandbox::bitwarden::{BitwardenConfig, CONFIG_FILE};++ #[tokio::test]+ async fn local_by_default_and_locked_once_bitwarden_is_set_up() {+ let dir = tempfile::tempdir().unwrap();+ let vault = PasswordVault::open(dir.path());+ assert_eq!(vault.store_name(), "local");+ assert!(!vault.is_locked().await);+ vault.save("team-1", "https://example.com", "alice", "DUMMY-PW").await.unwrap();+ assert!(vault.for_origin("team-1", "https://example.com/login").await.unwrap().is_some());++ std::fs::write(+ dir.path().join(VAULT_DIR).join(CONFIG_FILE),+ serde_json::to_vec(&BitwardenConfig {+ server_url: "https://vault.bitwarden.com".into(),+ email: "[email protected]".into(),+ client_id: None,+ device_id: "d".into(),+ })+ .unwrap(),+ )+ .unwrap();+ // After a restart with Bitwarden set up: locked, nothing filled, the local store unused+ let vault = PasswordVault::open(dir.path());+ assert_eq!(vault.store_name(), "bitwarden");+ assert!(vault.is_locked().await);+ 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");+ }+}diff --git a/src/server/auth.rs b/src/server/auth.rsindex e0e7aa75..f0bb5358 100644--- a/src/server/auth.rs+++ b/src/server/auth.rs@@ -183,7 +183,7 @@ fn exempt(path: &str) -> bool {|| path == "/api/mcp/self"}-/// Routes only the person may call: saved passwords, answering an approval card, and the+/// 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/// this machine and would otherwise reach them with a bare `curl`. Turn tokens are refused by the/// handlers themselves (403).@@ -191,6 +191,7 @@ 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", "passwords", ..] => true,["", "api", "approvals", _, "resolve"] => *method == Method::POST,["", "api", "spaces" | "kwants", _, "approvals"] => *method != Method::GET && *method != Method::HEAD,_ => false,@@ -481,6 +482,10 @@ mod tests {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(&get, "/api/passwords/store"));+ assert!(person_only(&post, "/api/passwords/bitwarden/unlock"));+ assert!(person_only(&del, "/api/passwords/bitwarden"));+ assert!(person_only(&post, "/api/passwords/migrate"));assert!(person_only(&post, "/api/approvals/a1/resolve"));assert!(person_only(&put, "/api/spaces/s1/approvals"));assert!(person_only(&put, "/api/kwants/k1/approvals"));diff --git a/src/server/mod.rs b/src/server/mod.rsindex 10e54bfc..1ce4835f 100644--- a/src/server/mod.rs+++ b/src/server/mod.rs@@ -77,7 +77,7 @@ pub struct AppState {/// The MCP Registry agents search and suggest servers from (`KWNT_MCP_REGISTRY_URL`).pub mcp_registry: Arc<crate::mcp::registry::McpRegistry>,/// Saved website passwords, outside every bot's folder (see `sandbox::credentials`).- pub credentials: Arc<dyn crate::sandbox::CredentialStore>,+ pub credentials: Arc<crate::sandbox::vault::PasswordVault>,}impl AppState {@@ -117,7 +117,7 @@ impl AppState {questions: Default::default(),claude_login: Default::default(),mcp_registry: Arc::new(crate::mcp::registry::McpRegistry::from_env()),- credentials: crate::sandbox::credentials::open_store(&config_data_dir),+ credentials: Arc::new(crate::sandbox::vault::PasswordVault::open(&config_data_dir)),}}@@ -198,6 +198,11 @@ pub fn create_router(state: AppState) -> Router {.route("/api/sandbox/:team_id/passwords/pending", post(passwords::save_pending).delete(passwords::discard_pending)).route("/api/sandbox/:team_id/passwords/:id", delete(passwords::remove)).route("/api/sandbox/:team_id/passwords/:id/reveal", post(passwords::reveal))+ .route("/api/passwords/store", get(passwords::store_status))+ .route("/api/passwords/bitwarden", delete(passwords::forget_bitwarden))+ .route("/api/passwords/bitwarden/unlock", post(passwords::unlock_bitwarden))+ .route("/api/passwords/bitwarden/lock", post(passwords::lock_bitwarden))+ .route("/api/passwords/migrate", post(passwords::migrate_to_bitwarden)).route("/api/mcp/servers", get(mcp_routes::list_servers).post(mcp_routes::create_server)).route("/api/mcp/servers/:id",diff --git a/src/server/passwords.rs b/src/server/passwords.rsindex c18c87ea..c5bcabc0 100644--- a/src/server/passwords.rs+++ b/src/server/passwords.rs@@ -5,15 +5,35 @@//! created_at, last_used}], pending: null | {origin, username, captured_at}}`. No passwords.//! - `POST /api/sandbox/:id/passwords {origin | domain, username, password}` → `{status://! "saved", credential: {…metadata}}`. The password is not echoed.-//! - `POST /api/sandbox/:id/passwords/:cid/reveal` → `{password}` (no-store).+//! - `POST /api/sandbox/:id/passwords/:cid/reveal` → `{password}` (no-store). With Bitwarden+//! the body must be `{master_password}`: the API token sits in kwnt's data folder, where a bot+//! with approvals off can read it, so it alone never shows a password. Wrong → 401+//! `{wrong_password: true}`; after 5 in a row the vault locks.//! - `DELETE /api/sandbox/:id/passwords/:cid` → `{status: "deleted" | "not_found"}`.//! - `POST /api/sandbox/:id/passwords/pending` → saves the captured password the browser holds//! for confirmation → `{status: "saved", credential}`; 404 when there is none.//! - `DELETE /api/sandbox/:id/passwords/pending` → `{status: "discarded"}`.+//!+//! The vault (all owners):+//! - `GET /api/passwords/store` → [`store_json`].+//! - `POST /api/passwords/bitwarden/unlock {server_url?, email?, master_password, client_id?,+//! client_secret?, two_factor_provider?, two_factor_token?, new_device_otp?}` → the store+//! status. The first unlock sets Bitwarden up and makes it the store. 401 `{error, needs:+//! "two_factor", providers}` / `{needs: "new_device_otp"}` / `{wrong_password: true}`; 409+//! another account is set up; 400 bad input; 502 Bitwarden unreachable or refusing.+//! - `POST /api/passwords/bitwarden/lock` → the store status (locked).+//! - `DELETE /api/passwords/bitwarden {master_password}` → back to the built-in store; needs the+//! vault unlocked. Items stay in the person's Bitwarden.+//! - `POST /api/passwords/migrate` → `{moved, failed}`: every built-in saved password moves+//! into the unlocked Bitwarden vault, then is deleted locally.+//!+//! While Bitwarden is locked, the per-owner routes answer 423 `{error, locked: true}` and the+//! browser fills nothing.use super::AppState;use crate::db::spaces::SpaceId;-use crate::sandbox::credentials::{migrate_legacy, normalize_origin, CredentialMeta, StoreError};+use crate::sandbox::bitwarden::{UnlockError, UnlockRequest};+use crate::sandbox::credentials::{migrate_legacy, normalize_origin, CredentialMeta, CredentialStore, StoreError};use axum::{extract::{Path, State},http::{header, HeaderMap, HeaderValue, StatusCode},@@ -30,8 +50,21 @@ fn error(status: StatusCode, message: &str) -> Response {}fn unavailable(e: StoreError) -> Response {- tracing::warn!(error = %e, "saved-password store failed");- error(StatusCode::SERVICE_UNAVAILABLE, "saved passwords are unavailable right now")+ match e {+ StoreError::Locked => (+ StatusCode::LOCKED,+ Json(json!({"error": "the password vault is locked: unlock Bitwarden first", "locked": true})),+ )+ .into_response(),+ StoreError::Remote(m) => {+ tracing::warn!(error = %m, "Bitwarden failed");+ error(StatusCode::BAD_GATEWAY, "Bitwarden could not be reached or refused the change")+ }+ e => {+ tracing::warn!(error = %e, "saved-password store failed");+ error(StatusCode::SERVICE_UNAVAILABLE, "saved passwords are unavailable right now")+ }+ }}/// The team, channel or bot an id names, with its space. Ids only: names don't resolve here.@@ -63,7 +96,7 @@ async fn owner_or_404(state: &AppState, headers: &HeaderMap, id: &str) -> Result/// Moves a legacy `.saved_passwords.json` from the owner's old browser folder into the store.async fn migrate_owner(state: &AppState, owner: &str) {if let Some((_, folder)) = super::routes::resolve_sandbox_target_info(state, owner).await {- match migrate_legacy(state.credentials.as_ref(), &folder, &[owner]) {+ match migrate_legacy(state.credentials.as_ref(), &folder, &[owner]).await {Ok(0) => {}Ok(n) => tracing::info!(moved = n, "moved saved passwords out of a bot folder into the vault"),Err(e) => tracing::warn!(error = %e, "could not move a saved-passwords file into the vault"),@@ -74,14 +107,7 @@ async fn migrate_owner(state: &AppState, owner: &str) {/// On start: every legacy `.saved_passwords.json` under a team's, channel's or bot's browser/// folder moves into the vault (for every owner that shared the folder) and is deleted.pub async fn migrate_all(state: &AppState) {- let Ok(spaces) = state.db.list_spaces().await else { return };- let mut owners: Vec<String> = Vec::new();- for space in spaces {- let space = SpaceId::new(&space.id);- owners.extend(state.db.list_teams(&space).await.unwrap_or_default().into_iter().map(|t| t.id));- owners.extend(state.db.list_channels(&space).await.unwrap_or_default().into_iter().map(|c| c.id));- owners.extend(state.db.list_kwants(&space).await.unwrap_or_default().into_iter().map(|k| k.id));- }+ let owners = all_owners(state).await;let mut by_folder: std::collections::BTreeMap<std::path::PathBuf, Vec<String>> = Default::default();for owner in owners {if let Some((_, folder)) = super::routes::resolve_sandbox_target_info(state, &owner).await {@@ -90,7 +116,7 @@ pub async fn migrate_all(state: &AppState) {}for (folder, owners) in by_folder {let refs: Vec<&str> = owners.iter().map(String::as_str).collect();- match migrate_legacy(state.credentials.as_ref(), &folder, &refs) {+ match migrate_legacy(state.credentials.as_ref(), &folder, &refs).await {Ok(0) => {}Ok(n) => tracing::info!(moved = n, folder = %folder.display(), "moved saved passwords into the vault"),Err(e) => tracing::warn!(error = %e, folder = %folder.display(), "could not move saved passwords into the vault"),@@ -98,6 +124,19 @@ pub async fn migrate_all(state: &AppState) {}}+/// Every team, channel and bot id: the owners saved passwords can belong to.+async fn all_owners(state: &AppState) -> Vec<String> {+ let Ok(spaces) = state.db.list_spaces().await else { return Vec::new() };+ let mut owners: Vec<String> = Vec::new();+ for space in spaces {+ let space = SpaceId::new(&space.id);+ owners.extend(state.db.list_teams(&space).await.unwrap_or_default().into_iter().map(|t| t.id));+ owners.extend(state.db.list_channels(&space).await.unwrap_or_default().into_iter().map(|c| c.id));+ owners.extend(state.db.list_kwants(&space).await.unwrap_or_default().into_iter().map(|k| k.id));+ }+ owners+}+fn meta_json(m: &CredentialMeta) -> Value {let domain = url::Url::parse(&m.origin).ok().and_then(|u| u.host_str().map(str::to_string)).unwrap_or_default();json!({@@ -121,7 +160,7 @@ pub async fn list(State(state): State<AppState>, headers: HeaderMap, Path(id): POk(o) => o,Err(r) => return r,};- let list = match state.credentials.list(&owner) {+ let list = match state.credentials.list(&owner).await {Ok(l) => l,Err(e) => return unavailable(e),};@@ -161,18 +200,62 @@ pub async fn save(let Ok(origin) = normalize_origin(&source) else {return error(StatusCode::BAD_REQUEST, "origin must be an http(s) address like https://example.com");};- match state.credentials.save(&owner, &origin, body.username.trim(), &body.password) {+ match state.credentials.save(&owner, &origin, body.username.trim(), &body.password).await {Ok(meta) => Json(json!({"status": "saved", "credential": meta_json(&meta)})).into_response(),Err(e) => unavailable(e),}}-pub async fn reveal(State(state): State<AppState>, headers: HeaderMap, Path((id, cid)): Path<(String, String)>) -> Response {+#[derive(Deserialize, Default)]+pub struct MasterPassword {+ #[serde(default)]+ pub master_password: String,+}++impl Drop for MasterPassword {+ fn drop(&mut self) {+ zeroize::Zeroize::zeroize(&mut self.master_password);+ }+}++fn master_password_of(body: &[u8]) -> MasterPassword {+ serde_json::from_slice(body).unwrap_or_default()+}++/// With Bitwarden, the master password the person typed must match before a password is shown+/// or the account is forgotten. `Err` is the response to send.+#[allow(clippy::result_large_err)]+async fn check_master_password(state: &AppState, given: &MasterPassword) -> Result<(), Response> {+ let bw = state.credentials.bitwarden();+ if given.master_password.is_empty() {+ return Err(error(StatusCode::UNAUTHORIZED, "type the Bitwarden master password"));+ }+ match bw.verify_master_password(&given.master_password).await {+ Ok(true) => Ok(()),+ Ok(false) => {+ tracing::warn!("a wrong Bitwarden master password was given");+ Err((StatusCode::UNAUTHORIZED, Json(json!({"error": "wrong master password", "wrong_password": true}))).into_response())+ }+ Err(e) => Err(unavailable(e)),+ }+}++pub async fn reveal(+ State(state): State<AppState>,+ headers: HeaderMap,+ Path((id, cid)): Path<(String, String)>,+ body: axum::body::Bytes,+) -> Response {let owner = match owner_or_404(&state, &headers, &id).await {Ok(o) => o,Err(r) => return r,};- match state.credentials.get(&owner, &cid) {+ if state.credentials.store_name() == "bitwarden" {+ if let Err(r) = check_master_password(&state, &master_password_of(&body)).await {+ return r;+ }+ }+ match state.credentials.get(&owner, &cid).await {Ok(Some(c)) => {tracing::info!(owner = %owner, credential = %cid, "the person revealed a saved password");let mut resp = Json(json!({"password": c.password})).into_response();@@ -189,7 +272,7 @@ pub async fn remove(State(state): State<AppState>, headers: HeaderMap, Path((id,Ok(o) => o,Err(r) => return r,};- match state.credentials.delete(&owner, &cid) {+ match state.credentials.delete(&owner, &cid).await {Ok(removed) => Json(json!({"status": if removed { "deleted" } else { "not_found" }})).into_response(),Err(e) => unavailable(e),}@@ -206,9 +289,13 @@ pub async fn save_pending(State(state): State<AppState>, headers: HeaderMap, Patlet Some(p) = ctrl.take_pending().await else {return error(StatusCode::NOT_FOUND, "no password is waiting to be saved");};- match state.credentials.save(&owner, &p.origin, &p.username, &p.password) {+ match state.credentials.save(&owner, &p.origin, &p.username, &p.password).await {Ok(meta) => Json(json!({"status": "saved", "credential": meta_json(&meta)})).into_response(),- Err(e) => unavailable(e),+ Err(e) => {+ // Locked or offline: keep it waiting so the person can save it after unlocking+ ctrl.hold_for_confirmation(p).await;+ unavailable(e)+ }}}@@ -222,3 +309,97 @@ pub async fn discard_pending(State(state): State<AppState>, headers: HeaderMap,}Json(json!({"status": "discarded"})).into_response()}++/// `{store: "local" | "bitwarden", locked, bitwarden: null | {server_url, email, login:+/// "password" | "api_key", client_id, unlocked, unlocked_at, item_count, last_sync},+/// local_count}`. `local_count` is how many passwords the built-in store still holds (what+/// `migrate` would move).+async fn store_json(state: &AppState) -> Value {+ let vault = &state.credentials;+ let owners = all_owners(state).await;+ json!({+ "store": vault.store_name(),+ "locked": vault.is_locked().await,+ "bitwarden": vault.bitwarden().status().await,+ "local_count": vault.local_count(&owners).await,+ })+}++#[allow(clippy::result_large_err)]+async fn person(state: &AppState, headers: &HeaderMap) -> Result<(), Response> {+ super::mcp_suggest::refuse_agent_tokens(state, headers, REFUSAL).await+}++pub async fn store_status(State(state): State<AppState>, headers: HeaderMap) -> Response {+ if let Err(r) = person(&state, &headers).await {+ return r;+ }+ Json(store_json(&state).await).into_response()+}++pub async fn unlock_bitwarden(State(state): State<AppState>, headers: HeaderMap, body: axum::body::Bytes) -> Response {+ if let Err(r) = person(&state, &headers).await {+ return r;+ }+ let Ok(req) = serde_json::from_slice::<UnlockRequest>(&body) else {+ return error(StatusCode::BAD_REQUEST, "send {master_password} (and server_url and email the first time)");+ };+ drop(body);+ match state.credentials.bitwarden().unlock(req).await {+ Ok(_) => Json(store_json(&state).await).into_response(),+ Err(e) => {+ let message = e.to_string();+ let (status, extra) = match e {+ UnlockError::Wrong => (StatusCode::UNAUTHORIZED, json!({"wrong_password": true})),+ UnlockError::TwoFactor(providers) => (StatusCode::UNAUTHORIZED, json!({"needs": "two_factor", "providers": providers})),+ UnlockError::NewDeviceOtp => (StatusCode::UNAUTHORIZED, json!({"needs": "new_device_otp"})),+ UnlockError::OtherAccount => (StatusCode::CONFLICT, json!({})),+ UnlockError::Invalid(_) | UnlockError::Unsupported(_) => (StatusCode::BAD_REQUEST, json!({})),+ UnlockError::Unreachable(_) | UnlockError::Server(_) => (StatusCode::BAD_GATEWAY, json!({})),+ };+ tracing::warn!(error = %message, "Bitwarden unlock failed");+ let mut body = extra;+ body["error"] = json!(message);+ (status, Json(body)).into_response()+ }+ }+}++pub async fn lock_bitwarden(State(state): State<AppState>, headers: HeaderMap) -> Response {+ if let Err(r) = person(&state, &headers).await {+ return r;+ }+ state.credentials.bitwarden().lock().await;+ tracing::info!("the person locked Bitwarden");+ Json(store_json(&state).await).into_response()+}++pub async fn forget_bitwarden(State(state): State<AppState>, headers: HeaderMap, body: axum::body::Bytes) -> Response {+ if let Err(r) = person(&state, &headers).await {+ return r;+ }+ if !state.credentials.bitwarden().is_configured() {+ return Json(store_json(&state).await).into_response();+ }+ if let Err(r) = check_master_password(&state, &master_password_of(&body)).await {+ return r;+ }+ if let Err(e) = state.credentials.bitwarden().forget().await {+ return unavailable(e);+ }+ Json(store_json(&state).await).into_response()+}++pub async fn migrate_to_bitwarden(State(state): State<AppState>, headers: HeaderMap) -> Response {+ if let Err(r) = person(&state, &headers).await {+ return r;+ }+ let owners = all_owners(&state).await;+ match state.credentials.move_local_to_bitwarden(&owners).await {+ Ok(done) => {+ tracing::info!(moved = done.moved, failed = done.failed, "the person moved saved passwords to Bitwarden");+ Json(json!(done)).into_response()+ }+ Err(e) => unavailable(e),+ }+}diff --git a/tests/bitwarden_test.rs b/tests/bitwarden_test.rsnew file mode 100644index 00000000..52fe1d55--- /dev/null+++ b/tests/bitwarden_test.rs@@ -0,0 +1,379 @@+//! Saved passwords in the person's Bitwarden vault (`sandbox::bitwarden`).+//!+//! The vault routes are the person's only: no token 401, a bot's turn token 403. The rest runs+//! against a real Bitwarden-compatible server when `KWNT_TEST_VAULTWARDEN` names one, e.g. a+//! throwaway Vaultwarden with signups open:+//!+//! ```sh+//! docker run -d --rm --name kwnt-bwtest -p 127.0.0.1:18990:80 -e SIGNUPS_ALLOWED=true vaultwarden/server+//! KWNT_TEST_VAULTWARDEN=http://127.0.0.1:18990 cargo test --test bitwarden_test+//! ```+//!+//! Without it those tests pass without doing anything (and say so).++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::{bitwarden, browser::BrowserController, credentials::CredentialStore, PendingCapture},+ 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,+ data: PathBuf,+ _tmp: TempDir,+}++fn config_for(data: &Path) -> Config {+ Config { data_dir: data.to_path_buf(), browser_cdp_url: Some("http://127.0.0.1:9".into()), ..Config::default() }+}++async fn setup_at(tmp: TempDir) -> Env {+ let data = tmp.path().join("data");+ let db = Database::init(&data).await.unwrap();+ let config = config_for(&data);+ 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, data, _tmp: tmp }+}++async fn setup() -> Env {+ setup_at(tempdir().unwrap()).await+}++async fn call(app: &Router, method: &str, uri: &str, bearer: 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) = bearer {+ 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();+ let bytes = to_bytes(resp.into_body(), usize::MAX).await.unwrap();+ (status, serde_json::from_slice(&bytes).unwrap_or(Value::Null))+}++impl Env {+ async fn person(&self, method: &str, uri: &str, body: Option<Value>) -> (StatusCode, Value) {+ call(&self.app, method, uri, Some(self.state.api_token.reveal()), body).await+ }+ async fn team(&self, name: &str) -> String {+ let bot = self.state.db.list_kwants(&SpaceId::default_space()).await.unwrap().remove(0);+ let team = NewTeam {+ name: name.into(),+ description: None,+ icon: None,+ lead_kwant_id: bot.id.clone(),+ member_kwants: vec![bot.id],+ workspace_path: None,+ repo_url: None,+ };+ self.state.db.create_team(&SpaceId::default_space(), &team).await.unwrap().id+ }+ async fn turn_token(&self, folder: &Path) -> String {+ let bot = self.state.db.list_kwants(&SpaceId::default_space()).await.unwrap().remove(0);+ let scope = SelfScope { kwant_id: bot.id.clone(), kwant_name: bot.name.clone(), ..Default::default() };+ mcp_runtime::prepare_turn_with_self(&self.state, &bot, None, Some(folder.to_path_buf()), Some(scope))+ .await+ .unwrap()+ .1+ }+}++fn files_under(dir: &Path) -> Vec<PathBuf> {+ let mut out = Vec::new();+ for e in std::fs::read_dir(dir).into_iter().flatten().flatten() {+ let p = e.path();+ if p.is_dir() {+ out.extend(files_under(&p));+ } else {+ out.push(p);+ }+ }+ out+}++fn no_file_contains(dir: &Path, needle: &str) {+ for f in files_under(dir) {+ let bytes = std::fs::read(&f).unwrap_or_default();+ assert!(!String::from_utf8_lossy(&bytes).contains(needle), "{needle} in clear in {}", f.display());+ }+}++#[tokio::test]+async fn vault_routes_are_the_persons_only() {+ let e = setup().await;+ let folder = tempdir().unwrap();+ let turn = e.turn_token(folder.path()).await;+ let routes: Vec<(&str, &str, Option<Value>)> = vec![+ ("GET", "/api/passwords/store", None),+ ("POST", "/api/passwords/bitwarden/unlock", Some(json!({"server_url": "http://127.0.0.1:9", "email": "[email protected]", "master_password": "DUMMY"}))),+ ("POST", "/api/passwords/bitwarden/lock", None),+ ("DELETE", "/api/passwords/bitwarden", Some(json!({"master_password": "DUMMY"}))),+ ("POST", "/api/passwords/migrate", None),+ ];+ for (method, uri, body) in &routes {+ let (s, v) = call(&e.app, method, uri, None, body.clone()).await;+ assert_eq!(s, StatusCode::UNAUTHORIZED, "{method} {uri} without a token: {v}");+ let (s, v) = call(&e.app, method, uri, Some(&turn), body.clone()).await;+ assert_eq!(s, StatusCode::FORBIDDEN, "{method} {uri} with a bot's turn token: {v}");+ }+ let (s, v) = e.person("GET", "/api/passwords/store", None).await;+ assert_eq!(s, StatusCode::OK);+ assert_eq!(v["store"], "local");+ assert_eq!(v["locked"], false);+ assert_eq!(v["bitwarden"], Value::Null);+ // Not set up: nothing to lock, forget or move into+ let (s, _) = e.person("POST", "/api/passwords/migrate", None).await;+ assert_eq!(s, StatusCode::LOCKED);+ // A plain-http server elsewhere is refused before anything is sent+ let (s, v) = e+ .person("POST", "/api/passwords/bitwarden/unlock", Some(json!({"server_url": "http://pw.example.org", "email": "[email protected]", "master_password": "DUMMY"})))+ .await;+ assert_eq!(s, StatusCode::BAD_REQUEST, "{v}");+ assert!(!e.data.join("kwnt-vault").join(bitwarden::CONFIG_FILE).exists());+}++fn server() -> Option<String> {+ let s = std::env::var("KWNT_TEST_VAULTWARDEN").ok().filter(|s| !s.is_empty());+ if s.is_none() {+ eprintln!("KWNT_TEST_VAULTWARDEN is not set: skipping the live Bitwarden test");+ }+ s+}++const MASTER: &str = "DUMMY-master-pw-kwnt-test";++async fn new_account(server: &str) -> String {+ let email = format!("kwnt-{}@kwnt.test", uuid::Uuid::new_v4().simple());+ // Vaultwarden's minimum; real accounts use 600000+ bitwarden::register_test_account(server, &email, MASTER, 100_000).await.expect("register a throwaway account");+}++/// The person unlocks, passwords are saved, filled on the exact origin only, survive in the+/// vault, and after a restart nothing is filled until the person unlocks again. Nothing that+/// unlocks the vault, and no saved password, is ever written under kwnt's data folder.+#[tokio::test]+async fn bitwarden_end_to_end() {+ let Some(server) = server() else { return };+ let email = new_account(&server).await;+ let tmp = tempdir().unwrap();+ let tmp_path = tmp.path().to_path_buf();+ let e = setup_at(tmp).await;+ let team = e.team("bwteam").await;++ // A local password from before Bitwarden+ let (s, _) = e+ .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);++ // Wrong master password+ let unlock = |pw: &str| json!({"server_url": server, "email": email, "master_password": pw});+ let (s, v) = e.person("POST", "/api/passwords/bitwarden/unlock", Some(unlock("DUMMY-wrong"))).await;+ assert_eq!(s, StatusCode::UNAUTHORIZED, "{v}");+ assert_eq!(v["wrong_password"], true);+ assert!(!e.data.join("kwnt-vault").join(bitwarden::CONFIG_FILE).exists(), "nothing set up on a failed unlock");++ let (s, v) = e.person("POST", "/api/passwords/bitwarden/unlock", Some(unlock(MASTER))).await;+ assert_eq!(s, StatusCode::OK, "{v}");+ assert_eq!(v["store"], "bitwarden");+ assert_eq!(v["locked"], false);+ assert_eq!(v["bitwarden"]["email"], email);+ assert_eq!(v["bitwarden"]["unlocked"], true);+ assert_eq!(v["bitwarden"]["login"], "password");+ assert_eq!(v["local_count"], 1);++ // Another account can't replace it without forgetting this one+ let (s, _) = e+ .person("POST", "/api/passwords/bitwarden/unlock", Some(json!({"server_url": server, "email": "[email protected]", "master_password": MASTER})))+ .await;+ assert_eq!(s, StatusCode::CONFLICT);++ // Move the local one over+ let (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);++ // Save one through the API and one the browser captured+ let uri = format!("/api/sandbox/{team}/passwords");+ let (s, v) = e.person("POST", &uri, Some(json!({"origin": "https://login.example.com/x", "username": "alice", "password": "DUMMY-BW-PW-1"}))).await;+ assert_eq!(s, StatusCode::OK, "{v}");+ let cid = v["credential"]["id"].as_str().unwrap().to_string();+ let ctrl = BrowserController::new(9);+ e.state.browser_controllers.lock().await.insert(team.clone(), ctrl.clone());+ ctrl.hold_for_confirmation(PendingCapture {+ origin: "https://shop.example.com".into(),+ username: "bob".into(),+ password: "DUMMY-BW-PW-2".into(),+ captured_at: "2026-10-20T00:00:00Z".into(),+ })+ .await;+ let (s, v) = e.person("POST", &format!("{uri}/pending"), None).await;+ assert_eq!(s, StatusCode::OK, "{v}");++ let (_, v) = e.person("GET", &uri, None).await;+ let origins: Vec<&str> = v["passwords"].as_array().unwrap().iter().map(|p| p["origin"].as_str().unwrap()).collect();+ assert_eq!(origins.len(), 3, "{v}");+ for o in ["https://old.example.com", "https://login.example.com", "https://shop.example.com"] {+ assert!(origins.contains(&o), "{o} in {v}");+ }+ assert!(!v.to_string().contains("DUMMY"), "metadata only: {v}");++ // Exact origin only+ let vault = &e.state.credentials;+ assert_eq!(vault.for_origin(&team, "https://login.example.com/other").await.unwrap().unwrap().password, "DUMMY-BW-PW-1");+ assert!(vault.for_origin(&team, "https://evil.login.example.com").await.unwrap().is_none());+ assert!(vault.for_origin(&team, "http://login.example.com").await.unwrap().is_none());+ assert!(vault.for_origin("another-owner", "https://login.example.com").await.unwrap().is_none());++ // Reveal needs the master password, not just the API token+ let reveal = format!("{uri}/{cid}/reveal");+ let (s, v) = e.person("POST", &reveal, None).await;+ assert_eq!(s, StatusCode::UNAUTHORIZED, "{v}");+ assert!(!v.to_string().contains("DUMMY-BW"));+ let (s, v) = e.person("POST", &reveal, Some(json!({"master_password": MASTER}))).await;+ assert_eq!(s, StatusCode::OK, "{v}");+ assert_eq!(v["password"], "DUMMY-BW-PW-1");++ // An update keeps one item+ let (s, _) = e.person("POST", &uri, Some(json!({"origin": "https://login.example.com", "username": "alice", "password": "DUMMY-BW-PW-1b"}))).await;+ assert_eq!(s, StatusCode::OK);+ let (_, v) = e.person("GET", &uri, None).await;+ assert_eq!(v["passwords"].as_array().unwrap().len(), 3);++ // Nothing secret on disk: no password, master password, or token+ no_file_contains(&tmp_path, "DUMMY-BW-PW");+ no_file_contains(&tmp_path, "DUMMY-LOCAL-PW");+ no_file_contains(&tmp_path, MASTER);+ let cfg = std::fs::read_to_string(e.data.join("kwnt-vault").join(bitwarden::CONFIG_FILE)).unwrap();+ let cfg: Value = serde_json::from_str(&cfg).unwrap();+ let mut keys: Vec<&str> = cfg.as_object().unwrap().keys().map(String::as_str).collect();+ keys.sort();+ assert_eq!(keys, vec!["client_id", "device_id", "email", "server_url"], "{cfg}");++ // A restart: the vault is locked, nothing is filled or listed+ let restarted = kwnt::sandbox::vault::PasswordVault::open(&e.data);+ assert!(restarted.is_locked().await);+ assert!(restarted.for_origin(&team, "https://login.example.com").await.unwrap().is_none());+ assert!(restarted.list(&team).await.is_err());++ // Lock through the API: same+ let (s, v) = e.person("POST", "/api/passwords/bitwarden/lock", None).await;+ assert_eq!(s, StatusCode::OK);+ assert_eq!(v["locked"], true);+ assert_eq!(v["bitwarden"]["unlocked"], false);+ assert!(vault.for_origin(&team, "https://login.example.com").await.unwrap().is_none());+ let (s, v) = e.person("GET", &uri, None).await;+ assert_eq!(s, StatusCode::LOCKED, "{v}");+ assert_eq!(v["locked"], true);+ // A capture made while locked waits instead of being lost+ ctrl.hold_for_confirmation(PendingCapture {+ origin: "https://later.example.com".into(),+ username: "carol".into(),+ password: "DUMMY-BW-PW-3".into(),+ captured_at: "2026-10-20T00:00:00Z".into(),+ })+ .await;+ let (s, _) = e.person("POST", &format!("{uri}/pending"), None).await;+ assert_eq!(s, StatusCode::LOCKED);+ assert!(ctrl.pending().await.is_some(), "the capture still waits");++ // Unlock again (the saved server and email are reused) and the items are back+ let (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!(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 it+ let (s, v) = e.person("DELETE", &format!("{uri}/{cid}"), None).await;+ assert_eq!(s, StatusCode::OK);+ assert_eq!(v["status"], "deleted");+ assert!(vault.for_origin(&team, "https://login.example.com").await.unwrap().is_none());++ // Forget needs the master password+ let (s, _) = e.person("DELETE", "/api/passwords/bitwarden", Some(json!({"master_password": "DUMMY-wrong"}))).await;+ assert_eq!(s, StatusCode::UNAUTHORIZED);+ let (s, v) = e.person("DELETE", "/api/passwords/bitwarden", Some(json!({"master_password": MASTER}))).await;+ assert_eq!(s, StatusCode::OK, "{v}");+ assert_eq!(v["store"], "local");+ assert_eq!(v["bitwarden"], Value::Null);+ assert!(!e.data.join("kwnt-vault").join(bitwarden::CONFIG_FILE).exists());+}++/// Five wrong master passwords in a row on reveal lock the vault.+#[tokio::test]+async fn wrong_master_passwords_lock_the_vault() {+ let Some(server) = server() else { return };+ let email = new_account(&server).await;+ let e = setup().await;+ let team = e.team("bwlock").await;+ let (s, v) = e+ .person("POST", "/api/passwords/bitwarden/unlock", Some(json!({"server_url": server, "email": email, "master_password": MASTER})))+ .await;+ assert_eq!(s, StatusCode::OK, "{v}");+ let uri = format!("/api/sandbox/{team}/passwords");+ let (_, v) = e.person("POST", &uri, Some(json!({"origin": "https://a.example.com", "username": "u", "password": "DUMMY-LOCKOUT"}))).await;+ let reveal = format!("{uri}/{}/reveal", v["credential"]["id"].as_str().unwrap());+ for _ in 0..bitwarden::MAX_WRONG_PASSWORDS - 1 {+ let (s, _) = e.person("POST", &reveal, Some(json!({"master_password": "DUMMY-guess"}))).await;+ assert_eq!(s, StatusCode::UNAUTHORIZED);+ }+ // A right one resets the count+ let (s, _) = e.person("POST", &reveal, Some(json!({"master_password": MASTER}))).await;+ assert_eq!(s, StatusCode::OK);+ for _ in 0..bitwarden::MAX_WRONG_PASSWORDS - 1 {+ let (s, _) = e.person("POST", &reveal, Some(json!({"master_password": "DUMMY-guess"}))).await;+ assert_eq!(s, StatusCode::UNAUTHORIZED);+ }+ let (s, v) = e.person("POST", &reveal, Some(json!({"master_password": "DUMMY-guess"}))).await;+ assert_eq!(s, StatusCode::LOCKED, "the fifth wrong one locks: {v}");+ assert!(e.state.credentials.is_locked().await);+ let (s, _) = e.person("POST", &reveal, Some(json!({"master_password": MASTER}))).await;+ assert_eq!(s, StatusCode::LOCKED, "locked until the person unlocks again");+}++/// kwnt holds the unlocked vault key in memory, so a same-user bot must not read its memory or+/// environment: `PR_SET_DUMPABLE` 0 makes `/proc/<kwnt>/{environ,mem,…}` root's.+#[cfg(target_os = "linux")]+#[test]+fn kwnt_is_not_dumpable() {+ use std::io::BufRead;+ use std::os::unix::fs::MetadataExt;+ let mut child = std::process::Command::new(env!("CARGO_BIN_EXE_kwnt"))+ .args(["mcp-oauth-mock-server", "--port", "0"])+ .stdout(std::process::Stdio::piped())+ .spawn()+ .unwrap();+ // Running, past main's start: it prints its address once listening+ let mut line = String::new();+ std::io::BufReader::new(child.stdout.take().unwrap()).read_line(&mut line).unwrap();+ assert!(line.contains("mock OAuth MCP server"), "{line}");+ let proc_dir = PathBuf::from(format!("/proc/{}", child.id()));+ let environ = std::fs::metadata(proc_dir.join("environ")).unwrap();+ let readable = std::fs::read(proc_dir.join("environ")).is_ok();+ child.kill().unwrap();+ child.wait().unwrap();+ assert_eq!(environ.uid(), 0, "/proc/<kwnt>/environ belongs to root");+ assert!(!readable, "kwnt's environment is unreadable to its own user");+}diff --git a/tests/browser_test.rs b/tests/browser_test.rsindex a8563e84..eef23fbb 100644--- a/tests/browser_test.rs+++ b/tests/browser_test.rs@@ -499,21 +499,21 @@ async fn test_browser_credential_vault_lifecycle() {let store = open_store(data.path());let controller = BrowserController::new(19222);controller.attach_vault(store.clone(), "team-1").await;- assert_eq!(store.list("team-1").unwrap().len(), 0);+ assert_eq!(store.list("team-1").await.unwrap().len(), 0);- let meta = store.save("team-1", "https://github.com", "dev_user", "DUMMY-secret_pass_123").unwrap();+ let meta = store.save("team-1", "https://github.com", "dev_user", "DUMMY-secret_pass_123").await.unwrap();assert_eq!(meta.origin, "https://github.com");assert_eq!(meta.username, "dev_user");- let list = store.list("team-1").unwrap();+ let list = store.list("team-1").await.unwrap();assert_eq!(list.len(), 1);assert_eq!(list[0].id, meta.id);// Exact origin only- assert!(store.for_origin("team-1", "https://github.com").unwrap().is_some());- assert!(store.for_origin("team-1", "http://github.com").unwrap().is_none());- assert!(store.for_origin("team-1", "https://gist.github.com").unwrap().is_none());- assert!(store.for_origin("team-2", "https://github.com").unwrap().is_none());+ assert!(store.for_origin("team-1", "https://github.com").await.unwrap().is_some());+ assert!(store.for_origin("team-1", "http://github.com").await.unwrap().is_none());+ assert!(store.for_origin("team-1", "https://gist.github.com").await.unwrap().is_none());+ assert!(store.for_origin("team-2", "https://github.com").await.unwrap().is_none());// Nothing on disk in clearfor entry in walk(data.path()) {@@ -524,9 +524,9 @@ async fn test_browser_credential_vault_lifecycle() {// A fresh store on the same data dir reads them backlet reopened = open_store(data.path());- assert_eq!(reopened.get("team-1", &meta.id).unwrap().unwrap().password, "DUMMY-secret_pass_123");- assert!(reopened.delete("team-1", &meta.id).unwrap());- assert_eq!(reopened.list("team-1").unwrap().len(), 0);+ assert_eq!(reopened.get("team-1", &meta.id).await.unwrap().unwrap().password, "DUMMY-secret_pass_123");+ assert!(reopened.delete("team-1", &meta.id).await.unwrap());+ assert_eq!(reopened.list("team-1").await.unwrap().len(), 0);}fn walk(dir: &std::path::Path) -> Vec<std::path::PathBuf> {@@ -716,7 +716,7 @@ async fn autofill_goes_only_to_the_exact_origin_in_kwnts_own_world() {use kwnt::sandbox::credentials::open_store;let data = tempfile::tempdir().unwrap();let store = open_store(data.path());- store.save("team-1", "https://example.com", "alice", "DUMMY-F5-PW").unwrap();+ store.save("team-1", "https://example.com", "alice", "DUMMY-F5-PW").await.unwrap();let url = Arc::new(tokio::sync::Mutex::new(String::new()));let (port, recorded) = fake_page(url.clone(), Value::Null).await;let ctrl = BrowserController::new(port);@@ -762,8 +762,8 @@ async fn a_capture_is_filed_under_the_real_origin_and_waits() {assert_eq!(capture.username, "admin");assert!(!serde_json::to_string(&capture).unwrap().contains("DUMMY-FORGED"), "the password isn't serialized");assert!(!format!("{capture:?}").contains("DUMMY-FORGED"));- assert!(store.list("team-1").unwrap().is_empty(), "nothing saved without the person");- assert!(store.for_origin("team-1", "https://victim.test").unwrap().is_none());+ assert!(store.list("team-1").await.unwrap().is_empty(), "nothing saved without the person");+ assert!(store.for_origin("team-1", "https://victim.test").await.unwrap().is_none());assert_eq!(ctrl.pending().await.unwrap().origin, "https://attacker.test");let evals: Vec<Value> = recorded.lock().await.iter().filter(|(m, _)| m == "Runtime.evaluate").map(|(_, p)| p.clone()).collect();assert!(evals.iter().all(|p| p["contextId"] == 77), "{evals:?}");