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