Skip to main content

codewhale_runtime/credentials/
store.rs

1//! App-owned credential storage: `modify` is the only write path.
2//!
3//! Ported from pi-mono `packages/ai/src/auth/types.ts` (`CredentialStore`) and
4//! `packages/ai/src/auth/credential-store.ts` (`InMemoryCredentialStore`),
5//! MIT, Copyright (c) 2025 Mario Zechner — full notice in the parent module.
6//! Several doc comments below are adapted closely from pi's.
7//!
8//! pi's rule, kept verbatim in spirit: every mutation is a serialized
9//! read-modify-write whose closure sees the current credential, so a refresh
10//! and a concurrent login cannot clobber each other.
11//!
12//! CodeWhale already serializes the xAI OAuth refresh that way, but not
13//! through this store: `xai_oauth` holds `with_xai_oauth_lifecycle_lock`
14//! across the token-file read, the refresh request, and the write-back, so
15//! two concurrent near-expiry observers share one rotated epoch rather than
16//! overwriting each other's refresh token. That lock is process- and
17//! file-level, not this registry's per-provider mutex, and the xAI flow is
18//! **not** rewritten onto [`CredentialStore::modify`] here. This trait is
19//! the shape that would put API-key slots and that OAuth flow on one write
20//! path.
21
22use std::collections::HashMap;
23use std::sync::{Arc, Mutex, OnceLock};
24
25use anyhow::Result;
26
27use super::{Credential, CredentialKind};
28
29/// Non-secret credential metadata for account/status enumeration.
30#[derive(Debug, Clone, PartialEq, Eq)]
31pub struct CredentialInfo {
32    pub provider_id: String,
33    pub(crate) kind: CredentialKind,
34}
35
36/// App-owned credential storage, keyed by provider id, one credential per
37/// provider.
38///
39/// `modify` is the only write path, so every mutation is a serialized
40/// read-modify-write. Callers that need to refresh a rotated token run the
41/// refresh *inside* `modify` so concurrent requests cannot double-refresh.
42///
43/// Error semantics: `read` yields `Ok(None)` for a missing entry and `Err`
44/// on storage failure. `list` is best-effort per slot: a single unreadable
45/// entry is omitted so one corrupt slot cannot hide every other stored
46/// credential from enumeration (status, `/provider`, logout). `list` fails
47/// only when enumeration itself cannot run. `list` must not execute
48/// configured API-key commands or open network flows.
49pub trait CredentialStore: Send + Sync {
50    /// Read the stored credential, possibly expired. Display/status use.
51    fn read(&self, provider_id: &str) -> Result<Option<Credential>>;
52
53    /// List stored credential metadata without exposing secrets.
54    ///
55    /// Per-slot read failures are omitted rather than propagated.
56    fn list(&self) -> Result<Vec<CredentialInfo>>;
57
58    /// Serialized write — the only write path. `f` sees the current
59    /// credential because correct writes (refresh, login-during-refresh)
60    /// depend on it; return the new credential, or `None` to leave the entry
61    /// unchanged. Mutual exclusion is per provider id. Yields the post-write
62    /// credential.
63    ///
64    /// Not yet on any production write path: CodeWhale's two credential writes
65    /// (`save_api_key_for_identity`, logout) already interleave a config-file
66    /// mutation and a compensating rollback between their snapshot and their
67    /// store write, so they take [`with_provider_write_lock`] around the whole
68    /// sequence instead. Collapsing them onto `modify` would change their
69    /// error messages and rollback shape, which is deliberately out of this
70    /// change's scope.
71    fn modify(
72        &self,
73        provider_id: &str,
74        f: &mut dyn FnMut(Option<Credential>) -> Result<Option<Credential>>,
75    ) -> Result<Option<Credential>>;
76
77    /// Remove a credential (logout). Serialized against `modify`.
78    ///
79    /// Exercised by the store tests but not yet on the production logout path:
80    /// the full-wipe logout in `config.rs` still deletes slots directly rather
81    /// than through this trait. Routing it here is the remaining half of the
82    /// port and is deliberately not folded into this change — logout is
83    /// security-sensitive and deserves its own commit and its own tests.
84    fn delete(&self, provider_id: &str) -> Result<()>;
85}
86
87/// Process-wide per-provider write locks.
88///
89/// pi serializes through a per-provider promise chain; the Rust equivalent is
90/// a registry of per-id mutexes. This is process-local: it does not serialize
91/// against another `codewhale` process writing the same slot, which is a real
92/// remaining gap and is called out in the module docs.
93fn provider_lock(provider_id: &str) -> Arc<Mutex<()>> {
94    static LOCKS: OnceLock<Mutex<HashMap<String, Arc<Mutex<()>>>>> = OnceLock::new();
95    let locks = LOCKS.get_or_init(|| Mutex::new(HashMap::new()));
96    let mut guard = locks
97        .lock()
98        .unwrap_or_else(std::sync::PoisonError::into_inner);
99    Arc::clone(
100        guard
101            .entry(provider_id.to_string())
102            .or_insert_with(|| Arc::new(Mutex::new(()))),
103    )
104}
105
106/// Run `body` holding this provider's write lock.
107pub fn with_provider_write_lock<T>(provider_id: &str, body: impl FnOnce() -> T) -> T {
108    let lock = provider_lock(provider_id);
109    let _guard = lock
110        .lock()
111        .unwrap_or_else(std::sync::PoisonError::into_inner);
112    body()
113}
114
115/// Run `body` holding every listed provider's write lock.
116///
117/// Locks are acquired in sorted, deduplicated order so a full logout that
118/// covers every slot cannot deadlock with a per-provider save (which holds
119/// only one). Callers that also take the xAI OAuth lifecycle lock must take
120/// that lock first, matching the documented xAI-then-config order.
121pub fn with_provider_write_locks<T>(
122    provider_ids: impl IntoIterator<Item = impl AsRef<str>>,
123    body: impl FnOnce() -> T,
124) -> T {
125    let mut ids: Vec<String> = provider_ids
126        .into_iter()
127        .map(|id| id.as_ref().to_string())
128        .collect();
129    ids.sort();
130    ids.dedup();
131    let locks: Vec<Arc<Mutex<()>>> = ids.iter().map(|id| provider_lock(id)).collect();
132    let _guards: Vec<_> = locks
133        .iter()
134        .map(|lock| {
135            lock.lock()
136                .unwrap_or_else(std::sync::PoisonError::into_inner)
137        })
138        .collect();
139    body()
140}
141
142/// Default in-memory store. Real stores are injected; this one backs tests and
143/// keeps the trait honest about its own contract — including the serialization
144/// guarantee, which is only observable through `modify`.
145#[derive(Debug, Default)]
146pub(crate) struct InMemoryCredentialStore {
147    entries: Mutex<HashMap<String, Credential>>,
148}
149
150impl InMemoryCredentialStore {
151    #[cfg_attr(not(test), expect(dead_code))]
152    pub(crate) fn new() -> Self {
153        Self::default()
154    }
155}
156
157impl CredentialStore for InMemoryCredentialStore {
158    fn read(&self, provider_id: &str) -> Result<Option<Credential>> {
159        Ok(self
160            .entries
161            .lock()
162            .unwrap_or_else(std::sync::PoisonError::into_inner)
163            .get(provider_id)
164            .cloned())
165    }
166
167    fn list(&self) -> Result<Vec<CredentialInfo>> {
168        let entries = self
169            .entries
170            .lock()
171            .unwrap_or_else(std::sync::PoisonError::into_inner);
172        let mut infos: Vec<CredentialInfo> = entries
173            .iter()
174            .map(|(provider_id, credential)| CredentialInfo {
175                provider_id: provider_id.clone(),
176                kind: credential.kind(),
177            })
178            .collect();
179        infos.sort_by(|left, right| left.provider_id.cmp(&right.provider_id));
180        Ok(infos)
181    }
182
183    fn modify(
184        &self,
185        provider_id: &str,
186        f: &mut dyn FnMut(Option<Credential>) -> Result<Option<Credential>>,
187    ) -> Result<Option<Credential>> {
188        with_provider_write_lock(provider_id, || {
189            let current = self.read(provider_id)?;
190            let next = f(current.clone())?;
191            match next {
192                Some(credential) => {
193                    self.entries
194                        .lock()
195                        .unwrap_or_else(std::sync::PoisonError::into_inner)
196                        .insert(provider_id.to_string(), credential.clone());
197                    Ok(Some(credential))
198                }
199                None => Ok(current),
200            }
201        })
202    }
203
204    fn delete(&self, provider_id: &str) -> Result<()> {
205        with_provider_write_lock(provider_id, || {
206            self.entries
207                .lock()
208                .unwrap_or_else(std::sync::PoisonError::into_inner)
209                .remove(provider_id);
210            Ok(())
211        })
212    }
213}
214
215/// Adapter over CodeWhale's existing durable secret store.
216///
217/// This changes no on-disk format: it reads and writes exactly the slots
218/// `codewhale_secrets::Secrets` already owns. Its value is that every write now
219/// goes through `modify` under the provider's lock, so a save racing a rotate
220/// no longer interleaves.
221pub struct SecretStoreCredentials {
222    secrets: codewhale_secrets::Secrets,
223    /// Slots to probe for `list`. The backing keyring exposes no key
224    /// enumeration, so the caller supplies the known slot names.
225    known_slots: Vec<String>,
226}
227
228impl SecretStoreCredentials {
229    pub fn new(secrets: codewhale_secrets::Secrets, known_slots: Vec<String>) -> Self {
230        Self {
231            secrets,
232            known_slots,
233        }
234    }
235}
236
237impl std::fmt::Debug for SecretStoreCredentials {
238    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
239        f.debug_struct("SecretStoreCredentials")
240            .field("backend", &self.secrets.backend_name())
241            .field("known_slots", &self.known_slots.len())
242            .finish()
243    }
244}
245
246impl CredentialStore for SecretStoreCredentials {
247    fn read(&self, provider_id: &str) -> Result<Option<Credential>> {
248        Ok(self
249            .secrets
250            .get(provider_id)?
251            .filter(|value| !value.trim().is_empty())
252            .map(|key| Credential::ApiKey { key }))
253    }
254
255    fn list(&self) -> Result<Vec<CredentialInfo>> {
256        let mut infos = Vec::new();
257        for slot in &self.known_slots {
258            match self.read(slot) {
259                Ok(Some(_)) => infos.push(CredentialInfo {
260                    provider_id: slot.clone(),
261                    kind: CredentialKind::ApiKey,
262                }),
263                Ok(None) => {}
264                Err(error) => {
265                    // Deliberate: skip the bad slot and keep going. Propagating
266                    // `read`'s error used to fail the whole enumeration, so one
267                    // unreadable entry hid every other credential from
268                    // `/provider` and left logout unable to delete the rest.
269                    tracing::warn!(
270                        slot,
271                        error = %error,
272                        "skipping unreadable credential slot during enumeration"
273                    );
274                }
275            }
276        }
277        Ok(infos)
278    }
279
280    fn modify(
281        &self,
282        provider_id: &str,
283        f: &mut dyn FnMut(Option<Credential>) -> Result<Option<Credential>>,
284    ) -> Result<Option<Credential>> {
285        with_provider_write_lock(provider_id, || {
286            let current = self.read(provider_id)?;
287            let next = f(current.clone())?;
288            match next {
289                Some(credential) => {
290                    self.secrets.set(provider_id, credential.expose_secret())?;
291                    Ok(Some(credential))
292                }
293                None => Ok(current),
294            }
295        })
296    }
297
298    fn delete(&self, provider_id: &str) -> Result<()> {
299        with_provider_write_lock(provider_id, || {
300            self.secrets.delete(provider_id)?;
301            Ok(())
302        })
303    }
304}