sylphx 0.3.6

The Sylphx SDK: one API, one key, every Sylphx service. Generated from the Sylphx schema registry.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
// @generated by sylphx-gen. Do not edit.
//! OAuth for a remote MCP server (or any API) that uses a Sylphx Auth
//! instance as its authorization server: the protected-resource side of the
//! MCP authorization spec (2025-11-25), RFC 9728 (protected resource
//! metadata), RFC 6750 (bearer challenges), RFC 7662 (token introspection)
//! and RFC 8707 (audience-bound tokens).
//!
//! Sylphx Auth access tokens are opaque (`identity_oauth_at_…`), so a token is
//! validated by introspection with the resource server's own confidential
//! OAuth client, never by parsing it. A token is accepted only when it is
//! active, issued by the configured authorization server, minted for this
//! resource (`aud`), a `Bearer` token (DPoP-bound tokens are refused: this
//! helper does not verify DPoP proofs), unexpired, and has a subject.
//! Positive answers are cached briefly under the SHA-256 of the token; an
//! unreachable authorization server fails closed (503).
//!
//! The module is framework-agnostic: it returns a [`Reply`] (status, headers,
//! body) that any server maps to its own response type.
//!
//! ```text
//! // axum: serve the metadata document and guard the MCP endpoint.
//! let rs = Arc::new(ProtectedResource::from_env()?);
//! let app = Router::new()
//!     .route(&rs.metadata_path(), get({
//!         let rs = rs.clone();
//!         move || async move { to_response(rs.metadata_response()) }
//!     }))
//!     .route("/mcp", post({
//!         let rs = rs.clone();
//!         move |headers: HeaderMap, body: Bytes| async move {
//!             let auth = headers.get("authorization").and_then(|v| v.to_str().ok());
//!             match rs.authorize(auth, &["mcp:tools"]).await {
//!                 Ok(grant) => handle_mcp(grant, body).await,
//!                 Err(challenge) => to_response(challenge.reply()),
//!             }
//!         }
//!     }));
//! // `to_response` copies `Reply::status`, `headers` and `body` into an `axum::response::Response`.
//! ```
//!
//! [`grant_from_introspection`] is the pure core (no network, caller-supplied
//! time) for tests and for callers who introspect themselves.
//!
//! Configuration (`ProtectedResource::from_env`): `SYLPHX_RESOURCE_URI`,
//! `SYLPHX_AUTH_ISSUER`, `SYLPHX_RESOURCE_CLIENT_ID`,
//! `SYLPHX_RESOURCE_CLIENT_SECRET`, optional `SYLPHX_RESOURCE_SCOPES`
//! (space-separated) and `SYLPHX_INTROSPECTION_URL`.

use std::collections::HashMap;
use std::sync::Mutex;
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};

use base64::engine::general_purpose::STANDARD;
use base64::Engine as _;
use serde_json::{json, Value};
use sha2::{Digest, Sha256};

const DEFAULT_INTROSPECTION: &str = "https://api.sylphx.com/v1/oauth/introspect";
const MAX_TOKEN_BYTES: usize = 4096;
const MAX_CACHE_TTL: Duration = Duration::from_secs(60);
const MAX_CACHE_ENTRIES: usize = 10_000;

/// A plain HTTP answer: status, lower-case header names, and a body.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Reply {
    /// The HTTP status code.
    pub status: u16,
    /// Response headers, in order.
    pub headers: Vec<(String, String)>,
    /// The response body (JSON).
    pub body: String,
}

/// The verified facts of an accepted access token.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Grant {
    /// The end user (`sub`).
    pub subject: String,
    /// The OAuth client the token was issued to.
    pub client_id: String,
    /// The granted scopes.
    pub scopes: Vec<String>,
    /// Expiry, unix seconds.
    pub expires_at: i64,
    /// Issue time, unix seconds (0 when unknown).
    pub issued_at: i64,
}

impl Grant {
    /// Whether the grant includes `scope`.
    pub fn has(&self, scope: &str) -> bool {
        self.scopes.iter().any(|s| s == scope)
    }
}

/// Which check refused an introspection answer.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Rejection {
    /// `active` is not true.
    Inactive,
    /// `aud` does not name this resource.
    Audience,
    /// `iss` is not the configured authorization server.
    Issuer,
    /// `token_type` is not `Bearer` (for example a DPoP-bound token).
    TokenType,
    /// `exp` is missing or not in the future.
    Expired,
    /// `sub` is empty.
    Subject,
    /// The answer is not the JSON object it must be.
    Malformed,
}

