1mod file_targets;
12#[cfg(test)]
13use file_targets::patch_file_access_targets;
14use file_targets::{command_text_for_tool, file_access_targets, proposed_changes_preview};
15
16use hashbrown::HashSet;
17use parking_lot::{Mutex, RwLock};
18use std::future::Future;
19use std::path::{Path, PathBuf};
20use std::sync::Arc;
21use std::time::{Duration, Instant};
22
23use serde::{Deserialize, Serialize};
24use serde_json::Value;
25use thiserror::Error;
26
27use crate::config::CommandsConfig;
28use crate::config::constants::tools;
29use crate::dotfile_protection::{AccessContext, AccessType, DotfileGuardian, ProtectionDecision, get_global_guardian};
30use crate::tools::apply_patch::{Patch, PatchOperation, decode_apply_patch_input};
31use crate::tools::command_policy::CommandPolicyEvaluator;
32use crate::tools::invocation::ToolInvocationId;
33use crate::tools::rate_limit_config::{tool_calls_per_minute_from_env, tool_calls_per_second_from_env};
34use crate::tools::registry::{RiskLevel, ToolRiskContext, ToolRiskScorer, ToolSource, WorkspaceTrust};
35use crate::tools::tool_intent::{
36 ToolIntent, action_qualified_policy_name, classify_tool_intent, command_session_action_in,
37 command_session_action_is, file_operation_action_is,
38};
39use vtcode_config::core::DotfileProtectionConfig;
40
41#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
43pub enum SafetyTrustLevel {
44 Untrusted,
45 #[default]
46 Standard,
47 Elevated,
48 Full,
49}
50
51impl SafetyTrustLevel {
52 #[inline]
53 #[must_use]
54 pub const fn can_bypass_approval(self) -> bool {
55 matches!(self, Self::Elevated | Self::Full)
56 }
57}
58
59#[derive(Debug, Clone)]
61pub struct SafetyContext {
62 pub session_id: String,
63 pub trust_level: SafetyTrustLevel,
64}
65
66impl SafetyContext {
67 #[must_use]
68 pub fn new(session_id: impl Into<String>) -> Self {
69 Self {
70 session_id: session_id.into(),
71 trust_level: SafetyTrustLevel::default(),
72 }
73 }
74}
75
76#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
78#[must_use = "safety decisions must be enforced before execution"]
79pub enum SafetyDecision {
80 Allow,
82 Deny(String),
84 NeedsApproval(String),
86}
87
88impl SafetyDecision {
89 #[inline]
91 #[must_use]
92 pub fn is_allowed(&self) -> bool {
93 matches!(self, SafetyDecision::Allow)
94 }
95
96 #[inline]
98 #[must_use]
99 pub fn is_denied(&self) -> bool {
100 matches!(self, SafetyDecision::Deny(_))
101 }
102
103 #[inline]
105 pub fn needs_approval(&self) -> bool {
106 matches!(self, SafetyDecision::NeedsApproval(_))
107 }
108
109 pub fn reason(&self) -> Option<&str> {
111 match self {
112 SafetyDecision::Allow => None,
113 SafetyDecision::Deny(reason) | SafetyDecision::NeedsApproval(reason) => Some(reason),
114 }
115 }
116}
117
118#[derive(Debug, Error, Clone)]
120pub enum SafetyError {
121 #[error("Rate limit exceeded: {current} calls in {window} (max: {max})")]
122 RateLimitExceeded {
123 current: usize,
124 max: usize,
125 window: &'static str,
126 },
127 #[error("Planning workflow violation: {0}")]
128 PlanningPolicyViolation(String),
129 #[error("Command policy denied: {0}")]
130 CommandPolicyDenied(String),
131 #[error("Dotfile protection violation: {0}")]
132 DotfileProtectionViolation(String),
133}
134
135#[derive(Debug, Clone)]
137pub struct SafetyCheckResult {
138 pub decision: SafetyDecision,
140 pub retry_after: Option<Duration>,
142 pub violation: Option<SafetyError>,
144}
145
146#[derive(Debug, Clone)]
148pub struct SafetyGatewayConfig {
149 pub rate_limit_per_second: usize,
151 pub rate_limit_per_minute: Option<usize>,
153 pub planning_active: bool,
155 pub workspace_trust: WorkspaceTrust,
157 pub approval_risk_threshold: RiskLevel,
159 pub enforce_rate_limits: bool,
161}
162
163impl Default for SafetyGatewayConfig {
164 fn default() -> Self {
165 let rate_limit_per_second = tool_calls_per_second_from_env().unwrap_or(5);
166
167 Self {
168 rate_limit_per_second,
169 rate_limit_per_minute: tool_calls_per_minute_from_env(),
170 planning_active: false,
171 workspace_trust: WorkspaceTrust::Trusted,
172 approval_risk_threshold: RiskLevel::Medium,
173 enforce_rate_limits: true,
174 }
175 }
176}
177
178#[derive(Debug, Default)]
180struct RateLimiterState {
181 calls_per_second: std::collections::VecDeque<Instant>,
182 calls_per_minute: std::collections::VecDeque<Instant>,
183}
184
185pub struct SafetyGateway {
191 config: RwLock<SafetyGatewayConfig>,
193 command_policy: Option<CommandPolicyEvaluator>,
195 rate_state: Mutex<RateLimiterState>,
197 preapproved: Mutex<HashSet<String>>,
199 dotfile_guardian: Option<Arc<DotfileGuardian>>,
201}
202
203impl SafetyGateway {
204 pub fn new() -> Self {
206 Self::with_config(SafetyGatewayConfig::default())
207 }
208
209 pub fn with_config(config: SafetyGatewayConfig) -> Self {
211 Self {
212 config: RwLock::new(config),
213 command_policy: None,
214 rate_state: Mutex::new(RateLimiterState::default()),
215 preapproved: Mutex::new(HashSet::new()),
216 dotfile_guardian: None,
217 }
218 }
219
220 pub fn with_dotfile_guardian(mut self, guardian: Arc<DotfileGuardian>) -> Self {
222 self.dotfile_guardian = Some(guardian);
223 self
224 }
225
226 pub async fn with_dotfile_protection(mut self, config: DotfileProtectionConfig) -> anyhow::Result<Self> {
228 let guardian = DotfileGuardian::new(config).await?;
229 self.dotfile_guardian = Some(Arc::new(guardian));
230 Ok(self)
231 }
232
233 pub fn with_command_policy(mut self, policy: CommandPolicyEvaluator) -> Self {
235 self.command_policy = Some(policy);
236 self
237 }
238
239 pub fn with_commands_config(mut self, config: &CommandsConfig) -> Self {
241 self.command_policy = Some(CommandPolicyEvaluator::from_config(config));
242 self
243 }
244
245 pub fn set_planning_workflow(&self, active: bool) {
247 self.config.write().planning_active = active;
248 }
249
250 pub fn set_workspace_trust(&self, trust: WorkspaceTrust) {
252 self.config.write().workspace_trust = trust;
253 }
254
255 pub fn set_rate_limits(&self, rate_limit_per_second: usize, rate_limit_per_minute: Option<usize>) {
257 let mut config = self.config.write();
258 if rate_limit_per_second > 0 {
259 config.rate_limit_per_second = rate_limit_per_second;
260 }
261 config.rate_limit_per_minute = rate_limit_per_minute.filter(|v| *v > 0);
262 }
263
264 pub fn set_rate_limit_enforcement(&self, enabled: bool) {
266 self.config.write().enforce_rate_limits = enabled;
267 }
268
269 pub fn start_turn(&self) {
271 let mut state = self.rate_state.lock();
272 state.calls_per_second.clear();
273 state.calls_per_minute.clear();
274 }
275
276 pub fn reset_for_fresh_execution(&self) {
279 self.start_turn();
280 }
281
282 pub fn preapprove(&self, tool_name: &str) {
284 let mut preapproved = self.preapproved.lock();
285 preapproved.insert(tool_name.to_string());
286 }
287
288 pub fn is_preapproved(&self, tool_name: &str) -> bool {
290 let preapproved = self.preapproved.lock();
291 preapproved.contains(tool_name)
292 }
293
294 pub fn check_safety<'a>(
300 &'a self,
301 ctx: &'a SafetyContext,
302 tool_name: &'a str,
303 args: &'a Value,
304 ) -> impl Future<Output = SafetyDecision> + 'a {
305 self.check_safety_with_id(ctx, tool_name, args, None)
306 }
307
308 pub async fn check_safety_with_id(
310 &self,
311 ctx: &SafetyContext,
312 tool_name: &str,
313 args: &Value,
314 invocation_id: Option<ToolInvocationId>,
315 ) -> SafetyDecision {
316 let inv_id = invocation_id.map(|id| id.short()).unwrap_or_else(|| "unknown".to_string());
317
318 tracing::trace!(
319 invocation_id = %inv_id,
320 tool = %tool_name,
321 "SafetyGateway: checking safety"
322 );
323
324 if let Err(err) = self.check_rate_limits() {
325 tracing::warn!(
326 invocation_id = %inv_id,
327 error = %err,
328 "SafetyGateway: rate limit exceeded"
329 );
330 return SafetyDecision::Deny(err.to_string());
331 }
332
333 self.evaluate_non_rate_decision(ctx, tool_name, args, &inv_id).await
334 }
335
336 pub async fn check_and_record(&self, ctx: &SafetyContext, tool_name: &str, args: &Value) -> SafetyCheckResult {
341 self.check_and_record_with_id(ctx, tool_name, args, None).await
342 }
343
344 pub async fn check_and_record_with_id(
346 &self,
347 ctx: &SafetyContext,
348 tool_name: &str,
349 args: &Value,
350 invocation_id: Option<ToolInvocationId>,
351 ) -> SafetyCheckResult {
352 let inv_id = invocation_id.map(|id| id.short()).unwrap_or_else(|| "unknown".to_string());
353 tracing::trace!(
354 invocation_id = %inv_id,
355 tool = %tool_name,
356 "SafetyGateway: checking and recording safety"
357 );
358
359 let decision = self.evaluate_non_rate_decision(ctx, tool_name, args, &inv_id).await;
360
361 if decision.is_denied() {
362 return SafetyCheckResult { decision, retry_after: None, violation: None };
363 }
364
365 let now = Instant::now();
366 let mut state = self.rate_state.lock();
367 match self.check_rate_limits_locked(&mut state, now) {
368 Ok(()) => {
369 self.record_execution_locked(&mut state, now);
370 SafetyCheckResult { decision, retry_after: None, violation: None }
371 }
372 Err(err) => {
373 tracing::warn!(
374 invocation_id = %inv_id,
375 error = %err,
376 "SafetyGateway: rate limit exceeded during atomic reservation"
377 );
378 SafetyCheckResult {
379 decision: SafetyDecision::Deny(err.to_string()),
380 retry_after: self.retry_after_for_violation(&err, &state, now),
381 violation: Some(err),
382 }
383 }
384 }
385 }
386
387 async fn evaluate_non_rate_decision(
388 &self,
389 ctx: &SafetyContext,
390 tool_name: &str,
391 args: &Value,
392 inv_id: &str,
393 ) -> SafetyDecision {
394 let command = command_text_for_tool(tool_name, args);
399
400 if let Some(decision) = self.check_dotfile_protection(tool_name, args, &ctx.session_id).await {
401 tracing::info!(
402 invocation_id = %inv_id,
403 tool = %tool_name,
404 "SafetyGateway: dotfile protection triggered"
405 );
406 return decision;
407 }
408
409 if let Some(ref policy) = self.command_policy
410 && let Some(command) = command.as_deref()
411 && !policy.allows_text(command)
412 {
413 let reason = format!("Command '{command}' blocked by policy");
414 tracing::info!(
415 invocation_id = %inv_id,
416 command = %command,
417 "SafetyGateway: command policy denied"
418 );
419 return SafetyDecision::Deny(reason);
420 }
421
422 if self.is_preapproved(tool_name) {
423 tracing::trace!(
424 invocation_id = %inv_id,
425 tool = %tool_name,
426 "SafetyGateway: tool preapproved"
427 );
428 return SafetyDecision::Allow;
429 }
430
431 if ctx.trust_level.can_bypass_approval() {
432 tracing::trace!(
433 invocation_id = %inv_id,
434 tool = %tool_name,
435 trust_level = ?ctx.trust_level,
436 "SafetyGateway: trust level allows bypass"
437 );
438 return SafetyDecision::Allow;
439 }
440
441 let intent = classify_tool_intent(tool_name, args);
445 let command = command.as_deref();
446 let risk_ctx = self.build_risk_context(tool_name, args, &intent, command);
447 let risk_level = ToolRiskScorer::calculate_risk(&risk_ctx);
448
449 if ToolRiskScorer::requires_justification(risk_level, self.config.read().approval_risk_threshold) {
450 let justification = self.build_approval_justification(tool_name, &risk_level, args, &intent, command);
451 tracing::info!(
452 invocation_id = %inv_id,
453 tool = %tool_name,
454 risk = %risk_level,
455 "SafetyGateway: requires approval"
456 );
457 return SafetyDecision::NeedsApproval(justification);
458 }
459
460 if intent.destructive {
461 let justification = format!("Tool '{tool_name}' is destructive and may modify files or execute commands.");
462 tracing::info!(
463 invocation_id = %inv_id,
464 tool = %tool_name,
465 "SafetyGateway: destructive tool requires approval"
466 );
467 return SafetyDecision::NeedsApproval(justification);
468 }
469
470 SafetyDecision::Allow
471 }
472
473 pub fn record_execution(&self) {
475 let mut state = self.rate_state.lock();
476 self.record_execution_locked(&mut state, Instant::now());
477 }
478
479 fn check_rate_limits(&self) -> Result<(), SafetyError> {
481 let mut state = self.rate_state.lock();
482 self.check_rate_limits_locked(&mut state, Instant::now())
483 }
484
485 fn check_rate_limits_locked(&self, state: &mut RateLimiterState, now: Instant) -> Result<(), SafetyError> {
486 let config = self.config.read();
487 self.prune_rate_windows(state, now);
488
489 if config.enforce_rate_limits {
490 if state.calls_per_second.len() >= config.rate_limit_per_second {
491 return Err(SafetyError::RateLimitExceeded {
492 current: state.calls_per_second.len(),
493 max: config.rate_limit_per_second,
494 window: "1s",
495 });
496 }
497
498 if let Some(limit) = config.rate_limit_per_minute
499 && state.calls_per_minute.len() >= limit
500 {
501 return Err(SafetyError::RateLimitExceeded {
502 current: state.calls_per_minute.len(),
503 max: limit,
504 window: "60s",
505 });
506 }
507 }
508
509 Ok(())
510 }
511
512 fn record_execution_locked(&self, state: &mut RateLimiterState, now: Instant) {
513 state.calls_per_second.push_back(now);
514 state.calls_per_minute.push_back(now);
515 }
516
517 fn prune_rate_windows(&self, state: &mut RateLimiterState, now: Instant) {
518 while let Some(front) = state.calls_per_second.front() {
519 if now.duration_since(*front) > Duration::from_secs(1) {
520 state.calls_per_second.pop_front();
521 } else {
522 break;
523 }
524 }
525 while let Some(front) = state.calls_per_minute.front() {
526 if now.duration_since(*front) > Duration::from_secs(60) {
527 state.calls_per_minute.pop_front();
528 } else {
529 break;
530 }
531 }
532 }
533
534 fn retry_after_for_violation(
535 &self,
536 violation: &SafetyError,
537 state: &RateLimiterState,
538 now: Instant,
539 ) -> Option<Duration> {
540 match violation {
541 SafetyError::RateLimitExceeded { window: "1s", .. } => state
542 .calls_per_second
543 .front()
544 .map(|first| Duration::from_secs(1).saturating_sub(now.duration_since(*first))),
545 SafetyError::RateLimitExceeded { window: "60s", .. } => state
546 .calls_per_minute
547 .front()
548 .map(|first| Duration::from_secs(60).saturating_sub(now.duration_since(*first))),
549 _ => None,
550 }
551 }
552
553 async fn check_dotfile_protection(
556 &self,
557 tool_name: &str,
558 args: &Value,
559 session_id: &str,
560 ) -> Option<SafetyDecision> {
561 let guardian = match self.dotfile_guardian.as_ref() {
563 Some(g) => g.clone(),
564 None => get_global_guardian()?,
565 };
566
567 let file_targets = file_access_targets(tool_name, args);
568 if file_targets.is_empty() {
569 return None;
570 }
571
572 let proposed_changes = proposed_changes_preview(args);
573
574 for target in file_targets {
575 if !guardian.is_protected(Path::new(&target.path)) {
576 continue;
577 }
578
579 let context = AccessContext::new(&target.path, target.access_type, tool_name, session_id)
580 .with_proposed_changes(&proposed_changes);
581
582 match guardian.request_access(&context).await {
583 Ok(ProtectionDecision::Allowed) => continue,
584 Ok(ProtectionDecision::RequiresConfirmation(req)) => {
585 return Some(SafetyDecision::NeedsApproval(format!(
586 "DOTFILE PROTECTION\n\n\
587 File: {}\n\
588 Operation: {}\n\
589 Reason: {}\n\n\
590 Proposed changes:\n{}\n\n\
591 {}",
592 req.file_path, req.access_type, req.protection_reason, req.proposed_changes, req.warning
593 )));
594 }
595 Ok(ProtectionDecision::RequiresSecondaryAuth(req)) => {
596 return Some(SafetyDecision::NeedsApproval(format!(
597 "DOTFILE SECONDARY AUTHENTICATION REQUIRED\n\n\
598 File: {} (whitelisted)\n\
599 Operation: {}\n\
600 Reason: {}\n\n\
601 This file is on the whitelist but requires secondary authentication.\n\n\
602 Proposed changes:\n{}\n\n\
603 {}",
604 req.file_path, req.access_type, req.protection_reason, req.proposed_changes, req.warning
605 )));
606 }
607 Ok(ProtectionDecision::Blocked(violation)) => {
608 return Some(SafetyDecision::Deny(format!(
609 "DOTFILE MODIFICATION BLOCKED\n\n\
610 File: {}\n\
611 Reason: {}\n\n\
612 Suggestion: {}",
613 violation.file_path, violation.reason, violation.suggestion
614 )));
615 }
616 Ok(ProtectionDecision::Denied(violation)) => {
617 return Some(SafetyDecision::Deny(format!(
618 "DOTFILE ACCESS DENIED\n\n\
619 File: {}\n\
620 Reason: {}\n\n\
621 Suggestion: {}",
622 violation.file_path, violation.reason, violation.suggestion
623 )));
624 }
625 Err(e) => {
626 tracing::error!("Dotfile protection check failed: {}", e);
627 return Some(SafetyDecision::Deny(format!("Dotfile protection check failed: {e}")));
628 }
629 }
630 }
631
632 None
633 }
634
635 pub fn dotfile_guardian(&self) -> Option<&Arc<DotfileGuardian>> {
637 self.dotfile_guardian.as_ref()
638 }
639
640 fn build_risk_context(
646 &self,
647 tool_name: &str,
648 args: &Value,
649 intent: &ToolIntent,
650 command: Option<&str>,
651 ) -> ToolRiskContext {
652 let source = if tool_name.starts_with("mcp_") {
653 ToolSource::Mcp
654 } else if tool_name.starts_with("acp_") {
655 ToolSource::Acp
656 } else {
657 ToolSource::Internal
658 };
659
660 let risk_tool_name = action_qualified_policy_name(tool_name, Some(args)).unwrap_or(tool_name);
661
662 let mut ctx = ToolRiskContext::new(risk_tool_name.to_string(), source, self.config.read().workspace_trust);
663
664 if intent.mutating {
666 ctx = ctx.as_write();
667 }
668 if intent.destructive {
669 ctx = ctx.as_destructive();
670 }
671
672 if ToolRiskScorer::is_network_tool(risk_tool_name) {
673 ctx = ctx.accesses_network();
674 }
675
676 if let Some(command) = command {
678 ctx = ctx.with_args(command.split_whitespace().map(String::from).collect());
679 }
680
681 ctx
682 }
683
684 fn build_approval_justification(
690 &self,
691 tool_name: &str,
692 risk_level: &RiskLevel,
693 args: &Value,
694 intent: &ToolIntent,
695 command: Option<&str>,
696 ) -> String {
697 let mut parts = Vec::new();
698
699 parts.push(format!("Tool: {tool_name}"));
700 parts.push(format!("Risk level: {risk_level}"));
701
702 if intent.destructive {
703 parts.push("This tool may modify or delete files.".to_string());
704 }
705
706 if let Some(command) = command {
707 parts.push(format!("Command: {command}"));
708 }
709
710 let file_targets = file_access_targets(tool_name, args);
711 if let Some(target) = file_targets.first() {
712 parts.push(format!("Path: {}", target.path.display()));
713 if file_targets.len() > 1 {
714 parts.push(format!("Additional targets: {}", file_targets.len() - 1));
715 }
716 }
717
718 parts.join("\n")
719 }
720}
721
722impl Default for SafetyGateway {
723 fn default() -> Self {
724 Self::new()
725 }
726}
727
728#[cfg(test)]
729mod tests;