Skip to main content

maple_sdk/
session.rs

1use crate::error::{Error, Result};
2use crate::types::TokenPair;
3use std::sync::{Arc, RwLock};
4use zeroize::Zeroizing;
5
6#[derive(Debug, Clone)]
7pub(crate) struct CredentialSnapshot {
8    pub(crate) tokens: Option<TokenPair>,
9    pub(crate) api_key: Option<String>,
10    pub(crate) generation: u64,
11    pub(crate) token_generation: u64,
12    pub(crate) api_key_generation: u64,
13}
14
15/// A caller-selected credential that must still be the exact credential held
16/// by this manager when a Transport V2 request is admitted.
17///
18/// Values are borrowed so this type never creates another long-lived secret
19/// copy. The comparison is made while holding the credential read lock, and
20/// the admission closure runs under that same lock.
21pub(crate) enum CredentialFence<'a> {
22    Generation { generation: u64 },
23    AccessToken { generation: u64, value: &'a str },
24    ApiKey { generation: u64, value: &'a str },
25    RefreshToken { generation: u64, value: &'a str },
26}
27
28#[derive(Debug, Default)]
29struct CredentialState {
30    tokens: Option<TokenPair>,
31    api_key: Option<String>,
32    generation: u64,
33    token_generation: u64,
34    api_key_generation: u64,
35}
36
37pub struct SessionManager {
38    credentials: Arc<RwLock<CredentialState>>,
39}
40
41impl SessionManager {
42    pub fn new() -> Self {
43        Self {
44            credentials: Arc::new(RwLock::new(CredentialState::default())),
45        }
46    }
47
48    pub fn new_with_api_key(api_key: String) -> Self {
49        Self {
50            credentials: Arc::new(RwLock::new(CredentialState {
51                api_key: Some(api_key),
52                generation: 1,
53                api_key_generation: 1,
54                ..CredentialState::default()
55            })),
56        }
57    }
58
59    pub fn set_api_key(&self, api_key: String) -> Result<()> {
60        let mut credentials = self.credentials.write().map_err(|e| {
61            Error::Authentication(format!("Failed to acquire credentials write lock: {}", e))
62        })?;
63
64        credentials.api_key = Some(api_key);
65        credentials.generation = credentials.generation.wrapping_add(1);
66        credentials.api_key_generation = credentials.api_key_generation.wrapping_add(1);
67        Ok(())
68    }
69
70    pub fn get_api_key(&self) -> Result<Option<String>> {
71        let credentials = self.credentials.read().map_err(|e| {
72            Error::Authentication(format!("Failed to acquire credentials read lock: {}", e))
73        })?;
74
75        Ok(credentials.api_key.clone())
76    }
77
78    pub fn clear_api_key(&self) -> Result<()> {
79        let mut credentials = self.credentials.write().map_err(|e| {
80            Error::Authentication(format!("Failed to acquire credentials write lock: {}", e))
81        })?;
82
83        credentials.api_key = None;
84        credentials.generation = credentials.generation.wrapping_add(1);
85        credentials.api_key_generation = credentials.api_key_generation.wrapping_add(1);
86        Ok(())
87    }
88
89    pub fn set_tokens(&self, access_token: String, refresh_token: Option<String>) -> Result<()> {
90        let mut credentials = self.credentials.write().map_err(|e| {
91            Error::Authentication(format!("Failed to acquire credentials write lock: {}", e))
92        })?;
93
94        credentials.tokens = Some(TokenPair {
95            access_token,
96            refresh_token,
97        });
98        credentials.generation = credentials.generation.wrapping_add(1);
99        credentials.token_generation = credentials.token_generation.wrapping_add(1);
100
101        Ok(())
102    }
103
104    pub(crate) fn set_tokens_if_generation(
105        &self,
106        expected_token_generation: u64,
107        access_token: String,
108        refresh_token: Option<String>,
109    ) -> Result<bool> {
110        let mut credentials = self.credentials.write().map_err(|e| {
111            Error::Authentication(format!("Failed to acquire credentials write lock: {}", e))
112        })?;
113
114        if credentials.token_generation != expected_token_generation {
115            return Ok(false);
116        }
117
118        credentials.tokens = Some(TokenPair {
119            access_token,
120            refresh_token,
121        });
122        credentials.generation = credentials.generation.wrapping_add(1);
123        credentials.token_generation = credentials.token_generation.wrapping_add(1);
124        Ok(true)
125    }
126
127    pub(crate) fn clear_tokens_if_generation(
128        &self,
129        expected_token_generation: u64,
130    ) -> Result<bool> {
131        let mut credentials = self.credentials.write().map_err(|e| {
132            Error::Authentication(format!("Failed to acquire credentials write lock: {}", e))
133        })?;
134
135        if credentials.token_generation != expected_token_generation {
136            return Ok(false);
137        }
138
139        credentials.tokens = None;
140        credentials.generation = credentials.generation.wrapping_add(1);
141        credentials.token_generation = credentials.token_generation.wrapping_add(1);
142        Ok(true)
143    }
144
145    pub(crate) fn get_credential_snapshot(&self) -> Result<CredentialSnapshot> {
146        let credentials = self.credentials.read().map_err(|e| {
147            Error::Authentication(format!("Failed to acquire credentials read lock: {}", e))
148        })?;
149
150        Ok(CredentialSnapshot {
151            tokens: credentials.tokens.clone(),
152            api_key: credentials.api_key.clone(),
153            generation: credentials.generation,
154            token_generation: credentials.token_generation,
155            api_key_generation: credentials.api_key_generation,
156        })
157    }
158
159    pub(crate) fn credential_generation(&self) -> Result<u64> {
160        self.credentials
161            .read()
162            .map(|credentials| credentials.generation)
163            .map_err(|_| Error::Authentication("Credential state is unavailable".to_string()))
164    }
165
166    pub(crate) fn anonymous_generation(&self) -> Result<u64> {
167        let credentials = self.credentials.read().map_err(|e| {
168            Error::Authentication(format!("Failed to acquire credentials read lock: {}", e))
169        })?;
170        if credentials.tokens.is_some() || credentials.api_key.is_some() {
171            return Err(Error::Authentication(
172                "Native OAuth handoff requires an anonymous client".to_string(),
173            ));
174        }
175        Ok(credentials.generation)
176    }
177
178    /// Linearize one request admission against synchronous credential changes.
179    ///
180    /// The closure must be synchronous and must not call back into this
181    /// manager. Transport V2 uses it only to allocate a one-time request ID and
182    /// seal the request. Once the closure returns successfully, the request is
183    /// considered admitted: a later credential change does not cancel work
184    /// already sealed for transmission.
185    pub(crate) fn admit_if_credential_is_current<T>(
186        &self,
187        fence: Option<CredentialFence<'_>>,
188        admit: impl FnOnce() -> Result<T>,
189    ) -> Result<T> {
190        let Some(fence) = fence else {
191            return admit();
192        };
193        let credentials = self.credentials.read().map_err(|e| {
194            Error::Authentication(format!("Failed to acquire credentials read lock: {}", e))
195        })?;
196        let is_current = match fence {
197            CredentialFence::Generation { generation } => credentials.generation == generation,
198            CredentialFence::AccessToken { generation, value } => {
199                credentials.token_generation == generation
200                    && credentials
201                        .tokens
202                        .as_ref()
203                        .is_some_and(|tokens| tokens.access_token == value)
204            }
205            CredentialFence::ApiKey { generation, value } => {
206                credentials.api_key_generation == generation
207                    && credentials.api_key.as_deref() == Some(value)
208            }
209            CredentialFence::RefreshToken { generation, value } => {
210                credentials.token_generation == generation
211                    && credentials
212                        .tokens
213                        .as_ref()
214                        .and_then(|tokens| tokens.refresh_token.as_deref())
215                        == Some(value)
216            }
217        };
218        if !is_current {
219            return Err(Error::Authentication(
220                "Credential changed before Transport V2 request admission".to_string(),
221            ));
222        }
223        admit()
224    }
225
226    /// Linearize an anonymous-only operation against every credential change.
227    ///
228    /// Native OAuth handoff prepares a request identifier before the hosted
229    /// browser flow begins. The exact same anonymous authority must still be
230    /// current when that identifier is later sealed for redemption.
231    pub(crate) fn admit_if_anonymous_generation_is_current<T>(
232        &self,
233        expected_generation: u64,
234        admit: impl FnOnce() -> Result<T>,
235    ) -> Result<T> {
236        let credentials = self.credentials.read().map_err(|e| {
237            Error::Authentication(format!("Failed to acquire credentials read lock: {}", e))
238        })?;
239        if credentials.generation != expected_generation
240            || credentials.tokens.is_some()
241            || credentials.api_key.is_some()
242        {
243            return Err(Error::Authentication(
244                "Authentication changed during native OAuth handoff".to_string(),
245            ));
246        }
247        admit()
248    }
249
250    pub(crate) fn set_tokens_if_anonymous_generation(
251        &self,
252        expected_generation: u64,
253        access_token: String,
254        refresh_token: String,
255    ) -> Result<bool> {
256        let mut access_token = Zeroizing::new(access_token);
257        let mut refresh_token = Zeroizing::new(refresh_token);
258        let mut credentials = self.credentials.write().map_err(|e| {
259            Error::Authentication(format!("Failed to acquire credentials write lock: {}", e))
260        })?;
261        if credentials.generation != expected_generation
262            || credentials.tokens.is_some()
263            || credentials.api_key.is_some()
264        {
265            return Ok(false);
266        }
267        credentials.tokens = Some(TokenPair {
268            access_token: std::mem::take(&mut *access_token),
269            refresh_token: Some(std::mem::take(&mut *refresh_token)),
270        });
271        credentials.generation = credentials.generation.wrapping_add(1);
272        credentials.token_generation = credentials.token_generation.wrapping_add(1);
273        Ok(true)
274    }
275
276    pub fn get_tokens(&self) -> Result<Option<TokenPair>> {
277        let credentials = self.credentials.read().map_err(|e| {
278            Error::Authentication(format!("Failed to acquire credentials read lock: {}", e))
279        })?;
280
281        Ok(credentials.tokens.clone())
282    }
283
284    pub fn get_access_token(&self) -> Result<Option<String>> {
285        let credentials = self.credentials.read().map_err(|e| {
286            Error::Authentication(format!("Failed to acquire credentials read lock: {}", e))
287        })?;
288
289        Ok(credentials
290            .tokens
291            .as_ref()
292            .map(|tokens| tokens.access_token.clone()))
293    }
294
295    pub fn get_refresh_token(&self) -> Result<Option<String>> {
296        let credentials = self.credentials.read().map_err(|e| {
297            Error::Authentication(format!("Failed to acquire credentials read lock: {}", e))
298        })?;
299
300        Ok(credentials
301            .tokens
302            .as_ref()
303            .and_then(|tokens| tokens.refresh_token.clone()))
304    }
305
306    pub fn update_access_token(&self, access_token: String) -> Result<()> {
307        let mut credentials = self.credentials.write().map_err(|e| {
308            Error::Authentication(format!("Failed to acquire credentials write lock: {}", e))
309        })?;
310
311        if let Some(tokens) = credentials.tokens.as_mut() {
312            tokens.access_token = access_token;
313        } else {
314            return Err(Error::Authentication("No tokens to update".to_string()));
315        }
316
317        credentials.generation = credentials.generation.wrapping_add(1);
318        credentials.token_generation = credentials.token_generation.wrapping_add(1);
319        Ok(())
320    }
321
322    pub fn clear_tokens(&self) -> Result<()> {
323        let mut credentials = self.credentials.write().map_err(|e| {
324            Error::Authentication(format!("Failed to acquire credentials write lock: {}", e))
325        })?;
326
327        credentials.tokens = None;
328        credentials.generation = credentials.generation.wrapping_add(1);
329        credentials.token_generation = credentials.token_generation.wrapping_add(1);
330        Ok(())
331    }
332
333    pub fn clear_all(&self) -> Result<()> {
334        let mut credentials = self.credentials.write().map_err(|e| {
335            Error::Authentication(format!("Failed to acquire credentials write lock: {}", e))
336        })?;
337        credentials.tokens = None;
338        credentials.api_key = None;
339        credentials.generation = credentials.generation.wrapping_add(1);
340        credentials.token_generation = credentials.token_generation.wrapping_add(1);
341        credentials.api_key_generation = credentials.api_key_generation.wrapping_add(1);
342        Ok(())
343    }
344
345    pub(crate) fn clear_all_if_generation(&self, expected_generation: u64) -> Result<bool> {
346        let mut credentials = self.credentials.write().map_err(|e| {
347            Error::Authentication(format!("Failed to acquire credentials write lock: {}", e))
348        })?;
349
350        if credentials.generation != expected_generation {
351            return Ok(false);
352        }
353
354        credentials.tokens = None;
355        credentials.api_key = None;
356        credentials.generation = credentials.generation.wrapping_add(1);
357        credentials.token_generation = credentials.token_generation.wrapping_add(1);
358        credentials.api_key_generation = credentials.api_key_generation.wrapping_add(1);
359        Ok(true)
360    }
361}
362
363impl Default for SessionManager {
364    fn default() -> Self {
365        Self::new()
366    }
367}
368
369#[cfg(test)]
370mod tests {
371    use super::*;
372
373    #[test]
374    fn test_token_management() {
375        let manager = SessionManager::new();
376
377        // Initially empty
378        assert!(manager.get_tokens().unwrap().is_none());
379
380        // Set tokens
381        manager
382            .set_tokens("access".to_string(), Some("refresh".to_string()))
383            .unwrap();
384
385        // Retrieve tokens
386        let tokens = manager.get_tokens().unwrap().unwrap();
387        assert_eq!(tokens.access_token, "access");
388        assert_eq!(tokens.refresh_token, Some("refresh".to_string()));
389
390        // Update access token
391        manager
392            .update_access_token("new_access".to_string())
393            .unwrap();
394        assert_eq!(
395            manager.get_access_token().unwrap(),
396            Some("new_access".to_string())
397        );
398
399        // Clear tokens
400        manager.clear_tokens().unwrap();
401        assert!(manager.get_tokens().unwrap().is_none());
402    }
403
404    #[test]
405    fn conditional_token_clear_never_removes_newer_credentials() {
406        let manager = SessionManager::new();
407        manager
408            .set_tokens("old-access".to_string(), Some("old-refresh".to_string()))
409            .unwrap();
410        let old_generation = manager.get_credential_snapshot().unwrap().token_generation;
411
412        manager
413            .set_tokens("new-access".to_string(), Some("new-refresh".to_string()))
414            .unwrap();
415
416        assert!(!manager.clear_tokens_if_generation(old_generation).unwrap());
417        assert_eq!(
418            manager.get_access_token().unwrap().as_deref(),
419            Some("new-access")
420        );
421        let current_generation = manager.get_credential_snapshot().unwrap().token_generation;
422        assert!(manager
423            .clear_tokens_if_generation(current_generation)
424            .unwrap());
425        assert!(manager.get_tokens().unwrap().is_none());
426    }
427
428    #[test]
429    fn conditional_full_clear_never_removes_newer_credentials() {
430        let manager = SessionManager::new_with_api_key("old-key".to_string());
431        manager
432            .set_tokens("old-access".to_string(), Some("old-refresh".to_string()))
433            .unwrap();
434        let old_generation = manager.get_credential_snapshot().unwrap().generation;
435
436        manager.set_api_key("new-key".to_string()).unwrap();
437        manager
438            .set_tokens("new-access".to_string(), Some("new-refresh".to_string()))
439            .unwrap();
440
441        assert!(!manager.clear_all_if_generation(old_generation).unwrap());
442        assert_eq!(
443            manager.get_access_token().unwrap().as_deref(),
444            Some("new-access")
445        );
446        assert_eq!(manager.get_api_key().unwrap().as_deref(), Some("new-key"));
447    }
448
449    #[test]
450    fn native_handoff_tokens_install_only_into_the_same_anonymous_generation() {
451        let manager = SessionManager::new();
452        let anonymous_generation = manager.get_credential_snapshot().unwrap().generation;
453
454        assert!(manager
455            .set_tokens_if_anonymous_generation(
456                anonymous_generation,
457                "handoff-access".to_string(),
458                "handoff-refresh".to_string(),
459            )
460            .unwrap());
461        let tokens = manager.get_tokens().unwrap().unwrap();
462        assert_eq!(tokens.access_token, "handoff-access");
463        assert_eq!(tokens.refresh_token.as_deref(), Some("handoff-refresh"));
464
465        assert!(!manager
466            .set_tokens_if_anonymous_generation(
467                anonymous_generation,
468                "stale-access".to_string(),
469                "stale-refresh".to_string(),
470            )
471            .unwrap());
472        assert_eq!(
473            manager.get_access_token().unwrap().as_deref(),
474            Some("handoff-access")
475        );
476    }
477
478    #[test]
479    fn native_handoff_tokens_do_not_replace_newer_api_key_state() {
480        let manager = SessionManager::new();
481        let anonymous_generation = manager.get_credential_snapshot().unwrap().generation;
482        manager.set_api_key("new-api-key".to_string()).unwrap();
483
484        assert!(!manager
485            .set_tokens_if_anonymous_generation(
486                anonymous_generation,
487                "stale-access".to_string(),
488                "stale-refresh".to_string(),
489            )
490            .unwrap());
491        assert!(manager.get_tokens().unwrap().is_none());
492        assert_eq!(
493            manager.get_api_key().unwrap().as_deref(),
494            Some("new-api-key")
495        );
496    }
497}