Expand $PWD in config paths to the launch directory

This commit is contained in:
2026-11-17 20:37:01 +01:00
parent 34bc50a256
commit 352ead2bf5
6 changed files with 134 additions and 13 deletions
+2
View File
@@ -49,6 +49,8 @@ ln -sf "$(pwd)/config-example.toml" "${XDG_CONFIG_HOME:-$HOME/.config}/agent-san
Top-level keys set defaults; `[profile.<name>]` sections define named presets selectable with `--profile <name>`. 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
+30 -13
View File
@@ -185,7 +185,7 @@ fn resolve_chdir(
) -> Result<PathBuf, SandboxError> {
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<PathBuf, SandboxError> {
}
fn expand_and_require_absolute(path: &Path) -> Result<PathBuf, SandboxError> {
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<PathBuf, SandboxError> {
let s = path.to_string_lossy();
if !s.starts_with('~') {
return Ok(path.to_path_buf());
fn expand_path(path: &Path) -> Result<PathBuf, SandboxError> {
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<PathBuf, SandboxError> {
let expanded = expand_tilde(path)?;
let expanded = expand_path(path)?;
require_absolute(&expanded)?;
std::fs::canonicalize(&expanded).map_err(|e| SandboxError::ConfigRead {
path: expanded,
+6
View File
@@ -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}")
}
+4
View File
@@ -83,6 +83,10 @@ pub fn require_home() -> Result<String, SandboxError> {
.ok_or(SandboxError::HomeNotSet)
}
pub fn require_current_dir() -> Result<PathBuf, SandboxError> {
std::env::current_dir().map_err(SandboxError::CurrentDirUnavailable)
}
pub fn require_run_user() -> Result<String, SandboxError> {
std::env::var("XDG_RUNTIME_DIR")
.ok()
+19
View File
@@ -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(&[])
+73
View File
@@ -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();