vellaveto-types 6.1.1

Core type definitions for Vellaveto policy engine
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
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
//
// Copyright 2026 Paolo Vella
// SPDX-License-Identifier: MPL-2.0

//! Non-Human Identity (NHI) lifecycle types — attestation, behavioral baselines,
//! delegation chains, DPoP proofs, and credential rotation.

use crate::verification::{AccountabilityAttestation, VerificationTier};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fmt;

/// Attestation type for agent identity verification.
///
/// Determines how an agent proves its identity to Vellaveto.
/// Different attestation types offer varying levels of security.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash, Default)]
#[serde(rename_all = "snake_case")]
pub enum NhiAttestationType {
    /// JWT-based attestation (signed identity claims).
    #[default]
    Jwt,
    /// Mutual TLS with client certificate.
    Mtls,
    /// SPIFFE/SPIRE workload identity.
    Spiffe,
    /// DPoP (Demonstration of Proof-of-Possession) per RFC 9449.
    DPoP,
    /// API key authentication (lowest security).
    ApiKey,
}

impl fmt::Display for NhiAttestationType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            NhiAttestationType::Jwt => write!(f, "jwt"),
            NhiAttestationType::Mtls => write!(f, "mtls"),
            NhiAttestationType::Spiffe => write!(f, "spiffe"),
            NhiAttestationType::DPoP => write!(f, "dpop"),
            NhiAttestationType::ApiKey => write!(f, "api_key"),
        }
    }
}

/// Status of an agent identity in the NHI lifecycle.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash, Default)]
#[serde(rename_all = "snake_case")]
pub enum NhiIdentityStatus {
    /// Identity is active and valid.
    Active,
    /// Identity is suspended pending review.
    Suspended,
    /// Identity has been revoked.
    Revoked,
    /// Identity has expired.
    Expired,
    /// Identity is in a probationary period (new or recently restored).
    /// SECURITY (FIND-R46-014): Default to Probationary for fail-closed behavior.
    /// New identities should start with restricted privileges until explicitly
    /// promoted to Active after verification. Prevents newly registered agents
    /// from immediately gaining full access.
    #[default]
    Probationary,
}

impl fmt::Display for NhiIdentityStatus {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            NhiIdentityStatus::Active => write!(f, "active"),
            NhiIdentityStatus::Suspended => write!(f, "suspended"),
            NhiIdentityStatus::Revoked => write!(f, "revoked"),
            NhiIdentityStatus::Expired => write!(f, "expired"),
            NhiIdentityStatus::Probationary => write!(f, "probationary"),
        }
    }
}

/// Registered agent identity for NHI lifecycle management.
///
/// Tracks the full lifecycle of a non-human identity, including:
/// - Attestation type and credentials
/// - Behavioral baseline for continuous authentication
/// - Credential rotation and expiration
///
/// SECURITY (IMP-R104-003): Custom Debug impl redacts public_key.
#[derive(Clone, Serialize, Deserialize, PartialEq, Default)]
#[serde(deny_unknown_fields)]
pub struct NhiAgentIdentity {
    /// Unique agent identifier.
    pub id: String,
    /// Human-readable name for the agent.
    pub name: String,
    /// Attestation type used for verification.
    pub attestation_type: NhiAttestationType,
    /// Current identity status.
    pub status: NhiIdentityStatus,
    /// SPIFFE ID if using SPIFFE attestation.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub spiffe_id: Option<String>,
    /// Public key for signature verification (hex-encoded).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub public_key: Option<String>,
    /// Key algorithm (e.g., "Ed25519", "ES256", "RS256").
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub key_algorithm: Option<String>,
    /// ISO 8601 timestamp when the identity was issued.
    pub issued_at: String,
    /// ISO 8601 timestamp when the identity expires.
    pub expires_at: String,
    /// ISO 8601 timestamp of last credential rotation.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub last_rotation: Option<String>,
    /// Number of successful authentications.
    #[serde(default)]
    pub auth_count: u64,
    /// ISO 8601 timestamp of last successful authentication.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub last_auth: Option<String>,
    /// Tags for categorization (e.g., "production", "internal").
    #[serde(default)]
    pub tags: Vec<String>,
    /// Custom metadata.
    #[serde(default)]
    pub metadata: HashMap<String, String>,
    /// Verification tier for this identity.
    #[serde(default)]
    pub verification_tier: VerificationTier,
    /// DID:PLC identifier (if generated).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub did_plc: Option<String>,
    /// Accountability attestations signed by this identity.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub attestations: Vec<AccountabilityAttestation>,
}

/// SECURITY (IMP-R104-003): Custom Debug redacts `public_key` to prevent
/// cryptographic material from leaking into logs. Follows the ToolSignature pattern.
impl std::fmt::Debug for NhiAgentIdentity {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("NhiAgentIdentity")
            .field("id", &self.id)
            .field("name", &self.name)
            .field("attestation_type", &self.attestation_type)
            .field("status", &self.status)
            .field("spiffe_id", &self.spiffe_id)
            .field(
                "public_key",
                &self.public_key.as_ref().map(|_| "[REDACTED]"),
            )
            .field("key_algorithm", &self.key_algorithm)
            .field("issued_at", &self.issued_at)
            .field("expires_at", &self.expires_at)
            .field("last_rotation", &self.last_rotation)
            .field("auth_count", &self.auth_count)
            .field("last_auth", &self.last_auth)
            .field("tags", &self.tags)
            .field("metadata", &self.metadata)
            .field("verification_tier", &self.verification_tier)
            .field("did_plc", &self.did_plc)
            .field("attestations", &self.attestations)
            .finish()
    }
}

