kanoniv-agent-auth 0.3.0

Sudo for AI agents - cryptographic delegation, Ed25519 identity, and signed audit trails
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
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
//! Cryptographic delegation with attenuated capabilities.
//!
//! Implements Macaroon-style delegation where an agent can grant another agent
//! a subset of its authority, with constraints (caveats). Delegations chain:
//! Agent A delegates to B, who delegates to C, each adding restrictions.
//! Verification walks the chain back to the root, checking every signature
//! and every caveat. No server calls required.
//!
//! # Concepts
//!
//! - **Delegation**: "I grant you power X with restrictions Y" (reusable)
//! - **Invocation**: "I'm using power X, here's my proof" (single-use action)
//! - **Caveat**: A constraint on what the delegated power can do
//! - **Chain**: A linked list of delegations from invoker back to root authority

use serde::{Deserialize, Serialize};

use crate::identity::{AgentIdentity, AgentKeyPair};
use crate::signing::SignedMessage;
use crate::CryptoError;

/// A constraint on delegated authority.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(tag = "type", content = "value")]
pub enum Caveat {
    /// Restrict to specific actions (e.g. ["resolve", "search"]).
    #[serde(rename = "action_scope")]
    ActionScope(Vec<String>),

    /// Delegation expires at this RFC 3339 timestamp.
    #[serde(rename = "expires_at")]
    ExpiresAt(String),

    /// Maximum cost ceiling for the delegated operation.
    #[serde(rename = "max_cost")]
    MaxCost(f64),

    /// Resource pattern the delegation applies to (glob-style).
    /// E.g. "entity:customer:*", "source:crm:*"
    #[serde(rename = "resource")]
    Resource(String),

    /// Restrict to a specific context (e.g. task_id, session_id).
    #[serde(rename = "context")]
    Context { key: String, value: String },

    /// Arbitrary user-defined caveat.
    #[serde(rename = "custom")]
    Custom {
        key: String,
        value: serde_json::Value,
    },
}

/// A cryptographic delegation of authority from one agent to another.
///
/// Delegations form a chain: each delegation optionally references a parent
/// delegation that granted the issuer their authority. The chain terminates
/// at the root authority (who needs no parent delegation).
/// Maximum delegation chain depth to prevent DoS via deeply nested chains.
pub const MAX_CHAIN_DEPTH: usize = 32;

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Delegation {
    /// DID of the agent granting authority
    pub issuer_did: String,
    /// DID of the agent receiving authority
    pub delegate_did: String,
    /// Issuer's public key bytes (for self-verifying chains without key resolver)
    pub issuer_public_key: Vec<u8>,
    /// Constraints on the delegated authority
    pub caveats: Vec<Caveat>,
    /// Parent delegation proving the issuer's authority (None for root)
    pub parent_proof: Option<Box<Delegation>>,
    /// Cryptographic proof (signed by issuer)
    pub proof: SignedMessage,
}

impl Delegation {
    /// Create and sign a new root delegation (no parent).
    ///
    /// The issuer is the root authority and does not need a parent delegation.
    pub fn create_root(
        issuer_keypair: &AgentKeyPair,
        delegate_did: &str,
        caveats: Vec<Caveat>,
    ) -> Result<Self, CryptoError> {
        let issuer_identity = issuer_keypair.identity();
        Self::create_inner(
            issuer_keypair,
            &issuer_identity.did,
            delegate_did,
            caveats,
            None,
        )
    }

    /// Create and sign a delegated delegation (with parent chain).
    ///
    /// The issuer must have been granted authority via the parent delegation.
    /// Additional caveats can only narrow the authority, never widen it.
    pub fn delegate(
        issuer_keypair: &AgentKeyPair,
        delegate_did: &str,
        additional_caveats: Vec<Caveat>,
        parent: Delegation,
    ) -> Result<Self, CryptoError> {
        let issuer_identity = issuer_keypair.identity();

        // Issuer must be the delegate of the parent delegation
        if parent.delegate_did != issuer_identity.did {
            return Err(CryptoError::DelegationChainBroken(
                "issuer is not the delegate of parent delegation".into(),
            ));
        }

        // Merge parent caveats with additional caveats (union of restrictions)
        let mut all_caveats = parent.caveats.clone();
        all_caveats.extend(additional_caveats);

        Self::create_inner(
            issuer_keypair,
            &issuer_identity.did,
            delegate_did,
            all_caveats,
            Some(Box::new(parent)),
        )
    }

