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
//! Turning a presented access token into the [`AuthContext`] a request runs under.
//!
//! The security-relevant part of T16 lives here and is a pure function:
//! [`verify`] takes claims an adapter has already authenticated (signature
//! checked, issuer confirmed), the resource the request arrived at, and a clock,
//! and it either produces an [`AuthContext`] or a [`Refusal`] that names why.
//! It reads no clock and opens no socket, so every branch in it — wrong audience,
//! expired, not yet valid, wrong issuer — is testable without a network.
//!
//! # Two rules that are worth stating plainly
//!
//! **The audience must be exactly this server.** RFC 8707 resource indicators
//! exist so a token minted for one resource cannot be presented at another, and
//! `2025-06-18` changelog §4 (PR #734) makes them a client `MUST`. Comparing
//! for "contains" rather than equality would defeat the whole mechanism: a token
//! with a two-element `aud` naming a malicious server and ours would pass.
//!
//! **No token means no context.** [`Refusal`] has no variant that means "let it
//! through unprivileged", because the route's only way to reach a session is
//! through the `&AuthContext` it was handed, and a context nobody can widen is
//! the fail-secure default.
//!
//! # On scope names
//!
//! The claims carry whatever scope strings the authorization server put there,
//! as strings. The vendored spec names none of them — the only scope sentence in
//! any revision's changelog is `2025-11-25` §3 (SEP-835) on incremental consent
//! via `WWW-Authenticate` — so there is no specified vocabulary to map onto
//! [`Scope`](crate::domain::Scope). Turning `mcp:tools` into
//! [`Read`](crate::domain::Scope::Read) is a *deployment's* policy, so it lives
//! behind [`ScopePolicy`] as configuration rather than being hardcoded here as
//! if the specification had said so.
use Arc;
use SystemTime;
use crateResourceUri;
use crateAuthorizationModel;
use crate;
/// What an adapter established about a presented token, before this crate's
/// own rules ran.
///
/// "Established" means the adapter verified the signature (JWT) or asked the
/// authorization server (introspection). It is deliberately *not* a type that can
/// be built from a raw string in this crate: there is no path from an
/// `Authorization` header to a `TokenClaims` that skips the adapter, because
/// that is the property that keeps a decode from becoming a verify.
/// Why a presented token was refused.
///
/// Every variant is a distinct reason a `401` might be correct, and the HTTP
/// layer does not get to choose between them on the way out: an expired token
/// and a wrong-audience token produce the same status and the same challenge,
/// because telling a caller *which* failed is telling it something about the
/// token it should not learn.
/// What a deployment decides its own OAuth scope strings mean.
///
/// Not in `domain/`, and deliberately not a hardcoded table: the vendored spec
/// names no scope strings, so any mapping written here would be this crate
/// inventing a vocabulary and presenting it as policy. A deployment supplies the
/// vocabulary it actually issues, and the default maps nothing — which means an
/// unconfigured deployment refuses every token rather than granting one a scope
/// nobody chose.
/// The fail-secure default: no scope string means anything.
///
/// Every token is refused with [`Refusal::Unscoped`] until a deployment supplies
/// a real policy. That is the whole design — a missing configuration must deny,
/// and it must deny *loudly* with a reason that says it was a configuration
/// rather than a forged token.
;
/// What the request is allowed to be, given the resource it reached and the
/// revision it negotiated.
///
/// Two deployment facts and one spec fact, all of which change whether a token
/// is checked at all. Bundled because passing three arguments to every call site
/// invites two of them being forgotten.
/// Turns claims an adapter authenticated into an [`AuthContext`], or refuses.
///
/// # Errors
///
/// The [`Refusal`] naming the first rule `claims` fails. Order is deliberate:
/// time is checked before audience so a stale token does not report a mismatch,
/// and audience before issuer because the audience is the binding that keeps a
/// token from crossing between servers, which is the one this crate must not get
/// wrong.
///
/// # Examples
///
/// ```
/// use std::time::{Duration, SystemTime};
///
/// use protocol_droid::application::oauth::{ScopePolicy, TokenClaims, TokenPolicy, verify};
/// use protocol_droid::domain::mcp::ResourceUri;
/// use protocol_droid::domain::registry::{Scope, ScopeSet};
/// use protocol_droid::domain::{ProtocolVersion, authorization_model};
///
/// struct Permissive;
/// impl ScopePolicy for Permissive {
/// fn resolve(&self, scope: &str) -> Option<Scope> {
/// match scope {
/// "mcp:read" => Some(Scope::Read),
/// _ => None,
/// }
/// }
/// }
///
/// let resource = ResourceUri::new("https://example.com/mcp")?;
/// let now = SystemTime::UNIX_EPOCH + Duration::from_secs(1_000);
/// let policy = TokenPolicy::new(&resource, authorization_model(ProtocolVersion::V2026_07_28));
///
/// let good = TokenClaims::new()
/// .with_subject("alice")
/// .with_audience(resource.clone())
/// .with_expiry(now + Duration::from_secs(60))
/// .with_scope("mcp:read");
///
/// let context = verify(&good, &policy, &Permissive, now)?;
/// assert_eq!(context.principal(), "alice");
/// assert!(context.holds(ScopeSet::empty().with(Scope::Read)));
///
/// // A token minted for a different server is refused.
/// let elsewhere = TokenClaims::new()
/// .with_subject("alice")
/// .with_audience(ResourceUri::new("https://evil.example/mcp")?)
/// .with_expiry(now + Duration::from_secs(60));
/// assert!(verify(&elsewhere, &policy, &Permissive, now).is_err());
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
/// Why no claims could be established for a presented token.
///
/// Two kinds, and the distinction is the one a client cannot recover from
/// either: a token that was *refused* is refused, and a token whose validity
/// could not be *determined* is in a different position. Reporting the second
/// as the first sends a caller to re-authenticate against an authorization
/// server that was merely unreachable, and reports a client's credentials as
/// bad when they were never wrong.
/// Where verified claims come from.
///
/// The consumer is [`authenticate`], and the line this port draws is the whole
/// design: an adapter establishes *authenticity* — the signature checked, or the
/// authorization server asked — and this crate applies *authorization*: the
/// audience, the expiry, the issuer, the scopes. Neither half can do the other's
/// job, and in particular a decode is not a verify, which is why
/// [`TokenClaims`] has no constructor that takes a raw string.
///
/// # Object safety
///
/// An `async fn` on a trait is native RPITIT and is not object safe. That is
/// deliberate: the call site takes `impl TokenSource`, so this monomorphises and
/// pays nothing per call. A deployment that must choose a source at runtime
/// holds an enum over two variants rather than a `dyn` — which costs less than
/// the per-request boxing that a trait object here would need.
/// Authenticates a presented bearer token end to end.
///
/// [`TokenSource::claims`] for the authenticity, then [`verify`] for the
/// authorization rules, in that order and with no other path between them.
///
/// The token is borrowed and never stored, cloned into a message, or logged —
/// it exists for the length of this call and then only as whatever the
/// authorization server chose to say about it.
///
/// # Errors
///
/// [`SourceError::Refused`] for a token that was refused, and
/// [`SourceError::Unavailable`] when the authorization server could not be
/// asked. The two mean different things to a caller and are not merged.
pub async