fastmcp-protocol 0.14.0

MCP protocol types and JSON-RPC implementation
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
//! Real-signature coverage for reviewed optional ID-JAG disclosures.
//!
//! Fixtures use only the public example RSA key from RFC 7515 Appendix A.2.
//! Preparation reproduced that appendix's published signature before signing
//! these cases. No private key or fixture signer is part of the repository.

use std::sync::OnceLock;

use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD};
use serde_json::json;

use super::super::{
    IdJagExpectations, IdJagVerificationKeys, JwtTimePolicy, ResourceTenantExpectation,
    TenantExpectation, verify_id_jag, verify_id_jag_with_disclosure,
};
use super::*;

const ISSUED: u64 = 2_000_000_000;
const ALL_CLAIMS: [IdJagDisclosureClaim; 4] = [
    IdJagDisclosureClaim::Email,
    IdJagDisclosureClaim::AuthenticationTime,
    IdJagDisclosureClaim::AuthenticationContext,
    IdJagDisclosureClaim::AuthenticationMethods,
];
const FIXTURE_NAMES: [&str; 14] = [
    "base",
    "email",
    "all_disclosures",
    "email_null",
    "email_too_long",
    "email_wrong_type",
    "amr_not_array",
    "amr_duplicate",
    "auth_time_future",
    "unknown_claim",
    "cnf",
    "act",
    "duplicate_email",
    "foreign_resource",
];

fn fixtures() -> &'static Value {
    static FIXTURES: OnceLock<Value> = OnceLock::new();
    FIXTURES.get_or_init(|| serde_json::from_str(include_str!("fixtures.json")).unwrap())
}

fn signed(name: &str) -> &'static str {
    fixtures()[name]
        .as_str()
        .expect("named signed disclosure fixture")
}

fn at(seconds: u64) -> SystemTime {
    UNIX_EPOCH + Duration::from_secs(seconds)
}

fn now() -> SystemTime {
    at(ISSUED + 10)
}

fn keys() -> IdJagVerificationKeys {
    let jwks = serde_json::to_vec(&fixtures()["jwks"]).unwrap();
    IdJagVerificationKeys::from_trusted_jwks("https://idp.example", 22, &jwks).unwrap()
}

fn expected() -> IdJagExpectations<'static> {
    IdJagExpectations {
        audience: "https://as.example",
        client_id: "native-resource",
        resource: "https://mcp.example/mcp",
        require_resource: true,
        idp_tenant: TenantExpectation::SingleTenant,
        resource_tenant: ResourceTenantExpectation::SingleTenant,
        time: JwtTimePolicy::id_jag_default(),
    }
}

fn configuration(claims: &[IdJagDisclosureClaim]) -> IdJagDisclosureConfiguration {
    IdJagDisclosureConfiguration {
        policy_id: "reviewed-id-jag-disclosures".to_owned(),
        generation: 7,
        idp_issuer: "https://idp.example".to_owned(),
        resource_as_issuer: "https://as.example".to_owned(),
        reviewed_at: at(ISSUED - 5),
        review_expires_at: at(ISSUED + 120),
        rules: claims
            .iter()
            .map(|claim| IdJagDisclosureRule {
                claim: *claim,
                purpose: format!("Validate and discard reviewed {}", claim.name()),
            })
            .collect(),
    }
}

fn policy(claims: &[IdJagDisclosureClaim]) -> IdJagDisclosurePolicy {
    IdJagDisclosurePolicy::from_trusted_configuration(configuration(claims)).unwrap()
}

#[test]
fn every_disclosure_fixture_has_a_real_rs256_signature_including_invalid_json() {
    let jwk = &fixtures()["jwks"]["keys"][0];
    let modulus = URL_SAFE_NO_PAD.decode(jwk["n"].as_str().unwrap()).unwrap();
    let exponent = URL_SAFE_NO_PAD.decode(jwk["e"].as_str().unwrap()).unwrap();
    let key = ring::signature::RsaPublicKeyComponents {
        n: modulus.as_slice(),
        e: exponent.as_slice(),
    };
    assert_eq!(
        fixtures().as_object().unwrap().len(),
        FIXTURE_NAMES.len() + 1
    );
    for name in FIXTURE_NAMES {
        let (input, signature) = signed(name).rsplit_once('.').unwrap();
        let signature = URL_SAFE_NO_PAD.decode(signature).unwrap();
        key.verify(
            &ring::signature::RSA_PKCS1_2048_8192_SHA256,
            input.as_bytes(),
            &signature,
        )
        .unwrap_or_else(|_| panic!("fixture signature failed: {name}"));
    }
}

