Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,9 @@ jobs:
- run: cargo clippy --all-targets
- run: cargo test --lib
- run: cargo test --bins
# incode's commands under `sandbox_engine = "sbx"`, for real (Linux;
# it says it skipped elsewhere).
- run: cargo test --test sbx_engine
# The standalone sandbox (`sbx`). Its escape tests run on Linux and
# macOS, and skip, saying so, where the OS cannot enforce what they check.
- run: cargo clippy -p incord-sandbox --all-targets -- -D warnings
Expand Down
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

11 changes: 11 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,12 @@ rust-version = "1.88"
name = "incode"
path = "src/main.rs"

# Runs the sbx engine for real: its binary is sbx's helper, so it has its own
# `main` (see the file).
[[test]]
name = "sbx_engine"
harness = false

[dependencies]
serde = { version = "1", features = ["derive"] }
serde_json = "1"
Expand Down Expand Up @@ -77,6 +83,11 @@ base64 = "0.22"
# NOTE: it turns on serde_json's `preserve_order` for the whole crate (feature
# unification), so a `serde_json::Map` keeps insertion order instead of sorting.
agent-client-protocol-schema = { version = "=1.9.1", default-features = false }
# The standalone sandbox in this workspace (`crates/sandbox`), as the `sbx`
# engine for shell commands: `sandbox_engine: "sbx"`. A path dependency, so
# no new package; it adds the seccomp filter, the host-allowlist proxy and the
# `.git` protection the built-in engine lacks.
incord-sandbox = { path = "crates/sandbox" }

# CLI-specific
rustyline = { version = "15", features = ["derive"] }
Expand Down
25 changes: 25 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -923,6 +923,30 @@ confined only when named; the operator's own `/bg` jobs at the REPL are never
sandboxed. Where a mode cannot be applied, the command runs unconfined and the
trace says which.