impl NhiAgentIdentity {
    /// Maximum tags per identity.
    pub const MAX_TAGS: usize = 100;
    /// Maximum metadata entries per identity.
    pub const MAX_METADATA_ENTRIES: usize = 100;
    /// Maximum attestations per identity.
    pub const MAX_ATTESTATIONS: usize = 100;
    /// Maximum length for a single tag.
    pub const MAX_TAG_LEN: usize = 256;
    /// Maximum length for a metadata key.
    pub const MAX_METADATA_KEY_LEN: usize = 256;
    /// Maximum length for a metadata value.
    pub const MAX_METADATA_VALUE_LEN: usize = 4096;
    /// Maximum length for the `id` field.
    pub const MAX_ID_LEN: usize = 256;
    /// Maximum length for the `name` field.
    pub const MAX_NAME_LEN: usize = 256;

    /// Validate bounds on deserialized data.
    ///
    /// SECURITY (FIND-R48-005): Unbounded tags, metadata, attestations from deserialization.
    /// SECURITY (FIND-R112-007): Per-entry tag/metadata content validation.
    /// SECURITY (FIND-R112-011): id and name field validation.
    pub fn validate(&self) -> Result<(), String> {
        // SECURITY (FIND-R112-011): Validate id field.
        if self.id.is_empty() {
            return Err("NhiAgentIdentity id must not be empty".to_string());
        }
        if self.id.len() > Self::MAX_ID_LEN {
            return Err(format!(
                "NhiAgentIdentity id length {} exceeds max {}",
                self.id.len(),
                Self::MAX_ID_LEN
            ));
        }
        if crate::core::has_dangerous_chars(&self.id) {
            return Err("NhiAgentIdentity id contains control or format characters".to_string());
        }

        // SECURITY (FIND-R112-011): Validate name field.
        if self.name.len() > Self::MAX_NAME_LEN {
            return Err(format!(
                "NhiAgentIdentity '{}' name length {} exceeds max {}",
                self.id,
                self.name.len(),
                Self::MAX_NAME_LEN
            ));
        }
        if crate::core::has_dangerous_chars(&self.name) {
            return Err(format!(
                "NhiAgentIdentity '{}' name contains control or format characters",
                self.id
            ));
        }

        if self.tags.len() > Self::MAX_TAGS {
            return Err(format!(
                "NhiAgentIdentity '{}' has {} tags (max {})",
                self.id,
                self.tags.len(),
                Self::MAX_TAGS
            ));
        }
        // SECURITY (FIND-R112-007): Per-entry tag validation.
        for (i, tag) in self.tags.iter().enumerate() {
            if tag.len() > Self::MAX_TAG_LEN {
                return Err(format!(
                    "NhiAgentIdentity '{}' tag[{i}] length {} exceeds max {}",
                    self.id,
                    tag.len(),
                    Self::MAX_TAG_LEN
                ));
            }
            if crate::core::has_dangerous_chars(tag) {
                return Err(format!(
                    "NhiAgentIdentity '{}' tag[{i}] contains control or format characters",
                    self.id
                ));
            }
        }

        if self.metadata.len() > Self::MAX_METADATA_ENTRIES {
            return Err(format!(
                "NhiAgentIdentity '{}' has {} metadata entries (max {})",
                self.id,
                self.metadata.len(),
                Self::MAX_METADATA_ENTRIES
            ));
        }
        // SECURITY (FIND-R112-007): Per-entry metadata key/value validation.
        for (key, value) in &self.metadata {
            if key.len() > Self::MAX_METADATA_KEY_LEN {
                return Err(format!(
                    "NhiAgentIdentity '{}' metadata key length {} exceeds max {}",
                    self.id,
                    key.len(),
                    Self::MAX_METADATA_KEY_LEN
                ));
            }
            if crate::core::has_dangerous_chars(key) {
                return Err(format!(
                    "NhiAgentIdentity '{}' metadata key contains control or format characters",
                    self.id
                ));
            }
            if value.len() > Self::MAX_METADATA_VALUE_LEN {
                return Err(format!(
                    "NhiAgentIdentity '{}' metadata value length {} exceeds max {}",
                    self.id,
                    value.len(),
                    Self::MAX_METADATA_VALUE_LEN
                ));
            }
            if crate::core::has_dangerous_chars(value) {
                return Err(format!(
                    "NhiAgentIdentity '{}' metadata value contains control or format characters",
                    self.id
                ));
            }
        }

        if self.attestations.len() > Self::MAX_ATTESTATIONS {
            return Err(format!(
                "NhiAgentIdentity '{}' has {} attestations (max {})",
                self.id,
                self.attestations.len(),
                Self::MAX_ATTESTATIONS
            ));
        }

        // SECURITY (IMP-R122-009): Validate ISO 8601 timestamp fields.
        // Malformed timestamps can bypass is_expired() checks.
        let issued_ts = crate::time_util::parse_iso8601_secs(&self.issued_at).map_err(|e| {
            format!(
                "NhiAgentIdentity '{}' issued_at is not valid ISO 8601: {}",
                self.id, e
            )
        })?;
        let expires_ts = crate::time_util::parse_iso8601_secs(&self.expires_at).map_err(|e| {
            format!(
                "NhiAgentIdentity '{}' expires_at is not valid ISO 8601: {}",
                self.id, e
            )
        })?;
        // SECURITY (FIND-R126-010): Temporal ordering — expires_at must be
        // strictly after issued_at.  An identity that expires before or at its
        // issuance time is nonsensical and could be used to confuse is_expired().
        if expires_ts <= issued_ts {
            return Err(format!(
                "NhiAgentIdentity '{}' expires_at ({}) must be after issued_at ({})",
                self.id, self.expires_at, self.issued_at
            ));
        }
        if let Some(ref lr) = self.last_rotation {
            crate::time_util::parse_iso8601_secs(lr).map_err(|e| {
                format!(
                    "NhiAgentIdentity '{}' last_rotation is not valid ISO 8601: {}",
                    self.id, e
                )
            })?;
        }
        if let Some(ref la) = self.last_auth {
            crate::time_util::parse_iso8601_secs(la).map_err(|e| {
                format!(
                    "NhiAgentIdentity '{}' last_auth is not valid ISO 8601: {}",
                    self.id, e
                )
            })?;
        }

        Ok(())
    }
}

