Skip to main content

chio_guards/
lib.rs

1//! Security guards for the Chio runtime kernel.
2//!
3//! This crate provides policy-driven security guards.  Each guard
4//! implements `chio_kernel::Guard` and can be registered on the kernel via
5//! `kernel.add_guard(...)` or composed into a [`GuardPipeline`].
6//!
7//! # Implemented guards
8//!
9//! | Guard | Status | Description |
10//! |-------|--------|-------------|
11//! | [`ForbiddenPathGuard`] | **Full** | Blocks access to sensitive filesystem paths |
12//! | [`ShellCommandGuard`] | **Full** | Blocks dangerous shell commands |
13//! | [`EgressAllowlistGuard`] | **Full** | Controls network egress by domain |
14//! | [`PathAllowlistGuard`] | **Full** | Allowlist-based path access control |
15//! | [`McpToolGuard`] | **Full** | Restricts MCP tool invocations |
16//! | [`SecretLeakGuard`] | **Full** | Detects secrets in file writes |
17//! | [`PatchIntegrityGuard`] | **Full** | Validates patch safety |
18//! | [`InternalNetworkGuard`] | **Full** | Blocks SSRF targeting private/reserved addresses |
19//! | [`AgentVelocityGuard`] | **Full** | Per-agent and per-session rate limiting |
20//! | [`DataFlowGuard`] | **Full** | Cumulative bytes-read/written limits via session journal |
21//! | [`BehavioralSequenceGuard`] | **Full** | Tool ordering policies via session journal |
22//! | [`ResponseSanitizationGuard`] | **Full** | PII/PHI pattern detection and redaction |
23//! | [`AdvisoryPipeline`] | **Full** | Non-blocking advisory signals with optional promotion |
24//! | [`AnomalyAdvisoryGuard`] | **Full** | Flags unusual invocation patterns and delegation depth |
25//! | [`DataTransferAdvisoryGuard`] | **Full** | Flags high data transfer volumes |
26//! | [`JailbreakGuard`] | **Full** | Multi-layer jailbreak detection (heuristic + statistical + ML) |
27//!
28//! # Guard pipeline
29//!
30//! The [`GuardPipeline`] runs guards in sequence, fail-closed.  If any guard
31//! denies, the pipeline denies.  Register it on the kernel:
32//!
33//! ```ignore
34//! use chio_guards::GuardPipeline;
35//!
36//! let pipeline = GuardPipeline::default_pipeline();
37//! kernel.add_guard(Box::new(pipeline));
38//! ```
39
40#![forbid(unsafe_code)]
41#![cfg_attr(test, allow(clippy::expect_used, clippy::unwrap_used))]
42
43pub mod action;
44mod path_normalization;
45
46pub mod external;
47
48pub mod advisory;
49pub mod agent_velocity;
50pub mod behavioral_profile;
51pub mod behavioral_sequence;
52pub mod data_flow;
53mod egress_allowlist;
54mod forbidden_path;
55pub mod internal_network;
56pub mod jailbreak;
57pub mod jailbreak_detector;
58pub mod mcp_tool;
59pub mod patch_integrity;
60pub mod path_allowlist;
61mod pipeline;
62pub mod post_invocation;
63pub mod prompt_injection;
64pub mod response_sanitization;
65pub mod secret_leak;
66mod shell_command;
67pub mod text_utils;
68pub mod velocity;
69
70// Computer Use Agent (CUA) and EmbeddingAnomaly guards.
71pub mod computer_use;
72pub mod embedding_anomaly;
73pub mod input_injection;
74pub mod remote_desktop;
75
76// Code execution, browser automation, content review, and memory
77// governance guards.
78pub mod browser_automation;
79pub mod code_execution;
80pub mod content_review;
81pub mod memory_governance;
82
83pub use advisory::{
84    AdvisoryGuard, AdvisoryPipeline, AdvisorySeverity, AdvisorySignal, AnomalyAdvisoryGuard,
85    DataTransferAdvisoryGuard, GuardOutput, PromotionPolicy, PromotionRule,
86};
87pub use agent_velocity::{AgentVelocityConfig, AgentVelocityGuard};
88pub use behavioral_profile::{
89    BehavioralMetric, BehavioralProfileConfig, BehavioralProfileGuard, InMemoryReceiptFeed,
90    ObservationOutcome, ReceiptFeedSource, DEFAULT_BASELINE_MIN_WINDOWS, DEFAULT_EMA_ALPHA,
91    DEFAULT_SIGMA_THRESHOLD, DEFAULT_WINDOW_SECS,
92};
93pub use behavioral_sequence::{BehavioralSequenceGuard, SequencePolicy};
94pub use data_flow::{DataFlowConfig, DataFlowGuard};
95pub use egress_allowlist::EgressAllowlistGuard;
96pub use forbidden_path::{ForbiddenPathConfigError, ForbiddenPathGuard};
97pub use internal_network::InternalNetworkGuard;
98pub use jailbreak::{
99    JailbreakGuard, JailbreakGuardConfig,
100    DEFAULT_FINGERPRINT_CAPACITY as JAILBREAK_DEFAULT_FINGERPRINT_CAPACITY,
101};
102pub use jailbreak_detector::{
103    Detection as JailbreakDetection, DetectorConfig as JailbreakDetectorConfig, JailbreakCategory,
104    JailbreakDetector, LayerScores as JailbreakLayerScores, LayerWeights,
105    LinearModel as JailbreakLinearModel, Signal as JailbreakSignal,
106    StatisticalThresholds as JailbreakStatisticalThresholds,
107    DEFAULT_DENY_THRESHOLD as JAILBREAK_DEFAULT_DENY_THRESHOLD,
108};
109pub use mcp_tool::McpToolGuard;
110pub use patch_integrity::PatchIntegrityGuard;
111pub use path_allowlist::PathAllowlistGuard;
112pub use pipeline::GuardPipeline;
113pub use post_invocation::{
114    sanitize_json, PipelineOutcome, PostInvocationHook, PostInvocationHookIdentity,
115    PostInvocationPipeline, PostInvocationVerdict, SanitizerHook,
116};
117pub use prompt_injection::{
118    Detection as PromptInjectionDetection, PromptInjectionConfig, PromptInjectionGuard,
119    Signal as PromptInjectionSignal,
120};
121pub use response_sanitization::{
122    AllowlistConfig, CategoryConfig, DenylistConfig, EntropyConfig, OutputSanitizer,
123    OutputSanitizerConfig, OutputSanitizerConfigError, ProcessingStats, Redaction,
124    RedactionStrategy, ResponseSanitizationGuard, SanitizationAction, SanitizationResult,
125    SanitizedValue, ScanResult, SensitiveCategory, SensitiveDataFinding, SensitivityLevel, Span,
126    TokenVault,
127};
128pub use secret_leak::SecretLeakGuard;
129pub use shell_command::{ShellCommandConfigError, ShellCommandGuard};
130pub use velocity::VelocityGuard;
131
132pub use action::{extract_action, extract_action_checked, MalformedAction, ToolAction};
133
134pub use external::{
135    AsyncGuardAdapter, AsyncGuardAdapterBuilder, AsyncGuardAdapterConfig, CircuitBreaker,
136    CircuitBreakerConfig, CircuitOpenVerdict, CircuitState, ExternalGuard, ExternalGuardError,
137    GuardCallContext, RateLimitedVerdict, RetryConfig, TokenBucket, TtlCache,
138};
139
140/// Default guard material installed by the control-plane runtime profile.
141pub struct RuntimeGuardProfile {
142    pub pre_invocation_guards: Vec<Box<dyn chio_kernel::Guard>>,
143    pub post_invocation_pipeline: PostInvocationPipeline,
144}
145
146/// Build the default Chio runtime guard profile without coupling the kernel to
147/// concrete guard implementations.
148pub fn default_runtime_guard_profile() -> RuntimeGuardProfile {
149    let mut post_invocation_pipeline = PostInvocationPipeline::new();
150    post_invocation_pipeline.add(Box::new(SanitizerHook::new()));
151
152    RuntimeGuardProfile {
153        pre_invocation_guards: vec![
154            Box::new(InternalNetworkGuard::new()),
155            Box::new(AgentVelocityGuard::new(AgentVelocityConfig::default())),
156            Box::new(AdvisoryPipeline::new(PromotionPolicy::new())),
157        ],
158        post_invocation_pipeline,
159    }
160}
161
162// Computer Use Agent (CUA) and EmbeddingAnomaly re-exports.
163pub use computer_use::{
164    default_allowed_action_types as computer_use_default_allowed_action_types, ComputerUseConfig,
165    ComputerUseGuard, EnforcementMode,
166};
167pub use embedding_anomaly::{
168    cosine_similarity as embedding_anomaly_cosine_similarity, extract_embedding, AmbiguousPolicy,
169    EmbeddingAnomalyConfig, EmbeddingAnomalyError, EmbeddingAnomalyGuard,
170    EmbeddingAnomalyPatternDb, PatternEntry, DEFAULT_AMBIGUITY_BAND, DEFAULT_SIMILARITY_THRESHOLD,
171    DEFAULT_TOP_K,
172};
173pub use input_injection::{
174    default_allowed_input_types, InputInjectionCapabilityConfig, InputInjectionCapabilityGuard,
175};
176pub use remote_desktop::{RemoteDesktopSideChannelConfig, RemoteDesktopSideChannelGuard};
177
178// Code execution, browser automation, content review, and memory
179// governance re-exports.
180pub use browser_automation::{
181    default_allowed_verbs as browser_automation_default_allowed_verbs, BrowserAutomationConfig,
182    BrowserAutomationError, BrowserAutomationGuard,
183};
184pub use code_execution::{
185    default_dangerous_modules as code_execution_default_dangerous_modules, CodeExecutionConfig,
186    CodeExecutionError, CodeExecutionGuard,
187};
188pub use content_review::{
189    ContentReviewConfig, ContentReviewError, ContentReviewGuard, ContentReviewRules,
190};
191pub use memory_governance::{MemoryGovernanceConfig, MemoryGovernanceError, MemoryGovernanceGuard};