Skip to content

Commit 5a64ee4

Browse files
wpfleger96npub1mn7jgtj4w2pd0g0zeuhxsa6jy6p0rewxz4kujt98my82ahfmp72sxjexk7
andauthored
fix(desktop): skip keychain write when blob contents are unchanged (#1377)
Signed-off-by: Will Pfleger <[email protected]> Co-authored-by: npub1mn7jgtj4w2pd0g0zeuhxsa6jy6p0rewxz4kujt98my82ahfmp72sxjexk7 <dcfd242e557282d7a1e2cf2e6877522682f1e5c6156dc92ca7d90eaedd3b0f95@sprout-oss.stage.blox.sqprod.co>
1 parent 2044ad7 commit 5a64ee4

2 files changed

Lines changed: 184 additions & 10 deletions

File tree

‎desktop/src-tauri/src/managed_agents/storage.rs‎

Lines changed: 79 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -254,6 +254,11 @@ fn persist_agent_keys(records: &mut [ManagedAgentRecord]) {
254254
// No keyring backend: keys stay inline.
255255
return;
256256
};
257+
persist_agent_keys_with(store, records);
258+
}
259+
260+
/// Testable core of [`persist_agent_keys`], generic over the [`KeyStore`] seam.
261+
fn persist_agent_keys_with(store: &impl KeyStore, records: &mut [ManagedAgentRecord]) {
257262
for record in records.iter_mut() {
258263
// Only a verified keyring entry lets us drop the inline copy. Both
259264
// other outcomes keep the key inline: `KeptInline` (keyring
@@ -464,8 +469,8 @@ mod tests {
464469
use tempfile::NamedTempFile;
465470

466471
use super::{
467-
agent_keyring_name, hydrate_keys_with, migrate_inline_key, KeyMigration, KeyStore,
468-
KeyringProbe, ManagedAgentRecord,
472+
agent_keyring_name, hydrate_keys_with, migrate_inline_key, persist_agent_keys_with,
473+
KeyMigration, KeyStore, KeyringProbe, ManagedAgentRecord,
469474
};
470475

471476
/// In-memory [`KeyStore`] for testing the migrate decision without the OS
@@ -475,6 +480,7 @@ mod tests {
475480
reachable: bool,
476481
fail_verify: bool,
477482
stored: RefCell<HashMap<String, String>>,
483+
write_count: RefCell<usize>,
478484
}
479485

480486
impl FakeKeyStore {
@@ -483,20 +489,23 @@ mod tests {
483489
reachable: true,
484490
fail_verify: false,
485491
stored: RefCell::new(HashMap::new()),
492+
write_count: RefCell::new(0),
486493
}
487494
}
488495
fn unreachable() -> Self {
489496
Self {
490497
reachable: false,
491498
fail_verify: false,
492499
stored: RefCell::new(HashMap::new()),
500+
write_count: RefCell::new(0),
493501
}
494502
}
495503
fn verify_fails() -> Self {
496504
Self {
497505
reachable: true,
498506
fail_verify: true,
499507
stored: RefCell::new(HashMap::new()),
508+
write_count: RefCell::new(0),
500509
}
501510
}
502511
/// Seed a key as already present in the keyring.
@@ -528,6 +537,7 @@ mod tests {
528537
if self.fail_verify {
529538
return Err("read-back verify failed".to_string());
530539
}
540+
*self.write_count.borrow_mut() += 1;
531541
self.stored
532542
.borrow_mut()
533543
.insert(name.to_string(), value.to_string());
@@ -536,9 +546,13 @@ mod tests {
536546
}
537547

538548
fn record_with_key(nsec: &str) -> ManagedAgentRecord {
549+
record_with_pubkey_and_key("agent-pubkey", nsec)
550+
}
551+
552+
fn record_with_pubkey_and_key(pubkey: &str, nsec: &str) -> ManagedAgentRecord {
539553
serde_json::from_str(&format!(
540554
r#"{{
541-
"pubkey": "agent-pubkey",
555+
"pubkey": "{pubkey}",
542556
"name": "test-agent",
543557
"private_key_nsec": "{nsec}",
544558
"relay_url": "wss://localhost:3000",
@@ -662,6 +676,68 @@ mod tests {
662676
assert!(super::spawn_key_refusal(&record).is_none());
663677
}
664678

679+
#[test]
680+
fn persist_agent_keys_issues_zero_writes_when_inline_keys_already_cleared() {
681+
// This is the dominant prompt-storm scenario: after the first successful
682+
// persist all inline copies are cleared, so subsequent saves (e.g. a
683+
// model change) must issue zero keychain writes. `migrate_inline_key`
684+
// returns `Nothing` for empty-key records, and `persist_agent_keys_with`
685+
// must propagate that guarantee — write_count stays at 0.
686+
let store = FakeKeyStore::reachable();
687+
// Records whose inline key is already blank (key lives in the keyring).
688+
let mut records = vec![record_with_key(""), record_with_key("")];
689+
690+
persist_agent_keys_with(&store, &mut records);
691+
692+
assert_eq!(
693+
*store.write_count.borrow(),
694+
0,
695+
"a save with no inline keys must issue zero keychain writes"
696+
);
697+
}
698+
699+
#[test]
700+
fn persist_agent_keys_writes_once_per_record_with_inline_key() {
701+
// A record carrying an inline key (e.g. first save, or keyring-outage
702+
// residue) must trigger exactly one write_and_verify per record — and
703+
// once persisted the inline copy is cleared so the next save is free.
704+
// Records use distinct pubkeys so each maps to a distinct keyring name,
705+
// verifying the "per record" behaviour rather than a single-key overwrite.
706+
let store = FakeKeyStore::reachable();
707+
let mut records = vec![
708+
record_with_pubkey_and_key("pubkey-agent-alpha", "nsec1key_a"),
709+
record_with_pubkey_and_key("pubkey-agent-beta", "nsec1key_b"),
710+
];
711+
712+
persist_agent_keys_with(&store, &mut records);
713+
714+
assert_eq!(
715+
*store.write_count.borrow(),
716+
2,
717+
"each record with an inline key must trigger exactly one write"
718+
);
719+
// Verify the correct keyring name was used for each agent.
720+
assert_eq!(
721+
store
722+
.stored
723+
.borrow()
724+
.get(&agent_keyring_name("pubkey-agent-alpha"))
725+
.map(String::as_str),
726+
Some("nsec1key_a"),
727+
);
728+
assert_eq!(
729+
store
730+
.stored
731+
.borrow()
732+
.get(&agent_keyring_name("pubkey-agent-beta"))
733+
.map(String::as_str),
734+
Some("nsec1key_b"),
735+
);
736+
// After persist the inline copies are cleared — next save is zero-write.
737+
assert!(records[0].private_key_nsec.is_empty());
738+
assert!(records[1].private_key_nsec.is_empty());
739+
}
740+
665741
fn write_log(content: &str) -> NamedTempFile {
666742
let mut file = NamedTempFile::new().expect("temp log");
667743
file.write_all(content.as_bytes()).expect("write log");

‎desktop/src-tauri/src/secret_store.rs‎

Lines changed: 105 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -194,9 +194,24 @@ impl SecretStore {
194194
}
195195
}
196196

197-
/// Atomically load the blob, apply `f` to the map, write back, and update
198-
/// the cache — all while holding the cache mutex. This serializes concurrent
199-
/// writes so no caller can observe a partial update.
197+
/// Atomically load the blob, apply `f` to a candidate map, write back if
198+
/// changed, and only then advance the cache — all while holding the cache
199+
/// mutex. This serializes concurrent writes so no caller can observe a
200+
/// partial update.
201+
///
202+
/// **Idempotent**: when `f` leaves the candidate equal to the current cached
203+
/// map, `write_blob_raw` is skipped entirely. On macOS the legacy
204+
/// `SecKeychain` API treats a write as a distinct ACL operation from the
205+
/// "Always Allow"-ed read, so skipping no-op writes eliminates the keychain
206+
/// prompt that fires when saving an agent whose model changed but whose key
207+
/// did not.
208+
///
209+
/// **Copy-on-write**: the candidate `next` is a separate allocation from the
210+
/// cached `current`. The cache is only replaced with `next` after
211+
/// `write_blob_raw` succeeds. On write failure the cache stays at the last
212+
/// known durable state — a transient ACL denial or keychain outage cannot
213+
/// advance the cache past durably-written storage and silently drop a later
214+
/// write attempt.
200215
///
201216
/// Deadlock-free: `read_blob_raw` and `write_blob_raw` do not acquire the
202217
/// cache mutex. `load_blob` does acquire it, but `mutate_blob` does not call
@@ -222,14 +237,29 @@ impl SecretStore {
222237
});
223238
}
224239

225-
let map = guard.as_mut().expect("just initialized above");
226-
f(map);
240+
let current = guard.as_ref().expect("just initialized above");
241+
242+
// Build the candidate state in a separate allocation so that a write
243+
// failure below cannot leave the cache ahead of durable storage.
244+
// `HashMap` `PartialEq` compares by content (key-value pairs), not
245+
// iteration order, so the equality check is order-safe.
246+
let mut next = current.clone();
247+
f(&mut next);
248+
249+
// Skip the keychain write when the candidate equals the current durable
250+
// state — the cache already mirrors storage and no I/O is needed.
251+
if next == *current {
252+
return Ok(());
253+
}
227254

228255
// Write to keyring while still holding the lock.
229-
let json = serde_json::to_string(map).map_err(|e| format!("blob serialize: {e}"))?;
256+
let json = serde_json::to_string(&next).map_err(|e| format!("blob serialize: {e}"))?;
230257
self.write_blob_raw(json.as_bytes())?;
231258

232-
// Cache is already up to date (we mutated it in place).
259+
// Advance the cache only after the durable write succeeds. On failure
260+
// the early return above means we never reach this line, so the cache
261+
// remains at the last known durable state.
262+
*guard = Some(next);
233263
Ok(())
234264
}
235265

@@ -514,6 +544,74 @@ mod tests {
514544
);
515545
}
516546

547+
#[test]
548+
fn mutate_blob_skips_write_when_map_unchanged() {
549+
// The idempotent-write guarantee: when the closure leaves the map
550+
// identical to its pre-call state, `write_blob_raw` must NOT be
551+
// invoked. On an unsigned CI build (no keychain entitlement) any real
552+
// write would return an error, so a successful `Ok(())` here proves
553+
// the skip path fired. The service name is unique so test isolation is
554+
// guaranteed even if the test runs locally on a machine with a keychain.
555+
let mut map = HashMap::new();
556+
map.insert("identity".to_string(), "nsec1test".to_string());
557+
let store = SecretStore::with_cache("buzz-test-idempotent-skip", Some(map));
558+
559+
// Re-storing the exact same value must succeed without touching the
560+
// keychain (which would fail on unsigned CI).
561+
let result = store.store("identity", "nsec1test");
562+
assert!(
563+
result.is_ok(),
564+
"no-op store must not reach write_blob_raw: {result:?}"
565+
);
566+
// A genuinely new key DOES change the map — this branch requires a
567+
// real keychain and is therefore left to the #[ignore] integration
568+
// tests; here we only verify the skip path.
569+
}
570+
571+
#[test]
572+
fn mutate_blob_does_not_advance_cache_on_write_failure() {
573+
// Copy-on-write safety: if `write_blob_raw` fails (denied prompt,
574+
// transient outage, ACL rejection), the cache must stay at the last
575+
// known durable state. A subsequent `store()` for the same key/value
576+
// must NOT be skipped as a no-op — the equality check must compare
577+
// against the durable cache, not an unpersisted candidate.
578+
//
579+
// On unsigned CI builds the keychain is unreachable, so any `store()`
580+
// for a key not already in the warm cache will call `write_blob_raw`
581+
// and receive an error. We verify that after the error:
582+
// 1. The cache is not advanced (the previously cached key is intact).
583+
// 2. The failed key is not present (the dirty candidate was discarded).
584+
let mut map = HashMap::new();
585+
map.insert("existing".to_string(), "durable_val".to_string());
586+
let store = SecretStore::with_cache("buzz-test-cow-write-fail", Some(map));
587+
588+
// Attempt to add a new key — on unsigned CI this will try write_blob_raw
589+
// and fail; with copy-on-write the cache must remain at {existing}.
590+
let result = store.store("new_key", "new_val");
591+
592+
if result.is_err() {
593+
// Write failed (expected on unsigned CI): confirm cache was not
594+
// advanced — the existing key is still intact and the new key
595+
// was never committed to the in-memory state.
596+
assert_eq!(
597+
store.load("existing").unwrap(),
598+
Some("durable_val".to_string()),
599+
"cache must remain at last durable state after write failure"
600+
);
601+
// load("new_key") goes through the unchanged cache (no entry),
602+
// then attempts migrate_legacy_key which also fails on unsigned CI,
603+
// returning either Ok(None) or Err — either is correct since the
604+
// key was never durably stored.
605+
let after = store.load("new_key");
606+
assert!(
607+
matches!(after, Ok(None) | Err(_)),
608+
"a key whose write failed must not be visible via load: {after:?}"
609+
);
610+
}
611+
// If result.is_ok() the test ran on a machine with a real keychain and
612+
// the write succeeded — no assertion needed for the failure path.
613+
}
614+
517615
#[test]
518616
fn availability_error_discriminator() {
519617
assert!(is_keyring_availability_error("dbus connection failed"));

0 commit comments

Comments
 (0)