/// Behavioral baseline for continuous agent authentication.
///
/// Tracks typical behavior patterns to detect anomalies that might
/// indicate credential theft or impersonation.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(deny_unknown_fields)]
pub struct NhiBehavioralBaseline {
    /// Agent ID this baseline belongs to.
    pub agent_id: String,
    /// Tool call frequency distribution (tool:function → calls per hour).
    #[serde(default)]
    pub tool_call_patterns: HashMap<String, f64>,
    /// Average interval between requests in seconds.
    #[serde(default)]
    pub avg_request_interval_secs: f64,
    /// Standard deviation of request intervals.
    #[serde(default)]
    pub request_interval_stddev: f64,
    /// Typical session duration in seconds.
    #[serde(default)]
    pub typical_session_duration_secs: f64,
    /// Number of observations used to build this baseline.
    #[serde(default)]
    pub observation_count: u64,
    /// ISO 8601 timestamp when the baseline was first created.
    pub created_at: String,
    /// ISO 8601 timestamp when the baseline was last updated.
    pub last_updated: String,
    /// Confidence score (0.0 - 1.0) based on observation count.
    #[serde(default)]
    pub confidence: f64,
    /// Typical IP addresses or ranges.
    #[serde(default)]
    pub typical_source_ips: Vec<String>,
    /// Typical time windows (hour of day, 0-23).
    #[serde(default)]
    pub active_hours: Vec<u8>,
}

impl NhiBehavioralBaseline {
    /// Maximum tool call pattern entries.
    pub const MAX_TOOL_CALL_PATTERNS: usize = 10_000;
    /// Maximum typical source IPs.
    pub const MAX_SOURCE_IPS: usize = 1000;
    /// Maximum entries in `active_hours`.
    pub const MAX_ACTIVE_HOURS: usize = 24;
    /// Maximum length for `agent_id` field (bytes).
    const MAX_AGENT_ID_LEN: usize = 256;
    /// Maximum length for a single tool_call_patterns key (bytes).
    const MAX_TOOL_PATTERN_KEY_LEN: usize = 512;
    /// Maximum length for a single typical_source_ips entry (bytes).
    const MAX_SOURCE_IP_LEN: usize = 128;

    /// Validate structural invariants: finite scores, range checks, collection bounds,
    /// and active hour validity.
    ///
    /// SECURITY (FIND-R48-009): Also check collection size bounds.
    /// SECURITY (FIND-R146-TE-004): Also validate agent_id bounds and dangerous characters.
    pub fn validate(&self) -> Result<(), String> {
        // SECURITY (FIND-R146-TE-004): Validate agent_id field.
        if self.agent_id.is_empty() {
            return Err("NhiBehavioralBaseline agent_id must not be empty".to_string());
        }
        if self.agent_id.len() > Self::MAX_AGENT_ID_LEN {
            return Err(format!(
                "NhiBehavioralBaseline agent_id length {} exceeds maximum {}",
                self.agent_id.len(),
                Self::MAX_AGENT_ID_LEN
            ));
        }
        if crate::core::has_dangerous_chars(&self.agent_id) {
            return Err("NhiBehavioralBaseline agent_id contains dangerous characters".to_string());
        }
        if self.tool_call_patterns.len() > Self::MAX_TOOL_CALL_PATTERNS {
            return Err(format!(
                "NhiBehavioralBaseline has {} tool_call_patterns (max {})",
                self.tool_call_patterns.len(),
                Self::MAX_TOOL_CALL_PATTERNS
            ));
        }
        if self.typical_source_ips.len() > Self::MAX_SOURCE_IPS {
            return Err(format!(
                "NhiBehavioralBaseline has {} typical_source_ips (max {})",
                self.typical_source_ips.len(),
                Self::MAX_SOURCE_IPS
            ));
        }
        // SECURITY (FIND-R216-007): Per-entry validation on typical_source_ips.
        for (i, ip) in self.typical_source_ips.iter().enumerate() {
            if ip.len() > Self::MAX_SOURCE_IP_LEN {
                return Err(format!(
                    "NhiBehavioralBaseline typical_source_ips[{}] length {} exceeds max {}",
                    i,
                    ip.len(),
                    Self::MAX_SOURCE_IP_LEN,
                ));
            }
            if crate::core::has_dangerous_chars(ip) {
                return Err(format!(
                    "NhiBehavioralBaseline typical_source_ips[{i}] contains control or format characters",
                ));
            }
        }
        if self.active_hours.len() > Self::MAX_ACTIVE_HOURS {
            return Err(format!(
                "NhiBehavioralBaseline has {} active_hours (max {})",
                self.active_hours.len(),
                Self::MAX_ACTIVE_HOURS
            ));
        }
        for (i, &hour) in self.active_hours.iter().enumerate() {
            if hour > 23 {
                return Err(format!(
                    "NhiBehavioralBaseline active_hours[{i}] value {hour} is not a valid hour (0-23)"
                ));
            }
        }
        for (key, val) in &self.tool_call_patterns {
            // SECURITY (FIND-R216-007): Per-key length and dangerous char checks.
            if key.len() > Self::MAX_TOOL_PATTERN_KEY_LEN {
                return Err(format!(
                    "NhiBehavioralBaseline tool_call_patterns key length {} exceeds max {}",
                    key.len(),
                    Self::MAX_TOOL_PATTERN_KEY_LEN,
                ));
            }
            if crate::core::has_dangerous_chars(key) {
                return Err(format!(
                    "NhiBehavioralBaseline tool_call_patterns key '{}' contains control or format characters",
                    key.escape_default(),
                ));
            }
            if !val.is_finite() {
                return Err(format!(
                    "NhiBehavioralBaseline tool_call_patterns['{key}'] is not finite: {val}"
                ));
            }
            // SECURITY (FIND-R53-P3-006): Negative call frequency is nonsensical.
            if *val < 0.0 {
                return Err(format!(
                    "NhiBehavioralBaseline tool_call_patterns['{key}'] must be >= 0.0, got {val}"
                ));
            }
        }
        if !self.avg_request_interval_secs.is_finite() {
            return Err(format!(
                "NhiBehavioralBaseline avg_request_interval_secs is not finite: {}",
                self.avg_request_interval_secs
            ));
        }
        // SECURITY (FIND-R53-P3-006): Negative timing values are nonsensical and could
        // cause unexpected comparisons (e.g., negative interval always < any threshold).
        if self.avg_request_interval_secs < 0.0 {
            return Err(format!(
                "NhiBehavioralBaseline avg_request_interval_secs must be >= 0.0, got {}",
                self.avg_request_interval_secs
            ));
        }
        if !self.request_interval_stddev.is_finite() {
            return Err(format!(
                "NhiBehavioralBaseline request_interval_stddev is not finite: {}",
                self.request_interval_stddev
            ));
        }
        if self.request_interval_stddev < 0.0 {
            return Err(format!(
                "NhiBehavioralBaseline request_interval_stddev must be >= 0.0, got {}",
                self.request_interval_stddev
            ));
        }
        if !self.typical_session_duration_secs.is_finite() {
            return Err(format!(
                "NhiBehavioralBaseline typical_session_duration_secs is not finite: {}",
                self.typical_session_duration_secs
            ));
        }
        if self.typical_session_duration_secs < 0.0 {
            return Err(format!(
                "NhiBehavioralBaseline typical_session_duration_secs must be >= 0.0, got {}",
                self.typical_session_duration_secs
            ));
        }
        if !self.confidence.is_finite() {
            return Err(format!(
                "NhiBehavioralBaseline confidence is not finite: {}",
                self.confidence
            ));
        }
        // SECURITY (FIND-R51-001): Validate confidence is in documented [0.0, 1.0] range.
        if self.confidence < 0.0 || self.confidence > 1.0 {
            return Err(format!(
                "NhiBehavioralBaseline confidence must be in [0.0, 1.0], got {}",
                self.confidence
            ));
        }
        // SECURITY (FIND-R126-011): Validate ISO 8601 timestamp fields.
        // Malformed timestamps bypass temporal comparisons.
        crate::time_util::parse_iso8601_secs(&self.created_at)
            .map_err(|e| format!("NhiBehavioralBaseline created_at is not valid ISO 8601: {e}"))?;
        crate::time_util::parse_iso8601_secs(&self.last_updated).map_err(|e| {
            format!("NhiBehavioralBaseline last_updated is not valid ISO 8601: {e}")
        })?;
        Ok(())
    }

