skyauth 0.3.3

High-assurance, formally verified OAuth 2.1 and RFC 9449 DPoP authentication engine for the AT Protocol (Bluesky)
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
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
//! Authenticated OAuth Session representation and token management.
//!
//! Stores user DID subject, access token, single-use refresh token, case-insensitive
//! "DPoP" token type, scopes, session expiration, and bound [`DPoPKey`].
//! Enforces single-use refresh token rotation semantics according to ATProto OAuth 2.1.

use std::time::{Duration, SystemTime};

use serde::{Deserialize, Serialize};

use crate::dpop::{compute_access_token_hash, DPoPKey};
use crate::error::{AtprotoOAuthError, DPoPError, TokenError};

use zeroize::{Zeroize, ZeroizeOnDrop};

/// An authenticated AT Protocol OAuth session.
///
/// Holds the authenticated user's DID, DPoP-bound access token, single-use refresh token,
/// session expiration time, and cryptographic [`DPoPKey`] for signing subsequent XRPC requests.
///
/// # Memory Zeroization & Partial Moves
/// This struct implements [`Drop`] and [`ZeroizeOnDrop`] to securely zeroize sensitive
/// credentials (`access_token` and `refresh_token`) from memory on destruction. As a consequence
/// of Rust's [`Drop`] safety rules (E0509), partial moves of individual fields out of
/// this struct are prohibited; callers should borrow fields or clone the structure.
#[derive(Clone, PartialEq, Eq, Serialize)]
pub struct OAuthSession {
    /// Authenticated subject DID (e.g. `did:plc:...`).
    pub sub: String,
    /// DPoP-bound access token string.
    pub access_token: String,
    /// Single-use refresh token for session renewal.
    pub refresh_token: Option<String>,
    /// Token type (must be case-insensitively `"DPoP"`).
    pub token_type: String,
    /// Granted OAuth scopes (e.g. `"atproto transition:generic"`).
    pub scope: Option<String>,
    /// Absolute expiration timestamp.
    pub expires_at: Option<SystemTime>,
    /// Cryptographic ECDSA P-256 keypair bound to this session's tokens.
    pub dpop_key: DPoPKey,
    /// User's Personal Data Server (PDS) endpoint origin, if known.
    pub pds_endpoint: Option<String>,
    /// Authorization server issuer URL, if known.
    pub auth_server_issuer: Option<String>,
    /// Authorization server token endpoint URL, if known.
    pub token_endpoint: Option<String>,
    /// Timestamp when this session was initially created or exchanged.
    pub created_at: SystemTime,
}

impl<'de> Deserialize<'de> for OAuthSession {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        #[derive(Deserialize)]
        struct RawSession {
            sub: String,
            access_token: String,
            #[serde(default)]
            refresh_token: Option<String>,
            token_type: String,
            #[serde(default)]
            scope: Option<String>,
            #[serde(default)]
            expires_at: Option<SystemTime>,
            dpop_key: DPoPKey,
            #[serde(default)]
            pds_endpoint: Option<String>,
            #[serde(default)]
            auth_server_issuer: Option<String>,
            #[serde(default)]
            token_endpoint: Option<String>,
            created_at: SystemTime,
        }

        let raw = RawSession::deserialize(deserializer)?;

        // Fail closed on the constructor contract (review #1/L1): any persisted
        // round-trip must re-apply the same validation as `OAuthSession::new`.
        // Previously `derive(Deserialize)` bypassed it entirely, so a tampered
        // persistence layer could produce `token_type: "Bearer"` (DPoP binding
        // silently disabled) or empty credentials.
        if !raw.token_type.eq_ignore_ascii_case("DPoP") {
            return Err(serde::de::Error::custom(format!(
                "OAuthSession deserialization rejected: token_type must be 'DPoP', got '{}'",
                raw.token_type
            )));
        }
        if raw.sub.trim().is_empty() {
            return Err(serde::de::Error::custom(
                "OAuthSession deserialization rejected: `sub` must be a non-empty DID",
            ));
        }
        if raw.access_token.trim().is_empty() {
            return Err(serde::de::Error::custom(
                "OAuthSession deserialization rejected: `access_token` must be non-empty",
            ));
        }

