exochain-gatekeeper 0.2.0-beta

EXOCHAIN judicial branch — CGR kernel, combinator algebra, invariant enforcement, Holon runtime, MCP middleware
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
// Copyright 2026 Exochain Foundation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at:
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// SPDX-License-Identifier: Apache-2.0

//! Model Context Protocol (MCP) enforcement.
//!
//! Ensures AI systems operating within the EXOCHAIN fabric respect
//! constitutional boundaries on autonomy, identity, and consent.
//!
//! **Key design**: The `SignerType` enum is part of a domain-separated
//! canonical CBOR signed payload, not a caller-set flag. Even if an AI has
//! valid key material, it cannot produce a signature that could be mistaken
//! for a human signature.

use exo_core::{Did, SignerType};
use serde::{Deserialize, Serialize};

use crate::{error::GatekeeperError, types::PermissionSet};

const MCP_TYPED_SIGNATURE_DOMAIN: &str = "exo.gatekeeper.mcp.typed-signature.v1";
const MCP_TYPED_SIGNATURE_SCHEMA_VERSION: u16 = 1;

#[derive(Serialize)]
struct McpTypedSignaturePayload<'a> {
    domain: &'static str,
    schema_version: u16,
    signer_type: &'a SignerType,
    message: &'a [u8],
}

// ---------------------------------------------------------------------------
// MCP rules
// ---------------------------------------------------------------------------

/// Constitutional rules governing AI behavior within the EXOCHAIN fabric.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum McpRule {
    Mcp001BctsScope,
    Mcp002NoSelfEscalation,
    Mcp003ProvenanceRequired,
    Mcp004NoIdentityForge,
    Mcp005Distinguishable,
    Mcp006ConsentBoundaries,
}

impl McpRule {
    #[must_use]
    pub fn all() -> Vec<McpRule> {
        vec![
            McpRule::Mcp001BctsScope,
            McpRule::Mcp002NoSelfEscalation,
            McpRule::Mcp003ProvenanceRequired,
            McpRule::Mcp004NoIdentityForge,
            McpRule::Mcp005Distinguishable,
            McpRule::Mcp006ConsentBoundaries,
        ]
    }

    #[must_use]
    pub fn id(&self) -> &'static str {
        match self {
            McpRule::Mcp001BctsScope => "mcp-001-bcts-scope",
            McpRule::Mcp002NoSelfEscalation => "mcp-002-no-self-escalation",
            McpRule::Mcp003ProvenanceRequired => "mcp-003-provenance-required",
            McpRule::Mcp004NoIdentityForge => "mcp-004-no-identity-forge",
            McpRule::Mcp005Distinguishable => "mcp-005-distinguishable",
            McpRule::Mcp006ConsentBoundaries => "mcp-006-consent-boundaries",
        }
    }

    #[must_use]
    pub fn description(&self) -> &'static str {
        match self {
            McpRule::Mcp001BctsScope => "AI must operate within BCTS scope",
            McpRule::Mcp002NoSelfEscalation => "AI cannot self-escalate capabilities",
            McpRule::Mcp003ProvenanceRequired => "AI actions require provenance metadata",
            McpRule::Mcp004NoIdentityForge => "AI cannot forge identity or signatures",
            McpRule::Mcp005Distinguishable => "AI outputs must be distinguishable from human",
            McpRule::Mcp006ConsentBoundaries => "AI must respect consent boundaries",
        }
    }
}

// ---------------------------------------------------------------------------
// MCP context — uses cryptographic SignerType, not a bool flag
// ---------------------------------------------------------------------------

/// Context describing an AI actor's action, used for MCP rule enforcement.
#[derive(Debug, Clone)]
pub struct McpContext {
    pub actor_did: Did,
    /// Cryptographic signer type — embedded in the signed payload.
    /// Replaces the old `is_ai: bool` with a type that is part of the
    /// signature itself, preventing AI impersonation of human signers.
    pub signer_type: SignerType,
    pub bcts_scope: Option<String>,
    pub capabilities: PermissionSet,
    pub action: String,
    pub has_provenance: bool,
    pub forging_identity: bool,
    pub output_marked_ai: bool,
    pub consent_active: bool,
    pub self_escalation: bool,
}