impl std::fmt::Display for Rejection {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(match self {
            Rejection::Inactive => "the token is not active",
            Rejection::Audience => "the token is not for this resource",
            Rejection::Issuer => "the token was not issued by the expected authorization server",
            Rejection::TokenType => "the token type is not accepted",
            Rejection::Expired => "the token is expired",
            Rejection::Subject => "the token has no subject",
            Rejection::Malformed => "the introspection answer is malformed",
        })
    }
}

/// Validate one RFC 7662 answer for `resource` and `issuer` at unix time `now`.
pub fn grant_from_introspection(
    body: &Value,
    resource: &str,
    issuer: &str,
    now: i64,
) -> Result<Grant, Rejection> {
    let obj = body.as_object().ok_or(Rejection::Malformed)?;
    if obj.get("active").and_then(Value::as_bool) != Some(true) {
        return Err(Rejection::Inactive);
    }
    let str_of = |k: &str| obj.get(k).and_then(Value::as_str).unwrap_or("");
    let aud_ok = match obj.get("aud") {
        Some(Value::String(s)) => s == resource,
        Some(Value::Array(a)) => a.iter().any(|v| v.as_str() == Some(resource)),
        _ => false,
    };
    if !aud_ok {
        return Err(Rejection::Audience);
    }
    if str_of("iss") != issuer {
        return Err(Rejection::Issuer);
    }
    if !str_of("token_type").eq_ignore_ascii_case("bearer") {
        return Err(Rejection::TokenType);
    }
    let exp = obj.get("exp").and_then(Value::as_i64).unwrap_or(0);
    if exp <= now {
        return Err(Rejection::Expired);
    }
    let sub = str_of("sub");
    if sub.is_empty() {
        return Err(Rejection::Subject);
    }
    Ok(Grant {
        subject: sub.to_string(),
        client_id: str_of("client_id").to_string(),
        scopes: str_of("scope")
            .split_whitespace()
            .map(String::from)
            .collect(),
        expires_at: exp,
        issued_at: obj.get("iat").and_then(Value::as_i64).unwrap_or(0),
    })
}

/// A refused request, ready to send: status, `WWW-Authenticate`, JSON body.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Challenge {
    kind: Kind,
    metadata_url: String,
    scope: String,
}

#[derive(Debug, Clone, PartialEq, Eq)]
enum Kind {
    NoCredentials,
    InvalidToken(&'static str),
    InvalidRequest,
    InsufficientScope(Vec<String>),
    Unavailable,
}

/// Remove characters that would break a quoted-string attribute value.
fn clean(v: &str) -> String {
    v.chars()
        .filter(|c| *c != '"' && *c != '\\' && !c.is_control())
        .collect()
}

impl Challenge {
    /// The HTTP status: 401, 400, 403 or 503.
    pub fn status(&self) -> u16 {
        match self.kind {
            Kind::NoCredentials | Kind::InvalidToken(_) => 401,
            Kind::InvalidRequest => 400,
            Kind::InsufficientScope(_) => 403,
            Kind::Unavailable => 503,
        }
    }

    /// The `WWW-Authenticate` value (empty for a 503, which carries none).
    pub fn www_authenticate(&self) -> String {
        let meta = format!("resource_metadata=\"{}\"", clean(&self.metadata_url));
        let scope = if self.scope.is_empty() {
            String::new()
        } else {
            format!(", scope=\"{}\"", clean(&self.scope))
        };
        match &self.kind {
            Kind::NoCredentials => format!("Bearer {meta}{scope}"),
            Kind::InvalidToken(d) => {
                format!("Bearer error=\"invalid_token\", error_description=\"{}\", {meta}{scope}", clean(d))
            }
            Kind::InvalidRequest => format!(
                "Bearer error=\"invalid_request\", error_description=\"malformed Authorization header\", {meta}"
            ),
            Kind::InsufficientScope(needed) => format!(
                "Bearer error=\"insufficient_scope\", scope=\"{}\", {meta}",
                clean(&needed.join(" "))
            ),
            Kind::Unavailable => String::new(),
        }
    }