    /// Deprecated alias for [`NhiBehavioralBaseline::validate()`].
    #[deprecated(since = "4.0.1", note = "renamed to validate()")]
    pub fn validate_finite(&self) -> Result<(), String> {
        self.validate()
    }
}

impl Default for NhiBehavioralBaseline {
    fn default() -> Self {
        // SECURITY (FIND-R126-011): Use a valid ISO 8601 epoch timestamp so that
        // `validate()` does not reject freshly-constructed defaults.  Previous
        // empty-string defaults would fail the new timestamp validation.
        let epoch = "1970-01-01T00:00:00Z".to_string();
        Self {
            agent_id: String::new(),
            tool_call_patterns: HashMap::new(),
            avg_request_interval_secs: 0.0,
            request_interval_stddev: 0.0,
            typical_session_duration_secs: 0.0,
            observation_count: 0,
            created_at: epoch.clone(),
            last_updated: epoch,
            confidence: 0.0,
            typical_source_ips: Vec::new(),
            active_hours: Vec::new(),
        }
    }
}

/// Result of behavioral attestation check.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(deny_unknown_fields)]
pub struct NhiBehavioralCheckResult {
    /// Whether the behavior is within acceptable bounds.
    pub within_baseline: bool,
    /// Anomaly score (0.0 = normal, 1.0 = highly anomalous).
    pub anomaly_score: f64,
    /// Specific deviations detected.
    #[serde(default)]
    pub deviations: Vec<NhiBehavioralDeviation>,
    /// Recommended action.
    pub recommendation: NhiBehavioralRecommendation,
}

impl NhiBehavioralCheckResult {
    /// Validate structural invariants: finite scores, range checks, deviation bounds.
    ///
    /// SECURITY (FIND-P2-007): Non-finite anomaly_score could bypass
    /// threshold comparisons that determine whether to allow or block.
    pub fn validate(&self) -> Result<(), String> {
        if !self.anomaly_score.is_finite() {
            return Err(format!(
                "NhiBehavioralCheckResult has non-finite anomaly_score: {}",
                self.anomaly_score
            ));
        }
        // SECURITY (FIND-R51-001): Validate anomaly_score is in documented [0.0, 1.0] range.
        if self.anomaly_score < 0.0 || self.anomaly_score > 1.0 {
            return Err(format!(
                "NhiBehavioralCheckResult anomaly_score must be in [0.0, 1.0], got {}",
                self.anomaly_score
            ));
        }
        // SECURITY (FIND-R52-002): Bound deviations collection size.
        const MAX_DEVIATIONS: usize = 256;
        if self.deviations.len() > MAX_DEVIATIONS {
            return Err(format!(
                "NhiBehavioralCheckResult deviations count {} exceeds max {}",
                self.deviations.len(),
                MAX_DEVIATIONS,
            ));
        }
        for dev in &self.deviations {
            if !dev.severity.is_finite() || dev.severity < 0.0 || dev.severity > 1.0 {
                return Err(format!(
                    "NhiBehavioralDeviation '{}' severity must be in [0.0, 1.0], got {}",
                    dev.deviation_type, dev.severity
                ));
            }
        }
        Ok(())
    }

    /// Deprecated alias for [`NhiBehavioralCheckResult::validate()`].
    #[deprecated(since = "4.0.1", note = "renamed to validate()")]
    pub fn validate_finite(&self) -> Result<(), String> {
        self.validate()
    }
}

