Skip to main content

auth_framework/protocols/
indieauth.rs

1//! IndieAuth protocol support (OAuth 2.0–based identity layer for the IndieWeb).
2//!
3//! Provides authorization endpoint discovery, PKCE-secured authorization code
4//! exchange, and profile URL verification per the IndieAuth specification.
5//!
6//! # References
7//!
8//! - [IndieAuth spec](https://indieauth.spec.indieweb.org/)
9
10use 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/// IndieAuth client configuration.
20#[derive(Debug, Clone, Serialize, Deserialize)]
21pub struct IndieAuthConfig {
22    /// Client application URL (used as client_id).
23    pub client_id: String,
24    /// Redirect URI for the authorization callback.
25    pub redirect_uri: String,
26    /// Authorization endpoint URL (discovered from the user's profile).
27    pub authorization_endpoint: Option<String>,
28    /// Token endpoint URL (discovered from the user's profile).
29    pub token_endpoint: Option<String>,
30}
31
32/// An IndieAuth authorization request.
33#[derive(Debug, Clone, Serialize, Deserialize)]
34pub struct IndieAuthRequest {
35    /// Type of response ("code").
36    pub response_type: String,
37    /// Client identifier (URL).
38    pub client_id: String,
39    /// Redirect URI.
40    pub redirect_uri: String,
41    /// State parameter for CSRF protection.
42    pub state: String,
43    /// PKCE code challenge.
44    pub code_challenge: String,
45    /// PKCE code challenge method ("S256").
46    pub code_challenge_method: String,
47    /// Profile URL the user is authenticating as.
48    pub me: Option<String>,
49    /// Requested scopes (e.g., "profile", "create", "update").
50    pub scope: Option<String>,
51}
52
53/// IndieAuth authorization response (callback parameters).
54#[derive(Debug, Clone, Serialize, Deserialize)]
55pub struct IndieAuthCallback {
56    /// Authorization code.
57    pub code: String,
58    /// State parameter (must match original request).
59    pub state: String,
60    /// The URL the user authenticated as (canonical form).
61    pub me: Option<String>,
62}
63
64/// IndieAuth token response.
65#[derive(Debug, Clone, Serialize, Deserialize)]
66pub struct IndieAuthTokenResponse {
67    /// The canonical profile URL.
68    pub me: String,
69    /// Access token (if scopes were requested).
70    pub access_token: Option<String>,
71    /// Token type ("Bearer").
72    pub token_type: Option<String>,
73    /// Granted scope.
74    pub scope: Option<String>,
75    /// Profile information.
76    pub profile: Option<IndieAuthProfile>,
77}
78
79/// Profile information returned by IndieAuth.
80#[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
88/// IndieAuth client for building authorization flows.
89pub struct IndieAuthClient {
90    config: IndieAuthConfig,
91}
92
93impl IndieAuthClient {
94    /// Create a new IndieAuth client.
95    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    /// Generate a PKCE code verifier (43–128 character random string).
106    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    /// Compute the S256 code challenge from a code verifier.
116    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    /// Build an authorization request URL.
122    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    /// Verify a callback matches the original request state.
170    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    /// Verify a PKCE code challenge against the stored verifier.
185    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    /// Validate that a profile URL is canonical per IndieAuth rules.
194    ///
195    /// - Must have scheme `https://` or `http://`
196    /// - Must not contain a fragment
197    /// - Must not contain a username/password
198    /// - Path must end with `/`
199    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        // Extract host portion
216        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        // Must not be an IP address
222        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// ── IndieAuth Server Metadata (RFC draft) ───────────────────────────
232
233/// IndieAuth server metadata (returned at `/.well-known/oauth-authorization-server`
234/// or linked from `<link rel="indieauth-metadata">` on the user's profile).
235#[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    /// Create a metadata document for the given issuer base URL.
253    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// ── IndieAuth Server (authorization + token exchange) ───────────────
274
275/// Access token record: `(me, scope, created_at)`.
276type TokenRecord = (String, Option<String>, u64);
277
278/// Stored authorization code with associated metadata.
279#[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
292/// IndieAuth server handling code issuance and token exchange.
293pub struct IndieAuthServer {
294    issuer: String,
295    /// Authorization code store: code → StoredAuthCode
296    codes: Arc<RwLock<HashMap<String, StoredAuthCode>>>,
297    /// Access token store: token → (me, scope, created_at)
298    tokens: Arc<RwLock<HashMap<String, TokenRecord>>>,
299    /// Authorization code lifetime (seconds).
300    code_lifetime: u64,
301    /// Access token lifetime (seconds).
302    token_lifetime: u64,
303}
304
305impl IndieAuthServer {
306    /// Create a new IndieAuth server with the given issuer URL.
307    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    /// Get server metadata.
318    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    /// Issue an authorization code after user consent.
339    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    /// Exchange an authorization code for a token response.
369    ///
370    /// This is the server-side token exchange endpoint handler.
371    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        // Validate client_id and redirect_uri
386        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        // Check code expiry
394        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        // Verify PKCE
400        IndieAuthClient::verify_pkce(code_verifier, &stored.code_challenge)?;
401
402        // Issue access token if scopes were requested
403        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    /// Introspect an access token.
424    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    /// Revoke an access token.
434    pub async fn revoke_token(&self, token: &str) -> bool {
435        self.tokens.write().await.remove(token).is_some()
436    }
437
438    /// Clean up expired codes and tokens.
439    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
452/// Generate a cryptographically random state parameter.
453fn 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        // SHA-256 of the verifier, base64url-encoded
502        assert!(!challenge.is_empty());
503        // Verify it's valid base64url
504        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    // ── Server metadata ─────────────────────────────────────────
617
618    #[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    // ── Server code exchange ────────────────────────────────────
632
633    #[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        // First exchange succeeds
687        server
688            .exchange_code(&code, "https://app/", "https://app/cb", &verifier)
689            .await
690            .unwrap();
691
692        // Second exchange fails (code consumed)
693        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}