返回 CodeWhale
tests.rs
根目录 / crates / engine / src / tools / spec / tests.rs
1 use super::*;
2 use serde_json::json;
3 #[cfg(unix)]
4 use std::os::unix::fs::symlink;
5 use tempfile::tempdir;
6
7 #[test]
8 fn test_tool_result_success() {
9 let result = ToolResult::success("hello");
10 assert!(result.success);
11 assert_eq!(result.content, "hello");
12 assert!(result.metadata.is_none());
13 }
14
15 #[test]
16 fn test_tool_result_error() {
17 let result = ToolResult::error("something failed");
18 assert!(!result.success);
19 assert_eq!(result.content, "something failed");
20 }
21
22 #[test]
23 fn test_tool_result_json() {
24 let data = json!({"key": "value"});
25 let result = ToolResult::json(&data).unwrap();
26 assert!(result.success);
27 assert!(result.content.contains("key"));
28 }
29
30 #[test]
31 fn test_tool_result_with_metadata() {
32 let result = ToolResult::success("content").with_metadata(json!({"extra": true}));
33 assert!(result.metadata.is_some());
34 }
35
36 #[test]
37 fn test_tool_context_resolve_path_relative() {
38 let tmp = tempdir().expect("tempdir");
39 let ctx = ToolContext::new(tmp.path().to_path_buf());
40
41 // Create a test file
42 let test_file = tmp.path().join("test.txt");
43 std::fs::write(&test_file, "test").expect("write");
44
45 let resolved = ctx.resolve_path("test.txt").expect("resolve");
46 assert!(resolved.ends_with("test.txt"));
47 }
48
49 #[test]
50 fn test_tool_context_resolve_path_escape() {
51 let tmp = tempdir().expect("tempdir");
52 let ctx = ToolContext::new(tmp.path().to_path_buf());
53
54 // Try to escape workspace
55 let result = ctx.resolve_path("/etc/passwd");
56 assert!(result.is_err());
57 }
58
59 #[test]
60 fn test_tool_context_resolve_path_parent_traversal() {
61 let tmp = tempdir().expect("tempdir");
62 let ctx = ToolContext::new(tmp.path().to_path_buf());
63
64 let result = ctx.resolve_path("../escape.txt");
65 assert!(result.is_err());
66 }
67
68 #[test]
69 fn test_tool_context_resolve_path_normalizes_parent() {
70 let tmp = tempdir().expect("tempdir");
71 let ctx = ToolContext::new(tmp.path().to_path_buf());
72
73 let result = ctx.resolve_path("new/../safe.txt");
74 assert!(result.is_ok());
75 }
76
77 #[test]
78 fn test_tool_context_trust_mode() {
79 let tmp = tempdir().expect("tempdir");
80 let ctx = ToolContext::new(tmp.path().to_path_buf()).with_trust_mode(true);
81
82 // In trust mode, absolute paths should work
83 let result = ctx.resolve_path("/tmp");
84 assert!(result.is_ok());
85 }
86
87 #[test]
88 fn tool_context_keeps_execution_state_grouped_and_value_cloned() {
89 let mut context = ToolContext::new(".");
90 context.auto_approve = true;
91 context.state_namespace = "session-a".to_string();
92
93 assert!(context.execution.auto_approve);
94 assert_eq!(context.execution.state_namespace, "session-a");
95
96 let mut cloned = context.clone();
97 cloned.state_namespace = "session-b".to_string();
98 assert_eq!(context.state_namespace, "session-a");
99 assert_eq!(cloned.execution.state_namespace, "session-b");
100 }
101
102 #[test]
103 fn legacy_auto_approve_bit_folds_into_the_context_posture() {
104 let plain = ToolContext::new(".");
105 assert_eq!(
106 plain.approval_mode,
107 codewhale_execpolicy::ApprovalMode::Suggest,
108 "a context with no authority runs under Ask"
109 );
110
111 let yolo = ToolContext::with_auto_approve(".", false, true);
112 assert!(yolo.auto_approve);
113 assert_eq!(
114 yolo.approval_mode,
115 codewhale_execpolicy::ApprovalMode::Bypass,
116 "a set auto-approve bit is the Full Access posture"
117 );
118 }
119
120 #[test]
121 fn tool_context_top_level_stays_slim_as_services_grow() {
122 assert!(
123 std::mem::size_of::<ToolContext>()
124 <= std::mem::size_of::<PathBuf>() + 2 * std::mem::size_of::<usize>(),
125 "ToolContext should contain only the workspace and boxed execution group"
126 );
127 }
128
129 /// Issue #29: paths under a user-trusted external directory resolve
130 /// successfully even though they fall outside the workspace, while
131 /// untrusted external paths still error with `PathEscape`.
132 #[test]
133 fn test_tool_context_trusted_external_path_allows_escape() {
134 let workspace = tempdir().expect("workspace tempdir");
135 let trusted_root = tempdir().expect("trusted tempdir");
136 let trusted_file = trusted_root.path().join("notes.md");
137 std::fs::write(&trusted_file, "shared notes").unwrap();
138
139 let ctx = ToolContext::new(workspace.path().to_path_buf()).with_trusted_external_paths(vec![
140 trusted_root
141 .path()
142 .canonicalize()
143 .unwrap_or_else(|_| trusted_root.path().to_path_buf()),
144 ]);
145
146 let resolved = ctx
147 .resolve_path(trusted_file.to_str().unwrap())
148 .expect("trusted path should resolve");
149 assert!(resolved.ends_with("notes.md"));
150
151 // Path outside workspace AND outside the trust list should still fail.
152 let other = tempdir().expect("untrusted tempdir");
153 let other_file = other.path().join("secret.md");
154 std::fs::write(&other_file, "x").unwrap();
155 let err = ctx
156 .resolve_path(other_file.to_str().unwrap())
157 .expect_err("untrusted path must error");
158 assert!(matches!(err, ToolError::PathEscape { .. }));
159 }
160
161 #[test]
162 #[cfg(unix)]
163 fn test_tool_context_follow_symlinks_allows_nonexistent_path_under_workspace_symlink() {
164 let tmp = tempdir().expect("tempdir");
165 let workspace = tmp.path().join("workspace");
166 let outside = tmp.path().join("outside");
167 std::fs::create_dir_all(&workspace).expect("mkdir workspace");
168 std::fs::create_dir_all(outside.join("target")).expect("mkdir outside target");
169 symlink(outside.join("target"), workspace.join("linked")).expect("symlink");
170
171 let ctx = ToolContext::new(workspace).with_follow_symlinks(true);
172 let resolved = ctx
173 .resolve_path("linked/new.txt")
174 .expect("path under workspace symlink should resolve");
175
176 let expected = outside
177 .join("target")
178 .canonicalize()
179 .expect("canonical target")
180 .join("new.txt");
181 assert_eq!(resolved, normalize_path(&expected));
182 }
183
184 #[test]
185 #[cfg(unix)]
186 fn test_tool_context_default_mode_rejects_nonexistent_path_under_workspace_symlink() {
187 let tmp = tempdir().expect("tempdir");
188 let workspace = tmp.path().join("workspace");
189 let outside = tmp.path().join("outside");
190 std::fs::create_dir_all(&workspace).expect("mkdir workspace");
191 std::fs::create_dir_all(outside.join("target")).expect("mkdir outside target");
192 symlink(outside.join("target"), workspace.join("linked")).expect("symlink");
193
194 let ctx = ToolContext::new(workspace);
195 let err = ctx
196 .resolve_path("linked/new.txt")
197 .expect_err("default mode should still reject workspace symlink escapes");
198
199 assert!(matches!(err, ToolError::PathEscape { .. }));
200 }
201
202 fn scoped_authority(roots: &[&str], files: &[&str]) -> ToolAuthorityEnvelope {
203 ToolAuthorityEnvelope {
204 schema_version: 1,
205 owner: "fleet-worker-1".to_string(),
206 authority: ToolMutationAuthority::ScopedWrite,
207 network_access: None,
208 shell: ToolShellAuthority::None,
209 verification: ToolVerificationAuthority::None,
210 writable_roots: roots.iter().map(|value| (*value).to_string()).collect(),
211 writable_files: files.iter().map(|value| (*value).to_string()).collect(),
212 coordination_contracts: Vec::new(),
213 }
214 .normalized()
215 .expect("valid test authority")
216 }
217
218 #[test]
219 fn tool_authority_allows_normal_nonexistent_children_only_inside_scope() {
220 let tmp = tempdir().expect("tempdir");
221 std::fs::create_dir(tmp.path().join("src")).expect("src");
222 let context = ToolContext::new(tmp.path().to_path_buf());
223 let authority = scoped_authority(&["src"], &[]);
224
225 assert!(
226 authority
227 .permits_mutation_path(&context, "src/new/nested.rs")
228 .expect("normal nonexistent child")
229 );
230 assert!(
231 !authority
232 .permits_mutation_path(&context, "docs/outside.md")
233 .expect("ordinary out-of-scope path")
234 );
235 }
236
237 #[cfg(unix)]
238 #[test]
239 fn tool_authority_rejects_exact_file_symlink_aliases() {
240 let tmp = tempdir().expect("tempdir");
241 std::fs::create_dir(tmp.path().join("src")).expect("src");
242 std::fs::create_dir(tmp.path().join("other")).expect("other");
243 std::fs::write(tmp.path().join("other/target.rs"), "outside scope\n").expect("target");
244 symlink("../other/target.rs", tmp.path().join("src/alias.rs")).expect("alias");
245 let context = ToolContext::new(tmp.path().to_path_buf());
246 let authority = scoped_authority(&[], &["src/alias.rs"]);
247
248 let error = authority
249 .permits_mutation_path(&context, "src/alias.rs")
250 .expect_err("an exact-file claim must not authorize a symlink target")
251 .to_string();
252 assert!(error.contains("must not traverse symlinks"), "{error}");
253 }
254
255 #[cfg(unix)]
256 #[test]
257 fn tool_authority_rejects_claimed_root_and_child_symlink_aliases() {
258 let tmp = tempdir().expect("tempdir");
259 std::fs::create_dir(tmp.path().join("real")).expect("real");
260 symlink("real", tmp.path().join("linked")).expect("linked root");
261 let context = ToolContext::new(tmp.path().to_path_buf());
262 let claimed_alias = scoped_authority(&["linked"], &[]);
263 let claimed_real = scoped_authority(&["real"], &[]);
264
265 for (authority, path) in [
266 (&claimed_alias, "linked/new.rs"),
267 (&claimed_real, "linked/new.rs"),
268 ] {
269 let error = authority
270 .permits_mutation_path(&context, path)
271 .expect_err("symlinked roots and mutation paths must fail closed")
272 .to_string();
273 assert!(error.contains("must not traverse symlinks"), "{error}");
274 }
275 }
276
277 #[test]
278 fn nested_tool_authority_may_only_narrow_the_outer_cap() {
279 let tmp = tempdir().expect("tempdir");
280 let outer = scoped_authority(&["src"], &["Cargo.toml"]);
281 let narrower = scoped_authority(&["src/parser"], &[]);
282 let expansion = scoped_authority(&["docs"], &[]);
283 ToolContext::new(tmp.path().to_path_buf())
284 .with_tool_authority(outer.clone())
285 .unwrap()
286 .with_tool_authority(narrower)
287 .expect("nested scope may narrow");
288 let error = ToolContext::new(tmp.path().to_path_buf())
289 .with_tool_authority(outer.clone())
290 .unwrap()
291 .with_tool_authority(expansion)
292 .err()
293 .expect("nested scope expansion must fail closed");
294 assert!(error.contains("cannot expand"), "{error}");
295
296 let read_only = ToolAuthorityEnvelope {
297 schema_version: 1,
298 owner: "read-only-child".to_string(),
299 authority: ToolMutationAuthority::ReadOnly,
300 network_access: None,
301 shell: ToolShellAuthority::None,
302 verification: ToolVerificationAuthority::None,
303 writable_roots: Vec::new(),
304 writable_files: Vec::new(),
305 coordination_contracts: Vec::new(),
306 };
307 ToolContext::new(tmp.path().to_path_buf())
308 .with_tool_authority(outer.clone())
309 .unwrap()
310 .with_tool_authority(read_only)
311 .expect("read-only always narrows a write cap");
312
313 let shell_expansion = ToolAuthorityEnvelope {
314 schema_version: 1,
315 owner: "shell-expansion".to_string(),
316 authority: ToolMutationAuthority::ReadOnly,
317 network_access: None,
318 shell: ToolShellAuthority::ReadOnly,
319 verification: ToolVerificationAuthority::None,
320 writable_roots: Vec::new(),
321 writable_files: Vec::new(),
322 coordination_contracts: Vec::new(),
323 };
324 ToolContext::new(tmp.path().to_path_buf())
325 .with_tool_authority(outer)
326 .unwrap()
327 .with_tool_authority(shell_expansion)
328 .err()
329 .expect("nested authority cannot add a shell cap the outer process lacks");
330 }
331
332 #[test]
333 fn legacy_v1_authority_envelopes_default_to_shell_none() {
334 let authority = ToolAuthorityEnvelope::from_json(
335 r#"{"schema_version":1,"owner":"legacy-worker","authority":"read_only"}"#,
336 )
337 .expect("pre-shell v1 envelope remains readable");
338 assert_eq!(authority.shell, ToolShellAuthority::None);
339 assert_eq!(authority.verification, ToolVerificationAuthority::None);
340 }
341
342 #[test]
343 fn headless_fleet_registers_bash_only_when_the_clamped_ceiling_keeps_it() {
344 assert!(fleet_exec_shell_enabled(
345 true,
346 ToolShellAuthority::ReadOnly,
347 None
348 ));
349 assert!(!fleet_exec_shell_enabled(
350 true,
351 ToolShellAuthority::ReadOnly,
352 Some(&["ba*".into()])
353 ));
354 assert!(!fleet_exec_shell_enabled(
355 true,
356 ToolShellAuthority::None,
357 None
358 ));
359 }
360
361 #[test]
362 fn bounded_verification_is_typed_and_cannot_smuggle_bash_authority() {
363 let bounded = ToolAuthorityEnvelope::from_json(
364 r#"{"schema_version":1,"owner":"verifier","authority":"read_only","verification":"bounded"}"#,
365 )
366 .expect("bounded verifier authority");
367 assert_eq!(bounded.verification, ToolVerificationAuthority::Bounded);
368
369 let widened = ToolAuthorityEnvelope {
370 shell: ToolShellAuthority::ReadOnly,
371 ..bounded
372 };
373 assert!(
374 widened.normalized().is_err(),
375 "bounded verification and Bash authority are separate, non-composable caps"
376 );
377 }
378
379 #[test]
380 fn read_only_machine_authority_clamps_live_shell_policy() {
381 let tmp = tempdir().expect("tempdir");
382 let read_only = ToolAuthorityEnvelope {
383 schema_version: 1,
384 owner: "scout".to_string(),
385 authority: ToolMutationAuthority::ReadOnly,
386 network_access: Some(true),
387 shell: ToolShellAuthority::ReadOnly,
388 verification: ToolVerificationAuthority::None,
389 writable_roots: Vec::new(),
390 writable_files: Vec::new(),
391 coordination_contracts: Vec::new(),
392 };
393 let mut context = ToolContext::new(tmp.path().to_path_buf())
394 .with_tool_authority(read_only)
395 .expect("read-only authority");
396
397 assert_eq!(context.shell_policy, ShellPolicy::ReadOnly);
398 context.set_shell_policy(ShellPolicy::Full);
399 assert_eq!(
400 context.shell_policy,
401 ShellPolicy::ReadOnly,
402 "a live mode refresh must not widen the process authority cap"
403 );
404
405 let scoped = ToolContext::new(tmp.path().to_path_buf())
406 .with_tool_authority(scoped_authority(&["src"], &[]))
407 .expect("scoped authority")
408 .with_shell_policy(ShellPolicy::Full);
409 assert_eq!(scoped.shell_policy, ShellPolicy::None);
410 }
411
412 #[test]
413 fn process_tool_authority_inherits_into_all_context_constructors() {
414 const CHILD_ENV: &str = "CODEWHALE_TEST_PROCESS_TOOL_AUTHORITY_CHILD";
415 if std::env::var_os(CHILD_ENV).is_some() {
416 let tmp = tempdir().expect("tempdir");
417 install_process_tool_authority(ToolAuthorityEnvelope {
418 schema_version: 1,
419 owner: "fleet-worker-child-process".to_string(),
420 authority: ToolMutationAuthority::ReadOnly,
421 network_access: None,
422 shell: ToolShellAuthority::ReadOnly,
423 verification: ToolVerificationAuthority::None,
424 writable_roots: Vec::new(),
425 writable_files: Vec::new(),
426 coordination_contracts: Vec::new(),
427 })
428 .expect("install process authority once in isolated child");
429 let contexts = [
430 ToolContext::new(tmp.path().to_path_buf()),
431 ToolContext::with_options(tmp.path().to_path_buf(), false),
432 ToolContext::with_auto_approve(tmp.path().to_path_buf(), false, true),
433 ];
434 for context in contexts {
435 let authority = context
436 .tool_authority
437 .as_ref()
438 .expect("every constructor inherits process authority");
439 assert_eq!(authority.owner, "fleet-worker-child-process");
440 assert_eq!(authority.authority, ToolMutationAuthority::ReadOnly);
441 assert_eq!(context.shell_policy, ShellPolicy::ReadOnly);
442 }
443 return;
444 }
445
446 let output = std::process::Command::new(std::env::current_exe().expect("test binary"))
447 .arg("--exact")
448 .arg("tools::spec::tests::process_tool_authority_inherits_into_all_context_constructors")
449 .arg("--nocapture")
450 .env(CHILD_ENV, "1")
451 .output()
452 .expect("spawn isolated authority test child");
453 assert!(
454 output.status.success(),
455 "child failed:\nstdout:\n{}\nstderr:\n{}",
456 String::from_utf8_lossy(&output.stdout),
457 String::from_utf8_lossy(&output.stderr)
458 );
459 }
460
461 #[test]
462 fn test_required_str() {
463 let input = json!({"name": "test", "count": 42});
464 assert_eq!(required_str(&input, "name").unwrap(), "test");
465 assert!(required_str(&input, "missing").is_err());
466 assert!(required_str(&input, "count").is_err()); // not a string
467 }
468
469 #[test]
470 fn test_optional_str() {
471 let input = json!({"name": "test", "count": 7});
472 assert_eq!(optional_str(&input, "name").unwrap(), Some("test"));
473 assert_eq!(optional_str(&input, "missing").unwrap(), None);
474 // An explicit null is the wire spelling of "absent", not a type error.
475 assert_eq!(optional_str(&json!({"name": null}), "name").unwrap(), None);
476 let err = optional_str(&input, "count").expect_err("a number is not a string");
477 let err = err.to_string();
478 assert!(
479 err.contains("count") && err.contains("number") && err.contains("string"),
480 "{err}"
481 );
482 }
483
484 #[test]
485 fn test_required_u64() {
486 let input = json!({"count": 42});
487 assert_eq!(required_u64(&input, "count").unwrap(), 42);
488 assert!(required_u64(&input, "missing").is_err());
489 }
490
491 #[test]
492 fn test_optional_u64() {
493 let input = json!({"count": 42});
494 assert_eq!(optional_u64(&input, "count", 0).unwrap(), 42);
495 assert_eq!(optional_u64(&input, "missing", 100).unwrap(), 100);
496 assert_eq!(
497 optional_u64(&json!({"count": null}), "count", 9).unwrap(),
498 9
499 );
500 // A stringy number keeps its default today only because the harness
501 // never noticed; it must be an error instead.
502 for bad in [json!("42"), json!(-1), json!(2.5), json!([42])] {
503 let err = optional_u64(&json!({"count": bad}), "count", 100)
504 .expect_err("a non-integer must not fall back to the default")
505 .to_string();
506 assert!(
507 err.contains("count") && err.contains("non-negative integer"),
508 "{err}"
509 );
510 }
511 }
512
513 #[test]
514 fn test_optional_bool() {
515 let input = json!({"flag": true});
516 assert!(optional_bool(&input, "flag", false).unwrap());
517 assert!(!optional_bool(&input, "missing", false).unwrap());
518 assert!(optional_bool(&json!({"flag": null}), "flag", true).unwrap());
519 // The whole point: "true" must never become the default `false`.
520 for bad in [json!("true"), json!("false"), json!(1), json!(0), json!([])] {
521 let err = optional_bool(&json!({"flag": bad}), "flag", false)
522 .expect_err("a non-boolean must not fall back to the default")
523 .to_string();
524 assert!(err.contains("flag") && err.contains("boolean"), "{err}");
525 }
526 }
527
528 #[test]
529 fn test_tool_error_display() {
530 let err = ToolError::missing_field("path");
531 assert_eq!(
532 format!("{err}"),
533 "Failed to validate input: missing required field 'path'"
534 );
535
536 let err = ToolError::execution_failed("boom");
537 assert_eq!(format!("{err}"), "Failed to execute tool: boom");
538 }
539
540 #[test]
541 fn test_approval_requirement_default() {
542 let level = ApprovalRequirement::default();
543 assert_eq!(level, ApprovalRequirement::Auto);
544 }
545
546 #[test]
547 fn test_resolve_home_path_exact_prefixes() {
548 let fake_home = PathBuf::from("/fake/user/home");
549
550 // Exact ~ and ~/ prefixes resolve
551 assert_eq!(
552 resolve_home_path_with("~", || Some(fake_home.clone())).unwrap(),
553 Some(fake_home.clone())
554 );
555 assert_eq!(
556 resolve_home_path_with("~/", || Some(fake_home.clone())).unwrap(),
557 Some(fake_home.clone())
558 );
559 assert_eq!(
560 resolve_home_path_with("~//", || Some(fake_home.clone())).unwrap(),
561 Some(fake_home.clone())
562 );
563 assert_eq!(
564 resolve_home_path_with("~/file.txt", || Some(fake_home.clone())).unwrap(),
565 Some(fake_home.join("file.txt"))
566 );
567 assert_eq!(
568 resolve_home_path_with("~/a/b/c.md", || Some(fake_home.clone())).unwrap(),
569 Some(fake_home.join("a/b/c.md"))
570 );
571
572 #[cfg(windows)]
573 {
574 assert_eq!(
575 resolve_home_path_with(r"~\", || Some(fake_home.clone())).unwrap(),
576 Some(fake_home.clone())
577 );
578 assert_eq!(
579 resolve_home_path_with(r"~\file.txt", || Some(fake_home.clone())).unwrap(),
580 Some(fake_home.join("file.txt"))
581 );
582 }
583
584 // Must NOT expand ~otheruser, shell variables, command substitutions, globs, or literals
585 assert_eq!(
586 resolve_home_path_with("~otheruser", || Some(fake_home.clone())).unwrap(),
587 None
588 );
589 assert_eq!(
590 resolve_home_path_with("~otheruser/file", || Some(fake_home.clone())).unwrap(),
591 None
592 );
593 assert_eq!(
594 resolve_home_path_with("./~/file", || Some(fake_home.clone())).unwrap(),
595 None
596 );
597 assert_eq!(
598 resolve_home_path_with("$HOME/file", || Some(fake_home.clone())).unwrap(),
599 None
600 );
601 assert_eq!(
602 resolve_home_path_with("`whoami`/file", || Some(fake_home.clone())).unwrap(),
603 None
604 );
605 assert_eq!(
606 resolve_home_path_with("~*", || Some(fake_home.clone())).unwrap(),
607 None
608 );
609 assert_eq!(
610 resolve_home_path_with("regular/path", || Some(fake_home.clone())).unwrap(),
611 None
612 );
613 assert_eq!(
614 resolve_home_path_with("/absolute/path", || Some(fake_home.clone())).unwrap(),
615 None
616 );
617 }
618
619 #[test]
620 fn test_resolve_home_path_unknown_home_fails_explicitly_without_cwd_guessing() {
621 let err = resolve_home_path_with("~", || None).expect_err("unknown home must fail explicitly");
622 let msg = err.to_string();
623 assert!(
624 msg.contains("user home directory could not be determined"),
625 "error message must be explicit: {msg}"
626 );
627
628 let err = resolve_home_path_with("~/nested/file.txt", || None)
629 .expect_err("unknown home must fail explicitly");
630 let msg = err.to_string();
631 assert!(
632 msg.contains("user home directory could not be determined"),
633 "error message must be explicit: {msg}"
634 );
635 }
636
637 #[test]
638 fn test_tool_context_resolve_path_home_prefix_inside_workspace() {
639 // The fixture lives inside the home, so the home must be the test's own.
640 let _sealed = crate::test_support::SealedHome::new();
641 let real_home = codewhale_paths::user_home().expect("test home must be available");
642 let home_temp = tempfile::Builder::new()
643 .prefix("cw_spec_test_home_")
644 .tempdir_in(&real_home)
645 .expect("create fixture inside test home");
646
647 let test_file = home_temp.path().join("inside.txt");
648 std::fs::write(&test_file, "inside workspace").expect("write test file");
649
650 let rel = test_file
651 .strip_prefix(&real_home)
652 .expect("fixture is below test home");
653 let tilde_path = format!("~/{}", rel.to_string_lossy());
654
655 let ctx = ToolContext::new(home_temp.path().to_path_buf());
656 let resolved = ctx
657 .resolve_path(&tilde_path)
658 .expect("home path inside workspace should resolve");
659
660 let expected = test_file
661 .canonicalize()
662 .unwrap_or_else(|_| normalize_path(&test_file));
663 assert_eq!(resolved, expected);
664 }
665
666 #[test]
667 fn test_tool_context_resolve_path_home_prefix_restricted_refusal() {
668 let workspace = tempdir().expect("workspace tempdir");
669 let ctx = ToolContext::new(workspace.path().to_path_buf());
670
671 // A home path outside workspace without trusted external path or trust mode must be refused
672 let err = ctx
673 .resolve_path("~/some_untrusted_file_never_present_12345.txt")
674 .expect_err("home path outside workspace must error");
675 assert!(matches!(err, ToolError::PathEscape { .. }));
676 }
677
678 #[test]
679 fn test_tool_context_resolve_path_home_prefix_trusted_external_path() {
680 // The fixture lives inside the home, so the home must be the test's own.
681 let _sealed = crate::test_support::SealedHome::new();
682 let real_home = codewhale_paths::user_home().expect("test home must be available");
683 let trusted_dir = tempfile::Builder::new()
684 .prefix("cw_spec_trusted_home_")
685 .tempdir_in(&real_home)
686 .expect("create fixture inside test home");
687 let trusted_file = trusted_dir.path().join("shared.md");
688 std::fs::write(&trusted_file, "shared content").expect("write trusted file");
689
690 let rel = trusted_file
691 .strip_prefix(&real_home)
692 .expect("fixture is below test home");
693 let tilde_path = format!("~/{}", rel.to_string_lossy());
694
695 let workspace = tempdir().expect("workspace tempdir");
696 let canonical_trusted = trusted_dir
697 .path()
698 .canonicalize()
699 .unwrap_or_else(|_| trusted_dir.path().to_path_buf());
700 let ctx = ToolContext::new(workspace.path().to_path_buf())
701 .with_trusted_external_paths(vec![canonical_trusted]);
702
703 let resolved = ctx
704 .resolve_path(&tilde_path)
705 .expect("trusted external home path should resolve");
706 assert_eq!(resolved, trusted_file.canonicalize().unwrap());
707 }
708
709 #[test]
710 fn test_tool_context_resolve_path_literal_tilde_in_workspace() {
711 let workspace = tempdir().expect("workspace tempdir");
712 let literal_tilde = workspace.path().join("~");
713 std::fs::create_dir_all(&literal_tilde).expect("create literal ~ dir");
714 let literal_file = literal_tilde.join("nested.txt");
715 std::fs::write(&literal_file, "literal tilde data").expect("write literal");
716
717 let ctx = ToolContext::new(workspace.path().to_path_buf());
718 let resolved = ctx
719 .resolve_path("./~/nested.txt")
720 .expect("literal ./~/ path must resolve inside workspace");
721 assert_eq!(resolved, literal_file.canonicalize().unwrap());
722 }
723
724 #[test]
725 fn test_tool_context_resolve_path_no_shell_expansion() {
726 let workspace = tempdir().expect("workspace tempdir");
727 let ctx = ToolContext::new(workspace.path().to_path_buf());
728
729 // $HOME/file should NOT expand shell env var, but be treated relative to workspace
730 let resolved = ctx
731 .resolve_path("$HOME/file.txt")
732 .expect("should treat as workspace child");
733 assert!(
734 resolved.starts_with(
735 workspace
736 .path()
737 .canonicalize()
738 .unwrap_or_else(|_| workspace.path().to_path_buf())
739 )
740 );
741 assert!(resolved.to_string_lossy().contains("$HOME"));
742
743 // ~otheruser should NOT expand other user home, but be treated relative to workspace
744 let resolved_other = ctx
745 .resolve_path("~otheruser/file.txt")
746 .expect("should treat as workspace child");
747 assert!(resolved_other.to_string_lossy().contains("~otheruser"));
748 }
749
750 #[test]
751 fn delegated_shell_is_refused_outright_when_the_session_lacks_it() {
752 let workspace = tempfile::tempdir().expect("workspace");
753 let mut ctx = ToolContext::new(workspace.path());
754
755 // Leaving the flag out would fall back to the host default, which may
756 // allow shell: a session without full shell must store an explicit "no".
757 ctx.shell_policy = codewhale_agent_contract::worker_profile::ShellPolicy::None;
758 assert_eq!(ctx.cap_delegated_authority(None, None, None).0, Some(false));
759 assert_eq!(
760 ctx.cap_delegated_authority(Some(true), None, None).0,
761 Some(false)
762 );
763
764 ctx.shell_policy = codewhale_agent_contract::worker_profile::ShellPolicy::Full;
765 assert_eq!(ctx.cap_delegated_authority(None, None, None).0, None);
766 assert_eq!(
767 ctx.cap_delegated_authority(Some(true), None, None).0,
768 Some(true)
769 );
770 }
771
771 lines RUST