/// A specific behavioral deviation from the established baseline.
///
/// Describes a single anomalous observation relative to an agent's
/// [`NhiBehavioralBaseline`]. Multiple deviations may be reported
/// in a single [`NhiBehavioralCheckResult`].
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(deny_unknown_fields)]
pub struct NhiBehavioralDeviation {
    /// Category of deviation (e.g., `"request_interval"`, `"tool_frequency"`,
    /// `"source_ip"`, `"active_hours"`).
    pub deviation_type: String,
    /// The actual value observed during the current request/session
    /// (e.g., `"1200ms"`, `"10.0.0.1"`, `"23"`).
    pub observed: String,
    /// The expected value or range from the baseline
    /// (e.g., `"300-500ms"`, `"192.168.1.0/24"`, `"9-17"`).
    pub expected: String,
    /// How severe this deviation is, from 0.0 (negligible) to 1.0 (extreme).
    /// Validated to be in `[0.0, 1.0]` by [`NhiBehavioralCheckResult::validate()`].
    pub severity: f64,
}

impl NhiBehavioralDeviation {
    /// Maximum length for string fields in a deviation.
    const MAX_FIELD_LEN: usize = 1024;

    /// Validate structural bounds on deserialized data.
    ///
    /// SECURITY (FIND-R216-013): Validates deviation_type, observed, and expected
    /// for length bounds and dangerous characters, and severity for range.
    pub fn validate(&self) -> Result<(), String> {
        if self.deviation_type.len() > Self::MAX_FIELD_LEN {
            return Err(format!(
                "NhiBehavioralDeviation deviation_type length {} exceeds max {}",
                self.deviation_type.len(),
                Self::MAX_FIELD_LEN,
            ));
        }
        if crate::core::has_dangerous_chars(&self.deviation_type) {
            return Err(
                "NhiBehavioralDeviation deviation_type contains control or format characters"
                    .to_string(),
            );
        }
        if self.observed.len() > Self::MAX_FIELD_LEN {
            return Err(format!(
                "NhiBehavioralDeviation observed length {} exceeds max {}",
                self.observed.len(),
                Self::MAX_FIELD_LEN,
            ));
        }
        if crate::core::has_dangerous_chars(&self.observed) {
            return Err(
                "NhiBehavioralDeviation observed contains control or format characters".to_string(),
            );
        }
        if self.expected.len() > Self::MAX_FIELD_LEN {
            return Err(format!(
                "NhiBehavioralDeviation expected length {} exceeds max {}",
                self.expected.len(),
                Self::MAX_FIELD_LEN,
            ));
        }
        if crate::core::has_dangerous_chars(&self.expected) {
            return Err(
                "NhiBehavioralDeviation expected contains control or format characters".to_string(),
            );
        }
        if !self.severity.is_finite() || self.severity < 0.0 || self.severity > 1.0 {
            return Err(format!(
                "NhiBehavioralDeviation severity must be in [0.0, 1.0], got {}",
                self.severity,
            ));
        }
        Ok(())
    }
}

/// Recommended action based on behavioral analysis.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum NhiBehavioralRecommendation {
    /// Allow the request normally.
    Allow,
    /// Allow but log for review.
    AllowWithLogging,
    /// Require additional authentication.
    StepUpAuth,
    /// Suspend the identity pending review.
    Suspend,
    /// Revoke the identity immediately.
    Revoke,
}

impl fmt::Display for NhiBehavioralRecommendation {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            NhiBehavioralRecommendation::Allow => write!(f, "allow"),
            NhiBehavioralRecommendation::AllowWithLogging => write!(f, "allow_with_logging"),
            NhiBehavioralRecommendation::StepUpAuth => write!(f, "step_up_auth"),
            NhiBehavioralRecommendation::Suspend => write!(f, "suspend"),
            NhiBehavioralRecommendation::Revoke => write!(f, "revoke"),
        }
    }
}

/// A link in a delegation chain for NHI accountability.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(deny_unknown_fields)]
pub struct NhiDelegationLink {
    /// Agent delegating permissions.
    pub from_agent: String,
    /// Agent receiving permissions.
    pub to_agent: String,
    /// Permissions being delegated.
    pub permissions: Vec<String>,
    /// Scope constraints (e.g., "tools:read_file", "domains:*.internal").
    #[serde(default)]
    pub scope_constraints: Vec<String>,
    /// ISO 8601 timestamp when the delegation was created.
    pub created_at: String,
    /// ISO 8601 timestamp when the delegation expires.
    pub expires_at: String,
    /// Whether the delegation is currently active.
    #[serde(default = "default_true_nhi")]
    pub active: bool,
    /// Reason for the delegation.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub reason: Option<String>,
}

impl NhiDelegationLink {
    /// Maximum permissions per delegation link.
    pub const MAX_PERMISSIONS: usize = 256;
    /// Maximum scope constraints per delegation link.
    pub const MAX_SCOPE_CONSTRAINTS: usize = 256;
    /// Maximum length for a single permission entry.
    const MAX_PERMISSION_LEN: usize = 1024;
    /// Maximum length for a single scope constraint entry.
    const MAX_SCOPE_CONSTRAINT_LEN: usize = 1024;
    /// Maximum length for the optional reason field.
    const MAX_REASON_LEN: usize = 512;

