vtcode_agent_plugins/
expansion.rs1use std::path::{Path, PathBuf};
2
3pub fn expand_placeholders(value: &str, plugin_root: &Path, plugin_data: &Path) -> String {
11 let root = plugin_root.display().to_string();
12 let data = plugin_data.display().to_string();
13 let mut out = String::with_capacity(value.len() + root.len());
14 let mut idx = 0;
15 while idx < value.len() {
16 let Some(rest) = value.get(idx..) else {
17 break;
18 };
19 if rest.starts_with("${PLUGIN_ROOT}") {
20 out.push_str(&root);
21 idx += "${PLUGIN_ROOT}".len();
22 } else if rest.starts_with("${PLUGIN_DATA}") {
23 out.push_str(&data);
24 idx += "${PLUGIN_DATA}".len();
25 } else {
26 let ch = rest.chars().next().unwrap_or_default();
28 out.push(ch);
29 idx += ch.len_utf8();
30 }
31 }
32 out
33}
34
35pub fn is_reserved_env_key(key: &str) -> bool {
39 key == "PLUGIN_ROOT" || key == "PLUGIN_DATA"
43}
44
45const SHELL_CONTROL_CHARS: &[char] = &[';', '|', '&', '>', '<', '`', '\n', '\r', '\0'];
50
51fn contains_shell_control(value: &str) -> bool {
52 value.chars().any(|c| SHELL_CONTROL_CHARS.contains(&c))
53}
54
55pub fn validate_command_token(command: &str) -> Result<(), String> {
64 if command.is_empty() {
65 return Err("command must not be empty".into());
66 }
67 if command == "./" || command == "./." {
68 return Err("command must name an executable, not a directory".into());
69 }
70 if contains_shell_control(command) {
71 return Err("command must be a single executable token, not a shell string".into());
72 }
73 if command.starts_with("./") {
74 Ok(())
75 } else {
76 if command.contains('/') || command.contains('\\') {
77 return Err("command with a path separator must start with ./".into());
78 }
79 if command.chars().any(|c| c.is_whitespace()) {
80 return Err("command must be a single executable token, not a shell string".into());
81 }
82 Ok(())
83 }
84}
85
86pub fn validate_cwd_form(cwd: &str) -> Result<(), String> {
92 if cwd.starts_with("./")
93 || cwd == "${PLUGIN_ROOT}"
94 || cwd.starts_with("${PLUGIN_ROOT}/")
95 || cwd == "${PLUGIN_DATA}"
96 || cwd.starts_with("${PLUGIN_DATA}/")
97 {
98 Ok(())
99 } else {
100 Err(format!("cwd has unsupported form: {cwd}"))
101 }
102}
103
104pub fn default_plugin_data_dir(plugin_name: &str) -> PathBuf {
113 if let Ok(paths) = vtcode_commons::VtCodePaths::resolve() {
114 return paths.data_dir().join("plugin-data").join(plugin_name);
115 }
116 if let Some(data_dir) = dirs::data_dir() {
117 return data_dir.join("vtcode").join("plugin-data").join(plugin_name);
118 }
119 std::env::temp_dir().join("vtcode-plugin-data").join(plugin_name)
120}
121
122pub fn resolve_cwd(cwd: Option<&str>, plugin_root: &Path, plugin_data: &Path) -> Result<PathBuf, crate::PluginError> {
130 let canonical_root = vtcode_commons::canonicalize(plugin_root)
131 .map_err(|e| crate::PluginError::PathEscape(format!("plugin root could not be resolved: {e}")))?;
132 let canonical_data = canonicalize_allow_missing(plugin_data).unwrap_or_else(|_| plugin_data.to_path_buf());
135
136 let Some(raw) = cwd else {
137 return Ok(canonical_root);
138 };
139 validate_cwd_form(raw).map_err(crate::PluginError::PathEscape)?;
140
141 let expanded = expand_placeholders(raw, plugin_root, plugin_data);
142 if raw.starts_with("./") {
143 if expanded.starts_with("./") {
147 return validate_plugin_relative(&expanded, plugin_root);
148 }
149 let candidate = PathBuf::from(&expanded);
150 let resolved = ensure_within(&canonical_root, &candidate)
151 .map_err(|e| crate::PluginError::PathEscape(format!("cwd escapes plugin root: {e}")))?;
152 return Ok(resolved);
153 }
154 if raw == "${PLUGIN_ROOT}" || raw.starts_with("${PLUGIN_ROOT}/") {
155 let candidate = PathBuf::from(&expanded);
156 let resolved = ensure_within(&canonical_root, &candidate)
157 .map_err(|e| crate::PluginError::PathEscape(format!("cwd escapes plugin root: {e}")))?;
158 return Ok(resolved);
159 }
160 let candidate = PathBuf::from(&expanded);
162 let resolved = ensure_within(&canonical_data, &candidate)
163 .map_err(|e| crate::PluginError::PathEscape(format!("cwd escapes plugin data dir: {e}")))?;
164 Ok(resolved)
165}
166
167pub(crate) fn canonicalize_allow_missing(path: &Path) -> std::io::Result<PathBuf> {
168 let mut probe = path;
177 let mut suffix: Vec<std::ffi::OsString> = Vec::new();
178 loop {
179 if let Ok(existing) = vtcode_commons::canonicalize(probe) {
180 for part in suffix.iter().rev() {
181 if *part == ".." {
182 return Err(std::io::Error::new(
183 std::io::ErrorKind::InvalidInput,
184 format!("path escapes its root: {}", path.display()),
185 ));
186 }
187 }
188 let mut resolved = existing;
189 for part in suffix.iter().rev() {
190 resolved.push(part);
191 }
192 return Ok(resolved);
193 }
194 let Some(name) = probe.file_name() else {
195 return Err(std::io::Error::new(
196 std::io::ErrorKind::NotFound,
197 format!("path could not be resolved: {}", path.display()),
198 ));
199 };
200 suffix.push(name.to_os_string());
201 let Some(parent) = probe.parent() else {
202 return Err(std::io::Error::new(
203 std::io::ErrorKind::NotFound,
204 format!("path could not be resolved: {}", path.display()),
205 ));
206 };
207 probe = parent;
208 }
209}
210
211pub(crate) fn ensure_within(canonical_root: &Path, candidate: &Path) -> Result<PathBuf, String> {
212 let resolved = canonicalize_allow_missing(candidate).map_err(|e| format!("{} ({e})", candidate.display()))?;
213 if resolved.components().any(|c| matches!(c, std::path::Component::ParentDir)) {
216 return Err(format!("{} escapes {}", candidate.display(), canonical_root.display()));
217 }
218 if resolved.starts_with(canonical_root) {
219 Ok(resolved)
220 } else {
221 Err(format!("{} escapes {}", candidate.display(), canonical_root.display()))
222 }
223}
224
225pub fn validate_plugin_relative(value: &str, root: &Path) -> Result<PathBuf, crate::PluginError> {
237 if !value.starts_with("./") {
238 return Err(crate::PluginError::PathEscape(format!("path must start with ./: {}", value)));
239 }
240
241 let canonical_root = vtcode_commons::canonicalize(root)
242 .map_err(|e| crate::PluginError::PathEscape(format!("plugin root could not be resolved: {e}")))?;
243
244 let candidate = root.join(value.get(2..).unwrap_or_default());
245
246 let lexical_ok = candidate
248 .components()
249 .all(|component| !matches!(component, std::path::Component::ParentDir));
250 if !lexical_ok {
251 return Err(crate::PluginError::PathEscape(format!("path escapes plugin root: {}", value)));
252 }
253
254 let mut probe = candidate.as_path();
257 let mut suffix: Vec<PathBuf> = Vec::new();
258 loop {
259 match vtcode_commons::canonicalize(probe) {
260 Ok(existing) => {
261 let mut resolved = existing;
262 for part in suffix.iter().rev() {
263 resolved.push(part);
264 }
265 if !resolved.starts_with(&canonical_root) {
266 return Err(crate::PluginError::PathEscape(format!("path escapes plugin root: {}", value)));
267 }
268 return Ok(resolved);
269 }
270 Err(_) => {
271 let Some(name) = probe.file_name() else {
272 return Err(crate::PluginError::PathEscape(format!("path could not be resolved: {}", value)));
273 };
274 suffix.push(PathBuf::from(name));
275 let Some(parent) = probe.parent() else {
276 return Err(crate::PluginError::PathEscape(format!("path could not be resolved: {}", value)));
277 };
278 probe = parent;
279 }
280 }
281 }
282}
283
284#[cfg(test)]
285mod tests {
286 use super::*;
287
288 #[cfg(unix)]
289 #[test]
290 fn canonicalize_allow_missing_resolves_existing_path_on_first_walk_step() {
291 use std::os::unix::fs::symlink;
292
293 let temp = tempfile::tempdir().expect("tempdir");
294 let target = temp.path().join("target");
295 std::fs::create_dir(&target).expect("create target");
296 let link = temp.path().join("link");
297 symlink(&target, &link).expect("symlink");
298
299 assert_eq!(
302 canonicalize_allow_missing(&link).expect("canonicalize link"),
303 vtcode_commons::canonicalize(&target).expect("canonicalize target"),
304 );
305 }
306
307 #[test]
308 fn canonicalize_allow_missing_appends_missing_tail_to_canonical_parent() {
309 let temp = tempfile::tempdir().expect("tempdir");
310 let missing = temp.path().join("absent").join("child");
311 let canonical_temp = vtcode_commons::canonicalize(temp.path()).expect("canonicalize temp");
312
313 assert_eq!(
314 canonicalize_allow_missing(&missing).expect("canonicalize missing"),
315 canonical_temp.join("absent").join("child"),
316 );
317 }
318}