use serde::{Deserialize, Serialize};
use std::fmt;
#[derive(
Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash, Default,
)]
#[serde(rename_all = "snake_case")]
#[repr(u8)]
pub enum AuthLevel {
#[default]
None = 0,
Basic = 1,
OAuth = 2,
OAuthMfa = 3,
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 {
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,
}
}
pub fn satisfies(&self, required: AuthLevel) -> bool {
*self >= required
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
pub struct McpCapability {
pub name: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub version: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub sub_capabilities: Vec<String>,
}
pub const MAX_SUB_CAPABILITIES: usize = 100;
impl McpCapability {
const MAX_NAME_LEN: usize = 256;
const MAX_VERSION_LEN: usize = 128;
const MAX_SUB_CAPABILITY_LEN: usize = 256;
pub fn new(name: impl Into<String>) -> Self {
Self {
name: name.into(),
version: None,
sub_capabilities: Vec::new(),
}
}
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(),
}
}
pub fn has_sub(&self, sub: &str) -> bool {
self.sub_capabilities.iter().any(|s| s == sub)
}
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,
));
}
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,
));
}
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(())
}
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
#[serde(rename_all = "snake_case")]
pub enum CircuitState {
#[default]
Closed,
Open,
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"),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(deny_unknown_fields)]
pub struct CircuitStats {
pub state: CircuitState,
pub failure_count: u32,
pub success_count: u32,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub last_failure: Option<u64>,
pub last_state_change: u64,
#[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,
}
}
}
#[derive(Clone, Serialize, Deserialize, PartialEq, Eq, Hash, Default)]
#[serde(deny_unknown_fields)]
pub struct AgentFingerprint {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub jwt_sub: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub jwt_iss: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub client_id: Option<String>,
#[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()
}
}
const MAX_FINGERPRINT_FIELD_LEN: usize = 1024;
impl AgentFingerprint {
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(())
}
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()
}
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(",")
}
}
}
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])
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Default)]
#[serde(rename_all = "snake_case")]
pub enum TrustLevel {
#[default]
Unknown = 0,
Low = 1,
Medium = 2,
High = 3,
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 {
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,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(deny_unknown_fields)]
pub struct SchemaRecord {
pub tool_name: String,
pub schema_hash: String,
pub first_seen: u64,
pub last_seen: u64,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub version_history: Vec<String>,
pub trust_score: f32,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub schema_content: Option<serde_json::Value>,
}
impl SchemaRecord {
pub const MAX_SCHEMA_SIZE: usize = 64 * 1024;
pub const MAX_VERSION_HISTORY: usize = 10;
pub const MAX_HASH_LEN: usize = 128;
const MAX_TOOL_NAME_LEN: usize = 256;
pub fn validate(&self) -> Result<(), String> {
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());
}
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(),
);
}
self.validate_finite_inner()?;
self.validate_version_history()?;
Ok(())
}
#[deprecated(since = "4.0.1", note = "use validate() instead")]
pub fn validate_finite(&self) -> Result<(), String> {
self.validate_finite_inner()
}
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
));
}
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(())
}
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, schema_content: None,
}
}
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,
}
}
pub fn push_version(&mut self, hash: String) {
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);
}
}
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(())
}
pub fn version_count(&self) -> usize {
self.version_history.len() + 1 }
pub fn is_stable(&self) -> bool {
self.version_history.is_empty()
|| self.version_history.iter().all(|h| h == &self.schema_hash)
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]
#[serde(deny_unknown_fields)]
pub struct PrincipalContext {
pub original_principal: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub delegated_to: Option<String>,
pub delegation_depth: u8,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub allowed_tools: Vec<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub delegation_expires: Option<u64>,
}
impl PrincipalContext {
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,
}
}
pub fn is_delegated(&self) -> bool {
self.delegated_to.is_some()
}
pub fn is_expired(&self, now: u64) -> bool {
self.delegation_expires.is_some_and(|exp| now >= exp)
}
const MAX_ALLOWED_TOOLS: usize = 1000;
const MAX_PRINCIPAL_LEN: usize = 256;
pub fn validate(&self) -> Result<(), String> {
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(),
);
}
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(),
);
}
}
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,
));
}
if crate::core::has_dangerous_chars(tool) {
return Err(format!(
"PrincipalContext allowed_tools[{i}] contains control or format characters",
));
}
}
if let Some(expires) = self.delegation_expires {
if expires == 0 {
return Err(
"PrincipalContext delegation_expires must be non-zero if present".to_string(),
);
}
}
Ok(())
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]
#[serde(deny_unknown_fields)]
pub struct SamplingStats {
pub request_count: u32,
pub last_request: u64,
pub window_start: u64,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub flagged_patterns: Vec<String>,
}
impl SamplingStats {
pub fn new(now: u64) -> Self {
Self {
request_count: 0,
last_request: now,
window_start: now,
flagged_patterns: Vec::new(),
}
}
const MAX_FLAGGED_PATTERNS: usize = 1000;
pub const MAX_PATTERN_ENTRY_LEN: usize = 1024;
pub fn reset_window(&mut self, now: u64) {
self.request_count = 0;
self.window_start = now;
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);
}
}
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
}
}
#[derive(Debug, Clone, PartialEq)]
pub enum ValidationError {
EmptyField { field: &'static str },
NullByte { field: &'static str },
ControlCharacter { field: &'static str },
TooLong {
field: &'static str,
len: usize,
max: usize,
},
TooManyTargets { count: usize, max: usize },
TargetTooLong {
field: &'static str,
index: usize,
len: usize,
max: usize,
},
TargetNullByte { field: &'static str, index: usize },
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::*;
#[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() {
assert_eq!(AuthLevel::from_u8(5), AuthLevel::None);
assert_eq!(AuthLevel::from_u8(100), AuthLevel::None);
assert_eq!(AuthLevel::from_u8(255), AuthLevel::None);
}
#[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));
}
#[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"));
}
#[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"));
}
#[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"));
}
}