Skip to main content

rig_core/providers/auth/
store.rs

1//! Where sign-ins keep their credentials: the [`TokenStore`] trait, an
2//! in-memory store, and the owner-only file store native targets default to.
3
4use crate::error::BoxError;
5use crate::wasm_compat::{WasmBoxedFuture, WasmCompatSend, WasmCompatSync};
6use std::collections::HashMap;
7use std::sync::{Arc, Mutex};
8
9/// Keeps the credentials a sign-in writes and refreshes, each a JSON text
10/// under a key the provider names, such as `chatgpt` or `copilot`.
11///
12/// An authenticator reads its record before every request that needs one,
13/// and saves it after a sign-in, a refresh, or an invalidated token. It never
14/// touches storage except through its store. Clones of one authenticator
15/// share a refresh lock, and a store shared with other processes holds the
16/// record against them while a refresh or sign-in reads and saves it
17/// ([`lock`](Self::lock)), so one refresh runs at a time and each request
18/// reads what the last one saved. When a refresh token turns out to be spent, the
19/// authenticator reads the store again and takes a fresh credential another
20/// client or process saved there, before asking for a new sign-in.
21///
22/// ```
23/// use rig_core::providers::auth::{DeviceCodeHandler, MemoryTokenStore};
24/// use rig_core::providers::chatgpt::auth::{AuthSource, Authenticator};
25/// use std::sync::Arc;
26///
27/// let store = Arc::new(MemoryTokenStore::default());
28/// let auth = Authenticator::new(AuthSource::OAuth, store, DeviceCodeHandler::default(), true);
29/// # let _ = auth;
30/// ```
31pub trait TokenStore: WasmCompatSend + WasmCompatSync {
32    /// The record kept under `key`, or `None` when there is none. An error
33    /// means the store could not answer, and fails the request.
34    fn load<'a>(&'a self, key: &'a str) -> WasmBoxedFuture<'a, Result<Option<String>, BoxError>>;
35
36    /// Keep `record` under `key`, replacing any record there.
37    fn save<'a>(
38        &'a self,
39        key: &'a str,
40        record: &'a str,
41    ) -> WasmBoxedFuture<'a, Result<(), BoxError>>;
42
43    /// Forget the record under `key`; forgetting a missing record succeeds.
44    fn delete<'a>(&'a self, key: &'a str) -> WasmBoxedFuture<'a, Result<(), BoxError>>;
45
46    /// Hold the record under `key` until the returned [`StoreLock`] is
47    /// dropped, against every other holder of it, in this process or
48    /// another (such as a refresh another rig runs at the same moment). The
49    /// default holds nothing: a store no other process reads needs no
50    /// lock beyond the authenticator's own.
51    fn lock<'a>(&'a self, _key: &'a str) -> WasmBoxedFuture<'a, Result<StoreLock, BoxError>> {
52        Box::pin(async { Ok(StoreLock::new(())) })
53    }
54}
55
56/// A record held by [`TokenStore::lock`], let go when dropped: it owns the
57/// store's guard and drops it then.
58pub struct StoreLock {
59    // Nothing reads the guard; the mutex only makes the lock `Sync` and
60    // unwind safe whatever the guard is.
61    _guard: Mutex<Box<dyn WasmCompatSend>>,
62}
63
64impl StoreLock {
65    /// Holds `guard`, any value whose drop releases the store's lock, such
66    /// as a locked file, an open database transaction or a lease on a
67    /// distributed lock, until this lock is dropped. A store with nothing
68    /// to release passes `()`.
69    ///
70    /// The guard's `Drop` runs synchronously, possibly inside an async task,
71    /// so it must not block. A release that needs I/O should spawn it from
72    /// `Drop` or let the lock's lease expire.
73    pub fn new(guard: impl WasmCompatSend + 'static) -> Self {
74        Self {
75            _guard: Mutex::new(Box::new(guard)),
76        }
77    }
78}
79
80impl std::fmt::Debug for StoreLock {
81    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
82        f.debug_struct("StoreLock").finish_non_exhaustive()
83    }
84}
85
86impl<T: TokenStore + ?Sized> TokenStore for Arc<T> {
87    fn load<'a>(&'a self, key: &'a str) -> WasmBoxedFuture<'a, Result<Option<String>, BoxError>> {
88        (**self).load(key)
89    }
90
91    fn save<'a>(
92        &'a self,
93        key: &'a str,
94        record: &'a str,
95    ) -> WasmBoxedFuture<'a, Result<(), BoxError>> {
96        (**self).save(key, record)
97    }
98
99    fn delete<'a>(&'a self, key: &'a str) -> WasmBoxedFuture<'a, Result<(), BoxError>> {
100        (**self).delete(key)
101    }
102
103    fn lock<'a>(&'a self, key: &'a str) -> WasmBoxedFuture<'a, Result<StoreLock, BoxError>> {
104        (**self).lock(key)
105    }
106}
107
108/// A [`TokenStore`] in this process's memory, gone when it is dropped.
109#[derive(Default)]
110pub struct MemoryTokenStore(Mutex<HashMap<String, String>>);
111
112impl std::fmt::Debug for MemoryTokenStore {
113    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
114        f.debug_struct("MemoryTokenStore").finish_non_exhaustive()
115    }
116}
117
118impl MemoryTokenStore {
119    fn records(&self) -> std::sync::MutexGuard<'_, HashMap<String, String>> {
120        crate::lock(&self.0)
121    }
122}
123
124impl TokenStore for MemoryTokenStore {
125    fn load<'a>(&'a self, key: &'a str) -> WasmBoxedFuture<'a, Result<Option<String>, BoxError>> {
126        Box::pin(async move { Ok(self.records().get(key).cloned()) })
127    }
128
129    fn save<'a>(
130        &'a self,
131        key: &'a str,
132        record: &'a str,
133    ) -> WasmBoxedFuture<'a, Result<(), BoxError>> {
134        Box::pin(async move {
135            self.records().insert(key.to_owned(), record.to_owned());
136            Ok(())
137        })
138    }
139
140    fn delete<'a>(&'a self, key: &'a str) -> WasmBoxedFuture<'a, Result<(), BoxError>> {
141        Box::pin(async move {
142            self.records().remove(key);
143            Ok(())
144        })
145    }
146}
147
148/// A [`TokenStore`] keeping each record in `<dir>/<key>.json`, written whole
149/// or not at all (a temporary file renamed over it, and on Unix the
150/// directory synced after), and held across processes with a file lock on
151/// `<dir>/<key>.lock`. On Unix the files, and the directories it creates for
152/// them, are readable by the owner alone. Native only.
153///
154/// [`load`](TokenStore::load) refuses a record that is a symlink or not a
155/// regular file, or is over 64 KiB, with a [`FileStoreError`]. On Unix, when
156/// group or others have any access to a record, it narrows the record to
157/// owner-only before reading it, and refuses the record when that fails.
158#[cfg(not(target_family = "wasm"))]
159#[derive(Debug, Clone)]
160pub struct FileTokenStore {
161    dir: std::path::PathBuf,
162    lock_wait: std::time::Duration,
163}
164
165#[cfg(not(target_family = "wasm"))]
166impl FileTokenStore {
167    /// A store over the files in `dir`, created when first written.
168    pub fn new(dir: impl Into<std::path::PathBuf>) -> Self {
169        Self {
170            dir: dir.into(),
171            lock_wait: LOCK_WAIT,
172        }
173    }
174
175    /// This store, with [`lock`](TokenStore::lock) waiting at most `wait`
176    /// for another holder instead of two minutes. A zero wait refuses a held
177    /// lock at once.
178    pub fn with_lock_wait(self, wait: std::time::Duration) -> Self {
179        Self {
180            lock_wait: wait,
181            ..self
182        }
183    }
184
185    /// The file the record under `key` is kept in.
186    pub fn path(&self, key: &str) -> std::path::PathBuf {
187        self.dir.join(format!("{key}.json"))
188    }
189}
190
191#[cfg(not(target_family = "wasm"))]
192impl TokenStore for FileTokenStore {
193    fn load<'a>(&'a self, key: &'a str) -> WasmBoxedFuture<'a, Result<Option<String>, BoxError>> {
194        Box::pin(async move { read_private(&self.path(key)) })
195    }
196
197    fn save<'a>(
198        &'a self,
199        key: &'a str,
200        record: &'a str,
201    ) -> WasmBoxedFuture<'a, Result<(), BoxError>> {
202        Box::pin(async move { Ok(write_private(&self.path(key), record.as_bytes())?) })
203    }
204
205    fn delete<'a>(&'a self, key: &'a str) -> WasmBoxedFuture<'a, Result<(), BoxError>> {
206        Box::pin(async move {
207            let path = self.path(key);
208            match std::fs::remove_file(&path) {
209                Ok(()) => Ok(sync_parent(&path)?),
210                Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
211                Err(error) => Err(error.into()),
212            }
213        })
214    }
215
216    /// Takes the file lock on `<dir>/<key>.lock`, waiting while another
217    /// holder has it, for at most two minutes unless
218    /// [`with_lock_wait`](FileTokenStore::with_lock_wait) set another wait,
219    /// then refusing with [`FileStoreError::Busy`]. A process that dies lets
220    /// go of it.
221    fn lock<'a>(&'a self, key: &'a str) -> WasmBoxedFuture<'a, Result<StoreLock, BoxError>> {
222        Box::pin(async move {
223            let path = self.dir.join(format!("{key}.lock"));
224            create_private_dir(&path)?;
225            let mut options = std::fs::OpenOptions::new();
226            options.read(true).write(true).create(true).truncate(false);
227            #[cfg(unix)]
228            std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600);
229            let file = options.open(&path)?;
230            let started = std::time::Instant::now();
231            loop {
232                match file.try_lock() {
233                    Ok(()) => return Ok(StoreLock::new(file)),
234                    Err(std::fs::TryLockError::WouldBlock)
235                        if started.elapsed() < self.lock_wait =>
236                    {
237                        crate::wasm_compat::sleep(std::time::Duration::from_millis(50)).await;
238                    }
239                    Err(std::fs::TryLockError::WouldBlock) => {
240                        return Err(FileStoreError::Busy {
241                            path,
242                            waited: self.lock_wait,
243                        }
244                        .into());
245                    }
246                    Err(std::fs::TryLockError::Error(error)) => return Err(error.into()),
247                }
248            }
249        })
250    }
251}
252
253/// Why a [`FileTokenStore`] refused to read a credential file or take its
254/// lock. It reaches the caller inside the store's boxed error.
255#[cfg(not(target_family = "wasm"))]
256#[derive(Debug, thiserror::Error)]
257#[non_exhaustive]
258pub enum FileStoreError {
259    /// The file is a symlink, a directory, or another kind of file than a
260    /// regular one, or was replaced by one while it was opened.
261    #[error("{} is a symlink or not a regular file; a credential is read only from a regular file", path.display())]
262    NotAFile {
263        /// The credential file.
264        path: std::path::PathBuf,
265    },
266    /// The file holds more than `limit` bytes.
267    #[error("{} is larger than {limit} bytes", path.display())]
268    TooLarge {
269        /// The credential file.
270        path: std::path::PathBuf,
271        /// The most a credential file may hold.
272        limit: u64,
273    },
274    /// Group or others have access to the file and it could not be made
275    /// owner-only, for example because another user owns it.
276    #[error("{} is open to group or others and could not be made owner-only", path.display())]
277    NotNarrowed {
278        /// The credential file.
279        path: std::path::PathBuf,
280        /// Why the permissions could not be changed.
281        #[source]
282        source: std::io::Error,
283    },
284    /// Another holder, in this process or another, still held the lock when
285    /// the wait ran out. Trying again later may succeed.
286    #[error("another holder kept {} locked for {waited:?}", path.display())]
287    Busy {
288        /// The lock file.
289        path: std::path::PathBuf,
290        /// How long the lock was waited for.
291        waited: std::time::Duration,
292    },
293}
294
295/// The most a credential file may hold.
296#[cfg(not(target_family = "wasm"))]
297const RECORD_LIMIT: u64 = 64 * 1024;
298
299/// Reads the credential file at `path`, `None` when there is none. The
300/// checks look at the file that was opened, so it cannot be swapped for a
301/// symlink between the check and the read: on Unix its identity is compared
302/// with the unfollowed path's, and on Windows the open does not follow a
303/// link.
304#[cfg(not(target_family = "wasm"))]
305fn read_private(path: &std::path::Path) -> Result<Option<String>, BoxError> {
306    use std::io::Read;
307
308    let not_a_file = || FileStoreError::NotAFile {
309        path: path.to_owned(),
310    };
311    let linked = match std::fs::symlink_metadata(path) {
312        Ok(linked) => linked,
313        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
314        Err(error) => return Err(error.into()),
315    };
316    if !linked.file_type().is_file() {
317        return Err(not_a_file().into());
318    }
319    let mut options = std::fs::OpenOptions::new();
320    options.read(true);
321    // FILE_FLAG_OPEN_REPARSE_POINT: open a symlink itself, which the handle
322    // check below then refuses.
323    #[cfg(windows)]
324    std::os::windows::fs::OpenOptionsExt::custom_flags(&mut options, 0x0020_0000);
325    let file = options.open(path)?;
326    let opened = file.metadata()?;
327    if !opened.is_file() {
328        return Err(not_a_file().into());
329    }
330    #[cfg(unix)]
331    {
332        use std::os::unix::fs::{MetadataExt, PermissionsExt};
333        if (opened.dev(), opened.ino()) != (linked.dev(), linked.ino()) {
334            return Err(not_a_file().into());
335        }
336        if opened.mode() & 0o077 != 0 {
337            file.set_permissions(std::fs::Permissions::from_mode(0o600))
338                .map_err(|source| FileStoreError::NotNarrowed {
339                    path: path.to_owned(),
340                    source,
341                })?;
342        }
343    }
344    let mut record = Vec::new();
345    file.take(RECORD_LIMIT + 1).read_to_end(&mut record)?;
346    if record.len() as u64 > RECORD_LIMIT {
347        return Err(FileStoreError::TooLarge {
348            path: path.to_owned(),
349            limit: RECORD_LIMIT,
350        }
351        .into());
352    }
353    Ok(Some(String::from_utf8(record)?))
354}
355
356/// How long [`FileTokenStore::lock`] waits for another holder by default:
357/// far longer than a refresh's one request takes.
358#[cfg(not(target_family = "wasm"))]
359const LOCK_WAIT: std::time::Duration = std::time::Duration::from_secs(120);
360
361/// Creates the directories above `path`, 0700 on Unix.
362#[cfg(not(target_family = "wasm"))]
363fn create_private_dir(path: &std::path::Path) -> Result<(), std::io::Error> {
364    let Some(parent) = path.parent() else {
365        return Ok(());
366    };
367    let mut builder = std::fs::DirBuilder::new();
368    builder.recursive(true);
369    #[cfg(unix)]
370    std::os::unix::fs::DirBuilderExt::mode(&mut builder, 0o700);
371    builder.create(parent)
372}
373
374/// Writes a credential file whole or not at all, creating the directories
375/// above it: the bytes go to a fresh temporary file beside it, which is
376/// synced and renamed over it, and on Unix the directory is synced so the
377/// rename survives a crash, so a crash or a reader at the same moment never
378/// sees half a credential. On Unix the directories it creates are
379/// 0700, and the file is created 0600, or narrowed to 0600 before anything
380/// is written to it.
381#[cfg(not(target_family = "wasm"))]
382fn write_private(path: &std::path::Path, bytes: &[u8]) -> Result<(), std::io::Error> {
383    use std::io::Write;
384    use std::sync::atomic::{AtomicU64, Ordering};
385
386    static WRITES: AtomicU64 = AtomicU64::new(0);
387    create_private_dir(path)?;
388    let mut temp = path.as_os_str().to_owned();
389    temp.push(format!(
390        ".tmp-{}-{}",
391        std::process::id(),
392        WRITES.fetch_add(1, Ordering::Relaxed)
393    ));
394    let temp = std::path::PathBuf::from(temp);
395    let write = || {
396        let mut options = std::fs::OpenOptions::new();
397        options.write(true).create_new(true);
398        #[cfg(unix)]
399        std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600);
400        let mut file = options.open(&temp)?;
401        #[cfg(unix)]
402        file.set_permissions(std::os::unix::fs::PermissionsExt::from_mode(0o600))?;
403        file.write_all(bytes)?;
404        file.sync_all()?;
405        std::fs::rename(&temp, path)
406    };
407    let written = write();
408    if written.is_err() {
409        std::fs::remove_file(&temp).ok();
410    }
411    written?;
412    sync_parent(path)
413}
414
415/// Syncs the directory holding `path`, so a rename or removal in it
416/// survives a crash. Windows cannot open a directory to sync it, so there
417/// this does nothing.
418#[cfg(not(target_family = "wasm"))]
419fn sync_parent(path: &std::path::Path) -> Result<(), std::io::Error> {
420    #[cfg(unix)]
421    if let Some(parent) = path.parent() {
422        std::fs::File::open(parent)?.sync_all()?;
423    }
424    #[cfg(not(unix))]
425    let _ = path;
426    Ok(())
427}
428
429/// The JSON record under `key`, or `T::default()` when there is none.
430pub(crate) async fn load_record<T: Default + serde::de::DeserializeOwned>(
431    store: &dyn TokenStore,
432    key: &str,
433) -> Result<T, super::AuthError> {
434    match store.load(key).await.map_err(super::AuthError::Store)? {
435        Some(record) => Ok(serde_json::from_str(&record)?),
436        None => Ok(T::default()),
437    }
438}
439
440/// Keep `record` under `key` as JSON.
441pub(crate) async fn save_record<T: serde::Serialize>(
442    store: &dyn TokenStore,
443    key: &str,
444    record: &T,
445) -> Result<(), super::AuthError> {
446    let text = serde_json::to_string_pretty(record)?;
447    store
448        .save(key, &text)
449        .await
450        .map_err(super::AuthError::Store)
451}
452
453#[cfg(test)]
454mod tests;