        Ok(OAuthSession {
            sub: raw.sub,
            access_token: raw.access_token,
            refresh_token: raw.refresh_token,
            token_type: raw.token_type,
            scope: raw.scope,
            expires_at: raw.expires_at,
            dpop_key: raw.dpop_key,
            pds_endpoint: raw.pds_endpoint,
            auth_server_issuer: raw.auth_server_issuer,
            token_endpoint: raw.token_endpoint,
            created_at: raw.created_at,
        })
    }
}

impl std::fmt::Debug for OAuthSession {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("OAuthSession")
            .field("sub", &self.sub)
            .field("access_token", &"[REDACTED]")
            .field(
                "refresh_token",
                &self.refresh_token.as_ref().map(|_| "[REDACTED]"),
            )
            .field("token_type", &self.token_type)
            .field("scope", &self.scope)
            .field("expires_at", &self.expires_at)
            .field("dpop_key", &self.dpop_key)
            .field("pds_endpoint", &self.pds_endpoint)
            .field("auth_server_issuer", &self.auth_server_issuer)
            .field("token_endpoint", &self.token_endpoint)
            .field("created_at", &self.created_at)
            .finish()
    }
}

impl Zeroize for OAuthSession {
    fn zeroize(&mut self) {
        self.access_token.zeroize();
        if let Some(ref mut rt) = self.refresh_token {
            rt.zeroize();
        }
    }
}

impl Drop for OAuthSession {
    fn drop(&mut self) {
        self.zeroize();
    }
}

impl ZeroizeOnDrop for OAuthSession {}

