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