    fn create_inner(
        issuer_keypair: &AgentKeyPair,
        issuer_did: &str,
        delegate_did: &str,
        caveats: Vec<Caveat>,
        parent: Option<Box<Delegation>>,
    ) -> Result<Self, CryptoError> {
        // Check chain depth limit
        if let Some(ref p) = parent {
            if p.depth() >= MAX_CHAIN_DEPTH {
                return Err(CryptoError::DelegationChainBroken(format!(
                    "chain depth exceeds maximum of {}",
                    MAX_CHAIN_DEPTH
                )));
            }
        }

        let issuer_identity = issuer_keypair.identity();
        let parent_hash = parent.as_ref().map(|p| p.proof.content_hash());

        let payload = serde_json::json!({
            "issuer_did": issuer_did,
            "delegate_did": delegate_did,
            "caveats": caveats,
            "parent_hash": parent_hash,
        });

        let proof = SignedMessage::sign(issuer_keypair, payload)?;

        Ok(Self {
            issuer_did: issuer_did.to_string(),
            delegate_did: delegate_did.to_string(),
            issuer_public_key: issuer_identity.public_key_bytes.clone(),
            caveats,
            parent_proof: parent,
            proof,
        })
    }

    /// Get the chain depth (0 for root, 1 for first delegation, etc.)
    pub fn depth(&self) -> usize {
        let mut depth = 0;
        let mut current = self;
        while let Some(ref parent) = current.parent_proof {
            depth += 1;
            current = parent;
        }
        depth
    }
}

/// An invocation: an agent exercising delegated authority.
///
/// Combines the action being performed with the delegation chain
/// that proves the agent has authority to perform it.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Invocation {
    /// DID of the agent performing the action
    pub invoker_did: String,
    /// The action being performed
    pub action: String,
    /// Action arguments / context
    pub args: serde_json::Value,
    /// The delegation chain proving authority
    pub delegation: Delegation,
    /// Cryptographic proof (signed by invoker)
    pub proof: SignedMessage,
}

impl Invocation {
    /// Create and sign an invocation.
    ///
    /// The invoker must be the delegate of the delegation.
    pub fn create(
        invoker_keypair: &AgentKeyPair,
        action: &str,
        args: serde_json::Value,
        delegation: Delegation,
    ) -> Result<Self, CryptoError> {
        let invoker_identity = invoker_keypair.identity();

        if delegation.delegate_did != invoker_identity.did {
            return Err(CryptoError::DelegationChainBroken(
                "invoker is not the delegate of the delegation".into(),
            ));
        }

        let payload = serde_json::json!({
            "invoker_did": invoker_identity.did,
            "action": action,
            "args": args,
            "delegation_hash": delegation.proof.content_hash(),
        });

        let proof = SignedMessage::sign(invoker_keypair, payload)?;

        Ok(Self {
            invoker_did: invoker_identity.did,
            action: action.to_string(),
            args,
            delegation,
            proof,
        })
    }
}

/// Result of a successful verification, containing the full authority chain.
#[derive(Debug)]
pub struct VerificationResult {
    /// The invoker's DID
    pub invoker_did: String,
    /// The root authority's DID
    pub root_did: String,
    /// The chain of DIDs from invoker back to root
    pub chain: Vec<String>,
    /// The chain depth
    pub depth: usize,
}

/// Verify an invocation's entire authority chain (no revocation check).
///
/// For revocation support, use `verify_invocation_with_revocation` instead.
pub fn verify_invocation(
    invocation: &Invocation,
    invoker_identity: &AgentIdentity,
    root_identity: &AgentIdentity,
) -> Result<VerificationResult, CryptoError> {
    verify_invocation_with_revocation(invocation, invoker_identity, root_identity, |_| false)
}

