|
| 1 | +//! One agent-only Keychain item; session caching never couples human custody. |
| 2 | +use super::{Failure, Keychain, SecretMap, MAX_BLOB, SERVICE}; |
| 3 | +use crate::{Result, Secret}; |
| 4 | +use std::sync::Mutex; |
| 5 | +use zeroize::{Zeroize, Zeroizing}; |
| 6 | + |
| 7 | +pub(super) const ACCOUNT: &str = "agent-bundle-v1"; |
| 8 | + |
| 9 | +// A non-secret epoch fences cached copies in other cooperating app processes. |
| 10 | +// Advance before a write, so a crash/uncertain write also invalidates old caches. |
| 11 | +pub(super) trait BundleLock { |
| 12 | + fn epoch(&mut self) -> std::result::Result<[u8; 16], Failure>; |
| 13 | + fn invalidate(&mut self) -> std::result::Result<[u8; 16], Failure>; |
| 14 | +} |
| 15 | +#[derive(Default)] |
| 16 | +pub(super) struct Bundle(Mutex<State>); |
| 17 | +#[derive(Default)] |
| 18 | +struct State { |
| 19 | + cached: Option<([u8; 16], SecretMap)>, |
| 20 | + failure: Option<Failure>, |
| 21 | +} |
| 22 | +impl Bundle { |
| 23 | + pub fn retry(&self) { |
| 24 | + if let Ok(mut state) = self.0.try_lock() { |
| 25 | + state.failure = None; |
| 26 | + } |
| 27 | + } |
| 28 | + fn access<T>( |
| 29 | + &self, |
| 30 | + keychain: &dyn Keychain, |
| 31 | + operation: impl FnOnce(&mut State, &mut dyn BundleLock) -> std::result::Result<T, Failure>, |
| 32 | + ) -> Result<T> { |
| 33 | + let mut state = self.0.try_lock().map_err(|_| Failure::Busy.message())?; |
| 34 | + if let Some(failure) = state.failure { |
| 35 | + return Err(failure.message()); |
| 36 | + } |
| 37 | + let result = keychain |
| 38 | + .bundle_lock() |
| 39 | + .and_then(|mut lock| operation(&mut state, lock.as_mut())); |
| 40 | + if let Err(error) = result { |
| 41 | + state.cached = None; |
| 42 | + // Only a denied unlock is shared. Busy and an individual malformed |
| 43 | + // migration must not poison otherwise valid agents in the queue. |
| 44 | + if error == Failure::Denied { |
| 45 | + state.failure = Some(error); |
| 46 | + } |
| 47 | + } |
| 48 | + result.map_err(Failure::message) |
| 49 | + } |
| 50 | + pub fn read( |
| 51 | + &self, |
| 52 | + keychain: &dyn Keychain, |
| 53 | + account: &str, |
| 54 | + pubkey: &str, |
| 55 | + ) -> Result<Option<Secret>> { |
| 56 | + self.access(keychain, |state, lock| { |
| 57 | + let epoch = lock.epoch()?; |
| 58 | + if state.cached.as_ref().map(|(at, _)| at) != Some(&epoch) { |
| 59 | + state.cached = Some((epoch, load(keychain)?)); |
| 60 | + } |
| 61 | + if let Some(value) = state |
| 62 | + .cached |
| 63 | + .as_ref() |
| 64 | + .and_then(|(_, map)| map.0.get(account)) |
| 65 | + { |
| 66 | + return parse(value, pubkey).map(Some); |
| 67 | + } |
| 68 | + // Only absence in a successfully loaded bundle permits migration. |
| 69 | + // Never consult old Buzz or substitute another identity/community. |
| 70 | + let bytes = match keychain.saved(SERVICE, account) { |
| 71 | + Ok(bytes) => bytes, |
| 72 | + Err(Failure::Absent) => return Ok(None), |
| 73 | + Err(error) => return Err(error), |
| 74 | + }; |
| 75 | + if bytes.len() > 64 { |
| 76 | + return Err(Failure::Corrupt); |
| 77 | + } |
| 78 | + let key = parse( |
| 79 | + std::str::from_utf8(&bytes).map_err(|_| Failure::Corrupt)?, |
| 80 | + pubkey, |
| 81 | + )?; |
| 82 | + // Fresh read under the mutation lock, never write back a session cache. |
| 83 | + let mut map = load(keychain)?; |
| 84 | + map.0.insert(account.into(), (*key.hex()).clone()); |
| 85 | + persist(keychain, lock, state, map)?; |
| 86 | + // Retain the individual entry for rollback. Explicit Delete removes both. |
| 87 | + Ok(Some(key)) |
| 88 | + }) |
| 89 | + } |
| 90 | + pub fn add(&self, keychain: &dyn Keychain, account: &str, key: &Secret) -> Result<()> { |
| 91 | + self.access(keychain, |state, lock| { |
| 92 | + let mut map = load(keychain)?; |
| 93 | + if map.0.contains_key(account) { |
| 94 | + return Err(Failure::Occupied); |
| 95 | + } |
| 96 | + match keychain.saved(SERVICE, account) { |
| 97 | + Ok(_) => return Err(Failure::Occupied), |
| 98 | + Err(Failure::Absent) => {} |
| 99 | + Err(error) => return Err(error), |
| 100 | + } |
| 101 | + map.0.insert(account.into(), (*key.hex()).clone()); |
| 102 | + persist(keychain, lock, state, map) |
| 103 | + }) |
| 104 | + } |
| 105 | + pub fn delete(&self, keychain: &dyn Keychain, account: &str) -> Result<()> { |
| 106 | + // Delete is explicit recovery too, including after a refused unlock. |
| 107 | + self.retry(); |
| 108 | + self.access(keychain, |state, lock| { |
| 109 | + let mut map = load(keychain)?; |
| 110 | + state.cached = None; |
| 111 | + lock.invalidate()?; |
| 112 | + // Remove the rollback copy first. A failure leaves the bundle intact; |
| 113 | + // a later bundle-write failure leaves the card available for retry. |
| 114 | + match keychain.delete(SERVICE, account) { |
| 115 | + Ok(()) | Err(Failure::Absent) => {} |
| 116 | + Err(error) => return Err(error), |
| 117 | + } |
| 118 | + if let Some(mut value) = map.0.remove(account) { |
| 119 | + value.zeroize(); |
| 120 | + } |
| 121 | + persist(keychain, lock, state, map) |
| 122 | + }) |
| 123 | + } |
| 124 | +} |
| 125 | +fn parse(value: &str, pubkey: &str) -> std::result::Result<Secret, Failure> { |
| 126 | + Secret::parse(value, pubkey).map_err(|_| Failure::Corrupt) |
| 127 | +} |
| 128 | +fn load(keychain: &dyn Keychain) -> std::result::Result<SecretMap, Failure> { |
| 129 | + let bytes = match keychain.saved(SERVICE, ACCOUNT) { |
| 130 | + Ok(bytes) => bytes, |
| 131 | + Err(Failure::Absent) => return Ok(SecretMap::default()), |
| 132 | + Err(error) => return Err(error), |
| 133 | + }; |
| 134 | + decode(&bytes) |
| 135 | +} |
| 136 | +fn decode(bytes: &[u8]) -> std::result::Result<SecretMap, Failure> { |
| 137 | + if bytes.len() > MAX_BLOB { |
| 138 | + return Err(Failure::Corrupt); |
| 139 | + } |
| 140 | + let map: SecretMap = serde_json::from_slice(bytes).map_err(|_| Failure::Corrupt)?; |
| 141 | + for (account, value) in &map.0 { |
| 142 | + let id = account.strip_prefix("agent:").ok_or(Failure::Corrupt)?; |
| 143 | + super::account(id).map_err(|_| Failure::Corrupt)?; |
| 144 | + parse(value, id.split_once('-').ok_or(Failure::Corrupt)?.0)?; |
| 145 | + } |
| 146 | + Ok(map) |
| 147 | +} |
| 148 | +fn persist( |
| 149 | + keychain: &dyn Keychain, |
| 150 | + lock: &mut dyn BundleLock, |
| 151 | + state: &mut State, |
| 152 | + map: SecretMap, |
| 153 | +) -> std::result::Result<(), Failure> { |
| 154 | + let mut bytes = Zeroizing::new(Vec::new()); |
| 155 | + serde_json::to_writer(&mut *bytes, &map.0).map_err(|_| Failure::Corrupt)?; |
| 156 | + if bytes.len() > MAX_BLOB { |
| 157 | + return Err(Failure::Corrupt); |
| 158 | + } |
| 159 | + state.cached = None; |
| 160 | + let epoch = lock.invalidate()?; |
| 161 | + keychain.replace(SERVICE, ACCOUNT, &bytes)?; |
| 162 | + let verified = decode(&keychain.saved(SERVICE, ACCOUNT)?)?; |
| 163 | + if verified.0 != map.0 { |
| 164 | + return Err(Failure::Corrupt); |
| 165 | + } |
| 166 | + state.cached = Some((epoch, verified)); |
| 167 | + Ok(()) |
| 168 | +} |
| 169 | + |
| 170 | +#[test] |
| 171 | +fn same_process_contention_reports_busy_without_blame_or_keychain_access() { |
| 172 | + let bundle = Bundle::default(); |
| 173 | + let _pending = bundle.0.lock().unwrap(); |
| 174 | + // Unit-test OsKeychain rejects access; the held session mutex must fail first. |
| 175 | + let result = bundle.read(&super::platform::OsKeychain, "agent:fixture", "fixture"); |
| 176 | + assert_eq!( |
| 177 | + result.err().unwrap(), |
| 178 | + "Credentials are busy; retry after the current operation finishes" |
| 179 | + ); |
| 180 | +} |
0 commit comments