mod file_targets;
#[cfg(test)]
use file_targets::patch_file_access_targets;
use file_targets::{command_text_for_tool, file_access_targets, proposed_changes_preview};
use hashbrown::HashSet;
use parking_lot::{Mutex, RwLock};
use std::future::Future;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::{Duration, Instant};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use thiserror::Error;
use crate::config::CommandsConfig;
use crate::config::constants::tools;
use crate::dotfile_protection::{AccessContext, AccessType, DotfileGuardian, ProtectionDecision, get_global_guardian};
use crate::tools::apply_patch::{Patch, PatchOperation, decode_apply_patch_input};
use crate::tools::command_policy::CommandPolicyEvaluator;
use crate::tools::invocation::ToolInvocationId;
use crate::tools::rate_limit_config::{tool_calls_per_minute_from_env, tool_calls_per_second_from_env};
use crate::tools::registry::{RiskLevel, ToolRiskContext, ToolRiskScorer, ToolSource, WorkspaceTrust};
use crate::tools::tool_intent::{
ToolIntent, action_qualified_policy_name, classify_tool_intent, command_session_action_in,
command_session_action_is, file_operation_action_is,
};
use vtcode_config::core::DotfileProtectionConfig;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum SafetyTrustLevel {
Untrusted,
#[default]
Standard,
Elevated,
Full,
}
impl SafetyTrustLevel {
#[inline]
#[must_use]
pub const fn can_bypass_approval(self) -> bool {
matches!(self, Self::Elevated | Self::Full)
}
}
#[derive(Debug, Clone)]
pub struct SafetyContext {
pub session_id: String,
pub trust_level: SafetyTrustLevel,
}
impl SafetyContext {
#[must_use]
pub fn new(session_id: impl Into<String>) -> Self {
Self {
session_id: session_id.into(),
trust_level: SafetyTrustLevel::default(),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[must_use = "safety decisions must be enforced before execution"]
pub enum SafetyDecision {
Allow,
Deny(String),
NeedsApproval(String),
}
impl SafetyDecision {
#[inline]
#[must_use]
pub fn is_allowed(&self) -> bool {
matches!(self, SafetyDecision::Allow)
}
#[inline]
#[must_use]
pub fn is_denied(&self) -> bool {
matches!(self, SafetyDecision::Deny(_))
}
#[inline]
pub fn needs_approval(&self) -> bool {
matches!(self, SafetyDecision::NeedsApproval(_))
}
pub fn reason(&self) -> Option<&str> {
match self {
SafetyDecision::Allow => None,
SafetyDecision::Deny(reason) | SafetyDecision::NeedsApproval(reason) => Some(reason),
}
}
}
#[derive(Debug, Error, Clone)]
pub enum SafetyError {
#[error("Rate limit exceeded: {current} calls in {window} (max: {max})")]
RateLimitExceeded {
current: usize,
max: usize,
window: &'static str,
},
#[error("Planning workflow violation: {0}")]
PlanningPolicyViolation(String),
#[error("Command policy denied: {0}")]
CommandPolicyDenied(String),
#[error("Dotfile protection violation: {0}")]
DotfileProtectionViolation(String),
}
#[derive(Debug, Clone)]
pub struct SafetyCheckResult {
pub decision: SafetyDecision,
pub retry_after: Option<Duration>,
pub violation: Option<SafetyError>,
}
#[derive(Debug, Clone)]
pub struct SafetyGatewayConfig {
pub rate_limit_per_second: usize,
pub rate_limit_per_minute: Option<usize>,
pub planning_active: bool,
pub workspace_trust: WorkspaceTrust,
pub approval_risk_threshold: RiskLevel,
pub enforce_rate_limits: bool,
}
impl Default for SafetyGatewayConfig {
fn default() -> Self {
let rate_limit_per_second = tool_calls_per_second_from_env().unwrap_or(5);
Self {
rate_limit_per_second,
rate_limit_per_minute: tool_calls_per_minute_from_env(),
planning_active: false,
workspace_trust: WorkspaceTrust::Trusted,
approval_risk_threshold: RiskLevel::Medium,
enforce_rate_limits: true,
}
}
}
#[derive(Debug, Default)]
struct RateLimiterState {
calls_per_second: std::collections::VecDeque<Instant>,
calls_per_minute: std::collections::VecDeque<Instant>,
}
pub struct SafetyGateway {
config: RwLock<SafetyGatewayConfig>,
command_policy: Option<CommandPolicyEvaluator>,
rate_state: Mutex<RateLimiterState>,
preapproved: Mutex<HashSet<String>>,
dotfile_guardian: Option<Arc<DotfileGuardian>>,
}
impl SafetyGateway {
pub fn new() -> Self {
Self::with_config(SafetyGatewayConfig::default())
}
pub fn with_config(config: SafetyGatewayConfig) -> Self {
Self {
config: RwLock::new(config),
command_policy: None,
rate_state: Mutex::new(RateLimiterState::default()),
preapproved: Mutex::new(HashSet::new()),
dotfile_guardian: None,
}
}
pub fn with_dotfile_guardian(mut self, guardian: Arc<DotfileGuardian>) -> Self {
self.dotfile_guardian = Some(guardian);
self
}
pub async fn with_dotfile_protection(mut self, config: DotfileProtectionConfig) -> anyhow::Result<Self> {
let guardian = DotfileGuardian::new(config).await?;
self.dotfile_guardian = Some(Arc::new(guardian));
Ok(self)
}
pub fn with_command_policy(mut self, policy: CommandPolicyEvaluator) -> Self {
self.command_policy = Some(policy);
self
}
pub fn with_commands_config(mut self, config: &CommandsConfig) -> Self {
self.command_policy = Some(CommandPolicyEvaluator::from_config(config));
self
}
pub fn set_planning_workflow(&self, active: bool) {
self.config.write().planning_active = active;
}
pub fn set_workspace_trust(&self, trust: WorkspaceTrust) {
self.config.write().workspace_trust = trust;
}
pub fn set_rate_limits(&self, rate_limit_per_second: usize, rate_limit_per_minute: Option<usize>) {
let mut config = self.config.write();
if rate_limit_per_second > 0 {
config.rate_limit_per_second = rate_limit_per_second;
}
config.rate_limit_per_minute = rate_limit_per_minute.filter(|v| *v > 0);
}
pub fn set_rate_limit_enforcement(&self, enabled: bool) {
self.config.write().enforce_rate_limits = enabled;
}
pub fn start_turn(&self) {
let mut state = self.rate_state.lock();
state.calls_per_second.clear();
state.calls_per_minute.clear();
}
pub fn reset_for_fresh_execution(&self) {
self.start_turn();
}
pub fn preapprove(&self, tool_name: &str) {
let mut preapproved = self.preapproved.lock();
preapproved.insert(tool_name.to_string());
}
pub fn is_preapproved(&self, tool_name: &str) -> bool {
let preapproved = self.preapproved.lock();
preapproved.contains(tool_name)
}
pub fn check_safety<'a>(
&'a self,
ctx: &'a SafetyContext,
tool_name: &'a str,
args: &'a Value,
) -> impl Future<Output = SafetyDecision> + 'a {
self.check_safety_with_id(ctx, tool_name, args, None)
}
pub async fn check_safety_with_id(
&self,
ctx: &SafetyContext,
tool_name: &str,
args: &Value,
invocation_id: Option<ToolInvocationId>,
) -> SafetyDecision {
let inv_id = invocation_id.map(|id| id.short()).unwrap_or_else(|| "unknown".to_string());
tracing::trace!(
invocation_id = %inv_id,
tool = %tool_name,
"SafetyGateway: checking safety"
);
if let Err(err) = self.check_rate_limits() {
tracing::warn!(
invocation_id = %inv_id,
error = %err,
"SafetyGateway: rate limit exceeded"
);
return SafetyDecision::Deny(err.to_string());
}
self.evaluate_non_rate_decision(ctx, tool_name, args, &inv_id).await
}
pub async fn check_and_record(&self, ctx: &SafetyContext, tool_name: &str, args: &Value) -> SafetyCheckResult {
self.check_and_record_with_id(ctx, tool_name, args, None).await
}
pub async fn check_and_record_with_id(
&self,
ctx: &SafetyContext,
tool_name: &str,
args: &Value,
invocation_id: Option<ToolInvocationId>,
) -> SafetyCheckResult {
let inv_id = invocation_id.map(|id| id.short()).unwrap_or_else(|| "unknown".to_string());
tracing::trace!(
invocation_id = %inv_id,
tool = %tool_name,
"SafetyGateway: checking and recording safety"
);
let decision = self.evaluate_non_rate_decision(ctx, tool_name, args, &inv_id).await;
if decision.is_denied() {
return SafetyCheckResult { decision, retry_after: None, violation: None };
}
let now = Instant::now();
let mut state = self.rate_state.lock();
match self.check_rate_limits_locked(&mut state, now) {
Ok(()) => {
self.record_execution_locked(&mut state, now);
SafetyCheckResult { decision, retry_after: None, violation: None }
}
Err(err) => {
tracing::warn!(
invocation_id = %inv_id,
error = %err,
"SafetyGateway: rate limit exceeded during atomic reservation"
);
SafetyCheckResult {
decision: SafetyDecision::Deny(err.to_string()),
retry_after: self.retry_after_for_violation(&err, &state, now),
violation: Some(err),
}
}
}
}
async fn evaluate_non_rate_decision(
&self,
ctx: &SafetyContext,
tool_name: &str,
args: &Value,
inv_id: &str,
) -> SafetyDecision {
let command = command_text_for_tool(tool_name, args);
if let Some(decision) = self.check_dotfile_protection(tool_name, args, &ctx.session_id).await {
tracing::info!(
invocation_id = %inv_id,
tool = %tool_name,
"SafetyGateway: dotfile protection triggered"
);
return decision;
}
if let Some(ref policy) = self.command_policy
&& let Some(command) = command.as_deref()
&& !policy.allows_text(command)
{
let reason = format!("Command '{command}' blocked by policy");
tracing::info!(
invocation_id = %inv_id,
command = %command,
"SafetyGateway: command policy denied"
);
return SafetyDecision::Deny(reason);
}
if self.is_preapproved(tool_name) {
tracing::trace!(
invocation_id = %inv_id,
tool = %tool_name,
"SafetyGateway: tool preapproved"
);
return SafetyDecision::Allow;
}
if ctx.trust_level.can_bypass_approval() {
tracing::trace!(
invocation_id = %inv_id,
tool = %tool_name,
trust_level = ?ctx.trust_level,
"SafetyGateway: trust level allows bypass"
);
return SafetyDecision::Allow;
}
let intent = classify_tool_intent(tool_name, args);
let command = command.as_deref();
let risk_ctx = self.build_risk_context(tool_name, args, &intent, command);
let risk_level = ToolRiskScorer::calculate_risk(&risk_ctx);
if ToolRiskScorer::requires_justification(risk_level, self.config.read().approval_risk_threshold) {
let justification = self.build_approval_justification(tool_name, &risk_level, args, &intent, command);
tracing::info!(
invocation_id = %inv_id,
tool = %tool_name,
risk = %risk_level,
"SafetyGateway: requires approval"
);
return SafetyDecision::NeedsApproval(justification);
}
if intent.destructive {
let justification = format!("Tool '{tool_name}' is destructive and may modify files or execute commands.");
tracing::info!(
invocation_id = %inv_id,
tool = %tool_name,
"SafetyGateway: destructive tool requires approval"
);
return SafetyDecision::NeedsApproval(justification);
}
SafetyDecision::Allow
}
pub fn record_execution(&self) {
let mut state = self.rate_state.lock();
self.record_execution_locked(&mut state, Instant::now());
}
fn check_rate_limits(&self) -> Result<(), SafetyError> {
let mut state = self.rate_state.lock();
self.check_rate_limits_locked(&mut state, Instant::now())
}
fn check_rate_limits_locked(&self, state: &mut RateLimiterState, now: Instant) -> Result<(), SafetyError> {
let config = self.config.read();
self.prune_rate_windows(state, now);
if config.enforce_rate_limits {
if state.calls_per_second.len() >= config.rate_limit_per_second {
return Err(SafetyError::RateLimitExceeded {
current: state.calls_per_second.len(),
max: config.rate_limit_per_second,
window: "1s",
});
}
if let Some(limit) = config.rate_limit_per_minute
&& state.calls_per_minute.len() >= limit
{
return Err(SafetyError::RateLimitExceeded {
current: state.calls_per_minute.len(),
max: limit,
window: "60s",
});
}
}
Ok(())
}
fn record_execution_locked(&self, state: &mut RateLimiterState, now: Instant) {
state.calls_per_second.push_back(now);
state.calls_per_minute.push_back(now);
}
fn prune_rate_windows(&self, state: &mut RateLimiterState, now: Instant) {
while let Some(front) = state.calls_per_second.front() {
if now.duration_since(*front) > Duration::from_secs(1) {
state.calls_per_second.pop_front();
} else {
break;
}
}
while let Some(front) = state.calls_per_minute.front() {
if now.duration_since(*front) > Duration::from_secs(60) {
state.calls_per_minute.pop_front();
} else {
break;
}
}
}
fn retry_after_for_violation(
&self,
violation: &SafetyError,
state: &RateLimiterState,
now: Instant,
) -> Option<Duration> {
match violation {
SafetyError::RateLimitExceeded { window: "1s", .. } => state
.calls_per_second
.front()
.map(|first| Duration::from_secs(1).saturating_sub(now.duration_since(*first))),
SafetyError::RateLimitExceeded { window: "60s", .. } => state
.calls_per_minute
.front()
.map(|first| Duration::from_secs(60).saturating_sub(now.duration_since(*first))),
_ => None,
}
}
async fn check_dotfile_protection(
&self,
tool_name: &str,
args: &Value,
session_id: &str,
) -> Option<SafetyDecision> {
let guardian = match self.dotfile_guardian.as_ref() {
Some(g) => g.clone(),
None => get_global_guardian()?,
};
let file_targets = file_access_targets(tool_name, args);
if file_targets.is_empty() {
return None;
}
let proposed_changes = proposed_changes_preview(args);
for target in file_targets {
if !guardian.is_protected(Path::new(&target.path)) {
continue;
}
let context = AccessContext::new(&target.path, target.access_type, tool_name, session_id)
.with_proposed_changes(&proposed_changes);
match guardian.request_access(&context).await {
Ok(ProtectionDecision::Allowed) => continue,
Ok(ProtectionDecision::RequiresConfirmation(req)) => {
return Some(SafetyDecision::NeedsApproval(format!(
"DOTFILE PROTECTION\n\n\
File: {}\n\
Operation: {}\n\
Reason: {}\n\n\
Proposed changes:\n{}\n\n\
{}",
req.file_path, req.access_type, req.protection_reason, req.proposed_changes, req.warning
)));
}
Ok(ProtectionDecision::RequiresSecondaryAuth(req)) => {
return Some(SafetyDecision::NeedsApproval(format!(
"DOTFILE SECONDARY AUTHENTICATION REQUIRED\n\n\
File: {} (whitelisted)\n\
Operation: {}\n\
Reason: {}\n\n\
This file is on the whitelist but requires secondary authentication.\n\n\
Proposed changes:\n{}\n\n\
{}",
req.file_path, req.access_type, req.protection_reason, req.proposed_changes, req.warning
)));
}
Ok(ProtectionDecision::Blocked(violation)) => {
return Some(SafetyDecision::Deny(format!(
"DOTFILE MODIFICATION BLOCKED\n\n\
File: {}\n\
Reason: {}\n\n\
Suggestion: {}",
violation.file_path, violation.reason, violation.suggestion
)));
}
Ok(ProtectionDecision::Denied(violation)) => {
return Some(SafetyDecision::Deny(format!(
"DOTFILE ACCESS DENIED\n\n\
File: {}\n\
Reason: {}\n\n\
Suggestion: {}",
violation.file_path, violation.reason, violation.suggestion
)));
}
Err(e) => {
tracing::error!("Dotfile protection check failed: {}", e);
return Some(SafetyDecision::Deny(format!("Dotfile protection check failed: {e}")));
}
}
}
None
}
pub fn dotfile_guardian(&self) -> Option<&Arc<DotfileGuardian>> {
self.dotfile_guardian.as_ref()
}
fn build_risk_context(
&self,
tool_name: &str,
args: &Value,
intent: &ToolIntent,
command: Option<&str>,
) -> ToolRiskContext {
let source = if tool_name.starts_with("mcp_") {
ToolSource::Mcp
} else if tool_name.starts_with("acp_") {
ToolSource::Acp
} else {
ToolSource::Internal
};
let risk_tool_name = action_qualified_policy_name(tool_name, Some(args)).unwrap_or(tool_name);
let mut ctx = ToolRiskContext::new(risk_tool_name.to_string(), source, self.config.read().workspace_trust);
if intent.mutating {
ctx = ctx.as_write();
}
if intent.destructive {
ctx = ctx.as_destructive();
}
if ToolRiskScorer::is_network_tool(risk_tool_name) {
ctx = ctx.accesses_network();
}
if let Some(command) = command {
ctx = ctx.with_args(command.split_whitespace().map(String::from).collect());
}
ctx
}
fn build_approval_justification(
&self,
tool_name: &str,
risk_level: &RiskLevel,
args: &Value,
intent: &ToolIntent,
command: Option<&str>,
) -> String {
let mut parts = Vec::new();
parts.push(format!("Tool: {tool_name}"));
parts.push(format!("Risk level: {risk_level}"));
if intent.destructive {
parts.push("This tool may modify or delete files.".to_string());
}
if let Some(command) = command {
parts.push(format!("Command: {command}"));
}
let file_targets = file_access_targets(tool_name, args);
if let Some(target) = file_targets.first() {
parts.push(format!("Path: {}", target.path.display()));
if file_targets.len() > 1 {
parts.push(format!("Additional targets: {}", file_targets.len() - 1));
}
}
parts.join("\n")
}
}
impl Default for SafetyGateway {
fn default() -> Self {
Self::new()
}
}
#[cfg(test)]
mod tests;