protocol-droid 0.3.0

A Model Context Protocol toolkit that speaks every published spec revision, with one canonical IR behind many per-revision codecs.
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
//! The rules a presented token has to pass, and each way it can fail.
//!
//! The task's three required cases are named tests here — wrong audience,
//! expired, valid — alongside the branches a reviewer would otherwise have to
//! take on trust.

use std::assert_matches;
use std::future::{Future, ready};
use std::sync::Arc;
use std::task::{Context, Poll, Wake, Waker};
use std::time::{Duration, SystemTime};

use super::{
    NoScopes, Refusal, ScopePolicy, SourceError, TokenClaims, TokenPolicy, TokenSource,
    authenticate, verify,
};
use crate::domain::mcp::{ResourceUri, ResourceUriError};
use crate::domain::registry::{Scope, ScopeSet};
use crate::domain::{ProtocolVersion, authorization_model};

/// The two unrelated error types these tests answer, collected so `?` works
/// and a failure prints the engine's own account of what it refused.
#[derive(Debug, thiserror::Error)]
enum Failure {
    /// A resource identifier did not parse.
    #[error(transparent)]
    Uri(#[from] ResourceUriError),
    /// A token was refused.
    #[error(transparent)]
    Refusal(#[from] Refusal),
    /// No claims could be obtained at all — the seam tests' subject.
    #[error(transparent)]
    Source(#[from] SourceError),
}

/// The resource these tests are about.
const RESOURCE: &str = "https://example.com/mcp";
/// A second server, which a token minted for it must not be usable here.
const OTHER: &str = "https://elsewhere.example/mcp";
/// A sibling path on our own host.
const SIBLING: &str = "https://example.com/other";

/// A fixed instant, so every time comparison in this file is deterministic.
const NOW_SECS: u64 = 1_000;
const FUTURE_SECS: u64 = NOW_SECS + 60;

fn now() -> SystemTime {
    SystemTime::UNIX_EPOCH + Duration::from_secs(NOW_SECS)
}

fn in_future() -> SystemTime {
    SystemTime::UNIX_EPOCH + Duration::from_secs(FUTURE_SECS)
}

/// A deployment whose vocabulary this crate does not know: only the two scopes
/// below mean anything. The names are the test's, not the specification's —
/// the vendored spec defines no scope strings.
struct TwoScopes;

impl ScopePolicy for TwoScopes {
    fn resolve(&self, scope: &str) -> Option<Scope> {
        match scope {
            "mcp:read" => Some(Scope::Read),
            "mcp:write" => Some(Scope::Write),
            _ => None,
        }
    }
}

/// A token that passes everything, for the individual tests to break one field
/// of at a time.
fn valid_claims() -> Result<TokenClaims, ResourceUriError> {
    claims_for(RESOURCE, &["mcp:read"])
}

/// A token for exactly `audience` carrying exactly `scopes`.
///
/// Built from scratch rather than from [`valid_claims`] on purpose:
/// `with_audience` *appends*, so starting from a valid token and adding a wrong
/// audience leaves a token that legitimately contains both — which verifies,
/// and tests nothing about refusal.
fn claims_for(audience: &str, scopes: &[&str]) -> Result<TokenClaims, ResourceUriError> {
    let mut claims = TokenClaims::new()
        .with_subject("alice")
        .with_audience(ResourceUri::new(audience)?)
        .with_expiry(in_future());
    for scope in scopes {
        claims = claims.with_scope(*scope);
    }
    Ok(claims)
}

#[test]
fn a_valid_token_yields_a_context_with_its_scopes() -> Result<(), Failure> {
    let resource = ResourceUri::new(RESOURCE)?;
    let policy = TokenPolicy::new(&resource, authorization_model(ProtocolVersion::V2026_07_28));

    let context = verify(&valid_claims()?, &policy, &TwoScopes, now())?;

    assert_eq!(context.principal(), "alice");
    assert!(context.holds(ScopeSet::empty().with(Scope::Read)));
    Ok(())
}

#[test]
fn a_wrong_audience_is_refused() -> Result<(), Failure> {
    // The task's first required case: signed, unexpired, names a subject — and
    // is only for a different server.
    let resource = ResourceUri::new(RESOURCE)?;
    let policy = TokenPolicy::new(&resource, authorization_model(ProtocolVersion::V2026_07_28));
    let claims = TokenClaims::new()
        .with_subject("alice")
        .with_audience(ResourceUri::new(OTHER)?)
        .with_expiry(in_future())
        .with_scope("mcp:read");

    assert_eq!(
        verify(&claims, &policy, &TwoScopes, now()),
        Err(Refusal::AudienceMismatch),
    );
    Ok(())
}

#[test]
fn an_expired_token_is_refused() -> Result<(), Failure> {
    // The task's second required case.
    let resource = ResourceUri::new(RESOURCE)?;
    let policy = TokenPolicy::new(&resource, authorization_model(ProtocolVersion::V2026_07_28));
    let claims = valid_claims()?.with_expiry(now() - Duration::from_secs(1));

    assert_eq!(
        verify(&claims, &policy, &TwoScopes, now()),
        Err(Refusal::Expired),
    );
    Ok(())
}

#[test]
fn a_token_expiring_exactly_now_is_refused() -> Result<(), Failure> {
    // `exp` is exclusive, so equality is expiry. Off-by-one here is a token
    // accepted for one instant past its life.
    let resource = ResourceUri::new(RESOURCE)?;
    let policy = TokenPolicy::new(&resource, authorization_model(ProtocolVersion::V2026_07_28));
    let claims = valid_claims()?.with_expiry(now());

    assert_eq!(
        verify(&claims, &policy, &TwoScopes, now()),
        Err(Refusal::Expired),
    );
    Ok(())
}

#[test]
fn a_token_that_is_not_valid_yet_is_refused() -> Result<(), Failure> {
    let resource = ResourceUri::new(RESOURCE)?;
    let policy = TokenPolicy::new(&resource, authorization_model(ProtocolVersion::V2026_07_28));
    let claims = valid_claims()?.with_not_before(in_future());

    assert_eq!(
        verify(&claims, &policy, &TwoScopes, now()),
        Err(Refusal::NotYetValid),
    );
    Ok(())
}

#[test]
fn a_token_with_no_audience_is_refused() -> Result<(), Failure> {
    // A token that names no audience is what a captured-token replay carries.
    let resource = ResourceUri::new(RESOURCE)?;
    let policy = TokenPolicy::new(&resource, authorization_model(ProtocolVersion::V2026_07_28));
    let claims = TokenClaims::new()
        .with_subject("alice")
        .with_expiry(in_future())
        .with_scope("mcp:read");

    assert_eq!(
        verify(&claims, &policy, &TwoScopes, now()),
        Err(Refusal::AudienceMismatch),
    );
    Ok(())
}

#[test]
fn sharing_an_audience_array_with_this_server_is_enough() -> Result<(), Failure> {
    // RFC 7519 §4.1.3 allows `aud` to be an array. A token naming two servers is
    // legitimately usable at ours — a check requiring the array to be exactly
    // one element would wrongly refuse it.
    let resource = ResourceUri::new(RESOURCE)?;
    let policy = TokenPolicy::new(&resource, authorization_model(ProtocolVersion::V2026_07_28));
    // Two entries, ours and theirs — which is the whole point of the array
    // form, and the reason this cannot reuse [`claims_for`]'s single audience.
    let claims = claims_for(OTHER, &["mcp:read"])?.with_audience(resource.clone());

    let context = verify(&claims, &policy, &TwoScopes, now())?;
    assert_eq!(context.principal(), "alice");
    Ok(())
}

#[test]
fn a_sibling_path_on_the_same_host_is_a_different_resource() -> Result<(), Failure> {
    // The check this design turns on. A server mounted at a sibling path shares
    // a host with ours, so anything matching on host would accept its token.
    let resource = ResourceUri::new(RESOURCE)?;
    let policy = TokenPolicy::new(&resource, authorization_model(ProtocolVersion::V2026_07_28));
    let claims = TokenClaims::new()
        .with_subject("alice")
        .with_audience(ResourceUri::new(SIBLING)?)
        .with_expiry(in_future())
        .with_scope("mcp:read");

    assert_eq!(
        verify(&claims, &policy, &TwoScopes, now()),
        Err(Refusal::AudienceMismatch),
    );
    Ok(())
}

#[test]
fn an_unexpected_issuer_is_refused() -> Result<(), Failure> {
    let resource = ResourceUri::new(RESOURCE)?;
    let policy = TokenPolicy::new(&resource, authorization_model(ProtocolVersion::V2026_07_28))
        .with_expected_issuer("https://auth.example.com");
    let claims = valid_claims()?.with_issuer("https://elsewhere.example.com");

    assert_eq!(
        verify(&claims, &policy, &TwoScopes, now()),
        Err(Refusal::IssuerMismatch),
    );
    Ok(())
}

#[test]
fn an_absent_issuer_is_not_a_mismatch() -> Result<(), Failure> {
    // Only a *present, wrong* issuer is fatal. A token naming none is unusual,
    // but it is not evidence of anything.
    let resource = ResourceUri::new(RESOURCE)?;
    let policy = TokenPolicy::new(&resource, authorization_model(ProtocolVersion::V2026_07_28))
        .with_expected_issuer("https://auth.example.com");

    assert!(!policy.accepts_any_issuer());
    assert!(verify(&valid_claims()?, &policy, &TwoScopes, now()).is_ok());
    Ok(())
}

#[test]
fn a_token_naming_no_subject_is_refused() -> Result<(), Failure> {
    let resource = ResourceUri::new(RESOURCE)?;
    let policy = TokenPolicy::new(&resource, authorization_model(ProtocolVersion::V2026_07_28));
    let claims = TokenClaims::new()
        .with_audience(resource.clone())
        .with_expiry(in_future())
        .with_scope("mcp:read");

    assert_eq!(
        verify(&claims, &policy, &TwoScopes, now()),
        Err(Refusal::NoSubject),
    );
    Ok(())
}

#[test]
fn a_token_whose_scopes_map_to_nothing_is_refused() -> Result<(), Failure> {
    // Refused loudly as a configuration problem rather than accepted with no
    // permissions — the two are indistinguishable over the wire and very
    // different in a log.
    let resource = ResourceUri::new(RESOURCE)?;
    let policy = TokenPolicy::new(&resource, authorization_model(ProtocolVersion::V2026_07_28));
    let claims = claims_for(RESOURCE, &["some:scope:this:deployment:never:issued"])?;

    assert_eq!(
        verify(&claims, &policy, &TwoScopes, now()),
        Err(Refusal::Unscoped),
    );
    Ok(())
}

#[test]
fn an_unconfigured_deployment_refuses_every_token() -> Result<(), Failure> {
    // `NoScopes` maps nothing, so a deployment that never supplied a policy
    // denies everything — fail-secure by construction rather than by
    // remembering to check a flag.
    let resource = ResourceUri::new(RESOURCE)?;
    let policy = TokenPolicy::new(&resource, authorization_model(ProtocolVersion::V2026_07_28));

    assert_eq!(
        verify(&valid_claims()?, &policy, &NoScopes, now()),
        Err(Refusal::Unscoped),
    );
    Ok(())
}

#[test]
fn several_scopes_union_rather_than_replace() -> Result<(), Failure> {
    let resource = ResourceUri::new(RESOURCE)?;
    let policy = TokenPolicy::new(&resource, authorization_model(ProtocolVersion::V2026_07_28));
    let claims = claims_for(RESOURCE, &["mcp:read", "mcp:write", "unknown:scope"])?;

    let context = verify(&claims, &policy, &TwoScopes, now())?;
    assert!(context.holds(ScopeSet::empty().with(Scope::Read).with(Scope::Write)));
    Ok(())
}

#[test]
fn a_revision_without_a_framework_accepts_no_token() -> Result<(), Failure> {
    // `2024-11-05` has no authorization framework, so there is no audience to
    // bind against and no correct way to accept one.
    let resource = ResourceUri::new(RESOURCE)?;
    let policy = TokenPolicy::new(&resource, authorization_model(ProtocolVersion::V2024_11_05));

    assert_eq!(
        verify(&valid_claims()?, &policy, &TwoScopes, now()),
        Err(Refusal::AudienceMismatch),
    );
    Ok(())
}

#[test]
fn every_revision_with_a_framework_checks_the_audience() -> Result<(), Failure> {
    // Gated by `audience_bound`, which follows `specified` — so `2025-03-26`
    // gets the check even though it has no protected-resource metadata to
    // publish. A regression that made the gate follow the metadata instead would
    // fail here rather than going unnoticed.
    for version in ProtocolVersion::KNOWN {
        let resource = ResourceUri::new(RESOURCE)?;
        let policy = TokenPolicy::new(&resource, authorization_model(version));
        let claims = claims_for(OTHER, &["mcp:read"])?;

        let got = verify(&claims, &policy, &TwoScopes, now());
        assert_eq!(
            got,
            Err(Refusal::AudienceMismatch),
            "{version} must refuse a foreign-audience token",
        );
    }
    Ok(())
}

#[test]
fn expiry_is_reported_before_a_mismatch() -> Result<(), Failure> {
    // The order is deliberate: a stale token should not report an audience
    // problem, because the audience may well be fine and the caller would then
    // go looking in the wrong place.
    let resource = ResourceUri::new(RESOURCE)?;
    let policy = TokenPolicy::new(&resource, authorization_model(ProtocolVersion::V2026_07_28));
    let claims = TokenClaims::new()
        .with_subject("alice")
        .with_audience(ResourceUri::new(OTHER)?)
        .with_expiry(now() - Duration::from_secs(1))
        .with_scope("mcp:read");

    assert_eq!(
        verify(&claims, &policy, &TwoScopes, now()),
        Err(Refusal::Expired),
    );
    Ok(())
}

#[test]
fn scope_strings_reach_the_verifier_untranslated() -> Result<(), Failure> {
    // The claims keep the strings the authorization server sent. Mapping them to
    // `Scope` is the deployment's policy, so it happens in `ScopePolicy` and not
    // on the way in.
    let claims = valid_claims()?;
    assert_eq!(claims.scopes(), &[Arc::from("mcp:read")]);

    let resource = ResourceUri::new(RESOURCE)?;
    let policy = TokenPolicy::new(&resource, authorization_model(ProtocolVersion::V2026_07_28));
    assert!(verify(&claims, &policy, &TwoScopes, now()).is_ok());
    Ok(())
}

// ---------------------------------------------------------------------------
// `authenticate` — the seam, tested where no adapter is compiled
//
// These live here rather than beside the introspection adapter because
// `default-features = false` drops that adapter, and `authenticate` is
// application logic that a lean build must still be able to reach. With no
// implementor of `TokenSource` anywhere in the configuration, these are what
// keep it from being dead code in exactly the build that cannot afford it.
// ---------------------------------------------------------------------------

/// A [`TokenSource`] that answers from a fixed answer, standing in for an
/// authorization server the test does not run.
struct Fixed(Result<TokenClaims, SourceError>);

impl TokenSource for Fixed {
    fn claims(
        &self,
        _presented: &str,
    ) -> impl Future<Output = Result<TokenClaims, SourceError>> + Send {
        ready(self.0.clone())
    }
}

/// Drives a future to completion on this thread.
///
/// Awaiting a ready future still needs an executor, and tokio is not compiled
/// under `default-features = false`. Fifteen lines of standard library is
/// cheaper than gating these tests behind a feature that would leave the lean
/// build untested.
fn block_on<F: Future>(future: F) -> F::Output {
    struct ThreadWaker(std::thread::Thread);

    impl Wake for ThreadWaker {
        fn wake(self: Arc<Self>) {
            self.0.unpark();
        }
    }

    let waker = Waker::from(Arc::new(ThreadWaker(std::thread::current())));
    let mut context = Context::from_waker(&waker);
    let mut future = Box::pin(future);
    loop {
        if let Poll::Ready(output) = future.as_mut().poll(&mut context) {
            return output;
        }
        std::thread::park();
    }
}

/// The policy every seam test below verifies against.
fn policy(resource: &ResourceUri) -> TokenPolicy<'_> {
    TokenPolicy::new(resource, authorization_model(ProtocolVersion::V2026_07_28))
}

#[test]
fn a_source_that_answers_produces_the_same_context_verifying_would_have() -> Result<(), Failure> {
    // `authenticate` must be exactly the seam it looks like: get claims, then
    // apply the policy. If it ever grew a rule of its own, this is the test
    // that would notice the two paths disagreeing.
    let resource = ResourceUri::new(RESOURCE)?;
    let source = Fixed(Ok(valid_claims()?));

    let context = block_on(authenticate(
        &source,
        &policy(&resource),
        &TwoScopes,
        "a-token",
        now(),
    ))?;

    assert_eq!(context.principal(), "alice");
    assert!(context.holds(ScopeSet::empty().with(Scope::Read)));
    Ok(())
}

#[test]
fn the_policy_still_gets_the_last_word_over_what_a_source_returned() -> Result<(), Failure> {
    // A source is trusted for authenticity, not for policy. One that hands back
    // a token minted for another server must still be refused here, or the
    // seam would be a way around the audience check.
    let resource = ResourceUri::new(RESOURCE)?;
    let source = Fixed(Ok(claims_for(OTHER, &["mcp:read"])?));

    let refusal = block_on(authenticate(
        &source,
        &policy(&resource),
        &TwoScopes,
        "a-token",
        now(),
    ));

    assert_matches!(
        refusal,
        Err(SourceError::Refused(Refusal::AudienceMismatch))
    );
    Ok(())
}

#[test]
fn a_source_that_says_no_is_not_re_written_as_an_unavailable_source() -> Result<(), Failure> {
    // The two failures are different acts. A refusal means the caller's token
    // is bad and re-authenticating may help; unavailable means we could not
    // find out. Collapsing them would send someone to re-authenticate while
    // the authorization server is down.
    let resource = ResourceUri::new(RESOURCE)?;
    let source = Fixed(Err(SourceError::Refused(Refusal::Expired)));

    let outcome = block_on(authenticate(
        &source,
        &policy(&resource),
        &TwoScopes,
        "a-token",
        now(),
    ));

    assert_matches!(outcome, Err(SourceError::Refused(Refusal::Expired)));
    Ok(())
}

#[test]
fn an_unreachable_source_stays_unavailable_and_never_becomes_a_refusal() -> Result<(), Failure> {
    let resource = ResourceUri::new(RESOURCE)?;
    let source = Fixed(Err(SourceError::Unavailable(
        "introspection responded 503".into(),
    )));

    let outcome = block_on(authenticate(
        &source,
        &policy(&resource),
        &TwoScopes,
        "a-token",
        now(),
    ));

    assert_matches!(&outcome, Err(SourceError::Unavailable(_)));
    // The status survives to the caller: it is what tells an operator the
    // authorization server is down rather than the token being bad.
    if let Err(SourceError::Unavailable(reason)) = &outcome {
        assert!(reason.contains("503"));
    }
    Ok(())
}