Skip to main content

larust_passport/
lib.rs

1//! Laravel's `laravel/passport` - a full OAuth2 authorization server (RFC
2//! 6749), narrowed to the three grant types nearly every real integration
3//! actually needs: Authorization Code with PKCE (RFC 7636, required -
4//! "plain" challenge method is rejected outright, not just discouraged -
5//! for every client, not only public ones, since there is no real
6//! downside to requiring it and a real upside: a leaked/misconfigured
7//! client secret stops being single-handedly sufficient to redeem a
8//! stolen authorization code), Client Credentials (machine-to-machine,
9//! confidential clients only), and Refresh Token (with rotation - see
10//! [`token`]'s own doc comment for why the old refresh token is always
11//! invalidated the moment a new one is issued, not left valid alongside
12//! it).
13//!
14//! **Narrower than real Passport in three specific ways, all deliberate:**
15//! - **One redirect URI per client**, not Passport's comma-separated
16//!   list. A real client registering multiple callback URLs (web +
17//!   mobile, say) registers multiple [`client::create_client`] rows
18//!   instead - more rows, not a parsing/validation surface for a
19//!   redirect-URI list this crate would otherwise own.
20//! - **No `php artisan passport:client`-equivalent interactive CLI.**
21//!   [`client::create_client`] is a plain async function - call it from
22//!   your own seeder, console command, or `xr tinker`-equivalent script.
23//!   Every other optional Tier-1 shim crate in this workspace
24//!   (`larust-sanctum`/`larust-socialite`/...) is a pure library with no
25//!   bespoke `xr` subcommand of its own; this one follows the same
26//!   precedent rather than being the first exception.
27//! - **No scopes UI/consent-screen rendering.** [`authorize::
28//!   create_authorization_code`] is called by *your own* `/oauth/authorize`
29//!   route handler once *you've* shown the user an approval screen and
30//!   they've approved - the same "framework provides the mechanism, the
31//!   app owns the actual route and its UI" split `larust-sanctum`/
32//!   `larust-socialite` already establish, not a `laravel/passport`-style
33//!   auto-registered route+Blade view this crate would otherwise have to
34//!   own and let every app style on its own.
35//!
36//! See each submodule's own doc comment for the full design of its own
37//! piece: [`client`] (registration), [`authorize`] (step 1 - issuing a
38//! code), [`token`] (step 2 - exchanging a code/refreshing/client-
39//! credentials), [`extractors`] (request-time bearer-token validation).
40//!
41//! Re-exported through `larust_support::passport` (see `crates/
42//! larust-support/src/lib.rs`) so generated apps depend only on
43//! `larust-support`, never on this crate directly.
44
45pub mod authorize;
46pub mod client;
47pub mod extractors;
48pub mod token;
49
50pub use authorize::{create_authorization_code, AuthorizeRequest, PkceMethod};
51pub use client::{create_client, NewClient};
52pub use extractors::{has_scope, require_scope, OAuthAuth, OAuthClientAuth};
53pub use token::{
54    exchange_token, revoke_access_token, revoke_refresh_token, TokenRequest, TokenResponse,
55};
56
57use larust_core::AppError;
58use larust_orm::Backend;
59use sqlx::AnyPool;
60use std::time::{SystemTime, UNIX_EPOCH};
61
62/// Every table this crate owns, created together - same lazy, `IF NOT
63/// EXISTS`-based self-bootstrap idiom `larust-sanctum`/
64/// `larust-notifications`'s own `ensure_table` establishes (see either's
65/// doc comment for why this is deliberately **not** memoized behind a
66/// `OnceCell`: a process-wide completion flag could point at a since-
67/// discarded test database). Every public entry point in this crate calls
68/// this first, the same way every one of `larust-sanctum`'s own public
69/// functions calls its own `ensure_table` first.
70pub(crate) async fn ensure_tables(pool: &AnyPool) -> Result<(), AppError> {
71    let statements: &[&str] = match larust_orm::backend() {
72        Backend::Sqlite => &[
73            "CREATE TABLE IF NOT EXISTS oauth_clients (\
74                id INTEGER PRIMARY KEY AUTOINCREMENT, \
75                client_id TEXT NOT NULL UNIQUE, \
76                client_secret_hash TEXT, \
77                name TEXT NOT NULL, \
78                redirect_uri TEXT NOT NULL, \
79                is_confidential INTEGER NOT NULL, \
80                created_at INTEGER NOT NULL\
81             )",
82            "CREATE TABLE IF NOT EXISTS oauth_auth_codes (\
83                id INTEGER PRIMARY KEY AUTOINCREMENT, \
84                code_hash TEXT NOT NULL UNIQUE, \
85                client_id TEXT NOT NULL, \
86                user_id INTEGER NOT NULL, \
87                redirect_uri TEXT NOT NULL, \
88                scopes TEXT NOT NULL, \
89                code_challenge TEXT NOT NULL, \
90                expires_at INTEGER NOT NULL\
91             )",
92            "CREATE TABLE IF NOT EXISTS oauth_access_tokens (\
93                id INTEGER PRIMARY KEY AUTOINCREMENT, \
94                token_hash TEXT NOT NULL UNIQUE, \
95                client_id TEXT NOT NULL, \
96                user_id INTEGER, \
97                scopes TEXT NOT NULL, \
98                revoked INTEGER NOT NULL DEFAULT 0, \
99                expires_at INTEGER NOT NULL\
100             )",
101            "CREATE TABLE IF NOT EXISTS oauth_refresh_tokens (\
102                id INTEGER PRIMARY KEY AUTOINCREMENT, \
103                token_hash TEXT NOT NULL UNIQUE, \
104                access_token_id INTEGER NOT NULL, \
105                revoked INTEGER NOT NULL DEFAULT 0, \
106                expires_at INTEGER NOT NULL\
107             )",
108        ],
109        // `VARCHAR`, not MySQL's own `TEXT` - the identical `Any`-driver
110        // `Text`-kind-decoding lesson `larust-cache`/`larust-sanctum`'s own
111        // `ensure_table` doc comments already document in detail (only
112        // `CHAR`/`VARCHAR` decode back as `String` through `sqlx`'s `Any`
113        // driver). `redirect_uri`/`scopes` get a generous cap (a scope
114        // list can legitimately be long) rather than an arbitrary-size one.
115        Backend::MySql => &[
116            "CREATE TABLE IF NOT EXISTS oauth_clients (\
117                id INTEGER PRIMARY KEY AUTO_INCREMENT, \
118                client_id VARCHAR(255) NOT NULL UNIQUE, \
119                client_secret_hash VARCHAR(255), \
120                name VARCHAR(255) NOT NULL, \
121                redirect_uri VARCHAR(2048) NOT NULL, \
122                is_confidential INTEGER NOT NULL, \
123                created_at INTEGER NOT NULL\
124             )",
125            "CREATE TABLE IF NOT EXISTS oauth_auth_codes (\
126                id INTEGER PRIMARY KEY AUTO_INCREMENT, \
127                code_hash VARCHAR(255) NOT NULL UNIQUE, \
128                client_id VARCHAR(255) NOT NULL, \
129                user_id INTEGER NOT NULL, \
130                redirect_uri VARCHAR(2048) NOT NULL, \
131                scopes VARCHAR(2000) NOT NULL, \
132                code_challenge VARCHAR(255) NOT NULL, \
133                expires_at INTEGER NOT NULL\
134             )",
135            "CREATE TABLE IF NOT EXISTS oauth_access_tokens (\
136                id INTEGER PRIMARY KEY AUTO_INCREMENT, \
137                token_hash VARCHAR(255) NOT NULL UNIQUE, \
138                client_id VARCHAR(255) NOT NULL, \
139                user_id INTEGER, \
140                scopes VARCHAR(2000) NOT NULL, \
141                revoked INTEGER NOT NULL DEFAULT 0, \
142                expires_at INTEGER NOT NULL\
143             )",
144            "CREATE TABLE IF NOT EXISTS oauth_refresh_tokens (\
145                id INTEGER PRIMARY KEY AUTO_INCREMENT, \
146                token_hash VARCHAR(255) NOT NULL UNIQUE, \
147                access_token_id INTEGER NOT NULL, \
148                revoked INTEGER NOT NULL DEFAULT 0, \
149                expires_at INTEGER NOT NULL\
150             )",
151        ],
152        // Postgres has native, unbounded `TEXT` - same shape as SQLite's
153        // own arm, just `GENERATED ALWAYS AS IDENTITY` for the primary key
154        // (the identical convention `larust-sanctum`'s own Postgres arm
155        // already uses).
156        Backend::Postgres => &[
157            "CREATE TABLE IF NOT EXISTS oauth_clients (\
158                id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY, \
159                client_id TEXT NOT NULL UNIQUE, \
160                client_secret_hash TEXT, \
161                name TEXT NOT NULL, \
162                redirect_uri TEXT NOT NULL, \
163                is_confidential INTEGER NOT NULL, \
164                created_at INTEGER NOT NULL\
165             )",
166            "CREATE TABLE IF NOT EXISTS oauth_auth_codes (\
167                id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY, \
168                code_hash TEXT NOT NULL UNIQUE, \
169                client_id TEXT NOT NULL, \
170                user_id INTEGER NOT NULL, \
171                redirect_uri TEXT NOT NULL, \
172                scopes TEXT NOT NULL, \
173                code_challenge TEXT NOT NULL, \
174                expires_at INTEGER NOT NULL\
175             )",
176            "CREATE TABLE IF NOT EXISTS oauth_access_tokens (\
177                id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY, \
178                token_hash TEXT NOT NULL UNIQUE, \
179                client_id TEXT NOT NULL, \
180                user_id INTEGER, \
181                scopes TEXT NOT NULL, \
182                revoked INTEGER NOT NULL DEFAULT 0, \
183                expires_at INTEGER NOT NULL\
184             )",
185            "CREATE TABLE IF NOT EXISTS oauth_refresh_tokens (\
186                id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY, \
187                token_hash TEXT NOT NULL UNIQUE, \
188                access_token_id INTEGER NOT NULL, \
189                revoked INTEGER NOT NULL DEFAULT 0, \
190                expires_at INTEGER NOT NULL\
191             )",
192        ],
193    };
194    for statement in statements {
195        sqlx::query(statement)
196            .execute(pool)
197            .await
198            .map_err(|source| AppError::Internal(Box::new(source)))?;
199    }
200    Ok(())
201}
202
203pub(crate) fn now_unix_secs() -> i64 {
204    SystemTime::now()
205        .duration_since(UNIX_EPOCH)
206        .expect("system clock is before the Unix epoch")
207        .as_secs() as i64
208}
209
210/// Hashes a high-entropy random secret (an authorization code, access
211/// token, or refresh token plaintext) for storage - plain SHA-256, not
212/// `argon2` (see [`client::hash_client_secret`]'s own doc comment for why
213/// client secrets specifically get the slower, password-grade hash
214/// instead). The identical trade-off `larust-sanctum`'s own `hash_token`
215/// already makes for its bearer tokens: a brute-force attacker already
216/// needs to search the same astronomically large keyspace a slow hash
217/// would also force them through, so the only thing a slow hash would add
218/// here is making every legitimate request slower for no real benefit -
219/// unlike a human-chosen password, which actually lives in a small enough
220/// keyspace that slow hashing meaningfully raises the cost of a dictionary
221/// attack.
222pub(crate) fn hash_secret(secret: &str) -> String {
223    use sha2::{Digest, Sha256};
224    use std::fmt::Write as _;
225    let digest = Sha256::digest(secret.as_bytes());
226    let mut hex = String::with_capacity(digest.len() * 2);
227    for byte in digest {
228        let _ = write!(hex, "{byte:02x}");
229    }
230    hex
231}
232
233/// Constant-time comparison for two hex-digest strings - avoids leaking a
234/// hash's own matching prefix length through a short-circuiting `==`
235/// timing side channel. Mirrors `larust-sanctum`'s own `hashes_match`
236/// (not imported from it - a cross-dependency just for one ten-line
237/// helper would be a real coupling, not a convenience, the same
238/// reasoning `larust-cache::redis_store`'s own tiny local `env` helper
239/// doc comment already gives for an identical choice).
240pub(crate) fn constant_time_eq(a: &str, b: &str) -> bool {
241    let (a, b) = (a.as_bytes(), b.as_bytes());
242    if a.len() != b.len() {
243        return false;
244    }
245    let mut diff = 0u8;
246    for (x, y) in a.iter().zip(b.iter()) {
247        diff |= x ^ y;
248    }
249    diff == 0
250}
251
252/// Generates a high-entropy random secret, hex-encoded - the identical
253/// shape `larust-sanctum`'s own token generator already establishes (not
254/// imported, for the same "ten-line helper, not worth a cross-dependency"
255/// reasoning [`constant_time_eq`]'s own doc comment gives). 32 bytes (256
256/// bits) throughout this crate - generous for every secret it issues
257/// (authorization codes, access tokens, refresh tokens, client secrets),
258/// never a tunable, since there is no real scenario that needs less.
259pub(crate) fn random_secret() -> String {
260    use rand::Rng;
261    use std::fmt::Write as _;
262    let mut bytes = [0u8; 32];
263    rand::thread_rng().fill(&mut bytes[..]);
264    let mut hex = String::with_capacity(bytes.len() * 2);
265    for byte in bytes {
266        let _ = write!(hex, "{byte:02x}");
267    }
268    hex
269}
270
271/// RFC 6749 ยง5.2's own error vocabulary - every variant renders as `400
272/// Bad Request` with the exact `{"error": "...", "error_description":
273/// "..."}` JSON shape a real OAuth2 client parses programmatically (`axum`
274/// route handlers calling into this crate return `Result<_, OAuthError>`
275/// directly; its own [`axum::response::IntoResponse`] impl handles the
276/// rest). `invalid_client` is RFC-permitted at `400` when client
277/// authentication arrives in the request body (every grant this crate
278/// supports does) rather than the `Authorization` header, which is the
279/// only context this crate ever uses it in - `401` is correct only for
280/// the header-based case, not attempted here.
281///
282/// `Internal` is the one variant that isn't part of RFC 6749's own
283/// vocabulary at all - a genuine unexpected failure (a database error)
284/// gets this framework's own ordinary [`AppError`] handling (the debug
285/// page in development, a generic 500 in production), not a misleading
286/// `invalid_request` dressed up as if the *caller* did something wrong.
287#[derive(Debug)]
288pub enum OAuthError {
289    InvalidRequest(String),
290    InvalidClient(String),
291    InvalidGrant(String),
292    UnauthorizedClient(String),
293    UnsupportedGrantType(String),
294    InvalidScope(String),
295    Internal(AppError),
296}
297
298impl OAuthError {
299    fn code(&self) -> &'static str {
300        match self {
301            OAuthError::InvalidRequest(_) => "invalid_request",
302            OAuthError::InvalidClient(_) => "invalid_client",
303            OAuthError::InvalidGrant(_) => "invalid_grant",
304            OAuthError::UnauthorizedClient(_) => "unauthorized_client",
305            OAuthError::UnsupportedGrantType(_) => "unsupported_grant_type",
306            OAuthError::InvalidScope(_) => "invalid_scope",
307            OAuthError::Internal(_) => "server_error",
308        }
309    }
310
311    fn description(&self) -> &str {
312        match self {
313            OAuthError::InvalidRequest(message)
314            | OAuthError::InvalidClient(message)
315            | OAuthError::InvalidGrant(message)
316            | OAuthError::UnauthorizedClient(message)
317            | OAuthError::UnsupportedGrantType(message)
318            | OAuthError::InvalidScope(message) => message,
319            OAuthError::Internal(_) => "an internal error occurred",
320        }
321    }
322}
323
324impl From<AppError> for OAuthError {
325    fn from(error: AppError) -> Self {
326        OAuthError::Internal(error)
327    }
328}
329
330impl axum::response::IntoResponse for OAuthError {
331    fn into_response(self) -> axum::response::Response {
332        // A real unexpected failure gets this framework's own ordinary
333        // error handling (the debug page in development, logging, a
334        // generic 500 in production) - see this type's own doc comment
335        // for why `Internal` is never rendered as a fake `invalid_*` body.
336        if let OAuthError::Internal(error) = self {
337            return error.into_response();
338        }
339        let status = axum::http::StatusCode::BAD_REQUEST;
340        let body = serde_json::json!({
341            "error": self.code(),
342            "error_description": self.description(),
343        });
344        (status, axum::Json(body)).into_response()
345    }
346}
347
348#[cfg(test)]
349pub(crate) mod test_support {
350    pub async fn connect_test_db() {
351        let dir = tempfile::tempdir().unwrap().keep();
352        let database_url = format!("sqlite://{}/test.sqlite", dir.display());
353        larust_orm::connect(&database_url).await.unwrap();
354    }
355}
356
357#[cfg(test)]
358mod tests {
359    use super::*;
360    use crate::authorize::{create_authorization_code, AuthorizeRequest, PkceMethod};
361    use crate::client::{create_client, find_client};
362    use crate::extractors::test_fixtures::{get_with_auth, router};
363    use crate::token::{exchange_token, revoke_access_token, TokenRequest};
364    use base64::engine::general_purpose::URL_SAFE_NO_PAD;
365    use base64::Engine;
366    use sha2::{Digest, Sha256};
367
368    /// Every DB-touching scenario across this entire crate, in one
369    /// function - `larust_orm::connect()` sets a process-wide pool
370    /// exactly once, and this crate spans multiple files/modules, each
371    /// of which originally had its own `#[tokio::test]` scenario calling
372    /// it independently. Confirmed directly, not assumed: `cargo test`'s
373    /// default parallelism ran all four concurrently in the same test
374    /// binary, and every one but whichever happened to win the race
375    /// failed with `"connect() called more than once"`. `larust-sanctum`/
376    /// `larust-permissions`/`larust-notifications` each avoid this
377    /// naturally, since their own DB-touching scenarios already live in
378    /// one file/one function each - this crate just has that same
379    /// one-function's-worth of scenarios spread across more source files
380    /// for readability, so the single shared test has to live somewhere
381    /// that can see all of them: here.
382    #[tokio::test]
383    async fn passport_crate_behaves_correctly_across_every_scenario() {
384        test_support::connect_test_db().await;
385
386        // --- Client registration ---
387        let confidential = create_client("Server App", "https://app.test/callback", true)
388            .await
389            .unwrap();
390        assert_eq!(confidential.client_id.len(), 64);
391        let secret = confidential
392            .client_secret
393            .clone()
394            .expect("confidential client must get a secret");
395        assert_eq!(secret.len(), 64);
396
397        let public = create_client("Mobile App", "myapp://callback", false)
398            .await
399            .unwrap();
400        assert!(public.client_secret.is_none());
401        assert_ne!(confidential.client_id, public.client_id);
402
403        let pool = larust_orm::pool().unwrap();
404        let found = find_client(pool, &confidential.client_id)
405            .await
406            .unwrap()
407            .expect("just-created confidential client should be found");
408        assert_eq!(found.redirect_uri, "https://app.test/callback");
409        assert!(found.is_confidential);
410        assert!(found.client_secret_hash.is_some());
411
412        let found_public = find_client(pool, &public.client_id)
413            .await
414            .unwrap()
415            .expect("just-created public client should be found");
416        assert!(!found_public.is_confidential);
417        assert!(found_public.client_secret_hash.is_none());
418        assert!(find_client(pool, "does-not-exist").await.unwrap().is_none());
419
420        // --- Authorization code issuance ---
421        let redirect_uri = "https://app.test/callback";
422        fn authorize_request(client_id: &str, redirect_uri: &str) -> AuthorizeRequest {
423            AuthorizeRequest {
424                client_id: client_id.to_string(),
425                redirect_uri: redirect_uri.to_string(),
426                user_id: 1,
427                scopes: vec!["read-posts".to_string()],
428                code_challenge: "a-real-challenge-value".to_string(),
429                code_challenge_method: PkceMethod::S256,
430            }
431        }
432
433        let throwaway_code =
434            create_authorization_code(authorize_request(&confidential.client_id, redirect_uri))
435                .await
436                .unwrap();
437        assert_eq!(throwaway_code.len(), 64);
438
439        let error = create_authorization_code(authorize_request("not-a-real-client", redirect_uri))
440            .await
441            .unwrap_err();
442        assert!(matches!(error, OAuthError::InvalidClient(_)));
443
444        let error = create_authorization_code(authorize_request(
445            &confidential.client_id,
446            "https://evil.test/callback",
447        ))
448        .await
449        .unwrap_err();
450        assert!(matches!(error, OAuthError::InvalidRequest(_)));
451
452        let mut plain_request = authorize_request(&confidential.client_id, redirect_uri);
453        plain_request.code_challenge_method = PkceMethod::Plain;
454        let error = create_authorization_code(plain_request).await.unwrap_err();
455        assert!(matches!(error, OAuthError::InvalidRequest(_)));
456
457        let mut empty_challenge = authorize_request(&confidential.client_id, redirect_uri);
458        empty_challenge.code_challenge = String::new();
459        let error = create_authorization_code(empty_challenge)
460            .await
461            .unwrap_err();
462        assert!(matches!(error, OAuthError::InvalidRequest(_)));
463
464        // --- Token exchange: authorization_code grant + PKCE ---
465        fn pkce_pair() -> (String, String) {
466            let verifier = random_secret();
467            let challenge = URL_SAFE_NO_PAD.encode(Sha256::digest(verifier.as_bytes()));
468            (verifier, challenge)
469        }
470        let (verifier, challenge) = pkce_pair();
471        let code = create_authorization_code(AuthorizeRequest {
472            client_id: confidential.client_id.clone(),
473            redirect_uri: redirect_uri.to_string(),
474            user_id: 42,
475            scopes: vec!["read-posts".to_string(), "write-posts".to_string()],
476            code_challenge: challenge,
477            code_challenge_method: PkceMethod::S256,
478        })
479        .await
480        .unwrap();
481
482        let wrong_verifier_result = exchange_token(TokenRequest::AuthorizationCode {
483            code: code.clone(),
484            redirect_uri: redirect_uri.to_string(),
485            client_id: confidential.client_id.clone(),
486            code_verifier: "not-the-real-verifier".to_string(),
487        })
488        .await;
489        assert!(matches!(
490            wrong_verifier_result,
491            Err(OAuthError::InvalidGrant(_))
492        ));
493
494        let response = exchange_token(TokenRequest::AuthorizationCode {
495            code: code.clone(),
496            redirect_uri: redirect_uri.to_string(),
497            client_id: confidential.client_id.clone(),
498            code_verifier: verifier.clone(),
499        })
500        .await
501        .unwrap();
502        assert_eq!(response.token_type, "Bearer");
503        assert_eq!(response.scope, "read-posts write-posts");
504        assert!(response.refresh_token.is_some());
505
506        let replay_result = exchange_token(TokenRequest::AuthorizationCode {
507            code,
508            redirect_uri: redirect_uri.to_string(),
509            client_id: confidential.client_id.clone(),
510            code_verifier: verifier,
511        })
512        .await;
513        assert!(matches!(replay_result, Err(OAuthError::InvalidGrant(_))));
514
515        // --- Token exchange: client_credentials grant ---
516        let cc_response = exchange_token(TokenRequest::ClientCredentials {
517            client_id: confidential.client_id.clone(),
518            client_secret: secret.clone(),
519            scope: Some("admin".to_string()),
520        })
521        .await
522        .unwrap();
523        assert!(cc_response.refresh_token.is_none());
524        assert_eq!(cc_response.scope, "admin");
525
526        let wrong_secret_result = exchange_token(TokenRequest::ClientCredentials {
527            client_id: confidential.client_id.clone(),
528            client_secret: "not-the-real-secret".to_string(),
529            scope: None,
530        })
531        .await;
532        assert!(matches!(
533            wrong_secret_result,
534            Err(OAuthError::InvalidClient(_))
535        ));
536
537        let public_cc_result = exchange_token(TokenRequest::ClientCredentials {
538            client_id: public.client_id.clone(),
539            client_secret: "anything".to_string(),
540            scope: None,
541        })
542        .await;
543        assert!(matches!(
544            public_cc_result,
545            Err(OAuthError::UnauthorizedClient(_))
546        ));
547
548        // --- Token exchange: refresh_token grant, with rotation ---
549        let refreshed = exchange_token(TokenRequest::RefreshToken {
550            refresh_token: response.refresh_token.clone().unwrap(),
551            client_id: confidential.client_id.clone(),
552        })
553        .await
554        .unwrap();
555        assert_ne!(refreshed.access_token, response.access_token);
556        assert_ne!(refreshed.refresh_token, response.refresh_token);
557        assert_eq!(refreshed.scope, "read-posts write-posts");
558
559        let reuse_old_refresh_result = exchange_token(TokenRequest::RefreshToken {
560            refresh_token: response.refresh_token.clone().unwrap(),
561            client_id: confidential.client_id.clone(),
562        })
563        .await;
564        assert!(matches!(
565            reuse_old_refresh_result,
566            Err(OAuthError::InvalidGrant(_))
567        ));
568
569        // --- Revocation ---
570        revoke_access_token(&refreshed.access_token).await.unwrap();
571        let revoked_refresh_result = exchange_token(TokenRequest::RefreshToken {
572            refresh_token: refreshed.refresh_token.clone().unwrap(),
573            client_id: confidential.client_id.clone(),
574        })
575        .await;
576        assert!(matches!(
577            revoked_refresh_result,
578            Err(OAuthError::InvalidGrant(_))
579        ));
580
581        // --- Request-time extractors ---
582        // A freshly-minted token, independent of `response`/`refreshed`
583        // above (both already revoked, deliberately, by the rotation/
584        // revocation steps this same test just exercised) - the
585        // extractor checks below need a token whose own lifecycle this
586        // section fully controls.
587        let (fresh_verifier, fresh_challenge) = pkce_pair();
588        let fresh_code = create_authorization_code(AuthorizeRequest {
589            client_id: confidential.client_id.clone(),
590            redirect_uri: redirect_uri.to_string(),
591            user_id: 99,
592            scopes: vec!["read-posts".to_string()],
593            code_challenge: fresh_challenge,
594            code_challenge_method: PkceMethod::S256,
595        })
596        .await
597        .unwrap();
598        let extractor_tokens = exchange_token(TokenRequest::AuthorizationCode {
599            code: fresh_code,
600            redirect_uri: redirect_uri.to_string(),
601            client_id: confidential.client_id.clone(),
602            code_verifier: fresh_verifier,
603        })
604        .await
605        .unwrap();
606
607        let api_router = router();
608        let (status, _) = get_with_auth(&api_router, "/me", None).await;
609        assert_eq!(status, axum::http::StatusCode::UNAUTHORIZED);
610        let (status, _) = get_with_auth(&api_router, "/me", Some("not-bearer-shaped")).await;
611        assert_eq!(status, axum::http::StatusCode::UNAUTHORIZED);
612        let (status, _) = get_with_auth(&api_router, "/me", Some("Bearer not-a-real-token")).await;
613        assert_eq!(status, axum::http::StatusCode::UNAUTHORIZED);
614
615        let (status, body) = get_with_auth(
616            &api_router,
617            "/me",
618            Some(&format!("Bearer {}", extractor_tokens.access_token)),
619        )
620        .await;
621        assert_eq!(status, axum::http::StatusCode::OK);
622        assert_eq!(body, "99:read-posts");
623
624        // A client_credentials token has no bound user - rejected by
625        // `OAuthAuth<U>` specifically, accepted fine by `OAuthClientAuth`.
626        let (status, _) = get_with_auth(
627            &api_router,
628            "/me",
629            Some(&format!("Bearer {}", cc_response.access_token)),
630        )
631        .await;
632        assert_eq!(status, axum::http::StatusCode::UNAUTHORIZED);
633
634        let (status, body) = get_with_auth(
635            &api_router,
636            "/client",
637            Some(&format!("Bearer {}", cc_response.access_token)),
638        )
639        .await;
640        assert_eq!(status, axum::http::StatusCode::OK);
641        assert!(body.contains(&confidential.client_id));
642        assert!(body.contains("\"has_admin\":true"));
643
644        // Revoking `extractor_tokens.access_token` specifically must not
645        // affect `cc_response.access_token` - revocation only ever
646        // touches the one token it was asked to revoke.
647        revoke_access_token(&extractor_tokens.access_token)
648            .await
649            .unwrap();
650        let (status, _) = get_with_auth(
651            &api_router,
652            "/me",
653            Some(&format!("Bearer {}", extractor_tokens.access_token)),
654        )
655        .await;
656        assert_eq!(status, axum::http::StatusCode::UNAUTHORIZED);
657        let (status, _) = get_with_auth(
658            &api_router,
659            "/client",
660            Some(&format!("Bearer {}", cc_response.access_token)),
661        )
662        .await;
663        assert_eq!(status, axum::http::StatusCode::OK);
664    }
665
666    #[test]
667    fn hash_secret_is_deterministic_and_sensitive_to_input() {
668        assert_eq!(hash_secret("abc"), hash_secret("abc"));
669        assert_ne!(hash_secret("abc"), hash_secret("abd"));
670    }
671
672    #[test]
673    fn random_secret_produces_64_hex_characters_and_is_never_repeated() {
674        let a = random_secret();
675        let b = random_secret();
676        assert_eq!(a.len(), 64);
677        assert!(a.chars().all(|c| c.is_ascii_hexdigit()));
678        assert_ne!(a, b);
679    }
680
681    #[test]
682    fn constant_time_eq_matches_identical_strings() {
683        assert!(constant_time_eq("abc123", "abc123"));
684    }
685
686    #[test]
687    fn constant_time_eq_rejects_a_single_differing_character() {
688        assert!(!constant_time_eq("abc123", "abc124"));
689    }
690
691    #[test]
692    fn constant_time_eq_rejects_differing_lengths() {
693        assert!(!constant_time_eq("abc", "abcd"));
694    }
695
696    #[test]
697    fn oauth_error_renders_the_exact_rfc_6749_json_shape() {
698        let error = OAuthError::InvalidGrant("the authorization code is invalid".to_string());
699        assert_eq!(error.code(), "invalid_grant");
700        assert_eq!(error.description(), "the authorization code is invalid");
701    }
702}