#[test]
fn signed_optional_disclosures_require_explicit_permission_and_retain_only_names() {
    let keys = keys();
    let expected = expected();
    let strict = verify_id_jag(signed("base"), &keys, &expected, now()).unwrap();
    assert!(strict.disclosure().is_none());
    for name in ["email", "all_disclosures"] {
        assert_eq!(
            verify_id_jag(signed(name), &keys, &expected, now()).unwrap_err(),
            EnterpriseVerificationError::InvalidClaims,
        );
    }

    let policy = policy(&ALL_CLAIMS);
    let admitted =
        verify_id_jag_with_disclosure(signed("all_disclosures"), &keys, &expected, &policy, now())
            .unwrap();
    assert_eq!(admitted.subject().as_str(), "resource-facing");
    assert_eq!(admitted.resource(), Some("https://mcp.example/mcp"));
    assert_eq!(admitted.scope(), Some("read"));
    let facts = admitted.disclosure().expect("reviewed disclosure facts");
    assert_eq!(facts.policy_id(), "reviewed-id-jag-disclosures");
    assert_eq!(facts.generation(), 7);
    assert_eq!(facts.configuration_digest(), policy.configuration_digest());
    assert_eq!(facts.review_expires_at(), at(ISSUED + 120));
    assert_eq!(facts.admitted_claims(), ALL_CLAIMS.as_slice());

    let diagnostic = format!("{policy:?} {admitted:?} {facts:?}");
    for private_value in [
        "hidden-contact@example.test",
        "urn:example:assurance:reviewed",
        "pwd",
        "hwk",
        "resource-facing",
        signed("all_disclosures"),
    ] {
        assert!(!diagnostic.contains(private_value));
    }
}

#[test]
fn partial_and_empty_allowlists_do_not_inherit_other_disclosure_permissions() {
    let keys = keys();
    let expected = expected();
    let email_only = policy(&[IdJagDisclosureClaim::Email]);
    let admitted =
        verify_id_jag_with_disclosure(signed("email"), &keys, &expected, &email_only, now())
            .unwrap();
    assert_eq!(
        admitted.disclosure().unwrap().admitted_claims(),
        &[IdJagDisclosureClaim::Email],
    );
    assert_eq!(
        verify_id_jag_with_disclosure(
            signed("all_disclosures"),
            &keys,
            &expected,
            &email_only,
            now(),
        )
        .unwrap_err(),
        EnterpriseVerificationError::InvalidClaims,
    );
    let empty = policy(&[]);
    let admitted =
        verify_id_jag_with_disclosure(signed("base"), &keys, &expected, &empty, now()).unwrap();
    assert!(admitted.disclosure().unwrap().admitted_claims().is_empty());
    assert_eq!(
        verify_id_jag_with_disclosure(signed("email"), &keys, &expected, &empty, now(),)
            .unwrap_err(),
        EnterpriseVerificationError::InvalidClaims,
    );
}

#[test]
fn signed_disclosure_values_refuse_wrong_types_bounds_and_authentication_order() {
    let keys = keys();
    let expected = expected();
    let policy = policy(&ALL_CLAIMS);
    for name in [
        "email_null",
        "email_too_long",
        "email_wrong_type",
        "amr_not_array",
        "amr_duplicate",
        "auth_time_future",
    ] {
        assert_eq!(
            verify_id_jag_with_disclosure(signed(name), &keys, &expected, &policy, now(),)
                .unwrap_err(),
            EnterpriseVerificationError::InvalidClaims,
            "{name}",
        );
    }
    assert!(
        verify_id_jag_with_disclosure(signed("all_disclosures"), &keys, &expected, &policy, now(),)
            .is_ok()
    );
}

#[test]
fn disclosure_permission_cannot_enable_actors_sender_constraints_or_duplicate_members() {
    let keys = keys();
    let expected = expected();
    let policy = policy(&ALL_CLAIMS);
    for name in ["unknown_claim", "cnf", "act"] {
        assert_eq!(
            verify_id_jag_with_disclosure(signed(name), &keys, &expected, &policy, now(),)
                .unwrap_err(),
            EnterpriseVerificationError::InvalidClaims,
            "{name}",
        );
    }
    assert_eq!(
        verify_id_jag_with_disclosure(signed("duplicate_email"), &keys, &expected, &policy, now(),)
            .unwrap_err(),
        EnterpriseVerificationError::InvalidToken,
    );
    for name in [
        "authorization_details",
        "act",
        "sub_id",
        "name",
        "given_name",
        "family_name",
        "preferred_username",
        "cnf",
        "jku",
        "jwk",
        "x5u",
        "iss",
        "sub",
        "aud",
        "client_id",
        "resource",
        "scope",
    ] {
        assert!(IdJagDisclosureClaim::from_name(name).is_none(), "{name}");
    }
}

