1use std::collections::VecDeque;
15use std::path::{Component, Path, PathBuf};
16use std::sync::Arc;
17
18use async_trait::async_trait;
19use regex::Regex;
20use serde_json::Value;
21
22use crate::{Guardrail, GuardrailResult, Severity};
23
24#[derive(Debug, Clone)]
26pub enum ToolGuardrailResult {
27 Allow,
29 Deny {
31 reason: String,
33 severity: Severity,
35 },
36 ReviseArgs {
41 args: Value,
43 reason: String,
45 },
46}
47
48impl ToolGuardrailResult {
49 pub fn deny(reason: impl Into<String>, severity: Severity) -> Self {
51 Self::Deny { reason: reason.into(), severity }
52 }
53
54 pub fn revise(args: Value, reason: impl Into<String>) -> Self {
56 Self::ReviseArgs { args, reason: reason.into() }
57 }
58
59 pub fn is_allowed(&self) -> bool {
61 !matches!(self, Self::Deny { .. })
62 }
63}
64
65#[derive(Debug, Clone)]
67pub enum ToolResultGuardrailResult {
68 Allow,
70 Withhold {
72 reason: String,
74 severity: Severity,
76 },
77 Revise {
79 result: Value,
81 reason: String,
83 },
84}
85
86impl ToolResultGuardrailResult {
87 pub fn withhold(reason: impl Into<String>, severity: Severity) -> Self {
89 Self::Withhold { reason: reason.into(), severity }
90 }
91
92 pub fn revise(result: Value, reason: impl Into<String>) -> Self {
94 Self::Revise { result, reason: reason.into() }
95 }
96}
97
98#[async_trait]
125pub trait ToolGuardrail: Send + Sync {
126 fn name(&self) -> &str;
128
129 async fn validate_call(&self, _tool_name: &str, _args: &Value) -> ToolGuardrailResult {
132 ToolGuardrailResult::Allow
133 }
134
135 async fn validate_result(
171 &self,
172 _tool_name: &str,
173 _args: &Value,
174 _result: &Value,
175 ) -> ToolResultGuardrailResult {
176 ToolResultGuardrailResult::Allow
177 }
178
179 fn applies_to(&self, _tool_name: &str) -> bool {
185 true
186 }
187}
188
189#[derive(Debug, Clone)]
191pub enum ToolCallDecision {
192 Allow {
194 args: Value,
196 },
197 Deny {
199 guardrail: String,
201 reason: String,
203 severity: Severity,
205 },
206}
207
208impl ToolCallDecision {
209 pub fn is_allowed(&self) -> bool {
211 matches!(self, Self::Allow { .. })
212 }
213}
214
215#[derive(Debug, Clone, PartialEq)]
217pub enum ToolResultDecision {
218 Deliver {
220 result: Value,
222 },
223 Withhold {
225 guardrail: String,
227 reason: String,
229 severity: Severity,
231 },
232}
233
234#[derive(Default)]
249pub struct ToolGuardrailSet {
250 guardrails: Vec<Arc<dyn ToolGuardrail>>,
251}
252
253impl ToolGuardrailSet {
254 pub fn new() -> Self {
256 Self { guardrails: Vec::new() }
257 }
258
259 pub fn with(mut self, guardrail: impl ToolGuardrail + 'static) -> Self {
261 self.guardrails.push(Arc::new(guardrail));
262 self
263 }
264
265 pub fn with_arc(mut self, guardrail: Arc<dyn ToolGuardrail>) -> Self {
267 self.guardrails.push(guardrail);
268 self
269 }
270
271 pub fn guardrails(&self) -> &[Arc<dyn ToolGuardrail>] {
273 &self.guardrails
274 }
275
276 pub fn is_empty(&self) -> bool {
278 self.guardrails.is_empty()
279 }
280
281 pub async fn evaluate(&self, tool_name: &str, args: &Value) -> ToolCallDecision {
289 let mut current = args.clone();
290
291 for guardrail in &self.guardrails {
292 if !guardrail.applies_to(tool_name) {
293 continue;
294 }
295
296 match guardrail.validate_call(tool_name, ¤t).await {
297 ToolGuardrailResult::Allow => {}
298 ToolGuardrailResult::Deny { reason, severity } => {
299 tracing::warn!(
302 guardrail = guardrail.name(),
303 tool = tool_name,
304 ?severity,
305 "tool call denied by guardrail"
306 );
307 return ToolCallDecision::Deny {
308 guardrail: guardrail.name().to_string(),
309 reason,
310 severity,
311 };
312 }
313 ToolGuardrailResult::ReviseArgs { args: revised, reason: _ } => {
314 tracing::debug!(
315 guardrail = guardrail.name(),
316 tool = tool_name,
317 "tool call arguments revised by guardrail"
318 );
319 current = revised;
320 }
321 }
322 }
323
324 ToolCallDecision::Allow { args: current }
325 }
326
327 pub async fn evaluate_result(
350 &self,
351 tool_name: &str,
352 args: &Value,
353 result: &Value,
354 ) -> ToolResultDecision {
355 let mut current = result.clone();
356
357 for guardrail in &self.guardrails {
358 if !guardrail.applies_to(tool_name) {
359 continue;
360 }
361
362 match guardrail.validate_result(tool_name, args, ¤t).await {
363 ToolResultGuardrailResult::Allow => {}
364 ToolResultGuardrailResult::Withhold { reason, severity } => {
365 tracing::warn!(
368 guardrail = guardrail.name(),
369 tool = tool_name,
370 ?severity,
371 "tool result withheld by guardrail"
372 );
373 return ToolResultDecision::Withhold {
374 guardrail: guardrail.name().to_string(),
375 reason,
376 severity,
377 };
378 }
379 ToolResultGuardrailResult::Revise { result: revised, reason: _ } => {
381 tracing::debug!(
382 guardrail = guardrail.name(),
383 tool = tool_name,
384 "tool result revised by guardrail"
385 );
386 current = revised;
387 }
388 }
389 }
390
391 ToolResultDecision::Deliver { result: current }
392 }
393}
394
395#[async_trait]
398impl adk_core::ToolResultScreen for ToolGuardrailSet {
399 async fn screen_result(
400 &self,
401 tool_name: &str,
402 args: &Value,
403 result: &Value,
404 ) -> std::result::Result<Value, String> {
405 match self.evaluate_result(tool_name, args, result).await {
406 ToolResultDecision::Deliver { result } => Ok(result),
407 ToolResultDecision::Withhold { guardrail, reason, severity } => {
408 Err(format!("tool guardrail '{guardrail}' ({severity:?}): {reason}"))
409 }
410 }
411 }
412}
413
414pub struct ResultTextGuardrail<G> {
437 guardrail: G,
438 tools: Option<Vec<String>>,
439}
440
441impl<G: Guardrail> ResultTextGuardrail<G> {
442 pub fn new(guardrail: G) -> Self {
444 Self { guardrail, tools: None }
445 }
446
447 pub fn on_tools<I, S>(mut self, tools: I) -> Self
449 where
450 I: IntoIterator<Item = S>,
451 S: Into<String>,
452 {
453 self.tools = Some(tools.into_iter().map(Into::into).collect());
454 self
455 }
456
457 async fn screen(&self, value: &mut Value) -> std::result::Result<bool, (String, Severity)> {
459 let mut changed = false;
460 let mut pending = vec![value];
461 while let Some(value) = pending.pop() {
462 match value {
463 Value::String(text) => {
464 let content = adk_core::Content::new("tool").with_text(text.as_str());
465 match self.guardrail.validate(&content).await {
466 GuardrailResult::Pass => {}
467 GuardrailResult::Fail { severity: Severity::Low, .. } => {
468 tracing::warn!(
469 guardrail.name = self.guardrail.name(),
470 "guardrail flagged a tool result at low severity; the result passes"
471 );
472 }
473 GuardrailResult::Fail { reason, severity } => {
474 return Err((reason, severity));
475 }
476 GuardrailResult::Transform { new_content, .. } => {
477 let screened: String =
478 new_content.parts.iter().filter_map(adk_core::Part::text).collect();
479 if screened != *text {
480 *text = screened;
481 changed = true;
482 }
483 }
484 }
485 }
486 Value::Array(items) => pending.extend(items.iter_mut()),
487 Value::Object(fields) => pending.extend(fields.values_mut()),
488 Value::Null | Value::Bool(_) | Value::Number(_) => {}
489 }
490 }
491 Ok(changed)
492 }
493}
494
495#[async_trait]
496impl<G: Guardrail> ToolGuardrail for ResultTextGuardrail<G> {
497 fn name(&self) -> &str {
498 self.guardrail.name()
499 }
500
501 fn applies_to(&self, tool_name: &str) -> bool {
502 match &self.tools {
503 Some(tools) => tools.iter().any(|t| t == tool_name),
504 None => true,
505 }
506 }
507
508 async fn validate_result(
509 &self,
510 _tool_name: &str,
511 _args: &Value,
512 result: &Value,
513 ) -> ToolResultGuardrailResult {
514 let mut screened = result.clone();
515 match self.screen(&mut screened).await {
516 Ok(false) => ToolResultGuardrailResult::Allow,
517 Ok(true) => ToolResultGuardrailResult::revise(
518 screened,
519 format!("{} rewrote the result's text", self.guardrail.name()),
520 ),
521 Err((reason, severity)) => ToolResultGuardrailResult::withhold(reason, severity),
522 }
523 }
524}
525
526pub struct DeniedArgumentPattern {
543 name: String,
544 pattern: Regex,
545 severity: Severity,
546 tools: Option<Vec<String>>,
547}
548
549impl DeniedArgumentPattern {
550 pub fn new(
556 name: impl Into<String>,
557 pattern: &str,
558 severity: Severity,
559 ) -> std::result::Result<Self, regex::Error> {
560 Ok(Self { name: name.into(), pattern: Regex::new(pattern)?, severity, tools: None })
561 }
562
563 pub fn on_tools<I, S>(mut self, tools: I) -> Self
565 where
566 I: IntoIterator<Item = S>,
567 S: Into<String>,
568 {
569 self.tools = Some(tools.into_iter().map(Into::into).collect());
570 self
571 }
572}
573
574#[async_trait]
575impl ToolGuardrail for DeniedArgumentPattern {
576 fn name(&self) -> &str {
577 &self.name
578 }
579
580 fn applies_to(&self, tool_name: &str) -> bool {
581 match &self.tools {
582 Some(tools) => tools.iter().any(|t| t == tool_name),
583 None => true,
584 }
585 }
586
587 async fn validate_call(&self, tool_name: &str, args: &Value) -> ToolGuardrailResult {
588 if self.pattern.is_match(&args.to_string()) {
589 return ToolGuardrailResult::deny(
590 format!(
591 "arguments to `{tool_name}` match the denied pattern `{}`",
592 self.pattern.as_str()
593 ),
594 self.severity,
595 );
596 }
597 ToolGuardrailResult::Allow
598 }
599}
600
601pub struct PathAllowList {
652 name: String,
653 arg_names: Vec<String>,
654 allowed_roots: Vec<PathBuf>,
655 severity: Severity,
656 tools: Option<Vec<String>>,
657 allow_missing: bool,
658}
659
660impl PathAllowList {
661 pub fn new<A, S, R, P>(name: impl Into<String>, arg_names: A, allowed_roots: R) -> Self
664 where
665 A: IntoIterator<Item = S>,
666 S: Into<String>,
667 R: IntoIterator<Item = P>,
668 P: Into<PathBuf>,
669 {
670 Self {
671 name: name.into(),
672 arg_names: arg_names.into_iter().map(Into::into).collect(),
673 allowed_roots: allowed_roots.into_iter().map(Into::into).collect(),
674 severity: Severity::Critical,
675 tools: None,
676 allow_missing: false,
677 }
678 }
679
680 pub fn with_severity(mut self, severity: Severity) -> Self {
682 self.severity = severity;
683 self
684 }
685
686 pub fn on_tools<I, S>(mut self, tools: I) -> Self
691 where
692 I: IntoIterator<Item = S>,
693 S: Into<String>,
694 {
695 self.tools = Some(tools.into_iter().map(Into::into).collect());
696 self
697 }
698
699 pub fn allow_missing(mut self) -> Self {
715 self.allow_missing = true;
716 self
717 }
718
719 fn is_permitted(&self, candidate: &str) -> bool {
721 let path = Path::new(candidate);
722
723 if !path.is_absolute() {
724 return false;
725 }
726
727 if path.components().any(|c| matches!(c, Component::ParentDir)) {
730 return false;
731 }
732
733 self.allowed_roots.iter().any(|root| {
734 if !root.is_absolute()
735 || root.components().any(|component| matches!(component, Component::ParentDir))
736 || !path.starts_with(root)
737 {
738 return false;
739 }
740
741 let Ok(canonical_root) = std::fs::canonicalize(root) else {
742 return false;
744 };
745
746 let Ok(relative) = path.strip_prefix(root) else {
747 return false;
748 };
749 let mut current = root.clone();
750 for component in relative.components() {
751 current.push(component);
752 match std::fs::symlink_metadata(¤t) {
753 Ok(_) => {
754 let Ok(canonical) = std::fs::canonicalize(¤t) else {
755 return false;
757 };
758 if !canonical.starts_with(&canonical_root) {
759 return false;
760 }
761 }
762 Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
763 break;
766 }
767 Err(_) => return false,
768 }
769 }
770
771 true
772 })
773 }
774}
775
776#[async_trait]
777impl ToolGuardrail for PathAllowList {
778 fn name(&self) -> &str {
779 &self.name
780 }
781
782 fn applies_to(&self, tool_name: &str) -> bool {
783 match &self.tools {
784 Some(tools) => tools.iter().any(|t| t == tool_name),
785 None => true,
786 }
787 }
788
789 async fn validate_call(&self, tool_name: &str, args: &Value) -> ToolGuardrailResult {
790 let deny = |reason: String| ToolGuardrailResult::deny(reason, self.severity);
791 let mut found = vec![0_usize; self.arg_names.len()];
793 let mut pending = VecDeque::from([(String::new(), args)]);
797
798 while let Some((pointer, value)) = pending.pop_front() {
799 match value {
800 Value::Object(map) => {
801 for (key, child) in map {
802 let at = format!("{pointer}/{}", key.replace('~', "~0").replace('/', "~1"));
803 let Some(index) = self.arg_names.iter().position(|name| name == key) else {
804 pending.push_back((at, child));
805 continue;
806 };
807 let candidates: Vec<(String, &Value)> = match child {
808 Value::Array(items) => items
809 .iter()
810 .enumerate()
811 .map(|(position, item)| (format!("{at}/{position}"), item))
812 .collect(),
813 Value::Null
814 | Value::Bool(_)
815 | Value::Number(_)
816 | Value::String(_)
817 | Value::Object(_) => vec![(at, child)],
818 };
819 for (at, candidate) in candidates {
820 let kind = match candidate {
821 Value::String(path) => {
822 if !self.is_permitted(path) {
823 let roots: Vec<_> = self
824 .allowed_roots
825 .iter()
826 .map(|root| root.display().to_string())
827 .collect();
828 return deny(format!(
829 "argument `{key}` of `{tool_name}` at `{at}` is \
830 {path:?}, which is not an absolute path inside an \
831 allowed root ({})",
832 roots.join(", ")
833 ));
834 }
835 found[index] += 1;
836 continue;
837 }
838 Value::Array(_) => "an array".to_string(),
839 Value::Object(_) => "an object".to_string(),
840 Value::Null | Value::Bool(_) | Value::Number(_) => {
841 candidate.to_string()
842 }
843 };
844 return deny(format!(
845 "argument `{key}` of `{tool_name}` at `{at}` must be a path string \
846 or an array of path strings, got {kind}"
847 ));
848 }
849 }
850 }
851 Value::Array(items) => {
852 for (position, item) in items.iter().enumerate() {
853 pending.push_back((format!("{pointer}/{position}"), item));
854 }
855 }
856 Value::Null | Value::Bool(_) | Value::Number(_) | Value::String(_) => {}
857 }
858 }
859
860 if !self.allow_missing
861 && let Some((arg_name, _)) =
862 self.arg_names.iter().zip(&found).find(|(_, count)| **count == 0)
863 {
864 return deny(format!(
865 "argument `{arg_name}` of `{tool_name}` holds no path at any depth, so it cannot \
866 be checked; configure the guardrail with allow_missing() to permit calls without \
867 it"
868 ));
869 }
870
871 ToolGuardrailResult::Allow
872 }
873}
874
875#[cfg(test)]
876mod tests {
877 use super::*;
878 use crate::{ContentFilter, PiiRedactor};
879 use adk_core::ToolResultScreen;
880 use serde_json::json;
881
882 #[tokio::test]
883 async fn result_text_guardrail_redacts_every_string_and_keeps_the_shape() {
884 let guardrails = ToolGuardrailSet::new().with(ResultTextGuardrail::new(PiiRedactor::new()));
885 let result = json!({
886 "order": 42,
887 "customer": {"email": "jane@example.com", "notes": ["ssn 123-45-6789", true]},
888 });
889 assert_eq!(
890 guardrails.evaluate_result("lookup", &json!({}), &result).await,
891 ToolResultDecision::Deliver {
892 result: json!({
893 "order": 42,
894 "customer": {"email": "[EMAIL REDACTED]", "notes": ["ssn [SSN REDACTED]", true]},
895 }),
896 }
897 );
898 }
899
900 #[tokio::test]
901 async fn a_failing_text_check_withholds_the_result() {
902 let filter = ContentFilter::blocked_keywords(vec!["internal only".into()]).unwrap();
903 let guardrails = ToolGuardrailSet::new().with(ResultTextGuardrail::new(filter));
904 let decision = guardrails
905 .evaluate_result("wiki", &json!({}), &json!({"page": ["INTERNAL ONLY: roadmap"]}))
906 .await;
907 assert!(matches!(
908 decision,
909 ToolResultDecision::Withhold { ref guardrail, severity: Severity::High, .. }
910 if guardrail == "blocked_keywords"
911 ));
912 let screened =
913 guardrails.screen_result("wiki", &json!({}), &json!({"page": "internal only"})).await;
914 assert!(screened.unwrap_err().starts_with("tool guardrail 'blocked_keywords' (High)"));
915 }
916
917 #[tokio::test]
918 async fn result_guardrails_are_scoped_and_compose() {
919 let guardrails = ToolGuardrailSet::new()
920 .with(ResultTextGuardrail::new(PiiRedactor::new()).on_tools(["lookup"]))
921 .with(ResultTextGuardrail::new(
922 ContentFilter::blocked_keywords(vec!["redacted".into()]).unwrap(),
923 ));
924 let other =
925 guardrails.evaluate_result("search", &json!({}), &json!("mail jane@example.com")).await;
926 assert_eq!(other, ToolResultDecision::Deliver { result: json!("mail jane@example.com") });
927 let lookup =
929 guardrails.evaluate_result("lookup", &json!({}), &json!("mail jane@example.com")).await;
930 assert!(matches!(lookup, ToolResultDecision::Withhold { .. }));
931 }
932
933 #[tokio::test]
934 async fn call_guardrails_deliver_results_unchanged() {
935 let guardrails = ToolGuardrailSet::new().with(ForceDryRun);
936 let result = json!({"ok": true});
937 assert_eq!(
938 guardrails.evaluate_result("run", &json!({}), &result).await,
939 ToolResultDecision::Deliver { result }
940 );
941 }
942
943 struct ForceDryRun;
945
946 #[async_trait]
947 impl ToolGuardrail for ForceDryRun {
948 fn name(&self) -> &str {
949 "force-dry-run"
950 }
951 async fn validate_call(&self, _tool: &str, args: &Value) -> ToolGuardrailResult {
952 let mut revised = args.clone();
953 if let Some(object) = revised.as_object_mut() {
954 object.insert("dry_run".to_string(), json!(true));
955 }
956 ToolGuardrailResult::revise(revised, "dry-run is mandatory here")
957 }
958 }
959
960 struct DenyAll;
961
962 #[async_trait]
963 impl ToolGuardrail for DenyAll {
964 fn name(&self) -> &str {
965 "deny-all"
966 }
967 async fn validate_call(&self, _tool: &str, _args: &Value) -> ToolGuardrailResult {
968 ToolGuardrailResult::deny("nothing is permitted", Severity::Critical)
969 }
970 }
971
972 #[tokio::test]
973 async fn an_empty_set_allows_the_call_unchanged() {
974 let decision = ToolGuardrailSet::new().evaluate("any", &json!({ "a": 1 })).await;
975
976 match decision {
977 ToolCallDecision::Allow { args } => assert_eq!(args, json!({ "a": 1 })),
978 other => panic!("expected Allow, got {other:?}"),
979 }
980 }
981
982 #[tokio::test]
983 async fn a_revision_is_returned_to_the_caller() {
984 let set = ToolGuardrailSet::new().with(ForceDryRun);
985
986 match set.evaluate("delete", &json!({ "path": "/tmp/x" })).await {
987 ToolCallDecision::Allow { args } => {
988 assert_eq!(args, json!({ "path": "/tmp/x", "dry_run": true }));
989 }
990 other => panic!("expected Allow, got {other:?}"),
991 }
992 }
993
994 #[tokio::test]
995 async fn a_denial_names_the_guardrail_that_refused() {
996 let set = ToolGuardrailSet::new().with(DenyAll);
997
998 match set.evaluate("delete", &json!({})).await {
999 ToolCallDecision::Deny { guardrail, severity, .. } => {
1000 assert_eq!(guardrail, "deny-all");
1001 assert_eq!(severity, Severity::Critical);
1002 }
1003 other => panic!("expected Deny, got {other:?}"),
1004 }
1005 }
1006
1007 #[tokio::test]
1008 async fn a_denial_stops_evaluation_so_a_denied_call_is_never_revised() {
1009 let set = ToolGuardrailSet::new().with(DenyAll).with(ForceDryRun);
1010
1011 assert!(!set.evaluate("delete", &json!({})).await.is_allowed());
1012 }
1013
1014 #[tokio::test]
1015 async fn a_later_guardrail_sees_an_earlier_revision() {
1016 struct RequireDryRun;
1018
1019 #[async_trait]
1020 impl ToolGuardrail for RequireDryRun {
1021 fn name(&self) -> &str {
1022 "require-dry-run"
1023 }
1024 async fn validate_call(&self, _tool: &str, args: &Value) -> ToolGuardrailResult {
1025 if args.get("dry_run") == Some(&json!(true)) {
1026 ToolGuardrailResult::Allow
1027 } else {
1028 ToolGuardrailResult::deny("dry_run was not set", Severity::High)
1029 }
1030 }
1031 }
1032
1033 let set = ToolGuardrailSet::new().with(ForceDryRun).with(RequireDryRun);
1034 assert!(
1035 set.evaluate("delete", &json!({})).await.is_allowed(),
1036 "revisions must compose in order"
1037 );
1038
1039 let reversed = ToolGuardrailSet::new().with(RequireDryRun).with(ForceDryRun);
1040 assert!(
1041 !reversed.evaluate("delete", &json!({})).await.is_allowed(),
1042 "order is meaningful and must not be silently reordered"
1043 );
1044 }
1045
1046 #[tokio::test]
1047 async fn applies_to_skips_an_unrelated_tool() {
1048 let set = ToolGuardrailSet::new().with(
1049 DeniedArgumentPattern::new("no-rf", r"-rf", Severity::Critical)
1050 .expect("valid pattern")
1051 .on_tools(["run_command"]),
1052 );
1053
1054 assert!(set.evaluate("read_file", &json!({ "flags": "-rf" })).await.is_allowed());
1055 assert!(!set.evaluate("run_command", &json!({ "flags": "-rf" })).await.is_allowed());
1056 }
1057
1058 #[tokio::test]
1059 async fn a_denied_pattern_matches_anywhere_in_the_arguments() {
1060 let guardrail = DeniedArgumentPattern::new("no-rf", r"-rf\b", Severity::Critical)
1061 .expect("valid pattern");
1062
1063 for args in [
1064 json!({ "cmd": "rm -rf /" }),
1065 json!({ "nested": { "cmd": "rm -rf ." } }),
1066 json!({ "argv": ["rm", "-rf", "/tmp"] }),
1067 ] {
1068 assert!(
1069 !guardrail.validate_call("run_command", &args).await.is_allowed(),
1070 "should deny {args}"
1071 );
1072 }
1073
1074 assert!(
1075 guardrail.validate_call("run_command", &json!({ "cmd": "ls -l" })).await.is_allowed()
1076 );
1077 }
1078
1079 #[test]
1080 fn an_invalid_pattern_is_reported() {
1081 assert!(DeniedArgumentPattern::new("bad", "([unclosed", Severity::Low).is_err());
1082 }
1083
1084 #[tokio::test]
1085 async fn a_path_inside_an_allowed_root_is_permitted() {
1086 let root = tempfile::tempdir().expect("allowed root");
1087 let guardrail = PathAllowList::new("agents", ["path"], [root.path()]);
1088 let candidate = root.path().join("x.plist");
1089
1090 assert!(
1091 guardrail
1092 .validate_call("plist_write", &json!({ "path": candidate }))
1093 .await
1094 .is_allowed()
1095 );
1096 }
1097
1098 #[tokio::test]
1099 async fn traversal_and_escape_attempts_are_denied() {
1100 let guardrail = PathAllowList::new("agents", ["path"], ["/Users/me/Library/LaunchAgents"]);
1101
1102 for candidate in [
1103 "/Users/me/Library/LaunchAgents/../../../etc/passwd",
1104 "/etc/passwd",
1105 "relative/path.plist",
1106 "/Users/me/Library/LaunchAgentsEvil/x.plist",
1107 ] {
1108 assert!(
1109 !guardrail
1110 .validate_call("plist_write", &json!({ "path": candidate }))
1111 .await
1112 .is_allowed(),
1113 "should deny {candidate:?}"
1114 );
1115 }
1116 }
1117
1118 #[tokio::test]
1119 async fn a_sibling_root_is_not_admitted_by_string_prefix() {
1120 let guardrail = PathAllowList::new("etc", ["path"], ["/etc/passwd"]);
1122
1123 assert!(
1124 !guardrail
1125 .validate_call("read", &json!({ "path": "/etc/passwd-backup" }))
1126 .await
1127 .is_allowed()
1128 );
1129 }
1130
1131 #[tokio::test]
1132 async fn a_non_string_path_argument_is_denied() {
1133 let guardrail = PathAllowList::new("agents", ["path"], ["/tmp"]);
1134
1135 assert!(
1136 !guardrail.validate_call("write", &json!({ "path": 42 })).await.is_allowed(),
1137 "a non-string path cannot be checked and must not be waved through"
1138 );
1139 }
1140
1141 #[cfg(unix)]
1142 #[tokio::test]
1143 async fn a_symlink_inside_the_root_cannot_escape_it() {
1144 let root = tempfile::tempdir().expect("allowed root");
1145 let outside = tempfile::tempdir().expect("outside root");
1146 std::os::unix::fs::symlink(outside.path(), root.path().join("escape"))
1147 .expect("create symlink");
1148 let guardrail = PathAllowList::new("root", ["path"], [root.path()]);
1149 let candidate = root.path().join("escape/secret.txt");
1150
1151 assert!(
1152 !guardrail.validate_call("write", &json!({ "path": candidate })).await.is_allowed(),
1153 "a lexical child resolving outside the allowed root must be denied"
1154 );
1155 }
1156
1157 #[cfg(unix)]
1158 #[tokio::test]
1159 async fn a_dangling_symlink_inside_the_root_is_denied() {
1160 let root = tempfile::tempdir().expect("allowed root");
1161 let outside = tempfile::tempdir().expect("outside root");
1162 let missing_target = outside.path().join("not-created");
1163 std::os::unix::fs::symlink(&missing_target, root.path().join("escape"))
1164 .expect("create dangling symlink");
1165 let guardrail = PathAllowList::new("root", ["path"], [root.path()]);
1166
1167 assert!(
1168 !guardrail
1169 .validate_call("write", &json!({ "path": root.path().join("escape/secret.txt") }))
1170 .await
1171 .is_allowed()
1172 );
1173 }
1174
1175 #[tokio::test]
1176 async fn an_unresolvable_allowed_root_is_fail_closed() {
1177 let root = tempfile::tempdir().expect("root");
1178 let missing = root.path().join("not-created");
1179 let guardrail = PathAllowList::new("missing", ["path"], [&missing]);
1180
1181 assert!(
1182 !guardrail
1183 .validate_call("write", &json!({ "path": missing.join("file.txt") }))
1184 .await
1185 .is_allowed()
1186 );
1187 }
1188
1189 #[tokio::test]
1190 async fn an_absent_path_argument_is_denied() {
1191 let guardrail = PathAllowList::new("agents", ["path"], ["/tmp"]);
1192
1193 for args in [json!({ "other": 1 }), json!({ "Path": "/etc/passwd" }), json!("/etc/passwd")]
1194 {
1195 assert!(
1196 !guardrail.validate_call("write", &args).await.is_allowed(),
1197 "a call without `path` cannot be shown to stay inside the roots: {args}"
1198 );
1199 }
1200 }
1201
1202 #[tokio::test]
1203 async fn allow_missing_permits_an_absent_argument_but_checks_a_present_one() {
1204 let root = tempfile::tempdir().expect("allowed root");
1205 let guardrail =
1206 PathAllowList::new("moves", ["source", "destination"], [root.path()]).allow_missing();
1207 let inside = root.path().join("a.txt");
1208
1209 assert!(guardrail.validate_call("rm", &json!({ "source": inside })).await.is_allowed());
1210 assert!(
1211 !guardrail
1212 .validate_call("mv", &json!({ "source": inside, "destination": "/etc/x" }))
1213 .await
1214 .is_allowed()
1215 );
1216 }
1217
1218 #[tokio::test]
1219 async fn a_nested_path_outside_the_roots_is_denied() {
1220 let root = tempfile::tempdir().expect("allowed root");
1221 let inside = root.path().join("notes.txt");
1222 let strict = PathAllowList::new("root", ["path"], [root.path()]);
1223 let lenient = PathAllowList::new("root", ["path"], [root.path()]).allow_missing();
1224
1225 for args in [
1226 json!({ "config": { "path": "/etc/shadow" } }),
1227 json!({ "request": { "target": { "path": "/etc/shadow" } } }),
1228 ] {
1229 assert!(!strict.validate_call("read", &args).await.is_allowed(), "should deny {args}");
1230 assert!(!lenient.validate_call("read", &args).await.is_allowed(), "should deny {args}");
1231 }
1232 let beside_a_permitted_one = json!({ "path": inside, "backup": { "path": "/etc/shadow" } });
1233 assert!(
1234 !strict.validate_call("read", &beside_a_permitted_one).await.is_allowed(),
1235 "a permitted top-level path must not vouch for a nested one"
1236 );
1237 }
1238
1239 #[tokio::test]
1240 async fn an_array_held_path_outside_the_roots_is_denied() {
1241 let root = tempfile::tempdir().expect("allowed root");
1242 let inside = root.path().join("notes.txt");
1243 let guardrail = PathAllowList::new("root", ["path"], [root.path()]).allow_missing();
1244
1245 for args in [
1246 json!({ "files": [{ "path": inside }, { "path": "/etc/shadow" }] }),
1247 json!({ "batches": [[{ "path": "/etc/shadow" }]] }),
1248 json!({ "path": [inside, "/etc/shadow"] }),
1249 ] {
1250 assert!(
1251 !guardrail.validate_call("read", &args).await.is_allowed(),
1252 "should deny {args}"
1253 );
1254 }
1255 }
1256
1257 #[tokio::test]
1258 async fn a_nested_path_inside_the_roots_is_permitted() {
1259 let root = tempfile::tempdir().expect("allowed root");
1260 let first = root.path().join("a.txt");
1261 let second = root.path().join("b.txt");
1262 let guardrail = PathAllowList::new("root", ["path"], [root.path()]);
1264
1265 for args in [
1266 json!({ "source": { "path": first } }),
1267 json!({ "files": [{ "path": first }, { "path": second }] }),
1268 json!({ "path": [first, second] }),
1269 json!({ "path": first, "backup": { "path": second } }),
1270 ] {
1271 assert!(
1272 guardrail.validate_call("read", &args).await.is_allowed(),
1273 "should allow {args}"
1274 );
1275 }
1276 }
1277
1278 #[tokio::test]
1279 async fn a_value_under_the_name_that_is_not_a_path_is_denied_at_any_depth() {
1280 let root = tempfile::tempdir().expect("allowed root");
1281 let inside = root.path().join("a.txt");
1282 let guardrail = PathAllowList::new("root", ["path"], [root.path()]).allow_missing();
1283
1284 for args in [
1285 json!({ "config": { "path": 42 } }),
1286 json!({ "config": { "path": null } }),
1287 json!({ "config": { "path": { "dir": inside } } }),
1288 json!({ "items": [{ "path": true }] }),
1289 json!({ "path": [inside, 7] }),
1290 json!({ "path": [[inside]] }),
1291 ] {
1292 assert!(
1293 !guardrail.validate_call("read", &args).await.is_allowed(),
1294 "a value that is not a path string cannot be checked: {args}"
1295 );
1296 }
1297 }
1298
1299 #[tokio::test]
1300 async fn an_empty_path_array_holds_no_path() {
1301 let root = tempfile::tempdir().expect("allowed root");
1302 let args = json!({ "options": { "path": [] } });
1303
1304 assert!(
1305 !PathAllowList::new("root", ["path"], [root.path()])
1306 .validate_call("read", &args)
1307 .await
1308 .is_allowed(),
1309 "an empty array shows no path, so it is denied as missing"
1310 );
1311 assert!(
1312 PathAllowList::new("root", ["path"], [root.path()])
1313 .allow_missing()
1314 .validate_call("read", &args)
1315 .await
1316 .is_allowed()
1317 );
1318 }
1319
1320 #[tokio::test]
1321 async fn a_denial_names_where_the_path_was_found() {
1322 let root = tempfile::tempdir().expect("allowed root");
1323 let guardrail = PathAllowList::new("root", ["path"], [root.path()]).allow_missing();
1324
1325 let decision =
1326 guardrail.validate_call("read", &json!({ "a/b": [{ "path": "/etc/shadow" }] })).await;
1327
1328 match decision {
1329 ToolGuardrailResult::Deny { reason, severity } => {
1330 assert_eq!(severity, Severity::Critical);
1331 assert!(reason.contains("at `/a~1b/0/path`"), "got {reason}");
1332 assert!(reason.contains("not an absolute path inside an allowed root"), "{reason}");
1333 }
1334 other => panic!("expected Deny, got {other:?}"),
1335 }
1336 }
1337
1338 #[tokio::test]
1339 async fn a_tool_outside_on_tools_is_not_checked() {
1340 let set = ToolGuardrailSet::new()
1341 .with(PathAllowList::new("writes", ["path"], ["/srv"]).on_tools(["write_file"]));
1342
1343 assert!(set.evaluate("read_file", &json!({ "path": "/etc/passwd" })).await.is_allowed());
1344 assert!(!set.evaluate("write_file", &json!({ "path": "/etc/passwd" })).await.is_allowed());
1345 assert!(!set.evaluate("write_file", &json!({})).await.is_allowed());
1346 }
1347}