agentmux_srv_core/backend/storage/muxbus.rs
1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4use rusqlite::params;
5use serde::{Deserialize, Serialize};
6
7use super::error::StoreError;
8use super::store::Store;
9use crate::identity::secret_store;
10
11/// The host-wide keychain namespace: the `stable` channel's (and any
12/// non-isolated channel's) MuxBus tokens. Same string as the broker's
13/// credential id, `crate::muxbus::CREDENTIAL_ID`.
14pub(super) const GLOBAL_KEYCHAIN_NS: &str = crate::muxbus::CREDENTIAL_ID;
15
16/// The channel whose own MuxBus sign-in this process uses. A channel is the
17/// unit of sign-in, not the host: every channel but `stable` (the installed
18/// releases, which have always used the host-wide set) signs in on its own, so
19/// two channels on one machine can be signed in at once, to the same account
20/// or to different ones, and one's refresh, sign-in or sign-out never touches
21/// the other's (SPEC_MUXBUS_SIGN_IN_PER_CHANNEL_2026_10_08.md).
22fn sign_in_channel(channel: Option<&str>) -> Option<&str> {
23 channel.filter(|c| !c.is_empty() && *c != "stable")
24}
25
26/// The keychain namespace this process's MuxBus tokens live under.
27pub(super) fn keychain_namespace() -> String {
28 namespace_for(std::env::var("AGENTMUX_CHANNEL").ok().as_deref())
29}
30
31fn namespace_for(channel: Option<&str>) -> String {
32 match sign_in_channel(channel) {
33 Some(ch) => format!("muxbus:channel:{ch}"),
34 None => GLOBAL_KEYCHAIN_NS.to_string(),
35 }
36}
37
38/// Whether the store this process reads is already this channel's own file
39/// (isolated auth with an instance dir: `registry::paths::resolve_shared_store_path`),
40/// where the channel needs no per-row scoping.
41fn store_is_channel_local() -> bool {
42 agentmux_common::isolated_auth_enabled()
43 && std::env::var_os("AGENTMUX_INSTANCE_DIR").is_some_and(|d| !d.is_empty())
44}
45
46/// The `db_muxbus_credentials` row id: `global` for `stable` and for a store
47/// that is already the channel's own, `channel:<ch>` for a channel's row in the
48/// store channels share.
49pub(super) fn row_id_for(channel: Option<&str>, own_store: bool) -> String {
50 match sign_in_channel(channel) {
51 Some(ch) if !own_store => format!("channel:{ch}"),
52 _ => "global".to_string(),
53 }
54}
55
56pub(super) fn current_row_id() -> String {
57 row_id_for(std::env::var("AGENTMUX_CHANNEL").ok().as_deref(), store_is_channel_local())
58}
59
60/// Prefix for this channel's rows in `db_agent_credentials`, which is keyed by
61/// agent id alone: empty for `stable` and for the channel's own store. An agent
62/// id is `[A-Za-z0-9_-]`, so the `/` can't collide with one.
63fn agent_credential_prefix_for(channel: Option<&str>, own_store: bool) -> String {
64 match sign_in_channel(channel) {
65 Some(ch) if !own_store => format!("{ch}/"),
66 _ => String::new(),
67 }
68}
69
70pub(super) fn current_agent_credential_prefix() -> String {
71 agent_credential_prefix_for(std::env::var("AGENTMUX_CHANNEL").ok().as_deref(), store_is_channel_local())
72}
73
74// ---- Cross-process lock ----------------------------------------------------
75//
76// `muxbus_save_lock` only serializes threads of ONE process, but the keychain
77// is host-wide and a Windows save is about a dozen writes. Two processes
78// interleaving left a torn set that reads treated as signed out. An OS file
79// lock makes save, load and clear one critical section across processes.
80
81/// How long a save, load or clear waits for another process. Past it the
82/// operation fails as transient (a load is retried, a sign-in reports an
83/// error) instead of running unlocked, which is what tore sign-ins.
84const XPROC_LOCK_WAIT: std::time::Duration = std::time::Duration::from_secs(5);
85
86/// A held OS advisory lock; released when dropped (the handle closes).
87pub(crate) struct CrossProcessGuard {
88 _file: std::fs::File,
89}
90
91/// Take the lock at `path`, polling until `wait` has passed. `None` when it
92/// couldn't be taken: another process held it the whole time, or the file
93/// couldn't be opened.
94pub(super) fn lock_file(path: &std::path::Path, wait: std::time::Duration) -> Option<CrossProcessGuard> {
95 if let Some(dir) = path.parent() {
96 let _ = std::fs::create_dir_all(dir);
97 }
98 // Never deleted: unlinking a locked file lets a waiter lock a different
99 // inode than a newcomer (registry/leases.rs `CriticalSection`).
100 let file = std::fs::OpenOptions::new().create(true).write(true).open(path).ok()?;
101 let deadline = std::time::Instant::now() + wait;
102 loop {
103 match crate::registry::try_lock_exclusive(&file) {
104 Ok(true) => return Some(CrossProcessGuard { _file: file }),
105 Ok(false) if std::time::Instant::now() < deadline => {
106 std::thread::sleep(std::time::Duration::from_millis(25));
107 }
108 Ok(false) | Err(_) => return None,
109 }
110 }
111}
112
113/// The lock for keychain namespace `ns`, under `root`'s `muxbus-locks`. With
114/// no shared root (some test setups) there is nowhere to put it: `Ok(None)`.
115fn lock_in(
116 root: Option<std::path::PathBuf>,
117 ns: &str,
118 wait: std::time::Duration,
119) -> Result<Option<CrossProcessGuard>, StoreError> {
120 let Some(root) = root else { return Ok(None) };
121 let path = root.join("muxbus-locks").join(format!("{}.lock", ns.replace(':', "_")));
122 lock_file(&path, wait).map(Some).ok_or_else(|| {
123 tracing::warn!(namespace = %ns, "muxbus: couldn't take the keychain lock within {wait:?}");
124 StoreError::Other(format!("muxbus: couldn't take the keychain lock for {ns} within {wait:?}; try again"))
125 })
126}
127
128pub(super) fn lock_namespace(ns: &str) -> Result<Option<CrossProcessGuard>, StoreError> {
129 lock_in(crate::registry::resolve_global_shared_root(), ns, XPROC_LOCK_WAIT)
130}
131
132/// How long a refresh waits for another process's refresh of the same
133/// sign-in: long enough to cover a slow token request.
134const REFRESH_LOCK_WAIT: std::time::Duration = std::time::Duration::from_secs(30);
135
136/// Single-entry key holding all three tokens as one JSON blob. Two different
137/// roles depending on platform (see `muxbus_load_tokens` / `muxbus_save`):
138///
139/// - **Windows**: legacy (pre-2026-08-03) only. Windows Credential Manager
140/// caps a single entry's blob at 2560 bytes (`CRED_MAX_CREDENTIAL_BLOB_SIZE`)
141/// — a Cognito `id_token` alone can approach that, and combined with
142/// `access_token`+`refresh_token` reliably exceeds it (see
143/// `docs/specs/PLAN_MUXBUS_KEYCHAIN_WINDOWS_BLOB_LIMIT_2026_08_03.md`). Kept
144/// only as a one-time migration source there; every Windows write goes
145/// through the chunked per-field layout below instead.
146/// - **macOS/Linux**: the CURRENT, preferred format. These platforms have no
147/// comparable blob-size cap, so the chunked layout's only purpose there
148/// was to be platform-uniform with Windows — but each of its ~12 separate
149/// keychain entries is its own OS-level access-consent decision, and macOS
150/// Keychain prompts per-entry until each is individually trusted. Granting
151/// "Always Allow" on one entry just surfaced the next entry's own prompt,
152/// making the whole flow look broken (retro-macos-muxbus-keychain-prompt-
153/// storm-2026-08-19.md). One combined blob means one prompt, that one
154/// "Always Allow" click actually sticks.
155/// The blob lives at the namespace itself (`muxbus:global` for the host-wide
156/// set), the split fields under it (`<ns>:access`, ...).
157pub(super) fn blob_key(ns: &str) -> String {
158 ns.to_string()
159}
160
161const FIELD_ACCESS: &str = "access";
162const FIELD_REFRESH: &str = "refresh";
163const FIELD_ID: &str = "id";
164
165fn field_key(ns: &str, field: &str) -> String {
166 format!("{ns}:{field}")
167}
168
169/// A first fix attempt (splitting the combined blob into one keychain entry
170/// per field) turned out NOT to be sufficient: live-tested against a real
171/// Cognito login, the exact same "Attribute 'password' is longer than
172/// platform limit of 2560 chars" error still fired — a single token field
173/// can itself exceed the cap depending on the app client's token content
174/// (custom claims, refresh token length), not just the three combined. So
175/// each field is further chunked into as many entries as it takes, tracked
176/// by an explicit `<field>:count` entry (`write_chunked_field` /
177/// `read_chunked_field` below) — this holds regardless of any individual
178/// token's real-world size, instead of relying on an assumption about it.
179///
180/// A second live test with a 1800-char budget hit the SAME error again —
181/// the `keyring` crate's Windows backend checks
182/// `password.encode_utf16().count() * 2 > CRED_MAX_CREDENTIAL_BLOB_SIZE`
183/// (2560 *bytes*), but its own error message reports that raw byte count as
184/// if it were a char limit ("longer than platform limit of 2560 chars").
185/// Since Windows stores the value as UTF-16 (2 bytes/char), the real
186/// character budget is `CRED_MAX_CREDENTIAL_BLOB_SIZE / 2` = 1280, not 2560
187/// — `keyring-2.3.3/src/windows.rs:182` vs. its own error text at
188/// that crate's `error.rs` (its `TooLong` message). 1800 was 40% over that
189/// real limit. Budget well under 1280 here, not just under the misleading
190/// 2560 the error text implies.
191const MAX_CHUNK_LEN: usize = 1000;
192
193fn chunk_key(field_key: &str, index: usize) -> String {
194 format!("{field_key}:{index}")
195}
196
197fn count_key(field_key: &str) -> String {
198 format!("{field_key}:count")
199}
200
201fn generation_key(field_key: &str) -> String {
202 format!("{field_key}:gen")
203}
204
205/// A per-write identifier stamped onto all three fields by a single
206/// `write_split_tokens` call, so `read_split_tokens` can detect a torn
207/// write ACROSS a process crash — not the concurrent-read-in-one-process
208/// case `muxbus_load_impl`'s lock already covers, but a kill signal
209/// landing mid-write, between one field's `write_chunked_field` call
210/// completing and the next one starting (reagent P2: each field is
211/// individually self-consistent, per `write_chunked_field`'s own
212/// chunk+rollback atomicity, but with no lock surviving the process
213/// there's nothing to stop the OLD stale value for the not-yet-reached
214/// field from still being present when the other two ARE the fresh ones —
215/// silently reconstructing a token set that pairs pieces from two
216/// different login sessions). High-resolution wall-clock nanos is unique
217/// enough for this purpose in practice; a formal UUID would work too but
218/// adds a dependency for no real benefit here.
219fn new_generation() -> String {
220 std::time::SystemTime::now()
221 .duration_since(std::time::UNIX_EPOCH)
222 .unwrap_or_default()
223 .as_nanos()
224 .to_string()
225}
226
227/// Pure chunking split — no keychain I/O — so the boundary math is testable
228/// without touching the real OS keychain. A token's bytes are always ASCII
229/// in practice (JWTs / opaque base64url strings), so splitting on byte
230/// boundaries never lands mid-character; `unwrap_or("")` is a defensive
231/// fallback only, not an expected path.
232fn chunk_value(value: &str) -> Vec<&str> {
233 if value.is_empty() {
234 return vec![""];
235 }
236 value
237 .as_bytes()
238 .chunks(MAX_CHUNK_LEN)
239 .map(|c| std::str::from_utf8(c).unwrap_or(""))
240 .collect()
241}
242
243/// A previous, longer value at a field could in principle need many chunks;
244/// no real Cognito token comes remotely close (`MAX_PLAUSIBLE_CHUNKS *
245/// MAX_CHUNK_LEN` = 32,000 chars). Used only as `muxbus_clear`'s fallback
246/// deletion bound when the real count can't be read (see its call site) —
247/// `secret_store::delete` on a non-existent entry is a no-op success, so
248/// scanning past the real count there is harmless, just wasted calls.
249const MAX_PLAUSIBLE_CHUNKS: usize = 32;
250
251/// `Ok(0)` means the `:count` entry genuinely doesn't exist (field never
252/// written under the chunked layout). `Err` means the read itself failed —
253/// reagent P1: a prior version of this collapsed both into the same `0`,
254/// which `muxbus_clear` used to bound its per-field deletion loop
255/// (`for i in 0..count`) — a transient read failure made that loop delete
256/// NOTHING, while the field's `:count` key was still deleted unconditionally
257/// right after, so logout appeared to succeed while the real token chunks
258/// were silently orphaned in the OS keychain. Callers must not treat `Err`
259/// as "0 chunks."
260fn read_chunk_count(field_key: &str) -> Result<usize, StoreError> {
261 match secret_store::get_optional(&count_key(field_key)) {
262 Ok(Some(v)) => v
263 .parse::<usize>()
264 .map_err(|e| StoreError::Other(format!("muxbus: corrupted chunk count for {field_key}: {e}"))),
265 Ok(None) => Ok(0),
266 Err(e) => Err(StoreError::Other(format!("muxbus: keychain read failed: {e}"))),
267 }
268}
269
270#[derive(Debug, Clone, Default)]
271pub struct MuxBusCredentials {
272 pub cognito_domain: String,
273 pub client_id: String,
274 pub access_token: String,
275 pub refresh_token: String,
276 pub id_token: String,
277 pub expires_at: i64,
278 pub user_email: String,
279 pub user_sub: String,
280}
281
282/// The actual secret material. Every field is written to its own keychain
283/// entry (`field_key`); this struct only groups them for callers and for
284/// deserializing the legacy combined-blob format during migration.
285/// Everything else on `MuxBusCredentials` is non-secret metadata and stays
286/// in SQLite, matching how `SecretRef::Keychain` accounts already split
287/// pointer-metadata (DB) from plaintext (keychain) elsewhere in this codebase.
288#[derive(Serialize, Deserialize, Default, Clone)]
289pub(super) struct MuxBusTokens {
290 pub(super) access_token: String,
291 pub(super) refresh_token: String,
292 pub(super) id_token: String,
293}
294
295impl MuxBusTokens {
296 /// The tokens `creds` holds, which are never written into a transcript from here on.
297 fn withheld_of(creds: &MuxBusCredentials) -> Self {
298 crate::backend::transcript::withhold_sources::cloud_sign_in(&creds.access_token, &creds.refresh_token, &creds.id_token, creds.expires_at);
299 Self { access_token: creds.access_token.clone(), refresh_token: creds.refresh_token.clone(), id_token: creds.id_token.clone() }
300 }
301}
302
303/// On-disk JSON shape for the single-blob format (macOS/Linux's preferred
304/// layout, `write_single_blob`/`blob_key`). Wraps
305/// `MuxBusTokens` with a generation stamp — the SAME `new_generation()`
306/// nanosecond-timestamp scheme the chunked layout already uses for its own
307/// cross-field torn-write check — so a blob and split entries found
308/// coexisting (`muxbus_load_tokens`'s reconciliation) can be compared for
309/// actual freshness instead of assuming a fixed direction is always right.
310///
311/// reagent P1 on PR #2665: an earlier version of the reconciliation logic
312/// hardcoded "split is always fresher," which was true for the ONE
313/// historical case that motivated it (an old pre-fix blob→split migration
314/// whose blob delete failed) but breaks once THIS fix's own self-heal can
315/// also leave stale split leftovers behind a newer blob (if
316/// `delete_split_tokens` partially fails, then a later muxbus_save — which
317/// on macOS/Linux only ever writes the blob — updates the blob but not the
318/// stale split entries). An actual freshness comparison handles both
319/// directions correctly instead of guessing.
320///
321/// `#[serde(default)]` on `generation` means a genuinely old, pre-fix
322/// legacy blob (written before this stamp existed) deserializes with an
323/// empty generation, which reads as timestamp `0` — always losing a
324/// freshness comparison against any split entry's real generation stamp,
325/// which is exactly the right outcome for that original historical case.
326#[derive(Serialize, Deserialize, Default)]
327pub(super) struct MuxBusBlob {
328 #[serde(flatten)]
329 pub(super) tokens: MuxBusTokens,
330 #[serde(default)]
331 pub(super) generation: String,
332}
333
334/// Parse a `new_generation()`-style nanosecond-timestamp string into a
335/// comparable number. An empty or corrupted value reads as `0` — the
336/// oldest possible timestamp — so it always loses a freshness comparison
337/// rather than erroring a read that would otherwise succeed.
338pub(super) fn generation_as_number(generation: &str) -> u128 {
339 generation.parse().unwrap_or(0)
340}
341
342/// What a keychain entry held immediately before a write to it, so a later
343/// failure (the SQL write in `muxbus_save`, or a sibling field's write in
344/// `write_split_tokens`) can be rolled back to that exact prior state.
345/// Three-way, not a bool: reagent P1 on #2260 caught a first version of this
346/// that collapsed `Ok(None)` ("genuinely no prior entry") and `Err` ("the
347/// read itself failed, prior state UNKNOWN") into the same `None`, so an
348/// unrelated transient read failure would make the rollback branch delete a
349/// real, valid, previously-stored credential it simply couldn't read —
350/// turning a transient glitch into a forced full re-login. `Unknown` gets
351/// neither restore nor delete: we truly don't know what was there, so the
352/// only safe move is to leave whatever the write just wrote and log loudly.
353pub(super) enum PriorKeychainState {
354 Existed(zeroize::Zeroizing<String>),
355 Absent,
356 Unknown,
357}
358
359impl PriorKeychainState {
360 fn capture(key: &str) -> Self {
361 match secret_store::get_optional(key) {
362 Ok(Some(v)) => PriorKeychainState::Existed(v),
363 Ok(None) => PriorKeychainState::Absent,
364 Err(_) => PriorKeychainState::Unknown,
365 }
366 }
367
368 fn restore(&self, key: &str) -> Result<(), String> {
369 match self {
370 PriorKeychainState::Existed(old) => secret_store::put(key, old.as_str()),
371 PriorKeychainState::Absent => secret_store::delete(key),
372 PriorKeychainState::Unknown => Ok(()),
373 }
374 }
375}
376
377/// Write `value` to `field_key` as one or more chunk entries (each under
378/// `MAX_CHUNK_LEN`) plus a `:count` entry, clearing any stale trailing
379/// chunks left over from a previous, longer value at this key, and stamps
380/// `generation` (same value across all three fields for one
381/// `write_split_tokens` call — see `new_generation`'s doc comment) on this
382/// field's `:gen` entry. Rolls back everything this call touched if any
383/// single write/delete fails partway through.
384///
385/// Write order matters here beyond just "rollback on failure" (reagent P1:
386/// a prior version wrote chunks, then cleared stale trailing chunks, then
387/// updated `:count`, then `:gen`, in that order — a process CRASH between
388/// the chunk-write and the trailing-chunk-delete left `:count` still
389/// pointing at the OLD larger count while the leading chunks already held
390/// NEW content; on restart `read_chunked_field` would read exactly
391/// `old_count` chunks — none technically missing, so no error — silently
392/// reconstructing a spliced new-prefix/old-suffix value that's neither the
393/// old nor the new token, with `:gen` untouched so `read_split_tokens`'s
394/// cross-field generation check never even saw a mismatch to catch). This
395/// version deletes `:gen` FIRST, before touching any chunk content, and
396/// writes the fresh `generation` value LAST, only once chunks + `:count`
397/// are fully consistent — `read_chunked_field` already treats a missing
398/// `:gen` on an otherwise-populated field as an error, so a crash ANYWHERE
399/// in between now makes this field unambiguously detectable as torn,
400/// rather than silently reconstructible.
401///
402/// On success, returns the PRE-call state of every entry touched (`:gen`,
403/// chunks, `:count`), so a caller doing more work of its own afterward
404/// (`write_split_tokens` covering a sibling field, or `muxbus_save`'s SQL
405/// write) can roll all of it back together if that later step fails too.
406fn write_chunked_field(
407 field_key: &str,
408 value: &str,
409 generation: &str,
410) -> Result<Vec<(String, PriorKeychainState)>, StoreError> {
411 let new_chunks = chunk_value(value);
412 let new_count = new_chunks.len();
413 // Propagate a genuine read failure rather than assuming 0 — silently
414 // treating "couldn't read the old count" as "there were no stale
415 // trailing chunks" would skip cleaning up real leftover chunk data from
416 // a previous, longer value (same class of bug as the read_chunk_count
417 // doc comment describes for muxbus_clear).
418 let old_count = read_chunk_count(field_key)?;
419
420 let mut priors: Vec<(String, PriorKeychainState)> = Vec::with_capacity(new_count.max(old_count) + 2);
421 let rollback = |priors: &[(String, PriorKeychainState)]| {
422 for (key, prior) in priors {
423 if let Err(re) = prior.restore(key) {
424 tracing::warn!(
425 error = %re,
426 key = %key,
427 "muxbus: rollback after a partial chunked-field write failure also failed \
428 for this entry — keychain may now hold a stale value for it"
429 );
430 }
431 }
432 };
433
434 // Invalidate this field before touching any chunk content — see the
435 // doc comment above for why this specific ordering is load-bearing.
436 // The captured `gen_prior` (this field's TRUE pre-call `:gen` state) is
437 // what a later rollback restores to, whether the failure happens here,
438 // mid-chunk-write, or in the final `:gen` write at the bottom of this
439 // function — there is deliberately only ONE priors entry for this key.
440 let gk = generation_key(field_key);
441 let gen_prior = PriorKeychainState::capture(&gk);
442 if let Err(e) = secret_store::delete(&gk) {
443 return Err(StoreError::Other(format!("muxbus: keychain write failed: {e}")));
444 }
445 priors.push((gk.clone(), gen_prior));
446
447 for (i, chunk) in new_chunks.iter().enumerate() {
448 let key = chunk_key(field_key, i);
449 let prior = PriorKeychainState::capture(&key);
450 if let Err(e) = secret_store::put(&key, chunk) {
451 rollback(&priors);
452 return Err(StoreError::Other(format!("muxbus: keychain write failed: {e}")));
453 }
454 priors.push((key, prior));
455 }
456
457 // A previous, longer value left trailing chunks beyond the new count —
458 // clear them, or a future read would append stale old data past the
459 // new count boundary... except reads stop at `count`, so leftover
460 // chunks are actually inert. Clear them anyway: cheap, and avoids ever
461 // depending on that "reads ignore trailing chunks" invariant holding.
462 for i in new_count..old_count {
463 let key = chunk_key(field_key, i);
464 let prior = PriorKeychainState::capture(&key);
465 if let Err(e) = secret_store::delete(&key) {
466 rollback(&priors);
467 return Err(StoreError::Other(format!("muxbus: keychain write failed: {e}")));
468 }
469 priors.push((key, prior));
470 }
471
472 let ck = count_key(field_key);
473 let prior = PriorKeychainState::capture(&ck);
474 if let Err(e) = secret_store::put(&ck, &new_count.to_string()) {
475 rollback(&priors);
476 return Err(StoreError::Other(format!("muxbus: keychain write failed: {e}")));
477 }
478 priors.push((ck, prior));
479
480 // Write the fresh generation LAST — only once chunks + :count are fully
481 // consistent. This is what makes the field valid (readable) again; the
482 // `gk` rollback entry already pushed above (this field's true pre-call
483 // state) is reused if THIS write itself fails, not a fresh capture —
484 // capturing now would wrongly record "Absent" (we deleted it ourselves
485 // above) as what to roll back to.
486 if let Err(e) = secret_store::put(&gk, generation) {
487 rollback(&priors);
488 return Err(StoreError::Other(format!("muxbus: keychain write failed: {e}")));
489 }
490
491 Ok(priors)
492}
493
494/// Read `field_key`'s value + generation stamp back from its chunk entries.
495/// `Ok(None)` means no `:count` entry exists yet (this field was never
496/// written under the chunked layout — caller falls through to the
497/// legacy-blob / legacy-plaintext sources). `Err` means a read genuinely
498/// failed, or the chunk state is internally inconsistent (a chunk went
499/// missing between the count write and now) — not just "no entry". A
500/// missing `:gen` entry on an otherwise-complete field is treated as a read
501/// failure too, not defaulted to some sentinel — see `read_split_tokens`,
502/// which needs a REAL generation to compare across fields, not a value
503/// that would spuriously "match" another field's own missing generation.
504/// Why `read_chunked_field` has no value: the field is mid-write or was
505/// interrupted (`Yes`, a torn read to retry), or the keychain failed (`No`).
506enum FieldIncomplete {
507 Yes,
508 No(StoreError),
509}
510
511fn read_chunked_field(field_key: &str) -> Result<Option<(String, String)>, FieldIncomplete> {
512 let failed = |e| FieldIncomplete::No(StoreError::Other(format!("muxbus: keychain read failed: {e}")));
513 let count = match secret_store::get_optional(&count_key(field_key)) {
514 Ok(Some(v)) => v.parse::<usize>().map_err(|e| {
515 FieldIncomplete::No(StoreError::Other(format!("muxbus: corrupted chunk count for {field_key}: {e}")))
516 })?,
517 Ok(None) => return Ok(None),
518 Err(e) => return Err(failed(e)),
519 };
520 let mut value = String::new();
521 for i in 0..count {
522 match secret_store::get_optional(&chunk_key(field_key, i)) {
523 Ok(Some(chunk)) => value.push_str(&chunk),
524 Ok(None) => return Err(FieldIncomplete::Yes),
525 Err(e) => return Err(failed(e)),
526 }
527 }
528 let generation = match secret_store::get_optional(&generation_key(field_key)) {
529 Ok(Some(g)) => g.to_string(),
530 Ok(None) => return Err(FieldIncomplete::Yes),
531 Err(e) => return Err(failed(e)),
532 };
533 Ok(Some((value, generation)))
534}
535
536/// Write all three tokens as one combined JSON blob under a single keychain
537/// entry (`blob_key` — the CURRENT preferred format on
538/// macOS/Linux, see that constant's doc comment). One `SecItemAdd`/
539/// `SecItemUpdate` call is inherently atomic at the OS level, so this needs
540/// none of `write_split_tokens`'s cross-field generation-stamp/rollback
541/// machinery — there's only one field. Returns the pre-call state wrapped in
542/// the same `Vec<(String, PriorKeychainState)>` shape `write_split_tokens`
543/// returns, so `muxbus_save`'s SQL-failure rollback branch works unchanged
544/// regardless of which one ran.
545pub(super) fn write_single_blob(ns: &str, tokens: &MuxBusTokens) -> Result<Vec<(String, PriorKeychainState)>, StoreError> {
546 let key = blob_key(ns);
547 let prior = PriorKeychainState::capture(&key);
548 // Always stamps a FRESH generation, even when the caller is re-writing
549 // the same token values (e.g. reconciling a coexisting blob + split
550 // layout in `muxbus_load_tokens` — see `MuxBusBlob`'s doc comment) —
551 // "written just now" is itself real freshness information for the next
552 // comparison, regardless of whether the underlying secret changed.
553 let value = MuxBusBlob {
554 tokens: tokens.clone(),
555 generation: new_generation(),
556 };
557 let blob = serde_json::to_string(&value)
558 .map_err(|e| StoreError::Other(format!("muxbus: failed to serialize tokens: {e}")))?;
559 if let Err(e) = secret_store::put(&key, &blob) {
560 return Err(StoreError::Other(format!("muxbus: keychain write failed: {e}")));
561 }
562 Ok(vec![(key, prior)])
563}
564
565/// Delete every entry the chunked per-field layout could have written
566/// (`FIELD_ACCESS`/`FIELD_REFRESH`/`FIELD_ID`'s chunks + `:count` + `:gen`).
567/// Shared by `muxbus_clear` (unconditional logout cleanup, any platform) and
568/// the macOS/Linux migration path in `muxbus_load_tokens` (collapsing a
569/// pre-fix install's chunked entries into the single-blob format — see
570/// `blob_key`'s doc comment). Best-effort: `secret_store::delete`
571/// on a non-existent entry is a no-op success, and a real delete failure here
572/// just leaves an orphaned, unreadable-without-the-others chunk behind rather
573/// than losing anything live.
574pub(super) fn delete_split_tokens(ns: &str) {
575 for field in [FIELD_ACCESS, FIELD_REFRESH, FIELD_ID] {
576 let fk = field_key(ns, field);
577 // A count-read failure must NOT be treated as "0 chunks" (see
578 // read_chunk_count's doc comment) — that would delete nothing here
579 // while still unconditionally deleting the `:count` key below,
580 // orphaning the real token chunks in the OS keychain. Fall back to
581 // scanning a generous bound instead: `secret_store::delete` on a
582 // non-existent entry is a no-op success, so deleting past the real
583 // count is harmless — it guarantees actual cleanup even when the
584 // count itself is unreadable.
585 let count = match read_chunk_count(&fk) {
586 Ok(n) => n,
587 Err(e) => {
588 tracing::warn!(
589 error = %e,
590 field = %fk,
591 "muxbus: couldn't read this field's chunk count while deleting split \
592 entries — falling back to a bounded scan so real token chunks still get \
593 deleted"
594 );
595 MAX_PLAUSIBLE_CHUNKS
596 }
597 };
598 for i in 0..count {
599 let _ = secret_store::delete(&chunk_key(&fk, i));
600 }
601 let _ = secret_store::delete(&count_key(&fk));
602 let _ = secret_store::delete(&generation_key(&fk));
603 }
604}
605
606/// Write all three token fields, each independently chunked
607/// (`write_chunked_field`). On a later field's failure, rolls back every
608/// entry every earlier field in this call already wrote — otherwise a
609/// partial failure would leave the three fields holding a mix of old and
610/// new tokens, which is worse than either the old or the new set alone.
611///
612/// On success, returns every entry's PRE-call state (across all three
613/// fields) so `muxbus_save`'s SQL-write failure branch can roll all of it
614/// back together too.
615pub(super) fn write_split_tokens(ns: &str, tokens: &MuxBusTokens) -> Result<Vec<(String, PriorKeychainState)>, StoreError> {
616 let generation = new_generation();
617 let fields: [(String, &str); 3] = [
618 (field_key(ns, FIELD_ACCESS), tokens.access_token.as_str()),
619 (field_key(ns, FIELD_REFRESH), tokens.refresh_token.as_str()),
620 (field_key(ns, FIELD_ID), tokens.id_token.as_str()),
621 ];
622 let mut all_priors: Vec<(String, PriorKeychainState)> = Vec::new();
623 for (key, value) in fields {
624 match write_chunked_field(&key, value, &generation) {
625 Ok(priors) => all_priors.extend(priors),
626 Err(e) => {
627 for (done_key, done_prior) in &all_priors {
628 if let Err(re) = done_prior.restore(done_key) {
629 tracing::warn!(
630 error = %re,
631 key = %done_key,
632 "muxbus: rollback after a partial split-token write failure also failed \
633 for this entry — keychain may now hold a stale value for it"
634 );
635 }
636 }
637 return Err(e);
638 }
639 }
640 }
641 Ok(all_priors)
642}
643
644/// The tokens stored under `ns` in either layout (chunked split entries or
645/// the single blob), without migrating or deleting anything. `None` when
646/// neither layout holds a complete, consistent set or a read fails. Used
647/// only to adopt the host-wide session into a channel namespace.
648///
649/// When both layouts are present, the fresher generation wins, the same
650/// rule `muxbus_load_tokens` applies: on macOS/Linux `muxbus_save` writes
651/// only the blob, so split entries left over beside it are older and must
652/// not be adopted over it. A blob without a generation (the legacy Windows
653/// format) ranks oldest, so Windows' current split layout wins over it.
654pub(super) fn read_any_layout(ns: &str) -> Option<MuxBusTokens> {
655 let split = read_split_tokens(ns).ok().flatten();
656 let blob = secret_store::get_optional(&blob_key(ns))
657 .ok()
658 .flatten()
659 .and_then(|b| serde_json::from_str::<MuxBusBlob>(&b).ok());
660 match (split, blob) {
661 (Some((split_tokens, split_gen)), Some(blob)) => {
662 if generation_as_number(&split_gen) > generation_as_number(&blob.generation) {
663 Some(split_tokens)
664 } else {
665 Some(blob.tokens)
666 }
667 }
668 (Some((split_tokens, _)), None) => Some(split_tokens),
669 (None, Some(blob)) => Some(blob.tokens),
670 (None, None) => None,
671 }
672}
673
674/// Read the three split-entry (chunked) tokens. `Ok(None)` means none of the
675/// three fields exist yet (not migrated to this layout — caller falls
676/// through to the legacy-blob / legacy-plaintext sources). `Err` means a
677/// read itself failed (locked keychain, no Secret Service daemon,
678/// permission denied — not just "no entry"), which the caller may still
679/// recover from via a legacy fallback.
680/// Returns the tokens plus the generation stamp shared by all three fields
681/// (validated equal below) — callers that need to compare this layout's
682/// freshness against a coexisting blob use the second element; callers that
683/// don't (the common case) just ignore it.
684pub(super) fn read_split_tokens(ns: &str) -> Result<Option<(MuxBusTokens, String)>, StoreError> {
685 match read_split_settled(ns)? {
686 SplitRead::Complete(tokens, generation) => Ok(Some((tokens, generation))),
687 SplitRead::Absent => Ok(None),
688 SplitRead::Torn { .. } => {
689 tracing::warn!(
690 "muxbus: split keychain entries have mismatched generation stamps or are \
691 incomplete (a torn write from an interrupted or concurrent save) — \
692 treating as not signed in; signing in again repairs it"
693 );
694 Ok(None)
695 }
696 }
697}
698
699/// Whether `tokens` were issued to the account `user_sub` names. A token that
700/// isn't a JWT, or a row with no `user_sub`, matches nothing.
701pub(super) fn same_account(tokens: &MuxBusTokens, user_sub: &str) -> bool {
702 let sub = crate::muxbus::pkce::token_sub(&tokens.id_token);
703 let sub = if sub.is_empty() { crate::muxbus::pkce::token_sub(&tokens.access_token) } else { sub };
704 !user_sub.is_empty() && sub == user_sub
705}
706
707/// What the three split entries held when read.
708pub(super) enum SplitRead {
709 /// None of the three fields exist yet.
710 Absent,
711 /// All three, from one save.
712 Complete(MuxBusTokens, String),
713 /// Present but not from one save: a read that landed mid-write, or a
714 /// write that was interrupted. `refresh` is the refresh token if its own
715 /// field is whole: Cognito doesn't rotate it, so refreshing with it can
716 /// make the set whole again.
717 Torn { refresh: Option<String> },
718}
719
720/// Read the split entries, retrying a few times while they look torn: a save
721/// by an older build (no cross-process lock) may be mid-write, and a moment
722/// later the same read is whole. A tear that persists is genuine.
723pub(super) fn read_split_settled(ns: &str) -> Result<SplitRead, StoreError> {
724 retry_while_torn(|| read_split_state(ns), 4, std::time::Duration::from_millis(120))
725}
726
727fn retry_while_torn<F>(mut read: F, tries: u32, pause: std::time::Duration) -> Result<SplitRead, StoreError>
728where
729 F: FnMut() -> Result<SplitRead, StoreError>,
730{
731 let mut last = read()?;
732 for _ in 1..tries {
733 if !matches!(last, SplitRead::Torn { .. }) {
734 break;
735 }
736 std::thread::sleep(pause);
737 last = read()?;
738 }
739 Ok(last)
740}
741
742fn read_split_state(ns: &str) -> Result<SplitRead, StoreError> {
743 let read = |field| match read_chunked_field(&field_key(ns, field)) {
744 Err(FieldIncomplete::No(e)) => Err(e),
745 Err(FieldIncomplete::Yes) => Ok(None),
746 Ok(v) => Ok(Some(v)),
747 };
748 let (access, refresh, id) = (read(FIELD_ACCESS)?, read(FIELD_REFRESH)?, read(FIELD_ID)?);
749 let surviving = refresh.clone().flatten().map(|(token, _)| token).filter(|t| !t.is_empty());
750 let torn = || Ok(SplitRead::Torn { refresh: surviving.clone() });
751 // `None` here is a field caught mid-write (a chunk or `:gen` missing).
752 let (Some(access), Some(refresh), Some(id)) = (access, refresh, id) else {
753 return torn();
754 };
755
756 match (access, refresh, id) {
757 (None, None, None) => Ok(SplitRead::Absent),
758 (Some((access_token, gen_a)), Some((refresh_token, gen_r)), Some((id_token, gen_i))) => {
759 // reagent P2: write_split_tokens's own writes are individually
760 // consistent per-field (write_chunked_field's chunk+rollback
761 // atomicity) but not atomic ACROSS fields — a process kill
762 // between two fields' writes can leave one field's stale OLD
763 // value sitting next to the other two fields' fresh values,
764 // each independently well-formed, silently pairing tokens from
765 // two different login sessions. All three fields' generation
766 // stamps only match when they came from the SAME
767 // write_split_tokens call — a mismatch means a torn write.
768 if gen_a == gen_r && gen_r == gen_i {
769 Ok(SplitRead::Complete(
770 MuxBusTokens {
771 access_token,
772 refresh_token,
773 id_token,
774 },
775 gen_a,
776 ))
777 } else {
778 torn()
779 }
780 }
781 // Some fields present, some absent: shouldn't happen in normal
782 // operation (write_split_tokens writes and rolls back all three
783 // together) but follows an interrupted write.
784 _ => torn(),
785 }
786}
787
788impl MuxBusCredentials {
789 pub fn is_valid(&self) -> bool {
790 !self.access_token.is_empty() && self.expires_at > agentmux_common::time::now_secs()
791 }
792
793 pub fn nearly_expired(&self) -> bool {
794 !self.access_token.is_empty() && self.expires_at - agentmux_common::time::now_secs() < 300
795 }
796}
797
798impl Store {
799 pub fn muxbus_load(&self) -> Result<Option<MuxBusCredentials>, StoreError> {
800 self.muxbus_load_impl(true)
801 }
802
803 /// Side-effect-free (no keychain/SQL WRITE, see `allow_migration` below)
804 /// freshness check: valid, non-empty access token that isn't nearing
805 /// expiry. Safe for `RefreshScheduler::register`'s `is_fresh` closure,
806 /// called as it is under the per-id lock on every `ensure_fresh`/sweep
807 /// tick — the concern that closure must avoid (reagent P2 on #2260) is
808 /// an unexpected WRITE happening inside a nominally read-only check,
809 /// not lock acquisition itself; `muxbus_load_impl` below still takes
810 /// `muxbus_save_lock` (reagent P1 on this PR — see its comment) purely
811 /// to serialize this read against a concurrent writer, with no side
812 /// effect of its own performed while holding it. Any error (including a
813 /// genuinely corrupted keychain entry) is treated as "not fresh" rather
814 /// than propagated — a freshness *check* has no error channel to
815 /// propagate through, and "not fresh" just means the broker will
816 /// attempt a refresh, which surfaces the real problem through THAT path
817 /// instead.
818 pub fn muxbus_is_fresh(&self) -> bool {
819 self.muxbus_load_impl(false)
820 .ok()
821 .flatten()
822 .map(|c| !c.access_token.is_empty() && c.is_valid() && !c.nearly_expired())
823 .unwrap_or(false)
824 }
825
826 /// `allow_migration` gates only the lazy-migration self-heal WRITES in
827 /// `muxbus_load_tokens` below (`false` for `muxbus_is_fresh`'s
828 /// side-effect-free contract, `true` for the normal `muxbus_load`
829 /// path) — it does NOT gate the lock below, which every call takes.
830 fn muxbus_load_impl(&self, allow_migration: bool) -> Result<Option<MuxBusCredentials>, StoreError> {
831 // reagent P1 on #2260 (write-vs-write race) + reagent P1 on this PR
832 // (torn read): held for the ENTIRE keychain-read sequence, not just
833 // when `allow_migration` is true. Two independent reasons this must
834 // be unconditional now:
835 // 1. (#2260) The migration branches in `muxbus_load_tokens` read
836 // the keychain, then (on a cache miss) write fresh tokens to it
837 // and update SQL — without this lock, a concurrent `muxbus_save`
838 // could commit a real refresh between this thread's stale SQL
839 // read and its own keychain write, so the migration then
840 // overwrites the freshly-refreshed keychain entries with old
841 // pre-migration data.
842 // 2. (this PR) Each field's tokens now live across MULTIPLE
843 // keychain entries (`write_chunked_field`'s chunks + `:count`),
844 // written sequentially with no atomicity across them — unlike
845 // the single combined-blob write this replaced, which the OS
846 // keychain wrote atomically. An UNLOCKED concurrent read
847 // landing mid-write (previously safe when `allow_migration` was
848 // `false`, i.e. every `muxbus_is_fresh` call) can now read a mix
849 // of old and new chunks for a multi-chunk token and silently
850 // reconstruct a CORRUPTED string — every individual
851 // `get_optional` call still succeeds, so nothing errors, it's
852 // just wrong data. Locking here doesn't reintroduce a write
853 // side effect (see `muxbus_is_fresh`'s own doc comment above);
854 // it only serializes this read against `muxbus_save`/
855 // `muxbus_clear`'s writes, which already take the same lock.
856 let _migration_guard = self.muxbus_save_lock.lock().unwrap();
857 let _xproc = lock_namespace(&keychain_namespace())?;
858 let row_id = current_row_id();
859 let row = {
860 let conn = self.conn.lock().unwrap();
861 let mut stmt = conn.prepare(
862 "SELECT cognito_domain, client_id, access_token, refresh_token, id_token,
863 expires_at, user_email, user_sub
864 FROM db_muxbus_credentials WHERE id = ?1",
865 )?;
866 match stmt.query_row(params![row_id], |row| {
867 Ok((
868 row.get::<_, String>(0)?,
869 row.get::<_, String>(1)?,
870 row.get::<_, String>(2)?, // legacy plaintext access_token (pre-keychain rows)
871 row.get::<_, String>(3)?, // legacy plaintext refresh_token
872 row.get::<_, String>(4)?, // legacy plaintext id_token
873 row.get::<_, i64>(5)?,
874 row.get::<_, String>(6)?,
875 row.get::<_, String>(7)?,
876 ))
877 }) {
878 Ok(r) => r,
879 Err(rusqlite::Error::QueryReturnedNoRows) => return Ok(None),
880 Err(e) => return Err(e.into()),
881 }
882 };
883 let (cognito_domain, client_id, legacy_access, legacy_refresh, legacy_id, expires_at, user_email, user_sub) = row;
884
885 let tokens = self.muxbus_load_tokens(allow_migration, &legacy_access, &legacy_refresh, &legacy_id, &user_sub)?;
886 crate::backend::transcript::withhold_sources::cloud_sign_in(&tokens.access_token, &tokens.refresh_token, &tokens.id_token, expires_at);
887
888 Ok(Some(MuxBusCredentials {
889 cognito_domain,
890 client_id,
891 access_token: tokens.access_token,
892 refresh_token: tokens.refresh_token,
893 id_token: tokens.id_token,
894 expires_at,
895 user_email,
896 user_sub,
897 }))
898 }
899
900 /// One process at a time refreshes this channel's sign-in; the others
901 /// wait, then find it already fresh. Its own lock, apart from the store's,
902 /// so reads aren't held up by the token request.
903 pub fn muxbus_refresh_lock(&self) -> Result<Option<CrossProcessGuard>, StoreError> {
904 let ns = format!("{}:refresh", keychain_namespace());
905 lock_in(crate::registry::resolve_global_shared_root(), &ns, REFRESH_LOCK_WAIT)
906 }
907
908 pub fn muxbus_save(&self, creds: &MuxBusCredentials) -> Result<(), StoreError> {
909 // Held for the ENTIRE keychain-read/write + SQL-write + rollback
910 // sequence below, not just the SQL portion `self.conn`'s own lock
911 // covers — reagent P1 on #2260: `muxbus.login` and the broker's
912 // refresh closure can each call muxbus_save independently, and
913 // without this a race between two concurrent calls could make one
914 // call's rollback restore a stale snapshot over the OTHER call's
915 // already-committed credential.
916 let _save_guard = self.muxbus_save_lock.lock().unwrap();
917 let ns = keychain_namespace();
918 let _xproc = lock_namespace(&ns)?;
919
920 // Read the outgoing account's user_sub now, before it's overwritten
921 // below, so a genuine account switch (vs. a same-account token
922 // refresh) can be detected after the write succeeds and the stale
923 // per-agent credential cache cleared. reagentx P0 on PR #2342.
924 let previous_user_sub: Option<String> = {
925 let conn = self.conn.lock().unwrap();
926 conn.query_row(
927 "SELECT user_sub FROM db_muxbus_credentials WHERE id = ?1",
928 params![current_row_id()],
929 |row| row.get(0),
930 )
931 .ok()
932 };
933
934 let tokens = MuxBusTokens::withheld_of(creds);
935
936 // Windows needs the chunked per-field layout (its 1280-char keychain
937 // entry cap — see `blob_key`'s doc comment); macOS/Linux
938 // have no such cap, so they write the single combined blob instead,
939 // to avoid the ~12-separate-consent-prompts problem chunking causes
940 // on macOS Keychain specifically. Either function returns each
941 // entry's pre-call state so the SQL failure branch below can roll it
942 // all back together too if the SQL write itself then fails (reagent
943 // P2 on #2260: without this, a keychain write that succeeds followed
944 // by a SQL write that then fails — e.g. a transient lock — leaves
945 // the FRESH tokens paired with the OLD SQL metadata, a mismatch that
946 // previously only self-healed on the next successful save).
947 let priors = if cfg!(target_os = "windows") {
948 write_split_tokens(&ns, &tokens)?
949 } else {
950 write_single_blob(&ns, &tokens)?
951 };
952
953 let sql_result = {
954 let conn = self.conn.lock().unwrap();
955 conn.execute(
956 "INSERT OR REPLACE INTO db_muxbus_credentials
957 (id, cognito_domain, client_id, access_token, refresh_token, id_token,
958 expires_at, user_email, user_sub)
959 VALUES (?6, ?1, ?2, '', '', '', ?3, ?4, ?5)",
960 params![
961 creds.cognito_domain,
962 creds.client_id,
963 creds.expires_at,
964 creds.user_email,
965 creds.user_sub,
966 current_row_id(),
967 ],
968 )
969 };
970 if let Err(e) = sql_result {
971 for (key, prior) in &priors {
972 if let Err(re) = prior.restore(key) {
973 tracing::warn!(
974 error = %re,
975 sql_error = %e,
976 key = %key,
977 "muxbus_save: SQL write failed AND restoring this field's prior keychain \
978 state also failed — keychain may now hold a fresh token for it with no \
979 matching SQL metadata until the next successful save"
980 );
981 }
982 }
983 return Err(e.into());
984 }
985
986 // Account switch (not a same-account token refresh): the previous
987 // account's per-agent M2M credentials must not silently keep
988 // authenticating this different account's requests. A first-ever
989 // login (previous_user_sub is None/empty) has nothing to clear.
990 // reagentx P0 on PR #2342.
991 if let Some(prev) = previous_user_sub {
992 if !prev.is_empty() && prev != creds.user_sub {
993 if let Err(e) = self.agent_credentials_clear_all() {
994 tracing::warn!(
995 error = %e,
996 "muxbus_save: failed to clear stale per-agent credentials after account switch",
997 );
998 }
999 }
1000 }
1001
1002 Ok(())
1003 }
1004
1005 pub fn muxbus_clear(&self) -> Result<(), StoreError> {
1006 // reagent P1 on #2260: without this lock, a concurrent muxbus_save
1007 // (broker refresh or muxbus.login) can commit its keychain + SQL
1008 // write after this function's own delete runs, silently
1009 // resurrecting a credential right after the user disconnected —
1010 // same race class muxbus_save/muxbus_load_impl already serialize
1011 // against each other for.
1012 let _clear_guard = self.muxbus_save_lock.lock().unwrap();
1013 let ns = keychain_namespace();
1014 let _xproc = lock_namespace(&ns)?;
1015 // Best-effort — a missing/inaccessible keychain entry must not block
1016 // clearing the (still-useful) SQL row. Clears every chunk + count/gen
1017 // entry the Windows-only chunked layout could have written (harmless
1018 // no-ops on macOS/Linux, which never write it, but a pre-fix install
1019 // there may still have some left over — see `delete_split_tokens`),
1020 // plus the single combined-blob key every platform's CURRENT write
1021 // path (`write_single_blob` on macOS/Linux) or legacy migration
1022 // source (Windows) uses.
1023 delete_split_tokens(&ns);
1024 let _ = secret_store::delete(&blob_key(&ns));
1025 {
1026 let conn = self.conn.lock().unwrap();
1027 conn.execute("DELETE FROM db_muxbus_credentials WHERE id = ?1", params![current_row_id()])?;
1028 }
1029 // Logging out invalidates any per-agent credentials provisioned
1030 // under this account too. reagentx P0 on PR #2342.
1031 if let Err(e) = self.agent_credentials_clear_all() {
1032 tracing::warn!(error = %e, "muxbus_clear: failed to clear per-agent credentials");
1033 }
1034 Ok(())
1035 }
1036}
1037
1038#[cfg(all(test, not(windows)))]
1039#[path = "muxbus_load_tests.rs"]
1040mod load_tests;
1041
1042#[cfg(test)]
1043mod tests {
1044 use super::*;
1045
1046 #[test]
1047 fn tokens_json_round_trips() {
1048 // Legacy combined-blob shape — still needed to deserialize an old
1049 // single-entry keychain value during one-time migration.
1050 let tokens = MuxBusTokens {
1051 access_token: "at".to_string(),
1052 refresh_token: "rt".to_string(),
1053 id_token: "it".to_string(),
1054 };
1055 let blob = serde_json::to_string(&tokens).unwrap();
1056 let back: MuxBusTokens = serde_json::from_str(&blob).unwrap();
1057 assert_eq!(back.access_token, "at");
1058 assert_eq!(back.refresh_token, "rt");
1059 assert_eq!(back.id_token, "it");
1060 }
1061
1062 #[test]
1063 fn muxbus_blob_round_trips_with_generation() {
1064 let value = MuxBusBlob {
1065 tokens: MuxBusTokens {
1066 access_token: "at".to_string(),
1067 refresh_token: "rt".to_string(),
1068 id_token: "it".to_string(),
1069 },
1070 generation: "12345".to_string(),
1071 };
1072 let json = serde_json::to_string(&value).unwrap();
1073 let back: MuxBusBlob = serde_json::from_str(&json).unwrap();
1074 assert_eq!(back.tokens.access_token, "at");
1075 assert_eq!(back.generation, "12345");
1076 }
1077
1078 #[test]
1079 fn muxbus_blob_deserializes_a_pre_generation_legacy_blob_with_empty_generation() {
1080 // A genuinely old, pre-fix blob has no `generation` key at all —
1081 // `#[serde(default)]` must fill it in as "" rather than fail to
1082 // parse, so it correctly reads as the oldest possible timestamp in
1083 // any freshness comparison (see `generation_as_number`).
1084 let legacy_json = r#"{"access_token":"at","refresh_token":"rt","id_token":"it"}"#;
1085 let back: MuxBusBlob = serde_json::from_str(legacy_json).unwrap();
1086 assert_eq!(back.tokens.access_token, "at");
1087 assert_eq!(back.generation, "");
1088 }
1089
1090 #[test]
1091 fn generation_as_number_orders_real_timestamps_correctly() {
1092 let older = new_generation();
1093 let newer = new_generation();
1094 assert!(
1095 generation_as_number(&newer) >= generation_as_number(&older),
1096 "a later new_generation() call must not compare as older"
1097 );
1098 }
1099
1100 #[test]
1101 fn generation_as_number_treats_empty_or_corrupted_values_as_the_oldest_possible() {
1102 assert_eq!(generation_as_number(""), 0);
1103 assert_eq!(generation_as_number("not-a-number"), 0);
1104 assert!(generation_as_number(&new_generation()) > generation_as_number(""));
1105 }
1106
1107 #[test]
1108 fn field_key_is_namespaced_and_distinct_per_field() {
1109 // The host-wide names must not change: installed `stable` users'
1110 // existing sign-ins live under exactly these entries.
1111 let access = field_key(GLOBAL_KEYCHAIN_NS, FIELD_ACCESS);
1112 let refresh = field_key(GLOBAL_KEYCHAIN_NS, FIELD_REFRESH);
1113 let id = field_key(GLOBAL_KEYCHAIN_NS, FIELD_ID);
1114 assert_eq!(access, "muxbus:global:access");
1115 assert_eq!(refresh, "muxbus:global:refresh");
1116 assert_eq!(id, "muxbus:global:id");
1117 assert_eq!(blob_key(GLOBAL_KEYCHAIN_NS), "muxbus:global");
1118 assert_ne!(access, blob_key(GLOBAL_KEYCHAIN_NS));
1119 }
1120
1121 #[test]
1122 fn every_channel_but_stable_signs_in_on_its_own() {
1123 // stable (the installed releases) and no channel: the host-wide set,
1124 // as ever.
1125 assert_eq!(namespace_for(Some("stable")), "muxbus:global");
1126 assert_eq!(namespace_for(None), "muxbus:global");
1127 assert_eq!(namespace_for(Some("")), "muxbus:global");
1128 // Any other channel is its own entry, whether or not auth is isolated:
1129 // the channel is the unit of sign-in, not the host.
1130 assert_eq!(namespace_for(Some("local-main-x")), "muxbus:channel:local-main-x");
1131 assert_eq!(namespace_for(Some("dev-feat-a-1234")), "muxbus:channel:dev-feat-a-1234");
1132 }
1133
1134 #[test]
1135 fn a_channels_row_is_its_own_in_the_store_channels_share() {
1136 assert_eq!(row_id_for(Some("stable"), false), "global");
1137 assert_eq!(row_id_for(None, false), "global");
1138 assert_eq!(row_id_for(Some("local-main-x"), false), "channel:local-main-x");
1139 assert_eq!(row_id_for(Some("local-main-y"), false), "channel:local-main-y");
1140 // A store that is already the channel's own keeps the row it has: an
1141 // isolated channel's existing sign-in stays valid.
1142 assert_eq!(row_id_for(Some("local-main-x"), true), "global");
1143 }
1144
1145 #[test]
1146 fn a_channels_agent_credentials_are_its_own_rows() {
1147 assert_eq!(agent_credential_prefix_for(Some("stable"), false), "");
1148 assert_eq!(agent_credential_prefix_for(None, false), "");
1149 assert_eq!(agent_credential_prefix_for(Some("local-main-x"), false), "local-main-x/");
1150 assert_eq!(agent_credential_prefix_for(Some("local-main-x"), true), "");
1151 // An agent id has no `/`, so a prefix can't be mistaken for one.
1152 assert!(!"agentx".contains('/'));
1153 }
1154
1155 #[test]
1156 fn channel_namespaces_never_share_an_entry_with_each_other_or_the_global_set() {
1157 let a = namespace_for(Some("local-main-a"));
1158 let b = namespace_for(Some("local-main-b"));
1159 let g = GLOBAL_KEYCHAIN_NS.to_string();
1160 let keys = |ns: &str| {
1161 let mut k = vec![blob_key(ns)];
1162 for f in [FIELD_ACCESS, FIELD_REFRESH, FIELD_ID] {
1163 let fk = field_key(ns, f);
1164 k.extend([chunk_key(&fk, 0), count_key(&fk), generation_key(&fk), fk]);
1165 }
1166 k
1167 };
1168 for (x, y) in [(&a, &b), (&a, &g), (&b, &g)] {
1169 let (kx, ky) = (keys(x), keys(y));
1170 assert!(kx.iter().all(|k| !ky.contains(k)), "{x} and {y} share a keychain entry");
1171 }
1172 }
1173
1174 /// Exercises the REAL OS keychain, so it's ignored in CI (no keychain
1175 /// there). Run on a dev machine:
1176 /// `cargo test -p agentmux-srv-core --lib per_channel_keychain_live -- --ignored`.
1177 /// Uses throwaway namespaces and cleans up after itself; never touches
1178 /// `muxbus:global`.
1179 #[test]
1180 #[ignore]
1181 fn per_channel_keychain_live() {
1182 let run = new_generation();
1183 let ns_a = format!("muxbus:channel:test-{run}-a");
1184 let ns_b = format!("muxbus:channel:test-{run}-b");
1185 let tok = |s: &str| MuxBusTokens {
1186 access_token: format!("access-{s}-{}", "x".repeat(1500)),
1187 refresh_token: format!("refresh-{s}"),
1188 id_token: format!("id-{s}"),
1189 };
1190 let write = |ns: &str, t: &MuxBusTokens| {
1191 if cfg!(target_os = "windows") {
1192 write_split_tokens(ns, t).map(|_| ())
1193 } else {
1194 write_single_blob(ns, t).map(|_| ())
1195 }
1196 };
1197 let clear = |ns: &str| {
1198 delete_split_tokens(ns);
1199 let _ = secret_store::delete(&blob_key(ns));
1200 };
1201
1202 write(&ns_a, &tok("a")).expect("write a");
1203 write(&ns_b, &tok("b")).expect("write b");
1204 // Each channel reads back its own session, not the other's.
1205 assert_eq!(read_any_layout(&ns_a).unwrap().refresh_token, "refresh-a");
1206 assert_eq!(read_any_layout(&ns_b).unwrap().refresh_token, "refresh-b");
1207 // Signing one channel out leaves the other signed in.
1208 clear(&ns_a);
1209 assert!(read_any_layout(&ns_a).is_none(), "a cleared");
1210 assert_eq!(read_any_layout(&ns_b).unwrap().access_token, tok("b").access_token);
1211 clear(&ns_b);
1212 assert!(read_any_layout(&ns_b).is_none(), "b cleared");
1213
1214 // Both layouts present under one namespace: the fresher generation
1215 // wins, whichever layout it's in (adoption must not pick stale
1216 // leftovers).
1217 // Small tokens here: a single blob over Windows Credential Manager's
1218 // 2560-byte cap can't be written at all (why Windows splits).
1219 let small = |s: &str| MuxBusTokens {
1220 access_token: format!("access-{s}"),
1221 refresh_token: format!("refresh-{s}"),
1222 id_token: format!("id-{s}"),
1223 };
1224 let ns_c = format!("muxbus:channel:test-{run}-c");
1225 write_split_tokens(&ns_c, &small("split-old")).expect("split old");
1226 write_single_blob(&ns_c, &small("blob-new")).expect("blob new");
1227 assert_eq!(read_any_layout(&ns_c).unwrap().refresh_token, "refresh-blob-new");
1228 write_split_tokens(&ns_c, &small("split-newest")).expect("split newest");
1229 assert_eq!(read_any_layout(&ns_c).unwrap().refresh_token, "refresh-split-newest");
1230 clear(&ns_c);
1231 assert!(read_any_layout(&ns_c).is_none(), "c cleared");
1232 }
1233
1234 /// Regression guard for every bug this file has fixed in sequence: the
1235 /// original combined-blob-exceeds-2560-bytes bug, the follow-up found
1236 /// live-testing the first fix (a single field's own token can ALSO
1237 /// exceed the cap), and the real character limit being HALF the
1238 /// byte constant the `keyring` crate's error message reports (Windows
1239 /// stores the value as UTF-16 — see PLAN_MUXBUS_KEYCHAIN_WINDOWS_BLOB_LIMIT_2026_08_03.md
1240 /// §6-§7). Doesn't exercise the real OS keychain (not available in CI);
1241 /// asserts the pure chunking math instead: every chunk of an oversized
1242 /// value stays under the REAL char limit (not the misleading one from
1243 /// the error text), and concatenating them reconstructs the original
1244 /// exactly.
1245 #[test]
1246 fn chunk_value_keeps_every_chunk_under_windows_credential_blob_limit_and_reconstructs() {
1247 // `keyring` checks `password.encode_utf16().count() * 2 >
1248 // CRED_MAX_CREDENTIAL_BLOB_SIZE` (2560 bytes) — so the real char
1249 // budget for an all-ASCII (1 UTF-16 unit each) token is half that.
1250 const WINDOWS_CRED_BLOB_BYTE_LIMIT: usize = 2560;
1251 const WINDOWS_CRED_CHAR_LIMIT: usize = WINDOWS_CRED_BLOB_BYTE_LIMIT / 2;
1252
1253 // Larger than even the old *combined* blob would have been —
1254 // proves this doesn't just move the limit, it removes it.
1255 let oversized_token = "i".repeat(6000);
1256
1257 let chunks = chunk_value(&oversized_token);
1258 assert!(chunks.len() > 1, "a value this large must actually split");
1259 for chunk in &chunks {
1260 assert!(chunk.len() < WINDOWS_CRED_CHAR_LIMIT);
1261 }
1262 assert_eq!(chunks.concat(), oversized_token);
1263 }
1264
1265 #[test]
1266 fn chunk_value_small_input_is_a_single_chunk() {
1267 assert_eq!(chunk_value("short-token"), vec!["short-token"]);
1268 }
1269
1270 #[test]
1271 fn chunk_value_empty_string_is_one_empty_chunk() {
1272 // Not zero chunks — `read_chunked_field` needs a `:count` of at
1273 // least 1 to distinguish "field written as empty" from "field never
1274 // written at all" (`Ok(None)`).
1275 assert_eq!(chunk_value(""), vec![""]);
1276 }
1277
1278 /// The point of the lock: a second holder waits for the first, across
1279 /// separate handles (what two processes have).
1280 #[test]
1281 fn the_cross_process_lock_makes_a_second_holder_wait() {
1282 let dir = tempfile::tempdir().unwrap();
1283 let path = dir.path().join("ns.lock");
1284 let first = lock_file(&path, std::time::Duration::from_secs(1)).expect("first lock");
1285 let started = std::time::Instant::now();
1286 // Held: a short wait gives up without the lock.
1287 assert!(lock_file(&path, std::time::Duration::from_millis(150)).is_none());
1288 assert!(started.elapsed() >= std::time::Duration::from_millis(140));
1289 drop(first);
1290 // Released: the next holder gets it at once.
1291 assert!(lock_file(&path, std::time::Duration::from_millis(150)).is_some());
1292 }
1293
1294 /// A namespace whose lock another process holds fails the operation
1295 /// instead of running it unlocked; with no shared root there is no lock.
1296 #[test]
1297 fn a_lock_that_cant_be_taken_fails_the_operation() {
1298 let dir = tempfile::tempdir().unwrap();
1299 let wait = std::time::Duration::from_millis(100);
1300 let held = lock_in(Some(dir.path().to_path_buf()), "muxbus:global", wait).unwrap();
1301 assert!(held.is_some());
1302 assert!(lock_in(Some(dir.path().to_path_buf()), "muxbus:global", wait).is_err());
1303 assert!(lock_in(Some(dir.path().to_path_buf()), "muxbus:channel:dev-x", wait).unwrap().is_some(), "per namespace");
1304 drop(held);
1305 assert!(lock_in(Some(dir.path().to_path_buf()), "muxbus:global", wait).unwrap().is_some());
1306 assert!(lock_in(None, "muxbus:global", wait).unwrap().is_none());
1307 }
1308
1309 /// A torn read that heals (an older build finished its save) is retried,
1310 /// not reported as a sign-out; one that stays torn is reported as such.
1311 #[test]
1312 fn a_torn_read_is_retried_until_it_settles() {
1313 let pause = std::time::Duration::from_millis(1);
1314 let mut calls = 0;
1315 let healed = retry_while_torn(
1316 || {
1317 calls += 1;
1318 Ok(if calls < 3 {
1319 SplitRead::Torn { refresh: None }
1320 } else {
1321 SplitRead::Complete(MuxBusTokens::default(), "1".to_string())
1322 })
1323 },
1324 4,
1325 pause,
1326 )
1327 .unwrap();
1328 assert!(matches!(healed, SplitRead::Complete(..)));
1329 assert_eq!(calls, 3);
1330
1331 let mut calls = 0;
1332 let stuck = retry_while_torn(|| { calls += 1; Ok(SplitRead::Torn { refresh: None }) }, 4, pause).unwrap();
1333 assert!(matches!(stuck, SplitRead::Torn { .. }));
1334 assert_eq!(calls, 4, "gives up after the allowed tries");
1335
1336 let mut calls = 0;
1337 let absent = retry_while_torn(|| { calls += 1; Ok(SplitRead::Absent) }, 4, pause).unwrap();
1338 assert!(matches!(absent, SplitRead::Absent));
1339 assert_eq!(calls, 1, "an absent login is not retried");
1340 }
1341
1342 /// The host-wide set is adopted into a channel only for the account the
1343 /// channel's row names.
1344 #[test]
1345 fn only_the_same_accounts_tokens_are_adopted() {
1346 use base64::Engine;
1347 let jwt = |sub: &str| {
1348 let payload = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(format!(r#"{{"sub":"{sub}"}}"#));
1349 format!("e30.{payload}.sig")
1350 };
1351 let tokens = |id: String, access: String| MuxBusTokens { access_token: access, refresh_token: "r".into(), id_token: id };
1352 assert!(same_account(&tokens(jwt("user-a"), jwt("user-a")), "user-a"));
1353 assert!(!same_account(&tokens(jwt("user-b"), jwt("user-b")), "user-a"), "another account's");
1354 assert!(same_account(&tokens(String::new(), jwt("user-a")), "user-a"), "no id token: the access token's");
1355 assert!(!same_account(&tokens("opaque".into(), "opaque".into()), "user-a"), "not a JWT");
1356 assert!(!same_account(&tokens(jwt(""), jwt("")), ""), "a row with no account matches nothing");
1357 }
1358
1359 /// A torn set keeps its refresh token when that field is whole (so a
1360 /// refresh can repair it), and not when the refresh field itself was
1361 /// caught mid-write. Real keychain, Windows (the split layout):
1362 /// `cargo test -p agentmux-srv-core --lib a_torn_set_keeps -- --ignored`.
1363 #[test]
1364 #[ignore]
1365 fn a_torn_set_keeps_a_whole_refresh_token_live() {
1366 if !cfg!(target_os = "windows") {
1367 return;
1368 }
1369 let ns = format!("muxbus:channel:test-{}-torn", new_generation());
1370 let tokens = MuxBusTokens {
1371 access_token: "access-a".into(),
1372 refresh_token: "refresh-a".into(),
1373 id_token: "id-a".into(),
1374 };
1375 write_split_tokens(&ns, &tokens).expect("write");
1376 // Another save's access token with its own stamp: the set is torn.
1377 write_chunked_field(&field_key(&ns, FIELD_ACCESS), "access-b", "1").expect("tear");
1378 let refresh_after = |ns: &str| match read_split_state(ns).expect("read") {
1379 SplitRead::Torn { refresh } => refresh,
1380 _ => panic!("expected a torn set"),
1381 };
1382 assert_eq!(refresh_after(&ns).as_deref(), Some("refresh-a"));
1383 // The refresh field mid-write: its stamp goes first.
1384 secret_store::delete(&generation_key(&field_key(&ns, FIELD_REFRESH))).expect("delete stamp");
1385 assert_eq!(refresh_after(&ns), None);
1386 delete_split_tokens(&ns);
1387 let _ = secret_store::delete(&generation_key(&field_key(&ns, FIELD_REFRESH)));
1388 }
1389
1390 const HAMMER_NS: &str = "AGENTMUX_TEST_MUXBUS_HAMMER_NS";
1391 const HAMMER_LOCK: &str = "AGENTMUX_TEST_MUXBUS_HAMMER_LOCK";
1392
1393 /// One child of `concurrent_processes_never_tear_a_live_sign_in`: save and
1394 /// read the same namespace in a loop, printing how many reads were torn
1395 /// or paired tokens from two saves.
1396 fn hammer(ns: &str, lock_path: Option<&std::path::Path>) -> usize {
1397 let me = std::process::id();
1398 let wait = std::time::Duration::from_secs(120);
1399 let mut torn = 0;
1400 let mut longest_save = std::time::Duration::ZERO;
1401 for i in 0..40 {
1402 let tag = format!("{me}-{i}");
1403 let tokens = MuxBusTokens {
1404 access_token: format!("access-{tag}-{}", "x".repeat(1500)),
1405 refresh_token: format!("refresh-{tag}"),
1406 id_token: format!("id-{tag}"),
1407 };
1408 {
1409 let _guard = lock_path.map(|p| lock_file(p, wait).expect("lock"));
1410 let started = std::time::Instant::now();
1411 // Unlocked, a write can fail when another removes an entry under it.
1412 let _ = write_split_tokens(ns, &tokens);
1413 longest_save = longest_save.max(started.elapsed());
1414 }
1415 let _guard = lock_path.map(|p| lock_file(p, wait).expect("lock"));
1416 // An `Err` is a read that found a field mid-write (its `:gen` is
1417 // deleted first): bad too, though callers retry it as transient.
1418 match read_split_state(ns) {
1419 Ok(SplitRead::Complete(t, _)) => {
1420 let saved = t.refresh_token.trim_start_matches("refresh-");
1421 if !t.access_token.starts_with(&format!("access-{saved}-")) || t.id_token != format!("id-{saved}") {
1422 torn += 1;
1423 }
1424 }
1425 Ok(SplitRead::Torn { .. }) | Err(_) => torn += 1,
1426 Ok(SplitRead::Absent) => panic!("the sign-in vanished"),
1427 }
1428 }
1429 println!("HAMMER longest_save_ms={}", longest_save.as_millis());
1430 torn
1431 }
1432
1433 /// The bug behind the retro, against the REAL OS keychain: several
1434 /// processes saving and reading one sign-in at once. Without the lock it
1435 /// usually tears (printed, not asserted: it's a race); with it, never.
1436 /// `cargo test -p agentmux-srv-core --lib concurrent_processes_never_tear -- --ignored --nocapture`
1437 #[test]
1438 #[ignore]
1439 fn concurrent_processes_never_tear_a_live_sign_in() {
1440 if let Ok(ns) = std::env::var(HAMMER_NS) {
1441 let lock = std::env::var(HAMMER_LOCK).ok().filter(|p| !p.is_empty());
1442 println!("HAMMER torn={}", hammer(&ns, lock.as_deref().map(std::path::Path::new)));
1443 return;
1444 }
1445 if !cfg!(target_os = "windows") {
1446 return; // only Windows splits a sign-in across entries
1447 }
1448 let dir = tempfile::tempdir().unwrap();
1449 let lock_path = dir.path().join("hammer.lock");
1450 let longest_save_ms = std::cell::Cell::new(0u128);
1451 let run = |locked: bool| -> usize {
1452 let ns = format!("muxbus:channel:test-hammer-{}", new_generation());
1453 let children: Vec<_> = (0..4)
1454 .map(|_| {
1455 std::process::Command::new(std::env::current_exe().unwrap())
1456 .args(["--exact", "backend::storage::muxbus::tests::concurrent_processes_never_tear_a_live_sign_in"])
1457 .args(["--ignored", "--nocapture"])
1458 .env(HAMMER_NS, &ns)
1459 .env(HAMMER_LOCK, if locked { lock_path.to_str().unwrap() } else { "" })
1460 .stdout(std::process::Stdio::piped())
1461 .spawn()
1462 .expect("spawn")
1463 })
1464 .collect();
1465 let torn = children
1466 .into_iter()
1467 .map(|c| {
1468 let out = String::from_utf8_lossy(&c.wait_with_output().unwrap().stdout).into_owned();
1469 if let Some(ms) = out.lines().find_map(|l| l.strip_prefix("HAMMER longest_save_ms=")) {
1470 longest_save_ms.set(longest_save_ms.get().max(ms.trim().parse().unwrap_or(0)));
1471 }
1472 let line = out.lines().find(|l| l.starts_with("HAMMER torn=")).unwrap_or_else(|| panic!("child output: {out}"));
1473 line["HAMMER torn=".len()..].trim().parse::<usize>().unwrap()
1474 })
1475 .sum();
1476 delete_split_tokens(&ns);
1477 torn
1478 };
1479 let unlocked = run(false);
1480 let locked = run(true);
1481 println!(
1482 "torn reads out of 160: without the lock {unlocked}, with it {locked}; longest save {} ms",
1483 longest_save_ms.get()
1484 );
1485 assert_eq!(locked, 0, "the lock must make save and read one critical section");
1486 }
1487}