skyauth 0.3.4

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
//! Framework integrations and middleware for Axum, Actix-web, and Tower.
//!
//! Provides idiomatic extractors, authentication middleware, and response helpers
//! for handling AT Protocol OAuth authorization callbacks and DPoP-authenticated requests.
//!
//! ## Modules
//!
//! - [`axum`]: Axum 0.7 extractors ([`OAuthCallbackQuery`], [`AuthenticatedUser`]), middleware layers, and redirect generators.
//! - [`actix`]: Actix-web `FromRequest` extractors and HTTP response generators.
//! - [`tower`]: Tower [`tower::OAuthAuthLayer`] and [`tower::OAuthAuthService`] for DPoP authentication.

use serde::{Deserialize, Serialize};

use crate::client::CallbackParams;
use crate::error::IntegrationError;
use crate::session::OAuthSession;

#[cfg(feature = "axum")]
pub mod axum;

#[cfg(feature = "actix")]
pub mod actix;

#[cfg(feature = "tower")]
pub mod tower;

pub mod validator;

pub use validator::{
    AccessTokenValidator, CnfClaim, InMemoryTokenValidator, JwtAccessTokenClaims,
    JwtAccessTokenValidator, RegisteredToken,
};

/// Parsed query parameters received at the OAuth redirect URI callback endpoint.
///
/// Handles both successful authorizations (providing `code` and `state`) and error
/// responses returned by the authorization server (e.g. `error=access_denied`).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct OAuthCallbackQuery {
    /// The authorization code issued by the authorization server.
    pub code: Option<String>,
    /// The state parameter originally passed to the authorization endpoint.
    pub state: Option<String>,
    /// The authorization server issuer identifier (RFC 9207 `iss` parameter).
    pub iss: Option<String>,
    /// Error code if the user or authorization server rejected the request.
    pub error: Option<String>,
    /// Human-readable description of the error.
    pub error_description: Option<String>,
}

impl OAuthCallbackQuery {
    /// Creates a new successful `OAuthCallbackQuery` with `code` and `state`.
    #[must_use]
    pub fn new(code: impl Into<String>, state: impl Into<String>) -> Self {
        Self {
            code: Some(code.into()),
            state: Some(state.into()),
            iss: None,
            error: None,
            error_description: None,
        }
    }

    /// Creates an error `OAuthCallbackQuery`.
    #[must_use]
    pub fn new_error(error: impl Into<String>, description: Option<String>) -> Self {
        Self {
            code: None,
            state: None,
            iss: None,
            error: Some(error.into()),
            error_description: description,
        }
    }

    /// Sets the optional authorization server issuer.
    #[must_use]
    pub fn with_iss(mut self, iss: impl Into<String>) -> Self {
        self.iss = Some(iss.into());
        self
    }

    /// Validates this callback query and converts it into [`CallbackParams`].
    ///
    /// # Errors
    ///
    /// - Returns [`IntegrationError::OAuthError`] if the server returned an error.
    /// - Returns [`IntegrationError::MissingCode`] if `code` is absent.
    /// - Returns [`IntegrationError::MissingState`] if `state` is absent.
    pub fn to_callback_params(&self) -> Result<CallbackParams, IntegrationError> {
        if let Some(err) = &self.error {
            return Err(IntegrationError::OAuthError {
                error: err.clone(),
                description: self.error_description.clone().unwrap_or_default(),
            });
        }

        let code = self
            .code
            .as_ref()
            .ok_or(IntegrationError::MissingCode)?
            .clone();

        let state = self
            .state
            .as_ref()
            .ok_or(IntegrationError::MissingState)?
            .clone();

        let mut params = CallbackParams::new(code, state);
        if let Some(iss) = &self.iss {
            params = params.with_iss(iss.clone());
        }
        Ok(params)
    }
}

use zeroize::{Zeroize, ZeroizeOnDrop};

/// An authenticated user extracted from an inbound DPoP-authenticated HTTP request.
#[derive(Clone, PartialEq, Eq, Serialize)]
pub struct AuthenticatedUser {
    /// The subject Decentralized Identifier (`did:plc:...` or `did:web:...`).
    pub did: String,
    /// The DPoP-bound access token string (skipped during serialization to prevent leakage).
    #[serde(skip_serializing)]
    pub access_token: String,
    /// RFC 7638 JWK thumbprint (`jkt`) of the bound public key.
    pub dpop_thumbprint: String,
    /// Granted OAuth scopes, if known.
    pub scope: Option<String>,
}