/// Verify an invocation's entire authority chain with optional revocation check.
///
/// Checks:
/// 1. Invocation signature is valid for the invoker
/// 2. Invoker is the delegate of the delegation
/// 3. **Every** delegation signature is verified (using embedded public keys)
/// 4. Each delegation's issuer is the delegate of its parent
/// 5. Embedded public keys match their DIDs
/// 6. No delegation in the chain has been revoked
/// 7. The chain terminates at the expected root authority
/// 8. All caveats are satisfied for the invoked action
///
/// The `is_revoked` callback receives a delegation's content hash and returns
/// `true` if that delegation has been revoked. Use `|_| false` to skip
/// revocation checks, or provide a lookup against your revocation service.
pub fn verify_invocation_with_revocation(
    invocation: &Invocation,
    invoker_identity: &AgentIdentity,
    root_identity: &AgentIdentity,
    is_revoked: impl Fn(&str) -> bool,
) -> Result<VerificationResult, CryptoError> {
    // 1. Verify invocation signature
    invocation.proof.verify(invoker_identity)?;

    // 2. Verify invoker matches delegation delegate
    if invocation.invoker_did != invocation.delegation.delegate_did {
        return Err(CryptoError::DelegationChainBroken(
            "invoker is not the delegate of the delegation".into(),
        ));
    }

    // 3. Walk and verify the full delegation chain
    let mut chain = vec![invocation.invoker_did.clone()];
    let mut current = &invocation.delegation;
    let mut all_caveats: Vec<Caveat> = Vec::new();
    let mut steps = 0usize;

    loop {
        steps += 1;
        if steps > MAX_CHAIN_DEPTH {
            return Err(CryptoError::DelegationChainBroken(format!(
                "chain depth exceeds maximum of {}",
                MAX_CHAIN_DEPTH
            )));
        }

        chain.push(current.issuer_did.clone());

        // Reconstruct issuer identity from embedded public key
        let issuer_identity =
            AgentIdentity::from_bytes(&current.issuer_public_key).map_err(|_| {
                CryptoError::DelegationChainBroken(format!(
                    "invalid embedded public key for '{}'",
                    current.issuer_did
                ))
            })?;

        // Verify the embedded public key matches the claimed DID
        if issuer_identity.did != current.issuer_did {
            return Err(CryptoError::DelegationChainBroken(format!(
                "embedded public key produces DID '{}' but delegation claims '{}'",
                issuer_identity.did, current.issuer_did
            )));
        }

        // Verify this delegation's signature using the embedded public key
        current.proof.verify(&issuer_identity)?;

        // Check if this delegation has been revoked
        let delegation_hash = current.proof.content_hash();
        if is_revoked(&delegation_hash) {
            return Err(CryptoError::DelegationRevoked(delegation_hash));
        }

        // Extract caveats from the SIGNED PAYLOAD (not outer fields) to prevent tampering
        if let Some(signed_caveats) = current.proof.payload.get("caveats") {
            if let Ok(caveats) = serde_json::from_value::<Vec<Caveat>>(signed_caveats.clone()) {
                all_caveats.extend(caveats);
            }
        }

        // Check chain linkage
        if current.issuer_did == root_identity.did {
            // Reached root - verify it matches the expected root identity
            if issuer_identity.public_key_bytes != root_identity.public_key_bytes {
                return Err(CryptoError::DelegationChainBroken(
                    "root public key mismatch".into(),
                ));
            }
            break;
        }

        // Not root - must have a parent proof
        match &current.parent_proof {
            Some(parent) => {
                if parent.delegate_did != current.issuer_did {
                    return Err(CryptoError::DelegationChainBroken(format!(
                        "delegation issuer '{}' is not the delegate of parent delegation '{}'",
                        current.issuer_did, parent.delegate_did
                    )));
                }
                current = parent;
            }
            None => {
                return Err(CryptoError::DelegationChainBroken(format!(
                    "chain terminates at '{}', expected root '{}'",
                    current.issuer_did, root_identity.did
                )));
            }
        }
    }

    // 4. Check all caveats (from signed payloads) against the invocation
    let now = chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Millis, true);
    for caveat in &all_caveats {
        check_caveat(caveat, &invocation.action, &invocation.args, &now)?;
    }

    let depth = chain.len() - 1;
    Ok(VerificationResult {
        invoker_did: invocation.invoker_did.clone(),
        root_did: root_identity.did.clone(),
        chain,
        depth,
    })
}

/// Verify a delegation chain without an invocation (no revocation check).
pub fn verify_delegation_chain(
    delegation: &Delegation,
    root_identity: &AgentIdentity,
) -> Result<Vec<String>, CryptoError> {
    verify_delegation_chain_with_revocation(delegation, root_identity, |_| false)
}

/// Verify a delegation chain with optional revocation check.
///
/// Verifies every signature in the chain using embedded public keys.
pub fn verify_delegation_chain_with_revocation(
    delegation: &Delegation,
    root_identity: &AgentIdentity,
    is_revoked: impl Fn(&str) -> bool,
) -> Result<Vec<String>, CryptoError> {
    let mut chain = Vec::new();
    let mut current = delegation;
    let mut steps = 0usize;

    loop {
        steps += 1;
        if steps > MAX_CHAIN_DEPTH {
            return Err(CryptoError::DelegationChainBroken(format!(
                "chain depth exceeds maximum of {}",
                MAX_CHAIN_DEPTH
            )));
        }

        chain.push(current.delegate_did.clone());
        chain.push(current.issuer_did.clone());

        // Verify signature using embedded public key
        let issuer_identity =
            AgentIdentity::from_bytes(&current.issuer_public_key).map_err(|_| {
                CryptoError::DelegationChainBroken(format!(
                    "invalid embedded public key for '{}'",
                    current.issuer_did
                ))
            })?;

        if issuer_identity.did != current.issuer_did {
            return Err(CryptoError::DelegationChainBroken(format!(
                "embedded public key produces DID '{}' but delegation claims '{}'",
                issuer_identity.did, current.issuer_did
            )));
        }

        current.proof.verify(&issuer_identity)?;

        let delegation_hash = current.proof.content_hash();
        if is_revoked(&delegation_hash) {
            return Err(CryptoError::DelegationRevoked(delegation_hash));
        }

        if current.issuer_did == root_identity.did {
            if issuer_identity.public_key_bytes != root_identity.public_key_bytes {
                return Err(CryptoError::DelegationChainBroken(
                    "root public key mismatch".into(),
                ));
            }
            break;
        }

        match &current.parent_proof {
            Some(parent) => {
                if parent.delegate_did != current.issuer_did {
                    return Err(CryptoError::DelegationChainBroken(
                        "chain linkage broken: issuer not delegate of parent".into(),
                    ));
                }
                current = parent;
            }
            None => {
                return Err(CryptoError::DelegationChainBroken(format!(
                    "chain terminates at '{}', expected root '{}'",
                    current.issuer_did, root_identity.did
                )));
            }
        }
    }

    chain.dedup();
    Ok(chain)
}

