Skip to content

Commit 71821aa

Browse files
author
Carl
committed
Merge main into presence repair and preserve updated Settings journeys
Signed-off-by: Carl <32a2e2c9d428ee08902cab75d956da2c1d235a22d4766b0dd4138bf6e2e5db1d@buzz.block.builderlab.xyz>
2 parents 765f629 + 0c3a601 commit 71821aa

77 files changed

Lines changed: 3475 additions & 548 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎.cargo/config.toml‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
# Each checkout builds into its own target/, even when a user-level Cargo config
2+
# sets a shared target-dir. The app binary and its bundled resources must come
3+
# from the same worktree's sources; Tauri also resolves resources beside it.
4+
[build]
5+
target-dir = "target"

‎Cargo.lock‎

Lines changed: 1 addition & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎bin/hermit.hcl‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,6 @@
11
sources = ["env:///bin/packages", "https://github.com/cashapp/hermit-packages.git"]
22
manage-git = false
3+
# Share Cargo's download caches across worktrees instead of per-worktree .hermit/rust.
4+
env = {
5+
"CARGO_HOME": "${HOME}/.cargo",
6+
}

‎crates/agent-controller/Cargo.toml‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ libc = "0.2"
2828

2929
[target.'cfg(target_os = "macos")'.dependencies]
3030
security-framework = "3.7"
31+
nix = { version = "0.31", features = ["user"] }
3132

3233
[target.'cfg(any(target_os = "windows", target_os = "linux"))'.dependencies]
3334
buzz-credential-store = { path = "../credential-store" }

