1use hashbrown::HashSet;
12use parking_lot::{Mutex, RwLock};
13use std::future::Future;
14use std::path::{Path, PathBuf};
15use std::sync::Arc;
16use std::time::{Duration, Instant};
17
18use serde::{Deserialize, Serialize};
19use serde_json::Value;
20use thiserror::Error;
21
22use crate::config::CommandsConfig;
23use crate::config::constants::tools;
24use crate::dotfile_protection::{AccessContext, AccessType, DotfileGuardian, ProtectionDecision, get_global_guardian};
25use crate::tools::apply_patch::{Patch, PatchOperation, decode_apply_patch_input};
26use crate::tools::command_policy::CommandPolicyEvaluator;
27use crate::tools::invocation::ToolInvocationId;
28use crate::tools::rate_limit_config::{tool_calls_per_minute_from_env, tool_calls_per_second_from_env};
29use crate::tools::registry::{RiskLevel, ToolRiskContext, ToolRiskScorer, ToolSource, WorkspaceTrust};
30use crate::tools::tool_intent::{
31 ToolIntent, action_qualified_policy_name, classify_tool_intent, command_session_action_in,
32 command_session_action_is, file_operation_action_is,
33};
34use vtcode_config::constants::tool_limits::{
35 DEFAULT_MAX_TOOL_CALLS_PER_TURN, DEFAULT_SAFETY_MAX_TOOL_CALLS_PER_SESSION, MAX_CONTROL_PLANE_TOOL_CALLS_PER_TURN,
36};
37use vtcode_config::core::DotfileProtectionConfig;
38
39#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
41pub enum SafetyTrustLevel {
42 Untrusted,
43 #[default]
44 Standard,
45 Elevated,
46 Full,
47}
48
49impl SafetyTrustLevel {
50 #[inline]
51 #[must_use]
52 pub const fn can_bypass_approval(self) -> bool {
53 matches!(self, Self::Elevated | Self::Full)
54 }
55}
56
57#[derive(Debug, Clone)]
59pub struct SafetyContext {
60 pub session_id: String,
61 pub trust_level: SafetyTrustLevel,
62}
63
64impl SafetyContext {
65 #[must_use]
66 pub fn new(session_id: impl Into<String>) -> Self {
67 Self {
68 session_id: session_id.into(),
69 trust_level: SafetyTrustLevel::default(),
70 }
71 }
72}
73
74#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
76#[must_use = "safety decisions must be enforced before execution"]
77pub enum SafetyDecision {
78 Allow,
80 Deny(String),
82 NeedsApproval(String),
84}
85
86impl SafetyDecision {
87 #[inline]
89 #[must_use]
90 pub fn is_allowed(&self) -> bool {
91 matches!(self, SafetyDecision::Allow)
92 }
93
94 #[inline]
96 #[must_use]
97 pub fn is_denied(&self) -> bool {
98 matches!(self, SafetyDecision::Deny(_))
99 }
100
101 #[inline]
103 pub fn needs_approval(&self) -> bool {
104 matches!(self, SafetyDecision::NeedsApproval(_))
105 }
106
107 pub fn reason(&self) -> Option<&str> {
109 match self {
110 SafetyDecision::Allow => None,
111 SafetyDecision::Deny(reason) | SafetyDecision::NeedsApproval(reason) => Some(reason),
112 }
113 }
114}
115
116#[derive(Debug, Error, Clone)]
118pub enum SafetyError {
119 #[error("Rate limit exceeded: {current} calls in {window} (max: {max})")]
120 RateLimitExceeded {
121 current: usize,
122 max: usize,
123 window: &'static str,
124 },
125 #[error("Per-turn tool limit reached (max: {max})")]
126 TurnLimitReached { max: usize },
127 #[error("Session tool limit reached (max: {max})")]
128 SessionLimitReached { max: usize },
129 #[error("Planning workflow violation: {0}")]
130 PlanningPolicyViolation(String),
131 #[error("Command policy denied: {0}")]
132 CommandPolicyDenied(String),
133 #[error("Dotfile protection violation: {0}")]
134 DotfileProtectionViolation(String),
135}
136
137#[derive(Debug, Clone)]
139pub struct SafetyCheckResult {
140 pub decision: SafetyDecision,
142 pub retry_after: Option<Duration>,
144 pub violation: Option<SafetyError>,
146}
147
148#[derive(Debug, Clone)]
150pub struct SafetyGatewayConfig {
151 pub max_per_turn: usize,
153 pub max_per_session: usize,
155 pub rate_limit_per_second: usize,
157 pub rate_limit_per_minute: Option<usize>,
159 pub planning_active: bool,
161 pub workspace_trust: WorkspaceTrust,
163 pub approval_risk_threshold: RiskLevel,
165 pub enforce_rate_limits: bool,
168}
169
170impl Default for SafetyGatewayConfig {
171 fn default() -> Self {
172 let rate_limit_per_second = tool_calls_per_second_from_env().unwrap_or(5);
173
174 Self {
175 max_per_turn: DEFAULT_MAX_TOOL_CALLS_PER_TURN,
176 max_per_session: DEFAULT_SAFETY_MAX_TOOL_CALLS_PER_SESSION,
177 rate_limit_per_second,
178 rate_limit_per_minute: tool_calls_per_minute_from_env(),
179 planning_active: false,
180 workspace_trust: WorkspaceTrust::Trusted,
181 approval_risk_threshold: RiskLevel::Medium,
182 enforce_rate_limits: true,
183 }
184 }
185}
186
187#[derive(Debug, Default)]
189struct RateLimiterState {
190 calls_per_second: std::collections::VecDeque<Instant>,
191 calls_per_minute: std::collections::VecDeque<Instant>,
192 current_turn_count: usize,
193 session_count: usize,
194 control_plane_turn_count: usize,
199}
200
201pub struct SafetyGateway {
207 config: RwLock<SafetyGatewayConfig>,
209 command_policy: Option<CommandPolicyEvaluator>,
211 rate_state: Mutex<RateLimiterState>,
213 preapproved: Mutex<HashSet<String>>,
215 dotfile_guardian: Option<Arc<DotfileGuardian>>,
217}
218
219#[derive(Debug, Clone, PartialEq, Eq, Hash)]
220struct FileAccessTarget {
221 path: PathBuf,
222 access_type: AccessType,
223}
224
225fn primary_path_arg(args: &Value) -> Option<&str> {
226 args.get("path")
227 .and_then(|value| value.as_str())
228 .or_else(|| args.get("file_path").and_then(|value| value.as_str()))
229 .or_else(|| args.get("filepath").and_then(|value| value.as_str()))
230 .or_else(|| args.get("target_path").and_then(|value| value.as_str()))
231}
232
233fn destination_path_arg(args: &Value) -> Option<&str> {
234 args.get("destination").and_then(|value| value.as_str())
235}
236
237fn push_file_access_target(targets: &mut Vec<FileAccessTarget>, path: &str, access_type: AccessType) {
238 let path_str = path.trim();
239 if path_str.is_empty() {
240 return;
241 }
242
243 let path = PathBuf::from(path_str);
244 if targets
247 .iter()
248 .any(|existing| existing.path == path && existing.access_type == access_type)
249 {
250 return;
251 }
252
253 targets.push(FileAccessTarget { path, access_type });
254}
255
256fn command_text_for_tool(tool_name: &str, args: &Value) -> Option<String> {
257 match tool_name {
258 tools::EXEC_COMMAND => crate::tools::command_args::command_text(args).ok().flatten(),
259 tools::WRITE_STDIN => crate::tools::command_args::interactive_input_text(args).map(str::to_owned),
260 tools::SHELL | tools::RUN_PTY_CMD => crate::tools::command_args::command_text(args).ok().flatten(),
261 tools::SEND_PTY_INPUT => crate::tools::command_args::interactive_input_text(args).map(str::to_owned),
262 tools::UNIFIED_EXEC if command_session_action_is(args, "run") => {
263 crate::tools::command_args::command_text(args).ok().flatten()
264 }
265 tools::UNIFIED_EXEC if command_session_action_in(args, &["write", "continue"]) => {
266 crate::tools::command_args::interactive_input_text(args).map(str::to_owned)
267 }
268 _ => None,
269 }
270}
271
272fn patch_file_access_targets(args: &Value) -> Vec<FileAccessTarget> {
273 let Ok(Some(patch_input)) = decode_apply_patch_input(args) else {
274 return Vec::new();
275 };
276 let Ok(patch) = Patch::parse(&patch_input.text) else {
277 return Vec::new();
278 };
279
280 let mut targets = Vec::new();
281 for operation in patch.operations() {
282 match operation {
283 PatchOperation::AddFile { path, .. } => {
284 push_file_access_target(&mut targets, path, AccessType::Write);
285 }
286 PatchOperation::DeleteFile { path } => {
287 push_file_access_target(&mut targets, path, AccessType::Delete);
288 }
289 PatchOperation::UpdateFile { path, new_path, .. } => {
290 push_file_access_target(&mut targets, path, AccessType::Modify);
291 if let Some(destination) = new_path.as_deref().filter(|candidate| *candidate != path) {
292 push_file_access_target(&mut targets, destination, AccessType::Write);
293 }
294 }
295 }
296 }
297
298 targets
299}
300
301fn file_access_targets(tool_name: &str, args: &Value) -> Vec<FileAccessTarget> {
302 let mut targets = Vec::new();
303
304 match tool_name {
305 tools::WRITE_FILE | tools::CREATE_FILE => {
306 if let Some(path) = primary_path_arg(args) {
307 push_file_access_target(&mut targets, path, AccessType::Write);
308 }
309 }
310 tools::EDIT_FILE | "search_replace" => {
311 if let Some(path) = primary_path_arg(args) {
312 push_file_access_target(&mut targets, path, AccessType::Modify);
313 }
314 }
315 tools::DELETE_FILE => {
316 if let Some(path) = primary_path_arg(args) {
317 push_file_access_target(&mut targets, path, AccessType::Delete);
318 }
319 }
320 tools::MOVE_FILE => {
321 if let Some(path) = primary_path_arg(args) {
322 push_file_access_target(&mut targets, path, AccessType::Modify);
323 }
324 if let Some(path) = destination_path_arg(args) {
325 push_file_access_target(&mut targets, path, AccessType::Write);
326 }
327 }
328 tools::COPY_FILE => {
329 if let Some(path) = destination_path_arg(args) {
330 push_file_access_target(&mut targets, path, AccessType::Write);
331 }
332 }
333 tools::APPLY_PATCH => {
334 targets.extend(patch_file_access_targets(args));
335 }
336 tools::UNIFIED_FILE => {
337 if file_operation_action_is(args, "write") {
340 if let Some(path) = primary_path_arg(args) {
341 push_file_access_target(&mut targets, path, AccessType::Write);
342 }
343 } else if file_operation_action_is(args, "edit") {
344 if let Some(path) = primary_path_arg(args) {
345 push_file_access_target(&mut targets, path, AccessType::Modify);
346 }
347 } else if file_operation_action_is(args, "delete") {
348 if let Some(path) = primary_path_arg(args) {
349 push_file_access_target(&mut targets, path, AccessType::Delete);
350 }
351 } else if file_operation_action_is(args, "move") {
352 if let Some(path) = primary_path_arg(args) {
353 push_file_access_target(&mut targets, path, AccessType::Modify);
354 }
355 if let Some(path) = destination_path_arg(args) {
356 push_file_access_target(&mut targets, path, AccessType::Write);
357 }
358 } else if file_operation_action_is(args, "copy") {
359 if let Some(path) = destination_path_arg(args) {
360 push_file_access_target(&mut targets, path, AccessType::Write);
361 }
362 }
363 }
364 _ => {}
365 }
366
367 targets
368}
369
370fn proposed_changes_preview(args: &Value) -> String {
371 const PREVIEW_LIMIT: usize = 500;
372
373 let preview_text = |label: &str, text: &str| {
374 let prefix = vtcode_commons::formatting::truncate_utf8_prefix(text, PREVIEW_LIMIT);
375 format!("{label} ({} bytes):\n{}{}", text.len(), prefix, if prefix.len() < text.len() { "..." } else { "" })
376 };
377
378 if let Some(content) = args.get("content").and_then(|value| value.as_str()) {
379 return preview_text("Content", content);
380 }
381
382 if let Some(old_str) = args.get("old_str").and_then(|value| value.as_str()) {
383 let new_str = args.get("new_str").and_then(|value| value.as_str()).unwrap_or("");
384 return format!(
387 "Replace:\n '{}'\nWith:\n '{}'",
388 vtcode_commons::formatting::truncate_byte_budget(old_str, PREVIEW_LIMIT, "..."),
389 vtcode_commons::formatting::truncate_byte_budget(new_str, PREVIEW_LIMIT, "...")
390 );
391 }
392
393 if let Ok(Some(patch_input)) = decode_apply_patch_input(args) {
394 return preview_text("Patch", &patch_input.text);
395 }
396
397 "No details provided".to_string()
398}
399
400impl SafetyGateway {
401 pub fn new() -> Self {
403 Self::with_config(SafetyGatewayConfig::default())
404 }
405
406 pub fn with_config(config: SafetyGatewayConfig) -> Self {
408 Self {
409 config: RwLock::new(config),
410 command_policy: None,
411 rate_state: Mutex::new(RateLimiterState::default()),
412 preapproved: Mutex::new(HashSet::new()),
413 dotfile_guardian: None,
414 }
415 }
416
417 pub fn with_dotfile_guardian(mut self, guardian: Arc<DotfileGuardian>) -> Self {
419 self.dotfile_guardian = Some(guardian);
420 self
421 }
422
423 pub async fn with_dotfile_protection(mut self, config: DotfileProtectionConfig) -> anyhow::Result<Self> {
425 let guardian = DotfileGuardian::new(config).await?;
426 self.dotfile_guardian = Some(Arc::new(guardian));
427 Ok(self)
428 }
429
430 pub fn with_command_policy(mut self, policy: CommandPolicyEvaluator) -> Self {
432 self.command_policy = Some(policy);
433 self
434 }
435
436 pub fn with_commands_config(mut self, config: &CommandsConfig) -> Self {
438 self.command_policy = Some(CommandPolicyEvaluator::from_config(config));
439 self
440 }
441
442 pub fn set_planning_workflow(&self, active: bool) {
444 self.config.write().planning_active = active;
445 }
446
447 pub fn set_workspace_trust(&self, trust: WorkspaceTrust) {
449 self.config.write().workspace_trust = trust;
450 }
451
452 pub fn set_limits(&self, max_per_turn: usize, max_per_session: usize) {
454 let mut config = self.config.write();
455 config.max_per_turn = max_per_turn;
456 config.max_per_session = max_per_session;
457 }
458
459 pub fn set_rate_limits(&self, rate_limit_per_second: usize, rate_limit_per_minute: Option<usize>) {
461 let mut config = self.config.write();
462 if rate_limit_per_second > 0 {
463 config.rate_limit_per_second = rate_limit_per_second;
464 }
465 config.rate_limit_per_minute = rate_limit_per_minute.filter(|v| *v > 0);
466 }
467
468 pub fn set_rate_limit_enforcement(&self, enabled: bool) {
470 self.config.write().enforce_rate_limits = enabled;
471 }
472
473 pub fn increase_session_limit(&self, increment: usize) {
475 let mut config = self.config.write();
476 let new_max = config.max_per_session.saturating_add(increment);
477 config.max_per_session = new_max;
478 tracing::info!("Session tool limit increased to {}", new_max);
479 }
480
481 pub fn max_per_session(&self) -> usize {
482 self.config.read().max_per_session
483 }
484
485 pub fn start_turn(&self) {
487 let mut state = self.rate_state.lock();
488 state.current_turn_count = 0;
489 state.control_plane_turn_count = 0;
490 state.calls_per_second.clear();
491 state.calls_per_minute.clear();
492 }
493
494 pub fn reset_for_fresh_execution(&self, max_per_turn: usize, max_per_session: usize) {
497 self.set_limits(max_per_turn, max_per_session);
498 let mut state = self.rate_state.lock();
499 state.current_turn_count = 0;
500 state.control_plane_turn_count = 0;
501 state.session_count = 0;
502 state.calls_per_second.clear();
503 state.calls_per_minute.clear();
504 }
505
506 pub fn preapprove(&self, tool_name: &str) {
508 let mut preapproved = self.preapproved.lock();
509 preapproved.insert(tool_name.to_string());
510 }
511
512 pub fn is_preapproved(&self, tool_name: &str) -> bool {
514 let preapproved = self.preapproved.lock();
515 preapproved.contains(tool_name)
516 }
517
518 pub fn check_safety<'a>(
524 &'a self,
525 ctx: &'a SafetyContext,
526 tool_name: &'a str,
527 args: &'a Value,
528 ) -> impl Future<Output = SafetyDecision> + 'a {
529 self.check_safety_with_id(ctx, tool_name, args, None)
530 }
531
532 pub async fn check_safety_with_id(
534 &self,
535 ctx: &SafetyContext,
536 tool_name: &str,
537 args: &Value,
538 invocation_id: Option<ToolInvocationId>,
539 ) -> SafetyDecision {
540 let inv_id = invocation_id.map(|id| id.short()).unwrap_or_else(|| "unknown".to_string());
541
542 tracing::trace!(
543 invocation_id = %inv_id,
544 tool = %tool_name,
545 "SafetyGateway: checking safety"
546 );
547
548 if let Err(err) = self.check_rate_limits(crate::tools::tool_intent::is_turn_budget_exempt_call(tool_name, args))
549 {
550 tracing::warn!(
551 invocation_id = %inv_id,
552 error = %err,
553 "SafetyGateway: rate limit exceeded"
554 );
555 return SafetyDecision::Deny(err.to_string());
556 }
557
558 self.evaluate_non_rate_decision(ctx, tool_name, args, &inv_id).await
559 }
560
561 pub async fn check_and_record(&self, ctx: &SafetyContext, tool_name: &str, args: &Value) -> SafetyCheckResult {
566 self.check_and_record_with_id(ctx, tool_name, args, None).await
567 }
568
569 pub async fn check_and_record_with_id(
571 &self,
572 ctx: &SafetyContext,
573 tool_name: &str,
574 args: &Value,
575 invocation_id: Option<ToolInvocationId>,
576 ) -> SafetyCheckResult {
577 let inv_id = invocation_id.map(|id| id.short()).unwrap_or_else(|| "unknown".to_string());
578 tracing::trace!(
579 invocation_id = %inv_id,
580 tool = %tool_name,
581 "SafetyGateway: checking and recording safety"
582 );
583
584 let decision = self.evaluate_non_rate_decision(ctx, tool_name, args, &inv_id).await;
585
586 if decision.is_denied() {
587 return SafetyCheckResult { decision, retry_after: None, violation: None };
588 }
589
590 let control_plane = crate::tools::tool_intent::is_turn_budget_exempt_call(tool_name, args);
591 let now = Instant::now();
592 let mut state = self.rate_state.lock();
593 match self.check_rate_limits_locked(&mut state, now, control_plane) {
594 Ok(()) => {
595 self.record_execution_locked(&mut state, now, control_plane);
596 SafetyCheckResult { decision, retry_after: None, violation: None }
597 }
598 Err(err) => {
599 tracing::warn!(
600 invocation_id = %inv_id,
601 error = %err,
602 "SafetyGateway: rate limit exceeded during atomic reservation"
603 );
604 SafetyCheckResult {
605 decision: SafetyDecision::Deny(err.to_string()),
606 retry_after: self.retry_after_for_violation(&err, &state, now),
607 violation: Some(err),
608 }
609 }
610 }
611 }
612
613 async fn evaluate_non_rate_decision(
614 &self,
615 ctx: &SafetyContext,
616 tool_name: &str,
617 args: &Value,
618 inv_id: &str,
619 ) -> SafetyDecision {
620 let command = command_text_for_tool(tool_name, args);
625
626 if let Some(decision) = self.check_dotfile_protection(tool_name, args, &ctx.session_id).await {
627 tracing::info!(
628 invocation_id = %inv_id,
629 tool = %tool_name,
630 "SafetyGateway: dotfile protection triggered"
631 );
632 return decision;
633 }
634
635 if let Some(ref policy) = self.command_policy
636 && let Some(command) = command.as_deref()
637 && !policy.allows_text(command)
638 {
639 let reason = format!("Command '{command}' blocked by policy");
640 tracing::info!(
641 invocation_id = %inv_id,
642 command = %command,
643 "SafetyGateway: command policy denied"
644 );
645 return SafetyDecision::Deny(reason);
646 }
647
648 if self.is_preapproved(tool_name) {
649 tracing::trace!(
650 invocation_id = %inv_id,
651 tool = %tool_name,
652 "SafetyGateway: tool preapproved"
653 );
654 return SafetyDecision::Allow;
655 }
656
657 if ctx.trust_level.can_bypass_approval() {
658 tracing::trace!(
659 invocation_id = %inv_id,
660 tool = %tool_name,
661 trust_level = ?ctx.trust_level,
662 "SafetyGateway: trust level allows bypass"
663 );
664 return SafetyDecision::Allow;
665 }
666
667 let intent = classify_tool_intent(tool_name, args);
671 let command = command.as_deref();
672 let risk_ctx = self.build_risk_context(tool_name, args, &intent, command);
673 let risk_level = ToolRiskScorer::calculate_risk(&risk_ctx);
674
675 if ToolRiskScorer::requires_justification(risk_level, self.config.read().approval_risk_threshold) {
676 let justification = self.build_approval_justification(tool_name, &risk_level, args, &intent, command);
677 tracing::info!(
678 invocation_id = %inv_id,
679 tool = %tool_name,
680 risk = %risk_level,
681 "SafetyGateway: requires approval"
682 );
683 return SafetyDecision::NeedsApproval(justification);
684 }
685
686 if intent.destructive {
687 let justification = format!("Tool '{tool_name}' is destructive and may modify files or execute commands.");
688 tracing::info!(
689 invocation_id = %inv_id,
690 tool = %tool_name,
691 "SafetyGateway: destructive tool requires approval"
692 );
693 return SafetyDecision::NeedsApproval(justification);
694 }
695
696 SafetyDecision::Allow
697 }
698
699 pub fn record_execution(&self) {
701 let mut state = self.rate_state.lock();
702 self.record_execution_locked(&mut state, Instant::now(), false);
703 }
704
705 fn check_rate_limits(&self, control_plane: bool) -> Result<(), SafetyError> {
707 let mut state = self.rate_state.lock();
708 self.check_rate_limits_locked(&mut state, Instant::now(), control_plane)
709 }
710
711 fn check_rate_limits_locked(
712 &self,
713 state: &mut RateLimiterState,
714 now: Instant,
715 control_plane: bool,
716 ) -> Result<(), SafetyError> {
717 let config = self.config.read();
718 self.prune_rate_windows(state, now);
719
720 if config.enforce_rate_limits {
721 if state.calls_per_second.len() >= config.rate_limit_per_second {
722 return Err(SafetyError::RateLimitExceeded {
723 current: state.calls_per_second.len(),
724 max: config.rate_limit_per_second,
725 window: "1s",
726 });
727 }
728
729 if let Some(limit) = config.rate_limit_per_minute
730 && state.calls_per_minute.len() >= limit
731 {
732 return Err(SafetyError::RateLimitExceeded {
733 current: state.calls_per_minute.len(),
734 max: limit,
735 window: "60s",
736 });
737 }
738 }
739
740 if control_plane {
741 if state.control_plane_turn_count >= MAX_CONTROL_PLANE_TOOL_CALLS_PER_TURN {
745 return Err(SafetyError::TurnLimitReached { max: MAX_CONTROL_PLANE_TOOL_CALLS_PER_TURN });
746 }
747 } else if state.current_turn_count >= config.max_per_turn {
748 return Err(SafetyError::TurnLimitReached { max: config.max_per_turn });
749 }
750
751 if state.session_count >= config.max_per_session {
752 return Err(SafetyError::SessionLimitReached { max: config.max_per_session });
753 }
754
755 Ok(())
756 }
757
758 fn record_execution_locked(&self, state: &mut RateLimiterState, now: Instant, control_plane: bool) {
759 state.calls_per_second.push_back(now);
760 state.calls_per_minute.push_back(now);
761 state.session_count = state.session_count.saturating_add(1);
762 if control_plane {
763 state.control_plane_turn_count = state.control_plane_turn_count.saturating_add(1);
764 } else {
765 state.current_turn_count = state.current_turn_count.saturating_add(1);
766 }
767 }
768
769 fn prune_rate_windows(&self, state: &mut RateLimiterState, now: Instant) {
770 while let Some(front) = state.calls_per_second.front() {
771 if now.duration_since(*front) > Duration::from_secs(1) {
772 state.calls_per_second.pop_front();
773 } else {
774 break;
775 }
776 }
777 while let Some(front) = state.calls_per_minute.front() {
778 if now.duration_since(*front) > Duration::from_secs(60) {
779 state.calls_per_minute.pop_front();
780 } else {
781 break;
782 }
783 }
784 }
785
786 fn retry_after_for_violation(
787 &self,
788 violation: &SafetyError,
789 state: &RateLimiterState,
790 now: Instant,
791 ) -> Option<Duration> {
792 match violation {
793 SafetyError::RateLimitExceeded { window: "1s", .. } => state
794 .calls_per_second
795 .front()
796 .map(|first| Duration::from_secs(1).saturating_sub(now.duration_since(*first))),
797 SafetyError::RateLimitExceeded { window: "60s", .. } => state
798 .calls_per_minute
799 .front()
800 .map(|first| Duration::from_secs(60).saturating_sub(now.duration_since(*first))),
801 _ => None,
802 }
803 }
804
805 async fn check_dotfile_protection(
808 &self,
809 tool_name: &str,
810 args: &Value,
811 session_id: &str,
812 ) -> Option<SafetyDecision> {
813 let guardian = match self.dotfile_guardian.as_ref() {
815 Some(g) => g.clone(),
816 None => get_global_guardian()?,
817 };
818
819 let file_targets = file_access_targets(tool_name, args);
820 if file_targets.is_empty() {
821 return None;
822 }
823
824 let proposed_changes = proposed_changes_preview(args);
825
826 for target in file_targets {
827 if !guardian.is_protected(Path::new(&target.path)) {
828 continue;
829 }
830
831 let context = AccessContext::new(&target.path, target.access_type, tool_name, session_id)
832 .with_proposed_changes(&proposed_changes);
833
834 match guardian.request_access(&context).await {
835 Ok(ProtectionDecision::Allowed) => continue,
836 Ok(ProtectionDecision::RequiresConfirmation(req)) => {
837 return Some(SafetyDecision::NeedsApproval(format!(
838 "DOTFILE PROTECTION\n\n\
839 File: {}\n\
840 Operation: {}\n\
841 Reason: {}\n\n\
842 Proposed changes:\n{}\n\n\
843 {}",
844 req.file_path, req.access_type, req.protection_reason, req.proposed_changes, req.warning
845 )));
846 }
847 Ok(ProtectionDecision::RequiresSecondaryAuth(req)) => {
848 return Some(SafetyDecision::NeedsApproval(format!(
849 "DOTFILE SECONDARY AUTHENTICATION REQUIRED\n\n\
850 File: {} (whitelisted)\n\
851 Operation: {}\n\
852 Reason: {}\n\n\
853 This file is on the whitelist but requires secondary authentication.\n\n\
854 Proposed changes:\n{}\n\n\
855 {}",
856 req.file_path, req.access_type, req.protection_reason, req.proposed_changes, req.warning
857 )));
858 }
859 Ok(ProtectionDecision::Blocked(violation)) => {
860 return Some(SafetyDecision::Deny(format!(
861 "DOTFILE MODIFICATION BLOCKED\n\n\
862 File: {}\n\
863 Reason: {}\n\n\
864 Suggestion: {}",
865 violation.file_path, violation.reason, violation.suggestion
866 )));
867 }
868 Ok(ProtectionDecision::Denied(violation)) => {
869 return Some(SafetyDecision::Deny(format!(
870 "DOTFILE ACCESS DENIED\n\n\
871 File: {}\n\
872 Reason: {}\n\n\
873 Suggestion: {}",
874 violation.file_path, violation.reason, violation.suggestion
875 )));
876 }
877 Err(e) => {
878 tracing::error!("Dotfile protection check failed: {}", e);
879 return Some(SafetyDecision::Deny(format!("Dotfile protection check failed: {e}")));
880 }
881 }
882 }
883
884 None
885 }
886
887 pub fn dotfile_guardian(&self) -> Option<&Arc<DotfileGuardian>> {
889 self.dotfile_guardian.as_ref()
890 }
891
892 fn build_risk_context(
898 &self,
899 tool_name: &str,
900 args: &Value,
901 intent: &ToolIntent,
902 command: Option<&str>,
903 ) -> ToolRiskContext {
904 let source = if tool_name.starts_with("mcp_") {
905 ToolSource::Mcp
906 } else if tool_name.starts_with("acp_") {
907 ToolSource::Acp
908 } else {
909 ToolSource::Internal
910 };
911
912 let risk_tool_name = action_qualified_policy_name(tool_name, Some(args)).unwrap_or(tool_name);
913
914 let mut ctx = ToolRiskContext::new(risk_tool_name.to_string(), source, self.config.read().workspace_trust);
915
916 if intent.mutating {
918 ctx = ctx.as_write();
919 }
920 if intent.destructive {
921 ctx = ctx.as_destructive();
922 }
923
924 if ToolRiskScorer::is_network_tool(risk_tool_name) {
925 ctx = ctx.accesses_network();
926 }
927
928 if let Some(command) = command {
930 ctx = ctx.with_args(command.split_whitespace().map(String::from).collect());
931 }
932
933 ctx
934 }
935
936 fn build_approval_justification(
942 &self,
943 tool_name: &str,
944 risk_level: &RiskLevel,
945 args: &Value,
946 intent: &ToolIntent,
947 command: Option<&str>,
948 ) -> String {
949 let mut parts = Vec::new();
950
951 parts.push(format!("Tool: {tool_name}"));
952 parts.push(format!("Risk level: {risk_level}"));
953
954 if intent.destructive {
955 parts.push("This tool may modify or delete files.".to_string());
956 }
957
958 if let Some(command) = command {
959 parts.push(format!("Command: {command}"));
960 }
961
962 let file_targets = file_access_targets(tool_name, args);
963 if let Some(target) = file_targets.first() {
964 parts.push(format!("Path: {}", target.path.display()));
965 if file_targets.len() > 1 {
966 parts.push(format!("Additional targets: {}", file_targets.len() - 1));
967 }
968 }
969
970 parts.join("\n")
971 }
972
973 pub fn get_stats(&self) -> SafetyStats {
975 let state = self.rate_state.lock();
976 let preapproved = self.preapproved.lock();
977 let config = self.config.read();
978
979 SafetyStats {
980 turn_count: state.current_turn_count,
981 session_count: state.session_count,
982 max_per_turn: config.max_per_turn,
983 max_per_session: config.max_per_session,
984 planning_active: config.planning_active,
985 preapproved_count: preapproved.len(),
986 }
987 }
988}
989
990impl Default for SafetyGateway {
991 fn default() -> Self {
992 Self::new()
993 }
994}
995
996#[derive(Debug, Clone)]
998pub struct SafetyStats {
999 pub turn_count: usize,
1000 pub session_count: usize,
1001 pub max_per_turn: usize,
1002 pub max_per_session: usize,
1003 pub planning_active: bool,
1004 pub preapproved_count: usize,
1005}
1006
1007#[cfg(test)]
1008mod tests {
1009 use super::*;
1010 use vtcode_config::core::DotfileProtectionConfig;
1011
1012 fn make_ctx() -> SafetyContext {
1013 SafetyContext::new("test-session")
1014 }
1015
1016 #[tokio::test]
1017 async fn test_allow_read_only_tools() {
1018 let gateway = SafetyGateway::new();
1019 let ctx = make_ctx();
1020
1021 let decision = gateway
1022 .check_safety(&ctx, "read_file", &serde_json::json!({"path": "/tmp/test"}))
1023 .await;
1024
1025 assert!(decision.is_allowed());
1026 }
1027
1028 #[tokio::test]
1029 async fn test_destructive_tool_needs_approval() {
1030 let gateway = SafetyGateway::new();
1031 let ctx = make_ctx();
1032
1033 let decision = gateway
1034 .check_safety(&ctx, "delete_file", &serde_json::json!({"path": "/tmp/test"}))
1035 .await;
1036
1037 assert!(decision.needs_approval());
1038 }
1039
1040 #[tokio::test]
1041 async fn test_planning_workflow_does_not_double_block_mutating() {
1042 let gateway = SafetyGateway::new();
1043 gateway.set_planning_workflow(true);
1044 let ctx = make_ctx();
1045
1046 let decision = gateway
1047 .check_safety(&ctx, "apply_patch", &serde_json::json!({"patch": "..."}))
1048 .await;
1049
1050 assert!(decision.needs_approval());
1051 }
1052
1053 #[tokio::test]
1059 async fn command_extraction_feeds_policy_risk_and_justification_identically() {
1060 let policy = CommandPolicyEvaluator::from_config(&CommandsConfig {
1061 allow_list: vec!["cargo".into()],
1062 ..Default::default()
1063 });
1064 let gateway = SafetyGateway::new().with_command_policy(policy);
1065
1066 let allowed = gateway
1069 .check_safety(&make_ctx(), tools::EXEC_COMMAND, &serde_json::json!({"command": "cargo test"}))
1070 .await;
1071 assert!(allowed.is_allowed());
1072
1073 let denied = gateway
1075 .check_safety(&make_ctx(), tools::EXEC_COMMAND, &serde_json::json!({"command": "rm -rf /"}))
1076 .await;
1077 let SafetyDecision::Deny(reason) = denied else {
1078 panic!("policy denial expected");
1079 };
1080 assert!(reason.contains("rm -rf /"), "denial must carry the extracted command: {reason}");
1081 assert!(reason.starts_with("Command 'rm -rf /' blocked by policy"), "unexpected denial shape: {reason}");
1082
1083 gateway.config.write().approval_risk_threshold.clone_from(&RiskLevel::Low);
1086 let justified = gateway
1087 .check_safety(&make_ctx(), tools::EXEC_COMMAND, &serde_json::json!({"command": "cargo publish"}))
1088 .await;
1089 if let SafetyDecision::NeedsApproval(justification) = justified {
1090 assert!(
1091 justification.contains("Command: cargo publish"),
1092 "justification must carry the extracted command: {justification}"
1093 );
1094 }
1095 gateway.config.write().approval_risk_threshold = RiskLevel::High;
1096 }
1097
1098 #[test]
1099 fn build_risk_context_uses_caller_supplied_command() {
1100 let gateway = SafetyGateway::new();
1101 let args = serde_json::json!({"command": "rg --files"});
1102 let intent = classify_tool_intent(tools::EXEC_COMMAND, &args);
1103
1104 let with_command = gateway.build_risk_context(tools::EXEC_COMMAND, &args, &intent, Some("rg --files"));
1105 assert_eq!(with_command.command_args, vec!["rg".to_string(), "--files".to_string()]);
1106
1107 let without_command = gateway.build_risk_context(tools::EXEC_COMMAND, &args, &intent, None);
1108 assert!(without_command.command_args.is_empty());
1109 }
1110
1111 #[tokio::test]
1112 async fn test_preapproved_tools_allowed() {
1113 let gateway = SafetyGateway::new();
1114 gateway.preapprove("delete_file");
1115 let ctx = make_ctx();
1116
1117 let decision = gateway
1118 .check_safety(&ctx, "delete_file", &serde_json::json!({"path": "/tmp/test"}))
1119 .await;
1120
1121 assert!(decision.is_allowed());
1122 }
1123
1124 #[tokio::test]
1125 async fn test_trust_level_bypass() {
1126 let gateway = SafetyGateway::new();
1127 let mut ctx = make_ctx();
1128 ctx.trust_level = SafetyTrustLevel::Full;
1129
1130 let decision = gateway
1131 .check_safety(&ctx, "delete_file", &serde_json::json!({"path": "/tmp/test"}))
1132 .await;
1133
1134 assert!(decision.is_allowed());
1135 }
1136
1137 #[tokio::test]
1138 async fn test_rate_limiting() {
1139 let config = SafetyGatewayConfig { rate_limit_per_second: 2, ..Default::default() };
1140 let gateway = SafetyGateway::with_config(config);
1141 let ctx = make_ctx();
1142
1143 gateway.record_execution();
1145 gateway.record_execution();
1146
1147 let decision = gateway.check_safety(&ctx, "read_file", &serde_json::json!({})).await;
1149
1150 assert!(decision.is_denied());
1151 assert!(decision.reason().unwrap().contains("Rate limit"));
1152 }
1153
1154 #[test]
1155 fn safety_gateway_defaults_use_shared_tool_call_budget() {
1156 let config = SafetyGatewayConfig::default();
1157
1158 assert_eq!(config.max_per_turn, DEFAULT_MAX_TOOL_CALLS_PER_TURN);
1159 assert_eq!(config.max_per_session, DEFAULT_SAFETY_MAX_TOOL_CALLS_PER_SESSION);
1160 }
1161
1162 #[tokio::test]
1163 async fn test_atomic_check_and_record_rate_limited() {
1164 let config = SafetyGatewayConfig { rate_limit_per_second: 2, ..Default::default() };
1165 let gateway = SafetyGateway::with_config(config);
1166 let ctx = make_ctx();
1167
1168 let first = gateway.check_and_record(&ctx, "read_file", &serde_json::json!({})).await;
1169 assert!(first.decision.is_allowed());
1170
1171 let second = gateway.check_and_record(&ctx, "read_file", &serde_json::json!({})).await;
1172 assert!(second.decision.is_allowed());
1173
1174 let third = gateway.check_and_record(&ctx, "read_file", &serde_json::json!({})).await;
1175 assert!(third.decision.is_denied());
1176 assert!(third.retry_after.is_some());
1177 assert!(matches!(third.violation, Some(SafetyError::RateLimitExceeded { .. })));
1178 }
1179
1180 #[tokio::test]
1181 async fn test_command_policy_enforcement() {
1182 let mut commands_config = CommandsConfig::default();
1183 commands_config.deny_list.push("rm".to_string());
1184
1185 let gateway = SafetyGateway::new().with_commands_config(&commands_config);
1186 let ctx = make_ctx();
1187
1188 let decision = gateway
1189 .check_safety(&ctx, "shell", &serde_json::json!({"command": "rm -rf /"}))
1190 .await;
1191
1192 assert!(decision.is_denied());
1193 }
1194
1195 #[tokio::test]
1196 async fn test_command_session_command_policy_enforcement_with_indexed_args() {
1197 let mut commands_config = CommandsConfig::default();
1198 commands_config.deny_list.push("rm".to_string());
1199
1200 let gateway = SafetyGateway::new().with_commands_config(&commands_config);
1201 let ctx = make_ctx();
1202
1203 let decision = gateway
1204 .check_safety(
1205 &ctx,
1206 tools::UNIFIED_EXEC,
1207 &serde_json::json!({
1208 "command.0": "rm",
1209 "command.1": "-rf",
1210 "command.2": "/"
1211 }),
1212 )
1213 .await;
1214
1215 assert!(decision.is_denied());
1216 }
1217
1218 #[tokio::test]
1219 async fn test_command_session_continue_command_policy_enforcement_with_input() {
1220 let mut commands_config = CommandsConfig::default();
1221 commands_config.deny_list.push("rm".to_string());
1222
1223 let gateway = SafetyGateway::new().with_commands_config(&commands_config);
1224 let ctx = make_ctx();
1225
1226 let decision = gateway
1227 .check_safety(
1228 &ctx,
1229 tools::UNIFIED_EXEC,
1230 &serde_json::json!({
1231 "action": "continue",
1232 "session_id": "run-123",
1233 "input": "rm -rf /\n"
1234 }),
1235 )
1236 .await;
1237
1238 assert!(decision.is_denied());
1239 }
1240
1241 #[tokio::test]
1242 async fn test_send_pty_input_command_policy_enforcement_with_input() {
1243 let mut commands_config = CommandsConfig::default();
1244 commands_config.deny_list.push("rm".to_string());
1245
1246 let gateway = SafetyGateway::new().with_commands_config(&commands_config);
1247 let ctx = make_ctx();
1248
1249 let decision = gateway
1250 .check_safety(
1251 &ctx,
1252 tools::SEND_PTY_INPUT,
1253 &serde_json::json!({
1254 "session_id": "run-123",
1255 "input": "rm -rf /\n"
1256 }),
1257 )
1258 .await;
1259
1260 assert!(decision.is_denied());
1261 }
1262
1263 #[tokio::test]
1264 async fn test_apply_patch_dotfile_input_dotfile_protection_requires_approval() {
1265 let guardian = Arc::new(
1266 DotfileGuardian::new(DotfileProtectionConfig {
1267 audit_logging_enabled: false,
1268 create_backups: false,
1269 ..Default::default()
1270 })
1271 .await
1272 .expect("guardian should initialize"),
1273 );
1274 let gateway = SafetyGateway::new().with_dotfile_guardian(guardian);
1275 let ctx = make_ctx();
1276
1277 let decision = gateway
1278 .check_safety(
1279 &ctx,
1280 tools::APPLY_PATCH,
1281 &serde_json::json!({
1282 "input": "*** Begin Patch\n*** Update File: .gitignore\n@@\n-old\n+new\n*** End Patch\n"
1283 }),
1284 )
1285 .await;
1286
1287 assert!(decision.needs_approval());
1288 assert!(decision.reason().is_some_and(|reason| reason.contains(".gitignore")));
1289 }
1290
1291 #[test]
1292 fn test_patch_file_access_targets_preserve_patch_order() {
1293 let targets = patch_file_access_targets(&serde_json::json!({
1294 "input": "*** Begin Patch\n*** Update File: src/main.rs\n@@\n-old\n+new\n*** Update File: .gitignore\n@@\n-old\n+new\n*** End Patch\n"
1295 }));
1296
1297 assert_eq!(targets.len(), 2);
1298 assert_eq!(targets[0].path, PathBuf::from("src/main.rs"));
1299 assert_eq!(targets[0].access_type, AccessType::Modify);
1300 assert_eq!(targets[1].path, PathBuf::from(".gitignore"));
1301 assert_eq!(targets[1].access_type, AccessType::Modify);
1302 }
1303
1304 #[test]
1305 fn unified_file_targets_mirror_legacy_file_helpers() {
1306 let write = file_access_targets(tools::UNIFIED_FILE, &serde_json::json!({"action": "write", "path": "a.txt"}));
1307 assert_eq!(write.len(), 1);
1308 assert_eq!(write[0].path, PathBuf::from("a.txt"));
1309 assert_eq!(write[0].access_type, AccessType::Write);
1310
1311 let moved = file_access_targets(
1312 tools::UNIFIED_FILE,
1313 &serde_json::json!({"action": "move", "path": "a.txt", "destination": "b.txt"}),
1314 );
1315 assert_eq!(moved.len(), 2);
1316 assert_eq!(moved[0].access_type, AccessType::Modify);
1317 assert_eq!(moved[1].access_type, AccessType::Write);
1318
1319 let unknown = file_access_targets(tools::UNIFIED_FILE, &serde_json::json!({"action": "read", "path": "a.txt"}));
1320 assert!(unknown.is_empty());
1321 }
1322
1323 #[test]
1324 fn proposed_changes_preview_bounds_old_and_new_str() {
1325 let short = proposed_changes_preview(&serde_json::json!({"old_str": "a", "new_str": "b"}));
1329 assert_eq!(short, "Replace:\n 'a'\nWith:\n 'b'");
1330
1331 let long_old = "a".repeat(600);
1332 let bounded = proposed_changes_preview(&serde_json::json!({"old_str": long_old, "new_str": ""}));
1333 assert!(bounded.contains("..."));
1334 assert!(bounded.len() < 600, "preview must stay bounded: {}", bounded.len());
1335
1336 let boundary_old = format!("{}{}", "a".repeat(499), "日".repeat(10));
1337 let boundary = proposed_changes_preview(&serde_json::json!({"old_str": boundary_old, "new_str": "b"}));
1338 assert!(boundary.contains("..."));
1339 assert!(boundary.ends_with("With:\n 'b'"));
1340 }
1341
1342 #[test]
1343 fn proposed_changes_preview_never_splits_utf8_boundary() {
1344 let content = format!("{}{}", "a".repeat(499), "日".repeat(10));
1347 let preview = proposed_changes_preview(&serde_json::json!({"content": content}));
1348 assert!(preview.contains("Content ("));
1349 assert!(preview.ends_with("..."));
1350 assert!(preview.len() < content.len() + 64);
1351 }
1352
1353 #[tokio::test]
1354 async fn test_apply_patch_patch_field_dotfile_protection_requires_approval() {
1355 let guardian = Arc::new(
1356 DotfileGuardian::new(DotfileProtectionConfig {
1357 audit_logging_enabled: false,
1358 create_backups: false,
1359 ..Default::default()
1360 })
1361 .await
1362 .expect("guardian should initialize"),
1363 );
1364 let gateway = SafetyGateway::new().with_dotfile_guardian(guardian);
1365 let ctx = make_ctx();
1366
1367 let decision = gateway
1368 .check_safety(
1369 &ctx,
1370 tools::APPLY_PATCH,
1371 &serde_json::json!({
1372 "patch": "*** Begin Patch\n*** Update File: .gitignore\n@@\n-old\n+new\n*** End Patch\n"
1373 }),
1374 )
1375 .await;
1376
1377 assert!(decision.needs_approval());
1378 assert!(decision.reason().is_some_and(|reason| reason.contains(".gitignore")));
1379 }
1380
1381 #[tokio::test]
1382 async fn test_stats_tracking() {
1383 let gateway = SafetyGateway::new();
1384 gateway.preapprove("test_tool");
1385 gateway.record_execution();
1386 gateway.record_execution();
1387
1388 let stats = gateway.get_stats();
1389 assert_eq!(stats.turn_count, 2);
1390 assert_eq!(stats.session_count, 2);
1391 assert_eq!(stats.preapproved_count, 1);
1392 }
1393
1394 #[tokio::test]
1395 async fn test_start_turn_resets_counters() {
1396 let gateway = SafetyGateway::new();
1397
1398 gateway.record_execution();
1399 gateway.record_execution();
1400
1401 let stats_before = gateway.get_stats();
1402 assert_eq!(stats_before.turn_count, 2);
1403
1404 gateway.start_turn();
1405
1406 let stats_after = gateway.get_stats();
1407 assert_eq!(stats_after.turn_count, 0);
1408 assert_eq!(stats_after.session_count, 2); }
1410
1411 #[tokio::test]
1412 async fn test_increase_session_limit_updates_limit() {
1413 let gateway = SafetyGateway::new();
1414 gateway.set_limits(10, 1);
1415 let ctx = make_ctx();
1416
1417 let first = gateway.check_and_record(&ctx, "read_file", &serde_json::json!({})).await;
1418 assert!(first.decision.is_allowed());
1419
1420 let second = gateway.check_and_record(&ctx, "read_file", &serde_json::json!({})).await;
1421 assert!(second.decision.is_denied());
1422
1423 gateway.increase_session_limit(1);
1424
1425 let third = gateway.check_and_record(&ctx, "read_file", &serde_json::json!({})).await;
1426 assert!(third.decision.is_allowed());
1427 }
1428
1429 #[tokio::test]
1430 async fn control_plane_wait_does_not_consume_per_turn_budget() {
1431 let config = SafetyGatewayConfig { max_per_turn: 1, ..Default::default() };
1432 let gateway = SafetyGateway::with_config(config);
1433 let ctx = make_ctx();
1434
1435 let work = gateway
1437 .check_and_record(&ctx, "read_file", &serde_json::json!({"path": "x.txt"}))
1438 .await;
1439 assert!(work.decision.is_allowed());
1440
1441 let wait = gateway
1444 .check_and_record(&ctx, tools::UNIFIED_EXEC, &serde_json::json!({"action": "wait", "session_id": "run-1"}))
1445 .await;
1446 assert!(wait.decision.is_allowed(), "wait must bypass the per-turn work budget");
1447
1448 let denied = gateway
1450 .check_and_record(&ctx, "read_file", &serde_json::json!({"path": "y.txt"}))
1451 .await;
1452 assert!(denied.decision.is_denied());
1453 }
1454
1455 #[tokio::test]
1456 async fn control_plane_calls_are_bounded_by_their_own_cap() {
1457 let config = SafetyGatewayConfig {
1458 max_per_turn: 1_000,
1459 enforce_rate_limits: false,
1460 ..Default::default()
1461 };
1462 let gateway = SafetyGateway::with_config(config);
1463 let ctx = make_ctx();
1464
1465 for _ in 0..MAX_CONTROL_PLANE_TOOL_CALLS_PER_TURN {
1466 let call = gateway
1467 .check_and_record(
1468 &ctx,
1469 tools::UNIFIED_EXEC,
1470 &serde_json::json!({"action": "wait", "session_id": "run-1"}),
1471 )
1472 .await;
1473 assert!(call.decision.is_allowed());
1474 }
1475
1476 let overflow = gateway
1478 .check_and_record(&ctx, tools::UNIFIED_EXEC, &serde_json::json!({"action": "wait", "session_id": "run-1"}))
1479 .await;
1480 assert!(overflow.decision.is_denied());
1481 assert!(overflow.decision.reason().is_some_and(|reason| reason.contains("limit")));
1482 }
1483
1484 #[tokio::test]
1485 async fn control_plane_calls_still_consume_session_and_rate_budget() {
1486 let config = SafetyGatewayConfig {
1488 max_per_turn: 1_000,
1489 max_per_session: 2,
1490 enforce_rate_limits: false,
1491 ..Default::default()
1492 };
1493 let gateway = SafetyGateway::with_config(config);
1494 let ctx = make_ctx();
1495
1496 for _ in 0..2 {
1497 let call = gateway
1498 .check_and_record(
1499 &ctx,
1500 tools::UNIFIED_EXEC,
1501 &serde_json::json!({"action": "wait", "session_id": "run-1"}),
1502 )
1503 .await;
1504 assert!(call.decision.is_allowed());
1505 }
1506 let third = gateway
1507 .check_and_record(&ctx, tools::UNIFIED_EXEC, &serde_json::json!({"action": "wait", "session_id": "run-1"}))
1508 .await;
1509 assert!(third.decision.is_denied(), "session fuse must bound control-plane calls");
1510 }
1511
1512 #[tokio::test]
1513 async fn start_turn_resets_control_plane_counter() {
1514 let config = SafetyGatewayConfig {
1515 max_per_turn: 1_000,
1516 enforce_rate_limits: false,
1517 ..Default::default()
1518 };
1519 let gateway = SafetyGateway::with_config(config);
1520 let ctx = make_ctx();
1521 let wait_args = serde_json::json!({"action": "wait", "session_id": "run-1"});
1522
1523 for _ in 0..MAX_CONTROL_PLANE_TOOL_CALLS_PER_TURN {
1524 assert!(
1525 gateway
1526 .check_and_record(&ctx, tools::UNIFIED_EXEC, &wait_args)
1527 .await
1528 .decision
1529 .is_allowed()
1530 );
1531 }
1532 assert!(
1533 gateway
1534 .check_and_record(&ctx, tools::UNIFIED_EXEC, &wait_args)
1535 .await
1536 .decision
1537 .is_denied()
1538 );
1539
1540 gateway.start_turn();
1541
1542 assert!(
1543 gateway
1544 .check_and_record(&ctx, tools::UNIFIED_EXEC, &wait_args)
1545 .await
1546 .decision
1547 .is_allowed(),
1548 "a fresh turn must refill the control-plane bucket"
1549 );
1550 }
1551}