fn check_caveat(
    caveat: &Caveat,
    action: &str,
    args: &serde_json::Value,
    now: &str,
) -> Result<(), CryptoError> {
    match caveat {
        Caveat::ActionScope(allowed) => {
            if !allowed.iter().any(|a| a == action) {
                return Err(CryptoError::CaveatViolation(format!(
                    "action '{}' not in allowed scope {:?}",
                    action, allowed
                )));
            }
        }
        Caveat::ExpiresAt(expiry) => {
            if now > expiry.as_str() {
                return Err(CryptoError::CaveatViolation(format!(
                    "delegation expired at {}",
                    expiry
                )));
            }
        }
        Caveat::MaxCost(max) => match args.get("cost").and_then(|v| v.as_f64()) {
            Some(cost) if cost > *max => {
                return Err(CryptoError::CaveatViolation(format!(
                    "cost {} exceeds max {}",
                    cost, max
                )));
            }
            None => {
                return Err(CryptoError::CaveatViolation(
                    "max_cost caveat requires 'cost' field in args".into(),
                ));
            }
            _ => {}
        },
        Caveat::Resource(pattern) => match args.get("resource").and_then(|v| v.as_str()) {
            Some(resource) if !matches_glob(pattern, resource) => {
                return Err(CryptoError::CaveatViolation(format!(
                    "resource '{}' does not match pattern '{}'",
                    resource, pattern
                )));
            }
            None => {
                return Err(CryptoError::CaveatViolation(
                    "resource caveat requires 'resource' field in args".into(),
                ));
            }
            _ => {}
        },
        Caveat::Context { key, value } => {
            let actual = args.get(key).and_then(|v| v.as_str());
            if actual != Some(value.as_str()) {
                return Err(CryptoError::CaveatViolation(format!(
                    "context '{}' expected '{}', got '{}'",
                    key,
                    value,
                    actual.unwrap_or("<missing>")
                )));
            }
        }
        Caveat::Custom { key, value } => {
            let actual = args.get(key);
            if actual != Some(value) {
                return Err(CryptoError::CaveatViolation(format!(
                    "custom caveat '{}' not satisfied",
                    key
                )));
            }
        }
    }
    Ok(())
}

