okami 0.2.0

Post-quantum cryptographic identity for AI agents
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
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
//! Delegation tokens and chains for OAuth-style capability passing between agents.
//!
//! This module implements the core delegation mechanism of okami:
//! Capability, DelegationToken, and DelegationChain.
//!
//! Delegation follows the principle of attenuation: a delegator can only grant
//! a subset of its own scopes. Chains are limited to depth 3.
//!
// @decision DEC-OKAMI-005 bincode for token serialization — accepted.
// Rationale: compact binary, clean serde integration. JWTs carry HTTP/JSON
// baggage. The token is signed over its bincode-serialized unsigned portion.
//
// @decision DEC-OKAMI-006 Scope as validated string (not enum) — accepted.
// Rationale: OAuth-style string scopes are familiar and composable with IAM.
// An enum would require knowing every possible scope in advance.
//
// @decision DEC-OKAMI-007 Clock skew tolerance: configurable, default 30s — accepted.
// Rationale: distributed systems have clock drift. 30s prevents spurious failures
// in well-behaved environments. Operators can set it to zero.
//
// @decision DEC-OKAMI-016
// @title Bounded bincode deserialization to prevent allocation DoS
// @status accepted
// @rationale bincode 1.x reads a raw u64 length prefix before allocating for
//   Vec<T>/String fields. A crafted payload with `[0xFF; 8]` as the first field
//   causes an immediate multi-exabyte allocation attempt, crashing the process.
//   Fix: use `DefaultOptions::with_fixint_encoding().allow_trailing_bytes().with_limit(N)`
//   which exactly mirrors the free-function default encoding but adds an allocation cap.
//   The legacy `bincode::config()` builder internally expands to the same Options chain
//   (confirmed via bincode 1.3.3 src/config/legacy.rs) but is deprecated since 1.3.0.
//   Limits: DelegationToken 8 KiB (embeds PqcCredential ~2 KiB + sig + scopes),
//   DelegationChain 32 KiB (max 3 tokens × 8 KiB + headroom).
//   See `/cso` audit Finding #4 (fingerprint `30a553fc`).

use std::time::Duration as StdDuration;

use chrono::{DateTime, Duration, Utc};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};

use crate::error::{Error, Result};
use crate::identity::{AgentIdentity, PqcCredential, SpiffeId, DOMAIN_TOKEN};

// ── Constants ─────────────────────────────────────────────────────────────────

/// Maximum delegation chain depth (depth field in token, 0-indexed).
/// A root token has depth 0; its delegate depth 1; maximum is depth 2.
pub const MAX_DELEGATION_DEPTH: u32 = 2;

/// Default clock skew tolerance in seconds.
pub const DEFAULT_CLOCK_SKEW_SECS: u64 = 30;

/// Maximum byte size accepted by [`DelegationToken::from_bytes`].
///
/// A token embeds the issuer's [`PqcCredential`] (~2 KiB), the PQC signature
/// (~3.3 KiB for ML-DSA-65), SPIFFE IDs, scopes, and timestamps. 8 KiB provides
/// generous headroom while blocking allocation-DoS via crafted length prefixes.
/// See `/cso` audit Finding #4.
pub const MAX_TOKEN_BYTES: u64 = 8 * 1024;

/// Maximum byte size accepted by [`DelegationChain::from_bytes`].
///
/// A chain holds up to 3 tokens (max depth). At 8 KiB each plus framing,
/// 32 KiB provides ample headroom. See `/cso` audit Finding #4.
pub const MAX_CHAIN_BYTES: u64 = 32 * 1024;

// ── Capability ────────────────────────────────────────────────────────────────

/// A validated OAuth-style capability scope string (e.g. `read:db`, `write:api`).
///
/// Scopes must be non-empty strings without whitespace. The conventional format
/// is `action:resource` but any non-empty whitespace-free string is accepted.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct Capability(String);

impl Capability {
    /// Parse and validate a capability scope string.
    ///
    /// # Errors
    ///
    /// Returns [`Error::InvalidScope`] if the string is empty or contains whitespace.
    pub fn new(scope: &str) -> Result<Self> {
        if scope.is_empty() {
            return Err(Error::InvalidScope("scope must not be empty".to_string()));
        }
        if scope.chars().any(|c| c.is_whitespace()) {
            return Err(Error::InvalidScope(format!(
                "scope must not contain whitespace: {:?}",
                scope
            )));
        }
        Ok(Capability(scope.to_string()))
    }

    /// Return the scope string.
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl std::fmt::Display for Capability {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.0)
    }
}

impl std::str::FromStr for Capability {
    type Err = Error;

    fn from_str(s: &str) -> Result<Self> {
        Capability::new(s)
    }
}

// ── UnsignedToken ─────────────────────────────────────────────────────────────

/// The unsigned payload of a delegation token (the bytes that are signed over).
///
/// Separated from [`DelegationToken`] so the signature covers only data fields.
#[derive(Debug, Clone, Serialize, Deserialize)]
struct UnsignedToken {
    issuer: SpiffeId,
    subject: SpiffeId,
    scopes: Vec<Capability>,
    issued_at: DateTime<Utc>,
    expires_at: DateTime<Utc>,
    parent_token_hash: Option<[u8; 32]>,
    depth: u32,
}

// ── DelegationToken ───────────────────────────────────────────────────────────

