agentmux_srv_core/backend/storage/
muxbus_load.rs1use 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
33struct 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
50enum Found {
52 Tokens(MuxBusTokens),
53 Next,
54}
55
56type Step = Result<Found, StoreError>;
57
58fn 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
75fn 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
86fn 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
98fn 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 Ok(SplitRead::Absent) => Ok(Found::Next),
113 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 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 Ok(None) => Ok(Found::Next),
145 Err(e) => read_failed(e, keychain_read_error, legacy),
146 }
147}
148
149fn 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 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 if allow_migration {
185 delete_split_tokens(ns);
186 }
187 }
188 Ok(None) => {} Err(e) => {
190 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 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 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), Err(e) => read_failed(e, |e| e, legacy),
264 }
265}
266
267fn adopt_host_wide_session(ns: &str, user_sub: &str, allow_migration: bool) -> Result<Option<MuxBusTokens>, StoreError> {
275 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 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 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 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}