/// Simple glob matching: supports trailing * only.
/// E.g. "entity:customer:*" matches "entity:customer:123"
fn matches_glob(pattern: &str, value: &str) -> bool {
    if let Some(prefix) = pattern.strip_suffix('*') {
        value.starts_with(prefix)
    } else {
        pattern == value
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn keypair() -> AgentKeyPair {
        AgentKeyPair::generate()
    }

    // --- Delegation creation ---

    #[test]
    fn test_root_delegation() {
        let root = keypair();
        let agent_b = keypair();

        let delegation = Delegation::create_root(
            &root,
            &agent_b.identity().did,
            vec![Caveat::ActionScope(vec!["resolve".into(), "search".into()])],
        )
        .unwrap();

        assert_eq!(delegation.issuer_did, root.identity().did);
        assert_eq!(delegation.delegate_did, agent_b.identity().did);
        assert_eq!(delegation.depth(), 0);
        assert!(delegation.parent_proof.is_none());
    }

    #[test]
    fn test_chained_delegation() {
        let root = keypair();
        let agent_b = keypair();
        let agent_c = keypair();

        let d1 = Delegation::create_root(
            &root,
            &agent_b.identity().did,
            vec![Caveat::ActionScope(vec!["resolve".into(), "search".into()])],
        )
        .unwrap();

        let d2 = Delegation::delegate(
            &agent_b,
            &agent_c.identity().did,
            vec![], // no additional restrictions
            d1,
        )
        .unwrap();

        assert_eq!(d2.issuer_did, agent_b.identity().did);
        assert_eq!(d2.delegate_did, agent_c.identity().did);
        assert_eq!(d2.depth(), 1);
        assert!(d2.parent_proof.is_some());
    }

    #[test]
    fn test_delegate_must_be_parent_delegate() {
        let root = keypair();
        let agent_b = keypair();
        let agent_c = keypair();
        let unrelated = keypair();

        let d1 = Delegation::create_root(&root, &agent_b.identity().did, vec![]).unwrap();

        // Agent C tries to delegate using Agent B's delegation (but C is not B)
        let result = Delegation::delegate(&unrelated, &agent_c.identity().did, vec![], d1);
        assert!(result.is_err());
    }

    // --- Invocation ---

    #[test]
    fn test_invocation_basic() {
        let root = keypair();
        let agent_b = keypair();

        let delegation = Delegation::create_root(
            &root,
            &agent_b.identity().did,
            vec![Caveat::ActionScope(vec!["resolve".into()])],
        )
        .unwrap();

        let invocation = Invocation::create(
            &agent_b,
            "resolve",
            serde_json::json!({"entity_id": "123"}),
            delegation,
        )
        .unwrap();

        assert_eq!(invocation.invoker_did, agent_b.identity().did);
        assert_eq!(invocation.action, "resolve");
    }

    #[test]
    fn test_invocation_must_be_delegation_delegate() {
        let root = keypair();
        let agent_b = keypair();
        let agent_c = keypair();

        let delegation = Delegation::create_root(&root, &agent_b.identity().did, vec![]).unwrap();

        // Agent C tries to invoke using Agent B's delegation
        let result = Invocation::create(&agent_c, "resolve", serde_json::json!({}), delegation);
        assert!(result.is_err());
    }

    // --- Verification ---

    #[test]
    fn test_verify_root_invocation() {
        let root = keypair();
        let agent_b = keypair();

        let delegation = Delegation::create_root(
            &root,
            &agent_b.identity().did,
            vec![Caveat::ActionScope(vec!["resolve".into()])],
        )
        .unwrap();

        let invocation =
            Invocation::create(&agent_b, "resolve", serde_json::json!({}), delegation).unwrap();

        let result = verify_invocation(&invocation, &agent_b.identity(), &root.identity()).unwrap();

        assert_eq!(result.invoker_did, agent_b.identity().did);
        assert_eq!(result.root_did, root.identity().did);
        assert_eq!(result.depth, 1); // invoker -> root
    }

    #[test]
    fn test_verify_chained_invocation() {
        let root = keypair();
        let agent_b = keypair();
        let agent_c = keypair();

        let d1 = Delegation::create_root(
            &root,
            &agent_b.identity().did,
            vec![Caveat::ActionScope(vec!["resolve".into(), "search".into()])],
        )
        .unwrap();

        let d2 = Delegation::delegate(
            &agent_b,
            &agent_c.identity().did,
            vec![], // inherit parent's caveats
            d1,
        )
        .unwrap();

        let invocation =
            Invocation::create(&agent_c, "resolve", serde_json::json!({}), d2).unwrap();

        let result = verify_invocation(&invocation, &agent_c.identity(), &root.identity()).unwrap();

        assert_eq!(result.invoker_did, agent_c.identity().did);
        assert_eq!(result.root_did, root.identity().did);
        assert_eq!(result.depth, 2); // C -> B -> root
    }

    #[test]
    fn test_verify_wrong_root_fails() {
        let root = keypair();
        let agent_b = keypair();
        let fake_root = keypair();

        let delegation = Delegation::create_root(&root, &agent_b.identity().did, vec![]).unwrap();

        let invocation =
            Invocation::create(&agent_b, "resolve", serde_json::json!({}), delegation).unwrap();

        let result = verify_invocation(&invocation, &agent_b.identity(), &fake_root.identity());
        assert!(result.is_err());
    }

    // --- Caveat enforcement ---

    #[test]
    fn test_action_scope_caveat_passes() {
        let root = keypair();
        let agent_b = keypair();

        let delegation = Delegation::create_root(
            &root,
            &agent_b.identity().did,
            vec![Caveat::ActionScope(vec!["resolve".into(), "search".into()])],
        )
        .unwrap();

        let invocation =
            Invocation::create(&agent_b, "resolve", serde_json::json!({}), delegation).unwrap();

        assert!(verify_invocation(&invocation, &agent_b.identity(), &root.identity()).is_ok());
    }

    #[test]
    fn test_action_scope_caveat_blocks() {
        let root = keypair();
        let agent_b = keypair();

        let delegation = Delegation::create_root(
            &root,
            &agent_b.identity().did,
            vec![Caveat::ActionScope(vec!["resolve".into()])],
        )
        .unwrap();

        let invocation = Invocation::create(
            &agent_b,
            "merge", // not in allowed scope
            serde_json::json!({}),
            delegation,
        )
        .unwrap();

        let result = verify_invocation(&invocation, &agent_b.identity(), &root.identity());
        assert!(matches!(result, Err(CryptoError::CaveatViolation(_))));
    }

    #[test]
    fn test_expires_at_caveat_blocks() {
        let root = keypair();
        let agent_b = keypair();

        let delegation = Delegation::create_root(
            &root,
            &agent_b.identity().did,
            vec![Caveat::ExpiresAt("2020-01-01T00:00:00.000Z".into())],
        )
        .unwrap();

        let invocation =
            Invocation::create(&agent_b, "resolve", serde_json::json!({}), delegation).unwrap();

        let result = verify_invocation(&invocation, &agent_b.identity(), &root.identity());
        assert!(matches!(result, Err(CryptoError::CaveatViolation(_))));
    }

    #[test]
    fn test_max_cost_caveat_passes() {
        let root = keypair();
        let agent_b = keypair();

        let delegation =
            Delegation::create_root(&root, &agent_b.identity().did, vec![Caveat::MaxCost(5.0)])
                .unwrap();

        let invocation = Invocation::create(
            &agent_b,
            "resolve",
            serde_json::json!({"cost": 3.50}),
            delegation,
        )
        .unwrap();

        assert!(verify_invocation(&invocation, &agent_b.identity(), &root.identity()).is_ok());
    }

    #[test]
    fn test_max_cost_caveat_blocks() {
        let root = keypair();
        let agent_b = keypair();

        let delegation =
            Delegation::create_root(&root, &agent_b.identity().did, vec![Caveat::MaxCost(5.0)])
                .unwrap();

        let invocation = Invocation::create(
            &agent_b,
            "resolve",
            serde_json::json!({"cost": 10.0}),
            delegation,
        )
        .unwrap();

        let result = verify_invocation(&invocation, &agent_b.identity(), &root.identity());
        assert!(matches!(result, Err(CryptoError::CaveatViolation(_))));
    }

    #[test]
    fn test_resource_caveat_glob() {
        let root = keypair();
        let agent_b = keypair();

        let delegation = Delegation::create_root(
            &root,
            &agent_b.identity().did,
            vec![Caveat::Resource("entity:customer:*".into())],
        )
        .unwrap();

        // Matching resource
        let inv_ok = Invocation::create(
            &agent_b,
            "resolve",
            serde_json::json!({"resource": "entity:customer:123"}),
            delegation.clone(),
        )
        .unwrap();
        assert!(verify_invocation(&inv_ok, &agent_b.identity(), &root.identity()).is_ok());

        // Non-matching resource
        let inv_bad = Invocation::create(
            &agent_b,
            "resolve",
            serde_json::json!({"resource": "entity:order:456"}),
            delegation,
        )
        .unwrap();
        let result = verify_invocation(&inv_bad, &agent_b.identity(), &root.identity());
        assert!(matches!(result, Err(CryptoError::CaveatViolation(_))));
    }

    #[test]
    fn test_context_caveat() {
        let root = keypair();
        let agent_b = keypair();

        let delegation = Delegation::create_root(
            &root,
            &agent_b.identity().did,
            vec![Caveat::Context {
                key: "task_id".into(),
                value: "task-abc".into(),
            }],
        )
        .unwrap();

        // Correct context
        let inv_ok = Invocation::create(
            &agent_b,
            "resolve",
            serde_json::json!({"task_id": "task-abc"}),
            delegation.clone(),
        )
        .unwrap();
        assert!(verify_invocation(&inv_ok, &agent_b.identity(), &root.identity()).is_ok());

        // Wrong context
        let inv_bad = Invocation::create(
            &agent_b,
            "resolve",
            serde_json::json!({"task_id": "task-xyz"}),
            delegation,
        )
        .unwrap();
        assert!(matches!(
            verify_invocation(&inv_bad, &agent_b.identity(), &root.identity()),
            Err(CryptoError::CaveatViolation(_))
        ));
    }

    #[test]
    fn test_attenuation_narrows_not_widens() {
        let root = keypair();
        let agent_b = keypair();
        let agent_c = keypair();

        // Root gives B: resolve + search
        let d1 = Delegation::create_root(
            &root,
            &agent_b.identity().did,
            vec![Caveat::ActionScope(vec!["resolve".into(), "search".into()])],
        )
        .unwrap();

        // B gives C: only resolve (narrower)
        let d2 = Delegation::delegate(
            &agent_b,
            &agent_c.identity().did,
            vec![Caveat::ActionScope(vec!["resolve".into()])],
            d1,
        )
        .unwrap();

        // C tries to search - blocked by C's caveat
        let inv = Invocation::create(&agent_c, "search", serde_json::json!({}), d2).unwrap();

        let result = verify_invocation(&inv, &agent_c.identity(), &root.identity());
        assert!(matches!(result, Err(CryptoError::CaveatViolation(_))));
    }

    #[test]
    fn test_three_level_chain() {
        let root = keypair();
        let agent_b = keypair();
        let agent_c = keypair();
        let agent_d = keypair();

        let d1 = Delegation::create_root(
            &root,
            &agent_b.identity().did,
            vec![Caveat::ActionScope(vec!["resolve".into()])],
        )
        .unwrap();

        let d2 = Delegation::delegate(&agent_b, &agent_c.identity().did, vec![], d1).unwrap();

        let d3 = Delegation::delegate(&agent_c, &agent_d.identity().did, vec![], d2).unwrap();

        let inv = Invocation::create(&agent_d, "resolve", serde_json::json!({}), d3).unwrap();

        let result = verify_invocation(&inv, &agent_d.identity(), &root.identity()).unwrap();
        assert_eq!(result.depth, 3); // D -> C -> B -> root
    }

    #[test]
    fn test_verify_delegation_chain() {
        let root = keypair();
        let agent_b = keypair();
        let agent_c = keypair();

        let d1 = Delegation::create_root(&root, &agent_b.identity().did, vec![]).unwrap();

        let d2 = Delegation::delegate(&agent_b, &agent_c.identity().did, vec![], d1).unwrap();

        let chain = verify_delegation_chain(&d2, &root.identity()).unwrap();
        assert!(chain.contains(&root.identity().did));
        assert!(chain.contains(&agent_b.identity().did));
        assert!(chain.contains(&agent_c.identity().did));
    }

    #[test]
    fn test_delegation_serialization_roundtrip() {
        let root = keypair();
        let agent_b = keypair();

        let delegation = Delegation::create_root(
            &root,
            &agent_b.identity().did,
            vec![
                Caveat::ActionScope(vec!["resolve".into()]),
                Caveat::ExpiresAt("2030-01-01T00:00:00.000Z".into()),
                Caveat::MaxCost(10.0),
            ],
        )
        .unwrap();

        let json = serde_json::to_string(&delegation).unwrap();
        let restored: Delegation = serde_json::from_str(&json).unwrap();
        assert_eq!(restored.issuer_did, delegation.issuer_did);
        assert_eq!(restored.delegate_did, delegation.delegate_did);
        assert_eq!(restored.caveats.len(), 3);
    }

    #[test]
    fn test_caveat_serialization_roundtrip() {
        let caveats = vec![
            Caveat::ActionScope(vec!["resolve".into(), "search".into()]),
            Caveat::ExpiresAt("2030-01-01T00:00:00.000Z".into()),
            Caveat::MaxCost(5.0),
            Caveat::Resource("entity:*".into()),
            Caveat::Context {
                key: "task_id".into(),
                value: "t1".into(),
            },
            Caveat::Custom {
                key: "org".into(),
                value: serde_json::json!("acme"),
            },
        ];

        for caveat in &caveats {
            let json = serde_json::to_string(caveat).unwrap();
            let restored: Caveat = serde_json::from_str(&json).unwrap();
            assert_eq!(&restored, caveat, "Roundtrip failed for {:?}", caveat);
        }
    }

    #[test]
    fn test_glob_matching() {
        assert!(matches_glob("entity:*", "entity:customer:123"));
        assert!(matches_glob("entity:customer:*", "entity:customer:123"));
        assert!(!matches_glob("entity:customer:*", "entity:order:456"));
        assert!(matches_glob("exact", "exact"));
        assert!(!matches_glob("exact", "other"));
        assert!(matches_glob("*", "anything"));
    }

    #[test]
    fn test_max_cost_missing_field_fails() {
        let root = keypair();
        let agent_b = keypair();

        let delegation =
            Delegation::create_root(&root, &agent_b.identity().did, vec![Caveat::MaxCost(5.0)])
                .unwrap();

        // No cost field in args - should fail (not silently pass)
        let invocation =
            Invocation::create(&agent_b, "resolve", serde_json::json!({}), delegation).unwrap();

        let result = verify_invocation(&invocation, &agent_b.identity(), &root.identity());
        assert!(matches!(result, Err(CryptoError::CaveatViolation(_))));
    }

    #[test]
    fn test_resource_missing_field_fails() {
        let root = keypair();
        let agent_b = keypair();

        let delegation = Delegation::create_root(
            &root,
            &agent_b.identity().did,
            vec![Caveat::Resource("entity:*".into())],
        )
        .unwrap();

        // No resource field in args - should fail
        let invocation =
            Invocation::create(&agent_b, "resolve", serde_json::json!({}), delegation).unwrap();

        let result = verify_invocation(&invocation, &agent_b.identity(), &root.identity());
        assert!(matches!(result, Err(CryptoError::CaveatViolation(_))));
    }

    #[test]
    fn test_embedded_public_key_present() {
        let root = keypair();
        let agent_b = keypair();

        let delegation = Delegation::create_root(&root, &agent_b.identity().did, vec![]).unwrap();

        assert_eq!(
            delegation.issuer_public_key,
            root.identity().public_key_bytes
        );
    }

    #[test]
    fn test_tampered_delegation_caveats_detected() {
        let root = keypair();
        let agent_b = keypair();

        let mut delegation = Delegation::create_root(
            &root,
            &agent_b.identity().did,
            vec![Caveat::ActionScope(vec!["resolve".into()])],
        )
        .unwrap();

        // Tamper with outer caveats to widen scope
        delegation.caveats = vec![Caveat::ActionScope(vec!["resolve".into(), "merge".into()])];

        let invocation =
            Invocation::create(&agent_b, "merge", serde_json::json!({}), delegation).unwrap();

        // Should fail because verification reads caveats from signed payload,
        // not from the tampered outer field
        let result = verify_invocation(&invocation, &agent_b.identity(), &root.identity());
        assert!(matches!(result, Err(CryptoError::CaveatViolation(_))));
    }

    #[test]
    fn test_intermediate_signature_verified() {
        let root = keypair();
        let agent_b = keypair();
        let agent_c = keypair();

        let d1 = Delegation::create_root(
            &root,
            &agent_b.identity().did,
            vec![Caveat::ActionScope(vec!["resolve".into()])],
        )
        .unwrap();

        let mut d2 = Delegation::delegate(&agent_b, &agent_c.identity().did, vec![], d1).unwrap();

        // Tamper with d2's proof signature (corrupt it)
        d2.proof.signature = "00".repeat(64);

        let invocation =
            Invocation::create(&agent_c, "resolve", serde_json::json!({}), d2).unwrap();

        // Should fail because B's delegation signature is now verified
        let result = verify_invocation(&invocation, &agent_c.identity(), &root.identity());
        assert!(result.is_err());
    }

    // --- Revocation ---

    #[test]
    fn test_revocation_blocks_invocation() {
        let root = keypair();
        let agent_b = keypair();

        let delegation = Delegation::create_root(&root, &agent_b.identity().did, vec![]).unwrap();

        let revoked_hash = delegation.proof.content_hash();

        let invocation =
            Invocation::create(&agent_b, "resolve", serde_json::json!({}), delegation).unwrap();

        // Without revocation - passes
        assert!(verify_invocation(&invocation, &agent_b.identity(), &root.identity()).is_ok());

        // With revocation - fails
        let result = verify_invocation_with_revocation(
            &invocation,
            &agent_b.identity(),
            &root.identity(),
            |hash| hash == revoked_hash,
        );
        assert!(matches!(result, Err(CryptoError::DelegationRevoked(_))));
    }

    #[test]
    fn test_revocation_in_chain_blocks() {
        let root = keypair();
        let agent_b = keypair();
        let agent_c = keypair();

        let d1 = Delegation::create_root(&root, &agent_b.identity().did, vec![]).unwrap();

        let revoked_hash = d1.proof.content_hash();

        let d2 = Delegation::delegate(&agent_b, &agent_c.identity().did, vec![], d1).unwrap();

        let invocation =
            Invocation::create(&agent_c, "resolve", serde_json::json!({}), d2).unwrap();

        // Revoking the root delegation blocks the entire chain
        let result = verify_invocation_with_revocation(
            &invocation,
            &agent_c.identity(),
            &root.identity(),
            |hash| hash == revoked_hash,
        );
        assert!(matches!(result, Err(CryptoError::DelegationRevoked(_))));
    }

    #[test]
    fn test_no_revocation_callback_passes() {
        let root = keypair();
        let agent_b = keypair();

        let delegation = Delegation::create_root(&root, &agent_b.identity().did, vec![]).unwrap();

        let invocation =
            Invocation::create(&agent_b, "resolve", serde_json::json!({}), delegation).unwrap();

        // Default (no revocation) always passes
        let result = verify_invocation_with_revocation(
            &invocation,
            &agent_b.identity(),
            &root.identity(),
            |_| false,
        );
        assert!(result.is_ok());
    }
}