impl McpContext {
    /// Whether this actor is an AI (derived from the cryptographic signer type).
    #[must_use]
    pub fn is_ai(&self) -> bool {
        self.signer_type.is_ai()
    }
}

// ---------------------------------------------------------------------------
// MCP violation
// ---------------------------------------------------------------------------

/// A violation produced when an AI action breaches an MCP rule.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct McpViolation {
    pub rule: McpRule,
    pub description: String,
    pub evidence: Vec<String>,
    pub severity: u8,
}

// ---------------------------------------------------------------------------
// Enforcement
// ---------------------------------------------------------------------------

/// Check all given MCP rules against the context, returning the first violation (if any).
pub fn enforce(rules: &[McpRule], context: &McpContext) -> Result<(), McpViolation> {
    if !context.is_ai() {
        return Ok(());
    }
    for rule in rules {
        check_rule(*rule, context)?;
    }
    Ok(())
}

fn check_rule(rule: McpRule, ctx: &McpContext) -> Result<(), McpViolation> {
    match rule {
        McpRule::Mcp001BctsScope => {
            if ctx.bcts_scope.is_none() {
                return Err(McpViolation {
                    rule,
                    description: "AI operating outside BCTS scope".into(),
                    evidence: vec![format!("actor: {}", ctx.actor_did)],
                    severity: 5,
                });
            }
            Ok(())
        }
        McpRule::Mcp002NoSelfEscalation => {
            if ctx.self_escalation {
                return Err(McpViolation {
                    rule,
                    description: "AI attempted self-escalation".into(),
                    evidence: vec![
                        format!("actor: {}", ctx.actor_did),
                        format!("action: {}", ctx.action),
                    ],
                    severity: 5,
                });
            }
            Ok(())
        }
        McpRule::Mcp003ProvenanceRequired => {
            if !ctx.has_provenance {
                return Err(McpViolation {
                    rule,
                    description: "AI action lacks provenance".into(),
                    evidence: vec![format!("action: {}", ctx.action)],
                    severity: 4,
                });
            }
            Ok(())
        }
        McpRule::Mcp004NoIdentityForge => {
            if ctx.forging_identity {
                return Err(McpViolation {
                    rule,
                    description: "AI attempted identity forge".into(),
                    evidence: vec![format!("actor: {}", ctx.actor_did)],
                    severity: 5,
                });
            }
            Ok(())
        }
        McpRule::Mcp005Distinguishable => {
            if !ctx.output_marked_ai {
                return Err(McpViolation {
                    rule,
                    description: "AI output not marked".into(),
                    evidence: vec![format!("action: {}", ctx.action)],
                    severity: 3,
                });
            }
            Ok(())
        }
        McpRule::Mcp006ConsentBoundaries => {
            if !ctx.consent_active {
                return Err(McpViolation {
                    rule,
                    description: "AI operating without consent".into(),
                    evidence: vec![format!("actor: {}", ctx.actor_did)],
                    severity: 5,
                });
            }
            Ok(())
        }
    }
}

/// Build a signable message that embeds the signer type.
///
/// The payload is a versioned, domain-separated canonical CBOR envelope so
/// signer identity is cryptographically bound without raw byte concatenation.
pub fn build_signed_payload(
    signer_type: &SignerType,
    message: &[u8],
) -> Result<Vec<u8>, GatekeeperError> {
    let payload = McpTypedSignaturePayload {
        domain: MCP_TYPED_SIGNATURE_DOMAIN,
        schema_version: MCP_TYPED_SIGNATURE_SCHEMA_VERSION,
        signer_type,
        message,
    };
    let mut encoded = Vec::new();
    ciborium::ser::into_writer(&payload, &mut encoded).map_err(|error| {
        GatekeeperError::McpTypedSignatureEncodingFailed {
            reason: error.to_string(),
        }
    })?;
    Ok(encoded)
}

