1pub 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
62pub(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 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 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
210pub(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
233pub(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
252pub(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#[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 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 #[tokio::test]
383 async fn passport_crate_behaves_correctly_across_every_scenario() {
384 test_support::connect_test_db().await;
385
386 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 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 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 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 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 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 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 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 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}