/// A signed delegation token granting scoped capabilities from issuer to subject.
///
/// Contains: issuer SPIFFE ID, subject SPIFFE ID, scopes, validity window,
/// parent chain linkage, embedded issuer credential, and PQC signature.
///
/// # Examples
///
/// ```
/// use okami::identity::{AgentIdentity, SpiffeId};
/// use okami::delegation::{Capability, DelegationToken};
/// use std::time::Duration;
///
/// let issuer = AgentIdentity::new("example.com", "orchestrator").unwrap();
/// let subject = SpiffeId::new("example.com", "worker/1").unwrap();
/// let scopes = vec![Capability::new("read:db").unwrap()];
///
/// // Issue a root token (no parent).
/// let token = DelegationToken::issue(
///     &issuer,
///     subject,
///     scopes.clone(),
///     &scopes,
///     Duration::from_secs(3600),
///     None,
/// ).unwrap();
///
/// assert_eq!(token.depth, 0);
/// assert!(token.parent_token_hash.is_none());
///
/// // Verify signature and validity window.
/// token.verify(None).unwrap();
///
/// // Round-trip through bytes (e.g. for network transport).
/// let bytes = token.to_bytes().unwrap();
/// let token2 = DelegationToken::from_bytes(&bytes).unwrap();
/// token2.verify(None).unwrap();
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DelegationToken {
    /// Issuer SPIFFE ID.
    pub issuer: SpiffeId,
    /// Subject SPIFFE ID (who receives the capabilities).
    pub subject: SpiffeId,
    /// Capabilities granted to the subject.
    pub scopes: Vec<Capability>,
    /// When this token was issued.
    pub issued_at: DateTime<Utc>,
    /// When this token expires.
    pub expires_at: DateTime<Utc>,
    /// SHA-256 of the parent token bytes (None for root tokens).
    pub parent_token_hash: Option<[u8; 32]>,
    /// Chain depth (0 = root, max = MAX_DELEGATION_DEPTH).
    pub depth: u32,
    /// The issuer's public credential, embedded for self-contained verification.
    pub issuer_credential: PqcCredential,
    /// PQC signature over the bincode-serialized unsigned payload.
    pub signature: Vec<u8>,
}

impl DelegationToken {
    /// Issue a new delegation token.
    ///
    /// Scopes must be a subset of `issuer_scopes` (attenuation enforced).
    /// Depth must not exceed [`MAX_DELEGATION_DEPTH`].
    ///
    /// # Parameters
    ///
    /// - `issuer` — the signing identity of the issuer
    /// - `subject_spiffe_id` — who receives the capabilities
    /// - `scopes` — capabilities to grant (subset of `issuer_scopes`)
    /// - `issuer_scopes` — the full scopes the issuer holds
    /// - `expiry` — how long until the token expires
    /// - `parent` — the parent token in the chain (None for root tokens)
    ///
    /// # Errors
    ///
    /// - [`Error::DelegationDepthExceeded`] if depth would exceed [`MAX_DELEGATION_DEPTH`]
    /// - [`Error::ScopeEscalation`] if requested scopes exceed issuer scopes
    /// - [`Error::Crypto`] if signing fails
    pub fn issue(
        issuer: &AgentIdentity,
        subject_spiffe_id: SpiffeId,
        scopes: Vec<Capability>,
        issuer_scopes: &[Capability],
        expiry: StdDuration,
        parent: Option<&DelegationToken>,
    ) -> Result<Self> {
        let depth = match parent {
            None => 0,
            Some(p) => p.depth + 1,
        };

        if depth > MAX_DELEGATION_DEPTH {
            return Err(Error::DelegationDepthExceeded);
        }

        // Attenuation: requested scopes must be a subset of issuer scopes.
        for scope in &scopes {
            if !issuer_scopes.contains(scope) {
                return Err(Error::ScopeEscalation);
            }
        }

        // Compute parent token hash.
        let parent_token_hash = parent
            .map(|p| -> Result<[u8; 32]> {
                let bytes = p.to_bytes()?;
                Ok(Sha256::digest(&bytes).into())
            })
            .transpose()?;

        let now = Utc::now();
        let expiry_secs: i64 = expiry.as_secs().try_into().unwrap_or(i64::MAX);
        let expires_at = now + Duration::seconds(expiry_secs);

        let unsigned = UnsignedToken {
            issuer: issuer.spiffe_id().clone(),
            subject: subject_spiffe_id.clone(),
            scopes: scopes.clone(),
            issued_at: now,
            expires_at,
            parent_token_hash,
            depth,
        };

        let payload_bytes = bincode::serialize(&unsigned)
            .map_err(|e| Error::Serialization(format!("token payload serialize: {e}")))?;

        // Domain tag prevents cross-protocol signature reuse (DEC-OKAMI-017).
        let signature = issuer.sign_with_domain(DOMAIN_TOKEN, &payload_bytes)?;

        Ok(DelegationToken {
            issuer: issuer.spiffe_id().clone(),
            subject: subject_spiffe_id,
            scopes,
            issued_at: now,
            expires_at,
            parent_token_hash,
            depth,
            issuer_credential: issuer.credential(),
            signature,
        })
    }

