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
// 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
//! Advanced threat detection types — auth levels, circuit breakers, fingerprints,
//! trust levels, schema records, principal context, and sampling stats.
use serde::{Deserialize, Serialize};
use std::fmt;
/// Authentication level for step-up authentication policies.
///
/// Step-up auth allows policies to require stronger authentication
/// for sensitive operations. Levels are ordered by strength.
#[derive(
Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash, Default,
)]
#[serde(rename_all = "snake_case")]
#[repr(u8)]
pub enum AuthLevel {
/// No authentication.
#[default]
None = 0,
/// Basic authentication (API key, simple token).
Basic = 1,
/// OAuth 2.0/2.1 authentication.
OAuth = 2,
/// OAuth with MFA (multi-factor authentication).
OAuthMfa = 3,
/// Hardware key authentication (`WebAuthn`, `FIDO2`).
HardwareKey = 4,
}
impl fmt::Display for AuthLevel {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
AuthLevel::None => write!(f, "none"),
AuthLevel::Basic => write!(f, "basic"),
AuthLevel::OAuth => write!(f, "oauth"),
AuthLevel::OAuthMfa => write!(f, "oauth_mfa"),
AuthLevel::HardwareKey => write!(f, "hardware_key"),
}
}
}
impl AuthLevel {
/// Convert from `u8` to `AuthLevel`, defaulting to `None` for unknown values.
///
/// # Security note (FIND-P2-010)
///
/// Unknown values (> 4) map to `AuthLevel::None` (lowest level) for
/// **fail-closed** behavior. This ensures that corrupted or attacker-
/// controlled numeric values never grant elevated authentication status.
/// An attacker sending `value = 255` gets `None`, not `HardwareKey`.
pub fn from_u8(value: u8) -> Self {
match value {
0 => AuthLevel::None,
1 => AuthLevel::Basic,
2 => AuthLevel::OAuth,
3 => AuthLevel::OAuthMfa,
4 => AuthLevel::HardwareKey,
_ => AuthLevel::None,
}
}
/// Returns true if this level meets or exceeds the required level.
pub fn satisfies(&self, required: AuthLevel) -> bool {
*self >= required
}
}
/// An MCP capability declaration for CIMD (Capability-Indexed Message Dispatch).
///
/// MCP 2025-11-25 introduces capability negotiation. Clients declare their
/// capabilities, and policies can require or block specific capabilities.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
pub struct McpCapability {
/// Capability name (e.g., "tools", "resources", "sampling").
pub name: String,
/// Optional version string for the capability.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub version: Option<String>,
/// Sub-capabilities (e.g., for "tools": ["read", "write", "execute"]).
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub sub_capabilities: Vec<String>,
}
/// Maximum number of sub-capabilities per `McpCapability`.
///
/// SECURITY (FIND-R53-P3-007): Prevents memory exhaustion from unbounded
/// sub-capability vectors in deserialized capability payloads.
pub const MAX_SUB_CAPABILITIES: usize = 100;
impl McpCapability {
/// Maximum length for `name` (bytes).
const MAX_NAME_LEN: usize = 256;
/// Maximum length for `version` (bytes).
const MAX_VERSION_LEN: usize = 128;
/// Maximum length for a single sub-capability string (bytes).
const MAX_SUB_CAPABILITY_LEN: usize = 256;
/// Create a new capability with just a name.
pub fn new(name: impl Into<String>) -> Self {
Self {
name: name.into(),
version: None,
sub_capabilities: Vec::new(),
}
}
/// Create a capability with a version.
pub fn with_version(name: impl Into<String>, version: impl Into<String>) -> Self {
Self {
name: name.into(),
version: Some(version.into()),
sub_capabilities: Vec::new(),
}
}
/// Check if this capability has a specific sub-capability.
pub fn has_sub(&self, sub: &str) -> bool {
self.sub_capabilities.iter().any(|s| s == sub)
}
/// Validate structural bounds on fields.
///
/// SECURITY (FIND-R53-P3-007): Prevents memory exhaustion and control character
/// injection from untrusted `McpCapability` payloads. Enforces
/// `MAX_SUB_CAPABILITIES` on the sub-capabilities vector.
pub fn validate(&self) -> Result<(), String> {
if self.name.is_empty() {
return Err("McpCapability name must not be empty".to_string());
}
if self.name.len() > Self::MAX_NAME_LEN {
return Err(format!(
"McpCapability name length {} exceeds max {}",
self.name.len(),
Self::MAX_NAME_LEN,
));
}
if crate::core::has_dangerous_chars(&self.name) {
return Err("McpCapability name contains control or format characters".to_string());
}
if let Some(ref ver) = self.version {
if ver.len() > Self::MAX_VERSION_LEN {
return Err(format!(
"McpCapability version length {} exceeds max {}",
ver.len(),
Self::MAX_VERSION_LEN,
));
}
// SECURITY (R235-TYP-1): Validate dangerous chars on version field
// (parity with name field check above).
if crate::core::has_dangerous_chars(ver) {
return Err(
"McpCapability version contains control or format characters".to_string(),
);
}
}
if self.sub_capabilities.len() > MAX_SUB_CAPABILITIES {
return Err(format!(
"McpCapability sub_capabilities count {} exceeds max {}",
self.sub_capabilities.len(),
MAX_SUB_CAPABILITIES,
));
}
for (i, sub) in self.sub_capabilities.iter().enumerate() {
if sub.len() > Self::MAX_SUB_CAPABILITY_LEN {
return Err(format!(
"McpCapability sub_capabilities[{}] length {} exceeds max {}",
i,
sub.len(),
Self::MAX_SUB_CAPABILITY_LEN,
));
}
// SECURITY (FIND-R83-007): Reject control and Unicode format characters
// in sub-capability strings, matching name validation above.
if sub
.chars()
.any(|c| c.is_control() || crate::core::is_unicode_format_char(c))
{
return Err(format!(
"McpCapability sub_capabilities[{i}] contains control or format characters",
));
}
}
Ok(())
}
}
/// State of a circuit breaker for cascading failure protection.
///
/// Circuit breakers prevent cascading failures by temporarily blocking
/// requests to failing tools. Aligned with OWASP ASI08.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
#[serde(rename_all = "snake_case")]
pub enum CircuitState {
/// Circuit is operating normally, requests are allowed.
#[default]
Closed,
/// Circuit is tripped due to failures, requests are blocked.
Open,
/// Circuit is testing recovery, limited requests allowed.
HalfOpen,
}
impl fmt::Display for CircuitState {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
CircuitState::Closed => write!(f, "closed"),
CircuitState::Open => write!(f, "open"),
CircuitState::HalfOpen => write!(f, "half_open"),
}
}
}
/// Statistics for a circuit breaker instance.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(deny_unknown_fields)]
pub struct CircuitStats {
/// Current state of the circuit.
pub state: CircuitState,
/// Number of consecutive failures.
pub failure_count: u32,
/// Number of consecutive successes (used in half-open state).
pub success_count: u32,
/// Unix timestamp of the last failure, if any.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub last_failure: Option<u64>,
/// Unix timestamp of the last state change.
pub last_state_change: u64,
/// Number of times the circuit has tripped (HalfOpen→Open transitions).
/// Used for exponential backoff of open duration. Capped at 5 (32x max).
#[serde(default)]
pub trip_count: u32,
}
impl Default for CircuitStats {
fn default() -> Self {
Self {
state: CircuitState::Closed,
failure_count: 0,
success_count: 0,
last_failure: None,
last_state_change: 0,
trip_count: 0,
}
}
}
/// Fingerprint for agent identity detection (shadow agent prevention).
///
/// Used to detect when an unknown agent claims to be a known agent,
/// indicating potential shadow agent attack.
///
/// SECURITY (FIND-R56-CORE-006): Custom `Debug` implementation redacts
/// `jwt_sub`, `jwt_iss`, and `client_id` as these may contain sensitive
/// identity information that should not appear in logs.
#[derive(Clone, Serialize, Deserialize, PartialEq, Eq, Hash, Default)]
#[serde(deny_unknown_fields)]
pub struct AgentFingerprint {
/// JWT subject claim, if present.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub jwt_sub: Option<String>,
/// JWT issuer claim, if present.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub jwt_iss: Option<String>,
/// OAuth client ID, if present.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub client_id: Option<String>,
/// Hashed IP address for privacy-preserving fingerprinting.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub ip_hash: Option<String>,
}
impl fmt::Debug for AgentFingerprint {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("AgentFingerprint")
.field("jwt_sub", &self.jwt_sub.as_ref().map(|_| "[REDACTED]"))
.field("jwt_iss", &self.jwt_iss.as_ref().map(|_| "[REDACTED]"))
.field("client_id", &self.client_id.as_ref().map(|_| "[REDACTED]"))
.field("ip_hash", &self.ip_hash)
.finish()
}
}
/// Maximum length for AgentFingerprint string fields.
const MAX_FINGERPRINT_FIELD_LEN: usize = 1024;
impl AgentFingerprint {
/// SECURITY (R241-TYP-1): Validate fingerprint fields for bounds and dangerous chars.
pub fn validate(&self) -> Result<(), String> {
fn check_opt(name: &str, value: &Option<String>) -> Result<(), String> {
if let Some(v) = value {
if v.len() > MAX_FINGERPRINT_FIELD_LEN {
return Err(format!(
"AgentFingerprint {name} length {} exceeds max {MAX_FINGERPRINT_FIELD_LEN}",
v.len()
));
}
if crate::core::has_dangerous_chars(v) {
return Err(format!(
"AgentFingerprint {name} contains control or format characters"
));
}
}
Ok(())
}
check_opt("jwt_sub", &self.jwt_sub)?;
check_opt("jwt_iss", &self.jwt_iss)?;
check_opt("client_id", &self.client_id)?;
check_opt("ip_hash", &self.ip_hash)?;
Ok(())
}
/// Returns true if this fingerprint has any identifying information.
pub fn is_populated(&self) -> bool {
self.jwt_sub.is_some()
|| self.jwt_iss.is_some()
|| self.client_id.is_some()
|| self.ip_hash.is_some()
}
/// Returns a summary string for logging (no sensitive data).
pub fn summary(&self) -> String {
let mut parts = Vec::new();
if let Some(sub) = &self.jwt_sub {
parts.push(format!("sub:{}", truncate_for_log(sub, 20)));
}
if let Some(iss) = &self.jwt_iss {
parts.push(format!("iss:{}", truncate_for_log(iss, 20)));
}
if let Some(cid) = &self.client_id {
parts.push(format!("cid:{}", truncate_for_log(cid, 20)));
}
if self.ip_hash.is_some() {
parts.push("ip:*".to_string());
}
if parts.is_empty() {
"empty".to_string()
} else {
parts.join(",")
}
}
}
/// Truncate a string for logging, adding "..." if truncated.
/// SECURITY (FIND-R44-031): Use char_indices() to find a valid char boundary
/// instead of byte slicing, which panics on multi-byte UTF-8.
/// SECURITY (FIND-R48-014): Guard against max_len < 4 where the "..." suffix
/// would exceed the requested maximum.
/// SECURITY (FIND-R56-CORE-009): pub(crate) for reuse by other modules in this crate.
pub(crate) fn truncate_for_log(s: &str, max_len: usize) -> String {
if s.len() <= max_len {
return s.to_string();
}
if max_len < 4 {
return s.chars().take(max_len).collect();
}
let truncate_at = max_len.saturating_sub(3);
let boundary = s
.char_indices()
.take_while(|&(i, _)| i <= truncate_at)
.last()
.map(|(i, _)| i)
.unwrap_or(0);
format!("{}...", &s[..boundary])
}
/// Trust level for known agents (shadow agent detection).
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Default)]
#[serde(rename_all = "snake_case")]
pub enum TrustLevel {
/// Unknown agent, no trust established.
#[default]
Unknown = 0,
/// Low trust, recently seen but not verified.
Low = 1,
/// Medium trust, consistent behavior observed.
Medium = 2,
/// High trust, extended consistent behavior.
High = 3,
/// Verified trust, administratively confirmed.
Verified = 4,
}
impl fmt::Display for TrustLevel {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
TrustLevel::Unknown => write!(f, "unknown"),
TrustLevel::Low => write!(f, "low"),
TrustLevel::Medium => write!(f, "medium"),
TrustLevel::High => write!(f, "high"),
TrustLevel::Verified => write!(f, "verified"),
}
}
}
impl TrustLevel {
/// Convert from `u8` to `TrustLevel`, defaulting to `Unknown` for invalid values.
///
/// # Security note (FIND-P2-011)
///
/// Unknown values (> 4) map to `TrustLevel::Unknown` (lowest level) for
/// **fail-closed** behavior. This ensures that corrupted or attacker-
/// controlled numeric values never grant elevated trust. An attacker
/// sending `value = 255` gets `Unknown`, not `Verified`.
pub fn from_u8(value: u8) -> Self {
match value {
0 => TrustLevel::Unknown,
1 => TrustLevel::Low,
2 => TrustLevel::Medium,
3 => TrustLevel::High,
4 => TrustLevel::Verified,
_ => TrustLevel::Unknown,
}
}
}
/// Record of a tool's schema for lineage tracking (schema poisoning detection).
///
/// Tracks schema changes over time to detect malicious mutations.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(deny_unknown_fields)]
pub struct SchemaRecord {
/// Name of the tool this schema belongs to.
pub tool_name: String,
/// SHA-256 hash of the current schema.
pub schema_hash: String,
/// Unix timestamp when this schema was first seen.
pub first_seen: u64,
/// Unix timestamp when this schema was last seen.
pub last_seen: u64,
/// History of schema hashes (oldest first, max 10 entries).
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub version_history: Vec<String>,
/// Trust score based on schema stability (0.0-1.0).
pub trust_score: f32,
/// SECURITY (R33-006): Actual schema content for field-level diff detection.
/// Only stored if schema is under 64KB to prevent memory exhaustion.
/// Enables real similarity calculation instead of heuristics.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub schema_content: Option<serde_json::Value>,
}
impl SchemaRecord {
/// Maximum schema size to store in memory (64 KB).
/// Larger schemas fall back to hash-only comparison.
pub const MAX_SCHEMA_SIZE: usize = 64 * 1024;
/// Maximum number of entries in version_history.
/// SECURITY (FIND-R46-016): Enforced to prevent unbounded memory growth
/// from rapidly mutating tool schemas (e.g., rug-pull attacks).
pub const MAX_VERSION_HISTORY: usize = 10;
/// Maximum byte length for a single hash entry in `version_history` or `schema_hash`.
///
/// SECURITY: Prevents memory exhaustion from excessively long hash strings
/// supplied by attacker-controlled payloads.
pub const MAX_HASH_LEN: usize = 128;
/// Maximum length for `tool_name`.
const MAX_TOOL_NAME_LEN: usize = 256;
/// Unified validation for `SchemaRecord` (IMP-R122-002).
///
/// Validates trust_score range, version_history bounds, and string field
/// length/content constraints.
pub fn validate(&self) -> Result<(), String> {
// Validate tool_name
if self.tool_name.is_empty() {
return Err("SchemaRecord tool_name must not be empty".to_string());
}
if self.tool_name.len() > Self::MAX_TOOL_NAME_LEN {
return Err(format!(
"SchemaRecord tool_name length {} exceeds max {}",
self.tool_name.len(),
Self::MAX_TOOL_NAME_LEN
));
}
if crate::core::has_dangerous_chars(&self.tool_name) {
return Err("SchemaRecord tool_name contains control or format characters".to_string());
}
// Validate schema_hash
if self.schema_hash.len() > Self::MAX_HASH_LEN {
return Err(format!(
"SchemaRecord schema_hash length {} exceeds max {}",
self.schema_hash.len(),
Self::MAX_HASH_LEN
));
}
if crate::core::has_dangerous_chars(&self.schema_hash) {
return Err(
"SchemaRecord schema_hash contains control or format characters".to_string(),
);
}
// Delegate to existing sub-validators
self.validate_finite_inner()?;
self.validate_version_history()?;
Ok(())
}
/// Validate that all float fields are finite (not NaN or Infinity).
#[deprecated(since = "4.0.1", note = "use validate() instead")]
pub fn validate_finite(&self) -> Result<(), String> {
self.validate_finite_inner()
}
/// Inner float validation (called by both `validate()` and deprecated `validate_finite()`).
fn validate_finite_inner(&self) -> Result<(), String> {
if !self.trust_score.is_finite() {
return Err(format!(
"SchemaRecord '{}' trust_score is not finite: {}",
self.tool_name, self.trust_score
));
}
// SECURITY (FIND-R51-001): Validate trust_score is in documented [0.0, 1.0] range.
if self.trust_score < 0.0 || self.trust_score > 1.0 {
return Err(format!(
"SchemaRecord '{}' trust_score must be in [0.0, 1.0], got {}",
self.tool_name, self.trust_score
));
}
Ok(())
}
/// Create a new schema record with initial observation.
pub fn new(tool_name: impl Into<String>, schema_hash: impl Into<String>, now: u64) -> Self {
Self {
tool_name: tool_name.into(),
schema_hash: schema_hash.into(),
first_seen: now,
last_seen: now,
version_history: Vec::new(),
trust_score: 0.0, // Start with no trust
schema_content: None,
}
}
/// Create a new schema record with content stored (if under size limit).
pub fn new_with_content(
tool_name: impl Into<String>,
schema_hash: impl Into<String>,
schema: &serde_json::Value,
now: u64,
) -> Self {
let content = serde_json::to_string(schema)
.ok()
.filter(|s| s.len() <= Self::MAX_SCHEMA_SIZE)
.map(|_| schema.clone());
Self {
tool_name: tool_name.into(),
schema_hash: schema_hash.into(),
first_seen: now,
last_seen: now,
version_history: Vec::new(),
trust_score: 0.0,
schema_content: content,
}
}
/// Push a schema hash into version_history, evicting the oldest entry
/// if the history exceeds [`Self::MAX_VERSION_HISTORY`].
///
/// SECURITY (FIND-R46-016): Prevents unbounded growth of version_history.
/// SECURITY: Truncates hash entries that exceed [`Self::MAX_HASH_LEN`].
pub fn push_version(&mut self, hash: String) {
// SECURITY (FIND-R82-001): Truncate entry at a UTF-8 char boundary
// to prevent panic on multi-byte characters.
let hash = if hash.len() > Self::MAX_HASH_LEN {
let mut end = Self::MAX_HASH_LEN;
while end > 0 && !hash.is_char_boundary(end) {
end -= 1;
}
hash[..end].to_string()
} else {
hash
};
self.version_history.push(hash);
while self.version_history.len() > Self::MAX_VERSION_HISTORY {
self.version_history.remove(0);
}
}
/// Validate that version_history does not exceed the maximum allowed length,
/// and that each entry does not exceed [`Self::MAX_HASH_LEN`].
/// Returns an error if any invariant is violated.
pub fn validate_version_history(&self) -> Result<(), String> {
if self.version_history.len() > Self::MAX_VERSION_HISTORY {
return Err(format!(
"SchemaRecord '{}' version_history has {} entries (max {})",
self.tool_name,
self.version_history.len(),
Self::MAX_VERSION_HISTORY,
));
}
for (i, entry) in self.version_history.iter().enumerate() {
if entry.len() > Self::MAX_HASH_LEN {
return Err(format!(
"SchemaRecord '{}' version_history[{}] length {} exceeds max {}",
self.tool_name,
i,
entry.len(),
Self::MAX_HASH_LEN,
));
}
}
Ok(())
}
/// Returns the number of schema versions observed.
pub fn version_count(&self) -> usize {
self.version_history.len() + 1 // Current + history
}
/// Returns true if the schema has been stable (no changes in history).
pub fn is_stable(&self) -> bool {
self.version_history.is_empty()
|| self.version_history.iter().all(|h| h == &self.schema_hash)
}
}
/// Principal context for confused deputy prevention.
///
/// Tracks the delegation chain to prevent unauthorized tool access
/// via confused deputy attacks (OWASP ASI02).
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]
#[serde(deny_unknown_fields)]
pub struct PrincipalContext {
/// The original principal that initiated the request.
pub original_principal: String,
/// The principal the original delegated to, if any.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub delegated_to: Option<String>,
/// Depth of the delegation chain (0 = direct, 1+ = delegated).
pub delegation_depth: u8,
/// Tools the delegate is allowed to access.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub allowed_tools: Vec<String>,
/// Unix timestamp when the delegation expires, if any.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub delegation_expires: Option<u64>,
}
impl PrincipalContext {
/// Create a new context for a direct (non-delegated) principal.
pub fn direct(principal: impl Into<String>) -> Self {
Self {
original_principal: principal.into(),
delegated_to: None,
delegation_depth: 0,
allowed_tools: Vec::new(),
delegation_expires: None,
}
}
/// Returns true if this context represents a delegated request.
pub fn is_delegated(&self) -> bool {
self.delegated_to.is_some()
}
/// Returns true if the delegation has expired.
pub fn is_expired(&self, now: u64) -> bool {
self.delegation_expires.is_some_and(|exp| now >= exp)
}
/// Maximum number of allowed_tools entries.
const MAX_ALLOWED_TOOLS: usize = 1000;
/// Maximum length for principal/tool name strings (bytes).
const MAX_PRINCIPAL_LEN: usize = 256;
/// Validate structural invariants of a `PrincipalContext`.
///
/// SECURITY (FIND-R55-CORE-006): Bounds `allowed_tools` count and per-entry length,
/// validates `original_principal` and `delegated_to` for control/format characters
/// and length, and validates `expires_at` (if present) is non-zero.
pub fn validate(&self) -> Result<(), String> {
// Validate original_principal
if self.original_principal.is_empty() {
return Err("PrincipalContext original_principal must not be empty".to_string());
}
if self.original_principal.len() > Self::MAX_PRINCIPAL_LEN {
return Err(format!(
"PrincipalContext original_principal length {} exceeds max {}",
self.original_principal.len(),
Self::MAX_PRINCIPAL_LEN,
));
}
if crate::core::has_dangerous_chars(&self.original_principal) {
return Err(
"PrincipalContext original_principal contains control or format characters"
.to_string(),
);
}
// Validate delegated_to
if let Some(ref delegated) = self.delegated_to {
if delegated.is_empty() {
return Err("PrincipalContext delegated_to is present but empty".to_string());
}
if delegated.len() > Self::MAX_PRINCIPAL_LEN {
return Err(format!(
"PrincipalContext delegated_to length {} exceeds max {}",
delegated.len(),
Self::MAX_PRINCIPAL_LEN,
));
}
if delegated
.chars()
.any(|c| c.is_control() || crate::core::is_unicode_format_char(c))
{
return Err(
"PrincipalContext delegated_to contains control or format characters"
.to_string(),
);
}
}
// Validate allowed_tools count and per-entry length
if self.allowed_tools.len() > Self::MAX_ALLOWED_TOOLS {
return Err(format!(
"PrincipalContext allowed_tools has {} entries, max {}",
self.allowed_tools.len(),
Self::MAX_ALLOWED_TOOLS,
));
}
for (i, tool) in self.allowed_tools.iter().enumerate() {
if tool.len() > Self::MAX_PRINCIPAL_LEN {
return Err(format!(
"PrincipalContext allowed_tools[{}] length {} exceeds max {}",
i,
tool.len(),
Self::MAX_PRINCIPAL_LEN,
));
}
// SECURITY (FIND-R146-TE-003): Reject control and Unicode format characters
// in allowed_tools entries, matching original_principal and delegated_to validation.
if crate::core::has_dangerous_chars(tool) {
return Err(format!(
"PrincipalContext allowed_tools[{i}] contains control or format characters",
));
}
}
// Validate delegation_expires if present (non-zero guard)
if let Some(expires) = self.delegation_expires {
if expires == 0 {
return Err(
"PrincipalContext delegation_expires must be non-zero if present".to_string(),
);
}
}
Ok(())
}
}
/// Statistics for sampling request rate limiting.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]
#[serde(deny_unknown_fields)]
pub struct SamplingStats {
/// Number of sampling requests in the current window.
pub request_count: u32,
/// Unix timestamp of the last sampling request.
pub last_request: u64,
/// Unix timestamp when the current window started.
pub window_start: u64,
/// Patterns flagged in recent requests (for monitoring).
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub flagged_patterns: Vec<String>,
}
impl SamplingStats {
/// Create new stats starting now.
pub fn new(now: u64) -> Self {
Self {
request_count: 0,
last_request: now,
window_start: now,
flagged_patterns: Vec::new(),
}
}
/// Maximum flagged patterns retained across window resets.
const MAX_FLAGGED_PATTERNS: usize = 1000;
/// Maximum byte length for a single entry in `flagged_patterns`.
///
/// SECURITY: Prevents memory exhaustion from excessively long pattern
/// strings in deserialized or accumulated `flagged_patterns` vectors.
pub const MAX_PATTERN_ENTRY_LEN: usize = 1024;
/// Reset the window, truncating flagged patterns if over limit and
/// capping individual entry lengths.
///
/// SECURITY (FIND-R48-010): Patterns accumulated without bound across resets.
/// SECURITY: Per-entry length cap prevents individual oversized entries.
pub fn reset_window(&mut self, now: u64) {
self.request_count = 0;
self.window_start = now;
// SECURITY (FIND-R82-002): Truncate individual entries at a UTF-8 char
// boundary to prevent panic on multi-byte characters.
for entry in &mut self.flagged_patterns {
if entry.len() > Self::MAX_PATTERN_ENTRY_LEN {
let mut end = Self::MAX_PATTERN_ENTRY_LEN;
while end > 0 && !entry.is_char_boundary(end) {
end -= 1;
}
entry.truncate(end);
}
}
if self.flagged_patterns.len() > Self::MAX_FLAGGED_PATTERNS {
self.flagged_patterns.truncate(Self::MAX_FLAGGED_PATTERNS);
}
}
/// Record a request and return the new count.
/// Uses saturating arithmetic to prevent overflow panic.
pub fn record_request(&mut self, now: u64) -> u32 {
self.last_request = now;
self.request_count = self.request_count.saturating_add(1);
self.request_count
}
}
/// Validation errors for Action fields.
#[derive(Debug, Clone, PartialEq)]
pub enum ValidationError {
/// Tool or function name is empty.
EmptyField { field: &'static str },
/// Tool or function name contains a null byte.
NullByte { field: &'static str },
/// Tool or function name contains a control character (tab, newline, etc.).
ControlCharacter { field: &'static str },
/// Tool or function name exceeds the maximum length.
TooLong {
field: &'static str,
len: usize,
max: usize,
},
/// Too many `target_paths` + `target_domains` entries.
TooManyTargets { count: usize, max: usize },
/// A target path or domain string is too long.
TargetTooLong {
field: &'static str,
index: usize,
len: usize,
max: usize,
},
/// A target path or domain contains a null byte.
TargetNullByte { field: &'static str, index: usize },
/// Serialized parameters exceed the maximum allowed size.
///
/// SECURITY (FIND-P3-016): Prevents memory exhaustion from oversized
/// parameter payloads being deserialized and evaluated.
ParametersTooLarge { size: usize, max: usize },
}
impl fmt::Display for ValidationError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ValidationError::EmptyField { field } => {
write!(f, "Action {field} must not be empty")
}
ValidationError::NullByte { field } => {
write!(f, "Action {field} contains null byte")
}
ValidationError::ControlCharacter { field } => {
write!(f, "Action {field} contains control character")
}
ValidationError::TooLong { field, len, max } => {
write!(f, "Action {field} too long: {len} bytes (max {max})")
}
ValidationError::TooManyTargets { count, max } => {
write!(f, "Too many targets: {count} (max {max})")
}
ValidationError::TargetTooLong {
field,
index,
len,
max,
} => {
write!(
f,
"Target {field}[{index}] too long: {len} bytes (max {max})"
)
}
ValidationError::TargetNullByte { field, index } => {
write!(f, "Target {field}[{index}] contains null byte")
}
ValidationError::ParametersTooLarge { size, max } => {
write!(f, "Action parameters too large: {size} bytes (max {max})")
}
}
}
}
impl std::error::Error for ValidationError {}
#[cfg(test)]
mod tests {
use super::*;
// ── AuthLevel::from_u8 ──────────────────────────────────────────────
#[test]
fn test_auth_level_from_u8_all_valid_values() {
assert_eq!(AuthLevel::from_u8(0), AuthLevel::None);
assert_eq!(AuthLevel::from_u8(1), AuthLevel::Basic);
assert_eq!(AuthLevel::from_u8(2), AuthLevel::OAuth);
assert_eq!(AuthLevel::from_u8(3), AuthLevel::OAuthMfa);
assert_eq!(AuthLevel::from_u8(4), AuthLevel::HardwareKey);
}
#[test]
fn test_auth_level_from_u8_unknown_values_fail_closed() {
// Fail-closed: unknown values map to None (lowest level)
assert_eq!(AuthLevel::from_u8(5), AuthLevel::None);
assert_eq!(AuthLevel::from_u8(100), AuthLevel::None);
assert_eq!(AuthLevel::from_u8(255), AuthLevel::None);
}
// ── AuthLevel::satisfies ────────────────────────────────────────────
#[test]
fn test_auth_level_satisfies_same_level_ok() {
assert!(AuthLevel::Basic.satisfies(AuthLevel::Basic));
assert!(AuthLevel::HardwareKey.satisfies(AuthLevel::HardwareKey));
}
#[test]
fn test_auth_level_satisfies_higher_meets_lower() {
assert!(AuthLevel::HardwareKey.satisfies(AuthLevel::None));
assert!(AuthLevel::OAuthMfa.satisfies(AuthLevel::OAuth));
assert!(AuthLevel::OAuth.satisfies(AuthLevel::Basic));
}
#[test]
fn test_auth_level_satisfies_lower_fails_higher() {
assert!(!AuthLevel::None.satisfies(AuthLevel::Basic));
assert!(!AuthLevel::Basic.satisfies(AuthLevel::OAuth));
assert!(!AuthLevel::OAuth.satisfies(AuthLevel::OAuthMfa));
assert!(!AuthLevel::OAuthMfa.satisfies(AuthLevel::HardwareKey));
}
#[test]
fn test_auth_level_satisfies_none_satisfies_none() {
assert!(AuthLevel::None.satisfies(AuthLevel::None));
}
// ── McpCapability::validate() ───────────────────────────────────────
#[test]
fn test_mcp_capability_validate_valid_ok() {
let cap = McpCapability::new("tools");
assert!(cap.validate().is_ok());
}
#[test]
fn test_mcp_capability_validate_empty_name_rejected() {
let cap = McpCapability::new("");
let err = cap.validate().unwrap_err();
assert!(err.contains("must not be empty"), "got: {err}");
}
#[test]
fn test_mcp_capability_validate_name_too_long_rejected() {
let cap = McpCapability::new("x".repeat(257));
let err = cap.validate().unwrap_err();
assert!(err.contains("name length"), "got: {err}");
}
#[test]
fn test_mcp_capability_validate_name_control_chars_rejected() {
let cap = McpCapability::new("tools\x00bad");
let err = cap.validate().unwrap_err();
assert!(err.contains("control or format"), "got: {err}");
}
#[test]
fn test_mcp_capability_validate_version_too_long_rejected() {
let cap = McpCapability::with_version("tools", "v".repeat(129));
let err = cap.validate().unwrap_err();
assert!(err.contains("version length"), "got: {err}");
}
#[test]
fn test_mcp_capability_validate_sub_capabilities_count_rejected() {
let mut cap = McpCapability::new("tools");
cap.sub_capabilities = vec!["sub".to_string(); MAX_SUB_CAPABILITIES + 1];
let err = cap.validate().unwrap_err();
assert!(err.contains("sub_capabilities count"), "got: {err}");
}
#[test]
fn test_mcp_capability_validate_sub_capability_too_long_rejected() {
let mut cap = McpCapability::new("tools");
cap.sub_capabilities = vec!["x".repeat(257)];
let err = cap.validate().unwrap_err();
assert!(err.contains("sub_capabilities[0] length"), "got: {err}");
}
#[test]
fn test_mcp_capability_validate_sub_capability_control_chars_rejected() {
let mut cap = McpCapability::new("tools");
cap.sub_capabilities = vec!["read".into(), "write\x01bad".into()];
let err = cap.validate().unwrap_err();
assert!(
err.contains("sub_capabilities[1]") && err.contains("control or format"),
"got: {err}"
);
}
#[test]
fn test_mcp_capability_validate_at_max_sub_capabilities_ok() {
let mut cap = McpCapability::new("tools");
cap.sub_capabilities = vec!["s".to_string(); MAX_SUB_CAPABILITIES];
assert!(cap.validate().is_ok());
}
#[test]
fn test_mcp_capability_has_sub() {
let mut cap = McpCapability::new("tools");
cap.sub_capabilities = vec!["read".into(), "write".into()];
assert!(cap.has_sub("read"));
assert!(!cap.has_sub("execute"));
}
// ── SchemaRecord::validate() ────────────────────────────────────────
#[test]
fn test_schema_record_validate_valid_ok() {
let sr = SchemaRecord::new("my-tool", "abc123", 1000);
assert!(sr.validate().is_ok());
}
#[test]
fn test_schema_record_validate_empty_tool_name_rejected() {
let sr = SchemaRecord::new("", "hash", 1000);
assert!(sr
.validate()
.unwrap_err()
.contains("tool_name must not be empty"));
}
#[test]
fn test_schema_record_validate_trust_score_nan_rejected() {
let mut sr = SchemaRecord::new("tool", "hash", 1000);
sr.trust_score = f32::NAN;
assert!(sr.validate().unwrap_err().contains("not finite"));
}
#[test]
fn test_schema_record_validate_trust_score_out_of_range_rejected() {
let mut sr = SchemaRecord::new("tool", "hash", 1000);
sr.trust_score = 1.5;
assert!(sr.validate().unwrap_err().contains("[0.0, 1.0]"));
sr.trust_score = -0.1;
assert!(sr.validate().unwrap_err().contains("[0.0, 1.0]"));
}
#[test]
fn test_schema_record_validate_version_history_overflow_rejected() {
let mut sr = SchemaRecord::new("tool", "hash", 1000);
sr.version_history = vec!["h".to_string(); SchemaRecord::MAX_VERSION_HISTORY + 1];
assert!(sr.validate().unwrap_err().contains("version_history"));
}
// ── PrincipalContext::validate() ────────────────────────────────────
#[test]
fn test_principal_context_validate_valid_direct_ok() {
let pc = PrincipalContext::direct("agent-1");
assert!(pc.validate().is_ok());
}
#[test]
fn test_principal_context_validate_empty_principal_rejected() {
let pc = PrincipalContext::direct("");
assert!(pc.validate().unwrap_err().contains("must not be empty"));
}
#[test]
fn test_principal_context_validate_expires_zero_rejected() {
let mut pc = PrincipalContext::direct("agent-1");
pc.delegation_expires = Some(0);
assert!(pc.validate().unwrap_err().contains("must be non-zero"));
}
}