Skip to content

armgit / jan

Public Imported from GitHub
0

Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.

fix(cli): accept only full object ids as workspace snapshot ids

James Dam3645f548edc2
diff --git a/src-tauri/src/core/agent/git.rs b/src-tauri/src/core/agent/git.rs
index 67e88e5a9..b99fa2fee 100644
--- a/src-tauri/src/core/agent/git.rs
+++ b/src-tauri/src/core/agent/git.rs
@@ -205,6 +205,9 @@ pub(crate) fn snapshot(
thread_id: &str,
changed: &[PathBuf],
) -> Result<String, String> {
+ if let Some(p) = parent {
+ require_object_id(p)?;
+ }
let idx = snapshot_index(thread_id)?;
if !idx.exists() {
let base_tree = run(repo, None, &["rev-parse", "--verify", "-q", "HEAD^{tree}"])
@@ -242,9 +245,29 @@ pub(crate) fn cleanup_snapshot_index(thread_id: &str) {
}
}
+/// Whether `s` is a full git object id: 40 (SHA-1) or 64 (SHA-256) lowercase
+/// hex digits. Snapshot ids are read back from thread metadata on disk, so
+/// every one is checked before it reaches a git command line, where a value
+/// like `--index-output=<path>` would be taken as an option.
+#[cfg(feature = "cli")]
+pub(crate) fn is_object_id(s: &str) -> bool {
+ matches!(s.len(), 40 | 64) && s.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f'))
+}
+
+/// `Ok` when `sha` is a full object id (see [`is_object_id`]).
+#[cfg(feature = "cli")]
+fn require_object_id(sha: &str) -> Result<(), String> {
+ if is_object_id(sha) {
+ Ok(())
+ } else {
+ Err(format!("not a snapshot id: {sha:?}"))
+ }
+}
+
/// Point the thread's snapshot ref at `sha` (create or update).
#[cfg(feature = "cli")]
pub(crate) fn update_ref(repo: &Path, thread_id: &str, sha: &str) -> Result<(), String> {
+ require_object_id(sha)?;
run(repo, None, &["update-ref", &snapshot_ref(thread_id)?, sha]).map(|_| ())
}
@@ -253,6 +276,8 @@ pub(crate) fn update_ref(repo: &Path, thread_id: &str, sha: &str) -> Result<(),
/// `target` so they can be removed. Files matching `.gitignore` are untouched.
#[cfg(feature = "cli")]
pub(crate) fn restore(repo: &Path, target: &str, latest: &str) -> Result<(), String> {
+ require_object_id(target)?;
+ require_object_id(latest)?;
let idx = temp_index();
let result = (|| {
run(repo, Some(&idx), &["read-tree", target])?;
@@ -261,7 +286,7 @@ pub(crate) fn restore(repo: &Path, target: &str, latest: &str) -> Result<(), Str
let added = run(
repo,
None,
- &["diff", "--name-only", "--diff-filter=A", target, latest],
+ &["diff", "--name-only", "--diff-filter=A", target, latest, "--"],
)?;
for rel in added.lines().filter(|l| !l.is_empty()) {
let _ = std::fs::remove_file(repo.join(rel));
@@ -282,7 +307,7 @@ pub(crate) fn head_sha(repo: &Path) -> Option<String> {
}
/// Create a worktree at `path`, checking out a new branch `branch` starting at
-/// `base` (any commit-ish). The parent directory is created first: `git
+/// `base` (a full commit id). The parent directory is created first: `git
/// worktree add` requires the path's parent to exist but refuses the path
/// itself to.
#[cfg(feature = "cli")]
@@ -292,6 +317,7 @@ pub(crate) fn worktree_add(
branch: &str,
base: &str,
) -> Result<(), String> {
+ require_object_id(base)?;
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent).map_err(|e| e.to_string())?;
}
@@ -303,6 +329,7 @@ pub(crate) fn worktree_add(
"add",
"-b",
branch,
+ "--",
&path.to_string_lossy(),
base,
],
@@ -466,6 +493,49 @@ mod tests {
let _ = std::fs::remove_dir_all(&wt);
}
+ #[test]
+ fn object_ids_are_full_lowercase_hex() {
+ assert!(is_object_id(&"a".repeat(40)));
+ assert!(is_object_id(&"0123456789abcdef".repeat(4)));
+ assert!(is_object_id(EMPTY_TREE));
+ for bad in [
+ "",
+ "cafe",
+ "--index-output=/tmp/x",
+ "-q",
+ "HEAD",
+ "main",
+ &"A".repeat(40),
+ &"a".repeat(39),
+ &"a".repeat(41),
+ &"g".repeat(40),
+ &format!("{}^{{tree}}", "a".repeat(40)),
+ ] {
+ assert!(!is_object_id(bad), "{bad}");
+ }
+ }
+
+ /// An id read back from thread metadata never reaches git as an option.
+ #[test]
+ fn snapshot_ids_that_are_not_object_ids_are_refused() {
+ let Some(root) = init_repo() else { return };
+ let out = root.join("index-output");
+ let hostile = format!("--index-output={}", out.display());
+ let head = head_sha(&root).unwrap();
+ assert!(restore(&root, &hostile, &head).is_err());
+ assert!(restore(&root, &head, &hostile).is_err());
+ assert!(restore(&root, "HEAD", "HEAD").is_err());
+ assert!(snapshot(&root, Some(&hostile), "m", "t-bad", &[]).is_err());
+ assert!(update_ref(&root, "t-bad", &hostile).is_err());
+ let wt = root.join("wt");
+ assert!(worktree_add(&root, &wt, "jan/agent/bad", &hostile).is_err());
+ assert!(!out.exists());
+ assert!(!wt.exists());
+ // A real id still works for restore.
+ restore(&root, &head, &head).expect("restore to HEAD");
+ let _ = std::fs::remove_dir_all(&root);
+ }
+
#[test]
fn snapshot_restore_roundtrip() {
let Some(root) = init_repo() else { return };
diff --git a/src-tauri/src/core/cli/mod.rs b/src-tauri/src/core/cli/mod.rs
index 1c896b0a6..f9832ac73 100644
--- a/src-tauri/src/core/cli/mod.rs
+++ b/src-tauri/src/core/cli/mod.rs
@@ -1616,6 +1616,7 @@ fn latest_snapshot(thread: Option<&serde_json::Value>) -> Option<String> {
.and_then(|c| c.get("sha"))
.or_else(|| metadata.get("base_snapshot"))
.and_then(|v| v.as_str())
+ .filter(|sha| crate::core::agent::git::is_object_id(sha))
.map(str::to_string)
}
@@ -4977,18 +4978,24 @@ mod tests {
/// files match the transcript it inherited.
#[test]
fn latest_snapshot_prefers_the_newest_checkpoint() {
+ let (base, s0, s1) = ("b".repeat(40), "0".repeat(40), "1".repeat(64));
let thread = serde_json::json!({ "metadata": {
- "base_snapshot": "base",
+ "base_snapshot": base,
"checkpoints": [
- { "user_index": 0, "preview": "one", "sha": "s0" },
- { "user_index": 1, "preview": "two", "sha": "s1" },
+ { "user_index": 0, "preview": "one", "sha": s0 },
+ { "user_index": 1, "preview": "two", "sha": s1 },
],
}});
- assert_eq!(latest_snapshot(Some(&thread)).as_deref(), Some("s1"));
+ assert_eq!(latest_snapshot(Some(&thread)), Some(s1));
// No checkpoints yet: the base snapshot is still better than HEAD.
- let fresh = serde_json::json!({ "metadata": { "base_snapshot": "base" } });
- assert_eq!(latest_snapshot(Some(&fresh)).as_deref(), Some("base"));
+ let fresh = serde_json::json!({ "metadata": { "base_snapshot": base } });
+ assert_eq!(latest_snapshot(Some(&fresh)), Some(base));
+ // An id that is not a full object id is never handed to git.
+ for bad in ["base", "--index-output=/tmp/x", "HEAD"] {
+ let t = serde_json::json!({ "metadata": { "base_snapshot": bad } });
+ assert_eq!(latest_snapshot(Some(&t)), None, "{bad}");
+ }
// Nothing recorded at all leaves the choice to the caller (HEAD).
assert_eq!(latest_snapshot(None), None);
assert_eq!(
@@ -5138,8 +5145,9 @@ mod tests {
std::fs::remove_dir_all(&wt).unwrap();
assert_eq!(fork_base(Some(&source)), None);
// A source that recorded a snapshot uses it, no capture needed.
- let snapped = serde_json::json!({ "id": "s", "metadata": { "base_snapshot": "cafe" } });
- assert_eq!(fork_base(Some(&snapped)).as_deref(), Some("cafe"));
+ let cafe = "cafe".repeat(10);
+ let snapped = serde_json::json!({ "id": "s", "metadata": { "base_snapshot": cafe } });
+ assert_eq!(fork_base(Some(&snapped)), Some(cafe));
}
/// `--max-session-tokens` outranks `[budget].max_tokens`, which outranks
diff --git a/src-tauri/src/core/cli/tui.rs b/src-tauri/src/core/cli/tui.rs
index 845bd1995..3b3f1e793 100644
--- a/src-tauri/src/core/cli/tui.rs
+++ b/src-tauri/src/core/cli/tui.rs
@@ -20533,17 +20533,24 @@ fn restore_snapshots(app: &mut App, metadata: Option<&serde_json::Value>) {
app.snap_queue.clear();
app.base_requested = false;
let Some(meta) = metadata else { return };
+ // The ids go to git on rewind, so only full object ids are taken back.
let Some(base) = meta
.get("base_snapshot")
.and_then(|v| v.as_str())
+ .filter(|sha| git::is_object_id(sha))
.map(str::to_string)
else {
return;
};
- app.checkpoints = meta
+ let checkpoints = meta
.get("checkpoints")
.and_then(|v| serde_json::from_value::<Vec<Checkpoint>>(v.clone()).ok())
.unwrap_or_default();
+ // Dropping just a bad one would make a rewind restore the wrong turn.
+ if !checkpoints.iter().all(|c| git::is_object_id(&c.sha)) {
+ return;
+ }
+ app.checkpoints = checkpoints;
app.base_snapshot = Some(base);
// A resumed thread already has its base; don't re-snapshot on next submit.
app.base_requested = true;
@@ -28488,6 +28495,34 @@ mod tests {
assert!(rendered.iter().any(|l| l.contains("[IMAGE] shot.png")));
}
+ #[test]
+ fn resume_takes_back_only_full_object_ids_as_snapshots() {
+ let mut app = test_app();
+ let (base, s0) = ("b".repeat(40), "0".repeat(40));
+ let good = serde_json::json!({
+ "base_snapshot": base,
+ "checkpoints": [{ "user_index": 0, "preview": "one", "sha": s0 }],
+ });
+ super::restore_snapshots(&mut app, Some(&good));
+ assert_eq!(app.base_snapshot.as_deref(), Some(base.as_str()));
+ assert_eq!(app.checkpoints.len(), 1);
+
+ for meta in [
+ serde_json::json!({ "base_snapshot": "--index-output=/tmp/x" }),
+ serde_json::json!({
+ "base_snapshot": base,
+ "checkpoints": [
+ { "user_index": 0, "preview": "one", "sha": s0 },
+ { "user_index": 1, "preview": "two", "sha": "--output=/tmp/x" },
+ ],
+ }),
+ ] {
+ super::restore_snapshots(&mut app, Some(&meta));
+ assert!(app.base_snapshot.is_none(), "{meta}");
+ assert!(app.checkpoints.is_empty(), "{meta}");
+ }
+ }
+
#[test]
fn base_snapshot_is_queued_off_loop_not_run_inline() {
let mut app = test_app();