    /// Validate bounds on deserialized data.
    ///
    /// SECURITY (FIND-R48-006): Unbounded permissions and scope_constraints.
    /// SECURITY (FIND-R216-006): Per-entry validation on permissions and scope_constraints.
    pub fn validate(&self) -> Result<(), String> {
        // SECURITY (FIND-R114-015): Reject control/format characters in from_agent
        // and to_agent BEFORE self-delegation check, preventing Unicode format char
        // bypass (e.g., "admin" vs "admin\u{200B}").
        if crate::core::has_dangerous_chars(&self.from_agent) {
            return Err(
                "NhiDelegationLink from_agent contains control or Unicode format characters"
                    .to_string(),
            );
        }
        if crate::core::has_dangerous_chars(&self.to_agent) {
            return Err(
                "NhiDelegationLink to_agent contains control or Unicode format characters"
                    .to_string(),
            );
        }
        // SECURITY (FIND-R51-009, FIND-R184-003): Reject self-delegation to prevent
        // privilege escalation loops. Use homoglyph-aware comparison to catch Cyrillic
        // confusables that bypass ASCII case-insensitive comparison.
        let from_norm = crate::unicode::normalize_identity(&self.from_agent);
        let to_norm = crate::unicode::normalize_identity(&self.to_agent);
        if from_norm == to_norm {
            return Err("self-delegation is not allowed".to_string());
        }
        // SECURITY (FIND-R51-012): Validate temporal ordering.
        // For ISO 8601 timestamps, lexicographic comparison preserves chronological order.
        // Only check when both fields are non-empty (empty fields caught elsewhere).
        if !self.created_at.is_empty()
            && !self.expires_at.is_empty()
            && self.expires_at <= self.created_at
        {
            return Err(format!(
                "NhiDelegationLink expires_at '{}' must be after created_at '{}'",
                self.expires_at, self.created_at,
            ));
        }
        if self.permissions.len() > Self::MAX_PERMISSIONS {
            return Err(format!(
                "NhiDelegationLink has {} permissions (max {})",
                self.permissions.len(),
                Self::MAX_PERMISSIONS
            ));
        }
        // SECURITY (FIND-R216-006): Per-entry length and dangerous char checks.
        for (i, perm) in self.permissions.iter().enumerate() {
            if perm.len() > Self::MAX_PERMISSION_LEN {
                return Err(format!(
                    "NhiDelegationLink permissions[{}] length {} exceeds max {}",
                    i,
                    perm.len(),
                    Self::MAX_PERMISSION_LEN,
                ));
            }
            if crate::core::has_dangerous_chars(perm) {
                return Err(format!(
                    "NhiDelegationLink permissions[{i}] contains control or format characters",
                ));
            }
        }
        if self.scope_constraints.len() > Self::MAX_SCOPE_CONSTRAINTS {
            return Err(format!(
                "NhiDelegationLink has {} scope_constraints (max {})",
                self.scope_constraints.len(),
                Self::MAX_SCOPE_CONSTRAINTS
            ));
        }
        for (i, sc) in self.scope_constraints.iter().enumerate() {
            if sc.len() > Self::MAX_SCOPE_CONSTRAINT_LEN {
                return Err(format!(
                    "NhiDelegationLink scope_constraints[{}] length {} exceeds max {}",
                    i,
                    sc.len(),
                    Self::MAX_SCOPE_CONSTRAINT_LEN,
                ));
            }
            if crate::core::has_dangerous_chars(sc) {
                return Err(format!(
                    "NhiDelegationLink scope_constraints[{i}] contains control or format characters",
                ));
            }
        }
        // SECURITY (R240-TYP-2): Validate optional reason field.
        if let Some(reason) = &self.reason {
            if reason.len() > Self::MAX_REASON_LEN {
                return Err(format!(
                    "NhiDelegationLink reason length {} exceeds max {}",
                    reason.len(),
                    Self::MAX_REASON_LEN,
                ));
            }
            if crate::core::has_dangerous_chars(reason) {
                return Err(
                    "NhiDelegationLink reason contains control or format characters".to_string(),
                );
            }
        }
        Ok(())
    }
}

fn default_true_nhi() -> bool {
    true
}

/// Full delegation chain for audit and accountability.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(deny_unknown_fields)]
pub struct NhiDelegationChain {
    /// Ordered list of delegation links from origin to current agent.
    pub chain: Vec<NhiDelegationLink>,
    /// Maximum allowed chain depth.
    pub max_depth: usize,
    /// ISO 8601 timestamp when this chain was resolved.
    pub resolved_at: String,
}

impl NhiDelegationChain {
    pub const MAX_DELEGATION_DEPTH: usize = 20;

    /// Returns the current depth of the chain.
    pub fn depth(&self) -> usize {
        self.chain.len()
    }

    /// Returns true if the chain exceeds the maximum allowed depth.
    pub fn exceeds_max_depth(&self) -> bool {
        let effective_max = self.max_depth.min(Self::MAX_DELEGATION_DEPTH);
        self.chain.len() > effective_max
    }

    /// Maximum length for the resolved_at timestamp.
    const MAX_RESOLVED_AT_LEN: usize = 64;

    pub fn validate(&self) -> Result<(), String> {
        if self.max_depth > Self::MAX_DELEGATION_DEPTH {
            return Err(format!(
                "NhiDelegationChain max_depth {} exceeds maximum allowed {} (capped internally)",
                self.max_depth,
                Self::MAX_DELEGATION_DEPTH
            ));
        }
        // SECURITY (R240-TYP-2): Validate resolved_at timestamp.
        if self.resolved_at.len() > Self::MAX_RESOLVED_AT_LEN {
            return Err(format!(
                "NhiDelegationChain resolved_at length {} exceeds max {}",
                self.resolved_at.len(),
                Self::MAX_RESOLVED_AT_LEN,
            ));
        }
        if crate::core::has_dangerous_chars(&self.resolved_at) {
            return Err(
                "NhiDelegationChain resolved_at contains control or format characters".to_string(),
            );
        }
        for link in &self.chain {
            link.validate()?;
        }
        Ok(())
    }

    /// Returns the originating agent (first in chain).
    pub fn origin(&self) -> Option<&str> {
        self.chain.first().map(|link| link.from_agent.as_str())
    }

    /// Returns the final delegated agent (last to_agent in chain).
    pub fn terminus(&self) -> Option<&str> {
        self.chain.last().map(|link| link.to_agent.as_str())
    }
}

/// DPoP (Demonstration of Proof-of-Possession) proof for RFC 9449 compliance.
///
/// SECURITY (IMP-R104-004): Custom Debug impl redacts `proof` JWT and `ath` hash.
#[derive(Clone, Serialize, Deserialize, PartialEq)]
#[serde(deny_unknown_fields)]
pub struct NhiDpopProof {
    /// The DPoP proof JWT.
    pub proof: String,
    /// HTTP method (e.g., "POST").
    pub htm: String,
    /// HTTP URI.
    pub htu: String,
    /// Access token hash (ath claim) if binding to an access token.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub ath: Option<String>,
    /// Nonce from the server (if required).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub nonce: Option<String>,
    /// ISO 8601 timestamp of proof creation.
    pub iat: String,
    /// Unique identifier for replay prevention (jti claim).
    pub jti: String,
}

