Skip to content

Craft Anything: understand how any software works, and craft your own.

Rust

Keep build tools and approvals from following links out of the project (#623)

Ole Bohmbach472d061921d1
diff --git a/crates/engine/src/tools/build_tools.rs b/crates/engine/src/tools/build_tools.rs
index 833c82a9..98a62d0a 100644
--- a/crates/engine/src/tools/build_tools.rs
+++ b/crates/engine/src/tools/build_tools.rs
@@ -6,7 +6,7 @@
//! dev servers are refused, anything else asks the person (or goes ahead in Auto mode, except
//! what's never done unasked). Ids follow docs/tool-ids.md.
-use super::interaction_tools::{approve, inbox, inside, resolve, workspace_of};
+use super::interaction_tools::{approve, inbox, inside, really_inside, resolve, workspace_of};
use crate::tool::{Ctx, Effects, Requires, ToolOutput, ToolSpec, Toolset, parse_params, schema_of};
use crate::workspace::Workspace;
use craft_anything_evidence::{ErrorCode, ToolError};
@@ -193,16 +193,17 @@ fn workspace(ctx: &Ctx<'_>) -> Result<Workspace, ToolError> {
})
}
-/// `rel` inside the project folder, or an error (no escaping with `..` or an absolute path).
+/// `rel` inside the project folder, or an error (no escaping with `..`, an absolute path or a
+/// link that leads out of the project).
/// Models often write the project's folders from the root (`/app/src/main.rs`): a path like that
/// whose first folder the project has is read inside the project, where it was meant (#24).
fn in_project(ws: &Workspace, rel: &str) -> Result<PathBuf, ToolError> {
let from_root = rel.trim_start_matches(['/', '\\']);
let names_a_folder = from_root != rel
&& from_root.split(['/', '\\']).next().is_some_and(|first| !first.is_empty() && (ws.root.join(first).is_dir() || ws.root.join(first) == ws.app_dir()));
- [Some(rel), names_a_folder.then_some(from_root)].into_iter().flatten().find_map(|r| resolve(&ws.root, r).filter(|p| inside(&ws.root, p))).ok_or_else(|| {
- ToolError::invalid(format!("{rel} is outside the project.")).with_remediation("Use a path relative to the project folder, like app/src/main.rs.")
- })
+ [Some(rel), names_a_folder.then_some(from_root)].into_iter().flatten().find_map(|r| resolve(&ws.root, r).filter(|p| really_inside(&ws.root, p))).ok_or_else(
+ || ToolError::invalid(format!("{rel} is outside the project.")).with_remediation("Use a path relative to the project folder, like app/src/main.rs."),
+ )
}
fn shown(ws: &Workspace, p: &Path) -> String {
@@ -232,7 +233,10 @@ fn build_files_list(ctx: &mut Ctx<'_>, params: Value) -> Result<ToolOutput, Tool
}
let path = e.path();
let name = e.file_name().to_string_lossy().into_owned();
- if path.is_dir() {
+ // A link is listed but never followed: it may lead out of the project.
+ if e.file_type().is_ok_and(|t| t.is_symlink()) {
+ entries.push(json!({"path": shown(&ws, &path), "link": true}));
+ } else if path.is_dir() {
entries.push(json!({"path": format!("{}/", shown(&ws, &path))}));
if d + 1 < depth && !SKIP.contains(&name.as_str()) {
stack.push((path, d + 1));
@@ -393,6 +397,42 @@ mod tests {
assert!(call(&e, "build_file_write", json!({"path": "../outside.txt", "content": "x"})).is_err());
}
+ /// A link to a folder; false where this system won't let a test make one.
+ fn link_dir(target: &Path, link: &Path) -> bool {
+ #[cfg(unix)]
+ let made = std::os::unix::fs::symlink(target, link);
+ #[cfg(windows)]
+ let made = std::os::windows::fs::symlink_dir(target, link);
+ made.is_ok()
+ }
+
+ #[test]
+ fn a_link_in_the_project_cannot_lead_outside_it() {
+ let (_d, ws, e) = building();
+ let outside = tempfile::tempdir().unwrap();
+ std::fs::write(outside.path().join("secret.txt"), "secret").unwrap();
+ std::fs::create_dir_all(ws.app_dir().join("src")).unwrap();
+ if !link_dir(outside.path(), &ws.app_dir().join("out")) {
+ eprintln!("skipped: this system won't make links for tests");
+ return;
+ }
+ assert!(call(&e, "build_file_read", json!({"path": "app/out/secret.txt"})).is_err());
+ assert!(call(&e, "build_file_edit", json!({"path": "app/out/secret.txt", "old_text": "secret", "new_text": "x"})).is_err());
+ assert!(call(&e, "build_file_write", json!({"path": "app/out/new.txt", "content": "x"})).is_err());
+ assert!(call(&e, "build_file_write", json!({"path": "app/out/deeper/new.txt", "content": "x"})).is_err());
+ assert_eq!(std::fs::read_to_string(outside.path().join("secret.txt")).unwrap(), "secret");
+ assert!(!outside.path().join("new.txt").exists() && !outside.path().join("deeper").exists());
+ // Listing shows the link but doesn't walk into it.
+ let list = call(&e, "build_files_list", json!({})).unwrap();
+ assert!(list["entries"].as_array().unwrap().iter().any(|x| x["path"] == "app/out" && x["link"] == true), "{list}");
+ assert!(!list.to_string().contains("secret.txt"), "{list}");
+ assert!(call(&e, "build_files_list", json!({"path": "app/out"})).is_err());
+ // A link that stays inside the project still works.
+ assert!(link_dir(&ws.app_dir().join("src"), &ws.app_dir().join("alias")));
+ call(&e, "build_file_write", json!({"path": "app/alias/lib.rs", "content": "x"})).unwrap();
+ assert!(ws.app_dir().join("src/lib.rs").is_file());
+ }
+
/// #280: a line longer than a page left reading stuck at it, with nothing shown.
#[test]
fn a_line_longer_than_a_page_is_shown_cut() {
diff --git a/crates/engine/src/tools/interaction_tools.rs b/crates/engine/src/tools/interaction_tools.rs
index 24724255..796f651b 100644
--- a/crates/engine/src/tools/interaction_tools.rs
+++ b/crates/engine/src/tools/interaction_tools.rs
@@ -252,7 +252,33 @@ pub(crate) fn resolve(base: &Path, p: &str) -> Option<PathBuf> {
Some(out)
}
-pub(crate) use crate::workspace::inside;
+/// [`resolve`], with `..` applied where the system applies it when the path is opened. Linux and
+/// macOS follow a link before the `..` after it, so `app/link/../x` is beside the link's target,
+/// not `app/x`; Windows takes `..` off the text first. And as every system does, `..` at the root
+/// stays at the root (`/..` is `/`), where [`resolve`] gives up. For the checks that decide what a
+/// builder's own tools may open, which mustn't read giving up as "not protected".
+pub(crate) fn resolve_as_opened(base: &Path, p: &str) -> Option<PathBuf> {
+ let path = Path::new(p);
+ let joined = if path.is_absolute() { path.to_path_buf() } else { base.join(path) };
+ let mut out = PathBuf::new();
+ for c in joined.components() {
+ match c {
+ Component::ParentDir => {
+ if cfg!(unix) && out.symlink_metadata().is_ok() {
+ out = crate::workspace::real_path(&out)?;
+ }
+ if !out.pop() && !out.has_root() {
+ return None;
+ }
+ }
+ Component::CurDir => {}
+ other => out.push(other.as_os_str()),
+ }
+ }
+ Some(out)
+}
+
+pub(crate) use crate::workspace::{inside, may_reach, really_inside};
/// The program a command part starts (a leading quoted path keeps its spaces) and the rest.
fn program_of(part: &str) -> (&str, &str) {
@@ -341,8 +367,11 @@ pub fn decide(ws: Option<&Workspace>, tool: &str, input: &Value) -> Decision {
// approvals are answered), the manifest and the person's pictures stay out of reach,
// also when the app is the project folder itself.
let checks = ws.map(Workspace::checks_dir);
- match (&app, resolve(app.as_deref().unwrap_or(Path::new("/")), &target)) {
- (Some(app), Some(p)) if (inside(app, &p) || checks.as_ref().is_some_and(|c| inside(c, &p))) && !ws.is_some_and(|w| w.is_own_record(&p)) => {
+ match (&app, resolve_as_opened(app.as_deref().unwrap_or(Path::new("/")), &target)) {
+ // Followed through links, so a link in app/ can't lead a write out of it.
+ (Some(app), Some(p))
+ if (really_inside(app, &p) || checks.as_ref().is_some_and(|c| really_inside(c, &p))) && !ws.is_some_and(|w| w.is_own_record(&p)) =>
+ {
Decision::Allow
}
_ => Decision::Ask { title: format!("Change a file outside the project: {target}"), kind },
@@ -424,7 +453,8 @@ pub fn off_limits(ws: Option<&Workspace>, tool: &str, input: &Value) -> Option<S
crate::workspace::TargetRef::Local { path } => {
// The original and, when it's one file, the folder it sits in.
let root = if path.is_file() { path.parent().unwrap_or(path) } else { path.as_path() };
- let touches = |p: &str| !p.is_empty() && resolve(&ws.root, p).is_some_and(|p| inside(root, &p) && !inside(&ws.root, &p));
+ // Followed through links, so a link in the project to the original doesn't open it.
+ let touches = |p: &str| !p.is_empty() && resolve_as_opened(&ws.root, p).is_some_and(|p| may_reach(root, &p) && !really_inside(&ws.root, &p));
match tool {
"Read" | "Write" | "Edit" | "MultiEdit" => touches(&s("file_path")),
"NotebookRead" | "NotebookEdit" => touches(&s("notebook_path")),
@@ -489,8 +519,9 @@ pub fn never_unasked(ws: Option<&Workspace>, tool: &str, input: &Value) -> Optio
match tool {
"Write" | "Edit" | "MultiEdit" | "NotebookEdit" => {
let target = if tool == "NotebookEdit" { s("notebook_path") } else { s("file_path") };
- let p = resolve(ws.map(|w| w.root.clone()).as_deref().unwrap_or(Path::new("/")), &target)?;
- let system = SYSTEM_DIRS.iter().any(|d| inside(Path::new(d), &p));
+ let p = resolve_as_opened(ws.map(|w| w.root.clone()).as_deref().unwrap_or(Path::new("/")), &target)?;
+ // Followed through links: a link in app/ to a system folder is that folder.
+ let system = SYSTEM_DIRS.iter().any(|d| may_reach(Path::new(d), &p));
// The inbox (where answers are written), the manifest and the other records stay out of reach.
let ours = ws.is_some_and(|w| w.is_own_record(&p));
(system || ours).then(|| refuse("changes system files or Craft Anything's own records")).flatten()
@@ -671,6 +702,141 @@ mod tests {
assert!(matches!(decide(None, "Write", &json!({"file_path": "/tmp/x"})), Decision::Ask { .. }));
}
+ /// A link to a folder; false where this system won't let a test make one.
+ fn link_dir(target: &Path, link: &Path) -> bool {
+ #[cfg(unix)]
+ let made = std::os::unix::fs::symlink(target, link);
+ #[cfg(windows)]
+ let made = std::os::windows::fs::symlink_dir(target, link);
+ made.is_ok()
+ }
+
+ #[test]
+ fn a_write_through_a_link_out_of_app_is_asked() {
+ let (_d, w) = ws();
+ let outside = tempfile::tempdir().unwrap();
+ std::fs::create_dir_all(w.app_dir()).unwrap();
+ let link = w.app_dir().join("out");
+ if !link_dir(outside.path(), &link) {
+ eprintln!("skipped: this system won't make links for tests");
+ return;
+ }
+ let through = |name: &str| json!({"file_path": link.join(name).display().to_string()});
+ assert!(matches!(decide(Some(&w), "Write", &through("x.txt")), Decision::Ask { .. }));
+ assert!(matches!(decide(Some(&w), "Edit", &through("new/y.txt")), Decision::Ask { .. }));
+ assert_eq!(decide(Some(&w), "Write", &json!({"file_path": w.app_dir().join("ok.txt").display().to_string()})), Decision::Allow);
+ assert_eq!(never_unasked(Some(&w), "Write", &through("x.txt")), None, "an ordinary folder may be asked about");
+ }
+
+ #[test]
+ fn dot_dot_after_a_link_is_applied_where_the_system_applies_it() {
+ let (_d, w) = ws();
+ let outside = tempfile::tempdir().unwrap();
+ std::fs::create_dir_all(outside.path().join("t")).unwrap();
+ std::fs::create_dir_all(w.app_dir()).unwrap();
+ if !link_dir(&outside.path().join("t"), &w.app_dir().join("out")) {
+ eprintln!("skipped: this system won't make links for tests");
+ return;
+ }
+ let raw = format!("{}/out/../x.txt", w.app_dir().display());
+ let opened = resolve_as_opened(Path::new("/"), &raw).unwrap();
+ let write = json!({"file_path": raw});
+ // Where the system really puts it is where the checks must look.
+ std::fs::write(&raw, "x").unwrap();
+ assert!(opened.is_file(), "{} isn't where the write landed", opened.display());
+ if cfg!(unix) {
+ // Opened, this is outside/x.txt: beside the link's target, outside the project.
+ assert_eq!(opened, crate::workspace::real_path(outside.path()).unwrap().join("x.txt"));
+ assert!(matches!(decide(Some(&w), "Write", &write), Decision::Ask { .. }));
+ } else {
+ // Windows takes `..` off the text before it follows anything: app/x.txt.
+ assert_eq!(opened, resolve(Path::new("/"), &raw).unwrap());
+ assert!(inside(&w.app_dir(), &opened));
+ assert_eq!(decide(Some(&w), "Write", &write), Decision::Allow);
+ }
+ }
+
+ /// A project folder behind a link (macOS's temp folders are) is still the project, also when
+ /// a path in it uses `..` and so comes back resolved.
+ #[test]
+ fn a_project_behind_a_link_is_still_the_project() {
+ let dir = tempfile::tempdir().unwrap();
+ let real = dir.path().join("real");
+ std::fs::create_dir_all(&real).unwrap();
+ let linked = dir.path().join("linked");
+ if !link_dir(&real, &linked) {
+ eprintln!("skipped: this system won't make links for tests");
+ return;
+ }
+ let w = Workspace::create(&linked, "t", "r", TargetRef::None).unwrap();
+ std::fs::create_dir_all(w.app_dir().join("src")).unwrap();
+ let write = |p: String| decide(Some(&w), "Write", &json!({"file_path": p}));
+ assert_eq!(write(format!("{}/src/../main.rs", w.app_dir().display())), Decision::Allow);
+ assert_eq!(write(w.app_dir().join("main.rs").display().to_string()), Decision::Allow);
+ assert!(matches!(write(format!("{}/../../outside.txt", w.app_dir().display())), Decision::Ask { .. }));
+ }
+
+ #[test]
+ fn dot_dot_at_the_root_stays_at_the_root() {
+ let (_d, w) = ws();
+ std::fs::create_dir_all(w.app_dir()).unwrap();
+ // On the drive the protected folders are on, wherever the temp folder is.
+ let (start, system) = if cfg!(windows) { ("C:/Users/a/b", "Windows") } else { ("/tmp/a/b", "etc") };
+ // More `..` than the path is deep: every system stops at the root.
+ let climbed = format!("{start}/{}{system}/x.conf", "../".repeat(64));
+ let opened = resolve_as_opened(Path::new("/"), &climbed).unwrap();
+ assert!(opened.ends_with(format!("{system}/x.conf")) && opened.components().count() <= 4, "{}", opened.display());
+ assert!(never_unasked(Some(&w), "Write", &json!({"file_path": climbed})).is_some());
+
+ // A link to the root, then `..`, is still the root on Linux and macOS.
+ let root = w.app_dir().join("root");
+ if cfg!(unix) && link_dir(Path::new("/"), &root) {
+ let through = |rest: &str| json!({"file_path": format!("{}/../{rest}", root.display())});
+ assert!(never_unasked(Some(&w), "Write", &through("etc/x.conf")).is_some());
+
+ let dir = tempfile::tempdir().unwrap();
+ let game = dir.path().join("Some Game");
+ std::fs::create_dir_all(&game).unwrap();
+ let cw = Workspace::create(&dir.path().join("projects"), "g", "Recreate this game", TargetRef::Local { path: game.clone() }).unwrap();
+ std::fs::create_dir_all(cw.app_dir()).unwrap();
+ let croot = cw.app_dir().join("root");
+ assert!(link_dir(Path::new("/"), &croot));
+ let real_game = crate::workspace::real_path(&game).unwrap();
+ let rest = real_game.to_string_lossy().trim_start_matches('/').to_string();
+ let read = json!({"file_path": format!("{}/../{rest}/data.ini", croot.display())});
+ assert!(off_limits(Some(&cw), "Read", &read).is_some());
+ }
+ }
+
+ /// Auto mode approves what the policy asks about, so the lines it never crosses must follow
+ /// links too: a link in app/ to a system folder, or (Clean room) to the original.
+ #[test]
+ fn auto_mode_and_clean_room_limits_follow_links() {
+ let (_d, w) = ws();
+ std::fs::create_dir_all(w.app_dir()).unwrap();
+ let system = if cfg!(windows) { "C:/Windows" } else { "/etc" };
+ let sys = w.app_dir().join("sys");
+ if !link_dir(Path::new(system), &sys) {
+ eprintln!("skipped: this system won't make links for tests");
+ return;
+ }
+ let write = |p: &Path| json!({"file_path": p.display().to_string()});
+ assert!(never_unasked(Some(&w), "Write", &write(&sys.join("hosts"))).is_some());
+ assert!(never_unasked(Some(&w), "Edit", &write(&sys.join("new/x.conf"))).is_some());
+ assert_eq!(never_unasked(Some(&w), "Write", &write(&w.app_dir().join("main.rs"))), None);
+
+ let dir = tempfile::tempdir().unwrap();
+ let game = dir.path().join("Some Game");
+ std::fs::create_dir_all(&game).unwrap();
+ let cw = Workspace::create(&dir.path().join("projects"), "g", "Recreate this game", TargetRef::Local { path: game.clone() }).unwrap();
+ std::fs::create_dir_all(cw.app_dir()).unwrap();
+ let orig = cw.app_dir().join("orig");
+ assert!(link_dir(&game, &orig));
+ assert!(off_limits(Some(&cw), "Read", &write(&orig.join("data.ini"))).is_some());
+ assert!(off_limits(Some(&cw), "Write", &write(&orig.join("new.txt"))).is_some());
+ assert_eq!(off_limits(Some(&cw), "Read", &write(&cw.app_dir().join("main.rs"))), None);
+ }
+
#[test]
fn commands() {
let (_d, w) = ws();
diff --git a/crates/engine/src/workspace.rs b/crates/engine/src/workspace.rs
index e03bc075..1b3cbbfb 100644
--- a/crates/engine/src/workspace.rs
+++ b/crates/engine/src/workspace.rs
@@ -811,7 +811,9 @@ impl Workspace {
/// the person's pictures…), which the builder never changes, even when the app is the
/// project folder itself. checks/ isn't one: the builder keeps its notes there.
pub fn is_own_record(&self, p: &Path) -> bool {
- OWN_NAMES.iter().filter(|n| **n != "checks").any(|n| inside(&self.root.join(n), p))
+ let own = |root: &Path, p: &Path| OWN_NAMES.iter().filter(|n| **n != "checks").any(|n| inside(&root.join(n), p));
+ // Also where a link would really take it.
+ own(&self.root, p) || matches!((real_path(&self.root), real_path(p)), (Some(root), Some(p)) if own(&root, &p))
}
/// Separate from capture/, which a website study replaces.
pub fn reference_dir(&self) -> PathBuf {
@@ -951,6 +953,40 @@ pub fn inside(dir: &Path, p: &Path) -> bool {
}
}
+/// Where `p` really is: its deepest part that exists, with every link in it followed, then the
+/// rest as written (parts that don't exist yet can't be links). `None` when an existing part
+/// can't be followed, such as a link to nothing, since writing there would follow it.
+pub fn real_path(p: &Path) -> Option<PathBuf> {
+ let mut existing = p;
+ let mut missing = Vec::new();
+ while existing.symlink_metadata().is_err() {
+ missing.push(existing.file_name()?);
+ existing = existing.parent()?;
+ }
+ let mut real = std::fs::canonicalize(existing).ok()?;
+ real.extend(missing.iter().rev());
+ Some(real)
+}
+
+/// [`inside`], after following links: `p` is inside `dir` where the file system really puts
+/// them both, so a link inside `dir` can't lead out of it. Only the real paths are compared: `p`
+/// may already be partly resolved (`..` after a link) while `dir` is as written, and a `dir`
+/// that sits behind a link (macOS's `/var` → `/private/var`) is still the same folder.
+pub fn really_inside(dir: &Path, p: &Path) -> bool {
+ matches!((real_path(dir), real_path(p)), (Some(d), Some(p)) if inside(&d, &p))
+}
+
+/// The other side of [`really_inside`], for places that must be kept out of: `p` may land in
+/// `dir` as written, once links are followed (also links in `dir`'s own path, such as macOS's
+/// `/etc` → `/private/etc`), or because a link in `p` can't be followed to tell.
+pub fn may_reach(dir: &Path, p: &Path) -> bool {
+ inside(dir, p)
+ || match real_path(p) {
+ Some(real) => inside(dir, &real) || real_path(dir).is_some_and(|d| inside(&d, &real)),
+ None => true,
+ }
+}
+
/// How many of a picked folder's names are kept for the builder.
pub const START_FILES_SHOWN: usize = 40;