1use crate::pb::pilot::CapabilityCallResult;
7use crate::plan_runtime::PlanRuntime;
8use robonix_atlas::client::AtlasClient;
9use robonix_atlas::pb as atlas_pb;
10use serde::Deserialize;
11use std::path::{Path, PathBuf};
12
13fn workspace_root() -> PathBuf {
18 std::env::var("ROBONIX_WORKSPACE")
19 .map(PathBuf::from)
20 .unwrap_or_else(|_| std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")))
21}
22
23fn safe_resolve(user_path: &str) -> anyhow::Result<PathBuf> {
27 safe_resolve_in(&workspace_root(), user_path)
28}
29
30fn safe_resolve_in(workspace: &Path, user_path: &str) -> anyhow::Result<PathBuf> {
34 let root = workspace
35 .canonicalize()
36 .unwrap_or_else(|_| workspace.to_path_buf());
37 let candidate = if Path::new(user_path).is_absolute() {
38 PathBuf::from(user_path)
39 } else {
40 root.join(user_path)
41 };
42 let resolved = if candidate.exists() {
45 candidate.canonicalize()?
46 } else {
47 let parent = candidate
48 .parent()
49 .ok_or_else(|| anyhow::anyhow!("invalid path: no parent directory"))?;
50 let parent_resolved = parent.canonicalize().map_err(|_| {
51 anyhow::anyhow!("parent directory does not exist: {}", parent.display())
52 })?;
53 parent_resolved.join(
54 candidate
55 .file_name()
56 .ok_or_else(|| anyhow::anyhow!("invalid path: no file name"))?,
57 )
58 };
59 if !resolved.starts_with(&root) {
60 anyhow::bail!(
61 "path traversal denied: {} resolves outside workspace {}",
62 user_path,
63 root.display()
64 );
65 }
66 Ok(resolved)
67}
68
69use crate::pb::pilot::CapabilityCall;
70
71pub async fn execute(
75 call: &CapabilityCall,
76 runtime: &PlanRuntime,
77 atlas: &mut AtlasClient,
78 plan_id: &str,
79) -> CapabilityCallResult {
80 let op = call
81 .contract_id
82 .rsplit_once('/')
83 .map(|(_, leaf)| leaf)
84 .unwrap_or(call.contract_id.as_str());
85 if op == "cancel_plan" {
86 return runtime.cancel_plan_builtin(call).await;
87 }
88 if op == "get_plan_status" {
89 return runtime.get_plan_status_builtin(call).await;
90 }
91 if op == "get_all_plans" {
92 return runtime.get_all_plans_builtin(call).await;
93 }
94 if op == "read_capability_doc" {
95 return read_capability_doc(call, atlas).await;
96 }
97
98 let result = run(op, &call.args_json, runtime, plan_id).await;
99 let mut out = CapabilityCallResult {
100 call_id: call.call_id.clone(),
101 provider_id: call.provider_id.clone(),
102 contract_id: call.contract_id.clone(),
103 ..Default::default()
104 };
105 match result {
106 Ok(s) => {
107 out.success = true;
108 out.output = s;
109 }
110 Err(e) => {
111 out.success = false;
112 out.error = e.to_string();
113 }
114 }
115 out
116}
117
118async fn run(
119 op: &str,
120 args_json: &str,
121 runtime: &PlanRuntime,
122 plan_id: &str,
123) -> anyhow::Result<String> {
124 match op {
125 "read_file" => read_file(args_json),
126 "write_file" => write_file(args_json),
127 "patch_file" => patch_file(args_json),
128 "list_dir" => list_dir(args_json),
129 "run_command" => run_command(args_json, runtime, plan_id).await,
130 other => anyhow::bail!("unknown builtin: {}", other),
131 }
132}
133
134pub struct BuiltinSpec {
137 pub op: &'static str,
139 pub description: &'static str,
141 pub input_schema_json: &'static str,
143}
144
145pub const BUILTINS: &[BuiltinSpec] = &[
146 BuiltinSpec {
147 op: "read_file",
148 description: "Read a file and return its contents",
149 input_schema_json: r#"{"type":"object","properties":{"path":{"type":"string","description":"Absolute or relative file path"}},"required":["path"]}"#,
150 },
151 BuiltinSpec {
152 op: "write_file",
153 description: "Write content to a file (creates or overwrites)",
154 input_schema_json: r#"{"type":"object","properties":{"path":{"type":"string"},"content":{"type":"string"}},"required":["path","content"]}"#,
155 },
156 BuiltinSpec {
157 op: "patch_file",
158 description: "Replace the first occurrence of a string in a file",
159 input_schema_json: r#"{"type":"object","properties":{"path":{"type":"string"},"old":{"type":"string"},"new":{"type":"string"}},"required":["path","old","new"]}"#,
160 },
161 BuiltinSpec {
162 op: "list_dir",
163 description: "List files and directories at a path",
164 input_schema_json: r#"{"type":"object","properties":{"path":{"type":"string","description":"Directory path (default: current dir)"}}}"#,
165 },
166 BuiltinSpec {
167 op: "run_command",
168 description: "Run a shell command and return stdout/stderr",
169 input_schema_json: r#"{"type":"object","properties":{"command":{"type":"string"}},"required":["command"]}"#,
170 },
171 BuiltinSpec {
172 op: "cancel_plan",
173 description: "Cancellation for an in-flight RTDL plan by plan_id",
174 input_schema_json: r#"{"type":"object","properties":{"plan_id":{"type":"string","description":"RTDL Plan.plan_id to cancel"},"wait_ms":{"type":"integer","minimum":0,"description":"Optional milliseconds to wait for the target plan to stop; default 5000"}},"required":["plan_id"]}"#,
175 },
176 BuiltinSpec {
177 op: "get_all_plans",
178 description: "List every in-flight RTDL plan with its plan_id, a short description of the task, op_count, and cancelled flag. Call this to discover which plans are currently running, then inspect one with get_plan_status before stopping it. Takes no arguments.",
179 input_schema_json: r#"{"type":"object","properties":{}}"#,
180 },
181 BuiltinSpec {
182 op: "get_plan_status",
183 description: "Inspect an in-flight RTDL plan: returns its ops, each with op_id, kind, description, current state (pending/running/verifying/succeeded/failed/canceled/timeout/paused). Call this to inspect live progress before issuing cancel_plan. Errors if the plan is not active (stale/wrong id or already finished) — use get_all_plans to list running plans.",
184 input_schema_json: r#"{"type":"object","properties":{"plan_id":{"type":"string","description":"RTDL Plan.plan_id to inspect"}},"required":["plan_id"]}"#,
185 },
186 BuiltinSpec {
187 op: "read_capability_doc",
188 description: "Read a capability provider's full CAPABILITY.md manual by provider_id. Call this to learn how to use a provider before invoking it. Only providers listed as having a doc carry one; never guess or read a file path for docs.",
189 input_schema_json: r#"{"type":"object","properties":{"provider_id":{"type":"string","description":"The provider_id whose CAPABILITY.md to read"}},"required":["provider_id"]}"#,
190 },
191];
192
193#[derive(Deserialize)]
195struct DocArgs {
196 provider_id: String,
198}
199
200async fn read_capability_doc(
209 call: &CapabilityCall,
210 atlas: &mut AtlasClient,
211) -> CapabilityCallResult {
212 let mut out = CapabilityCallResult {
213 call_id: call.call_id.clone(),
214 provider_id: call.provider_id.clone(),
215 contract_id: call.contract_id.clone(),
216 ..Default::default()
217 };
218 let provider_id = match serde_json::from_str::<DocArgs>(&call.args_json) {
219 Ok(a) => a.provider_id.trim().to_string(),
220 Err(e) => {
221 out.error = format!("invalid read_capability_doc args: {e}");
222 return out;
223 }
224 };
225 if provider_id.is_empty() {
226 out.error = "read_capability_doc: provider_id is required".to_string();
227 return out;
228 }
229 match atlas
230 .query_capabilities(&provider_id, "", atlas_pb::Transport::Unspecified)
231 .await
232 {
233 Ok(providers) => match providers.iter().find(|p| p.id == provider_id) {
234 Some(p) => {
235 let doc = render_provider_doc(p);
236 if doc.is_empty() {
237 out.error = format!("provider '{provider_id}' published no documentation");
238 } else {
239 out.success = true;
240 out.output = doc;
241 }
242 }
243 None => {
244 out.error = format!("no provider '{provider_id}' registered in atlas");
245 }
246 },
247 Err(e) => {
248 out.error = format!("atlas query for '{provider_id}' failed: {e}");
249 }
250 }
251 out
252}
253
254fn render_provider_doc(provider: &atlas_pb::CapabilityProvider) -> String {
265 let mut doc = String::new();
266 let manual = provider.capability_md.trim();
267 if !manual.is_empty() {
268 doc.push_str(manual);
269 doc.push('\n');
270 }
271 for cap in &provider.capabilities {
272 let description = cap.description.trim();
273 if description.is_empty() {
274 continue;
275 }
276 doc.push_str(&format!("\n## {}\n\n{}\n", cap.contract_id, description));
277 }
278 doc
279}
280
281#[derive(Deserialize)]
285struct ReadArgs {
286 path: String,
288}
289#[derive(Deserialize)]
291struct WriteArgs {
292 path: String,
294 content: String,
296}
297#[derive(Deserialize)]
299struct PatchArgs {
300 path: String,
302 old: String,
304 new: String,
306}
307#[derive(Deserialize)]
309struct ListArgs {
310 path: Option<String>,
312}
313#[derive(Deserialize)]
315struct CmdArgs {
316 command: String,
318}
319
320fn read_file(args: &str) -> anyhow::Result<String> {
321 let a: ReadArgs = serde_json::from_str(args)?;
322 let path = safe_resolve(&a.path)?;
323 if std::fs::metadata(&path)?.len() > crate::output_view::inline_bytes() as u64 {
324 let mut reference = crate::output_view::describe(&path)?;
326 reference["note"] = "Too long to inline. Search this file with run_command (rg -n, or \
327 grep -n -F), then read the matching lines with sed -n."
328 .into();
329 return Ok(reference.to_string());
330 }
331 Ok(std::fs::read_to_string(path)?)
332}
333
334fn write_file(args: &str) -> anyhow::Result<String> {
335 let a: WriteArgs = serde_json::from_str(args)?;
336 let path = safe_resolve(&a.path)?;
337 if let Some(parent) = path.parent() {
338 std::fs::create_dir_all(parent).ok();
339 }
340 std::fs::write(&path, &a.content)?;
341 Ok(format!(
342 "wrote {} bytes to {}",
343 a.content.len(),
344 path.display()
345 ))
346}
347
348fn patch_file(args: &str) -> anyhow::Result<String> {
349 let a: PatchArgs = serde_json::from_str(args)?;
351 let path = safe_resolve(&a.path)?;
352 let content = std::fs::read_to_string(&path)?;
353 if !content.contains(&a.old) {
354 anyhow::bail!("old string not found in file");
355 }
356 std::fs::write(&path, content.replacen(&a.old, &a.new, 1))?;
357 Ok(format!("patched {}", path.display()))
358}
359
360fn list_dir(args: &str) -> anyhow::Result<String> {
361 let a: ListArgs = serde_json::from_str(args)?;
362 let dir = a.path.as_deref().unwrap_or(".");
363 let resolved = safe_resolve(dir)?;
364 let mut items: Vec<String> = std::fs::read_dir(resolved)?
365 .flatten()
366 .map(|e| {
367 let ft = e
368 .file_type()
369 .map(|t| if t.is_dir() { "dir" } else { "file" })
370 .unwrap_or("?");
371 format!("{} {}", ft, e.file_name().to_string_lossy())
372 })
373 .collect();
374 items.sort();
375 Ok(items.join("\n"))
376}
377
378const MAX_COMMAND_LEN: usize = 8192;
380const COMMAND_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(120);
382async fn run_command(args: &str, runtime: &PlanRuntime, plan_id: &str) -> anyhow::Result<String> {
383 let dir = crate::output_view::output_dir().map_err(|error| {
384 anyhow::anyhow!("command not started: the temporary directory is unusable: {error}")
385 })?;
386 run_command_in(
387 args,
388 runtime,
389 plan_id,
390 &dir,
391 crate::output_view::inline_bytes(),
392 )
393 .await
394}
395
396async fn run_command_in(
400 args: &str,
401 runtime: &PlanRuntime,
402 plan_id: &str,
403 dir: &Path,
404 inline: usize,
405) -> anyhow::Result<String> {
406 let a: CmdArgs = serde_json::from_str(args)?;
407 if a.command.len() > MAX_COMMAND_LEN {
408 anyhow::bail!(
409 "command too long ({} bytes, max {})",
410 a.command.len(),
411 MAX_COMMAND_LEN
412 );
413 }
414 if runtime.is_cancelled(plan_id).await {
415 anyhow::bail!("command canceled before spawn");
416 }
417
418 let (stdout_path, stdout_file) = crate::output_view::create(dir)?;
419 let (stderr_path, stderr_file) = crate::output_view::create(dir)?;
420 let paths = [stdout_path.as_path(), stderr_path.as_path()];
421 use std::process::Stdio;
422 let mut command = tokio::process::Command::new("bash");
423 command
424 .arg("-c")
425 .arg(&a.command)
426 .stdin(Stdio::null())
427 .stdout(Stdio::piped())
428 .stderr(Stdio::piped())
429 .kill_on_drop(true)
430 .process_group(0);
431 let mut child = match command.spawn() {
432 Ok(child) => child,
433 Err(error) => {
434 paths
435 .iter()
436 .for_each(|path| drop(std::fs::remove_file(path)));
437 anyhow::bail!("failed to execute command: {error}");
438 }
439 };
440 let pgid = child
441 .id()
442 .ok_or_else(|| anyhow::anyhow!("spawned command has no pid"))?;
443 let (stdout, stderr) = (child.stdout.take(), child.stderr.take());
444 let output = async move {
445 let (stdout, stderr, status) = tokio::join!(
446 spool(stdout, stdout_file),
447 spool(stderr, stderr_file),
448 child.wait()
449 );
450 std::io::Result::Ok((stdout?.or(stderr?), status?))
451 };
452 tokio::pin!(output);
453
454 enum StopReason {
455 Canceled,
456 Timeout,
457 }
458 let canceled = async {
459 loop {
460 if runtime.is_cancelled(plan_id).await {
461 break;
462 }
463 tokio::time::sleep(std::time::Duration::from_millis(50)).await;
464 }
465 };
466 tokio::pin!(canceled);
467 let deadline = tokio::time::sleep(COMMAND_TIMEOUT);
468 tokio::pin!(deadline);
469
470 let stop_reason = tokio::select! {
471 result = &mut output => {
472 let (failure, status) =
473 result.map_err(|e| anyhow::anyhow!("failed to execute command: {e}"))?;
474 return Ok(command_result(&paths, status.code(), failure, inline)?);
475 }
476 _ = &mut canceled => StopReason::Canceled,
477 _ = &mut deadline => StopReason::Timeout,
478 };
479
480 terminate_command_group(pgid, nix::sys::signal::Signal::SIGTERM);
481 let finished = match tokio::time::timeout(std::time::Duration::from_secs(2), &mut output).await
482 {
483 Ok(result) => result,
484 Err(_) => {
485 terminate_command_group(pgid, nix::sys::signal::Signal::SIGKILL);
486 output.await
487 }
488 };
489 let reason = match stop_reason {
490 StopReason::Canceled => "command canceled".to_owned(),
491 StopReason::Timeout => format!("command timed out after {}s", COMMAND_TIMEOUT.as_secs()),
492 };
493 let failure = finished.ok().and_then(|(failure, _)| failure);
494 anyhow::bail!(
495 "{reason}; output written before it stopped:\n{}",
496 command_result(&paths, None, failure, inline)?
497 )
498}
499
500async fn spool(
504 stream: Option<impl tokio::io::AsyncRead + Unpin>,
505 file: std::fs::File,
506) -> std::io::Result<Option<std::io::Error>> {
507 use tokio::io::{AsyncReadExt, AsyncWriteExt};
508 let mut file = tokio::fs::File::from_std(file);
509 let mut failure = None;
510 if let Some(mut stream) = stream {
511 let mut buffer = vec![0; 64 * 1024];
512 loop {
513 let count = stream.read(&mut buffer).await?;
514 if count == 0 {
515 break;
516 }
517 if failure.is_none() {
518 failure = file.write_all(&buffer[..count]).await.err();
519 }
520 }
521 }
522 Ok(failure.or(file.flush().await.err()))
523}
524
525fn command_result(
529 paths: &[&Path; 2],
530 code: Option<i32>,
531 failure: Option<std::io::Error>,
532 inline: usize,
533) -> std::io::Result<String> {
534 let sizes = paths.map(|path| std::fs::metadata(path).map_or(0, |metadata| metadata.len()));
535 if failure.is_none() && sizes.iter().sum::<u64>() <= inline as u64 {
536 let text =
537 format_command_output(&std::fs::read(paths[0])?, &std::fs::read(paths[1])?, code);
538 paths
539 .iter()
540 .for_each(|path| drop(std::fs::remove_file(path)));
541 return Ok(text);
542 }
543 let mut reference = serde_json::json!({
544 "observed_unix": crate::output_view::now_unix(),
545 "exit_code": code,
546 "note": crate::output_view::SEARCH_NOTE,
547 });
548 if let Some(error) = failure {
549 robonix_scribe::warn!("[executor] command output is incomplete: {error}");
550 reference["storage_error"] = error.to_string().into();
551 reference["note"] = crate::output_view::STORAGE_NOTE.into();
552 }
553 for (name, path, size) in [
554 ("stdout", paths[0], sizes[0]),
555 ("stderr", paths[1], sizes[1]),
556 ] {
557 if size == 0 {
558 let _ = std::fs::remove_file(path);
559 } else {
560 reference[name] = crate::output_view::describe(path)?;
561 }
562 }
563 Ok(reference.to_string())
564}
565
566fn terminate_command_group(pgid: u32, signal: nix::sys::signal::Signal) {
567 use nix::sys::signal::killpg;
568 use nix::unistd::Pid;
569 match killpg(Pid::from_raw(pgid as i32), signal) {
570 Ok(()) | Err(nix::errno::Errno::ESRCH) => {}
571 Err(error) => robonix_scribe::warn!(
572 "[executor] signal {:?} command pgid {} failed: {}",
573 signal,
574 pgid,
575 error
576 ),
577 }
578}
579
580fn format_command_output(stdout: &[u8], stderr: &[u8], code: Option<i32>) -> String {
583 let mut result = String::from_utf8_lossy(stdout).into_owned();
584 if !stderr.is_empty() {
585 if !result.is_empty() && !result.ends_with('\n') {
586 result.push('\n');
587 }
588 result.push_str("stderr: ");
589 result.push_str(&String::from_utf8_lossy(stderr));
590 }
591 if !result.is_empty() && !result.ends_with('\n') {
592 result.push('\n');
593 }
594 result.push_str(&format!("exit code: {}", code.unwrap_or(-1)));
595 result
596}
597
598#[cfg(test)]
599mod tests {
600 use super::*;
601
602 async fn run(command: &str, dir: &Path, inline: usize) -> anyhow::Result<String> {
603 let args = serde_json::json!({ "command": command }).to_string();
604 run_command_in(&args, &PlanRuntime::default(), "test", dir, inline).await
605 }
606
607 #[tokio::test]
608 async fn short_output_is_inline_with_its_exit_code() {
609 let dir = crate::output_view::tests::TempDir::new();
610 let no_match = run("printf 'alpha\\n' | grep -n -F -e absent", &dir.0, 1024).await;
611 assert_eq!(no_match.unwrap(), "exit code: 1");
612 let failed = run("printf 'diagnostic\\n' >&2; exit 2", &dir.0, 1024)
613 .await
614 .unwrap();
615 assert_eq!(failed, "stderr: diagnostic\nexit code: 2");
616 assert_eq!(std::fs::read_dir(&dir.0).unwrap().count(), 0);
617 }
618
619 #[tokio::test]
620 async fn long_output_is_written_to_disk_whole_and_the_command_runs_once() {
621 let dir = crate::output_view::tests::TempDir::new();
622 let count = dir.0.join("count");
623 let command = format!(
624 "echo run >> '{}'; head -c 20000000 /dev/zero | tr '\\0' x; echo TAIL-972",
625 count.display()
626 );
627 let reference: serde_json::Value =
628 serde_json::from_str(&run(&command, &dir.0, 1024).await.unwrap()).unwrap();
629 assert_eq!(reference["exit_code"], 0);
630 assert!(reference.get("stderr").is_none());
631 assert_eq!(reference["stdout"]["bytes"], 20_000_009);
632 let saved = std::fs::read(reference["stdout"]["file"].as_str().unwrap()).unwrap();
633 assert_eq!(saved.len(), 20_000_009);
634 assert!(saved.ends_with(b"xTAIL-972\n"));
635 assert_eq!(std::fs::read_to_string(count).unwrap(), "run\n");
636 }
637
638 #[cfg(target_os = "linux")]
639 #[tokio::test]
640 async fn a_full_disk_is_reported_and_the_stream_is_still_drained() {
641 let full = std::fs::OpenOptions::new()
642 .write(true)
643 .open("/dev/full")
644 .unwrap();
645 let data = vec![b'x'; 300_000];
646 let failure = spool(Some(&data[..]), full).await.unwrap().unwrap();
647 assert_eq!(failure.raw_os_error(), Some(28));
648 }
649
650 #[test]
651 fn storage_failure_keeps_what_was_written_and_tells_the_model() {
652 let dir = crate::output_view::tests::TempDir::new();
653 let (stdout, stderr) = (dir.0.join("out"), dir.0.join("err"));
654 std::fs::write(&stdout, "partial\n").unwrap();
655 std::fs::write(&stderr, "").unwrap();
656 let text = command_result(
657 &[stdout.as_path(), stderr.as_path()],
658 Some(0),
659 Some(std::io::Error::from_raw_os_error(28)),
660 1024,
661 )
662 .unwrap();
663 let reference: serde_json::Value = serde_json::from_str(&text).unwrap();
664 assert!(!reference["storage_error"].as_str().unwrap().is_empty());
665 assert_eq!(reference["stdout"]["bytes"], 8);
666 assert!(stdout.exists());
667 }
668
669 fn isolated_workspace_test(name: &str) -> bool {
672 if std::env::var("RBNX_TEST_WORKSPACE_CASE").as_deref() == Ok(name) {
673 return false;
674 }
675 let status = std::process::Command::new(std::env::current_exe().unwrap())
676 .args([
677 "--exact",
678 &format!("dispatch::builtin::tests::{name}"),
679 "--nocapture",
680 ])
681 .env("RBNX_TEST_WORKSPACE_CASE", name)
682 .status()
683 .unwrap();
684 assert!(status.success(), "isolated workspace test failed: {name}");
685 true
686 }
687
688 #[test]
690 fn a_provider_without_a_manual_still_documents_its_capabilities() {
691 let provider = atlas_pb::CapabilityProvider {
696 id: "memgraph".to_string(),
697 capability_md: String::new(),
698 capabilities: vec![atlas_pb::Capability {
699 contract_id: "robonix/service/memory/hybrid_search".to_string(),
700 description: "Search memory.\n\nRequest JSON: {...}".to_string(),
701 ..Default::default()
702 }],
703 ..Default::default()
704 };
705 let doc = render_provider_doc(&provider);
706 assert!(doc.contains("robonix/service/memory/hybrid_search"));
707 assert!(doc.contains("Request JSON: {...}"));
708 }
709
710 #[test]
711 fn a_provider_with_neither_manual_nor_descriptions_documents_nothing() {
712 let provider = atlas_pb::CapabilityProvider {
713 id: "bare".to_string(),
714 ..Default::default()
715 };
716 assert!(render_provider_doc(&provider).is_empty());
717 }
718
719 #[test]
720 fn path_traversal_dotdot_is_rejected() {
721 if isolated_workspace_test("path_traversal_dotdot_is_rejected") {
722 return;
723 }
724 let tmp = std::env::temp_dir().join("rbnx_test_ws");
726 std::fs::create_dir_all(&tmp).unwrap();
727
728 let result = safe_resolve_in(&tmp, "../../../etc/passwd");
730 assert!(
731 result.is_err(),
732 "path traversal with ../../../etc/passwd should fail"
733 );
734 let err_msg = result.unwrap_err().to_string();
735 assert!(
736 err_msg.contains("path traversal denied") || err_msg.contains("does not exist"),
737 "error should mention traversal or nonexistent path, got: {err_msg}"
738 );
739 }
740
741 #[test]
743 fn path_traversal_absolute_outside_workspace_is_rejected() {
744 if isolated_workspace_test("path_traversal_absolute_outside_workspace_is_rejected") {
745 return;
746 }
747 let tmp = std::env::temp_dir().join("rbnx_test_ws2");
748 std::fs::create_dir_all(&tmp).unwrap();
749
750 let result = safe_resolve_in(&tmp, "/etc/hostname");
752 assert!(
753 result.is_err(),
754 "absolute path /etc/hostname outside workspace should fail"
755 );
756 let err_msg = result.unwrap_err().to_string();
757 assert!(
758 err_msg.contains("path traversal denied"),
759 "error should mention traversal, got: {err_msg}"
760 );
761 }
762
763 #[test]
765 fn path_resolve_within_workspace_is_allowed() {
766 if isolated_workspace_test("path_resolve_within_workspace_is_allowed") {
767 return;
768 }
769 let tmp = std::env::temp_dir().join("rbnx_test_ws3");
770 std::fs::create_dir_all(&tmp).unwrap();
771 let test_file = tmp.join("allowed.txt");
773 std::fs::write(&test_file, "hello").unwrap();
774
775 let result = safe_resolve_in(&tmp, "allowed.txt");
776 assert!(
777 result.is_ok(),
778 "path within workspace should be allowed: {:?}",
779 result.err()
780 );
781
782 let _ = std::fs::remove_file(&test_file);
784 let _ = std::fs::remove_dir(&tmp);
785 }
786}