impl std::fmt::Debug for NhiDpopProof {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("NhiDpopProof")
            .field("proof", &"[REDACTED]")
            .field("htm", &self.htm)
            .field("htu", &self.htu)
            .field("ath", &self.ath.as_ref().map(|_| "[REDACTED]"))
            .field("nonce", &self.nonce)
            .field("iat", &self.iat)
            .field("jti", &self.jti)
            .finish()
    }
}

impl NhiDpopProof {
    /// Maximum length for the `proof` JWT field.
    const MAX_PROOF_LEN: usize = 16_384;
    /// Maximum length for `htm`, `htu`, `ath`, `nonce`, `iat`, and `jti` fields.
    const MAX_FIELD_LEN: usize = 1024;

    /// Validate structural bounds on string fields.
    ///
    /// SECURITY (FIND-R71-002): Prevents memory exhaustion via oversized DPoP proofs.
    pub fn validate(&self) -> Result<(), String> {
        if self.proof.len() > Self::MAX_PROOF_LEN {
            return Err(format!(
                "NhiDpopProof proof length {} exceeds max {}",
                self.proof.len(),
                Self::MAX_PROOF_LEN,
            ));
        }
        if self.htm.len() > Self::MAX_FIELD_LEN {
            return Err(format!(
                "NhiDpopProof htm length {} exceeds max {}",
                self.htm.len(),
                Self::MAX_FIELD_LEN,
            ));
        }
        // SECURITY (FIND-R104-005): Reject Unicode format characters in htm/htu/iat/jti
        // to prevent bidi-override and zero-width character injection.
        if crate::core::has_dangerous_chars(&self.htm) {
            return Err("NhiDpopProof htm contains control or format characters".to_string());
        }
        if self.htu.len() > Self::MAX_FIELD_LEN {
            return Err(format!(
                "NhiDpopProof htu length {} exceeds max {}",
                self.htu.len(),
                Self::MAX_FIELD_LEN,
            ));
        }
        if crate::core::has_dangerous_chars(&self.htu) {
            return Err("NhiDpopProof htu contains control or format characters".to_string());
        }
        if let Some(ref ath) = self.ath {
            if ath.len() > Self::MAX_FIELD_LEN {
                return Err(format!(
                    "NhiDpopProof ath length {} exceeds max {}",
                    ath.len(),
                    Self::MAX_FIELD_LEN,
                ));
            }
            // SECURITY (FIND-R112-008): Reject control and format characters in ath.
            if crate::core::has_dangerous_chars(ath) {
                return Err("NhiDpopProof ath contains control or format characters".to_string());
            }
        }
        if let Some(ref nonce) = self.nonce {
            if nonce.len() > Self::MAX_FIELD_LEN {
                return Err(format!(
                    "NhiDpopProof nonce length {} exceeds max {}",
                    nonce.len(),
                    Self::MAX_FIELD_LEN,
                ));
            }
            // SECURITY (FIND-R112-008): Reject control and format characters in nonce.
            if crate::core::has_dangerous_chars(nonce) {
                return Err("NhiDpopProof nonce contains control or format characters".to_string());
            }
        }
        if self.iat.len() > Self::MAX_FIELD_LEN {
            return Err(format!(
                "NhiDpopProof iat length {} exceeds max {}",
                self.iat.len(),
                Self::MAX_FIELD_LEN,
            ));
        }
        if crate::core::has_dangerous_chars(&self.iat) {
            return Err("NhiDpopProof iat contains control or format characters".to_string());
        }
        if self.jti.len() > Self::MAX_FIELD_LEN {
            return Err(format!(
                "NhiDpopProof jti length {} exceeds max {}",
                self.jti.len(),
                Self::MAX_FIELD_LEN,
            ));
        }
        if crate::core::has_dangerous_chars(&self.jti) {
            return Err("NhiDpopProof jti contains control or format characters".to_string());
        }
        Ok(())
    }
}

/// Result of DPoP proof verification.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(deny_unknown_fields)]
pub struct NhiDpopVerificationResult {
    /// Whether the proof is valid.
    pub valid: bool,
    /// Public key thumbprint (JWK thumbprint).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub thumbprint: Option<String>,
    /// Error message if verification failed.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub error: Option<String>,
    /// Nonce to return for retry (if applicable).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub new_nonce: Option<String>,
}

impl NhiDpopVerificationResult {
    /// Maximum length for thumbprint strings.
    const MAX_THUMBPRINT_LEN: usize = 512;
    /// Maximum length for error messages.
    const MAX_ERROR_LEN: usize = 1024;
    /// Maximum length for nonce strings.
    const MAX_NONCE_LEN: usize = 256;

    /// Validate structural bounds on string fields.
    ///
    /// SECURITY (IMP-R122-011): Unbounded thumbprint/error/nonce fields from
    /// external input could cause memory exhaustion or log injection.
    pub fn validate(&self) -> Result<(), String> {
        if let Some(ref t) = self.thumbprint {
            if t.len() > Self::MAX_THUMBPRINT_LEN {
                return Err(format!(
                    "NhiDpopVerificationResult thumbprint length {} exceeds max {}",
                    t.len(),
                    Self::MAX_THUMBPRINT_LEN
                ));
            }
            if crate::core::has_dangerous_chars(t) {
                return Err(
                    "NhiDpopVerificationResult thumbprint contains control or format characters"
                        .to_string(),
                );
            }
        }
        if let Some(ref e) = self.error {
            if e.len() > Self::MAX_ERROR_LEN {
                return Err(format!(
                    "NhiDpopVerificationResult error length {} exceeds max {}",
                    e.len(),
                    Self::MAX_ERROR_LEN
                ));
            }
            if crate::core::has_dangerous_chars(e) {
                return Err(
                    "NhiDpopVerificationResult error contains control or format characters"
                        .to_string(),
                );
            }
        }
        if let Some(ref n) = self.new_nonce {
            if n.len() > Self::MAX_NONCE_LEN {
                return Err(format!(
                    "NhiDpopVerificationResult new_nonce length {} exceeds max {}",
                    n.len(),
                    Self::MAX_NONCE_LEN
                ));
            }
            if crate::core::has_dangerous_chars(n) {
                return Err(
                    "NhiDpopVerificationResult new_nonce contains control or format characters"
                        .to_string(),
                );
            }
        }
        Ok(())
    }
}

