1use crate::errors::{AuthError, Result};
11use base64::Engine;
12use serde::{Deserialize, Serialize};
13use sha2::{Digest, Sha256};
14use std::collections::HashMap;
15use std::sync::Arc;
16use std::time::{Duration, SystemTime, UNIX_EPOCH};
17use tokio::sync::RwLock;
18
19#[derive(Debug, Clone, Serialize, Deserialize)]
21pub struct IndieAuthConfig {
22 pub client_id: String,
24 pub redirect_uri: String,
26 pub authorization_endpoint: Option<String>,
28 pub token_endpoint: Option<String>,
30}
31
32#[derive(Debug, Clone, Serialize, Deserialize)]
34pub struct IndieAuthRequest {
35 pub response_type: String,
37 pub client_id: String,
39 pub redirect_uri: String,
41 pub state: String,
43 pub code_challenge: String,
45 pub code_challenge_method: String,
47 pub me: Option<String>,
49 pub scope: Option<String>,
51}
52
53#[derive(Clone, Serialize, Deserialize)]
55pub struct IndieAuthCallback {
56 pub code: String,
58 pub state: String,
60 pub me: Option<String>,
62}
63
64impl std::fmt::Debug for IndieAuthCallback {
65 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
66 let mut d = f.debug_struct("IndieAuthCallback");
67 d.field("code", &crate::utils::redact::redacted(&self.code));
68 d.field("state", &self.state);
69 d.field("me", &self.me);
70 d.finish()
71 }
72}
73
74#[derive(Clone, Serialize, Deserialize)]
76pub struct IndieAuthTokenResponse {
77 pub me: String,
79 pub access_token: Option<String>,
81 pub token_type: Option<String>,
83 pub scope: Option<String>,
85 pub profile: Option<IndieAuthProfile>,
87}
88
89impl std::fmt::Debug for IndieAuthTokenResponse {
90 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
91 let mut d = f.debug_struct("IndieAuthTokenResponse");
92 d.field("me", &self.me);
93 d.field(
94 "access_token",
95 &crate::utils::redact::redacted(&self.access_token),
96 );
97 d.field("token_type", &self.token_type);
98 d.field("scope", &self.scope);
99 d.field("profile", &self.profile);
100 d.finish()
101 }
102}
103
104#[derive(Debug, Clone, Serialize, Deserialize)]
106pub struct IndieAuthProfile {
107 pub name: Option<String>,
108 pub url: Option<String>,
109 pub photo: Option<String>,
110 pub email: Option<String>,
111}
112
113pub struct IndieAuthClient {
115 config: IndieAuthConfig,
116}
117
118impl IndieAuthClient {
119 pub fn new(config: IndieAuthConfig) -> Result<Self> {
121 if config.client_id.is_empty() {
122 return Err(AuthError::validation("client_id cannot be empty"));
123 }
124 if config.redirect_uri.is_empty() {
125 return Err(AuthError::validation("redirect_uri cannot be empty"));
126 }
127 Ok(Self { config })
128 }
129
130 pub fn generate_code_verifier() -> Result<String> {
132 use ring::rand::{SecureRandom, SystemRandom};
133 let rng = SystemRandom::new();
134 let mut buf = [0u8; 32];
135 rng.fill(&mut buf)
136 .map_err(|_| AuthError::crypto("Failed to generate code verifier".to_string()))?;
137 Ok(base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(buf))
138 }
139
140 pub fn compute_code_challenge(verifier: &str) -> String {
142 let hash = Sha256::digest(verifier.as_bytes());
143 base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(hash)
144 }
145
146 pub fn build_authorization_url(
148 &self,
149 code_verifier: &str,
150 scope: Option<&str>,
151 me: Option<&str>,
152 ) -> Result<(IndieAuthRequest, String)> {
153 let auth_endpoint = self
154 .config
155 .authorization_endpoint
156 .as_deref()
157 .ok_or_else(|| {
158 AuthError::config("Authorization endpoint not discovered yet".to_string())
159 })?;
160
161 let state = generate_state()?;
162 let code_challenge = Self::compute_code_challenge(code_verifier);
163
164 let request = IndieAuthRequest {
165 response_type: "code".to_string(),
166 client_id: self.config.client_id.clone(),
167 redirect_uri: self.config.redirect_uri.clone(),
168 state: state.clone(),
169 code_challenge: code_challenge.clone(),
170 code_challenge_method: "S256".to_string(),
171 me: me.map(|s| s.to_string()),
172 scope: scope.map(|s| s.to_string()),
173 };
174
175 let mut url = format!(
176 "{endpoint}?response_type=code&client_id={cid}&redirect_uri={ruri}&state={state}&code_challenge={cc}&code_challenge_method=S256",
177 endpoint = auth_endpoint,
178 cid = urlencoding::encode(&self.config.client_id),
179 ruri = urlencoding::encode(&self.config.redirect_uri),
180 state = urlencoding::encode(&state),
181 cc = urlencoding::encode(&code_challenge),
182 );
183
184 if let Some(s) = scope {
185 url.push_str(&format!("&scope={}", urlencoding::encode(s)));
186 }
187 if let Some(m) = me {
188 url.push_str(&format!("&me={}", urlencoding::encode(m)));
189 }
190
191 Ok((request, url))
192 }
193
194 pub fn verify_callback(
196 &self,
197 callback: &IndieAuthCallback,
198 expected_state: &str,
199 ) -> Result<()> {
200 if callback.state != expected_state {
201 return Err(AuthError::validation("State parameter mismatch"));
202 }
203 if callback.code.is_empty() {
204 return Err(AuthError::validation("Authorization code is empty"));
205 }
206 Ok(())
207 }
208
209 pub fn verify_pkce(code_verifier: &str, code_challenge: &str) -> Result<()> {
211 let expected = Self::compute_code_challenge(code_verifier);
212 if expected != code_challenge {
213 return Err(AuthError::validation("PKCE code challenge mismatch"));
214 }
215 Ok(())
216 }
217
218 pub fn validate_profile_url(url: &str) -> Result<()> {
225 if !(url.starts_with("https://") || url.starts_with("http://")) {
226 return Err(AuthError::validation(
227 "Profile URL must use http or https scheme",
228 ));
229 }
230 if url.contains('#') {
231 return Err(AuthError::validation(
232 "Profile URL must not contain a fragment",
233 ));
234 }
235 if url.contains('@') {
236 return Err(AuthError::validation(
237 "Profile URL must not contain userinfo",
238 ));
239 }
240 let after_scheme = url.split("://").nth(1).unwrap_or("");
242 let host = after_scheme.split('/').next().unwrap_or("");
243 if host.is_empty() {
244 return Err(AuthError::validation("Profile URL has no host"));
245 }
246 if host.parse::<std::net::Ipv4Addr>().is_ok() {
248 return Err(AuthError::validation(
249 "Profile URL must not be an IP address",
250 ));
251 }
252 Ok(())
253 }
254}
255
256#[derive(Debug, Clone, Serialize, Deserialize)]
261pub struct IndieAuthMetadata {
262 pub issuer: String,
263 pub authorization_endpoint: String,
264 pub token_endpoint: String,
265 #[serde(skip_serializing_if = "Option::is_none")]
266 pub introspection_endpoint: Option<String>,
267 #[serde(skip_serializing_if = "Option::is_none")]
268 pub revocation_endpoint: Option<String>,
269 pub code_challenge_methods_supported: Vec<String>,
270 #[serde(skip_serializing_if = "Vec::is_empty", default)]
271 pub scopes_supported: Vec<String>,
272 #[serde(skip_serializing_if = "Vec::is_empty", default)]
273 pub response_types_supported: Vec<String>,
274}
275
276impl IndieAuthMetadata {
277 pub fn new(issuer: &str) -> Self {
279 Self {
280 issuer: issuer.to_string(),
281 authorization_endpoint: format!("{issuer}/auth"),
282 token_endpoint: format!("{issuer}/token"),
283 introspection_endpoint: Some(format!("{issuer}/introspect")),
284 revocation_endpoint: Some(format!("{issuer}/revoke")),
285 code_challenge_methods_supported: vec!["S256".to_string()],
286 scopes_supported: vec![
287 "profile".to_string(),
288 "email".to_string(),
289 "create".to_string(),
290 "update".to_string(),
291 "delete".to_string(),
292 ],
293 response_types_supported: vec!["code".to_string()],
294 }
295 }
296}
297
298type TokenRecord = (String, Option<String>, u64);
302
303#[derive(Debug, Clone)]
305struct StoredAuthCode {
306 client_id: String,
307 redirect_uri: String,
308 me: String,
309 scope: Option<String>,
310 code_challenge: String,
311 created_at: u64,
312}
313
314pub struct IndieAuthServer {
316 issuer: String,
317 codes: Arc<RwLock<HashMap<String, StoredAuthCode>>>,
319 tokens: Arc<RwLock<HashMap<String, TokenRecord>>>,
321 code_lifetime: u64,
323 token_lifetime: u64,
325}
326
327impl IndieAuthServer {
328 pub fn new(issuer: &str, code_lifetime: u64, token_lifetime: u64) -> Self {
330 Self {
331 issuer: issuer.to_string(),
332 codes: Arc::new(RwLock::new(HashMap::new())),
333 tokens: Arc::new(RwLock::new(HashMap::new())),
334 code_lifetime,
335 token_lifetime,
336 }
337 }
338
339 pub fn metadata(&self) -> IndieAuthMetadata {
341 IndieAuthMetadata::new(&self.issuer)
342 }
343
344 fn now_secs() -> u64 {
345 SystemTime::now()
346 .duration_since(UNIX_EPOCH)
347 .unwrap_or(Duration::ZERO)
348 .as_secs()
349 }
350
351 fn generate_token() -> Result<String> {
352 use ring::rand::{SecureRandom, SystemRandom};
353 let rng = SystemRandom::new();
354 let mut buf = [0u8; 32];
355 rng.fill(&mut buf)
356 .map_err(|_| AuthError::crypto("Failed to generate token"))?;
357 Ok(hex::encode(buf))
358 }
359
360 pub async fn issue_code(
362 &self,
363 client_id: &str,
364 redirect_uri: &str,
365 me: &str,
366 scope: Option<&str>,
367 code_challenge: &str,
368 code_challenge_method: &str,
369 ) -> Result<String> {
370 if code_challenge_method != "S256" {
371 return Err(AuthError::validation(
372 "Only S256 code_challenge_method is supported",
373 ));
374 }
375 let code = Self::generate_token()?;
376 let stored = StoredAuthCode {
377 client_id: client_id.to_string(),
378 redirect_uri: redirect_uri.to_string(),
379 me: me.to_string(),
380 scope: scope.map(|s| s.to_string()),
381 code_challenge: code_challenge.to_string(),
382 created_at: Self::now_secs(),
383 };
384 self.codes.write().await.insert(code.clone(), stored);
385 Ok(code)
386 }
387
388 pub async fn exchange_code(
392 &self,
393 code: &str,
394 client_id: &str,
395 redirect_uri: &str,
396 code_verifier: &str,
397 ) -> Result<IndieAuthTokenResponse> {
398 let stored = {
399 let mut codes = self.codes.write().await;
400 codes
401 .remove(code)
402 .ok_or_else(|| AuthError::validation("Invalid or expired authorization code"))?
403 };
404
405 if stored.client_id != client_id {
407 return Err(AuthError::validation("client_id mismatch"));
408 }
409 if stored.redirect_uri != redirect_uri {
410 return Err(AuthError::validation("redirect_uri mismatch"));
411 }
412
413 let now = Self::now_secs();
415 if now - stored.created_at > self.code_lifetime {
416 return Err(AuthError::validation("Authorization code has expired"));
417 }
418
419 IndieAuthClient::verify_pkce(code_verifier, &stored.code_challenge)?;
421
422 let (access_token, token_type) = if stored.scope.is_some() {
424 let token = Self::generate_token()?;
425 self.tokens.write().await.insert(
426 token.clone(),
427 (stored.me.clone(), stored.scope.clone(), now),
428 );
429 (Some(token), Some("Bearer".to_string()))
430 } else {
431 (None, None)
432 };
433
434 Ok(IndieAuthTokenResponse {
435 me: stored.me,
436 access_token,
437 token_type,
438 scope: stored.scope,
439 profile: None,
440 })
441 }
442
443 pub async fn introspect_token(&self, token: &str) -> Option<(String, Option<String>, bool)> {
445 let tokens = self.tokens.read().await;
446 tokens.get(token).map(|(me, scope, created_at)| {
447 let now = Self::now_secs();
448 let active = now - created_at <= self.token_lifetime;
449 (me.clone(), scope.clone(), active)
450 })
451 }
452
453 pub async fn revoke_token(&self, token: &str) -> bool {
455 self.tokens.write().await.remove(token).is_some()
456 }
457
458 pub async fn cleanup(&self) {
460 let now = Self::now_secs();
461 self.codes
462 .write()
463 .await
464 .retain(|_, v| now - v.created_at <= self.code_lifetime);
465 self.tokens
466 .write()
467 .await
468 .retain(|_, (_, _, created)| now - *created <= self.token_lifetime);
469 }
470}
471
472fn generate_state() -> Result<String> {
474 use ring::rand::{SecureRandom, SystemRandom};
475 let rng = SystemRandom::new();
476 let mut buf = [0u8; 16];
477 rng.fill(&mut buf)
478 .map_err(|_| AuthError::crypto("Failed to generate state".to_string()))?;
479 Ok(hex::encode(buf))
480}
481
482#[cfg(test)]
483mod tests {
484 use super::*;
485 use base64::Engine;
486
487 fn test_config() -> IndieAuthConfig {
488 IndieAuthConfig {
489 client_id: "https://app.example.com/".to_string(),
490 redirect_uri: "https://app.example.com/callback".to_string(),
491 authorization_endpoint: Some("https://indieauth.example.com/auth".to_string()),
492 token_endpoint: Some("https://indieauth.example.com/token".to_string()),
493 }
494 }
495
496 #[test]
497 fn test_create_client() {
498 let client = IndieAuthClient::new(test_config()).unwrap();
499 assert_eq!(client.config.client_id, "https://app.example.com/");
500 }
501
502 #[test]
503 fn test_empty_client_id_rejected() {
504 let mut cfg = test_config();
505 cfg.client_id = String::new();
506 assert!(IndieAuthClient::new(cfg).is_err());
507 }
508
509 #[test]
510 fn test_generate_code_verifier() {
511 let v1 = IndieAuthClient::generate_code_verifier().unwrap();
512 let v2 = IndieAuthClient::generate_code_verifier().unwrap();
513 assert!(v1.len() >= 43);
514 assert_ne!(v1, v2);
515 }
516
517 #[test]
518 fn test_pkce_challenge_s256() {
519 let verifier = "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk";
520 let challenge = IndieAuthClient::compute_code_challenge(verifier);
521 assert!(!challenge.is_empty());
523 assert!(
525 base64::engine::general_purpose::URL_SAFE_NO_PAD
526 .decode(&challenge)
527 .is_ok()
528 );
529 }
530
531 #[test]
532 fn test_pkce_verify_success() {
533 let verifier = IndieAuthClient::generate_code_verifier().unwrap();
534 let challenge = IndieAuthClient::compute_code_challenge(&verifier);
535 IndieAuthClient::verify_pkce(&verifier, &challenge).unwrap();
536 }
537
538 #[test]
539 fn test_pkce_verify_mismatch() {
540 let verifier = IndieAuthClient::generate_code_verifier().unwrap();
541 assert!(IndieAuthClient::verify_pkce(&verifier, "wrong-challenge").is_err());
542 }
543
544 #[test]
545 fn test_build_authorization_url() {
546 let client = IndieAuthClient::new(test_config()).unwrap();
547 let verifier = IndieAuthClient::generate_code_verifier().unwrap();
548 let (req, url) = client
549 .build_authorization_url(
550 &verifier,
551 Some("profile"),
552 Some("https://user.example.com/"),
553 )
554 .unwrap();
555
556 assert_eq!(req.response_type, "code");
557 assert_eq!(req.code_challenge_method, "S256");
558 assert!(url.starts_with("https://indieauth.example.com/auth?"));
559 assert!(url.contains("response_type=code"));
560 assert!(url.contains("code_challenge="));
561 assert!(url.contains("scope=profile"));
562 }
563
564 #[test]
565 fn test_build_url_no_endpoint() {
566 let mut cfg = test_config();
567 cfg.authorization_endpoint = None;
568 let client = IndieAuthClient::new(cfg).unwrap();
569 let verifier = IndieAuthClient::generate_code_verifier().unwrap();
570 assert!(
571 client
572 .build_authorization_url(&verifier, None, None)
573 .is_err()
574 );
575 }
576
577 #[test]
578 fn test_verify_callback_valid() {
579 let client = IndieAuthClient::new(test_config()).unwrap();
580 let cb = IndieAuthCallback {
581 code: "auth-code-123".to_string(),
582 state: "expected-state".to_string(),
583 me: None,
584 };
585 client.verify_callback(&cb, "expected-state").unwrap();
586 }
587
588 #[test]
589 fn test_verify_callback_state_mismatch() {
590 let client = IndieAuthClient::new(test_config()).unwrap();
591 let cb = IndieAuthCallback {
592 code: "auth-code-123".to_string(),
593 state: "wrong-state".to_string(),
594 me: None,
595 };
596 assert!(client.verify_callback(&cb, "expected-state").is_err());
597 }
598
599 #[test]
600 fn test_verify_callback_empty_code() {
601 let client = IndieAuthClient::new(test_config()).unwrap();
602 let cb = IndieAuthCallback {
603 code: String::new(),
604 state: "ok".to_string(),
605 me: None,
606 };
607 assert!(client.verify_callback(&cb, "ok").is_err());
608 }
609
610 #[test]
611 fn test_validate_profile_url_valid() {
612 IndieAuthClient::validate_profile_url("https://user.example.com/").unwrap();
613 IndieAuthClient::validate_profile_url("http://user.example.com/path").unwrap();
614 }
615
616 #[test]
617 fn test_validate_profile_url_no_scheme() {
618 assert!(IndieAuthClient::validate_profile_url("ftp://example.com").is_err());
619 }
620
621 #[test]
622 fn test_validate_profile_url_fragment() {
623 assert!(IndieAuthClient::validate_profile_url("https://example.com/#frag").is_err());
624 }
625
626 #[test]
627 fn test_validate_profile_url_userinfo() {
628 assert!(IndieAuthClient::validate_profile_url("https://user@example.com/").is_err());
629 }
630
631 #[test]
632 fn test_validate_profile_url_ip_address() {
633 assert!(IndieAuthClient::validate_profile_url("https://127.0.0.1/").is_err());
634 }
635
636 #[test]
639 fn test_server_metadata() {
640 let meta = IndieAuthMetadata::new("https://auth.example.com");
641 assert_eq!(meta.issuer, "https://auth.example.com");
642 assert_eq!(meta.authorization_endpoint, "https://auth.example.com/auth");
643 assert!(
644 meta.code_challenge_methods_supported
645 .contains(&"S256".to_string())
646 );
647 let json = serde_json::to_string(&meta).unwrap();
648 assert!(json.contains("issuer"));
649 }
650
651 #[tokio::test]
654 async fn test_server_issue_and_exchange_code() {
655 let server = IndieAuthServer::new("https://auth.example.com", 600, 3600);
656
657 let verifier = IndieAuthClient::generate_code_verifier().unwrap();
658 let challenge = IndieAuthClient::compute_code_challenge(&verifier);
659
660 let code = server
661 .issue_code(
662 "https://app.example.com/",
663 "https://app.example.com/callback",
664 "https://user.example.com/",
665 Some("profile create"),
666 &challenge,
667 "S256",
668 )
669 .await
670 .unwrap();
671
672 let resp = server
673 .exchange_code(
674 &code,
675 "https://app.example.com/",
676 "https://app.example.com/callback",
677 &verifier,
678 )
679 .await
680 .unwrap();
681
682 assert_eq!(resp.me, "https://user.example.com/");
683 assert!(resp.access_token.is_some());
684 assert_eq!(resp.token_type.as_deref(), Some("Bearer"));
685 assert_eq!(resp.scope.as_deref(), Some("profile create"));
686 }
687
688 #[tokio::test]
689 async fn test_server_code_single_use() {
690 let server = IndieAuthServer::new("https://auth.example.com", 600, 3600);
691 let verifier = IndieAuthClient::generate_code_verifier().unwrap();
692 let challenge = IndieAuthClient::compute_code_challenge(&verifier);
693
694 let code = server
695 .issue_code(
696 "https://app/",
697 "https://app/cb",
698 "https://me/",
699 None,
700 &challenge,
701 "S256",
702 )
703 .await
704 .unwrap();
705
706 server
708 .exchange_code(&code, "https://app/", "https://app/cb", &verifier)
709 .await
710 .unwrap();
711
712 assert!(
714 server
715 .exchange_code(&code, "https://app/", "https://app/cb", &verifier)
716 .await
717 .is_err()
718 );
719 }
720
721 #[tokio::test]
722 async fn test_server_pkce_mismatch() {
723 let server = IndieAuthServer::new("https://auth.example.com", 600, 3600);
724 let verifier = IndieAuthClient::generate_code_verifier().unwrap();
725 let challenge = IndieAuthClient::compute_code_challenge(&verifier);
726
727 let code = server
728 .issue_code(
729 "https://app/",
730 "https://app/cb",
731 "https://me/",
732 None,
733 &challenge,
734 "S256",
735 )
736 .await
737 .unwrap();
738
739 assert!(
740 server
741 .exchange_code(&code, "https://app/", "https://app/cb", "wrong-verifier")
742 .await
743 .is_err()
744 );
745 }
746
747 #[tokio::test]
748 async fn test_server_introspect_and_revoke() {
749 let server = IndieAuthServer::new("https://auth.example.com", 600, 3600);
750 let verifier = IndieAuthClient::generate_code_verifier().unwrap();
751 let challenge = IndieAuthClient::compute_code_challenge(&verifier);
752
753 let code = server
754 .issue_code(
755 "https://app/",
756 "https://app/cb",
757 "https://me/",
758 Some("profile"),
759 &challenge,
760 "S256",
761 )
762 .await
763 .unwrap();
764
765 let resp = server
766 .exchange_code(&code, "https://app/", "https://app/cb", &verifier)
767 .await
768 .unwrap();
769
770 let token = resp.access_token.unwrap();
771 let (me, scope, active) = server.introspect_token(&token).await.unwrap();
772 assert_eq!(me, "https://me/");
773 assert_eq!(scope.as_deref(), Some("profile"));
774 assert!(active);
775
776 assert!(server.revoke_token(&token).await);
777 assert!(server.introspect_token(&token).await.is_none());
778 }
779
780 #[tokio::test]
781 async fn test_server_no_token_without_scope() {
782 let server = IndieAuthServer::new("https://auth.example.com", 600, 3600);
783 let verifier = IndieAuthClient::generate_code_verifier().unwrap();
784 let challenge = IndieAuthClient::compute_code_challenge(&verifier);
785
786 let code = server
787 .issue_code(
788 "https://app/",
789 "https://app/cb",
790 "https://me/",
791 None,
792 &challenge,
793 "S256",
794 )
795 .await
796 .unwrap();
797
798 let resp = server
799 .exchange_code(&code, "https://app/", "https://app/cb", &verifier)
800 .await
801 .unwrap();
802
803 assert!(resp.access_token.is_none());
804 assert_eq!(resp.me, "https://me/");
805 }
806}