    /// Verify this token's signature and validity window.
    ///
    /// Checks: issuer/credential binding, not expired, not issued in the far
    /// future, PQC signature valid.
    ///
    /// # Parameters
    ///
    /// - `clock_skew` — grace period (default: [`DEFAULT_CLOCK_SKEW_SECS`] seconds)
    ///
    /// # Errors
    ///
    /// - [`Error::ChainVerificationFailed`] if the claimed issuer does not match the
    ///   embedded credential's SPIFFE ID, or if the PQC signature is invalid
    /// - [`Error::TokenExpired`] if the token's validity window has passed
    /// - [`Error::TokenNotYetValid`] if the token's `issued_at` is too far in the future
    /// - [`Error::Serialization`] if the unsigned payload cannot be re-serialized
    /// - [`Error::Crypto`] if the verifying key in the embedded credential is structurally invalid
    //
    // @decision DEC-OKAMI-014
    // @title Verify embedded credential SPIFFE ID matches claimed issuer
    // @status accepted
    // @rationale DelegationToken::verify uses the verifying key from the embedded
    //   issuer_credential. Without checking that issuer_credential.spiffe_id matches
    //   the claimed issuer, any keypair holder could forge tokens claiming any issuer
    //   identity: they generate their own AgentIdentity, set issuer = <victim SPIFFE ID>,
    //   embed their own credential, sign the UnsignedToken with their key, and
    //   verify() returns Ok because the signature check only validates that the
    //   payload was signed by the embedded key — not that the embedded key belongs
    //   to the claimed issuer. The check is placed before time-window validation so
    //   the error is stable regardless of system clock state.
    //   See /cso report 2026-04-24 Finding #1
    //   (fingerprint fc51b5488084256e84c03c389a26d5899f5424399d8d4fe99fc9e0e5ff8baeb8).
    pub fn verify(&self, clock_skew: Option<StdDuration>) -> Result<()> {
        // Invariant: the claimed issuer must be the subject of the embedded credential.
        // A token whose issuer field names entity X but embeds Y's verifying key is
        // a forgery — reject before touching the clock.
        if self.issuer != self.issuer_credential.spiffe_id {
            return Err(Error::ChainVerificationFailed(format!(
                "issuer {} does not match embedded credential subject {}",
                self.issuer, self.issuer_credential.spiffe_id
            )));
        }

        let skew_secs = clock_skew
            .unwrap_or(StdDuration::from_secs(DEFAULT_CLOCK_SKEW_SECS))
            .as_secs() as i64;
        let skew = Duration::seconds(skew_secs);
        let now = Utc::now();

        if now > self.expires_at + skew {
            return Err(Error::TokenExpired);
        }
        if self.issued_at > now + skew {
            return Err(Error::TokenNotYetValid);
        }

        let unsigned = UnsignedToken {
            issuer: self.issuer.clone(),
            subject: self.subject.clone(),
            scopes: self.scopes.clone(),
            issued_at: self.issued_at,
            expires_at: self.expires_at,
            parent_token_hash: self.parent_token_hash,
            depth: self.depth,
        };
        let payload_bytes = bincode::serialize(&unsigned)
            .map_err(|e| Error::Serialization(format!("token payload serialize: {e}")))?;

        // Verify with the domain tag that was prepended at issue time (DEC-OKAMI-017).
        let valid = AgentIdentity::verify_with_domain(
            &self.issuer_credential.verifying_key_bytes,
            DOMAIN_TOKEN,
            &payload_bytes,
            &self.signature,
        )?;

        if !valid {
            return Err(Error::ChainVerificationFailed(format!(
                "signature invalid for token from {} to {}",
                self.issuer, self.subject
            )));
        }

        Ok(())
    }

    /// Serialize this token to bytes (bincode).
    ///
    /// # Errors
    ///
    /// Returns [`Error::Serialization`] if bincode encoding fails.
    pub fn to_bytes(&self) -> Result<Vec<u8>> {
        bincode::serialize(self).map_err(|e| Error::Serialization(format!("token serialize: {e}")))
    }

    /// Deserialize a token from bytes (bincode).
    ///
    /// Enforces a [`MAX_TOKEN_BYTES`] allocation cap to prevent DoS via crafted
    /// length-prefix fields. See `/cso` audit Finding #4 (fingerprint `30a553fc`).
    ///
    /// # Errors
    ///
    /// Returns [`Error::Serialization`] if the input exceeds `MAX_TOKEN_BYTES` or
    /// if bincode decoding fails.
    pub fn from_bytes(bytes: &[u8]) -> Result<Self> {
        if bytes.len() as u64 > MAX_TOKEN_BYTES {
            return Err(Error::Serialization(format!(
                "input exceeds maximum size ({} > {})",
                bytes.len(),
                MAX_TOKEN_BYTES
            )));
        }
        use bincode::Options as _;
        bincode::DefaultOptions::new()
            .with_fixint_encoding()
            .allow_trailing_bytes()
            .with_limit(MAX_TOKEN_BYTES)
            .deserialize(bytes)
            .map_err(|e| Error::Serialization(format!("token deserialize: {e}")))
    }

    /// Return a SHA-256 hash of this token's serialized bytes.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Serialization`] if bincode encoding fails.
    pub fn hash(&self) -> Result<[u8; 32]> {
        let bytes = self.to_bytes()?;
        Ok(Sha256::digest(&bytes).into())
    }
}

// ── DelegationChain ───────────────────────────────────────────────────────────

/// An ordered list of delegation tokens forming a verifiable trust chain.
///
/// The chain is ordered root-first. Verification checks each token individually
/// plus structural integrity: parent hash linkage, scope attenuation, depth
/// limit, and issuer/subject linkage across hops.
///
/// # Examples
///
/// ```
/// use okami::identity::{AgentIdentity, SpiffeId};
/// use okami::delegation::{Capability, DelegationToken, DelegationChain};
/// use std::time::Duration;
///
/// let orchestrator = AgentIdentity::new("example.com", "orchestrator").unwrap();
/// let worker = AgentIdentity::new("example.com", "worker/1").unwrap();
/// let sub_id = SpiffeId::new("example.com", "sub-worker/1").unwrap();
/// let scopes = vec![Capability::new("read:db").unwrap()];
///
/// // Root token: orchestrator -> worker.
/// let root = DelegationToken::issue(
///     &orchestrator,
///     worker.spiffe_id().clone(),
///     scopes.clone(),
///     &scopes,
///     Duration::from_secs(3600),
///     None,
/// ).unwrap();
///
/// // Child token: worker -> sub-worker (attenuated scopes).
/// let child = DelegationToken::issue(
///     &worker,
///     sub_id,
///     scopes.clone(),
///     &root.scopes,
///     Duration::from_secs(1800),
///     Some(&root),
/// ).unwrap();
///
/// let chain = DelegationChain::new(vec![root, child]);
/// chain.verify(None).unwrap();
///
/// // Effective scopes are the leaf token's scopes.
/// assert_eq!(chain.effective_scopes().len(), 1);
/// assert_eq!(chain.effective_scopes()[0].as_str(), "read:db");
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DelegationChain {
    /// Ordered tokens, root at index 0.
    pub tokens: Vec<DelegationToken>,
}

