From 58aeaf67a48973e6badfe762e56da985031295a1 Mon Sep 17 00:00:00 2001 From: "gominimal-aw-bot[bot]" <281738952+gominimal-aw-bot[bot]@users.noreply.github.com> Date: Sat, 17 Oct 2026 11:03:50 +0000 Subject: [PATCH 01/21] fix(task): gate task patch declarations against [patches] policy A task's patch.dir/patch.file entries were passed to the daemon ungated: the daemon holds no user policy and mounts what it is given, so a minimal.toml task could patch in any host path the [patches] rules were written to constrain. The same file's [session] patches were already gated, so the rules silently did not apply to tasks. Gate the declared paths client-side in 'min task run', both lanes: the interactive prompt and the non-interactive collect-and-refuse. Entries the policy ignores cannot be carried as resolved values - the daemon mounts the declared path itself - so the client sends the ignored raw keys on the exec channel and the daemon removes them from the task's declarations before mounting. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- crates/boxes/src/core/compose.rs | 228 +++++++++++++- crates/boxes/src/core/compose/tests.rs | 181 +++++++++++ crates/minimal-client/src/lib.rs | 22 +- crates/minimal/src/task.rs | 404 ++++++++++++++++++++++++- crates/minimald-rpc/src/taskenv.rs | 77 ++++- crates/minimald/src/exec.rs | 24 ++ 6 files changed, 915 insertions(+), 21 deletions(-) diff --git a/crates/boxes/src/core/compose.rs b/crates/boxes/src/core/compose.rs index 05f827c27f..f79182f1ec 100644 --- a/crates/boxes/src/core/compose.rs +++ b/crates/boxes/src/core/compose.rs @@ -16,7 +16,7 @@ use std::collections::BTreeMap; use crate::core::decision::{CheckOutcome, Decision, ItemDecision}; use crate::core::enumerate::{ExpandedProvenancedPatch, PatchFile, enumerate_patch_files}; use crate::core::hooks::{HookResult, PolicyHooks, Unapproved}; -use crate::core::policy::{PatchesPolicy, UserPolicy, VarsPolicy}; +use crate::core::policy::{ExpandedPatchesPolicy, PatchesPolicy, UserPolicy, VarsPolicy}; use crate::core::primitives::{ResolvedPatch, ResolvedVar, VarError}; use crate::core::source::{ Provenanced, ProvenancedHook, ProvenancedPackage, ProvenancedPatch, ProvenancedVar, Source, @@ -1533,6 +1533,232 @@ pub fn gate_names( Ok((verdicts, policy)) } +/// One declared task patch entry, for [`gate_task_patch_paths`]. +/// +/// `declared` is the raw key the task's `minimal.toml` wrote into +/// `patch.dir` / `patch.file` — the exact string a removal must name again, +/// which is why the gate hands it back untouched. `is_file` selects which +/// of the two maps it came from. +pub struct TaskPatchEntry<'a> { + /// The declared path key, verbatim. + pub declared: &'a str, + /// `true` for a `patch.file` entry, `false` for `patch.dir`. + pub is_file: bool, + /// The contributing task's provenance — always a project, since only + /// `minimal.toml` declares tasks. + pub source: &'a Source, +} + +/// One declared path's [`PathDecision`](crate::core::policy::PathDecision): +/// the declared form, plus the canonicalized form when it differs, +/// combined. Canonicalization is best-effort — an entry that does not +/// exist yet (`create_if_missing`) is checked by its declared form alone. +fn check_task_patch_path( + expanded: &ExpandedPatchesPolicy, + source: &Source, + path: &camino::Utf8Path, +) -> crate::core::policy::PathDecision { + let item = NameItem { source }; + let canonical = std::fs::canonicalize(path.as_std_path()) + .ok() + .and_then(|p| { + camino::Utf8PathBuf::from_path_buf(p) + .ok() + .filter(|c| c != path) + }); + let target = path.to_path_buf(); + match expanded.check(canonical.as_deref(), &target, item) { + CheckOutcome::Decided(Decision::Allowed(_)) => crate::core::policy::PathDecision::Allowed, + CheckOutcome::Decided(Decision::Ignored) => crate::core::policy::PathDecision::Ignored, + CheckOutcome::Decided(Decision::Denied(_)) => crate::core::policy::PathDecision::Denied, + CheckOutcome::NeedsApproval(_) => crate::core::policy::PathDecision::NeedsApproval, + } +} + +/// A declared directory entry's decision: the directory's own path, then +/// every file it currently holds. A directory that cannot be walked (missing +/// for a future `create_if_missing` mount, or unreadable) is decided by its +/// own path alone. +fn check_task_patch_dir( + expanded: &ExpandedPatchesPolicy, + source: &Source, + dir: &camino::Utf8Path, +) -> crate::core::policy::PathDecision { + let mut verdict = check_task_patch_path(expanded, source, dir); + // Best-effort name walk: any IO failure (a missing directory a + // `create_if_missing` mount would create, a permission error) leaves + // the entry's fate to the path check above. + let mut stack = vec![dir.to_path_buf()]; + while let Some(cur) = stack.pop() { + let Ok(read) = std::fs::read_dir(cur.as_std_path()) else { + continue; + }; + for entry in read.flatten() { + let Ok(path) = camino::Utf8PathBuf::from_path_buf(entry.path()) else { + continue; + }; + let is_dir = entry.file_type().is_ok_and(|t| t.is_dir()); + if is_dir { + stack.push(path); + } else { + verdict = verdict.combine(check_task_patch_path(expanded, source, &path)); + } + } + } + verdict +} + +/// A declared entry's decision: the file form checks its one path, the +/// directory form also checks the files it currently holds. +fn check_task_patch_entry( + expanded: &ExpandedPatchesPolicy, + entry: &TaskPatchEntry<'_>, + path: &camino::Utf8Path, +) -> crate::core::policy::PathDecision { + if entry.is_file { + check_task_patch_path(expanded, entry.source, path) + } else { + check_task_patch_dir(expanded, entry.source, path) + } +} + +/// Drive the `[patches]` policy over a task's declared `patch.dir` / +/// `patch.file` entries and return one [`NameVerdict`] per entry, in +/// order, plus the policy as the hook may have amended it. +/// +/// This is the patch-side sibling of [`gate_names`], with the same +/// contract: callers that must decide *before* the daemon mounts anything +/// call it directly, because the daemon holds no policy and mounts what +/// it is given. A task's patches are declared by the project, and the +/// project is exactly what `[patches]` exists to constrain — the same +/// file's `[session]` patches have always been gated by [`gate_patches`]. +/// +/// Unlike [`gate_patches`], which checks each file a walked patch source +/// produced, this checks the *declared* paths themselves: a task's patch +/// is a host path the sandbox mounts (or creates) directly, not a source +/// pattern to walk. A directory entry is checked twice — once as the +/// declared path (a deny on the directory itself must deny the entry) and +/// once per file the directory currently holds (a deny on a contained file +/// must deny the entry that would mount it), with the outcomes combined +/// by [`PathDecision::combine`]'s most-restrictive-first precedence. A +/// directory that cannot be read is decided by its own path alone. +/// +/// `~/`-rooted entries are expanded against `home_fallback` for the +/// check; a `~` entry with no fallback routes to the hook (fail-closed). +/// Each path is also checked in canonicalized form, so a symlink cannot +/// evade a deny rule that names its target. +/// +/// # Errors +/// +/// - [`ComposeError::Denied`] — a `deny` rule matched. Returned from the +/// first denial found, before any hook is consulted, so a forbidden +/// path is never preceded by a prompt about its neighbours. +/// - [`ComposeError::HookRequired`] — an entry needed approval and there +/// was no hook to ask. +/// - [`ComposeError::Aborted`] — the hook cancelled. +/// - [`ComposeError::HookContract`] — the hook returned the wrong number +/// of decisions, or answered `UseRule` for an entry the policy still +/// cannot decide. +/// - [`ComposeError::Expansion`] — a policy pattern failed to expand +/// against `resolved_vars` (an undefined `$VAR`, for instance). +pub fn gate_task_patch_paths( + entries: &[TaskPatchEntry<'_>], + mut policy: PatchesPolicy, + hooks: Option<&dyn PolicyHooks>, + resolved_vars: &(impl crate::core::expansion::VarLookup + ?Sized), + home_fallback: Option<&str>, +) -> Result<(Vec, PatchesPolicy), ComposeError> { + // Same two policies in flight as `gate_patches`: the raw form travels + // to and from the hook, the expanded form does the matching. Expanded + // first so a malformed pattern surfaces before any filesystem probe. + let mut expanded = policy.expand_with(resolved_vars, home_fallback)?; + + let expand_declared = |declared: &str| -> camino::Utf8PathBuf { + match (declared.strip_prefix("~/"), home_fallback) { + (Some(rest), Some(home)) => camino::Utf8PathBuf::from(format!("{home}/{rest}")), + _ => camino::Utf8PathBuf::from(declared), + } + }; + + // Pass 1: categorize per entry. Undecided entries are seeded + // `Ignored` and queued; pass 3 overwrites every one. The placeholder + // is fail-closed on purpose — should a future edit ever leave one + // unwritten, the caller drops the entry rather than mounting it. + let mut verdicts: Vec = Vec::with_capacity(entries.len()); + let mut unapproved: Vec = Vec::new(); + for (i, entry) in entries.iter().enumerate() { + let path = expand_declared(entry.declared); + let verdict = check_task_patch_entry(&expanded, entry, &path); + match verdict { + crate::core::policy::PathDecision::Allowed => verdicts.push(NameVerdict::Allowed), + crate::core::policy::PathDecision::Ignored => verdicts.push(NameVerdict::Ignored), + crate::core::policy::PathDecision::Denied => { + return Err(ComposeError::Denied { + what: entry.declared.to_owned(), + from: entry.source.clone(), + }); + } + crate::core::policy::PathDecision::NeedsApproval => { + unapproved.push(i); + verdicts.push(NameVerdict::Ignored); + } + } + } + + if !unapproved.is_empty() { + let Some(hooks) = hooks else { + let i = unapproved[0]; + return Err(ComposeError::HookRequired { + what: entries[i].declared.to_owned(), + from: entries[i].source.clone(), + }); + }; + // Pass 2: prompt, with the expanded form as the user-facing item — + // the prompt reads better as the path the entry names on this + // machine, and a rule chosen for it must expand to match. + let view: Vec> = unapproved + .iter() + .map(|&i| Unapproved { + item: camino::Utf8Path::new(entries[i].declared), + source: entries[i].source, + }) + .collect(); + let (decisions, new_policy, policy_updated) = prompt_patch_hook(hooks, policy, &view)?; + policy = new_policy; + if policy_updated { + expanded = policy.expand_with(resolved_vars, home_fallback)?; + } + // Pass 3: apply. + for (&i, decision) in unapproved.iter().zip(decisions) { + let entry = &entries[i]; + let path = expand_declared(entry.declared); + let verdict = check_task_patch_entry(&expanded, entry, &path); + verdicts[i] = match decision { + ItemDecision::AllowOnce => NameVerdict::Allowed, + ItemDecision::IgnoreOnce => NameVerdict::Ignored, + ItemDecision::UseRule => match verdict { + crate::core::policy::PathDecision::Allowed => NameVerdict::Allowed, + crate::core::policy::PathDecision::Ignored => NameVerdict::Ignored, + crate::core::policy::PathDecision::Denied => { + return Err(ComposeError::Denied { + what: entry.declared.to_owned(), + from: entry.source.clone(), + }); + } + crate::core::policy::PathDecision::NeedsApproval => { + return Err(ComposeError::use_rule_undecided( + HookDomain::Patch, + format!("source path `{}`", entry.declared), + )); + } + }, + }; + } + } + + Ok((verdicts, policy)) +} + /// Drive the policy pass over a batch of vars. /// /// `hooks` is `None` for user-only composition — all items are diff --git a/crates/boxes/src/core/compose/tests.rs b/crates/boxes/src/core/compose/tests.rs index 53097d7ae6..9266d66775 100644 --- a/crates/boxes/src/core/compose/tests.rs +++ b/crates/boxes/src/core/compose/tests.rs @@ -2501,3 +2501,184 @@ mod extend_from_wire { assert_eq!(names, vec!["helix", "ripgrep"]); } } + +// ================================================================= +// Task patch gating +// ================================================================= + +/// [`gate_task_patch_paths`] drives the `[patches]` policy over a task's +/// declared `patch.dir` / `patch.file` entries. These tests pin its +/// verdicts; the client wiring that calls it is covered in `minimal`. +mod gate_task_patch_paths { + use super::*; + use crate::core::compose::{TaskPatchEntry, gate_task_patch_paths}; + use crate::core::policy::PatchesPolicy; + + /// A var lookup that answers nothing — for policies with no `$VAR` + /// patterns, which is every policy below. + struct NoVars; + impl crate::core::expansion::VarLookup for NoVars { + fn lookup(&self, _: &str) -> Option<&str> { + None + } + } + + fn entries_for<'a>( + source: &'a Source, + declared: &[(&'a str, bool)], + ) -> Vec> { + declared + .iter() + .map(|&(d, is_file)| TaskPatchEntry { + declared: d, + is_file, + source, + }) + .collect() + } + + #[test] + fn a_denied_entry_aborts_before_the_hook() { + let source = project_source(); + let entries = entries_for(&source, &[("/etc/passwd", true)]); + let policy = PatchesPolicy::default().with_deny(vec!["/etc/passwd".to_string()]); + let err = gate_task_patch_paths(&entries, policy, None, &NoVars, None).unwrap_err(); + assert!(matches!(err, ComposeError::Denied { what, .. } if what == "/etc/passwd")); + } + + #[test] + fn an_ignored_entry_reports_ignored() { + let source = project_source(); + let entries = entries_for(&source, &[("/opt/tool/bin", true)]); + let policy = PatchesPolicy::default().with_ignore(vec!["/opt/**".to_string()]); + let (verdicts, _) = gate_task_patch_paths(&entries, policy, None, &NoVars, None).unwrap(); + assert_eq!(verdicts, vec![NameVerdict::Ignored]); + } + + #[test] + fn an_allowed_entry_reports_allowed() { + let source = project_source(); + let entries = entries_for(&source, &[("/usr/local/bin/tool", true)]); + let policy = PatchesPolicy::default().with_allow(vec!["/usr/**".to_string()]); + let (verdicts, _) = gate_task_patch_paths(&entries, policy, None, &NoVars, None).unwrap(); + assert_eq!(verdicts, vec![NameVerdict::Allowed]); + } + + #[test] + fn an_unmatched_entry_without_a_hook_requires_one() { + let source = project_source(); + let entries = entries_for(&source, &[("/home/dev/notes.txt", true)]); + let err = gate_task_patch_paths(&entries, PatchesPolicy::default(), None, &NoVars, None) + .unwrap_err(); + assert!(matches!(err, ComposeError::HookRequired { .. })); + } + + #[test] + fn an_unmatched_entry_with_a_hook_can_be_allowed() { + struct Allow; + impl crate::core::hooks::PolicyHooks for Allow { + fn on_var_unapproved( + &self, + _: crate::core::policy::VarsPolicy, + _: &[Unapproved<'_, str>], + ) -> HookResult { + panic!("var hook should not have been invoked") + } + fn on_patch_unapproved( + &self, + _: PatchesPolicy, + _: &[Unapproved<'_, camino::Utf8Path>], + ) -> HookResult { + HookResult::decided(vec![ItemDecision::AllowOnce]) + } + } + let source = project_source(); + let entries = entries_for(&source, &[("/home/dev/notes.txt", true)]); + let (verdicts, _) = gate_task_patch_paths( + &entries, + PatchesPolicy::default(), + Some(&Allow), + &NoVars, + None, + ) + .unwrap(); + assert_eq!(verdicts, vec![NameVerdict::Allowed]); + } + + #[test] + fn a_directory_entry_is_denied_by_a_contained_file() { + let tmp = tempfile::tempdir().unwrap(); + let root = Utf8Path::from_path(tmp.path()).unwrap().to_path_buf(); + let secrets = root.join(".ssh"); + std::fs::create_dir(secrets.as_std_path()).unwrap(); + std::fs::write(secrets.join("id_ed25519").as_std_path(), "x").unwrap(); + + let source = project_source(); + let entries = entries_for(&source, &[(secrets.as_str(), false)]); + let policy = PatchesPolicy::default().with_deny(vec![format!("{}/**", secrets)]); + let err = gate_task_patch_paths(&entries, policy, None, &NoVars, None).unwrap_err(); + assert!(matches!(err, ComposeError::Denied { .. })); + } + + #[test] + fn a_directory_entry_denied_on_its_own_path_stays_denied() { + let source = project_source(); + let entries = entries_for(&source, &[("/srv/data", false)]); + let policy = PatchesPolicy::default().with_deny(vec!["/srv/data".to_string()]); + let err = gate_task_patch_paths(&entries, policy, None, &NoVars, None).unwrap_err(); + assert!(matches!(err, ComposeError::Denied { .. })); + } + + #[test] + fn a_tilde_entry_expands_against_the_home_fallback() { + let source = project_source(); + let entries = entries_for(&source, &[("~/.config/app", true)]); + let policy = PatchesPolicy::default().with_allow(vec!["/home/dev/**".to_string()]); + let (verdicts, _) = + gate_task_patch_paths(&entries, policy, None, &NoVars, Some("/home/dev")).unwrap(); + assert_eq!(verdicts, vec![NameVerdict::Allowed]); + } + + #[test] + fn a_tilde_entry_without_a_home_fallback_needs_approval() { + let source = project_source(); + let entries = entries_for(&source, &[("~/.config/app", true)]); + let err = gate_task_patch_paths(&entries, PatchesPolicy::default(), None, &NoVars, None) + .unwrap_err(); + assert!(matches!(err, ComposeError::HookRequired { .. })); + } + + #[test] + fn use_rule_rechecks_the_amended_policy() { + struct Amend; + impl crate::core::hooks::PolicyHooks for Amend { + fn on_var_unapproved( + &self, + _: crate::core::policy::VarsPolicy, + _: &[Unapproved<'_, str>], + ) -> HookResult { + panic!("var hook should not have been invoked") + } + fn on_patch_unapproved( + &self, + _: PatchesPolicy, + _: &[Unapproved<'_, camino::Utf8Path>], + ) -> HookResult { + HookResult::decided(vec![ItemDecision::UseRule]) + } + } + let source = project_source(); + let entries = entries_for(&source, &[("/home/dev/notes.txt", true)]); + let err = gate_task_patch_paths( + &entries, + PatchesPolicy::default(), + Some(&Amend), + &NoVars, + None, + ) + .unwrap_err(); + // UseRule with no recorded rule: still undecided — a contract + // error, not a silent allow. + assert!(err.to_string().contains("UseRule returned for a patch")); + } +} diff --git a/crates/minimal-client/src/lib.rs b/crates/minimal-client/src/lib.rs index cd64c7bf5f..a29b1758f9 100644 --- a/crates/minimal-client/src/lib.rs +++ b/crates/minimal-client/src/lib.rs @@ -588,9 +588,11 @@ impl Client { /// /// `task_env` carries a task's `env_vars` already resolved against the /// invoking shell: values under - /// [`TASK_ENV_PREFIX`](minimald_rpc::taskenv::TASK_ENV_PREFIX), and the - /// names to remove under - /// [`TASK_ENV_DROP`](minimald_rpc::taskenv::TASK_ENV_DROP). Only + /// [`TASK_ENV_PREFIX`](minimald_rpc::taskenv::TASK_ENV_PREFIX), the + /// variable names to remove under + /// [`TASK_ENV_DROP`](minimald_rpc::taskenv::TASK_ENV_DROP), and the + /// declared patch paths the policy ignored under + /// [`TASK_PATCH_DROP`](minimald_rpc::taskenv::TASK_PATCH_DROP). Only /// [`ExecRequest::TaskRun`](minimald_rpc::exec::ExecRequest::TaskRun) has /// any to send; every other caller passes an empty /// [`TaskEnv`](minimald_rpc::taskenv::TaskEnv) and the daemon behaves @@ -645,6 +647,20 @@ impl Client { .await .context("set task env drop list")?; } + // Same contract for the patch entries the client's policy dropped: + // the raw declared keys the daemon removes from the task's `patch` + // maps before mounting. Absent means the client gated nothing — + // or predates the gate. + if !task_env.patch_drop.is_empty() { + channel + .set_env( + true, + minimald_rpc::taskenv::TASK_PATCH_DROP, + minimald_rpc::taskenv::encode_drops(&task_env.patch_drop), + ) + .await + .context("set task patch drop list")?; + } channel .exec(true, command) .await diff --git a/crates/minimal/src/task.rs b/crates/minimal/src/task.rs index bd89ebc2f7..047c4b472d 100644 --- a/crates/minimal/src/task.rs +++ b/crates/minimal/src/task.rs @@ -289,11 +289,16 @@ fn resolve_task_env( #[derive(Default)] struct RefuseAndRecord { names: std::cell::RefCell>, + patch_paths: std::cell::RefCell>, } impl RefuseAndRecord { - fn into_names(self) -> Vec { - self.names.into_inner() + fn recorded_names(&self) -> Vec { + self.names.borrow().clone() + } + + fn recorded_patch_paths(&self) -> Vec { + self.patch_paths.borrow().clone() } } @@ -316,9 +321,19 @@ impl boxes::core::hooks::PolicyHooks for RefuseAndRecord { fn on_patch_unapproved( &self, _policy: boxes::core::policy::PatchesPolicy, - _items: &[boxes::core::hooks::Unapproved<'_, camino::Utf8Path>], + items: &[boxes::core::hooks::Unapproved<'_, camino::Utf8Path>], ) -> boxes::core::hooks::HookResult { - unreachable!("task env resolution never gates patches") + // Same record-and-refuse as the vars half: an unapproved patch + // path must not reach the daemon's mount set, and the names land + // in the operator's snippet instead. + let mut paths = self.patch_paths.borrow_mut(); + for item in items { + let path = item.item().to_string(); + if !paths.contains(&path) { + paths.push(path); + } + } + boxes::core::hooks::HookResult::Abort } } @@ -339,6 +354,37 @@ fn refused_vars_snippet(names: &[String]) -> String { doc.to_string() } +/// Format refused patch paths as the `[patches] allow` snippet an +/// operator can paste — the patch-side sibling of +/// [`refused_vars_snippet`](fn@refused_vars_snippet), emitted through +/// `toml_edit` for the same escaping reason. +fn refused_patches_snippet(paths: &[String]) -> String { + let mut doc = toml_edit::DocumentMut::new(); + let mut patches = toml_edit::Table::new(); + let mut allow = toml_edit::Array::new(); + for path in paths { + allow.push(path.as_str()); + } + patches.insert("allow", toml_edit::value(allow)); + doc.insert("patches", toml_edit::Item::Table(patches)); + doc.to_string() +} + +/// Var lookup over the resolved task env plus the client's home: the +/// values a `[patches]` pattern's `$VAR` references expand against +/// client-side. Task vars are in because the task's own declarations can +/// name them; `HOME` is in because `~` in a pattern must expand to the +/// same directory the declared `~/` keys will. +struct TaskEnvLookup { + vars: std::collections::BTreeMap, +} + +impl boxes::core::expansion::VarLookup for TaskEnvLookup { + fn lookup(&self, name: &str) -> Option<&str> { + self.vars.get(name).map(String::as_str) + } +} + /// The `[vars] deny` rejection body: names the task, the variable, and the /// file the rule lives in, so the fix is reachable without guessing where /// the policy is stored. Split out for unit tests. @@ -351,6 +397,101 @@ fn denied_task_var_message(task_name: &str, name: &str, policy_path: &std::path: ) } +/// The `[patches] deny` rejection body for a task patch: names the task, +/// the declared path, and the file the rule lives in. Split out for unit +/// tests. +fn denied_task_patch_message(task_name: &str, path: &str, policy_path: &std::path::Path) -> String { + format!( + "task '{task_name}' declares `patch.{path}`, but it is denied by \ + `[patches] deny` in {policy}; remove the declaration, or the deny \ + rule if this task should mount it", + policy = policy_path.display(), + ) +} + +/// Gate a task's declared `patch.dir` / `patch.file` entries against +/// `[patches]`, the same two lanes as the `env_vars` gate above: the +/// interactive prompt on a real terminal, the collect-and-refuse +/// `RefuseAndRecord` anywhere else. Returns the raw declared keys the +/// policy ignored, for the daemon to drop from the mount set — the wire +/// half of the fix, since the daemon holds no policy and mounts what it +/// is given. +fn resolve_task_patches( + task: &mfile::Task, + task_name: &str, + patches_policy: boxes::core::policy::PatchesPolicy, + policy_path: &std::path::Path, + source: &boxes::core::source::Source, + hooks: &dyn boxes::core::hooks::PolicyHooks, + resolved_env: &minimald_rpc::taskenv::TaskEnv, +) -> Result, anyhow::Error> { + use boxes::core::compose::{TaskPatchEntry, gate_task_patch_paths}; + + // Echo tasks never reach the daemon's mount path — the daemon answers + // an echo from the declaration itself — so there is nothing to gate. + if task.action.as_echo().is_some() { + return Ok(Default::default()); + } + + // The gate expands policy patterns through this lookup. A pattern + // naming `$HOME` is the common case for patches, so the resolved + // task vars share the lookup with the client's own home — the same + // base the daemon expands `~/` keys against. + let mut vars: std::collections::BTreeMap = resolved_env.set.clone(); + if let Some(home) = std::env::var_os("HOME") + && let Some(home) = home.to_str() + { + vars.insert("HOME".to_string(), home.to_string()); + } + let lookup = TaskEnvLookup { vars }; + + // Dir entries first, then files, each in declaration order — the + // same order `to_fs_mappings` iterates when mounting. + let mut entries: Vec> = Vec::new(); + for key in task.patch.dir.keys() { + entries.push(TaskPatchEntry { + declared: key, + is_file: false, + source, + }); + } + for key in task.patch.file.keys() { + entries.push(TaskPatchEntry { + declared: key, + is_file: true, + source, + }); + } + + let home_fallback = std::env::var_os("HOME").and_then(|h| h.into_string().ok()); + let (verdicts, _policy) = match gate_task_patch_paths( + &entries, + patches_policy, + Some(hooks), + &lookup, + home_fallback.as_deref(), + ) { + Ok(out) => out, + Err(boxes::core::compose::ComposeError::Denied { what, .. }) => { + bail!(denied_task_patch_message(task_name, &what, policy_path)) + } + Err(e) => { + return Err(anyhow::Error::new(e)) + .with_context(|| format!("gating `patch` for task '{task_name}'")); + } + }; + + // Verdicts pair with `entries` in order; an ignored entry's raw + // declared key is what the daemon must remove from its mount set. + let mut drops = std::collections::BTreeSet::new(); + for (entry, verdict) in entries.iter().zip(verdicts) { + if matches!(verdict, boxes::core::compose::NameVerdict::Ignored) { + drops.insert(entry.declared.to_string()); + } + } + Ok(drops) +} + /// The whitespace rejection body: the name is debug-quoted so the offending /// whitespace is visible. Split out for unit tests. fn untrimmed_task_message(task: &str) -> String { @@ -609,7 +750,7 @@ pub async fn cmd_task_run(global: &GlobalArgs, args: TaskRunArgs) -> Result<(), ); // Checked before the result: the hook refused, so `task_env` is // the abort error and the names are the useful half of it. - let refused = hooks.into_names(); + let refused = hooks.recorded_names(); if !refused.is_empty() { let count = refused.len(); let snippet = refused_vars_snippet(&refused); @@ -623,7 +764,33 @@ pub async fn cmd_task_run(global: &GlobalArgs, args: TaskRunArgs) -> Result<(), s = if count == 1 { "" } else { "s" }, ); } - (task_env?, user_policy) + let task_env = task_env?; + let patch_drops = resolve_task_patches( + &declared, + &args.task, + user_policy.patches().clone(), + &policy_path, + &source, + &hooks, + &task_env, + )?; + let refused_patches = hooks.recorded_patch_paths(); + if !refused_patches.is_empty() { + let count = refused_patches.len(); + let snippet = refused_patches_snippet(&refused_patches); + bail!( + "task '{task}' declares {count} patch{es} that your policy does \ + not allow, and stdin/stderr is not a terminal.\n\n\ + Add the following to {path}:\n\n{snippet}\n\ + Then re-run this command.", + task = args.task, + path = policy_path.display(), + es = if count == 1 { "" } else { "es" }, + ); + } + let mut task_env = task_env; + task_env.patch_drop = patch_drops; + (task_env, user_policy) } else { let hooks = crate::prompt::InteractivePrompt::new(&policy_path, user_policy.clone()); let task_env = resolve_task_env( @@ -635,6 +802,19 @@ pub async fn cmd_task_run(global: &GlobalArgs, args: TaskRunArgs) -> Result<(), &hooks, |k| std::env::var(k), ); + let task_env = task_env?; + // Same lane for patches, against the same interactive hook, so a + // rule the user records for a patch lands in the same policy + // save as a rule recorded for a variable. + let patch_drops = resolve_task_patches( + &declared, + &args.task, + user_policy.patches().clone(), + &policy_path, + &source, + &hooks, + &task_env, + )?; // Persist before propagating a refusal: a rule the user chose to // record is theirs whether or not this run goes on to fail. let after = hooks.into_final_policy(); @@ -644,7 +824,9 @@ pub async fn cmd_task_run(global: &GlobalArgs, args: TaskRunArgs) -> Result<(), Err(e) => eprintln!("warning: failed to update {}: {e}", policy_path.display()), } } - (task_env?, after) + let mut task_env = task_env; + task_env.patch_drop = patch_drops; + (task_env, after) }; crate::ensure_daemon(global)?; @@ -1166,6 +1348,11 @@ mod tests { struct ScriptedHook { decision: boxes::core::decision::ItemDecision, asked: std::cell::RefCell>, + /// Answers patch-path referrals the same way as names; `None` + /// (the default) refuses them, standing in for the + /// non-interactive lane's collect-and-refuse. + patch_decision: Option, + asked_paths: std::cell::RefCell>, } impl ScriptedHook { @@ -1173,12 +1360,23 @@ mod tests { Self { decision, asked: std::cell::RefCell::new(Vec::new()), + patch_decision: None, + asked_paths: std::cell::RefCell::new(Vec::new()), } } + fn allowing_patches(mut self) -> Self { + self.patch_decision = Some(boxes::core::decision::ItemDecision::AllowOnce); + self + } + fn asked(&self) -> Vec { self.asked.borrow().clone() } + + fn asked_paths(&self) -> Vec { + self.asked_paths.borrow().clone() + } } impl boxes::core::hooks::PolicyHooks for ScriptedHook { @@ -1196,9 +1394,17 @@ mod tests { fn on_patch_unapproved( &self, _policy: boxes::core::policy::PatchesPolicy, - _items: &[boxes::core::hooks::Unapproved<'_, camino::Utf8Path>], + items: &[boxes::core::hooks::Unapproved<'_, camino::Utf8Path>], ) -> boxes::core::hooks::HookResult { - unreachable!("task env resolution never gates patches") + match self.patch_decision { + Some(d) => { + self.asked_paths + .borrow_mut() + .extend(items.iter().map(|i| i.item().to_string())); + boxes::core::hooks::HookResult::decided(vec![d; items.len()]) + } + None => boxes::core::hooks::HookResult::Abort, + } } } @@ -1218,9 +1424,9 @@ mod tests { fn on_patch_unapproved( &self, _policy: boxes::core::policy::PatchesPolicy, - _items: &[boxes::core::hooks::Unapproved<'_, camino::Utf8Path>], + items: &[boxes::core::hooks::Unapproved<'_, camino::Utf8Path>], ) -> boxes::core::hooks::HookResult { - unreachable!("task env resolution never gates patches") + panic!("the policy should have decided alone, was asked about {items:?}"); } } @@ -1560,7 +1766,7 @@ mod tests { "names the gate that failed: {chain}" ); assert_eq!( - hooks.into_names(), + hooks.recorded_names(), vec!["AWS_SECRET_ACCESS_KEY".to_string(), "OTHER".to_string()], "the refused names are what the caller's snippet is built from", ); @@ -1606,7 +1812,7 @@ mod tests { assert!(msg.contains("AWS_KEY"), "names the denied variable: {msg}"); assert!(msg.contains("[vars] deny"), "names the rule: {msg}"); assert!( - hooks.into_names().is_empty(), + hooks.recorded_names().is_empty(), "the hook must not be consulted once a name is denied", ); } @@ -1641,6 +1847,178 @@ mod tests { assert!(out.is_empty(), "nothing to send: {out:?}"); } + /// A denied patch path is reported with the task, the declared path, + /// and the policy file the rule lives in. + #[test] + fn a_denied_patch_is_reported_with_the_policy_file() { + let msg = denied_task_patch_message("t", "/etc/secrets", &policy_path_fixture()); + assert!(msg.contains("task 't'"), "names the task: {msg}"); + assert!(msg.contains("/etc/secrets"), "names the path: {msg}"); + assert!(msg.contains("[patches] deny"), "names the rule: {msg}"); + assert!( + msg.contains("user_policy.toml"), + "names the policy file: {msg}" + ); + } + + /// A declared patch the policy denies fails the gate client-side, and + /// the hook is never consulted — the same short-circuit as a denied + /// variable. + #[test] + fn a_denied_task_patch_fails_the_gate_before_the_hook() { + let task = task_from_toml( + "[tasks.t]\nexec = 'true'\n[tasks.t.patch.file]\n\"/etc/passwd\" = \"ro\"\n", + ); + // Pinned: the fixture must declare a patch, not just an exec. + assert!(task.patch.file.contains_key("/etc/passwd")); + let policy = boxes::core::policy::PatchesPolicy::default() + .with_deny(vec!["/etc/passwd".to_string()]); + + let err = resolve_task_patches( + &task, + "t", + policy, + &policy_path_fixture(), + &project_source(), + &NeverAsked, + &minimald_rpc::taskenv::TaskEnv::default(), + ) + .expect_err("a denied patch must fail the gate"); + + let msg = err.to_string(); + assert!( + msg.contains("patch./etc/passwd"), + "names the declared path: {msg}" + ); + assert!(msg.contains("[patches] deny"), "names the rule: {msg}"); + } + + /// The refusal snippet is the `[patches] allow` block an operator + /// pastes, and stays valid TOML for a path that needs escaping. + #[test] + fn the_patch_refusal_snippet_is_pasteable_toml() { + let snippet = refused_patches_snippet(&["/etc/secrets".to_string()]); + assert!(snippet.contains("[patches]"), "{snippet}"); + assert!(snippet.contains("/etc/secrets"), "{snippet}"); + let parsed: toml::Value = toml::from_str(&snippet).expect("snippet must parse"); + assert!(parsed.get("patches").is_some()); + } + + /// The non-interactive patch hook refuses and records, the same + /// contract as its vars half: nothing reaches the daemon's mount set, + /// and the paths land in the snippet the caller builds. + #[test] + fn the_non_interactive_patch_hook_refuses_and_records() { + let task = task_from_toml( + "[tasks.t]\nexec = 'true'\n[tasks.t.patch.file]\n\"/opt/tool/bin\" = \"ro\"\n", + ); + let hooks = RefuseAndRecord::default(); + + let err = resolve_task_patches( + &task, + "t", + boxes::core::policy::PatchesPolicy::default(), + &policy_path_fixture(), + &project_source(), + &hooks, + &minimald_rpc::taskenv::TaskEnv::default(), + ) + .expect_err("a refusing hook must fail the run"); + + let chain = format!("{err:#}"); + assert!(chain.contains("patch"), "names the gate: {chain}"); + assert_eq!( + hooks.recorded_patch_paths(), + vec!["/opt/tool/bin".to_string()], + "the refused paths are what the caller's snippet is built from", + ); + } + + /// An ignored patch path lands in the drop list the daemon removes + /// from the mount set, keyed exactly as declared. + #[test] + fn an_ignored_task_patch_lands_in_the_drop_list() { + let task = task_from_toml( + "[tasks.t]\nexec = 'true'\n[tasks.t.patch.file]\n\"/opt/tool/bin\" = \"ro\"\n\ + [tasks.t.patch.dir]\n\"/opt/cache\" = \"rw\"\n", + ); + let policy = + boxes::core::policy::PatchesPolicy::default().with_ignore(vec!["/opt/**".to_string()]); + + let drops = resolve_task_patches( + &task, + "t", + policy, + &policy_path_fixture(), + &project_source(), + &NeverAsked, + &minimald_rpc::taskenv::TaskEnv::default(), + ) + .expect("ignored entries drop, they do not fail"); + + let expect: std::collections::BTreeSet = ["/opt/tool/bin", "/opt/cache"] + .map(String::from) + .into_iter() + .collect(); + assert_eq!(drops, expect, "raw declared keys, verbatim"); + } + + /// An echo task's patches are gated by nobody, the same exemption as + /// its `env_vars`: the daemon answers an echo from the declaration + /// and returns before it builds an environment to mount into. + #[test] + fn an_echo_task_gates_no_patches_whatever_it_declares() { + let task = task_from_toml( + "[tasks.t]\necho = 'hi'\n[tasks.t.patch.file]\n\"/etc/passwd\" = \"ro\"\n", + ); + assert_eq!(task.action.as_echo(), Some("hi")); + let policy = boxes::core::policy::PatchesPolicy::default() + .with_deny(vec!["/etc/passwd".to_string()]); + + let drops = resolve_task_patches( + &task, + "t", + policy, + &policy_path_fixture(), + &project_source(), + &NeverAsked, + &minimald_rpc::taskenv::TaskEnv::default(), + ) + .expect("an echo task neither resolves nor denies"); + + assert!(drops.is_empty(), "nothing to drop: {drops:?}"); + } + + /// The interactive lane's hook approves an undecided patch on the + /// spot, and an approved patch is kept — it must not land in the + /// drop list the daemon removes from the mount set. + #[test] + fn an_approved_task_patch_is_kept_out_of_the_drop_list() { + let task = task_from_toml( + "[tasks.t]\nexec = 'true'\n[tasks.t.patch.file]\n\"/opt/tool/bin\" = \"ro\"\n", + ); + let hooks = + ScriptedHook::new(boxes::core::decision::ItemDecision::AllowOnce).allowing_patches(); + + let drops = resolve_task_patches( + &task, + "t", + boxes::core::policy::PatchesPolicy::default(), + &policy_path_fixture(), + &project_source(), + &hooks, + &minimald_rpc::taskenv::TaskEnv::default(), + ) + .expect("an approved patch runs"); + + assert_eq!( + hooks.asked_paths(), + vec!["/opt/tool/bin".to_string()], + "the prompt was about the declared path" + ); + assert!(drops.is_empty(), "an approved patch is not dropped"); + } + /// `cmd_task_run` rejects a task the project's minimal.toml does not /// declare *before* it ever touches the daemon: the declared-task guard /// runs on the resolved project path ahead of `ensure_daemon`, so an diff --git a/crates/minimald-rpc/src/taskenv.rs b/crates/minimald-rpc/src/taskenv.rs index 80feea51f9..4717b0f8ad 100644 --- a/crates/minimald-rpc/src/taskenv.rs +++ b/crates/minimald-rpc/src/taskenv.rs @@ -41,6 +41,20 @@ pub const TASK_ENV_PREFIX: &str = "MINIMAL_TASK_ENV_"; /// task as a variable called `DROP`. pub const TASK_ENV_DROP: &str = "MINIMAL_TASK_DROP"; +/// Channel env var carrying the declared patch paths the daemon must +/// *remove* from the task's declarations, as a JSON array — the keys +/// exactly as `minimal.toml` wrote them, so a removal matches the +/// declaration it names. +/// +/// The client gates a task's `patch.dir` / `patch.file` entries against +/// `[patches]` before the run; the entries the policy ignores cannot be +/// carried the way a resolved value can (the daemon mounts the declared +/// path itself), so an ignored entry has to be named for removal. +/// +/// Deliberately **not** under [`TASK_ENV_PREFIX`], for the same reason as +/// [`TASK_ENV_DROP`]. +pub const TASK_PATCH_DROP: &str = "MINIMAL_TASK_PATCH_DROP"; + /// The channel env var name carrying task variable `name`. #[must_use] pub fn wire_name(name: &str) -> String { @@ -86,18 +100,36 @@ pub fn drops_from_channel_env(env_vars: &BTreeMap) -> BTreeSet) -> BTreeSet { + env_vars + .get(TASK_PATCH_DROP) + .and_then(|raw| serde_json_lenient::from_str(raw).ok()) + .unwrap_or_default() +} + +/// A task's `env_vars` as the client resolved them, plus the `patch` +/// entries its policy dropped: the values to apply, and the names to +/// remove. /// /// The two halves are disjoint by construction — a name is either resolved /// or dropped — and travel together because the daemon needs both to -/// arrive at the set the task actually sees. +/// arrive at the set the task actually sees. `patch_drop` is a third, +/// separate list: declared patch paths, not variable names, removed from +/// the task's `patch.dir` / `patch.file` maps before they are mounted. #[derive(Clone, Debug, Default, PartialEq, Eq)] pub struct TaskEnv { /// Values to apply over the task's own declarations. pub set: BTreeMap, /// Names to remove from the task's declarations entirely. pub drop: BTreeSet, + /// Declared patch paths to remove from the task's `patch` entries + /// entirely — the keys exactly as `minimal.toml` wrote them. + pub patch_drop: BTreeSet, } impl TaskEnv { @@ -106,7 +138,7 @@ impl TaskEnv { /// `env_vars`. #[must_use] pub fn is_empty(&self) -> bool { - self.set.is_empty() && self.drop.is_empty() + self.set.is_empty() && self.drop.is_empty() && self.patch_drop.is_empty() } } @@ -280,6 +312,43 @@ mod tests { #[test] fn the_drop_carrier_is_not_under_the_value_prefix() { assert!(!TASK_ENV_DROP.starts_with(TASK_ENV_PREFIX)); + assert!(!TASK_PATCH_DROP.starts_with(TASK_ENV_PREFIX)); + } + + /// The patch drop list round-trips, and the paths on it are the raw + /// declared keys — `~/`-rooted or otherwise — so a removal matches the + /// `minimal.toml` entry it names. + #[test] + fn patch_drop_list_round_trips() { + let drops: BTreeSet = ["~/.claude".to_string(), "/etc/secrets".to_string()] + .into_iter() + .collect(); + let mut channel = BTreeMap::new(); + channel.insert(TASK_PATCH_DROP.to_string(), encode_drops(&drops)); + + assert_eq!(patch_drops_from_channel_env(&channel), drops); + // The carrier is not itself a task variable. + assert!(from_channel_env(&channel).is_empty()); + // And it is not the env-drop carrier: the two lists stay separate. + assert!(drops_from_channel_env(&channel).is_empty()); + } + + /// No patch drop list, an empty one, and a malformed one all mean + /// "remove nothing" — same fail-safe as the env drop list, and an + /// older client sends none at all. + #[test] + fn an_absent_or_unparseable_patch_drop_list_removes_nothing() { + let mut absent = BTreeMap::new(); + absent.insert("MINIMAL_SESSION_ID".to_string(), "an-id".to_string()); + assert!(patch_drops_from_channel_env(&absent).is_empty()); + + let mut empty = BTreeMap::new(); + empty.insert(TASK_PATCH_DROP.to_string(), encode_drops(&BTreeSet::new())); + assert!(patch_drops_from_channel_env(&empty).is_empty()); + + let mut junk = BTreeMap::new(); + junk.insert(TASK_PATCH_DROP.to_string(), "not json".to_string()); + assert!(patch_drops_from_channel_env(&junk).is_empty()); } /// No drop list, an empty one, and a malformed one all mean "remove diff --git a/crates/minimald/src/exec.rs b/crates/minimald/src/exec.rs index b99fcbcb10..ca17f3ec2b 100644 --- a/crates/minimald/src/exec.rs +++ b/crates/minimald/src/exec.rs @@ -116,6 +116,16 @@ pub struct TaskExec { /// daemon's own environment — the very indirection #585 removes. A /// dropped name has to be named. pub drop_env: BTreeSet, + /// Declared patch paths the client's `[patches]` policy ignored, to + /// be removed from the task's `patch.dir` / `patch.file` declarations + /// before anything is mounted. The keys are raw — exactly as + /// `minimal.toml` wrote them — because patch keys are never + /// interpolated, so a removal matches the declaration it names. + /// + /// Empty when the client sent none — an older `min`, or any caller + /// other than `min task run` — in which case the declared patches + /// apply as before. + pub patch_drop: BTreeSet, /// The client's invocation directory relative to the uploaded tree, /// already refused by [`minimald_rpc::exec::ExecRequest::parse`] if it /// is absolute or holds a `..`. A task that declares `inherit_cwd` @@ -414,6 +424,15 @@ async fn task_producer( for name in &exec.drop_env { task.vars.remove(name); } + // Patch removals join them: the client's `[patches]` gate decided + // these declared paths must not mount, and the keys are raw — + // never interpolated — so they match the declarations exactly. + // The daemon holds no policy; applying the client's verdicts + // here is the whole wire contract. + for key in &exec.patch_drop { + task.patch.dir.remove(key); + task.patch.file.remove(key); + } for (name, value) in &exec.env { task.vars .insert(name.clone(), mfile::EnvVarValue::Value(value.clone())); @@ -1872,6 +1891,10 @@ pub(crate) async fn handle_exec( trace_env.clone(), ); let drop_env = minimald_rpc::taskenv::drops_from_channel_env(&config.env_vars); + // Patch paths the client's policy dropped, same wire contract + // as `drop_env`: absent from an older client, meaning the + // declared patches apply as before. + let patch_drop = minimald_rpc::taskenv::patch_drops_from_channel_env(&config.env_vars); let span = span.clone(); session.channel_success(id)?; spawn(tracing::Instrument::instrument( @@ -1890,6 +1913,7 @@ pub(crate) async fn handle_exec( task: task.clone(), env: task_env, drop_env, + patch_drop, cwd, }, }; From 0156c1964d01f97e682b20e2c440c47b7b4f6c22 Mon Sep 17 00:00:00 2001 From: "gominimal-aw-bot[bot]" <281738952+gominimal-aw-bot[bot]@users.noreply.github.com> Date: Sat, 17 Oct 2026 19:24:44 -0700 Subject: [PATCH 02/21] fix(task): let a directory rule approve its contents and keep the refusal paths A rule naming a declared patch.dir now approves it whatever it holds; contained files can still deny or drop it. Without this the pasted [patches] allow snippet and the prompt's allow-always never settled a non-empty directory. The non-interactive lane reads the refused paths before propagating the gate's abort, so the allow snippet is reachable, and the interactive lane saves recorded rules before either gate's error propagates. --- crates/boxes/src/core/compose.rs | 37 +++++--- crates/boxes/src/core/compose/tests.rs | 91 ++++++++++++++++++ crates/minimal/src/task.rs | 122 +++++++++++++++++-------- 3 files changed, 201 insertions(+), 49 deletions(-) diff --git a/crates/boxes/src/core/compose.rs b/crates/boxes/src/core/compose.rs index f79182f1ec..704efb0cb7 100644 --- a/crates/boxes/src/core/compose.rs +++ b/crates/boxes/src/core/compose.rs @@ -1579,33 +1579,45 @@ fn check_task_patch_path( /// every file it currently holds. A directory that cannot be walked (missing /// for a future `create_if_missing` mount, or unreadable) is decided by its /// own path alone. +/// +/// Contained files can only make the entry stricter: a `deny` or `ignore` +/// on one denies or drops the whole entry, but the allow step is the +/// directory's own. A rule naming the declared directory, as the prompt +/// and the refusal snippet record it, therefore approves the entry +/// whatever it holds. Folding contained files' `NeedsApproval` in as well +/// would leave a non-empty directory undecidable by any exact-path rule. fn check_task_patch_dir( expanded: &ExpandedPatchesPolicy, source: &Source, dir: &camino::Utf8Path, ) -> crate::core::policy::PathDecision { - let mut verdict = check_task_patch_path(expanded, source, dir); + use crate::core::policy::PathDecision; + let own = check_task_patch_path(expanded, source, dir); + let mut contents = PathDecision::Allowed; // Best-effort name walk: any IO failure (a missing directory a // `create_if_missing` mount would create, a permission error) leaves // the entry's fate to the path check above. - let mut stack = vec![dir.to_path_buf()]; + let mut stack = vec![dir.as_std_path().to_path_buf()]; while let Some(cur) = stack.pop() { - let Ok(read) = std::fs::read_dir(cur.as_std_path()) else { + let Ok(read) = std::fs::read_dir(&cur) else { continue; }; for entry in read.flatten() { - let Ok(path) = camino::Utf8PathBuf::from_path_buf(entry.path()) else { - continue; - }; let is_dir = entry.file_type().is_ok_and(|t| t.is_dir()); if is_dir { - stack.push(path); + stack.push(entry.path()); } else { - verdict = verdict.combine(check_task_patch_path(expanded, source, &path)); + // Lossy rather than skipped: a non-UTF-8 name must still + // meet a `**` deny or ignore on its directory. + let path = camino::Utf8PathBuf::from(entry.path().to_string_lossy().into_owned()); + contents = contents.combine(check_task_patch_path(expanded, source, &path)); } } } - verdict + match contents { + PathDecision::Denied | PathDecision::Ignored => own.combine(contents), + PathDecision::NeedsApproval | PathDecision::Allowed => own, + } } /// A declared entry's decision: the file form checks its one path, the @@ -1639,9 +1651,10 @@ fn check_task_patch_entry( /// pattern to walk. A directory entry is checked twice — once as the /// declared path (a deny on the directory itself must deny the entry) and /// once per file the directory currently holds (a deny on a contained file -/// must deny the entry that would mount it), with the outcomes combined -/// by [`PathDecision::combine`]'s most-restrictive-first precedence. A -/// directory that cannot be read is decided by its own path alone. +/// must deny the entry that would mount it, an ignore on one drops it). The +/// allow step is the directory's own path, so a rule naming the declared +/// directory approves it however many files it holds. A directory that +/// cannot be read is decided by its own path alone. /// /// `~/`-rooted entries are expanded against `home_fallback` for the /// check; a `~` entry with no fallback routes to the hook (fail-closed). diff --git a/crates/boxes/src/core/compose/tests.rs b/crates/boxes/src/core/compose/tests.rs index 9266d66775..264a933069 100644 --- a/crates/boxes/src/core/compose/tests.rs +++ b/crates/boxes/src/core/compose/tests.rs @@ -2620,6 +2620,97 @@ mod gate_task_patch_paths { assert!(matches!(err, ComposeError::Denied { .. })); } + /// A rule naming the declared directory approves it with whatever it + /// holds: the allow step is the directory's own, which is the rule the + /// prompt records and the refusal snippet prints. + #[test] + fn an_exact_allow_on_a_non_empty_directory_allows_it() { + let tmp = tempfile::tempdir().unwrap(); + // Canonical, so the declared and resolved forms agree (macOS + // tempdirs sit behind the `/var` -> `/private/var` link). + let root = + camino::Utf8PathBuf::from_path_buf(std::fs::canonicalize(tmp.path()).unwrap()).unwrap(); + let cache = root.join("cache"); + std::fs::create_dir_all(cache.join("nested").as_std_path()).unwrap(); + std::fs::write(cache.join("a.txt").as_std_path(), "x").unwrap(); + std::fs::write(cache.join("nested/b.txt").as_std_path(), "x").unwrap(); + + let source = project_source(); + let entries = entries_for(&source, &[(cache.as_str(), false)]); + let policy = PatchesPolicy::default().with_allow(vec![cache.to_string()]); + let (verdicts, _) = gate_task_patch_paths(&entries, policy, None, &NoVars, None).unwrap(); + assert_eq!(verdicts, vec![NameVerdict::Allowed]); + } + + /// An ignore on a contained file still drops an allowed directory. + #[test] + fn a_directory_entry_is_dropped_by_an_ignored_contained_file() { + let tmp = tempfile::tempdir().unwrap(); + // Canonical, so the declared and resolved forms agree (macOS + // tempdirs sit behind the `/var` -> `/private/var` link). + let root = + camino::Utf8PathBuf::from_path_buf(std::fs::canonicalize(tmp.path()).unwrap()).unwrap(); + let cache = root.join("cache"); + std::fs::create_dir(cache.as_std_path()).unwrap(); + std::fs::write(cache.join("token").as_std_path(), "x").unwrap(); + + let source = project_source(); + let entries = entries_for(&source, &[(cache.as_str(), false)]); + let policy = PatchesPolicy::default() + .with_allow(vec![cache.to_string()]) + .with_ignore(vec![format!("{cache}/token")]); + let (verdicts, _) = gate_task_patch_paths(&entries, policy, None, &NoVars, None).unwrap(); + assert_eq!(verdicts, vec![NameVerdict::Ignored]); + } + + /// `UseRule` after the hook records the declared directory path, as + /// the interactive "allow always" does, settles a non-empty directory + /// rather than failing the hook contract. + #[test] + fn use_rule_with_a_recorded_directory_rule_allows_a_non_empty_directory() { + struct RecordDir(String); + impl crate::core::hooks::PolicyHooks for RecordDir { + fn on_var_unapproved( + &self, + _: crate::core::policy::VarsPolicy, + _: &[Unapproved<'_, str>], + ) -> HookResult { + panic!("var hook should not have been invoked") + } + fn on_patch_unapproved( + &self, + policy: PatchesPolicy, + _: &[Unapproved<'_, camino::Utf8Path>], + ) -> HookResult { + HookResult::decided_with_policy( + vec![ItemDecision::UseRule], + policy.with_allow(vec![self.0.clone()]), + ) + } + } + let tmp = tempfile::tempdir().unwrap(); + // Canonical, so the declared and resolved forms agree (macOS + // tempdirs sit behind the `/var` -> `/private/var` link). + let root = + camino::Utf8PathBuf::from_path_buf(std::fs::canonicalize(tmp.path()).unwrap()).unwrap(); + let cache = root.join("cache"); + std::fs::create_dir(cache.as_std_path()).unwrap(); + std::fs::write(cache.join("a.txt").as_std_path(), "x").unwrap(); + + let source = project_source(); + let entries = entries_for(&source, &[(cache.as_str(), false)]); + let hook = RecordDir(cache.to_string()); + let (verdicts, _) = gate_task_patch_paths( + &entries, + PatchesPolicy::default(), + Some(&hook), + &NoVars, + None, + ) + .unwrap(); + assert_eq!(verdicts, vec![NameVerdict::Allowed]); + } + #[test] fn a_directory_entry_denied_on_its_own_path_stays_denied() { let source = project_source(); diff --git a/crates/minimal/src/task.rs b/crates/minimal/src/task.rs index 047c4b472d..1f8448befa 100644 --- a/crates/minimal/src/task.rs +++ b/crates/minimal/src/task.rs @@ -402,9 +402,9 @@ fn denied_task_var_message(task_name: &str, name: &str, policy_path: &std::path: /// tests. fn denied_task_patch_message(task_name: &str, path: &str, policy_path: &std::path::Path) -> String { format!( - "task '{task_name}' declares `patch.{path}`, but it is denied by \ - `[patches] deny` in {policy}; remove the declaration, or the deny \ - rule if this task should mount it", + "task '{task_name}' declares the patch path `{path}`, but it is \ + denied by `[patches] deny` in {policy}; remove the declaration, or \ + the deny rule if this task should mount it", policy = policy_path.display(), ) } @@ -492,6 +492,44 @@ fn resolve_task_patches( Ok(drops) } +/// The non-interactive lane of [`resolve_task_patches`]: gate against a +/// collect-and-refuse hook, and turn a refusal into the `[patches] allow` +/// snippet the operator pastes. The recorded paths are read before the +/// gate's own result, which is the abort error once the hook refused. +fn resolve_task_patches_non_interactive( + task: &mfile::Task, + task_name: &str, + patches_policy: boxes::core::policy::PatchesPolicy, + policy_path: &std::path::Path, + source: &boxes::core::source::Source, + resolved_env: &minimald_rpc::taskenv::TaskEnv, +) -> Result, anyhow::Error> { + let hooks = RefuseAndRecord::default(); + let drops = resolve_task_patches( + task, + task_name, + patches_policy, + policy_path, + source, + &hooks, + resolved_env, + ); + let refused = hooks.recorded_patch_paths(); + if !refused.is_empty() { + let count = refused.len(); + let snippet = refused_patches_snippet(&refused); + bail!( + "task '{task_name}' declares {count} patch{es} that your policy does \ + not allow, and stdin/stderr is not a terminal.\n\n\ + Add the following to {path}:\n\n{snippet}\n\ + Then re-run this command.", + path = policy_path.display(), + es = if count == 1 { "" } else { "es" }, + ); + } + drops +} + /// The whitespace rejection body: the name is debug-quoted so the offending /// whitespace is visible. Split out for unit tests. fn untrimmed_task_message(task: &str) -> String { @@ -764,32 +802,15 @@ pub async fn cmd_task_run(global: &GlobalArgs, args: TaskRunArgs) -> Result<(), s = if count == 1 { "" } else { "s" }, ); } - let task_env = task_env?; - let patch_drops = resolve_task_patches( + let mut task_env = task_env?; + task_env.patch_drop = resolve_task_patches_non_interactive( &declared, &args.task, user_policy.patches().clone(), &policy_path, &source, - &hooks, &task_env, )?; - let refused_patches = hooks.recorded_patch_paths(); - if !refused_patches.is_empty() { - let count = refused_patches.len(); - let snippet = refused_patches_snippet(&refused_patches); - bail!( - "task '{task}' declares {count} patch{es} that your policy does \ - not allow, and stdin/stderr is not a terminal.\n\n\ - Add the following to {path}:\n\n{snippet}\n\ - Then re-run this command.", - task = args.task, - path = policy_path.display(), - es = if count == 1 { "" } else { "es" }, - ); - } - let mut task_env = task_env; - task_env.patch_drop = patch_drops; (task_env, user_policy) } else { let hooks = crate::prompt::InteractivePrompt::new(&policy_path, user_policy.clone()); @@ -802,19 +823,22 @@ pub async fn cmd_task_run(global: &GlobalArgs, args: TaskRunArgs) -> Result<(), &hooks, |k| std::env::var(k), ); - let task_env = task_env?; // Same lane for patches, against the same interactive hook, so a // rule the user records for a patch lands in the same policy - // save as a rule recorded for a variable. - let patch_drops = resolve_task_patches( - &declared, - &args.task, - user_policy.patches().clone(), - &policy_path, - &source, - &hooks, - &task_env, - )?; + // save as a rule recorded for a variable. Gated only once the + // vars resolved; either error is held until after the save. + let gated = task_env.and_then(|mut task_env| { + task_env.patch_drop = resolve_task_patches( + &declared, + &args.task, + user_policy.patches().clone(), + &policy_path, + &source, + &hooks, + &task_env, + )?; + Ok(task_env) + }); // Persist before propagating a refusal: a rule the user chose to // record is theirs whether or not this run goes on to fail. let after = hooks.into_final_policy(); @@ -824,9 +848,7 @@ pub async fn cmd_task_run(global: &GlobalArgs, args: TaskRunArgs) -> Result<(), Err(e) => eprintln!("warning: failed to update {}: {e}", policy_path.display()), } } - let mut task_env = task_env; - task_env.patch_drop = patch_drops; - (task_env, after) + (gated?, after) }; crate::ensure_daemon(global)?; @@ -1887,7 +1909,7 @@ mod tests { let msg = err.to_string(); assert!( - msg.contains("patch./etc/passwd"), + msg.contains("patch path `/etc/passwd`"), "names the declared path: {msg}" ); assert!(msg.contains("[patches] deny"), "names the rule: {msg}"); @@ -1934,6 +1956,32 @@ mod tests { ); } + /// The non-interactive lane surfaces the `[patches] allow` snippet, + /// not the hook's abort: the recorded paths are read before the gate's + /// own error is propagated. + #[test] + fn the_non_interactive_patch_refusal_carries_the_allow_snippet() { + let task = task_from_toml( + "[tasks.t]\nexec = 'true'\n[tasks.t.patch.file]\n\"/opt/tool/bin\" = \"ro\"\n", + ); + + let err = resolve_task_patches_non_interactive( + &task, + "t", + boxes::core::policy::PatchesPolicy::default(), + &policy_path_fixture(), + &project_source(), + &minimald_rpc::taskenv::TaskEnv::default(), + ) + .expect_err("an unapproved patch must fail the run"); + + let msg = err.to_string(); + assert!(msg.contains("task 't' declares 1 patch "), "{msg}"); + assert!(msg.contains("[patches]"), "carries the snippet: {msg}"); + assert!(msg.contains("/opt/tool/bin"), "names the path: {msg}"); + assert!(msg.contains("user_policy.toml"), "names the file: {msg}"); + } + /// An ignored patch path lands in the drop list the daemon removes /// from the mount set, keyed exactly as declared. #[test] From 4e4fa438f508464001b6fee956bfed03f5d4e41d Mon Sep 17 00:00:00 2001 From: "gominimal-aw-bot[bot]" <281738952+gominimal-aw-bot[bot]@users.noreply.github.com> Date: Sat, 17 Oct 2026 20:00:25 -0700 Subject: [PATCH 03/21] fix(task): require a patch verdict daemon-side and gate min session run The daemon now mounts only the patch keys the client's [patches] verdict allows, and refuses a task that declares patches without one, so an older client or an ungated lane fails closed. min session run now gates the session project's task patches and sends the verdict over ssh. The gate refuses keys with `.` or `..` segments, and checks a declared absolute path where it resolves (deepest existing ancestor) as a tightening-only backstop. It no longer walks or resolves `~/` entries, which the daemon mounts from the session home, and a contained-file ignore no longer drops a whole directory. The non-interactive refusal names --no-input when that caused it. --- crates/boxes/src/core/compose.rs | 247 ++++++++++++++++++------- crates/boxes/src/core/compose/tests.rs | 162 +++++++++++++++- crates/minimal-client/src/attach.rs | 53 ++++++ crates/minimal-client/src/lib.rs | 28 +-- crates/minimal/src/cmd/session.rs | 38 +++- crates/minimal/src/task.rs | 231 ++++++++++++++++++++--- crates/minimald-rpc/src/taskenv.rs | 176 ++++++++++++------ crates/minimald/src/exec.rs | 157 +++++++++++++--- docs/reference/tasks.md | 8 +- docs/reference/user-policy.md | 27 +++ 10 files changed, 926 insertions(+), 201 deletions(-) diff --git a/crates/boxes/src/core/compose.rs b/crates/boxes/src/core/compose.rs index 704efb0cb7..d4d072f600 100644 --- a/crates/boxes/src/core/compose.rs +++ b/crates/boxes/src/core/compose.rs @@ -523,6 +523,12 @@ pub enum ComposeError { /// metadata, not an error. #[error("policy denied `{what}` (from {from})")] Denied { what: String, from: Source }, + /// A task's declared `patch.dir` / `patch.file` key holds a `.` or + /// `..` segment, so the policy cannot tell which path it mounts: the + /// OS resolves `..` after any symlinked parent. Surfaces from + /// [`gate_task_patch_paths`]. + #[error("the patch path `{what}` (from {from}) holds a `.` or `..` segment")] + TaskPatchDotSegment { what: String, from: Source }, /// User cancelled at the prompt. #[error("user aborted session construction")] Aborted, @@ -1549,25 +1555,49 @@ pub struct TaskPatchEntry<'a> { pub source: &'a Source, } -/// One declared path's [`PathDecision`](crate::core::policy::PathDecision): -/// the declared form, plus the canonicalized form when it differs, -/// combined. Canonicalization is best-effort — an entry that does not -/// exist yet (`create_if_missing`) is checked by its declared form alone. -fn check_task_patch_path( +/// Upper bound on the entries a directory walk in [`check_task_patch_dir`] +/// visits. The walk is a best-effort deny probe of this machine's view of +/// the directory, so a huge tree stops it rather than stalling every +/// `min task run`. +const TASK_PATCH_DIR_WALK_LIMIT: usize = 10_000; + +/// Whether a declared key holds a `.` or `..` segment. The daemon hands +/// the raw key to the OS, which resolves `..` after any symlinked parent, +/// so no lexical collapse here could say what the mount will reach. Such +/// keys are refused instead. +fn has_dot_segment(declared: &str) -> bool { + declared.split('/').any(|seg| seg == "." || seg == "..") +} + +/// The path `path` reaches on this machine: its deepest existing ancestor +/// canonicalized, with the missing tail joined back on. So a +/// `create_if_missing` entry under a symlinked parent resolves to the +/// directory the parent points at. `None` when it resolves to itself or +/// to nothing. +fn resolve_existing_prefix(path: &camino::Utf8Path) -> Option { + let mut tail: Vec<&str> = Vec::new(); + let mut cur = path; + loop { + if let Ok(canonical) = std::fs::canonicalize(cur.as_std_path()) { + let mut out = camino::Utf8PathBuf::from_path_buf(canonical).ok()?; + for seg in tail.iter().rev() { + out.push(seg); + } + return (out != path).then_some(out); + } + tail.push(cur.file_name()?); + cur = cur.parent()?; + } +} + +/// One path's decision against the expanded policy, as written. +fn decide_task_patch_path( expanded: &ExpandedPatchesPolicy, source: &Source, path: &camino::Utf8Path, ) -> crate::core::policy::PathDecision { let item = NameItem { source }; - let canonical = std::fs::canonicalize(path.as_std_path()) - .ok() - .and_then(|p| { - camino::Utf8PathBuf::from_path_buf(p) - .ok() - .filter(|c| c != path) - }); - let target = path.to_path_buf(); - match expanded.check(canonical.as_deref(), &target, item) { + match expanded.check(None, path, item) { CheckOutcome::Decided(Decision::Allowed(_)) => crate::core::policy::PathDecision::Allowed, CheckOutcome::Decided(Decision::Ignored) => crate::core::policy::PathDecision::Ignored, CheckOutcome::Decided(Decision::Denied(_)) => crate::core::policy::PathDecision::Denied, @@ -1575,62 +1605,104 @@ fn check_task_patch_path( } } +/// One declared path's [`PathDecision`](crate::core::policy::PathDecision). +/// +/// The declared form decides: it is the string the daemon is handed, and +/// on a VM-backed host the daemon resolves it in a filesystem this process +/// cannot see. When `resolve` is set, the form the path reaches on this +/// machine ([`resolve_existing_prefix`]) is checked too, and can only make +/// the entry stricter: a `deny` or `ignore` on the resolved form applies, +/// but its allow step does not. That keeps a symlink, including a +/// symlinked parent of an entry that does not exist yet, from carrying a +/// path past a deny on its target. It does not let this machine's view +/// raise prompts the daemon's view would not, such as macOS's +/// `/tmp` → `/private/tmp`. +fn check_task_patch_path( + expanded: &ExpandedPatchesPolicy, + source: &Source, + path: &camino::Utf8Path, + resolve: bool, +) -> crate::core::policy::PathDecision { + use crate::core::policy::PathDecision; + let own = decide_task_patch_path(expanded, source, path); + if !resolve || own == PathDecision::Denied { + return own; + } + match resolve_existing_prefix(path).map(|r| decide_task_patch_path(expanded, source, &r)) { + Some(stricter @ (PathDecision::Denied | PathDecision::Ignored)) => own.combine(stricter), + _ => own, + } +} + /// A declared directory entry's decision: the directory's own path, then -/// every file it currently holds. A directory that cannot be walked (missing -/// for a future `create_if_missing` mount, or unreadable) is decided by its -/// own path alone. +/// a deny probe over what it currently holds on this machine. +/// +/// Contained files can only deny the entry. A `deny` on one denies the +/// whole entry, since mounting the directory would expose it. An `ignore` +/// on one does not apply: a bind mount cannot leave a single file out, and +/// dropping the whole directory over one ignored file would remove a mount +/// the user allowed without a word. The allow step is the directory's own, +/// so a rule naming the declared directory, as the prompt and the refusal +/// snippet record it, approves the entry whatever it holds. /// -/// Contained files can only make the entry stricter: a `deny` or `ignore` -/// on one denies or drops the whole entry, but the allow step is the -/// directory's own. A rule naming the declared directory, as the prompt -/// and the refusal snippet record it, therefore approves the entry -/// whatever it holds. Folding contained files' `NeedsApproval` in as well -/// would leave a non-empty directory undecidable by any exact-path rule. +/// The probe is best-effort: it stops at the first denial and after +/// [`TASK_PATCH_DIR_WALK_LIMIT`] entries, and a directory that cannot be +/// read (missing for a `create_if_missing` mount, or unreadable) is +/// decided by its own path alone. Only an entry checked with `resolve` +/// is walked; see [`gate_task_patch_paths`] for why `~/` entries are not. fn check_task_patch_dir( expanded: &ExpandedPatchesPolicy, source: &Source, dir: &camino::Utf8Path, + resolve: bool, ) -> crate::core::policy::PathDecision { use crate::core::policy::PathDecision; - let own = check_task_patch_path(expanded, source, dir); - let mut contents = PathDecision::Allowed; - // Best-effort name walk: any IO failure (a missing directory a - // `create_if_missing` mount would create, a permission error) leaves - // the entry's fate to the path check above. + let own = check_task_patch_path(expanded, source, dir, resolve); + if !resolve || own == PathDecision::Denied { + return own; + } + let mut seen = 0usize; let mut stack = vec![dir.as_std_path().to_path_buf()]; while let Some(cur) = stack.pop() { let Ok(read) = std::fs::read_dir(&cur) else { continue; }; for entry in read.flatten() { - let is_dir = entry.file_type().is_ok_and(|t| t.is_dir()); - if is_dir { + seen += 1; + if seen > TASK_PATCH_DIR_WALK_LIMIT { + return own; + } + let file_type = entry.file_type().ok(); + if file_type.is_some_and(|t| t.is_dir()) { stack.push(entry.path()); - } else { - // Lossy rather than skipped: a non-UTF-8 name must still - // meet a `**` deny or ignore on its directory. - let path = camino::Utf8PathBuf::from(entry.path().to_string_lossy().into_owned()); - contents = contents.combine(check_task_patch_path(expanded, source, &path)); + continue; + } + // Lossy rather than skipped: a non-UTF-8 name must still + // meet a `**` deny on its directory. + let path = camino::Utf8PathBuf::from(entry.path().to_string_lossy().into_owned()); + // Only a symlink reaches somewhere other than its own path, + // so only a symlink pays for the resolution. + let is_link = file_type.is_some_and(|t| t.is_symlink()); + if check_task_patch_path(expanded, source, &path, is_link) == PathDecision::Denied { + return PathDecision::Denied; } } } - match contents { - PathDecision::Denied | PathDecision::Ignored => own.combine(contents), - PathDecision::NeedsApproval | PathDecision::Allowed => own, - } + own } /// A declared entry's decision: the file form checks its one path, the -/// directory form also checks the files it currently holds. +/// directory form also probes the files it currently holds. fn check_task_patch_entry( expanded: &ExpandedPatchesPolicy, entry: &TaskPatchEntry<'_>, path: &camino::Utf8Path, + resolve: bool, ) -> crate::core::policy::PathDecision { if entry.is_file { - check_task_patch_path(expanded, entry.source, path) + check_task_patch_path(expanded, entry.source, path, resolve) } else { - check_task_patch_dir(expanded, entry.source, path) + check_task_patch_dir(expanded, entry.source, path, resolve) } } @@ -1648,24 +1720,36 @@ fn check_task_patch_entry( /// Unlike [`gate_patches`], which checks each file a walked patch source /// produced, this checks the *declared* paths themselves: a task's patch /// is a host path the sandbox mounts (or creates) directly, not a source -/// pattern to walk. A directory entry is checked twice — once as the -/// declared path (a deny on the directory itself must deny the entry) and -/// once per file the directory currently holds (a deny on a contained file -/// must deny the entry that would mount it, an ignore on one drops it). The -/// allow step is the directory's own path, so a rule naming the declared -/// directory approves it however many files it holds. A directory that -/// cannot be read is decided by its own path alone. +/// pattern to walk. The declared string decides, since it is what the +/// daemon is handed: the allow step matches it as written, so a rule +/// naming the declared directory approves it however many files it holds. +/// +/// A key holding a `.` or `..` segment is refused outright +/// ([`ComposeError::TaskPatchDotSegment`]): the OS resolves `..` after any +/// symlinked parent, so the declared string would not say what it mounts. /// -/// `~/`-rooted entries are expanded against `home_fallback` for the -/// check; a `~` entry with no fallback routes to the hook (fail-closed). -/// Each path is also checked in canonicalized form, so a symlink cannot -/// evade a deny rule that names its target. +/// An absolute entry is also checked as it resolves on this machine, and +/// a directory entry is probed for contained files a `deny` names. Both +/// can only make the entry stricter (see [`check_task_patch_path`] and +/// [`check_task_patch_dir`]), so a symlink, including a symlinked parent +/// of an entry that does not exist yet, cannot carry it past a deny on +/// its target. On a VM-backed host this machine is not the daemon's, so +/// the extra checks are a best-effort backstop there. +/// +/// `~/`-rooted entries are matched as declared, with `~/` expanded against +/// `home_fallback` the same way the policy's own `~` is. They are neither +/// resolved nor walked: the daemon mounts `~/` from the session's home, +/// not this machine's, so what this machine's home holds says nothing +/// about the mount. A `~` entry with no fallback routes to the hook +/// (fail-closed). /// /// # Errors /// /// - [`ComposeError::Denied`] — a `deny` rule matched. Returned from the /// first denial found, before any hook is consulted, so a forbidden /// path is never preceded by a prompt about its neighbours. +/// - [`ComposeError::TaskPatchDotSegment`] — a declared key holds a `.` +/// or `..` segment. Checked before anything else. /// - [`ComposeError::HookRequired`] — an entry needed approval and there /// was no hook to ask. /// - [`ComposeError::Aborted`] — the hook cancelled. @@ -1692,6 +1776,18 @@ pub fn gate_task_patch_paths( _ => camino::Utf8PathBuf::from(declared), } }; + // Only an absolute key names a path on the daemon's filesystem that + // this machine can look at; a `~/` key names the session's home. + let resolvable = |declared: &str| declared.starts_with('/'); + + // Refused before any decision, so no prompt is ever about a path whose + // meaning the gate cannot pin down. + if let Some(entry) = entries.iter().find(|e| has_dot_segment(e.declared)) { + return Err(ComposeError::TaskPatchDotSegment { + what: entry.declared.to_owned(), + from: entry.source.clone(), + }); + } // Pass 1: categorize per entry. Undecided entries are seeded // `Ignored` and queued; pass 3 overwrites every one. The placeholder @@ -1701,7 +1797,7 @@ pub fn gate_task_patch_paths( let mut unapproved: Vec = Vec::new(); for (i, entry) in entries.iter().enumerate() { let path = expand_declared(entry.declared); - let verdict = check_task_patch_entry(&expanded, entry, &path); + let verdict = check_task_patch_entry(&expanded, entry, &path, resolvable(entry.declared)); match verdict { crate::core::policy::PathDecision::Allowed => verdicts.push(NameVerdict::Allowed), crate::core::policy::PathDecision::Ignored => verdicts.push(NameVerdict::Ignored), @@ -1741,30 +1837,37 @@ pub fn gate_task_patch_paths( if policy_updated { expanded = policy.expand_with(resolved_vars, home_fallback)?; } - // Pass 3: apply. + // Pass 3: apply. Only a `UseRule` answer needs the entry decided + // again, against the policy as the hook amended it. for (&i, decision) in unapproved.iter().zip(decisions) { let entry = &entries[i]; - let path = expand_declared(entry.declared); - let verdict = check_task_patch_entry(&expanded, entry, &path); verdicts[i] = match decision { ItemDecision::AllowOnce => NameVerdict::Allowed, ItemDecision::IgnoreOnce => NameVerdict::Ignored, - ItemDecision::UseRule => match verdict { - crate::core::policy::PathDecision::Allowed => NameVerdict::Allowed, - crate::core::policy::PathDecision::Ignored => NameVerdict::Ignored, - crate::core::policy::PathDecision::Denied => { - return Err(ComposeError::Denied { - what: entry.declared.to_owned(), - from: entry.source.clone(), - }); - } - crate::core::policy::PathDecision::NeedsApproval => { - return Err(ComposeError::use_rule_undecided( - HookDomain::Patch, - format!("source path `{}`", entry.declared), - )); + ItemDecision::UseRule => { + let path = expand_declared(entry.declared); + match check_task_patch_entry( + &expanded, + entry, + &path, + resolvable(entry.declared), + ) { + crate::core::policy::PathDecision::Allowed => NameVerdict::Allowed, + crate::core::policy::PathDecision::Ignored => NameVerdict::Ignored, + crate::core::policy::PathDecision::Denied => { + return Err(ComposeError::Denied { + what: entry.declared.to_owned(), + from: entry.source.clone(), + }); + } + crate::core::policy::PathDecision::NeedsApproval => { + return Err(ComposeError::use_rule_undecided( + HookDomain::Patch, + format!("source path `{}`", entry.declared), + )); + } } - }, + } }; } } diff --git a/crates/boxes/src/core/compose/tests.rs b/crates/boxes/src/core/compose/tests.rs index 264a933069..8e10d7cefc 100644 --- a/crates/boxes/src/core/compose/tests.rs +++ b/crates/boxes/src/core/compose/tests.rs @@ -2642,25 +2642,169 @@ mod gate_task_patch_paths { assert_eq!(verdicts, vec![NameVerdict::Allowed]); } - /// An ignore on a contained file still drops an allowed directory. + /// An ignore on a contained file does not apply to the directory: a + /// bind mount cannot leave one file out, and dropping the whole entry + /// over it would remove a mount the user allowed without a word. #[test] - fn a_directory_entry_is_dropped_by_an_ignored_contained_file() { + fn an_ignored_contained_file_leaves_an_allowed_directory_alone() { let tmp = tempfile::tempdir().unwrap(); - // Canonical, so the declared and resolved forms agree (macOS - // tempdirs sit behind the `/var` -> `/private/var` link). - let root = - camino::Utf8PathBuf::from_path_buf(std::fs::canonicalize(tmp.path()).unwrap()).unwrap(); + let root = canonical_root(&tmp); let cache = root.join("cache"); std::fs::create_dir(cache.as_std_path()).unwrap(); - std::fs::write(cache.join("token").as_std_path(), "x").unwrap(); + std::fs::write(cache.join(".DS_Store").as_std_path(), "x").unwrap(); let source = project_source(); let entries = entries_for(&source, &[(cache.as_str(), false)]); let policy = PatchesPolicy::default() .with_allow(vec![cache.to_string()]) - .with_ignore(vec![format!("{cache}/token")]); + .with_ignore(vec!["**/.DS_Store".to_string()]); let (verdicts, _) = gate_task_patch_paths(&entries, policy, None, &NoVars, None).unwrap(); - assert_eq!(verdicts, vec![NameVerdict::Ignored]); + assert_eq!(verdicts, vec![NameVerdict::Allowed]); + } + + /// A tempdir with its symlinks resolved, so the declared and resolved + /// forms of a path under it agree (macOS tempdirs sit behind the + /// `/var` -> `/private/var` link). + fn canonical_root(tmp: &tempfile::TempDir) -> camino::Utf8PathBuf { + camino::Utf8PathBuf::from_path_buf(std::fs::canonicalize(tmp.path()).unwrap()).unwrap() + } + + /// A `..` segment is refused outright, whatever the policy says: the + /// literal string `/tmp/../home/u/.ssh/authorized_keys2` matches a + /// `/tmp/**` allow and misses a `~/.ssh/**` deny, yet the OS writes + /// into `.ssh`. + #[test] + fn a_dot_dot_segment_is_refused_before_the_policy_decides() { + let source = project_source(); + for declared in [ + "/tmp/../home/u/.ssh/authorized_keys2", + "/tmp/./x", + "~/../u/.ssh", + ] { + let entries = entries_for(&source, &[(declared, true)]); + let policy = PatchesPolicy::default() + .with_allow(vec!["/tmp/**".to_string()]) + .with_deny(vec!["/home/u/.ssh/**".to_string()]); + let err = gate_task_patch_paths(&entries, policy, None, &NoVars, Some("/home/u")) + .unwrap_err(); + assert!( + matches!(err, ComposeError::TaskPatchDotSegment { ref what, .. } if what == declared), + "{declared}: {err}" + ); + } + } + + /// A `create_if_missing` entry that does not exist yet, under a + /// symlinked parent, is checked where the parent points: a deny on + /// the target applies though the declared string matches only an + /// allow. + #[cfg(unix)] + #[test] + fn a_missing_entry_under_a_symlinked_parent_meets_the_targets_deny() { + let tmp = tempfile::tempdir().unwrap(); + let root = canonical_root(&tmp); + let ssh = root.join("home/.ssh"); + std::fs::create_dir_all(ssh.as_std_path()).unwrap(); + std::fs::create_dir(root.join("tmp").as_std_path()).unwrap(); + let link = root.join("tmp/link"); + std::os::unix::fs::symlink(ssh.as_std_path(), link.as_std_path()).unwrap(); + let declared = link.join("authorized_keys2"); + assert!(!declared.as_std_path().exists()); + + let source = project_source(); + let entries = entries_for(&source, &[(declared.as_str(), true)]); + let policy = PatchesPolicy::default() + .with_allow(vec![format!("{root}/tmp/**")]) + .with_deny(vec![format!("{ssh}/**")]); + let err = gate_task_patch_paths(&entries, policy, None, &NoVars, None).unwrap_err(); + assert!(matches!(err, ComposeError::Denied { .. }), "{err}"); + } + + /// A declared path that is itself a symlink meets a deny on its + /// target. + #[cfg(unix)] + #[test] + fn a_symlinked_entry_meets_the_targets_deny() { + let tmp = tempfile::tempdir().unwrap(); + let root = canonical_root(&tmp); + let ssh = root.join("home/.ssh"); + std::fs::create_dir_all(ssh.as_std_path()).unwrap(); + std::fs::write(ssh.join("id").as_std_path(), "x").unwrap(); + std::fs::create_dir(root.join("tmp").as_std_path()).unwrap(); + let key = root.join("tmp/key"); + std::os::unix::fs::symlink(ssh.join("id").as_std_path(), key.as_std_path()).unwrap(); + + let source = project_source(); + let entries = entries_for(&source, &[(key.as_str(), true)]); + let policy = PatchesPolicy::default() + .with_allow(vec![format!("{root}/tmp/**")]) + .with_deny(vec![format!("{ssh}/**")]); + let err = gate_task_patch_paths(&entries, policy, None, &NoVars, None).unwrap_err(); + assert!(matches!(err, ComposeError::Denied { .. }), "{err}"); + } + + /// A directory entry holding a symlink to a denied target is denied. + #[cfg(unix)] + #[test] + fn a_directory_holding_a_symlink_to_a_denied_target_is_denied() { + let tmp = tempfile::tempdir().unwrap(); + let root = canonical_root(&tmp); + let ssh = root.join("home/.ssh"); + std::fs::create_dir_all(ssh.as_std_path()).unwrap(); + std::fs::write(ssh.join("id").as_std_path(), "x").unwrap(); + let cache = root.join("proj/cache"); + std::fs::create_dir_all(cache.as_std_path()).unwrap(); + std::os::unix::fs::symlink(ssh.join("id").as_std_path(), cache.join("k").as_std_path()) + .unwrap(); + + let source = project_source(); + let entries = entries_for(&source, &[(cache.as_str(), false)]); + let policy = PatchesPolicy::default() + .with_allow(vec![cache.to_string()]) + .with_deny(vec![format!("{ssh}/**")]); + let err = gate_task_patch_paths(&entries, policy, None, &NoVars, None).unwrap_err(); + assert!(matches!(err, ComposeError::Denied { .. }), "{err}"); + } + + /// The resolved form only tightens: an allow on the declared string + /// decides, so a symlinked prefix (macOS's `/tmp` -> `/private/tmp`) + /// does not turn an allowed entry into a prompt. + #[cfg(unix)] + #[test] + fn a_symlinked_prefix_does_not_unsettle_an_allow_on_the_declared_path() { + let tmp = tempfile::tempdir().unwrap(); + let root = canonical_root(&tmp); + std::fs::create_dir(root.join("real").as_std_path()).unwrap(); + let alias = root.join("alias"); + std::os::unix::fs::symlink(root.join("real").as_std_path(), alias.as_std_path()).unwrap(); + let declared = alias.join("tool"); + + let source = project_source(); + let entries = entries_for(&source, &[(declared.as_str(), true)]); + let policy = PatchesPolicy::default().with_allow(vec![format!("{alias}/**")]); + let (verdicts, _) = gate_task_patch_paths(&entries, policy, None, &NoVars, None).unwrap(); + assert_eq!(verdicts, vec![NameVerdict::Allowed]); + } + + /// A `~/` entry is matched as declared and never walked: the daemon + /// mounts `~/` from the session's home, so a denied file in this + /// machine's home says nothing about the mount. + #[test] + fn a_tilde_directory_is_not_walked() { + let tmp = tempfile::tempdir().unwrap(); + let home = canonical_root(&tmp); + let app = home.join(".config/app"); + std::fs::create_dir_all(app.as_std_path()).unwrap(); + std::fs::write(app.join("secret").as_std_path(), "x").unwrap(); + + let source = project_source(); + let entries = entries_for(&source, &[("~/.config/app", false)]); + let policy = PatchesPolicy::default() + .with_allow(vec!["~/.config/app".to_string()]) + .with_deny(vec!["~/.config/app/secret".to_string()]); + let (verdicts, _) = + gate_task_patch_paths(&entries, policy, None, &NoVars, Some(home.as_str())).unwrap(); + assert_eq!(verdicts, vec![NameVerdict::Allowed]); } /// `UseRule` after the hook records the declared directory path, as diff --git a/crates/minimal-client/src/attach.rs b/crates/minimal-client/src/attach.rs index 09de38f5b7..f710eebcc9 100644 --- a/crates/minimal-client/src/attach.rs +++ b/crates/minimal-client/src/attach.rs @@ -104,6 +104,22 @@ pub fn attach_command( id: boxes::SessionId, wire: Option<&str>, session_keys: Option<&boxes::keys::SessionKeys>, +) -> Result { + attach_command_with_env(sock, id, wire, session_keys, &[]) +} + +/// [`attach_command`], plus `channel_env`: extra variables sent on the +/// channel ahead of the exec request, each set on ssh and named in a +/// `SendEnv` option. `min session run` carries a task's `[patches]` +/// verdict ([`minimald_rpc::taskenv::TASK_PATCH_VERDICT`]) this way, which +/// the daemon reads from the channel config like the native client's +/// `set_env`. +pub fn attach_command_with_env( + sock: &Path, + id: boxes::SessionId, + wire: Option<&str>, + session_keys: Option<&boxes::keys::SessionKeys>, + channel_env: &[(&str, &str)], ) -> Result { // ProxyCommand points at our own `proxy` subcommand so we don't // depend on socat or nc being installed. @@ -136,6 +152,10 @@ pub fn attach_command( let (trace_var, trace_value) = trace_env(); ssh.env(trace_var, trace_value); ssh.args(["-o", &format!("SendEnv={trace_var}")]); + for (name, value) in channel_env { + ssh.env(name, value); + ssh.args(["-o", &format!("SendEnv={name}")]); + } ssh.args([ "-o", "SendEnv=MINIMAL_SESSION_ID", @@ -1083,6 +1103,39 @@ mod tests { } } + /// Channel env rides ahead of the command: each variable is set on ssh + /// and named in a `SendEnv` option before the host alias, so ssh sends + /// it as an env request rather than as part of the remote command. + #[test] + fn channel_env_is_set_and_sent_before_the_command() { + let sock = PathBuf::from("/tmp/x/providers/local-minimald0/ssh.sock"); + let cmd = attach_command_with_env( + &sock, + boxes::SessionId::nil(), + Some("wire"), + None, + &[("MINIMAL_TASK_PATCH_VERDICT", r#"{"allow":[],"drop":[]}"#)], + ) + .unwrap(); + let args: Vec<_> = cmd + .get_args() + .map(|a| a.to_string_lossy().into_owned()) + .collect(); + let send = args + .iter() + .position(|a| a == "SendEnv=MINIMAL_TASK_PATCH_VERDICT") + .expect("named in a SendEnv option"); + let host = args + .iter() + .position(|a| a == "local-minimald0") + .expect("host alias"); + assert!(send < host, "options precede the host: {args:?}"); + assert_eq!(args.last().map(String::as_str), Some("wire")); + assert!(cmd.get_envs().any(|(k, v)| { + k == "MINIMAL_TASK_PATCH_VERDICT" && v.is_some_and(|v| v == r#"{"allow":[],"drop":[]}"#) + })); + } + /// Every attach bounds its connect and handshake with the shared deadline; /// only the non-interactive exec path adds keepalives, so a peer that /// stops answering ends the exec instead of hanging it. diff --git a/crates/minimal-client/src/lib.rs b/crates/minimal-client/src/lib.rs index a29b1758f9..fd96560bb2 100644 --- a/crates/minimal-client/src/lib.rs +++ b/crates/minimal-client/src/lib.rs @@ -591,8 +591,8 @@ impl Client { /// [`TASK_ENV_PREFIX`](minimald_rpc::taskenv::TASK_ENV_PREFIX), the /// variable names to remove under /// [`TASK_ENV_DROP`](minimald_rpc::taskenv::TASK_ENV_DROP), and the - /// declared patch paths the policy ignored under - /// [`TASK_PATCH_DROP`](minimald_rpc::taskenv::TASK_PATCH_DROP). Only + /// `[patches]` verdict on its declared patch paths under + /// [`TASK_PATCH_VERDICT`](minimald_rpc::taskenv::TASK_PATCH_VERDICT). Only /// [`ExecRequest::TaskRun`](minimald_rpc::exec::ExecRequest::TaskRun) has /// any to send; every other caller passes an empty /// [`TaskEnv`](minimald_rpc::taskenv::TaskEnv) and the daemon behaves @@ -647,19 +647,21 @@ impl Client { .await .context("set task env drop list")?; } - // Same contract for the patch entries the client's policy dropped: - // the raw declared keys the daemon removes from the task's `patch` - // maps before mounting. Absent means the client gated nothing — - // or predates the gate. - if !task_env.patch_drop.is_empty() { - channel - .set_env( - true, - minimald_rpc::taskenv::TASK_PATCH_DROP, - minimald_rpc::taskenv::encode_drops(&task_env.patch_drop), + // The patch verdict is the opposite: sent whenever the client gated, + // empty or not, because a daemon refuses a task that declares + // patches without one. + if let Some(verdict) = &task_env.patch { + let encoded = minimald_rpc::taskenv::encode_patch_verdict(verdict).map_err(|len| { + anyhow::anyhow!( + "the task's patch declarations are too large to send ({len} bytes, \ + limit {}); declare fewer `patch` entries", + minimald_rpc::taskenv::TASK_PATCH_VERDICT_MAX_BYTES ) + })?; + channel + .set_env(true, minimald_rpc::taskenv::TASK_PATCH_VERDICT, encoded) .await - .context("set task patch drop list")?; + .context("set task patch verdict")?; } channel .exec(true, command) diff --git a/crates/minimal/src/cmd/session.rs b/crates/minimal/src/cmd/session.rs index 41ad7cd36c..83e3c69a8e 100644 --- a/crates/minimal/src/cmd/session.rs +++ b/crates/minimal/src/cmd/session.rs @@ -1856,7 +1856,20 @@ pub async fn cmd_session_run( "found session" ); - session_via_ssh( + // Gate the task's declared patches against `[patches]` here, as `min + // task run` does: the daemon holds no policy, and refuses a task that + // declares patches without this verdict. + let verdict = + crate::task::gate_session_task_patches(global, r.project_path.as_utf8_path(), &args.task)?; + let verdict = minimald_rpc::taskenv::encode_patch_verdict(&verdict).map_err(|len| { + anyhow::anyhow!( + "the task's patch declarations are too large to send ({len} bytes, limit {}); \ + declare fewer `patch` entries", + minimald_rpc::taskenv::TASK_PATCH_VERDICT_MAX_BYTES + ) + })?; + + session_via_ssh_with_env( &sock, r.id, // No owns-box flag (NET-131): the task runs in a session someone @@ -1872,6 +1885,7 @@ pub async fn cmd_session_run( ), None, None, + &[(minimald_rpc::taskenv::TASK_PATCH_VERDICT, verdict.as_str())], ) .await } @@ -2013,6 +2027,19 @@ pub(crate) async fn session_via_ssh( wire: Option, config_dir: Option<&std::path::Path>, host_asks_for: Option<&str>, +) -> Result<(), anyhow::Error> { + session_via_ssh_with_env(sock, id, wire, config_dir, host_asks_for, &[]).await +} + +/// [`session_via_ssh`], plus `channel_env` sent on the exec channel ahead +/// of the request (see [`minimal_client::attach::attach_command_with_env`]). +pub(crate) async fn session_via_ssh_with_env( + sock: &std::path::Path, + id: boxes::SessionId, + wire: Option, + config_dir: Option<&std::path::Path>, + host_asks_for: Option<&str>, + channel_env: &[(&str, &str)], ) -> Result<(), anyhow::Error> { // The command itself lives in minimal-client, shared with the dash TUI's // suspend-attach-resume flow. The interactive path resolves the @@ -2023,8 +2050,13 @@ pub(crate) async fn session_via_ssh( } else { None }; - let mut ssh = - minimal_client::attach::attach_command(sock, id, wire.as_deref(), session_keys.as_ref())?; + let mut ssh = minimal_client::attach::attach_command_with_env( + sock, + id, + wire.as_deref(), + session_keys.as_ref(), + channel_env, + )?; // The session's record, read before the attach or the exec on a // VM-backed host — one with a VM host daemon's control socket beside diff --git a/crates/minimal/src/task.rs b/crates/minimal/src/task.rs index 1f8448befa..6dc4756aef 100644 --- a/crates/minimal/src/task.rs +++ b/crates/minimal/src/task.rs @@ -412,10 +412,11 @@ fn denied_task_patch_message(task_name: &str, path: &str, policy_path: &std::pat /// Gate a task's declared `patch.dir` / `patch.file` entries against /// `[patches]`, the same two lanes as the `env_vars` gate above: the /// interactive prompt on a real terminal, the collect-and-refuse -/// `RefuseAndRecord` anywhere else. Returns the raw declared keys the -/// policy ignored, for the daemon to drop from the mount set — the wire -/// half of the fix, since the daemon holds no policy and mounts what it -/// is given. +/// `RefuseAndRecord` anywhere else. Returns the verdict the daemon +/// applies: the raw declared keys the policy allowed, and those it +/// ignored, for the daemon to drop from the mount set. The daemon holds +/// no policy, mounts only allowed keys, and refuses a task whose patches +/// arrive with no verdict. fn resolve_task_patches( task: &mfile::Task, task_name: &str, @@ -424,7 +425,7 @@ fn resolve_task_patches( source: &boxes::core::source::Source, hooks: &dyn boxes::core::hooks::PolicyHooks, resolved_env: &minimald_rpc::taskenv::TaskEnv, -) -> Result, anyhow::Error> { +) -> Result { use boxes::core::compose::{TaskPatchEntry, gate_task_patch_paths}; // Echo tasks never reach the daemon's mount path — the daemon answers @@ -475,21 +476,46 @@ fn resolve_task_patches( Err(boxes::core::compose::ComposeError::Denied { what, .. }) => { bail!(denied_task_patch_message(task_name, &what, policy_path)) } + Err(boxes::core::compose::ComposeError::TaskPatchDotSegment { what, .. }) => { + bail!(dot_segment_task_patch_message(task_name, &what)) + } Err(e) => { return Err(anyhow::Error::new(e)) .with_context(|| format!("gating `patch` for task '{task_name}'")); } }; - // Verdicts pair with `entries` in order; an ignored entry's raw - // declared key is what the daemon must remove from its mount set. - let mut drops = std::collections::BTreeSet::new(); + // Verdicts pair with `entries` in order, each naming its raw declared + // key: an allowed one may mount, an ignored one the daemon removes. + let mut out = minimald_rpc::taskenv::PatchVerdict::default(); for (entry, verdict) in entries.iter().zip(verdicts) { - if matches!(verdict, boxes::core::compose::NameVerdict::Ignored) { - drops.insert(entry.declared.to_string()); - } + let key = entry.declared.to_string(); + match verdict { + boxes::core::compose::NameVerdict::Allowed => out.allow.insert(key), + boxes::core::compose::NameVerdict::Ignored => out.drop.insert(key), + }; + } + Ok(out) +} + +/// The rejection body for a declared patch key holding a `.` or `..` +/// segment. Split out for unit tests. +fn dot_segment_task_patch_message(task_name: &str, path: &str) -> String { + format!( + "task '{task_name}' declares the patch path `{path}`, which holds a \ + `.` or `..` segment, so your [patches] policy cannot tell what it \ + mounts; declare the path it means without them" + ) +} + +/// Why a policy refusal could not become a prompt, for the refusal text: +/// `--no-input` when the user set it, otherwise the terminal check. +fn no_prompt_reason(no_input: bool) -> &'static str { + if no_input { + "--no-input is set" + } else { + "stdin/stderr is not a terminal" } - Ok(drops) } /// The non-interactive lane of [`resolve_task_patches`]: gate against a @@ -503,9 +529,10 @@ fn resolve_task_patches_non_interactive( policy_path: &std::path::Path, source: &boxes::core::source::Source, resolved_env: &minimald_rpc::taskenv::TaskEnv, -) -> Result, anyhow::Error> { + no_input: bool, +) -> Result { let hooks = RefuseAndRecord::default(); - let drops = resolve_task_patches( + let verdict = resolve_task_patches( task, task_name, patches_policy, @@ -520,14 +547,76 @@ fn resolve_task_patches_non_interactive( let snippet = refused_patches_snippet(&refused); bail!( "task '{task_name}' declares {count} patch{es} that your policy does \ - not allow, and stdin/stderr is not a terminal.\n\n\ + not allow, and {reason}.\n\n\ Add the following to {path}:\n\n{snippet}\n\ Then re-run this command.", + reason = no_prompt_reason(no_input), path = policy_path.display(), es = if count == 1 { "" } else { "es" }, ); } - drops + verdict +} + +/// Gate a task's declared patches for `min session run`, which runs a task +/// in a session that already exists: the task as the session project's +/// `minimal.toml` declares it on this machine, through the same two lanes +/// as `min task run`, saving any rule the user records at the prompt. +/// +/// A task this machine cannot find declared (one a stack provides, or a +/// project whose `minimal.toml` is gone) gets an empty verdict rather than +/// an error. The daemon still runs it when it declares no patches, and +/// refuses it when it does, since nothing here checked them. +pub(crate) fn gate_session_task_patches( + global: &GlobalArgs, + project_path: &camino::Utf8Path, + task_name: &str, +) -> Result { + let Ok(declared) = declared_task(project_path, task_name) else { + return Ok(minimald_rpc::taskenv::PatchVerdict::default()); + }; + if declared.patch.dir.is_empty() && declared.patch.file.is_empty() { + return Ok(minimald_rpc::taskenv::PatchVerdict::default()); + } + let policy_path = crate::config::user_policy_path(global); + let user_policy = crate::config::read_user_policy(global)?; + let source = boxes::core::source::Source::Project { + path: paths::HostPath::try_new(project_path.to_path_buf()) + .context("Invalid project path")?, + }; + // No env resolution on this lane: `min session run` leaves a task's + // `env_vars` to the daemon, so only HOME feeds a pattern's `$VAR`. + let resolved_env = minimald_rpc::taskenv::TaskEnv::default(); + if global.no_input || !crate::can_prompt_interactively() { + return resolve_task_patches_non_interactive( + &declared, + task_name, + user_policy.patches().clone(), + &policy_path, + &source, + &resolved_env, + global.no_input, + ); + } + let hooks = crate::prompt::InteractivePrompt::new(&policy_path, user_policy.clone()); + let verdict = resolve_task_patches( + &declared, + task_name, + user_policy.patches().clone(), + &policy_path, + &source, + &hooks, + &resolved_env, + ); + // Persist before propagating a refusal, as `min task run` does. + let after = hooks.into_final_policy(); + if after != user_policy { + match crate::prompt::save_user_policy(&policy_path, &after) { + Ok(()) => eprintln!("Updated {}", policy_path.display()), + Err(e) => eprintln!("warning: failed to update {}: {e}", policy_path.display()), + } + } + verdict } /// The whitespace rejection body: the name is debug-quoted so the offending @@ -794,23 +883,25 @@ pub async fn cmd_task_run(global: &GlobalArgs, args: TaskRunArgs) -> Result<(), let snippet = refused_vars_snippet(&refused); bail!( "task '{task}' declares {count} environment variable{s} that your \ - policy does not allow, and stdin/stderr is not a terminal.\n\n\ + policy does not allow, and {reason}.\n\n\ Add the following to {path}:\n\n{snippet}\n\ Then re-run this command.", + reason = no_prompt_reason(global.no_input), task = args.task, path = policy_path.display(), s = if count == 1 { "" } else { "s" }, ); } let mut task_env = task_env?; - task_env.patch_drop = resolve_task_patches_non_interactive( + task_env.patch = Some(resolve_task_patches_non_interactive( &declared, &args.task, user_policy.patches().clone(), &policy_path, &source, &task_env, - )?; + global.no_input, + )?); (task_env, user_policy) } else { let hooks = crate::prompt::InteractivePrompt::new(&policy_path, user_policy.clone()); @@ -828,7 +919,7 @@ pub async fn cmd_task_run(global: &GlobalArgs, args: TaskRunArgs) -> Result<(), // save as a rule recorded for a variable. Gated only once the // vars resolved; either error is held until after the save. let gated = task_env.and_then(|mut task_env| { - task_env.patch_drop = resolve_task_patches( + task_env.patch = Some(resolve_task_patches( &declared, &args.task, user_policy.patches().clone(), @@ -836,7 +927,7 @@ pub async fn cmd_task_run(global: &GlobalArgs, args: TaskRunArgs) -> Result<(), &source, &hooks, &task_env, - )?; + )?); Ok(task_env) }); // Persist before propagating a refusal: a rule the user chose to @@ -1972,6 +2063,7 @@ mod tests { &policy_path_fixture(), &project_source(), &minimald_rpc::taskenv::TaskEnv::default(), + true, ) .expect_err("an unapproved patch must fail the run"); @@ -1980,6 +2072,82 @@ mod tests { assert!(msg.contains("[patches]"), "carries the snippet: {msg}"); assert!(msg.contains("/opt/tool/bin"), "names the path: {msg}"); assert!(msg.contains("user_policy.toml"), "names the file: {msg}"); + assert!(msg.contains("--no-input is set"), "names the cause: {msg}"); + } + + /// The refusal names what stopped the prompt: `--no-input` when the + /// user set it, so a user at a terminal is not told it is missing. + #[test] + fn the_refusal_names_the_cause_of_no_prompt() { + assert_eq!(no_prompt_reason(true), "--no-input is set"); + assert_eq!(no_prompt_reason(false), "stdin/stderr is not a terminal"); + } + + /// A declared key with a `..` segment is refused with a message that + /// names the task and the path, before any policy decision. + #[test] + fn a_dot_dot_patch_key_is_refused_by_name() { + let task = task_from_toml( + "[tasks.t]\nexec = 'true'\n[tasks.t.patch.file]\n\ + \"/tmp/../etc/shadow\" = \"rw\"\n", + ); + let policy = + boxes::core::policy::PatchesPolicy::default().with_allow(vec!["/tmp/**".to_string()]); + + let err = resolve_task_patches( + &task, + "t", + policy, + &policy_path_fixture(), + &project_source(), + &NeverAsked, + &minimald_rpc::taskenv::TaskEnv::default(), + ) + .expect_err("a `..` key must fail the gate"); + + let msg = err.to_string(); + assert!(msg.contains("task 't'"), "{msg}"); + assert!(msg.contains("`/tmp/../etc/shadow`"), "{msg}"); + assert!(msg.contains("`..` segment"), "{msg}"); + } + + /// `min session run` gates the task as the session project declares + /// it: a task with no patches, or one this machine cannot find, gets + /// an empty verdict; a declared patch the policy does not allow is + /// refused non-interactively with the snippet. + #[test] + fn session_run_gates_the_project_tasks_patches() { + let tmp = tempfile::tempdir().unwrap(); + let dir = camino::Utf8Path::from_path(tmp.path()).unwrap(); + std::fs::write( + dir.join(mfile::MFILE_NAME), + "[tasks.plain]\nexec = 'true'\n\ + [tasks.mounts]\nexec = 'true'\n[tasks.mounts.patch.file]\n\ + \"/opt/tool/bin\" = \"ro\"\n", + ) + .unwrap(); + let config = tempfile::tempdir().unwrap(); + let global = GlobalArgs { + config_dir: Some(config.path().to_path_buf()), + no_input: true, + ..Default::default() + }; + + let empty = minimald_rpc::taskenv::PatchVerdict::default(); + assert_eq!( + gate_session_task_patches(&global, dir, "plain").unwrap(), + empty + ); + assert_eq!( + gate_session_task_patches(&global, dir, "from-a-stack").unwrap(), + empty, + "an undeclared task is left to the daemon, which refuses its patches" + ); + let err = gate_session_task_patches(&global, dir, "mounts") + .expect_err("an unapproved patch must fail the run"); + let msg = err.to_string(); + assert!(msg.contains("task 'mounts' declares 1 patch "), "{msg}"); + assert!(msg.contains("/opt/tool/bin"), "{msg}"); } /// An ignored patch path lands in the drop list the daemon removes @@ -1993,7 +2161,7 @@ mod tests { let policy = boxes::core::policy::PatchesPolicy::default().with_ignore(vec!["/opt/**".to_string()]); - let drops = resolve_task_patches( + let verdict = resolve_task_patches( &task, "t", policy, @@ -2008,7 +2176,8 @@ mod tests { .map(String::from) .into_iter() .collect(); - assert_eq!(drops, expect, "raw declared keys, verbatim"); + assert_eq!(verdict.drop, expect, "raw declared keys, verbatim"); + assert!(verdict.allow.is_empty(), "nothing ignored is allowed"); } /// An echo task's patches are gated by nobody, the same exemption as @@ -2023,7 +2192,7 @@ mod tests { let policy = boxes::core::policy::PatchesPolicy::default() .with_deny(vec!["/etc/passwd".to_string()]); - let drops = resolve_task_patches( + let verdict = resolve_task_patches( &task, "t", policy, @@ -2034,7 +2203,11 @@ mod tests { ) .expect("an echo task neither resolves nor denies"); - assert!(drops.is_empty(), "nothing to drop: {drops:?}"); + assert_eq!( + verdict, + minimald_rpc::taskenv::PatchVerdict::default(), + "nothing to send" + ); } /// The interactive lane's hook approves an undecided patch on the @@ -2048,7 +2221,7 @@ mod tests { let hooks = ScriptedHook::new(boxes::core::decision::ItemDecision::AllowOnce).allowing_patches(); - let drops = resolve_task_patches( + let verdict = resolve_task_patches( &task, "t", boxes::core::policy::PatchesPolicy::default(), @@ -2064,7 +2237,11 @@ mod tests { vec!["/opt/tool/bin".to_string()], "the prompt was about the declared path" ); - assert!(drops.is_empty(), "an approved patch is not dropped"); + assert!(verdict.drop.is_empty(), "an approved patch is not dropped"); + assert!( + verdict.allow.contains("/opt/tool/bin"), + "an approved patch is named as allowed, or the daemon refuses it" + ); } /// `cmd_task_run` rejects a task the project's minimal.toml does not diff --git a/crates/minimald-rpc/src/taskenv.rs b/crates/minimald-rpc/src/taskenv.rs index 4717b0f8ad..45e290b71e 100644 --- a/crates/minimald-rpc/src/taskenv.rs +++ b/crates/minimald-rpc/src/taskenv.rs @@ -41,19 +41,26 @@ pub const TASK_ENV_PREFIX: &str = "MINIMAL_TASK_ENV_"; /// task as a variable called `DROP`. pub const TASK_ENV_DROP: &str = "MINIMAL_TASK_DROP"; -/// Channel env var carrying the declared patch paths the daemon must -/// *remove* from the task's declarations, as a JSON array — the keys -/// exactly as `minimal.toml` wrote them, so a removal matches the -/// declaration it names. +/// Channel env var carrying the client's `[patches]` verdict on a task's +/// declared `patch.dir` / `patch.file` entries, as a JSON +/// [`PatchVerdict`]: the keys it allowed and the keys it dropped, each +/// exactly as `minimal.toml` wrote them. /// -/// The client gates a task's `patch.dir` / `patch.file` entries against -/// `[patches]` before the run; the entries the policy ignores cannot be -/// carried the way a resolved value can (the daemon mounts the declared -/// path itself), so an ignored entry has to be named for removal. +/// The client gates those entries before the run, because the daemon +/// holds no policy and mounts the declared path itself. The verdict is +/// required, not advisory: a daemon mounts only the keys it names as +/// allowed, and refuses a task that declares patches when the verdict is +/// absent (an older client, or a lane that never gated), unparseable, or +/// larger than [`TASK_PATCH_VERDICT_MAX_BYTES`]. /// /// Deliberately **not** under [`TASK_ENV_PREFIX`], for the same reason as /// [`TASK_ENV_DROP`]. -pub const TASK_PATCH_DROP: &str = "MINIMAL_TASK_PATCH_DROP"; +pub const TASK_PATCH_VERDICT: &str = "MINIMAL_TASK_PATCH_VERDICT"; + +/// The largest encoded [`TASK_PATCH_VERDICT`] a daemon reads. A task +/// declares a handful of patches; anything near this bound is not a +/// verdict worth parsing, and the client refuses to send one. +pub const TASK_PATCH_VERDICT_MAX_BYTES: usize = 64 * 1024; /// The channel env var name carrying task variable `name`. #[must_use] @@ -100,45 +107,77 @@ pub fn drops_from_channel_env(env_vars: &BTreeMap) -> BTreeSet, + /// Declared keys the policy ignored, to remove before mounting. + pub drop: BTreeSet, +} + +/// Encode a verdict for [`TASK_PATCH_VERDICT`]. +/// +/// # Errors +/// +/// The encoded form when it exceeds [`TASK_PATCH_VERDICT_MAX_BYTES`], as +/// its length: a daemon would refuse it, so the client must not send it. +pub fn encode_patch_verdict(verdict: &PatchVerdict) -> Result { + let encoded = serde_json_lenient::to_string(verdict) + .expect("two sets of strings always serialize to JSON"); + if encoded.len() > TASK_PATCH_VERDICT_MAX_BYTES { + return Err(encoded.len()); + } + Ok(encoded) +} + +/// The patch verdict a client sent, from a channel's env map. +/// +/// `None` when it is absent, unparseable, or over +/// [`TASK_PATCH_VERDICT_MAX_BYTES`]. Unlike the drop lists, `None` is not +/// "remove nothing": it means no client checked the task's patches, and a +/// daemon must not mount any. #[must_use] -pub fn patch_drops_from_channel_env(env_vars: &BTreeMap) -> BTreeSet { - env_vars - .get(TASK_PATCH_DROP) - .and_then(|raw| serde_json_lenient::from_str(raw).ok()) - .unwrap_or_default() +pub fn patch_verdict_from_channel_env(env_vars: &BTreeMap) -> Option { + let raw = env_vars.get(TASK_PATCH_VERDICT)?; + if raw.len() > TASK_PATCH_VERDICT_MAX_BYTES { + return None; + } + serde_json_lenient::from_str(raw).ok() } -/// A task's `env_vars` as the client resolved them, plus the `patch` -/// entries its policy dropped: the values to apply, and the names to -/// remove. +/// A task's `env_vars` as the client resolved them, plus its `[patches]` +/// verdict: the values to apply, the names to remove, and which declared +/// patches may mount. /// -/// The two halves are disjoint by construction — a name is either resolved -/// or dropped — and travel together because the daemon needs both to -/// arrive at the set the task actually sees. `patch_drop` is a third, -/// separate list: declared patch paths, not variable names, removed from -/// the task's `patch.dir` / `patch.file` maps before they are mounted. +/// The two env halves are disjoint by construction — a name is either +/// resolved or dropped — and travel together because the daemon needs +/// both to arrive at the set the task actually sees. `patch` is separate: +/// declared patch paths, not variable names. #[derive(Clone, Debug, Default, PartialEq, Eq)] pub struct TaskEnv { /// Values to apply over the task's own declarations. pub set: BTreeMap, /// Names to remove from the task's declarations entirely. pub drop: BTreeSet, - /// Declared patch paths to remove from the task's `patch` entries - /// entirely — the keys exactly as `minimal.toml` wrote them. - pub patch_drop: BTreeSet, + /// The client's verdict on the task's declared patches. `None` for + /// every caller that does not run a task; a task run always sends + /// one, empty when the task declares no patches. + pub patch: Option, } impl TaskEnv { /// `true` when there is nothing for the daemon to apply — the case for - /// every caller other than a task run, and for a task declaring no - /// `env_vars`. + /// every caller other than a task run. #[must_use] pub fn is_empty(&self) -> bool { - self.set.is_empty() && self.drop.is_empty() && self.patch_drop.is_empty() + self.set.is_empty() && self.drop.is_empty() && self.patch.is_none() } } @@ -312,43 +351,74 @@ mod tests { #[test] fn the_drop_carrier_is_not_under_the_value_prefix() { assert!(!TASK_ENV_DROP.starts_with(TASK_ENV_PREFIX)); - assert!(!TASK_PATCH_DROP.starts_with(TASK_ENV_PREFIX)); + assert!(!TASK_PATCH_VERDICT.starts_with(TASK_ENV_PREFIX)); } - /// The patch drop list round-trips, and the paths on it are the raw - /// declared keys — `~/`-rooted or otherwise — so a removal matches the + /// The patch verdict round-trips, and the paths on it are the raw + /// declared keys — `~/`-rooted or otherwise — so each matches the /// `minimal.toml` entry it names. #[test] - fn patch_drop_list_round_trips() { - let drops: BTreeSet = ["~/.claude".to_string(), "/etc/secrets".to_string()] - .into_iter() - .collect(); + fn patch_verdict_round_trips() { + let verdict = PatchVerdict { + allow: ["~/.claude".to_string()].into_iter().collect(), + drop: ["/etc/secrets".to_string()].into_iter().collect(), + }; let mut channel = BTreeMap::new(); - channel.insert(TASK_PATCH_DROP.to_string(), encode_drops(&drops)); + channel.insert( + TASK_PATCH_VERDICT.to_string(), + encode_patch_verdict(&verdict).unwrap(), + ); - assert_eq!(patch_drops_from_channel_env(&channel), drops); + assert_eq!(patch_verdict_from_channel_env(&channel), Some(verdict)); // The carrier is not itself a task variable. assert!(from_channel_env(&channel).is_empty()); - // And it is not the env-drop carrier: the two lists stay separate. + // And it is not the env-drop carrier: the two stay separate. assert!(drops_from_channel_env(&channel).is_empty()); } - /// No patch drop list, an empty one, and a malformed one all mean - /// "remove nothing" — same fail-safe as the env drop list, and an - /// older client sends none at all. + /// An empty verdict is still a verdict: the client checked a task + /// that declares no patches, which differs from not checking at all. + #[test] + fn an_empty_patch_verdict_is_present() { + let mut channel = BTreeMap::new(); + channel.insert( + TASK_PATCH_VERDICT.to_string(), + encode_patch_verdict(&PatchVerdict::default()).unwrap(), + ); + assert_eq!( + patch_verdict_from_channel_env(&channel), + Some(PatchVerdict::default()) + ); + } + + /// No verdict, a malformed one, and an oversized one all read as + /// "never checked", which a daemon refuses for a task with patches. #[test] - fn an_absent_or_unparseable_patch_drop_list_removes_nothing() { + fn an_absent_unparseable_or_oversized_patch_verdict_is_none() { let mut absent = BTreeMap::new(); absent.insert("MINIMAL_SESSION_ID".to_string(), "an-id".to_string()); - assert!(patch_drops_from_channel_env(&absent).is_empty()); - - let mut empty = BTreeMap::new(); - empty.insert(TASK_PATCH_DROP.to_string(), encode_drops(&BTreeSet::new())); - assert!(patch_drops_from_channel_env(&empty).is_empty()); + assert_eq!(patch_verdict_from_channel_env(&absent), None); let mut junk = BTreeMap::new(); - junk.insert(TASK_PATCH_DROP.to_string(), "not json".to_string()); - assert!(patch_drops_from_channel_env(&junk).is_empty()); + junk.insert(TASK_PATCH_VERDICT.to_string(), "not json".to_string()); + assert_eq!(patch_verdict_from_channel_env(&junk), None); + + let huge = PatchVerdict { + allow: (0..TASK_PATCH_VERDICT_MAX_BYTES / 8) + .map(|i| format!("/p/{i}")) + .collect(), + drop: BTreeSet::new(), + }; + assert!( + encode_patch_verdict(&huge).is_err(), + "the client refuses it" + ); + let mut oversized = BTreeMap::new(); + oversized.insert( + TASK_PATCH_VERDICT.to_string(), + serde_json_lenient::to_string(&huge).unwrap(), + ); + assert_eq!(patch_verdict_from_channel_env(&oversized), None); } /// No drop list, an empty one, and a malformed one all mean "remove diff --git a/crates/minimald/src/exec.rs b/crates/minimald/src/exec.rs index ca17f3ec2b..c080ef8a53 100644 --- a/crates/minimald/src/exec.rs +++ b/crates/minimald/src/exec.rs @@ -116,16 +116,16 @@ pub struct TaskExec { /// daemon's own environment — the very indirection #585 removes. A /// dropped name has to be named. pub drop_env: BTreeSet, - /// Declared patch paths the client's `[patches]` policy ignored, to - /// be removed from the task's `patch.dir` / `patch.file` declarations - /// before anything is mounted. The keys are raw — exactly as - /// `minimal.toml` wrote them — because patch keys are never - /// interpolated, so a removal matches the declaration it names. + /// The client's `[patches]` verdict on the task's declared + /// `patch.dir` / `patch.file` keys, applied by + /// [`apply_patch_verdict`] before anything is mounted. The keys are + /// raw — exactly as `minimal.toml` wrote them — because patch keys are + /// never interpolated, so each matches the declaration it names. /// - /// Empty when the client sent none — an older `min`, or any caller - /// other than `min task run` — in which case the declared patches - /// apply as before. - pub patch_drop: BTreeSet, + /// `None` when the client sent none (an older `min`), or sent one this + /// daemon could not read; a task that declares patches is then + /// refused. + pub patch: Option, /// The client's invocation directory relative to the uploaded tree, /// already refused by [`minimald_rpc::exec::ExecRequest::parse`] if it /// is absolute or holds a `..`. A task that declares `inherit_cwd` @@ -356,6 +356,121 @@ fn parse_task_args( /// `env` lives on a single stack frame across every spawn — that frame /// is alive for the whole life of this tokio task, which in turn is /// governed by the consumer's stream. +/// Apply the client's `[patches]` verdict to a task's declared patches: +/// remove every dropped key, then require every key left to be one the +/// verdict allowed. +/// +/// The daemon holds no policy, so this is the only thing standing between +/// a project's `patch` declarations and a mount. It fails closed: a task +/// that declares patches with no verdict (an older `min`, or a verdict +/// this daemon could not read) is refused, and so is a key the verdict +/// does not name, since the client never checked it. A task that +/// declares no patches needs no verdict. +/// +/// # Errors +/// +/// The refusal text, naming the task and what to do about it. +fn apply_patch_verdict( + task_name: &str, + patch: &mut mfile::EnvPatches, + verdict: Option<&minimald_rpc::taskenv::PatchVerdict>, +) -> Result<(), String> { + if patch.dir.is_empty() && patch.file.is_empty() { + return Ok(()); + } + let Some(verdict) = verdict else { + return Err(format!( + "task '{task_name}' declares `patch` entries, and the `min` that \ + started it did not check them against your [patches] policy, so \ + the task did not run. Upgrade min to match the daemon, then run \ + the task again" + )); + }; + for key in &verdict.drop { + patch.dir.remove(key); + patch.file.remove(key); + } + if let Some(key) = patch + .dir + .keys() + .chain(patch.file.keys()) + .find(|key| !verdict.allow.contains(*key)) + { + return Err(format!( + "task '{task_name}' declares the patch path `{key}`, which `min` \ + did not check against your [patches] policy, so the task did not \ + run. The task's declaration here differs from the minimal.toml \ + `min` read; run the task again once they match" + )); + } + Ok(()) +} + +#[cfg(test)] +mod patch_verdict_tests { + use super::apply_patch_verdict; + use minimald_rpc::taskenv::PatchVerdict; + + fn patches(dirs: &[&str], files: &[&str]) -> mfile::EnvPatches { + let mut p = mfile::EnvPatches::default(); + for d in dirs { + p.dir + .insert((*d).to_string(), mfile::PatchSetting::default()); + } + for f in files { + p.file + .insert((*f).to_string(), mfile::PatchSetting::default()); + } + p + } + + fn verdict(allow: &[&str], drop: &[&str]) -> PatchVerdict { + PatchVerdict { + allow: allow.iter().map(|s| (*s).to_string()).collect(), + drop: drop.iter().map(|s| (*s).to_string()).collect(), + } + } + + /// A task with no patches needs no verdict: every non-patch task run + /// from an older client keeps working. + #[test] + fn a_task_without_patches_needs_no_verdict() { + let mut p = patches(&[], &[]); + apply_patch_verdict("t", &mut p, None).expect("nothing to gate"); + } + + /// No verdict for a task with patches is a refusal that names the fix, + /// never a mount of what the project declared. + #[test] + fn a_task_with_patches_and_no_verdict_is_refused() { + let mut p = patches(&["/opt/cache"], &[]); + let err = apply_patch_verdict("t", &mut p, None).unwrap_err(); + assert!(err.contains("task 't'"), "{err}"); + assert!(err.contains("Upgrade min"), "{err}"); + } + + /// Dropped keys leave both maps, allowed keys stay. + #[test] + fn dropped_keys_go_and_allowed_keys_stay() { + let mut p = patches(&["/opt/cache"], &["/etc/token", "~/.claude.json"]); + let v = verdict(&["/opt/cache", "~/.claude.json"], &["/etc/token"]); + apply_patch_verdict("t", &mut p, Some(&v)).expect("every key was gated"); + assert!(p.dir.contains_key("/opt/cache")); + assert!(p.file.contains_key("~/.claude.json")); + assert!(!p.file.contains_key("/etc/token")); + } + + /// A declared key the verdict does not name was never gated, so the + /// task is refused rather than the key mounted. + #[test] + fn a_key_the_verdict_does_not_name_is_refused() { + let mut p = patches(&["/opt/cache"], &["/etc/shadow"]); + let v = verdict(&["/opt/cache"], &[]); + let err = apply_patch_verdict("t", &mut p, Some(&v)).unwrap_err(); + assert!(err.contains("`/etc/shadow`"), "{err}"); + } +} + async fn task_producer( exec: TaskExec, session: BoxHandle, @@ -424,15 +539,11 @@ async fn task_producer( for name in &exec.drop_env { task.vars.remove(name); } - // Patch removals join them: the client's `[patches]` gate decided - // these declared paths must not mount, and the keys are raw — - // never interpolated — so they match the declarations exactly. - // The daemon holds no policy; applying the client's verdicts - // here is the whole wire contract. - for key in &exec.patch_drop { - task.patch.dir.remove(key); - task.patch.file.remove(key); - } + // The daemon holds no policy, so the client's `[patches]` verdict + // decides what mounts: dropped keys go, and a task declaring a + // key the verdict does not allow is refused before any mount. + apply_patch_verdict(&exec.task, &mut task.patch, exec.patch.as_ref()) + .map_err(io::Error::other)?; for (name, value) in &exec.env { task.vars .insert(name.clone(), mfile::EnvVarValue::Value(value.clone())); @@ -1891,10 +2002,10 @@ pub(crate) async fn handle_exec( trace_env.clone(), ); let drop_env = minimald_rpc::taskenv::drops_from_channel_env(&config.env_vars); - // Patch paths the client's policy dropped, same wire contract - // as `drop_env`: absent from an older client, meaning the - // declared patches apply as before. - let patch_drop = minimald_rpc::taskenv::patch_drops_from_channel_env(&config.env_vars); + // The client's `[patches]` verdict. Unlike `drop_env`, absence + // is a signal: no verdict means no client checked the task's + // patches, and `apply_patch_verdict` refuses a task with any. + let patch = minimald_rpc::taskenv::patch_verdict_from_channel_env(&config.env_vars); let span = span.clone(); session.channel_success(id)?; spawn(tracing::Instrument::instrument( @@ -1913,7 +2024,7 @@ pub(crate) async fn handle_exec( task: task.clone(), env: task_env, drop_env, - patch_drop, + patch, cwd, }, }; diff --git a/docs/reference/tasks.md b/docs/reference/tasks.md index 8061ac5327..463b4edede 100644 --- a/docs/reference/tasks.md +++ b/docs/reference/tasks.md @@ -245,7 +245,7 @@ interactive = true ``` -### `patches` - Map in files/directories from the system +### `patches` - Map in files/directories from the system {#patches} _Optional. `patches` is an alias of the canonical `patch` key; both parse_ @@ -274,6 +274,12 @@ mounts a mapping inside that home or the project tree at the matching path under `/workbench`. It mounts the mapping on top of the read-write session mounts, so a read-only mapping stays read-only. It mounts any other absolute path at that same path. +Before `min task run` or `min session run` starts the task, Minimal checks each declared path +against the `[patches]` section of your [user policy](./user-policy.md#task-patches). A denied path +stops the run, and an ignored path stays out. An uncovered path gets a prompt, which without a +terminal stops the run instead. The daemon refuses a task that declares +patches when the `min` that started it did not check them. + ### `inherit_cwd` - Use parent working directory instead of repository root _Optional, Default `false`_ diff --git a/docs/reference/user-policy.md b/docs/reference/user-policy.md index f71fe7cf66..e33a80027d 100644 --- a/docs/reference/user-policy.md +++ b/docs/reference/user-policy.md @@ -154,6 +154,33 @@ deny = ["~/.ssh/**", "**/*.pem"] ignore = ["**/.DS_Store"] ``` +#### Task patches {#task-patches} + +Before `min task run` or `min session run` starts a task, Minimal checks the +task's [`patch.dir` and `patch.file`](./tasks.md#patches) entries against +`[patches]` too. A task patch is a host path that the session mounts directly, +so the rules apply to the **declared path** itself: + +- `allow` must match the path as `minimal.toml` declares it. A rule naming a + declared directory approves that directory whatever it holds. +- `deny` on the declared path, or on any file a declared directory holds, + stops the run. +- For a declared absolute path, Minimal also checks the path it resolves to on + your machine. A symlink cannot carry the path past a `deny` on its target. + This includes a symlinked parent of a path that does not exist yet. +- `ignore` on the declared path leaves that entry out. An `ignore` on a file + inside a declared directory does not apply, because a mount cannot leave + one file out. +- A declared path with a `.` or `..` segment stops the run. +- Minimal matches a `~/` path as declared, and expands its `~/` against your + home the same way as a rule's `~/`. The session mounts `~/` from the + session's own home, so Minimal does not check what your home holds. + +On a host where Minimal runs in a VM (macOS), the symlink and directory checks +read your computer's files. The VM's files can differ, so there these checks +are a backstop. Without a terminal, or with `--no-input`, a path that needs +approval stops the run. The error prints the `[patches] allow` lines to add. + ### `[hooks]` — Lifecycle-script rules Patterns match the **project root path** that declared the hook — as you refer From 5c64e8f5ed51ddcb79730a54a4f6856606c3783e Mon Sep 17 00:00:00 2001 From: "gominimal-aw-bot[bot]" <281738952+gominimal-aw-bot[bot]@users.noreply.github.com> Date: Sat, 17 Oct 2026 20:07:42 -0700 Subject: [PATCH 04/21] fix(task): probe a symlinked patch directory at its target --- crates/boxes/src/core/compose.rs | 9 +++++++++ crates/boxes/src/core/compose/tests.rs | 23 +++++++++++++++++++++++ 2 files changed, 32 insertions(+) diff --git a/crates/boxes/src/core/compose.rs b/crates/boxes/src/core/compose.rs index d4d072f600..75448c1566 100644 --- a/crates/boxes/src/core/compose.rs +++ b/crates/boxes/src/core/compose.rs @@ -1661,6 +1661,9 @@ fn check_task_patch_dir( if !resolve || own == PathDecision::Denied { return own; } + // A symlinked directory (or parent) holds its files where it points, + // so each file is checked under that root as well as the declared one. + let resolved_root = resolve_existing_prefix(dir); let mut seen = 0usize; let mut stack = vec![dir.as_std_path().to_path_buf()]; while let Some(cur) = stack.pop() { @@ -1686,6 +1689,12 @@ fn check_task_patch_dir( if check_task_patch_path(expanded, source, &path, is_link) == PathDecision::Denied { return PathDecision::Denied; } + if let Some(root) = &resolved_root + && let Ok(rel) = path.strip_prefix(dir) + && decide_task_patch_path(expanded, source, &root.join(rel)) == PathDecision::Denied + { + return PathDecision::Denied; + } } } own diff --git a/crates/boxes/src/core/compose/tests.rs b/crates/boxes/src/core/compose/tests.rs index 8e10d7cefc..24365c657c 100644 --- a/crates/boxes/src/core/compose/tests.rs +++ b/crates/boxes/src/core/compose/tests.rs @@ -2766,6 +2766,29 @@ mod gate_task_patch_paths { assert!(matches!(err, ComposeError::Denied { .. }), "{err}"); } + /// A declared directory that is a symlink is probed where it points: + /// a deny naming one file in the target denies the entry. + #[cfg(unix)] + #[test] + fn a_symlinked_directory_is_probed_at_its_target() { + let tmp = tempfile::tempdir().unwrap(); + let root = canonical_root(&tmp); + let ssh = root.join("home/.ssh"); + std::fs::create_dir_all(ssh.as_std_path()).unwrap(); + std::fs::write(ssh.join("id").as_std_path(), "x").unwrap(); + std::fs::create_dir(root.join("tmp").as_std_path()).unwrap(); + let link = root.join("tmp/d"); + std::os::unix::fs::symlink(ssh.as_std_path(), link.as_std_path()).unwrap(); + + let source = project_source(); + let entries = entries_for(&source, &[(link.as_str(), false)]); + let policy = PatchesPolicy::default() + .with_allow(vec![format!("{root}/tmp/**")]) + .with_deny(vec![format!("{ssh}/id")]); + let err = gate_task_patch_paths(&entries, policy, None, &NoVars, None).unwrap_err(); + assert!(matches!(err, ComposeError::Denied { .. }), "{err}"); + } + /// The resolved form only tightens: an allow on the declared string /// decides, so a symlinked prefix (macOS's `/tmp` -> `/private/tmp`) /// does not turn an allowed entry into a prompt. From f68b09a088c864049e03df6853c34fa4a55f7991 Mon Sep 17 00:00:00 2001 From: "gominimal-aw-bot[bot]" <281738952+gominimal-aw-bot[bot]@users.noreply.github.com> Date: Sat, 17 Oct 2026 23:00:58 -0700 Subject: [PATCH 05/21] fix(task): refuse patch declarations on an in-box min run An in-box `min run ` reads the task from the box's own workspace minimal.toml, which anything in the box can edit, and no client checks its patches against a policy. Refuse a task that declares any patch.dir or patch.file there, naming `min task run ` on the host as the way to run it. A task without patches runs as before. --- crates/minimald/src/env.rs | 64 ++++++++++++++++++++++++++++++++++++- crates/minimald/src/exec.rs | 41 +++++++++++++++++++++++- docs/reference/tasks.md | 4 ++- 3 files changed, 106 insertions(+), 3 deletions(-) diff --git a/crates/minimald/src/env.rs b/crates/minimald/src/env.rs index 0ca71ed420..67bf98d5b8 100644 --- a/crates/minimald/src/env.rs +++ b/crates/minimald/src/env.rs @@ -1463,6 +1463,14 @@ impl BoxChannel { Ok(Some(v)) => v, }; + // The task came from the box's own workspace minimal.toml, which + // anything in the box can edit, and no client checked its patches + // against a policy: refuse them all rather than mount host paths. + if let Err(e) = crate::exec::refuse_in_box_patches(task_name, &task.patch) { + let _ = writeln!(stream, "error: {e}"); + return; + } + let parsed_args = if !task.args.is_empty() { match task.args.parse(args) { Err(e) => { @@ -2728,6 +2736,21 @@ exit $rc fn setup_channel_with( session: crate::box_actor::WeakBoxHandle, name: &str, + ) -> (TempDir, TempDir, TempDir, BoxChannel) { + let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR")); + setup_channel_at( + session, + name, + &manifest_dir.join("../mctx/testdata/fakerepo"), + ) + } + + /// [`setup_channel_with`] against the project at `repo` rather than the + /// fakerepo fixture, for tests that need a task the fixture lacks. + fn setup_channel_at( + session: crate::box_actor::WeakBoxHandle, + name: &str, + repo: &Path, ) -> (TempDir, TempDir, TempDir, BoxChannel) { let cwd = tempdir().unwrap(); let state = tempdir().unwrap(); @@ -2736,7 +2759,7 @@ exit $rc let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR")); let config = ConfigBuilder::new() .with_state_dir(state.path().to_path_buf()) - .with_repo_dir(manifest_dir.join("../mctx/testdata/fakerepo")) + .with_repo_dir(repo.to_path_buf()) .with_stdlib_dir(manifest_dir.join("../stdlib/minimal-ncl")) .with_no_fetch(true) .build() @@ -2785,6 +2808,45 @@ exit $rc .collect() } + /// An in-box `min run` of a task that declares a patch is refused before + /// anything resolves, naming the host-side command. A task without + /// patches is not refused for it and goes on to the session, which is + /// gone here because the harness's session handle is dangling. + #[tokio::test] + async fn in_box_run_refuses_a_task_with_patches() { + let repo = tempdir().unwrap(); + let fakepkgs = Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../mctx/testdata/fakepkgs") + .canonicalize() + .unwrap(); + let manifest = format!( + "[upstream]\ndir = {:?}\n\n\ + [tasks.leak]\npackages = [\"uroot\"]\nexec = \"/bbin/date\"\n\ + patch.dir.\"/home/user/.ssh\" = \"read-only\"\n\n\ + [tasks.plain]\npackages = [\"uroot\"]\nexec = \"/bbin/date\"\n", + fakepkgs.display().to_string() + ); + std::fs::write(repo.path().join("minimal.toml"), manifest).unwrap(); + for (task, want) in [ + ( + "leak", + "error: this task declares patches; run it from the host with `min task run \ + leak` so your patch policy can approve them", + ), + ("plain", "error: session is gone"), + ] { + let (_state, _rootfs, _cwd, mut chan) = setup_channel_at( + crate::box_actor::WeakBoxHandle::dangling(), + "web", + repo.path(), + ); + let (mut ours, theirs) = UnixStream::pair().unwrap(); + chan.handle(&format!("run%{task}"), &mut ours).await; + drop(ours); + assert_eq!(read_lines(&theirs), vec![want.to_string()], "task {task}"); + } + } + #[tokio::test] async fn errs_on_unknown_command() { let (_state, _rootfs, _cwd, mut chan) = setup_channel(); diff --git a/crates/minimald/src/exec.rs b/crates/minimald/src/exec.rs index c080ef8a53..f912728c82 100644 --- a/crates/minimald/src/exec.rs +++ b/crates/minimald/src/exec.rs @@ -406,9 +406,34 @@ fn apply_patch_verdict( Ok(()) } +/// Refuses a task started from inside a box (`min run `) that +/// declares any patch path. +/// +/// No client policy runs on that path: the daemon reads the task from the +/// box's own workspace `minimal.toml`, which anything in the box can edit, +/// so a verdict is impossible there and every patch is refused rather than +/// mounted. A task that declares no patches runs as before. +/// +/// # Errors +/// +/// The refusal text, naming the task and the host-side command that can +/// check its patches. +pub(crate) fn refuse_in_box_patches( + task_name: &str, + patch: &mfile::EnvPatches, +) -> Result<(), String> { + if patch.dir.is_empty() && patch.file.is_empty() { + return Ok(()); + } + Err(format!( + "this task declares patches; run it from the host with `min task run {task_name}` so \ + your patch policy can approve them" + )) +} + #[cfg(test)] mod patch_verdict_tests { - use super::apply_patch_verdict; + use super::{apply_patch_verdict, refuse_in_box_patches}; use minimald_rpc::taskenv::PatchVerdict; fn patches(dirs: &[&str], files: &[&str]) -> mfile::EnvPatches { @@ -469,6 +494,20 @@ mod patch_verdict_tests { let err = apply_patch_verdict("t", &mut p, Some(&v)).unwrap_err(); assert!(err.contains("`/etc/shadow`"), "{err}"); } + + /// An in-box run refuses any declared patch, dir or file, and names + /// the host-side command; a task without patches passes. + #[test] + fn an_in_box_run_refuses_any_patch() { + refuse_in_box_patches("t", &patches(&[], &[])).expect("nothing to refuse"); + for p in [patches(&["/opt/cache"], &[]), patches(&[], &["~/.netrc"])] { + assert_eq!( + refuse_in_box_patches("t", &p).unwrap_err(), + "this task declares patches; run it from the host with `min task run t` so \ + your patch policy can approve them" + ); + } + } } async fn task_producer( diff --git a/docs/reference/tasks.md b/docs/reference/tasks.md index 463b4edede..7ffb43a06a 100644 --- a/docs/reference/tasks.md +++ b/docs/reference/tasks.md @@ -278,7 +278,9 @@ Before `min task run` or `min session run` starts the task, Minimal checks each against the `[patches]` section of your [user policy](./user-policy.md#task-patches). A denied path stops the run, and an ignored path stays out. An uncovered path gets a prompt, which without a terminal stops the run instead. The daemon refuses a task that declares -patches when the `min` that started it did not check them. +patches when the `min` that started it did not check them. Inside a session, +`min run` refuses a task that declares patches, since no policy check runs +there; run it from the host with `min task run`. ### `inherit_cwd` - Use parent working directory instead of repository root From aad78f47755ebbc1722ebb2c541a92536d7db905 Mon Sep 17 00:00:00 2001 From: "gominimal-aw-bot[bot]" <281738952+gominimal-aw-bot[bot]@users.noreply.github.com> Date: Sat, 17 Oct 2026 23:01:05 -0700 Subject: [PATCH 06/21] fix(task): require the resolved patch path to pass the allow step For a resolvable absolute task patch, the path it resolves to on this machine now has to be allowed as well as the declared string, so a symlink cannot carry an allowed path onto a target no rule allows. Before, the resolved form could only add a deny or an ignore. When an entry is undecided, the hook is asked about each form the policy cannot decide, so "allow always" and the non-interactive [patches] allow snippet record the resolved path too and a UseRule answer settles the entry. `~/` entries are still matched as declared. --- crates/boxes/src/core/compose.rs | 209 ++++++++++++++++++------- crates/boxes/src/core/compose/tests.rs | 120 ++++++++++++-- docs/reference/user-policy.md | 6 +- 3 files changed, 260 insertions(+), 75 deletions(-) diff --git a/crates/boxes/src/core/compose.rs b/crates/boxes/src/core/compose.rs index 75448c1566..9fd68b1548 100644 --- a/crates/boxes/src/core/compose.rs +++ b/crates/boxes/src/core/compose.rs @@ -1607,16 +1607,15 @@ fn decide_task_patch_path( /// One declared path's [`PathDecision`](crate::core::policy::PathDecision). /// -/// The declared form decides: it is the string the daemon is handed, and -/// on a VM-backed host the daemon resolves it in a filesystem this process -/// cannot see. When `resolve` is set, the form the path reaches on this -/// machine ([`resolve_existing_prefix`]) is checked too, and can only make -/// the entry stricter: a `deny` or `ignore` on the resolved form applies, -/// but its allow step does not. That keeps a symlink, including a -/// symlinked parent of an entry that does not exist yet, from carrying a -/// path past a deny on its target. It does not let this machine's view -/// raise prompts the daemon's view would not, such as macOS's -/// `/tmp` → `/private/tmp`. +/// The declared form is the string the daemon is handed, so it must pass. +/// When `resolve` is set, the form the path reaches on this machine +/// ([`resolve_existing_prefix`]) must pass as well, allow step included: +/// the two decisions combine, the stricter winning. So a symlink, including +/// a symlinked parent of an entry that does not exist yet, cannot carry a +/// path past a deny on its target, nor onto a target no rule allows. A +/// symlinked prefix such as macOS's `/tmp` → `/private/tmp` therefore needs +/// the resolved form allowed too; the prompt and the refusal snippet name +/// it (see [`task_patch_forms`]). fn check_task_patch_path( expanded: &ExpandedPatchesPolicy, source: &Source, @@ -1628,12 +1627,95 @@ fn check_task_patch_path( if !resolve || own == PathDecision::Denied { return own; } - match resolve_existing_prefix(path).map(|r| decide_task_patch_path(expanded, source, &r)) { - Some(stricter @ (PathDecision::Denied | PathDecision::Ignored)) => own.combine(stricter), - _ => own, + match resolve_existing_prefix(path) { + Some(resolved) => own.combine(decide_task_patch_path(expanded, source, &resolved)), + None => own, } } +/// The forms of one declared entry the policy must each allow: the +/// declared key as written, then, for a resolvable entry that resolves +/// somewhere else on this machine, the resolved path. Each pairs the +/// string a rule records with the path it is matched as. +/// +/// An undecided entry is put to the hook once per form the policy cannot +/// decide, so "allow always" and the non-interactive snippet record every +/// form that needs a rule, and a `UseRule` answer can settle the entry. +fn task_patch_forms( + declared: &str, + path: &camino::Utf8Path, + resolve: bool, +) -> Vec<(String, camino::Utf8PathBuf)> { + let mut forms = vec![(declared.to_owned(), path.to_path_buf())]; + if resolve && let Some(resolved) = resolve_existing_prefix(path) { + forms.push((resolved.to_string(), resolved)); + } + forms +} + +/// The [`task_patch_forms`] of an undecided entry that the policy cannot +/// decide, the ones the hook is asked about. Never empty: should no form +/// be undecided, the declared form is asked about rather than the entry +/// left to be allowed unasked. +fn undecided_task_patch_forms( + expanded: &ExpandedPatchesPolicy, + entry: &TaskPatchEntry<'_>, + path: &camino::Utf8Path, + resolve: bool, +) -> Vec<(String, camino::Utf8PathBuf)> { + use crate::core::policy::PathDecision; + let forms: Vec<_> = task_patch_forms(entry.declared, path, resolve) + .into_iter() + .filter(|(_, at)| { + decide_task_patch_path(expanded, entry.source, at) == PathDecision::NeedsApproval + }) + .collect(); + if forms.is_empty() { + return vec![(entry.declared.to_owned(), path.to_path_buf())]; + } + forms +} + +/// Each entry's decision from the hook's answers about its queued forms, +/// combined stricter-wins, plus whether any of its answers was `UseRule`. +/// A form answered `UseRule` is decided again against the policy as the +/// hook amended it. Entries with no queued form stay `Allowed`; the caller +/// reads only the entries it queued. +/// +/// # Errors +/// +/// [`ComposeError::HookContract`] when a `UseRule` form is still undecided. +fn decide_answered_task_patch_forms( + expanded: &ExpandedPatchesPolicy, + entries: &[TaskPatchEntry<'_>], + queued: &[(usize, String, camino::Utf8PathBuf)], + decisions: Vec, +) -> Result<(Vec, Vec), ComposeError> { + use crate::core::policy::PathDecision; + let mut decided = vec![PathDecision::Allowed; entries.len()]; + let mut rule_used = vec![false; entries.len()]; + for ((i, item, at), decision) in queued.iter().zip(decisions) { + let form = match decision { + ItemDecision::AllowOnce => PathDecision::Allowed, + ItemDecision::IgnoreOnce => PathDecision::Ignored, + ItemDecision::UseRule => { + rule_used[*i] = true; + match decide_task_patch_path(expanded, entries[*i].source, at) { + PathDecision::NeedsApproval => { + return Err(ComposeError::use_rule_undecided( + HookDomain::Patch, + format!("source path `{item}`"), + )); + } + other => other, + } + } + }; + decided[*i] = decided[*i].combine(form); + } + Ok((decided, rule_used)) +} + /// A declared directory entry's decision: the directory's own path, then /// a deny probe over what it currently holds on this machine. /// @@ -1740,10 +1822,14 @@ fn check_task_patch_entry( /// An absolute entry is also checked as it resolves on this machine, and /// a directory entry is probed for contained files a `deny` names. Both /// can only make the entry stricter (see [`check_task_patch_path`] and -/// [`check_task_patch_dir`]), so a symlink, including a symlinked parent -/// of an entry that does not exist yet, cannot carry it past a deny on -/// its target. On a VM-backed host this machine is not the daemon's, so -/// the extra checks are a best-effort backstop there. +/// [`check_task_patch_dir`]): the resolved form must pass the allow step +/// too, so a symlink, including a symlinked parent of an entry that does +/// not exist yet, cannot carry it past a deny on its target or onto a +/// target no rule allows. When only the resolved form is undecided, the +/// hook is asked about that form, so "allow always" and the refusal +/// snippet record a rule that settles it. On a VM-backed host this +/// machine is not the daemon's, so the extra checks are a best-effort +/// backstop there. /// /// `~/`-rooted entries are matched as declared, with `~/` expanded against /// `home_fallback` the same way the policy's own `~` is. They are neither @@ -1774,6 +1860,7 @@ pub fn gate_task_patch_paths( resolved_vars: &(impl crate::core::expansion::VarLookup + ?Sized), home_fallback: Option<&str>, ) -> Result<(Vec, PatchesPolicy), ComposeError> { + use crate::core::policy::PathDecision; // Same two policies in flight as `gate_patches`: the raw form travels // to and from the hook, the expanded form does the matching. Expanded // first so a malformed pattern surfaces before any filesystem probe. @@ -1802,23 +1889,31 @@ pub fn gate_task_patch_paths( // `Ignored` and queued; pass 3 overwrites every one. The placeholder // is fail-closed on purpose — should a future edit ever leave one // unwritten, the caller drops the entry rather than mounting it. + // Each undecided entry queues every form the policy cannot decide, + // so the hook is asked about each one. let mut verdicts: Vec = Vec::with_capacity(entries.len()); let mut unapproved: Vec = Vec::new(); + let mut queued: Vec<(usize, String, camino::Utf8PathBuf)> = Vec::new(); for (i, entry) in entries.iter().enumerate() { let path = expand_declared(entry.declared); - let verdict = check_task_patch_entry(&expanded, entry, &path, resolvable(entry.declared)); - match verdict { - crate::core::policy::PathDecision::Allowed => verdicts.push(NameVerdict::Allowed), - crate::core::policy::PathDecision::Ignored => verdicts.push(NameVerdict::Ignored), - crate::core::policy::PathDecision::Denied => { + let resolve = resolvable(entry.declared); + match check_task_patch_entry(&expanded, entry, &path, resolve) { + PathDecision::Allowed => verdicts.push(NameVerdict::Allowed), + PathDecision::Ignored => verdicts.push(NameVerdict::Ignored), + PathDecision::Denied => { return Err(ComposeError::Denied { what: entry.declared.to_owned(), from: entry.source.clone(), }); } - crate::core::policy::PathDecision::NeedsApproval => { + PathDecision::NeedsApproval => { unapproved.push(i); verdicts.push(NameVerdict::Ignored); + queued.extend( + undecided_task_patch_forms(&expanded, entry, &path, resolve) + .into_iter() + .map(|(item, at)| (i, item, at)), + ); } } } @@ -1831,14 +1926,15 @@ pub fn gate_task_patch_paths( from: entries[i].source.clone(), }); }; - // Pass 2: prompt, with the expanded form as the user-facing item — - // the prompt reads better as the path the entry names on this - // machine, and a rule chosen for it must expand to match. - let view: Vec> = unapproved + // Pass 2: prompt, one item per undecided form. The declared form + // is shown as written, so a rule chosen for it expands to match + // as the policy's own `~` does; the resolved form is shown as the + // path it reaches. + let view: Vec> = queued .iter() - .map(|&i| Unapproved { - item: camino::Utf8Path::new(entries[i].declared), - source: entries[i].source, + .map(|(i, item, _)| Unapproved { + item: camino::Utf8Path::new(item), + source: entries[*i].source, }) .collect(); let (decisions, new_policy, policy_updated) = prompt_patch_hook(hooks, policy, &view)?; @@ -1846,36 +1942,31 @@ pub fn gate_task_patch_paths( if policy_updated { expanded = policy.expand_with(resolved_vars, home_fallback)?; } - // Pass 3: apply. Only a `UseRule` answer needs the entry decided - // again, against the policy as the hook amended it. - for (&i, decision) in unapproved.iter().zip(decisions) { + // Pass 3: apply. An entry is the stricter of its answered forms. + let (decided, rule_used) = + decide_answered_task_patch_forms(&expanded, entries, &queued, decisions)?; + for &i in &unapproved { let entry = &entries[i]; - verdicts[i] = match decision { - ItemDecision::AllowOnce => NameVerdict::Allowed, - ItemDecision::IgnoreOnce => NameVerdict::Ignored, - ItemDecision::UseRule => { - let path = expand_declared(entry.declared); - match check_task_patch_entry( - &expanded, - entry, - &path, - resolvable(entry.declared), - ) { - crate::core::policy::PathDecision::Allowed => NameVerdict::Allowed, - crate::core::policy::PathDecision::Ignored => NameVerdict::Ignored, - crate::core::policy::PathDecision::Denied => { - return Err(ComposeError::Denied { - what: entry.declared.to_owned(), - from: entry.source.clone(), - }); - } - crate::core::policy::PathDecision::NeedsApproval => { - return Err(ComposeError::use_rule_undecided( - HookDomain::Patch, - format!("source path `{}`", entry.declared), - )); - } - } + let mut outcome = decided[i]; + // An amended policy may also deny what a directory entry + // holds, which its forms alone do not see. + if rule_used[i] { + let path = expand_declared(entry.declared); + match check_task_patch_entry(&expanded, entry, &path, resolvable(entry.declared)) { + PathDecision::NeedsApproval => {} + stricter => outcome = outcome.combine(stricter), + } + } + verdicts[i] = match outcome { + PathDecision::Allowed => NameVerdict::Allowed, + // `NeedsApproval` cannot arise, since only decided forms + // are combined into `decided`; it fails closed regardless. + PathDecision::Ignored | PathDecision::NeedsApproval => NameVerdict::Ignored, + PathDecision::Denied => { + return Err(ComposeError::Denied { + what: entry.declared.to_owned(), + from: entry.source.clone(), + }); } }; } diff --git a/crates/boxes/src/core/compose/tests.rs b/crates/boxes/src/core/compose/tests.rs index 24365c657c..7fec0409e4 100644 --- a/crates/boxes/src/core/compose/tests.rs +++ b/crates/boxes/src/core/compose/tests.rs @@ -2587,9 +2587,11 @@ mod gate_task_patch_paths { fn on_patch_unapproved( &self, _: PatchesPolicy, - _: &[Unapproved<'_, camino::Utf8Path>], + items: &[Unapproved<'_, camino::Utf8Path>], ) -> HookResult { - HookResult::decided(vec![ItemDecision::AllowOnce]) + // One answer per form: on macOS `/home` resolves elsewhere, + // so the entry is asked about twice. + HookResult::decided(vec![ItemDecision::AllowOnce; items.len()]) } } let source = project_source(); @@ -2789,22 +2791,111 @@ mod gate_task_patch_paths { assert!(matches!(err, ComposeError::Denied { .. }), "{err}"); } - /// The resolved form only tightens: an allow on the declared string - /// decides, so a symlinked prefix (macOS's `/tmp` -> `/private/tmp`) - /// does not turn an allowed entry into a prompt. + /// A hook that records every item it is asked about, then answers + /// each with "allow always": the item becomes an allow rule and the + /// answer is `UseRule`, as the interactive prompt does. + #[derive(Default)] + struct AllowAlways(std::cell::RefCell>); + impl crate::core::hooks::PolicyHooks for AllowAlways { + fn on_var_unapproved( + &self, + _: crate::core::policy::VarsPolicy, + _: &[Unapproved<'_, str>], + ) -> HookResult { + panic!("var hook should not have been invoked") + } + fn on_patch_unapproved( + &self, + policy: PatchesPolicy, + items: &[Unapproved<'_, camino::Utf8Path>], + ) -> HookResult { + let names: Vec = items.iter().map(|i| i.item().to_string()).collect(); + self.0.borrow_mut().extend(names.iter().cloned()); + let allow: Vec = policy.allow().iter().cloned().chain(names).collect(); + HookResult::decided_with_policy( + vec![ItemDecision::UseRule; items.len()], + policy.with_allow(allow), + ) + } + } + + /// `/tmp/link` -> `/etc`, for the resolved-form tests. + #[cfg(unix)] + fn tmp_link_to_etc(root: &camino::Utf8Path) -> (camino::Utf8PathBuf, camino::Utf8PathBuf) { + let etc = root.join("etc"); + std::fs::create_dir(etc.as_std_path()).unwrap(); + std::fs::create_dir(root.join("tmp").as_std_path()).unwrap(); + let link = root.join("tmp/link"); + std::os::unix::fs::symlink(etc.as_std_path(), link.as_std_path()).unwrap(); + (link, etc) + } + + /// The resolved form must pass the allow step too: `allow = + /// ["/tmp/**"]` allows the declared `/tmp/link`, but not the `/etc` + /// it points at, so the entry is undecided, never silently allowed. + /// The hook is asked about the resolved form alone, the one that + /// needs a rule. #[cfg(unix)] #[test] - fn a_symlinked_prefix_does_not_unsettle_an_allow_on_the_declared_path() { + fn a_symlink_to_an_unallowed_target_is_not_allowed() { let tmp = tempfile::tempdir().unwrap(); let root = canonical_root(&tmp); - std::fs::create_dir(root.join("real").as_std_path()).unwrap(); - let alias = root.join("alias"); - std::os::unix::fs::symlink(root.join("real").as_std_path(), alias.as_std_path()).unwrap(); - let declared = alias.join("tool"); + let (link, etc) = tmp_link_to_etc(&root); let source = project_source(); - let entries = entries_for(&source, &[(declared.as_str(), true)]); - let policy = PatchesPolicy::default().with_allow(vec![format!("{alias}/**")]); + let entries = entries_for(&source, &[(link.as_str(), false)]); + let policy = PatchesPolicy::default().with_allow(vec![format!("{root}/tmp/**")]); + let err = gate_task_patch_paths(&entries, policy.clone(), None, &NoVars, None).unwrap_err(); + assert!(matches!(err, ComposeError::HookRequired { .. }), "{err}"); + + let hook = AllowAlways::default(); + let (verdicts, _) = + gate_task_patch_paths(&entries, policy, Some(&hook), &NoVars, None).unwrap(); + assert_eq!(*hook.0.borrow(), vec![etc.to_string()]); + assert_eq!(verdicts, vec![NameVerdict::Allowed]); + } + + /// A rule for each form, declared and resolved, allows the entry + /// without asking. + #[cfg(unix)] + #[test] + fn allowing_both_forms_allows_a_symlinked_entry() { + let tmp = tempfile::tempdir().unwrap(); + let root = canonical_root(&tmp); + let (link, etc) = tmp_link_to_etc(&root); + + let source = project_source(); + let entries = entries_for(&source, &[(link.as_str(), false)]); + let policy = + PatchesPolicy::default().with_allow(vec![format!("{root}/tmp/**"), etc.to_string()]); + let (verdicts, _) = gate_task_patch_paths(&entries, policy, None, &NoVars, None).unwrap(); + assert_eq!(verdicts, vec![NameVerdict::Allowed]); + } + + /// With neither form allowed, the hook is asked about both, so "allow + /// always" records both rules and settles the entry rather than + /// failing the `UseRule` contract. + #[cfg(unix)] + #[test] + fn allow_always_records_both_forms_of_a_symlinked_entry() { + let tmp = tempfile::tempdir().unwrap(); + let root = canonical_root(&tmp); + let (link, etc) = tmp_link_to_etc(&root); + + let source = project_source(); + let entries = entries_for(&source, &[(link.as_str(), false)]); + let hook = AllowAlways::default(); + let (verdicts, policy) = gate_task_patch_paths( + &entries, + PatchesPolicy::default(), + Some(&hook), + &NoVars, + None, + ) + .unwrap(); + assert_eq!(*hook.0.borrow(), vec![link.to_string(), etc.to_string()]); + assert_eq!(verdicts, vec![NameVerdict::Allowed]); + // The recorded policy settles the entry on the next run unasked. let (verdicts, _) = gate_task_patch_paths(&entries, policy, None, &NoVars, None).unwrap(); assert_eq!(verdicts, vec![NameVerdict::Allowed]); } @@ -2920,9 +3011,10 @@ mod gate_task_patch_paths { fn on_patch_unapproved( &self, _: PatchesPolicy, - _: &[Unapproved<'_, camino::Utf8Path>], + items: &[Unapproved<'_, camino::Utf8Path>], ) -> HookResult { - HookResult::decided(vec![ItemDecision::UseRule]) + // One answer per form, as above. + HookResult::decided(vec![ItemDecision::UseRule; items.len()]) } } let source = project_source(); diff --git a/docs/reference/user-policy.md b/docs/reference/user-policy.md index e33a80027d..2cb9f46508 100644 --- a/docs/reference/user-policy.md +++ b/docs/reference/user-policy.md @@ -166,8 +166,10 @@ so the rules apply to the **declared path** itself: - `deny` on the declared path, or on any file a declared directory holds, stops the run. - For a declared absolute path, Minimal also checks the path it resolves to on - your machine. A symlink cannot carry the path past a `deny` on its target. - This includes a symlinked parent of a path that does not exist yet. + your machine, and `allow` must match that path too. A symlink cannot carry + the path past a `deny` on its target, or onto a target no rule allows. This + includes a symlinked parent of a path that does not exist yet. When the + resolved path needs a rule, the prompt and the error name it as well. - `ignore` on the declared path leaves that entry out. An `ignore` on a file inside a declared directory does not apply, because a mount cannot leave one file out. From 55b975f46163de3fe81e91508af84b1014334af0 Mon Sep 17 00:00:00 2001 From: "gominimal-aw-bot[bot]" <281738952+gominimal-aw-bot[bot]@users.noreply.github.com> Date: Sat, 17 Oct 2026 23:02:11 -0700 Subject: [PATCH 07/21] docs(reference): split the in-box min run sentence for the prose lint --- docs/reference/tasks.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/reference/tasks.md b/docs/reference/tasks.md index 7ffb43a06a..6e85508b53 100644 --- a/docs/reference/tasks.md +++ b/docs/reference/tasks.md @@ -280,7 +280,7 @@ stops the run, and an ignored path stays out. An uncovered path gets a prompt, w terminal stops the run instead. The daemon refuses a task that declares patches when the `min` that started it did not check them. Inside a session, `min run` refuses a task that declares patches, since no policy check runs -there; run it from the host with `min task run`. +there. Run such a task from the host with `min task run`. ### `inherit_cwd` - Use parent working directory instead of repository root From e7c9feaddaed49d1a06ea7bbad484f4bb1564247 Mon Sep 17 00:00:00 2001 From: "gominimal-aw-bot[bot]" <281738952+gominimal-aw-bot[bot]@users.noreply.github.com> Date: Sun, 18 Oct 2026 00:10:19 -0700 Subject: [PATCH 08/21] fix(task): walk symlinked subdirectories and follow dangling patch links The deny probe over a declared patch directory treated a contained symlink to a directory as one entry, so a deny on a file reached through it was not enforced although the mount keeps the link and exposes the file. The walk now descends such a link at its canonical target, checking each file in its mount form and its on-disk form, and skips canonical directories it has already walked so a link cycle ends the walk. The entry cap stays. A declared path that is a dangling symlink resolved to itself, so only the declared form was checked, while a read-write file mapping writes through the link and creates its target. The resolution now follows a dangling link by hand, relative targets against the link's parent, for at most 40 hops. A link it cannot follow denies the entry. --- crates/boxes/src/core/compose.rs | 116 ++++++++++++++++++++----- crates/boxes/src/core/compose/tests.rs | 77 ++++++++++++++++ docs/reference/user-policy.md | 6 +- 3 files changed, 174 insertions(+), 25 deletions(-) diff --git a/crates/boxes/src/core/compose.rs b/crates/boxes/src/core/compose.rs index 9fd68b1548..f4c016d037 100644 --- a/crates/boxes/src/core/compose.rs +++ b/crates/boxes/src/core/compose.rs @@ -1569,24 +1569,72 @@ fn has_dot_segment(declared: &str) -> bool { declared.split('/').any(|seg| seg == "." || seg == "..") } +/// The most symlinks [`resolve_existing_prefix`] follows by hand, Linux's +/// own `MAXSYMLINKS`. A chain longer than this cannot be mounted anyway. +const TASK_PATCH_LINK_HOPS: usize = 40; + +/// Why [`resolve_existing_prefix`] could not say where a path leads: a +/// dangling symlink it could not follow (unreadable, too many hops, or a +/// target it cannot pin down). The caller denies the entry, since the +/// daemon would write through the link to a path no rule was checked on. +#[derive(Debug)] +struct UnresolvableLink; + /// The path `path` reaches on this machine: its deepest existing ancestor /// canonicalized, with the missing tail joined back on. So a /// `create_if_missing` entry under a symlinked parent resolves to the -/// directory the parent points at. `None` when it resolves to itself or -/// to nothing. -fn resolve_existing_prefix(path: &camino::Utf8Path) -> Option { +/// directory the parent points at. A dangling symlink on the way, which +/// canonicalization cannot see through, is followed by hand: writing a +/// missing `rw` entry creates the link's target, so the target is what +/// must be checked. `Ok(None)` when it resolves to itself. +fn resolve_existing_prefix( + path: &camino::Utf8Path, +) -> Result, UnresolvableLink> { + let resolved = resolve_path(path, 0)?; + Ok(resolved.filter(|out| out != path)) +} + +/// [`resolve_existing_prefix`]'s walk, `hops` links in. `Ok(None)` only +/// for a path that is not UTF-8 once canonicalized, which no rule can +/// match differently from the declared form. +fn resolve_path( + path: &camino::Utf8Path, + hops: usize, +) -> Result, UnresolvableLink> { let mut tail: Vec<&str> = Vec::new(); let mut cur = path; loop { if let Ok(canonical) = std::fs::canonicalize(cur.as_std_path()) { - let mut out = camino::Utf8PathBuf::from_path_buf(canonical).ok()?; + let Ok(mut out) = camino::Utf8PathBuf::from_path_buf(canonical) else { + return Ok(None); + }; for seg in tail.iter().rev() { out.push(seg); } - return (out != path).then_some(out); + return Ok(Some(out)); + } + // `cur` does not resolve. If it is a link, it dangles: follow it + // to where it points, where a write through it would land. + if std::fs::symlink_metadata(cur.as_std_path()).is_ok_and(|m| m.file_type().is_symlink()) { + if hops >= TASK_PATCH_LINK_HOPS { + return Err(UnresolvableLink); + } + let target = std::fs::read_link(cur.as_std_path()).map_err(|_| UnresolvableLink)?; + let target = + camino::Utf8PathBuf::from_path_buf(target).map_err(|_| UnresolvableLink)?; + let mut next = match cur.parent() { + Some(parent) if target.is_relative() => parent.join(target), + _ => target, + }; + for seg in tail.iter().rev() { + next.push(seg); + } + return resolve_path(&next, hops + 1); } - tail.push(cur.file_name()?); - cur = cur.parent()?; + // A `..` from a link's target, under a parent that does not exist, + // has no name to carry: the walk cannot say where it lands. + tail.push(cur.file_name().ok_or(UnresolvableLink)?); + cur = cur.parent().ok_or(UnresolvableLink)?; } } @@ -1615,7 +1663,8 @@ fn decide_task_patch_path( /// path past a deny on its target, nor onto a target no rule allows. A /// symlinked prefix such as macOS's `/tmp` → `/private/tmp` therefore needs /// the resolved form allowed too; the prompt and the refusal snippet name -/// it (see [`task_patch_forms`]). +/// it (see [`task_patch_forms`]). A dangling link that cannot be followed +/// denies the entry ([`UnresolvableLink`]). fn check_task_patch_path( expanded: &ExpandedPatchesPolicy, source: &Source, @@ -1628,8 +1677,9 @@ fn check_task_patch_path( return own; } match resolve_existing_prefix(path) { - Some(resolved) => own.combine(decide_task_patch_path(expanded, source, &resolved)), - None => own, + Ok(Some(resolved)) => own.combine(decide_task_patch_path(expanded, source, &resolved)), + Ok(None) => own, + Err(UnresolvableLink) => PathDecision::Denied, } } @@ -1647,7 +1697,7 @@ fn task_patch_forms( resolve: bool, ) -> Vec<(String, camino::Utf8PathBuf)> { let mut forms = vec![(declared.to_owned(), path.to_path_buf())]; - if resolve && let Some(resolved) = resolve_existing_prefix(path) { + if resolve && let Ok(Some(resolved)) = resolve_existing_prefix(path) { forms.push((resolved.to_string(), resolved)); } forms @@ -1727,6 +1777,9 @@ fn decide_answered_task_patch_forms( /// so a rule naming the declared directory, as the prompt and the refusal /// snippet record it, approves the entry whatever it holds. /// +/// The probe follows a contained symlink to a directory and walks what the +/// target holds, since the mount keeps the link and so exposes it. +/// /// The probe is best-effort: it stops at the first denial and after /// [`TASK_PATCH_DIR_WALK_LIMIT`] entries, and a directory that cannot be /// read (missing for a `create_if_missing` mount, or unreadable) is @@ -1743,12 +1796,21 @@ fn check_task_patch_dir( if !resolve || own == PathDecision::Denied { return own; } - // A symlinked directory (or parent) holds its files where it points, - // so each file is checked under that root as well as the declared one. - let resolved_root = resolve_existing_prefix(dir); + // Lossy rather than skipped: a non-UTF-8 name must still meet a `**` + // deny on its directory. + let utf8 = |p: &std::path::Path| camino::Utf8PathBuf::from(p.to_string_lossy().into_owned()); + // Each directory is walked as it is reached through the mount and as + // it sits on disk, so each file is checked in both forms. A symlinked + // directory (the declared one, or one met mid-walk) holds its files + // where it points, and the mount keeps the link, so it is walked at + // its target. Canonical directories already walked are skipped, which + // ends a link cycle. + let root_canonical = std::fs::canonicalize(dir.as_std_path()).ok(); + let mut visited: std::collections::HashSet = + root_canonical.iter().cloned().collect(); + let mut stack = vec![(dir.as_std_path().to_path_buf(), root_canonical)]; let mut seen = 0usize; - let mut stack = vec![dir.as_std_path().to_path_buf()]; - while let Some(cur) = stack.pop() { + while let Some((cur, canonical)) = stack.pop() { let Ok(read) = std::fs::read_dir(&cur) else { continue; }; @@ -1758,25 +1820,33 @@ fn check_task_patch_dir( return own; } let file_type = entry.file_type().ok(); + let on_disk = canonical.as_ref().map(|c| c.join(entry.file_name())); if file_type.is_some_and(|t| t.is_dir()) { - stack.push(entry.path()); + if on_disk.as_ref().is_none_or(|c| visited.insert(c.clone())) { + stack.push((entry.path(), on_disk)); + } continue; } - // Lossy rather than skipped: a non-UTF-8 name must still - // meet a `**` deny on its directory. - let path = camino::Utf8PathBuf::from(entry.path().to_string_lossy().into_owned()); + let path = utf8(&entry.path()); // Only a symlink reaches somewhere other than its own path, // so only a symlink pays for the resolution. let is_link = file_type.is_some_and(|t| t.is_symlink()); if check_task_patch_path(expanded, source, &path, is_link) == PathDecision::Denied { return PathDecision::Denied; } - if let Some(root) = &resolved_root - && let Ok(rel) = path.strip_prefix(dir) - && decide_task_patch_path(expanded, source, &root.join(rel)) == PathDecision::Denied + if let Some(on_disk) = &on_disk + && *on_disk != entry.path() + && decide_task_patch_path(expanded, source, &utf8(on_disk)) == PathDecision::Denied { return PathDecision::Denied; } + if is_link + && let Ok(target) = std::fs::canonicalize(entry.path()) + && target.is_dir() + && visited.insert(target.clone()) + { + stack.push((entry.path(), Some(target))); + } } } own diff --git a/crates/boxes/src/core/compose/tests.rs b/crates/boxes/src/core/compose/tests.rs index 7fec0409e4..9a1601c275 100644 --- a/crates/boxes/src/core/compose/tests.rs +++ b/crates/boxes/src/core/compose/tests.rs @@ -2791,6 +2791,83 @@ mod gate_task_patch_paths { assert!(matches!(err, ComposeError::Denied { .. }), "{err}"); } + /// A symlink to a directory inside a declared directory is walked at + /// its target, since the mount keeps the link: a declared `/opt/cache` + /// holding `link -> /etc` meets a deny on `/etc/shadow`. + #[cfg(unix)] + #[test] + fn a_symlinked_subdirectory_is_walked_at_its_target() { + let tmp = tempfile::tempdir().unwrap(); + let root = canonical_root(&tmp); + let etc = root.join("etc"); + std::fs::create_dir(etc.as_std_path()).unwrap(); + std::fs::write(etc.join("shadow").as_std_path(), "x").unwrap(); + let cache = root.join("opt/cache"); + std::fs::create_dir_all(cache.as_std_path()).unwrap(); + std::os::unix::fs::symlink(etc.as_std_path(), cache.join("link").as_std_path()).unwrap(); + + let source = project_source(); + let entries = entries_for(&source, &[(cache.as_str(), false)]); + let policy = PatchesPolicy::default() + .with_allow(vec![cache.to_string()]) + .with_deny(vec![format!("{etc}/shadow")]); + let err = gate_task_patch_paths(&entries, policy, None, &NoVars, None).unwrap_err(); + assert!(matches!(err, ComposeError::Denied { .. }), "{err}"); + } + + /// A link cycle inside a declared directory ends the walk rather than + /// looping, and a directory holding nothing denied stays allowed. + #[cfg(unix)] + #[test] + fn a_link_cycle_in_a_declared_directory_ends_the_walk() { + let tmp = tempfile::tempdir().unwrap(); + let root = canonical_root(&tmp); + let cache = root.join("opt/cache"); + std::fs::create_dir_all(cache.join("sub").as_std_path()).unwrap(); + std::os::unix::fs::symlink(cache.as_std_path(), cache.join("sub/up").as_std_path()) + .unwrap(); + std::os::unix::fs::symlink(root.as_std_path(), cache.join("top").as_std_path()).unwrap(); + + let source = project_source(); + let entries = entries_for(&source, &[(cache.as_str(), false)]); + let policy = PatchesPolicy::default() + .with_allow(vec![cache.to_string()]) + .with_deny(vec![format!("{root}/elsewhere")]); + let (verdicts, _) = gate_task_patch_paths(&entries, policy, None, &NoVars, None).unwrap(); + assert_eq!(verdicts, vec![NameVerdict::Allowed]); + } + + /// A declared file that is a dangling symlink is checked at the target + /// it points to, absolute or relative, since writing a missing `rw` + /// entry creates that target. A link that cannot be followed, such as + /// one pointing at itself, denies the entry. + #[cfg(unix)] + #[test] + fn a_dangling_symlinked_entry_meets_the_targets_deny() { + let tmp = tempfile::tempdir().unwrap(); + let root = canonical_root(&tmp); + let ssh = root.join("home/.ssh"); + std::fs::create_dir_all(ssh.as_std_path()).unwrap(); + std::fs::create_dir(root.join("tmp").as_std_path()).unwrap(); + let absolute = root.join("tmp/abs"); + std::os::unix::fs::symlink(ssh.join("authorized_keys2").as_std_path(), &absolute).unwrap(); + let relative = root.join("tmp/rel"); + std::os::unix::fs::symlink("../home/.ssh/authorized_keys2", &relative).unwrap(); + let looped = root.join("tmp/loop"); + std::os::unix::fs::symlink(looped.as_std_path(), &looped).unwrap(); + + let source = project_source(); + for key in [&absolute, &relative, &looped] { + assert!(!key.as_std_path().exists(), "{key} dangles"); + let entries = entries_for(&source, &[(key.as_str(), true)]); + let policy = PatchesPolicy::default() + .with_allow(vec![format!("{root}/tmp/**")]) + .with_deny(vec![format!("{ssh}/**")]); + let err = gate_task_patch_paths(&entries, policy, None, &NoVars, None).unwrap_err(); + assert!(matches!(err, ComposeError::Denied { .. }), "{key}: {err}"); + } + } + /// A hook that records every item it is asked about, then answers /// each with "allow always": the item becomes an allow rule and the /// answer is `UseRule`, as the interactive prompt does. diff --git a/docs/reference/user-policy.md b/docs/reference/user-policy.md index 2cb9f46508..14f074c67e 100644 --- a/docs/reference/user-policy.md +++ b/docs/reference/user-policy.md @@ -164,11 +164,13 @@ so the rules apply to the **declared path** itself: - `allow` must match the path as `minimal.toml` declares it. A rule naming a declared directory approves that directory whatever it holds. - `deny` on the declared path, or on any file a declared directory holds, - stops the run. + stops the run. Minimal follows a symlink to a directory inside a declared + directory and checks the files it reaches, since the mount exposes them. - For a declared absolute path, Minimal also checks the path it resolves to on your machine, and `allow` must match that path too. A symlink cannot carry the path past a `deny` on its target, or onto a target no rule allows. This - includes a symlinked parent of a path that does not exist yet. When the + includes a symlinked parent of a path that does not exist yet, and a + symlink whose target does not exist yet. When the resolved path needs a rule, the prompt and the error name it as well. - `ignore` on the declared path leaves that entry out. An `ignore` on a file inside a declared directory does not apply, because a mount cannot leave From bcd6a25b561c2d35c00c4c491df0ce1d2b639cb6 Mon Sep 17 00:00:00 2001 From: "gominimal-aw-bot[bot]" <281738952+gominimal-aw-bot[bot]@users.noreply.github.com> Date: Sun, 18 Oct 2026 00:10:19 -0700 Subject: [PATCH 09/21] fix(task): bind the patch verdict to each declaration's kind and mode The verdict named allowed patches by key alone. The daemon reads the task from the session workspace, which can differ from the minimal.toml the client checked, so a key allowed as a read-only file could mount read-write, or as a directory that never met the client's deny walk. Each allowed entry now carries its kind and mode, and the daemon refuses a declaration whose kind or mode differs from the one the client checked. --- crates/minimal/src/task.rs | 22 ++++++++-- crates/minimald-rpc/src/taskenv.rs | 60 ++++++++++++++++++++++---- crates/minimald/src/exec.rs | 69 ++++++++++++++++++++++++------ docs/reference/tasks.md | 4 +- 4 files changed, 129 insertions(+), 26 deletions(-) diff --git a/crates/minimal/src/task.rs b/crates/minimal/src/task.rs index 6dc4756aef..9f8ae8b60c 100644 --- a/crates/minimal/src/task.rs +++ b/crates/minimal/src/task.rs @@ -486,12 +486,25 @@ fn resolve_task_patches( }; // Verdicts pair with `entries` in order, each naming its raw declared - // key: an allowed one may mount, an ignored one the daemon removes. + // key: an allowed one may mount, an ignored one the daemon removes. An + // allowed one carries the kind and mode it was checked as, so the + // daemon refuses a declaration that changed either since. let mut out = minimald_rpc::taskenv::PatchVerdict::default(); for (entry, verdict) in entries.iter().zip(verdicts) { let key = entry.declared.to_string(); match verdict { - boxes::core::compose::NameVerdict::Allowed => out.allow.insert(key), + boxes::core::compose::NameVerdict::Allowed => { + let setting = if entry.is_file { + &task.patch.file[entry.declared] + } else { + &task.patch.dir[entry.declared] + }; + out.allow.insert(minimald_rpc::taskenv::AllowedPatch { + path: key, + is_file: entry.is_file, + read_only: matches!(setting, mfile::PatchSetting::ReadOnly), + }) + } boxes::core::compose::NameVerdict::Ignored => out.drop.insert(key), }; } @@ -2239,8 +2252,9 @@ mod tests { ); assert!(verdict.drop.is_empty(), "an approved patch is not dropped"); assert!( - verdict.allow.contains("/opt/tool/bin"), - "an approved patch is named as allowed, or the daemon refuses it" + verdict.allows("/opt/tool/bin", true, true), + "an approved patch is named as allowed, with its kind and mode, or the daemon \ + refuses it" ); } diff --git a/crates/minimald-rpc/src/taskenv.rs b/crates/minimald-rpc/src/taskenv.rs index 45e290b71e..b5dddc5f29 100644 --- a/crates/minimald-rpc/src/taskenv.rs +++ b/crates/minimald-rpc/src/taskenv.rs @@ -111,17 +111,44 @@ pub fn drops_from_channel_env(env_vars: &BTreeMap) -> BTreeSet, + /// Declarations the policy, or the user at its prompt, allowed. + pub allow: BTreeSet, /// Declared keys the policy ignored, to remove before mounting. pub drop: BTreeSet, } +impl PatchVerdict { + /// Whether `allow` names the declaration at `path` with this kind and + /// mode. + #[must_use] + pub fn allows(&self, path: &str, is_file: bool, read_only: bool) -> bool { + self.allow.contains(&AllowedPatch { + path: path.to_string(), + is_file, + read_only, + }) + } +} + +/// One declaration a [`PatchVerdict`] allowed, as the client checked it. +#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, serde::Serialize, serde::Deserialize)] +pub struct AllowedPatch { + /// The declared key, verbatim. + pub path: String, + /// `true` for a `patch.file` entry, `false` for `patch.dir`. + pub is_file: bool, + /// `true` for a read-only declaration, `false` for read-write. + pub read_only: bool, +} + /// Encode a verdict for [`TASK_PATCH_VERDICT`]. /// /// # Errors @@ -360,7 +387,13 @@ mod tests { #[test] fn patch_verdict_round_trips() { let verdict = PatchVerdict { - allow: ["~/.claude".to_string()].into_iter().collect(), + allow: [AllowedPatch { + path: "~/.claude".to_string(), + is_file: false, + read_only: true, + }] + .into_iter() + .collect(), drop: ["/etc/secrets".to_string()].into_iter().collect(), }; let mut channel = BTreeMap::new(); @@ -369,7 +402,14 @@ mod tests { encode_patch_verdict(&verdict).unwrap(), ); - assert_eq!(patch_verdict_from_channel_env(&channel), Some(verdict)); + assert_eq!( + patch_verdict_from_channel_env(&channel), + Some(verdict.clone()) + ); + // The allowed entry is bound to its kind and mode, not its key alone. + assert!(verdict.allows("~/.claude", false, true)); + assert!(!verdict.allows("~/.claude", false, false), "a mode change"); + assert!(!verdict.allows("~/.claude", true, true), "a kind change"); // The carrier is not itself a task variable. assert!(from_channel_env(&channel).is_empty()); // And it is not the env-drop carrier: the two stay separate. @@ -405,7 +445,11 @@ mod tests { let huge = PatchVerdict { allow: (0..TASK_PATCH_VERDICT_MAX_BYTES / 8) - .map(|i| format!("/p/{i}")) + .map(|i| AllowedPatch { + path: format!("/p/{i}"), + is_file: true, + read_only: true, + }) .collect(), drop: BTreeSet::new(), }; diff --git a/crates/minimald/src/exec.rs b/crates/minimald/src/exec.rs index f912728c82..0af4b16268 100644 --- a/crates/minimald/src/exec.rs +++ b/crates/minimald/src/exec.rs @@ -357,14 +357,15 @@ fn parse_task_args( /// is alive for the whole life of this tokio task, which in turn is /// governed by the consumer's stream. /// Apply the client's `[patches]` verdict to a task's declared patches: -/// remove every dropped key, then require every key left to be one the -/// verdict allowed. +/// remove every dropped key, then require every declaration left to be one +/// the verdict allowed, with the kind and mode the client checked. /// /// The daemon holds no policy, so this is the only thing standing between /// a project's `patch` declarations and a mount. It fails closed: a task /// that declares patches with no verdict (an older `min`, or a verdict /// this daemon could not read) is refused, and so is a key the verdict -/// does not name, since the client never checked it. A task that +/// does not name, or names as another kind or mode, since the client never +/// checked that declaration. A task that /// declares no patches needs no verdict. /// /// # Errors @@ -390,12 +391,21 @@ fn apply_patch_verdict( patch.dir.remove(key); patch.file.remove(key); } - if let Some(key) = patch + // An allowed key must also keep the kind and mode it was checked as: + // the client walks a directory and not a file, and a read-only entry + // that is now read-write would be writable, and created if missing. + let declared = patch .dir - .keys() - .chain(patch.file.keys()) - .find(|key| !verdict.allow.contains(*key)) - { + .iter() + .map(|(key, setting)| (key, false, setting)) + .chain(patch.file.iter().map(|(key, setting)| (key, true, setting))); + if let Some((key, _, _)) = declared.into_iter().find(|(key, is_file, setting)| { + !verdict.allows( + key, + *is_file, + matches!(setting, mfile::PatchSetting::ReadOnly), + ) + }) { return Err(format!( "task '{task_name}' declares the patch path `{key}`, which `min` \ did not check against your [patches] policy, so the task did not \ @@ -434,7 +444,7 @@ pub(crate) fn refuse_in_box_patches( #[cfg(test)] mod patch_verdict_tests { use super::{apply_patch_verdict, refuse_in_box_patches}; - use minimald_rpc::taskenv::PatchVerdict; + use minimald_rpc::taskenv::{AllowedPatch, PatchVerdict}; fn patches(dirs: &[&str], files: &[&str]) -> mfile::EnvPatches { let mut p = mfile::EnvPatches::default(); @@ -449,9 +459,18 @@ mod patch_verdict_tests { p } - fn verdict(allow: &[&str], drop: &[&str]) -> PatchVerdict { + /// A verdict allowing each `(key, is_file)` read-only, the mode + /// [`patches`] declares. + fn verdict(allow: &[(&str, bool)], drop: &[&str]) -> PatchVerdict { PatchVerdict { - allow: allow.iter().map(|s| (*s).to_string()).collect(), + allow: allow + .iter() + .map(|(path, is_file)| AllowedPatch { + path: (*path).to_string(), + is_file: *is_file, + read_only: true, + }) + .collect(), drop: drop.iter().map(|s| (*s).to_string()).collect(), } } @@ -478,7 +497,10 @@ mod patch_verdict_tests { #[test] fn dropped_keys_go_and_allowed_keys_stay() { let mut p = patches(&["/opt/cache"], &["/etc/token", "~/.claude.json"]); - let v = verdict(&["/opt/cache", "~/.claude.json"], &["/etc/token"]); + let v = verdict( + &[("/opt/cache", false), ("~/.claude.json", true)], + &["/etc/token"], + ); apply_patch_verdict("t", &mut p, Some(&v)).expect("every key was gated"); assert!(p.dir.contains_key("/opt/cache")); assert!(p.file.contains_key("~/.claude.json")); @@ -490,11 +512,32 @@ mod patch_verdict_tests { #[test] fn a_key_the_verdict_does_not_name_is_refused() { let mut p = patches(&["/opt/cache"], &["/etc/shadow"]); - let v = verdict(&["/opt/cache"], &[]); + let v = verdict(&[("/opt/cache", false)], &[]); let err = apply_patch_verdict("t", &mut p, Some(&v)).unwrap_err(); assert!(err.contains("`/etc/shadow`"), "{err}"); } + /// A key the client allowed as a read-only file is refused once it is + /// declared read-write, or as a directory: the client checked neither. + #[test] + fn a_key_whose_kind_or_mode_changed_is_refused() { + let v = verdict(&[("/opt/tool/bin", true)], &[]); + + let mut same = patches(&[], &["/opt/tool/bin"]); + apply_patch_verdict("t", &mut same, Some(&v)).expect("as the client checked it"); + + let mut writable = patches(&[], &[]); + writable + .file + .insert("/opt/tool/bin".to_string(), mfile::PatchSetting::ReadWrite); + let err = apply_patch_verdict("t", &mut writable, Some(&v)).unwrap_err(); + assert!(err.contains("`/opt/tool/bin`"), "{err}"); + + let mut as_dir = patches(&["/opt/tool/bin"], &[]); + let err = apply_patch_verdict("t", &mut as_dir, Some(&v)).unwrap_err(); + assert!(err.contains("`/opt/tool/bin`"), "{err}"); + } + /// An in-box run refuses any declared patch, dir or file, and names /// the host-side command; a task without patches passes. #[test] diff --git a/docs/reference/tasks.md b/docs/reference/tasks.md index 6e85508b53..be6bcb1d60 100644 --- a/docs/reference/tasks.md +++ b/docs/reference/tasks.md @@ -278,7 +278,9 @@ Before `min task run` or `min session run` starts the task, Minimal checks each against the `[patches]` section of your [user policy](./user-policy.md#task-patches). A denied path stops the run, and an ignored path stays out. An uncovered path gets a prompt, which without a terminal stops the run instead. The daemon refuses a task that declares -patches when the `min` that started it did not check them. Inside a session, +patches when the `min` that started it did not check them. It also refuses +a patch whose path, kind (`dir` or `file`) or mode differs from the one +`min` checked. Inside a session, `min run` refuses a task that declares patches, since no policy check runs there. Run such a task from the host with `min task run`. From 69642d43e100edc78a0ae6739525d453415d7cd4 Mon Sep 17 00:00:00 2001 From: "gominimal-aw-bot[bot]" <281738952+gominimal-aw-bot[bot]@users.noreply.github.com> Date: Sun, 18 Oct 2026 12:46:13 -0700 Subject: [PATCH 10/21] fix(task): gate an echo task's patches like any other task's The daemon answers an echo task from its declaration only when the session workspace minimal.toml declares it as one. A stack-provided echo task, or one whose workspace copy differs, reaches the mount path, where the empty verdict the client sent was refused as if min were too old. Drop the client's echo exemption: a task with no patches still gets an empty verdict and no prompt. --- crates/minimal/src/task.rs | 44 +++++++++++++++++++++++++++----------- 1 file changed, 32 insertions(+), 12 deletions(-) diff --git a/crates/minimal/src/task.rs b/crates/minimal/src/task.rs index 9f8ae8b60c..7d2119cacd 100644 --- a/crates/minimal/src/task.rs +++ b/crates/minimal/src/task.rs @@ -417,6 +417,12 @@ fn denied_task_patch_message(task_name: &str, path: &str, policy_path: &std::pat /// ignored, for the daemon to drop from the mount set. The daemon holds /// no policy, mounts only allowed keys, and refuses a task whose patches /// arrive with no verdict. +/// +/// An echo task is gated like any other. The daemon answers one from the +/// declaration only when its session-workspace `minimal.toml` declares it +/// as an echo; a stack-provided echo task, or one whose workspace copy +/// differs, reaches the mount path and needs this verdict. A task that +/// declares no patches gets an empty verdict without a prompt. fn resolve_task_patches( task: &mfile::Task, task_name: &str, @@ -428,12 +434,6 @@ fn resolve_task_patches( ) -> Result { use boxes::core::compose::{TaskPatchEntry, gate_task_patch_paths}; - // Echo tasks never reach the daemon's mount path — the daemon answers - // an echo from the declaration itself — so there is nothing to gate. - if task.action.as_echo().is_some() { - return Ok(Default::default()); - } - // The gate expands policy patterns through this lookup. A pattern // naming `$HOME` is the common case for patches, so the resolved // task vars share the lookup with the client's own home — the same @@ -2193,11 +2193,11 @@ mod tests { assert!(verdict.allow.is_empty(), "nothing ignored is allowed"); } - /// An echo task's patches are gated by nobody, the same exemption as - /// its `env_vars`: the daemon answers an echo from the declaration - /// and returns before it builds an environment to mount into. + /// An echo task's patches are gated like any other task's: the daemon + /// short-circuits only an echo its workspace `minimal.toml` declares, + /// so a stack-provided one reaches the mount path and needs a verdict. #[test] - fn an_echo_task_gates_no_patches_whatever_it_declares() { + fn an_echo_task_gates_its_patches_like_any_task() { let task = task_from_toml( "[tasks.t]\necho = 'hi'\n[tasks.t.patch.file]\n\"/etc/passwd\" = \"ro\"\n", ); @@ -2205,7 +2205,7 @@ mod tests { let policy = boxes::core::policy::PatchesPolicy::default() .with_deny(vec!["/etc/passwd".to_string()]); - let verdict = resolve_task_patches( + let err = resolve_task_patches( &task, "t", policy, @@ -2214,7 +2214,27 @@ mod tests { &NeverAsked, &minimald_rpc::taskenv::TaskEnv::default(), ) - .expect("an echo task neither resolves nor denies"); + .expect_err("a denied patch on an echo task must fail the run"); + assert!(err.to_string().contains("`/etc/passwd`"), "{err}"); + } + + /// An echo task that declares no patches gets an empty verdict and no + /// prompt, so gating it costs nothing. + #[test] + fn an_echo_task_without_patches_gets_an_empty_verdict() { + let task = task_from_toml("[tasks.t]\necho = 'hi'\n"); + assert_eq!(task.action.as_echo(), Some("hi")); + + let verdict = resolve_task_patches( + &task, + "t", + boxes::core::policy::PatchesPolicy::default(), + &policy_path_fixture(), + &project_source(), + &NeverAsked, + &minimald_rpc::taskenv::TaskEnv::default(), + ) + .expect("nothing to gate"); assert_eq!( verdict, From 4f2d05ea93eb2124d2a67bb4a8e909d9c780ede6 Mon Sep 17 00:00:00 2001 From: "gominimal-aw-bot[bot]" <281738952+gominimal-aw-bot[bot]@users.noreply.github.com> Date: Sun, 18 Oct 2026 13:04:37 -0700 Subject: [PATCH 11/21] fix(boxes): refuse a task patch directory the deny walk cannot finish With a [patches] deny set, check_task_patch_dir now refuses a declared directory whose walk stops early instead of falling back to the directory's own decision: more than TASK_PATCH_DIR_WALK_LIMIT entries, or a directory in the tree that cannot be read for any reason other than NotFound. The refusal travels as ComposeError::TaskPatchUnchecked with a TaskPatchWalkGap reason, and min names it. With no deny rule nothing is walked. The limit rises from 10,000 to 100,000. --- crates/boxes/src/core/compose.rs | 116 +++++++++++++++++++------ crates/boxes/src/core/compose/tests.rs | 98 +++++++++++++++++++++ crates/minimal/src/task.rs | 57 ++++++++++++ docs/reference/user-policy.md | 2 + 4 files changed, 246 insertions(+), 27 deletions(-) diff --git a/crates/boxes/src/core/compose.rs b/crates/boxes/src/core/compose.rs index f4c016d037..07eec38801 100644 --- a/crates/boxes/src/core/compose.rs +++ b/crates/boxes/src/core/compose.rs @@ -529,6 +529,18 @@ pub enum ComposeError { /// [`gate_task_patch_paths`]. #[error("the patch path `{what}` (from {from}) holds a `.` or `..` segment")] TaskPatchDotSegment { what: String, from: Source }, + /// A task's declared `patch.dir` entry could not be checked file by + /// file against a `[patches] deny`: the walk of what it holds could + /// not finish. The entry is refused rather than mounted unchecked. + /// Surfaces from [`gate_task_patch_paths`]. + #[error( + "the patch directory `{what}` (from {from}) cannot be checked against [patches] deny: {gap}" + )] + TaskPatchUnchecked { + what: String, + from: Source, + gap: TaskPatchWalkGap, + }, /// User cancelled at the prompt. #[error("user aborted session construction")] Aborted, @@ -1556,10 +1568,30 @@ pub struct TaskPatchEntry<'a> { } /// Upper bound on the entries a directory walk in [`check_task_patch_dir`] -/// visits. The walk is a best-effort deny probe of this machine's view of -/// the directory, so a huge tree stops it rather than stalling every -/// `min task run`. -const TASK_PATCH_DIR_WALK_LIMIT: usize = 10_000; +/// visits, so a huge tree stops the walk rather than stalling every +/// `min task run`. Reaching it refuses the entry. +const TASK_PATCH_DIR_WALK_LIMIT: usize = 100_000; + +/// Why [`check_task_patch_dir`] could not check every file a directory +/// holds against `[patches] deny`. Either one refuses the entry +/// ([`ComposeError::TaskPatchUnchecked`]). +#[derive(Debug)] +pub enum TaskPatchWalkGap { + /// The directory holds more than `limit` entries. + TooLarge { limit: usize }, + /// The directory at `dir`, the declared one or one inside it, could + /// not be read. + Unreadable { dir: String, error: std::io::Error }, +} + +impl fmt::Display for TaskPatchWalkGap { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::TooLarge { limit } => write!(f, "it holds more than {limit} entries"), + Self::Unreadable { dir, error } => write!(f, "{dir} cannot be read ({error})"), + } + } +} /// Whether a declared key holds a `.` or `..` segment. The daemon hands /// the raw key to the OS, which resolves `..` after any symlinked parent, @@ -1780,22 +1812,32 @@ fn decide_answered_task_patch_forms( /// The probe follows a contained symlink to a directory and walks what the /// target holds, since the mount keeps the link and so exposes it. /// -/// The probe is best-effort: it stops at the first denial and after -/// [`TASK_PATCH_DIR_WALK_LIMIT`] entries, and a directory that cannot be -/// read (missing for a `create_if_missing` mount, or unreadable) is -/// decided by its own path alone. Only an entry checked with `resolve` -/// is walked; see [`gate_task_patch_paths`] for why `~/` entries are not. +/// With no `deny` rule there is nothing to probe for, so the directory's +/// own decision stands and nothing is walked. With one, the walk must +/// check every file or the entry is refused: more than `limit` entries +/// ([`TASK_PATCH_DIR_WALK_LIMIT`] in use), or a directory in the tree that +/// cannot be read, gives [`TaskPatchWalkGap`]. A directory that is not +/// found is skipped: a declared one missing for a `create_if_missing` +/// mount holds nothing yet, and one inside it vanished during the walk. +/// The walk stops at the first denial. Only an entry checked with +/// `resolve` is walked; see [`gate_task_patch_paths`] for why `~/` +/// entries are not. fn check_task_patch_dir( expanded: &ExpandedPatchesPolicy, source: &Source, dir: &camino::Utf8Path, resolve: bool, -) -> crate::core::policy::PathDecision { + limit: usize, +) -> Result { use crate::core::policy::PathDecision; let own = check_task_patch_path(expanded, source, dir, resolve); - if !resolve || own == PathDecision::Denied { - return own; + if !resolve || own == PathDecision::Denied || expanded.deny().is_empty() { + return Ok(own); } + let unreadable = |cur: &std::path::Path, error| TaskPatchWalkGap::Unreadable { + dir: cur.to_string_lossy().into_owned(), + error, + }; // Lossy rather than skipped: a non-UTF-8 name must still meet a `**` // deny on its directory. let utf8 = |p: &std::path::Path| camino::Utf8PathBuf::from(p.to_string_lossy().into_owned()); @@ -1811,13 +1853,16 @@ fn check_task_patch_dir( let mut stack = vec![(dir.as_std_path().to_path_buf(), root_canonical)]; let mut seen = 0usize; while let Some((cur, canonical)) = stack.pop() { - let Ok(read) = std::fs::read_dir(&cur) else { - continue; + let read = match std::fs::read_dir(&cur) { + Ok(read) => read, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => continue, + Err(e) => return Err(unreadable(&cur, e)), }; - for entry in read.flatten() { + for entry in read { + let entry = entry.map_err(|e| unreadable(&cur, e))?; seen += 1; - if seen > TASK_PATCH_DIR_WALK_LIMIT { - return own; + if seen > limit { + return Err(TaskPatchWalkGap::TooLarge { limit }); } let file_type = entry.file_type().ok(); let on_disk = canonical.as_ref().map(|c| c.join(entry.file_name())); @@ -1832,13 +1877,13 @@ fn check_task_patch_dir( // so only a symlink pays for the resolution. let is_link = file_type.is_some_and(|t| t.is_symlink()); if check_task_patch_path(expanded, source, &path, is_link) == PathDecision::Denied { - return PathDecision::Denied; + return Ok(PathDecision::Denied); } if let Some(on_disk) = &on_disk && *on_disk != entry.path() && decide_task_patch_path(expanded, source, &utf8(on_disk)) == PathDecision::Denied { - return PathDecision::Denied; + return Ok(PathDecision::Denied); } if is_link && let Ok(target) = std::fs::canonicalize(entry.path()) @@ -1849,22 +1894,37 @@ fn check_task_patch_dir( } } } - own + Ok(own) } /// A declared entry's decision: the file form checks its one path, the /// directory form also probes the files it currently holds. +/// +/// # Errors +/// +/// [`ComposeError::TaskPatchUnchecked`] when a directory's probe could +/// not finish ([`check_task_patch_dir`]). fn check_task_patch_entry( expanded: &ExpandedPatchesPolicy, entry: &TaskPatchEntry<'_>, path: &camino::Utf8Path, resolve: bool, -) -> crate::core::policy::PathDecision { +) -> Result { if entry.is_file { - check_task_patch_path(expanded, entry.source, path, resolve) - } else { - check_task_patch_dir(expanded, entry.source, path, resolve) - } + return Ok(check_task_patch_path(expanded, entry.source, path, resolve)); + } + check_task_patch_dir( + expanded, + entry.source, + path, + resolve, + TASK_PATCH_DIR_WALK_LIMIT, + ) + .map_err(|gap| ComposeError::TaskPatchUnchecked { + what: entry.declared.to_owned(), + from: entry.source.clone(), + gap, + }) } /// Drive the `[patches]` policy over a task's declared `patch.dir` / @@ -1915,6 +1975,8 @@ fn check_task_patch_entry( /// path is never preceded by a prompt about its neighbours. /// - [`ComposeError::TaskPatchDotSegment`] — a declared key holds a `.` /// or `..` segment. Checked before anything else. +/// - [`ComposeError::TaskPatchUnchecked`] — a `deny` rule is set and a +/// directory entry's probe could not check every file it holds. /// - [`ComposeError::HookRequired`] — an entry needed approval and there /// was no hook to ask. /// - [`ComposeError::Aborted`] — the hook cancelled. @@ -1967,7 +2029,7 @@ pub fn gate_task_patch_paths( for (i, entry) in entries.iter().enumerate() { let path = expand_declared(entry.declared); let resolve = resolvable(entry.declared); - match check_task_patch_entry(&expanded, entry, &path, resolve) { + match check_task_patch_entry(&expanded, entry, &path, resolve)? { PathDecision::Allowed => verdicts.push(NameVerdict::Allowed), PathDecision::Ignored => verdicts.push(NameVerdict::Ignored), PathDecision::Denied => { @@ -2022,7 +2084,7 @@ pub fn gate_task_patch_paths( // holds, which its forms alone do not see. if rule_used[i] { let path = expand_declared(entry.declared); - match check_task_patch_entry(&expanded, entry, &path, resolvable(entry.declared)) { + match check_task_patch_entry(&expanded, entry, &path, resolvable(entry.declared))? { PathDecision::NeedsApproval => {} stricter => outcome = outcome.combine(stricter), } diff --git a/crates/boxes/src/core/compose/tests.rs b/crates/boxes/src/core/compose/tests.rs index 9a1601c275..c19410445e 100644 --- a/crates/boxes/src/core/compose/tests.rs +++ b/crates/boxes/src/core/compose/tests.rs @@ -3108,4 +3108,102 @@ mod gate_task_patch_paths { // error, not a silent allow. assert!(err.to_string().contains("UseRule returned for a patch")); } + + /// An allowed directory holding `n` plain files, with its policy's + /// `allow` naming it and `deny` set to `deny`. + fn allowed_dir_with_files( + tmp: &tempfile::TempDir, + n: usize, + deny: Vec, + ) -> ( + camino::Utf8PathBuf, + crate::core::policy::ExpandedPatchesPolicy, + ) { + let dir = canonical_root(tmp).join("data"); + std::fs::create_dir(dir.as_std_path()).unwrap(); + for i in 0..n { + std::fs::write(dir.join(format!("f{i}")).as_std_path(), "x").unwrap(); + } + let policy = PatchesPolicy::default() + .with_allow(vec![dir.to_string()]) + .with_deny(deny) + .expand_with(&NoVars, None) + .unwrap(); + (dir, policy) + } + + /// With a deny set, a directory holding more entries than the walk + /// visits is refused: the files past the limit went unchecked. + #[test] + fn a_directory_over_the_walk_limit_is_refused_under_a_deny() { + use crate::core::compose::{TaskPatchWalkGap, check_task_patch_dir}; + let tmp = tempfile::tempdir().unwrap(); + let (dir, policy) = allowed_dir_with_files(&tmp, 4, vec!["/nowhere/**".to_string()]); + let source = project_source(); + let gap = check_task_patch_dir(&policy, &source, &dir, true, 3).unwrap_err(); + assert!( + matches!(gap, TaskPatchWalkGap::TooLarge { limit: 3 }), + "{gap}" + ); + // At the limit, every entry was checked. + let decision = check_task_patch_dir(&policy, &source, &dir, true, 4).unwrap(); + assert_eq!(decision, crate::core::policy::PathDecision::Allowed); + } + + /// With no deny set, nothing is walked, so a directory over the limit + /// keeps its own decision. + #[test] + fn a_directory_over_the_walk_limit_keeps_its_own_decision_without_a_deny() { + use crate::core::compose::check_task_patch_dir; + let tmp = tempfile::tempdir().unwrap(); + let (dir, policy) = allowed_dir_with_files(&tmp, 4, Vec::new()); + let source = project_source(); + let decision = check_task_patch_dir(&policy, &source, &dir, true, 3).unwrap(); + assert_eq!(decision, crate::core::policy::PathDecision::Allowed); + } + + /// With a deny set, a directory holding a subdirectory that cannot be + /// read is refused, naming the subdirectory: a file in it could match + /// the deny. + #[cfg(unix)] + #[test] + fn a_directory_holding_an_unreadable_subdirectory_is_refused_under_a_deny() { + use std::os::unix::fs::PermissionsExt; + let tmp = tempfile::tempdir().unwrap(); + let root = canonical_root(&tmp); + let dir = root.join("data"); + let locked = dir.join("locked"); + std::fs::create_dir_all(locked.as_std_path()).unwrap(); + std::fs::set_permissions(locked.as_std_path(), std::fs::Permissions::from_mode(0o000)) + .unwrap(); + // Root reads it regardless, so there is nothing to refuse. + if std::fs::read_dir(locked.as_std_path()).is_ok() { + std::fs::set_permissions(locked.as_std_path(), std::fs::Permissions::from_mode(0o755)) + .unwrap(); + eprintln!("skipped: running as root, a 0o000 directory is readable"); + return; + } + + let source = project_source(); + let entries = entries_for(&source, &[(dir.as_str(), false)]); + let policy = PatchesPolicy::default() + .with_allow(vec![dir.to_string()]) + .with_deny(vec!["/nowhere/**".to_string()]); + let err = gate_task_patch_paths(&entries, policy, None, &NoVars, None).unwrap_err(); + // Restored first, so the temp dir is removable whatever happens. + std::fs::set_permissions(locked.as_std_path(), std::fs::Permissions::from_mode(0o755)) + .unwrap(); + match err { + ComposeError::TaskPatchUnchecked { + what, + gap: crate::core::compose::TaskPatchWalkGap::Unreadable { dir: at, error }, + .. + } => { + assert_eq!(what, dir.as_str()); + assert_eq!(at, locked.as_str()); + assert_eq!(error.kind(), std::io::ErrorKind::PermissionDenied); + } + other => panic!("expected an unreadable refusal, got {other}"), + } + } } diff --git a/crates/minimal/src/task.rs b/crates/minimal/src/task.rs index 7d2119cacd..b8f4a06eae 100644 --- a/crates/minimal/src/task.rs +++ b/crates/minimal/src/task.rs @@ -479,6 +479,9 @@ fn resolve_task_patches( Err(boxes::core::compose::ComposeError::TaskPatchDotSegment { what, .. }) => { bail!(dot_segment_task_patch_message(task_name, &what)) } + Err(boxes::core::compose::ComposeError::TaskPatchUnchecked { what, gap, .. }) => { + bail!(unchecked_task_patch_message(task_name, &what, &gap)) + } Err(e) => { return Err(anyhow::Error::new(e)) .with_context(|| format!("gating `patch` for task '{task_name}'")); @@ -521,6 +524,28 @@ fn dot_segment_task_patch_message(task_name: &str, path: &str) -> String { ) } +/// The rejection body for a declared patch directory whose files could +/// not all be checked against `[patches] deny`. Split out for unit tests. +fn unchecked_task_patch_message( + task_name: &str, + path: &str, + gap: &boxes::core::compose::TaskPatchWalkGap, +) -> String { + use boxes::core::compose::TaskPatchWalkGap; + match gap { + TaskPatchWalkGap::TooLarge { limit } => format!( + "task '{task_name}': cannot check every file in patch directory {path} \ + against your [patches] deny rules: it holds more than {limit} entries. \ + Declare a smaller directory inside it, the part the task needs." + ), + TaskPatchWalkGap::Unreadable { dir, error } => format!( + "task '{task_name}': cannot check patch directory {path} against your \ + [patches] deny rules: {dir} cannot be read ({error}). Make it readable, \ + or declare a directory that leaves it out." + ), + } +} + /// Why a policy refusal could not become a prompt, for the refusal text: /// `--no-input` when the user set it, otherwise the terminal check. fn no_prompt_reason(no_input: bool) -> &'static str { @@ -1973,6 +1998,38 @@ mod tests { assert!(out.is_empty(), "nothing to send: {out:?}"); } + /// A patch directory the deny probe could not finish is refused with + /// the reason, and the refusal never suggests dropping a deny rule. + #[test] + fn an_unchecked_patch_directory_is_reported_with_the_reason() { + use boxes::core::compose::TaskPatchWalkGap; + let msg = unchecked_task_patch_message( + "t", + "/data", + &TaskPatchWalkGap::TooLarge { limit: 100_000 }, + ); + assert_eq!( + msg, + "task 't': cannot check every file in patch directory /data against your \ + [patches] deny rules: it holds more than 100000 entries. Declare a smaller \ + directory inside it, the part the task needs." + ); + let msg = unchecked_task_patch_message( + "t", + "/data", + &TaskPatchWalkGap::Unreadable { + dir: "/data/locked".to_owned(), + error: std::io::Error::from(std::io::ErrorKind::PermissionDenied), + }, + ); + assert_eq!( + msg, + "task 't': cannot check patch directory /data against your [patches] deny \ + rules: /data/locked cannot be read (permission denied). Make it readable, or \ + declare a directory that leaves it out." + ); + } + /// A denied patch path is reported with the task, the declared path, /// and the policy file the rule lives in. #[test] diff --git a/docs/reference/user-policy.md b/docs/reference/user-policy.md index 14f074c67e..8e1519b51a 100644 --- a/docs/reference/user-policy.md +++ b/docs/reference/user-policy.md @@ -166,6 +166,8 @@ so the rules apply to the **declared path** itself: - `deny` on the declared path, or on any file a declared directory holds, stops the run. Minimal follows a symlink to a directory inside a declared directory and checks the files it reaches, since the mount exposes them. + If a directory is too large or partly unreadable to check against your deny + rules, the run stops and names the reason. - For a declared absolute path, Minimal also checks the path it resolves to on your machine, and `allow` must match that path too. A symlink cannot carry the path past a `deny` on its target, or onto a target no rule allows. This From ff709ba95883162678e81118a5cb204de41120fd Mon Sep 17 00:00:00 2001 From: "gominimal-aw-bot[bot]" <281738952+gominimal-aw-bot[bot]@users.noreply.github.com> Date: Sun, 18 Oct 2026 13:08:26 -0700 Subject: [PATCH 12/21] fix(boxes): refuse a task patch directory that is a file as a file When the deny walk's read of the declared directory fails with ENOTDIR, the refusal now says the entry is a file and points at patch.file, through a new TaskPatchWalkGap::NotADirectory. A subdirectory that turns into a file mid-walk still reports Unreadable. --- crates/boxes/src/core/compose.rs | 8 ++++++++ crates/boxes/src/core/compose/tests.rs | 27 ++++++++++++++++++++++++++ crates/minimal/src/task.rs | 10 ++++++++++ 3 files changed, 45 insertions(+) diff --git a/crates/boxes/src/core/compose.rs b/crates/boxes/src/core/compose.rs index 07eec38801..1a29e78691 100644 --- a/crates/boxes/src/core/compose.rs +++ b/crates/boxes/src/core/compose.rs @@ -1582,6 +1582,8 @@ pub enum TaskPatchWalkGap { /// The directory at `dir`, the declared one or one inside it, could /// not be read. Unreadable { dir: String, error: std::io::Error }, + /// The declared directory is a file. + NotADirectory, } impl fmt::Display for TaskPatchWalkGap { @@ -1589,6 +1591,7 @@ impl fmt::Display for TaskPatchWalkGap { match self { Self::TooLarge { limit } => write!(f, "it holds more than {limit} entries"), Self::Unreadable { dir, error } => write!(f, "{dir} cannot be read ({error})"), + Self::NotADirectory => write!(f, "it is a file, not a directory"), } } } @@ -1819,6 +1822,8 @@ fn decide_answered_task_patch_forms( /// cannot be read, gives [`TaskPatchWalkGap`]. A directory that is not /// found is skipped: a declared one missing for a `create_if_missing` /// mount holds nothing yet, and one inside it vanished during the walk. +/// A declared directory that is a file gives +/// [`TaskPatchWalkGap::NotADirectory`]. /// The walk stops at the first denial. Only an entry checked with /// `resolve` is walked; see [`gate_task_patch_paths`] for why `~/` /// entries are not. @@ -1856,6 +1861,9 @@ fn check_task_patch_dir( let read = match std::fs::read_dir(&cur) { Ok(read) => read, Err(e) if e.kind() == std::io::ErrorKind::NotFound => continue, + Err(e) if cur == dir.as_std_path() && e.kind() == std::io::ErrorKind::NotADirectory => { + return Err(TaskPatchWalkGap::NotADirectory); + } Err(e) => return Err(unreadable(&cur, e)), }; for entry in read { diff --git a/crates/boxes/src/core/compose/tests.rs b/crates/boxes/src/core/compose/tests.rs index c19410445e..2241568499 100644 --- a/crates/boxes/src/core/compose/tests.rs +++ b/crates/boxes/src/core/compose/tests.rs @@ -3206,4 +3206,31 @@ mod gate_task_patch_paths { other => panic!("expected an unreadable refusal, got {other}"), } } + + /// With a deny set, a `patch.dir` entry naming a regular file is + /// refused as a file, not reported as unreadable. + #[test] + fn a_directory_entry_naming_a_file_is_refused_under_a_deny() { + let tmp = tempfile::tempdir().unwrap(); + let file = canonical_root(&tmp).join("notes.txt"); + std::fs::write(file.as_std_path(), "x").unwrap(); + + let source = project_source(); + let entries = entries_for(&source, &[(file.as_str(), false)]); + let policy = PatchesPolicy::default() + .with_allow(vec![file.to_string()]) + .with_deny(vec!["/nowhere/**".to_string()]); + let err = gate_task_patch_paths(&entries, policy, None, &NoVars, None).unwrap_err(); + assert!( + matches!( + err, + ComposeError::TaskPatchUnchecked { + ref what, + gap: crate::core::compose::TaskPatchWalkGap::NotADirectory, + .. + } if what == file.as_str() + ), + "{err}" + ); + } } diff --git a/crates/minimal/src/task.rs b/crates/minimal/src/task.rs index b8f4a06eae..c3a581e7cf 100644 --- a/crates/minimal/src/task.rs +++ b/crates/minimal/src/task.rs @@ -543,6 +543,10 @@ fn unchecked_task_patch_message( [patches] deny rules: {dir} cannot be read ({error}). Make it readable, \ or declare a directory that leaves it out." ), + TaskPatchWalkGap::NotADirectory => format!( + "task '{task_name}': patch directory {path} is a file, not a directory. \ + Declare it under patch.file instead." + ), } } @@ -2028,6 +2032,12 @@ mod tests { rules: /data/locked cannot be read (permission denied). Make it readable, or \ declare a directory that leaves it out." ); + let msg = unchecked_task_patch_message("t", "/data", &TaskPatchWalkGap::NotADirectory); + assert_eq!( + msg, + "task 't': patch directory /data is a file, not a directory. Declare it under \ + patch.file instead." + ); } /// A denied patch path is reported with the task, the declared path, From ecfe8003d1ec34f286a6afe65c3fd39d42bcb0c4 Mon Sep 17 00:00:00 2001 From: "gominimal-aw-bot[bot]" <281738952+gominimal-aw-bot[bot]@users.noreply.github.com> Date: Sun, 18 Oct 2026 13:15:42 -0700 Subject: [PATCH 13/21] fix(minimald): drop a task patch only from the map of its kind The patch verdict's drop list now carries each key with its kind, as allow does, so a path declared under both patch.dir and patch.file loses only the entry the client ignored. apply_patch_verdict and its tests move above task_producer's doc comment, which sits on task_producer again. --- crates/minimal/src/task.rs | 24 +++++++++++---- crates/minimald-rpc/src/taskenv.rs | 26 +++++++++++++--- crates/minimald/src/exec.rs | 49 +++++++++++++++++++++--------- 3 files changed, 74 insertions(+), 25 deletions(-) diff --git a/crates/minimal/src/task.rs b/crates/minimal/src/task.rs index c3a581e7cf..4e70f9dbff 100644 --- a/crates/minimal/src/task.rs +++ b/crates/minimal/src/task.rs @@ -508,7 +508,12 @@ fn resolve_task_patches( read_only: matches!(setting, mfile::PatchSetting::ReadOnly), }) } - boxes::core::compose::NameVerdict::Ignored => out.drop.insert(key), + boxes::core::compose::NameVerdict::Ignored => { + out.drop.insert(minimald_rpc::taskenv::DroppedPatch { + path: key, + is_file: entry.is_file, + }) + } }; } Ok(out) @@ -2252,11 +2257,18 @@ mod tests { ) .expect("ignored entries drop, they do not fail"); - let expect: std::collections::BTreeSet = ["/opt/tool/bin", "/opt/cache"] - .map(String::from) - .into_iter() - .collect(); - assert_eq!(verdict.drop, expect, "raw declared keys, verbatim"); + let expect: std::collections::BTreeSet<_> = + [("/opt/tool/bin", true), ("/opt/cache", false)] + .map(|(path, is_file)| minimald_rpc::taskenv::DroppedPatch { + path: path.to_string(), + is_file, + }) + .into_iter() + .collect(); + assert_eq!( + verdict.drop, expect, + "raw declared keys, verbatim, with their kind" + ); assert!(verdict.allow.is_empty(), "nothing ignored is allowed"); } diff --git a/crates/minimald-rpc/src/taskenv.rs b/crates/minimald-rpc/src/taskenv.rs index b5dddc5f29..09b58f7dda 100644 --- a/crates/minimald-rpc/src/taskenv.rs +++ b/crates/minimald-rpc/src/taskenv.rs @@ -110,8 +110,8 @@ pub fn drops_from_channel_env(env_vars: &BTreeMap) -> BTreeSet) -> BTreeSet, - /// Declared keys the policy ignored, to remove before mounting. - pub drop: BTreeSet, + /// Declarations the policy ignored, to remove before mounting. + pub drop: BTreeSet, } impl PatchVerdict { @@ -149,6 +149,17 @@ pub struct AllowedPatch { pub read_only: bool, } +/// One declaration a [`PatchVerdict`] dropped. It carries its kind +/// because the client gates a `patch.dir` and a `patch.file` entry under +/// the same key separately, so dropping one must leave the other. +#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, serde::Serialize, serde::Deserialize)] +pub struct DroppedPatch { + /// The declared key, verbatim. + pub path: String, + /// `true` for a `patch.file` entry, `false` for `patch.dir`. + pub is_file: bool, +} + /// Encode a verdict for [`TASK_PATCH_VERDICT`]. /// /// # Errors @@ -394,7 +405,12 @@ mod tests { }] .into_iter() .collect(), - drop: ["/etc/secrets".to_string()].into_iter().collect(), + drop: [DroppedPatch { + path: "/etc/secrets".to_string(), + is_file: true, + }] + .into_iter() + .collect(), }; let mut channel = BTreeMap::new(); channel.insert( diff --git a/crates/minimald/src/exec.rs b/crates/minimald/src/exec.rs index 0af4b16268..031e9262da 100644 --- a/crates/minimald/src/exec.rs +++ b/crates/minimald/src/exec.rs @@ -352,13 +352,10 @@ fn parse_task_args( .map_err(|e| e.to_string()) } -/// Producer side of [`TaskExec::exec`]. Inlined in one async fn so that -/// `env` lives on a single stack frame across every spawn — that frame -/// is alive for the whole life of this tokio task, which in turn is -/// governed by the consumer's stream. /// Apply the client's `[patches]` verdict to a task's declared patches: -/// remove every dropped key, then require every declaration left to be one -/// the verdict allowed, with the kind and mode the client checked. +/// remove every dropped declaration from the map of its kind, then require +/// every declaration left to be one the verdict allowed, with the kind and +/// mode the client checked. /// /// The daemon holds no policy, so this is the only thing standing between /// a project's `patch` declarations and a mount. It fails closed: a task @@ -387,9 +384,12 @@ fn apply_patch_verdict( the task again" )); }; - for key in &verdict.drop { - patch.dir.remove(key); - patch.file.remove(key); + for dropped in &verdict.drop { + if dropped.is_file { + patch.file.remove(&dropped.path); + } else { + patch.dir.remove(&dropped.path); + } } // An allowed key must also keep the kind and mode it was checked as: // the client walks a directory and not a file, and a read-only entry @@ -444,7 +444,7 @@ pub(crate) fn refuse_in_box_patches( #[cfg(test)] mod patch_verdict_tests { use super::{apply_patch_verdict, refuse_in_box_patches}; - use minimald_rpc::taskenv::{AllowedPatch, PatchVerdict}; + use minimald_rpc::taskenv::{AllowedPatch, DroppedPatch, PatchVerdict}; fn patches(dirs: &[&str], files: &[&str]) -> mfile::EnvPatches { let mut p = mfile::EnvPatches::default(); @@ -461,7 +461,7 @@ mod patch_verdict_tests { /// A verdict allowing each `(key, is_file)` read-only, the mode /// [`patches`] declares. - fn verdict(allow: &[(&str, bool)], drop: &[&str]) -> PatchVerdict { + fn verdict(allow: &[(&str, bool)], drop: &[(&str, bool)]) -> PatchVerdict { PatchVerdict { allow: allow .iter() @@ -471,7 +471,13 @@ mod patch_verdict_tests { read_only: true, }) .collect(), - drop: drop.iter().map(|s| (*s).to_string()).collect(), + drop: drop + .iter() + .map(|(path, is_file)| DroppedPatch { + path: (*path).to_string(), + is_file: *is_file, + }) + .collect(), } } @@ -493,13 +499,13 @@ mod patch_verdict_tests { assert!(err.contains("Upgrade min"), "{err}"); } - /// Dropped keys leave both maps, allowed keys stay. + /// Dropped keys leave the map of their kind, allowed keys stay. #[test] fn dropped_keys_go_and_allowed_keys_stay() { let mut p = patches(&["/opt/cache"], &["/etc/token", "~/.claude.json"]); let v = verdict( &[("/opt/cache", false), ("~/.claude.json", true)], - &["/etc/token"], + &[("/etc/token", true)], ); apply_patch_verdict("t", &mut p, Some(&v)).expect("every key was gated"); assert!(p.dir.contains_key("/opt/cache")); @@ -507,6 +513,17 @@ mod patch_verdict_tests { assert!(!p.file.contains_key("/etc/token")); } + /// A key declared as both a directory and a file is gated per kind: + /// dropping the directory leaves the allowed file mounted. + #[test] + fn a_dropped_dir_leaves_an_allowed_file_under_the_same_key() { + let mut p = patches(&["/opt/shared"], &["/opt/shared"]); + let v = verdict(&[("/opt/shared", true)], &[("/opt/shared", false)]); + apply_patch_verdict("t", &mut p, Some(&v)).expect("each kind was gated"); + assert!(p.file.contains_key("/opt/shared"), "the allowed file stays"); + assert!(!p.dir.contains_key("/opt/shared"), "the dropped dir goes"); + } + /// A declared key the verdict does not name was never gated, so the /// task is refused rather than the key mounted. #[test] @@ -553,6 +570,10 @@ mod patch_verdict_tests { } } +/// Producer side of [`TaskExec::exec`]. Inlined in one async fn so that +/// `env` lives on a single stack frame across every spawn — that frame +/// is alive for the whole life of this tokio task, which in turn is +/// governed by the consumer's stream. async fn task_producer( exec: TaskExec, session: BoxHandle, From ee024a74e09fa1ac0051c0cd621ade7f4fe19721 Mon Sep 17 00:00:00 2001 From: "gominimal-aw-bot[bot]" <281738952+gominimal-aw-bot[bot]@users.noreply.github.com> Date: Sun, 18 Oct 2026 13:23:04 -0700 Subject: [PATCH 14/21] docs(policy): say a ~/ task patch is matched by its path only --- crates/boxes/src/core/compose.rs | 2 ++ docs/reference/user-policy.md | 4 +++- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/crates/boxes/src/core/compose.rs b/crates/boxes/src/core/compose.rs index 1a29e78691..900147fdd5 100644 --- a/crates/boxes/src/core/compose.rs +++ b/crates/boxes/src/core/compose.rs @@ -2014,6 +2014,8 @@ pub fn gate_task_patch_paths( }; // Only an absolute key names a path on the daemon's filesystem that // this machine can look at; a `~/` key names the session's home. + // A `~/` entry is matched against the rules by its path only: its + // contents and links are not checked, because the box writes them. let resolvable = |declared: &str| declared.starts_with('/'); // Refused before any decision, so no prompt is ever about a path whose diff --git a/docs/reference/user-policy.md b/docs/reference/user-policy.md index 8e1519b51a..ab3b6bbcb9 100644 --- a/docs/reference/user-policy.md +++ b/docs/reference/user-policy.md @@ -167,7 +167,9 @@ so the rules apply to the **declared path** itself: stops the run. Minimal follows a symlink to a directory inside a declared directory and checks the files it reaches, since the mount exposes them. If a directory is too large or partly unreadable to check against your deny - rules, the run stops and names the reason. + rules, the run stops and names the reason. A `~/` entry names the + session's home. It is matched against your rules by its path only: its + contents and links are not checked, because the box writes them. - For a declared absolute path, Minimal also checks the path it resolves to on your machine, and `allow` must match that path too. A symlink cannot carry the path past a `deny` on its target, or onto a target no rule allows. This From c25812601681801a63d973c90c711ac4d65de89c Mon Sep 17 00:00:00 2001 From: "gominimal-aw-bot[bot]" <281738952+gominimal-aw-bot[bot]@users.noreply.github.com> Date: Sun, 18 Oct 2026 13:23:33 -0700 Subject: [PATCH 15/21] docs(policy): state the ~/ patch rule in the active voice --- crates/boxes/src/core/compose.rs | 4 ++-- docs/reference/user-policy.md | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/crates/boxes/src/core/compose.rs b/crates/boxes/src/core/compose.rs index 900147fdd5..f4a3d16384 100644 --- a/crates/boxes/src/core/compose.rs +++ b/crates/boxes/src/core/compose.rs @@ -2014,8 +2014,8 @@ pub fn gate_task_patch_paths( }; // Only an absolute key names a path on the daemon's filesystem that // this machine can look at; a `~/` key names the session's home. - // A `~/` entry is matched against the rules by its path only: its - // contents and links are not checked, because the box writes them. + // `min` matches a `~/` entry against the rules by its path only, and + // does not check its contents or links, because the box writes them. let resolvable = |declared: &str| declared.starts_with('/'); // Refused before any decision, so no prompt is ever about a path whose diff --git a/docs/reference/user-policy.md b/docs/reference/user-policy.md index ab3b6bbcb9..f5f33f2083 100644 --- a/docs/reference/user-policy.md +++ b/docs/reference/user-policy.md @@ -168,8 +168,8 @@ so the rules apply to the **declared path** itself: directory and checks the files it reaches, since the mount exposes them. If a directory is too large or partly unreadable to check against your deny rules, the run stops and names the reason. A `~/` entry names the - session's home. It is matched against your rules by its path only: its - contents and links are not checked, because the box writes them. + session's home. `min` matches it against your rules by its path only, and + does not check its contents or links, because the box writes them. - For a declared absolute path, Minimal also checks the path it resolves to on your machine, and `allow` must match that path too. A symlink cannot carry the path past a `deny` on its target, or onto a target no rule allows. This From 4accca768e612555298b991ccb6ee22ccc57a972 Mon Sep 17 00:00:00 2001 From: "minimal-foundry[bot]" <327719912+minimal-foundry[bot]@users.noreply.github.com> Date: Tue, 20 Oct 2026 02:00:16 +0000 Subject: [PATCH 16/21] fix(task): close patch gate gaps found in review A canonicalize error other than NotFound now fails closed, so a link in an unsearchable directory cannot pass a deny on its target. Relative patch keys are refused. A read-write patch.dir is refused when a deny rule can name a path inside it, and the walk checks directory entries against deny too. The refusal snippet escapes glob metacharacters, and min session run reports a broken minimal.toml as the cause. --- crates/boxes/src/core/compose.rs | 229 +++++++++++++++++++++---- crates/boxes/src/core/compose/tests.rs | 177 +++++++++++++++++++ crates/minimal/src/task.rs | 164 ++++++++++++++++-- 3 files changed, 525 insertions(+), 45 deletions(-) diff --git a/crates/boxes/src/core/compose.rs b/crates/boxes/src/core/compose.rs index f4a3d16384..efa8ef6a1b 100644 --- a/crates/boxes/src/core/compose.rs +++ b/crates/boxes/src/core/compose.rs @@ -529,6 +529,24 @@ pub enum ComposeError { /// [`gate_task_patch_paths`]. #[error("the patch path `{what}` (from {from}) holds a `.` or `..` segment")] TaskPatchDotSegment { what: String, from: Source }, + /// A task's declared `patch.dir` / `patch.file` key is neither absolute + /// nor `~/`-rooted. The daemon would mount it relative to its own + /// working directory, which no `[patches]` rule names. Surfaces from + /// [`gate_task_patch_paths`]. + #[error("the patch path `{what}` (from {from}) is not absolute and does not start with `~/`")] + TaskPatchNotAbsolute { what: String, from: Source }, + /// A task's declared read-write `patch.dir` entry holds a place where + /// the task could create a path that a `[patches] deny` rule names, so + /// mounting it would let the task write past that rule. `pattern` is + /// the deny rule, as expanded. Surfaces from [`gate_task_patch_paths`]. + #[error( + "the read-write patch directory `{what}` (from {from}) can hold a path that the [patches] deny rule `{pattern}` names" + )] + TaskPatchWritableDeny { + what: String, + from: Source, + pattern: String, + }, /// A task's declared `patch.dir` entry could not be checked file by /// file against a `[patches] deny`: the walk of what it holds could /// not finish. The entry is refused rather than mounted unchecked. @@ -1562,6 +1580,10 @@ pub struct TaskPatchEntry<'a> { pub declared: &'a str, /// `true` for a `patch.file` entry, `false` for `patch.dir`. pub is_file: bool, + /// `true` for a `"ro"` entry. A read-write directory lets the task + /// create paths in it, so it is checked against every path a `deny` + /// rule can name inside it, not only the paths it holds now. + pub read_only: bool, /// The contributing task's provenance — always a project, since only /// `minimal.toml` declares tasks. pub source: &'a Source, @@ -1610,10 +1632,12 @@ const TASK_PATCH_LINK_HOPS: usize = 40; /// Why [`resolve_existing_prefix`] could not say where a path leads: a /// dangling symlink it could not follow (unreadable, too many hops, or a -/// target it cannot pin down). The caller denies the entry, since the -/// daemon would write through the link to a path no rule was checked on. +/// target it cannot pin down), or a path the OS refused to resolve for a +/// reason other than "not found" (a directory on the way that cannot be +/// searched, say). The caller denies the entry, since the daemon would +/// reach a path no rule was checked on. #[derive(Debug)] -struct UnresolvableLink; +struct Unresolvable; /// The path `path` reaches on this machine: its deepest existing ancestor /// canonicalized, with the missing tail joined back on. So a @@ -1622,9 +1646,14 @@ struct UnresolvableLink; /// canonicalization cannot see through, is followed by hand: writing a /// missing `rw` entry creates the link's target, so the target is what /// must be checked. `Ok(None)` when it resolves to itself. +/// +/// Only a "not found" error means a path is missing. Any other error +/// (permission denied on a parent, a file where a directory must be, a +/// link loop) is [`Unresolvable`]: such a path can still be a symlink +/// that leads anywhere. fn resolve_existing_prefix( path: &camino::Utf8Path, -) -> Result, UnresolvableLink> { +) -> Result, Unresolvable> { let resolved = resolve_path(path, 0)?; Ok(resolved.filter(|out| out != path)) } @@ -1635,28 +1664,36 @@ fn resolve_existing_prefix( fn resolve_path( path: &camino::Utf8Path, hops: usize, -) -> Result, UnresolvableLink> { +) -> Result, Unresolvable> { let mut tail: Vec<&str> = Vec::new(); let mut cur = path; loop { - if let Ok(canonical) = std::fs::canonicalize(cur.as_std_path()) { - let Ok(mut out) = camino::Utf8PathBuf::from_path_buf(canonical) else { - return Ok(None); - }; - for seg in tail.iter().rev() { - out.push(seg); + match std::fs::canonicalize(cur.as_std_path()) { + Ok(canonical) => { + let Ok(mut out) = camino::Utf8PathBuf::from_path_buf(canonical) else { + return Ok(None); + }; + for seg in tail.iter().rev() { + out.push(seg); + } + return Ok(Some(out)); } - return Ok(Some(out)); + Err(e) if e.kind() == std::io::ErrorKind::NotFound => {} + Err(_) => return Err(Unresolvable), } // `cur` does not resolve. If it is a link, it dangles: follow it // to where it points, where a write through it would land. - if std::fs::symlink_metadata(cur.as_std_path()).is_ok_and(|m| m.file_type().is_symlink()) { + let is_link = match std::fs::symlink_metadata(cur.as_std_path()) { + Ok(meta) => meta.file_type().is_symlink(), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => false, + Err(_) => return Err(Unresolvable), + }; + if is_link { if hops >= TASK_PATCH_LINK_HOPS { - return Err(UnresolvableLink); + return Err(Unresolvable); } - let target = std::fs::read_link(cur.as_std_path()).map_err(|_| UnresolvableLink)?; - let target = - camino::Utf8PathBuf::from_path_buf(target).map_err(|_| UnresolvableLink)?; + let target = std::fs::read_link(cur.as_std_path()).map_err(|_| Unresolvable)?; + let target = camino::Utf8PathBuf::from_path_buf(target).map_err(|_| Unresolvable)?; let mut next = match cur.parent() { Some(parent) if target.is_relative() => parent.join(target), _ => target, @@ -1668,8 +1705,65 @@ fn resolve_path( } // A `..` from a link's target, under a parent that does not exist, // has no name to carry: the walk cannot say where it lands. - tail.push(cur.file_name().ok_or(UnresolvableLink)?); - cur = cur.parent().ok_or(UnresolvableLink)?; + tail.push(cur.file_name().ok_or(Unresolvable)?); + cur = cur.parent().ok_or(Unresolvable)?; + } +} + +/// Where `path` leads on this machine: its deepest existing ancestor +/// canonicalized, a dangling symlink on the way followed by hand, and the +/// missing tail joined back on. `None` when that cannot be said, for a +/// link that cannot be followed or any error other than "not found". The +/// daemon uses it to keep a `~/` patch key inside the session's home. +#[must_use] +pub fn resolve_patch_target(path: &camino::Utf8Path) -> Option { + resolve_path(path, 0).ok().flatten() +} + +/// Whether the `deny` pattern `pattern` can match a path strictly inside +/// the directory `dir`. It errs towards `true`: the caller refuses a +/// read-write directory on it, so a false `true` costs a refusal and a +/// false `false` costs a write past a deny. +/// +/// The pattern's literal prefix decides, read up to its first glob +/// metacharacter (`*`, `?`, `[`, `{`). A backslash escape and a one-byte +/// class such as `[*]` count as literal. A pattern with no metacharacter +/// names one path, so it must lie under `dir`. Otherwise `*` and `**` +/// cross `/` in these patterns, so the prefix only has to agree with +/// `dir/` as far as the shorter of the two reaches. +pub(crate) fn deny_reaches_inside(pattern: &str, dir: &str) -> bool { + let inside = format!("{}/", dir.trim_end_matches('/')); + let chars: Vec = pattern.chars().collect(); + let mut literal = String::with_capacity(pattern.len()); + let mut i = 0; + let mut has_meta = false; + while i < chars.len() { + match chars[i] { + '\\' if i + 1 < chars.len() => { + literal.push(chars[i + 1]); + i += 2; + } + '[' if i + 2 < chars.len() + && chars[i + 2] == ']' + && !matches!(chars[i + 1], '!' | '^' | ']') => + { + literal.push(chars[i + 1]); + i += 3; + } + '*' | '?' | '[' | '{' => { + has_meta = true; + break; + } + c => { + literal.push(c); + i += 1; + } + } + } + if has_meta { + literal.starts_with(&inside) || inside.starts_with(&literal) + } else { + literal.starts_with(&inside) } } @@ -1699,7 +1793,8 @@ fn decide_task_patch_path( /// symlinked prefix such as macOS's `/tmp` → `/private/tmp` therefore needs /// the resolved form allowed too; the prompt and the refusal snippet name /// it (see [`task_patch_forms`]). A dangling link that cannot be followed -/// denies the entry ([`UnresolvableLink`]). +/// denies the entry ([`Unresolvable`]), as does a path the OS refuses +/// to resolve for any reason other than "not found". fn check_task_patch_path( expanded: &ExpandedPatchesPolicy, source: &Source, @@ -1714,7 +1809,7 @@ fn check_task_patch_path( match resolve_existing_prefix(path) { Ok(Some(resolved)) => own.combine(decide_task_patch_path(expanded, source, &resolved)), Ok(None) => own, - Err(UnresolvableLink) => PathDecision::Denied, + Err(Unresolvable) => PathDecision::Denied, } } @@ -1812,7 +1907,9 @@ fn decide_answered_task_patch_forms( /// so a rule naming the declared directory, as the prompt and the refusal /// snippet record it, approves the entry whatever it holds. /// -/// The probe follows a contained symlink to a directory and walks what the +/// Every entry the walk meets is checked, a directory as well as a file, +/// so a `deny` that names a directory without `/**` still applies. The +/// probe follows a contained symlink to a directory and walks what the /// target holds, since the mount keeps the link and so exposes it. /// /// With no `deny` rule there is nothing to probe for, so the directory's @@ -1874,12 +1971,9 @@ fn check_task_patch_dir( } let file_type = entry.file_type().ok(); let on_disk = canonical.as_ref().map(|c| c.join(entry.file_name())); - if file_type.is_some_and(|t| t.is_dir()) { - if on_disk.as_ref().is_none_or(|c| visited.insert(c.clone())) { - stack.push((entry.path(), on_disk)); - } - continue; - } + // Every entry meets the deny rules, a directory too: a deny + // that names a directory (no `/**`) is bypassed when the walk + // only checks what lies beneath it. let path = utf8(&entry.path()); // Only a symlink reaches somewhere other than its own path, // so only a symlink pays for the resolution. @@ -1893,6 +1987,12 @@ fn check_task_patch_dir( { return Ok(PathDecision::Denied); } + if file_type.is_some_and(|t| t.is_dir()) { + if on_disk.as_ref().is_none_or(|c| visited.insert(c.clone())) { + stack.push((entry.path(), on_disk)); + } + continue; + } if is_link && let Ok(target) = std::fs::canonicalize(entry.path()) && target.is_dir() @@ -1905,21 +2005,61 @@ fn check_task_patch_dir( Ok(own) } +/// The first `deny` rule that can name a path inside the read-write +/// directory `dir`, as declared or, when `resolve` is set, as it resolves +/// on this machine ([`deny_reaches_inside`]). A read-write mount lets the +/// task create such a path, so what the directory holds now does not +/// settle it. +fn writable_task_patch_deny( + expanded: &ExpandedPatchesPolicy, + dir: &camino::Utf8Path, + resolve: bool, +) -> Option { + let mut forms = vec![dir.to_path_buf()]; + if resolve && let Ok(Some(resolved)) = resolve_existing_prefix(dir) { + forms.push(resolved); + } + expanded + .deny() + .iter() + .find(|rule| { + forms + .iter() + .any(|form| deny_reaches_inside(rule.pattern(), form.as_str())) + }) + .map(|rule| rule.pattern().to_owned()) +} + /// A declared entry's decision: the file form checks its one path, the -/// directory form also probes the files it currently holds. +/// directory form also probes the files it currently holds. A read-write +/// directory is also refused when a `deny` rule can name a path inside it +/// ([`writable_task_patch_deny`]). /// /// # Errors /// -/// [`ComposeError::TaskPatchUnchecked`] when a directory's probe could -/// not finish ([`check_task_patch_dir`]). +/// - [`ComposeError::TaskPatchUnchecked`] when a directory's probe could +/// not finish ([`check_task_patch_dir`]). +/// - [`ComposeError::TaskPatchWritableDeny`] when a read-write directory +/// can hold a path a `deny` rule names. fn check_task_patch_entry( expanded: &ExpandedPatchesPolicy, entry: &TaskPatchEntry<'_>, path: &camino::Utf8Path, resolve: bool, ) -> Result { - if entry.is_file { - return Ok(check_task_patch_path(expanded, entry.source, path, resolve)); + use crate::core::policy::PathDecision; + let own = check_task_patch_path(expanded, entry.source, path, resolve); + if entry.is_file || own == PathDecision::Denied { + return Ok(own); + } + if !entry.read_only + && let Some(pattern) = writable_task_patch_deny(expanded, path, resolve) + { + return Err(ComposeError::TaskPatchWritableDeny { + what: entry.declared.to_owned(), + from: entry.source.clone(), + pattern, + }); } check_task_patch_dir( expanded, @@ -1956,6 +2096,14 @@ fn check_task_patch_entry( /// A key holding a `.` or `..` segment is refused outright /// ([`ComposeError::TaskPatchDotSegment`]): the OS resolves `..` after any /// symlinked parent, so the declared string would not say what it mounts. +/// A key that is neither absolute nor `~/`-rooted is refused too +/// ([`ComposeError::TaskPatchNotAbsolute`]): no rule matches it, and the +/// daemon would mount it against its own working directory. +/// +/// A read-write directory entry is refused when a `deny` rule can name a +/// path inside it ([`ComposeError::TaskPatchWritableDeny`]), since the +/// task can create that path. This check reads only the declared and +/// resolved strings, so it applies to `~/` entries too. /// /// An absolute entry is also checked as it resolves on this machine, and /// a directory entry is probed for contained files a `deny` names. Both @@ -1983,8 +2131,12 @@ fn check_task_patch_entry( /// path is never preceded by a prompt about its neighbours. /// - [`ComposeError::TaskPatchDotSegment`] — a declared key holds a `.` /// or `..` segment. Checked before anything else. +/// - [`ComposeError::TaskPatchNotAbsolute`] — a declared key is neither +/// absolute nor `~/`-rooted. Checked right after the dot segments. /// - [`ComposeError::TaskPatchUnchecked`] — a `deny` rule is set and a /// directory entry's probe could not check every file it holds. +/// - [`ComposeError::TaskPatchWritableDeny`] — a read-write directory +/// entry can hold a path a `deny` rule names. /// - [`ComposeError::HookRequired`] — an entry needed approval and there /// was no hook to ask. /// - [`ComposeError::Aborted`] — the hook cancelled. @@ -2026,6 +2178,17 @@ pub fn gate_task_patch_paths( from: entry.source.clone(), }); } + // A relative key matches no absolute rule, and the daemon would mount + // it against its own working directory, so it is refused too. + if let Some(entry) = entries + .iter() + .find(|e| !e.declared.starts_with('/') && !e.declared.starts_with("~/")) + { + return Err(ComposeError::TaskPatchNotAbsolute { + what: entry.declared.to_owned(), + from: entry.source.clone(), + }); + } // Pass 1: categorize per entry. Undecided entries are seeded // `Ignored` and queued; pass 3 overwrites every one. The placeholder diff --git a/crates/boxes/src/core/compose/tests.rs b/crates/boxes/src/core/compose/tests.rs index 2241568499..91c413d698 100644 --- a/crates/boxes/src/core/compose/tests.rs +++ b/crates/boxes/src/core/compose/tests.rs @@ -2532,6 +2532,7 @@ mod gate_task_patch_paths { .map(|&(d, is_file)| TaskPatchEntry { declared: d, is_file, + read_only: true, source, }) .collect() @@ -3233,4 +3234,180 @@ mod gate_task_patch_paths { "{err}" ); } + + /// A writable `patch.dir` entry, for the tests of the read-write + /// rules. `entries_for` gives read-only ones. + fn writable_dir<'a>(source: &'a Source, declared: &'a str) -> Vec> { + vec![TaskPatchEntry { + declared, + is_file: false, + read_only: false, + source, + }] + } + + /// A symlink inside a directory the walk cannot search does not + /// resolve. That is not "missing": the link can lead to `/etc`, so + /// the entry fails closed rather than being matched as declared. + #[cfg(unix)] + #[test] + fn a_symlink_in_an_unsearchable_directory_is_denied() { + use std::os::unix::fs::PermissionsExt; + let tmp = tempfile::tempdir().unwrap(); + let root = canonical_root(&tmp); + let locked = root.join("locked"); + std::fs::create_dir(locked.as_std_path()).unwrap(); + let link = locked.join("link"); + std::os::unix::fs::symlink("/etc", link.as_std_path()).unwrap(); + std::fs::set_permissions(locked.as_std_path(), std::fs::Permissions::from_mode(0o000)) + .unwrap(); + let restore = || { + std::fs::set_permissions(locked.as_std_path(), std::fs::Permissions::from_mode(0o755)) + .unwrap(); + }; + // Root searches it regardless, so there is nothing to refuse. + if std::fs::canonicalize(link.as_std_path()).is_ok() { + restore(); + eprintln!("skipped: running as root, a 0o000 directory is searchable"); + return; + } + + let source = project_source(); + let entries = entries_for(&source, &[(link.as_str(), true)]); + let policy = PatchesPolicy::default() + .with_allow(vec![format!("{root}/**")]) + .with_deny(vec!["/etc/**".to_string()]); + let err = gate_task_patch_paths(&entries, policy, None, &NoVars, None).unwrap_err(); + restore(); + assert!( + matches!(err, ComposeError::Denied { ref what, .. } if what == link.as_str()), + "{err}" + ); + } + + /// A relative key matches no absolute rule and would be mounted + /// against the daemon's working directory, so it is refused, whatever + /// the policy says. + #[test] + fn a_relative_key_is_refused_before_the_policy_decides() { + let source = project_source(); + for declared in ["root/.cache", "~", "~user/x", ""] { + let entries = entries_for(&source, &[(declared, false)]); + let policy = PatchesPolicy::default().with_allow(vec!["**".to_string()]); + let err = gate_task_patch_paths(&entries, policy, None, &NoVars, Some("/home/u")) + .unwrap_err(); + assert!( + matches!(err, ComposeError::TaskPatchNotAbsolute { ref what, .. } if what == declared), + "{declared:?}: {err}" + ); + } + } + + /// A read-write directory lets the task create a file a deny names, + /// so the deny applies to the paths it can hold, not only the ones it + /// holds now. A read-only one cannot gain the file, so it is allowed. + #[test] + fn a_writable_directory_is_refused_when_a_deny_reaches_into_it() { + let tmp = tempfile::tempdir().unwrap(); + let home = canonical_root(&tmp).join("home"); + std::fs::create_dir(home.as_std_path()).unwrap(); + let deny = format!("{home}/.ssh/authorized_keys"); + let policy = || { + PatchesPolicy::default() + .with_allow(vec![home.to_string()]) + .with_deny(vec![deny.clone()]) + }; + + let source = project_source(); + let err = gate_task_patch_paths( + &writable_dir(&source, home.as_str()), + policy(), + None, + &NoVars, + None, + ) + .unwrap_err(); + assert!( + matches!(err, ComposeError::TaskPatchWritableDeny { ref what, ref pattern, .. } + if what == home.as_str() && *pattern == deny), + "{err}" + ); + + let entries = entries_for(&source, &[(home.as_str(), false)]); + let (verdicts, _) = gate_task_patch_paths(&entries, policy(), None, &NoVars, None).unwrap(); + assert_eq!(verdicts, vec![NameVerdict::Allowed]); + } + + /// The read-write rule matches `~/` entries too, against the same home + /// the policy's own `~` expands to, and leaves alone a directory no + /// deny reaches into. + #[test] + fn a_writable_tilde_directory_meets_a_deny_inside_it() { + let source = project_source(); + let policy = || { + PatchesPolicy::default() + .with_allow(vec!["~/**".to_string()]) + .with_deny(vec!["~/.ssh/**".to_string()]) + }; + let err = gate_task_patch_paths( + &writable_dir(&source, "~/"), + policy(), + None, + &NoVars, + Some("/home/u"), + ) + .unwrap_err(); + assert!( + matches!(err, ComposeError::TaskPatchWritableDeny { .. }), + "{err}" + ); + + let (verdicts, _) = gate_task_patch_paths( + &writable_dir(&source, "~/.cache"), + policy(), + None, + &NoVars, + Some("/home/u"), + ) + .unwrap(); + assert_eq!(verdicts, vec![NameVerdict::Allowed]); + } + + /// The literal prefix of a deny pattern decides whether it can reach + /// inside a directory, erring towards yes once a metacharacter starts. + #[test] + fn deny_reaches_inside_reads_the_literal_prefix() { + use crate::core::compose::deny_reaches_inside; + assert!(deny_reaches_inside("/h/u/.ssh/**", "/h/u")); + assert!(deny_reaches_inside("/h/u/.ssh/authorized_keys", "/h/u/")); + assert!(deny_reaches_inside("**/.env", "/srv/app")); + assert!(deny_reaches_inside("/h/*/.ssh/**", "/h/u/proj")); + assert!(deny_reaches_inside("/h/u/a[*]b/**", "/h/u/a*b")); + assert!(!deny_reaches_inside("/h/u/.ssh/**", "/h/u/proj")); + assert!(!deny_reaches_inside("/etc/**", "/h/u")); + assert!(!deny_reaches_inside("/h/u", "/h/u")); + assert!(!deny_reaches_inside("/h/u/a[*]b/**", "/h/u/axb")); + assert!(!deny_reaches_inside("/h/uu/x", "/h/u")); + } + + /// A deny that names a directory without `/**` still applies to that + /// directory when the walk meets it inside a declared one. + #[test] + fn a_contained_directory_a_deny_names_denies_the_entry() { + let tmp = tempfile::tempdir().unwrap(); + let home = canonical_root(&tmp).join("home"); + let ssh = home.join(".ssh"); + std::fs::create_dir_all(ssh.as_std_path()).unwrap(); + + let source = project_source(); + let entries = entries_for(&source, &[(home.as_str(), false)]); + let policy = PatchesPolicy::default() + .with_allow(vec![home.to_string()]) + .with_deny(vec![ssh.to_string()]); + let err = gate_task_patch_paths(&entries, policy, None, &NoVars, None).unwrap_err(); + assert!( + matches!(err, ComposeError::Denied { ref what, .. } if what == home.as_str()), + "{err}" + ); + } } diff --git a/crates/minimal/src/task.rs b/crates/minimal/src/task.rs index 4e70f9dbff..9bf7064e05 100644 --- a/crates/minimal/src/task.rs +++ b/crates/minimal/src/task.rs @@ -357,13 +357,15 @@ fn refused_vars_snippet(names: &[String]) -> String { /// Format refused patch paths as the `[patches] allow` snippet an /// operator can paste — the patch-side sibling of /// [`refused_vars_snippet`](fn@refused_vars_snippet), emitted through -/// `toml_edit` for the same escaping reason. +/// `toml_edit` for the same escaping reason. Each path is written as a +/// pattern that matches only that path, as "allow always" records it, so a +/// `*`, `[` or `{` in a path neither widens the rule nor breaks the policy. fn refused_patches_snippet(paths: &[String]) -> String { let mut doc = toml_edit::DocumentMut::new(); let mut patches = toml_edit::Table::new(); let mut allow = toml_edit::Array::new(); for path in paths { - allow.push(path.as_str()); + allow.push(boxes::core::expansion::literal_policy_pattern(path)); } patches.insert("allow", toml_edit::value(allow)); doc.insert("patches", toml_edit::Item::Table(patches)); @@ -449,17 +451,19 @@ fn resolve_task_patches( // Dir entries first, then files, each in declaration order — the // same order `to_fs_mappings` iterates when mounting. let mut entries: Vec> = Vec::new(); - for key in task.patch.dir.keys() { + for (key, setting) in &task.patch.dir { entries.push(TaskPatchEntry { declared: key, is_file: false, + read_only: matches!(setting, mfile::PatchSetting::ReadOnly), source, }); } - for key in task.patch.file.keys() { + for (key, setting) in &task.patch.file { entries.push(TaskPatchEntry { declared: key, is_file: true, + read_only: matches!(setting, mfile::PatchSetting::ReadOnly), source, }); } @@ -482,6 +486,19 @@ fn resolve_task_patches( Err(boxes::core::compose::ComposeError::TaskPatchUnchecked { what, gap, .. }) => { bail!(unchecked_task_patch_message(task_name, &what, &gap)) } + Err(boxes::core::compose::ComposeError::TaskPatchNotAbsolute { what, .. }) => { + bail!(relative_task_patch_message(task_name, &what)) + } + Err(boxes::core::compose::ComposeError::TaskPatchWritableDeny { + what, pattern, .. + }) => { + bail!(writable_deny_task_patch_message( + task_name, + &what, + &pattern, + policy_path + )) + } Err(e) => { return Err(anyhow::Error::new(e)) .with_context(|| format!("gating `patch` for task '{task_name}'")); @@ -497,15 +514,10 @@ fn resolve_task_patches( let key = entry.declared.to_string(); match verdict { boxes::core::compose::NameVerdict::Allowed => { - let setting = if entry.is_file { - &task.patch.file[entry.declared] - } else { - &task.patch.dir[entry.declared] - }; out.allow.insert(minimald_rpc::taskenv::AllowedPatch { path: key, is_file: entry.is_file, - read_only: matches!(setting, mfile::PatchSetting::ReadOnly), + read_only: entry.read_only, }) } boxes::core::compose::NameVerdict::Ignored => { @@ -529,6 +541,33 @@ fn dot_segment_task_patch_message(task_name: &str, path: &str) -> String { ) } +/// The rejection body for a declared patch key that is neither absolute +/// nor `~/`-rooted. Split out for unit tests. +fn relative_task_patch_message(task_name: &str, path: &str) -> String { + format!( + "task '{task_name}' declares the patch path `{path}`, which is not an \ + absolute path and does not start with `~/`, so your [patches] policy \ + cannot check it; declare the full path, starting with `/` or `~/`" + ) +} + +/// The rejection body for a read-write patch directory that a `deny` rule +/// reaches into. Split out for unit tests. +fn writable_deny_task_patch_message( + task_name: &str, + path: &str, + pattern: &str, + policy_path: &std::path::Path, +) -> String { + format!( + "task '{task_name}' declares the read-write patch directory `{path}`. \ + The task can create files in it that the `[patches] deny` rule \ + `{pattern}` in {policy} forbids. Declare the directory \"ro\", or \ + declare a directory that leaves those paths out", + policy = policy_path.display(), + ) +} + /// The rejection body for a declared patch directory whose files could /// not all be checked against `[patches] deny`. Split out for unit tests. fn unchecked_task_patch_message( @@ -613,13 +652,24 @@ fn resolve_task_patches_non_interactive( /// A task this machine cannot find declared (one a stack provides, or a /// project whose `minimal.toml` is gone) gets an empty verdict rather than /// an error. The daemon still runs it when it declares no patches, and -/// refuses it when it does, since nothing here checked them. +/// refuses it when it does, since nothing here checked them. A +/// `minimal.toml` that cannot be read is a different case: its error is +/// returned, since it is the real cause of any refusal that follows. pub(crate) fn gate_session_task_patches( global: &GlobalArgs, project_path: &camino::Utf8Path, task_name: &str, ) -> Result { - let Ok(declared) = declared_task(project_path, task_name) else { + let file = match mfile::File::from_dir_recursive(project_path.as_std_path()) { + Ok(file) => file, + Err(mfile::Error::NotFound) => return Ok(minimald_rpc::taskenv::PatchVerdict::default()), + Err(e) => bail!( + "cannot check the patch paths of task '{task_name}': the {name} for \ + {project_path} cannot be read: {e}", + name = mfile::MFILE_NAME, + ), + }; + let Some(declared) = file.task(task_name) else { return Ok(minimald_rpc::taskenv::PatchVerdict::default()); }; if declared.patch.dir.is_empty() && declared.patch.file.is_empty() { @@ -2196,6 +2246,76 @@ mod tests { assert!(msg.contains("`..` segment"), "{msg}"); } + /// A relative key would be mounted against the daemon's working + /// directory, where no rule reaches, so it is refused by name. + #[test] + fn a_relative_patch_key_is_refused_by_name() { + let task = task_from_toml( + "[tasks.t]\nexec = 'true'\n[tasks.t.patch.dir]\n\"root/.cache\" = \"rw\"\n", + ); + let policy = + boxes::core::policy::PatchesPolicy::default().with_allow(vec!["**".to_string()]); + let err = resolve_task_patches( + &task, + "t", + policy, + &policy_path_fixture(), + &project_source(), + &NeverAsked, + &minimald_rpc::taskenv::TaskEnv::default(), + ) + .expect_err("a relative key must fail the gate"); + let msg = err.to_string(); + assert!(msg.contains("`root/.cache`"), "{msg}"); + assert!(msg.contains("start with `~/`"), "{msg}"); + } + + /// A read-write directory a deny rule reaches into is refused, naming + /// the rule and the way out, even though the file does not exist yet. + #[test] + fn a_writable_directory_under_a_deny_is_refused_naming_the_rule() { + let task = task_from_toml( + "[tasks.t]\nexec = 'true'\n[tasks.t.patch.dir]\n\ + \"/nonexistent-min-test/home\" = \"rw\"\n", + ); + let policy = boxes::core::policy::PatchesPolicy::default() + .with_allow(vec!["/nonexistent-min-test/**".to_string()]) + .with_deny(vec!["/nonexistent-min-test/home/.ssh/**".to_string()]); + let err = resolve_task_patches( + &task, + "t", + policy, + &policy_path_fixture(), + &project_source(), + &NeverAsked, + &minimald_rpc::taskenv::TaskEnv::default(), + ) + .expect_err("a writable directory under a deny must fail the gate"); + let msg = err.to_string(); + assert!( + msg.contains("`/nonexistent-min-test/home/.ssh/**`"), + "{msg}" + ); + assert!(msg.contains("\"ro\""), "{msg}"); + } + + /// A glob metacharacter in a refused path is escaped in the snippet, + /// so the rule matches that one path and the policy still loads. + #[test] + fn the_patch_refusal_snippet_escapes_glob_metacharacters() { + let path = "/srv/a*b[1]{c,d}".to_string(); + let snippet = refused_patches_snippet(std::slice::from_ref(&path)); + let parsed: toml::Value = toml::from_str(&snippet).expect("snippet must parse"); + let rule = parsed["patches"]["allow"][0] + .as_str() + .expect("one rule") + .to_owned(); + assert_ne!(rule, path, "{snippet}"); + let set = boxes::core::primitives::FileSet::try_new(rule.clone()).expect("rule compiles"); + assert!(set.is_match(&path), "{rule}"); + assert!(!set.is_match("/srv/aXb1c"), "{rule}"); + } + /// `min session run` gates the task as the session project declares /// it: a task with no patches, or one this machine cannot find, gets /// an empty verdict; a declared patch the policy does not allow is @@ -2235,6 +2355,26 @@ mod tests { assert!(msg.contains("/opt/tool/bin"), "{msg}"); } + /// A broken `minimal.toml` is reported as the cause, not left for the + /// daemon to refuse the task for a reason that hides it. + #[test] + fn session_run_reports_a_broken_project_file() { + let tmp = tempfile::tempdir().unwrap(); + let dir = camino::Utf8Path::from_path(tmp.path()).unwrap(); + std::fs::write(dir.join(mfile::MFILE_NAME), "[tasks.t\n").unwrap(); + let config = tempfile::tempdir().unwrap(); + let global = GlobalArgs { + config_dir: Some(config.path().to_path_buf()), + no_input: true, + ..Default::default() + }; + let err = gate_session_task_patches(&global, dir, "t") + .expect_err("a broken minimal.toml must fail the run"); + let msg = err.to_string(); + assert!(msg.contains("task 't'"), "{msg}"); + assert!(msg.contains("cannot be read"), "{msg}"); + } + /// An ignored patch path lands in the drop list the daemon removes /// from the mount set, keyed exactly as declared. #[test] From 9bc5189f30dc9eb2ebaf562faab2a19e436f882a Mon Sep 17 00:00:00 2001 From: "minimal-foundry[bot]" <327719912+minimal-foundry[bot]@users.noreply.github.com> Date: Tue, 20 Oct 2026 02:00:16 +0000 Subject: [PATCH 17/21] fix(minimald): refuse a ~/ task patch that leaves the session home The session home is box-writable, so a symlink there could send a ~/ key the client allowed by name to any directory the daemon can reach. --- crates/minimald/src/exec.rs | 90 ++++++++++++++++++++++++++++++++++++- 1 file changed, 89 insertions(+), 1 deletion(-) diff --git a/crates/minimald/src/exec.rs b/crates/minimald/src/exec.rs index 9d74da31eb..e2825f7ebb 100644 --- a/crates/minimald/src/exec.rs +++ b/crates/minimald/src/exec.rs @@ -416,6 +416,57 @@ fn apply_patch_verdict( Ok(()) } +/// Refuses a task whose `~/` patch key leads outside the session's home. +/// +/// The session's home is the box's own `/home`, so anything in the box can +/// put a symlink there. The bind mount follows it on this machine, so a +/// `~/x` the client allowed by name could mount any directory the daemon +/// can reach. The client cannot look inside the session's home, so this +/// check runs here: each `~/` key must still lie under the home once its +/// links are followed. A key whose links cannot be followed is refused. +/// A box that swaps a link after this check and before the mount is not +/// caught. +/// +/// # Errors +/// +/// The refusal text, naming the task and the key. +fn refuse_escaping_home_patches( + task_name: &str, + patch: &mfile::EnvPatches, + home: &camino::Utf8Path, +) -> Result<(), String> { + use boxes::core::compose::resolve_patch_target; + let mut tilde = patch + .dir + .keys() + .chain(patch.file.keys()) + .filter_map(|key| key.strip_prefix("~/").map(|rest| (key, rest))) + .peekable(); + if tilde.peek().is_none() { + return Ok(()); + } + let Some(home_real) = resolve_patch_target(home) else { + return Err(format!( + "task '{task_name}' declares patch paths under `~/`, and the session's \ + home {home} cannot be read, so the task did not run" + )); + }; + for (key, rest) in tilde { + match resolve_patch_target(&home.join(rest)) { + Some(target) if target.starts_with(&home_real) => {} + _ => { + return Err(format!( + "task '{task_name}' declares the patch path `{key}`, which leads \ + outside the session's home through a symbolic link, so the task \ + did not run. Remove the link from the session, then run the task \ + again" + )); + } + } + } + Ok(()) +} + /// Refuses a task started from inside a box (`min run `) that /// declares any patch path. /// @@ -443,9 +494,42 @@ pub(crate) fn refuse_in_box_patches( #[cfg(test)] mod patch_verdict_tests { - use super::{apply_patch_verdict, refuse_in_box_patches}; + use super::{apply_patch_verdict, refuse_escaping_home_patches, refuse_in_box_patches}; use minimald_rpc::taskenv::{AllowedPatch, DroppedPatch, PatchVerdict}; + /// A `~/` key that a link in the session's home sends elsewhere is + /// refused. A key that stays inside, including one that does not + /// exist yet, and an absolute key, pass. + #[cfg(unix)] + #[test] + fn a_tilde_patch_through_a_link_out_of_the_home_is_refused() { + let tmp = tempfile::tempdir().unwrap(); + let root = + camino::Utf8PathBuf::from_path_buf(std::fs::canonicalize(tmp.path()).unwrap()).unwrap(); + let home = root.join("home"); + let outside = root.join("outside"); + std::fs::create_dir_all(home.join("inside").as_std_path()).unwrap(); + std::fs::create_dir(outside.as_std_path()).unwrap(); + std::os::unix::fs::symlink(outside.as_std_path(), home.join("x").as_std_path()).unwrap(); + std::os::unix::fs::symlink( + root.join("gone").as_std_path(), + home.join("dangling").as_std_path(), + ) + .unwrap(); + + for key in ["~/x", "~/x/sub", "~/dangling"] { + let err = refuse_escaping_home_patches("t", &patches(&[key], &[]), &home).unwrap_err(); + assert!(err.contains(&format!("`{key}`")), "{err}"); + assert!(err.contains("outside the session's home"), "{err}"); + } + refuse_escaping_home_patches( + "t", + &patches(&["~/inside", "~/new/dir", "/opt/x"], &["~/inside/f"]), + &home, + ) + .expect("every key stays inside the home"); + } + fn patches(dirs: &[&str], files: &[&str]) -> mfile::EnvPatches { let mut p = mfile::EnvPatches::default(); for d in dirs { @@ -668,6 +752,10 @@ async fn task_producer( // `/workbench`), and a patch that expanded into either directory is // mounted at the matching path there, keeping its declared mode. let session_paths = session.paths().await?; + // A `~/` key the client allowed by name must not lead out of the + // session's home through a link the box put there. + refuse_escaping_home_patches(&exec.task, &task.patch, session_paths.home.as_utf8_path()) + .map_err(io::Error::other)?; // `inherit_cwd`: start where the client was invoked, inside the // uploaded tree, or fall back to the root with a notice. let (start_dir, mut start_notice) = match task_start_dir( From 4fa327f4d54b635e4938bc4d6d1ca74e872f7468 Mon Sep 17 00:00:00 2001 From: "minimal-foundry[bot]" <327719912+minimal-foundry[bot]@users.noreply.github.com> Date: Tue, 20 Oct 2026 02:00:29 +0000 Subject: [PATCH 18/21] docs(policy): describe the stricter task patch checks --- docs/reference/user-policy.md | 27 +++++++++++++++++++-------- 1 file changed, 19 insertions(+), 8 deletions(-) diff --git a/docs/reference/user-policy.md b/docs/reference/user-policy.md index f5f33f2083..0c183cd968 100644 --- a/docs/reference/user-policy.md +++ b/docs/reference/user-policy.md @@ -163,13 +163,19 @@ so the rules apply to the **declared path** itself: - `allow` must match the path as `minimal.toml` declares it. A rule naming a declared directory approves that directory whatever it holds. -- `deny` on the declared path, or on any file a declared directory holds, - stops the run. Minimal follows a symlink to a directory inside a declared - directory and checks the files it reaches, since the mount exposes them. - If a directory is too large or partly unreadable to check against your deny - rules, the run stops and names the reason. A `~/` entry names the - session's home. `min` matches it against your rules by its path only, and - does not check its contents or links, because the box writes them. +- `deny` on the declared path, or on any file or directory a declared + directory holds, stops the run. Minimal follows a symlink to a directory + inside a declared directory and checks the files it reaches, since the mount + exposes them. If a directory is too large or partly unreadable to check + against your deny rules, the run stops and names the reason. A `~/` entry + names the session's home. `min` matches it against your rules by its path + only, and does not check its contents or links, because the box writes them. +- A read-write (`"rw"`) directory stops the run when a `deny` rule can name a + path inside it, even a path that does not exist yet, because the task can + create it. Declare the directory `"ro"`, or declare a directory that leaves + that path out. +- A `~/` path that leads out of the session's home through a symlink stops the + run. The session checks this when the task starts. - For a declared absolute path, Minimal also checks the path it resolves to on your machine, and `allow` must match that path too. A symlink cannot carry the path past a `deny` on its target, or onto a target no rule allows. This @@ -179,7 +185,12 @@ so the rules apply to the **declared path** itself: - `ignore` on the declared path leaves that entry out. An `ignore` on a file inside a declared directory does not apply, because a mount cannot leave one file out. -- A declared path with a `.` or `..` segment stops the run. +- A declared path with a `.` or `..` segment stops the run, and so does a + path that does not start with `/` or `~/`. +- A path that Minimal cannot resolve on your machine, for example a symlink + inside a directory you cannot read, stops the run. +- The `[patches] allow` lines in the error match each path exactly: Minimal + escapes a `*`, `?`, `[` or `{` in a path. - Minimal matches a `~/` path as declared, and expands its `~/` against your home the same way as a rule's `~/`. The session mounts `~/` from the session's own home, so Minimal does not check what your home holds. From b5221dc40bf9690f18639ed80cd6d1f414b40b19 Mon Sep 17 00:00:00 2001 From: "gominimal-aw-bot[bot]" <281738952+gominimal-aw-bot[bot]@users.noreply.github.com> Date: Tue, 20 Oct 2026 12:57:21 -0400 Subject: [PATCH 19/21] fix(task): recheck ~/ patch links per spawn and name the failing link The daemon now runs the ~/ containment check before each spawn, since every spawn follows the links again and an earlier invocation can change them. The refusal names the first path on the key that cannot be resolved or that leaves the home, with separate texts for each, and the unreadable-home text names a next step. The check is still not race-free; the docs say so. A read-write patch directory refused by a deny rule with no fixed prefix, such as **/*.pem, now says the rule can match inside any directory and asks for "ro" only, and the policy docs say the same. Adds tests for a ~/ key through a link loop, a home that is itself a symlink, and deny_reaches_any_dir. --- crates/boxes/src/core/compose.rs | 35 ++++++-- crates/boxes/src/core/compose/tests.rs | 13 +++ crates/minimal/src/task.rs | 37 ++++++++- crates/minimald/src/exec.rs | 110 ++++++++++++++++++++++--- docs/reference/user-policy.md | 8 +- 5 files changed, 178 insertions(+), 25 deletions(-) diff --git a/crates/boxes/src/core/compose.rs b/crates/boxes/src/core/compose.rs index efa8ef6a1b..c420af6adf 100644 --- a/crates/boxes/src/core/compose.rs +++ b/crates/boxes/src/core/compose.rs @@ -1712,9 +1712,10 @@ fn resolve_path( /// Where `path` leads on this machine: its deepest existing ancestor /// canonicalized, a dangling symlink on the way followed by hand, and the -/// missing tail joined back on. `None` when that cannot be said, for a -/// link that cannot be followed or any error other than "not found". The -/// daemon uses it to keep a `~/` patch key inside the session's home. +/// missing tail joined back on. `None` when that cannot be said: for a +/// link that cannot be followed, any error other than "not found", or a +/// path that is not valid UTF-8 once resolved. The daemon uses it to keep +/// a `~/` patch key inside the session's home. #[must_use] pub fn resolve_patch_target(path: &camino::Utf8Path) -> Option { resolve_path(path, 0).ok().flatten() @@ -1733,6 +1734,28 @@ pub fn resolve_patch_target(path: &camino::Utf8Path) -> Option bool { let inside = format!("{}/", dir.trim_end_matches('/')); + let (literal, has_meta) = deny_literal_prefix(pattern); + if has_meta { + literal.starts_with(&inside) || inside.starts_with(&literal) + } else { + literal.starts_with(&inside) + } +} + +/// Whether the `deny` pattern `pattern` has no fixed directory to start +/// from, such as `**/*.pem` or `/*/.env`, so it can match inside any +/// directory: [`deny_reaches_inside`] holds for every absolute `dir`. No +/// read-write directory can leave such a rule's paths out. +#[must_use] +pub fn deny_reaches_any_dir(pattern: &str) -> bool { + let (literal, has_meta) = deny_literal_prefix(pattern); + has_meta && "/".starts_with(literal.as_str()) +} + +/// The literal prefix of `pattern`, read up to its first glob +/// metacharacter (`*`, `?`, `[`, `{`), and whether it has one. A +/// backslash escape and a one-byte class such as `[*]` count as literal. +fn deny_literal_prefix(pattern: &str) -> (String, bool) { let chars: Vec = pattern.chars().collect(); let mut literal = String::with_capacity(pattern.len()); let mut i = 0; @@ -1760,11 +1783,7 @@ pub(crate) fn deny_reaches_inside(pattern: &str, dir: &str) -> bool { } } } - if has_meta { - literal.starts_with(&inside) || inside.starts_with(&literal) - } else { - literal.starts_with(&inside) - } + (literal, has_meta) } /// One path's decision against the expanded policy, as written. diff --git a/crates/boxes/src/core/compose/tests.rs b/crates/boxes/src/core/compose/tests.rs index 91c413d698..7a16ecd20f 100644 --- a/crates/boxes/src/core/compose/tests.rs +++ b/crates/boxes/src/core/compose/tests.rs @@ -3390,6 +3390,19 @@ mod gate_task_patch_paths { assert!(!deny_reaches_inside("/h/uu/x", "/h/u")); } + /// A deny with no fixed directory before its first metacharacter can + /// match inside any directory; one with a fixed directory cannot. + #[test] + fn deny_reaches_any_dir_needs_no_fixed_prefix() { + use crate::core::compose::deny_reaches_any_dir; + for pattern in ["**/*.pem", "**/.env", "/*/.env", "*"] { + assert!(deny_reaches_any_dir(pattern), "{pattern}"); + } + for pattern in ["/h/u/.ssh/**", "/h/*/.ssh/**", "/etc/token", "/", "[*]/x"] { + assert!(!deny_reaches_any_dir(pattern), "{pattern}"); + } + } + /// A deny that names a directory without `/**` still applies to that /// directory when the walk meets it inside a declared one. #[test] diff --git a/crates/minimal/src/task.rs b/crates/minimal/src/task.rs index 9bf7064e05..9f7f6f06b0 100644 --- a/crates/minimal/src/task.rs +++ b/crates/minimal/src/task.rs @@ -559,11 +559,15 @@ fn writable_deny_task_patch_message( pattern: &str, policy_path: &std::path::Path, ) -> String { + let next = if boxes::core::compose::deny_reaches_any_dir(pattern) { + "This rule can match inside any directory, so declare the directory \"ro\"" + } else { + "Declare the directory \"ro\", or declare a directory that leaves those paths out" + }; format!( "task '{task_name}' declares the read-write patch directory `{path}`. \ The task can create files in it that the `[patches] deny` rule \ - `{pattern}` in {policy} forbids. Declare the directory \"ro\", or \ - declare a directory that leaves those paths out", + `{pattern}` in {policy} forbids. {next}", policy = policy_path.display(), ) } @@ -2299,6 +2303,35 @@ mod tests { assert!(msg.contains("\"ro\""), "{msg}"); } + /// A deny rule with no fixed directory, such as `**/*.pem`, reaches + /// into every read-write directory, so the refusal asks for "ro" only + /// and does not suggest declaring another directory. + #[test] + fn a_writable_directory_under_a_deny_anywhere_asks_for_ro_only() { + let task = task_from_toml( + "[tasks.t]\nexec = 'true'\n[tasks.t.patch.dir]\n\ + \"/nonexistent-min-test/cache\" = \"rw\"\n", + ); + let policy = boxes::core::policy::PatchesPolicy::default() + .with_allow(vec!["/nonexistent-min-test/**".to_string()]) + .with_deny(vec!["**/*.pem".to_string()]); + let err = resolve_task_patches( + &task, + "t", + policy, + &policy_path_fixture(), + &project_source(), + &NeverAsked, + &minimald_rpc::taskenv::TaskEnv::default(), + ) + .expect_err("a writable directory under a deny anywhere must fail the gate"); + let msg = err.to_string(); + assert!(msg.contains("`**/*.pem`"), "{msg}"); + assert!(msg.contains("can match inside any directory"), "{msg}"); + assert!(msg.contains("\"ro\""), "{msg}"); + assert!(!msg.contains("leaves those paths out"), "{msg}"); + } + /// A glob metacharacter in a refused path is escaped in the snippet, /// so the rule matches that one path and the policy still loads. #[test] diff --git a/crates/minimald/src/exec.rs b/crates/minimald/src/exec.rs index e2825f7ebb..8255b20b0e 100644 --- a/crates/minimald/src/exec.rs +++ b/crates/minimald/src/exec.rs @@ -424,12 +424,16 @@ fn apply_patch_verdict( /// can reach. The client cannot look inside the session's home, so this /// check runs here: each `~/` key must still lie under the home once its /// links are followed. A key whose links cannot be followed is refused. -/// A box that swaps a link after this check and before the mount is not -/// caught. +/// +/// The task runs it before each command it spawns, since the mount +/// follows the links again at each spawn and an earlier command can +/// change them. It is still not race-free: a link swapped after this +/// check and before the mount is not caught. /// /// # Errors /// -/// The refusal text, naming the task and the key. +/// The refusal text, naming the task, the key, and the first path on it +/// that cannot be resolved or that resolves outside the home. fn refuse_escaping_home_patches( task_name: &str, patch: &mfile::EnvPatches, @@ -448,19 +452,38 @@ fn refuse_escaping_home_patches( let Some(home_real) = resolve_patch_target(home) else { return Err(format!( "task '{task_name}' declares patch paths under `~/`, and the session's \ - home {home} cannot be read, so the task did not run" + home {home} cannot be resolved, so the task did not run. Check that \ + the session is still running with `min session list`, then run the \ + task again" )); }; for (key, rest) in tilde { - match resolve_patch_target(&home.join(rest)) { - Some(target) if target.starts_with(&home_real) => {} - _ => { - return Err(format!( - "task '{task_name}' declares the patch path `{key}`, which leads \ - outside the session's home through a symbolic link, so the task \ - did not run. Remove the link from the session, then run the task \ - again" - )); + // Each path from the home down to the key in turn, so the refusal + // names the first one that cannot be resolved or that leaves. + let mut at = camino::Utf8PathBuf::from("~"); + let mut on_disk = home.to_path_buf(); + for part in camino::Utf8Path::new(rest).components() { + at.push(part); + on_disk.push(part); + match resolve_patch_target(&on_disk) { + Some(target) if target.starts_with(&home_real) => {} + Some(target) => { + return Err(format!( + "task '{task_name}' declares the patch path `{key}`, and \ + `{at}` in the session is a symbolic link to {target}, \ + outside the session's home, so the task did not run. \ + Remove the link from the session, then run the task again" + )); + } + None => { + return Err(format!( + "task '{task_name}' declares the patch path `{key}`, and \ + `{at}` in the session cannot be resolved: a symbolic link \ + on it loops, or a directory on it cannot be read, so the \ + task did not run. Fix or remove that link or directory in \ + the session, then run the task again" + )); + } } } } @@ -522,6 +545,13 @@ mod patch_verdict_tests { assert!(err.contains(&format!("`{key}`")), "{err}"); assert!(err.contains("outside the session's home"), "{err}"); } + let err = + refuse_escaping_home_patches("t", &patches(&["~/x/sub"], &[]), &home).unwrap_err(); + assert!( + err.contains("`~/x` in the session is a symbolic link"), + "{err}" + ); + assert!(err.contains(outside.as_str()), "{err}"); refuse_escaping_home_patches( "t", &patches(&["~/inside", "~/new/dir", "/opt/x"], &["~/inside/f"]), @@ -530,6 +560,51 @@ mod patch_verdict_tests { .expect("every key stays inside the home"); } + /// A `~/` key through a link loop cannot be resolved: it is refused + /// with its own text, naming the looping link, not as leaving the home. + #[cfg(unix)] + #[test] + fn a_tilde_patch_through_a_link_loop_is_refused() { + let tmp = tempfile::tempdir().unwrap(); + let home = + camino::Utf8PathBuf::from_path_buf(std::fs::canonicalize(tmp.path()).unwrap()).unwrap(); + std::os::unix::fs::symlink(home.join("b").as_std_path(), home.join("a").as_std_path()) + .unwrap(); + std::os::unix::fs::symlink(home.join("a").as_std_path(), home.join("b").as_std_path()) + .unwrap(); + + let err = + refuse_escaping_home_patches("t", &patches(&["~/a/sub"], &[]), &home).unwrap_err(); + assert!(err.contains("`~/a/sub`"), "{err}"); + assert!( + err.contains("`~/a` in the session cannot be resolved"), + "{err}" + ); + assert!(!err.contains("outside the session's home"), "{err}"); + } + + /// A home that is itself a symlink is compared by where it leads: a + /// key inside its target passes, and a link out of it is still refused. + #[cfg(unix)] + #[test] + fn a_home_that_is_a_symlink_is_checked_by_its_target() { + let tmp = tempfile::tempdir().unwrap(); + let root = + camino::Utf8PathBuf::from_path_buf(std::fs::canonicalize(tmp.path()).unwrap()).unwrap(); + let real = root.join("real-home"); + let home = root.join("home"); + let outside = root.join("outside"); + std::fs::create_dir_all(real.join("inside").as_std_path()).unwrap(); + std::fs::create_dir(outside.as_std_path()).unwrap(); + std::os::unix::fs::symlink(real.as_std_path(), home.as_std_path()).unwrap(); + std::os::unix::fs::symlink(outside.as_std_path(), real.join("x").as_std_path()).unwrap(); + + refuse_escaping_home_patches("t", &patches(&["~/inside", "~/new"], &[]), &home) + .expect("keys inside the home's target pass"); + let err = refuse_escaping_home_patches("t", &patches(&["~/x"], &[]), &home).unwrap_err(); + assert!(err.contains("outside the session's home"), "{err}"); + } + fn patches(dirs: &[&str], files: &[&str]) -> mfile::EnvPatches { let mut p = mfile::EnvPatches::default(); for d in dirs { @@ -813,6 +888,15 @@ async fn task_producer( cmd.stdin(hakoniwa::Stdio::piped()) .stdout(hakoniwa::Stdio::piped()) .stderr(hakoniwa::Stdio::piped()); + // The spawn follows the `~/` links again, and an earlier + // invocation mounts the session home, so it can have changed + // them: check again right before this mount. + refuse_escaping_home_patches( + &exec.task, + &task.patch, + session_paths.home.as_utf8_path(), + ) + .map_err(io::Error::other)?; let mut child = cmd .spawn() .map_err(|e| io::Error::other(format!("command launch failed: {}", e)))?; diff --git a/docs/reference/user-policy.md b/docs/reference/user-policy.md index 0c183cd968..8ba898fcab 100644 --- a/docs/reference/user-policy.md +++ b/docs/reference/user-policy.md @@ -173,9 +173,13 @@ so the rules apply to the **declared path** itself: - A read-write (`"rw"`) directory stops the run when a `deny` rule can name a path inside it, even a path that does not exist yet, because the task can create it. Declare the directory `"ro"`, or declare a directory that leaves - that path out. + that path out. A rule with no fixed directory at its start, such as + `**/*.pem`, can match inside any directory, so no read-write directory + leaves it out: declare the directory `"ro"`. - A `~/` path that leads out of the session's home through a symlink stops the - run. The session checks this when the task starts. + run. The session checks this when the task starts and again before each + command the task runs. The check does not catch a symlink that changes + after the check and before the mount. - For a declared absolute path, Minimal also checks the path it resolves to on your machine, and `allow` must match that path too. A symlink cannot carry the path past a `deny` on its target, or onto a target no rule allows. This From 9d38f6fe9ff2ee4cad51b234e2b89e19ebd67358 Mon Sep 17 00:00:00 2001 From: "gominimal-aw-bot[bot]" <281738952+gominimal-aw-bot[bot]@users.noreply.github.com> Date: Tue, 20 Oct 2026 13:24:52 -0400 Subject: [PATCH 20/21] fix(boxes): check every symlink alias in a task patch walk The patch.dir walk skipped any canonical directory it had already walked, so files reached through a second symlink to it never met a deny naming that alias. Track the canonical ancestors per branch instead: an alias is walked and checked again, a link back to an ancestor still ends the branch, and the entry limit bounds the repeats. --- crates/boxes/src/core/compose.rs | 56 +++++++++++++--- crates/boxes/src/core/compose/tests.rs | 89 ++++++++++++++++++++++++++ 2 files changed, 135 insertions(+), 10 deletions(-) diff --git a/crates/boxes/src/core/compose.rs b/crates/boxes/src/core/compose.rs index c420af6adf..eb4846341e 100644 --- a/crates/boxes/src/core/compose.rs +++ b/crates/boxes/src/core/compose.rs @@ -1915,6 +1915,35 @@ fn decide_answered_task_patch_forms( Ok((decided, rule_used)) } +/// The canonical directories on one branch of a patch directory walk, from +/// the directory being walked back to the declared one +/// ([`check_task_patch_dir`]). Shared between siblings, so a push is O(1). +struct PatchWalkBranch { + dir: std::path::PathBuf, + parent: Option>, +} + +impl PatchWalkBranch { + /// `parent` extended by `dir`, or `parent` itself when `dir` is unknown. + fn push( + parent: Option>, + dir: Option<&std::path::PathBuf>, + ) -> Option> { + match dir { + Some(dir) => Some(std::rc::Rc::new(Self { + dir: dir.clone(), + parent, + })), + None => parent, + } + } + + /// Whether `dir` is on the branch `from`: walking it again is a cycle. + fn holds(from: Option<&std::rc::Rc>, dir: &std::path::Path) -> bool { + std::iter::successors(from.map(std::rc::Rc::as_ref), |b| b.parent.as_deref()).any(|b| b.dir == dir) + } +} + /// A declared directory entry's decision: the directory's own path, then /// a deny probe over what it currently holds on this machine. /// @@ -1966,14 +1995,16 @@ fn check_task_patch_dir( // it sits on disk, so each file is checked in both forms. A symlinked // directory (the declared one, or one met mid-walk) holds its files // where it points, and the mount keeps the link, so it is walked at - // its target. Canonical directories already walked are skipped, which - // ends a link cycle. + // its target. A directory reached again through another path is walked + // again, since the mount exposes its files under that path too; only a + // canonical directory already on the current branch is skipped, which + // ends a link cycle. `limit` bounds the walk however much aliasing + // repeats it. let root_canonical = std::fs::canonicalize(dir.as_std_path()).ok(); - let mut visited: std::collections::HashSet = - root_canonical.iter().cloned().collect(); - let mut stack = vec![(dir.as_std_path().to_path_buf(), root_canonical)]; + let root_branch = PatchWalkBranch::push(None, root_canonical.as_ref()); + let mut stack = vec![(dir.as_std_path().to_path_buf(), root_canonical, root_branch)]; let mut seen = 0usize; - while let Some((cur, canonical)) = stack.pop() { + while let Some((cur, canonical, branch)) = stack.pop() { let read = match std::fs::read_dir(&cur) { Ok(read) => read, Err(e) if e.kind() == std::io::ErrorKind::NotFound => continue, @@ -2007,17 +2038,22 @@ fn check_task_patch_dir( return Ok(PathDecision::Denied); } if file_type.is_some_and(|t| t.is_dir()) { - if on_disk.as_ref().is_none_or(|c| visited.insert(c.clone())) { - stack.push((entry.path(), on_disk)); + if on_disk + .as_ref() + .is_none_or(|c| !PatchWalkBranch::holds(branch.as_ref(), c)) + { + let next = PatchWalkBranch::push(branch.clone(), on_disk.as_ref()); + stack.push((entry.path(), on_disk, next)); } continue; } if is_link && let Ok(target) = std::fs::canonicalize(entry.path()) && target.is_dir() - && visited.insert(target.clone()) + && !PatchWalkBranch::holds(branch.as_ref(), &target) { - stack.push((entry.path(), Some(target))); + let next = PatchWalkBranch::push(branch.clone(), Some(&target)); + stack.push((entry.path(), Some(target), next)); } } } diff --git a/crates/boxes/src/core/compose/tests.rs b/crates/boxes/src/core/compose/tests.rs index 7a16ecd20f..356ca9ed34 100644 --- a/crates/boxes/src/core/compose/tests.rs +++ b/crates/boxes/src/core/compose/tests.rs @@ -3151,6 +3151,95 @@ mod gate_task_patch_paths { assert_eq!(decision, crate::core::policy::PathDecision::Allowed); } + /// An allowed directory `data` holding a real directory `real/secret` + /// and the symlinks `aliases`, each pointing at `real`, with `deny` set + /// to the rules `deny` builds from `data`. + #[cfg(unix)] + fn allowed_dir_with_aliases( + tmp: &tempfile::TempDir, + aliases: &[&str], + deny: impl FnOnce(&camino::Utf8Path) -> Vec, + ) -> ( + camino::Utf8PathBuf, + crate::core::policy::ExpandedPatchesPolicy, + ) { + let dir = canonical_root(tmp).join("data"); + let real = dir.join("real"); + std::fs::create_dir_all(real.as_std_path()).unwrap(); + std::fs::write(real.join("secret").as_std_path(), "x").unwrap(); + for alias in aliases { + std::os::unix::fs::symlink(real.as_std_path(), dir.join(alias).as_std_path()).unwrap(); + } + let policy = PatchesPolicy::default() + .with_allow(vec![dir.to_string()]) + .with_deny(deny(&dir)) + .expand_with(&NoVars, None) + .unwrap(); + (dir, policy) + } + + /// Two symlinks to one directory are each walked, since the mount + /// exposes its files under both: a deny that names a file only through + /// one alias refuses the entry, whichever alias the walk meets first. + #[cfg(unix)] + #[test] + fn a_deny_through_a_second_symlink_alias_is_refused() { + use crate::core::compose::check_task_patch_dir; + for denied in ["a1", "a2"] { + let tmp = tempfile::tempdir().unwrap(); + let (dir, policy) = allowed_dir_with_aliases(&tmp, &["a1", "a2"], |dir| { + vec![dir.join(denied).join("secret").to_string()] + }); + let source = project_source(); + let decision = check_task_patch_dir(&policy, &source, &dir, true, 100).unwrap(); + assert_eq!( + decision, + crate::core::policy::PathDecision::Denied, + "deny through {denied}" + ); + } + } + + /// A symlink back to a directory on the current branch, the declared + /// one or one below it, ends that branch rather than looping. + #[cfg(unix)] + #[test] + fn a_link_to_an_ancestor_ends_the_walk() { + use crate::core::compose::check_task_patch_dir; + let tmp = tempfile::tempdir().unwrap(); + let (dir, policy) = + allowed_dir_with_aliases(&tmp, &[], |dir| vec![dir.join("elsewhere").to_string()]); + let real = dir.join("real"); + std::os::unix::fs::symlink(dir.as_std_path(), real.join("root").as_std_path()).unwrap(); + std::os::unix::fs::symlink(real.as_std_path(), real.join("self").as_std_path()).unwrap(); + let source = project_source(); + let decision = check_task_patch_dir(&policy, &source, &dir, true, 1_000).unwrap(); + assert_eq!(decision, crate::core::policy::PathDecision::Allowed); + } + + /// Every alias of a directory is walked in full, so the entry limit, + /// not the number of distinct directories, bounds the walk. + #[cfg(unix)] + #[test] + fn many_symlink_aliases_are_bounded_by_the_walk_limit() { + use crate::core::compose::{TaskPatchWalkGap, check_task_patch_dir}; + let tmp = tempfile::tempdir().unwrap(); + let names: Vec = (0..20).map(|i| format!("a{i}")).collect(); + let aliases: Vec<&str> = names.iter().map(String::as_str).collect(); + let (dir, policy) = allowed_dir_with_aliases(&tmp, &aliases, |dir| { + vec![dir.join("elsewhere").to_string()] + }); + let source = project_source(); + // `real`, its file, then each alias and the file under it: 42. + let gap = check_task_patch_dir(&policy, &source, &dir, true, 41).unwrap_err(); + assert!( + matches!(gap, TaskPatchWalkGap::TooLarge { limit: 41 }), + "{gap}" + ); + let decision = check_task_patch_dir(&policy, &source, &dir, true, 42).unwrap(); + assert_eq!(decision, crate::core::policy::PathDecision::Allowed); + } + /// With no deny set, nothing is walked, so a directory over the limit /// keeps its own decision. #[test] From 0f7a0235ae8ad67d50d1a7d03ad0df6debf44847 Mon Sep 17 00:00:00 2001 From: "gominimal-aw-bot[bot]" <281738952+gominimal-aw-bot[bot]@users.noreply.github.com> Date: Wed, 21 Oct 2026 10:52:08 -0400 Subject: [PATCH 21/21] style(boxes): apply rustfmt to the patch-gate compose code --- crates/boxes/src/core/compose.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/crates/boxes/src/core/compose.rs b/crates/boxes/src/core/compose.rs index eb4846341e..fe7052167b 100644 --- a/crates/boxes/src/core/compose.rs +++ b/crates/boxes/src/core/compose.rs @@ -1940,7 +1940,8 @@ impl PatchWalkBranch { /// Whether `dir` is on the branch `from`: walking it again is a cycle. fn holds(from: Option<&std::rc::Rc>, dir: &std::path::Path) -> bool { - std::iter::successors(from.map(std::rc::Rc::as_ref), |b| b.parent.as_deref()).any(|b| b.dir == dir) + std::iter::successors(from.map(std::rc::Rc::as_ref), |b| b.parent.as_deref()) + .any(|b| b.dir == dir) } }