Skip to main content

agentmux_srv_core/backend/storage/
muxbus_load.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Finding a channel's MuxBus tokens (`Store::muxbus_load_tokens`): one step per
5//! place they can be, tried in this order, the first that has them wins:
6//!
7//! 1. this platform's current layout (`preferred_layout`),
8//! 2. the other platform's layout, migrated in place (`other_layout`),
9//! 3. the plaintext SQL columns of a row that predates keychain storage,
10//! 4. the host-wide session of the same account, adopted once by a channel that
11//!    signed in before tokens were scoped per channel.
12//!
13//! A keychain READ failure at any step falls back to the plaintext SQL columns
14//! when they have data (`read_failed`): a transient storage failure must not
15//! present as a full logout while usable data sits right there.
16//!
17//! `allow_migration` gates only the self-heal WRITES (`false` for
18//! `muxbus_is_fresh`'s side-effect-free contract, `true` for a normal load).
19//! The caller (`muxbus_load_impl`) already holds the store's save lock and the
20//! channel's cross-process lock.
21
22use rusqlite::params;
23
24use super::error::StoreError;
25use super::muxbus::{
26    blob_key, current_row_id, delete_split_tokens, generation_as_number, keychain_namespace, lock_namespace, read_any_layout, read_split_settled,
27    read_split_tokens, same_account, write_single_blob, write_split_tokens, MuxBusBlob, MuxBusTokens, PriorKeychainState, SplitRead,
28    GLOBAL_KEYCHAIN_NS,
29};
30use super::store::Store;
31use crate::identity::secret_store;
32
33/// The plaintext SQL columns of a row, which hold tokens only if it predates keychain storage.
34struct Legacy<'a> {
35    access: &'a str,
36    refresh: &'a str,
37    id: &'a str,
38}
39
40impl Legacy<'_> {
41    fn has_tokens(&self) -> bool {
42        !self.access.is_empty()
43    }
44
45    fn tokens(&self) -> MuxBusTokens {
46        MuxBusTokens { access_token: self.access.to_string(), refresh_token: self.refresh.to_string(), id_token: self.id.to_string() }
47    }
48}
49
50/// What a step found: the tokens, or nothing, so the next step looks.
51enum Found {
52    Tokens(MuxBusTokens),
53    Next,
54}
55
56type Step = Result<Found, StoreError>;
57
58/// A keychain read failed: the plaintext columns when they hold the tokens, else the error.
59fn read_failed<E: std::fmt::Display>(e: E, as_error: impl FnOnce(E) -> StoreError, legacy: &Legacy) -> Step {
60    if legacy.has_tokens() {
61        tracing::warn!(error = %e, "muxbus: keychain read failed, falling back to legacy plaintext columns");
62        return Ok(Found::Tokens(legacy.tokens()));
63    }
64    Err(as_error(e))
65}
66
67fn keychain_read_error(e: String) -> StoreError {
68    StoreError::Other(format!("muxbus: keychain read failed: {e}"))
69}
70
71fn corrupted_blob(e: serde_json::Error) -> StoreError {
72    StoreError::Other(format!("muxbus: stored keychain blob is corrupted: {e}"))
73}
74
75/// This platform's own layout: Windows needs the chunked per-field layout (its
76/// 1280-char keychain entry cap); macOS and Linux use the single combined blob
77/// (see `blob_key`). A hit needs no migration: it is already the right format.
78fn preferred_layout(ns: &str, allow_migration: bool, legacy: &Legacy) -> Step {
79    if cfg!(target_os = "windows") {
80        windows_split_layout(ns, legacy)
81    } else {
82        unix_blob_layout(ns, allow_migration, legacy)
83    }
84}
85
86/// The other platform's layout as a migration source. On Windows that is the
87/// pre-2026-08-03 single blob. On macOS and Linux it is the chunked layout an
88/// install from before the 2026-08-19 fix may have written (every platform
89/// wrote it then); see retro-macos-muxbus-keychain-prompt-storm-2026-08-19.md.
90fn other_layout(ns: &str, allow_migration: bool, legacy: &Legacy) -> Step {
91    if cfg!(target_os = "windows") {
92        windows_legacy_blob(ns, allow_migration, legacy)
93    } else {
94        unix_legacy_split_layout(ns, allow_migration, legacy)
95    }
96}
97
98/// Write `tokens` in this platform's preferred layout.
99fn write_preferred_layout(ns: &str, tokens: &MuxBusTokens) -> Result<Vec<(String, PriorKeychainState)>, StoreError> {
100    if cfg!(target_os = "windows") {
101        write_split_tokens(ns, tokens)
102    } else {
103        write_single_blob(ns, tokens)
104    }
105}
106
107fn windows_split_layout(ns: &str, legacy: &Legacy) -> Step {
108    match read_split_settled(ns) {
109        Ok(SplitRead::Complete(tokens, _generation)) => Ok(Found::Tokens(tokens)),
110        // Not yet on the split layout, or torn and still torn after
111        // the retries: check the other sources.
112        Ok(SplitRead::Absent) => Ok(Found::Next),
113        // Torn, but its refresh token is whole: hand back just that,
114        // and the next refresh (which checks the account) saves a
115        // whole set again. No sign-in needed.
116        Ok(SplitRead::Torn { refresh: Some(refresh_token) }) => {
117            tracing::warn!(
118                "muxbus: split keychain entries are torn and stayed so on retry — \
119                 keeping the refresh token so the next refresh repairs them"
120            );
121            Ok(Found::Tokens(MuxBusTokens { refresh_token, ..Default::default() }))
122        }
123        Ok(SplitRead::Torn { refresh: None }) => {
124            tracing::warn!(
125                "muxbus: split keychain entries are torn (mismatched generation stamps \
126                 or incomplete) and stayed so on retry, with no whole refresh token — \
127                 treating as not signed in; signing in again repairs it"
128            );
129            Ok(Found::Next)
130        }
131        Err(e) => read_failed(e, |e| e, legacy),
132    }
133}
134
135fn unix_blob_layout(ns: &str, allow_migration: bool, legacy: &Legacy) -> Step {
136    match secret_store::get_optional_if_trusted(&blob_key(ns)) {
137        Ok(Some(blob)) => {
138            // A blob that doesn't parse means something wrote bad data, not
139            // "no credential": an error, not a silent logout.
140            let parsed: MuxBusBlob = serde_json::from_str(&blob).map_err(corrupted_blob)?;
141            Ok(Found::Tokens(blob_or_fresher_split(ns, allow_migration, parsed)))
142        }
143        // Not yet on the single-blob layout: check the other sources.
144        Ok(None) => Ok(Found::Next),
145        Err(e) => read_failed(e, keychain_read_error, legacy),
146    }
147}
148
149/// The tokens of a blob, unless split entries beside it are fresher.
150///
151/// A blob and split entries can coexist on this machine two ways, and they
152/// don't agree on which is fresher, so an actual timestamp comparison (not a
153/// fixed direction) is the only way to get both right (see `MuxBusBlob`):
154///   1. An earlier blob-to-split migration (it ran on every platform) wrote
155///      split entries but its own best-effort blob delete failed: split is
156///      fresher there.
157///   2. The self-heal below (split to blob) can leave stale split leftovers if
158///      `delete_split_tokens` partially fails; a later `muxbus_save` (macOS and
159///      Linux only ever write the blob) then makes the blob fresher.
160fn blob_or_fresher_split(ns: &str, allow_migration: bool, parsed: MuxBusBlob) -> MuxBusTokens {
161    let blob_generation = generation_as_number(&parsed.generation);
162    match read_split_tokens(ns) {
163        Ok(Some((split_tokens, split_generation))) => {
164            if generation_as_number(&split_generation) > blob_generation {
165                // Split is genuinely newer: finish the interrupted migration
166                // into the preferred single-blob format.
167                if allow_migration {
168                    match write_single_blob(ns, &split_tokens) {
169                        Ok(_) => delete_split_tokens(ns),
170                        Err(_) => {
171                            tracing::warn!(
172                                "muxbus: keychain write failed reconciling coexisting \
173                                 blob + split entries (split was fresher) — leaving \
174                                 both in place for now"
175                            );
176                        }
177                    }
178                }
179                return split_tokens;
180            }
181            // The blob is the same age or newer, so it is authoritative. The
182            // split entries are a stale leftover from an incomplete cleanup:
183            // finish it now instead of letting it mislead the next load too.
184            if allow_migration {
185                delete_split_tokens(ns);
186            }
187        }
188        Ok(None) => {} // no coexistence: the blob alone is authoritative
189        Err(e) => {
190            // Can't confirm whether split entries coexist: use the blob in
191            // hand rather than failing a read that would otherwise succeed.
192            tracing::warn!(
193                error = %e,
194                "muxbus: couldn't check for a coexisting split-entry layout — \
195                 using the blob value"
196            );
197        }
198    }
199    parsed.tokens
200}
201
202fn windows_legacy_blob(ns: &str, allow_migration: bool, legacy: &Legacy) -> Step {
203    match secret_store::get_optional(&blob_key(ns)) {
204        Ok(Some(blob)) => {
205            let tokens: MuxBusTokens = serde_json::from_str(&blob).map_err(corrupted_blob)?;
206            if allow_migration {
207                match write_split_tokens(ns, &tokens) {
208                    Ok(_) => {
209                        let _ = secret_store::delete(&blob_key(ns));
210                    }
211                    Err(_) => {
212                        tracing::warn!(
213                            "muxbus: keychain write failed migrating the legacy combined-blob \
214                             entry to split entries — leaving the old entry in place for now"
215                        );
216                    }
217                }
218            }
219            Ok(Found::Tokens(tokens))
220        }
221        Ok(None) => Ok(Found::Next),
222        Err(e) => read_failed(e, keychain_read_error, legacy),
223    }
224}
225
226fn unix_legacy_split_layout(ns: &str, allow_migration: bool, legacy: &Legacy) -> Step {
227    match read_split_settled(ns) {
228        // Pre-blob split entries left torn: as on Windows, the refresh's save writes a whole blob.
229        Ok(SplitRead::Torn { refresh: Some(refresh_token) }) => {
230            tracing::warn!(
231                "muxbus: legacy split keychain entries are torn — keeping the refresh token \
232                 so the next refresh repairs them"
233            );
234            Ok(Found::Tokens(MuxBusTokens { refresh_token, ..Default::default() }))
235        }
236        Ok(SplitRead::Torn { refresh: None }) => {
237            tracing::warn!(
238                "muxbus: legacy split keychain entries are torn with no whole refresh token — \
239                 treating as not signed in; signing in again repairs it"
240            );
241            Ok(Found::Next)
242        }
243        Ok(SplitRead::Complete(tokens, _generation)) => {
244            // No coexisting blob was found (the blob step already checked and
245            // returned): self-heal by collapsing the pre-fix chunked entries
246            // into one blob, so every later load, and every OS Keychain
247            // consent prompt, touches one entry instead of up to twelve.
248            if allow_migration {
249                match write_single_blob(ns, &tokens) {
250                    Ok(_) => delete_split_tokens(ns),
251                    Err(_) => {
252                        tracing::warn!(
253                            "muxbus: keychain write failed migrating chunked entries to a \
254                             single blob — leaving the old entries in place for now"
255                        );
256                    }
257                }
258            }
259            Ok(Found::Tokens(tokens))
260        }
261        Ok(SplitRead::Absent) => Ok(Found::Next),
262        Err(e) if secret_store::is_needs_consent(&e.to_string()) => Ok(Found::Next), // saved by an untrusted older build: signed out
263        Err(e) => read_failed(e, |e| e, legacy),
264    }
265}
266
267/// This channel has its own SQL row (the caller got past the row gate) but
268/// nothing under its own keychain namespace: it signed in before tokens were
269/// scoped per channel, when they went to the host-wide set. Adopt that set
270/// once, read-only — the global entries are never written or deleted from here,
271/// so other channels and `stable` keep theirs. From the next save on, this
272/// channel's tokens are its own. Only the same account's: `stable` may be
273/// signed in as another, and its tokens must not pair with this row.
274fn adopt_host_wide_session(ns: &str, user_sub: &str, allow_migration: bool) -> Result<Option<MuxBusTokens>, StoreError> {
275    // Its own lock: `stable` saves the host-wide set under that one.
276    // Always taken after this channel's, never the other way round.
277    let global_tokens = {
278        let _global = lock_namespace(GLOBAL_KEYCHAIN_NS)?;
279        read_any_layout(GLOBAL_KEYCHAIN_NS)
280    };
281    let Some(tokens) = global_tokens.filter(|t| same_account(t, user_sub)) else {
282        return Ok(None);
283    };
284    tracing::info!(namespace = %ns, "muxbus: adopting the host-wide session for this channel (one-time, pre-per-channel sign-in)");
285    if allow_migration && write_preferred_layout(ns, &tokens).is_err() {
286        tracing::warn!(
287            "muxbus: couldn't copy the adopted session into this channel's \
288             keychain namespace — it stays readable from the host-wide set for now"
289        );
290    }
291    Ok(Some(tokens))
292}
293
294impl Store {
295    /// Resolve the three token fields from the first place that has them (see the module docs).
296    pub(super) fn muxbus_load_tokens(
297        &self,
298        allow_migration: bool,
299        legacy_access: &str,
300        legacy_refresh: &str,
301        legacy_id: &str,
302        user_sub: &str,
303    ) -> Result<MuxBusTokens, StoreError> {
304        let legacy = Legacy { access: legacy_access, refresh: legacy_refresh, id: legacy_id };
305        let ns = keychain_namespace();
306
307        if let Found::Tokens(tokens) = preferred_layout(&ns, allow_migration, &legacy)? {
308            return Ok(tokens);
309        }
310        if let Found::Tokens(tokens) = other_layout(&ns, allow_migration, &legacy)? {
311            return Ok(tokens);
312        }
313        if legacy.has_tokens() {
314            return Ok(self.adopt_plaintext_columns(&ns, allow_migration, &legacy));
315        }
316        if ns != GLOBAL_KEYCHAIN_NS {
317            if let Some(tokens) = adopt_host_wide_session(&ns, user_sub, allow_migration)? {
318                return Ok(tokens);
319            }
320        }
321        Ok(MuxBusTokens::default())
322    }
323
324    /// The row predates keychain-backed storage: use the plaintext columns. With
325    /// migration allowed, also self-heal once, by writing them into this
326    /// platform's preferred layout and blanking the SQL columns, so every later
327    /// load takes the keychain path. Without it (`muxbus_is_fresh`) the read
328    /// stays read-only: the same values a migration would have written, without
329    /// touching the keychain or the SQL columns.
330    fn adopt_plaintext_columns(&self, ns: &str, allow_migration: bool, legacy: &Legacy) -> MuxBusTokens {
331        let tokens = legacy.tokens();
332        if !allow_migration {
333            return tokens;
334        }
335        match write_preferred_layout(ns, &tokens) {
336            Ok(_) => {
337                let conn = self.conn.lock().unwrap();
338                let _ = conn.execute(
339                    "UPDATE db_muxbus_credentials
340                     SET access_token = '', refresh_token = '', id_token = ''
341                     WHERE id = ?1",
342                    params![current_row_id()],
343                );
344            }
345            Err(_) => {
346                tracing::warn!(
347                    "muxbus: keychain write failed during lazy migration — \
348                     leaving plaintext columns in place for now"
349                );
350            }
351        }
352        tokens
353    }
354}
355
356#[cfg(test)]
357mod tests {
358    use super::*;
359
360    #[test]
361    fn a_failed_keychain_read_uses_the_plaintext_columns_when_they_have_tokens_and_is_an_error_otherwise() {
362        let with = Legacy { access: "a", refresh: "r", id: "i" };
363        let Ok(Found::Tokens(t)) = read_failed("locked".to_string(), keychain_read_error, &with) else { panic!("the plaintext tokens") };
364        assert_eq!((t.access_token.as_str(), t.refresh_token.as_str(), t.id_token.as_str()), ("a", "r", "i"));
365
366        let without = Legacy { access: "", refresh: "r-only", id: "" };
367        let err = read_failed("locked".to_string(), keychain_read_error, &without).err().expect("an error").to_string();
368        assert!(err.contains("muxbus: keychain read failed: locked"), "{err}");
369        // The split-entry paths hand their own error back unwrapped.
370        let err = read_failed(StoreError::Other("as is".into()), |e| e, &without).err().expect("an error").to_string();
371        assert!(err.contains("as is") && !err.contains("keychain read failed"), "{err}");
372    }
373}