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