maple-sdk 4.0.0

Maple Rust SDK for secure AI APIs, encrypted sessions, and Nitro attestation
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
use crate::error::{Error, Result};
use crate::types::{SessionState, TokenPair};
use std::sync::{Arc, RwLock};
use uuid::Uuid;
use zeroize::Zeroizing;

#[derive(Debug, Clone)]
pub(crate) struct CredentialSnapshot {
    pub(crate) tokens: Option<TokenPair>,
    pub(crate) api_key: Option<String>,
    pub(crate) generation: u64,
    pub(crate) token_generation: u64,
    pub(crate) api_key_generation: u64,
}

/// A caller-selected credential that must still be the exact credential held
/// by this manager when a Transport V2 request is admitted.
///
/// Values are borrowed so this type never creates another long-lived secret
/// copy. The comparison is made while holding the credential read lock, and
/// the admission closure runs under that same lock.
pub(crate) enum CredentialFence<'a> {
    Generation { generation: u64 },
    AccessToken { generation: u64, value: &'a str },
    ApiKey { generation: u64, value: &'a str },
    RefreshToken { generation: u64, value: &'a str },
}

#[derive(Debug, Default)]
struct CredentialState {
    tokens: Option<TokenPair>,
    api_key: Option<String>,
    generation: u64,
    token_generation: u64,
    api_key_generation: u64,
}

pub struct SessionManager {
    session: Arc<RwLock<Option<SessionState>>>,
    credentials: Arc<RwLock<CredentialState>>,
}

impl SessionManager {
    pub fn new() -> Self {
        Self {
            session: Arc::new(RwLock::new(None)),
            credentials: Arc::new(RwLock::new(CredentialState::default())),
        }
    }

    pub fn new_with_api_key(api_key: String) -> Self {
        Self {
            session: Arc::new(RwLock::new(None)),
            credentials: Arc::new(RwLock::new(CredentialState {
                api_key: Some(api_key),
                generation: 1,
                api_key_generation: 1,
                ..CredentialState::default()
            })),
        }
    }

    pub fn set_api_key(&self, api_key: String) -> Result<()> {
        let mut credentials = self.credentials.write().map_err(|e| {
            Error::Authentication(format!("Failed to acquire credentials write lock: {}", e))
        })?;

        credentials.api_key = Some(api_key);
        credentials.generation = credentials.generation.wrapping_add(1);
        credentials.api_key_generation = credentials.api_key_generation.wrapping_add(1);
        Ok(())
    }

    pub fn get_api_key(&self) -> Result<Option<String>> {
        let credentials = self.credentials.read().map_err(|e| {
            Error::Authentication(format!("Failed to acquire credentials read lock: {}", e))
        })?;

        Ok(credentials.api_key.clone())
    }

    pub fn clear_api_key(&self) -> Result<()> {
        let mut credentials = self.credentials.write().map_err(|e| {
            Error::Authentication(format!("Failed to acquire credentials write lock: {}", e))
        })?;

        credentials.api_key = None;
        credentials.generation = credentials.generation.wrapping_add(1);
        credentials.api_key_generation = credentials.api_key_generation.wrapping_add(1);
        Ok(())
    }

    pub fn set_session(&self, session_id: Uuid, session_key: [u8; 32]) -> Result<()> {
        let mut session_guard = self
            .session
            .write()
            .map_err(|e| Error::Session(format!("Failed to acquire session write lock: {}", e)))?;

        *session_guard = Some(SessionState {
            session_id,
            session_key,
        });

        Ok(())
    }

    pub fn get_session(&self) -> Result<Option<SessionState>> {
        let session_guard = self
            .session
            .read()
            .map_err(|e| Error::Session(format!("Failed to acquire session read lock: {}", e)))?;

        Ok(session_guard.clone())
    }

    pub fn clear_session(&self) -> Result<()> {
        let mut session_guard = self
            .session
            .write()
            .map_err(|e| Error::Session(format!("Failed to acquire session write lock: {}", e)))?;

        *session_guard = None;
        Ok(())
    }

    pub fn set_tokens(&self, access_token: String, refresh_token: Option<String>) -> Result<()> {
        let mut credentials = self.credentials.write().map_err(|e| {
            Error::Authentication(format!("Failed to acquire credentials write lock: {}", e))
        })?;

        credentials.tokens = Some(TokenPair {
            access_token,
            refresh_token,
        });
        credentials.generation = credentials.generation.wrapping_add(1);
        credentials.token_generation = credentials.token_generation.wrapping_add(1);

        Ok(())
    }

    pub(crate) fn set_tokens_if_generation(
        &self,
        expected_token_generation: u64,
        access_token: String,
        refresh_token: Option<String>,
    ) -> Result<bool> {
        let mut credentials = self.credentials.write().map_err(|e| {
            Error::Authentication(format!("Failed to acquire credentials write lock: {}", e))
        })?;

        if credentials.token_generation != expected_token_generation {
            return Ok(false);
        }

        credentials.tokens = Some(TokenPair {
            access_token,
            refresh_token,
        });
        credentials.generation = credentials.generation.wrapping_add(1);
        credentials.token_generation = credentials.token_generation.wrapping_add(1);
        Ok(true)
    }

    pub(crate) fn clear_tokens_if_generation(
        &self,
        expected_token_generation: u64,
    ) -> Result<bool> {
        let mut credentials = self.credentials.write().map_err(|e| {
            Error::Authentication(format!("Failed to acquire credentials write lock: {}", e))
        })?;

        if credentials.token_generation != expected_token_generation {
            return Ok(false);
        }

        credentials.tokens = None;
        credentials.generation = credentials.generation.wrapping_add(1);
        credentials.token_generation = credentials.token_generation.wrapping_add(1);
        Ok(true)
    }

    pub(crate) fn get_credential_snapshot(&self) -> Result<CredentialSnapshot> {
        let credentials = self.credentials.read().map_err(|e| {
            Error::Authentication(format!("Failed to acquire credentials read lock: {}", e))
        })?;

        Ok(CredentialSnapshot {
            tokens: credentials.tokens.clone(),
            api_key: credentials.api_key.clone(),
            generation: credentials.generation,
            token_generation: credentials.token_generation,
            api_key_generation: credentials.api_key_generation,
        })
    }

    pub(crate) fn credential_generation(&self) -> Result<u64> {
        self.credentials
            .read()
            .map(|credentials| credentials.generation)
            .map_err(|_| Error::Authentication("Credential state is unavailable".to_string()))
    }

    pub(crate) fn anonymous_generation(&self) -> Result<u64> {
        let credentials = self.credentials.read().map_err(|e| {
            Error::Authentication(format!("Failed to acquire credentials read lock: {}", e))
        })?;
        if credentials.tokens.is_some() || credentials.api_key.is_some() {
            return Err(Error::Authentication(
                "Native OAuth handoff requires an anonymous client".to_string(),
            ));
        }
        Ok(credentials.generation)
    }

    /// Linearize one request admission against synchronous credential changes.
    ///
    /// The closure must be synchronous and must not call back into this
    /// manager. Transport V2 uses it only to allocate a one-time request ID and
    /// seal the request. Once the closure returns successfully, the request is
    /// considered admitted: a later credential change does not cancel work
    /// already sealed for transmission.
    pub(crate) fn admit_if_credential_is_current<T>(
        &self,
        fence: Option<CredentialFence<'_>>,
        admit: impl FnOnce() -> Result<T>,
    ) -> Result<T> {
        let Some(fence) = fence else {
            return admit();
        };
        let credentials = self.credentials.read().map_err(|e| {
            Error::Authentication(format!("Failed to acquire credentials read lock: {}", e))
        })?;
        let is_current = match fence {
            CredentialFence::Generation { generation } => credentials.generation == generation,
            CredentialFence::AccessToken { generation, value } => {
                credentials.token_generation == generation
                    && credentials
                        .tokens
                        .as_ref()
                        .is_some_and(|tokens| tokens.access_token == value)
            }
            CredentialFence::ApiKey { generation, value } => {
                credentials.api_key_generation == generation
                    && credentials.api_key.as_deref() == Some(value)
            }
            CredentialFence::RefreshToken { generation, value } => {
                credentials.token_generation == generation
                    && credentials
                        .tokens
                        .as_ref()
                        .and_then(|tokens| tokens.refresh_token.as_deref())
                        == Some(value)
            }
        };
        if !is_current {
            return Err(Error::Authentication(
                "Credential changed before Transport V2 request admission".to_string(),
            ));
        }
        admit()
    }

    /// Linearize an anonymous-only operation against every credential change.
    ///
    /// Native OAuth handoff prepares a request identifier before the hosted
    /// browser flow begins. The exact same anonymous authority must still be
    /// current when that identifier is later sealed for redemption.
    pub(crate) fn admit_if_anonymous_generation_is_current<T>(
        &self,
        expected_generation: u64,
        admit: impl FnOnce() -> Result<T>,
    ) -> Result<T> {
        let credentials = self.credentials.read().map_err(|e| {
            Error::Authentication(format!("Failed to acquire credentials read lock: {}", e))
        })?;
        if credentials.generation != expected_generation
            || credentials.tokens.is_some()
            || credentials.api_key.is_some()
        {
            return Err(Error::Authentication(
                "Authentication changed during native OAuth handoff".to_string(),
            ));
        }
        admit()
    }

    pub(crate) fn set_tokens_if_anonymous_generation(
        &self,
        expected_generation: u64,
        access_token: String,
        refresh_token: String,
    ) -> Result<bool> {
        let mut access_token = Zeroizing::new(access_token);
        let mut refresh_token = Zeroizing::new(refresh_token);
        let mut credentials = self.credentials.write().map_err(|e| {
            Error::Authentication(format!("Failed to acquire credentials write lock: {}", e))
        })?;
        if credentials.generation != expected_generation
            || credentials.tokens.is_some()
            || credentials.api_key.is_some()
        {
            return Ok(false);
        }
        credentials.tokens = Some(TokenPair {
            access_token: std::mem::take(&mut *access_token),
            refresh_token: Some(std::mem::take(&mut *refresh_token)),
        });
        credentials.generation = credentials.generation.wrapping_add(1);
        credentials.token_generation = credentials.token_generation.wrapping_add(1);
        Ok(true)
    }

    pub fn get_tokens(&self) -> Result<Option<TokenPair>> {
        let credentials = self.credentials.read().map_err(|e| {
            Error::Authentication(format!("Failed to acquire credentials read lock: {}", e))
        })?;

        Ok(credentials.tokens.clone())
    }

    pub fn get_access_token(&self) -> Result<Option<String>> {
        let credentials = self.credentials.read().map_err(|e| {
            Error::Authentication(format!("Failed to acquire credentials read lock: {}", e))
        })?;

        Ok(credentials
            .tokens
            .as_ref()
            .map(|tokens| tokens.access_token.clone()))
    }

    pub fn get_refresh_token(&self) -> Result<Option<String>> {
        let credentials = self.credentials.read().map_err(|e| {
            Error::Authentication(format!("Failed to acquire credentials read lock: {}", e))
        })?;

        Ok(credentials
            .tokens
            .as_ref()
            .and_then(|tokens| tokens.refresh_token.clone()))
    }

    pub fn update_access_token(&self, access_token: String) -> Result<()> {
        let mut credentials = self.credentials.write().map_err(|e| {
            Error::Authentication(format!("Failed to acquire credentials write lock: {}", e))
        })?;

        if let Some(tokens) = credentials.tokens.as_mut() {
            tokens.access_token = access_token;
        } else {
            return Err(Error::Authentication("No tokens to update".to_string()));
        }

        credentials.generation = credentials.generation.wrapping_add(1);
        credentials.token_generation = credentials.token_generation.wrapping_add(1);
        Ok(())
    }

    pub fn clear_tokens(&self) -> Result<()> {
        let mut credentials = self.credentials.write().map_err(|e| {
            Error::Authentication(format!("Failed to acquire credentials write lock: {}", e))
        })?;

        credentials.tokens = None;
        credentials.generation = credentials.generation.wrapping_add(1);
        credentials.token_generation = credentials.token_generation.wrapping_add(1);
        Ok(())
    }

    pub fn clear_all(&self) -> Result<()> {
        self.clear_session()?;
        let mut credentials = self.credentials.write().map_err(|e| {
            Error::Authentication(format!("Failed to acquire credentials write lock: {}", e))
        })?;
        credentials.tokens = None;
        credentials.api_key = None;
        credentials.generation = credentials.generation.wrapping_add(1);
        credentials.token_generation = credentials.token_generation.wrapping_add(1);
        credentials.api_key_generation = credentials.api_key_generation.wrapping_add(1);
        Ok(())
    }

    pub(crate) fn clear_all_if_generation(&self, expected_generation: u64) -> Result<bool> {
        let mut credentials = self.credentials.write().map_err(|e| {
            Error::Authentication(format!("Failed to acquire credentials write lock: {}", e))
        })?;

        if credentials.generation != expected_generation {
            return Ok(false);
        }

        self.clear_session()?;
        credentials.tokens = None;
        credentials.api_key = None;
        credentials.generation = credentials.generation.wrapping_add(1);
        credentials.token_generation = credentials.token_generation.wrapping_add(1);
        credentials.api_key_generation = credentials.api_key_generation.wrapping_add(1);
        Ok(true)
    }
}

impl Default for SessionManager {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_session_management() {
        let manager = SessionManager::new();

        // Initially empty
        assert!(manager.get_session().unwrap().is_none());

        // Set session
        let session_id = Uuid::new_v4();
        let session_key = [0u8; 32];
        manager.set_session(session_id, session_key).unwrap();

        // Retrieve session
        let session = manager.get_session().unwrap().unwrap();
        assert_eq!(session.session_id, session_id);
        assert_eq!(session.session_key, session_key);

        // Clear session
        manager.clear_session().unwrap();
        assert!(manager.get_session().unwrap().is_none());
    }

    #[test]
    fn test_token_management() {
        let manager = SessionManager::new();

        // Initially empty
        assert!(manager.get_tokens().unwrap().is_none());

        // Set tokens
        manager
            .set_tokens("access".to_string(), Some("refresh".to_string()))
            .unwrap();

        // Retrieve tokens
        let tokens = manager.get_tokens().unwrap().unwrap();
        assert_eq!(tokens.access_token, "access");
        assert_eq!(tokens.refresh_token, Some("refresh".to_string()));

        // Update access token
        manager
            .update_access_token("new_access".to_string())
            .unwrap();
        assert_eq!(
            manager.get_access_token().unwrap(),
            Some("new_access".to_string())
        );

        // Clear tokens
        manager.clear_tokens().unwrap();
        assert!(manager.get_tokens().unwrap().is_none());
    }

    #[test]
    fn conditional_token_clear_never_removes_newer_credentials() {
        let manager = SessionManager::new();
        manager
            .set_tokens("old-access".to_string(), Some("old-refresh".to_string()))
            .unwrap();
        let old_generation = manager.get_credential_snapshot().unwrap().token_generation;

        manager
            .set_tokens("new-access".to_string(), Some("new-refresh".to_string()))
            .unwrap();

        assert!(!manager.clear_tokens_if_generation(old_generation).unwrap());
        assert_eq!(
            manager.get_access_token().unwrap().as_deref(),
            Some("new-access")
        );
        let current_generation = manager.get_credential_snapshot().unwrap().token_generation;
        assert!(manager
            .clear_tokens_if_generation(current_generation)
            .unwrap());
        assert!(manager.get_tokens().unwrap().is_none());
    }

    #[test]
    fn conditional_full_clear_never_removes_newer_credentials() {
        let manager = SessionManager::new_with_api_key("old-key".to_string());
        manager
            .set_tokens("old-access".to_string(), Some("old-refresh".to_string()))
            .unwrap();
        let old_generation = manager.get_credential_snapshot().unwrap().generation;

        manager.set_api_key("new-key".to_string()).unwrap();
        manager
            .set_tokens("new-access".to_string(), Some("new-refresh".to_string()))
            .unwrap();

        assert!(!manager.clear_all_if_generation(old_generation).unwrap());
        assert_eq!(
            manager.get_access_token().unwrap().as_deref(),
            Some("new-access")
        );
        assert_eq!(manager.get_api_key().unwrap().as_deref(), Some("new-key"));
    }

    #[test]
    fn native_handoff_tokens_install_only_into_the_same_anonymous_generation() {
        let manager = SessionManager::new();
        let anonymous_generation = manager.get_credential_snapshot().unwrap().generation;

        assert!(manager
            .set_tokens_if_anonymous_generation(
                anonymous_generation,
                "handoff-access".to_string(),
                "handoff-refresh".to_string(),
            )
            .unwrap());
        let tokens = manager.get_tokens().unwrap().unwrap();
        assert_eq!(tokens.access_token, "handoff-access");
        assert_eq!(tokens.refresh_token.as_deref(), Some("handoff-refresh"));

        assert!(!manager
            .set_tokens_if_anonymous_generation(
                anonymous_generation,
                "stale-access".to_string(),
                "stale-refresh".to_string(),
            )
            .unwrap());
        assert_eq!(
            manager.get_access_token().unwrap().as_deref(),
            Some("handoff-access")
        );
    }

    #[test]
    fn native_handoff_tokens_do_not_replace_newer_api_key_state() {
        let manager = SessionManager::new();
        let anonymous_generation = manager.get_credential_snapshot().unwrap().generation;
        manager.set_api_key("new-api-key".to_string()).unwrap();

        assert!(!manager
            .set_tokens_if_anonymous_generation(
                anonymous_generation,
                "stale-access".to_string(),
                "stale-refresh".to_string(),
            )
            .unwrap());
        assert!(manager.get_tokens().unwrap().is_none());
        assert_eq!(
            manager.get_api_key().unwrap().as_deref(),
            Some("new-api-key")
        );
    }
}