#[test]
fn optional_claims_do_not_bypass_signature_target_or_signed_expiry_checks() {
    let keys = keys();
    let mut expected = expected();
    let mut config = configuration(&ALL_CLAIMS);
    config.review_expires_at = at(ISSUED + 3600);
    let policy = IdJagDisclosurePolicy::from_trusted_configuration(config).unwrap();
    assert_eq!(
        verify_id_jag_with_disclosure(
            signed("foreign_resource"), &keys, &expected, &policy, now(),
        ).unwrap_err(),
        EnterpriseVerificationError::BindingMismatch,
    );
    expected.client_id = "different-resource-client";
    assert_eq!(
        verify_id_jag_with_disclosure(signed("email"), &keys, &expected, &policy, now(),)
            .unwrap_err(),
        EnterpriseVerificationError::BindingMismatch,
    );
    expected.client_id = "native-resource";
    assert_eq!(
        verify_id_jag_with_disclosure(
            signed("email"), &keys, &expected, &policy, at(ISSUED + 300),
        ).unwrap_err(),
        EnterpriseVerificationError::Expired,
    );
    let (input, signature) = signed("email").rsplit_once('.').unwrap();
    let first = if signature.starts_with('A') { 'B' } else { 'A' };
    let altered = format!("{input}.{first}{}", &signature[1..]);
    assert_eq!(
        verify_id_jag_with_disclosure(&altered, &keys, &expected, &policy, now(),).unwrap_err(),
        EnterpriseVerificationError::InvalidToken,
    );
}

#[test]
fn exact_trust_relationship_and_review_window_have_no_implicit_alias_or_skew() {
    let keys = keys();
    let expected = expected();
    let selected = policy(&[IdJagDisclosureClaim::Email]);
    for time in [at(ISSUED - 5), at(ISSUED + 119)] {
        assert!(
            verify_id_jag_with_disclosure(signed("email"), &keys, &expected, &selected, time,)
                .is_ok()
        );
    }
    for time in [at(ISSUED - 6), at(ISSUED + 120)] {
        assert_eq!(
            verify_id_jag_with_disclosure(signed("email"), &keys, &expected, &selected, time,)
                .unwrap_err(),
            EnterpriseVerificationError::InvalidConfiguration,
        );
    }
    for change_idp in [false, true] {
        let mut config = configuration(&[IdJagDisclosureClaim::Email]);
        if change_idp {
            config.idp_issuer = "https://idp.example/".to_owned();
        } else {
            config.resource_as_issuer = "https://as.example/".to_owned();
        }
        let other = IdJagDisclosurePolicy::from_trusted_configuration(config).unwrap();
        assert_eq!(
            verify_id_jag_with_disclosure(signed("email"), &keys, &expected, &other, now(),)
                .unwrap_err(),
            EnterpriseVerificationError::BindingMismatch,
        );
    }
}

#[test]
fn disclosure_configuration_requires_bounded_reviewed_identity_and_unique_purposes() {
    for mutation in 0..13 {
        let mut config = configuration(&[IdJagDisclosureClaim::Email]);
        match mutation {
            0 => config.generation = 0,
            1 => config.policy_id.clear(),
            2 => config.policy_id = "unreviewed ".to_owned(),
            3 => config.policy_id = "x".repeat(MAX_POLICY_ID_BYTES + 1),
            4 => config.idp_issuer = "http://idp.example".to_owned(),
            5 => config.resource_as_issuer = "https://user@as.example".to_owned(),
            6 => config.reviewed_at = UNIX_EPOCH - Duration::from_secs(1),
            7 => config.review_expires_at = config.reviewed_at,
            8 => {
                config.review_expires_at =
                    config.reviewed_at + MAX_DISCLOSURE_REVIEW_LIFETIME + Duration::from_nanos(1);
            }
            9 => config.rules.push(IdJagDisclosureRule {
                claim: IdJagDisclosureClaim::Email,
                purpose: "Another purpose cannot duplicate an existing claim".to_owned(),
            }),
            10 => config.rules[0].purpose.clear(),
            11 => config.rules[0].purpose = "x".repeat(MAX_PURPOSE_BYTES + 1),
            12 => config.rules[0].purpose = "hidden\ncontrol".to_owned(),
            _ => unreachable!(),
        }
        assert_eq!(
            IdJagDisclosurePolicy::from_trusted_configuration(config).unwrap_err(),
            EnterpriseVerificationError::InvalidConfiguration,
            "mutation {mutation}",
        );
    }
    assert!(IdJagDisclosurePolicy::from_trusted_configuration(configuration(&ALL_CLAIMS)).is_ok());
}

