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.
Rust ai-agentsai-assistantai-botautomationbotbots-teamchatbotclaude-duetgrokgrok-botgrok-bot-alternativeharnessllmmulti-agentopenai-dotsopenbotpersonal-agentrustself-hostedselfhosted-ai
Checkpoints: git_head never follows a symlink or leaves .git (0.7.7) (#443)
Oleksandr Ivanchenko20d3d0e3e7de
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex d1605747..ff6f4c88 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -8,6 +8,9 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).## Unreleased+### Fixed+- **A checkpoint's git commit only comes from the task's own git files.** When a mission takes a checkpoint, kwant notes the commit the task's folder is on. It now never follows a symlink inside `.git`, ignores a `ref:` that points outside it, skips FIFOs and oversized files, and keeps the value only when it's a real 40- or 64-character commit id. Before, a bot that could write its task folder could make a checkpoint show the first 64 characters of another file kwant can read. (#443)+## [Mac 0.7.6] - 2026-11-08### Addeddiff --git a/src/server/missions/checkpoints.rs b/src/server/missions/checkpoints.rsindex 1e663cd2..f2e21fd3 100644--- a/src/server/missions/checkpoints.rs+++ b/src/server/missions/checkpoints.rs@@ -195,19 +195,91 @@ fn store_blob(blobs: &FsPath, src: &FsPath) -> std::io::Result<String> {Ok(sha)}+/// HEAD and loose ref files are tiny; a bigger one isn't git's.+const GIT_REF_MAX: u64 = 4 * 1024;+/// packed-refs can list many refs, but never this many for a task folder.+const GIT_PACKED_MAX: u64 = 1024 * 1024;+/// The commit the folder's git checkout is on, if it is one (read-only info).+///+/// The folder is written by the task's bots, so everything under `.git` is untrusted: it never+/// follows a symlink (at any component), never opens anything but a regular file (a FIFO can't+/// block it), reads at most [`GIT_REF_MAX`] / [`GIT_PACKED_MAX`] bytes, only follows a `ref:`+/// that is a plain `refs/...` name, and only returns 40 or 64 hex characters. Anything else,+/// including a `.git` file (a `gitdir:` worktree pointer), is `None`.fn git_head(folder: &FsPath) -> Option<String> {let git = folder.join(".git");- let head = std::fs::read_to_string(git.join("HEAD")).ok()?;+ if !std::fs::symlink_metadata(&git).ok()?.file_type().is_dir() {+ return None;+ }+ let head = read_git_file(&git, "HEAD", GIT_REF_MAX)?;let head = head.trim();let Some(r) = head.strip_prefix("ref: ") else {- return Some(head.chars().take(64).collect());+ return commit_id(head);};- if let Ok(s) = std::fs::read_to_string(git.join(r)) {- return Some(s.trim().chars().take(64).collect());+ let r = r.trim();+ if !plain_ref(r) {+ return None;+ }+ if let Some(s) = read_git_file(&git, r, GIT_REF_MAX) {+ return commit_id(s.trim());+ }+ let packed = read_git_file(&git, "packed-refs", GIT_PACKED_MAX)?;+ packed+ .lines()+ .filter(|l| !l.starts_with('#') && !l.starts_with('^'))+ .find_map(|l| l.split_once(' ').filter(|(_, name)| name.trim_end() == r).map(|(sha, _)| sha))+ .and_then(commit_id)+}++/// A `ref:` target git would write: `refs/` then plain components of `[A-Za-z0-9._-]`, so it+/// can't leave `.git` (no `..`, no empty or absolute part, no backslash).+fn plain_ref(r: &str) -> bool {+ r.len() <= 1024+ && r.starts_with("refs/")+ && !r.contains("..")+ && r.bytes().all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'/' | b'-'))+ && r.split('/').all(|c| !c.is_empty() && c != ".")+}++/// A full SHA-1 (40) or SHA-256 (64) commit id, lowercased.+fn commit_id(s: &str) -> Option<String> {+ ((s.len() == 40 || s.len() == 64) && s.bytes().all(|b| b.is_ascii_hexdigit())).then(|| s.to_ascii_lowercase())+}++/// Reads `<git>/<rel>` (`rel` is `/`-separated and already checked) only when every component+/// below `git` is a real folder and the last a regular file of at most `max` bytes. Never+/// follows a symlink and never blocks on a FIFO, socket or device.+fn read_git_file(git: &FsPath, rel: &str, max: u64) -> Option<String> {+ let mut at = git.to_path_buf();+ let parts: Vec<&str> = rel.split('/').collect();+ for (i, p) in parts.iter().enumerate() {+ at.push(p);+ let ft = std::fs::symlink_metadata(&at).ok()?.file_type();+ let last = i + 1 == parts.len();+ if (last && !ft.is_file()) || (!last && !ft.is_dir()) {+ return None;+ }+ }+ let mut o = std::fs::OpenOptions::new();+ o.read(true);+ #[cfg(unix)]+ {+ use std::os::unix::fs::OpenOptionsExt;+ // A symlink swapped in after the check fails to open; a FIFO opens without waiting+ o.custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK);+ }+ let f = o.open(&at).ok()?;+ let m = f.metadata().ok()?;+ if !m.file_type().is_file() || m.len() > max {+ return None;}- let packed = std::fs::read_to_string(git.join("packed-refs")).ok()?;- packed.lines().find_map(|l| l.strip_suffix(r).map(|sha| sha.trim().chars().take(64).collect()))+ let mut buf = Vec::with_capacity(m.len() as usize);+ f.take(max + 1).read_to_end(&mut buf).ok()?;+ if buf.len() as u64 > max {+ return None;+ }+ String::from_utf8(buf).ok()}struct Taken {@@ -1231,6 +1303,170 @@ mod tests {assert!(summary("Bash", &json!({"command": "x".repeat(1000)})).chars().count() <= 300);}+ const SHA: &str = "0123456789abcdef0123456789abcdef01234567";+ /// Hex-shaped on purpose: only the symlink and path checks can keep it out, not the hex check.+ const CANARY: &str = "c0ffeec0ffeec0ffeec0ffeec0ffeec0ffeec0ff";++ /// A task folder with `.git/` and a canary file outside it.+ fn repo() -> (tempfile::TempDir, PathBuf, PathBuf) {+ let dir = tempfile::tempdir().unwrap();+ let folder = dir.path().join("task");+ std::fs::create_dir_all(folder.join(".git/refs/heads")).unwrap();+ let canary = dir.path().join("canary");+ std::fs::write(&canary, format!("{CANARY}\n")).unwrap();+ (dir, folder, canary)+ }++ fn head_of(folder: &FsPath) -> Option<String> {+ let h = git_head(folder);+ assert!(!h.as_deref().unwrap_or("").contains("c0ffee"), "canary leaked: {h:?}");+ h+ }++ #[test]+ fn git_head_reads_a_branch_a_detached_head_and_a_packed_ref() {+ let (_d, folder, _) = repo();+ let git = folder.join(".git");+ std::fs::write(git.join("HEAD"), "ref: refs/heads/main\n").unwrap();+ std::fs::write(git.join("refs/heads/main"), format!("{SHA}\n")).unwrap();+ assert_eq!(head_of(&folder).as_deref(), Some(SHA));++ std::fs::write(git.join("HEAD"), format!("{}\n", SHA.to_uppercase())).unwrap();+ assert_eq!(head_of(&folder).as_deref(), Some(SHA), "detached, lowercased");+ let sha256 = "ab".repeat(32);+ std::fs::write(git.join("HEAD"), &sha256).unwrap();+ assert_eq!(head_of(&folder), Some(sha256), "a SHA-256 repo");++ std::fs::write(git.join("HEAD"), "ref: refs/heads/feature/x\n").unwrap();+ std::fs::write(+ git.join("packed-refs"),+ format!("# pack-refs with: peeled fully-peeled sorted\n{CANARY} refs/heads/feature/xy\n{SHA} refs/heads/feature/x\n^{CANARY}\n"),+ )+ .unwrap();+ assert_eq!(head_of(&folder).as_deref(), Some(SHA), "exact name in packed-refs");+ std::fs::write(git.join("HEAD"), "ref: refs/heads/none\n").unwrap();+ assert_eq!(head_of(&folder), None, "a branch with no commit yet");+ assert_eq!(head_of(&folder.join("missing")), None);+ }++ #[test]+ fn git_head_only_returns_a_commit_id() {+ let (_d, folder, _) = repo();+ let git = folder.join(".git");+ for bad in ["hello world", "0123456789abcdef", &format!("{SHA}0"), "g123456789abcdef0123456789abcdef01234567", "", "ref: "] {+ std::fs::write(git.join("HEAD"), bad).unwrap();+ assert_eq!(head_of(&folder), None, "{bad:?}");+ }+ std::fs::write(git.join("HEAD"), "ref: refs/heads/main").unwrap();+ std::fs::write(git.join("refs/heads/main"), "root:x:0:0:root:/root:/bin/bash\n").unwrap();+ assert_eq!(head_of(&folder), None, "a ref file that isn't a commit id");+ std::fs::write(git.join("refs/heads/main"), format!("{SHA}\n{}", " ".repeat(5000))).unwrap();+ assert_eq!(head_of(&folder), None, "over the 4 KB cap");+ }++ #[test]+ fn git_head_never_leaves_dot_git() {+ let (dir, folder, _) = repo();+ let git = folder.join(".git");+ // A real loose ref outside .git that a traversal would reach+ std::fs::create_dir_all(dir.path().join("refs/heads")).unwrap();+ std::fs::write(dir.path().join("refs/heads/main"), CANARY).unwrap();+ for r in [+ "../../canary",+ "refs/../../../canary",+ "refs/heads/../../../../canary",+ "/etc/hostname",+ "refs//heads/main",+ "refs/./heads/main",+ "refs\\heads\\main",+ "refs/heads/ma in",+ "heads/main",+ "refs/",+ ] {+ std::fs::write(git.join("HEAD"), format!("ref: {r}\n")).unwrap();+ assert_eq!(head_of(&folder), None, "{r:?}");+ }+ assert!(plain_ref("refs/heads/feature/x-1_2.3") && !plain_ref("refs/heads/a..b"));+ }++ #[test]+ fn git_head_ignores_a_gitdir_file() {+ let (dir, folder, _) = repo();+ std::fs::remove_dir_all(folder.join(".git")).unwrap();+ let other = dir.path().join("other.git");+ std::fs::create_dir_all(&other).unwrap();+ std::fs::write(other.join("HEAD"), CANARY).unwrap();+ std::fs::write(folder.join(".git"), format!("gitdir: {}\n", other.display())).unwrap();+ assert_eq!(head_of(&folder), None);+ }++ #[cfg(unix)]+ #[test]+ fn git_head_never_follows_a_symlink() {+ use std::os::unix::fs::symlink;+ let (dir, folder, canary) = repo();+ let git = folder.join(".git");++ // HEAD → canary+ symlink(&canary, git.join("HEAD")).unwrap();+ assert_eq!(head_of(&folder), None, "HEAD symlink");+ std::fs::remove_file(git.join("HEAD")).unwrap();++ // the ref file → canary+ std::fs::write(git.join("HEAD"), "ref: refs/heads/main\n").unwrap();+ symlink(&canary, git.join("refs/heads/main")).unwrap();+ assert_eq!(head_of(&folder), None, "ref file symlink");+ std::fs::remove_file(git.join("refs/heads/main")).unwrap();++ // a folder on the ref's way → elsewhere+ let elsewhere = dir.path().join("elsewhere");+ std::fs::create_dir_all(&elsewhere).unwrap();+ std::fs::write(elsewhere.join("main"), CANARY).unwrap();+ std::fs::remove_dir(git.join("refs/heads")).unwrap();+ symlink(&elsewhere, git.join("refs/heads")).unwrap();+ assert_eq!(head_of(&folder), None, "refs/heads symlink");+ std::fs::remove_file(git.join("refs/heads")).unwrap();+ std::fs::create_dir(git.join("refs/heads")).unwrap();++ // packed-refs → a canary in packed-refs shape+ let packed = dir.path().join("packed");+ std::fs::write(&packed, format!("{CANARY} refs/heads/main\n")).unwrap();+ symlink(&packed, git.join("packed-refs")).unwrap();+ assert_eq!(head_of(&folder), None, "packed-refs symlink");+ std::fs::remove_file(git.join("packed-refs")).unwrap();++ // .git → a whole other repo whose HEAD is the canary+ let other = dir.path().join("other.git");+ std::fs::create_dir_all(&other).unwrap();+ std::fs::write(other.join("HEAD"), CANARY).unwrap();+ std::fs::remove_dir_all(&git).unwrap();+ symlink(&other, &git).unwrap();+ assert_eq!(head_of(&folder), None, ".git symlink");+ }++ #[cfg(unix)]+ #[test]+ fn git_head_does_not_block_on_a_fifo() {+ let (_d, folder, _) = repo();+ let git = folder.join(".git");+ let fifo = |p: &FsPath| {+ let c = std::ffi::CString::new(p.as_os_str().as_encoded_bytes()).unwrap();+ assert_eq!(unsafe { libc::mkfifo(c.as_ptr(), 0o644) }, 0);+ };+ fifo(&git.join("HEAD"));+ let run = |folder: PathBuf| {+ let (tx, rx) = std::sync::mpsc::channel();+ std::thread::spawn(move || tx.send(git_head(&folder)).unwrap());+ rx.recv_timeout(std::time::Duration::from_secs(5)).expect("git_head blocked on a FIFO")+ };+ assert_eq!(run(folder.clone()), None, "HEAD FIFO");+ std::fs::remove_file(git.join("HEAD")).unwrap();+ std::fs::write(git.join("HEAD"), "ref: refs/heads/main\n").unwrap();+ fifo(&git.join("refs/heads/main"));+ fifo(&git.join("packed-refs"));+ assert_eq!(run(folder), None, "ref and packed-refs FIFOs");+ }+#[test]fn a_run_owns_what_it_created_changed_or_deleted() {let before = m(&[("same", "1"), ("edited", "1"), ("gone", "1")], &["big", "node_modules/"]);