**The engine**: `admin.json` `sandbox_engine` or `INCODE_SANDBOX_ENGINE`,
`builtin` (the default: everything above) or `sbx`, which confines the same
commands with [`sbx`](#sbx-the-same-sandbox-for-any-agent) instead, with the
same mode and network switch, and adds:

- `sandbox_allow_hosts` (or `INCODE_SANDBOX_ALLOW_HOSTS`, comma-separated): the
only hosts a command may reach, through a proxy sbx runs for it;
- on Linux, a seccomp filter against terminal injection, `io_uring` and vsock;
- `.git/hooks` and `.git/config` in each writable root put back as they were
when a command ends, so a planted hook never runs;
- the variables that redirect git, attach to the agent session or inject a
library stripped; a private temp directory per command.

```json
{ "sandbox_engine": "sbx", "sandbox_allow_hosts": ["crates.io", "static.crates.io", "github.com"] }
```

Linux and macOS run it inside incode. Windows runs `sbx.exe` (installed beside
`incode.exe`), natively or inside WSL2 as `sandbox_backend` (or
`INCODE_SANDBOX_BACKEND`) says: `native`, `wsl` or `auto`; under `wsl` the
command runs in WSL's `sh`. What a machine cannot enforce is named in the
trace and `/doctor`; a run sbx cannot start at all is refused, not run
unconfined.

### `sbx`: the same sandbox for any agent

`crates/sandbox` builds `sbx`, a standalone sandbox that doesn't depend on
Expand Down Expand Up @@ -1138,6 +1162,7 @@ and `--admin` prints which layer decided each value.
| `browser_bin` · `pdf_renderer` | For development, a headless browser executable that wins over the installed one · which program `RenderPdf` uses |
| `sandbox` | `off` · `workspace-write` · `read-only`; unset follows the permission mode |
| `sandbox_network` | `allow` (default) · `deny` — see [the OS sandbox](#the-os-sandbox) |
| `sandbox_engine` · `sandbox_allow_hosts` · `sandbox_backend` | `builtin` (default) · `sbx`; under sbx, the hosts a command may reach and, on Windows, `native` · `wsl` · `auto` — see [the OS sandbox](#the-os-sandbox) |
| `hooks` (also `desktop_hooks`) | Your `pre_tool_use` / `post_tool_use` commands, run for every tool. The event is JSON on stdin; exit 2 on a pre-tool command denies; bounded at 10 s |
| `desktop_limits` | The desktop's limits, each optional: `max_actions_per_minute` (120), `heartbeat_deadline_secs` (30), `tree_depth` (12), `tree_max_elements` (400), `journal_max_bytes` (262144), `xvfb_start_timeout_secs` (10), `clipboard_timeout_secs` (5), `accessibility_call_timeout_ms` (1000), `paste_restore_delay_ms` (500, how long the pasted text stays on the clipboard before the old one is put back), `settle_ms` (300, the pause before a `screenshot_after`), `max_scroll_steps` (50, wheel steps in one `scroll`), `tree_max_visited` (4000, elements one tree walk may visit), and `blocked_apps` (application names, matched case-insensitively as a part of the name, added to the built-in password managers: 1Password, Bitwarden, LastPass, Dashlane, KeePass, NordPass, Proton Pass, Enpass, RoboForm, Keeper). The first two are safety limits and may only be lowered; zero and unknown keys are refused, and the desktop does not start on a malformed admin.json |
| `desktop_display` | Linux computer use: `":N"` drives a running X display; `"xvfb"` or `"xvfb:1280x800"` starts a private Xvfb for the desktop server's lifetime (default 1920x1080). Unset refuses rather than using `$DISPLAY`. `paste_text` needs `xclip` or `xsel`; `ui_tree` needs a D-Bus session with at-spi2-core |
Expand Down
20 changes: 19 additions & 1 deletion crates/sandbox/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -402,6 +402,9 @@ pub struct Sandbox {
policy: Policy,
helper: Option<PathBuf>,
strict: bool,
/// The environment the policy's `[env]` rules start from. Default: this
/// process's own.
base_env: Option<Vec<(OsString, OsString)>>,
}

/// Everything a running command needs kept alive: the proxy and the private
Expand Down Expand Up @@ -487,9 +490,20 @@ impl Sandbox {
policy,
helper: None,
strict: true,
base_env: None,
}
}

/// Start the command's environment from `vars` instead of this process's
/// own, for a caller that filters it first. The policy's `[env]` rules
/// still apply on top, and the run's own variables (the temp directory,
/// the proxy) are still added.
#[must_use]
pub fn inherit_from(mut self, vars: Vec<(OsString, OsString)>) -> Self {
self.base_env = Some(vars);
self
}

/// The binary re-executed as the helper. Default: the current executable,
/// which must then call [`enter_if_requested`].
#[must_use]
Expand Down Expand Up @@ -604,7 +618,11 @@ impl Sandbox {
if let Some(p) = &proxy {
extra.extend(p.client_env());
}
let mut environment = env::compute(&self.policy.env, std::env::vars_os(), &extra);
let inherited = match &self.base_env {
Some(vars) => vars.clone(),
None => std::env::vars_os().collect(),
};
let mut environment = env::compute(&self.policy.env, inherited, &extra);
if block_interop {
environment.retain(|(k, _)| k != "WSL_INTEROP");
}
Expand Down
74 changes: 74 additions & 0 deletions src/admin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -190,6 +190,20 @@ pub struct AdminConfig {
/// reports. `INCODE_SANDBOX_NETWORK` wins over it.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub sandbox_network: Option<String>,
/// What confines the commands: `builtin` (the default) or `sbx`, the
/// standalone sandbox — see [`crate::sandbox::sbx`].
/// `INCODE_SANDBOX_ENGINE` wins over it.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub sandbox_engine: Option<String>,
/// Under the sbx engine: the only hosts a command may reach, when the
/// network is not denied. Empty leaves it open.
/// `INCODE_SANDBOX_ALLOW_HOSTS` (comma-separated) wins over it.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub sandbox_allow_hosts: Vec<String>,
/// Under the sbx engine on Windows: `native`, `wsl` or `auto` (the
/// default). `INCODE_SANDBOX_BACKEND` wins over it.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub sandbox_backend: Option<String>,
/// The shell the `Bash` tool runs commands in on Windows, as a path or a
/// program on `PATH` — see `tools::shell_choice`. `INCODE_SHELL` wins over
/// it. Unset, Git for Windows' bash is used, then PowerShell; never
Expand Down Expand Up @@ -956,6 +970,25 @@ impl AdminConfig {
mode: mode.value,
network: self.resolve_sandbox_network().value,
named: mode.source != Source::BuiltIn,
engine: self.resolve_sandbox_engine().value,
}
}

/// What confines the commands, and where that was decided: the
/// environment, then the settings, then `builtin`.
#[must_use]
pub fn resolve_sandbox_engine(&self) -> Resolved<crate::sandbox::SandboxEngine> {
let named = |raw: &str| crate::sandbox::SandboxEngine::parse(raw.trim());
if let Some(engine) = std::env::var(crate::sandbox::SANDBOX_ENGINE_ENV)
.ok()
.as_deref()
.and_then(named)
{
return Resolved::new(engine, Source::Environment);
}
match self.sandbox_engine.as_deref().and_then(named) {
Some(engine) => Resolved::new(engine, Source::AdminFile),
None => Resolved::new(crate::sandbox::SandboxEngine::Builtin, Source::BuiltIn),
}
}

Expand Down Expand Up @@ -1117,6 +1150,7 @@ mod tests {
std::env::remove_var(DATA_DIR_ENV);
std::env::remove_var(crate::sandbox::SANDBOX_ENV);
std::env::remove_var(crate::sandbox::SANDBOX_NETWORK_ENV);
std::env::remove_var(crate::sandbox::SANDBOX_ENGINE_ENV);
std::env::remove_var(AGENT_ENV);
std::env::remove_var(crate::config::MODEL_ENV);
std::env::remove_var(crate::budget::BUDGET_ENV);
Expand Down Expand Up @@ -1473,6 +1507,9 @@ mod tests {
pdf_renderer: Some(PdfRenderer::Browser),
sandbox: Some("read-only".to_string()),
sandbox_network: Some("deny".to_string()),
sandbox_engine: Some("sbx".to_string()),
sandbox_allow_hosts: vec!["crates.io".to_string()],
sandbox_backend: Some("wsl".to_string()),
// The Bash tool's shell, which the owner may pin on Windows.
shell: Some("C:/Program Files/Git/bin/bash.exe".to_string()),
// The ladder has to survive the file too — a tier an operator
Expand Down Expand Up @@ -1574,6 +1611,43 @@ mod tests {
clear_env();
}

/// The engine: `builtin` unless named, the settings name it, the
/// environment wins, and a word nobody uses is the built-in default.
#[test]
fn the_sandbox_engine_resolves_like_the_other_settings() {
use crate::permissions::PermissionMode as P;
use crate::sandbox::{SandboxEngine, SANDBOX_ENGINE_ENV};
let _guard = lock();
clear_env();
let unset = AdminConfig::default();
assert_eq!(
unset.sandbox_policy(P::WorkspaceWrite).engine,
SandboxEngine::Builtin
);

let admin = AdminConfig {
sandbox_engine: Some("sbx".to_string()),
..Default::default()
};
assert_eq!(
admin.sandbox_policy(P::WorkspaceWrite).engine,
SandboxEngine::Sbx
);
assert_eq!(admin.resolve_sandbox_engine().source, Source::AdminFile);

let typo = AdminConfig {
sandbox_engine: Some("bubblewrap".to_string()),
..Default::default()
};
assert_eq!(typo.resolve_sandbox_engine().value, SandboxEngine::Builtin);
assert_eq!(typo.resolve_sandbox_engine().source, Source::BuiltIn);

std::env::set_var(SANDBOX_ENGINE_ENV, "builtin");
assert_eq!(admin.resolve_sandbox_engine().value, SandboxEngine::Builtin);
assert_eq!(admin.resolve_sandbox_engine().source, Source::Environment);
clear_env();
}

/// **"NONE" IS NOT AN ANSWER AN OPERATOR CAN ACT ON.**
///
/// Two workspaces get no check for opposite reasons: one names no
Expand Down
4 changes: 4 additions & 0 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,10 @@ OPTIONS:
";

fn main() -> anyhow::Result<()> {
// The sbx engine's helper (`incode __sbx-enter ...`): confine this
// process and exec the command, before any thread starts. Returns at once
// for every other invocation.
incord_sandbox::enter_if_requested();
// BEFORE ANYTHING ELSE, and before any thread starts: this mode applies the
// OS sandbox to THIS process and then execs the command, and an early
// Landlock ruleset binds only the thread that set it. On success it never
Expand Down
1 change: 1 addition & 0 deletions src/sandbox/linux.rs
Original file line number Diff line number Diff line change
Expand Up @@ -173,6 +173,7 @@ mod tests {
mode: SandboxMode::WorkspaceWrite,
network: SandboxNetwork::Allow,
named: false,
engine: crate::sandbox::SandboxEngine::Builtin,
},
&[PathBuf::from("/ws")],
"echo hi",
Expand Down
Loading
Loading