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.

feat(agent-cli): make the bash sandbox opt-in, and fix symlink/scratch holes (#8677)

Akarshan Biswasdf40b3536668
diff --git a/docs/src/pages/docs/agent/cli.mdx b/docs/src/pages/docs/agent/cli.mdx
index 5c09e10d9..2f4e3c8f7 100644
--- a/docs/src/pages/docs/agent/cli.mdx
+++ b/docs/src/pages/docs/agent/cli.mdx
@@ -37,6 +37,8 @@ jan <COMMAND>
| `--image <PATH>` | Attach an image to the first message. Repeatable |
| `--plan` | Start in read-only plan mode |
| `--safe` | Ask for approval before writes, shell commands, and MCP tool calls |
+| `--sandbox` | Run shell commands under OS confinement. Off by default |
+| `--no-sandbox` | Run shell commands unconfined, overriding a persistent `sandbox` setting |
| `--resume [ID]` | Resume the most recent session, or one whose id starts with `ID` |
| `-c`, `--continue` | Resume the most recent session |
| `--provider <ID>` | Target a specific provider for this run |
@@ -50,13 +52,15 @@ jan -c # resume the latest session
jan --resume 3f7a91c2 # resume by id prefix
jan --plan # read-only
jan --safe # ask before writes and shell commands
+jan --sandbox # confine shell commands to the project
```
-<Callout type="info">
-Tool calls are auto-approved by default. Shell commands still run inside the OS sandbox
-(bubblewrap, Seatbelt, or AppContainer), confined to the project directory, and the hard denies
-never lift: `.jan/agent/` internals, anything in `[tools] deny`, and everything plan mode blocks.
-`--safe` adds the interactive approval prompt on top of that.
+<Callout type="warning">
+Tool calls are auto-approved by default, and shell commands are **not** sandboxed by default - an
+approved command runs with your own access. The hard denies never lift: `.jan/agent/` internals,
+anything in `[tools] deny`, and everything plan mode blocks. `--safe` adds the interactive approval
+prompt; `--sandbox` adds OS confinement (bubblewrap, Seatbelt, or AppContainer). See
+[tool permissions](/docs/agent/permissions#the-shell-sandbox).
</Callout>
## `jan cli agent`
@@ -80,6 +84,8 @@ jan cli agent run --safe "run the migration" # approve each step
| `--project <PATH>` | Project root. Defaults to `.` |
| `--model <ID>` | Model id, overriding `[agent].model` |
| `--safe` | Ask for approval before writes, shell commands, and MCP tool calls |
+| `--sandbox` | Run shell commands under OS confinement. Off by default |
+| `--no-sandbox` | Run shell commands unconfined, overriding a persistent `sandbox` setting |
| `--resume[=ID]` | Resume the most recent session, or one by id |
| `-c`, `--continue` | Resume the most recent session |
| `--provider`, `--api-key` | Credential overrides for this run |
diff --git a/docs/src/pages/docs/agent/index.mdx b/docs/src/pages/docs/agent/index.mdx
index f7964bc08..afadfb1af 100644
--- a/docs/src/pages/docs/agent/index.mdx
+++ b/docs/src/pages/docs/agent/index.mdx
@@ -116,15 +116,17 @@ Desktop's [local API server](/docs/desktop/api-server), with `jan config set --b
## Staying in control
-The agent edits files and runs commands without stopping to ask, but a shell command runs inside an
-OS sandbox confined to the project directory, and `.jan/agent/` internals and anything in
-`[tools] deny` are refused outright.
+The agent edits files and runs commands without stopping to ask. File paths are checked against the
+project root, and `.jan/agent/` internals and anything in `[tools] deny` are refused outright - but
+shell commands are not sandboxed by default, so one runs with your own access.
-Two ways to change that:
+Three ways to change that:
- **Plan mode** (`jan --plan`) makes the session read-only. The agent investigates and proposes, but
cannot change anything.
- **Safe mode** (`jan --safe`) asks before every write and shell command, instead of auto-approving
- them inside the sandbox.
+ them.
+- **Sandbox** (`jan --sandbox`) confines shell commands to the project with an OS sandbox. Off by
+ default on the CLI, always on in the desktop app.
See [Tools & permissions](/docs/agent/permissions) for the full picture.
diff --git a/docs/src/pages/docs/agent/permissions.mdx b/docs/src/pages/docs/agent/permissions.mdx
index 12d463af9..f8ae2b1b6 100644
--- a/docs/src/pages/docs/agent/permissions.mdx
+++ b/docs/src/pages/docs/agent/permissions.mdx
@@ -46,6 +46,11 @@ Tools that take a path have it checked against the project root, so a write outs
refused before it happens. `bash` has no path argument and runs in the project root; a command you
approve can still reach outside, which is why plan mode exists as the hard boundary.
+A symbolic link is followed only while it stays inside the project (or the session scratch). Links
+that point back into your own tree - the ones every `node_modules` is full of - work normally; a
+link out of the project is refused, so it can't be used to smuggle a read or a write past the check
+above.
+
## Project policy
`.jan/agent/agent.toml` sets what a project exposes:
@@ -64,6 +69,9 @@ allow_write = []
# Whether the sandboxed shell can reach the network
# allow_network = true
+
+# Whether shell commands run under OS confinement at all
+# sandbox = true
```
| `default` | Effect |
@@ -74,10 +82,69 @@ allow_write = []
`deny` always wins over `allow`. A tool in both lists is denied.
+## The shell sandbox
+
+Jan can run shell commands under OS confinement - bubblewrap on Linux, Seatbelt on macOS,
+AppContainer on Windows. Confined, a command can **write** only the project and its scratch
+directory, and reaches the network only if allowed. Reads are looser: the CLI keeps `$HOME` readable
+so `git` and `ssh` credential helpers work (`[tools].allow_home_read`, set it to `false` to close
+that), while the desktop masks it entirely.
+
+Whether it is on depends on the surface:
+
+| Surface | Sandbox | Can it be changed? |
+| --- | --- | --- |
+| Desktop chat agent | Always on | No. If no sandbox can be established, `bash` is withheld rather than run unconfined |
+| `jan` CLI and console | **Off by default** | Yes, see below |
+
+The CLI runs unconfined because it is a coding agent in your own project, started from your own
+terminal - the same trust `make`, `git push`, or any other tool you run there already has - and
+confinement breaks the toolchains projects actually build with often enough to be the wrong default.
+Note that approval prompts are also off by default, so out of the box nothing gates a shell command
+at all - `--safe`, `--sandbox`, or both are how you change that.
+
+<Callout type="warning">
+With the sandbox off, a shell command you approve runs with exactly your access. Nothing confines it
+to the project. If that isn't the trade you want, turn it on.
+</Callout>
+
+### Turning it on
+
+Three levels, most specific first:
+
+```bash
+jan --sandbox # this session only
+jan --no-sandbox # this session only, overriding a setting below
+```
+
+```toml
+# .jan/agent/agent.toml - for everyone who checks this project out
+[tools]
+sandbox = true
+```
+
+```toml
+# ~/.jan/config.toml - for every project you work on
+sandbox = true
+```
+
+A flag beats the project file, which beats the global setting, which beats the default. Every level
+works in both directions, which is why `--no-sandbox` exists: without it, turning confinement on
+permanently would leave no way to run a single command without it.
+
+`jan cli agent status` reports what a run would actually do:
+
+```json
+"sandbox": { "enabled": false, "backend": "bubblewrap" }
+```
+
+`backend` is the confinement that *would* be used. `none` means none is available on this machine -
+with `enabled: true` that combination is what withholds `bash` entirely.
+
## Network access
-A `bash` command runs inside an OS sandbox. Whether that sandbox has network access depends on the
-surface, and the two defaults differ:
+Network access is a property of the sandbox, so it applies when the sandbox is on. Unconfined, a
+command has whatever network access you do. The two surfaces default differently:
| Surface | How to set network access | Default |
| --- | --- | --- |
@@ -106,6 +173,7 @@ Approval prompts are opt-in: by default every call above is auto-approved. Start
`jan --safe` to be asked instead. See [run modes](/docs/agent/run-modes).
<Callout type="info">
-Auto-approval only removes the prompt. The OS sandbox around shell commands, the `.jan/agent/`
-restriction, and `[tools] deny` all still apply.
+Auto-approval only removes the prompt. The `.jan/agent/` restriction, the path checks, and
+`[tools] deny` all still apply, as does the shell sandbox where it is on - but on the CLI it is off
+by default, so auto-approved shell commands run with your own access unless you turn it on.
</Callout>
diff --git a/docs/src/pages/docs/agent/project-config.mdx b/docs/src/pages/docs/agent/project-config.mdx
index 4e09f6860..99b625926 100644
--- a/docs/src/pages/docs/agent/project-config.mdx
+++ b/docs/src/pages/docs/agent/project-config.mdx
@@ -81,6 +81,7 @@ default = "read-only"
allow = []
deny = []
allow_write = []
+# sandbox = true
[skills]
enabled = []
@@ -114,7 +115,9 @@ marginal token spend (replayed context is not recharged each turn).
### `[tools]`
-See [Tool permissions](/docs/agent/permissions#project-policy).
+See [Tool permissions](/docs/agent/permissions#project-policy). `sandbox` is how a project requires
+[shell confinement](/docs/agent/permissions#the-shell-sandbox) for everyone who checks it out; it is
+off by default on the CLI.
### `[skills]`
diff --git a/docs/src/pages/docs/agent/run-modes.mdx b/docs/src/pages/docs/agent/run-modes.mdx
index e251320ba..17ab7324c 100644
--- a/docs/src/pages/docs/agent/run-modes.mdx
+++ b/docs/src/pages/docs/agent/run-modes.mdx
@@ -13,15 +13,20 @@ without you.
| Mode | Reads | Writes and commands | Start with |
| --- | --- | --- | --- |
-| Default | Free | Auto-approved, inside the sandbox | `jan` |
+| Default | Free | Auto-approved | `jan` |
| Safe | Free | Prompt for approval | `jan --safe` |
| Plan | Free | Blocked | `jan --plan` |
## Default
-The agent works without stopping to ask. That is not the same as unrestricted: shell commands run
-inside an OS sandbox (bubblewrap on Linux, Seatbelt on macOS, AppContainer on Windows) confined to
-the project directory, and if no sandbox can be established the `bash` tool refuses to run at all.
+The agent works without stopping to ask. That is not the same as unrestricted - file paths are still
+checked against the project root - but a shell command you never saw runs with your own access,
+because the CLI does not sandbox commands by default.
+
+Add `--sandbox` to run them under OS confinement (bubblewrap on Linux, Seatbelt on macOS,
+AppContainer on Windows), confined to the project directory; with it on, if no sandbox can be
+established the `bash` tool refuses to run at all. It can also be turned on permanently - see
+[the shell sandbox](/docs/agent/permissions#the-shell-sandbox).
Some things are denied outright and no mode lifts them:
diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/commands.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/commands.rs
index 2fdb06334..1e1a3b32f 100644
--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/commands.rs
+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/commands.rs
@@ -118,11 +118,18 @@ pub async fn thread_workspace_delete(
/// Delete every sandbox not belonging to a surviving thread, returning how many
/// were removed. Called once at startup: sandboxes are ephemeral, but a crash or
/// a thread deleted while the app was closed would otherwise leave one behind.
+///
+/// Abandoned host-temp scratch directories are collected in the same pass. They
+/// need their own sweep because they are keyed to ids the caller holds (a run,
+/// a thread, a CLI session), so unlike a thread sandbox there is no `keep` list
+/// to compare against -- see [`workspace::sweep_stale_scratch_dirs`]. Their
+/// count is not added to the return value, which names thread sandboxes.
#[tauri::command]
pub async fn thread_workspace_sweep(
data_folder: String,
keep: Vec<String>,
) -> Result<usize, AgentToolsError> {
+ workspace::sweep_stale_scratch_dirs().await;
workspace::sweep_thread_workspaces(Path::new(&data_folder), &keep)
.await
.map_err(Into::into)
diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/handlers.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/handlers.rs
index ad7af1b72..115cfaf91 100644
--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/handlers.rs
+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/handlers.rs
@@ -17,7 +17,7 @@ use crate::tools::jail;
use crate::tools::proc;
use crate::tools::sandbox::{
escapes_project, in_scratch, is_hidden_jan_path, lexical_normalize, resolve_path,
- scratch_display_path,
+ scratch_display_path, symlink_escapes_root,
};
use crate::tools::{BuiltinTool, ToolContext};
@@ -454,6 +454,11 @@ async fn read(args: &serde_json::Value, root: &Path, scratch: Option<&Path>) ->
let offset = arg_u64(args, "offset").map(|v| v as usize);
let limit = arg_u64(args, "limit").map(|v| v as usize);
let target = resolve_path(root, scratch, path);
+ // Fail closed: a component swapped to a symlink after the gate validated
+ // the path must not redirect the open out of the workspace.
+ if symlink_escapes_root(root, scratch, &target) {
+ return format!("ERROR: refused to read through a symlink out of the workspace: {path}");
+ }
let bytes = match tokio::fs::read(&target).await {
Ok(b) => b,
@@ -496,7 +501,12 @@ async fn ls(args: &serde_json::Value, root: &Path, scratch: Option<&Path>) -> St
let limit = arg_u64(args, "limit")
.map(|v| v as usize)
.unwrap_or(LS_DEFAULT_LIMIT);
- let mut entries = match tokio::fs::read_dir(resolve_path(root, scratch, path)).await {
+ let target = resolve_path(root, scratch, path);
+ // Names are content too: a symlinked directory would list a host directory.
+ if symlink_escapes_root(root, scratch, &target) {
+ return format!("ERROR: refused to list through a symlink out of the workspace: {path}");
+ }
+ let mut entries = match tokio::fs::read_dir(&target).await {
Ok(rd) => rd,
Err(e) => return format!("ERROR: {e}"),
};
@@ -546,6 +556,13 @@ async fn write(args: &serde_json::Value, root: &Path, scratch: Option<&Path>, co
// Report the resolved location, not the raw argument: an absolute or `../`
// path lands outside the project and the model must see where it went.
let shown = display_path(root, scratch, &target);
+ // Re-validate before `create_dir_all`, not just before the write: a
+ // concurrent sandboxed process can swap a path component between the gate
+ // decision and this call, and creating the parents first would already have
+ // made directories through the swapped link. Fail closed.
+ if symlink_escapes_root(root, scratch, &target) {
+ return format!("ERROR: refused to write through a symlink out of the workspace: {path}");
+ }
if let Some(parent) = target.parent() {
if let Err(e) = tokio::fs::create_dir_all(parent).await {
return format!("ERROR: {shown}: {e}");
@@ -582,6 +599,11 @@ async fn edit(args: &serde_json::Value, root: &Path, scratch: Option<&Path>, con
return format!("ERROR: refused to edit outside the agent workspace: {path}");
}
let shown = display_path(root, scratch, &target);
+ // Re-validate before the final read+write pair so a swapped symlink cannot
+ // redirect either the read or the later write.
+ if symlink_escapes_root(root, scratch, &target) {
+ return format!("ERROR: refused to edit through a symlink out of the workspace: {path}");
+ }
let mut content = match tokio::fs::read_to_string(&target).await {
Ok(c) => c,
Err(e) => return format!("ERROR: {shown}: {e}"),
@@ -631,8 +653,6 @@ async fn bash(args: &serde_json::Value, ctx: &ToolContext<'_>) -> String {
);
}
- // No confinement available means no shell: running unsandboxed would give the
- // command the whole machine, which is never what the caller asked for.
let mut policy = jail::Policy::new(root, ctx.allow_network)
.with_home_readonly(ctx.home_readonly)
.with_hide_root(&root.join(crate::tools::sandbox::JAN_DIR));
@@ -642,13 +662,31 @@ async fn bash(args: &serde_json::Value, ctx: &ToolContext<'_>) -> String {
if let Some(scratch) = ctx.scratch_root {
policy = policy.with_scratch_root(scratch);
}
- let Some(shell) = jail::wrap(proc::shell(), &policy) else {
- return "ERROR: bash is unavailable because no OS sandbox could be established on this \
- system. Use the read/ls/find/grep tools instead."
- .to_string();
+ // With the sandbox off the shell is spawned bare, the way the user's own
+ // terminal would: no wrapper, no policy, the real `$HOME` and `/tmp`. Only
+ // a surface that opted in gets here (the CLI's `--sandbox`/`sandbox`
+ // setting); the desktop never does, so `bash` there is still confined or
+ // withheld. `policy` is still built either way -- it is what
+ // `denial_hint` reads, and an unconfined command can still hit a plain
+ // filesystem permission error worth explaining.
+ let shell = if ctx.sandbox {
+ // No confinement available means no shell: running unsandboxed would give
+ // the command the whole machine, which is never what the caller asked for.
+ let Some(wrapped) = jail::wrap(proc::shell(), &policy) else {
+ return "ERROR: bash is unavailable because no OS sandbox could be established on \
+ this system. Use the read/ls/find/grep tools instead."
+ .to_string();
+ };
+ wrapped
+ } else {
+ proc::shell().clone()
};
- let sandbox_tmp = jail::scratch_env_path(jail::backend(), &policy);
+ let sandbox_tmp = if ctx.sandbox {
+ jail::scratch_env_path(jail::backend(), &policy)
+ } else {
+ None
+ };
let child = match proc::spawn(&shell, command, root, sandbox_tmp.as_deref()).await {
Ok(c) => c,
Err(e) => return format!("ERROR: failed to run command: {e}"),
@@ -662,12 +700,15 @@ async fn bash(args: &serde_json::Value, ctx: &ToolContext<'_>) -> String {
// reap its whole process tree if it is still running.
let (tx, mut rx) = oneshot::channel();
let spill_scratch = ctx.scratch_root.map(Path::to_path_buf);
+ let sandboxed = ctx.sandbox;
tokio::spawn(async move {
let mut out = collect_and_format(child, spill_scratch).await;
// Appended inside the task so a backgrounded job carries the hint too.
// `Permission denied` on its own tells the model nothing about *why*;
- // without this it retries the same command until it gives up.
- if bash_result_failed(&out) && jail::looks_denied(&out) {
+ // without this it retries the same command until it gives up. Only when
+ // confined: unsandboxed, a denial is an ordinary filesystem permission
+ // and the hint would name limits that are not in force.
+ if sandboxed && bash_result_failed(&out) && jail::looks_denied(&out) {
out.push_str(&jail::denial_hint(&policy));
}
if let Some(pid) = pid {
@@ -767,14 +808,15 @@ impl BashCapture {
// yet), so dumping it captures the full prefix before we start
// dropping from the front.
if self.spill.is_none() && self.tail.len() + chunk.len() > BASH_MAX_BYTES {
- let path = new_temp_path(self.scratch.as_deref());
- if let Ok(file) = std::fs::File::create(&path) {
- let mut w = std::io::BufWriter::new(file);
- let (a, b) = self.tail.as_slices();
- let _ = w.write_all(a);
- let _ = w.write_all(b);
- self.spill = Some(w);
- self.spill_path = Some(path);
+ if let Some(path) = new_temp_path(self.scratch.as_deref()) {
+ if let Ok(file) = open_spill_file(&path) {
+ let mut w = std::io::BufWriter::new(file);
+ let (a, b) = self.tail.as_slices();
+ let _ = w.write_all(a);
+ let _ = w.write_all(b);
+ self.spill = Some(w);
+ self.spill_path = Some(path);
+ }
}
}
if let Some(w) = self.spill.as_mut() {
@@ -817,7 +859,7 @@ impl BashCapture {
if !truncated {
if let Some(p) = self.spill_path.take() {
- let _ = std::fs::remove_file(p);
+ remove_spill_file(&p);
}
return body;
}
@@ -871,7 +913,7 @@ impl Drop for BashCapture {
/// fires on the leak paths.
fn drop(&mut self) {
if let Some(p) = self.spill_path.take() {
- let _ = std::fs::remove_file(p);
+ remove_spill_file(&p);
}
}
}
@@ -918,31 +960,84 @@ fn tail_cap(s: &str, max_lines: usize, max_bytes: usize) -> String {
/// same `/tmp/jan-bash/...` name from both the filesystem tools and the shell,
/// and is reclaimed when the session's scratch is removed.
///
+/// The directory is validated as a real, non-symlink directory before use: the
+/// sandboxed shell can write the scratch, so it could have redirected `jan-bash`
+/// at a host directory. Refuse to spill through a redirect (returning `None`)
+/// rather than write the model's bytes through an attacker-chosen path.
+///
/// Deliberately not swept on first use: the files are removed individually by
/// [`BashCapture::finish`] and its `Drop`, and the host fallback is a shared
/// path, so a global purge there would delete a concurrent instance's live
/// spill files rather than only stale ones.
-fn spill_dir(scratch: Option<&Path>) -> PathBuf {
+fn spill_dir(scratch: Option<&Path>) -> Option<PathBuf> {
let base = scratch
.map(Path::to_path_buf)
.unwrap_or_else(std::env::temp_dir);
let dir = base.join("jan-bash");
- let _ = std::fs::create_dir_all(&dir);
- dir
+ match std::fs::symlink_metadata(&dir) {
+ Ok(meta) if !meta.is_dir() => return None,
+ Ok(_) => {}
+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
+ // create_dir (not create_dir_all) refuses to follow a planted
+ // symlink in the path it creates.
+ let r = std::fs::create_dir(&dir);
+ if let Err(e) = r {
+ if e.kind() != std::io::ErrorKind::AlreadyExists {
+ return None;
+ }
+ }
+ }
+ Err(_) => return None,
+ }
+ // Re-verify the node is a real directory, not a symlink a concurrent
+ // process swapped in between the create and this check.
+ match std::fs::symlink_metadata(&dir) {
+ Ok(meta) if !meta.file_type().is_symlink() && meta.is_dir() => Some(dir),
+ _ => None,
+ }
}
-fn new_temp_path(scratch: Option<&Path>) -> PathBuf {
+fn new_temp_path(scratch: Option<&Path>) -> Option<PathBuf> {
let n = TEMP_COUNTER.fetch_add(1, Ordering::SeqCst);
- spill_dir(scratch).join(format!("jan-bash-{}-{}.txt", std::process::id(), n))
+ Some(
+ spill_dir(scratch)?.join(format!("jan-bash-{}-{}.txt", std::process::id(), n)),
+ )
}
-/// Write `content` to a uniquely named temp file, returning its path on success.
+/// Open a spill file atomically with `O_EXCL` so we never truncate or write
+/// through an existing symlink the shell planted: `create_new` fails if the
+/// path already exists (as a file or a symlink). Combined with the validated
+/// non-symlink parent from [`spill_dir`], the model-controlled spill bytes
+/// cannot be redirected onto a host file.
+fn open_spill_file(path: &Path) -> std::io::Result<std::fs::File> {
+ std::fs::OpenOptions::new().write(true).create_new(true).open(path)
+}
+
+/// Write `content` to a uniquely named temp file, returning its path on
+/// success. Uses [`open_spill_file`] so the write never follows a symlink.
fn write_temp_output(content: &str, scratch: Option<&Path>) -> Option<PathBuf> {
- let path = new_temp_path(scratch);
- std::fs::write(&path, content).ok()?;
+ use std::io::Write;
+ let path = new_temp_path(scratch)?;
+ let mut file = open_spill_file(&path).ok()?;
+ file.write_all(content.as_bytes()).ok()?;
Some(path)
}
+/// Remove a spill file only through a real, non-symlink parent directory. The
+/// shell controls the scratch, so a redirected `jan-bash` dir must not redirect
+/// our cleanup either; if it has been swapped, leave the file behind (it is
+/// reclaimed with the session's scratch). `remove_file` itself unlinks a
+/// symlink rather than following it, so only the parent needs re-checking.
+fn remove_spill_file(path: &Path) {
+ if let Some(parent) = path.parent() {
+ match std::fs::symlink_metadata(parent) {
+ Ok(meta) if !meta.file_type().is_symlink() && meta.is_dir() => {}
+ _ => return,
+ }
+ }
+ let _ = std::fs::remove_file(path);
+}
+
async fn find(args: &serde_json::Value, root: &Path, scratch: Option<&Path>) -> String {
let pattern = arg_str(args, "pattern").map(String::from);
let path = arg_str(args, "path").unwrap_or(".").to_string();
@@ -950,6 +1045,9 @@ async fn find(args: &serde_json::Value, root: &Path, scratch: Option<&Path>) ->
.map(|v| v as usize)
.unwrap_or(FIND_DEFAULT_LIMIT);
let base = resolve_path(root, scratch, &path);
+ if symlink_escapes_root(root, scratch, &base) {
+ return format!("ERROR: refused to search through a symlink out of the workspace: {path}");
+ }
let root_owned = root.to_path_buf();
let Some(pattern) = pattern else {
@@ -1007,7 +1105,11 @@ async fn grep(args: &serde_json::Value, root: &Path, scratch: Option<&Path>) ->
.map(|v| v as usize)
.unwrap_or(GREP_DEFAULT_LIMIT);
let base = resolve_path(root, scratch, &path);
+ if symlink_escapes_root(root, scratch, &base) {
+ return format!("ERROR: refused to search through a symlink out of the workspace: {path}");
+ }
let root_owned = root.to_path_buf();
+ let scratch_owned = scratch.map(Path::to_path_buf);
let Some(pattern) = pattern else {
return "ERROR: missing required argument 'pattern'".to_string();
@@ -1092,7 +1194,19 @@ async fn grep(args: &serde_json::Value, root: &Path, scratch: Option<&Path>) ->
.build()
.flatten()
{
- if entry.file_type().map(|t| t.is_dir()).unwrap_or(true) {
+ let Some(file_type) = entry.file_type() else {
+ continue;
+ };
+ if file_type.is_dir() {
+ continue;
+ }
+ // The walk does not descend symlinked directories, but a symlink
+ // to a *file* is not a directory and would be opened and read.
+ // Checked (not skipped outright) so a link that stays inside the
+ // workspace -- every yarn workspace has them -- is still searched.
+ if file_type.is_symlink()
+ && symlink_escapes_root(&root_owned, scratch_owned.as_deref(), entry.path())
+ {
continue;
}
if is_hidden_jan_path(&root_owned, &entry.path().to_string_lossy()) {
@@ -1692,6 +1806,99 @@ mod tests {
let _ = std::fs::remove_dir_all(&outside);
}
+ /// A recursive `grep` must not follow a *file* symlink out of the root.
+ /// The directory-symlink case is covered by WalkBuilder's no-follow default
+ /// (directories are recursed, symlinks to dirs are not entered), but a
+ /// symlink to a file is not classified as a directory and would be opened
+ /// and read. Skip every symlink so a planted `key -> $HOME/.ssh/id_rsa`
+ /// cannot be disclosed without a separate approval.
+ #[cfg(target_os = "linux")]
+ #[tokio::test]
+ async fn grep_does_not_read_a_file_symlink_out_of_the_root() {
+ let root = unique_root();
+ let outside = unique_root();
+ std::fs::write(outside.join("secret.txt"), b"classified").unwrap();
+ std::os::unix::fs::symlink(outside.join("secret.txt"), root.join("key.txt")).unwrap();
+ std::fs::write(root.join("real.txt"), b"plain").unwrap();
+ let out = execute_builtin(lookup("grep").unwrap(), &json!({"pattern": "classified", "path": "."}), &root).await;
+ assert!(
+ !out.contains("secret") && !out.contains("classified"),
+ "read through a file symlink outside the root: {out}"
+ );
+ let _ = std::fs::remove_dir_all(&root);
+ let _ = std::fs::remove_dir_all(&outside);
+ }
+
+ /// The escaping-symlink refusals must not become a blanket "no symlinks":
+ /// a link that stays inside the workspace is ordinary (every yarn workspace
+ /// links `node_modules/<pkg>` back into the repo), so `grep` still searches
+ /// through it and `read` still opens it.
+ #[cfg(unix)]
+ #[tokio::test]
+ async fn in_root_symlinks_stay_readable_and_searchable() {
+ let root = unique_root();
+ std::fs::create_dir_all(root.join("pkg")).unwrap();
+ std::fs::write(root.join("pkg/index.js"), b"needle here").unwrap();
+ std::os::unix::fs::symlink(root.join("pkg/index.js"), root.join("linked.js")).unwrap();
+
+ let out = execute_builtin(lookup("read").unwrap(), &json!({"path": "linked.js"}), &root).await;
+ assert!(out.contains("needle"), "in-root symlink was refused: {out}");
+
+ let out = execute_builtin(lookup("grep").unwrap(), &json!({"pattern": "needle", "path": "."}), &root).await;
+ assert!(out.contains("linked.js"), "in-root symlink was skipped: {out}");
+
+ let _ = std::fs::remove_dir_all(&root);
+ }
+
+ /// A redirected spill directory must refuse to write through it. The shell
+ /// can replace `scratch/jan-bash` with a symlink to a host directory (or
+ /// point `jan-bash` at one), so both spill entry points must come up empty
+ /// rather than place the model's bytes at an attacker-chosen location.
+ #[cfg(unix)]
+ #[test]
+ fn spill_writing_refuses_a_redirected_spill_dir() {
+ let scratch = unique_root();
+ let outside = unique_root();
+ std::os::unix::fs::symlink(&outside, scratch.join("jan-bash")).unwrap();
+
+ assert!(new_temp_path(Some(&scratch)).is_none(), "dir symlink accepted");
+ assert!(
+ write_temp_output("x", Some(&scratch)).is_none(),
+ "wrote through a redirected spill dir"
+ );
+ // The outside host directory is untouched.
+ assert_eq!(
+ std::fs::read_dir(&outside).unwrap().count(),
+ 0,
+ "host files created via a symlinked spill dir"
+ );
+ let _ = std::fs::remove_dir_all(&scratch);
+ let _ = std::fs::remove_dir_all(&outside);
+ }
+
+ /// A spill *file* that is a planted symlink must never be opened (truncated
+ /// and written through), so the host target it points at stays intact.
+ #[cfg(unix)]
+ #[test]
+ fn spill_file_writes_never_follow_a_planted_symlink() {
+ let scratch = unique_root();
+ let outside = unique_root();
+ std::fs::create_dir_all(scratch.join("jan-bash")).unwrap();
+ let victim = outside.join("victim.txt");
+ std::fs::write(&victim, b"precious").unwrap();
+ let planted = scratch.join("jan-bash/spill.txt");
+ std::os::unix::fs::symlink(&victim, &planted).unwrap();
+
+ assert!(open_spill_file(&planted).is_err(), "opened a spill symlink");
+ assert_eq!(
+ std::fs::read_to_string(&victim).unwrap(),
+ "precious",
+ "wrote through the spill symlink to the host file"
+ );
+ let _ = std::fs::remove_dir_all(&scratch);
+ let _ = std::fs::remove_dir_all(&outside);
+ }
+
/// The write escape the scratch clamp is there to stop, spelled with a
/// symlink instead of `..`: a confined `write` through `/tmp/esc` must be
/// refused and must leave nothing behind outside the scratch.
@@ -1722,9 +1929,68 @@ mod tests {
let _ = std::fs::remove_dir_all(&outside);
}
+ /// The handler itself re-checks for symlinks immediately before opening,
+ /// closing the gate-vs-use window. A read through a planted symlink must be
+ /// refused (not silently resolved), even when the gate already allowed the
+ /// path inside the root.
+ #[cfg(unix)]
+ #[tokio::test]
+ async fn read_refuses_a_symlink_redirected_file() {
+ let root = unique_root();
+ let outside = unique_root();
+ std::fs::write(outside.join("secret.txt"), b"classified").unwrap();
+ std::os::unix::fs::symlink(outside.join("secret.txt"), root.join("link.txt")).unwrap();
+ let out = execute_builtin(lookup("read").unwrap(), &json!({"path": "link.txt"}), &root).await;
+ assert!(out.starts_with("ERROR"), "must refuse, got: {out}");
+ let _ = std::fs::remove_dir_all(&root);
+ let _ = std::fs::remove_dir_all(&outside);
+ }
+
+ /// The same re-check on the writing side, and it must fire *before* the
+ /// parent directories are created: a refused write that has already made
+ /// directories through the planted link has still touched the host.
+ #[cfg(unix)]
+ #[tokio::test]
+ async fn write_and_edit_refuse_a_symlink_redirected_file() {
+ let root = unique_root();
+ let outside = unique_root();
+ std::fs::write(outside.join("victim.txt"), b"precious").unwrap();
+ std::os::unix::fs::symlink(&outside, root.join("escape")).unwrap();
+
+ let out = execute_builtin(
+ lookup("write").unwrap(),
+ &json!({"path": "escape/victim.txt", "content": "owned"}),
+ &root,
+ )
+ .await;
+ assert!(out.starts_with("ERROR"), "write must refuse, got: {out}");
+
+ let out = execute_builtin(
+ lookup("edit").unwrap(),
+ &json!({"path": "escape/victim.txt", "edits": [{"old_string": "precious", "new_string": "owned"}]}),
+ &root,
+ )
+ .await;
+ assert!(out.starts_with("ERROR"), "edit must refuse, got: {out}");
+
+ assert_eq!(
+ std::fs::read_to_string(outside.join("victim.txt")).unwrap(),
+ "precious"
+ );
+ // Nothing was created through the link on the way to the refusal.
+ assert_eq!(
+ std::fs::read_dir(&outside).unwrap().count(),
+ 1,
+ "directories were created through the symlink"
+ );
+ let _ = std::fs::remove_dir_all(&root);
+ let _ = std::fs::remove_dir_all(&outside);
+ }
+
/// A `write` to `/tmp/x` lands in the session scratch, and a `read` of the
/// same path sees it: every fs tool shares the one `/tmp` the shell sees.
#[tokio::test]
+ #[cfg(target_os = "linux")]
async fn write_then_read_via_tmp_persists_in_scratch() {
let root = unique_root();
let scratch = unique_root();
@@ -1756,6 +2022,7 @@ mod tests {
/// The bare `/tmp` dir resolves to the scratch root; files written there by
/// the shell (or a sibling tool) are listable through the file tools.
#[test]
+ #[cfg(target_os = "linux")]
fn resolve_path_maps_tmp_into_scratch() {
let root = unique_root();
let scratch = unique_root();
@@ -1781,6 +2048,7 @@ mod tests {
/// scratch root (chroot semantics, matching the `/tmp` bind mount), so it
/// can never reach the host temp.
#[test]
+ #[cfg(target_os = "linux")]
fn tmp_path_cannot_climb_out_with_dotdot() {
let root = unique_root();
let scratch = unique_root();
@@ -1801,6 +2069,7 @@ mod tests {
/// The gate treats a scratch-backed `/tmp` write as inside, not an escape.
#[test]
+ #[cfg(target_os = "linux")]
fn gate_allows_tmp_write_when_scratch_is_set() {
let root = unique_root();
let scratch = unique_root();
@@ -2272,6 +2541,58 @@ mod tests {
let _ = std::fs::remove_dir_all(&scratch);
}
+ /// With the sandbox off, `bash` runs bare instead of being wrapped or
+ /// withheld. The point of the opt-out is that it works on a machine where
+ /// no backend can be established, so this must not depend on one.
+ #[cfg(unix)]
+ #[tokio::test]
+ async fn unsandboxed_bash_runs_without_a_backend() {
+ let root = unique_root();
+ let store = crate::workspace::project_store(&root);
+ let ctx = ToolContext::new(&root, &store, &[]).with_sandbox(false);
+ let out = super::execute_builtin(
+ lookup("bash").unwrap(),
+ &json!({"command": "echo unconfined"}),
+ &ctx,
+ )
+ .await;
+ assert!(out.contains("unconfined"), "unsandboxed bash did not run: {out}");
+ assert!(
+ !out.contains("no OS sandbox could be established"),
+ "withheld despite the opt-out: {out}"
+ );
+ let _ = std::fs::remove_dir_all(&root);
+ }
+
+ /// Dropping the sandbox drops the scratch with it, in either builder order.
+ /// A scratch that outlived the sandbox would leave the fs tools rewriting
+ /// `/tmp/...` into a directory the unconfined shell never looks at.
+ #[test]
+ fn unsandboxed_context_has_no_scratch() {
+ let root = unique_root();
+ let scratch = unique_root();
+ let store = crate::workspace::project_store(&root);
+ assert!(ToolContext::new(&root, &store, &[])
+ .with_scratch_root(&scratch)
+ .with_sandbox(false)
+ .scratch_root
+ .is_none());
+ assert!(ToolContext::new(&root, &store, &[])
+ .with_sandbox(false)
+ .with_scratch_root(&scratch)
+ .scratch_root
+ .is_none());
+ // The sandboxed default still binds it.
+ assert_eq!(
+ ToolContext::new(&root, &store, &[])
+ .with_scratch_root(&scratch)
+ .scratch_root,
+ Some(scratch.as_path())
+ );
+ let _ = std::fs::remove_dir_all(&root);
+ let _ = std::fs::remove_dir_all(&scratch);
+ }
+
#[tokio::test]
async fn bash_line_overflow_keeps_the_tail_not_the_head() {
let root = unique_root();
diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/mod.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/mod.rs
index cd6bde773..62e19cee4 100644
--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/mod.rs
+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/mod.rs
@@ -61,6 +61,15 @@ pub struct ToolContext<'a> {
/// default throwaway per-command tmpfs. Cleaned up with the session (run end
/// on the CLI, thread teardown on the desktop).
pub scratch_root: Option<&'a Path>,
+ /// Whether `bash` runs under OS confinement. On by default, and the desktop
+ /// keeps it that way: there, `bash` is either sandboxed or withheld.
+ ///
+ /// The CLI turns it off (see its `--sandbox` flag and the `sandbox` config
+ /// key), which runs the shell exactly as the user's own terminal would --
+ /// no mounts, no policy, the user's real `$HOME` and `/tmp`. The permission
+ /// gate is then the only thing between the model and the machine, which is
+ /// why nothing else about the gate changes when this is off.
+ pub sandbox: bool,
}
impl<'a> ToolContext<'a> {
@@ -74,6 +83,7 @@ impl<'a> ToolContext<'a> {
mask_root: None,
home_readonly: false,
scratch_root: None,
+ sandbox: true,
}
}
@@ -100,8 +110,27 @@ impl<'a> ToolContext<'a> {
/// Bind `scratch_root` over the sandbox's `/tmp` so scratch files survive
/// across `bash` calls. See [`Self::scratch_root`].
+ /// Ignored when the sandbox is off, so the two builders commute (see
+ /// [`Self::with_sandbox`] for why an unconfined run has no scratch).
pub fn with_scratch_root(mut self, scratch_root: &'a Path) -> Self {
- self.scratch_root = Some(scratch_root);
+ if self.sandbox {
+ self.scratch_root = Some(scratch_root);
+ }
+ self
+ }
+
+ /// Run `bash` under OS confinement (the default). See [`Self::sandbox`].
+ ///
+ /// Turning it off also drops the scratch: the scratch only makes sense as
+ /// the thing bound over the sandbox's `/tmp`. Unconfined, the shell sees the
+ /// real `/tmp`, and leaving the scratch set would have the filesystem tools
+ /// still rewriting `/tmp/...` into a directory the shell never looks at --
+ /// two tools disagreeing about what one path means.
+ pub fn with_sandbox(mut self, sandbox: bool) -> Self {
+ self.sandbox = sandbox;
+ if !sandbox {
+ self.scratch_root = None;
+ }
self
}
}
diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/sandbox.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/sandbox.rs
index 06332d867..da0a2f853 100644
--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/sandbox.rs
+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/sandbox.rs
@@ -159,11 +159,12 @@ fn tmp_relative(raw: &str) -> Option<String> {
if !path.is_absolute() {
return None;
}
- let rest = raw.strip_prefix("/tmp")?;
- if rest.is_empty() {
+ // Match only the exact `/tmp` dir or a genuine `/tmp/...` descendant: a
+ // raw string prefix would treat `/tmpx` and `/tmp-archive` as inside /tmp.
+ if raw == "/tmp" {
return Some(String::new());
}
- Some(rest.strip_prefix('/').unwrap_or(rest).to_string())
+ Some(raw.strip_prefix("/tmp/")?.to_string())
}
/// The agent's own state directory inside a project. Hidden wholesale rather
@@ -206,6 +207,49 @@ pub fn command_touches_hidden_jan_path(project_root: &Path, command: &str) -> bo
.any(|t| is_hidden_jan_path(project_root, t))
}
+/// True when `target` *claims* to be inside a trusted root but resolves outside
+/// every one of them: the fail-closed re-check a handler runs immediately
+/// before its final open, closing the window between the gate's
+/// decision-time canonicalization and the handler's use of the raw path.
+///
+/// Containment, not symlink-avoidance: a link that stays beneath a trusted root
+/// is ordinary and must keep working (a yarn workspace's
+/// `node_modules/<pkg> -> ../../pkg` is one, and refusing those would make the
+/// tools useless in a monorepo). Only a link whose target leaves the roots is an
+/// escape.
+///
+/// A target that is not even lexically under a root is left alone: it is an
+/// escape the gate already put to the user, and re-deciding it here would
+/// override their approval. An unresolvable path fails closed.
+///
+/// Still a re-check, not a guarantee: a swap landing between this call and the
+/// open is not covered. That needs descriptor-relative no-follow opens
+/// (`openat2` with `RESOLVE_BENEATH`, reparse-point handling on Windows).
+pub fn symlink_escapes_root(
+ project_root: &Path,
+ scratch: Option<&Path>,
+ target: &Path,
+) -> bool {
+ let mut roots = vec![project_root];
+ if let Some(s) = scratch {
+ roots.push(s);
+ }
+ let normalized = lexical_normalize(target);
+ if !roots
+ .iter()
+ .any(|r| normalized.starts_with(lexical_normalize(r)))
+ {
+ return false;
+ }
+ let Ok(resolved) = canonicalize_lenient(&normalized) else {
+ return true;
+ };
+ !roots
+ .iter()
+ .filter_map(|r| r.canonicalize().ok())
+ .any(|r| resolved.starts_with(r))
+}
+
/// Canonicalize a path that may not fully exist: canonicalize the deepest
/// existing ancestor, then re-append the non-existing tail (resolving `.`/`..`
/// lexically). Errors only if no ancestor up to root exists.
@@ -501,4 +545,50 @@ mod tests {
let _ = std::fs::remove_dir_all(&root);
let _ = std::fs::remove_dir_all(&outside);
}
+
+ /// The re-check flags only symlinks that *leave* the trusted roots. An
+ /// in-root link (the shape every yarn workspace has) resolves back inside
+ /// and must stay usable; a link out of the root is an escape; a path that
+ /// was never under a root at all is the gate's business, not this check's.
+ #[cfg(unix)]
+ #[test]
+ fn symlink_escape_recheck_allows_in_root_links() {
+ let root = unique_root();
+ let outside = unique_root();
+ std::fs::create_dir_all(root.join("pkg")).unwrap();
+ std::fs::write(root.join("pkg/index.js"), b"x").unwrap();
+ std::fs::write(outside.join("secret.txt"), b"s").unwrap();
+
+ let inward = root.join("linked");
+ std::os::unix::fs::symlink(root.join("pkg"), &inward).unwrap();
+ let outward = root.join("escape");
+ std::os::unix::fs::symlink(&outside, &outward).unwrap();
+
+ assert!(!symlink_escapes_root(&root, None, &inward.join("index.js")));
+ assert!(symlink_escapes_root(&root, None, &outward.join("secret.txt")));
+ // A not-yet-existing leaf under a real directory is not an escape.
+ assert!(!symlink_escapes_root(&root, None, &root.join("pkg/new.txt")));
+ // Outside both roots: the gate already decided, so this check abstains.
+ assert!(!symlink_escapes_root(&root, None, &outside.join("secret.txt")));
+ // The scratch counts as a trusted root, so a link between the two is in.
+ let scratch = unique_root();
+ let cross = scratch.join("into-project");
+ std::os::unix::fs::symlink(root.join("pkg"), &cross).unwrap();
+ assert!(!symlink_escapes_root(&root, Some(&scratch), &cross.join("index.js")));
+
+ let _ = std::fs::remove_dir_all(&root);
+ let _ = std::fs::remove_dir_all(&outside);
+ let _ = std::fs::remove_dir_all(&scratch);
+ }
+
+ /// `/tmpx` and `/tmp-archive` are not descendants of `/tmp` and must not be
+ /// silently redirected into the scratch.
+ #[test]
+ fn tmp_lookalikes_are_not_remapped() {
+ assert_eq!(tmp_relative("/tmp"), Some(String::new()));
+ assert_eq!(tmp_relative("/tmp/"), Some(String::new()));
+ assert_eq!(tmp_relative("/tmp/a.txt"), Some("a.txt".to_string()));
+ assert_eq!(tmp_relative("/tmpx"), None);
+ assert_eq!(tmp_relative("/tmp-archive/a.txt"), None);
+ }
}
diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/workspace.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/workspace.rs
index 0d1dc4a0a..e92a63183 100644
--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/workspace.rs
+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/workspace.rs
@@ -81,11 +81,112 @@ pub fn scratch_dir(session: &str) -> PathBuf {
/// its teardown: thread deletion on the desktop, run end on the CLI, and
/// session end in the TUI.
pub async fn ensure_scratch_dir(session: &str) -> Result<PathBuf, String> {
- let dir = scratch_dir(session);
- tokio::fs::create_dir_all(&dir)
- .await
- .map_err(|e| format!("ERROR: {e}"))?;
- Ok(dir)
+ ensure_scratch_dir_path(&scratch_dir(session)).await
+}
+
+/// Create a scratch directory at an explicit path, hardening it against a
+/// pre-planted symlink: the sandbox must never bind or trust an
+/// attacker-selected directory as its sanctioned scratch. Refuses (fail
+/// closed) when the target already exists as a symlink or is not a real
+/// directory, and applies restrictive 0700 permissions on Unix so no other
+/// local user can read the session's scratch files. `create_dir` (not
+/// `create_dir_all`) is used so the final component is created directly and a
+/// parent symlink cannot redirect it.
+pub async fn ensure_scratch_dir_path(dir: &Path) -> Result<PathBuf, String> {
+ match tokio::fs::symlink_metadata(dir).await {
+ Ok(meta) => {
+ if !meta.file_type().is_symlink() && meta.is_dir() {
+ // Already a real directory; keep it.
+ } else {
+ return Err(format!(
+ "ERROR: scratch path {:?} is not a real directory",
+ dir
+ ));
+ }
+ }
+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
+ if let Some(parent) = dir.parent() {
+ tokio::fs::create_dir_all(parent)
+ .await
+ .map_err(|e| format!("ERROR: {e}"))?;
+ }
+ // `create_dir` (not `create_dir_all`) so the final component is made
+ // directly and a parent symlink cannot redirect it. A concurrent
+ // creator is fine: re-verify the existing node is a real directory.
+ if let Err(e) = tokio::fs::create_dir(dir).await {
+ if e.kind() != std::io::ErrorKind::AlreadyExists {
+ return Err(format!("ERROR: {e}"));
+ }
+ }
+ // Re-verify after creation: a concurrent swap could have replaced
+ // the freshly made directory with a symlink.
+ match tokio::fs::symlink_metadata(dir).await {
+ Ok(meta) if !meta.file_type().is_symlink() && meta.is_dir() => {}
+ _ => return Err(format!("ERROR: scratch path {:?} is not a real directory", dir)),
+ }
+ }
+ Err(e) => return Err(format!("ERROR: {e}")),
+ }
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+ let _ = tokio::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700)).await;
+ }
+ Ok(dir.to_path_buf())
+}
+
+/// How long a scratch directory may sit untouched before the startup sweep
+/// treats it as abandoned. Age-based rather than "remove every scratch at
+/// startup" so a second Jan instance cannot wipe the first one's live scratch.
+const SCRATCH_STALE_AFTER: std::time::Duration = std::time::Duration::from_secs(24 * 60 * 60);
+
+/// Delete abandoned scratch directories in the host temp dir, returning how many
+/// were removed.
+///
+/// Every scratch has an owner that removes it (run end, thread deletion, session
+/// end), but a kill -9 or a power loss leaves one behind with nobody left to
+/// claim it: the id it is keyed to lives in the caller's state, not on disk, so
+/// no `keep` list can be reconstructed the way [`sweep_thread_workspaces`] does
+/// it. Age is the only signal available, so anything untouched for
+/// [`SCRATCH_STALE_AFTER`] is collected. Called once at startup.
+///
+/// Failures are silent per entry: another user's `jan-agent-*` in a shared
+/// `/tmp` is not ours to delete and simply fails the unlink.
+pub async fn sweep_stale_scratch_dirs() -> usize {
+ sweep_scratch_older_than(SCRATCH_STALE_AFTER).await
+}
+
+/// [`sweep_stale_scratch_dirs`] with an explicit age, so a test can collect a
+/// scratch it just created instead of waiting a day.
+async fn sweep_scratch_older_than(max_age: std::time::Duration) -> usize {
+ let Ok(mut entries) = tokio::fs::read_dir(std::env::temp_dir()).await else {
+ return 0;
+ };
+ let mut removed = 0;
+ while let Ok(Some(entry)) = entries.next_entry().await {
+ let name = entry.file_name();
+ let Some(name) = name.to_str() else { continue };
+ if !name.starts_with("jan-agent-") {
+ continue;
+ }
+ // `symlink_metadata`: a symlink named like a scratch is not one, and
+ // following it would delete whatever it points at.
+ let Ok(meta) = tokio::fs::symlink_metadata(entry.path()).await else {
+ continue;
+ };
+ if meta.file_type().is_symlink() || !meta.is_dir() {
+ continue;
+ }
+ let stale = meta
+ .modified()
+ .ok()
+ .and_then(|m| m.elapsed().ok())
+ .is_some_and(|age| age >= max_age);
+ if stale && tokio::fs::remove_dir_all(entry.path()).await.is_ok() {
+ removed += 1;
+ }
+ }
+ removed
}
/// Delete a session's scratch directory. Idempotent: a missing scratch is Ok.
@@ -280,6 +381,58 @@ mod tests {
remove_scratch_dir(session).await.unwrap();
}
+ /// A scratch whose owner died (kill -9, power loss) has nobody left to
+ /// remove it and no `keep` list to rebuild, so the startup sweep collects it
+ /// by age. Nothing else in the temp dir is touched, and a fresh scratch
+ /// survives the real 24h threshold.
+ #[tokio::test]
+ async fn stale_scratch_dirs_are_swept_and_fresh_ones_are_not() {
+ let session = format!("sweep-stale-{}", std::process::id());
+ let orphan = ensure_scratch_dir(&session).await.unwrap();
+ std::fs::write(orphan.join("spill.txt"), b"leaked").unwrap();
+ let bystander = std::env::temp_dir().join(format!("not-a-scratch-{session}"));
+ std::fs::create_dir_all(&bystander).unwrap();
+
+ assert_eq!(sweep_stale_scratch_dirs().await, 0, "a fresh scratch is live");
+ assert!(orphan.is_dir());
+
+ assert!(sweep_scratch_older_than(std::time::Duration::ZERO).await >= 1);
+ assert!(!orphan.exists(), "an abandoned scratch must be collected");
+ assert!(bystander.is_dir(), "swept a directory that is not a scratch");
+
+ let _ = std::fs::remove_dir_all(&bystander);
+ }
+
+ /// The scratch root must never be a pre-planted symlink to another
+ /// directory: the sandbox binds it as `/tmp`, so trusting a redirect would
+ /// sanction an attacker-selected directory as the session's scratch.
+ #[cfg(unix)]
+ #[tokio::test]
+ async fn scratch_root_refuses_a_pre_planted_symlink() {
+ let dir = unique_data_folder();
+ let outside = unique_data_folder();
+ std::os::unix::fs::symlink(&outside, &dir).unwrap();
+ let r = ensure_scratch_dir_path(&dir).await;
+ assert!(r.is_err(), "symlinked scratch root accepted: {:?}", r);
+ let _ = std::fs::remove_dir_all(&dir);
+ let _ = std::fs::remove_dir_all(&outside);
+ }
+
+ /// A freshly created scratch root is a real, restrictive directory.
+ #[cfg(unix)]
+ #[tokio::test]
+ async fn scratch_root_creation_is_a_real_private_dir() {
+ use std::os::unix::fs::PermissionsExt;
+ let dir = unique_data_folder();
+ let r = ensure_scratch_dir_path(&dir).await;
+ assert_eq!(r.unwrap(), dir);
+ let meta = std::fs::symlink_metadata(&dir).unwrap();
+ assert!(!meta.file_type().is_symlink());
+ assert!(meta.is_dir());
+ assert_eq!(meta.permissions().mode() & 0o777, 0o700);
+ let _ = std::fs::remove_dir_all(&dir);
+ }
+
#[test]
fn thread_segment_rejects_traversal_and_separators() {
for bad in [
diff --git a/src-tauri/src/bin/jan.rs b/src-tauri/src/bin/jan.rs
index 609c9b3b2..65314f128 100644
--- a/src-tauri/src/bin/jan.rs
+++ b/src-tauri/src/bin/jan.rs
@@ -14,7 +14,7 @@ use app_lib::core::cli::run_report::OutputFormat;
use app_lib::core::cli::{
cli_agent_config_list, cli_agent_config_path, cli_agent_config_set, cli_agent_config_unset,
cli_agent_run, cli_agent_status, cli_agent_step, cli_agent_ui, cli_delete_thread,
- cli_get_thread, cli_list_messages, cli_list_threads, ResumeTarget,
+ cli_get_thread, cli_list_messages, cli_list_threads, ResumeTarget, SessionFlags,
};
// ── Top-level CLI ──────────────────────────────────────────────────────────
@@ -70,6 +70,36 @@ struct Cli {
/// Ignored when a subcommand is given.
#[arg(long)]
plan: bool,
+ #[command(flatten)]
+ sandbox: SandboxArgs,
+}
+
+/// Whether this invocation confines the shell, shared by every surface that
+/// starts an agent.
+///
+/// Two flags rather than one because the setting is also persistent
+/// (`sandbox` in `~/.jan/config.toml`, `[tools].sandbox` in agent.toml): with
+/// only `--sandbox` there would be no way to run unconfined once, and a user who
+/// turned it on permanently would have to edit a file to get out of it.
+#[derive(Args, Clone, Copy)]
+struct SandboxArgs {
+ /// Run shell commands under OS confinement (bubblewrap, Seatbelt, AppContainer)
+ #[arg(long)]
+ sandbox: bool,
+ /// Run shell commands unconfined, overriding a persistent sandbox setting
+ #[arg(long, conflicts_with = "sandbox")]
+ no_sandbox: bool,
+}
+
+impl SandboxArgs {
+ /// `None` when neither flag was passed, so the config files decide.
+ fn into_flag(self) -> Option<bool> {
+ match (self.sandbox, self.no_sandbox) {
+ (true, _) => Some(true),
+ (_, true) => Some(false),
+ _ => None,
+ }
+ }
}
/// Session-resume selection, shared by the bare TUI and `jan cli agent run`.
@@ -211,6 +241,8 @@ enum AgentCommands {
#[command(flatten)]
providers: ProviderArgs,
#[command(flatten)]
+ sandbox: SandboxArgs,
+ #[command(flatten)]
resume: ResumeRunArgs,
/// `text` streams the answer as it arrives; `json` prints one result
/// object on stdout when the run finishes
@@ -232,6 +264,8 @@ enum AgentCommands {
safe: bool,
#[command(flatten)]
providers: ProviderArgs,
+ #[command(flatten)]
+ sandbox: SandboxArgs,
},
/// Print resolved project config and available providers as JSON
Status {
@@ -369,8 +403,12 @@ async fn main() {
cli.model,
cli.images,
overrides,
- !cli.safe,
- cli.plan,
+ SessionFlags {
+ auto_approve: !cli.safe,
+ plan: cli.plan,
+ sandbox: cli.sandbox.into_flag(),
+ ..Default::default()
+ },
cli.resume.into_target(),
)
.await
@@ -461,6 +499,7 @@ async fn handle_agent(cmd: AgentCommands) {
model,
safe,
providers,
+ sandbox,
resume,
output_format,
} => {
@@ -469,7 +508,11 @@ async fn handle_agent(cmd: AgentCommands) {
&task,
model,
providers.into_overrides(),
- !safe,
+ SessionFlags {
+ auto_approve: !safe,
+ sandbox: sandbox.into_flag(),
+ ..Default::default()
+ },
resume.into_target(),
output_format,
)
@@ -481,7 +524,21 @@ async fn handle_agent(cmd: AgentCommands) {
model,
safe,
providers,
- } => cli_agent_step(&project, &task, model, providers.into_overrides(), !safe).await,
+ sandbox,
+ } => {
+ cli_agent_step(
+ &project,
+ &task,
+ model,
+ providers.into_overrides(),
+ SessionFlags {
+ auto_approve: !safe,
+ sandbox: sandbox.into_flag(),
+ ..Default::default()
+ },
+ )
+ .await
+ }
AgentCommands::Status { project, providers } => {
match cli_agent_status(&project, &providers.into_overrides()) {
Ok(status) => {
diff --git a/src-tauri/src/core/agent/commands.rs b/src-tauri/src/core/agent/commands.rs
index 3e6206a92..71290d8e5 100644
--- a/src-tauri/src/core/agent/commands.rs
+++ b/src-tauri/src/core/agent/commands.rs
@@ -75,6 +75,7 @@ fn build_orchestration_args<R: Runtime>(
auto_approve: false,
run_mode: crate::core::agent::plan::RunMode::Normal,
session_id: None,
+ sandbox: None,
}
}
@@ -103,6 +104,12 @@ pub async fn agent_run<R: Runtime>(
let cfg = load_agent_config(&project_root)?;
args.permissions = permissions_from(&cfg);
args.project_root = Some(project_root);
+ // Give this run its own scratch. Without this the session-less desktop
+ // path would fall back to a shared `<project>/agent-scratch` that
+ // accumulates across runs and across sessions; a per-run id also means
+ // the scratch can be wiped when the run ends (success, error, or
+ // cancel) instead of persisting in the user's project.
+ args.session_id = Some(uuid::Uuid::new_v4().to_string());
}
let (tx, mut rx) = mpsc::unbounded_channel::<StreamEvent>();
@@ -134,6 +141,14 @@ pub async fn agent_run<R: Runtime>(
let _ = forward.await;
runs.0.lock().await.remove(&run_id);
+ // Wipe this run's dedicated scratch on every terminal path (success, error,
+ // or cancel) so scratch and bash spill files never accumulate. A hard kill
+ // is the one path that skips this; the startup sweep collects what it
+ // leaves behind (`workspace::sweep_stale_scratch_dirs`).
+ if let Some(session) = args.session_id.as_deref() {
+ let _ = workspace::remove_scratch_dir(session).await;
+ }
+
result.map(|_| ())
}
diff --git a/src-tauri/src/core/agent/global_config.rs b/src-tauri/src/core/agent/global_config.rs
index 161a042d4..06c11a503 100644
--- a/src-tauri/src/core/agent/global_config.rs
+++ b/src-tauri/src/core/agent/global_config.rs
@@ -19,6 +19,9 @@ const GLOBAL_CONFIG_TEMPLATE: &str = r#"# Jan Agent global provider config.
# # defaults to `default_model` when unset
# mouse = false # disable TUI mouse tracking (scroll wheel,
# # click-to-expand); on by default
+# sandbox = true # run `bash` under OS confinement (same as
+# # passing --sandbox); off by default, so
+# # shell commands run with your own access
#
# [providers.my-provider]
# api_key = "sk-..."
@@ -40,6 +43,11 @@ struct GlobalConfigToml {
/// default, on.
#[serde(default, skip_serializing_if = "Option::is_none")]
mouse: Option<bool>,
+ /// Run the CLI's `bash` tool under OS confinement. `None` = the default,
+ /// off. This is the "permanently on" answer to the per-invocation
+ /// `--sandbox` flag.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ sandbox: Option<bool>,
#[serde(default)]
providers: HashMap<String, GlobalProviderEntry>,
}
@@ -148,6 +156,17 @@ pub(crate) fn mouse_enabled() -> bool {
.unwrap_or(true)
}
+/// Whether `bash` runs sandboxed by default (`sandbox` in `~/.jan/config.toml`).
+/// `None` when unset, so the caller can let a project's `agent.toml` or the
+/// `--sandbox` flag decide before falling back to the surface default.
+///
+/// An unreadable or malformed config yields `None` rather than an error: the
+/// resolved default is the *safe* direction to fall back to, and a config the
+/// user cannot parse must not be the thing that blocks a session from starting.
+pub(crate) fn sandbox_setting() -> Option<bool> {
+ load_raw().ok().and_then(|config| config.sandbox)
+}
+
/// Read `~/.jan/config.toml` into the raw TOML struct for editing. Missing file
/// -> default (empty); malformed file -> error, so a set never silently drops an
/// unparseable file's contents.
diff --git a/src-tauri/src/core/agent/loop.rs b/src-tauri/src/core/agent/loop.rs
index db538b0ae..1bb150478 100644
--- a/src-tauri/src/core/agent/loop.rs
+++ b/src-tauri/src/core/agent/loop.rs
@@ -5,6 +5,7 @@
//! completion JSON, so the API server's original contract is unchanged.
use std::collections::HashMap;
+use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;
use async_trait::async_trait;
@@ -98,6 +99,12 @@ pub(crate) struct OrchestrationArgs {
/// code paths with no session (server proxy runs) keeps the default
/// throwaway per-command tmpfs.
pub session_id: Option<String>,
+ /// Per-invocation override for `bash` confinement (the CLI's `--sandbox`).
+ /// `None` falls through to `[tools].sandbox`, then the user's global
+ /// `sandbox`, then the surface default -- see [`resolve_sandbox`]. Inherited
+ /// by dispatched subagents via the cloned parent args, so a child shell is
+ /// confined exactly as its parent's was.
+ pub sandbox: Option<bool>,
}
#[async_trait]
@@ -213,6 +220,9 @@ struct CompositeToolInvoker {
/// Whether the sandboxed shell may read `$HOME`. Resolved once per run
/// from `[tools].allow_home_read`, falling back to `true` on the CLI.
allow_home_read: bool,
+ /// Whether `bash` is confined at all. Resolved once per run by
+ /// [`resolve_sandbox`]; always true on the desktop.
+ sandbox: bool,
/// Session-scoped scratch directory the shell and the filesystem tools share
/// (see `workspace::scratch_dir`), so `bash` scratch files persist across
/// calls for the whole run. Created at run start and wiped at run end.
@@ -266,23 +276,71 @@ fn resolve_allow_home_read(configured: Option<bool>) -> bool {
configured.unwrap_or(DEFAULT_ALLOW_HOME_READ)
}
+/// Default for whether `bash` runs under OS confinement.
+///
+/// The desktop is not configurable here: its shell is either sandboxed or
+/// withheld, because the workspace it runs in is ephemeral and there is no one
+/// to prompt about a command that could reach the whole machine.
+///
+/// The CLI defaults off. It runs against the user's own project, from their own
+/// terminal, on their behalf -- the same trust a `make`, a `git push`, or any
+/// other tool they run there already has -- and the shell is what the agent
+/// does most of its work with, so confining it breaks the tools the project
+/// builds with far more often than it stops anything. Confinement is opt-in per
+/// invocation (`--sandbox`), per user (`sandbox` in `~/.jan/config.toml`) or
+/// per project (`[tools].sandbox`). The permission gate is unchanged either
+/// way: an unconfined command is still one the user approved.
+#[cfg(feature = "cli")]
+const DEFAULT_SANDBOX: bool = false;
+#[cfg(not(feature = "cli"))]
+const DEFAULT_SANDBOX: bool = true;
+
+/// Resolve whether the shell is confined, most specific source first: the
+/// per-invocation `--sandbox` flag, then the project's `[tools].sandbox`, then
+/// the user's global `sandbox`, then this surface's default.
+#[cfg(feature = "cli")]
+fn resolve_sandbox(flag: Option<bool>, configured: Option<bool>) -> bool {
+ flag.or(configured)
+ .or_else(crate::core::agent::global_config::sandbox_setting)
+ .unwrap_or(DEFAULT_SANDBOX)
+}
+
+/// The desktop has no opt-out: its shell is sandboxed or withheld, so neither
+/// a project file nor the user's global config is consulted (reading them here
+/// would also be reaching into the CLI's config from the app).
+#[cfg(not(feature = "cli"))]
+fn resolve_sandbox(_flag: Option<bool>, _configured: Option<bool>) -> bool {
+ DEFAULT_SANDBOX
+}
+
+/// Whether `bash` would be confined in `project_root` with no `--sandbox` flag
+/// passed: the answer `jan cli agent status` reports and the TUI notices on.
+pub fn effective_sandbox(project_root: &std::path::Path) -> bool {
+ resolve_sandbox(None, crate::core::agent::project::run_settings(project_root).sandbox)
+}
+
/// agent.toml resolved for one run: the skill whitelist, plus the network
/// decision with this surface's default already applied.
struct ResolvedSettings {
enabled_skills: Vec<String>,
allow_network: bool,
allow_home_read: bool,
+ sandbox: bool,
}
/// Kept out of the invoker's struct literal so it is reachable from a test.
/// Inline, it was silently passing `None` instead of the parsed value, which
/// made `[tools].allow_network` a no-op that nothing detected.
-fn resolve_run_settings(project_root: &std::path::Path) -> ResolvedSettings {
+fn resolve_run_settings(
+ project_root: &std::path::Path,
+ sandbox_flag: Option<bool>,
+) -> ResolvedSettings {
let settings = crate::core::agent::project::run_settings(project_root);
ResolvedSettings {
enabled_skills: settings.enabled_skills,
allow_network: resolve_allow_network(settings.allow_network),
allow_home_read: resolve_allow_home_read(settings.allow_home_read),
+ sandbox: resolve_sandbox(sandbox_flag, settings.sandbox),
}
}
@@ -295,6 +353,7 @@ impl CompositeToolInvoker {
)
.with_network(self.allow_network)
.with_home_readonly(self.allow_home_read)
+ .with_sandbox(self.sandbox)
.with_scratch_root(&self.scratch_root)
}
@@ -761,11 +820,13 @@ impl ToolInvoker for CompositeToolInvoker {
let enabled = self.enabled_skills.clone();
let allow_network = self.allow_network;
let allow_home_read = self.allow_home_read;
+ let sandbox = self.sandbox;
let scratch = self.scratch_root.clone();
read_futures.push(async move {
let ctx = ToolContext::new(&root, &store, &enabled)
.with_network(allow_network)
.with_home_readonly(allow_home_read)
+ .with_sandbox(sandbox)
.with_scratch_root(&scratch);
let (text, diff) = execute_builtin_with_diff(tool, &args, &ctx).await;
ToolOutcome {
@@ -913,6 +974,7 @@ pub(crate) async fn run_server_side_openai_orchestration(
auto_approve: false,
run_mode: crate::core::agent::plan::RunMode::Normal,
session_id: None,
+ sandbox: None,
};
let body = match json_body.get("max_turns") {
Some(_) => std::borrow::Cow::Borrowed(json_body),
@@ -1021,15 +1083,19 @@ fn build_run_system_prompt(
project_root: Option<&std::path::Path>,
session_id: Option<&str>,
subagents_enabled: bool,
+ sandbox: bool,
) -> Option<String> {
let base = override_prompt.or(assistant_instructions);
match project_root {
Some(root) => {
- let scratch = scratch_root_for(session_id, root);
+ // No sandbox, no scratch: unconfined, the shell already has the
+ // real `/tmp`, and advertising a scratch nothing binds would send
+ // the model to a directory only the filesystem tools can see.
+ let scratch = sandbox.then(|| scratch_root_for(session_id, root));
crate::core::agent::context::build_system_prompt(
base,
root,
- Some(&scratch),
+ scratch.as_deref(),
subagents_enabled,
)
}
@@ -1039,16 +1105,27 @@ fn build_run_system_prompt(
/// Where this run's scratch lives. Session-keyed so it persists across turns in
/// the interactive TUI (and across calls in a one-shot run), then is wiped at the
-/// session boundary; a run with no session (the server proxy) gets a per-project
-/// directory instead. Pure path math -- [`ensure_scratch_dir`] is what creates
-/// it -- so the system prompt can name the scratch before the tools are built.
+/// session boundary. Pure path math -- [`ensure_scratch_dir`] is what creates it
+/// -- so the system prompt can name the scratch before the tools are built.
+///
+/// A session-less run gets a throwaway in the host temp dir, never a directory
+/// inside the project: a project-level scratch is shared by every session
+/// working that checkout, accumulates spill files with no owner to remove them,
+/// and fails outright on a read-only checkout. Nothing wipes a throwaway at run
+/// end (there is no session boundary to hang it on), so it is left to the
+/// startup sweep -- which is why it must live where that sweep looks.
fn scratch_root_for(
session_id: Option<&str>,
- project_root: &std::path::Path,
+ _project_root: &std::path::Path,
) -> std::path::PathBuf {
+ static ANONYMOUS_RUN: AtomicUsize = AtomicUsize::new(0);
match session_id {
Some(session) => tauri_plugin_agent_tools::workspace::scratch_dir(session),
- None => project_root.join("agent-scratch"),
+ None => tauri_plugin_agent_tools::workspace::scratch_dir(&format!(
+ "anon-{}-{}",
+ std::process::id(),
+ ANONYMOUS_RUN.fetch_add(1, Ordering::Relaxed)
+ )),
}
}
@@ -1115,6 +1192,7 @@ async fn orchestrate_inner(
auto_approve,
run_mode,
session_id,
+ sandbox,
} = args;
// Per-turn override: the TUI toggles plan mode live via the request body
@@ -1153,12 +1231,19 @@ async fn orchestrate_inner(
(None, None)
};
+ // Resolved here rather than where the tools are built: the system prompt
+ // names the scratch, and whether there *is* one is the sandbox decision, so
+ // both have to read the same answer or the model is told about a directory
+ // nothing binds.
+ let settings = project_root.as_deref().map(|root| resolve_run_settings(root, *sandbox));
+
let system_prompt = build_run_system_prompt(
assistant_instructions.as_deref(),
system_prompt_override.as_deref(),
project_root.as_deref(),
session_id.as_deref(),
*subagents_enabled,
+ settings.as_ref().is_some_and(|s| s.sandbox),
);
// Child (subagent) runs are excluded via `system_prompt_override`, the
// same gate the memory-recall block above uses to distinguish a
@@ -1369,22 +1454,28 @@ async fn orchestrate_inner(
max_session_tokens,
bg: bg.clone(),
});
- let settings = resolve_run_settings(root);
+ // Resolved once above, where the system prompt also needed it.
+ let settings = settings.expect("resolved whenever there is a project root");
// The same path `build_run_system_prompt` advertised (both go through
// `scratch_root_for`), created here before the first tool call reaches
// for it. Created for a session-less run too: the policy binds this path
// either way, and bubblewrap refuses to bind a directory that is not
- // there -- which would take `bash` down with it.
+ // there -- which would take `bash` down with it. Hardened against a
+ // pre-planted symlink so the sandbox never binds an attacker-selected
+ // directory as its sanctioned scratch. Skipped entirely when the shell
+ // is unconfined: nothing binds it, so creating it would only leave an
+ // empty directory behind.
let scratch_root = scratch_root_for(session_id.as_deref(), root);
- tokio::fs::create_dir_all(&scratch_root)
- .await
- .map_err(|e| format!("ERROR: {e}"))?;
+ if settings.sandbox {
+ tauri_plugin_agent_tools::workspace::ensure_scratch_dir_path(&scratch_root).await?;
+ }
let tools = CompositeToolInvoker {
mcp: mcp_tools,
store_root: tauri_plugin_agent_tools::workspace::project_store(root),
enabled_skills: settings.enabled_skills,
allow_network: settings.allow_network,
allow_home_read: settings.allow_home_read,
+ sandbox: settings.sandbox,
scratch_root: scratch_root.clone(),
project_root: root.clone(),
permissions: permissions.clone(),
@@ -2034,22 +2125,28 @@ mod tests {
/// The prompt names the scratch and the tools bind it, so both must derive
/// it the same way or the model is told about a directory nothing set up.
#[test]
- fn scratch_root_is_session_keyed_and_falls_back_to_the_project() {
+ fn scratch_root_is_session_keyed_and_never_lands_in_the_project() {
let root = unique_project_root();
assert_eq!(
scratch_root_for(Some("sess-1"), &root),
tauri_plugin_agent_tools::workspace::scratch_dir("sess-1")
);
- assert_eq!(
- scratch_root_for(None, &root),
- root.join("agent-scratch"),
- "a session-less run still needs a scratch to bind"
- );
// Two sessions never share one scratch.
assert_ne!(
scratch_root_for(Some("sess-1"), &root),
scratch_root_for(Some("sess-2"), &root)
);
+ // A session-less run still needs a scratch to bind, but it belongs in
+ // the host temp dir: a directory inside the project would be shared by
+ // every session on that checkout and never collected.
+ let anon = scratch_root_for(None, &root);
+ assert!(!anon.starts_with(&root), "scratch leaked into the project");
+ assert!(anon.starts_with(std::env::temp_dir()));
+ assert_ne!(
+ anon,
+ scratch_root_for(None, &root),
+ "two session-less runs must not share a scratch"
+ );
}
#[test]
@@ -2061,6 +2158,7 @@ mod tests {
Some(&root),
Some("test-session"),
false,
+ true,
)
.expect("prompt");
@@ -2851,6 +2949,7 @@ mod tests {
registry: PermissionRegistry,
) -> CompositeToolInvoker {
CompositeToolInvoker {
+ sandbox: true,
mcp: McpToolInvoker {
tool_to_server: HashMap::new(),
mcp_servers: Arc::new(Mutex::new(HashMap::new())),
@@ -2895,19 +2994,19 @@ mod tests {
};
write("[tools]\nallow_network = false\n[skills]\nenabled = [\"deploy\"]\n");
- let denied = resolve_run_settings(&root);
+ let denied = resolve_run_settings(&root, None);
assert!(!denied.allow_network, "explicit false must be honoured");
assert_eq!(denied.enabled_skills, vec!["deploy".to_string()]);
write("[tools]\nallow_network = true\n");
assert!(
- resolve_run_settings(&root).allow_network,
+ resolve_run_settings(&root, None).allow_network,
"explicit true must be honoured"
);
write("[tools]\ndefault = \"read-only\"\n");
assert_eq!(
- resolve_run_settings(&root).allow_network,
+ resolve_run_settings(&root, None).allow_network,
DEFAULT_ALLOW_NETWORK,
"unset must fall back to the surface default"
);
@@ -2934,6 +3033,74 @@ mod tests {
assert_eq!(resolve_allow_home_read(None), DEFAULT_ALLOW_HOME_READ);
}
+ /// Sandbox precedence, most specific source first: the `--sandbox` flag
+ /// beats the project's `[tools].sandbox`, which beats the user's global
+ /// `sandbox`, which beats the surface default. Each level must be able to
+ /// push in *both* directions, or a user who turned confinement on
+ /// permanently could never run a single command without it.
+ #[cfg(feature = "cli")]
+ #[test]
+ fn sandbox_precedence_runs_flag_then_project_then_global() {
+ crate::core::agent::global_config::with_temp_home(|_| {
+ // Nothing set anywhere: the CLI surface default.
+ assert_eq!(resolve_sandbox(None, None), DEFAULT_SANDBOX);
+ // The flag wins over everything below it, both ways.
+ assert!(resolve_sandbox(Some(true), Some(false)));
+ assert!(!resolve_sandbox(Some(false), Some(true)));
+ // With no flag, the project decides.
+ assert!(resolve_sandbox(None, Some(true)));
+ assert!(!resolve_sandbox(None, Some(false)));
+
+ let path =
+ crate::core::agent::global_config::ensure_global_config().expect("config path");
+ // The scaffolded template leaves `sandbox` commented out, so the
+ // default still stands until it is actually set.
+ assert_eq!(resolve_sandbox(None, None), DEFAULT_SANDBOX);
+ std::fs::write(&path, "sandbox = true\n").unwrap();
+ assert!(resolve_sandbox(None, None), "global sandbox ignored");
+ assert!(!resolve_sandbox(None, Some(false)), "project must win");
+ assert!(!resolve_sandbox(Some(false), None), "--no-sandbox must win");
+
+ std::fs::write(&path, "not valid toml [[[").unwrap();
+ assert_eq!(
+ resolve_sandbox(None, None),
+ DEFAULT_SANDBOX,
+ "an unparseable config falls back to the default, not an error"
+ );
+ });
+ }
+
+ /// The desktop has no opt-out: its shell is confined or withheld, and
+ /// neither a project file nor the CLI's global config can change that.
+ #[cfg(not(feature = "cli"))]
+ #[test]
+ fn desktop_sandbox_cannot_be_turned_off() {
+ // Every input, including the two that turn it off on the CLI. Asserted
+ // through `resolve_sandbox` rather than on `DEFAULT_SANDBOX` directly:
+ // the constant being true is not the property worth pinning, the
+ // resolver ignoring its arguments is.
+ assert!(resolve_sandbox(None, None));
+ assert!(resolve_sandbox(None, Some(false)));
+ assert!(resolve_sandbox(Some(false), None));
+ assert!(resolve_sandbox(Some(false), Some(false)));
+ }
+
+ /// An unconfined run has no scratch, so the prompt must not name one: the
+ /// shell sees the real `/tmp` and would never find the directory the
+ /// scratch line points at.
+ #[test]
+ fn unsandboxed_prompt_does_not_advertise_a_scratch() {
+ let root = unique_project_root();
+ let confined =
+ build_run_system_prompt(None, Some("do things"), Some(&root), Some("s1"), false, true)
+ .expect("prompt");
+ assert!(confined.contains("Scratch:"), "{confined}");
+ let bare =
+ build_run_system_prompt(None, Some("do things"), Some(&root), Some("s1"), false, false)
+ .expect("prompt");
+ assert!(!bare.contains("Scratch:"), "{bare}");
+ }
+
/// The CLI agent's shell keeps its network namespace. Before the sandbox
/// existed this shell ran fully unconfined, so flipping this to `false`
/// silently breaks `curl`, `git fetch` and package installs while every
diff --git a/src-tauri/src/core/agent/project.rs b/src-tauri/src/core/agent/project.rs
index 2f6eef005..aafcc8b56 100644
--- a/src-tauri/src/core/agent/project.rs
+++ b/src-tauri/src/core/agent/project.rs
@@ -122,6 +122,13 @@ pub(crate) struct ToolsSection {
/// `$HOME` entirely. Writes are confined to the workspace either way.
#[serde(default)]
pub allow_home_read: Option<bool>,
+ /// Whether the shell runs under OS confinement. `None` (unset) leaves the
+ /// choice to the surface: the desktop always confines, the CLI defaults to
+ /// off and opts in with `--sandbox` or the global `sandbox` setting.
+ /// Setting it here is how a repo requires confinement for everyone who
+ /// checks it out.
+ #[serde(default)]
+ pub sandbox: Option<bool>,
}
const AGENT_TOML_TEMPLATE: &str = r#"[agent]
@@ -166,6 +173,11 @@ allow_write = []
# credential helpers and ~/.ssh/config). Unset follows the surface: the CLI
# allows it (true), the desktop masks $HOME. Writes stay in the workspace.
# allow_home_read = true
+# Whether `bash` runs under OS confinement at all. Unset follows the surface:
+# the CLI runs unconfined unless you pass --sandbox or set sandbox = true in
+# ~/.jan/config.toml; the desktop always confines. Set it here to require
+# confinement for anyone working in this project.
+# sandbox = true
[skills]
enabled = []
@@ -201,6 +213,9 @@ pub(crate) struct RunSettings {
/// `[tools].allow_home_read`; `None` when unset, so the caller applies the
/// default appropriate to its surface.
pub allow_home_read: Option<bool>,
+ /// `[tools].sandbox`; `None` when unset, so the caller applies the default
+ /// appropriate to its surface.
+ pub sandbox: Option<bool>,
}
/// A missing or malformed config yields defaults rather than an error: a project
@@ -213,6 +228,7 @@ pub(crate) fn run_settings(project_root: &Path) -> RunSettings {
enabled_skills: cfg.skills.enabled,
allow_network: cfg.tools.allow_network,
allow_home_read: cfg.tools.allow_home_read,
+ sandbox: cfg.tools.sandbox,
}
}
diff --git a/src-tauri/src/core/agent/subagent.rs b/src-tauri/src/core/agent/subagent.rs
index 437ea4fa9..5cab3510c 100644
--- a/src-tauri/src/core/agent/subagent.rs
+++ b/src-tauri/src/core/agent/subagent.rs
@@ -1513,6 +1513,7 @@ mod tests {
auto_approve: false,
run_mode: crate::core::agent::plan::RunMode::Normal,
session_id: None,
+ sandbox: None,
}
}
diff --git a/src-tauri/src/core/cli/mod.rs b/src-tauri/src/core/cli/mod.rs
index 06f704eff..ed9be504d 100644
--- a/src-tauri/src/core/cli/mod.rs
+++ b/src-tauri/src/core/cli/mod.rs
@@ -522,6 +522,16 @@ pub fn cli_agent_status(
"allow_write": cfg.tools.allow_write,
"allow_network": cfg.tools.allow_network,
"allow_home_read": cfg.tools.allow_home_read,
+ "sandbox": cfg.tools.sandbox,
+ },
+ // What `bash` will actually do, with the config files already resolved
+ // (the `--sandbox` flag is per-invocation and so cannot be reported
+ // here). `backend` names the confinement that would be used and is
+ // `none` where none can be established -- with `enabled` true that
+ // combination is what withholds `bash` entirely.
+ "sandbox": {
+ "enabled": crate::core::agent::r#loop::effective_sandbox(&project_root),
+ "backend": tauri_plugin_agent_tools::tools::jail::backend().as_str(),
},
"providers": providers,
}))
@@ -591,21 +601,11 @@ pub async fn cli_agent_run(
task: &str,
model: Option<String>,
overrides: ProviderOverrides,
- auto_approve: bool,
+ flags: SessionFlags,
resume: Option<ResumeTarget>,
format: OutputFormat,
) -> Result<(), String> {
- run_agent_loop(
- project,
- task,
- model,
- false,
- overrides,
- auto_approve,
- resume,
- format,
- )
- .await
+ run_agent_loop(project, task, model, false, overrides, flags, resume, format).await
}
/// Single-turn run for debugging: the one place a turn cap is still applied,
@@ -615,7 +615,7 @@ pub async fn cli_agent_step(
task: &str,
model: Option<String>,
overrides: ProviderOverrides,
- auto_approve: bool,
+ flags: SessionFlags,
) -> Result<(), String> {
run_agent_loop(
project,
@@ -623,7 +623,7 @@ pub async fn cli_agent_step(
model,
true,
overrides,
- auto_approve,
+ flags,
None,
OutputFormat::Text,
)
@@ -641,6 +641,7 @@ fn build_cli_orchestration_args(
auto_approve: bool,
plan: bool,
max_parallel_subagents: u32,
+ sandbox: Option<bool>,
) -> OrchestrationArgs {
OrchestrationArgs {
client: reqwest::Client::new(),
@@ -667,6 +668,9 @@ fn build_cli_orchestration_args(
// reuses `args` across turns and wipes it when the interactive session
// ends.
session_id: Some(uuid::Uuid::new_v4().to_string()),
+ // `--sandbox` only when passed; unset falls through to the project's
+ // `[tools].sandbox` and then the user's global `sandbox`.
+ sandbox,
}
}
@@ -748,15 +752,33 @@ impl AgentSession {
}
}
+/// The per-invocation switches a session starts with.
+///
+/// A struct rather than a run of positional `bool`s: `(.., false, false, true)`
+/// at a call site names none of them, and the compiler cannot catch two of them
+/// being swapped.
+#[derive(Debug, Clone, Copy, Default)]
+pub struct SessionFlags {
+ /// Skip the permission prompt for writes, shell, and MCP calls.
+ pub auto_approve: bool,
+ /// Start in read-only plan mode.
+ pub plan: bool,
+ /// Fail when no model resolves instead of launching with an empty one. The
+ /// TUI leaves this off so `/login` can fill the model in later.
+ pub require_model: bool,
+ /// `--sandbox`: run `bash` under OS confinement. `None` (not passed) defers
+ /// to `[tools].sandbox`, then the global `sandbox`, then the CLI default of
+ /// off.
+ pub sandbox: Option<bool>,
+}
+
/// Resolve project config + credentials into a ready-to-run engine handle.
/// Shared by `run_agent_loop` (plain CLI) and `cli_agent_ui` (TUI).
fn prepare_agent_session(
project: &str,
model_override: Option<String>,
overrides: ProviderOverrides,
- auto_approve: bool,
- plan: bool,
- require_model: bool,
+ flags: SessionFlags,
) -> Result<AgentSession, String> {
let project_root = resolve_project_root(project);
ensure_project(&project_root)?;
@@ -782,7 +804,7 @@ fn prepare_agent_session(
// (--model/--api-key) or some provider can actually be reached; otherwise
// treat it as unset so the TUI's sign-in notice fires instead of failing on
// the first message.
- let model = if !require_model
+ let model = if !flags.require_model
&& !explicit
&& !crate::core::cli::providers::has_usable_provider(Some(&project_root))
{
@@ -790,7 +812,7 @@ fn prepare_agent_session(
} else {
model.unwrap_or_default()
};
- if model.is_empty() && require_model {
+ if model.is_empty() && flags.require_model {
return Err(
"no model specified: run `jan login` to sign in to Tokamak, or pass --model, set [agent].model in agent.toml, set default_model in ~/.jan/config.toml, or select a model in the desktop app"
.to_string(),
@@ -851,9 +873,10 @@ fn prepare_agent_session(
mcp_servers.clone(),
mcp_settings,
permission_requests.clone(),
- auto_approve,
- plan,
+ flags.auto_approve,
+ flags.plan,
max_parallel_subagents,
+ flags.sandbox,
);
Ok(AgentSession {
@@ -907,18 +930,21 @@ fn prepare_agent_run(
model_override: Option<String>,
single_turn: bool,
overrides: ProviderOverrides,
- auto_approve: bool,
+ flags: SessionFlags,
resume: Option<ResumeTarget>,
) -> Result<PreparedRun, String> {
// Non-interactive runs (`agent run`/`step`) have no plan-review handoff, so
- // plan mode stays a TUI-only startup option.
+ // plan mode stays a TUI-only startup option, and a run with no model has no
+ // terminal to recover in, so it must fail rather than launch empty.
let session = prepare_agent_session(
project,
model_override,
overrides,
- auto_approve,
- false,
- true,
+ SessionFlags {
+ plan: false,
+ require_model: true,
+ ..flags
+ },
)?;
let project_root = resolve_project_root(project);
let (clean_task, injected) = path_refs::resolve_references(task, &project_root);
@@ -980,7 +1006,7 @@ async fn run_agent_loop(
model_override: Option<String>,
single_turn: bool,
overrides: ProviderOverrides,
- auto_approve: bool,
+ flags: SessionFlags,
resume: Option<ResumeTarget>,
format: OutputFormat,
) -> Result<(), String> {
@@ -991,7 +1017,7 @@ async fn run_agent_loop(
model_override,
single_turn,
overrides,
- auto_approve,
+ flags,
resume,
);
// A setup failure never reaches the event stream, so a JSON consumer would
@@ -1153,8 +1179,7 @@ pub async fn cli_agent_ui(
model: Option<String>,
images: Vec<String>,
overrides: ProviderOverrides,
- auto_approve: bool,
- plan: bool,
+ flags: SessionFlags,
resume: Option<ResumeTarget>,
) -> Result<(), String> {
let project_root = resolve_project_root(project);
@@ -1167,7 +1192,15 @@ pub async fn cli_agent_ui(
// Fresh install with a terminal attached: launch with no model rather than
// forcing sign-in here. The TUI shows a one-line notice and `/login` (or
// `jan login`) picks a model up once the user is ready.
- let session = prepare_agent_session(project, model, overrides, auto_approve, plan, false)?;
+ let session = prepare_agent_session(
+ project,
+ model,
+ overrides,
+ SessionFlags {
+ require_model: false,
+ ..flags
+ },
+ )?;
// TUI threads persist under the project's .jan/agent dir, separate from the
// desktop store, so continuing here never mutates desktop threads.
let agent_dir = agent_dir_for(&project_root);
@@ -1640,9 +1673,7 @@ mod tests {
dir.path().to_str().unwrap(),
None,
ProviderOverrides::default(),
- false,
- false,
- false,
+ SessionFlags::default(),
)
.expect("TUI session prep must not fail with nothing configured");
assert_eq!(session.model, "");
@@ -1675,9 +1706,7 @@ mod tests {
dir.path().to_str().unwrap(),
None,
ProviderOverrides::default(),
- false,
- false,
- false,
+ SessionFlags::default(),
)
.expect("session prep");
assert_eq!(session.model, "tokamak-1-preview");
diff --git a/src-tauri/src/core/cli/tui.rs b/src-tauri/src/core/cli/tui.rs
index 1eef73e98..86c42c827 100644
--- a/src-tauri/src/core/cli/tui.rs
+++ b/src-tauri/src/core/cli/tui.rs
@@ -4558,11 +4558,19 @@ pub async fn run(
let seeded = initial_task
.as_deref()
.is_some_and(|t| !t.trim().is_empty());
+ // The banner has to name the confinement, not assume it: "auto-approved
+ // inside the OS sandbox" is a promise, and with the sandbox off it is the
+ // wrong one. Unconfined, an approved command has exactly the access the
+ // user does, and that is the thing worth saying up front.
+ let sandboxed = args
+ .sandbox
+ .unwrap_or_else(|| crate::core::agent::r#loop::effective_sandbox(&app.project_root));
app.push_banner(
- if args.auto_approve {
- "auto-approved inside the OS sandbox (start with --safe to be asked first)"
- } else {
- "--safe: writes, shell commands and MCP tool calls need approval"
+ match (args.auto_approve, sandboxed) {
+ (true, true) => "auto-approved inside the OS sandbox (start with --safe to be asked first)",
+ (true, false) => "auto-approved and unsandboxed: commands run with your own access (--safe to be asked first, --sandbox to confine)",
+ (false, true) => "--safe: writes, shell commands and MCP tool calls need approval",
+ (false, false) => "--safe: approval needed, but unsandboxed - what you approve runs with your own access (--sandbox to confine)",
},
!seeded,
);