impl DelegationChain {
    /// Create a chain from an ordered list of tokens (root first).
    pub fn new(tokens: Vec<DelegationToken>) -> Self {
        DelegationChain { tokens }
    }

    /// Verify the entire delegation chain.
    ///
    /// Checks per-token validity then structural integrity across all links:
    /// each token's signature and expiry, depth ordering, parent-hash linkage,
    /// scope attenuation, and issuer/subject continuity across hops.
    ///
    /// # Errors
    ///
    /// - [`Error::ChainVerificationFailed`] if the chain is empty, a token's depth
    ///   does not match its position, the parent hash does not match, a scope
    ///   escalation is detected, or the issuer/subject chain is broken
    /// - Any error propagated from [`DelegationToken::verify`] for each token
    ///   (see its `# Errors` section)
    pub fn verify(&self, clock_skew: Option<StdDuration>) -> Result<()> {
        if self.tokens.is_empty() {
            return Err(Error::ChainVerificationFailed("chain is empty".to_string()));
        }

        let mut prev_token: Option<&DelegationToken> = None;

        for (i, token) in self.tokens.iter().enumerate() {
            // Per-token verification (signature + expiry).
            token.verify(clock_skew)?;

            // Depth must match position in chain.
            if token.depth as usize != i {
                return Err(Error::ChainVerificationFailed(format!(
                    "token at index {i} has depth {} (expected {i})",
                    token.depth
                )));
            }

            if let Some(prev) = prev_token {
                // Parent hash linkage.
                let expected_hash = prev.hash()?;
                match token.parent_token_hash {
                    None => {
                        return Err(Error::ChainVerificationFailed(format!(
                            "token at index {i} missing parent_token_hash"
                        )));
                    }
                    Some(h) if h != expected_hash => {
                        return Err(Error::ChainVerificationFailed(format!(
                            "token at index {i} parent_token_hash mismatch"
                        )));
                    }
                    _ => {}
                }

                // Scope attenuation.
                for scope in &token.scopes {
                    if !prev.scopes.contains(scope) {
                        return Err(Error::ChainVerificationFailed(format!(
                            "scope escalation at index {i}: {scope} not in parent scopes"
                        )));
                    }
                }

                // Issuer/subject linkage.
                if token.issuer != prev.subject {
                    return Err(Error::ChainVerificationFailed(format!(
                        "chain broken at index {i}: token issuer {} != prev subject {}",
                        token.issuer, prev.subject
                    )));
                }
            } else {
                // Root token must have no parent hash.
                if token.parent_token_hash.is_some() {
                    return Err(Error::ChainVerificationFailed(
                        "root token (index 0) must not have a parent_token_hash".to_string(),
                    ));
                }
            }

            prev_token = Some(token);
        }

        Ok(())
    }

    /// Return the final (leaf) token in the chain.
    pub fn leaf(&self) -> Option<&DelegationToken> {
        self.tokens.last()
    }

    /// Return the effective scopes at the end of the chain (leaf token scopes).
    pub fn effective_scopes(&self) -> &[Capability] {
        self.leaf().map(|t| t.scopes.as_slice()).unwrap_or(&[])
    }

    /// Serialize this chain to bytes (bincode).
    ///
    /// # Errors
    ///
    /// Returns [`Error::Serialization`] if bincode encoding fails.
    pub fn to_bytes(&self) -> Result<Vec<u8>> {
        bincode::serialize(self).map_err(|e| Error::Serialization(format!("chain serialize: {e}")))
    }

    /// Deserialize a chain from bytes (bincode).
    ///
    /// Enforces a [`MAX_CHAIN_BYTES`] allocation cap to prevent DoS via crafted
    /// length-prefix fields. See `/cso` audit Finding #4 (fingerprint `30a553fc`).
    ///
    /// # Errors
    ///
    /// Returns [`Error::Serialization`] if the input exceeds `MAX_CHAIN_BYTES` or
    /// if bincode decoding fails.
    pub fn from_bytes(bytes: &[u8]) -> Result<Self> {
        if bytes.len() as u64 > MAX_CHAIN_BYTES {
            return Err(Error::Serialization(format!(
                "input exceeds maximum size ({} > {})",
                bytes.len(),
                MAX_CHAIN_BYTES
            )));
        }
        use bincode::Options as _;
        bincode::DefaultOptions::new()
            .with_fixint_encoding()
            .allow_trailing_bytes()
            .with_limit(MAX_CHAIN_BYTES)
            .deserialize(bytes)
            .map_err(|e| Error::Serialization(format!("chain deserialize: {e}")))
    }

