Skip to main content

rig_core/providers/
auth.rs

1//! The sign-in types the ChatGPT and Copilot authenticators share: errors,
2//! device-code callbacks, token stores, and the browser sign-in's loopback
3//! listener.
4//!
5//! ```
6//! use rig_core::providers::auth::DeviceCodeHandler;
7//! let handler = DeviceCodeHandler::new(|prompt| {
8//!     println!("Visit {} and enter {}", prompt.verification_uri, prompt.user_code);
9//! });
10//! ```
11
12use crate::http_client::{self, HttpClientExt};
13use crate::wasm_compat::{WasmCompatSend, WasmCompatSync};
14use std::sync::Arc;
15
16/// Device authorization details surfaced to a provider callback.
17#[derive(Debug, Clone)]
18pub struct DeviceCodePrompt {
19    /// URL where the user authorizes the device.
20    pub verification_uri: String,
21    /// Short code the user enters at the verification URL.
22    pub user_code: String,
23}
24
25/// Device-code callback with thread-safety bounds outside browser WASM.
26/// Browser WASM authenticators do not invoke it.
27#[cfg(not(target_family = "wasm"))]
28pub(crate) type DeviceCodeCallback = dyn Fn(DeviceCodePrompt) + Send + Sync;
29#[cfg(target_family = "wasm")]
30pub(crate) type DeviceCodeCallback = dyn Fn(DeviceCodePrompt);
31
32/// Optional callback invoked when an OAuth device flow needs user action.
33#[derive(Clone, Default)]
34pub struct DeviceCodeHandler(pub(crate) Option<Arc<DeviceCodeCallback>>);
35
36impl DeviceCodeHandler {
37    /// Wraps a device-code callback.
38    pub fn new<F>(handler: F) -> Self
39    where
40        F: Fn(DeviceCodePrompt) + WasmCompatSend + WasmCompatSync + 'static,
41    {
42        Self(Some(Arc::new(handler)))
43    }
44}
45
46impl DeviceCodeHandler {
47    /// Show `prompt` with the callback, or print `fallback_message` to
48    /// stdout when there is none.
49    #[cfg(not(target_family = "wasm"))]
50    pub(crate) fn show(&self, prompt: DeviceCodePrompt, fallback_message: &str) {
51        match &self.0 {
52            Some(callback) => callback(prompt),
53            None => println!("{fallback_message}"),
54        }
55    }
56}
57
58impl std::fmt::Debug for DeviceCodeHandler {
59    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
60        if self.0.is_some() {
61            f.write_str("DeviceCodeHandler(<callback>)")
62        } else {
63            f.write_str("DeviceCodeHandler(None)")
64        }
65    }
66}
67
68#[derive(Debug, thiserror::Error)]
69pub enum AuthError {
70    #[error("{0}")]
71    Message(String),
72    #[error(transparent)]
73    Io(#[from] std::io::Error),
74    #[error(transparent)]
75    Json(#[from] serde_json::Error),
76    /// The HTTP transport failed. Non-success responses arrive as the
77    /// status-bearing [`http_client::Error`] variants (so the status is still
78    /// inspectable); response-less failures as
79    /// [`http_client::Error::Transient`] or [`http_client::Error::Permanent`].
80    #[error(transparent)]
81    Http(#[from] http_client::Error),
82    /// The sign-in server answered with a failure: `message` says what it
83    /// said, and `source`, its reply, says whether asking again may work.
84    #[error("{message}")]
85    Reply {
86        /// What the failure means for the sign-in.
87        message: String,
88        /// The non-success reply.
89        #[source]
90        source: http_client::Error,
91    },
92    /// The [`TokenStore`] could not load or save a credential.
93    #[error("token store failed: {0}")]
94    Store(#[source] crate::error::BoxError),
95}
96
97/// The credential a signed-in request is sent with.
98#[derive(Debug, Clone, PartialEq, Eq)]
99pub struct AuthContext {
100    /// The resolved key. Use [`Secret::expose`](crate::wire::Secret::expose)
101    /// only when raw bytes are required.
102    pub api_key: crate::wire::Secret,
103    /// The account the key belongs to, when the provider names one
104    /// (ChatGPT's `ChatGPT-Account-Id`).
105    pub account_id: Option<String>,
106    /// The API root the sign-in names, when it names one (Copilot's
107    /// session endpoint).
108    pub api_base: Option<String>,
109}
110
111/// What every provider's authenticator holds: where its credential comes
112/// from, the store that keeps it, how a device code is shown, whether a
113/// device flow may start, the lock a refresh holds and the credential last
114/// resolved. Clones share the store, the lock and the remembered credential.
115#[derive(Clone)]
116#[cfg_attr(target_family = "wasm", allow(dead_code))]
117pub(crate) struct Shell<S> {
118    pub(crate) source: S,
119    pub(crate) store: Arc<dyn TokenStore>,
120    pub(crate) device_code_handler: DeviceCodeHandler,
121    pub(crate) allow_device_flow: bool,
122    /// Held across a cache refresh to prevent concurrent updates.
123    pub(crate) refresh_lock: Arc<futures::lock::Mutex<()>>,
124    pub(crate) remembered: Remembered,
125}
126
127impl<S> Shell<S> {
128    pub(crate) fn new(
129        source: S,
130        store: impl TokenStore + 'static,
131        device_code_handler: DeviceCodeHandler,
132        allow_device_flow: bool,
133    ) -> Self {
134        Self {
135            source,
136            store: Arc::new(store),
137            device_code_handler,
138            allow_device_flow,
139            refresh_lock: Arc::default(),
140            remembered: Remembered::default(),
141        }
142    }
143}
144
145impl<S> Shell<S> {
146    /// Holds the record under `key` for a refresh, a sign-in or a sign-out:
147    /// the refresh lock its clones share, then the store's lock on `key`
148    /// ([`TokenStore::lock`]), so one runs at a time across clones and
149    /// processes, and each reads what the last one saved.
150    #[cfg_attr(target_family = "wasm", allow(dead_code))]
151    pub(crate) async fn hold(&self, key: &str) -> Result<Held<'_>, AuthError> {
152        let refresh = self.refresh_lock.lock().await;
153        let store = self.store.lock(key).await.map_err(AuthError::Store)?;
154        Ok(Held {
155            _refresh: refresh,
156            _store: store,
157        })
158    }
159}
160
161/// What [`Shell::hold`] holds, let go when dropped: the store's lock first.
162#[cfg_attr(target_family = "wasm", allow(dead_code))]
163pub(crate) struct Held<'a> {
164    _store: StoreLock,
165    _refresh: futures::lock::MutexGuard<'a, ()>,
166}
167
168impl<'a> Held<'a> {
169    /// Run `wait` with the store's lock let go, so other processes can use
170    /// the store meanwhile, and the refresh lock kept, so clones still wait.
171    /// The store's lock on `key` is taken again before returning.
172    #[cfg_attr(target_family = "wasm", allow(dead_code))]
173    pub(crate) async fn store_free_during<S, T>(
174        self,
175        shell: &Shell<S>,
176        key: &str,
177        wait: impl Future<Output = T>,
178    ) -> Result<(T, Held<'a>), AuthError> {
179        let Held { _store, _refresh } = self;
180        drop(_store);
181        let out = wait.await;
182        let store = shell.store.lock(key).await.map_err(AuthError::Store)?;
183        Ok((
184            out,
185            Held {
186                _store: store,
187                _refresh,
188            },
189        ))
190    }
191}
192
193impl<S: std::fmt::Debug> std::fmt::Debug for Shell<S> {
194    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
195        f.debug_struct("Authenticator")
196            .field("source", &self.source)
197            .field("device_code_handler", &self.device_code_handler)
198            .field("allow_device_flow", &self.allow_device_flow)
199            .finish_non_exhaustive()
200    }
201}
202
203/// The last credential an authenticator resolved and its expiry, shared by
204/// its clones: a live one is served without the store, its lock or a parse.
205#[derive(Clone, Default)]
206pub(crate) struct Remembered(Arc<std::sync::Mutex<Option<(AuthContext, i64)>>>);
207
208impl Remembered {
209    /// The credential while it is live, `skew_seconds` before its expiry.
210    pub(crate) fn live(&self, skew_seconds: i64) -> Option<AuthContext> {
211        let held = self.0.lock().ok()?;
212        let (context, expires_at) = held.as_ref()?;
213        (!token_expired(Some(*expires_at), skew_seconds)).then(|| context.clone())
214    }
215
216    /// Remember `context` until `expires_at`; one with no expiry is not
217    /// remembered.
218    pub(crate) fn keep(&self, context: &AuthContext, expires_at: Option<i64>) {
219        if let Ok(mut held) = self.0.lock() {
220            *held = expires_at.map(|expires_at| (context.clone(), expires_at));
221        }
222    }
223
224    /// Forget the remembered credential.
225    pub(crate) fn forget(&self) {
226        if let Ok(mut held) = self.0.lock() {
227            *held = None;
228        }
229    }
230}
231
232/// Build a request to an absolute authentication URL, independent of the API base.
233pub(crate) fn request(method: http::Method, url: &str) -> http::request::Builder {
234    http::Request::builder().method(method).uri(url)
235}
236
237/// `builder` finished with `pairs` as a form-encoded body.
238#[cfg(not(target_family = "wasm"))]
239pub(crate) fn form(
240    builder: http::request::Builder,
241    pairs: &[(&str, &str)],
242) -> http::Result<http::Request<bytes::Bytes>> {
243    let body = url::form_urlencoded::Serializer::new(String::new())
244        .extend_pairs(pairs)
245        .finish();
246    builder
247        .header(
248            http::header::CONTENT_TYPE,
249            "application/x-www-form-urlencoded",
250        )
251        .body(body.into())
252}
253
254/// Send `req` and decode its JSON response.
255/// Request and transport failures return [`AuthError::Http`], preserving HTTP
256/// status when available. Invalid JSON returns [`AuthError::Json`].
257pub(crate) async fn send_json<H, T>(
258    http: &H,
259    req: http::Result<http::Request<bytes::Bytes>>,
260) -> Result<T, AuthError>
261where
262    H: HttpClientExt,
263    T: serde::de::DeserializeOwned,
264{
265    let bytes = send_bytes(http, req).await?;
266    Ok(serde_json::from_slice(&bytes)?)
267}
268
269/// Send `req` through the transport and return the raw success body. A
270/// non-success reply the transport returned as `Ok` is the same
271/// [`AuthError::Http`] the bundled transport reports for it.
272pub(crate) async fn send_bytes<H>(
273    http: &H,
274    req: http::Result<http::Request<bytes::Bytes>>,
275) -> Result<bytes::Bytes, AuthError>
276where
277    H: HttpClientExt,
278{
279    let req = req.map_err(http_client::Error::Protocol)?;
280    let (parts, body) = http.send(req).await?.into_parts();
281    let body = body.await?;
282    if !parts.status.is_success() {
283        return Err(http_client::Error::InvalidStatusCodeWithDetails {
284            status: parts.status,
285            body: String::from_utf8_lossy(&body).into_owned(),
286            headers: parts.headers,
287        }
288        .into());
289    }
290    Ok(body)
291}
292
293/// Returns true when the token is expired (or has no expiry), treating the
294/// token as expired `skew_seconds` before its actual `expires_at`.
295pub(crate) fn token_expired(expires_at: Option<i64>, skew_seconds: i64) -> bool {
296    let now = (crate::now_ms() / 1000) as i64;
297    expires_at.is_none_or(|exp| now >= exp - skew_seconds)
298}
299
300#[cfg(not(target_family = "wasm"))]
301pub mod loopback;
302mod store;
303
304#[cfg(not(target_family = "wasm"))]
305pub use store::{FileStoreError, FileTokenStore};
306pub use store::{MemoryTokenStore, StoreLock, TokenStore};
307pub(crate) use store::{load_record, save_record};