impl OAuthSession {
    /// Creates a new `OAuthSession` after validating that `token_type` is case-insensitively `"DPoP"`.
    ///
    /// # Errors
    ///
    /// Returns [`TokenError::InvalidTokenType`] if `token_type` is not `"DPoP"`.
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        sub: impl Into<String>,
        access_token: impl Into<String>,
        refresh_token: Option<String>,
        token_type: impl Into<String>,
        scope: Option<String>,
        expires_in_secs: Option<u64>,
        dpop_key: DPoPKey,
        pds_endpoint: Option<String>,
        auth_server_issuer: Option<String>,
        token_endpoint: Option<String>,
    ) -> Result<Self, AtprotoOAuthError> {
        let ttype = token_type.into();
        if !ttype.eq_ignore_ascii_case("DPoP") {
            return Err(TokenError::InvalidTokenType(ttype).into());
        }

        let now = SystemTime::now();
        // Fail closed on overflow: if `now + expires_in` overflows `SystemTime`
        // (possible for absurd `expires_in` values from a compromised/malicious
        // AS), treat the session as already expired rather than never-expiring
        // (`None` previously meant "no local expiry", an attacker-usable
        // fail-open; independent review finding L3).
        let expires_at =
            expires_in_secs.and_then(|secs| now.checked_add(Duration::from_secs(secs)));
        if expires_in_secs.is_some() && expires_at.is_none() {
            return Err(TokenError::Http(
                "expires_in value overflows session expiry timestamp; refusing to issue a never-expiring session (fail-closed)"
                    .to_string(),
            )
            .into());
        }

        Ok(Self {
            sub: sub.into(),
            access_token: access_token.into(),
            refresh_token,
            token_type: ttype,
            scope,
            expires_at,
            dpop_key,
            pds_endpoint,
            auth_server_issuer,
            token_endpoint,
            created_at: now,
        })
    }

    /// Checks whether the access token is expired based on current system time.
    #[must_use]
    pub fn is_expired(&self) -> bool {
        self.is_expired_with_leeway(Duration::ZERO)
    }

    /// Checks whether the access token is expired, with an additional clock leeway window.
    ///
    /// Returns `true` if `expires_at` is present and less than or equal to `now + leeway`.
    #[must_use]
    pub fn is_expired_with_leeway(&self, leeway: Duration) -> bool {
        match self.expires_at {
            Some(exp) => {
                let now = SystemTime::now();
                match now.checked_add(leeway) {
                    Some(now_with_leeway) => exp <= now_with_leeway,
                    None => true,
                }
            }
            None => false,
        }
    }

    /// Atomically rotates the session tokens upon successful refresh token exchange.
    ///
    /// Updates `access_token`, `refresh_token`, and recalculates `expires_at` based on current time.
    /// Outgoing token strings are zeroized in memory before being replaced.
    pub fn rotate_tokens(
        &mut self,
        access_token: impl Into<String>,
        refresh_token: Option<String>,
        expires_in_secs: Option<u64>,
    ) {
        self.rotate_tokens_with_scope(access_token, refresh_token, expires_in_secs, None);
    }

    /// Atomically rotates the session tokens upon successful refresh token exchange,
    /// optionally persisting the authorization server's returned scope.
    ///
    /// Updates `access_token`, `refresh_token`, recalculates `expires_at` based on
    /// current time, and (when `scope` is `Some`) replaces the session scope so
    /// authorization decisions cannot use stale grants (review H4). Outgoing token
    /// strings are zeroized in memory before being replaced.
    pub fn rotate_tokens_with_scope(
        &mut self,
        access_token: impl Into<String>,
        refresh_token: Option<String>,
        expires_in_secs: Option<u64>,
        scope: Option<String>,
    ) {
        // Explicitly zeroize outgoing credentials before overwriting so the previous
        // secrets are scrubbed rather than simply dropped unzeroed.
        self.access_token.zeroize();
        if let Some(ref mut rt) = self.refresh_token {
            rt.zeroize();
        }

        self.access_token = access_token.into();
        self.refresh_token = refresh_token;
        if let Some(new_scope) = scope {
            self.scope = Some(new_scope);
        }
        let now = SystemTime::now();
        // Fail closed on overflow (same rationale as `new`): an overflowing
        // `expires_in` must not yield a never-expiring session.
        let expires_at =
            expires_in_secs.and_then(|secs| now.checked_add(Duration::from_secs(secs)));
        if expires_in_secs.is_some() && expires_at.is_none() {
            // Overflow: mark the session expired at `now` (fail-closed) — the
            // rotation itself has already zeroized and replaced the tokens, so
            // surfacing the anomaly here keeps local expiry semantics safe.
            self.expires_at = Some(now);
            return;
        }
        self.expires_at = expires_at;
    }

    /// Generates a signed RFC 9449 DPoP proof for this session, bound to the current access token.
    ///
    /// Computes the access token hash (`ath`) and includes it in the DPoP proof claims.
    ///
    /// # Errors
    ///
    /// Returns [`DPoPError`] if proof generation fails.
    pub fn create_dpop_proof(
        &self,
        htm: &str,
        htu: &str,
        nonce: Option<&str>,
    ) -> Result<String, DPoPError> {
        let ath = compute_access_token_hash(&self.access_token);
        self.dpop_key
            .create_proof(htm, htu, nonce, Some(ath.as_str()))
    }

    /// Returns the standard HTTP `Authorization` header value (`DPoP <access_token>`).
    #[must_use]
    pub fn dpop_auth_header(&self) -> String {
        format!("DPoP {}", self.access_token)
    }

    /// Returns a reference to the subject DID.
    #[must_use]
    pub fn sub(&self) -> &str {
        &self.sub
    }

    /// Returns a reference to the current access token string.
    #[must_use]
    pub fn access_token(&self) -> &str {
        &self.access_token
    }

    /// Returns a reference to the current refresh token string, if any.
    #[must_use]
    pub fn refresh_token(&self) -> Option<&str> {
        self.refresh_token.as_deref()
    }

    /// Returns a reference to the token type.
    #[must_use]
    pub fn token_type(&self) -> &str {
        &self.token_type
    }

    /// Returns a reference to the granted scope string, if any.
    #[must_use]
    pub fn scope(&self) -> Option<&str> {
        self.scope.as_deref()
    }

    /// Returns the session expiration timestamp, if known.
    #[must_use]
    pub fn expires_at(&self) -> Option<SystemTime> {
        self.expires_at
    }

    /// Returns a reference to the bound [`DPoPKey`].
    #[must_use]
    pub fn dpop_key(&self) -> &DPoPKey {
        &self.dpop_key
    }

    /// Returns a reference to the PDS endpoint origin, if known.
    #[must_use]
    pub fn pds_endpoint(&self) -> Option<&str> {
        self.pds_endpoint.as_deref()
    }

    /// Returns a reference to the authorization server issuer URL, if known.
    #[must_use]
    pub fn auth_server_issuer(&self) -> Option<&str> {
        self.auth_server_issuer.as_deref()
    }

    /// Returns a reference to the token endpoint URL, if known.
    #[must_use]
    pub fn token_endpoint(&self) -> Option<&str> {
        self.token_endpoint.as_deref()
    }

    /// Returns the timestamp when this session was created.
    #[must_use]
    pub fn created_at(&self) -> SystemTime {
        self.created_at
    }
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic, missing_docs)]
mod tests {
    use super::*;
    use crate::dpop::DPoPVerifier;

