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
298#[allow(dead_code)]
302#[derive(Clone)]
303struct StoredAuthCode {
304 code: String,
305 client_id: String,
306 redirect_uri: String,
307 me: String,
308 scope: Option<String>,
309 code_challenge: String,
310 code_challenge_method: String,
311 created_at: u64,
312}
313
314impl std::fmt::Debug for StoredAuthCode {
315 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
316 let mut d = f.debug_struct("StoredAuthCode");
317 d.field("code", &crate::utils::redact::redacted(&self.code));
318 d.field("client_id", &self.client_id);
319 d.field("redirect_uri", &self.redirect_uri);
320 d.field("me", &self.me);
321 d.field("scope", &self.scope);
322 d.field("code_challenge", &self.code_challenge);
323 d.field("code_challenge_method", &self.code_challenge_method);
324 d.field("created_at", &self.created_at);
325 d.finish()
326 }
327}
328
329pub struct IndieAuthServer {
331 issuer: String,
332 codes: Arc<RwLock<HashMap<String, StoredAuthCode>>>,
334 #[allow(clippy::type_complexity)] tokens: Arc<RwLock<HashMap<String, (String, Option<String>, u64)>>>,
337 code_lifetime: u64,
339 token_lifetime: u64,
341}
342
343impl IndieAuthServer {
344 pub fn new(issuer: &str, code_lifetime: u64, token_lifetime: u64) -> Self {
346 Self {
347 issuer: issuer.to_string(),
348 codes: Arc::new(RwLock::new(HashMap::new())),
349 tokens: Arc::new(RwLock::new(HashMap::new())),
350 code_lifetime,
351 token_lifetime,
352 }
353 }
354
355 pub fn metadata(&self) -> IndieAuthMetadata {
357 IndieAuthMetadata::new(&self.issuer)
358 }
359
360 fn now_secs() -> u64 {
361 SystemTime::now()
362 .duration_since(UNIX_EPOCH)
363 .unwrap_or(Duration::ZERO)
364 .as_secs()
365 }
366
367 fn generate_token() -> Result<String> {
368 use ring::rand::{SecureRandom, SystemRandom};
369 let rng = SystemRandom::new();
370 let mut buf = [0u8; 32];
371 rng.fill(&mut buf)
372 .map_err(|_| AuthError::crypto("Failed to generate token"))?;
373 Ok(hex::encode(buf))
374 }
375
376 pub async fn issue_code(
378 &self,
379 client_id: &str,
380 redirect_uri: &str,
381 me: &str,
382 scope: Option<&str>,
383 code_challenge: &str,
384 code_challenge_method: &str,
385 ) -> Result<String> {
386 if code_challenge_method != "S256" {
387 return Err(AuthError::validation(
388 "Only S256 code_challenge_method is supported",
389 ));
390 }
391 let code = Self::generate_token()?;
392 let stored = StoredAuthCode {
393 code: code.clone(),
394 client_id: client_id.to_string(),
395 redirect_uri: redirect_uri.to_string(),
396 me: me.to_string(),
397 scope: scope.map(|s| s.to_string()),
398 code_challenge: code_challenge.to_string(),
399 code_challenge_method: code_challenge_method.to_string(),
400 created_at: Self::now_secs(),
401 };
402 self.codes.write().await.insert(code.clone(), stored);
403 Ok(code)
404 }
405
406 pub async fn exchange_code(
410 &self,
411 code: &str,
412 client_id: &str,
413 redirect_uri: &str,
414 code_verifier: &str,
415 ) -> Result<IndieAuthTokenResponse> {
416 let stored = {
417 let mut codes = self.codes.write().await;
418 codes
419 .remove(code)
420 .ok_or_else(|| AuthError::validation("Invalid or expired authorization code"))?
421 };
422
423 if stored.client_id != client_id {
425 return Err(AuthError::validation("client_id mismatch"));
426 }
427 if stored.redirect_uri != redirect_uri {
428 return Err(AuthError::validation("redirect_uri mismatch"));
429 }
430
431 let now = Self::now_secs();
433 if now - stored.created_at > self.code_lifetime {
434 return Err(AuthError::validation("Authorization code has expired"));
435 }
436
437 IndieAuthClient::verify_pkce(code_verifier, &stored.code_challenge)?;
439
440 let (access_token, token_type) = if stored.scope.is_some() {
442 let token = Self::generate_token()?;
443 self.tokens.write().await.insert(
444 token.clone(),
445 (stored.me.clone(), stored.scope.clone(), now),
446 );
447 (Some(token), Some("Bearer".to_string()))
448 } else {
449 (None, None)
450 };
451
452 Ok(IndieAuthTokenResponse {
453 me: stored.me,
454 access_token,
455 token_type,
456 scope: stored.scope,
457 profile: None,
458 })
459 }
460
461 pub async fn introspect_token(&self, token: &str) -> Option<(String, Option<String>, bool)> {
463 let tokens = self.tokens.read().await;
464 tokens.get(token).map(|(me, scope, created_at)| {
465 let now = Self::now_secs();
466 let active = now - created_at <= self.token_lifetime;
467 (me.clone(), scope.clone(), active)
468 })
469 }
470
471 pub async fn revoke_token(&self, token: &str) -> bool {
473 self.tokens.write().await.remove(token).is_some()
474 }
475
476 pub async fn cleanup(&self) {
478 let now = Self::now_secs();
479 self.codes
480 .write()
481 .await
482 .retain(|_, v| now - v.created_at <= self.code_lifetime);
483 self.tokens
484 .write()
485 .await
486 .retain(|_, (_, _, created)| now - *created <= self.token_lifetime);
487 }
488}
489
490fn generate_state() -> Result<String> {
492 use ring::rand::{SecureRandom, SystemRandom};
493 let rng = SystemRandom::new();
494 let mut buf = [0u8; 16];
495 rng.fill(&mut buf)
496 .map_err(|_| AuthError::crypto("Failed to generate state".to_string()))?;
497 Ok(hex::encode(buf))
498}
499
500#[cfg(test)]
501mod tests {
502 use super::*;
503 use base64::Engine;
504
505 fn test_config() -> IndieAuthConfig {
506 IndieAuthConfig {
507 client_id: "https://app.example.com/".to_string(),
508 redirect_uri: "https://app.example.com/callback".to_string(),
509 authorization_endpoint: Some("https://indieauth.example.com/auth".to_string()),
510 token_endpoint: Some("https://indieauth.example.com/token".to_string()),
511 }
512 }
513
514 #[test]
515 fn test_create_client() {
516 let client = IndieAuthClient::new(test_config()).unwrap();
517 assert_eq!(client.config.client_id, "https://app.example.com/");
518 }
519
520 #[test]
521 fn test_empty_client_id_rejected() {
522 let mut cfg = test_config();
523 cfg.client_id = String::new();
524 assert!(IndieAuthClient::new(cfg).is_err());
525 }
526
527 #[test]
528 fn test_generate_code_verifier() {
529 let v1 = IndieAuthClient::generate_code_verifier().unwrap();
530 let v2 = IndieAuthClient::generate_code_verifier().unwrap();
531 assert!(v1.len() >= 43);
532 assert_ne!(v1, v2);
533 }
534
535 #[test]
536 fn test_pkce_challenge_s256() {
537 let verifier = "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk";
538 let challenge = IndieAuthClient::compute_code_challenge(verifier);
539 assert!(!challenge.is_empty());
541 assert!(
543 base64::engine::general_purpose::URL_SAFE_NO_PAD
544 .decode(&challenge)
545 .is_ok()
546 );
547 }
548
549 #[test]
550 fn test_pkce_verify_success() {
551 let verifier = IndieAuthClient::generate_code_verifier().unwrap();
552 let challenge = IndieAuthClient::compute_code_challenge(&verifier);
553 IndieAuthClient::verify_pkce(&verifier, &challenge).unwrap();
554 }
555
556 #[test]
557 fn test_pkce_verify_mismatch() {
558 let verifier = IndieAuthClient::generate_code_verifier().unwrap();
559 assert!(IndieAuthClient::verify_pkce(&verifier, "wrong-challenge").is_err());
560 }
561
562 #[test]
563 fn test_build_authorization_url() {
564 let client = IndieAuthClient::new(test_config()).unwrap();
565 let verifier = IndieAuthClient::generate_code_verifier().unwrap();
566 let (req, url) = client
567 .build_authorization_url(
568 &verifier,
569 Some("profile"),
570 Some("https://user.example.com/"),
571 )
572 .unwrap();
573
574 assert_eq!(req.response_type, "code");
575 assert_eq!(req.code_challenge_method, "S256");
576 assert!(url.starts_with("https://indieauth.example.com/auth?"));
577 assert!(url.contains("response_type=code"));
578 assert!(url.contains("code_challenge="));
579 assert!(url.contains("scope=profile"));
580 }
581
582 #[test]
583 fn test_build_url_no_endpoint() {
584 let mut cfg = test_config();
585 cfg.authorization_endpoint = None;
586 let client = IndieAuthClient::new(cfg).unwrap();
587 let verifier = IndieAuthClient::generate_code_verifier().unwrap();
588 assert!(
589 client
590 .build_authorization_url(&verifier, None, None)
591 .is_err()
592 );
593 }
594
595 #[test]
596 fn test_verify_callback_valid() {
597 let client = IndieAuthClient::new(test_config()).unwrap();
598 let cb = IndieAuthCallback {
599 code: "auth-code-123".to_string(),
600 state: "expected-state".to_string(),
601 me: None,
602 };
603 client.verify_callback(&cb, "expected-state").unwrap();
604 }
605
606 #[test]
607 fn test_verify_callback_state_mismatch() {
608 let client = IndieAuthClient::new(test_config()).unwrap();
609 let cb = IndieAuthCallback {
610 code: "auth-code-123".to_string(),
611 state: "wrong-state".to_string(),
612 me: None,
613 };
614 assert!(client.verify_callback(&cb, "expected-state").is_err());
615 }
616
617 #[test]
618 fn test_verify_callback_empty_code() {
619 let client = IndieAuthClient::new(test_config()).unwrap();
620 let cb = IndieAuthCallback {
621 code: String::new(),
622 state: "ok".to_string(),
623 me: None,
624 };
625 assert!(client.verify_callback(&cb, "ok").is_err());
626 }
627
628 #[test]
629 fn test_validate_profile_url_valid() {
630 IndieAuthClient::validate_profile_url("https://user.example.com/").unwrap();
631 IndieAuthClient::validate_profile_url("http://user.example.com/path").unwrap();
632 }
633
634 #[test]
635 fn test_validate_profile_url_no_scheme() {
636 assert!(IndieAuthClient::validate_profile_url("ftp://example.com").is_err());
637 }
638
639 #[test]
640 fn test_validate_profile_url_fragment() {
641 assert!(IndieAuthClient::validate_profile_url("https://example.com/#frag").is_err());
642 }
643
644 #[test]
645 fn test_validate_profile_url_userinfo() {
646 assert!(IndieAuthClient::validate_profile_url("https://user@example.com/").is_err());
647 }
648
649 #[test]
650 fn test_validate_profile_url_ip_address() {
651 assert!(IndieAuthClient::validate_profile_url("https://127.0.0.1/").is_err());
652 }
653
654 #[test]
657 fn test_server_metadata() {
658 let meta = IndieAuthMetadata::new("https://auth.example.com");
659 assert_eq!(meta.issuer, "https://auth.example.com");
660 assert_eq!(meta.authorization_endpoint, "https://auth.example.com/auth");
661 assert!(
662 meta.code_challenge_methods_supported
663 .contains(&"S256".to_string())
664 );
665 let json = serde_json::to_string(&meta).unwrap();
666 assert!(json.contains("issuer"));
667 }
668
669 #[tokio::test]
672 async fn test_server_issue_and_exchange_code() {
673 let server = IndieAuthServer::new("https://auth.example.com", 600, 3600);
674
675 let verifier = IndieAuthClient::generate_code_verifier().unwrap();
676 let challenge = IndieAuthClient::compute_code_challenge(&verifier);
677
678 let code = server
679 .issue_code(
680 "https://app.example.com/",
681 "https://app.example.com/callback",
682 "https://user.example.com/",
683 Some("profile create"),
684 &challenge,
685 "S256",
686 )
687 .await
688 .unwrap();
689
690 let resp = server
691 .exchange_code(
692 &code,
693 "https://app.example.com/",
694 "https://app.example.com/callback",
695 &verifier,
696 )
697 .await
698 .unwrap();
699
700 assert_eq!(resp.me, "https://user.example.com/");
701 assert!(resp.access_token.is_some());
702 assert_eq!(resp.token_type.as_deref(), Some("Bearer"));
703 assert_eq!(resp.scope.as_deref(), Some("profile create"));
704 }
705
706 #[tokio::test]
707 async fn test_server_code_single_use() {
708 let server = IndieAuthServer::new("https://auth.example.com", 600, 3600);
709 let verifier = IndieAuthClient::generate_code_verifier().unwrap();
710 let challenge = IndieAuthClient::compute_code_challenge(&verifier);
711
712 let code = server
713 .issue_code(
714 "https://app/",
715 "https://app/cb",
716 "https://me/",
717 None,
718 &challenge,
719 "S256",
720 )
721 .await
722 .unwrap();
723
724 server
726 .exchange_code(&code, "https://app/", "https://app/cb", &verifier)
727 .await
728 .unwrap();
729
730 assert!(
732 server
733 .exchange_code(&code, "https://app/", "https://app/cb", &verifier)
734 .await
735 .is_err()
736 );
737 }
738
739 #[tokio::test]
740 async fn test_server_pkce_mismatch() {
741 let server = IndieAuthServer::new("https://auth.example.com", 600, 3600);
742 let verifier = IndieAuthClient::generate_code_verifier().unwrap();
743 let challenge = IndieAuthClient::compute_code_challenge(&verifier);
744
745 let code = server
746 .issue_code(
747 "https://app/",
748 "https://app/cb",
749 "https://me/",
750 None,
751 &challenge,
752 "S256",
753 )
754 .await
755 .unwrap();
756
757 assert!(
758 server
759 .exchange_code(&code, "https://app/", "https://app/cb", "wrong-verifier")
760 .await
761 .is_err()
762 );
763 }
764
765 #[tokio::test]
766 async fn test_server_introspect_and_revoke() {
767 let server = IndieAuthServer::new("https://auth.example.com", 600, 3600);
768 let verifier = IndieAuthClient::generate_code_verifier().unwrap();
769 let challenge = IndieAuthClient::compute_code_challenge(&verifier);
770
771 let code = server
772 .issue_code(
773 "https://app/",
774 "https://app/cb",
775 "https://me/",
776 Some("profile"),
777 &challenge,
778 "S256",
779 )
780 .await
781 .unwrap();
782
783 let resp = server
784 .exchange_code(&code, "https://app/", "https://app/cb", &verifier)
785 .await
786 .unwrap();
787
788 let token = resp.access_token.unwrap();
789 let (me, scope, active) = server.introspect_token(&token).await.unwrap();
790 assert_eq!(me, "https://me/");
791 assert_eq!(scope.as_deref(), Some("profile"));
792 assert!(active);
793
794 assert!(server.revoke_token(&token).await);
795 assert!(server.introspect_token(&token).await.is_none());
796 }
797
798 #[tokio::test]
799 async fn test_server_no_token_without_scope() {
800 let server = IndieAuthServer::new("https://auth.example.com", 600, 3600);
801 let verifier = IndieAuthClient::generate_code_verifier().unwrap();
802 let challenge = IndieAuthClient::compute_code_challenge(&verifier);
803
804 let code = server
805 .issue_code(
806 "https://app/",
807 "https://app/cb",
808 "https://me/",
809 None,
810 &challenge,
811 "S256",
812 )
813 .await
814 .unwrap();
815
816 let resp = server
817 .exchange_code(&code, "https://app/", "https://app/cb", &verifier)
818 .await
819 .unwrap();
820
821 assert!(resp.access_token.is_none());
822 assert_eq!(resp.me, "https://me/");
823 }
824}