    /// The full HTTP answer.
    pub fn reply(&self) -> Reply {
        let (error, description) = match &self.kind {
            Kind::NoCredentials => ("invalid_request", "authentication required"),
            Kind::InvalidToken(d) => ("invalid_token", *d),
            Kind::InvalidRequest => ("invalid_request", "malformed Authorization header"),
            Kind::InsufficientScope(_) => (
                "insufficient_scope",
                "the token lacks a scope this operation needs",
            ),
            Kind::Unavailable => ("temporarily_unavailable", ""),
        };
        let body = if self.kind == Kind::Unavailable {
            json!({ "error": error })
        } else {
            json!({ "error": error, "error_description": description })
        };
        let mut headers = vec![("content-type".to_string(), "application/json".to_string())];
        if self.kind == Kind::Unavailable {
            headers.push(("retry-after".into(), "5".into()));
        } else {
            headers.push(("www-authenticate".into(), self.www_authenticate()));
        }
        Reply {
            status: self.status(),
            headers,
            body: body.to_string(),
        }
    }
}

/// A configuration error from [`ProtectedResourceBuilder::build`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ConfigError(String);

impl std::fmt::Display for ConfigError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "resource configuration: {}", self.0)
    }
}

impl std::error::Error for ConfigError {}

fn cfg(m: impl Into<String>) -> ConfigError {
    ConfigError(m.into())
}

/// https only; http only for a loopback host (local development).
fn check_url(what: &str, raw: &str) -> Result<reqwest::Url, ConfigError> {
    let url =
        reqwest::Url::parse(raw).map_err(|_| cfg(format!("{what} is not an absolute URL")))?;
    let host = url
        .host_str()
        .ok_or_else(|| cfg(format!("{what} has no host")))?;
    let loopback = matches!(host, "localhost" | "127.0.0.1" | "[::1]");
    match url.scheme() {
        "https" => {}
        "http" if loopback => {}
        _ => {
            return Err(cfg(format!(
                "{what} must be https (http only for localhost)"
            )))
        }
    }
    if url.fragment().is_some() {
        return Err(cfg(format!("{what} must not have a fragment")));
    }
    Ok(url)
}

/// Builds a [`ProtectedResource`].
pub struct ProtectedResourceBuilder {
    resource: String,
    issuer: String,
    scopes: Vec<String>,
    name: Option<String>,
    credentials: Option<(String, String)>,
    endpoint: String,
    ttl: Duration,
    timeout: Duration,
}

impl ProtectedResourceBuilder {
    /// Scopes advertised in the metadata and the challenge.
    pub fn scopes_supported<I, S>(mut self, scopes: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        self.scopes = scopes.into_iter().map(Into::into).collect();
        self
    }
    /// A human-readable `resource_name` for the metadata.
    pub fn resource_name(mut self, name: impl Into<String>) -> Self {
        self.name = Some(name.into());
        self
    }
    /// The resource server's own confidential OAuth client.
    pub fn client_credentials(mut self, id: impl Into<String>, secret: impl Into<String>) -> Self {
        self.credentials = Some((id.into(), secret.into()));
        self
    }
    /// Replace the introspection endpoint (tests, other deployments).
    pub fn introspection_endpoint(mut self, url: impl Into<String>) -> Self {
        self.endpoint = url.into();
        self
    }
    /// How long a positive answer is reused (default 30 s, at most 60 s, 0 disables).
    pub fn cache_ttl(mut self, ttl: Duration) -> Self {
        self.ttl = ttl;
        self
    }
    /// The introspection timeout (default 5 s).
    pub fn timeout(mut self, timeout: Duration) -> Self {
        self.timeout = timeout;
        self
    }

    /// Validate and build.
    pub fn build(self) -> Result<ProtectedResource, ConfigError> {
        let res = check_url("resource", &self.resource)?;
        if res.query().is_some() {
            return Err(cfg("resource must not have a query"));
        }
        let iss = check_url("authorization server", &self.issuer)?;
        if iss.query().is_some() {
            return Err(cfg("authorization server must not have a query"));
        }
        check_url("introspection endpoint", &self.endpoint)?;
        let (id, secret) = self
            .credentials
            .ok_or_else(|| cfg("client credentials are required"))?;
        if id.is_empty() || secret.is_empty() {
            return Err(cfg("client id and secret must not be empty"));
        }
        let http = reqwest::Client::builder()
            .timeout(self.timeout)
            .redirect(reqwest::redirect::Policy::none())
            .build()
            .map_err(|e| cfg(format!("http client: {e}")))?;
        let origin = res.origin().ascii_serialization();
        let path = res.path();
        let metadata_path = if path.is_empty() || path == "/" {
            "/.well-known/oauth-protected-resource".to_string()
        } else {
            format!("/.well-known/oauth-protected-resource{path}")
        };
        Ok(ProtectedResource {
            resource: self.resource,
            // Sylphx Auth names its issuer without a trailing slash, and the
            // introspection `iss` is compared byte for byte.
            issuer: self.issuer.trim_end_matches('/').to_string(),
            scopes: self.scopes,
            name: self.name,
            id,
            secret,
            endpoint: self.endpoint,
            ttl: self.ttl.min(MAX_CACHE_TTL),
            metadata_url: format!("{origin}{metadata_path}"),
            metadata_path,
            http,
            cache: Mutex::new(HashMap::new()),
        })
    }
}