    #[test]
    fn test_session_creation_valid() {
        let key = DPoPKey::generate();
        let session = OAuthSession::new(
            "did:plc:alice123",
            "at_sample_access_token",
            Some("rt_sample_refresh_token".to_string()),
            "DPoP",
            Some("atproto transition:generic".to_string()),
            Some(3600),
            key.clone(),
            Some("https://pds.example.com".to_string()),
            Some("https://auth.example.com".to_string()),
            Some("https://auth.example.com/oauth/token".to_string()),
        )
        .unwrap();

        assert_eq!(session.sub(), "did:plc:alice123");
        assert_eq!(session.access_token(), "at_sample_access_token");
        assert_eq!(session.refresh_token(), Some("rt_sample_refresh_token"));
        assert_eq!(session.token_type(), "DPoP");
        assert_eq!(session.scope(), Some("atproto transition:generic"));
        assert!(!session.is_expired());
        assert_eq!(session.dpop_auth_header(), "DPoP at_sample_access_token");
    }

    #[test]
    fn test_session_creation_case_insensitive_dpop() {
        let key = DPoPKey::generate();
        let session = OAuthSession::new(
            "did:plc:alice123",
            "at_123",
            None,
            "dpop",
            None,
            None,
            key,
            None,
            None,
            None,
        )
        .unwrap();
        assert_eq!(session.token_type(), "dpop");
    }

    #[test]
    fn test_session_creation_bearer_rejected() {
        let key = DPoPKey::generate();
        let res = OAuthSession::new(
            "did:plc:alice123",
            "at_123",
            None,
            "Bearer",
            None,
            None,
            key,
            None,
            None,
            None,
        );
        assert!(matches!(
            res,
            Err(AtprotoOAuthError::Token(TokenError::InvalidTokenType(_)))
        ));
    }

    #[test]
    fn test_session_token_rotation() {
        let key = DPoPKey::generate();
        let mut session = OAuthSession::new(
            "did:plc:alice123",
            "at_initial",
            Some("rt_initial".to_string()),
            "DPoP",
            None,
            Some(300),
            key,
            None,
            None,
            None,
        )
        .unwrap();

        assert_eq!(session.access_token(), "at_initial");
        assert_eq!(session.refresh_token(), Some("rt_initial"));

        session.rotate_tokens("at_rotated", Some("rt_rotated".to_string()), Some(600));

        assert_eq!(session.access_token(), "at_rotated");
        assert_eq!(session.refresh_token(), Some("rt_rotated"));
        assert!(!session.is_expired());
    }