    /// Render an ASCII tree visualization of this chain.
    ///
    /// Example output:
    /// ```text
    /// [0] spiffe://example.com/orchestrator [read:db, write:api]
    ///  -> [1] spiffe://example.com/worker [read:db]
    ///      -> [2] spiffe://example.com/sub-worker [read:db]
    /// ```
    pub fn ascii_tree(&self) -> String {
        let mut out = String::new();
        for (i, token) in self.tokens.iter().enumerate() {
            let indent = "    ".repeat(i);
            let connector = if i == 0 { "" } else { "-> " };
            let scopes: Vec<&str> = token.scopes.iter().map(|s| s.as_str()).collect();
            let scopes_str = if scopes.is_empty() {
                "(no scopes)".to_string()
            } else {
                format!("[{}]", scopes.join(", "))
            };
            out.push_str(&format!(
                "{indent}{connector}[{i}] {} {scopes_str}\n",
                token.subject
            ));
        }
        out
    }
}

// ── Tests ─────────────────────────────────────────────────────────────────────

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

    fn with_large_stack<F: FnOnce() + Send + 'static>(f: F) {
        std::thread::Builder::new()
            .stack_size(32 * 1024 * 1024)
            .spawn(f)
            .expect("thread spawn failed")
            .join()
            .expect("thread panicked");
    }

    // ── Capability ────────────────────────────────────────────────────────────

    #[test]
    fn capability_valid_scopes() {
        assert!(Capability::new("read:db").is_ok());
        assert!(Capability::new("write:api").is_ok());
        assert!(Capability::new("invoke:llm").is_ok());
        assert!(Capability::new("admin").is_ok());
        assert!(Capability::new("read:db:table1").is_ok());
    }

    #[test]
    fn capability_empty_scope_rejected() {
        assert!(matches!(Capability::new(""), Err(Error::InvalidScope(_))));
    }

    #[test]
    fn capability_whitespace_rejected() {
        assert!(matches!(
            Capability::new("read db"),
            Err(Error::InvalidScope(_))
        ));
        assert!(matches!(
            Capability::new("read\tdb"),
            Err(Error::InvalidScope(_))
        ));
        assert!(matches!(
            Capability::new("read\ndb"),
            Err(Error::InvalidScope(_))
        ));
    }

    #[test]
    fn capability_display() {
        let c = Capability::new("read:db").unwrap();
        assert_eq!(c.to_string(), "read:db");
    }

    #[test]
    fn capability_from_str() {
        let c: Capability = "write:api".parse().unwrap();
        assert_eq!(c.as_str(), "write:api");
    }

    #[test]
    fn capability_serialize_roundtrip() {
        let c = Capability::new("read:db").unwrap();
        let bytes = bincode::serialize(&c).unwrap();
        let c2: Capability = bincode::deserialize(&bytes).unwrap();
        assert_eq!(c, c2);
    }

    // ── DelegationToken ───────────────────────────────────────────────────────

    #[test]
    fn delegation_token_issue_and_verify() {
        with_large_stack(|| {
            let issuer = AgentIdentity::new("example.com", "orchestrator").unwrap();
            let subject_id = SpiffeId::new("example.com", "worker/1").unwrap();
            let scopes = vec![
                Capability::new("read:db").unwrap(),
                Capability::new("write:api").unwrap(),
            ];
            let token = DelegationToken::issue(
                &issuer,
                subject_id,
                scopes.clone(),
                &scopes,
                StdDuration::from_secs(3600),
                None,
            )
            .unwrap();
            token.verify(None).unwrap();
            assert_eq!(token.depth, 0);
            assert!(token.parent_token_hash.is_none());
        });
    }

    #[test]
    fn delegation_token_serialize_roundtrip() {
        with_large_stack(|| {
            let issuer = AgentIdentity::new("example.com", "orchestrator").unwrap();
            let subject_id = SpiffeId::new("example.com", "worker/1").unwrap();
            let scopes = vec![Capability::new("read:db").unwrap()];
            let token = DelegationToken::issue(
                &issuer,
                subject_id,
                scopes.clone(),
                &scopes,
                StdDuration::from_secs(3600),
                None,
            )
            .unwrap();
            let bytes = token.to_bytes().unwrap();
            let token2 = DelegationToken::from_bytes(&bytes).unwrap();
            assert_eq!(token.issuer, token2.issuer);
            assert_eq!(token.subject, token2.subject);
            assert_eq!(token.scopes, token2.scopes);
            assert_eq!(token.depth, token2.depth);
            token2.verify(None).unwrap();
        });
    }

    #[test]
    fn delegation_token_scope_escalation_rejected() {
        with_large_stack(|| {
            let issuer = AgentIdentity::new("example.com", "orchestrator").unwrap();
            let subject_id = SpiffeId::new("example.com", "worker/1").unwrap();
            let issuer_scopes = vec![Capability::new("read:db").unwrap()];
            let requested = vec![
                Capability::new("read:db").unwrap(),
                Capability::new("admin").unwrap(),
            ];
            let result = DelegationToken::issue(
                &issuer,
                subject_id,
                requested,
                &issuer_scopes,
                StdDuration::from_secs(3600),
                None,
            );
            assert!(matches!(result, Err(Error::ScopeEscalation)));
        });
    }

    #[test]
    fn delegation_token_verify_rejects_tampered_signature() {
        with_large_stack(|| {
            let issuer = AgentIdentity::new("example.com", "orchestrator").unwrap();
            let subject_id = SpiffeId::new("example.com", "worker/1").unwrap();
            let scopes = vec![Capability::new("read:db").unwrap()];
            let mut token = DelegationToken::issue(
                &issuer,
                subject_id,
                scopes.clone(),
                &scopes,
                StdDuration::from_secs(3600),
                None,
            )
            .unwrap();
            token.signature[0] ^= 0xFF;
            let result = token.verify(None);
            assert!(matches!(
                result,
                Err(Error::ChainVerificationFailed(_)) | Err(Error::Crypto(_))
            ));
        });
    }

    #[test]
    fn delegation_token_verify_rejects_expired() {
        with_large_stack(|| {
            let issuer = AgentIdentity::new("example.com", "orchestrator").unwrap();
            let subject_id = SpiffeId::new("example.com", "worker/1").unwrap();
            let scopes = vec![Capability::new("read:db").unwrap()];
            let mut token = DelegationToken::issue(
                &issuer,
                subject_id,
                scopes.clone(),
                &scopes,
                StdDuration::from_secs(3600),
                None,
            )
            .unwrap();
            token.expires_at = Utc::now() - Duration::seconds(100);
            let result = token.verify(Some(StdDuration::from_secs(0)));
            assert!(matches!(result, Err(Error::TokenExpired)));
        });
    }

    #[test]
    fn delegation_token_empty_scopes_allowed() {
        with_large_stack(|| {
            let issuer = AgentIdentity::new("example.com", "orchestrator").unwrap();
            let subject_id = SpiffeId::new("example.com", "worker/1").unwrap();
            let issuer_scopes: Vec<Capability> = vec![];
            let token = DelegationToken::issue(
                &issuer,
                subject_id,
                vec![],
                &issuer_scopes,
                StdDuration::from_secs(3600),
                None,
            )
            .unwrap();
            token.verify(None).unwrap();
        });
    }

    // ── DelegationChain ───────────────────────────────────────────────────────

    #[test]
    fn delegation_chain_two_hops() {
        with_large_stack(|| {
            let orchestrator = AgentIdentity::new("example.com", "orchestrator").unwrap();
            let worker = AgentIdentity::new("example.com", "worker/1").unwrap();
            let sub_id = SpiffeId::new("example.com", "sub-worker/1").unwrap();

            let root_scopes = vec![
                Capability::new("read:db").unwrap(),
                Capability::new("write:api").unwrap(),
            ];

            let token1 = DelegationToken::issue(
                &orchestrator,
                worker.spiffe_id().clone(),
                root_scopes.clone(),
                &root_scopes,
                StdDuration::from_secs(3600),
                None,
            )
            .unwrap();

            let worker_scopes = vec![Capability::new("read:db").unwrap()];
            let token2 = DelegationToken::issue(
                &worker,
                sub_id,
                worker_scopes,
                &token1.scopes,
                StdDuration::from_secs(1800),
                Some(&token1),
            )
            .unwrap();

            assert_eq!(token2.depth, 1);
            assert!(token2.parent_token_hash.is_some());

            let chain = DelegationChain::new(vec![token1, token2]);
            chain.verify(None).unwrap();
        });
    }

    #[test]
    fn delegation_chain_max_depth_enforced() {
        with_large_stack(|| {
            let a = AgentIdentity::new("example.com", "agent/a").unwrap();
            let b = AgentIdentity::new("example.com", "agent/b").unwrap();
            let c = AgentIdentity::new("example.com", "agent/c").unwrap();

            let scopes = vec![Capability::new("read:db").unwrap()];

            let t1 = DelegationToken::issue(
                &a,
                b.spiffe_id().clone(),
                scopes.clone(),
                &scopes,
                StdDuration::from_secs(3600),
                None,
            )
            .unwrap();

            let t2 = DelegationToken::issue(
                &b,
                c.spiffe_id().clone(),
                scopes.clone(),
                &t1.scopes,
                StdDuration::from_secs(3600),
                Some(&t1),
            )
            .unwrap();

            let d_id = SpiffeId::new("example.com", "agent/d").unwrap();
            let t3 = DelegationToken::issue(
                &c,
                d_id,
                scopes.clone(),
                &t2.scopes,
                StdDuration::from_secs(3600),
                Some(&t2),
            )
            .unwrap();

            assert_eq!(t3.depth, 2);

            // Attempting depth 3 must fail.
            let e_id = SpiffeId::new("example.com", "agent/e").unwrap();
            let result = DelegationToken::issue(
                &c,
                e_id,
                scopes.clone(),
                &t3.scopes,
                StdDuration::from_secs(3600),
                Some(&t3),
            );
            assert!(matches!(result, Err(Error::DelegationDepthExceeded)));
        });
    }

    #[test]
    fn delegation_chain_broken_parent_hash_rejected() {
        with_large_stack(|| {
            let orchestrator = AgentIdentity::new("example.com", "orchestrator").unwrap();
            let worker = AgentIdentity::new("example.com", "worker/1").unwrap();
            let sub_id = SpiffeId::new("example.com", "sub-worker/1").unwrap();
            let scopes = vec![Capability::new("read:db").unwrap()];

            let token1 = DelegationToken::issue(
                &orchestrator,
                worker.spiffe_id().clone(),
                scopes.clone(),
                &scopes,
                StdDuration::from_secs(3600),
                None,
            )
            .unwrap();

            let mut token2 = DelegationToken::issue(
                &worker,
                sub_id,
                scopes.clone(),
                &token1.scopes,
                StdDuration::from_secs(1800),
                Some(&token1),
            )
            .unwrap();

            if let Some(ref mut h) = token2.parent_token_hash {
                h[0] ^= 0xFF;
            }

            let chain = DelegationChain::new(vec![token1, token2]);
            assert!(matches!(
                chain.verify(None),
                Err(Error::ChainVerificationFailed(_))
            ));
        });
    }

    #[test]
    fn delegation_chain_scope_escalation_in_chain_rejected() {
        with_large_stack(|| {
            let orchestrator = AgentIdentity::new("example.com", "orchestrator").unwrap();
            let worker = AgentIdentity::new("example.com", "worker/1").unwrap();
            let sub_id = SpiffeId::new("example.com", "sub-worker/1").unwrap();
            let root_scopes = vec![Capability::new("read:db").unwrap()];

            let token1 = DelegationToken::issue(
                &orchestrator,
                worker.spiffe_id().clone(),
                root_scopes.clone(),
                &root_scopes,
                StdDuration::from_secs(3600),
                None,
            )
            .unwrap();

            let mut token2 = DelegationToken::issue(
                &worker,
                sub_id,
                root_scopes.clone(),
                &root_scopes,
                StdDuration::from_secs(1800),
                Some(&token1),
            )
            .unwrap();

            // Inject escalated scope post-issuance to simulate tampering.
            token2.scopes.push(Capability::new("admin").unwrap());

            let chain = DelegationChain::new(vec![token1, token2]);
            assert!(matches!(
                chain.verify(None),
                Err(Error::ChainVerificationFailed(_))
            ));
        });
    }

    #[test]
    fn delegation_chain_ascii_tree_nonempty() {
        with_large_stack(|| {
            let orchestrator = AgentIdentity::new("example.com", "orchestrator").unwrap();
            let worker_id = SpiffeId::new("example.com", "worker/1").unwrap();
            let scopes = vec![Capability::new("read:db").unwrap()];
            let token = DelegationToken::issue(
                &orchestrator,
                worker_id,
                scopes.clone(),
                &scopes,
                StdDuration::from_secs(3600),
                None,
            )
            .unwrap();
            let chain = DelegationChain::new(vec![token]);
            let tree = chain.ascii_tree();
            assert!(tree.contains("read:db"));
            assert!(tree.contains("worker/1"));
        });
    }

    #[test]
    fn delegation_chain_empty_fails_verify() {
        let chain = DelegationChain::new(vec![]);
        assert!(matches!(
            chain.verify(None),
            Err(Error::ChainVerificationFailed(_))
        ));
    }

    #[test]
    fn delegation_chain_serialize_roundtrip() {
        with_large_stack(|| {
            let orchestrator = AgentIdentity::new("example.com", "orchestrator").unwrap();
            let worker_id = SpiffeId::new("example.com", "worker/1").unwrap();
            let scopes = vec![Capability::new("read:db").unwrap()];
            let token = DelegationToken::issue(
                &orchestrator,
                worker_id,
                scopes.clone(),
                &scopes,
                StdDuration::from_secs(3600),
                None,
            )
            .unwrap();
            let chain = DelegationChain::new(vec![token]);
            let bytes = chain.to_bytes().unwrap();
            let chain2 = DelegationChain::from_bytes(&bytes).unwrap();
            chain2.verify(None).unwrap();
        });
    }

    #[test]
    fn delegation_chain_effective_scopes() {
        with_large_stack(|| {
            let orchestrator = AgentIdentity::new("example.com", "orchestrator").unwrap();
            let worker_id = SpiffeId::new("example.com", "worker/1").unwrap();
            let scopes = vec![
                Capability::new("read:db").unwrap(),
                Capability::new("write:api").unwrap(),
            ];
            let token = DelegationToken::issue(
                &orchestrator,
                worker_id,
                scopes.clone(),
                &scopes,
                StdDuration::from_secs(3600),
                None,
            )
            .unwrap();
            let chain = DelegationChain::new(vec![token]);
            assert_eq!(chain.effective_scopes().len(), 2);
        });
    }

    // ── Security regression: issuer/credential mismatch (Finding #1) ──────────

    /// An attacker with their own valid keypair forges a token claiming to be
    /// issued by a different SPIFFE ID. The signature is cryptographically valid
    /// (the attacker signs with their own key), but the issuer field names a
    /// different identity than the embedded credential. verify() must reject it.
    #[test]
    fn delegation_token_verify_rejects_issuer_credential_mismatch() {
        with_large_stack(|| {
            // Attacker generates a legitimate keypair for their own identity.
            let attacker = AgentIdentity::new("example.com", "attacker").unwrap();
            // Victim identity the attacker wants to impersonate.
            let victim_id = SpiffeId::new("example.com", "victim").unwrap();
            let subject_id = SpiffeId::new("example.com", "subject").unwrap();

            let scopes = vec![Capability::new("read:db").unwrap()];
            let now = chrono::Utc::now();

            // Build the UnsignedToken as the attacker would: claiming victim as issuer.
            let unsigned = UnsignedToken {
                issuer: victim_id.clone(),
                subject: subject_id.clone(),
                scopes: scopes.clone(),
                issued_at: now,
                expires_at: now + chrono::Duration::seconds(3600),
                parent_token_hash: None,
                depth: 0,
            };
            let payload_bytes = bincode::serialize(&unsigned).unwrap();

            // Attacker signs with their own key — signature is valid for the payload.
            let signature = attacker.sign(&payload_bytes).unwrap();

            // Construct a token where issuer claims to be victim but embeds attacker's
            // credential (whose spiffe_id == attacker, not victim).
            let forged = DelegationToken {
                issuer: victim_id.clone(),
                subject: subject_id,
                scopes,
                issued_at: now,
                expires_at: now + chrono::Duration::seconds(3600),
                parent_token_hash: None,
                depth: 0,
                issuer_credential: attacker.credential(), // attacker's cred, not victim's
                signature,
            };

            let result = forged.verify(None);
            assert!(
                matches!(result, Err(Error::ChainVerificationFailed(ref msg)) if msg.contains("does not match")),
                "expected ChainVerificationFailed(\"does not match ...\"), got: {result:?}"
            );
        });
    }

    /// End-to-end chain variant: a root token with mismatched issuer/credential
    /// must cause chain.verify() to fail at the root, even when a legitimate-
    /// looking child token chains off it.
    #[test]
    fn delegation_chain_rejects_forged_root_with_mismatched_credential() {
        with_large_stack(|| {
            let attacker = AgentIdentity::new("example.com", "attacker").unwrap();
            let legitimate_worker = AgentIdentity::new("example.com", "worker/1").unwrap();
            let victim_id = SpiffeId::new("example.com", "victim").unwrap();
            let subject_id = legitimate_worker.spiffe_id().clone();

            let scopes = vec![Capability::new("read:db").unwrap()];
            let now = chrono::Utc::now();

            // Forge the root token: issuer claims victim but embeds attacker's credential.
            let unsigned_root = UnsignedToken {
                issuer: victim_id.clone(),
                subject: subject_id.clone(),
                scopes: scopes.clone(),
                issued_at: now,
                expires_at: now + chrono::Duration::seconds(3600),
                parent_token_hash: None,
                depth: 0,
            };
            let root_payload = bincode::serialize(&unsigned_root).unwrap();
            let root_sig = attacker.sign(&root_payload).unwrap();

            let forged_root = DelegationToken {
                issuer: victim_id,
                subject: subject_id,
                scopes: scopes.clone(),
                issued_at: now,
                expires_at: now + chrono::Duration::seconds(3600),
                parent_token_hash: None,
                depth: 0,
                issuer_credential: attacker.credential(),
                signature: root_sig,
            };

            // Build a legitimate child token that chains off the forged root.
            let leaf_subject = SpiffeId::new("example.com", "leaf").unwrap();
            let child = DelegationToken::issue(
                &legitimate_worker,
                leaf_subject,
                scopes.clone(),
                &scopes,
                StdDuration::from_secs(1800),
                Some(&forged_root),
            )
            .unwrap();

            let chain = DelegationChain::new(vec![forged_root, child]);
            let result = chain.verify(None);
            assert!(
                matches!(result, Err(Error::ChainVerificationFailed(_))),
                "expected ChainVerificationFailed, got: {result:?}"
            );
        });
    }

    // ── Security: allocation-DoS rejection (Finding #4) ───────────────────────

    /// Feeding a payload whose first 8 bytes are 0xFF (a u64 length prefix of
    /// ~18 exabytes) to DelegationToken::from_bytes must return Err, not panic.
    /// Regression test for /cso Finding #4 (fingerprint `30a553fc`).
    #[test]
    fn delegation_token_from_bytes_rejects_oversized_length_prefix() {
        let mut crafted = vec![0xFFu8; 8];
        crafted.extend_from_slice(&[0u8; 16]);
        let result = DelegationToken::from_bytes(&crafted);
        assert!(
            result.is_err(),
            "oversized length prefix must be rejected, got Ok"
        );
        assert!(
            matches!(result, Err(Error::Serialization(_))),
            "expected Serialization error, got: {:?}",
            result
        );
    }

    /// Feeding a payload whose first 8 bytes are 0xFF to DelegationChain::from_bytes
    /// must return Err, not panic or OOM.
    /// Regression test for /cso Finding #4 (fingerprint `30a553fc`).
    #[test]
    fn delegation_chain_from_bytes_rejects_oversized_length_prefix() {
        let mut crafted = vec![0xFFu8; 8];
        crafted.extend_from_slice(&[0u8; 16]);
        let result = DelegationChain::from_bytes(&crafted);
        assert!(
            result.is_err(),
            "oversized length prefix must be rejected, got Ok"
        );
        assert!(
            matches!(result, Err(Error::Serialization(_))),
            "expected Serialization error, got: {:?}",
            result
        );
    }

    /// A valid but oversized DelegationToken (serialized size > MAX_TOKEN_BYTES)
    /// must be rejected by from_bytes before bincode is invoked.
    ///
    /// Uses 500 scopes (~20 chars each) to push the token over 8 KiB.
    /// Regression test for the boundary invariant gap reported by the tester.
    #[test]
    fn delegation_token_from_bytes_rejects_oversized_valid_input() {
        with_large_stack(|| {
            let issuer = AgentIdentity::new("example.com", "orchestrator").unwrap();
            let subject_id = SpiffeId::new("example.com", "worker/oversized").unwrap();

            // 500 scopes of ~20 chars each yields ~20 KiB serialized — well over MAX_TOKEN_BYTES (8 KiB).
            let big_scopes: Vec<Capability> = (0..500)
                .map(|i| Capability::new(&format!("scope:aaaaaaaaaaa{i:04}")).unwrap())
                .collect();
            let big_issuer_scopes = big_scopes.clone();

            let big_token = DelegationToken::issue(
                &issuer,
                subject_id,
                big_scopes,
                &big_issuer_scopes,
                std::time::Duration::from_secs(3600),
                None,
            )
            .expect("issue oversized token failed");

            let big_bytes = big_token
                .to_bytes()
                .expect("to_bytes failed for oversized token");
            assert!(
                big_bytes.len() as u64 > MAX_TOKEN_BYTES,
                "oversized token must exceed MAX_TOKEN_BYTES ({} <= {})",
                big_bytes.len(),
                MAX_TOKEN_BYTES
            );

            let result = DelegationToken::from_bytes(&big_bytes);
            assert!(
                result.is_err(),
                "Expected Err for oversized valid token, got Ok"
            );
            let err_str = format!("{:?}", result);
            assert!(
                err_str.contains("exceeds maximum"),
                "error must mention 'exceeds maximum', got: {err_str}"
            );
        });
    }
}