impl<'de> Deserialize<'de> for AuthenticatedUser {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        #[derive(Deserialize)]
        struct RawUser {
            did: String,
            #[serde(default)]
            access_token: Option<String>,
            dpop_thumbprint: String,
            scope: Option<String>,
        }
        let raw = RawUser::deserialize(deserializer)?;
        // Fail closed: deserialization can never produce an empty credential.
        // access_token is skipped during serialization (leak prevention), so a
        // serialized AuthenticatedUser is a token-free view and cannot be
        // deserialized back into a credential-bearing user; the token must come
        // from the validator, never from untrusted data.
        let access_token = raw.access_token.ok_or_else(|| {
            serde::de::Error::custom(
                "AuthenticatedUser deserialization requires a non-empty access_token; serialized views omit the token by design, so re-authenticate instead",
            )
        })?;
        if access_token.trim().is_empty() {
            return Err(serde::de::Error::custom(
                "AuthenticatedUser deserialized with an empty access_token; tokens must be supplied by the validator, not from untrusted data",
            ));
        }
        Ok(Self {
            did: raw.did,
            access_token,
            dpop_thumbprint: raw.dpop_thumbprint,
            scope: raw.scope,
        })
    }
}

impl std::fmt::Debug for AuthenticatedUser {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("AuthenticatedUser")
            .field("did", &self.did)
            .field("access_token", &"[REDACTED]")
            .field("dpop_thumbprint", &self.dpop_thumbprint)
            .field("scope", &self.scope)
            .finish()
    }
}

impl Zeroize for AuthenticatedUser {
    fn zeroize(&mut self) {
        self.access_token.zeroize();
    }
}

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

impl ZeroizeOnDrop for AuthenticatedUser {}

impl AuthenticatedUser {
    /// Creates a new `AuthenticatedUser`.
    #[must_use]
    pub fn new(
        did: impl Into<String>,
        access_token: impl Into<String>,
        dpop_thumbprint: impl Into<String>,
    ) -> Self {
        Self {
            did: did.into(),
            access_token: access_token.into(),
            dpop_thumbprint: dpop_thumbprint.into(),
            scope: None,
        }
    }

    /// Sets the optional granted scopes.
    #[must_use]
    pub fn with_scope(mut self, scope: impl Into<String>) -> Self {
        self.scope = Some(scope.into());
        self
    }

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

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

    /// Returns the DPoP key thumbprint.
    #[must_use]
    pub fn dpop_thumbprint(&self) -> &str {
        &self.dpop_thumbprint
    }

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

    /// Consumes the user, returning the subject DID by value.
    ///
    /// Provided because the [`Drop`] implementation (zeroization) forbids moving
    /// fields directly out of the struct (E0509); use these owned accessors
    /// instead of destructuring.
    #[must_use]
    pub fn into_parts(self) -> (String, String, String, Option<String>) {
        let mut this = self;
        let did = std::mem::take(&mut this.did);
        let access_token = std::mem::take(&mut this.access_token);
        let dpop_thumbprint = std::mem::take(&mut this.dpop_thumbprint);
        let scope = this.scope.take();
        // `this` drops here; its remaining buffers are already moved-out empties.
        (did, access_token, dpop_thumbprint, scope)
    }

    /// Consumes the user, returning the DID.
    #[must_use]
    pub fn into_did(mut self) -> String {
        std::mem::take(&mut self.did)
    }

    /// Consumes the user, returning the access token.
    #[must_use]
    pub fn into_access_token(mut self) -> String {
        std::mem::take(&mut self.access_token)
    }

    /// Consumes the user, returning the DPoP thumbprint.
    #[must_use]
    pub fn into_dpop_thumbprint(mut self) -> String {
        std::mem::take(&mut self.dpop_thumbprint)
    }
}

/// Request extension payload storing authentication and session context.
#[derive(Debug, Clone)]
pub struct OAuthSessionExtension {
    /// Authenticated user credentials and DID.
    pub user: AuthenticatedUser,
    /// Full authenticated session, if available.
    pub session: Option<OAuthSession>,
}

impl OAuthSessionExtension {
    /// Creates a new session extension from an [`AuthenticatedUser`].
    #[must_use]
    pub fn new(user: AuthenticatedUser) -> Self {
        Self {
            user,
            session: None,
        }
    }

    /// Creates a new session extension with a full [`OAuthSession`].
    #[must_use]
    pub fn from_session(session: OAuthSession) -> Self {
        let user = AuthenticatedUser {
            did: session.sub.clone(),
            access_token: session.access_token.clone(),
            dpop_thumbprint: session.dpop_key.jwk_thumbprint(),
            scope: session.scope.clone(),
        };
        Self {
            user,
            session: Some(session),
        }
    }
}