#[test]
fn disclosure_digest_is_order_independent_and_changes_with_each_authority_dimension() {
    let original = policy(&ALL_CLAIMS);
    let mut reordered = configuration(&ALL_CLAIMS);
    reordered.rules.reverse();
    let reordered = IdJagDisclosurePolicy::from_trusted_configuration(reordered).unwrap();
    assert_eq!(
        original.configuration_digest(),
        reordered.configuration_digest()
    );

    for mutation in 0..8 {
        let mut config = configuration(&ALL_CLAIMS);
        match mutation {
            0 => config.policy_id.push_str("-different"),
            1 => config.generation += 1,
            2 => config.idp_issuer.push('/'),
            3 => config.resource_as_issuer.push('/'),
            4 => config.reviewed_at += Duration::from_secs(1),
            5 => config.review_expires_at += Duration::from_secs(1),
            6 => config.rules[0]
                .purpose
                .push_str(" for a different reviewed purpose"),
            7 => {
                config.rules.pop();
            }
            _ => unreachable!(),
        }
        let changed = IdJagDisclosurePolicy::from_trusted_configuration(config).unwrap();
        assert_ne!(
            original.configuration_digest(),
            changed.configuration_digest(),
            "{mutation}"
        );
    }
}

#[test]
fn optional_disclosure_schemas_enforce_exact_size_and_type_boundaries() {
    let policy = policy(&ALL_CLAIMS);
    let methods: Vec<String> = (0..MAX_AUTHENTICATION_METHODS)
        .map(|index| {
            format!(
                "{index:02}{}",
                "m".repeat(MAX_AUTHENTICATION_METHOD_BYTES - 2)
            )
        })
        .collect();
    for (name, value) in [
        ("email", json!("x".repeat(MAX_EMAIL_BYTES))),
        ("acr", json!("x".repeat(MAX_AUTHENTICATION_CONTEXT_BYTES))),
        ("amr", json!(methods)),
        (
            "auth_time",
            serde_json::from_str("2000000000.000000000").unwrap(),
        ),
    ] {
        let mut claims = Map::new();
        claims.insert("iat".to_owned(), json!(ISSUED));
        claims.insert(name.to_owned(), value);
        assert_eq!(
            policy
                .admit_claims(&claims)
                .unwrap()
                .admitted_claims()
                .len(),
            1
        );
    }

    for (name, value) in [
        ("email", json!("")),
        ("email", json!("x".repeat(MAX_EMAIL_BYTES + 1))),
        ("email", Value::Null),
        ("acr", json!(true)),
        (
            "acr",
            json!("x".repeat(MAX_AUTHENTICATION_CONTEXT_BYTES + 1)),
        ),
        ("amr", json!([])),
        ("amr", json!("pwd")),
        ("amr", json!([null])),
        ("amr", json!(["pwd", "pwd"])),
        (
            "amr",
            json!(["x".repeat(MAX_AUTHENTICATION_METHOD_BYTES + 1)]),
        ),
        (
            "amr",
            json!(
                (0..=MAX_AUTHENTICATION_METHODS)
                    .map(|index| format!("method-{index}"))
                    .collect::<Vec<_>>()
            ),
        ),
        ("auth_time", json!("2000000000")),
        ("auth_time", json!(ISSUED + 1)),
        ("auth_time", serde_json::from_str("-0").unwrap()),
        (
            "auth_time",
            serde_json::from_str("1999999999.0000000001").unwrap(),
        ),
    ] {
        let mut claims = Map::new();
        claims.insert("iat".to_owned(), json!(ISSUED));
        claims.insert(name.to_owned(), value);
        assert_eq!(
            policy.admit_claims(&claims).unwrap_err(),
            EnterpriseVerificationError::InvalidClaims,
            "{name}",
        );
    }
}