use serde::{Deserialize, Serialize};
use crate::core::Verdict;
use crate::has_dangerous_chars;
use crate::identity::AgentIdentity;
use crate::provenance::{
validate_lineage_refs, ClientProvenance, ContainmentMode, LineageRef, SemanticRiskScore,
SemanticTaint, SinkClass, TrustTier,
};
const MAX_DECISION_ID_LEN: usize = 64;
const MAX_SESSION_ID_LEN: usize = 512;
const MAX_FINGERPRINT_LEN: usize = 128;
const MAX_POLICY_ID_LEN: usize = 256;
const MAX_REASON_LEN: usize = 4096;
const MAX_TENANT_ID_LEN: usize = 256;
const MAX_TRANSPORT_LEN: usize = 32;
const MAX_AGENT_ID_LEN: usize = 512;
const MAX_TOOL_LEN: usize = 256;
const MAX_FUNCTION_LEN: usize = 256;
const MAX_FINDINGS: usize = 64;
const MAX_FINDING_LEN: usize = 512;
const MAX_SEMANTIC_TAINT: usize = 32;
const MAX_EVALUATION_US: u64 = 3_600_000_000;
const MAX_CALL_CHAIN_DEPTH: u32 = 256;
const MAX_TARGET_COUNT: u32 = 100_000;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum DecisionKind {
Allow,
Deny,
RequireApproval,
}
impl Default for DecisionKind {
fn default() -> Self {
Self::Deny
}
}
impl From<&Verdict> for DecisionKind {
fn from(v: &Verdict) -> Self {
match v {
Verdict::Allow => Self::Allow,
Verdict::Deny { .. } => Self::Deny,
Verdict::RequireApproval { .. } => Self::RequireApproval,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum DecisionOrigin {
PolicyEngine,
Dlp,
InjectionScanner,
MemoryPoisoning,
ApprovalGate,
CapabilityEnforcement,
RateLimiter,
CircuitBreaker,
TopologyGuard,
SessionGuard,
ProvenanceGuard,
SemanticContainment,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct AcisActionSummary {
pub tool: String,
pub function: String,
pub target_path_count: u32,
pub target_domain_count: u32,
}
impl AcisActionSummary {
pub fn validate(&self) -> Result<(), String> {
if self.tool.is_empty() {
return Err("action_summary.tool must not be empty".into());
}
if self.tool.len() > MAX_TOOL_LEN {
return Err("action_summary.tool exceeds maximum length".into());
}
if has_dangerous_chars(&self.tool) {
return Err("action_summary.tool contains dangerous characters".into());
}
if self.function.is_empty() {
return Err("action_summary.function must not be empty".into());
}
if self.function.len() > MAX_FUNCTION_LEN {
return Err("action_summary.function exceeds maximum length".into());
}
if has_dangerous_chars(&self.function) {
return Err("action_summary.function contains dangerous characters".into());
}
if self.target_path_count > MAX_TARGET_COUNT {
return Err("action_summary.target_path_count exceeds maximum".into());
}
if self.target_domain_count > MAX_TARGET_COUNT {
return Err("action_summary.target_domain_count exceeds maximum".into());
}
Ok(())
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct AcisDecisionEnvelope {
pub decision_id: String,
pub timestamp: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub session_id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tenant_id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub agent_identity: Option<AgentIdentity>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub agent_id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub client_provenance: Option<ClientProvenance>,
pub action_summary: AcisActionSummary,
pub action_fingerprint: String,
pub decision: DecisionKind,
pub origin: DecisionOrigin,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub reason: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub matched_policy_id: Option<String>,
pub transport: String,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub findings: Vec<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub semantic_taint: Vec<SemanticTaint>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub lineage_refs: Vec<LineageRef>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub effective_trust_tier: Option<TrustTier>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub sink_class: Option<SinkClass>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub containment_mode: Option<ContainmentMode>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub semantic_risk_score: Option<SemanticRiskScore>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub evaluation_us: Option<u64>,
#[serde(default)]
pub call_chain_depth: u32,
}
impl AcisDecisionEnvelope {
pub fn validate(&self) -> Result<(), String> {
if self.decision_id.is_empty() {
return Err("acis: decision_id must not be empty".into());
}
if self.decision_id.len() > MAX_DECISION_ID_LEN {
return Err("acis: decision_id exceeds maximum length".into());
}
if has_dangerous_chars(&self.decision_id) {
return Err("acis: decision_id contains dangerous characters".into());
}
if self.timestamp.is_empty() {
return Err("acis: timestamp must not be empty".into());
}
if !self.timestamp.ends_with('Z')
&& !self.timestamp.ends_with('z')
&& !self.timestamp.ends_with("+00:00")
{
return Err("acis: timestamp must be UTC (end with Z or +00:00)".into());
}
if let Some(ref sid) = self.session_id {
if sid.len() > MAX_SESSION_ID_LEN {
return Err("acis: session_id exceeds maximum length".into());
}
if has_dangerous_chars(sid) {
return Err("acis: session_id contains dangerous characters".into());
}
}
if let Some(ref tid) = self.tenant_id {
if tid.len() > MAX_TENANT_ID_LEN {
return Err("acis: tenant_id exceeds maximum length".into());
}
if has_dangerous_chars(tid) {
return Err("acis: tenant_id contains dangerous characters".into());
}
}
if let Some(ref aid) = self.agent_id {
if aid.is_empty() {
return Err("acis: agent_id must not be empty when present".into());
}
if aid.len() > MAX_AGENT_ID_LEN {
return Err("acis: agent_id exceeds maximum length".into());
}
if has_dangerous_chars(aid) {
return Err("acis: agent_id contains dangerous characters".into());
}
}
if let Some(ref identity) = self.agent_identity {
if let Err(e) = identity.validate() {
return Err(format!("acis: agent_identity validation failed: {e}"));
}
}
if let Some(ref provenance) = self.client_provenance {
provenance
.validate()
.map_err(|e| format!("acis: client_provenance validation failed: {e}"))?;
}
if self.action_fingerprint.is_empty() {
return Err("acis: action_fingerprint must not be empty".into());
}
if self.action_fingerprint.len() > MAX_FINGERPRINT_LEN {
return Err("acis: action_fingerprint exceeds maximum length".into());
}
self.action_summary
.validate()
.map_err(|e| format!("acis: {e}"))?;
if self.reason.len() > MAX_REASON_LEN {
return Err("acis: reason exceeds maximum length".into());
}
if has_dangerous_chars(&self.reason) {
return Err("acis: reason contains dangerous characters".into());
}
if let Some(ref pid) = self.matched_policy_id {
if pid.len() > MAX_POLICY_ID_LEN {
return Err("acis: matched_policy_id exceeds maximum length".into());
}
if has_dangerous_chars(pid) {
return Err("acis: matched_policy_id contains dangerous characters".into());
}
}
if self.transport.is_empty() {
return Err("acis: transport must not be empty".into());
}
if self.transport.len() > MAX_TRANSPORT_LEN {
return Err("acis: transport exceeds maximum length".into());
}
if has_dangerous_chars(&self.transport) {
return Err("acis: transport contains dangerous characters".into());
}
if self.findings.len() > MAX_FINDINGS {
return Err("acis: findings exceeds maximum count".into());
}
for (i, f) in self.findings.iter().enumerate() {
if f.len() > MAX_FINDING_LEN {
return Err(format!("acis: findings[{i}] exceeds maximum length"));
}
if has_dangerous_chars(f) {
return Err(format!("acis: findings[{i}] contains dangerous characters"));
}
}
if self.semantic_taint.len() > MAX_SEMANTIC_TAINT {
return Err("acis: semantic_taint exceeds maximum count".into());
}
validate_lineage_refs(&self.lineage_refs).map_err(|e| format!("acis: {e}"))?;
if let Some(ref risk_score) = self.semantic_risk_score {
risk_score.validate().map_err(|e| format!("acis: {e}"))?;
}
if let Some(us) = self.evaluation_us {
if us > MAX_EVALUATION_US {
return Err("acis: evaluation_us exceeds maximum (1 hour)".into());
}
}
if self.call_chain_depth > MAX_CALL_CHAIN_DEPTH {
return Err("acis: call_chain_depth exceeds maximum (256)".into());
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
fn minimal_envelope() -> AcisDecisionEnvelope {
AcisDecisionEnvelope {
decision_id: "550e8400-e29b-41d4-a716-446655440000".into(),
timestamp: "2026-03-09T10:00:00Z".into(),
session_id: None,
tenant_id: None,
agent_identity: None,
agent_id: None,
client_provenance: None,
action_summary: AcisActionSummary {
tool: "file_write".into(),
function: "write".into(),
target_path_count: 1,
target_domain_count: 0,
},
action_fingerprint: "a1b2c3d4e5f6".into(),
decision: DecisionKind::Allow,
origin: DecisionOrigin::PolicyEngine,
reason: String::new(),
matched_policy_id: Some("policy-001".into()),
transport: "stdio".into(),
findings: vec![],
semantic_taint: vec![],
lineage_refs: vec![],
effective_trust_tier: None,
sink_class: None,
containment_mode: None,
semantic_risk_score: None,
evaluation_us: Some(42),
call_chain_depth: 0,
}
}
#[test]
fn test_minimal_envelope_validates() {
let env = minimal_envelope();
assert!(env.validate().is_ok());
}
#[test]
fn test_decision_kind_default_is_deny() {
assert_eq!(DecisionKind::default(), DecisionKind::Deny);
}
#[test]
fn test_decision_kind_from_verdict() {
assert_eq!(DecisionKind::from(&Verdict::Allow), DecisionKind::Allow);
assert_eq!(
DecisionKind::from(&Verdict::Deny { reason: "x".into() }),
DecisionKind::Deny
);
assert_eq!(
DecisionKind::from(&Verdict::RequireApproval { reason: "x".into() }),
DecisionKind::RequireApproval
);
}
#[test]
fn test_empty_decision_id_rejected() {
let mut env = minimal_envelope();
env.decision_id = String::new();
let err = env.validate().unwrap_err();
assert!(err.contains("decision_id must not be empty"));
}
#[test]
fn test_non_utc_timestamp_rejected() {
let mut env = minimal_envelope();
env.timestamp = "2026-03-09T10:00:00+01:00".into();
let err = env.validate().unwrap_err();
assert!(err.contains("timestamp must be UTC"));
}
#[test]
fn test_dangerous_chars_in_session_id_rejected() {
let mut env = minimal_envelope();
env.session_id = Some("sess\x00ion".into());
let err = env.validate().unwrap_err();
assert!(err.contains("session_id contains dangerous"));
}
#[test]
fn test_empty_transport_rejected() {
let mut env = minimal_envelope();
env.transport = String::new();
let err = env.validate().unwrap_err();
assert!(err.contains("transport must not be empty"));
}
#[test]
fn test_too_many_findings_rejected() {
let mut env = minimal_envelope();
env.findings = vec!["f".into(); 65];
let err = env.validate().unwrap_err();
assert!(err.contains("findings exceeds maximum count"));
}
#[test]
fn test_empty_fingerprint_rejected() {
let mut env = minimal_envelope();
env.action_fingerprint = String::new();
let err = env.validate().unwrap_err();
assert!(err.contains("action_fingerprint must not be empty"));
}
#[test]
fn test_oversized_fingerprint_rejected() {
let mut env = minimal_envelope();
env.action_fingerprint = "x".repeat(129);
let err = env.validate().unwrap_err();
assert!(err.contains("action_fingerprint exceeds maximum length"));
}
#[test]
fn test_envelope_serialization_roundtrip() {
let env = minimal_envelope();
let json = serde_json::to_string(&env).expect("serialize");
let decoded: AcisDecisionEnvelope = serde_json::from_str(&json).expect("deserialize");
assert_eq!(decoded.decision_id, env.decision_id);
assert_eq!(decoded.action_fingerprint, env.action_fingerprint);
assert_eq!(decoded.decision, env.decision);
}
#[test]
fn test_deny_unknown_fields_rejects_extra() {
let json = r#"{
"decision_id": "abc",
"timestamp": "2026-03-09T00:00:00Z",
"action_summary": {"tool":"t","function":"f","target_path_count":0,"target_domain_count":0},
"action_fingerprint": "abc123",
"decision": "allow",
"origin": "policy_engine",
"transport": "http",
"call_chain_depth": 0,
"evil_field": true
}"#;
assert!(serde_json::from_str::<AcisDecisionEnvelope>(json).is_err());
}
#[test]
fn test_dangerous_chars_in_tenant_id_rejected() {
let mut env = minimal_envelope();
env.tenant_id = Some("tenant\x07id".into());
let err = env.validate().unwrap_err();
assert!(err.contains("tenant_id contains dangerous"));
}
#[test]
fn test_oversized_reason_rejected() {
let mut env = minimal_envelope();
env.reason = "x".repeat(4097);
let err = env.validate().unwrap_err();
assert!(err.contains("reason exceeds maximum length"));
}
#[test]
fn test_finding_too_long_rejected() {
let mut env = minimal_envelope();
env.findings = vec!["x".repeat(513)];
let err = env.validate().unwrap_err();
assert!(err.contains("findings[0] exceeds maximum length"));
}
#[test]
fn test_utc_plus_zero_timestamp_accepted() {
let mut env = minimal_envelope();
env.timestamp = "2026-03-09T10:00:00+00:00".into();
assert!(env.validate().is_ok());
}
#[test]
fn test_r244_agent_id_dangerous_chars_rejected() {
let mut env = minimal_envelope();
env.agent_id = Some("agent\x00id".into());
let err = env.validate().unwrap_err();
assert!(err.contains("agent_id contains dangerous"));
}
#[test]
fn test_r244_agent_id_oversized_rejected() {
let mut env = minimal_envelope();
env.agent_id = Some("a".repeat(513));
let err = env.validate().unwrap_err();
assert!(err.contains("agent_id exceeds maximum length"));
}
#[test]
fn test_r244_agent_id_valid_accepted() {
let mut env = minimal_envelope();
env.agent_id = Some("claude-agent-v4".into());
assert!(env.validate().is_ok());
}
#[test]
fn test_r244_agent_id_empty_rejected() {
let mut env = minimal_envelope();
env.agent_id = Some(String::new());
let err = env.validate().unwrap_err();
assert!(err.contains("agent_id must not be empty"));
}
#[test]
fn test_r244_tool_oversized_rejected() {
let mut env = minimal_envelope();
env.action_summary.tool = "t".repeat(257);
let err = env.validate().unwrap_err();
assert!(err.contains("action_summary.tool exceeds maximum length"));
}
#[test]
fn test_r244_function_oversized_rejected() {
let mut env = minimal_envelope();
env.action_summary.function = "f".repeat(257);
let err = env.validate().unwrap_err();
assert!(err.contains("action_summary.function exceeds maximum length"));
}
#[test]
fn test_r244_function_empty_rejected() {
let mut env = minimal_envelope();
env.action_summary.function = String::new();
let err = env.validate().unwrap_err();
assert!(err.contains("action_summary.function must not be empty"));
}
#[test]
fn test_r244_agent_identity_validation_delegated() {
let mut env = minimal_envelope();
let mut identity = AgentIdentity::default();
for i in 0..65 {
identity
.claims
.insert(format!("claim_{i}"), serde_json::json!("v"));
}
env.agent_identity = Some(identity);
let err = env.validate().unwrap_err();
assert!(
err.contains("agent_identity validation failed"),
"expected nested validation delegation: {err}"
);
}
#[test]
fn test_r244_reason_dangerous_chars_rejected() {
let mut env = minimal_envelope();
env.reason = "denied\x07bell".into();
let err = env.validate().unwrap_err();
assert!(err.contains("reason contains dangerous"));
}
#[test]
fn test_r244_finding_dangerous_chars_rejected() {
let mut env = minimal_envelope();
env.findings = vec!["DLP: found key\x00 in params".into()];
let err = env.validate().unwrap_err();
assert!(err.contains("findings[0] contains dangerous"));
}
#[test]
fn test_r244_finding_bidi_chars_rejected() {
let mut env = minimal_envelope();
env.findings = vec!["injection: found \u{202E}override".into()];
let err = env.validate().unwrap_err();
assert!(err.contains("findings[0] contains dangerous"));
}
#[test]
fn test_r244_evaluation_us_max_rejected() {
let mut env = minimal_envelope();
env.evaluation_us = Some(3_600_000_001);
let err = env.validate().unwrap_err();
assert!(err.contains("evaluation_us exceeds maximum"));
}
#[test]
fn test_r244_evaluation_us_max_accepted() {
let mut env = minimal_envelope();
env.evaluation_us = Some(3_600_000_000);
assert!(env.validate().is_ok());
}
#[test]
fn test_r244_call_chain_depth_max_rejected() {
let mut env = minimal_envelope();
env.call_chain_depth = 257;
let err = env.validate().unwrap_err();
assert!(err.contains("call_chain_depth exceeds maximum"));
}
#[test]
fn test_r244_call_chain_depth_max_accepted() {
let mut env = minimal_envelope();
env.call_chain_depth = 256;
assert!(env.validate().is_ok());
}
#[test]
fn test_r246_target_path_count_max_rejected() {
let mut env = minimal_envelope();
env.action_summary.target_path_count = 100_001;
let err = env.validate().unwrap_err();
assert!(err.contains("target_path_count exceeds maximum"));
}
#[test]
fn test_r246_target_domain_count_max_rejected() {
let mut env = minimal_envelope();
env.action_summary.target_domain_count = 100_001;
let err = env.validate().unwrap_err();
assert!(err.contains("target_domain_count exceeds maximum"));
}
#[test]
fn test_r246_target_counts_at_max_accepted() {
let mut env = minimal_envelope();
env.action_summary.target_path_count = 100_000;
env.action_summary.target_domain_count = 100_000;
assert!(env.validate().is_ok());
}
#[test]
fn test_r246_action_summary_standalone_validate_ok() {
let summary = AcisActionSummary {
tool: "file_write".into(),
function: "write".into(),
target_path_count: 5,
target_domain_count: 0,
};
assert!(summary.validate().is_ok());
}
#[test]
fn test_r246_action_summary_standalone_empty_tool_rejected() {
let summary = AcisActionSummary {
tool: String::new(),
function: "write".into(),
target_path_count: 0,
target_domain_count: 0,
};
let err = summary.validate().unwrap_err();
assert!(err.contains("tool must not be empty"));
}
#[test]
fn test_r246_action_summary_standalone_dangerous_chars_rejected() {
let summary = AcisActionSummary {
tool: "file\x00write".into(),
function: "write".into(),
target_path_count: 0,
target_domain_count: 0,
};
let err = summary.validate().unwrap_err();
assert!(err.contains("dangerous characters"));
}
#[test]
fn test_r254_decision_origin_all_variants_roundtrip() {
let origins = [
DecisionOrigin::PolicyEngine,
DecisionOrigin::Dlp,
DecisionOrigin::InjectionScanner,
DecisionOrigin::MemoryPoisoning,
DecisionOrigin::ApprovalGate,
DecisionOrigin::CapabilityEnforcement,
DecisionOrigin::RateLimiter,
DecisionOrigin::CircuitBreaker,
DecisionOrigin::TopologyGuard,
DecisionOrigin::SessionGuard,
DecisionOrigin::ProvenanceGuard,
DecisionOrigin::SemanticContainment,
];
for origin in &origins {
let json = serde_json::to_string(origin).expect("serialize");
let decoded: DecisionOrigin = serde_json::from_str(&json).expect("deserialize");
assert_eq!(
*origin, decoded,
"roundtrip failed for {origin:?}: serialized as {json}"
);
}
}
#[test]
fn test_r254_decision_origin_snake_case_format() {
assert_eq!(
serde_json::to_string(&DecisionOrigin::PolicyEngine).unwrap(),
"\"policy_engine\""
);
assert_eq!(
serde_json::to_string(&DecisionOrigin::InjectionScanner).unwrap(),
"\"injection_scanner\""
);
assert_eq!(
serde_json::to_string(&DecisionOrigin::CircuitBreaker).unwrap(),
"\"circuit_breaker\""
);
assert_eq!(
serde_json::to_string(&DecisionOrigin::SessionGuard).unwrap(),
"\"session_guard\""
);
assert_eq!(
serde_json::to_string(&DecisionOrigin::ProvenanceGuard).unwrap(),
"\"provenance_guard\""
);
assert_eq!(
serde_json::to_string(&DecisionOrigin::SemanticContainment).unwrap(),
"\"semantic_containment\""
);
}
#[test]
fn test_r254_findings_exactly_at_max_accepted() {
let mut env = minimal_envelope();
env.findings = vec!["f".into(); 64];
assert!(env.validate().is_ok());
}
#[test]
fn test_r254_session_id_exactly_at_max_accepted() {
let mut env = minimal_envelope();
env.session_id = Some("s".repeat(512));
assert!(env.validate().is_ok());
}
#[test]
fn test_r254_session_id_over_max_rejected() {
let mut env = minimal_envelope();
env.session_id = Some("s".repeat(513));
let err = env.validate().unwrap_err();
assert!(err.contains("session_id exceeds maximum"));
}
#[test]
fn test_r254_decision_id_exactly_at_max_accepted() {
let mut env = minimal_envelope();
env.decision_id = "d".repeat(64);
assert!(env.validate().is_ok());
}
#[test]
fn test_r254_decision_id_over_max_rejected() {
let mut env = minimal_envelope();
env.decision_id = "d".repeat(65);
let err = env.validate().unwrap_err();
assert!(err.contains("decision_id exceeds maximum"));
}
#[test]
fn test_r254_matched_policy_id_dangerous_chars_rejected() {
let mut env = minimal_envelope();
env.matched_policy_id = Some("policy\x00id".into());
let err = env.validate().unwrap_err();
assert!(err.contains("matched_policy_id contains dangerous"));
}
#[test]
fn test_r254_transport_dangerous_chars_rejected() {
let mut env = minimal_envelope();
env.transport = "http\x07".into();
let err = env.validate().unwrap_err();
assert!(err.contains("transport contains dangerous"));
}
#[test]
fn test_r254_transport_oversized_rejected() {
let mut env = minimal_envelope();
env.transport = "x".repeat(33);
let err = env.validate().unwrap_err();
assert!(err.contains("transport exceeds maximum"));
}
#[test]
fn test_r254_both_target_counts_at_max_accepted() {
let mut env = minimal_envelope();
env.action_summary.target_path_count = 100_000;
env.action_summary.target_domain_count = 100_000;
assert!(env.validate().is_ok());
}
}