Skip to main content

aidaemon_tools/fs/
guard.rs

1//! Secret and sensitive paths as a `before_tool` hook.
2
3use std::collections::HashMap;
4use std::path::{Path, PathBuf};
5use std::sync::Arc;
6
7use aidaemon_core::{Hook, HookContext, ToolCall, ToolDecision, ToolInfo};
8use async_trait::async_trait;
9
10use super::{FilePolicy, SharedBackend, workspace_parts};
11use crate::backend::BackendPath;
12use crate::semantics::FileGuard;
13use crate::workspace::Workspace;
14
15/// Refuses a call whose declared paths hold secrets or must not be changed.
16///
17/// Paths are resolved through the [`ExecutionBackend`] the tool uses, and
18/// symlinks are followed, so a link to a secret is judged as the secret.
19///
20/// [`ExecutionBackend`]: crate::backend::ExecutionBackend
21pub struct ProtectedPathGuard {
22    backend: SharedBackend,
23    policy: Arc<dyn FilePolicy>,
24    tools: HashMap<String, FileGuard>,
25}
26
27impl ProtectedPathGuard {
28    pub fn new(backend: SharedBackend, policy: Arc<dyn FilePolicy>) -> Self {
29        Self {
30            backend,
31            policy,
32            tools: HashMap::new(),
33        }
34    }
35
36    /// The guard for the bundled file tools confined to `workspace`.
37    pub fn for_workspace(workspace: Workspace) -> Self {
38        let (backend, policy) = workspace_parts(workspace);
39        Self::new(backend, policy)
40            .tool("read_file", FileGuard::Reads)
41            .tool("write_file", FileGuard::Writes)
42            .tool("edit_file", FileGuard::Writes)
43    }
44
45    /// State which of `tool`'s paths are judged.
46    pub fn tool(mut self, tool: impl Into<String>, guard: FileGuard) -> Self {
47        self.tools.insert(tool.into(), guard);
48        self
49    }
50
51    /// Why a call of `tool` over these paths is refused, if it is. A path
52    /// the backend cannot resolve is left to the tool to report.
53    pub async fn refusal(&self, tool: &str, reads: &[String], writes: &[String]) -> Option<String> {
54        match self.tools.get(tool).copied().unwrap_or_default() {
55            FileGuard::None => None,
56            FileGuard::Reads => {
57                for raw in reads {
58                    if self.resolved_any(raw, |path| self.holds_secret(path)).await {
59                        return Some(match self.hint(raw).await {
60                            Some(hint) => format!(
61                                "{tool} does not open credential or secret files ({raw}). {hint}"
62                            ),
63                            None => format!(
64                                "{tool} does not open credential or secret files ({raw}). Ask \
65                                 the owner to share what is needed."
66                            ),
67                        });
68                    }
69                }
70                None
71            }
72            FileGuard::SensitiveReads => {
73                for raw in reads {
74                    if self
75                        .resolved_any(raw, |path| self.policy.is_sensitive(path))
76                        .await
77                    {
78                        return Some(format!("{tool} cannot read sensitive path: {raw}"));
79                    }
80                }
81                None
82            }
83            FileGuard::Writes => {
84                for raw in writes {
85                    if self
86                        .resolved_any(raw, |path| self.policy.is_sensitive(path))
87                        .await
88                    {
89                        return Some(match self.hint(raw).await {
90                            Some(hint) => {
91                                format!("{tool} cannot change sensitive path: {raw}. {hint}")
92                            }
93                            None => format!("{tool} cannot change sensitive path: {raw}"),
94                        });
95                    }
96                }
97                None
98            }
99        }
100    }
101
102    /// The policy's pointer for a refused path, as named or as it really is.
103    async fn hint(&self, raw: &str) -> Option<String> {
104        let path = self.backend.resolve_path(raw).await.ok()?;
105        if let Some(hint) = self.policy.refusal_hint(Path::new(path.as_str())) {
106            return Some(hint);
107        }
108        let real = self.real_path(&path).await?;
109        self.policy.refusal_hint(&real)
110    }
111
112    /// `.env.example` style templates hold placeholders: they are judged by
113    /// where they live, not by their `.env.` name.
114    fn holds_secret(&self, path: &Path) -> bool {
115        if is_env_template(path) {
116            self.policy.is_secret_ignoring_name_shape(path)
117        } else {
118            self.policy.is_secret(path)
119        }
120    }
121
122    /// Whether `question` holds for the path as named or as it really is.
123    async fn resolved_any(&self, raw: &str, question: impl Fn(&Path) -> bool) -> bool {
124        let Ok(path) = self.backend.resolve_path(raw).await else {
125            return false;
126        };
127        question(Path::new(path.as_str()))
128            || self
129                .real_path(&path)
130                .await
131                .is_some_and(|real| question(&real))
132    }
133
134    /// `path` through its symlinks. A path that does not exist yet is taken
135    /// through its nearest existing ancestor.
136    async fn real_path(&self, path: &BackendPath) -> Option<PathBuf> {
137        let mut existing = path.clone();
138        let mut tail: Vec<String> = Vec::new();
139        loop {
140            if let Ok(real) = self.backend.canonicalize(&existing).await {
141                let mut resolved = PathBuf::from(real.as_str());
142                resolved.extend(tail.iter().rev());
143                return Some(resolved);
144            }
145            tail.push(existing.file_name()?.to_string());
146            existing = existing.parent()?;
147        }
148    }
149}
150
151fn is_env_template(path: &Path) -> bool {
152    path.file_name().is_some_and(|name| {
153        let name = name.to_string_lossy().to_ascii_lowercase();
154        matches!(
155            name.as_str(),
156            ".env.example" | ".env.sample" | ".env.template"
157        )
158    })
159}
160
161#[async_trait]
162impl Hook for ProtectedPathGuard {
163    async fn before_tool(
164        &self,
165        _ctx: &HookContext<'_>,
166        call: &ToolCall,
167        tool: &ToolInfo,
168    ) -> ToolDecision {
169        match self
170            .refusal(&call.name, &tool.access.reads, &tool.access.writes)
171            .await
172        {
173            Some(reason) => ToolDecision::Deny { reason },
174            None => ToolDecision::Allow,
175        }
176    }
177}