返回 CodeWhale
dsh_workspace.rs
根目录 / crates / engine / src / extension_host / dsh_workspace.rs
1 use std::path::{Path, PathBuf};
2
3 use codewhale_workflow_js::ToolCallResponse;
4 use serde::Deserialize;
5 use serde_json::{Value, json};
6
7 use super::dsh_broker::{BrokerCall, BrokerFuture, BrokerMethods, BrokerRefusal, decode};
8 use super::protocol::DshService;
9 use crate::tools::execution_envelope::enforce_tool_denial;
10 use crate::tools::spec::{
11 ToolContext, has_forbidden_windows_colon, has_windows_drive_or_unc_prefix,
12 is_protected_workspace_metadata_segment, resolve_strict_authority_path,
13 strip_workspace_root_str, validate_windows_relative_segments,
14 };
15
16 const MAX_PATH_BYTES: usize = 512;
17 const MAX_WRITE_BYTES: usize = 1024 * 1024;
18 const MAX_READ_LINES: u64 = 10_000;
19 const MAX_ARGS: usize = 8;
20 const MAX_ARG_BYTES: usize = 1024;
21 const LOG: &str = "codewhale::dsh_workspace";
22
23 static CONFINE_GATE: tokio::sync::Semaphore = tokio::sync::Semaphore::const_new(4);
24
25 #[derive(Deserialize)]
26 #[serde(tag = "method", content = "input", deny_unknown_fields)]
27 enum WorkspaceMethod {
28 #[serde(rename = "read")]
29 Read(ReadInput),
30 #[serde(rename = "list")]
31 List(ListInput),
32 #[serde(rename = "write")]
33 Write(WriteInput),
34 #[serde(rename = "exec")]
35 Exec(ExecInput),
36 }
37
38 impl BrokerMethods for WorkspaceMethod {
39 const NAMES: &'static [&'static str] = &["read", "list", "write", "exec"];
40 }
41
42 #[derive(Deserialize)]
43 #[serde(deny_unknown_fields)]
44 struct ReadInput {
45 path: String,
46 #[serde(default)]
47 start_line: Option<u64>,
48 #[serde(default)]
49 max_lines: Option<u64>,
50 }
51
52 #[derive(Deserialize)]
53 #[serde(deny_unknown_fields)]
54 struct ListInput {
55 #[serde(default)]
56 path: Option<String>,
57 }
58
59 #[derive(Deserialize)]
60 #[serde(deny_unknown_fields)]
61 struct WriteInput {
62 path: String,
63 content: String,
64 #[serde(default)]
65 expected_hash: Option<String>,
66 }
67
68 #[derive(Deserialize)]
69 #[serde(deny_unknown_fields)]
70 struct ExecInput {
71 argv: Vec<String>,
72 #[serde(default)]
73 cwd: Option<String>,
74 }
75
76 #[derive(Clone, Copy, PartialEq, Eq)]
77 enum Access {
78 Read,
79 Overlay,
80 }
81
82 pub(super) fn serve(call: BrokerCall) -> BrokerFuture {
83 Box::pin(async move {
84 let method = decode::<WorkspaceMethod>(&call)?;
85 if call.context.cancel().is_cancelled() {
86 return Err(refused("the workspace call was withdrawn"));
87 }
88 match method {
89 WorkspaceMethod::Read(ReadInput {
90 path,
91 start_line,
92 max_lines,
93 }) => {
94 if start_line == Some(0) {
95 return Err(invalid("start_line starts at 1"));
96 }
97 if max_lines.is_some_and(|lines| !(1..=MAX_READ_LINES).contains(&lines)) {
98 return Err(invalid(format!(
99 "max_lines is between 1 and {MAX_READ_LINES}"
100 )));
101 }
102 let tool = caller(&call, "read_file", &json!({}))?;
103 let (shown, resolved) = confine(&call, &tool, &path, Access::Read).await?;
104 let mut input = json!({ "path": resolved });
105 if let Some(start_line) = start_line {
106 input["start_line"] = json!(start_line);
107 }
108 if let Some(max_lines) = max_lines {
109 input["max_lines"] = json!(max_lines);
110 }
111 nested(&call, "read_file", input)
112 .await
113 .map(|response| file_outcome(&shown, response))
114 }
115 WorkspaceMethod::List(ListInput { path }) => {
116 let tool = caller(&call, "list_dir", &json!({}))?;
117 let raw = path.as_deref().unwrap_or(".");
118 let (shown, resolved) = confine(&call, &tool, raw, Access::Read).await?;
119 nested(&call, "list_dir", json!({ "path": resolved }))
120 .await
121 .map(|response| file_outcome(&shown, response))
122 }
123 WorkspaceMethod::Write(WriteInput {
124 path,
125 content,
126 expected_hash,
127 }) => {
128 if content.len() > MAX_WRITE_BYTES {
129 return Err(invalid(format!(
130 "a write is at most {MAX_WRITE_BYTES} bytes"
131 )));
132 }
133 if expected_hash
134 .as_deref()
135 .is_some_and(|hash| hash.is_empty() || hash.len() > 128)
136 {
137 return Err(invalid("expected_hash is 1 to 128 characters"));
138 }
139 if !overlay_granted() {
140 tracing::info!(target: LOG, plugin = %call.owner.plugin_id, "workspace write refused: no reviewed overlay grant");
141 return Err(refused("this plugin may not write to the workspace"));
142 }
143 let tool = caller(&call, "write_file", &json!({}))?;
144 let (shown, resolved) = confine(&call, &tool, &path, Access::Overlay).await?;
145 let mut input = json!({ "path": resolved, "content": content });
146 if let Some(expected_hash) = expected_hash {
147 input["expected_hash"] = json!(expected_hash);
148 }
149 nested(&call, "write_file", input)
150 .await
151 .map(|response| file_outcome(&shown, response))
152 }
153 WorkspaceMethod::Exec(ExecInput { argv, cwd }) => {
154 let mut input = literal_git(&argv)?;
155 input["action"] = json!("review_scope");
156 let tool = caller(&call, "Git", &input)?;
157 if let Some(cwd) = cwd.as_deref() {
158 let (shown, _) = confine(&call, &tool, cwd, Access::Read).await?;
159 if shown != "." {
160 tracing::info!(target: LOG, plugin = %call.owner.plugin_id, "workspace exec refused: cwd is not the workspace root");
161 return Err(refused("git runs only at the workspace root"));
162 }
163 }
164 nested(&call, "Git", input).await.map(exec_outcome)
165 }
166 }
167 })
168 }
169
170 fn invalid(message: impl Into<String>) -> BrokerRefusal {
171 BrokerRefusal::InvalidInput {
172 service: DshService::Workspace,
173 message: message.into(),
174 }
175 }
176
177 fn refused(message: &str) -> BrokerRefusal {
178 BrokerRefusal::Refused {
179 service: DshService::Workspace,
180 message: message.to_string(),
181 }
182 }
183
184 #[cfg(test)]
185 thread_local! {
186 static TEST_OVERLAY: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
187 }
188
189 #[cfg(test)]
190 pub(super) struct TestOverlay(bool);
191
192 #[cfg(test)]
193 impl TestOverlay {
194 pub(super) fn granted() -> Self {
195 Self(TEST_OVERLAY.with(|overlay| overlay.replace(true)))
196 }
197 }
198
199 #[cfg(test)]
200 impl Drop for TestOverlay {
201 fn drop(&mut self) {
202 TEST_OVERLAY.with(|overlay| overlay.set(self.0));
203 }
204 }
205
206 fn overlay_granted() -> bool {
207 #[cfg(test)]
208 {
209 TEST_OVERLAY.with(std::cell::Cell::get)
210 }
211 #[cfg(not(test))]
212 {
213 false
214 }
215 }
216
217 fn caller(
218 call: &BrokerCall,
219 tool_name: &'static str,
220 input: &Value,
221 ) -> Result<ToolContext, BrokerRefusal> {
222 let mut tool = call.context.tool().clone();
223 let _ = tool.refresh_live_posture();
224 if enforce_tool_denial(&tool, tool_name, input).is_err() {
225 tracing::info!(target: LOG, plugin = %call.owner.plugin_id, tool = tool_name, "workspace refused: the caller may not use this tool");
226 return Err(refused(
227 "this workspace call is not available to this caller",
228 ));
229 }
230 Ok(tool)
231 }
232
233 fn relative_for(workspace: &Path, canonical: &Path, raw: &str, windows: bool) -> Option<String> {
234 let path = Path::new(raw);
235 let is_absolute = path.is_absolute()
236 || raw.starts_with('/')
237 || (windows && (raw.starts_with('\\') || has_windows_drive_or_unc_prefix(raw)));
238 if !is_absolute {
239 return Some(raw.to_string());
240 }
241 let ws_str = workspace.to_str()?;
242 let canonical_str = canonical.to_str();
243 strip_workspace_root_str(ws_str, canonical_str, raw, windows)
244 }
245
246 fn shape(raw: &str) -> Result<(), BrokerRefusal> {
247 if raw.is_empty()
248 || raw.len() > MAX_PATH_BYTES
249 || raw.trim() != raw
250 || raw.chars().any(char::is_control)
251 {
252 return Err(invalid(format!(
253 "a path is 1 to {MAX_PATH_BYTES} bytes on one line with no surrounding spaces"
254 )));
255 }
256 Ok(())
257 }
258
259 fn protected_for(relative: &str, windows: bool) -> bool {
260 relative
261 .replace('\\', "/")
262 .split('/')
263 .any(|segment| is_protected_workspace_metadata_segment(segment, windows))
264 }
265
266 fn resolve(tool: &ToolContext, raw: &str, access: Access) -> Result<(String, PathBuf), String> {
267 resolve_for(tool, raw, access, cfg!(windows))
268 }
269
270 fn resolve_for(
271 tool: &ToolContext,
272 raw: &str,
273 access: Access,
274 windows: bool,
275 ) -> Result<(String, PathBuf), String> {
276 if has_forbidden_windows_colon(raw, windows) {
277 return Err("windows colons and alternate data streams are not allowed".to_string());
278 }
279 let root = tool.workspace.canonicalize().map_err(|e| e.to_string())?;
280 let relative =
281 relative_for(&tool.workspace, &root, raw, windows).ok_or_else(|| "outside".to_string())?;
282 validate_windows_relative_segments(&relative, windows)?;
283 let resolved = resolve_strict_authority_path(tool, &relative).map_err(|e| e.to_string())?;
284 #[cfg(windows)]
285 let resolved = if resolved.exists() {
286 resolved.canonicalize().map_err(|e| e.to_string())?
287 } else {
288 resolved
289 };
290 let shown = resolved
291 .strip_prefix(&root)
292 .map_err(|_| "outside".to_string())?
293 .to_str()
294 .ok_or_else(|| "not UTF-8".to_string())?
295 .replace('\\', "/");
296 let shown = if shown.is_empty() { ".".into() } else { shown };
297 validate_windows_relative_segments(&shown, windows)?;
298 if access == Access::Overlay && (shown == "." || protected_for(&shown, windows)) {
299 return Err(format!("overlay excludes {shown}"));
300 }
301 Ok((shown, resolved))
302 }
303
304 async fn confine(
305 call: &BrokerCall,
306 tool: &ToolContext,
307 raw: &str,
308 access: Access,
309 ) -> Result<(String, String), BrokerRefusal> {
310 shape(raw)?;
311 let owned = tool.clone();
312 let raw_owned = raw.to_string();
313 let work = async move {
314 let permit = CONFINE_GATE
315 .acquire()
316 .await
317 .map_err(|_| "closed".to_string())?;
318 tokio::task::spawn_blocking(move || {
319 let _permit = permit;
320 resolve(&owned, &raw_owned, access)
321 })
322 .await
323 .map_err(|error| error.to_string())?
324 };
325 let resolved = tokio::select! {
326 biased;
327 () = call.context.cancel().cancelled() => return Err(refused("the workspace call was withdrawn")),
328 resolved = work => resolved,
329 };
330 match resolved {
331 Ok((shown, path)) => {
332 let path = path
333 .to_str()
334 .ok_or_else(|| refused("that path is not available to this plugin"))?
335 .to_string();
336 Ok((shown, path))
337 }
338 Err(detail) => {
339 tracing::info!(target: LOG, plugin = %call.owner.plugin_id, %detail, "workspace path refused");
340 Err(refused("that path is not available to this plugin"))
341 }
342 }
343 }
344
345 fn literal_git(argv: &[String]) -> Result<Value, BrokerRefusal> {
346 if argv.is_empty()
347 || argv.len() > MAX_ARGS + 1
348 || argv
349 .iter()
350 .any(|arg| arg.len() > MAX_ARG_BYTES || arg.chars().any(char::is_control))
351 {
352 return Err(invalid(format!(
353 "argv is 1 to {} strings of at most {MAX_ARG_BYTES} bytes with no control characters",
354 MAX_ARGS + 1
355 )));
356 }
357 let refuse = || {
358 tracing::info!(target: LOG, program = %argv[0].chars().take(64).collect::<String>(), "workspace exec refused: not a literal read-only git command");
359 refused("only read-only git metadata commands run for plugins")
360 };
361 if argv[0] != "git" {
362 return Err(refuse());
363 }
364 let args: Vec<&str> = argv[1..].iter().map(String::as_str).collect();
365 let args = match args.split_first() {
366 Some((&"--no-optional-locks", rest)) => rest,
367 _ => &args[..],
368 };
369 let query = match args {
370 ["for-each-ref", "--format=%(refname:short)", "refs/heads"] => {
371 json!({ "query": "branches" })
372 }
373 ["log", "-n", "100", "--format=%H%x09%s"] => json!({ "query": "commits" }),
374 ["rev-parse", "--show-toplevel"] => json!({ "query": "root" }),
375 ["rev-parse", "--verify", "--end-of-options", rev] => {
376 json!({ "query": "resolve", "rev": rev })
377 }
378 ["rev-list", "--left-right", "--count", range] => match range.split_once("...") {
379 Some((ours, theirs)) if !theirs.contains("...") => {
380 json!({ "query": "ahead_behind", "ours": ours, "theirs": theirs })
381 }
382 _ => return Err(refuse()),
383 },
384 ["merge-base", ours, theirs] => {
385 json!({ "query": "merge_base", "ours": ours, "theirs": theirs })
386 }
387 _ => return Err(refuse()),
388 };
389 Ok(query)
390 }
391
392 async fn nested(
393 call: &BrokerCall,
394 tool: &'static str,
395 input: Value,
396 ) -> Result<ToolCallResponse, BrokerRefusal> {
397 let plugin = &call.owner.plugin_id;
398 match call.context.core_call(tool, input).await {
399 Ok(response) => {
400 tracing::info!(target: LOG, %plugin, tool, ok = response.ok, "workspace call ran through the gate");
401 Ok(response)
402 }
403 Err(refusal) => {
404 let code = refusal.code();
405 let detail = match &refusal {
406 BrokerRefusal::Denied { message, .. } | BrokerRefusal::Refused { message, .. } => {
407 message.as_str()
408 }
409 _ => "",
410 };
411 tracing::info!(target: LOG, %plugin, tool, code, detail, "workspace call not run");
412 Err(match refusal {
413 BrokerRefusal::Denied { .. } => BrokerRefusal::Denied {
414 service: DshService::Workspace,
415 message: "the workspace call was denied".to_string(),
416 },
417 _ => refused("the workspace call was refused"),
418 })
419 }
420 }
421 }
422
423 fn text(value: &Value) -> String {
424 match value {
425 Value::String(text) => text.clone(),
426 Value::Null => String::new(),
427 other => other.to_string(),
428 }
429 }
430
431 fn file_outcome(path: &str, response: ToolCallResponse) -> Value {
432 if !response.ok {
433 return json!({ "ok": false, "path": path, "output": text(&response.result) });
434 }
435 json!({
436 "ok": true,
437 "path": path,
438 "output": text(&response.result["content"]),
439 "truncated": !response.result["truncated"].is_null(),
440 })
441 }
442
443 fn exec_outcome(response: ToolCallResponse) -> Value {
444 if !response.ok {
445 return json!({ "ok": false, "stdout": "", "stderr": text(&response.result), "exit_code": null });
446 }
447 let parsed = serde_json::from_str::<Value>(&text(&response.result["content"]))
448 .ok()
449 .filter(|value| value["stdout"].is_string() && value["stderr"].is_string());
450 match parsed {
451 Some(value) => json!({
452 "ok": value["exit_code"] == json!(0),
453 "stdout": value["stdout"],
454 "stderr": value["stderr"],
455 "exit_code": value["exit_code"],
456 }),
457 None => json!({
458 "ok": false,
459 "stdout": "",
460 "stderr": "git output exceeded what a plugin call returns",
461 "exit_code": null,
462 }),
463 }
464 }
465
466 #[cfg(test)]
467 mod tests {
468 use super::super::dsh_broker::BrokerContext;
469 use super::*;
470 use codewhale_config::OwnerRef;
471
472 fn call(owner: &OwnerRef, method: &str, input: Value) -> BrokerCall {
473 BrokerCall {
474 owner: owner.clone(),
475 session_id: "session".into(),
476 service: DshService::Workspace,
477 method: method.into(),
478 input,
479 context: BrokerContext::detached_for_test(owner, DshService::Workspace),
480 }
481 }
482
483 fn owner() -> OwnerRef {
484 OwnerRef {
485 plugin_id: "a".into(),
486 generation: 1,
487 owner_token: "t".into(),
488 }
489 }
490
491 fn argv(args: &[&str]) -> Vec<String> {
492 args.iter().map(|arg| (*arg).to_string()).collect()
493 }
494
495 #[tokio::test]
496 async fn workspace_methods_decode_strictly_and_bound_every_input_before_anything_runs() {
497 let owner = owner();
498 for method in ["delete", "rename", "spawn", "shell", "watch", "core", "Git"] {
499 let refusal = serve(call(&owner, method, json!({}))).await.unwrap_err();
500 assert_eq!(refusal.code(), "unknown_method", "{method}");
501 }
502 let long_path = "p".repeat(MAX_PATH_BYTES + 1);
503 let long_content = "c".repeat(MAX_WRITE_BYTES + 1);
504 for (method, input) in [
505 ("read", json!({})),
506 ("read", json!({ "path": "" })),
507 ("read", json!({ "path": " x" })),
508 ("read", json!({ "path": "a\nb" })),
509 ("read", json!({ "path": long_path })),
510 ("read", json!({ "path": "x", "start_line": 0 })),
511 ("read", json!({ "path": "x", "max_lines": 0 })),
512 (
513 "read",
514 json!({ "path": "x", "max_lines": MAX_READ_LINES + 1 }),
515 ),
516 ("read", json!({ "path": "x", "follow_symlinks": true })),
517 ("list", json!({ "path": "x", "recursive": true })),
518 ("write", json!({ "path": "x" })),
519 ("write", json!({ "path": "x", "content": long_content })),
520 (
521 "write",
522 json!({ "path": "x", "content": "", "expected_hash": "" }),
523 ),
524 ("write", json!({ "path": "x", "content": "", "mode": 493 })),
525 ("exec", json!({})),
526 ("exec", json!({ "argv": [] })),
527 ("exec", json!({ "argv": ["git", "a\u{0}b"] })),
528 ("exec", json!({ "argv": ["git"], "env": {} })),
529 ("exec", json!({ "argv": ["git"], "shell": true })),
530 ] {
531 let refusal = serve(call(&owner, method, input.clone()))
532 .await
533 .unwrap_err();
534 assert_eq!(refusal.code(), "invalid_input", "{method} {input}");
535 }
536 }
537
538 #[tokio::test]
539 async fn a_workspace_call_whose_cancel_has_fired_has_no_effect() {
540 let owner = owner();
541 let _overlay = TestOverlay::granted();
542 for (method, input) in [
543 ("read", json!({ "path": "x" })),
544 ("list", json!({})),
545 ("write", json!({ "path": "x", "content": "y" })),
546 (
547 "exec",
548 json!({ "argv": ["git", "rev-parse", "--show-toplevel"] }),
549 ),
550 ] {
551 let fired = call(&owner, method, input);
552 fired.context.cancel().cancel();
553 let refusal = serve(fired).await.unwrap_err();
554 assert_eq!(refusal.code(), "refused", "{method}");
555 }
556 }
557
558 #[tokio::test]
559 async fn a_workspace_read_of_a_file_outside_the_workspace_is_refused() {
560 let owner = owner();
561 let _overlay = TestOverlay::granted();
562 let outside = tempfile::tempdir().unwrap();
563 let file = outside.path().canonicalize().unwrap().join("skill.md");
564 std::fs::write(&file, "OUTSIDE-MARKER").unwrap();
565 for (method, input) in [
566 ("read", json!({ "path": file.to_string_lossy() })),
567 ("list", json!({ "path": outside.path().to_string_lossy() })),
568 ] {
569 let refusal = serve(call(&owner, method, input)).await.unwrap_err();
570 assert_eq!(refusal.code(), "refused", "{method}");
571 assert!(!refusal.wire().message.contains("OUTSIDE-MARKER"));
572 }
573 }
574
575 #[tokio::test]
576 async fn a_write_without_the_reviewed_overlay_grant_is_refused_before_any_path_is_read() {
577 let owner = owner();
578 let refusal = serve(call(
579 &owner,
580 "write",
581 json!({ "path": "x", "content": "y" }),
582 ))
583 .await
584 .unwrap_err();
585 assert_eq!(refusal.code(), "refused");
586 assert_eq!(
587 refusal.wire().message,
588 "this plugin may not write to the workspace"
589 );
590 }
591
592 #[test]
593 fn only_literal_read_only_git_metadata_argv_maps_to_the_git_tool() {
594 for (args, expected) in [
595 (
596 argv(&["git", "rev-parse", "--show-toplevel"]),
597 json!({ "query": "root" }),
598 ),
599 (
600 argv(&[
601 "git",
602 "--no-optional-locks",
603 "for-each-ref",
604 "--format=%(refname:short)",
605 "refs/heads",
606 ]),
607 json!({ "query": "branches" }),
608 ),
609 (
610 argv(&["git", "log", "-n", "100", "--format=%H%x09%s"]),
611 json!({ "query": "commits" }),
612 ),
613 (
614 argv(&["git", "rev-parse", "--verify", "--end-of-options", "main"]),
615 json!({ "query": "resolve", "rev": "main" }),
616 ),
617 (
618 argv(&["git", "rev-list", "--left-right", "--count", "a...b"]),
619 json!({ "query": "ahead_behind", "ours": "a", "theirs": "b" }),
620 ),
621 (
622 argv(&["git", "merge-base", "a", "b"]),
623 json!({ "query": "merge_base", "ours": "a", "theirs": "b" }),
624 ),
625 ] {
626 assert_eq!(literal_git(&args).unwrap(), expected, "{args:?}");
627 }
628 for args in [
629 argv(&["sh", "-c", "git status"]),
630 argv(&["/usr/bin/git", "rev-parse", "--show-toplevel"]),
631 argv(&["git"]),
632 argv(&["git", "status"]),
633 argv(&["git", "rev-parse", "--show-toplevel", "--git-dir"]),
634 argv(&[
635 "git",
636 "-c",
637 "core.fsmonitor=x",
638 "rev-parse",
639 "--show-toplevel",
640 ]),
641 argv(&[
642 "git",
643 "--no-optional-locks",
644 "--no-optional-locks",
645 "rev-parse",
646 "--show-toplevel",
647 ]),
648 argv(&["git", "log", "-n", "100", "--format=%H%x09%s", "-p"]),
649 argv(&["git", "rev-list", "--left-right", "--count", "a..b"]),
650 argv(&["git", "rev-list", "--left-right", "--count", "a...b...c"]),
651 argv(&["git", "push", "origin", "main"]),
652 argv(&["git", "config", "core.hooksPath", "/tmp"]),
653 ] {
654 assert_eq!(
655 literal_git(&args).unwrap_err().code(),
656 "refused",
657 "{args:?}"
658 );
659 }
660 let too_many = vec!["git".to_string(); MAX_ARGS + 2];
661 assert_eq!(literal_git(&too_many).unwrap_err().code(), "invalid_input");
662 }
663
664 #[test]
665 fn paths_are_confined_to_the_workspace_and_the_overlay_excludes_its_internals() {
666 let dir = tempfile::tempdir().unwrap();
667 let root = dir.path().canonicalize().unwrap();
668 std::fs::create_dir_all(root.join("src")).unwrap();
669 std::fs::write(root.join("src/a.txt"), "a").unwrap();
670 let tool = ToolContext::new(&root);
671 let read = |raw: &str| resolve(&tool, raw, Access::Read).map(|(shown, _)| shown);
672 let write = |raw: &str| resolve(&tool, raw, Access::Overlay).map(|(shown, _)| shown);
673
674 assert_eq!(read("src/a.txt").unwrap(), "src/a.txt");
675 assert_eq!(read("./src//a.txt").unwrap(), "src/a.txt");
676 assert_eq!(
677 read(root.join("src/a.txt").to_str().unwrap()).unwrap(),
678 "src/a.txt"
679 );
680 assert_eq!(read(root.to_str().unwrap()).unwrap(), ".");
681 assert_eq!(read(".").unwrap(), ".");
682 assert_eq!(write("src/new/b.txt").unwrap(), "src/new/b.txt");
683
684 let outside = tempfile::tempdir().unwrap();
685 for raw in [
686 "../x",
687 "src/../../x",
688 outside.path().to_str().unwrap(),
689 "/etc/passwd",
690 ] {
691 assert!(read(raw).is_err(), "{raw}");
692 assert!(write(raw).is_err(), "{raw}");
693 }
694 for raw in [
695 ".",
696 ".git/config",
697 ".GIT/hooks/pre-commit",
698 "src/.git",
699 ".codewhale/x",
700 ] {
701 assert!(write(raw).is_err(), "{raw}");
702 }
703 assert_eq!(read(".git/HEAD").unwrap(), ".git/HEAD");
704 }
705
706 #[cfg(unix)]
707 #[test]
708 fn a_symlink_anywhere_on_the_path_is_refused_even_when_it_points_inside() {
709 let dir = tempfile::tempdir().unwrap();
710 let root = dir.path().canonicalize().unwrap();
711 let outside = tempfile::tempdir().unwrap();
712 std::fs::write(outside.path().join("secret"), "s").unwrap();
713 std::fs::create_dir_all(root.join("src")).unwrap();
714 std::fs::write(root.join("src/a.txt"), "a").unwrap();
715 std::os::unix::fs::symlink(outside.path(), root.join("out")).unwrap();
716 std::os::unix::fs::symlink(root.join("src"), root.join("in")).unwrap();
717 std::os::unix::fs::symlink(root.join("src/a.txt"), root.join("link.txt")).unwrap();
718 let tool = ToolContext::new(&root);
719 for raw in ["out/secret", "out", "in/a.txt", "link.txt", "out/new.txt"] {
720 assert!(resolve(&tool, raw, Access::Read).is_err(), "{raw}");
721 assert!(resolve(&tool, raw, Access::Overlay).is_err(), "{raw}");
722 }
723 }
724
725 #[test]
726 fn windows_metadata_aliases_short_names_and_ads_are_refused_in_validation() {
727 let dir = tempfile::tempdir().unwrap();
728 let root = dir.path().canonicalize().unwrap();
729 std::fs::create_dir_all(root.join("src")).unwrap();
730 std::fs::write(root.join("src/a.txt"), "a").unwrap();
731 let tool = ToolContext::new(&root);
732
733 for alias in [
734 "GIT~1",
735 "GIT~1/hooks/pre-commit",
736 "git~12/config",
737 "sub/GIT~2/HEAD",
738 "CODEWH~1",
739 "CODEWH~1/config.json",
740 "codew~1/auth.json",
741 "code~1/sessions",
742 "SUBDIR~1/file.txt",
743 ".git::$INDEX_ALLOCATION",
744 ".GIT::$INDEX_ALLOCATION",
745 "sub/.git:stream",
746 "sub/.codewhale:secret",
747 "file.txt:Zone.Identifier",
748 "C:rel.txt",
749 ".git.",
750 ".git /config",
751 ".codewhale.",
752 "sub/.codewhale /x",
753 ] {
754 assert!(
755 resolve_for(&tool, alias, Access::Read, true).is_err(),
756 "read must reject {alias}"
757 );
758 assert!(
759 resolve_for(&tool, alias, Access::Overlay, true).is_err(),
760 "overlay must reject {alias}"
761 );
762 }
763
764 for metadata in [
765 "GIT~1/hooks/pre-commit",
766 "git~1",
767 "CODEWH~1/config.json",
768 "codew~2",
769 ".git::$INDEX_ALLOCATION",
770 "sub/.git:stream",
771 "sub/.codewhale:secret",
772 ".git.",
773 ".git ",
774 ".codewhale.",
775 ".codewhale ",
776 ] {
777 assert!(
778 protected_for(metadata, true),
779 "protected_for must catch {metadata}"
780 );
781 }
782
783 assert_eq!(
784 resolve_for(&tool, "src/a.txt", Access::Overlay, true)
785 .unwrap()
786 .0,
787 "src/a.txt"
788 );
789 assert!(has_forbidden_windows_colon(".git::$INDEX_ALLOCATION", true));
790 assert!(has_forbidden_windows_colon("sub/.git:stream", true));
791 assert!(has_forbidden_windows_colon("C:rel.txt", true));
792 assert!(!has_forbidden_windows_colon(r"C:\ws\src\a.txt", true));
793 assert!(!has_forbidden_windows_colon(r"\\?\C:\ws\src\a.txt", true));
794
795 assert_eq!(
796 strip_workspace_root_str(r"C:\ws", Some(r"\\?\C:\ws"), r"\\?\C:\ws\src\a.txt", true)
797 .as_deref(),
798 Some("src/a.txt")
799 );
800 assert_eq!(
801 strip_workspace_root_str(r"C:\ws", None, r"c:/ws/src/a.txt", true).as_deref(),
802 Some("src/a.txt")
803 );
804 assert!(
805 has_forbidden_windows_colon(r"C:\ws\.git::$INDEX_ALLOCATION", true),
806 "drive prefix must not exempt trailing colons"
807 );
808 }
809
810 #[test]
811 fn results_are_typed_projections() {
812 let read = file_outcome(
813 "src/a.txt",
814 ToolCallResponse {
815 ok: true,
816 result: json!({ "content": "1: a", "truncated": null, "metadata": { "path": "/private" } }),
817 },
818 );
819 assert_eq!(
820 read,
821 json!({ "ok": true, "path": "src/a.txt", "output": "1: a", "truncated": false })
822 );
823 let ran = exec_outcome(ToolCallResponse {
824 ok: true,
825 result: json!({ "content": json!({ "stdout": "/w\n", "stderr": "", "exit_code": 0 }).to_string() }),
826 });
827 assert_eq!(
828 ran,
829 json!({ "ok": true, "stdout": "/w\n", "stderr": "", "exit_code": 0 })
830 );
831 let cut = exec_outcome(ToolCallResponse {
832 ok: true,
833 result: json!({ "content": "{\"stdout\": \"/w [output truncated" }),
834 });
835 assert_eq!(cut["ok"], false);
836 assert_eq!(cut["exit_code"], Value::Null);
837 }
838 }
839
839 lines RUST