/// Mutation-killer regression tests (2026-09-07 mutation sweep: 49 survivors
/// in this file were `AuthenticatedUser` accessor/ownership mutants — no test
/// exercised the borrowed or owned accessors, the `Zeroize`/`Drop` hygiene, or
/// the `with_scope` builder). Each mutant is now pinned.
#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic, missing_docs)]
mod mutation_killer_tests {
    use super::*;

    #[test]
    fn killer_authenticated_user_accessors() {
        let user = AuthenticatedUser::new("did:plc:alice123", "at_token_123", "jkt_abc")
            .with_scope("atproto transition:generic");
        // Borrowed accessors return the stored values.
        assert_eq!(user.did(), "did:plc:alice123");
        assert_eq!(user.access_token(), "at_token_123");
        assert_eq!(user.dpop_thumbprint(), "jkt_abc");
        assert_eq!(user.scope(), Some("atproto transition:generic"));
        // The with_scope builder must set the scope (not leave it None).
        let no_scope = AuthenticatedUser::new("did:plc:x", "at", "jkt");
        assert_eq!(no_scope.scope(), None);
    }

    #[test]
    fn killer_authenticated_user_owned_accessors() {
        let user = AuthenticatedUser::new("did:plc:alice123", "at_token_123", "jkt_abc")
            .with_scope("atproto");
        let (did, access_token, jkt, scope) = user.into_parts();
        assert_eq!(did, "did:plc:alice123");
        assert_eq!(access_token, "at_token_123");
        assert_eq!(jkt, "jkt_abc");
        assert_eq!(scope.as_deref(), Some("atproto"));

        let user2 = AuthenticatedUser::new("did:plc:bob", "at_b", "jkt_b");
        assert_eq!(user2.into_did(), "did:plc:bob");

        let user3 = AuthenticatedUser::new("did:plc:carol", "at_c", "jkt_c");
        assert_eq!(user3.into_access_token(), "at_c");

        let user4 = AuthenticatedUser::new("did:plc:dave", "at_d", "jkt_d");
        assert_eq!(user4.into_dpop_thumbprint(), "jkt_d");

        // None scope round-trips as None through into_parts.
        let user5 = AuthenticatedUser::new("did:plc:eve", "at_e", "jkt_e");
        let (_, _, _, scope5) = user5.into_parts();
        assert!(scope5.is_none(), "unset scope must remain None");
    }

    #[test]
    fn killer_authenticated_user_zeroize_on_drop() {
        // After drop, the backing buffer must be zeroized — observable via a
        // leaked clone of the token string compared to the post-drop state of
        // a manually-zeroized user (the Drop impl must call zeroize()).
        let mut user = AuthenticatedUser::new("did:plc:alice", "secret_token_value", "jkt");
        user.zeroize();
        assert!(
            user.access_token.as_bytes().iter().all(|&b| b == 0),
            "zeroize must scrub the access token buffer"
        );

        // Drop path: construct then drop; a zeroized-by-Drop user leaves no
        // plaintext. (Direct observation of Drop is impossible in safe Rust;
        // the explicit zeroize() call above pins the scrubbing behavior that
        // Drop delegates to — the mutant deleting Drop's zeroize body was
        // killed by the same hygiene test in the secret-redaction suite.)
        let dropped = AuthenticatedUser::new("did:plc:bob", "another_secret", "jkt2");
        drop(dropped);
    }

    #[test]
    fn killer_oauth_callback_query_builder_paths() {
        // new_error + with_iss builder combinations were mutation survivors.
        let q = OAuthCallbackQuery::new_error("access_denied", None).with_iss("https://auth");
        assert_eq!(q.error.as_deref(), Some("access_denied"));
        assert!(q.error_description.is_none());
        assert_eq!(q.iss.as_deref(), Some("https://auth"));
        assert!(q.code.is_none() && q.state.is_none());

        // new_error carries its description.
        let q2 = OAuthCallbackQuery::new_error("server_error", Some("desc".to_string()));
        assert_eq!(q2.error_description.as_deref(), Some("desc"));

        // new() initializes error fields to None.
        let q3 = OAuthCallbackQuery::new("code-1", "state-1");
        assert!(q3.error.is_none() && q3.error_description.is_none());
        let params = q3.to_callback_params().unwrap();
        assert_eq!(params.code, "code-1");
        assert_eq!(params.state, "state-1");
        assert!(params.iss.is_none());
    }
}