/// Statistics for NHI lifecycle management.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
#[serde(deny_unknown_fields)]
pub struct NhiStats {
    /// Total registered agent identities.
    pub total_identities: u64,
    /// Active identities.
    pub active_identities: u64,
    /// Suspended identities.
    pub suspended_identities: u64,
    /// Revoked identities.
    pub revoked_identities: u64,
    /// Expired identities.
    pub expired_identities: u64,
    /// Identities with behavioral baselines.
    pub with_baselines: u64,
    /// Authentications in the last hour.
    pub auths_last_hour: u64,
    /// Behavioral anomalies detected in the last hour.
    pub anomalies_last_hour: u64,
    /// Active delegations.
    pub active_delegations: u64,
    /// DPoP proofs verified in the last hour.
    pub dpop_verifications_last_hour: u64,
}

impl NhiStats {
    /// Validate structural invariants.
    ///
    /// Currently a no-op since all fields are bounded integer types,
    /// but provided for forward-compatibility with future string fields.
    pub fn validate(&self) -> Result<(), String> {
        // All fields are u64 — no string bounds to check.
        // total_identities should be >= sum of sub-counts, but this is
        // a consistency check rather than a security bound, so we only
        // enforce it as a warning-level audit finding, not a hard reject.
        Ok(())
    }
}

/// Credential rotation event for audit.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(deny_unknown_fields)]
pub struct NhiCredentialRotation {
    /// Agent ID.
    pub agent_id: String,
    /// Previous key thumbprint (if applicable).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub previous_thumbprint: Option<String>,
    /// New key thumbprint.
    pub new_thumbprint: String,
    /// ISO 8601 timestamp of rotation.
    pub rotated_at: String,
    /// Rotation trigger (scheduled, manual, security_event).
    pub trigger: String,
    /// New expiration time.
    pub new_expires_at: String,
}

impl NhiCredentialRotation {
    /// Maximum length for `agent_id`.
    const MAX_AGENT_ID_LEN: usize = 256;
    /// Maximum length for thumbprint strings.
    const MAX_THUMBPRINT_LEN: usize = 512;
    /// Maximum length for ISO 8601 timestamp strings.
    const MAX_TIMESTAMP_LEN: usize = 64;
    /// Maximum length for `trigger`.
    const MAX_TRIGGER_LEN: usize = 128;

    /// Validate structural bounds on string fields.
    ///
    /// SECURITY (FIND-R112-009): Control and Unicode format character validation on all string fields.
    pub fn validate(&self) -> Result<(), String> {
        if self.agent_id.len() > Self::MAX_AGENT_ID_LEN {
            return Err(format!(
                "NhiCredentialRotation agent_id length {} exceeds max {}",
                self.agent_id.len(),
                Self::MAX_AGENT_ID_LEN,
            ));
        }
        if crate::core::has_dangerous_chars(&self.agent_id) {
            return Err(
                "NhiCredentialRotation agent_id contains control or format characters".to_string(),
            );
        }

        if let Some(ref pt) = self.previous_thumbprint {
            if pt.len() > Self::MAX_THUMBPRINT_LEN {
                return Err(format!(
                    "NhiCredentialRotation previous_thumbprint length {} exceeds max {}",
                    pt.len(),
                    Self::MAX_THUMBPRINT_LEN,
                ));
            }
            if crate::core::has_dangerous_chars(pt) {
                return Err("NhiCredentialRotation previous_thumbprint contains control or format characters".to_string());
            }
        }

        if self.new_thumbprint.len() > Self::MAX_THUMBPRINT_LEN {
            return Err(format!(
                "NhiCredentialRotation new_thumbprint length {} exceeds max {}",
                self.new_thumbprint.len(),
                Self::MAX_THUMBPRINT_LEN,
            ));
        }
        if crate::core::has_dangerous_chars(&self.new_thumbprint) {
            return Err(
                "NhiCredentialRotation new_thumbprint contains control or format characters"
                    .to_string(),
            );
        }

        if self.rotated_at.len() > Self::MAX_TIMESTAMP_LEN {
            return Err(format!(
                "NhiCredentialRotation rotated_at length {} exceeds max {}",
                self.rotated_at.len(),
                Self::MAX_TIMESTAMP_LEN,
            ));
        }
        if crate::core::has_dangerous_chars(&self.rotated_at) {
            return Err(
                "NhiCredentialRotation rotated_at contains control or format characters"
                    .to_string(),
            );
        }

        if self.trigger.len() > Self::MAX_TRIGGER_LEN {
            return Err(format!(
                "NhiCredentialRotation trigger length {} exceeds max {}",
                self.trigger.len(),
                Self::MAX_TRIGGER_LEN,
            ));
        }
        if crate::core::has_dangerous_chars(&self.trigger) {
            return Err(
                "NhiCredentialRotation trigger contains control or format characters".to_string(),
            );
        }

        if self.new_expires_at.len() > Self::MAX_TIMESTAMP_LEN {
            return Err(format!(
                "NhiCredentialRotation new_expires_at length {} exceeds max {}",
                self.new_expires_at.len(),
                Self::MAX_TIMESTAMP_LEN,
            ));
        }
        if crate::core::has_dangerous_chars(&self.new_expires_at) {
            return Err(
                "NhiCredentialRotation new_expires_at contains control or format characters"
                    .to_string(),
            );
        }

        Ok(())
    }
}