‎crates/agent-controller/src/bundle.rs‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,13 @@ impl RuntimeBundle {
7979
bundle.files = observed;
8080
Ok(bundle)
8181
}
82+
/// Configured path for display only. Does not inspect files or authorize launch.
83+
pub(crate) fn display_path(&self, name: &str) -> Option<PathBuf> {
84+
let filename = filename(name);
85+
self.files
86+
.contains_key(&filename)
87+
.then(|| self.directory.join(filename))
88+
}
8289
pub(crate) fn executable(&self, name: &str) -> Result<PathBuf> {
8390
let filename = filename(name);
8491
let expected = self

‎crates/agent-controller/src/config.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,7 @@ pub struct HarnessView {
7171
#[serde(rename_all = "lowercase")]
7272
pub enum ProcessStatus {
7373
Stopped,
74+
Waiting,
7475
Starting,
7576
Running,
7677
Stopping,

‎crates/agent-controller/src/credentials.rs‎

Lines changed: 36 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,14 @@
11
//! Exact-source read-only legacy lookup and create-only native credential custody.
2-
//! No environment, shell, per-key migration or fallback to another legacy service.
2+
//! No environment, shell or fallback to another legacy service.
33
use crate::{Credentials, LegacySource, Result, Secret};
44
use std::collections::BTreeMap;
55
use std::sync::Arc;
66
use zeroize::{Zeroize, Zeroizing};
77

8+
#[cfg(any(target_os = "macos", test))]
9+
mod bundle;
10+
#[cfg(any(target_os = "macos", test))]
11+
mod bundle_lock;
812
mod platform;
913
#[cfg(test)]
1014
mod tests;
@@ -19,7 +23,6 @@ enum Failure {
1923
Denied,
2024
Corrupt,
2125
Unavailable,
22-
#[cfg(any(target_os = "windows", target_os = "linux", test))]
2326
Busy,
2427
}
2528
impl Failure {
@@ -31,8 +34,7 @@ impl Failure {
3134
}
3235
Self::Denied => "Secure storage access was denied; allow access explicitly and retry",
3336
Self::Corrupt => "Selected secure-storage credential is malformed",
34-
#[cfg(any(target_os = "windows", target_os = "linux", test))]
35-
Self::Busy => "Another Buzz app is accessing this credential; retry shortly",
37+
Self::Busy => "Credentials are busy; retry after the current operation finishes",
3638
Self::Unavailable => "The OS credential store is unavailable on this platform",
3739
}
3840
.into()
@@ -53,15 +55,27 @@ trait Keychain: Send + Sync {
5355
) -> std::result::Result<Zeroizing<Vec<u8>>, Failure>;
5456
fn add(&self, service: &str, account: &str, value: &[u8]) -> std::result::Result<(), Failure>;
5557
fn delete(&self, service: &str, account: &str) -> std::result::Result<(), Failure>;
58+
#[cfg(any(target_os = "macos", test))]
59+
fn replace(&self, _: &str, _: &str, _: &[u8]) -> std::result::Result<(), Failure> {
60+
Err(Failure::Unavailable)
61+
}
62+
#[cfg(any(target_os = "macos", test))]
63+
fn bundle_lock(&self) -> std::result::Result<Box<dyn bundle::BundleLock>, Failure> {
64+
Err(Failure::Unavailable)
65+
}
5666
}
5767

5868
pub struct PlatformCredentials {
5969
keychain: Arc<dyn Keychain>,
70+
#[cfg(any(target_os = "macos", test))]
71+
bundle: Option<bundle::Bundle>,
6072
}
6173
impl Default for PlatformCredentials {
6274
fn default() -> Self {
6375
Self {
6476
keychain: Arc::new(platform::OsKeychain),
77+
#[cfg(any(target_os = "macos", test))]
78+
bundle: cfg!(target_os = "macos").then(bundle::Bundle::default),
6579
}
6680
}
6781
}
@@ -78,6 +92,12 @@ fn account(id: &str) -> Result<String> {
7892
}
7993

8094
impl Credentials for PlatformCredentials {
95+
fn retry(&self) {
96+
#[cfg(any(target_os = "macos", test))]
97+
if let Some(bundle) = &self.bundle {
98+
bundle.retry();
99+
}
100+
}
81101
fn read_legacy(&self, source: LegacySource, pubkey: &str) -> Result<Secret> {
82102
if !crate::config::canonical_key(pubkey) {
83103
return Err("Invalid selected agent identity".into());
@@ -102,6 +122,10 @@ impl Credentials for PlatformCredentials {
102122
if id.split_once('-').map(|(key, _)| key) != Some(pubkey) {
103123
return Err("Credential identifier does not match the selected agent".into());
104124
}
125+
#[cfg(any(target_os = "macos", test))]
126+
if let Some(bundle) = &self.bundle {
127+
return bundle.read(self.keychain.as_ref(), &account, pubkey);
128+
}
105129
match self.keychain.saved(SERVICE, &account) {
106130
Ok(bytes) => {
107131
if bytes.len() > 64 {
@@ -119,6 +143,10 @@ impl Credentials for PlatformCredentials {
119143
if id.split_once('-').map(|(pubkey, _)| pubkey) != Some(key.pubkey()) {
120144
return Err("Credential identifier does not match the selected agent".into());
121145
}
146+
#[cfg(any(target_os = "macos", test))]
147+
if let Some(bundle) = &self.bundle {
148+
return bundle.add(self.keychain.as_ref(), &account, key);
149+
}
122150
let value = key.hex();
123151
self.keychain
124152
.add(SERVICE, &account, value.as_bytes())
@@ -129,6 +157,10 @@ impl Credentials for PlatformCredentials {
129157
if id.split_once('-').map(|(key, _)| key) != Some(pubkey) {
130158
return Err("Credential identifier does not match the selected agent".into());
131159
}
160+
#[cfg(any(target_os = "macos", test))]
161+
if let Some(bundle) = &self.bundle {
162+
return bundle.delete(self.keychain.as_ref(), &account);
163+
}
132164
match self.keychain.delete(SERVICE, &account) {
133165
Ok(()) | Err(Failure::Absent) => Ok(()),
134166
Err(error) => Err(error.message()),
Lines changed: 180 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,180 @@
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

Comments
 (0)