/// Verify that a signature was produced with the claimed signer type.
/// The signer type is embedded in the canonical signed payload before verification.
#[must_use]
pub fn verify_typed_signature(
    signer_type: &SignerType,
    message: &[u8],
    signature: &exo_core::Signature,
    public_key: &exo_core::PublicKey,
) -> bool {
    match build_signed_payload(signer_type, message) {
        Ok(payload) => exo_core::crypto::verify(&payload, signature, public_key),
        Err(_) => false,
    }
}

// ===========================================================================
// Tests
// ===========================================================================

#[cfg(test)]
mod tests {
    use exo_core::{Hash256, crypto::KeyPair};
    use serde::Deserialize;

    use super::*;
    use crate::types::Permission;

    fn production_source() -> &'static str {
        let source = include_str!("mcp.rs");
        let end = source
            .find("// ===========================================================================")
            .expect("tests section marker must exist");
        &source[..end]
    }

    fn did(s: &str) -> Did {
        Did::new(s).expect("valid DID")
    }

    fn valid_ai() -> McpContext {
        McpContext {
            actor_did: did("did:exo:ai-agent-1"),
            signer_type: SignerType::Ai {
                delegation_id: Hash256::digest(b"delegation-1"),
            },
            bcts_scope: Some("data:medical".into()),
            capabilities: PermissionSet::new(vec![Permission::new("read")]),
            action: "summarize".into(),
            has_provenance: true,
            forging_identity: false,
            output_marked_ai: true,
            consent_active: true,
            self_escalation: false,
        }
    }

    fn human() -> McpContext {
        McpContext {
            actor_did: did("did:exo:human-1"),
            signer_type: SignerType::Human,
            bcts_scope: None,
            capabilities: PermissionSet::default(),
            action: "anything".into(),
            has_provenance: false,
            forging_identity: false,
            output_marked_ai: false,
            consent_active: false,
            self_escalation: false,
        }
    }

    #[test]
    fn all_pass_valid_ai() {
        assert!(enforce(&McpRule::all(), &valid_ai()).is_ok());
    }
    #[test]
    fn human_exempt() {
        assert!(enforce(&McpRule::all(), &human()).is_ok());
    }

    #[test]
    fn mcp001_fail() {
        let mut c = valid_ai();
        c.bcts_scope = None;
        let e = enforce(&[McpRule::Mcp001BctsScope], &c).unwrap_err();
        assert_eq!(e.rule, McpRule::Mcp001BctsScope);
        assert_eq!(e.severity, 5);
    }
    #[test]
    fn mcp001_pass() {
        assert!(enforce(&[McpRule::Mcp001BctsScope], &valid_ai()).is_ok());
    }

    #[test]
    fn mcp002_fail() {
        let mut c = valid_ai();
        c.self_escalation = true;
        assert_eq!(
            enforce(&[McpRule::Mcp002NoSelfEscalation], &c)
                .unwrap_err()
                .rule,
            McpRule::Mcp002NoSelfEscalation
        );
    }
    #[test]
    fn mcp002_pass() {
        assert!(enforce(&[McpRule::Mcp002NoSelfEscalation], &valid_ai()).is_ok());
    }

    #[test]
    fn mcp003_fail() {
        let mut c = valid_ai();
        c.has_provenance = false;
        let e = enforce(&[McpRule::Mcp003ProvenanceRequired], &c).unwrap_err();
        assert_eq!(e.rule, McpRule::Mcp003ProvenanceRequired);
        assert_eq!(e.severity, 4);
    }
    #[test]
    fn mcp003_pass() {
        assert!(enforce(&[McpRule::Mcp003ProvenanceRequired], &valid_ai()).is_ok());
    }

    #[test]
    fn mcp004_fail() {
        let mut c = valid_ai();
        c.forging_identity = true;
        assert_eq!(
            enforce(&[McpRule::Mcp004NoIdentityForge], &c)
                .unwrap_err()
                .rule,
            McpRule::Mcp004NoIdentityForge
        );
    }
    #[test]
    fn mcp004_pass() {
        assert!(enforce(&[McpRule::Mcp004NoIdentityForge], &valid_ai()).is_ok());
    }

    #[test]
    fn mcp005_fail() {
        let mut c = valid_ai();
        c.output_marked_ai = false;
        let e = enforce(&[McpRule::Mcp005Distinguishable], &c).unwrap_err();
        assert_eq!(e.rule, McpRule::Mcp005Distinguishable);
        assert_eq!(e.severity, 3);
    }
    #[test]
    fn mcp005_pass() {
        assert!(enforce(&[McpRule::Mcp005Distinguishable], &valid_ai()).is_ok());
    }

    #[test]
    fn mcp006_fail() {
        let mut c = valid_ai();
        c.consent_active = false;
        assert_eq!(
            enforce(&[McpRule::Mcp006ConsentBoundaries], &c)
                .unwrap_err()
                .rule,
            McpRule::Mcp006ConsentBoundaries
        );
    }
    #[test]
    fn mcp006_pass() {
        assert!(enforce(&[McpRule::Mcp006ConsentBoundaries], &valid_ai()).is_ok());
    }

    #[test]
    fn first_violation_returned() {
        let mut c = valid_ai();
        c.bcts_scope = None;
        c.has_provenance = false;
        assert_eq!(
            enforce(
                &[McpRule::Mcp001BctsScope, McpRule::Mcp003ProvenanceRequired],
                &c
            )
            .unwrap_err()
            .rule,
            McpRule::Mcp001BctsScope
        );
    }
    #[test]
    fn empty_rules_pass() {
        assert!(enforce(&[], &valid_ai()).is_ok());
    }
    #[test]
    fn all_six_rules() {
        assert_eq!(McpRule::all().len(), 6);
    }
    #[test]
    fn descriptions_non_empty() {
        for r in McpRule::all() {
            assert!(!r.description().is_empty());
        }
    }
    #[test]
    fn rule_ids_are_stable_and_non_debug() {
        assert_eq!(McpRule::Mcp001BctsScope.id(), "mcp-001-bcts-scope");
        for r in McpRule::all() {
            assert!(r.id().starts_with("mcp-00"));
            assert!(
                !r.id().contains("Mcp"),
                "stable MCP rule IDs must not mirror Rust Debug variant names"
            );
        }
    }

    // -- Cryptographic AI identity binding tests --

    #[test]
    fn ai_cannot_impersonate_human() {
        // An AI signs a message with the AI prefix, then tries to verify
        // it as a human-signed message. This MUST fail.
        let kp = KeyPair::generate();
        let message = b"important governance vote";

        // AI signs with AI prefix
        let ai_type = SignerType::Ai {
            delegation_id: Hash256::digest(b"session-1"),
        };
        let ai_payload = build_signed_payload(&ai_type, message).expect("AI payload encodes");
        let ai_sig = kp.sign(&ai_payload);

        // Verify as AI — should succeed
        assert!(verify_typed_signature(
            &ai_type,
            message,
            &ai_sig,
            kp.public_key()
        ));

        // Try to verify same signature as human — MUST fail
        assert!(!verify_typed_signature(
            &SignerType::Human,
            message,
            &ai_sig,
            kp.public_key()
        ));
    }

    #[test]
    fn human_signature_cannot_be_replayed_as_ai() {
        let kp = KeyPair::generate();
        let message = b"budget approval";

        // Human signs
        let human_payload =
            build_signed_payload(&SignerType::Human, message).expect("human payload encodes");
        let human_sig = kp.sign(&human_payload);

        // Verify as human — should succeed
        assert!(verify_typed_signature(
            &SignerType::Human,
            message,
            &human_sig,
            kp.public_key()
        ));

        // Try to verify as AI — MUST fail
        let ai_type = SignerType::Ai {
            delegation_id: Hash256::digest(b"d"),
        };
        assert!(!verify_typed_signature(
            &ai_type,
            message,
            &human_sig,
            kp.public_key()
        ));
    }

    #[test]
    fn different_delegation_ids_produce_different_signatures() {
        let kp = KeyPair::generate();
        let message = b"action";

        let ai1 = SignerType::Ai {
            delegation_id: Hash256::digest(b"delegation-A"),
        };
        let ai2 = SignerType::Ai {
            delegation_id: Hash256::digest(b"delegation-B"),
        };

        let payload1 = build_signed_payload(&ai1, message).expect("AI payload encodes");
        let payload2 = build_signed_payload(&ai2, message).expect("AI payload encodes");
        assert_ne!(payload1, payload2);

        let sig1 = kp.sign(&payload1);
        // sig1 verifies under ai1 but NOT under ai2
        assert!(verify_typed_signature(
            &ai1,
            message,
            &sig1,
            kp.public_key()
        ));
        assert!(!verify_typed_signature(
            &ai2,
            message,
            &sig1,
            kp.public_key()
        ));
    }

    #[test]
    fn typed_signature_payload_is_domain_separated_versioned_cbor() {
        #[derive(Debug, Deserialize, PartialEq, Eq)]
        struct TypedSignaturePayload {
            domain: String,
            schema_version: u16,
            signer_type: SignerType,
            message: Vec<u8>,
        }

        let signer_type = SignerType::Ai {
            delegation_id: Hash256::digest(b"typed-signature-session"),
        };
        let message = b"constitutional MCP action";

        let payload = build_signed_payload(&signer_type, message).expect("payload encodes");
        let decoded: TypedSignaturePayload =
            ciborium::from_reader(payload.as_slice()).expect("typed signature payload is CBOR");

        assert_eq!(decoded.domain, "exo.gatekeeper.mcp.typed-signature.v1");
        assert_eq!(decoded.schema_version, 1);
        assert_eq!(decoded.signer_type, signer_type);
        assert_eq!(decoded.message, message);
    }

    #[test]
    fn typed_signature_payload_source_uses_cbor_not_raw_concatenation() {
        let production = production_source();
        let start = production
            .find("pub fn build_signed_payload")
            .expect("build_signed_payload exists");
        let end = production
            .find("/// Verify that a signature was produced with the claimed signer type.")
            .expect("verify_typed_signature marker exists");
        let body = &production[start..end];

        assert!(
            body.contains("ciborium::"),
            "typed signature payloads must use canonical CBOR"
        );
        assert!(
            !body.contains("extend_from_slice"),
            "typed signature payloads must not be raw byte concatenations"
        );
        assert!(
            !body.contains("to_payload_prefix"),
            "typed signature payloads must bind the structured signer type, not an ad hoc prefix"
        );
        assert!(
            !body.contains("return Vec::new()"),
            "typed signature serialization must not silently fall back to an empty payload"
        );
    }

    #[test]
    fn signer_type_prefix_bytes() {
        assert_eq!(SignerType::Human.prefix_byte(), 0x01);
        let ai = SignerType::Ai {
            delegation_id: Hash256::ZERO,
        };
        assert_eq!(ai.prefix_byte(), 0x02);
        assert_eq!(ai.to_payload_prefix().len(), 33); // 1 prefix + 32 hash
    }

    #[test]
    fn signer_type_is_checks() {
        assert!(SignerType::Human.is_human());
        assert!(!SignerType::Human.is_ai());
        let ai = SignerType::Ai {
            delegation_id: Hash256::ZERO,
        };
        assert!(ai.is_ai());
        assert!(!ai.is_human());
    }

    #[test]
    fn context_is_ai_derived() {
        assert!(valid_ai().is_ai());
        assert!(!human().is_ai());
    }
}