/// A protected resource server's view of its Sylphx Auth authorization server.
pub struct ProtectedResource {
    resource: String,
    issuer: String,
    scopes: Vec<String>,
    name: Option<String>,
    id: String,
    secret: String,
    endpoint: String,
    ttl: Duration,
    metadata_path: String,
    metadata_url: String,
    http: reqwest::Client,
    cache: Mutex<HashMap<[u8; 32], (Grant, Instant)>>,
}

impl std::fmt::Debug for ProtectedResource {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ProtectedResource")
            .field("resource", &self.resource)
            .field("issuer", &self.issuer)
            .field("client_id", &self.id)
            .field("client_secret", &"<redacted>")
            .finish_non_exhaustive()
    }
}

fn now_secs() -> i64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|d| d.as_secs() as i64)
        .unwrap_or(0)
}

/// How an `Authorization` header reads.
enum Presented<'a> {
    /// `Bearer <token>`: scheme case-insensitive, exactly one token.
    Bearer(&'a str),
    /// Another scheme: no bearer credentials (RFC 6750 §3.1, a plain 401).
    OtherScheme,
    /// A bearer header that is not well formed.
    Malformed,
}

fn parse_bearer(header: &str) -> Presented<'_> {
    let (scheme, rest) = header.split_once(' ').unwrap_or((header, ""));
    if !scheme.eq_ignore_ascii_case("bearer") {
        return Presented::OtherScheme;
    }
    if rest.is_empty()
        || rest.len() > MAX_TOKEN_BYTES
        || rest.chars().any(|c| c.is_whitespace() || c.is_control())
    {
        return Presented::Malformed;
    }
    Presented::Bearer(rest)
}

fn form_encode(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    for b in s.bytes() {
        match b {
            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~' => {
                out.push(b as char)
            }
            _ => out.push_str(&format!("%{b:02X}")),
        }
    }
    out
}

impl ProtectedResource {
    /// Start a builder for `resource` (its canonical URI) served by `authorization_server` (its issuer).
    pub fn builder(
        resource: impl Into<String>,
        authorization_server: impl Into<String>,
    ) -> ProtectedResourceBuilder {
        ProtectedResourceBuilder {
            resource: resource.into(),
            issuer: authorization_server.into(),
            scopes: Vec::new(),
            name: None,
            credentials: None,
            endpoint: DEFAULT_INTROSPECTION.into(),
            ttl: Duration::from_secs(30),
            timeout: Duration::from_secs(5),
        }
    }

    /// Build from `SYLPHX_RESOURCE_URI`, `SYLPHX_AUTH_ISSUER`,
    /// `SYLPHX_RESOURCE_CLIENT_ID`, `SYLPHX_RESOURCE_CLIENT_SECRET`, and the
    /// optional `SYLPHX_RESOURCE_SCOPES` and `SYLPHX_INTROSPECTION_URL`.
    pub fn from_env() -> Result<Self, ConfigError> {
        let get = |k: &str| std::env::var(k).map_err(|_| cfg(format!("{k} is not set")));
        let mut b = Self::builder(get("SYLPHX_RESOURCE_URI")?, get("SYLPHX_AUTH_ISSUER")?)
            .client_credentials(
                get("SYLPHX_RESOURCE_CLIENT_ID")?,
                get("SYLPHX_RESOURCE_CLIENT_SECRET")?,
            );
        if let Ok(s) = std::env::var("SYLPHX_RESOURCE_SCOPES") {
            b = b.scopes_supported(s.split_whitespace().map(String::from));
        }
        if let Ok(u) = std::env::var("SYLPHX_INTROSPECTION_URL") {
            b = b.introspection_endpoint(u);
        }
        b.build()
    }

    /// The RFC 9728 metadata document.
    pub fn metadata(&self) -> Value {
        let mut doc = json!({
            "resource": self.resource,
            "authorization_servers": [self.issuer],
            "scopes_supported": self.scopes,
            "bearer_methods_supported": ["header"],
        });
        if let Some(n) = &self.name {
            doc["resource_name"] = json!(n);
        }
        doc
    }

    /// Where the metadata is served on the resource's origin (RFC 9728 §3.1).
    pub fn metadata_path(&self) -> String {
        self.metadata_path.clone()
    }

    /// The absolute metadata URL, advertised in challenges.
    pub fn metadata_url(&self) -> String {
        self.metadata_url.clone()
    }

