Skip to content

armgit / kwant

Public Imported from GitHub
0

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

0.7.3: built-in password store is a warning, not a wall; Bitwarden salt fix (#370)

Oleksandr Ivanchenko4624cb509152
diff --git a/CHANGELOG.md b/CHANGELOG.md
index d0e1afb3..38da3be3 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -14,8 +14,10 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
### Changed
- **Dev mode reads commit history with git, not GitHub's API.** Each watched repo gets a copy in kwant's data folder, up to 1 GB each; a bigger repo reads "Too big to read". Repo addresses that point at this server, link-local addresses or cloud metadata addresses are refused, and https reads are pinned to the address that was checked. A team folder whose .git points somewhere else is refused. GitHub PRs, checks and logins still come from GitHub. (#366)
+- **Saving a password on this server no longer dead-ends.** An archived space, and the bots in it, no longer count as "Ask only when risky" or "Don't ask", so they don't block saving passwords. When a space or bot that doesn't ask is still active, you can choose to save the password on this server anyway. You make that choice once for the server, and a bot can never make it for you. The warning that such passwords are exposed stays. Restoring an archived space that doesn't ask needs the same choice.
### Fixed
+- **Connecting Bitwarden works with accounts whose key salt isn't their email.** kwant now uses the salt Bitwarden's server reports, and also reads the account key from Bitwarden's newer login reply. Each failed connect or unlock logs one line with what went wrong, the HTTP status and the server's host. That line never includes the email, password or codes.
- A custom server's models that have no name now show their id in the model picker instead of "[redacted]" (#365).
## [Mac 0.7.2] - 2026-11-06
diff --git a/src/db/approval_modes.rs b/src/db/approval_modes.rs
index 8c04f949..e718d2ae 100644
--- a/src/db/approval_modes.rs
+++ b/src/db/approval_modes.rs
@@ -149,11 +149,15 @@ impl Database {
/// Whether approvals are off, or only ask when risky, for any existing space or bot. Both let
/// a bot run code without a card, so both keep passwords out of the built-in store. A space
/// counts even when every bot in it overrides to `ask`: a new bot there would inherit it.
+ /// An archived space and the bots in it don't count (0.7.3 A1): nothing runs there, and its
+ /// approvals can't be changed until it is restored, which would leave the gate shut for good.
pub async fn any_approvals_off(&self) -> Result<bool, DbError> {
let row: Option<(i64,)> = sqlx::query_as(
"SELECT 1 FROM approval_modes WHERE mode IN ('off', 'smart') AND (
- (scope = 'space' AND id IN (SELECT id FROM spaces))
- OR (scope = 'kwant' AND id IN (SELECT id FROM kwants))
+ (scope = 'space' AND id IN (SELECT id FROM spaces WHERE archived_at IS NULL))
+ OR (scope = 'kwant' AND id IN (
+ SELECT k.id FROM kwants k JOIN spaces s ON s.id = k.space_id WHERE s.archived_at IS NULL
+ ))
) LIMIT 1",
)
.fetch_optional(&self.pool)
@@ -161,6 +165,21 @@ impl Database {
Ok(row.is_some())
}
+ /// Whether `space` itself, or a bot in it, is on approvals off or "Ask only when risky",
+ /// archived or not: what restoring it would bring back into [`Self::any_approvals_off`].
+ pub async fn space_approvals_off(&self, space: &SpaceId) -> Result<bool, DbError> {
+ let row: Option<(i64,)> = sqlx::query_as(
+ "SELECT 1 FROM approval_modes WHERE mode IN ('off', 'smart') AND (
+ (scope = 'space' AND id = ?1)
+ OR (scope = 'kwant' AND id IN (SELECT id FROM kwants WHERE space_id = ?1))
+ ) LIMIT 1",
+ )
+ .bind(space.as_str())
+ .fetch_optional(&self.pool)
+ .await?;
+ Ok(row.is_some())
+ }
+
/// A bot's approvals in `space`: its override, else the space's.
pub async fn kwant_approvals_in(&self, space: &SpaceId, kwant_id: &str) -> Result<ApprovalMode, DbError> {
let space_mode = self.space_approvals(space).await?;
diff --git a/src/sandbox/bitwarden.rs b/src/sandbox/bitwarden.rs
index 859d0f75..06a8f34b 100644
--- a/src/sandbox/bitwarden.rs
+++ b/src/sandbox/bitwarden.rs
@@ -66,6 +66,23 @@ pub enum UnlockError {
Unsupported(String),
}
+impl UnlockError {
+ /// A short name for the log line of a failed unlock (spec C3); never the message, which can
+ /// quote the server.
+ pub fn kind(&self) -> &'static str {
+ match self {
+ UnlockError::Wrong => "wrong",
+ UnlockError::TwoFactor(_) => "two_factor",
+ UnlockError::NewDeviceOtp => "new_device_otp",
+ UnlockError::OtherAccount => "other_account",
+ UnlockError::Invalid(_) => "invalid",
+ UnlockError::Unreachable(_) => "unreachable",
+ UnlockError::Server(_) => "server",
+ UnlockError::Unsupported(_) => "unsupported",
+ }
+ }
+}
+
#[derive(Debug)]
struct CryptoFail;
@@ -158,16 +175,32 @@ pub enum Kdf {
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.
+ /// kwnt spend minutes or gigabytes on one unlock. The flat `kdf`/`kdfIterations` members, else
+ /// a nested `kdfSettings` object (newer servers).
pub fn from_json(v: &Value) -> Result<Self, UnlockError> {
+ if field(v, "kdfIterations").is_none() {
+ if let Some(settings) = field(v, "kdfSettings") {
+ return Self::from_settings(settings);
+ }
+ }
+ Self::parse(v, ["kdf", "kdfIterations", "kdfMemory", "kdfParallelism"])
+ }
+
+ /// From a `{kdfType, iterations, memory, parallelism}` object: prelogin's `kdfSettings`, or
+ /// the token response's `UserDecryptionOptions.MasterPasswordUnlock.Kdf`.
+ pub fn from_settings(v: &Value) -> Result<Self, UnlockError> {
+ Self::parse(v, ["kdfType", "iterations", "memory", "parallelism"])
+ }
+
+ fn parse(v: &Value, [kind, iters, memory, parallel]: [&str; 4]) -> 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) {
+ let iterations = num(iters).ok_or_else(|| UnlockError::Server("no KDF settings".into()))?;
+ let kdf = match num(kind).unwrap_or(0) {
0 => Kdf::Pbkdf2 { iterations },
1 => Kdf::Argon2id {
iterations,
- memory_mib: num("kdfMemory").unwrap_or(64),
- parallelism: num("kdfParallelism").unwrap_or(4),
+ memory_mib: num(memory).unwrap_or(64),
+ parallelism: num(parallel).unwrap_or(4),
},
other => return Err(UnlockError::Unsupported(format!("KDF type {other}"))),
};
@@ -185,9 +218,19 @@ impl Kdf {
}
}
-/// The account's master key from its master password and email.
+/// The account's master key from its master password and email (the salt older accounts use).
pub fn master_key(password: &str, email: &str, kdf: Kdf) -> Result<Zeroizing<[u8; 32]>, UnlockError> {
- let salt = email.trim().to_lowercase();
+ master_key_salted(password, &email_salt(email), kdf)
+}
+
+/// The salt of an account whose server names none: its email, trimmed and lowercased.
+pub fn email_salt(email: &str) -> String {
+ email.trim().to_lowercase()
+}
+
+/// The master key with the salt as the server gives it (prelogin's `salt`, spec C1): Bitwarden is
+/// decoupling the salt from the email, so it is used as is, never lowercased again.
+pub fn master_key_salted(password: &str, salt: &str, kdf: Kdf) -> Result<Zeroizing<[u8; 32]>, UnlockError> {
let mut key = Zeroizing::new([0u8; 32]);
match kdf {
Kdf::Pbkdf2 { iterations } => {
@@ -207,6 +250,18 @@ pub fn master_key(password: &str, email: &str, kdf: Kdf) -> Result<Zeroizing<[u8
Ok(key)
}
+/// The master key and the login hash, off the async threads (a KDF takes a while).
+async fn derive(password: &Zeroizing<String>, salt: &str, kdf: Kdf) -> Result<(Zeroizing<[u8; 32]>, Zeroizing<String>), UnlockError> {
+ let (password, salt) = (password.clone(), salt.to_string());
+ tokio::task::spawn_blocking(move || {
+ let mk = master_key_salted(&password, &salt, kdf)?;
+ let hash = auth_hash(&mk, &password);
+ Ok::<_, UnlockError>((mk, hash))
+ })
+ .await
+ .map_err(|e| UnlockError::Server(e.to_string()))?
+}
+
/// 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]);
@@ -347,6 +402,8 @@ struct Session {
expires: Instant,
user_key: SymKey,
kdf: Kdf,
+ /// The master key's salt (prelogin's, else the email; spec C1).
+ salt: String,
auth_hash: Zeroizing<String>,
folder_id: Option<String>,
/// The account's id, which new items name as `encryptedFor`.
@@ -444,7 +501,24 @@ impl BitwardenStore {
/// 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`]).
+ /// A failed unlock logs one line: its kind, the last HTTP status and the server's host, never
+ /// the email, password, codes or a body (spec C3).
pub async fn unlock(&self, req: UnlockRequest) -> Result<BitwardenStatus, UnlockError> {
+ let server = req.server_url.clone().filter(|s| !s.trim().is_empty()).or_else(|| self.config().map(|c| c.server_url));
+ let mut status = None;
+ let result = self.try_unlock(req, &mut status).await;
+ if let Err(e) = &result {
+ let host = endpoints(server.as_deref().unwrap_or_default())
+ .ok()
+ .and_then(|(base, _)| url::Url::parse(&base).ok()?.host_str().map(str::to_string))
+ .unwrap_or_else(|| "invalid".into());
+ let http = status.map_or_else(|| "none".to_string(), |s: u16| s.to_string());
+ tracing::warn!(kind = e.kind(), http_status = %http, server = %host, "Bitwarden connect or unlock failed");
+ }
+ result
+ }
+
+ async fn try_unlock(&self, req: UnlockRequest, status: &mut Option<u16>) -> 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()))
@@ -479,18 +553,9 @@ impl BitwardenStore {
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 (kdf, salt) = self.prelogin(&ep, &email, status).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 (mk, hash) = derive(&password, &salt, kdf).await?;
let mut form: Vec<(&str, String)> = self.device_form(&cfg);
match (&client_id, &client_secret) {
@@ -522,9 +587,30 @@ impl BitwardenStore {
}
}
}
- let token = self.token_request(&ep, &email, form).await?;
+ let token = self.token_request(&ep, &email, form, status).await?;
- let protected = field_str(&token, "Key").ok_or_else(|| UnlockError::Unsupported("the account has no key".into()))?;
+ // The account key: top-level `Key`, else the newer UserDecryptionOptions.MasterPasswordUnlock,
+ // whose own KDF and salt (when given) are what that key is wrapped with (spec C2)
+ let (protected, mk, hash, kdf, salt) = match field_str(&token, "Key") {
+ Some(k) => (k.to_string(), mk, hash, kdf, salt),
+ None => {
+ let unlock = field(&token, "UserDecryptionOptions").and_then(|o| field(o, "MasterPasswordUnlock"));
+ let key = unlock
+ .and_then(|u| field_str(u, "MasterKeyEncryptedUserKey"))
+ .ok_or_else(|| UnlockError::Unsupported("the account has no key".into()))?
+ .to_string();
+ let unlock = unlock.expect("the key came from it");
+ let kdf2 = field(unlock, "Kdf").map(Kdf::from_settings).transpose()?.unwrap_or(kdf);
+ let salt2 = field_str(unlock, "Salt").filter(|s| !s.is_empty()).map(str::to_string).unwrap_or_else(|| salt.clone());
+ if kdf2 == kdf && salt2 == salt {
+ (key, mk, hash, kdf, salt)
+ } else {
+ let (mk, hash) = derive(&password, &salt2, kdf2).await?;
+ (key, mk, hash, kdf2, salt2)
+ }
+ }
+ };
+ let protected = protected.as_str();
// 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)
@@ -542,6 +628,7 @@ impl BitwardenStore {
expires: Instant::now() + Duration::from_secs(expires_in),
user_key,
kdf,
+ salt,
auth_hash: hash,
folder_id: None,
user_id: None,
@@ -551,6 +638,8 @@ impl BitwardenStore {
unlocked_at: now,
wrong_passwords: 0,
};
+ // A failed sync has no status of its own: don't log the token's 200 with it
+ *status = None;
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),
@@ -566,14 +655,14 @@ impl BitwardenStore {
/// 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 (salt, 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())
+ (s.salt.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)
+ master_key_salted(&password, &salt, kdf)
.map(|mk| same_secret(auth_hash(&mk, &password).as_bytes(), expected.as_bytes()))
.unwrap_or(false)
})
@@ -633,7 +722,9 @@ impl BitwardenStore {
.header("Bitwarden-Client-Version", CLIENT_VERSION)
}
- async fn prelogin(&self, ep: &Endpoints, email: &str) -> Result<Kdf, UnlockError> {
+ /// The account's KDF and master-key salt: the server's `salt` when it gives a non-empty one,
+ /// else the email (spec C1).
+ async fn prelogin(&self, ep: &Endpoints, email: &str, status: &mut Option<u16>) -> Result<(Kdf, String), 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))
@@ -641,16 +732,18 @@ impl BitwardenStore {
.send()
.await
.map_err(|e| UnlockError::Unreachable(short(&e.without_url().to_string())))?;
+ *status = Some(resp.status().as_u16());
if resp.status().is_success() {
let v: Value = resp.json().await.map_err(|_| UnlockError::Server("unreadable KDF settings".into()))?;
- return Kdf::from_json(&v);
+ let salt = field_str(&v, "salt").filter(|s| !s.is_empty()).map(str::to_string).unwrap_or_else(|| email_salt(email));
+ return Ok((Kdf::from_json(&v)?, salt));
}
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> {
+ async fn token_request(&self, ep: &Endpoints, email: &str, form: Vec<(&str, String)>, status_out: &mut Option<u16>) -> 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));
@@ -658,6 +751,7 @@ impl BitwardenStore {
drop(form);
let resp = rb.send().await.map_err(|e| UnlockError::Unreachable(short(&e.without_url().to_string())))?;
let status = resp.status();
+ *status_out = Some(status.as_u16());
let body: Value = resp.json().await.unwrap_or(Value::Null);
if status.is_success() {
return Ok(body);
@@ -708,7 +802,7 @@ impl BitwardenStore {
} else {
return Err(ApiError::Auth);
}
- let token = self.token_request(&s.ep, &s.cfg.email, form).await.map_err(|e| match e {
+ let token = self.token_request(&s.ep, &s.cfg.email, form, &mut None).await.map_err(|e| match e {
UnlockError::Unreachable(m) => ApiError::Other(m),
_ => ApiError::Auth,
})?;
diff --git a/src/server/approval_modes.rs b/src/server/approval_modes.rs
index 56f85e9e..f9454099 100644
--- a/src/server/approval_modes.rs
+++ b/src/server/approval_modes.rs
@@ -39,6 +39,9 @@ fn relaxes(mode: &str) -> bool {
#[derive(Deserialize)]
pub struct ModeBody {
pub approvals: String,
+ /// The person accepts the built-in password store's risk (`passwords::accept_risk`).
+ #[serde(default)]
+ pub accept_risk: bool,
}
/// A bot's setting as the API shows it, next to its other fields.
@@ -94,6 +97,9 @@ pub async fn put_space(
return error(StatusCode::BAD_REQUEST, "approvals must be \"ask\", \"smart\" or \"off\"");
}
if relaxes(mode) {
+ if let Err(r) = super::passwords::accept_risk(&state, &headers, body.accept_risk).await {
+ return r;
+ }
if let Some(r) = super::passwords::refuse_approvals_off(&state).await {
return r;
}
@@ -152,6 +158,9 @@ pub async fn put_kwant(
let turns_off = relaxes(mode)
|| (mode == INHERIT && state.db.space_approvals(&space).await.map_or(true, |m| relaxes(&m)));
if turns_off {
+ if let Err(r) = super::passwords::accept_risk(&state, &headers, body.accept_risk).await {
+ return r;
+ }
if let Some(r) = super::passwords::refuse_approvals_off(&state).await {
return r;
}
diff --git a/src/server/bot_actions.rs b/src/server/bot_actions.rs
index cb24d681..298b6149 100644
--- a/src/server/bot_actions.rs
+++ b/src/server/bot_actions.rs
@@ -1445,7 +1445,7 @@ impl Ctx<'_> {
Ok(p) => p,
Err(e) => return fail(format!("The space was not changed: {e}")),
};
- if let Err(e) = read(super::spaces::update(State(self.state.clone()), Path(self.space.to_string()), Json(patch)).await).await {
+ if let Err(e) = read(super::spaces::update(State(self.state.clone()), Default::default(), Path(self.space.to_string()), Json(patch)).await).await {
return fail(format!("The space was not changed: {e}"));
}
let after = self.space_json(&self.space).await;
@@ -1920,13 +1920,13 @@ async fn undo_action(state: &AppState, a: &BotAction) -> Result<Option<String>,
}
"space_create" => {
let patch = serde_json::from_value(json!({"archived": true})).map_err(|_| StatusCode::INTERNAL_SERVER_ERROR.into_response())?;
- ok_or_conflict(super::spaces::update(State(state.clone()), Path(target), Json(patch)).await, "the space can't be archived")
+ ok_or_conflict(super::spaces::update(State(state.clone()), Default::default(), Path(target), Json(patch)).await, "the space can't be archived")
.await?;
}
"space_update" => {
let patch = serde_json::from_value(json!({"name": before["name"], "icon": before["icon"], "color": before["color"]}))
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR.into_response())?;
- ok_or_conflict(super::spaces::update(State(state.clone()), Path(target), Json(patch)).await, "the space can't be put back")
+ ok_or_conflict(super::spaces::update(State(state.clone()), Default::default(), Path(target), Json(patch)).await, "the space can't be put back")
.await?;
}
"channel_create" => match state.db.delete_empty_channel(&target).await {
@@ -1965,7 +1965,7 @@ async fn confirm_action(state: &AppState, a: &BotAction) -> Result<(), Response>
"bot_delete" => delete_unused_bot(state, &target).await,
"space_archive" => {
let patch = serde_json::from_value(json!({"archived": true})).map_err(|_| StatusCode::INTERNAL_SERVER_ERROR.into_response())?;
- ok_or_conflict(super::spaces::update(State(state.clone()), Path(target), Json(patch)).await, "the space can't be archived")
+ ok_or_conflict(super::spaces::update(State(state.clone()), Default::default(), Path(target), Json(patch)).await, "the space can't be archived")
.await
.map(|_| ())
}
diff --git a/src/server/mod.rs b/src/server/mod.rs
index 42c7b9a1..e0a1d07e 100644
--- a/src/server/mod.rs
+++ b/src/server/mod.rs
@@ -291,6 +291,7 @@ pub fn create_router(state: AppState) -> Router {
.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/store/accept_risk", post(passwords::accept_store_risk))
.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))
diff --git a/src/server/passwords.rs b/src/server/passwords.rs
index 7feb04a0..59f0f876 100644
--- a/src/server/passwords.rs
+++ b/src/server/passwords.rs
@@ -39,6 +39,13 @@
//!
//! and switching approvals off answers 409 while the built-in store holds any password (see
//! [`refuse_approvals_off`]). An install already in that state is reported as `exposed: true`.
+//! Archived spaces, and the bots in them, don't count: they can't run anything (0.7.3 A1).
+//!
+//! A warning, not a wall (0.7.3 A2): every one of those 409s carries `can_accept: true`, and the
+//! person can accept the risk once for this server, with `accept_risk: true` on the refused call
+//! or `POST /api/passwords/store/accept_risk`. That sets the setting [`RISK_ACCEPTED`]; from then
+//! on none of them refuses. Bots' turn tokens can never accept. `exposed` and the startup warning
+//! stay as they are, so the person still sees the risk they took.
//! "Ask only when risky" (`smart`) counts as off here: it runs scripts in the bot's folder
//! without a card, and those can read the data folder just the same.
//! `local_count` counts every file in the built-in store, those of deleted teams, channels and
@@ -59,6 +66,10 @@ use serde_json::{json, Value};
const REFUSAL: &str = "only the person manages saved passwords";
+/// The setting that holds when the person accepted keeping passwords in the built-in store while
+/// some bots don't ask before running commands (RFC 3339). Missing or blank: not accepted.
+pub const RISK_ACCEPTED: &str = "local_store_risk_accepted_at";
+
fn error(status: StatusCode, message: &str) -> Response {
(status, Json(json!({"error": message}))).into_response()
}
@@ -195,6 +206,9 @@ pub struct SaveBody {
pub domain: Option<String>,
pub username: String,
pub password: String,
+ /// The person accepts the built-in store's risk (see [`accept_risk`]).
+ #[serde(default)]
+ pub accept_risk: bool,
}
pub async fn save(
@@ -210,6 +224,9 @@ pub async fn save(
if body.password.is_empty() {
return error(StatusCode::BAD_REQUEST, "password is empty");
}
+ if let Err(r) = accept_risk(&state, &headers, body.accept_risk).await {
+ return r;
+ }
if let Some(r) = refuse_local_save(&state).await {
return r;
}
@@ -295,11 +312,26 @@ pub async fn remove(State(state): State<AppState>, headers: HeaderMap, Path((id,
}
}
-pub async fn save_pending(State(state): State<AppState>, headers: HeaderMap, Path(id): Path<String>) -> Response {
+/// An optional body that only says whether the person accepts the built-in store's risk.
+#[derive(Deserialize, Default)]
+pub struct AcceptRiskBody {
+ #[serde(default)]
+ pub accept_risk: bool,
+}
+
+/// `{accept_risk}` from a body that may be empty or missing.
+pub fn accept_risk_of(body: &[u8]) -> bool {
+ serde_json::from_slice::<AcceptRiskBody>(body).unwrap_or_default().accept_risk
+}
+
+pub async fn save_pending(State(state): State<AppState>, headers: HeaderMap, Path(id): Path<String>, body: axum::body::Bytes) -> Response {
let owner = match owner_or_404(&state, &headers, &id).await {
Ok(o) => o,
Err(r) => return r,
};
+ if let Err(r) = accept_risk(&state, &headers, accept_risk_of(&body)).await {
+ return r;
+ }
let Some(ctrl) = open_controller(&state, &id, &owner).await else {
return error(StatusCode::NOT_FOUND, "no password is waiting to be saved");
};
@@ -333,9 +365,11 @@ pub async fn discard_pending(State(state): State<AppState>, headers: HeaderMap,
/// `{store: "local" | "bitwarden", locked, bitwarden: null | {server_url, email, login:
/// "password" | "api_key", client_id, unlocked, unlocked_at, item_count, last_sync},
-/// local_count, approvals_off, exposed}`. `local_count` is how many passwords the built-in store
-/// still holds (what `migrate` would move). `approvals_off`: any space or bot has approvals off.
-/// `exposed`: both at once, so a bot could read those passwords; nothing changes it on its own.
+/// local_count, approvals_off, exposed, risk_accepted}`. `local_count` is how many passwords the
+/// built-in store still holds (what `migrate` would move). `approvals_off`: any space or bot that
+/// isn't archived has approvals off or "Ask only when risky". `exposed`: both at once, so a bot
+/// could read those passwords; nothing changes it on its own, accepting the risk included.
+/// `risk_accepted`: the person accepted that risk for this server, so nothing refuses a save.
async fn store_json(state: &AppState) -> Value {
let vault = &state.credentials;
let local_count = local_count(state).await;
@@ -347,9 +381,56 @@ async fn store_json(state: &AppState) -> Value {
"local_count": local_count,
"approvals_off": approvals_off,
"exposed": approvals_off && local_count > 0,
+ "risk_accepted": risk_accepted(state).await,
})
}
+/// Whether the person accepted keeping passwords in the built-in store while some bots don't ask
+/// before commands. A failed read counts as not accepted.
+pub async fn risk_accepted(state: &AppState) -> bool {
+ matches!(state.db.get_setting(RISK_ACCEPTED).await, Ok(Some(v)) if !v.trim().is_empty())
+}
+
+/// With `asked` (`accept_risk: true` in the body): the person accepts the built-in store's risk
+/// for this server, once. A bot's turn token is refused (403) and accepts nothing. The first
+/// acceptance is logged, with counts only. `Err` is the response to send.
+#[allow(clippy::result_large_err)]
+pub async fn accept_risk(state: &AppState, headers: &HeaderMap, asked: bool) -> Result<(), Response> {
+ if !asked {
+ return Ok(());
+ }
+ super::mcp_suggest::refuse_agent_tokens(state, headers, "only the person can accept this risk").await?;
+ match state.db.set_setting_if_blank(RISK_ACCEPTED, &chrono::Utc::now().to_rfc3339()).await {
+ Ok(true) => {
+ // Awaited first: a future awaited inside the macro isn't Send
+ let (count, off) = (local_count(state).await, approvals_off_anywhere(state).await);
+ tracing::warn!(
+ local_count = count,
+ approvals_off = off,
+ "the person accepted saving passwords in this server's built-in password store while some bots run commands without asking"
+ );
+ Ok(())
+ }
+ Ok(false) => Ok(()),
+ Err(e) => {
+ tracing::warn!(error = %e, "could not save the accepted password-store risk");
+ Err(error(StatusCode::INTERNAL_SERVER_ERROR, "could not save that choice"))
+ }
+ }
+}
+
+/// `POST /api/passwords/store/accept_risk`: the person accepts the built-in store's risk before
+/// typing anything (the "Save it on this server" button) → the store status.
+pub async fn accept_store_risk(State(state): State<AppState>, headers: HeaderMap) -> Response {
+ if let Err(r) = person(&state, &headers).await {
+ return r;
+ }
+ if let Err(r) = accept_risk(&state, &headers, true).await {
+ return r;
+ }
+ Json(store_json(&state).await).into_response()
+}
+
/// How many passwords the built-in store holds, deleted owners' files included (audit F-11). In
/// Bitwarden mode these are leftovers that were never moved, still readable with the built-in key.
pub async fn local_count(state: &AppState) -> usize {
@@ -370,17 +451,18 @@ pub async fn forget_deleted_owners(state: &AppState, ids: &[&str]) {
}
}
-/// Whether any space or bot has approvals off or "Ask only when risky". A failed read counts as off.
+/// Whether any space or bot that isn't archived has approvals off or "Ask only when risky". A
+/// failed read counts as off.
pub async fn approvals_off_anywhere(state: &AppState) -> bool {
state.db.any_approvals_off().await.unwrap_or(true)
}
/// The 409 for switching approvals off while the built-in store holds passwords: a bot with
/// approvals off could read them (audit F-10). Bitwarden mode with nothing left in the built-in
-/// store is fine. `None` when approvals may go off.
+/// store is fine, and so is a server whose person accepted the risk. `None` when approvals may go off.
pub async fn refuse_approvals_off(state: &AppState) -> Option<Response> {
let n = local_count(state).await;
- if n == 0 {
+ if n == 0 || risk_accepted(state).await {
return None;
}
tracing::info!(local_count = n, "refused to switch approvals off while the built-in store holds passwords");
@@ -390,6 +472,7 @@ pub async fn refuse_approvals_off(state: &AppState) -> Option<Response> {
Json(json!({
"error": "approvals can't be switched off, or to \"Ask only when risky\", while passwords are saved on this server: a bot that can run commands could read them. Move them to Bitwarden first.",
"needs_bitwarden": true,
+ "can_accept": true,
"local_count": n,
})),
)
@@ -399,9 +482,9 @@ pub async fn refuse_approvals_off(state: &AppState) -> Option<Response> {
/// The 409 for saving into the built-in store while any space or bot is on "Ask only when risky" or
/// "Don't ask" (both count as off here). Zombie Hunter's
-/// mailbox and GitHub logins go through it too.
+/// mailbox and GitHub logins go through it too. Never once the person accepted the risk.
pub(crate) async fn refuse_local_save(state: &AppState) -> Option<Response> {
- if state.credentials.store_name() != "local" || !approvals_off_anywhere(state).await {
+ if state.credentials.store_name() != "local" || !approvals_off_anywhere(state).await || risk_accepted(state).await {
return None;
}
Some(
@@ -410,6 +493,7 @@ pub(crate) async fn refuse_local_save(state: &AppState) -> Option<Response> {
Json(json!({
"error": "this server's built-in password store only takes passwords while every space and bot is on \"Ask before running commands\": under \"Ask only when risky\" or \"Don't ask\", a bot that can run commands could read them. Connect Bitwarden, or switch every space and bot to \"Ask before running commands\".",
"needs_bitwarden": true,
+ "can_accept": true,
})),
)
.into_response(),
@@ -460,7 +544,7 @@ pub async fn unlock_bitwarden(State(state): State<AppState>, headers: HeaderMap,
UnlockError::Invalid(_) | UnlockError::Unsupported(_) => (StatusCode::BAD_REQUEST, json!({})),
UnlockError::Unreachable(_) | UnlockError::Server(_) => (StatusCode::BAD_GATEWAY, json!({})),
};
- tracing::warn!(error = %message, "Bitwarden unlock failed");
+ // Logged once by the store, by kind: the message can quote the server (spec C3)
let mut body = extra;
body["error"] = json!(message);
(status, Json(body)).into_response()
@@ -486,12 +570,16 @@ pub async fn forget_bitwarden(State(state): State<AppState>, headers: HeaderMap,
}
// Back to the built-in store would expose what it still holds to bots with approvals off
let n = local_count(&state).await;
- if n > 0 && approvals_off_anywhere(&state).await {
+ if let Err(r) = accept_risk(&state, &headers, accept_risk_of(&body)).await {
+ return r;
+ }
+ if n > 0 && approvals_off_anywhere(&state).await && !risk_accepted(&state).await {
return (
StatusCode::CONFLICT,
Json(json!({
"error": "this server can't go back to its built-in password store while it still holds passwords and a space or bot is on \"Ask only when risky\" or \"Don't ask\": a bot that can run commands could read them. Switch every space and bot to \"Ask before running commands\" first.",
"needs_bitwarden": true,
+ "can_accept": true,
"local_count": n,
})),
)
diff --git a/src/server/spaces.rs b/src/server/spaces.rs
index 1853e06f..95f9f225 100644
--- a/src/server/spaces.rs
+++ b/src/server/spaces.rs
@@ -378,18 +378,39 @@ pub struct PatchBody {
pub sort: Option<i64>,
/// `true` archives, `false` restores.
pub archived: Option<bool>,
+ /// With a restore: the person accepts the built-in password store's risk
+ /// (`passwords::accept_risk`).
+ #[serde(default)]
+ pub accept_risk: bool,
}
/// `PATCH /api/spaces/:id`: rename, restyle, reorder, archive or restore. Archiving pauses the
/// space's routines and stops its running turns; restoring brings back only the routines the
/// archive paused. The Default space can be renamed but not archived (409). No hard delete.
-pub async fn update(State(state): State<AppState>, Path(id): Path<String>, Json(body): Json<PatchBody>) -> Response {
+/// Restoring a space that is on approvals off or "Ask only when risky" (or holds a bot that is)
+/// answers the same 409 as switching approvals off while passwords are saved on this server,
+/// unless the person accepts the risk (`accept_risk: true`, see `passwords`): archived spaces
+/// don't count there (0.7.3 A1), so a restore would otherwise bring the risk back unseen.
+pub async fn update(
+ State(state): State<AppState>,
+ headers: axum::http::HeaderMap,
+ Path(id): Path<String>,
+ Json(body): Json<PatchBody>,
+) -> Response {
let id = SpaceId::new(id);
let current = match state.db.get_space(&id).await {
Ok(Some(s)) => s,
Ok(None) => return error(StatusCode::NOT_FOUND, "no such space"),
Err(_) => return internal(),
};
+ if body.archived == Some(false) && current.archived_at.is_some() && state.db.space_approvals_off(&id).await.unwrap_or(true) {
+ if let Err(r) = super::passwords::accept_risk(&state, &headers, body.accept_risk).await {
+ return r;
+ }
+ if let Some(r) = super::passwords::refuse_approvals_off(&state).await {
+ return r;
+ }
+ }
let name = match body.name.as_deref().map(check_name).transpose() {
Ok(n) => n,
Err(r) => return r,
diff --git a/src/server/zombie_routes.rs b/src/server/zombie_routes.rs
index ee76b6fb..2b55062e 100644
--- a/src/server/zombie_routes.rs
+++ b/src/server/zombie_routes.rs
@@ -434,6 +434,9 @@ pub struct NewSource {
pub label: String,
pub config: Value,
pub secret: String,
+ /// The person accepts the built-in password store's risk (`passwords::accept_risk`).
+ #[serde(default)]
+ pub accept_risk: bool,
}
pub async fn add_source(State(state): State<AppState>, headers: HeaderMap, Json(b): Json<NewSource>) -> Res {
@@ -445,6 +448,7 @@ pub async fn add_source(State(state): State<AppState>, headers: HeaderMap, Json(
if state.credentials.is_locked().await {
return Err(vault_error(StoreError::Locked));
}
+ super::passwords::accept_risk(&state, &headers, b.accept_risk).await?;
// Before the connection test, so a refused save never reaches the server
if let Some(refused) = super::passwords::refuse_local_save(&state).await {
return Err(refused);
@@ -480,6 +484,9 @@ pub struct SourcePatch {
pub enabled: Option<bool>,
pub config: Option<Value>,
pub secret: Option<String>,
+ /// The person accepts the built-in password store's risk (`passwords::accept_risk`).
+ #[serde(default)]
+ pub accept_risk: bool,
}
async fn source_or_404(state: &AppState, id: &str) -> Result<SourceRow, Response> {
@@ -497,6 +504,7 @@ pub async fn update_source(State(state): State<AppState>, headers: HeaderMap, Pa
}
let mut test = None;
if b.config.is_some() || b.secret.is_some() {
+ super::passwords::accept_risk(&state, &headers, b.accept_risk).await?;
// Before the connection test, so a refused save never reaches the server
if let Some(refused) = super::passwords::refuse_local_save(&state).await {
return Err(refused);
diff --git a/tests/approvals_passwords_test.rs b/tests/approvals_passwords_test.rs
index 933dff55..c1e53682 100644
--- a/tests/approvals_passwords_test.rs
+++ b/tests/approvals_passwords_test.rs
@@ -8,6 +8,8 @@
//! - While any space or bot is on "Ask only when risky" or "Don't ask", saving into the built-in store answers 409 and going back
//! from Bitwarden to the built-in store answers 409 unless it is empty.
//! - An install already in that state shows `exposed: true` and keeps its approvals.
+//! - 0.7.3 A1: archived spaces, and bots in them, don't count. A2: the person (never a bot's turn
+//! token) can accept the risk once (`accept_risk: true`), and then none of these refuse.
use axum::{
body::{to_bytes, Body},
@@ -132,6 +134,8 @@ fn assert_needs_bitwarden(s: StatusCode, v: &Value, count: Option<u64>) {
if let Some(n) = count {
assert_eq!(v["local_count"], n, "{v}");
}
+ // 0.7.3 A2: the person may accept the risk instead
+ assert_eq!(v["can_accept"], true, "{v}");
assert!(!v.to_string().contains("DUMMY"), "no password in a refusal: {v}");
}
@@ -332,3 +336,211 @@ async fn ask_only_when_risky_follows_the_same_rule_as_off() {
let (s, v) = e.bot_approvals("inherit").await;
assert_needs_bitwarden(s, &v, Some(1));
}
+
+// ---- 0.7.3 A1 and A2 (github-connect-073/spec.md) ----
+
+use kwnt::{
+ db::{models::NewKwant, spaces::NewSpace},
+ server::{
+ continuity::{SelfScope, TurnOrigin},
+ mcp_runtime,
+ passwords::RISK_ACCEPTED,
+ },
+};
+
+impl Env {
+ async fn as_bot(&self, token: &str, method: &str, uri: &str, body: Option<Value>) -> (StatusCode, Value) {
+ let req = Request::builder()
+ .method(method)
+ .uri(uri)
+ .header("content-type", "application/json")
+ .header("authorization", format!("Bearer {token}"));
+ let body = body.map(|b| Body::from(b.to_string())).unwrap_or_else(Body::empty);
+ let resp = self.app.clone().oneshot(req.body(body).unwrap()).await.unwrap();
+ let status = resp.status();
+ let bytes = to_bytes(resp.into_body(), usize::MAX).await.unwrap();
+ (status, serde_json::from_slice(&bytes).unwrap_or(Value::Null))
+ }
+ /// A bot's turn token in #general, as a running turn holds it.
+ async fn bot_token(&self) -> String {
+ let space = SpaceId::default_space();
+ let general = self.state.db.list_channels(&space).await.unwrap().into_iter().find(|c| c.name == "general").unwrap();
+ let scope = SelfScope {
+ kwant_id: self.bot.id.clone(),
+ kwant_name: self.bot.name.clone(),
+ origin: Some(TurnOrigin { channel_id: Some(general.id.clone()), ..Default::default() }),
+ turn_id: Some("t-risk".into()),
+ ..Default::default()
+ };
+ mcp_runtime::prepare_turn_with_self(&self.state, &self.bot, Some("t-risk".into()), None, Some(scope)).await.unwrap().1
+ }
+ async fn space(&self, approvals: &str) -> SpaceId {
+ let input = NewSpace { name: "Old".into(), icon: "x".into(), color: None, this_machine_enabled: true };
+ SpaceId::new(self.state.db.create_space_with_approvals(&input, approvals).await.unwrap().id)
+ }
+ async fn accepted(&self) -> Option<String> {
+ self.state.db.get_setting(RISK_ACCEPTED).await.unwrap().filter(|v| !v.is_empty())
+ }
+ async fn archived(&self, space: &SpaceId) -> bool {
+ self.state.db.get_space(space).await.unwrap().unwrap().archived_at.is_some()
+ }
+}
+
+#[tokio::test]
+async fn an_archived_space_on_ask_only_when_risky_does_not_count() {
+ // Oleks's dead end: an archived space on smart refused every save, with no way to see why
+ let e = setup(false).await;
+ let old = e.space("smart").await;
+ assert_eq!(e.store().await["approvals_off"], true);
+ let (s, v) = e.save("DUMMY-PW-A1").await;
+ assert_needs_bitwarden(s, &v, None);
+
+ let (s, v) = e.person("PATCH", &format!("/api/spaces/{}", old.as_str()), Some(json!({"archived": true}))).await;
+ assert_eq!(s, StatusCode::OK, "{v}");
+ assert!(!e.state.db.any_approvals_off().await.unwrap());
+ let st = e.store().await;
+ assert_eq!((st["approvals_off"].clone(), st["risk_accepted"].clone()), (json!(false), json!(false)), "{st}");
+ let (s, v) = e.save("DUMMY-PW-A1").await;
+ assert_eq!(s, StatusCode::OK, "{v}");
+
+ // Restoring it would bring the risk back: the same 409, nothing restored
+ let uri = format!("/api/spaces/{}", old.as_str());
+ let (s, v) = e.person("PATCH", &uri, Some(json!({"archived": false}))).await;
+ assert_needs_bitwarden(s, &v, Some(1));
+ assert!(e.archived(&old).await, "still archived");
+ // A bot can't accept it on the person's behalf
+ let token = e.bot_token().await;
+ let (s, v) = e.as_bot(&token, "PATCH", &uri, Some(json!({"archived": false, "accept_risk": true}))).await;
+ assert_eq!(s, StatusCode::FORBIDDEN, "{v}");
+ assert!(e.archived(&old).await);
+ assert_eq!(e.accepted().await, None);
+ // The person accepts and restores
+ let (s, v) = e.person("PATCH", &uri, Some(json!({"archived": false, "accept_risk": true}))).await;
+ assert_eq!(s, StatusCode::OK, "{v}");
+ assert!(!e.archived(&old).await);
+ let st = e.store().await;
+ assert_eq!(st["risk_accepted"], true, "{st}");
+ assert_eq!(st["exposed"], true, "accepting doesn't hide the exposure: {st}");
+}
+
+#[tokio::test]
+async fn restoring_a_space_that_asks_is_never_refused() {
+ let e = setup(false).await;
+ e.local_password().await;
+ let old = e.space("ask").await;
+ let uri = format!("/api/spaces/{}", old.as_str());
+ assert_eq!(e.person("PATCH", &uri, Some(json!({"archived": true}))).await.0, StatusCode::OK);
+ let (s, v) = e.person("PATCH", &uri, Some(json!({"archived": false}))).await;
+ assert_eq!(s, StatusCode::OK, "{v}");
+ assert_eq!(e.accepted().await, None, "nothing accepted");
+}
+
+#[tokio::test]
+async fn a_bot_override_in_an_archived_space_does_not_count() {
+ let e = setup(false).await;
+ let old = e.space("ask").await;
+ let input = NewKwant {
+ name: "Oldie".into(),
+ title: "t".into(),
+ persona_prompt: "p".into(),
+ soul: String::new(),
+ avatar_sprite: "architect".into(),
+ driver_type: "api".into(),
+ preferred_model: "auto".into(),
+ };
+ let oldie = e.state.db.create_kwant(&old, &input).await.unwrap();
+ e.state.db.set_kwant_approvals(&oldie.id, "smart").await.unwrap();
+ assert!(e.state.db.any_approvals_off().await.unwrap());
+ e.state.db.archive_space(&old).await.unwrap();
+ assert!(!e.state.db.any_approvals_off().await.unwrap());
+ let (s, v) = e.save("DUMMY-PW-A1B").await;
+ assert_eq!(s, StatusCode::OK, "{v}");
+ // Restoring it is refused while the built-in store holds that password
+ let uri = format!("/api/spaces/{}", old.as_str());
+ let (s, v) = e.person("PATCH", &uri, Some(json!({"archived": false}))).await;
+ assert_needs_bitwarden(s, &v, Some(1));
+}
+
+#[tokio::test]
+async fn accepting_the_risk_on_save_lets_every_later_step_through() {
+ let e = setup(false).await;
+ assert_eq!(e.bot_approvals("smart").await.0, StatusCode::OK);
+ let (s, v) = e.save("DUMMY-PW-R1").await;
+ assert_needs_bitwarden(s, &v, None);
+ assert_eq!(e.store().await["local_count"], 0);
+
+ let body = json!({"origin": "https://a.test", "username": "u", "password": "DUMMY-PW-R1", "accept_risk": true});
+ let (s, v) = e.person("POST", &format!("/api/sandbox/{}/passwords", e.team), Some(body)).await;
+ assert_eq!(s, StatusCode::OK, "{v}");
+ let at = e.accepted().await.expect("acceptance saved");
+ assert!(chrono::DateTime::parse_from_rfc3339(&at).is_ok(), "{at}");
+ let st = e.store().await;
+ assert_eq!(st["risk_accepted"], true, "{st}");
+ assert_eq!(st["local_count"], 1);
+ assert_eq!(st["exposed"], true, "{st}");
+ assert!(!st.to_string().contains("DUMMY"), "{st}");
+ kwnt::server::passwords::warn_if_exposed(&e.state).await;
+
+ // Later saves and relaxing approvals need no flag
+ let (s, v) = e.save("DUMMY-PW-R2").await;
+ assert_eq!(s, StatusCode::OK, "{v}");
+ let (s, v) = e.space_approvals("off").await;
+ assert_eq!(s, StatusCode::OK, "{v}");
+ assert_eq!(e.state.db.space_approvals(&SpaceId::default_space()).await.unwrap(), "off");
+ // Accepted once: a second acceptance keeps the first time
+ let (s, v) = e.person("POST", "/api/passwords/store/accept_risk", None).await;
+ assert_eq!(s, StatusCode::OK, "{v}");
+ assert_eq!(e.accepted().await.as_deref(), Some(at.as_str()));
+}
+
+#[tokio::test]
+async fn the_accept_route_and_the_approvals_flag_accept_too() {
+ let e = setup(false).await;
+ e.local_password().await;
+ let (s, v) = e.person("POST", "/api/passwords/store/accept_risk", None).await;
+ assert_eq!(s, StatusCode::OK, "{v}");
+ assert_eq!(v["risk_accepted"], true, "the store reply: {v}");
+ assert_eq!(v["store"], "local", "{v}");
+ assert_eq!(e.space_approvals("smart").await.0, StatusCode::OK);
+
+ let e = setup(false).await;
+ e.local_password().await;
+ let uri = format!("/api/spaces/{}/approvals", SpaceId::default_space().as_str());
+ let (s, v) = e.person("PUT", &uri, Some(json!({"approvals": "smart", "accept_risk": true}))).await;
+ assert_eq!(s, StatusCode::OK, "{v}");
+ assert!(e.accepted().await.is_some());
+ // Without the flag nothing is accepted: a plain refusal
+ let e = setup(false).await;
+ e.local_password().await;
+ let (s, v) = e.person("PUT", &uri, Some(json!({"approvals": "smart", "accept_risk": false}))).await;
+ assert_needs_bitwarden(s, &v, Some(1));
+ assert_eq!(e.accepted().await, None);
+}
+
+#[tokio::test]
+async fn a_bot_turn_token_can_never_accept_the_risk() {
+ let e = setup(false).await;
+ e.local_password().await;
+ let token = e.bot_token().await;
+ let save = json!({"origin": "https://a.test", "username": "u", "password": "DUMMY-PW-BOT", "accept_risk": true});
+ let space = format!("/api/spaces/{}/approvals", SpaceId::default_space().as_str());
+ let bot = format!("/api/kwants/{}/approvals", e.bot.id);
+ let calls = [
+ ("POST", "/api/passwords/store/accept_risk".to_string(), None),
+ ("POST", format!("/api/sandbox/{}/passwords", e.team), Some(save)),
+ ("POST", format!("/api/sandbox/{}/passwords/pending", e.team), Some(json!({"accept_risk": true}))),
+ ("PUT", space, Some(json!({"approvals": "off", "accept_risk": true}))),
+ ("PUT", bot, Some(json!({"approvals": "smart", "accept_risk": true}))),
+ ("DELETE", "/api/passwords/bitwarden".to_string(), Some(json!({"accept_risk": true}))),
+ ("POST", "/api/zombie/sources".to_string(), Some(json!({"kind": "github", "accept_risk": true}))),
+ ];
+ for (method, uri, body) in calls {
+ let (s, v) = e.as_bot(&token, method, &uri, body).await;
+ // The person-only routes stop it at the door (401/403); the rest in accept_risk (403)
+ assert!(matches!(s, StatusCode::FORBIDDEN | StatusCode::UNAUTHORIZED), "{method} {uri}: {s} {v}");
+ assert_eq!(e.accepted().await, None, "{method} {uri}");
+ }
+ assert_eq!(e.effective().await, "ask", "nothing relaxed");
+ assert_eq!(e.store().await["local_count"], 1, "nothing saved");
+ assert_eq!(e.store().await["risk_accepted"], false);
+}
diff --git a/tests/bitwarden_test.rs b/tests/bitwarden_test.rs
index e951915c..a98226e3 100644
--- a/tests/bitwarden_test.rs
+++ b/tests/bitwarden_test.rs
@@ -396,3 +396,157 @@ fn kwnt_is_not_dumpable() {
assert_eq!(environ.uid(), 0, "/proc/<kwnt>/environ belongs to root");
assert!(!readable, "kwnt's environment is unreadable to its own user");
}
+
+// ---- 0.7.3 C1, C2, C4 (github-connect-073/spec.md): a mock Bitwarden on this machine ----
+
+mod mock {
+ use axum::{extract::State, routing::{get, post}, Form, Json, Router};
+ use kwnt::sandbox::bitwarden::{self, Kdf, SymKey};
+ use ring::rand::SystemRandom;
+ use serde_json::{json, Value};
+ use std::collections::HashMap;
+ use std::sync::Arc;
+
+ pub const PASSWORD: &str = "DUMMY-master-pw-073";
+ pub const EMAIL: &str = "[email protected]";
+ const ITERATIONS: u32 = 5000;
+
+ #[derive(Clone)]
+ struct Mock {
+ prelogin: Value,
+ hash: String,
+ token: Value,
+ }
+
+ /// How the account's key comes back from `/connect/token`.
+ pub enum KeyIn {
+ TopLevel,
+ /// Only `UserDecryptionOptions.MasterPasswordUnlock`; `camel` names its members as newer
+ /// servers do.
+ MasterPasswordUnlock { camel: bool },
+ }
+
+ /// Serves prelogin, token and sync for one account whose master-key salt is `salt`.
+ /// `prelogin_salt`: what prelogin says about it (None: nothing, as older servers).
+ pub async fn serve(salt: &str, prelogin_salt: Option<&str>, key_in: KeyIn) -> String {
+ let rng = SystemRandom::new();
+ let kdf = Kdf::Pbkdf2 { iterations: ITERATIONS };
+ let mk = bitwarden::master_key_salted(PASSWORD, salt, kdf).unwrap();
+ let user_key = SymKey::stretch(&mk).encrypt(&[7u8; 64], &rng).unwrap();
+ let mut prelogin = json!({"kdf": 0, "kdfIterations": ITERATIONS, "kdfMemory": null, "kdfParallelism": null});
+ if let Some(s) = prelogin_salt {
+ prelogin["salt"] = json!(s);
+ prelogin["kdfSettings"] = json!({"kdfType": 0, "iterations": ITERATIONS});
+ }
+ let mut token = json!({"access_token": "DUMMY-ACCESS", "expires_in": 3600, "refresh_token": "DUMMY-REFRESH", "token_type": "Bearer"});
+ match key_in {
+ KeyIn::TopLevel => token["Key"] = json!(user_key),
+ KeyIn::MasterPasswordUnlock { camel: false } => {
+ token["UserDecryptionOptions"] = json!({"HasMasterPassword": true, "MasterPasswordUnlock": {
+ "Kdf": {"KdfType": 0, "Iterations": ITERATIONS, "Memory": null, "Parallelism": null},
+ "MasterKeyEncryptedUserKey": user_key, "Salt": salt}});
+ }
+ KeyIn::MasterPasswordUnlock { camel: true } => {
+ token["userDecryptionOptions"] = json!({"hasMasterPassword": true, "masterPasswordUnlock": {
+ "kdf": {"kdfType": 0, "iterations": ITERATIONS},
+ "masterKeyEncryptedUserKey": user_key, "salt": salt}});
+ }
+ }
+ let state = Arc::new(Mock { prelogin, hash: bitwarden::auth_hash(&mk, PASSWORD).to_string(), token });
+ let app = Router::new()
+ .route("/identity/accounts/prelogin", post(|State(m): State<Arc<Mock>>| async move { Json(m.prelogin.clone()) }))
+ .route(
+ "/identity/connect/token",
+ post(|State(m): State<Arc<Mock>>, Form(f): Form<HashMap<String, String>>| async move {
+ if f.get("password") == Some(&m.hash) {
+ (axum::http::StatusCode::OK, Json(m.token.clone()))
+ } else {
+ let wrong = json!({"error": "invalid_grant", "error_description": "invalid_username_or_password",
+ "ErrorModel": {"Message": "Username or password is incorrect. Try again."}});
+ (axum::http::StatusCode::BAD_REQUEST, Json(wrong))
+ }
+ }),
+ )
+ .route("/api/sync", get(|| async { Json(json!({"profile": {"id": "u-073"}, "folders": [], "ciphers": []})) }))
+ .with_state(state);
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let addr = listener.local_addr().unwrap();
+ tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
+ format!("http://{addr}")
+ }
+}
+
+fn unlock_req(server: &str, password: &str) -> bitwarden::UnlockRequest {
+ // Not `..Default::default()`: the request wipes itself on drop
+ let mut req = bitwarden::UnlockRequest::default();
+ req.server_url = Some(server.into());
+ req.email = Some(mock::EMAIL.into());
+ req.master_password = password.into();
+ req
+}
+
+#[tokio::test]
+async fn the_servers_salt_is_used_when_it_differs_from_the_email() {
+ let salt = "Salt-Not-The-Email-7f3a";
+ let server = mock::serve(salt, Some(salt), mock::KeyIn::TopLevel).await;
+ let dir = tempdir().unwrap();
+ let store = bitwarden::BitwardenStore::open(dir.path());
+ let status = store.unlock(unlock_req(&server, mock::PASSWORD)).await.expect("unlocks with prelogin's salt, as given");
+ assert_eq!(status.email, mock::EMAIL);
+ assert!(store.is_unlocked().await);
+ // Checking the master password later (reveal, forget) uses the same salt
+ assert!(store.verify_master_password(mock::PASSWORD).await.unwrap());
+ assert!(!store.verify_master_password("DUMMY-not-it").await.unwrap());
+
+ // The same account behind a server that names no salt: the email salt can't open it
+ let server = mock::serve(salt, None, mock::KeyIn::TopLevel).await;
+ let dir = tempdir().unwrap();
+ let store = bitwarden::BitwardenStore::open(dir.path());
+ let err = store.unlock(unlock_req(&server, mock::PASSWORD)).await.expect_err("refused");
+ assert_eq!(err.kind(), "wrong");
+ // An empty salt falls back to the email
+ let server = mock::serve(&bitwarden::email_salt(mock::EMAIL), Some(""), mock::KeyIn::TopLevel).await;
+ let store = bitwarden::BitwardenStore::open(dir.path());
+ store.unlock(unlock_req(&server, mock::PASSWORD)).await.expect("email salt");
+}
+
+#[tokio::test]
+async fn the_account_key_can_come_only_from_master_password_unlock() {
+ for camel in [false, true] {
+ let salt = "Another-Salt-c2";
+ let server = mock::serve(salt, Some(salt), mock::KeyIn::MasterPasswordUnlock { camel }).await;
+ let dir = tempdir().unwrap();
+ let store = bitwarden::BitwardenStore::open(dir.path());
+ store.unlock(unlock_req(&server, mock::PASSWORD)).await.unwrap_or_else(|e| panic!("camel {camel}: {e}"));
+ assert!(store.is_unlocked().await);
+ assert!(dir.path().join(bitwarden::CONFIG_FILE).exists(), "set up");
+ assert!(store.verify_master_password(mock::PASSWORD).await.unwrap());
+ }
+}
+
+#[tokio::test]
+async fn a_failed_connect_sets_nothing_up() {
+ let salt = bitwarden::email_salt(mock::EMAIL);
+ let server = mock::serve(&salt, Some(&salt), mock::KeyIn::TopLevel).await;
+ let e = setup().await;
+ let config = e.data.join(kwnt::sandbox::credentials::VAULT_DIR).join(bitwarden::CONFIG_FILE);
+ for (server, password, status) in [
+ (server.as_str(), "DUMMY-wrong-pw", StatusCode::UNAUTHORIZED),
+ ("http://127.0.0.1:9", mock::PASSWORD, StatusCode::BAD_GATEWAY),
+ ] {
+ let body = json!({"server_url": server, "email": mock::EMAIL, "master_password": password});
+ let (s, v) = e.person("POST", "/api/passwords/bitwarden/unlock", Some(body)).await;
+ assert_eq!(s, status, "{server}: {v}");
+ assert!(!v.to_string().contains("DUMMY"), "{v}");
+ assert!(!config.exists(), "{server}: no bitwarden.json");
+ assert_eq!(e.state.credentials.store_name(), "local", "{server}");
+ assert!(!e.state.credentials.bitwarden().is_configured());
+ }
+ no_file_contains(&e.data, "DUMMY-wrong-pw");
+ // The right password then connects
+ let body = json!({"server_url": server, "email": mock::EMAIL, "master_password": mock::PASSWORD});
+ let (s, v) = e.person("POST", "/api/passwords/bitwarden/unlock", Some(body)).await;
+ assert_eq!(s, StatusCode::OK, "{v}");
+ assert_eq!(v["store"], "bitwarden", "{v}");
+ assert!(config.exists());
+}