    #[test]
    fn test_session_dpop_proof_generation_with_ath() {
        let key = DPoPKey::generate();
        let access_token = "at_alice_secret_token";
        let session = OAuthSession::new(
            "did:plc:alice123",
            access_token,
            None,
            "DPoP",
            None,
            Some(3600),
            key.clone(),
            None,
            None,
            None,
        )
        .unwrap();

        let htu = "https://pds.example.com/xrpc/app.bsky.actor.getProfile";
        let proof = session.create_dpop_proof("GET", htu, None).unwrap();

        let expected_ath = compute_access_token_hash(access_token);
        let verifier = DPoPVerifier::new();
        let (claims, jwk) = verifier
            .verify_proof(&proof, "GET", htu, None, Some(&expected_ath), None)
            .unwrap();

        assert_eq!(claims.htm, "GET");
        assert_eq!(claims.ath.as_deref(), Some(expected_ath.as_str()));
        assert_eq!(jwk.thumbprint(), key.jwk_thumbprint());
    }
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic, missing_docs)]
mod deserialization_tests {
    use super::*;

    fn sample_session_json(token_type: &str, sub: &str, access_token: &str) -> String {
        let key = DPoPKey::generate();
        let session = OAuthSession::new(
            sub,
            access_token,
            Some("rt_sample".to_string()),
            token_type,
            Some("atproto".to_string()),
            Some(3600),
            key,
            Some("https://pds.example.com".to_string()),
            Some("https://as.example.com".to_string()),
            Some("https://as.example.com/token".to_string()),
        )
        .unwrap();
        serde_json::to_string(&session).unwrap()
    }

    #[test]
    fn test_roundtrip_preserves_valid_session() {
        let json = sample_session_json("DPoP", "did:plc:alice123", "at_token");
        let deserialized: OAuthSession = serde_json::from_str(&json).unwrap();
        assert_eq!(deserialized.sub, "did:plc:alice123");
        assert_eq!(deserialized.access_token, "at_token");
        assert_eq!(deserialized.token_type, "DPoP");
        assert_eq!(deserialized.refresh_token(), Some("rt_sample"));
    }

    #[test]
    fn test_deserialize_rejects_bearer_token_type() {
        // Review #1: derive(Deserialize) bypassed the constructor contract, so a
        // tampered persistence layer could produce `token_type: "Bearer"` and
        // silently disable the DPoP binding. Deserialization must fail closed.
        // (Built by hand: the constructor itself already rejects "Bearer".)
        let key = DPoPKey::generate();
        let bearer_session = OAuthSession::new(
            "did:plc:alice123",
            "at_token",
            Some("rt_sample".to_string()),
            "DPoP",
            Some("atproto".to_string()),
            Some(3600),
            key,
            None,
            None,
            None,
        )
        .unwrap();
        let mut value = serde_json::to_value(&bearer_session).unwrap();
        value["token_type"] = serde_json::Value::String("Bearer".to_string());
        let json = serde_json::to_string(&value).unwrap();
        assert!(serde_json::from_str::<OAuthSession>(&json).is_err());
    }

    #[test]
    fn test_deserialize_rejects_empty_sub() {
        let json = sample_session_json("DPoP", "", "at_token");
        assert!(serde_json::from_str::<OAuthSession>(&json).is_err());
    }

    #[test]
    fn test_deserialize_rejects_whitespace_only_sub() {
        let json = sample_session_json("DPoP", "   ", "at_token");
        assert!(serde_json::from_str::<OAuthSession>(&json).is_err());
    }

    #[test]
    fn test_deserialize_rejects_empty_access_token() {
        let json = sample_session_json("DPoP", "did:plc:alice123", "");
        assert!(serde_json::from_str::<OAuthSession>(&json).is_err());
    }

    #[test]
    fn test_deserialize_rejects_missing_fields() {
        // A struct missing mandatory fields must not deserialize into a
        // half-valid session.
        let json = r#"{"sub":"did:plc:alice123","access_token":"at"}"#;
        assert!(serde_json::from_str::<OAuthSession>(json).is_err());
    }
}