    /// The metadata document as a 200 answer.
    pub fn metadata_response(&self) -> Reply {
        Reply {
            status: 200,
            headers: vec![
                ("content-type".into(), "application/json".into()),
                ("cache-control".into(), "public, max-age=300".into()),
            ],
            body: self.metadata().to_string(),
        }
    }

    fn challenge(&self, kind: Kind, scope: &[&str]) -> Challenge {
        let scope = if scope.is_empty() {
            self.scopes.join(" ")
        } else {
            scope.join(" ")
        };
        Challenge {
            kind,
            metadata_url: self.metadata_url.clone(),
            scope,
        }
    }

    /// Authenticate an `Authorization` header: a [`Grant`], or the
    /// [`Challenge`] to send.
    pub async fn authenticate(
        &self,
        authorization_header: Option<&str>,
    ) -> Result<Grant, Challenge> {
        self.authenticate_for(authorization_header, &[]).await
    }

    /// [`authenticate`](Self::authenticate), naming `needed` as the scope in a
    /// 401 so the client asks for it up front.
    async fn authenticate_for(
        &self,
        authorization_header: Option<&str>,
        needed: &[&str],
    ) -> Result<Grant, Challenge> {
        let Some(header) = authorization_header else {
            return Err(self.challenge(Kind::NoCredentials, needed));
        };
        let token = match parse_bearer(header) {
            Presented::Bearer(token) => token,
            Presented::OtherScheme => return Err(self.challenge(Kind::NoCredentials, needed)),
            Presented::Malformed => return Err(self.challenge(Kind::InvalidRequest, needed)),
        };
        let key: [u8; 32] = Sha256::digest(token.as_bytes()).into();
        if !self.ttl.is_zero() {
            let mut cache = self.cache.lock().unwrap_or_else(|e| e.into_inner());
            if let Some((grant, until)) = cache.get(&key) {
                if Instant::now() < *until && grant.expires_at > now_secs() {
                    return Ok(grant.clone());
                }
                cache.remove(&key);
            }
        }
        let answer = self
            .introspect(token)
            .await
            .map_err(|_| self.challenge(Kind::Unavailable, &[]))?;
        let now = now_secs();
        match grant_from_introspection(&answer, &self.resource, &self.issuer, now) {
            Ok(grant) => {
                if !self.ttl.is_zero() {
                    let life = self
                        .ttl
                        .min(Duration::from_secs((grant.expires_at - now).max(0) as u64));
                    let mut cache = self.cache.lock().unwrap_or_else(|e| e.into_inner());
                    if cache.len() >= MAX_CACHE_ENTRIES {
                        let t = Instant::now();
                        cache.retain(|_, (_, until)| *until > t);
                        if cache.len() >= MAX_CACHE_ENTRIES {
                            cache.clear();
                        }
                    }
                    cache.insert(key, (grant.clone(), Instant::now() + life));
                }
                Ok(grant)
            }
            Err(r) => Err(self.challenge(
                Kind::InvalidToken(match r {
                    Rejection::Expired => "the access token expired",
                    Rejection::Audience => "the access token is not for this resource",
                    Rejection::TokenType => "sender-constrained tokens are not accepted",
                    _ => "the access token is invalid",
                }),
                needed,
            )),
        }
    }

    /// Require every scope in `needed`; a refusal lists all of them (MCP step-up).
    pub fn require(&self, grant: &Grant, needed: &[&str]) -> Result<(), Challenge> {
        if needed.iter().all(|s| grant.has(s)) {
            Ok(())
        } else {
            Err(self.challenge(
                Kind::InsufficientScope(needed.iter().map(|s| s.to_string()).collect()),
                needed,
            ))
        }
    }

    /// [`authenticate`](Self::authenticate), then [`require`](Self::require).
    pub async fn authorize(
        &self,
        authorization_header: Option<&str>,
        needed: &[&str],
    ) -> Result<Grant, Challenge> {
        let grant = self.authenticate_for(authorization_header, needed).await?;
        self.require(&grant, needed)?;
        Ok(grant)
    }

    async fn introspect(&self, token: &str) -> Result<Value, ()> {
        let basic = STANDARD.encode(format!("{}:{}", self.id, self.secret));
        let resp = self
            .http
            .post(&self.endpoint)
            .header("authorization", format!("Basic {basic}"))
            .header("content-type", "application/x-www-form-urlencoded")
            .header("accept", "application/json")
            .body(format!("token={}", form_encode(token)))
            .send()
            .await
            .map_err(|_| ())?;
        if resp.status().as_u16() != 200 {
            return Err(());
        }
        resp.json::<Value>().await.map_err(|_| ())
    }
}