diff --git a/README.md b/README.md index 3287dcb..2298b3b 100644 --- a/README.md +++ b/README.md @@ -49,6 +49,8 @@ ln -sf "$(pwd)/config-example.toml" "${XDG_CONFIG_HOME:-$HOME/.config}/agent-san Top-level keys set defaults; `[profile.]` sections define named presets selectable with `--profile `. CLI flags always take highest precedence, followed by the active profiles, then top-level defaults. When a profile is active, list-valued fields (`ro`, `rw`, `mask`, `env`, `unsetenv`, `bwrap-args`, `keep-fd`) append to the globals; scalar fields (modes, flags, `entrypoint`, `command`, `chdir`) replace them. +Paths in the config file must be absolute, so a reader never has to guess what a relative path is relative to. Two prefixes expand: `~` to `$HOME`, and `$PWD` (or `${PWD}`) to the directory agent-sandbox was started in, read from the process rather than the `PWD` variable. No other variable expands. + Several profiles combine: `--profile claude,gpu` (or `--profile claude --profile gpu`, or `profile = ["claude", "gpu"]` in the config) merges them left to right under the same rules, so a later profile's scalars win. A CLI `--profile` replaces the config's list rather than extending it. A profile's own `profile = ...` names its parents, which merge before it; a profile reached twice merges once. ```toml diff --git a/src/config.rs b/src/config.rs index 2a472c5..a0f10a6 100644 --- a/src/config.rs +++ b/src/config.rs @@ -185,7 +185,7 @@ fn resolve_chdir( ) -> Result { match cli.or(profile).or(globals) { Some(p) => std::fs::canonicalize(&p).map_err(|_| SandboxError::ChdirMissing(p)), - None => std::env::current_dir().map_err(SandboxError::CurrentDirUnavailable), + None => crate::require_current_dir(), } } @@ -592,7 +592,7 @@ fn expand_and_require_existing(path: &Path) -> Result { } fn expand_and_require_absolute(path: &Path) -> Result { - let expanded = expand_tilde(path)?; + let expanded = expand_path(path)?; require_absolute(&expanded)?; Ok(expanded) } @@ -671,19 +671,36 @@ fn validate_mode(opts: &Options) -> Result<(), SandboxError> { Ok(()) } -fn expand_tilde(path: &Path) -> Result { - let s = path.to_string_lossy(); - if !s.starts_with('~') { - return Ok(path.to_path_buf()); +fn expand_path(path: &Path) -> Result { + if let Ok(rest) = path.strip_prefix("~") { + let home = PathBuf::from(crate::require_home()?); + return Ok(join_without_trailing_slash(home, rest)); } - if s.len() > 1 && !s.starts_with("~/") { + for token in ["$PWD", "${PWD}"] { + if let Ok(rest) = path.strip_prefix(token) { + let cwd = crate::require_current_dir()?; + return Ok(join_without_trailing_slash(cwd, rest)); + } + } + + reject_unknown_prefix(path)?; + Ok(path.to_path_buf()) +} + +fn join_without_trailing_slash(mut base: PathBuf, rest: &Path) -> PathBuf { + base.extend(rest); + base +} + +fn reject_unknown_prefix(path: &Path) -> Result<(), SandboxError> { + let s = path.to_string_lossy(); + if s.starts_with('~') { return Err(SandboxError::ConfigPathNotAbsolute(path.to_path_buf())); } - let home = std::env::var("HOME") - .ok() - .filter(|h| !h.is_empty()) - .ok_or(SandboxError::HomeNotSet)?; - Ok(PathBuf::from(home).join(s.strip_prefix("~/").unwrap_or(""))) + if s.starts_with('$') { + return Err(SandboxError::UnsupportedConfigVariable(path.to_path_buf())); + } + Ok(()) } fn require_absolute(path: &Path) -> Result<(), SandboxError> { @@ -694,7 +711,7 @@ fn require_absolute(path: &Path) -> Result<(), SandboxError> { } fn expand_and_canonicalize(path: &Path) -> Result { - let expanded = expand_tilde(path)?; + let expanded = expand_path(path)?; require_absolute(&expanded)?; std::fs::canonicalize(&expanded).map_err(|e| SandboxError::ConfigRead { path: expanded, diff --git a/src/errors.rs b/src/errors.rs index 89dc742..6e75d89 100644 --- a/src/errors.rs +++ b/src/errors.rs @@ -29,6 +29,7 @@ pub enum SandboxError { UnknownConfigKey(String), NestedExtraConfig(PathBuf), ConfigPathNotAbsolute(PathBuf), + UnsupportedConfigVariable(PathBuf), InvalidBwrapArg(String), InvalidBindSpec(String), NoCommand, @@ -97,6 +98,11 @@ impl std::fmt::Display for SandboxError { Self::ConfigPathNotAbsolute(p) => { write!(f, "config path is not absolute: {}", p.display()) } + Self::UnsupportedConfigVariable(p) => write!( + f, + "config paths only expand $PWD and ${{PWD}}; use ~ or an absolute path: {}", + p.display() + ), Self::InvalidBwrapArg(s) => { write!(f, "invalid quoting in --bwrap-arg: {s}") } diff --git a/src/lib.rs b/src/lib.rs index 53d31f3..0467dc9 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -83,6 +83,10 @@ pub fn require_home() -> Result { .ok_or(SandboxError::HomeNotSet) } +pub fn require_current_dir() -> Result { + std::env::current_dir().map_err(SandboxError::CurrentDirUnavailable) +} + pub fn require_run_user() -> Result { std::env::var("XDG_RUNTIME_DIR") .ok() diff --git a/tests/e2e/mounts.rs b/tests/e2e/mounts.rs index 79c341a..299d3e9 100644 --- a/tests/e2e/mounts.rs +++ b/tests/e2e/mounts.rs @@ -43,6 +43,25 @@ fn cwd_is_writable() { ); } +#[test] +fn config_pwd_binds_launch_directory_writable() { + let dir = TempDir::new().unwrap(); + let config = ConfigFile::new(r#"rw = ["$PWD"]"#); + + let output = Command::new(env!("CARGO_BIN_EXE_agent-sandbox")) + .args(["--config", &config, "--", "touch", "canary"]) + .current_dir(dir.path()) + .output() + .expect("agent-sandbox binary failed to execute"); + + assert!( + output.status.success(), + "stderr: {}", + String::from_utf8_lossy(&output.stderr) + ); + assert!(dir.path().join("canary").exists()); +} + #[test] fn host_fs_is_readonly() { let output = Sandbox::new(&[]) diff --git a/tests/unit/config.rs b/tests/unit/config.rs index 353e769..0d2ff66 100644 --- a/tests/unit/config.rs +++ b/tests/unit/config.rs @@ -741,6 +741,79 @@ fn build_tilde_expansion_in_config_paths() { assert_eq!(config.extra_rw, vec![same_bind(Path::new(&home))]); } +#[test] +fn build_pwd_expands_to_current_dir_in_config_paths() { + let cwd = std::env::current_dir().unwrap(); + let file_config = FileConfig { + options: Options { + rw: vec!["$PWD".into()], + ro: vec!["$PWD/src".into()], + ..Options::default() + }, + ..FileConfig::default() + }; + let config = build(args_with_command(), Some(file_config)).unwrap(); + assert_eq!(config.extra_rw, vec![same_bind(&cwd)]); + assert_eq!(config.extra_ro, vec![same_bind(&cwd.join("src"))]); +} + +#[test] +fn build_braced_pwd_expands_to_current_dir_in_config_paths() { + let cwd = std::env::current_dir().unwrap(); + let file_config = FileConfig { + options: Options { + rw: vec!["${PWD}".into()], + ro: vec!["${PWD}/src".into()], + ..Options::default() + }, + ..FileConfig::default() + }; + let config = build(args_with_command(), Some(file_config)).unwrap(); + assert_eq!(config.extra_rw, vec![same_bind(&cwd)]); + assert_eq!(config.extra_ro, vec![same_bind(&cwd.join("src"))]); +} + +#[test] +fn build_pwd_expands_in_target() { + let home = std::env::var("HOME").unwrap(); + let cwd = std::env::current_dir().unwrap(); + let file_config = FileConfig { + options: Options { + rw: vec!["~/:$PWD/mounted".into()], + ..Options::default() + }, + ..FileConfig::default() + }; + let config = build(args_with_command(), Some(file_config)).unwrap(); + assert_eq!( + config.extra_rw, + vec![BindSpec { + source: PathBuf::from(&home), + target: cwd.join("mounted"), + }] + ); +} + +#[test] +fn build_other_variables_in_config_paths_rejected() { + for raw in ["$HOME/x", "${HOME}", "$PWDX", "${PWD}x", "$"] { + let file_config = FileConfig { + options: Options { + rw: vec![raw.into()], + ..Options::default() + }, + ..FileConfig::default() + }; + assert!( + matches!( + build(args_with_command(), Some(file_config)), + Err(SandboxError::UnsupportedConfigVariable(_)) + ), + "{raw} should be rejected" + ); + } +} + #[test] fn build_preserves_symlinks_in_config_paths() { let dir = TempDir::new().unwrap();