From 6c70861cefb121a9ecff186b01c4db70c5c68ca2 Mon Sep 17 00:00:00 2001 From: Mike Lyons Date: Fri, 20 Nov 2026 11:49:58 -0500 Subject: [PATCH 1/2] fix(restore): refuse a bundle whose session id isn't a plain file name A session id from a bundle was joined into the restored transcript's path, so a crafted bundle could write anywhere (`../../x`, `/x`) and inject into resumeCommand. Bundles come from shared stores, so the id is now checked on unpack (bundle-unreadable) and in both find_transcripts. Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 9 +++++ src/agent.rs | 14 ++++++++ src/bundle.rs | 10 +++++- src/claude.rs | 9 +++++ src/codex.rs | 4 +++ tests/bundle.rs | 31 ++++++++++++++++ tests/codex.rs | 94 +++++++++++++++++++++++++++++++++++++++++++++++++ 7 files changed, 170 insertions(+), 1 deletion(-) diff --git a/CLAUDE.md b/CLAUDE.md index 795545f..73795d3 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -928,6 +928,15 @@ stay at 1 and keep their refs, and no ref of a version-2 bundle predates the rule, so nothing moved. `Bundle::required_version` decides it, and both cases are pinned. Index entries name their first session's agent. +**A bundle's session ids are untrusted input.** Both adapters build the +restored file's name from the id, and `resumeCommand` puts it in a shell +line, so an id of `../../x` or `/x` chose where `restore` wrote and `;` what +the command ran. `agent::is_safe_session_id` (non-empty, `[A-Za-z0-9._-]`, +no leading `.`, at most 128 bytes) is checked when a bundle is unpacked, so a +bundle failing it is `bundle-unreadable` as a whole, and by both +`find_transcript`s, whose ids come from edit records in the same shared +store. Real ids are UUIDs. The bad id is never echoed back. + **Never the matched text.** Redaction is reported as `{"": }` plus a `redacted` total, exactly as much as the prose summary carries and no more — `save`'s stdout lands in the next agent's transcript. The one field diff --git a/src/agent.rs b/src/agent.rs index 00993f7..8b3df53 100644 --- a/src/agent.rs +++ b/src/agent.rs @@ -38,6 +38,20 @@ pub struct SessionMeta { pub other_cwds: Vec, } +/// Whether a session id can be put into a file name, and a resume command, +/// as it is. Every adapter files a transcript under a name built from its id, +/// and a bundle's or a store's id is someone else's input: `../x` or `/x` +/// would choose where `restore` writes, and `;` what a resume command runs. +/// Both agents' ids are UUIDs, so an allowlist costs nothing real. +pub fn is_safe_session_id(id: &str) -> bool { + !id.is_empty() + && id.len() <= 128 + && !id.starts_with('.') + && id + .bytes() + .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.')) +} + /// What the transcript says about a turn: the record that began it and the /// last record written. Each id is whatever the agent's transcript uses to /// name a position in itself — a record uuid for Claude Code, a turn id for diff --git a/src/bundle.rs b/src/bundle.rs index 4a7c719..b0a6dcd 100644 --- a/src/bundle.rs +++ b/src/bundle.rs @@ -259,8 +259,16 @@ pub fn unpack_bundle(data: &[u8]) -> Result { .ok_or_else(|| format!("'{}'", key)) }; let optional = |key: &str| session.get(key).and_then(Value::as_str).map(str::to_string); + let session_id = required("sessionId")?; + // Not echoed: it is whatever the bundle's author chose to put there. + if !crate::agent::is_safe_session_id(&session_id) { + return Err(format!( + "session {} has an id that isn't a safe file name", + sessions.len() + 1 + )); + } sessions.push(BundleSession { - session_id: required("sessionId")?, + session_id, agent: optional("agent"), agent_version: optional("agentVersion"), cwd: required("cwd")?, diff --git a/src/claude.rs b/src/claude.rs index 89d97a5..b4d9646 100644 --- a/src/claude.rs +++ b/src/claude.rs @@ -326,6 +326,10 @@ pub fn find_transcript( session_id: &str, store: Option<&dyn Store>, ) -> Result, StoreError> { + // The id comes from an edit record, which a shared store also supplies. + if !crate::agent::is_safe_session_id(session_id) { + return Ok(None); + } let root = projects_dir(None); if Path::new(&root).is_dir() { for project in list_dir(&root) { @@ -353,6 +357,11 @@ pub fn find_transcript( .next() .unwrap_or("") .to_string(); + // A listed key is the store's to choose too: `..` would step out + // of the cache. + if project.is_empty() || project.starts_with('.') || project.contains('\\') { + continue; + } let data = match store.get(&key) { Ok(data) => data, Err(StoreError::Missing(_)) => return Ok(None), diff --git a/src/codex.rs b/src/codex.rs index 40c8f3d..793b700 100644 --- a/src/codex.rs +++ b/src/codex.rs @@ -346,6 +346,10 @@ pub fn find_transcript( session_id: &str, store: Option<&dyn Store>, ) -> Result, StoreError> { + // The id comes from an edit record, which a shared store also supplies. + if !crate::agent::is_safe_session_id(session_id) { + return Ok(None); + } if let Some(path) = rollout_for(session_id) { return Ok(Some(path)); } diff --git a/tests/bundle.rs b/tests/bundle.rs index 9392c8a..b21ffff 100644 --- a/tests/bundle.rs +++ b/tests/bundle.rs @@ -250,3 +250,34 @@ fn a_bundle_whose_agent_is_not_claude_is_version_2() { bundle.agent = "codex".into(); assert_eq!(bundle.required_version(), 2); } + +#[test] +fn a_session_id_must_be_a_plain_file_name() { + use loch::agent::is_safe_session_id; + for good in [ + "11111111-2222-4333-8444-555555555555", + "abc", + "old-id", + "a.b_c", + ] { + assert!(is_safe_session_id(good), "{}", good); + } + for bad in [ + "", + "..", + ".hidden", + "../x", + "/etc/x", + "a/b", + "a\\b", + "x; rm -rf ~", + "a b", + "a\0b", + ] { + assert!(!is_safe_session_id(bad), "{:?}", bad); + } + let mut bundle = sample_bundle(None); + bundle.sessions[0].session_id = "../../x".into(); + let packed = pack_bundle(&bundle).unwrap(); + assert!(unpack_bundle(&packed).is_err()); +} diff --git a/tests/codex.rs b/tests/codex.rs index 41f35ab..f2ede37 100644 --- a/tests/codex.rs +++ b/tests/codex.rs @@ -918,3 +918,97 @@ fn ask_on_a_turn_of_an_agent_this_build_lacks_is_unsupported() { assert_ne!(code, 0); assert_eq!(text(&document, "code"), "unsupported-agent"); } + +// -- untrusted bundles ------------------------------------------------------------------ + +/// A bundle that `restore` is handed came from a shared store, so its +/// session ids are someone else's input: one shaped like a path must not +/// decide where a transcript is written. +fn crafted_bundle(world: &World, agent: &str, session_id: &str) -> String { + let repo = s(&world.repo); + let transcript = if agent == "codex" { + format!( + "{{\"timestamp\":\"x\",\"type\":\"session_meta\",\"payload\":{{\"id\":\"{}\",\"timestamp\":\"2026-11-18T10:00:00.000Z\",\"cwd\":\"{}\"}}}}\n", + session_id, repo + ) + } else { + format!("{{\"type\":\"user\",\"cwd\":\"{}\"}}\n", repo) + }; + let bundle = loch::bundle::Bundle { + version: 2, + agent: agent.into(), + created_at: "2026-11-18T10:00:00.000Z".into(), + origin: loch::bundle::BundleOrigin { + home: s(&world.home), + platform: "darwin".into(), + hostname: "elsewhere".into(), + }, + sessions: vec![loch::bundle::BundleSession { + session_id: session_id.into(), + agent: None, + agent_version: None, + cwd: repo, + git_branch: None, + claude_version: None, + modified_at: "2026-11-18T10:00:00.000Z".into(), + transcript, + }], + }; + let packed = loch::bundle::pack_bundle(&bundle).unwrap(); + let reference = loch::bundle::bundle_ref(&packed); + let path = world.store.join(format!("bundles/{}.loch", reference)); + fs::create_dir_all(path.parent().unwrap()).unwrap(); + fs::write(path, packed).unwrap(); + reference +} + +#[test] +fn a_session_id_shaped_like_a_path_cannot_place_a_restore() { + let world = World::new(); + let target = world.root.join("escaped"); + for agent in ["claude-code", "codex"] { + for id in [ + format!("../../../../../../../../../../..{}", s(&target)), + s(&target), + "a/b".to_string(), + "a\\b".to_string(), + ] { + let reference = crafted_bundle(&world, agent, &id); + let (document, code) = world.json(&["restore", &reference]); + assert_ne!(code, 0, "{} {}: {:?}", agent, id, document); + assert_eq!( + text(&document, "code"), + "bundle-unreadable", + "{} {}", + agent, + id + ); + assert!( + !world.root.join("escaped.jsonl").exists(), + "{} {} wrote outside the sessions directory", + agent, + id + ); + let mut stray = Vec::new(); + collect_files(&world.root, &mut stray); + assert!( + stray.iter().all(|p| !s(p).ends_with(".jsonl")), + "{} {} wrote {:?}", + agent, + id, + stray + ); + } + } +} + +fn collect_files(dir: &Path, into: &mut Vec) { + for entry in fs::read_dir(dir).into_iter().flatten().flatten() { + let path = entry.path(); + if path.is_dir() { + collect_files(&path, into); + } else { + into.push(path); + } + } +} From a2ba16b7a9aed7640a1a5fd7ccb6ad3371ad3072 Mon Sep 17 00:00:00 2001 From: Mike Lyons Date: Fri, 20 Nov 2026 12:02:06 -0500 Subject: [PATCH 2/2] test: pin review findings on Codex support (#2 passes, #3 and #4 ignored) - SessionEnd killed at Codex's 3s while the store hangs: the turn is already closed locally; the store copy and the state cleanup are lost. - ask --at-turn on a turn before a move: the fork keeps naming that turn's cwd, which Codex's resume then offers as the session directory. - One directory recorded two ways (resolved, and -C through a link): reported as otherCwds, and only one spelling is rewritten on restore. Co-Authored-By: Claude Opus 5.5 --- tests/codex.rs | 197 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 197 insertions(+) diff --git a/tests/codex.rs b/tests/codex.rs index f2ede37..4868818 100644 --- a/tests/codex.rs +++ b/tests/codex.rs @@ -1012,3 +1012,200 @@ fn collect_files(dir: &Path, into: &mut Vec) { } } } + +// -- SessionEnd under Codex's 3s clamp --------------------------------------------------- + +/// Codex kills a `SessionEnd` hook after 3s. `end` closes the open turn +/// locally — snapshot, diff, the edit record written aside and renamed — +/// before it touches the store, so a kill during a slow store loses the +/// store's copy and not the turn. This pins that order, and what the kill +/// leaves behind: the record on this machine, nothing in the store (no later +/// hook of an ended session publishes it), and the session's state still +/// open. +#[test] +fn a_session_end_killed_while_the_store_hangs_keeps_the_turn_locally() { + use std::net::TcpListener; + use std::time::{Duration, Instant}; + let world = World::new(); + let repo = s(&world.repo); + world.meta(SESSION, &repo, "feat/x"); + world.begin(SESSION, TURN_A, &repo, 1, "cut short"); + world.hook( + "prompt", + &world.event(SESSION, Some(TURN_A), Some("cut short")), + ); + world.sh("echo 'a line written before quitting' > a.txt"); + + // A store that accepts and never answers. + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let port = listener.local_addr().unwrap().port(); + let held = std::thread::spawn(move || { + let mut open = Vec::new(); + for stream in listener.incoming().take(1) { + open.push(stream); + } + std::thread::sleep(Duration::from_secs(10)); + drop(open); + }); + let mut child = world + .command(env!("CARGO_BIN_EXE_loch"), &world.repo) + .args(["hook", "end", "--agent", "codex"]) + .env("LOCH_STORE", "s3://sessions") + .env("LOCH_S3_ENDPOINT", format!("http://127.0.0.1:{}", port)) + .env("LOCH_S3_REGION", "us-east-1") + .env("AWS_ACCESS_KEY_ID", "test") + .env("AWS_SECRET_ACCESS_KEY", "test") + .stdin(Stdio::piped()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .spawn() + .unwrap(); + child + .stdin + .take() + .unwrap() + .write_all(world.event(SESSION, None, None).as_bytes()) + .unwrap(); + let started = Instant::now(); + while started.elapsed() < Duration::from_secs(3) { + if child.try_wait().unwrap().is_some() { + break; + } + std::thread::sleep(Duration::from_millis(50)); + } + assert!( + child.try_wait().unwrap().is_none(), + "end was still waiting on the store at 3s" + ); + child.kill().unwrap(); + child.wait().unwrap(); + drop(held); + + let local = world + .home + .join(".loch/edits/codex") + .join(format!("{}.json", SESSION)); + let record = json::loads(&fs::read_to_string(&local).unwrap()).unwrap(); + let turns = items(&record, "turns"); + assert_eq!(turns.len(), 1); + assert_eq!(text(&turns[0], "promptUuid"), TURN_A); + assert_eq!(turns[0].get("interrupted"), Some(&Value::Bool(true))); + assert!(!items(&turns[0], "files").is_empty()); + assert!( + world + .home + .join(".loch/sessions") + .join(format!("{}.json", SESSION)) + .exists(), + "the kill came before the state was let go" + ); +} + +// -- the cwd a fork is rewritten from -------------------------------------------------- + +/// Codex's TUI compares the latest cwd a rollout records with the directory +/// it was started in, and asks which to use ("Use session directory" / "Use +/// current directory") when they differ. A fork cut at a turn from before the +/// session moved ends on a `turn_context` naming where that turn ran, so it +/// has to be rewritten from that cwd, not the session's live one: otherwise +/// the fork names a directory it isn't being resumed in. +#[test] +#[ignore = "review finding 3, not fixed: the fork is rewritten from the live cwd"] +fn a_fork_cut_before_a_move_is_rewritten_from_that_turns_cwd() { + let world = World::new(); + let repo = s(&world.repo); + let old = s(&world.root.join("removed-worktree")); + world.meta(SESSION, &old, "feat/x"); + world.begin(SESSION, TURN_A, &old, 1, "make a"); + world.hook( + "prompt", + &world.event(SESSION, Some(TURN_A), Some("make a")), + ); + world.sh("echo 'alpha line here' > a.txt"); + world.finish(SESSION, TURN_A, 1); + world.hook("stop", &world.event(SESSION, Some(TURN_A), None)); + world.turn(TURN_B, 2, "make b", "echo 'bravo line here' > b.txt"); + + let ask = world.ok(&["ask", "a.txt:1", "--at-turn", "--no-launch"]); + let fork = at(&ask, "fork"); + assert_eq!(text(fork, "cwd"), repo); + let named: Vec = records(Path::new(text(fork, "path"))) + .iter() + .filter(|r| matches!(text(r, "type"), "session_meta" | "turn_context")) + .map(|r| text(at(r, "payload"), "cwd").to_string()) + .collect(); + assert!(!named.is_empty()); + assert!( + named.iter().all(|cwd| *cwd == repo), + "the fork names {:?}, and is resumed in {}", + named, + repo + ); +} + +// -- one directory, two spellings --------------------------------------------------------- + +/// Codex records `-C` as given and its own cwd resolved, so one session can +/// name one directory two ways: begun in it (`/private/tmp/x`), resumed with +/// `-C` through a link (`/tmp/x`). That is not a move. +#[cfg(unix)] +fn a_session_through_two_spellings(world: &World) -> String { + let link = world.root.join("link-to-repo"); + std::os::unix::fs::symlink(&world.repo, &link).unwrap(); + let link = s(&link); + let repo = s(&world.repo); + world.meta(SESSION, &repo, "feat/x"); + world.begin(SESSION, TURN_A, &repo, 1, "begun here"); + world.finish(SESSION, TURN_A, 1); + world.begin( + SESSION, + TURN_B, + &link, + 2, + "resumed with -C through the link", + ); + world.finish(SESSION, TURN_B, 2); + link +} + +#[cfg(unix)] +#[test] +#[ignore = "review finding 4, not fixed: other_cwds compares cwds unresolved"] +fn a_second_spelling_of_the_live_cwd_is_not_another_cwd() { + let world = World::new(); + a_session_through_two_spellings(&world); + let list = world.ok(&["list", "--agent", "codex"]); + let session = &items(&list, "sessions")[0]; + assert_eq!( + text(session, "branch"), + "feat/x", + "already right: not a move" + ); + assert!( + items(session, "otherCwds").is_empty(), + "{:?}", + items(session, "otherCwds") + ); +} + +#[cfg(unix)] +#[test] +#[ignore = "review finding 4, not fixed: only the live cwd's spelling is rewritten"] +fn both_spellings_of_the_live_cwd_are_restored_into_the_target() { + let world = World::new(); + a_session_through_two_spellings(&world); + let reference = text(&world.ok(&["save"]), "ref").to_string(); + let there = world.elsewhere("b"); + let restore = there.ok(&["restore", &reference, "--new-id"]); + let session = &items(&restore, "sessions")[0]; + let raw = fs::read_to_string(text(session, "path")).unwrap(); + assert!( + !raw.contains(&s(&world.repo)), + "a record still names the origin" + ); + assert!( + at(session, "foreignCwds").as_object().unwrap().is_empty(), + "{:?}", + at(session, "foreignCwds") + ); +}