Skip to content

armgit / kwant

Public Imported from GitHub
0

Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.

0.8.0 F backend: walk limits, git-spawn proof, forget a folder, read-only hooks, one-transaction brief move (#462)

Oleksandr Ivanchenkobe2691e48cf2
diff --git a/docs/agents-in-vm.md b/docs/agents-in-vm.md
index 1a0f7f2e..bff98967 100644
--- a/docs/agents-in-vm.md
+++ b/docs/agents-in-vm.md
@@ -38,7 +38,24 @@ text, can't do these things while it runs inside the VM:
- kwnt's own git calls run with `GIT_CONFIG_NOSYSTEM=1 -c core.fsmonitor=false
-c core.hooksPath=/dev/null -c core.pager=cat`;
- kwnt reads bot folders (checkpoints, restore, team discovery) without following symlinks,
- one folder at a time, so a link or a swapped folder can't point a read outside.
+ one folder at a time, so a link or a swapped folder can't point a read outside. A checkpoint
+ walk stops at 64 folders deep and at an entry limit, and a restore never deletes files the
+ walk didn't reach.
+- **Plant a git hook.** When the folder is a git repository (a real `.git` folder, not a link or
+ a `.git` file), an empty read-only folder that only kwnt writes is mounted over its
+ `.git/hooks` in the container: `git commit`, branches and the rest still work, but no hook can
+ be added or changed. The mount's source is never a path inside the bot's folder, so a link the
+ bot swaps in can't get a folder from your computer mounted. Your own hooks don't run for
+ commits the bot makes inside the container; they still run for yours. A `.git/hooks` that is a
+ link or a file is left as it is (kwnt's log says so).
+
+**Forgetting a folder.** Only you can take a folder off the record, in Settings (`GET` and
+`POST /api/isolated-folders/forget`; a bot gets 403). The list shows which files a program
+started there would load (`.mcp.json`, `.envrc`, `.claude/settings*.json`, `.codex`, `.grok`,
+`.git/config`, `.git/hooks`), so you can look at them first. A `.git` that is a file or a link,
+or a `.git/hooks` that isn't a real folder, is listed too (`.git (file)`, `.git/hooks -> link`):
+git then loads hooks from somewhere the list doesn't show. Once forgotten, kwnt trusts the
+folder as before.
## What it doesn't protect against
@@ -49,8 +66,13 @@ text, can't do these things while it runs inside the VM:
each bot's approval settings, so a bot that may run commands without asking still can.
- **kwnt's built-in shell.** `execute_shell` runs in kwnt's own executor container, which keeps
its network. Isolating Claude doesn't change it.
-- **Files you run later.** A bot can still write `.git/hooks`, `.envrc`, package scripts or editor
- tasks in its folder. They run if **you** use them on your own computer.
+- **Files you run later.** A bot can still write `.envrc`, package scripts or editor tasks in its
+ folder. They run if **you** use them on your own computer.
+- **Other ways around the read-only hooks.** `.git/config` stays writable (a bot needs `git remote`
+ and branch tracking), so a bot can point `core.hooksPath` at a folder it writes, or rename
+ `.git` and make a new one. kwnt's own git calls never run hooks; your own `git` there would. A
+ repository the bot creates during a reply gets read-only hooks only from its next reply. The
+ forget list shows `.git/config`, any hooks, and a `.git` file or link so you can check them.
- **Codex, Grok, and Claude API-key or Custom accounts.** They run on this computer as before.
- **A Docker or kernel escape.** The container drops every capability, runs as your user id with
a read-only root and no network, but it shares the kernel.
@@ -117,5 +139,7 @@ this computer.
(`folder_rule.rs`) and the chat notices (`notice.rs`).
- `src/sandbox/safe_fs.rs`: the no-follow folder reader.
- `src/db/isolated_folders.rs`: the record of folders isolated replies used.
+- `src/server/isolated_folders_routes.rs`: the person's list and Forget
+ (`release-080/forget-folder-contract.md`).
- `docker/agent.Dockerfile`, `docker/agent-entry.sh`: the image (`kwnt-agent:v1-claude-<version>`).
- `proto/agents-in-vm/`: the Python spike, `gate0.sh` and the evidence it wrote.
diff --git a/src/db/dev_jira.rs b/src/db/dev_jira.rs
index 87646ce5..f7408caf 100644
--- a/src/db/dev_jira.rs
+++ b/src/db/dev_jira.rs
@@ -5,7 +5,8 @@
//!
//! `set_dev_ticket_state` is the one writer of `dev_tickets.state` (api.md §1.4): it refuses a
//! move the table below doesn't allow and logs every move it makes in `dev_ticket_events`.
-//! `tickets::store::set_state` wraps it to send `dev_ticket` on the event stream.
+//! `tickets::store::set_state` wraps it to send `dev_ticket` on the event stream. The ticket's brief
+//! row (`dev_ticket_briefs.state`) is moved in the same transaction.
use super::{Database, DbError};
use chrono::{DateTime, Utc};
@@ -834,6 +835,10 @@ impl Database {
.bind(now)
.execute(&mut *tx)
.await?;
+ // The brief row's `state` mirrors the card (D2). Same transaction: if the mirror fails the
+ // move is rolled back, so the brief page and Vega's hooks never disagree with the board
+ // (Rigel's #452 note). A ticket without a brief row moves the same.
+ super::dev_ticket_briefs::move_brief(&mut tx, space_id, key, STATES, to).await?;
tx.commit().await?;
Ok(Some(current))
}
@@ -983,6 +988,45 @@ mod tests {
assert!(db.set_dev_ticket_state("s1", "TRAIL-2", IN_REVIEW).await.unwrap());
}
+ #[tokio::test]
+ async fn a_move_and_its_brief_mirror_are_one_transaction() {
+ // Rigel's #452 note: the card and its brief row moved in two writes, so a failed mirror
+ // left them disagreeing. Now a refused brief write rolls the move back.
+ let dir = tempfile::tempdir().unwrap();
+ let db = Database::init(dir.path()).await.unwrap();
+ for k in ["MIR-1", "MIR-2"] {
+ let f = TicketFacts { key: k.into(), project: "MIR".into(), url: format!("https://acme.atlassian.net/browse/{k}"), ..Default::default() };
+ assert!(db.insert_dev_ticket("s1", "site1", &f, PICKED_UP, Some("team1"), Some("label")).await.unwrap());
+ }
+ db.upsert_ticket_brief("s1", "MIR-1", "site1", "team1", "https://acme.atlassian.net/browse/MIR-1", "one").await.unwrap();
+
+ // Each writer moves the brief row with the card
+ assert!(db.set_dev_ticket_state("s1", "MIR-1", READING).await.unwrap());
+ assert_eq!(db.ticket_brief("s1", "MIR-1").await.unwrap().unwrap().state, READING);
+ assert!(db.fail_dev_ticket("s1", "MIR-1", FAIL_DEFAULT_CODE, Some("x")).await.unwrap());
+ assert_eq!(db.ticket_brief("s1", "MIR-1").await.unwrap().unwrap().state, FAILED);
+ assert!(db.person_move_dev_ticket("s1", "MIR-1", PersonMove::Retry).await.unwrap().is_some());
+ let retried = db.dev_ticket("s1", "MIR-1").await.unwrap().unwrap().state;
+ assert_eq!(db.ticket_brief("s1", "MIR-1").await.unwrap().unwrap().state, retried);
+ // A ticket without a brief row moves as before
+ assert!(db.set_dev_ticket_state("s1", "MIR-2", READING).await.unwrap());
+
+ // The brief write fails: the move is undone, card, event log and brief alike
+ sqlx::query("CREATE TRIGGER refuse_brief BEFORE UPDATE OF state ON dev_ticket_briefs BEGIN SELECT RAISE(ABORT, 'refused'); END")
+ .execute(&db.pool)
+ .await
+ .unwrap();
+ let events = db.dev_ticket_events("s1", "MIR-1", 50).await.unwrap().len();
+ assert!(db.set_dev_ticket_state("s1", "MIR-1", READING).await.is_err(), "the failed mirror is the move's error");
+ assert_eq!(db.dev_ticket("s1", "MIR-1").await.unwrap().unwrap().state, retried, "the card didn't move");
+ assert_eq!(db.ticket_brief("s1", "MIR-1").await.unwrap().unwrap().state, retried);
+ assert_eq!(db.dev_ticket_events("s1", "MIR-1", 50).await.unwrap().len(), events, "no event for a move that didn't happen");
+ assert!(db.fail_dev_ticket("s1", "MIR-1", FAIL_DEFAULT_CODE, None).await.is_err());
+ assert_eq!(db.dev_ticket("s1", "MIR-1").await.unwrap().unwrap().state, retried);
+ // The trigger only fires for a row that exists: other tickets still move, and the lock is free
+ assert!(db.set_dev_ticket_state("s1", "MIR-2", BRIEF_READY).await.unwrap());
+ }
+
#[test]
fn the_persons_moves_are_api_md_1_4() {
let all = [PersonMove::Stop, PersonMove::Skip, PersonMove::Close, PersonMove::Retry];
diff --git a/src/db/dev_ticket_briefs.rs b/src/db/dev_ticket_briefs.rs
index 3cf1dba1..fc7950a3 100644
--- a/src/db/dev_ticket_briefs.rs
+++ b/src/db/dev_ticket_briefs.rs
@@ -85,6 +85,21 @@ pub struct TicketQuestion {
pub created_at: i64,
}
+/// [`Database::move_ticket_brief`] on a connection the caller holds, so `dev_jira`'s state writer
+/// moves the brief row inside its own transaction.
+pub(super) async fn move_brief(conn: &mut sqlx::SqliteConnection, space_id: &str, key: &str, from: &[&str], to: &str) -> Result<bool, sqlx::Error> {
+ if from.is_empty() {
+ return Ok(false);
+ }
+ let marks = vec!["?"; from.len()].join(", ");
+ let sql = format!("UPDATE dev_ticket_briefs SET state = ?, updated_at = ? WHERE space_id = ? AND key = ? AND state IN ({marks})");
+ let mut q = sqlx::query(&sql).bind(to).bind(now_ms()).bind(space_id).bind(key);
+ for f in from {
+ q = q.bind(*f);
+ }
+ Ok(q.execute(conn).await?.rows_affected() == 1)
+}
+
fn now_ms() -> i64 {
chrono::Utc::now().timestamp_millis()
}
@@ -144,16 +159,7 @@ impl Database {
/// Moves the row from `from` (any of them) to `to`; false when it wasn't in one of them.
pub async fn move_ticket_brief(&self, space_id: &str, key: &str, from: &[&str], to: &str) -> Result<bool, DbError> {
- if from.is_empty() {
- return Ok(false);
- }
- let marks = vec!["?"; from.len()].join(", ");
- let sql = format!("UPDATE dev_ticket_briefs SET state = ?, updated_at = ? WHERE space_id = ? AND key = ? AND state IN ({marks})");
- let mut q = sqlx::query(&sql).bind(to).bind(now_ms()).bind(space_id).bind(key);
- for f in from {
- q = q.bind(*f);
- }
- Ok(q.execute(&self.pool).await?.rows_affected() == 1)
+ Ok(move_brief(&mut *self.pool.acquire().await?, space_id, key, from, to).await?)
}
/// Sets the named optional column (`thread_id`, `task_id`, `mission_id`, `brief`,
diff --git a/src/db/isolated_folders.rs b/src/db/isolated_folders.rs
index c19f9a19..ee5f95be 100644
--- a/src/db/isolated_folders.rs
+++ b/src/db/isolated_folders.rs
@@ -19,6 +19,15 @@ pub fn overlaps(folder: &Path, recorded: &Path) -> bool {
folder.starts_with(recorded) || recorded.starts_with(folder)
}
+/// One recorded folder.
+#[derive(Debug, Clone, PartialEq)]
+pub struct IsolatedFolder {
+ pub path: PathBuf,
+ pub first_bot_id: String,
+ pub first_used_at: chrono::DateTime<chrono::Utc>,
+ pub last_used_at: chrono::DateTime<chrono::Utc>,
+}
+
/// The error a refused host command records (its code first, for the API and the UI).
pub const HOST_COMMAND_REFUSED: &str = "folder_used_by_isolated_bot: a bot that runs Claude inside the VM used this folder, \
so commands from it don't run on this computer. Nothing ran.";
@@ -104,9 +113,26 @@ impl Database {
})
}
- /// Forgets a recorded folder (the person cleared it). Returns whether one was there.
+ /// Every recorded folder with who first used it and when, for the person's list.
+ pub async fn isolated_folder_records(&self) -> Result<Vec<IsolatedFolder>, DbError> {
+ let rows: Vec<(String, String, chrono::DateTime<chrono::Utc>, chrono::DateTime<chrono::Utc>)> = sqlx::query_as(
+ "SELECT path, first_bot_id, first_used_at, last_used_at FROM isolated_folders ORDER BY path",
+ )
+ .fetch_all(&self.pool)
+ .await?;
+ Ok(rows
+ .into_iter()
+ .map(|(path, first_bot_id, first_used_at, last_used_at)| IsolatedFolder { path: PathBuf::from(path), first_bot_id, first_used_at, last_used_at })
+ .collect())
+ }
+
+ /// Forgets a recorded folder (the person cleared it). Returns whether one was there. Matches
+ /// the path as recorded (a folder that was deleted or moved since can still be forgotten by
+ /// the path the list shows) or its canonical form. Only that one record: a recorded folder
+ /// inside or around it stays.
pub async fn forget_isolated_folder(&self, folder: &Path) -> Result<bool, DbError> {
- let done = sqlx::query("DELETE FROM isolated_folders WHERE path = ?")
+ let done = sqlx::query("DELETE FROM isolated_folders WHERE path = ? OR path = ?")
+ .bind(folder.to_string_lossy().as_ref())
.bind(canonical(folder).to_string_lossy().as_ref())
.execute(&self.pool)
.await?;
diff --git a/src/sandbox/agent_vm/mod.rs b/src/sandbox/agent_vm/mod.rs
index bde08a42..dfa4754b 100644
--- a/src/sandbox/agent_vm/mod.rs
+++ b/src/sandbox/agent_vm/mod.rs
@@ -624,7 +624,9 @@ impl AgentVm {
std::fs::create_dir_all(d).map_err(|e| fail(format!("Couldn't prepare the bot's computer folders: {e}")))?;
set_private(d);
}
- let mounts = Mounts::new(workdir, home, run_dir)?;
+ let ro_hooks = self.bot_dir(bot_id).join(RO_HOOKS);
+ prepare_ro_hooks(&ro_hooks).map_err(|e| fail(format!("Couldn't prepare the bot's computer folders: {e}")))?;
+ let mounts = Mounts::new(workdir, home, run_dir, &ro_hooks)?;
let args = run_args(&name, &self.root_label(), &mounts, &self.image(), host_ids(), self.limits.memory_mb);
let out = Command::new("docker")
.args(&args)
@@ -716,27 +718,89 @@ impl AgentVm {
}
}
-/// The three bind mounts of a bot's container, as `--mount` values. Docker reads `--mount` as
-/// CSV, so each field is quoted (a `,` or `"` in a folder name can't add an option); a name with
-/// a newline or that isn't UTF-8 is refused instead.
+/// The bind mounts of a bot's container, as `--mount` values: the folder, the bot's home, the
+/// broker's socket folder (read-only) and, in a git repo, kwnt's own empty folder (read-only)
+/// over its `.git/hooks`. Every source but the folder itself is a folder only kwnt writes. Docker
+/// reads `--mount` as CSV, so each field is quoted (a `,` or `"` in a folder name can't add an
+/// option); a name with a newline or that isn't UTF-8 is refused instead.
#[derive(Debug, Clone, PartialEq, Eq)]
struct Mounts {
workdir: String,
- args: [String; 3],
+ args: Vec<String>,
}
impl Mounts {
- fn new(workdir: &Path, home: &Path, run_dir: &Path) -> Result<Self, Refusal> {
+ /// `ro_hooks` is [`RO_HOOKS`] in the bot's kwnt folder, made by [`prepare_ro_hooks`].
+ fn new(workdir: &Path, home: &Path, run_dir: &Path, ro_hooks: &Path) -> Result<Self, Refusal> {
let w = check_mountable(workdir)?;
let h = check_mountable(home)?;
let r = check_mountable(run_dir)?;
- Ok(Self {
- workdir: w.to_string(),
- args: [mount_arg(w, w, false), mount_arg(h, CONTAINER_HOME, false), mount_arg(r, CONTAINER_RUN, true)],
- })
+ let mut args = vec![mount_arg(w, w, false), mount_arg(h, CONTAINER_HOME, false), mount_arg(r, CONTAINER_RUN, true)];
+ if let Some(hooks) = git_hooks_to_protect(workdir) {
+ // #462 review must-fix 1: the source is never a path in the bot's folder. Docker
+ // follows links in `src`, so a bot that swapped `.git/hooks` for a link between the
+ // check and `docker run` would get a host folder mounted. The destination is resolved
+ // inside the container, so a swap there at worst leaves hooks unprotected that time.
+ let src = check_mountable(ro_hooks)?;
+ args.push(mount_arg(src, check_mountable(&hooks)?, true));
+ }
+ Ok(Self { workdir: w.to_string(), args })
+ }
+}
+
+/// #446 item 13 (S-14): a hook the bot writes would run on this computer the next time the person
+/// commits there. When the folder is a git repo with a real `.git` folder, kwnt's own empty
+/// read-only folder is bound over its `.git/hooks`, so the bot can't add or change a hook (and the
+/// person's own hooks don't run for commits made inside the container); commits, branches and
+/// everything else in `.git` still work. A missing `hooks` folder is made first (git makes it
+/// too), so the bot can't create one later. Read without following links: a `.git` that is a file
+/// (a worktree or submodule, whose hooks live in a repo outside the folder) or a link, or a
+/// `hooks` that is a link, gets no extra mount. Not covered, and said in docs/agents-in-vm.md:
+/// `core.hooksPath` in `.git/config`, renaming `.git`, and a repo the bot makes during the turn.
+fn git_hooks_to_protect(workdir: &Path) -> Option<PathBuf> {
+ use crate::sandbox::safe_fs::Dir;
+ let git = Dir::open(workdir).ok()?.open_dir(Path::new(".git")).ok()?;
+ match git.make_dirs(Path::new("hooks")) {
+ Ok(_) => Some(workdir.join(".git").join("hooks")),
+ Err(e) => {
+ if e.kind() != std::io::ErrorKind::NotFound {
+ // A `hooks` that is a link or a file is a legitimate setup: not refused, but said
+ tracing::info!(folder = %workdir.display(), error = %e, "no read-only .git/hooks mount for this folder: its .git/hooks isn't a real folder");
+ }
+ None
+ }
}
}
+/// The empty folder in the bot's kwnt folder that is mounted over a repo's `.git/hooks`.
+const RO_HOOKS: &str = "ro-hooks";
+
+/// Makes [`RO_HOOKS`]: a real, empty folder, mode 0555. It sits next to the bot's `home` and
+/// `run` in kwnt's data folder, outside every folder a container can write. Anything else there
+/// (a link, a file, a folder with entries) is refused rather than mounted.
+fn prepare_ro_hooks(p: &Path) -> std::io::Result<()> {
+ match std::fs::symlink_metadata(p) {
+ Ok(m) if m.is_dir() => {}
+ Ok(_) => return Err(std::io::Error::other(format!("{} isn't a folder", p.display()))),
+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
+ if let Some(parent) = p.parent() {
+ std::fs::create_dir_all(parent)?;
+ }
+ std::fs::create_dir(p)?;
+ }
+ Err(e) => return Err(e),
+ }
+ if std::fs::read_dir(p)?.next().is_some() {
+ return Err(std::io::Error::other(format!("{} isn't empty", p.display())));
+ }
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+ std::fs::set_permissions(p, std::fs::Permissions::from_mode(0o555))?;
+ }
+ Ok(())
+}
+
fn csv_field(f: &str) -> String {
format!("\"{}\"", f.replace('"', "\"\""))
}
@@ -1187,7 +1251,7 @@ mod tests {
#[cfg(unix)]
#[test]
fn run_args_isolate_the_container() {
- let m = Mounts::new(Path::new("/w/proj"), Path::new("/d/h"), Path::new("/d/run")).unwrap();
+ let m = Mounts::new(Path::new("/w/proj"), Path::new("/d/h"), Path::new("/d/run"), Path::new("/d/ro-hooks")).unwrap();
let a = run_args("kwnt-agent-a-b", "r", &m, "img", Some((1000, 1000)), 1024);
let s = a.join(" ");
for want in [
@@ -1207,23 +1271,225 @@ mod tests {
assert!(!s.contains("docker.sock"));
}
+ /// The `src=` of each `--mount` value (the tests' own folder names have no `"` or `,`).
+ #[cfg(unix)]
+ fn mount_sources(m: &Mounts) -> Vec<PathBuf> {
+ m.args.iter().map(|a| PathBuf::from(a.split("\"src=").nth(1).unwrap().split('"').next().unwrap())).collect()
+ }
+
+ // #446 item 13: kwnt's own empty folder is mounted read-only over a repo's `.git/hooks`, never
+ // anything through a link
+ #[cfg(unix)]
+ #[test]
+ fn a_repos_git_hooks_are_mounted_read_only() {
+ let d = tempfile::tempdir().unwrap();
+ let (home, run) = (d.path().join("h"), d.path().join("run"));
+ let kwnt_ro = d.path().join("kwnt").join(RO_HOOKS);
+ let rh = kwnt_ro.as_path();
+ let ro_hooks = |m: &Mounts, repo: &Path| {
+ let h = repo.join(".git/hooks");
+ let (h, src) = (h.to_str().unwrap(), kwnt_ro.to_str().unwrap());
+ m.args.iter().any(|a| *a == format!(r#"type=bind,"src={src}","dst={h}",readonly"#))
+ };
+ // A repo with hooks: four mounts, the fourth the hooks, read-only and last (so it lies over
+ // the folder's rw mount)
+ let repo = d.path().join("repo");
+ std::fs::create_dir_all(repo.join(".git/hooks")).unwrap();
+ let m = Mounts::new(&repo, &home, &run, rh).unwrap();
+ assert_eq!(m.args.len(), 4, "{m:?}");
+ assert!(ro_hooks(&m, &repo) && m.args[3].ends_with(",readonly"), "{m:?}");
+ let a = run_args("n", "r", &m, "img", Some((1000, 1000)), 512);
+ assert_eq!(a.iter().filter(|x| *x == "--mount").count(), 4);
+
+ // A repo without a hooks folder gets one first, so the bot can't make it later
+ let bare = d.path().join("nohooks");
+ std::fs::create_dir_all(bare.join(".git")).unwrap();
+ assert!(ro_hooks(&Mounts::new(&bare, &home, &run, rh).unwrap(), &bare));
+ assert!(bare.join(".git/hooks").is_dir());
+
+ // Not a repo: three mounts, and no `.git` is made
+ let plain = d.path().join("plain");
+ std::fs::create_dir_all(&plain).unwrap();
+ assert_eq!(Mounts::new(&plain, &home, &run, rh).unwrap().args.len(), 3);
+ assert!(!plain.join(".git").exists());
+
+ // A worktree or submodule (`.git` is a file), a linked `.git` and a linked `hooks` get no
+ // extra mount, and nothing is made through a link
+ let wt = d.path().join("worktree");
+ std::fs::create_dir_all(&wt).unwrap();
+ std::fs::write(wt.join(".git"), "gitdir: /elsewhere/.git/worktrees/x\n").unwrap();
+ assert_eq!(Mounts::new(&wt, &home, &run, rh).unwrap().args.len(), 3);
+ let target = d.path().join("target");
+ std::fs::create_dir_all(&target).unwrap();
+ let linked = d.path().join("linked");
+ std::fs::create_dir_all(&linked).unwrap();
+ std::os::unix::fs::symlink(&target, linked.join(".git")).unwrap();
+ assert_eq!(Mounts::new(&linked, &home, &run, rh).unwrap().args.len(), 3);
+ assert!(!target.join("hooks").exists(), "nothing made through the link");
+ let lh = d.path().join("linkedhooks");
+ std::fs::create_dir_all(lh.join(".git")).unwrap();
+ std::os::unix::fs::symlink(&target, lh.join(".git/hooks")).unwrap();
+ assert_eq!(Mounts::new(&lh, &home, &run, rh).unwrap().args.len(), 3);
+ }
+
+ // #462 review must-fix 1: Docker follows links in a mount's `src`, so no source may be a path
+ // the bot can change. The folder's own mount is the only source under it; the hooks mount's
+ // source is kwnt's folder.
+ #[cfg(unix)]
+ #[test]
+ fn no_mount_source_is_in_the_bots_folder_except_the_folder_itself() {
+ let d = tempfile::tempdir().unwrap();
+ let repo = d.path().join("repo");
+ std::fs::create_dir_all(repo.join(".git/hooks")).unwrap();
+ let kwnt = d.path().join("kwnt");
+ let ro = kwnt.join(RO_HOOKS);
+ let m = Mounts::new(&repo, &kwnt.join("home"), &kwnt.join("run"), &ro).unwrap();
+ let srcs = mount_sources(&m);
+ assert_eq!(srcs.len(), 4, "{m:?}");
+ assert_eq!(srcs[0], repo, "the folder's own mount comes first");
+ for s in &srcs[1..] {
+ assert!(!s.starts_with(&repo), "{} is in the bot's folder: {m:?}", s.display());
+ assert!(s.starts_with(&kwnt), "{} isn't kwnt's: {m:?}", s.display());
+ }
+ assert_eq!(srcs[3], ro, "the hooks mount's source is kwnt's empty folder");
+ assert!(m.args[3].contains(&format!("\"dst={}\"", repo.join(".git/hooks").display())) && m.args[3].ends_with(",readonly"));
+ // Still true when the bot's `.git/hooks` is a link into kwnt's folder or anywhere else:
+ // there's no hooks mount at all then
+ std::fs::remove_dir(repo.join(".git/hooks")).unwrap();
+ std::os::unix::fs::symlink(&kwnt, repo.join(".git/hooks")).unwrap();
+ assert_eq!(mount_sources(&Mounts::new(&repo, &kwnt.join("home"), &kwnt.join("run"), &ro).unwrap()).len(), 3);
+ }
+
+ #[cfg(unix)]
+ #[test]
+ fn the_ro_hooks_folder_is_made_empty_and_read_only_and_anything_else_is_refused() {
+ use std::os::unix::fs::PermissionsExt;
+ let d = tempfile::tempdir().unwrap();
+ let ro = d.path().join("bot").join(RO_HOOKS);
+ prepare_ro_hooks(&ro).unwrap();
+ let meta = std::fs::symlink_metadata(&ro).unwrap();
+ assert!(meta.is_dir());
+ assert_eq!(meta.permissions().mode() & 0o777, 0o555);
+ prepare_ro_hooks(&ro).unwrap(); // a second turn reuses it
+ // Not empty, a link or a file: refused, never mounted
+ std::fs::set_permissions(&ro, std::fs::Permissions::from_mode(0o755)).unwrap();
+ std::fs::write(ro.join("pre-commit"), "").unwrap();
+ assert!(prepare_ro_hooks(&ro).is_err());
+ let link = d.path().join("link").join(RO_HOOKS);
+ std::fs::create_dir_all(link.parent().unwrap()).unwrap();
+ std::os::unix::fs::symlink(d.path(), &link).unwrap();
+ assert!(prepare_ro_hooks(&link).is_err());
+ let file = d.path().join("file");
+ std::fs::write(&file, "").unwrap();
+ assert!(prepare_ro_hooks(&file).is_err());
+ }
+
+ /// Rigel's S-14 case in a real container started with [`run_args`]: the bot's
+ /// `echo x > .git/hooks/pre-commit` fails, and so do chmod, mv, touch and rmdir on the hooks
+ /// folder; a normal `git commit` inside still works, and nothing reached the hooks folder on
+ /// this computer. Then the #462 review's race, made certain: `.git/hooks` is checked as a real
+ /// folder, then swapped for a link to a "secret" folder before `docker run`, and the secret
+ /// must not be readable inside. Needs Docker and the agent image; skips without them unless
+ /// `KWNT_AGENT_TEST_REQUIRE=1`.
+ #[cfg(target_os = "linux")]
+ #[test]
+ fn in_a_real_container_a_hook_cant_be_written_but_git_commit_works() {
+ use std::process::Command as Std;
+ if !Std::new("docker").args(["image", "inspect", &image_tag()]).output().is_ok_and(|o| o.status.success()) {
+ assert!(std::env::var("KWNT_AGENT_TEST_REQUIRE").is_err(), "Docker or the agent image {} is missing", image_tag());
+ eprintln!("skipped: needs Docker and the agent image {}", image_tag());
+ return;
+ }
+ let d = tempfile::tempdir().unwrap();
+ let repo = d.path().join("repo");
+ std::fs::create_dir_all(&repo).unwrap();
+ let git = |args: &[&str]| assert!(Std::new("git").args(args).current_dir(&repo).output().unwrap().status.success(), "{args:?}");
+ git(&["init", "-q", "."]);
+ git(&["-c", "user.name=t", "-c", "user.email=t@t", "commit", "-q", "--allow-empty", "-m", "init"]);
+ let hooks_before = std::fs::read_dir(repo.join(".git/hooks")).unwrap().count();
+ let (home, run) = (d.path().join("h"), d.path().join("run"));
+ std::fs::create_dir_all(&home).unwrap();
+ std::fs::create_dir_all(&run).unwrap();
+ let name = format!("kwnt-agent-hooks-test-{}", std::process::id());
+ struct Rm(String);
+ impl Drop for Rm {
+ fn drop(&mut self) {
+ let _ = std::process::Command::new("docker").args(["rm", "-f", &self.0]).output();
+ }
+ }
+ let _rm = Rm(name.clone());
+ let ro = d.path().join("kwnt").join(RO_HOOKS);
+ prepare_ro_hooks(&ro).unwrap();
+ let m = Mounts::new(&repo, &home, &run, &ro).unwrap();
+ let out = Std::new("docker").args(run_args(&name, "hooks-test", &m, &image_tag(), host_ids(), 512)).output().unwrap();
+ assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
+ // Each probe prints its name only if it worked; none may
+ let probe = r#"
+ echo x > .git/hooks/pre-commit 2>/dev/null && echo HOOK_WRITTEN || echo HOOK_REFUSED
+ chmod u+w .git/hooks 2>/dev/null && echo CHMOD_UW
+ chmod 777 .git/hooks 2>/dev/null && echo CHMOD_777
+ touch .git/hooks/x 2>/dev/null && echo TOUCHED
+ mv .git/hooks .git/h2 2>/dev/null && echo MOVED
+ rm -f .git/hooks/*.sample 2>/dev/null; rmdir .git/hooks 2>/dev/null && echo HOOKS_REMOVED
+ [ -d .git/hooks ] && [ -z "$(ls -A .git/hooks)" ] && echo HOOKS_EMPTY
+ echo hi > a.txt && git add a.txt && git -c user.name=b -c user.email=b@b commit -qm a && echo COMMIT_OK
+ git checkout -qb feature && echo BRANCH_OK
+ "#;
+ let out = Std::new("docker").args(["exec", "-e", "HOME=/tmp", &name, "sh", "-c", probe]).output().unwrap();
+ let said = String::from_utf8_lossy(&out.stdout);
+ for want in ["HOOK_REFUSED", "HOOKS_EMPTY", "COMMIT_OK", "BRANCH_OK"] {
+ assert!(said.contains(want), "{want} in {said}");
+ }
+ for never in ["HOOK_WRITTEN", "CHMOD_UW", "CHMOD_777", "TOUCHED", "MOVED", "HOOKS_REMOVED"] {
+ assert!(!said.contains(never), "{never} in {said}");
+ }
+ assert!(!repo.join(".git/h2").exists() && !repo.join(".git/hooks/x").exists());
+ assert!(!repo.join(".git/hooks/pre-commit").exists());
+ assert_eq!(std::fs::read_dir(repo.join(".git/hooks")).unwrap().count(), hooks_before);
+ // The commit the bot made is in the repo on this computer
+ let log = Std::new("git").args(["log", "--format=%s", "-1"]).current_dir(&repo).output().unwrap();
+ assert_eq!(String::from_utf8_lossy(&log.stdout).trim(), "a");
+ // kwnt's empty folder is unchanged too
+ assert_eq!(std::fs::read_dir(&ro).unwrap().count(), 0);
+
+ // The race from the #462 review, made certain: checked as a real folder, then swapped for
+ // a link to a folder outside before the container starts. The source is kwnt's folder, so
+ // the secret is never mounted; the container may start or not, but can't read it.
+ let _ = Std::new("docker").args(["rm", "-f", &name]).output();
+ let secret = d.path().join("secret");
+ std::fs::create_dir_all(&secret).unwrap();
+ std::fs::write(secret.join("id_rsa"), "SECRET-KEY").unwrap();
+ let m = Mounts::new(&repo, &home, &run, &ro).unwrap();
+ assert_eq!(m.args.len(), 4, "checked while still a real folder: {m:?}");
+ std::fs::rename(repo.join(".git/hooks"), repo.join(".git/hooks-real")).unwrap();
+ std::os::unix::fs::symlink(&secret, repo.join(".git/hooks")).unwrap();
+ let started = Std::new("docker").args(run_args(&name, "hooks-test", &m, &image_tag(), host_ids(), 512)).output().unwrap();
+ if started.status.success() {
+ let peek = format!("cat .git/hooks/id_rsa {s}/id_rsa 2>/dev/null; ls -A .git/hooks/ {s}/ 2>/dev/null; echo PEEKED", s = secret.display());
+ let out = Std::new("docker").args(["exec", "-e", "HOME=/tmp", &name, "sh", "-c", &peek]).output().unwrap();
+ let said = String::from_utf8_lossy(&out.stdout);
+ assert!(said.contains("PEEKED"), "{said}");
+ assert!(!said.contains("SECRET-KEY") && !said.contains("id_rsa"), "the secret was visible: {said}");
+ }
+ }
+
// Container paths are unix paths (`/w/proj` isn't absolute on Windows); isolation is Linux only
#[cfg(unix)]
#[test]
fn mount_values_cant_add_options_and_odd_names_are_refused() {
// A comma or quote stays inside the src field (Docker reads --mount as CSV)
- let m = Mounts::new(Path::new("/w/a,dst=/etc,readonly=false"), Path::new("/d/h"), Path::new("/d/run")).unwrap();
+ let m = Mounts::new(Path::new("/w/a,dst=/etc,readonly=false"), Path::new("/d/h"), Path::new("/d/run"), Path::new("/d/ro-hooks")).unwrap();
assert_eq!(m.args[0], r#"type=bind,"src=/w/a,dst=/etc,readonly=false","dst=/w/a,dst=/etc,readonly=false""#);
- let q = Mounts::new(Path::new("/w/say \"hi\": x=1"), Path::new("/d/h"), Path::new("/d/run")).unwrap();
+ let q = Mounts::new(Path::new("/w/say \"hi\": x=1"), Path::new("/d/h"), Path::new("/d/run"), Path::new("/d/ro-hooks")).unwrap();
assert_eq!(q.args[0], r#"type=bind,"src=/w/say ""hi"": x=1","dst=/w/say ""hi"": x=1""#);
for bad in ["/w/new\nline", "relative/dir", "/w/tab\there"] {
- assert_eq!(Mounts::new(Path::new(bad), Path::new("/d/h"), Path::new("/d/run")).unwrap_err().code, codes::FOLDER_NAME_UNSUPPORTED, "{bad:?}");
+ assert_eq!(Mounts::new(Path::new(bad), Path::new("/d/h"), Path::new("/d/run"), Path::new("/d/ro-hooks")).unwrap_err().code, codes::FOLDER_NAME_UNSUPPORTED, "{bad:?}");
}
#[cfg(unix)]
{
use std::os::unix::ffi::OsStrExt;
let p = Path::new(std::ffi::OsStr::from_bytes(b"/w/\xff"));
- assert_eq!(Mounts::new(p, Path::new("/d/h"), Path::new("/d/run")).unwrap_err().code, codes::FOLDER_NAME_UNSUPPORTED);
+ assert_eq!(Mounts::new(p, Path::new("/d/h"), Path::new("/d/run"), Path::new("/d/ro-hooks")).unwrap_err().code, codes::FOLDER_NAME_UNSUPPORTED);
}
}
diff --git a/src/sandbox/safe_fs.rs b/src/sandbox/safe_fs.rs
index 289ae807..d1a2991d 100644
--- a/src/sandbox/safe_fs.rs
+++ b/src/sandbox/safe_fs.rs
@@ -267,6 +267,12 @@ mod imp {
/// This folder's entries (without `.` and `..`), each seen with `fstatat(…,
/// AT_SYMLINK_NOFOLLOW)` from this descriptor. An entry gone by then is left out.
pub fn list(&self) -> io::Result<Vec<Entry>> {
+ self.list_at_most(usize::MAX).map(|(l, _)| l)
+ }
+
+ /// [`list`](Self::list), reading at most `max` names: a folder with millions of entries
+ /// costs kwant no more than `max`. The flag is true when entries were left unread.
+ pub fn list_at_most(&self, max: usize) -> io::Result<(Vec<Entry>, bool)> {
// fdopendir takes the descriptor over: give it a copy
let dup = self.fd.try_clone()?;
// SAFETY: a valid descriptor whose ownership passes to the DIR stream
@@ -274,7 +280,13 @@ mod imp {
if stream.is_null() {
return Err(io::Error::last_os_error());
}
+ // The copy shares the read position with `self.fd`: after an earlier listing (or one
+ // cut short) it sits past the start, and a second listing of the same Dir came back
+ // short or empty. Start from the first entry every time.
+ // SAFETY: `stream` is a valid open DIR
+ unsafe { libc::rewinddir(stream) };
let mut names = Vec::new();
+ let mut cut = false;
loop {
// SAFETY: `stream` is a valid open DIR until closedir below
let ent = unsafe { libc::readdir(stream) };
@@ -284,6 +296,10 @@ mod imp {
// SAFETY: readdir returned a valid entry whose name is NUL-terminated
let name = unsafe { CStr::from_ptr((*ent).d_name.as_ptr()) }.to_bytes().to_vec();
if name != b"." && name != b".." {
+ if names.len() >= max {
+ cut = true;
+ break;
+ }
names.push(OsString::from_vec(name));
}
}
@@ -304,7 +320,7 @@ mod imp {
let mode = st.st_mode as u32;
out.push(Entry { name, kind: mode_kind(mode), len: st.st_size.max(0) as u64, mode: mode & 0o7777 });
}
- Ok(out)
+ Ok((out, cut))
}
}
}
@@ -409,8 +425,15 @@ mod imp {
}
pub fn list(&self) -> io::Result<Vec<Entry>> {
+ self.list_at_most(usize::MAX).map(|(l, _)| l)
+ }
+
+ pub fn list_at_most(&self, max: usize) -> io::Result<(Vec<Entry>, bool)> {
let mut out = Vec::new();
for e in std::fs::read_dir(&self.path)?.flatten() {
+ if out.len() >= max {
+ return Ok((out, true));
+ }
let Ok(m) = std::fs::symlink_metadata(e.path()) else { continue };
let ft = m.file_type();
let kind = if ft.is_symlink() {
@@ -424,7 +447,7 @@ mod imp {
};
out.push(Entry { name: e.file_name(), kind, len: m.len(), mode: if m.permissions().readonly() { 0o444 } else { 0o644 } });
}
- Ok(out)
+ Ok((out, false))
}
}
}
@@ -645,4 +668,22 @@ mod tests {
}
}
}
+
+ /// #446 should-fix 2: a listing reads at most what it is allowed and says it stopped.
+ #[test]
+ fn a_capped_listing_reads_no_more_than_its_limit() {
+ let d = tempfile::tempdir().unwrap();
+ for i in 0..7 {
+ std::fs::write(d.path().join(format!("f{i}")), "x").unwrap();
+ }
+ let dir = Dir::open(d.path()).unwrap();
+ let (l, cut) = dir.list_at_most(3).unwrap();
+ assert_eq!((l.len(), cut), (3, true));
+ // Listing the same Dir again starts from the first entry (the copied descriptor shares
+ // its read position; before the fix a second listing came back short or empty)
+ let (l, cut) = dir.list_at_most(7).unwrap();
+ assert_eq!((l.len(), cut), (7, false));
+ assert_eq!(dir.list().unwrap().len(), 7);
+ assert_eq!(dir.list().unwrap().len(), 7);
+ }
}
diff --git a/src/server/auth.rs b/src/server/auth.rs
index b7f4c24f..776ba9c7 100644
--- a/src/server/auth.rs
+++ b/src/server/auth.rs
@@ -333,6 +333,9 @@ pub fn person_only(method: &Method, path: &str) -> bool {
let segs: Vec<&str> = path.trim_end_matches('/').split('/').collect();
match segs.as_slice() {
["", "api", "sandbox", _, "passwords", ..] => true,
+ // Folders isolated bots used (#446 item 6): forgetting one lets host CLIs load its files
+ // again, so only the person reads or changes the list
+ ["", "api", "isolated-folders", ..] => true,
// Raw clicks by position are the person's live view: a bot clicking by coordinates would
// skip the payment floor, which reads the element under a label (bots use /act)
["", "api", "sandbox", _, "interact"] => true,
@@ -928,6 +931,9 @@ mod tests {
assert!(person_only(&post, "/api/sandbox/t1/interact"));
assert!(!person_only(&post, "/api/sandbox/t1/act"));
assert!(person_only(&get, "/api/passwords/store"));
+ assert!(person_only(&get, "/api/isolated-folders"));
+ assert!(person_only(&post, "/api/isolated-folders/forget"));
+ assert!(person_only(&Method::HEAD, "/api/isolated-folders/"));
// 0.7.7 ready-made teams: everything but the catalogue
assert!(person_only(&get, "/api/team-templates/inbox/preview"));
assert!(person_only(&post, "/api/teams/from-template"));
diff --git a/src/server/dev/tickets/store.rs b/src/server/dev/tickets/store.rs
index b366262d..61a19fe6 100644
--- a/src/server/dev/tickets/store.rs
+++ b/src/server/dev/tickets/store.rs
@@ -66,7 +66,6 @@ fn all_keys(s: &str) -> Vec<String> {
pub async fn set_state(state: &AppState, space_id: &str, key: &str, to: &str, detail: Option<&str>) -> Result<bool, DbError> {
let moved = state.db.set_dev_ticket_state_with(space_id, key, to, detail).await?;
if moved {
- mirror(state, space_id, key, to).await;
notify(state, space_id, key, to);
if to == dev_jira::WORKING {
progress(state, space_id, key, Progress::Work).await;
@@ -136,7 +135,6 @@ pub fn error_json(row: &TicketRow) -> serde_json::Value {
pub async fn fail(state: &AppState, space_id: &str, key: &str, code: FailCode, detail: Option<&str>) -> Result<bool, DbError> {
let moved = state.db.fail_dev_ticket(space_id, key, code.code(), detail).await?;
if moved {
- mirror(state, space_id, key, dev_jira::FAILED).await;
notify(state, space_id, key, dev_jira::FAILED);
}
Ok(moved)
@@ -147,7 +145,6 @@ pub async fn fail(state: &AppState, space_id: &str, key: &str, code: FailCode, d
pub async fn person_move(state: &AppState, space_id: &str, key: &str, mv: dev_jira::PersonMove) -> Result<Option<String>, DbError> {
let from = state.db.person_move_dev_ticket(space_id, key, mv).await?;
if from.is_some() {
- mirror(state, space_id, key, mv.to()).await;
notify(state, space_id, key, mv.to());
}
Ok(from)
@@ -155,7 +152,9 @@ pub async fn person_move(state: &AppState, space_id: &str, key: &str, mv: dev_ji
/// Copies the card's new state onto the ticket's brief row, if it has one. The card row
/// (`dev_tickets.state`) is the one truth (D2); the brief row's `state` only mirrors it, so the
-/// brief page and Vega's hooks never disagree with the board. Called after every card move here.
+/// brief page and Vega's hooks never disagree with the board. A card move (`set_state`, `fail`,
+/// `person_move`) already moves the brief row in its own transaction; this is for the hooks that
+/// copy the card's state onto a brief row written after it.
pub async fn mirror(state: &AppState, space_id: &str, key: &str, to: &str) {
if let Err(e) = state.db.move_ticket_brief(space_id, key, dev_jira::STATES, to).await {
tracing::warn!(%key, %to, "dev: couldn't mirror the ticket state onto its brief: {e}");
diff --git a/src/server/isolated_folders_routes.rs b/src/server/isolated_folders_routes.rs
new file mode 100644
index 00000000..891c1a82
--- /dev/null
+++ b/src/server/isolated_folders_routes.rs
@@ -0,0 +1,260 @@
+//! Folders isolated Claude turns used, and forgetting one (#446 item 6, 0.8.0 section F).
+//!
+//! Every folder a reply that ran Claude inside the VM used is recorded (`db::isolated_folders`),
+//! and kwnt then treats it as untrusted on this computer: Codex and Grok don't start there, host
+//! commands are refused, Claude starts without the folder's own settings. Only the person can end
+//! that, after looking at what a bot may have left behind. Contract:
+//! `release-080/forget-folder-contract.md`.
+//!
+//! - `GET /api/isolated-folders`: the recorded folders, with the files to check first.
+//! - `POST /api/isolated-folders/forget` `{ "path": … }`: forgets that one record.
+//!
+//! Person-only, every method (`auth::person_only`): a bot that could forget a folder could plant
+//! a hook in it and then have a host CLI load it.
+
+use super::AppState;
+use crate::db::isolated_folders::IsolatedFolder;
+use crate::sandbox::safe_fs::{Dir, Kind};
+use axum::{
+ extract::{rejection::JsonRejection, State},
+ http::StatusCode,
+ response::{IntoResponse, Response},
+ Json,
+};
+use serde::Serialize;
+use serde_json::{json, Value};
+use std::collections::HashMap;
+use std::path::{Path, PathBuf};
+
+/// Hook files listed per folder, at most (a folder full of them still shows the first ones).
+const MAX_HOOKS: usize = 20;
+
+/// Files a program kwnt or the person starts in the folder would load or run, by folder.
+const LOADED_FILES: &[(&str, &[&str])] = &[
+ ("", &[".mcp.json", ".envrc"]),
+ (".claude", &["settings.json", "settings.local.json"]),
+ (".codex", &["config.toml"]),
+ (".grok", &["settings.json", "config.toml"]),
+ (".git", &["config"]),
+];
+
+fn error(status: StatusCode, code: &str, message: &str) -> Response {
+ (status, Json(json!({ "error": message, "code": code }))).into_response()
+}
+
+fn internal(e: impl std::fmt::Display) -> Response {
+ tracing::warn!(error = %e, "isolated folders: database error");
+ error(StatusCode::INTERNAL_SERVER_ERROR, "internal", "Couldn't read the list of folders. Try again.")
+}
+
+#[derive(Serialize, Debug, PartialEq)]
+pub struct FolderView {
+ pub path: String,
+ pub first_bot_id: String,
+ /// `null` when that bot was deleted since
+ pub first_bot_name: Option<String>,
+ pub first_used_at: chrono::DateTime<chrono::Utc>,
+ pub last_used_at: chrono::DateTime<chrono::Utc>,
+ /// `false` when the folder was deleted or moved: it can still be forgotten
+ pub exists: bool,
+ /// Paths inside the folder (relative, `/`-separated) that a CLI, git or the person's shell
+ /// started there would load. A bot in the VM could have written them; look before forgetting.
+ /// A symlink is listed with ` -> link` (never followed). A `.git` or `.git/hooks` that isn't a
+ /// real folder is listed too (`.git (file)`, `.git/hooks -> link`, …): git then loads hooks
+ /// from somewhere kwnt doesn't look.
+ pub check_first: Vec<String>,
+}
+
+/// What [`LOADED_FILES`] and `.git/hooks` hold in `folder`. Read without following any link
+/// below the folder (a bot made them), names only, never contents.
+pub fn check_first(folder: &Path) -> (bool, Vec<String>) {
+ let Ok(root) = Dir::open(folder) else {
+ return (false, Vec::new());
+ };
+ let mut out = Vec::new();
+ let show = |dir: &str, name: &str, kind: Kind| {
+ let rel = if dir.is_empty() { name.to_string() } else { format!("{dir}/{name}") };
+ if kind == Kind::Symlink {
+ format!("{rel} -> link")
+ } else {
+ rel
+ }
+ };
+ let entries = |dir: &str, max: usize| -> Vec<(String, Kind)> {
+ root.open_dir(Path::new(dir))
+ .and_then(|d| d.list_at_most(max))
+ .map(|(es, _)| es.into_iter().map(|e| (e.name.to_string_lossy().into_owned(), e.kind)).collect())
+ .unwrap_or_default()
+ };
+ // A folder may hold many entries; only the named ones matter, so read each (bounded)
+ let top = entries("", 10_000);
+ for (dir, names) in LOADED_FILES {
+ let found = if dir.is_empty() { top.clone() } else { entries(dir, 10_000) };
+ for name in *names {
+ if let Some((_, kind)) = found.iter().find(|(n, _)| n == name) {
+ out.push(show(dir, name, *kind));
+ }
+ }
+ // `.claude`, `.codex`, … as a link: everything in it comes from somewhere else
+ if !dir.is_empty() {
+ if let Some((_, Kind::Symlink)) = top.iter().find(|(n, _)| n == dir) {
+ out.push(show("", dir, Kind::Symlink));
+ }
+ }
+ }
+ // #462 review must-fix 2: a `.git` file (`gitdir: .x`, the "rename `.git`" way around the
+ // read-only hooks) or a `hooks` that isn't a real folder sends git to hooks this list can't
+ // see, so say so instead of showing nothing
+ let not_a_folder = |rel: &str, kind: Kind| match kind {
+ Kind::Dir => None,
+ Kind::Symlink => Some(format!("{rel} -> link")),
+ Kind::File => Some(format!("{rel} (file)")),
+ Kind::Other => Some(format!("{rel} (not a folder)")),
+ };
+ match top.iter().find(|(n, _)| n == ".git").map(|(_, k)| *k) {
+ Some(Kind::Dir) => {
+ if let Some((_, kind)) = entries(".git", 10_000).into_iter().find(|(n, _)| n == "hooks") {
+ out.extend(not_a_folder(".git/hooks", kind));
+ }
+ }
+ // A linked `.git` is already listed as `.git -> link` by the loop above
+ Some(Kind::Symlink) | None => {}
+ Some(kind) => out.extend(not_a_folder(".git", kind)),
+ }
+ let mut hooks: Vec<(String, Kind)> = entries(".git/hooks", 1_000).into_iter().filter(|(n, _)| !n.ends_with(".sample")).collect();
+ hooks.sort_by(|a, b| a.0.cmp(&b.0));
+ let more = hooks.len().saturating_sub(MAX_HOOKS);
+ out.extend(hooks.into_iter().take(MAX_HOOKS).map(|(n, k)| show(".git/hooks", &n, k)));
+ if more > 0 {
+ out.push(format!(".git/hooks: {more} more"));
+ }
+ out.dedup();
+ (true, out)
+}
+
+async fn views(state: &AppState, records: Vec<IsolatedFolder>) -> Vec<FolderView> {
+ let mut names: HashMap<String, Option<String>> = HashMap::new();
+ let mut out = Vec::with_capacity(records.len());
+ for r in records {
+ if !names.contains_key(&r.first_bot_id) {
+ let name = state.db.get_kwant(&r.first_bot_id).await.ok().flatten().map(|k| k.name);
+ names.insert(r.first_bot_id.clone(), name);
+ }
+ let path = r.path.clone();
+ let (exists, check) = tokio::task::spawn_blocking(move || check_first(&path)).await.unwrap_or((false, Vec::new()));
+ out.push(FolderView {
+ path: r.path.to_string_lossy().into_owned(),
+ first_bot_name: names.get(&r.first_bot_id).cloned().flatten(),
+ first_bot_id: r.first_bot_id,
+ first_used_at: r.first_used_at,
+ last_used_at: r.last_used_at,
+ exists,
+ check_first: check,
+ });
+ }
+ out
+}
+
+/// `GET /api/isolated-folders`
+pub async fn list(State(state): State<AppState>) -> Response {
+ match state.db.isolated_folder_records().await {
+ Ok(records) => Json(json!({ "folders": views(&state, records).await })).into_response(),
+ Err(e) => internal(e),
+ }
+}
+
+/// `POST /api/isolated-folders/forget` `{ "path": "<as listed>" }`
+pub async fn forget(State(state): State<AppState>, body: Result<Json<Value>, JsonRejection>) -> Response {
+ let bad = || error(StatusCode::BAD_REQUEST, "invalid", "Send the folder's path, as the list shows it.");
+ let Ok(Json(body)) = body else { return bad() };
+ let Some(path) = body.get("path").and_then(Value::as_str) else { return bad() };
+ if path.is_empty() || path.len() > 4096 || path.contains('\0') || !Path::new(path).is_absolute() {
+ return bad();
+ }
+ let path = PathBuf::from(path);
+ match state.db.forget_isolated_folder(&path).await {
+ Ok(true) => {
+ tracing::info!(folder = %path.display(), "the person forgot a folder an isolated bot used");
+ let rest = match state.db.isolated_folder_records().await {
+ Ok(r) => views(&state, r).await,
+ Err(e) => return internal(e),
+ };
+ Json(json!({ "forgotten": path.to_string_lossy(), "folders": rest })).into_response()
+ }
+ Ok(false) => error(StatusCode::NOT_FOUND, "not_recorded", "That folder isn't on the list (it may have been forgotten already)."),
+ Err(e) => internal(e),
+ }
+}
+
+#[cfg(all(test, unix))]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn check_first_names_what_a_cli_or_git_would_load_without_following_links() {
+ let d = tempfile::tempdir().unwrap();
+ let f = d.path();
+ assert_eq!(check_first(f), (true, vec![]), "an empty folder has nothing to check");
+ std::fs::create_dir_all(f.join(".claude")).unwrap();
+ std::fs::write(f.join(".claude/settings.json"), "{}").unwrap();
+ std::fs::write(f.join(".mcp.json"), "{}").unwrap();
+ std::fs::create_dir_all(f.join(".git/hooks")).unwrap();
+ std::fs::write(f.join(".git/hooks/pre-commit.sample"), "").unwrap();
+ std::fs::write(f.join(".git/hooks/post-checkout"), "#!/bin/sh").unwrap();
+ std::fs::write(f.join(".git/config"), "").unwrap();
+ let elsewhere = tempfile::tempdir().unwrap();
+ std::fs::write(elsewhere.path().join("config.toml"), "").unwrap();
+ std::os::unix::fs::symlink(elsewhere.path(), f.join(".codex")).unwrap();
+ let (exists, got) = check_first(f);
+ assert!(exists);
+ assert_eq!(got, vec![".mcp.json", ".claude/settings.json", ".codex -> link", ".git/config", ".git/hooks/post-checkout"]);
+ // A folder that's gone
+ assert_eq!(check_first(&f.join("nope")), (false, vec![]));
+ }
+
+ // #462 review must-fix 2: when git is sent elsewhere, the list says so instead of looking empty
+ #[test]
+ fn check_first_names_a_git_or_hooks_that_isnt_a_real_folder() {
+ let d = tempfile::tempdir().unwrap();
+ let elsewhere = tempfile::tempdir().unwrap();
+ // `.git` is a file (`gitdir: .x`, the renamed-.git bypass)
+ let f = d.path().join("gitfile");
+ std::fs::create_dir_all(f.join(".x/hooks")).unwrap();
+ std::fs::write(f.join(".x/hooks/pre-commit"), "#!/bin/sh").unwrap();
+ std::fs::write(f.join(".git"), "gitdir: .x\n").unwrap();
+ assert_eq!(check_first(&f), (true, vec![".git (file)".to_string()]));
+ // `.git` is a link: named once
+ let f = d.path().join("gitlink");
+ std::fs::create_dir_all(&f).unwrap();
+ std::os::unix::fs::symlink(elsewhere.path(), f.join(".git")).unwrap();
+ assert_eq!(check_first(&f).1, vec![".git -> link"]);
+ // `.git/hooks` is a link
+ let f = d.path().join("hookslink");
+ std::fs::create_dir_all(f.join(".git")).unwrap();
+ std::fs::write(f.join(".git/config"), "").unwrap();
+ std::os::unix::fs::symlink(elsewhere.path(), f.join(".git/hooks")).unwrap();
+ assert_eq!(check_first(&f).1, vec![".git/config", ".git/hooks -> link"]);
+ // `.git/hooks` is a file
+ let f = d.path().join("hooksfile");
+ std::fs::create_dir_all(f.join(".git")).unwrap();
+ std::fs::write(f.join(".git/hooks"), "").unwrap();
+ assert_eq!(check_first(&f).1, vec![".git/hooks (file)"]);
+ // A real `.git/hooks` with only samples still shows nothing
+ let f = d.path().join("plain");
+ std::fs::create_dir_all(f.join(".git/hooks")).unwrap();
+ std::fs::write(f.join(".git/hooks/pre-commit.sample"), "").unwrap();
+ assert_eq!(check_first(&f).1, Vec::<String>::new());
+ }
+
+ #[test]
+ fn many_hooks_are_cut_with_a_count() {
+ let d = tempfile::tempdir().unwrap();
+ std::fs::create_dir_all(d.path().join(".git/hooks")).unwrap();
+ for i in 0..(MAX_HOOKS + 3) {
+ std::fs::write(d.path().join(format!(".git/hooks/h{i:02}")), "").unwrap();
+ }
+ let (_, got) = check_first(d.path());
+ assert_eq!(got.len(), MAX_HOOKS + 1);
+ assert_eq!(got.last().unwrap(), ".git/hooks: 3 more");
+ }
+}
diff --git a/src/server/missions/checkpoints.rs b/src/server/missions/checkpoints.rs
index fceaf583..9318792e 100644
--- a/src/server/missions/checkpoints.rs
+++ b/src/server/missions/checkpoints.rs
@@ -38,6 +38,14 @@ pub const FILE_MAX_BYTES: u64 = 20 * 1024 * 1024;
pub const TOTAL_MAX_BYTES: u64 = 2 * 1024 * 1024 * 1024;
/// Files per checkpoint.
pub const MAX_FILES: usize = 20_000;
+/// Folders below the task folder a snapshot goes into; deeper ones are skipped. Each folder on
+/// the way down stays open while it's walked, so this also bounds the descriptors one walk holds.
+pub const MAX_DEPTH: usize = 64;
+/// Entries (files, folders, anything) a snapshot looks at before it stops walking: a folder with
+/// millions of entries costs kwant this much listing and memory, not more.
+pub const MAX_ENTRIES: usize = MAX_FILES * 4;
+/// How a manifest's skip says the walk stopped early (after the number).
+const WALK_STOPPED: &str = "entry limit";
/// Folders never snapshotted (and never restored).
pub const SKIP_DIRS: [&str; 4] = [".git", "node_modules", "target", ".venv"];
/// What restore says about external side effects, always.
@@ -318,6 +326,11 @@ fn snapshot(blobs: &FsPath, folder: &FsPath, max_bytes: u64) -> Result<Taken, St
/// [`snapshot`] of a folder already open: a restore snapshots and writes through the same
/// descriptor, so a folder swapped in between is never the one written (QA F-3).
fn snapshot_in(blobs: &FsPath, top: crate::sandbox::safe_fs::Dir, max_bytes: u64) -> Result<Taken, String> {
+ snapshot_within(blobs, top, max_bytes, MAX_DEPTH, MAX_ENTRIES)
+}
+
+/// [`snapshot_in`] with its walk limits given (tests use small ones).
+fn snapshot_within(blobs: &FsPath, top: crate::sandbox::safe_fs::Dir, max_bytes: u64, max_depth: usize, max_entries: usize) -> Result<Taken, String> {
private_dir(blobs).map_err(|e| format!("the checkpoint store can't be written: {e}"))?;
let mut m = Manifest::default();
// Every folder is reached from its parent's descriptor and every file opened from the
@@ -326,16 +339,21 @@ fn snapshot_in(blobs: &FsPath, top: crate::sandbox::safe_fs::Dir, max_bytes: u64
use crate::sandbox::safe_fs::{Dir, Kind};
let top = std::rc::Rc::new(top);
let mut candidates: Vec<(String, PathBuf, u64, u32)> = Vec::new();
- let mut stack: Vec<(std::rc::Rc<Dir>, Option<std::ffi::OsString>, String, PathBuf)> =
- vec![(top.clone(), None, String::new(), PathBuf::new())];
+ // Each stack item: the parent's descriptor, the folder's name in it, its relative path and its
+ // depth (the task folder is 0). Depth-first, so at most MAX_DEPTH folders are open at once.
+ type Pending = (std::rc::Rc<Dir>, Option<std::ffi::OsString>, String, PathBuf, usize);
+ let mut stack: Vec<Pending> = vec![(top.clone(), None, String::new(), PathBuf::new(), 0)];
let mut first = true;
- while let Some((parent, name, prefix, at)) = stack.pop() {
+ let mut looked_at: usize = 0;
+ while let Some((parent, name, prefix, at, depth)) = stack.pop() {
+ // One more than what's left, so a folder that fills the budget exactly isn't called cut
+ let room = max_entries - looked_at;
let listed = match name {
None => Ok(parent),
Some(n) => parent.open_dir(FsPath::new(&n)).map(std::rc::Rc::new),
}
- .and_then(|d| d.list().map(|l| (d, l)));
- let (dir, entries) = match listed {
+ .and_then(|d| d.list_at_most(room.saturating_add(1)).map(|l| (d, l)));
+ let (dir, (mut entries, mut cut)) = match listed {
Ok(x) => x,
Err(e) if first => return Err(format!("the folder can't be read: {e}")),
Err(_) => {
@@ -344,6 +362,11 @@ fn snapshot_in(blobs: &FsPath, top: crate::sandbox::safe_fs::Dir, max_bytes: u64
}
};
first = false;
+ if entries.len() > room {
+ entries.truncate(room);
+ cut = true;
+ }
+ looked_at += entries.len();
for entry in entries {
let name = entry.name.to_string_lossy().into_owned();
let rel = format!("{prefix}{name}");
@@ -352,12 +375,21 @@ fn snapshot_in(blobs: &FsPath, top: crate::sandbox::safe_fs::Dir, max_bytes: u64
Kind::Dir if SKIP_DIRS.contains(&name.as_str()) => {
m.skipped.push(Skip { path: format!("{rel}/"), why: "not snapshotted".into() })
}
- Kind::Dir => stack.push((dir.clone(), Some(entry.name.clone()), format!("{rel}/"), at.join(&entry.name))),
+ Kind::Dir if depth >= max_depth => {
+ m.skipped.push(Skip { path: format!("{rel}/"), why: format!("deeper than {max_depth} folders") })
+ }
+ Kind::Dir => stack.push((dir.clone(), Some(entry.name.clone()), format!("{rel}/"), at.join(&entry.name), depth + 1)),
Kind::Other => m.skipped.push(Skip { path: rel, why: "not a regular file".into() }),
Kind::File if entry.len > FILE_MAX_BYTES => m.skipped.push(Skip { path: rel, why: "over 20 MB".into() }),
Kind::File => candidates.push((rel, at.join(&entry.name), entry.len, entry.mode & 0o777)),
}
}
+ if cut || looked_at >= max_entries && !stack.is_empty() {
+ // One skip names where the walk stopped; folders not reached yet aren't listed
+ let path = if prefix.is_empty() { "./".to_string() } else { prefix.clone() };
+ m.skipped.push(Skip { path, why: format!("walk stopped at the {max_entries}-{WALK_STOPPED}") });
+ break;
+ }
}
candidates.sort_by(|a, b| a.0.cmp(&b.0));
if candidates.len() > MAX_FILES {
@@ -490,6 +522,22 @@ fn changed(before: &Manifest, after: &Manifest) -> Vec<String> {
.collect()
}
+/// Why the checkpoint can't say what `rel` was when it was taken, or None when it can (the file
+/// is in it, or the walk reached where it would be and it wasn't there). A restore never creates,
+/// overwrites or deletes a path the checkpoint can't vouch for: a file under a folder the walk
+/// skipped (too deep, unreadable, never snapshotted), or anywhere at all once the walk stopped at
+/// [`MAX_ENTRIES`], since folders not reached yet aren't listed.
+/// The caller has already checked that `rel` isn't one of the checkpoint's files.
+fn not_vouched(m: &Manifest, rel: &str) -> Option<String> {
+ if let Some(s) = m.skipped.iter().find(|s| s.path == rel) {
+ return Some(s.why.clone());
+ }
+ if let Some(s) = m.skipped.iter().find(|s| s.path.ends_with('/') && s.path != "./" && rel.starts_with(&s.path)) {
+ return Some(s.why.clone());
+ }
+ m.skipped.iter().find(|s| s.why.ends_with(WALK_STOPPED)).map(|s| s.why.clone())
+}
+
fn read_runs(dir: &FsPath) -> Vec<Run> {
std::fs::read_to_string(dir.join("runs.jsonl"))
.unwrap_or_default()
@@ -923,14 +971,13 @@ pub async fn plan(state: &AppState, task: &Task, c: &Checkpoint) -> Result<Plan,
entries.insert(e.path.clone(), e.clone());
}
}
- let skipped_in: BTreeMap<&str, &str> = manifest.skipped.iter().map(|s| (s.path.as_str(), s.why.as_str())).collect();
let mut changes = Vec::new();
let mut conflicts = Vec::new();
let mut forced = BTreeMap::new();
let mut hashes = Vec::new();
let check = {
let (folder, owned, entries, blobs) = (folder.clone(), owned.clone(), entries.clone(), blobs.clone());
- let skipped_in: BTreeMap<String, String> = skipped_in.iter().map(|(k, v)| (k.to_string(), v.to_string())).collect();
+ let manifest = manifest.clone();
tokio::task::spawn_blocking(move || {
owned
.into_iter()
@@ -938,7 +985,7 @@ pub async fn plan(state: &AppState, task: &Task, c: &Checkpoint) -> Result<Plan,
if !safe_rel(&p) {
return (p, Err("unsafe path".to_string()));
}
- if let Some(why) = skipped_in.get(&p) {
+ if let Some(why) = (!entries.contains_key(&p)).then(|| not_vouched(&manifest, &p)).flatten() {
return (p, Err(format!("{why}, not in the checkpoint")));
}
let now = match current(&folder, &p) {
@@ -1766,4 +1813,88 @@ mod tests {
assert_eq!(resolve_above(&home.join("Projects")), home.canonicalize().unwrap().join("Projects"));
assert!(snapshot(&blobs, &resolve_above(&home.join("Projects")), 1 << 30).is_err());
}
+
+ /// #446 should-fix 2: the walk goes MAX_DEPTH folders down and no further. Each folder deeper
+ /// is one skip naming it, and a file at the limit is still snapshotted.
+ #[test]
+ fn a_snapshot_goes_64_folders_deep_and_skips_what_is_deeper() {
+ let d = tempfile::tempdir().unwrap();
+ let (folder, blobs) = (d.path().join("proj"), d.path().join("blobs"));
+ // One-letter names keep the deepest path under Windows' 260 characters
+ let mut at_limit = folder.clone();
+ for _ in 0..MAX_DEPTH {
+ at_limit = at_limit.join("d");
+ }
+ let too_deep = at_limit.join("deeper");
+ std::fs::create_dir_all(&too_deep).unwrap();
+ std::fs::write(at_limit.join("at-the-limit.txt"), "kept").unwrap();
+ std::fs::write(too_deep.join("lost.txt"), "skipped").unwrap();
+ let t = snapshot(&blobs, &folder, 1 << 30).unwrap();
+ let rel_limit = "d/".repeat(MAX_DEPTH);
+ let files: Vec<&str> = t.manifest.files.iter().map(|f| f.path.as_str()).collect();
+ assert_eq!(files, vec![format!("{rel_limit}at-the-limit.txt")]);
+ let skip = t.manifest.skipped.iter().find(|s| s.path == format!("{rel_limit}deeper/")).expect("the deeper folder is named");
+ assert_eq!(skip.why, "deeper than 64 folders");
+ // A restore never acts on a path under it
+ assert_eq!(not_vouched(&t.manifest, &format!("{rel_limit}deeper/lost.txt")).as_deref(), Some("deeper than 64 folders"));
+ }
+
+ /// #446 should-fix 2: the walk looks at no more than its entry budget, records one skip where
+ /// it stopped, and a folder that fills the budget exactly isn't called cut.
+ #[test]
+ fn a_snapshot_stops_at_its_entry_limit_with_one_skip() {
+ let d = tempfile::tempdir().unwrap();
+ let (folder, blobs) = (d.path().join("proj"), d.path().join("blobs"));
+ for sub in ["a", "b"] {
+ std::fs::create_dir_all(folder.join(sub)).unwrap();
+ for i in 0..10 {
+ std::fs::write(folder.join(format!("{sub}/f{i}")), format!("{sub}{i}")).unwrap();
+ }
+ }
+ let open = || crate::sandbox::safe_fs::Dir::open_strict(&folder).unwrap();
+ // 2 folders + 20 files = 22 entries; a budget of 12 reaches the top and one folder
+ let t = snapshot_within(&blobs, open(), 1 << 30, MAX_DEPTH, 12).unwrap();
+ assert_eq!(t.manifest.files.len(), 10, "{:?}", t.manifest.files);
+ let stops: Vec<&Skip> = t.manifest.skipped.iter().filter(|s| s.why.ends_with(WALK_STOPPED)).collect();
+ assert_eq!(stops.len(), 1, "{:?}", t.manifest.skipped);
+ assert_eq!(stops[0].why, "walk stopped at the 12-entry limit");
+ // Inside one wide folder: cut while listing it
+ let t = snapshot_within(&blobs, open(), 1 << 30, MAX_DEPTH, 5).unwrap();
+ assert!(t.manifest.files.len() <= 5);
+ assert_eq!(t.manifest.skipped.iter().filter(|s| s.why.ends_with(WALK_STOPPED)).count(), 1, "{:?}", t.manifest.skipped);
+ // Exactly the budget: everything, no stop
+ let t = snapshot_within(&blobs, open(), 1 << 30, MAX_DEPTH, 22).unwrap();
+ assert_eq!(t.manifest.files.len(), 20);
+ assert!(t.manifest.skipped.is_empty(), "{:?}", t.manifest.skipped);
+ assert_eq!(MAX_ENTRIES, 4 * MAX_FILES);
+ }
+
+ /// A walk that stopped early can't say a file it never reached was absent: when the run's
+ /// before_run stopped short and its after_run didn't, the files the after_run newly saw look
+ /// created by the run, and a restore must skip them, never delete them.
+ #[test]
+ fn a_restore_never_deletes_a_file_a_stopped_walk_did_not_reach() {
+ let d = tempfile::tempdir().unwrap();
+ let (folder, blobs) = (d.path().join("proj"), d.path().join("blobs"));
+ for sub in ["a", "b"] {
+ std::fs::create_dir_all(folder.join(sub)).unwrap();
+ for i in 0..10 {
+ std::fs::write(folder.join(format!("{sub}/f{i}")), format!("{sub}{i}")).unwrap();
+ }
+ }
+ let open = || crate::sandbox::safe_fs::Dir::open_strict(&folder).unwrap();
+ let before = snapshot_within(&blobs, open(), 1 << 30, MAX_DEPTH, 12).unwrap().manifest;
+ let after = snapshot_within(&blobs, open(), 1 << 30, MAX_DEPTH, 22).unwrap().manifest;
+ let unseen: Vec<String> = changed(&before, &after);
+ assert_eq!(unseen.len(), 10, "{unseen:?}");
+ for p in &unseen {
+ assert_eq!(not_vouched(&before, p).as_deref(), Some("walk stopped at the 12-entry limit"), "{p}");
+ }
+ // A complete walk vouches for an absent path, so a real delete is still planned
+ assert_eq!(not_vouched(&after, "a/new-file"), None);
+ // An unreadable or never-snapshotted folder covers what is under it
+ let m = Manifest { files: vec![], skipped: vec![Skip { path: "x/".into(), why: "folder can't be read".into() }] };
+ assert_eq!(not_vouched(&m, "x/y/z").as_deref(), Some("folder can't be read"));
+ assert_eq!(not_vouched(&m, "xy"), None);
+ }
}
diff --git a/src/server/mod.rs b/src/server/mod.rs
index d769fa1f..a5848c26 100644
--- a/src/server/mod.rs
+++ b/src/server/mod.rs
@@ -40,6 +40,7 @@ pub mod hires;
pub mod concierge;
pub mod rerouting;
pub mod import_routes;
+pub mod isolated_folders_routes;
pub mod approval_modes;
pub mod passwords;
pub mod loose_ends_owner;
@@ -303,6 +304,8 @@ pub fn create_router(state: AppState) -> Router {
.route("/api/kwants/:id/approvals", get(approval_modes::get_kwant).put(approval_modes::put_kwant))
.route("/api/settings", get(routes::get_settings).post(routes::save_settings))
.route("/api/settings/computer", get(computer::get_computer).put(computer::put_computer))
+ .route("/api/isolated-folders", get(isolated_folders_routes::list))
+ .route("/api/isolated-folders/forget", post(isolated_folders_routes::forget))
.route("/api/settings/computer/window", put(computer::put_window))
.route("/api/settings/computer/browser", post(computer::retry_browser))
.route("/api/system/directories", get(routes::list_system_directories))
diff --git a/tests/host_git_calls_test.rs b/tests/host_git_calls_test.rs
index 0f5e5620..b87a31b1 100644
--- a/tests/host_git_calls_test.rs
+++ b/tests/host_git_calls_test.rs
@@ -1,12 +1,569 @@
//! D4c / S-13 (agents in the VM): kwant starts git on this computer only through
//! `server::dev::git::host_git_command`, which forces `GIT_CONFIG_NOSYSTEM=1` and turns off
//! hooks, fsmonitor and the pager. It is built from its blocking twin
-//! `host_git_command_blocking` (used by Windows' `git_bash`), the one line that starts git. This
-//! fails when anything else in `src/` (outside test code) starts git itself.
+//! `host_git_command_blocking`, whose `Command::new(bin)` is the one line that starts git.
+//!
+//! #446 should-fix 8: the first version of this test cut each file at its first `#[cfg(test)]`
+//! and matched the literal text `Command::new("git")`, so `Command::new(GIT)`, a `"git"` kept in
+//! a variable, a path like `"/usr/bin/git"`, a renamed `Command`, or any code after a test-only
+//! function in the middle of a file all passed. This version reads `src/` as Rust tokens and
+//! proves the claim from both ends:
+//!
+//! 1. **Every process start is accounted for.** Each `Command::new(…)` outside test code is either
+//! a string literal naming a program that isn't git (a shell must be listed in [`SHELLS_OK`]
+//! with what it runs), or an expression listed in [`DYNAMIC_OK`] with where the program comes
+//! from. The helper's `bin` is the only git entry. A renamed `Command` (`use … Command as X`)
+//! and the other ways to start a program (`libc::exec*`, `posix_spawn`, `CreateProcess…`) fail
+//! outright. A list entry nothing matches fails too, so the lists stay the exact inventory.
+//! 2. **The word git goes only where it's safe.** Every string literal that names git (any case,
+//! any folder, with or without `.exe`) must be a match pattern, a comparison, an item in a word
+//! list, an argument to a listed call (the helper, or `run`/`run_with`/`version` in
+//! `server/dev/git.rs`, which have no spawn of their own besides the helper), or the value of a
+//! listed label binding (`const GIT: &str = "git"`, `let provider = match … { … => "git" }`).
+//! `let bin = "git"` fails, so a git name can't travel to a listed dynamic spawn either.
+//!
+//! The scanner's own tests at the end feed it each way around the old check.
-use std::path::Path;
+use std::collections::{BTreeMap, BTreeSet};
+use std::path::{Path, PathBuf};
-fn rs_files(dir: &Path, out: &mut Vec<std::path::PathBuf>) {
+/// `Command::new` arguments that aren't string literals, by file (relative to `src/`) and the
+/// argument's tokens as written. Each says where the program comes from and why it isn't git.
+const DYNAMIC_OK: &[(&str, &str, &str)] = &[
+ ("server/dev/git.rs", "bin", "THE git helper (host_git_command_blocking): adds the safe -c flags and GIT_CONFIG_NOSYSTEM"),
+ ("drivers/cli.rs", "bin", "the AI CLI (claude/codex/grok) found by find_cli_binary"),
+ ("drivers/cli.rs", "node", "node, to run a CLI's .js entry point"),
+ ("documents/reader.rs", "&self.bin", "the document reader's own program (pdftotext etc.)"),
+ ("zombie/classify.rs", "&self.bin", "the zombie classifier's model runner"),
+ ("tools/shell.rs", "shell_program()?", "the bot's own shell tool under its approval settings (sh/bash/cmd), not a call kwant makes for itself"),
+ ("setup.rs", "&command", "a CLI being checked with --version during setup"),
+ ("setup.rs", "&chrome", "Chrome for Testing, during setup"),
+ ("setup.rs", "&py", "python, during setup"),
+ ("setup.rs", "&cmd.argv[_]", "an install command from setup's fixed recipes"),
+ ("setup.rs", "npm", "npm, to find its global prefix"),
+ ("server/video.rs", "bin", "ffmpeg/ffprobe"),
+ ("server/engine_login.rs", "&bin", "the AI CLI's own sign-in command"),
+ ("server/dev/scan/gitleaks.rs", "bin", "gitleaks (reads files; never runs git)"),
+ ("server/dev/prepush.rs", "bin", "semgrep, found on PATH by which(\"semgrep\"); scans a temp copy of the pushed files, never runs git (0.8.0 B2)"),
+ ("sandbox/computer.rs", "chrome", "the local Chrome binary"),
+ ("sandbox/computer.rs", "&chrome", "the local Chrome binary"),
+ ("sandbox/chrome_download.rs", "bin", "the downloaded Chrome, checked with --version"),
+ ("router/sidecar.rs", "&cmd.argv[_]", "the router sidecar's install recipe"),
+ ("router/sidecar.rs", "bin", "the router sidecar binary"),
+ ("mcp/client.rs", "program", "a stdio MCP server the person added (refused in recorded folders, D4/M2)"),
+];
+
+/// Shells started by name, with what they run. A shell can run git, so each is listed.
+/// Empty: the `powershell` (fsx.rs) and `cmd` (server/gitfile.rs) calls are in their test modules,
+/// which the scan skips.
+const SHELLS_OK: &[(&str, &str, &str)] = &[];
+
+/// `name = "git"` bindings, and `let name = match … { … => "git" }`: a label, never a program.
+const BINDINGS_OK: &[(&str, &str)] = &[
+ ("db/dev_mode.rs", "GIT"),
+ // A repo's provider label ("git" or "github") for the repos list
+ ("server/dev/routes.rs", "provider"),
+];
+
+/// Calls a git-naming literal may be an argument of, by file (`*` = any file).
+const CALLS_OK: &[(&str, &str)] = &[
+ ("*", "host_git_command"),
+ ("*", "host_git_command_blocking"),
+ ("*", "contains_key"),
+ ("*", "starts_with"),
+ ("*", "ends_with"),
+ // A JSON error's code (`coded(status, "git", message)`)
+ ("server/dev/routes.rs", "coded"),
+ // The pre-push gate (0.8.0 B2) reads a bot's shell command to spot `git push`: its cheap
+ // `lower.contains("git")` pre-check and the word test `w.rsplit('/').next() == Some("git")`.
+ // Both only read the command text; the gate never starts git itself.
+ ("server/dev/prepush.rs", "contains"),
+ ("server/dev/prepush.rs", "Some"),
+ ("server/dev/git.rs", "run"),
+ ("server/dev/git.rs", "run_with"),
+ ("server/dev/git.rs", "version"),
+];
+
+const SHELLS: &[&str] = &["sh", "bash", "zsh", "dash", "fish", "cmd", "powershell", "pwsh"];
+
+#[derive(Debug, Clone, PartialEq)]
+enum T {
+ Ident(String),
+ Str(String),
+ Punct(String),
+ Other,
+}
+
+#[derive(Debug, Clone)]
+struct Tok {
+ t: T,
+ line: usize,
+}
+
+/// A small Rust lexer: comments dropped (nested block comments too), string, raw string, byte
+/// and char literals read whole, so nothing inside a comment or a string looks like code.
+fn lex(src: &str) -> Vec<Tok> {
+ let b: Vec<char> = src.chars().collect();
+ let (mut i, mut line, mut out) = (0usize, 1usize, Vec::new());
+ let ident_start = |c: char| c == '_' || c.is_alphabetic();
+ let ident_char = |c: char| c == '_' || c.is_alphanumeric();
+ while i < b.len() {
+ let c = b[i];
+ if c == '\n' {
+ line += 1;
+ i += 1;
+ } else if c.is_whitespace() {
+ i += 1;
+ } else if c == '/' && b.get(i + 1) == Some(&'/') {
+ while i < b.len() && b[i] != '\n' {
+ i += 1;
+ }
+ } else if c == '/' && b.get(i + 1) == Some(&'*') {
+ let mut depth = 0;
+ while i < b.len() {
+ if b[i] == '/' && b.get(i + 1) == Some(&'*') {
+ depth += 1;
+ i += 2;
+ } else if b[i] == '*' && b.get(i + 1) == Some(&'/') {
+ depth -= 1;
+ i += 2;
+ if depth == 0 {
+ break;
+ }
+ } else {
+ if b[i] == '\n' {
+ line += 1;
+ }
+ i += 1;
+ }
+ }
+ } else if let Some((value, len, lines)) = string_at(&b, i) {
+ out.push(Tok { t: T::Str(value), line });
+ line += lines;
+ i += len;
+ } else if c == '\'' {
+ // A char literal ('x', '\n', '\'', '\u{1F600}') or a lifetime ('a)
+ let close = if b.get(i + 1) == Some(&'\\') {
+ (i + 2..b.len().min(i + 12)).find(|&j| b[j] == '\'' && j > i + 2)
+ } else if b.get(i + 2) == Some(&'\'') {
+ Some(i + 2)
+ } else {
+ None
+ };
+ match close {
+ Some(j) => {
+ out.push(Tok { t: T::Other, line });
+ i = j + 1;
+ }
+ None => {
+ i += 1;
+ while i < b.len() && ident_char(b[i]) {
+ i += 1;
+ }
+ out.push(Tok { t: T::Other, line });
+ }
+ }
+ } else if ident_start(c) {
+ let s = i;
+ if c == 'r' && b.get(i + 1) == Some(&'#') && b.get(i + 2).is_some_and(|&c| ident_start(c)) {
+ i += 2;
+ }
+ let from = i;
+ while i < b.len() && ident_char(b[i]) {
+ i += 1;
+ }
+ let _ = s;
+ out.push(Tok { t: T::Ident(b[from..i].iter().collect()), line });
+ } else if c.is_ascii_digit() {
+ while i < b.len() && (ident_char(b[i]) || b[i] == '.' && b.get(i + 1).is_some_and(|c| c.is_ascii_digit())) {
+ i += 1;
+ }
+ out.push(Tok { t: T::Other, line });
+ } else {
+ let two: String = b[i..b.len().min(i + 2)].iter().collect();
+ let p = if ["::", "=>", "==", "!=", "->", "&&", "||"].contains(&two.as_str()) { two } else { c.to_string() };
+ i += p.chars().count();
+ out.push(Tok { t: T::Punct(p), line });
+ }
+ }
+ out
+}
+
+/// A string literal starting at `i` ("…", b"…", c"…", r"…", r#"…"#, br#"…"#): its rough value,
+/// its length in chars and the newlines in it.
+fn string_at(b: &[char], i: usize) -> Option<(String, usize, usize)> {
+ let mut j = i;
+ if matches!(b.get(j), Some('b') | Some('c')) {
+ j += 1;
+ }
+ let raw = b.get(j) == Some(&'r');
+ if raw {
+ j += 1;
+ }
+ let mut hashes = 0;
+ while raw && b.get(j) == Some(&'#') {
+ hashes += 1;
+ j += 1;
+ }
+ if b.get(j) != Some(&'"') {
+ return None;
+ }
+ // A prefix letter must not be the end of an identifier (`abr"…"` isn't a literal start)
+ if i > 0 && (b[i - 1] == '_' || b[i - 1].is_alphanumeric()) && j > i {
+ return None;
+ }
+ j += 1;
+ let (mut value, mut lines) = (String::new(), 0);
+ while j < b.len() {
+ let c = b[j];
+ if c == '\n' {
+ lines += 1;
+ }
+ if !raw && c == '\\' {
+ if let Some(&n) = b.get(j + 1) {
+ value.push(match n {
+ 'n' => '\n',
+ 't' => '\t',
+ '0' => '\0',
+ other => other,
+ });
+ if n == '\n' {
+ lines += 1;
+ }
+ }
+ j += 2;
+ continue;
+ }
+ if c == '"' && (0..hashes).all(|k| b.get(j + 1 + k) == Some(&'#')) {
+ return Some((value, j + 1 + hashes - i, lines));
+ }
+ value.push(c);
+ j += 1;
+ }
+ None
+}
+
+fn is_p(t: Option<&Tok>, p: &str) -> bool {
+ matches!(t, Some(Tok { t: T::Punct(x), .. }) if x == p)
+}
+
+fn is_i(t: Option<&Tok>, s: &str) -> bool {
+ matches!(t, Some(Tok { t: T::Ident(x), .. }) if x == s)
+}
+
+/// Index of the innermost group (`(`, `[` or `{`) still open at `k`.
+fn open_group(toks: &[Tok], k: usize) -> Option<usize> {
+ let mut depth = 0i32;
+ for j in (0..k).rev() {
+ if let T::Punct(p) = &toks[j].t {
+ match p.as_str() {
+ ")" | "]" | "}" => depth += 1,
+ "(" | "[" | "{" if depth == 0 => return Some(j),
+ "(" | "[" | "{" => depth -= 1,
+ _ => {}
+ }
+ }
+ }
+ None
+}
+
+/// For a match arm's value at `k`: `NAME` when the match is `let NAME = match … {` (or
+/// `let mut NAME`). Anything else (a match returned, passed or assigned elsewhere) is `None`.
+fn match_binding(toks: &[Tok], k: usize) -> Option<String> {
+ let body = open_group(toks, k)?;
+ if !is_p(toks.get(body), "{") {
+ return None;
+ }
+ // Back over the scrutinee (parentheses and all) to `match`
+ let mut depth = 0i32;
+ let mut j = body;
+ let kw = loop {
+ j = j.checked_sub(1)?;
+ match &toks[j].t {
+ T::Punct(p) if p == ")" || p == "]" => depth += 1,
+ T::Punct(p) if p == "(" || p == "[" => depth -= 1,
+ T::Punct(p) if depth == 0 && (p == "{" || p == "}" || p == ";") => return None,
+ T::Ident(m) if depth == 0 && m == "match" => break j,
+ _ => {}
+ }
+ };
+ if !is_p(toks.get(kw.checked_sub(1)?), "=") {
+ return None;
+ }
+ let name = kw.checked_sub(2)?;
+ let T::Ident(n) = &toks[name].t else { return None };
+ let before = name.checked_sub(1).and_then(|b| toks.get(b));
+ (is_i(before, "let") || (is_i(before, "mut") && is_i(toks.get(name.checked_sub(2)?), "let"))).then(|| n.clone())
+}
+
+/// Index of the token closing the group opened at `open` (`(`, `[` or `{`).
+fn close_of(toks: &[Tok], open: usize) -> usize {
+ let mut depth = 0i32;
+ for (k, t) in toks.iter().enumerate().skip(open) {
+ if let T::Punct(p) = &t.t {
+ match p.as_str() {
+ "(" | "[" | "{" => depth += 1,
+ ")" | "]" | "}" => {
+ depth -= 1;
+ if depth == 0 {
+ return k;
+ }
+ }
+ _ => {}
+ }
+ }
+ }
+ toks.len() - 1
+}
+
+/// Whether the attribute tokens (inside `#[…]`) make the next item test-only: `test`,
+/// `tokio::test` (any `…::test`), `cfg(test)`, `cfg(all(test, …))`. `cfg(not(test))` doesn't.
+fn test_attr(inner: &[Tok]) -> bool {
+ let last_is_test = matches!(inner.last(), Some(Tok { t: T::Ident(x), .. }) if x == "test")
+ && inner.iter().all(|t| matches!(&t.t, T::Ident(_)) || matches!(&t.t, T::Punct(p) if p == "::"));
+ if last_is_test {
+ return true;
+ }
+ if !is_i(inner.first(), "cfg") {
+ return false;
+ }
+ inner.iter().enumerate().any(|(k, t)| t.t == T::Ident("test".into()) && !(k >= 2 && is_i(inner.get(k - 2), "not")))
+}
+
+/// The tokens of non-test code, and the `mod name;` declarations that are test-only.
+fn strip_tests(toks: Vec<Tok>) -> (Vec<Tok>, Vec<String>) {
+ let (mut out, mut test_mods) = (Vec::new(), Vec::new());
+ let mut i = 0;
+ // `#![cfg(test)]` at the top: the whole file is test code
+ if is_p(toks.first(), "#") && is_p(toks.get(1), "!") && is_p(toks.get(2), "[") {
+ let end = close_of(&toks, 2);
+ if test_attr(&toks[3..end]) {
+ return (Vec::new(), Vec::new());
+ }
+ }
+ while i < toks.len() {
+ if is_p(toks.get(i), "#") && is_p(toks.get(i + 1), "[") {
+ let end = close_of(&toks, i + 1);
+ if test_attr(&toks[i + 2..end]) {
+ // Skip any further attributes, then the item: to its `;` or its `{…}`
+ let mut k = end + 1;
+ while is_p(toks.get(k), "#") && is_p(toks.get(k + 1), "[") {
+ k = close_of(&toks, k + 1) + 1;
+ }
+ let item_start = k;
+ let mut depth = 0i32;
+ while k < toks.len() {
+ match &toks[k].t {
+ T::Punct(p) if p == "(" || p == "[" => depth += 1,
+ T::Punct(p) if p == ")" || p == "]" => depth -= 1,
+ T::Punct(p) if p == ";" && depth == 0 => break,
+ T::Punct(p) if p == "{" => {
+ k = close_of(&toks, k);
+ break;
+ }
+ _ => {}
+ }
+ k += 1;
+ }
+ // `mod name;` (optionally `pub`): that file is test code
+ let item: Vec<&Tok> = toks[item_start..k.min(toks.len())].iter().collect();
+ if let Some(pos) = item.iter().position(|t| t.t == T::Ident("mod".into())) {
+ if let Some(Tok { t: T::Ident(name), .. }) = item.get(pos + 1) {
+ if is_p(toks.get(k), ";") {
+ test_mods.push(name.clone());
+ }
+ }
+ }
+ i = k + 1;
+ continue;
+ }
+ }
+ out.push(toks[i].clone());
+ i += 1;
+ }
+ (out, test_mods)
+}
+
+/// Lowercased file name without folders and without `.exe`: what a program literal names.
+fn program_name(s: &str) -> String {
+ let base = s.rsplit(['/', '\\']).next().unwrap_or(s).to_ascii_lowercase();
+ base.strip_suffix(".exe").map(str::to_string).unwrap_or(base)
+}
+
+fn text(toks: &[Tok]) -> String {
+ toks.iter()
+ .map(|t| match &t.t {
+ T::Ident(s) | T::Punct(s) => s.clone(),
+ T::Str(s) => format!("{s:?}"),
+ T::Other => "_".into(),
+ })
+ .collect()
+}
+
+#[derive(Default)]
+struct Lists<'a> {
+ dynamic: &'a [(&'a str, &'a str, &'a str)],
+ shells: &'a [(&'a str, &'a str, &'a str)],
+ bindings: &'a [(&'a str, &'a str)],
+ calls: &'a [(&'a str, &'a str)],
+}
+
+#[derive(Default, Debug)]
+struct Report {
+ problems: Vec<String>,
+ /// List entries that matched, as (file, key).
+ used: BTreeSet<(String, String)>,
+ /// Every git start found: file and line.
+ git_starts: Vec<String>,
+}
+
+/// Scans one file's non-test tokens.
+fn scan_file(file: &str, toks: &[Tok], lists: &Lists, r: &mut Report) {
+ let at = |k: usize| format!("{file}:{}", toks[k].line);
+ for k in 0..toks.len() {
+ // Other ways to start a program
+ if let T::Ident(name) = &toks[k].t {
+ let after_libc = k >= 2 && is_p(toks.get(k - 1), "::") && (is_i(toks.get(k - 2), "libc") || is_i(toks.get(k - 2), "unistd"));
+ let exec_like = name.starts_with("exec") || ["posix_spawn", "posix_spawnp", "fork", "vfork", "system", "popen"].contains(&name.as_str());
+ if after_libc && exec_like || name.starts_with("CreateProcess") || name.starts_with("ShellExecute") {
+ r.problems.push(format!("{}: starts a program with {name}", at(k)));
+ }
+ if name == "Command" && is_i(toks.get(k + 1), "as") {
+ r.problems.push(format!("{}: Command renamed with `as`, which hides its spawns from this test", at(k)));
+ }
+ }
+ // Command::new(…)
+ if is_i(toks.get(k), "Command") && is_p(toks.get(k + 1), "::") && is_i(toks.get(k + 2), "new") && is_p(toks.get(k + 3), "(") {
+ let end = close_of(toks, k + 3);
+ let arg = &toks[k + 4..end];
+ match arg {
+ [Tok { t: T::Str(s), .. }] => {
+ let p = program_name(s);
+ if p == "git" {
+ r.problems.push(format!("{}: Command::new({s:?}) starts git without the helper", at(k)));
+ } else if SHELLS.contains(&p.as_str()) {
+ match lists.shells.iter().find(|(f, sh, _)| *f == file && *sh == p) {
+ Some(_) => {
+ r.used.insert((file.to_string(), format!("shell:{p}")));
+ }
+ None => r.problems.push(format!("{}: starts the shell {s:?}, which can run git; list it in SHELLS_OK with what it runs", at(k))),
+ }
+ }
+ }
+ _ => {
+ let a = text(arg);
+ match lists.dynamic.iter().find(|(f, e, _)| *f == file && *e == a) {
+ Some((_, _, why)) => {
+ r.used.insert((file.to_string(), format!("dyn:{a}")));
+ if why.starts_with("THE git helper") {
+ r.git_starts.push(at(k));
+ }
+ }
+ None => r.problems.push(format!("{}: Command::new({a}) starts a program this test can't name; list it in DYNAMIC_OK with where it comes from", at(k))),
+ }
+ }
+ }
+ }
+ // Where a literal naming git goes
+ if let T::Str(s) = &toks[k].t {
+ if program_name(s) != "git" {
+ continue;
+ }
+ let (prev, next) = (k.checked_sub(1).and_then(|p| toks.get(p)), toks.get(k + 1));
+ let pattern = is_p(next, "=>") || is_p(next, "|") || is_p(prev, "|");
+ let some_pattern = is_p(prev, "(") && k >= 2 && is_i(toks.get(k - 2), "Some") && is_p(next, ")") && (is_p(toks.get(k + 2), "=>") || is_p(toks.get(k + 2), "|"));
+ let compare = is_p(prev, "==") || is_p(prev, "!=") || is_p(next, "==") || is_p(next, "!=");
+ // An item of a `[…]` word list: the innermost open group is a `[`
+ let in_list = (is_p(prev, "[") || is_p(prev, ",")) && {
+ let mut depth = 0i32;
+ let mut opener = None;
+ for t in toks[..k].iter().rev() {
+ if let T::Punct(p) = &t.t {
+ match p.as_str() {
+ ")" | "]" | "}" => depth += 1,
+ "(" | "[" | "{" if depth == 0 => {
+ opener = Some(p.clone());
+ break;
+ }
+ "(" | "[" | "{" => depth -= 1,
+ _ => {}
+ }
+ }
+ }
+ opener.as_deref() == Some("[")
+ };
+ // An argument (any position) of a listed call: the innermost open group is a `(`
+ // right after the call's name
+ let call = (is_p(prev, "(") || is_p(prev, ",")) && {
+ match open_group(toks, k) {
+ Some(o) if is_p(toks.get(o), "(") && o >= 1 => match &toks[o - 1].t {
+ T::Ident(f) => lists.calls.iter().any(|(cf, name)| (*cf == "*" || *cf == file) && name == f),
+ _ => false,
+ },
+ _ => false,
+ }
+ };
+ // A match arm's value, the match bound to a listed label: `let NAME = match … { … => "git" }`
+ let arm_label = is_p(prev, "=>") && (is_p(next, ",") || is_p(next, "}")) && {
+ match match_binding(toks, k) {
+ Some(n) if lists.bindings.iter().any(|(f, b)| *f == file && *b == n) => {
+ r.used.insert((file.to_string(), format!("bind:{n}")));
+ true
+ }
+ _ => false,
+ }
+ };
+ let binding = is_p(prev, "=") && k >= 4 && {
+ // `NAME: &str = "git"` or `NAME = "git"`
+ let name = toks[..k - 1].iter().rev().find_map(|t| match &t.t {
+ T::Ident(n) if n != "str" && n != "static" => Some(n.clone()),
+ _ => None,
+ });
+ match name {
+ Some(n) if lists.bindings.iter().any(|(f, b)| *f == file && *b == n) => {
+ r.used.insert((file.to_string(), format!("bind:{n}")));
+ true
+ }
+ _ => false,
+ }
+ };
+ if !(pattern || some_pattern || compare || in_list || call || binding || arm_label) {
+ r.problems.push(format!("{}: {s:?} goes somewhere this test can't follow (a variable, a format, a call it doesn't know); git must start through host_git_command", at(k)));
+ }
+ }
+ }
+}
+
+/// Scans every file: `files` are (path relative to `src/`, source).
+fn scan(files: &[(String, String)], lists: &Lists) -> Report {
+ let mut r = Report::default();
+ let mut stripped: BTreeMap<String, Vec<Tok>> = BTreeMap::new();
+ let mut test_files: BTreeSet<String> = BTreeSet::new();
+ for (path, src) in files {
+ let (toks, mods) = strip_tests(lex(src));
+ // A module's own folder: `a/mod.rs`, `lib.rs`, `main.rs` → its folder; `a/b.rs` → `a/b/`
+ let p = Path::new(path);
+ let fname = p.file_name().unwrap().to_string_lossy();
+ let dir = if fname == "mod.rs" || (p.parent() == Some(Path::new("")) && (fname == "lib.rs" || fname == "main.rs")) {
+ p.parent().unwrap().to_path_buf()
+ } else {
+ p.with_extension("")
+ };
+ for m in mods {
+ test_files.insert(dir.join(format!("{m}.rs")).to_string_lossy().into_owned());
+ test_files.insert(dir.join(&m).join("mod.rs").to_string_lossy().into_owned());
+ }
+ stripped.insert(path.clone(), toks);
+ }
+ for (path, toks) in &stripped {
+ if !test_files.contains(path) {
+ scan_file(path, toks, lists, &mut r);
+ }
+ }
+ r
+}
+
+fn rs_files(dir: &Path, out: &mut Vec<PathBuf>) {
for e in std::fs::read_dir(dir).unwrap().flatten() {
let p = e.path();
if p.is_dir() {
@@ -17,31 +574,187 @@ fn rs_files(dir: &Path, out: &mut Vec<std::path::PathBuf>) {
}
}
-/// The file without its `#[cfg(test)]` modules (everything from the first one on; kwant keeps
-/// its unit tests at the end of each file).
-fn non_test(src: &str) -> &str {
- src.find("#[cfg(test)]").map_or(src, |i| &src[..i])
+fn kwant_lists() -> Lists<'static> {
+ Lists { dynamic: DYNAMIC_OK, shells: SHELLS_OK, bindings: BINDINGS_OK, calls: CALLS_OK }
}
#[test]
fn only_the_helper_starts_git() {
let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("src");
- let mut files = Vec::new();
- rs_files(&root, &mut files);
- let mut found = Vec::new();
- for f in files {
- let text = std::fs::read_to_string(&f).unwrap();
- let code = non_test(&text);
- for (n, line) in code.lines().enumerate() {
- let l = line.split("//").next().unwrap_or("");
- let starts_git = l.contains("Command::new(\"git\")") || l.contains("Command::new(\"git.exe\")");
- let helper = f.ends_with("server/dev/git.rs") && l.contains("Command::new(bin)");
- if starts_git || helper {
- found.push(format!("{}:{}", f.strip_prefix(&root).unwrap().display(), n + 1));
- }
- }
- }
- // Exactly one: the line inside `host_git_command_blocking`, which `host_git_command` wraps
- assert_eq!(found.len(), 1, "git started outside host_git_command: {found:?}");
- assert!(found[0].starts_with("server/dev/git.rs:"), "{found:?}");
+ let mut paths = Vec::new();
+ rs_files(&root, &mut paths);
+ let files: Vec<(String, String)> = paths
+ .iter()
+ .map(|p| (p.strip_prefix(&root).unwrap().to_string_lossy().replace('\\', "/"), std::fs::read_to_string(p).unwrap()))
+ .collect();
+ let r = scan(&files, &kwant_lists());
+ assert!(r.problems.is_empty(), "host git safety (D4c):\n{}", r.problems.join("\n"));
+ // Exactly one git start: the helper's
+ assert_eq!(r.git_starts.len(), 1, "{:?}", r.git_starts);
+ assert!(r.git_starts[0].starts_with("server/dev/git.rs:"), "{:?}", r.git_starts);
+ // Every list entry is still needed: the lists are the inventory, not a pass-anything
+ let mut stale = Vec::new();
+ for (f, e, _) in DYNAMIC_OK {
+ if !r.used.contains(&(f.to_string(), format!("dyn:{e}"))) {
+ stale.push(format!("DYNAMIC_OK {f} {e}"));
+ }
+ }
+ for (f, s, _) in SHELLS_OK {
+ if !r.used.contains(&(f.to_string(), format!("shell:{s}"))) {
+ stale.push(format!("SHELLS_OK {f} {s}"));
+ }
+ }
+ for (f, b) in BINDINGS_OK {
+ if !r.used.contains(&(f.to_string(), format!("bind:{b}"))) {
+ stale.push(format!("BINDINGS_OK {f} {b}"));
+ }
+ }
+ assert!(stale.is_empty(), "list entries nothing matches any more: {stale:?}");
+}
+
+/// The scanner itself: each way around the first version of this test is caught.
+mod scanner {
+ use super::*;
+
+ fn problems(src: &str) -> Vec<String> {
+ let lists = Lists {
+ dynamic: &[("server/dev/git.rs", "bin", "THE git helper"), ("a.rs", "program", "listed")],
+ shells: &[],
+ bindings: &[],
+ calls: &[("*", "host_git_command")],
+ };
+ scan(&[("a.rs".into(), src.into())], &lists).problems
+ }
+
+ fn caught(src: &str) {
+ assert!(!problems(src).is_empty(), "not caught:\n{src}");
+ }
+
+ fn passes(src: &str) {
+ let p = problems(src);
+ assert!(p.is_empty(), "flagged:\n{src}\n{p:?}");
+ }
+
+ #[test]
+ fn the_old_literal_is_caught() {
+ caught(r#"fn f() { std::process::Command::new("git").arg("status"); }"#);
+ }
+
+ #[test]
+ fn other_spellings_of_git_are_caught() {
+ caught(r#"fn f() { Command::new("/usr/bin/git"); }"#);
+ caught(r#"fn f() { Command::new("GIT.EXE"); }"#);
+ caught(r##"fn f() { Command::new(r#"git"#); }"##);
+ caught(r#"fn f() { tokio::process::Command::new( "C:\\Program Files\\Git\\cmd\\git.exe" ); }"#);
+ }
+
+ #[test]
+ fn git_through_a_variable_or_constant_is_caught() {
+ caught(r#"const GIT: &str = "git"; fn f() { Command::new(GIT); }"#);
+ caught(r#"fn f() { let bin = "git"; Command::new(bin); }"#);
+ // Even into a spawn the list allows: the name can't get there
+ caught(r#"fn f() { let program = "git"; Command::new(program); }"#);
+ caught(r#"fn f() { Command::new(format!("{}", "git")); }"#);
+ caught(r#"fn f() { Command::new(which("git").unwrap()); }"#);
+ }
+
+ #[test]
+ fn a_name_built_without_the_word_is_caught() {
+ caught(r#"fn f() { Command::new(concat!("gi", "t")); }"#);
+ caught(r#"fn f() { Command::new(String::from_utf8(vec![103, 105, 116]).unwrap()); }"#);
+ }
+
+ #[test]
+ fn a_renamed_command_or_another_spawn_api_is_caught() {
+ caught(r#"use std::process::Command as Run; fn f() { Run::new("ls"); }"#);
+ caught(r#"fn f() { unsafe { libc::execvp(p, a) }; }"#);
+ caught(r#"fn f() { unsafe { libc::posix_spawnp(a, b, c, d, e, g) }; }"#);
+ caught(r#"fn f() { unsafe { CreateProcessW(a) }; }"#);
+ caught(r#"fn f() { Command::new("sh").arg("-c").arg("git status"); }"#);
+ }
+
+ #[test]
+ fn code_after_a_test_only_item_is_still_read() {
+ // The old version stopped reading at the first #[cfg(test)]
+ caught(
+ r#"
+#[cfg(test)]
+fn helper() {}
+fn real() { Command::new("git"); }
+"#,
+ );
+ caught(
+ r#"
+#[test]
+fn t() { let x = [0u8; 4]; }
+fn real() { Command::new("git"); }
+"#,
+ );
+ }
+
+ #[test]
+ fn comments_strings_and_test_modules_are_not_code() {
+ passes(
+ r#"
+// Command::new("git") in a comment
+/* and /* nested */ Command::new("git") */
+fn f() { let msg = "never Command::new(\"git\") here"; let c = 'x'; let l: &'static str = ""; }
+#[cfg(test)]
+mod tests { fn t() { std::process::Command::new("git"); } }
+#[cfg(all(test, unix))]
+mod more { fn t() { Command::new("git"); } }
+#[tokio::test]
+async fn t2() { Command::new("git"); }
+"#,
+ );
+ // A test-only file declared with `#[cfg(test)] mod x;`
+ let lists = Lists { calls: &[], ..Default::default() };
+ let files = vec![("lib.rs".to_string(), "#[cfg(test)]\nmod x;\n".to_string()), ("x.rs".to_string(), r#"fn f() { Command::new("git"); }"#.to_string())];
+ assert!(scan(&files, &lists).problems.is_empty());
+ // …but not cfg(not(test))
+ caught(r#"#[cfg(not(test))] fn f() { Command::new("git"); }"#);
+ }
+
+ #[test]
+ fn safe_uses_of_the_word_pass() {
+ passes(
+ r#"
+fn f(s: &str, w: &[String]) -> bool {
+ host_git_command("git");
+ match s { "git" => true, "hg" | "git" => true, _ => false };
+ let _ = matches!(s, "https" | "git");
+ let _ = matches!(Some(s), Some("git") => 1);
+ let _ = ["npm:", "git", "http"].iter().any(|p| s.starts_with(p));
+ w.iter().any(|x| x == "git") || s == "git" || "git" != s
+}
+fn g() { Command::new(program); Command::new("docker").arg("ps"); }
+"#,
+ );
+ // A dynamic spawn nobody listed
+ caught(r#"fn g() { Command::new(something_else); }"#);
+ }
+
+ #[test]
+ fn a_label_must_be_listed_and_really_a_label() {
+ let lists = Lists {
+ dynamic: &[("server/dev/git.rs", "bin", "THE git helper")],
+ shells: &[],
+ bindings: &[("a.rs", "provider")],
+ calls: &[("*", "host_git_command"), ("a.rs", "coded")],
+ };
+ let check = |src: &str| scan(&[("a.rs".into(), src.into())], &lists).problems;
+ // A listed label binding and a listed call, in any argument position
+ let ok = check(r#"fn f(x: u8) -> u8 { let provider = match (x, 1) { (0, _) => "git", _ => "github" }; coded(500, "git", provider); 0 }"#);
+ assert!(ok.is_empty(), "{ok:?}");
+ // The same match bound to another name, returned, or passed on: caught
+ for src in [
+ r#"fn f(x: u8) { let bin = match x { 0 => "git", _ => "hg" }; }"#,
+ r#"fn f(x: u8) -> &'static str { match x { 0 => "git", _ => "hg" } }"#,
+ r#"fn f(x: u8) { spawn(match x { 0 => "git", _ => "hg" }); }"#,
+ r#"fn f(x: u8) { let provider = if x == 0 { "git" } else { "hg" }; }"#,
+ r#"fn f() { other(1, "git"); }"#,
+ ] {
+ assert!(!check(src).is_empty(), "not caught:\n{src}");
+ }
+ }
}
diff --git a/tests/isolated_folders_forget_test.rs b/tests/isolated_folders_forget_test.rs
new file mode 100644
index 00000000..c7dc5f9b
--- /dev/null
+++ b/tests/isolated_folders_forget_test.rs
@@ -0,0 +1,174 @@
+//! #446 item 6: the person lists the folders isolated bots used and forgets one
+//! (`GET /api/isolated-folders`, `POST /api/isolated-folders/forget`). Contract:
+//! release-080/forget-folder-contract.md. A bot can't do either: if it could, it could plant a
+//! hook in its folder and then have a CLI on this computer load it.
+
+use axum::{
+ body::{to_bytes, Body},
+ extract::ConnectInfo,
+ http::{Request, StatusCode},
+ Router,
+};
+use kwnt::{
+ broker::PermissionBroker,
+ config::Config,
+ db::{isolated_folders::canonical, spaces::SpaceId, Database},
+ router::LayaRouter,
+ server::{
+ auth::{ApiToken, Require},
+ continuity::SelfScope,
+ create_router, mcp_runtime, AppState,
+ },
+ tools::ToolRunner,
+};
+use serde_json::{json, Value};
+use std::net::SocketAddr;
+use std::sync::Arc;
+use tempfile::{tempdir, TempDir};
+use tower::ServiceExt;
+
+const TOKEN: &str = "test-api-token-0123456789";
+const LOCAL: &str = "127.0.0.1:50000";
+const REMOTE: &str = "203.0.113.9:50000";
+
+async fn setup() -> (Router, AppState, TempDir) {
+ let tmp = tempdir().unwrap();
+ let data = tmp.path().join("data");
+ let db = Database::init(&data).await.unwrap();
+ let config = Config { data_dir: data.clone(), browser_cdp_url: Some("http://127.0.0.1:9".into()), ..Config::default() };
+ let mut state = AppState::new(
+ config.clone(),
+ db,
+ ToolRunner::new(data.join("workspace")),
+ PermissionBroker::new(),
+ LayaRouter::new(config.laya_url.clone()),
+ );
+ state.api_token = Arc::new(ApiToken::for_tests(TOKEN, Require::Auto, config.port));
+ (create_router(state.clone()), state, tmp)
+}
+
+async fn call(app: &Router, peer: &str, method: &str, uri: &str, body: Option<Value>, bearer: Option<&str>) -> (StatusCode, Value) {
+ let host = if peer == LOCAL { "127.0.0.1:8799" } else { "kwnt.example.com" };
+ let mut req = Request::builder().method(method).uri(uri).header("host", host).header("content-type", "application/json");
+ if let Some(t) = bearer {
+ req = req.header("authorization", format!("Bearer {t}"));
+ }
+ let mut req = req.body(body.map(|b| Body::from(b.to_string())).unwrap_or_else(Body::empty)).unwrap();
+ req.extensions_mut().insert(ConnectInfo(peer.parse::<SocketAddr>().unwrap()));
+ let resp = app.clone().oneshot(req).await.unwrap();
+ let status = resp.status();
+ let bytes = to_bytes(resp.into_body(), usize::MAX).await.unwrap();
+ (status, serde_json::from_slice(&bytes).unwrap_or(Value::Null))
+}
+
+/// A POST with a raw body, and a content type only when one is given.
+async fn post_raw(app: &Router, uri: &str, body: &'static str, content_type: Option<&str>) -> (StatusCode, Value) {
+ let mut req = Request::builder().method("POST").uri(uri).header("host", "127.0.0.1:8799");
+ if let Some(ct) = content_type {
+ req = req.header("content-type", ct);
+ }
+ let mut req = req.body(Body::from(body)).unwrap();
+ req.extensions_mut().insert(ConnectInfo(LOCAL.parse::<SocketAddr>().unwrap()));
+ let resp = app.clone().oneshot(req).await.unwrap();
+ let status = resp.status();
+ let bytes = to_bytes(resp.into_body(), usize::MAX).await.unwrap();
+ (status, serde_json::from_slice(&bytes).unwrap_or(Value::Null))
+}
+
+async fn turn_token(state: &AppState, folder: &std::path::Path) -> (String, String) {
+ let bot = state.db.list_kwants(&SpaceId::default_space()).await.unwrap().remove(0);
+ let scope = SelfScope { kwant_id: bot.id.clone(), kwant_name: bot.name.clone(), ..Default::default() };
+ let (_, token) = mcp_runtime::prepare_turn_with_self(state, &bot, None, Some(folder.to_path_buf()), Some(scope))
+ .await
+ .unwrap();
+ (bot.id, token)
+}
+
+#[tokio::test]
+async fn the_person_lists_and_forgets_a_folder_and_a_bot_cant() {
+ let (app, state, tmp) = setup().await;
+ let proj = tmp.path().join("proj");
+ let other = tmp.path().join("other");
+ std::fs::create_dir_all(proj.join(".claude")).unwrap();
+ std::fs::create_dir_all(&other).unwrap();
+ std::fs::write(proj.join(".claude/settings.json"), r#"{"hooks":{}}"#).unwrap();
+ let (bot_id, turn) = turn_token(&state, &proj).await;
+ state.db.record_isolated_folder(&canonical(&proj), &bot_id).await.unwrap();
+ state.db.record_isolated_folder(&canonical(&other), "deleted-bot").await.unwrap();
+
+ let (s, v) = call(&app, LOCAL, "GET", "/api/isolated-folders", None, None).await;
+ assert_eq!(s, StatusCode::OK, "{v}");
+ let folders = v["folders"].as_array().unwrap();
+ assert_eq!(folders.len(), 2, "{v}");
+ let p = folders.iter().find(|f| f["path"] == canonical(&proj).to_string_lossy().as_ref()).unwrap();
+ assert_eq!(p["first_bot_id"], bot_id.as_str());
+ assert!(p["first_bot_name"].is_string(), "{p}");
+ assert_eq!(p["exists"], true);
+ assert_eq!(p["check_first"], json!([".claude/settings.json"]));
+ assert!(p["first_used_at"].is_string() && p["last_used_at"].is_string(), "{p}");
+ let o = folders.iter().find(|f| f["first_bot_id"] == "deleted-bot").unwrap();
+ assert_eq!(o["first_bot_name"], Value::Null, "a deleted bot has no name: {o}");
+
+ // A bot's own turn token is refused on both routes, from this machine too; nothing changes
+ let path = canonical(&proj).to_string_lossy().into_owned();
+ let (s, v) = call(&app, LOCAL, "GET", "/api/isolated-folders", None, Some(&turn)).await;
+ assert_eq!(s, StatusCode::FORBIDDEN, "{v}");
+ assert!(v.get("folders").is_none(), "{v}");
+ let (s, _) = call(&app, LOCAL, "POST", "/api/isolated-folders/forget", Some(json!({ "path": path })), Some(&turn)).await;
+ assert_eq!(s, StatusCode::FORBIDDEN);
+ // Another machine without the API token
+ let (s, _) = call(&app, REMOTE, "POST", "/api/isolated-folders/forget", Some(json!({ "path": path })), None).await;
+ assert_eq!(s, StatusCode::UNAUTHORIZED);
+ assert!(state.db.isolated_folder_for(&proj).await.unwrap().is_some(), "still recorded");
+
+ // Bad bodies
+ for body in [json!({}), json!({ "path": "" }), json!({ "path": "relative/proj" }), json!({ "path": 5 }), json!("x")] {
+ let (s, v) = call(&app, LOCAL, "POST", "/api/isolated-folders/forget", Some(body.clone()), None).await;
+ assert_eq!(s, StatusCode::BAD_REQUEST, "{body}: {v}");
+ assert_eq!(v["code"], "invalid");
+ }
+ // #462 review must-fix 3: a NUL, a path over 4096 bytes, a body that isn't JSON and one sent
+ // without a JSON content type are 400 too, with the same code; exactly 4096 bytes is allowed
+ // (and isn't recorded, so 404)
+ let long = |n: usize| format!("/{}", "a".repeat(n - 1));
+ for body in [json!({ "path": "/a\u{0000}b" }), json!({ "path": long(4097) })] {
+ let (s, v) = call(&app, LOCAL, "POST", "/api/isolated-folders/forget", Some(body.clone()), None).await;
+ assert_eq!(s, StatusCode::BAD_REQUEST, "{}: {v}", &body.to_string()[..40]);
+ assert_eq!(v["code"], "invalid");
+ }
+ assert_eq!(long(4096).len(), 4096);
+ let (s, v) = call(&app, LOCAL, "POST", "/api/isolated-folders/forget", Some(json!({ "path": long(4096) })), None).await;
+ assert_eq!(s, StatusCode::NOT_FOUND, "4096 bytes is a path kwnt looks up: {v}");
+ assert_eq!(v["code"], "not_recorded");
+ for (body, ct) in [("not json", Some("application/json")), (r#"{"path":"/x"}"#, None), (r#"{"path":"/x"}"#, Some("text/plain"))] {
+ let (s, v) = post_raw(&app, "/api/isolated-folders/forget", body, ct).await;
+ assert_eq!(s, StatusCode::BAD_REQUEST, "{body} as {ct:?}: {v}");
+ assert_eq!(v["code"], "invalid", "{body} as {ct:?}");
+ }
+ assert!(state.db.isolated_folder_for(&proj).await.unwrap().is_some(), "still recorded after every refusal");
+ // A folder that isn't recorded, even one inside a recorded folder
+ let inside = canonical(&proj).join(".claude").to_string_lossy().into_owned();
+ let (s, v) = call(&app, LOCAL, "POST", "/api/isolated-folders/forget", Some(json!({ "path": inside })), None).await;
+ assert_eq!(s, StatusCode::NOT_FOUND, "{v}");
+ assert_eq!(v["code"], "not_recorded");
+
+ // The person forgets it: only that record goes, and kwnt trusts the folder again
+ assert!(state.db.host_command_refusal(&proj).await.is_some());
+ let (s, v) = call(&app, LOCAL, "POST", "/api/isolated-folders/forget", Some(json!({ "path": path })), None).await;
+ assert_eq!(s, StatusCode::OK, "{v}");
+ assert_eq!(v["forgotten"], path.as_str());
+ assert_eq!(v["folders"].as_array().unwrap().len(), 1, "the other folder stays: {v}");
+ assert!(state.db.host_command_refusal(&proj).await.is_none(), "host commands run in it again");
+ let (s, v) = call(&app, LOCAL, "POST", "/api/isolated-folders/forget", Some(json!({ "path": path })), None).await;
+ assert_eq!(s, StatusCode::NOT_FOUND, "twice: {v}");
+
+ // A folder deleted since is still listed, and forgotten by the path the list shows
+ std::fs::remove_dir_all(&other).unwrap();
+ let (_, v) = call(&app, LOCAL, "GET", "/api/isolated-folders", None, None).await;
+ let gone = &v["folders"][0];
+ assert_eq!(gone["exists"], false, "{v}");
+ assert_eq!(gone["check_first"], json!([]));
+ let (s, v) = call(&app, REMOTE, "POST", "/api/isolated-folders/forget", Some(json!({ "path": gone["path"] })), Some(TOKEN)).await;
+ assert_eq!(s, StatusCode::OK, "with the API token from another machine: {v}");
+ assert_eq!(v["folders"], json!([]));
+}