From 11df9287e52738af294a3e321728aa95dc906a54 Mon Sep 17 00:00:00 2001 From: Peter Greis Date: Tue, 24 Nov 2026 16:41:32 +0100 Subject: [PATCH 1/6] #1830: one keychain item per secret on macOS; an unchanged token isn't written again --- apps/mailcraft/src/secrets.rs | 192 ++++++++++++-- apps/mailcraft/src/secrets_security_tests.rs | 2 +- apps/mailcraft/src/secrets_whole_tests.rs | 263 +++++++++++++++++++ crates/ui-egui/src/lib.rs | 9 + crates/ui-egui/src/password_kept_tests.rs | 26 ++ crates/ui-egui/src/secrets_binding_tests.rs | 4 +- packaging/release-notes.d/fixes/1830.md | 1 + 7 files changed, 475 insertions(+), 22 deletions(-) create mode 100644 apps/mailcraft/src/secrets_whole_tests.rs create mode 100644 packaging/release-notes.d/fixes/1830.md diff --git a/apps/mailcraft/src/secrets.rs b/apps/mailcraft/src/secrets.rs index dbef1a843e..56605dd737 100644 --- a/apps/mailcraft/src/secrets.rs +++ b/apps/mailcraft/src/secrets.rs @@ -25,7 +25,13 @@ pub fn store() -> Option> { /// Windows keeps at most 2560 bytes per credential (1280 UTF-16 units), and a refresh token can /// be longer, so a secret is kept in pieces: `#n` holds how many, `#0`… hold them. -/// (The same on every system, so that what is kept looks alike everywhere.) +/// (Linux and FreeBSD keep that layout too, as earlier versions did everywhere.) +/// +/// The macOS keychain keeps a secret of any length in one item, and asks the owner about each +/// item on its own (a keychain item's access list trusts one build of the program), so there a +/// secret is one item, `#all` ([`os::WHOLE`]): one question per secret instead of one per +/// piece and one for the count. What earlier versions kept in pieces is still read, and moved +/// into one item when it is. #[cfg_attr(not(any(target_os = "windows", target_os = "macos", target_os = "linux", target_os = "freebsd", test)), allow(dead_code))] const PIECE: usize = 1000; /// More pieces than any secret needs; a count beyond it is damage, not a secret. @@ -42,6 +48,7 @@ fn pieces(secret: &str) -> Option> { #[cfg(any(target_os = "windows", target_os = "macos", target_os = "linux", target_os = "freebsd"))] mod os { + use std::collections::HashSet; use std::sync::{Arc, Mutex}; use keyring_core::{CredentialStore, Entry, Error}; @@ -84,6 +91,30 @@ mod os { } } + /// The name of the one item a secret is kept in where it is kept whole (the macOS keychain): + /// `#all`. (Never a piece's name: those are numbers, or `n`.) + pub(super) const WHOLE: &str = "all"; + + /// How a secret is laid out in the store (see [`super::PIECE`]). + #[derive(Clone, Copy, Debug, PartialEq, Eq)] + pub(super) enum Layout { + /// `#n` with the count, `#0`… with the pieces (Windows, Linux, FreeBSD). + Pieces, + /// One item, `#all` (the macOS keychain); pieces an earlier version left are read + /// and moved into it. + Whole, + } + + impl Layout { + /// This system's. + fn here() -> Self { + if cfg!(target_os = "macos") { Layout::Whole } else { Layout::Pieces } + } + } + + /// Most keys whose leftover pieces this run has already cleared (a mailbox's accounts are few). + const CLEARED: usize = 1000; + pub struct OsStore { /// Why the store couldn't be used the last time, until the window takes it. trouble: Mutex>, @@ -91,6 +122,11 @@ mod os { /// couldn't be reached (a Secret Service started, or started again, after the window). store: Mutex>>, connect: Connect, + layout: Layout, + /// Kept whole: the keys whose pieces from earlier versions this run has already removed, + /// so that writing a secret again (a refresh token, after each refresh) doesn't remove + /// them again. + cleared: Mutex>, } impl Default for OsStore { @@ -100,9 +136,15 @@ mod os { } impl OsStore { - /// A store that opens what `connect` gives: the system's, or in tests a mock. + /// A store that opens what `connect` gives: the system's, or in tests a mock; laid out + /// as this system lays it out. pub(super) fn with(connect: Connect) -> Self { - Self { trouble: Mutex::new(None), store: Mutex::new(None), connect } + Self::with_layout(connect, Layout::here()) + } + + /// [`with`](Self::with), laid out as `layout` says (tests try both on any system). + pub(super) fn with_layout(connect: Connect, layout: Layout) -> Self { + Self { trouble: Mutex::new(None), store: Mutex::new(None), connect, layout, cleared: Mutex::new(HashSet::new()) } } /// Remember why the store couldn't be used, when that is what `e` says. @@ -144,10 +186,20 @@ mod os { fn count(&self, key: &str) -> Option { self.read(key, "n")?.parse::().ok().filter(|n| (1..=MAX_PIECES).contains(n)) } - } - impl SecretStore for OsStore { - fn get(&self, key: &str) -> Option { + /// Remove one item, without reading it (reading is what the macOS keychain asks the + /// owner about). Nothing there is what removing wants anyway. + fn remove_part(&self, key: &str, part: &str) { + if let Some(e) = self.entry(key, part) + && let Err(err) = e.delete_credential() + { + self.note(&err); + } + } + + // ---- In pieces (Windows, Linux, FreeBSD, and what earlier versions left on macOS). ---- + + fn get_pieces(&self, key: &str) -> Option { let mut secret = String::new(); for i in 0..self.count(key)? { secret.push_str(&self.read(key, &i.to_string())?); @@ -155,34 +207,30 @@ mod os { Some(secret) } - fn set(&self, key: &str, secret: &str) -> Result<(), mailcraft_host::SecretError> { + fn set_pieces(&self, key: &str, secret: &str) -> Result<(), SecretError> { // Platform errors may echo the attempted secret, so never return their words. let refused = |e: Error| { self.note(&e); SecretError::Refused }; - if secret.is_empty() { - self.delete(key); - return Ok(()); - } let pieces = pieces(secret).ok_or(SecretError::TooLong)?; - self.delete(key); + self.delete_pieces(key); for (i, piece) in pieces.iter().enumerate() { if let Err(e) = self.build(key, &i.to_string()).and_then(|entry| entry.set_password(piece)) { // The count marker is deliberately written last. Clean up even an // incomplete write so an account removal cannot leave token fragments. - self.delete(key); + self.delete_pieces(key); return Err(refused(e)); } } if let Err(e) = self.build(key, "n").and_then(|entry| entry.set_password(&pieces.len().to_string())) { - self.delete(key); + self.delete_pieces(key); return Err(refused(e)); } Ok(()) } - fn delete(&self, key: &str) { + fn delete_pieces(&self, key: &str) { // A failed older write may have stored #0, #1... without ever committing #n. // A damaged or stale #n can also underestimate the parts. Probe #0 or the // first uncounted piece, then sweep the bounded number of parts only if needed. @@ -194,15 +242,114 @@ mod os { None => 0, }; for part in (0..pieces).map(|i| i.to_string()).chain(["n".to_string()]) { - if let Some(e) = self.entry(key, &part) { - // Nothing kept under the key is what deleting wants anyway. - if let Err(err) = e.delete_credential() { - self.note(&err); + self.remove_part(key, &part); + } + } + + // ---- Whole (the macOS keychain). ---- + + /// What is kept whole under `key`: `Ok(None)` when nothing is, `Err` when the store + /// couldn't say (locked, refused): then nothing else is asked of it. + fn read_whole(&self, key: &str) -> Result, ()> { + let Some(entry) = self.entry(key, WHOLE) else { return Err(()) }; + match entry.get_password() { + Ok(secret) => Ok(Some(secret)), + Err(Error::NoEntry) => Ok(None), + Err(e) => { + self.note(&e); + Err(()) + } + } + } + + /// Remove every piece an earlier version may have left under `key`, reading none of them + /// (a missing one is not asked about; a present one is removed, not read). + fn clear_pieces_unread(&self, key: &str) { + for part in (0..MAX_PIECES).map(|i| i.to_string()).chain(["n".to_string()]) { + self.remove_part(key, &part); + } + if let Ok(mut cleared) = self.cleared.lock() + && cleared.len() < CLEARED + { + cleared.insert(key.to_string()); + } + } + + fn pieces_cleared(&self, key: &str) -> bool { + self.cleared.lock().is_ok_and(|cleared| cleared.contains(key)) + } + + fn get_whole(&self, key: &str) -> Option { + match self.read_whole(key) { + Ok(Some(secret)) => Some(secret), + Err(()) => None, + // Not kept whole: perhaps in pieces, by an earlier version. Moved into one item, + // so that the next start asks about one item, not about each piece. + Ok(None) => { + let secret = self.get_pieces(key)?; + if let Err(e) = self.set_whole(key, &secret) { + // (Kept as it was: the pieces stay until a write succeeds.) + log::warn!("couldn't move a remembered sign-in into one keychain item: {e}"); } + Some(secret) } } } + fn set_whole(&self, key: &str, secret: &str) -> Result<(), SecretError> { + // As long as the pieces could be: no longer than what any system keeps. + if pieces(secret).is_none() { + return Err(SecretError::TooLong); + } + // Removed first, then added: writing over an item that is there reads it first, + // and reading an item an earlier build made asks the owner for the keychain + // password. A new item trusts this build, so reading it later asks nothing. + self.remove_part(key, WHOLE); + if let Err(e) = self.build(key, WHOLE).and_then(|entry| entry.set_password(secret)) { + // Platform errors may echo the attempted secret, so never return their words. + self.note(&e); + self.remove_part(key, WHOLE); + return Err(SecretError::Refused); + } + // The secret is safe in one item: what an earlier version left in pieces goes, once. + if !self.pieces_cleared(key) { + self.clear_pieces_unread(key); + } + Ok(()) + } + + fn delete_whole(&self, key: &str) { + self.remove_part(key, WHOLE); + self.clear_pieces_unread(key); + } + } + + impl SecretStore for OsStore { + fn get(&self, key: &str) -> Option { + match self.layout { + Layout::Pieces => self.get_pieces(key), + Layout::Whole => self.get_whole(key), + } + } + + fn set(&self, key: &str, secret: &str) -> Result<(), mailcraft_host::SecretError> { + if secret.is_empty() { + self.delete(key); + return Ok(()); + } + match self.layout { + Layout::Pieces => self.set_pieces(key, secret), + Layout::Whole => self.set_whole(key, secret), + } + } + + fn delete(&self, key: &str) { + match self.layout { + Layout::Pieces => self.delete_pieces(key), + Layout::Whole => self.delete_whole(key), + } + } + fn take_trouble(&self) -> Option { self.trouble.lock().ok()?.take() } @@ -213,6 +360,11 @@ mod os { #[path = "secrets_security_tests.rs"] mod security_tests; +#[cfg(test)] +#[cfg(any(target_os = "windows", target_os = "macos", target_os = "linux", target_os = "freebsd"))] +#[path = "secrets_whole_tests.rs"] +mod whole_tests; + #[cfg(test)] mod tests { use super::*; @@ -277,7 +429,7 @@ mod tests { let mock: Arc = mock::Store::new().unwrap(); let store = { let mock = mock.clone(); - os::OsStore::with(Box::new(move || Ok(mock.clone()))) + os::OsStore::with_layout(Box::new(move || Ok(mock.clone())), os::Layout::Pieces) }; let entry = |user: &str| mock.build("MailCraft", user, None).unwrap(); assert_eq!(os::SERVICE, "MailCraft"); diff --git a/apps/mailcraft/src/secrets_security_tests.rs b/apps/mailcraft/src/secrets_security_tests.rs index 0915edbd52..de2e1389b2 100644 --- a/apps/mailcraft/src/secrets_security_tests.rs +++ b/apps/mailcraft/src/secrets_security_tests.rs @@ -13,7 +13,7 @@ use super::os::{self, OsStore}; fn backend() -> (OsStore, Arc) { let mock: Arc = mock::Store::new().unwrap(); let own = mock.clone(); - (OsStore::with(Box::new(move || Ok(own.clone()))), mock) + (OsStore::with_layout(Box::new(move || Ok(own.clone())), os::Layout::Pieces), mock) } fn entry(mock: &Arc, name: &str) -> keyring_core::Entry { diff --git a/apps/mailcraft/src/secrets_whole_tests.rs b/apps/mailcraft/src/secrets_whole_tests.rs new file mode 100644 index 0000000000..fbafd04da4 --- /dev/null +++ b/apps/mailcraft/src/secrets_whole_tests.rs @@ -0,0 +1,263 @@ +// SPDX-FileCopyrightText: MailCraft contributors +// SPDX-License-Identifier: MIT OR Apache-2.0 +//! A secret kept whole, as in the macOS keychain: one item per secret, so that a build the +//! keychain doesn't yet trust asks the owner about one item, not about each piece and the count; +//! pieces from earlier versions read once and moved; and writing a secret again (a refresh token, +//! after each refresh) reading nothing. In keyring's mock store, behind a wrapper that counts what +//! the keychain would ask about: reading an item that is there, or writing over one. + +use std::collections::HashMap; +use std::sync::{Arc, Mutex}; + +use keyring_core::api::{CredentialApi, CredentialStoreApi}; +use keyring_core::{Credential, CredentialStore, Entry, Error, mock}; +use mailcraft_host::{SecretError, SecretStore, StoreTrouble}; + +use super::os::{Layout, OsStore, SERVICE, WHOLE}; +use super::{MAX_PIECES, PIECE}; + +/// What the store was asked, by item name. +#[derive(Default)] +struct Asked { + /// Reads of an item that was there (each one a keychain prompt for an untrusted build). + reads: Vec, + /// Writes over an item that was there (also a prompt: the keychain reads it first). + overwrites: Vec, + /// Items removed. + deletes: Vec, + /// When set, every read fails as a locked keychain does. + locked: bool, +} + +struct Counting { + mock: Arc, + asked: Arc>, +} + +struct Counted { + entry: Entry, + user: String, + asked: Arc>, +} + +impl Counted { + fn there(&self) -> bool { + self.entry.get_secret().is_ok() + } +} + +impl CredentialApi for Counted { + fn set_secret(&self, secret: &[u8]) -> keyring_core::Result<()> { + if self.there() { + self.asked.lock().unwrap().overwrites.push(self.user.clone()); + } + self.entry.set_secret(secret) + } + + fn get_secret(&self) -> keyring_core::Result> { + if self.asked.lock().unwrap().locked { + return Err(Error::NoStorageAccess(Box::new(std::io::Error::other("locked")))); + } + let got = self.entry.get_secret(); + if got.is_ok() { + self.asked.lock().unwrap().reads.push(self.user.clone()); + } + got + } + + fn delete_credential(&self) -> keyring_core::Result<()> { + let done = self.entry.delete_credential(); + if done.is_ok() { + self.asked.lock().unwrap().deletes.push(self.user.clone()); + } + done + } + + fn get_credential(&self) -> keyring_core::Result>> { + Ok(None) + } + + fn get_specifiers(&self) -> Option<(String, String)> { + Some((SERVICE.to_string(), self.user.clone())) + } + + fn as_any(&self) -> &dyn std::any::Any { + self + } +} + +impl CredentialStoreApi for Counting { + fn vendor(&self) -> String { + "counting mock".into() + } + + fn id(&self) -> String { + "counting".into() + } + + fn build(&self, service: &str, user: &str, mods: Option<&HashMap<&str, &str>>) -> keyring_core::Result { + let entry = self.mock.build(service, user, mods)?; + let counted: Arc = Arc::new(Counted { entry, user: user.to_string(), asked: self.asked.clone() }); + Ok(Entry::new_with_credential(counted)) + } + + fn as_any(&self) -> &dyn std::any::Any { + self + } +} + +/// A store kept whole over a counting mock, the mock itself (to look in, uncounted), and the counts. +fn backend() -> (OsStore, Arc, Arc>) { + let mock: Arc = mock::Store::new().unwrap(); + let asked = Arc::new(Mutex::new(Asked::default())); + let counting: Arc = Arc::new(Counting { mock: mock.clone(), asked: asked.clone() }); + (OsStore::with_layout(Box::new(move || Ok(counting.clone())), Layout::Whole), mock, asked) +} + +fn there(mock: &Arc, name: &str) -> Option { + mock.build(SERVICE, name, None).unwrap().get_password().ok() +} + +fn put(mock: &Arc, name: &str, value: &str) { + mock.build(SERVICE, name, None).unwrap().set_password(value).unwrap(); +} + +fn forget_counts(asked: &Arc>) { + let mut asked = asked.lock().unwrap(); + asked.reads.clear(); + asked.overwrites.clear(); + asked.deletes.clear(); +} + +/// As long as a real refresh token: three pieces in the old layout. +fn token() -> String { + "0.AXoA-made_up.token~".chars().cycle().take(PIECE * 2 + 300).collect() +} + +#[test] +fn a_long_secret_is_one_item_and_reading_it_asks_once() { + let (store, mock, asked) = backend(); + let key = "refresh:one@example.org|graph"; + let secret = token(); + store.set(key, &secret).unwrap(); + assert_eq!(there(&mock, &format!("{key}#{WHOLE}")).as_deref(), Some(secret.as_str())); + for part in ["n", "0", "1"] { + assert_eq!(there(&mock, &format!("{key}#{part}")), None, "no piece #{part}"); + } + + forget_counts(&asked); + assert_eq!(store.get(key).as_deref(), Some(secret.as_str())); + assert_eq!(asked.lock().unwrap().reads, [format!("{key}#{WHOLE}")], "one item read, one question"); +} + +#[test] +fn pieces_an_earlier_version_kept_are_read_once_and_moved_into_one_item() { + let (store, mock, asked) = backend(); + let key = "refresh:one@example.org|graph"; + put(&mock, &format!("{key}#n"), "2"); + put(&mock, &format!("{key}#0"), "first-"); + put(&mock, &format!("{key}#1"), "second"); + + assert_eq!(store.get(key).as_deref(), Some("first-second")); + assert_eq!(there(&mock, &format!("{key}#{WHOLE}")).as_deref(), Some("first-second")); + for part in ["n", "0", "1"] { + assert_eq!(there(&mock, &format!("{key}#{part}")), None, "piece #{part} removed"); + } + + // The next start asks about one item. + forget_counts(&asked); + let again = OsStore::with_layout( + { + let counting: Arc = Arc::new(Counting { mock: mock.clone(), asked: asked.clone() }); + Box::new(move || Ok(counting.clone())) + }, + Layout::Whole, + ); + assert_eq!(again.get(key).as_deref(), Some("first-second")); + assert_eq!(asked.lock().unwrap().reads, [format!("{key}#{WHOLE}")]); +} + +#[test] +fn writing_a_new_refresh_token_reads_nothing_and_overwrites_nothing() { + let (store, mock, asked) = backend(); + let key = "refresh:one@example.org|graph"; + store.set(key, &token()).unwrap(); + + // A refresh brings a new token, and another, and another. + forget_counts(&asked); + for turn in 0..3 { + let next = format!("{}-{turn}", token()); + store.set(key, &next).unwrap(); + assert_eq!(there(&mock, &format!("{key}#{WHOLE}")).as_deref(), Some(next.as_str())); + } + let asked = asked.lock().unwrap(); + assert!(asked.reads.is_empty(), "read: {:?}", asked.reads); + assert!(asked.overwrites.is_empty(), "written over: {:?}", asked.overwrites); + // Removed and added again each time; the old pieces were swept once, not each time. + assert_eq!(asked.deletes, vec![format!("{key}#{WHOLE}"); 3]); +} + +#[test] +fn an_item_an_earlier_build_made_is_replaced_without_being_read() { + let (store, mock, asked) = backend(); + let key = "password:one@example.org|imap=imap.example.org:993|smtp=none"; + // Made by another build: reading or writing over it would ask for the keychain password. + put(&mock, &format!("{key}#{WHOLE}"), "old-password"); + store.set(key, "new-password").unwrap(); + assert_eq!(there(&mock, &format!("{key}#{WHOLE}")).as_deref(), Some("new-password")); + let asked = asked.lock().unwrap(); + assert!(asked.reads.is_empty() && asked.overwrites.is_empty()); +} + +#[test] +fn deleting_removes_the_item_and_any_pieces_left_behind() { + let (store, mock, _) = backend(); + let key = "refresh:one@example.org|graph"; + let other = "refresh:two@example.org|graph"; + store.set(key, "whole").unwrap(); + store.set(other, "someone-else").unwrap(); + // Pieces of an interrupted older write, with no count. + put(&mock, &format!("{key}#0"), "stray-0"); + put(&mock, &format!("{key}#{}", MAX_PIECES - 1), "stray-last"); + + store.delete(key); + assert_eq!(store.get(key), None); + for part in ["all".to_string(), "n".to_string(), "0".to_string(), (MAX_PIECES - 1).to_string()] { + assert_eq!(there(&mock, &format!("{key}#{part}")), None, "#{part} removed"); + } + assert_eq!(store.get(other).as_deref(), Some("someone-else")); +} + +#[test] +fn an_empty_secret_forgets_and_a_too_long_one_is_refused_keeping_nothing() { + let (store, mock, _) = backend(); + let key = "refresh:one@example.org|graph"; + store.set(key, "kept").unwrap(); + store.set(key, "").unwrap(); + assert_eq!(store.get(key), None); + let long = "x".repeat(PIECE * MAX_PIECES + 1); + assert_eq!(store.set(key, &long), Err(SecretError::TooLong)); + assert_eq!(there(&mock, &format!("{key}#{WHOLE}")), None); +} + +#[test] +fn a_locked_keychain_is_trouble_and_no_piece_is_asked_for() { + let (store, mock, asked) = backend(); + let key = "refresh:one@example.org|graph"; + put(&mock, &format!("{key}#n"), "1"); + put(&mock, &format!("{key}#0"), "old"); + asked.lock().unwrap().locked = true; + assert_eq!(store.get(key), None); + assert_eq!(store.take_trouble(), Some(StoreTrouble::Locked)); + // Nothing moved or removed while the keychain couldn't say what it holds. + assert_eq!(there(&mock, &format!("{key}#0")).as_deref(), Some("old")); + assert!(asked.lock().unwrap().deletes.is_empty()); +} + +#[test] +fn nothing_kept_is_nothing_and_no_trouble() { + let (store, _, asked) = backend(); + assert_eq!(store.get("password:nobody@example.org"), None); + assert_eq!(store.take_trouble(), None); + assert!(asked.lock().unwrap().reads.is_empty()); +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index c4c749f0ac..281a4c540a 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -3471,6 +3471,15 @@ impl MailApp { } let Some(account) = self.session.mailbox.account(account) else { return }; let key = Self::secret_key(kind, account); + if self.services.secrets.is_none() { + return; + } + // Already kept, as it is: the store is not asked again. (Each sync's jobs hand back the + // account's refresh token; writing it each time cost a keychain question each time.) + if self.secret_cache.get(&key).is_some_and(|kept| kept == secret) { + self.index_secret_key(key); + return; + } let Some(store) = &self.services.secrets else { return }; match store.set(&key, secret) { Ok(()) => { diff --git a/crates/ui-egui/src/password_kept_tests.rs b/crates/ui-egui/src/password_kept_tests.rs index ef8bfc4c4d..eaac67d0fb 100644 --- a/crates/ui-egui/src/password_kept_tests.rs +++ b/crates/ui-egui/src/password_kept_tests.rs @@ -275,3 +275,29 @@ fn an_exchange_password_is_kept_once_the_server_answers_with_its_folders() { assert_eq!(kept(&a, &store, id), None); assert!(!a.passwords.contains_key(&id), "the next Send/Receive asks"); } + +/// A refresh token handed back unchanged (each job of a sync hands back the account's newest) is +/// not written again: on macOS each write of a keychain item a build doesn't yet trust asks the +/// owner for the keychain password. A new one is written, once. +#[test] +fn an_unchanged_secret_is_not_written_again() { + let store = Store::default(); + let mut a = app(&store); + a.ui.remember_sign_in = true; + a.execute("account.add", json!({"email": "avery@mail.example", "auth": "oauth2", "incoming": {"host": "imap.mail.example"}})).unwrap(); + let account = a.account_at("avery@mail.example").map_or(0, |x| x.id); + + a.remember("refresh", account, "invented-refresh-one"); + assert_eq!(store.writes(), 1); + for _ in 0..5 { + a.remember("refresh", account, "invented-refresh-one"); + } + assert_eq!(store.writes(), 1, "the same token is not written again"); + + a.remember("refresh", account, "invented-refresh-two"); + a.remember("refresh", account, "invented-refresh-two"); + assert_eq!(store.writes(), 2, "a new token is written once"); + assert_eq!(a.remembered("refresh", account).as_deref(), Some("invented-refresh-two")); + let key = MailApp::secret_key("refresh", a.session.mailbox.account(account).unwrap()); + assert_eq!(store.get(&key).as_deref(), Some("invented-refresh-two")); +} diff --git a/crates/ui-egui/src/secrets_binding_tests.rs b/crates/ui-egui/src/secrets_binding_tests.rs index f48fba9e39..bd2b0d8e39 100644 --- a/crates/ui-egui/src/secrets_binding_tests.rs +++ b/crates/ui-egui/src/secrets_binding_tests.rs @@ -353,7 +353,9 @@ fn the_secret_cache_and_the_old_names_are_used_only_where_they_are_listed() { let allowed: &[(&str, &str, usize)] = &[ ("lib.rs", "legacy_secret_key(", 2), ("secret_read.rs", "legacy_secret_key(", 1), - ("lib.rs", "secret_cache.get(", 2), + // `remembered`; and `keep_accepted_password` and `remember`, which only compare a secret + // they are handed with the one kept, so as not to write the same one to the store again. + ("lib.rs", "secret_cache.get(", 3), ("secret_read.rs", "secret_cache.contains_key(", 2), // A subscribed calendar's address is kept like a password (#209): found again by the name // that holds its host (`subscribed_address`), and moved into memory for the session when diff --git a/packaging/release-notes.d/fixes/1830.md b/packaging/release-notes.d/fixes/1830.md new file mode 100644 index 0000000000..8c68a3e4e3 --- /dev/null +++ b/packaging/release-notes.d/fixes/1830.md @@ -0,0 +1 @@ +- On macOS the keychain asks for its password once per remembered sign-in, not once per piece of it and again after each Send/Receive: a sign-in is kept as one keychain item, and a refresh token that hasn't changed is not written again ([#1830](https://github.com/GITHUB_REPOSITORY/issues/1830)). From a8f933169bf7467daf893ca6ad9b57faf6ea6416 Mon Sep 17 00:00:00 2001 From: Peter Greis Date: Tue, 24 Nov 2026 18:05:08 +0100 Subject: [PATCH 2/6] #1830: review fixes: a failed sweep is tried again; moving out of pieces never overwrites or restores --- apps/mailcraft/src/secrets.rs | 69 +++++++++++---- apps/mailcraft/src/secrets_whole_tests.rs | 103 ++++++++++++++++++++++ 2 files changed, 156 insertions(+), 16 deletions(-) diff --git a/apps/mailcraft/src/secrets.rs b/apps/mailcraft/src/secrets.rs index 56605dd737..aa306ad150 100644 --- a/apps/mailcraft/src/secrets.rs +++ b/apps/mailcraft/src/secrets.rs @@ -127,6 +127,12 @@ mod os { /// so that writing a secret again (a refresh token, after each refresh) doesn't remove /// them again. cleared: Mutex>, + /// Kept whole: how many writes and deletes have been made through this store. Held while + /// one is made, so that moving a secret out of its old pieces (read on the background + /// thread, with no lock held while the keychain may ask) writes only if no write or + /// delete came in since it read them: never over a newer secret, nor bringing back one + /// the owner removed. + writes: Mutex, } impl Default for OsStore { @@ -144,7 +150,7 @@ mod os { /// [`with`](Self::with), laid out as `layout` says (tests try both on any system). pub(super) fn with_layout(connect: Connect, layout: Layout) -> Self { - Self { trouble: Mutex::new(None), store: Mutex::new(None), connect, layout, cleared: Mutex::new(HashSet::new()) } + Self { trouble: Mutex::new(None), store: Mutex::new(None), connect, layout, cleared: Mutex::new(HashSet::new()), writes: Mutex::new(0) } } /// Remember why the store couldn't be used, when that is what `e` says. @@ -188,15 +194,25 @@ mod os { } /// Remove one item, without reading it (reading is what the macOS keychain asks the - /// owner about). Nothing there is what removing wants anyway. - fn remove_part(&self, key: &str, part: &str) { - if let Some(e) = self.entry(key, part) - && let Err(err) = e.delete_credential() - { - self.note(&err); + /// owner about). Gives whether it is gone: removed, or not there, which is what removing + /// wants anyway. + fn remove_part(&self, key: &str, part: &str) -> bool { + let Some(e) = self.entry(key, part) else { return false }; + match e.delete_credential() { + Ok(()) | Err(Error::NoEntry) => true, + Err(err) => { + self.note(&err); + false + } } } + /// The count of writes and deletes, held: a poisoned lock still counts (nothing kept + /// under it can be left half made). + fn writing(&self) -> std::sync::MutexGuard<'_, u64> { + self.writes.lock().unwrap_or_else(std::sync::PoisonError::into_inner) + } + // ---- In pieces (Windows, Linux, FreeBSD, and what earlier versions left on macOS). ---- fn get_pieces(&self, key: &str) -> Option { @@ -242,7 +258,7 @@ mod os { None => 0, }; for part in (0..pieces).map(|i| i.to_string()).chain(["n".to_string()]) { - self.remove_part(key, &part); + let _ = self.remove_part(key, &part); } } @@ -263,12 +279,16 @@ mod os { } /// Remove every piece an earlier version may have left under `key`, reading none of them - /// (a missing one is not asked about; a present one is removed, not read). + /// (a missing one is not asked about; a present one is removed, not read). Noted as done + /// only when every one is gone: a piece the store wouldn't remove is tried again with the + /// next write. fn clear_pieces_unread(&self, key: &str) { + let mut all_gone = true; for part in (0..MAX_PIECES).map(|i| i.to_string()).chain(["n".to_string()]) { - self.remove_part(key, &part); + all_gone &= self.remove_part(key, &part); } - if let Ok(mut cleared) = self.cleared.lock() + if all_gone + && let Ok(mut cleared) = self.cleared.lock() && cleared.len() < CLEARED { cleared.insert(key.to_string()); @@ -286,11 +306,20 @@ mod os { // Not kept whole: perhaps in pieces, by an earlier version. Moved into one item, // so that the next start asks about one item, not about each piece. Ok(None) => { + let before = *self.writing(); let secret = self.get_pieces(key)?; + let writes = self.writing(); + // A write or delete came in while the pieces were read: it may be a newer + // secret, or the owner removing this one. What it left stands; the pieces, if + // any are left, are moved another time. + if *writes != before { + return Some(secret); + } if let Err(e) = self.set_whole(key, &secret) { // (Kept as it was: the pieces stay until a write succeeds.) log::warn!("couldn't move a remembered sign-in into one keychain item: {e}"); } + drop(writes); Some(secret) } } @@ -304,11 +333,11 @@ mod os { // Removed first, then added: writing over an item that is there reads it first, // and reading an item an earlier build made asks the owner for the keychain // password. A new item trusts this build, so reading it later asks nothing. - self.remove_part(key, WHOLE); + let _ = self.remove_part(key, WHOLE); if let Err(e) = self.build(key, WHOLE).and_then(|entry| entry.set_password(secret)) { // Platform errors may echo the attempted secret, so never return their words. self.note(&e); - self.remove_part(key, WHOLE); + let _ = self.remove_part(key, WHOLE); return Err(SecretError::Refused); } // The secret is safe in one item: what an earlier version left in pieces goes, once. @@ -319,7 +348,7 @@ mod os { } fn delete_whole(&self, key: &str) { - self.remove_part(key, WHOLE); + let _ = self.remove_part(key, WHOLE); self.clear_pieces_unread(key); } } @@ -339,14 +368,22 @@ mod os { } match self.layout { Layout::Pieces => self.set_pieces(key, secret), - Layout::Whole => self.set_whole(key, secret), + Layout::Whole => { + let mut writes = self.writing(); + *writes = writes.wrapping_add(1); + self.set_whole(key, secret) + } } } fn delete(&self, key: &str) { match self.layout { Layout::Pieces => self.delete_pieces(key), - Layout::Whole => self.delete_whole(key), + Layout::Whole => { + let mut writes = self.writing(); + *writes = writes.wrapping_add(1); + self.delete_whole(key); + } } } diff --git a/apps/mailcraft/src/secrets_whole_tests.rs b/apps/mailcraft/src/secrets_whole_tests.rs index fbafd04da4..68f3a93255 100644 --- a/apps/mailcraft/src/secrets_whole_tests.rs +++ b/apps/mailcraft/src/secrets_whole_tests.rs @@ -27,6 +27,11 @@ struct Asked { deletes: Vec, /// When set, every read fails as a locked keychain does. locked: bool, + /// When set, every removal of an item that is there fails as a locked keychain does. + stuck: bool, + /// Done once, just after the item of this name is read (another thread's write or delete + /// landing in the middle of a read). + on_read: Option<(String, Box)>, } struct Counting { @@ -62,10 +67,27 @@ impl CredentialApi for Counted { if got.is_ok() { self.asked.lock().unwrap().reads.push(self.user.clone()); } + // (Taken out first: what it does goes through the store, and so through these counts.) + let hook = { + let mut asked = self.asked.lock().unwrap(); + match asked.on_read.take() { + Some((name, hook)) if name == self.user => Some(hook), + other => { + asked.on_read = other; + None + } + } + }; + if let Some(hook) = hook { + hook(); + } got } fn delete_credential(&self) -> keyring_core::Result<()> { + if self.asked.lock().unwrap().stuck && self.there() { + return Err(Error::NoStorageAccess(Box::new(std::io::Error::other("locked")))); + } let done = self.entry.delete_credential(); if done.is_ok() { self.asked.lock().unwrap().deletes.push(self.user.clone()); @@ -261,3 +283,84 @@ fn nothing_kept_is_nothing_and_no_trouble() { assert_eq!(store.take_trouble(), None); assert!(asked.lock().unwrap().reads.is_empty()); } + +/// Leftover pieces the keychain wouldn't remove (locked at that moment) are removed with a later +/// write, not noted as gone and left behind. +#[test] +fn pieces_that_couldnt_be_removed_are_tried_again_with_the_next_write() { + let (store, mock, asked) = backend(); + let key = "refresh:one@example.org|graph"; + put(&mock, &format!("{key}#n"), "1"); + put(&mock, &format!("{key}#0"), "old-token-piece"); + + asked.lock().unwrap().stuck = true; + // The new token is kept; only the old piece couldn't go yet. + store.set(key, "new-one").unwrap(); + assert_eq!(there(&mock, &format!("{key}#{WHOLE}")).as_deref(), Some("new-one")); + assert_eq!(there(&mock, &format!("{key}#0")).as_deref(), Some("old-token-piece")); + assert_eq!(store.take_trouble(), Some(StoreTrouble::Locked)); + + asked.lock().unwrap().stuck = false; + store.set(key, "new-two").unwrap(); + assert_eq!(there(&mock, &format!("{key}#{WHOLE}")).as_deref(), Some("new-two")); + for part in ["n", "0"] { + assert_eq!(there(&mock, &format!("{key}#{part}")), None, "piece #{part} removed"); + } +} + +/// A store kept whole, shared as the window's thread and the background read share it, with a +/// counting mock under it. +fn shared() -> (Arc, Arc, Arc>) { + let (store, mock, asked) = backend(); + (Arc::new(store), mock, asked) +} + +/// The owner removes the account while the background read is moving its sign-in out of the old +/// pieces: the old token is not written back afterwards. +#[test] +fn a_delete_during_the_move_out_of_pieces_is_not_undone() { + let (store, mock, asked) = shared(); + let key = "refresh:one@example.org|graph"; + put(&mock, &format!("{key}#n"), "1"); + put(&mock, &format!("{key}#0"), "old-token"); + let deleter = Arc::downgrade(&store); + asked.lock().unwrap().on_read = Some(( + format!("{key}#0"), + Box::new(move || { + if let Some(store) = deleter.upgrade() { + store.delete("refresh:one@example.org|graph"); + } + }), + )); + + // (What the read found is handed back to the read that asked; it is the window's business + // to drop it for an account that has gone.) + assert_eq!(store.get(key).as_deref(), Some("old-token")); + for part in [WHOLE, "n", "0"] { + assert_eq!(there(&mock, &format!("{key}#{part}")), None, "#{part} stays removed"); + } + assert_eq!(store.get(key), None); +} + +/// A new token written while the background read moves the old one out of its pieces stays: the +/// old one doesn't go over it. +#[test] +fn a_write_during_the_move_out_of_pieces_is_not_overwritten() { + let (store, mock, asked) = shared(); + let key = "refresh:one@example.org|graph"; + put(&mock, &format!("{key}#n"), "1"); + put(&mock, &format!("{key}#0"), "old-token"); + let writer = Arc::downgrade(&store); + asked.lock().unwrap().on_read = Some(( + format!("{key}#0"), + Box::new(move || { + if let Some(store) = writer.upgrade() { + store.set("refresh:one@example.org|graph", "newer-token").unwrap(); + } + }), + )); + + let _ = store.get(key); + assert_eq!(there(&mock, &format!("{key}#{WHOLE}")).as_deref(), Some("newer-token")); + assert_eq!(store.get(key).as_deref(), Some("newer-token")); +} From 917bb32e62115a9a3a6156e7ca645b986345dfdf Mon Sep 17 00:00:00 2001 From: Peter Greis Date: Tue, 24 Nov 2026 18:34:37 +0100 Subject: [PATCH 3/6] #1830: a read that a write or delete overtook gives what the store holds now, not the old pieces --- apps/mailcraft/src/secrets.rs | 13 ++++-- apps/mailcraft/src/secrets_whole_tests.rs | 57 +++++++++++++++++++++-- 2 files changed, 62 insertions(+), 8 deletions(-) diff --git a/apps/mailcraft/src/secrets.rs b/apps/mailcraft/src/secrets.rs index aa306ad150..efb8647080 100644 --- a/apps/mailcraft/src/secrets.rs +++ b/apps/mailcraft/src/secrets.rs @@ -300,20 +300,25 @@ mod os { } fn get_whole(&self, key: &str) -> Option { + // Counted before the item is looked for: a write after this, even one that lands + // between the look and the pieces' read and couldn't sweep the pieces, stops the move. + let before = *self.writing(); match self.read_whole(key) { Ok(Some(secret)) => Some(secret), Err(()) => None, // Not kept whole: perhaps in pieces, by an earlier version. Moved into one item, // so that the next start asks about one item, not about each piece. Ok(None) => { - let before = *self.writing(); let secret = self.get_pieces(key)?; let writes = self.writing(); // A write or delete came in while the pieces were read: it may be a newer - // secret, or the owner removing this one. What it left stands; the pieces, if - // any are left, are moved another time. + // secret, or the owner removing this one. What it left stands, and is what is + // given back (nothing, when it was a delete): the pieces' value is older than + // it, and a caller would keep it as current. (Read again with no lock held; + // an item this build just wrote, or none, asks the owner nothing.) if *writes != before { - return Some(secret); + drop(writes); + return self.read_whole(key).ok().flatten(); } if let Err(e) = self.set_whole(key, &secret) { // (Kept as it was: the pieces stay until a write succeeds.) diff --git a/apps/mailcraft/src/secrets_whole_tests.rs b/apps/mailcraft/src/secrets_whole_tests.rs index 68f3a93255..2171cef568 100644 --- a/apps/mailcraft/src/secrets_whole_tests.rs +++ b/apps/mailcraft/src/secrets_whole_tests.rs @@ -333,9 +333,8 @@ fn a_delete_during_the_move_out_of_pieces_is_not_undone() { }), )); - // (What the read found is handed back to the read that asked; it is the window's business - // to drop it for an account that has gone.) - assert_eq!(store.get(key).as_deref(), Some("old-token")); + // Nor is the removed token handed back, to be kept in memory as the current one. + assert_eq!(store.get(key), None); for part in [WHOLE, "n", "0"] { assert_eq!(there(&mock, &format!("{key}#{part}")), None, "#{part} stays removed"); } @@ -360,7 +359,57 @@ fn a_write_during_the_move_out_of_pieces_is_not_overwritten() { }), )); - let _ = store.get(key); + // The read gives the newer token, not the older one it found in the pieces. + assert_eq!(store.get(key).as_deref(), Some("newer-token")); assert_eq!(there(&mock, &format!("{key}#{WHOLE}")).as_deref(), Some("newer-token")); assert_eq!(store.get(key).as_deref(), Some("newer-token")); } + +/// A new token written just after the read found no single item, whose sweep of the old pieces +/// failed (the keychain locked at that moment), is not overwritten by the move of those pieces. +#[test] +fn a_write_between_the_look_and_the_pieces_read_is_not_overwritten() { + let (store, mock, asked) = shared(); + let key = "refresh:one@example.org|graph"; + put(&mock, &format!("{key}#n"), "1"); + put(&mock, &format!("{key}#0"), "old-token"); + let (writer, flags) = (Arc::downgrade(&store), asked.clone()); + asked.lock().unwrap().on_read = Some(( + format!("{key}#{WHOLE}"), + Box::new(move || { + if let Some(store) = writer.upgrade() { + flags.lock().unwrap().stuck = true; + store.set("refresh:one@example.org|graph", "newer-token").unwrap(); + flags.lock().unwrap().stuck = false; + } + }), + )); + + assert_eq!(store.get(key).as_deref(), Some("newer-token")); + assert_eq!(there(&mock, &format!("{key}#{WHOLE}")).as_deref(), Some("newer-token")); +} + +/// The owner removes the sign-in just after the read found no single item, and the sweep of the +/// old pieces fails (the keychain locked at that moment): the move doesn't bring the token back, +/// nor does the read hand it out. +#[test] +fn a_delete_between_the_look_and_the_pieces_read_is_not_undone() { + let (store, mock, asked) = shared(); + let key = "refresh:one@example.org|graph"; + put(&mock, &format!("{key}#n"), "1"); + put(&mock, &format!("{key}#0"), "old-token"); + let (deleter, flags) = (Arc::downgrade(&store), asked.clone()); + asked.lock().unwrap().on_read = Some(( + format!("{key}#{WHOLE}"), + Box::new(move || { + if let Some(store) = deleter.upgrade() { + flags.lock().unwrap().stuck = true; + store.delete("refresh:one@example.org|graph"); + flags.lock().unwrap().stuck = false; + } + }), + )); + + assert_eq!(store.get(key), None); + assert_eq!(there(&mock, &format!("{key}#{WHOLE}")), None, "not written back"); +} From 97e91f6e0aa6ebb028ef5ae942c9cba64aacab5b Mon Sep 17 00:00:00 2001 From: Peter Greis Date: Tue, 24 Nov 2026 18:50:02 +0100 Subject: [PATCH 4/6] #1830: the move out of pieces is put off only by a write of its own key, and a piece swept by that write gives the new secret --- apps/mailcraft/src/secrets.rs | 84 ++++++++++++++++----- apps/mailcraft/src/secrets_whole_tests.rs | 90 ++++++++++++++++++++++- 2 files changed, 154 insertions(+), 20 deletions(-) diff --git a/apps/mailcraft/src/secrets.rs b/apps/mailcraft/src/secrets.rs index efb8647080..eca9ff6e0c 100644 --- a/apps/mailcraft/src/secrets.rs +++ b/apps/mailcraft/src/secrets.rs @@ -127,12 +127,45 @@ mod os { /// so that writing a secret again (a refresh token, after each refresh) doesn't remove /// them again. cleared: Mutex>, - /// Kept whole: how many writes and deletes have been made through this store. Held while - /// one is made, so that moving a secret out of its old pieces (read on the background - /// thread, with no lock held while the keychain may ask) writes only if no write or - /// delete came in since it read them: never over a newer secret, nor bringing back one - /// the owner removed. - writes: Mutex, + /// Kept whole: the writes and deletes made through this store. Held while one is made, + /// so that moving a secret out of its old pieces (read on the background thread, with no + /// lock held while the keychain may ask) writes only if no write or delete of that key + /// came in since it looked: never over a newer secret, nor bringing back one the owner + /// removed. + writes: Mutex, + } + + /// Most keys whose last write is noted one by one; past it, any write counts for every key. + pub(super) const NOTED: usize = 1000; + + /// The writes and deletes made through a store kept whole. + #[derive(Default)] + pub(super) struct Writes { + /// How many, all keys together. + count: u64, + /// The count at each key's last write or delete, so that one account's refresh doesn't + /// stop another's move out of its pieces. + last: std::collections::HashMap, + /// The count at the last write of a key that found no room in `last`: a change to any key + /// since then may have been to the one asked about. + unnoted: u64, + } + + impl Writes { + /// Note a write or delete of `key`. + pub(super) fn note(&mut self, key: &str) { + self.count = self.count.wrapping_add(1); + if self.last.len() < NOTED || self.last.contains_key(key) { + self.last.insert(key.to_string(), self.count); + } else { + self.unnoted = self.count; + } + } + + /// Whether `key` may have been written or deleted since the count was `before`. + pub(super) fn changed_since(&self, key: &str, before: u64) -> bool { + self.unnoted > before || self.last.get(key).is_some_and(|&at| at > before) + } } impl Default for OsStore { @@ -150,7 +183,14 @@ mod os { /// [`with`](Self::with), laid out as `layout` says (tests try both on any system). pub(super) fn with_layout(connect: Connect, layout: Layout) -> Self { - Self { trouble: Mutex::new(None), store: Mutex::new(None), connect, layout, cleared: Mutex::new(HashSet::new()), writes: Mutex::new(0) } + Self { + trouble: Mutex::new(None), + store: Mutex::new(None), + connect, + layout, + cleared: Mutex::new(HashSet::new()), + writes: Mutex::new(Writes::default()), + } } /// Remember why the store couldn't be used, when that is what `e` says. @@ -207,9 +247,9 @@ mod os { } } - /// The count of writes and deletes, held: a poisoned lock still counts (nothing kept - /// under it can be left half made). - fn writing(&self) -> std::sync::MutexGuard<'_, u64> { + /// The writes and deletes, held: a poisoned lock still counts (nothing kept under it can + /// be left half made). + fn writing(&self) -> std::sync::MutexGuard<'_, Writes> { self.writes.lock().unwrap_or_else(std::sync::PoisonError::into_inner) } @@ -300,26 +340,30 @@ mod os { } fn get_whole(&self, key: &str) -> Option { - // Counted before the item is looked for: a write after this, even one that lands - // between the look and the pieces' read and couldn't sweep the pieces, stops the move. - let before = *self.writing(); + // Counted before the item is looked for: a write of this key after this, even one that + // lands between the look and the pieces' read and couldn't sweep the pieces, stops the + // move. (Another key's write doesn't.) + let before = self.writing().count; match self.read_whole(key) { Ok(Some(secret)) => Some(secret), Err(()) => None, // Not kept whole: perhaps in pieces, by an earlier version. Moved into one item, // so that the next start asks about one item, not about each piece. Ok(None) => { - let secret = self.get_pieces(key)?; + // (Kept until the writes are looked at: a write of this key while the pieces + // are read may have swept one still to be read, and its secret is the answer.) + let pieces = self.get_pieces(key); let writes = self.writing(); - // A write or delete came in while the pieces were read: it may be a newer - // secret, or the owner removing this one. What it left stands, and is what is + // A write or delete of this key came in while the pieces were read: it may be + // a newer secret, or the owner removing this one. What it left stands, and is what is // given back (nothing, when it was a delete): the pieces' value is older than // it, and a caller would keep it as current. (Read again with no lock held; // an item this build just wrote, or none, asks the owner nothing.) - if *writes != before { + if writes.changed_since(key, before) { drop(writes); return self.read_whole(key).ok().flatten(); } + let secret = pieces?; if let Err(e) = self.set_whole(key, &secret) { // (Kept as it was: the pieces stay until a write succeeds.) log::warn!("couldn't move a remembered sign-in into one keychain item: {e}"); @@ -374,8 +418,9 @@ mod os { match self.layout { Layout::Pieces => self.set_pieces(key, secret), Layout::Whole => { + // (Held while the write is made: the move out of pieces waits for it.) let mut writes = self.writing(); - *writes = writes.wrapping_add(1); + writes.note(key); self.set_whole(key, secret) } } @@ -385,8 +430,9 @@ mod os { match self.layout { Layout::Pieces => self.delete_pieces(key), Layout::Whole => { + // (Held while the write is made: the move out of pieces waits for it.) let mut writes = self.writing(); - *writes = writes.wrapping_add(1); + writes.note(key); self.delete_whole(key); } } diff --git a/apps/mailcraft/src/secrets_whole_tests.rs b/apps/mailcraft/src/secrets_whole_tests.rs index 2171cef568..169fe95f86 100644 --- a/apps/mailcraft/src/secrets_whole_tests.rs +++ b/apps/mailcraft/src/secrets_whole_tests.rs @@ -13,7 +13,7 @@ use keyring_core::api::{CredentialApi, CredentialStoreApi}; use keyring_core::{Credential, CredentialStore, Entry, Error, mock}; use mailcraft_host::{SecretError, SecretStore, StoreTrouble}; -use super::os::{Layout, OsStore, SERVICE, WHOLE}; +use super::os::{Layout, NOTED, OsStore, SERVICE, WHOLE, Writes}; use super::{MAX_PIECES, PIECE}; /// What the store was asked, by item name. @@ -413,3 +413,91 @@ fn a_delete_between_the_look_and_the_pieces_read_is_not_undone() { assert_eq!(store.get(key), None); assert_eq!(there(&mock, &format!("{key}#{WHOLE}")), None, "not written back"); } + +/// Another account's new token written while this one's pieces are read doesn't stop this one's +/// move, nor make its sign-in read as absent. +#[test] +fn another_keys_write_during_the_move_out_of_pieces_lets_it_go_on() { + let (store, mock, asked) = shared(); + let key = "refresh:one@example.org|graph"; + let other = "refresh:two@example.org|graph"; + put(&mock, &format!("{key}#n"), "1"); + put(&mock, &format!("{key}#0"), "one-token"); + let writer = Arc::downgrade(&store); + asked.lock().unwrap().on_read = Some(( + format!("{key}#0"), + Box::new(move || { + if let Some(store) = writer.upgrade() { + store.set("refresh:two@example.org|graph", "two-token").unwrap(); + } + }), + )); + + assert_eq!(store.get(key).as_deref(), Some("one-token")); + assert_eq!(there(&mock, &format!("{key}#{WHOLE}")).as_deref(), Some("one-token"), "moved into one item"); + for part in ["n", "0"] { + assert_eq!(there(&mock, &format!("{key}#{part}")), None, "piece #{part} removed"); + } + assert_eq!(store.get(other).as_deref(), Some("two-token")); +} + +/// Each key's writes are told apart, and past the keys that can be noted one by one, a write of +/// an unnoted key counts as a write of every key (the move is put off, never run over a write). +#[test] +fn writes_are_told_apart_by_key_and_too_many_keys_count_for_all() { + let mut writes = Writes::default(); + writes.note("a"); + let before = 1; + writes.note("b"); + assert!(!writes.changed_since("a", before), "b's write is not a's"); + assert!(writes.changed_since("b", before)); + writes.note("a"); + assert!(writes.changed_since("a", before)); + + let mut full = Writes::default(); + for i in 0..NOTED { + full.note(&format!("key-{i}")); + } + let before = NOTED as u64; + assert!(!full.changed_since("key-0", before)); + full.note("one-too-many"); + assert!(full.changed_since("key-0", before), "an unnoted write may have been any key's"); + assert!(full.changed_since("never-written", before)); +} + +/// A new token written after the first of two old pieces is read sweeps the second before it is +/// read: the read gives the new token, not nothing. +#[test] +fn a_write_that_sweeps_a_piece_still_to_be_read_gives_the_new_secret() { + let (store, mock, asked) = shared(); + let key = "refresh:one@example.org|graph"; + put(&mock, &format!("{key}#n"), "2"); + put(&mock, &format!("{key}#0"), "old-"); + put(&mock, &format!("{key}#1"), "token"); + let writer = Arc::downgrade(&store); + asked.lock().unwrap().on_read = Some(( + format!("{key}#0"), + Box::new(move || { + if let Some(store) = writer.upgrade() { + store.set("refresh:one@example.org|graph", "newer-token").unwrap(); + } + }), + )); + + assert_eq!(store.get(key).as_deref(), Some("newer-token")); + assert_eq!(there(&mock, &format!("{key}#{WHOLE}")).as_deref(), Some("newer-token")); + for part in ["n", "0", "1"] { + assert_eq!(there(&mock, &format!("{key}#{part}")), None, "piece #{part} removed"); + } +} + +/// With no write meanwhile, a piece that is missing still means nothing whole is kept. +#[test] +fn a_missing_piece_with_no_write_meanwhile_is_nothing() { + let (store, mock, _) = shared(); + let key = "refresh:one@example.org|graph"; + put(&mock, &format!("{key}#n"), "2"); + put(&mock, &format!("{key}#0"), "half-"); + assert_eq!(store.get(key), None); + assert_eq!(there(&mock, &format!("{key}#{WHOLE}")), None, "nothing half made is moved"); +} From f96a2f6c369e78e93e0d4699e25330a598efe2a0 Mon Sep 17 00:00:00 2001 From: Peter Greis Date: Sat, 28 Nov 2026 09:05:29 +0100 Subject: [PATCH 5/6] #1830: maintainer review: a move notes its write, sweeps with no lock held; downgrade note; remember tidied --- apps/mailcraft/src/secrets.rs | 42 +++++++++++++-- apps/mailcraft/src/secrets_whole_tests.rs | 64 +++++++++++++++++++++++ crates/ui-egui/src/lib.rs | 5 +- 3 files changed, 102 insertions(+), 9 deletions(-) diff --git a/apps/mailcraft/src/secrets.rs b/apps/mailcraft/src/secrets.rs index eca9ff6e0c..2d4944cdf4 100644 --- a/apps/mailcraft/src/secrets.rs +++ b/apps/mailcraft/src/secrets.rs @@ -340,6 +340,10 @@ mod os { } fn get_whole(&self, key: &str) -> Option { + // (An older build run after this one keeps a sign-in in pieces again and leaves this + // build's item as it was: a newer build then reads that item first. The server refuses + // the stale secret and the owner is asked to sign in once more; nothing is lost.) + // // Counted before the item is looked for: a write of this key after this, even one that // lands between the look and the pieces' read and couldn't sweep the pieces, stops the // move. (Another key's write doesn't.) @@ -364,17 +368,34 @@ mod os { return self.read_whole(key).ok().flatten(); } let secret = pieces?; - if let Err(e) = self.set_whole(key, &secret) { - // (Kept as it was: the pieces stay until a write succeeds.) - log::warn!("couldn't move a remembered sign-in into one keychain item: {e}"); + let mut writes = writes; + let moved = self.write_whole(key, &secret); + if moved.is_ok() { + // A write of this key like any other: a read of it under way at the same + // time, which may find a piece this move sweeps, reads the item instead. + writes.note(key); } + // The item is written: the pieces are swept with no lock held, so that a write + // from the window never waits on the keychain removing them. drop(writes); + match moved { + Ok(()) => self.sweep_once(key), + // (Kept as it was: the pieces stay until a write succeeds.) + Err(e) => log::warn!("couldn't move a remembered sign-in into one keychain item: {e}"), + } Some(secret) } } } fn set_whole(&self, key: &str, secret: &str) -> Result<(), SecretError> { + self.write_whole(key, secret)?; + self.sweep_once(key); + Ok(()) + } + + /// The one item for `key` holds `secret`: what a write must do under the lock. + fn write_whole(&self, key: &str, secret: &str) -> Result<(), SecretError> { // As long as the pieces could be: no longer than what any system keeps. if pieces(secret).is_none() { return Err(SecretError::TooLong); @@ -389,11 +410,14 @@ mod os { let _ = self.remove_part(key, WHOLE); return Err(SecretError::Refused); } - // The secret is safe in one item: what an earlier version left in pieces goes, once. + Ok(()) + } + + /// The secret is safe in one item: what an earlier version left in pieces goes, once. + fn sweep_once(&self, key: &str) { if !self.pieces_cleared(key) { self.clear_pieces_unread(key); } - Ok(()) } fn delete_whole(&self, key: &str) { @@ -442,6 +466,14 @@ mod os { self.trouble.lock().ok()?.take() } } + + #[cfg(test)] + impl OsStore { + /// Whether a write holds the lock on the writes just now. + pub(super) fn writes_held(&self) -> bool { + self.writes.try_lock().is_err() + } + } } #[cfg(test)] diff --git a/apps/mailcraft/src/secrets_whole_tests.rs b/apps/mailcraft/src/secrets_whole_tests.rs index 169fe95f86..ba5a4b79d8 100644 --- a/apps/mailcraft/src/secrets_whole_tests.rs +++ b/apps/mailcraft/src/secrets_whole_tests.rs @@ -32,6 +32,8 @@ struct Asked { /// Done once, just after the item of this name is read (another thread's write or delete /// landing in the middle of a read). on_read: Option<(String, Box)>, + /// Done once, just before the item of this name is removed. + on_delete: Option<(String, Box)>, } struct Counting { @@ -85,6 +87,19 @@ impl CredentialApi for Counted { } fn delete_credential(&self) -> keyring_core::Result<()> { + let hook = { + let mut asked = self.asked.lock().unwrap(); + match asked.on_delete.take() { + Some((name, hook)) if name == self.user => Some(hook), + other => { + asked.on_delete = other; + None + } + } + }; + if let Some(hook) = hook { + hook(); + } if self.asked.lock().unwrap().stuck && self.there() { return Err(Error::NoStorageAccess(Box::new(std::io::Error::other("locked")))); } @@ -501,3 +516,52 @@ fn a_missing_piece_with_no_write_meanwhile_is_nothing() { assert_eq!(store.get(key), None); assert_eq!(there(&mock, &format!("{key}#{WHOLE}")), None, "nothing half made is moved"); } + +/// Two reads of one key at once: the one that finishes the move first sweeps a piece the other +/// has still to read. The other then reads the item the move wrote, not nothing. +#[test] +fn two_reads_at_once_both_give_the_secret() { + let (store, mock, asked) = shared(); + let key = "refresh:one@example.org|graph"; + put(&mock, &format!("{key}#n"), "2"); + put(&mock, &format!("{key}#0"), "old-"); + put(&mock, &format!("{key}#1"), "token"); + let (second, got) = (Arc::downgrade(&store), Arc::new(Mutex::new(None))); + let kept = got.clone(); + asked.lock().unwrap().on_read = Some(( + format!("{key}#0"), + Box::new(move || { + if let Some(store) = second.upgrade() { + *kept.lock().unwrap() = Some(store.get("refresh:one@example.org|graph")); + } + }), + )); + + assert_eq!(store.get(key).as_deref(), Some("old-token"), "the first read"); + assert_eq!(got.lock().unwrap().clone(), Some(Some("old-token".to_string())), "the second read"); + assert_eq!(there(&mock, &format!("{key}#{WHOLE}")).as_deref(), Some("old-token")); +} + +/// The move sweeps the old pieces with no lock held, so a write from the window never waits on +/// the keychain removing them (nor on any question it might ask about that). +#[test] +fn the_move_sweeps_the_pieces_with_no_lock_held() { + let (store, mock, asked) = shared(); + let key = "refresh:one@example.org|graph"; + put(&mock, &format!("{key}#n"), "1"); + put(&mock, &format!("{key}#0"), "old-token"); + let (watched, held) = (Arc::downgrade(&store), Arc::new(Mutex::new(None))); + let seen = held.clone(); + asked.lock().unwrap().on_delete = Some(( + format!("{key}#0"), + Box::new(move || { + if let Some(store) = watched.upgrade() { + *seen.lock().unwrap() = Some(store.writes_held()); + } + }), + )); + + assert_eq!(store.get(key).as_deref(), Some("old-token")); + assert_eq!(*held.lock().unwrap(), Some(false), "the sweep ran, and with the lock free"); + assert_eq!(there(&mock, &format!("{key}#0")), None); +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 281a4c540a..09dfc2922b 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -3471,16 +3471,13 @@ impl MailApp { } let Some(account) = self.session.mailbox.account(account) else { return }; let key = Self::secret_key(kind, account); - if self.services.secrets.is_none() { - return; - } + let Some(store) = self.services.secrets.clone() else { return }; // Already kept, as it is: the store is not asked again. (Each sync's jobs hand back the // account's refresh token; writing it each time cost a keychain question each time.) if self.secret_cache.get(&key).is_some_and(|kept| kept == secret) { self.index_secret_key(key); return; } - let Some(store) = &self.services.secrets else { return }; match store.set(&key, secret) { Ok(()) => { self.secret_cache.insert(key.clone(), secret.to_string()); From 5d8ede9b6a11c4c576cafdde771155e62a52a37e Mon Sep 17 00:00:00 2001 From: Peter Greis Date: Thu, 3 Dec 2026 14:06:16 +0100 Subject: [PATCH 6/6] #1830: a removal macOS refuses as another build's is no locked store; a key deleted this run is never moved back from pieces --- apps/mailcraft/src/secrets.rs | 99 ++++++++++++++++---- apps/mailcraft/src/secrets_whole_tests.rs | 106 +++++++++++++++++++++- 2 files changed, 188 insertions(+), 17 deletions(-) diff --git a/apps/mailcraft/src/secrets.rs b/apps/mailcraft/src/secrets.rs index 2d4944cdf4..09bf6e58ab 100644 --- a/apps/mailcraft/src/secrets.rs +++ b/apps/mailcraft/src/secrets.rs @@ -85,12 +85,46 @@ mod os { match e { // No store answered: on Linux no Secret Service on the session bus, or no session bus. Error::PlatformFailure(_) | Error::NoDefaultStore => Some(StoreTrouble::Unavailable), + // An item another build made, that this one may read but not remove: the store works. + Error::NoStorageAccess(_) if not_ours(e) => None, // The store is there but locked, and unlocking it was dismissed or refused. Error::NoStorageAccess(_) => Some(StoreTrouble::Locked), _ => None, } } + /// Whether `e` says the item belongs to another program, which this one may not remove: in + /// the macOS keychain an item another build made (an ad-hoc signed build is told apart by its + /// code hash) is removed only by a build the owner answered Always Allow, and for one he + /// answered Allow macOS refuses the removal without asking. Told by the error's code + /// (`errSecInvalidOwnerEdit`, -25244, or `wrPermErr`, -61), never its text. + pub(super) fn not_ours(e: &Error) -> bool { + let Error::NoStorageAccess(inner) = e else { return false }; + #[cfg(target_os = "macos")] + if let Some(e) = inner.downcast_ref::() { + return matches!(e.code(), -25244 | -61); + } + // (Tests stand in for the keychain's refusal, on any system, with a refused permission.) + #[cfg(test)] + if let Some(e) = inner.downcast_ref::() { + return e.kind() == std::io::ErrorKind::PermissionDenied; + } + let _ = inner; + false + } + + /// What became of an item asked to go. + #[derive(Clone, Copy, Debug, PartialEq, Eq)] + pub(super) enum Removal { + /// Removed, or not there. + Gone, + /// Another build's, which this build may not remove ([`not_ours`]): there it stays, and + /// trying again in this run won't change that. + NotOurs, + /// The store couldn't remove it (locked, unreachable): worth trying again. + Failed, + } + /// The name of the one item a secret is kept in where it is kept whole (the macOS keychain): /// `#all`. (Never a piece's name: those are numbers, or `n`.) pub(super) const WHOLE: &str = "all"; @@ -130,8 +164,8 @@ mod os { /// Kept whole: the writes and deletes made through this store. Held while one is made, /// so that moving a secret out of its old pieces (read on the background thread, with no /// lock held while the keychain may ask) writes only if no write or delete of that key - /// came in since it looked: never over a newer secret, nor bringing back one the owner - /// removed. + /// came in since it looked, and never for a key deleted in this run: never over a newer + /// secret, nor bringing back one the owner removed. writes: Mutex, } @@ -149,10 +183,16 @@ mod os { /// The count at the last write of a key that found no room in `last`: a change to any key /// since then may have been to the one asked about. unnoted: u64, + /// The keys deleted in this run and not written since: what an earlier version left of + /// them in pieces is never moved into one item again (a removal this build couldn't make + /// leaves the pieces in the keychain; reading them back would undo the owner's removal). + removed: std::collections::HashSet, + /// A key was deleted past the keys that can be noted one by one: any key may be one. + removed_unnoted: bool, } impl Writes { - /// Note a write or delete of `key`. + /// Note a write of `key` (or, through [`note_removed`](Self::note_removed), a delete). pub(super) fn note(&mut self, key: &str) { self.count = self.count.wrapping_add(1); if self.last.len() < NOTED || self.last.contains_key(key) { @@ -160,6 +200,22 @@ mod os { } else { self.unnoted = self.count; } + self.removed.remove(key); + } + + /// Note a delete of `key`. + pub(super) fn note_removed(&mut self, key: &str) { + self.note(key); + if self.removed.len() < NOTED { + self.removed.insert(key.to_string()); + } else { + self.removed_unnoted = true; + } + } + + /// Whether `key` may have been deleted in this run and not written since. + pub(super) fn was_removed(&self, key: &str) -> bool { + self.removed_unnoted || self.removed.contains(key) } /// Whether `key` may have been written or deleted since the count was `before`. @@ -234,15 +290,16 @@ mod os { } /// Remove one item, without reading it (reading is what the macOS keychain asks the - /// owner about). Gives whether it is gone: removed, or not there, which is what removing - /// wants anyway. - fn remove_part(&self, key: &str, part: &str) -> bool { - let Some(e) = self.entry(key, part) else { return false }; + /// owner about). Gives what became of it. + fn remove_part(&self, key: &str, part: &str) -> Removal { + let Some(e) = self.entry(key, part) else { return Removal::Failed }; match e.delete_credential() { - Ok(()) | Err(Error::NoEntry) => true, + // (Not there is what removing wants anyway.) + Ok(()) | Err(Error::NoEntry) => Removal::Gone, + Err(err) if not_ours(&err) => Removal::NotOurs, Err(err) => { self.note(&err); - false + Removal::Failed } } } @@ -320,14 +377,15 @@ mod os { /// Remove every piece an earlier version may have left under `key`, reading none of them /// (a missing one is not asked about; a present one is removed, not read). Noted as done - /// only when every one is gone: a piece the store wouldn't remove is tried again with the - /// next write. + /// when every one is gone, or is another build's that this one may not remove (that won't + /// change in this run; a later build tries again): a piece the store couldn't remove just + /// then (locked) is tried again with the next write. fn clear_pieces_unread(&self, key: &str) { - let mut all_gone = true; + let mut all_done = true; for part in (0..MAX_PIECES).map(|i| i.to_string()).chain(["n".to_string()]) { - all_gone &= self.remove_part(key, &part); + all_done &= self.remove_part(key, &part) != Removal::Failed; } - if all_gone + if all_done && let Ok(mut cleared) = self.cleared.lock() && cleared.len() < CLEARED { @@ -347,7 +405,16 @@ mod os { // Counted before the item is looked for: a write of this key after this, even one that // lands between the look and the pieces' read and couldn't sweep the pieces, stops the // move. (Another key's write doesn't.) - let before = self.writing().count; + let (before, removed) = { + let writes = self.writing(); + (writes.count, writes.was_removed(key)) + }; + // Deleted in this run (Remove Account, then its check that the secret is gone): only + // the one item is looked for. Pieces an earlier build made, which this build may not + // have been allowed to remove, are neither read (no questions) nor moved back. + if removed { + return self.read_whole(key).ok().flatten(); + } match self.read_whole(key) { Ok(Some(secret)) => Some(secret), Err(()) => None, @@ -456,7 +523,7 @@ mod os { Layout::Whole => { // (Held while the write is made: the move out of pieces waits for it.) let mut writes = self.writing(); - writes.note(key); + writes.note_removed(key); self.delete_whole(key); } } diff --git a/apps/mailcraft/src/secrets_whole_tests.rs b/apps/mailcraft/src/secrets_whole_tests.rs index ba5a4b79d8..b243cb59d1 100644 --- a/apps/mailcraft/src/secrets_whole_tests.rs +++ b/apps/mailcraft/src/secrets_whole_tests.rs @@ -13,7 +13,7 @@ use keyring_core::api::{CredentialApi, CredentialStoreApi}; use keyring_core::{Credential, CredentialStore, Entry, Error, mock}; use mailcraft_host::{SecretError, SecretStore, StoreTrouble}; -use super::os::{Layout, NOTED, OsStore, SERVICE, WHOLE, Writes}; +use super::os::{Layout, NOTED, OsStore, SERVICE, WHOLE, Writes, trouble}; use super::{MAX_PIECES, PIECE}; /// What the store was asked, by item name. @@ -34,6 +34,11 @@ struct Asked { on_read: Option<(String, Box)>, /// Done once, just before the item of this name is removed. on_delete: Option<(String, Box)>, + /// Items another build made: read as with the owner's Allow, but this build's removal of one + /// is refused, as the macOS keychain refuses it (`errSecInvalidOwnerEdit`), with no question. + foreign: std::collections::HashSet, + /// Removals refused so. + refused: Vec, } struct Counting { @@ -100,6 +105,10 @@ impl CredentialApi for Counted { if let Some(hook) = hook { hook(); } + if self.there() && self.asked.lock().unwrap().foreign.contains(&self.user) { + self.asked.lock().unwrap().refused.push(self.user.clone()); + return Err(Error::NoStorageAccess(Box::new(std::io::Error::from(std::io::ErrorKind::PermissionDenied)))); + } if self.asked.lock().unwrap().stuck && self.there() { return Err(Error::NoStorageAccess(Box::new(std::io::Error::other("locked")))); } @@ -565,3 +574,98 @@ fn the_move_sweeps_the_pieces_with_no_lock_held() { assert_eq!(*held.lock().unwrap(), Some(false), "the sweep ran, and with the lock free"); assert_eq!(there(&mock, &format!("{key}#0")), None); } + +/// Pieces an earlier build made, kept as the earlier version kept a password, that this build may +/// read (the owner answered Allow) but not remove. +fn foreign_pieces(mock: &Arc, asked: &Arc>, key: &str, secret: &str) { + put(mock, &format!("{key}#n"), "1"); + put(mock, &format!("{key}#0"), secret); + let mut asked = asked.lock().unwrap(); + asked.foreign.insert(format!("{key}#n")); + asked.foreign.insert(format!("{key}#0")); +} + +/// A removal the keychain refuses because the item is another build's is not a locked keychain: +/// the owner isn't told the store can't be used. +#[test] +fn another_builds_item_that_cant_be_removed_is_no_trouble() { + let refused = keyring_core::Error::NoStorageAccess(Box::new(std::io::Error::from(std::io::ErrorKind::PermissionDenied))); + assert_eq!(trouble(&refused), None); + let locked = keyring_core::Error::NoStorageAccess(Box::new(std::io::Error::other("locked"))); + assert_eq!(trouble(&locked), Some(StoreTrouble::Locked)); +} + +/// The move out of pieces this build may not remove: the item is written and used, the pieces +/// stay, the owner hears of no trouble, and the sweep isn't tried again at each write of the run. +#[test] +fn a_move_whose_pieces_are_another_builds_tells_no_trouble_and_tries_once() { + let (store, mock, asked) = backend(); + let key = "password:one@example.org|imap=imap.example.org:993|smtp=none"; + foreign_pieces(&mock, &asked, key, "the-password"); + + assert_eq!(store.get(key).as_deref(), Some("the-password")); + assert_eq!(there(&mock, &format!("{key}#{WHOLE}")).as_deref(), Some("the-password")); + assert_eq!(there(&mock, &format!("{key}#0")).as_deref(), Some("the-password"), "not this build's to remove"); + assert_eq!(store.take_trouble(), None, "no locked notice"); + + let tries = asked.lock().unwrap().refused.len(); + store.set(key, "a-new-password").unwrap(); + store.set(key, "another-one").unwrap(); + assert_eq!(asked.lock().unwrap().refused.len(), tries, "the sweep isn't tried again in this run"); + assert_eq!(store.get(key).as_deref(), Some("another-one")); +} + +/// Remove Account after the move, where the pieces are another build's: the check that follows +/// the removal reads no piece (asks nothing) and finds nothing, and nothing is written back. +#[test] +fn a_removed_sign_in_is_not_brought_back_from_pieces_this_build_couldnt_remove() { + let (store, mock, asked) = backend(); + let key = "password:one@example.org|imap=imap.example.org:993|smtp=none"; + foreign_pieces(&mock, &asked, key, "the-password"); + assert_eq!(store.get(key).as_deref(), Some("the-password")); + + forget_counts(&asked); + store.delete(key); + assert_eq!(store.get(key), None, "the check after the removal finds nothing"); + assert_eq!(there(&mock, &format!("{key}#{WHOLE}")), None, "nothing written back"); + assert!(asked.lock().unwrap().reads.is_empty(), "no piece read, so no question: {:?}", asked.lock().unwrap().reads); + assert_eq!(store.take_trouble(), None, "no locked notice"); + // The pieces are still there: this build may not remove them. + assert_eq!(there(&mock, &format!("{key}#0")).as_deref(), Some("the-password")); + + // Signing in again afterwards is kept, and read, as ever. + store.set(key, "signed-in-again").unwrap(); + assert_eq!(store.get(key).as_deref(), Some("signed-in-again")); +} + +/// Removed before the move ever ran (the account removed before its secret was first read, in a +/// run where the pieces can't be removed): a read doesn't move them back either. +#[test] +fn a_key_removed_before_its_first_read_is_not_moved_back() { + let (store, mock, asked) = backend(); + let key = "password:one@example.org|imap=imap.example.org:993|smtp=none"; + foreign_pieces(&mock, &asked, key, "the-password"); + store.delete(key); + assert_eq!(store.get(key), None); + assert_eq!(there(&mock, &format!("{key}#{WHOLE}")), None); +} + +/// Deleted keys are told apart, a write takes a key off the list, and past the keys that can be +/// noted one by one any key counts as removed (the move is put off, never run over a removal). +#[test] +fn removals_are_noted_by_key_and_too_many_count_for_all() { + let mut writes = Writes::default(); + writes.note_removed("a"); + assert!(writes.was_removed("a")); + assert!(!writes.was_removed("b")); + writes.note("a"); + assert!(!writes.was_removed("a"), "written since"); + + let mut full = Writes::default(); + for i in 0..NOTED { + full.note_removed(&format!("key-{i}")); + } + assert!(!full.was_removed("never-removed")); + full.note_removed("one-too-many"); + assert!(full.was_removed("never-removed")); +}