diff --git a/crates/boxes/src/core/compose.rs b/crates/boxes/src/core/compose.rs
index 05f827c27f..fe7052167b 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,
@@ -523,6 +523,42 @@ 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 },
+ /// 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.
+ /// 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,
@@ -1533,6 +1569,773 @@ 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,
+ /// `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,
+}
+
+/// Upper bound on the entries a directory walk in [`check_task_patch_dir`]
+/// 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 },
+ /// The declared directory is a file.
+ NotADirectory,
+}
+
+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})"),
+ Self::NotADirectory => write!(f, "it is a file, not a directory"),
+ }
+ }
+}
+
+/// 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 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), 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 Unresolvable;
+
+/// 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. 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.
+///
+/// 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, Unresolvable> {
+ 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 , Unresolvable> {
+ let mut tail: Vec<&str> = Vec::new();
+ let mut cur = path;
+ loop {
+ 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));
+ }
+ 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.
+ 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(Unresolvable);
+ }
+ 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,
+ };
+ for seg in tail.iter().rev() {
+ next.push(seg);
+ }
+ return resolve_path(&next, hops + 1);
+ }
+ // 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(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, 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()
+}
+
+/// 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 (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;
+ 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;
+ }
+ }
+ }
+ (literal, has_meta)
+}
+
+/// 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 };
+ 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,
+ CheckOutcome::NeedsApproval(_) => crate::core::policy::PathDecision::NeedsApproval,
+ }
+}
+
+/// One declared path's [`PathDecision`](crate::core::policy::PathDecision).
+///
+/// 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`]). A dangling link that cannot be followed
+/// 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,
+ 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) {
+ Ok(Some(resolved)) => own.combine(decide_task_patch_path(expanded, source, &resolved)),
+ Ok(None) => own,
+ Err(Unresolvable) => PathDecision::Denied,
+ }
+}
+
+/// 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 Ok(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))
+}
+
+/// 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.
+///
+/// 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.
+///
+/// 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
+/// 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.
+/// 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.
+fn check_task_patch_dir(
+ expanded: &ExpandedPatchesPolicy,
+ source: &Source,
+ dir: &camino::Utf8Path,
+ resolve: bool,
+ limit: usize,
+) -> Result {
+ use crate::core::policy::PathDecision;
+ let own = check_task_patch_path(expanded, source, dir, resolve);
+ 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());
+ // 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. 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 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, branch)) = stack.pop() {
+ 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 {
+ let entry = entry.map_err(|e| unreadable(&cur, e))?;
+ seen += 1;
+ 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()));
+ // 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.
+ 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 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 Ok(PathDecision::Denied);
+ }
+ if file_type.is_some_and(|t| t.is_dir()) {
+ 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()
+ && !PatchWalkBranch::holds(branch.as_ref(), &target)
+ {
+ let next = PatchWalkBranch::push(branch.clone(), Some(&target));
+ stack.push((entry.path(), Some(target), next));
+ }
+ }
+ }
+ 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. 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::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 {
+ 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,
+ 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` /
+/// `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. 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.
+/// 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
+/// can only make the entry stricter (see [`check_task_patch_path`] and
+/// [`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
+/// 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::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.
+/// - [`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> {
+ 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.
+ 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),
+ }
+ };
+ // 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.
+ // `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
+ // 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(),
+ });
+ }
+ // 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
+ // 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 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(),
+ });
+ }
+ 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)),
+ );
+ }
+ }
+ }
+
+ 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, 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, item, _)| Unapproved {
+ item: camino::Utf8Path::new(item),
+ 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. 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];
+ 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(),
+ });
+ }
+ };
+ }
+ }
+
+ 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..356ca9ed34 100644
--- a/crates/boxes/src/core/compose/tests.rs
+++ b/crates/boxes/src/core/compose/tests.rs
@@ -2501,3 +2501,1015 @@ 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,
+ read_only: true,
+ 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,
+ items: &[Unapproved<'_, camino::Utf8Path>],
+ ) -> HookResult {
+ // 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();
+ 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 { .. }));
+ }
+
+ /// 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 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 an_ignored_contained_file_leaves_an_allowed_directory_alone() {
+ let tmp = tempfile::tempdir().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(".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!["**/.DS_Store".to_string()]);
+ let (verdicts, _) = gate_task_patch_paths(&entries, policy, None, &NoVars, None).unwrap();
+ 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}");
+ }
+
+ /// 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}");
+ }
+
+ /// 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.
+ #[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_symlink_to_an_unallowed_target_is_not_allowed() {
+ 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/**")]);
+ 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]);
+ }
+
+ /// 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
+ /// 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();
+ 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,
+ items: &[Unapproved<'_, camino::Utf8Path>],
+ ) -> HookResult {
+ // One answer per form, as above.
+ HookResult::decided(vec![ItemDecision::UseRule; items.len()])
+ }
+ }
+ 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"));
+ }
+
+ /// 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);
+ }
+
+ /// 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]
+ 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}"),
+ }
+ }
+
+ /// 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}"
+ );
+ }
+
+ /// 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 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]
+ 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-client/src/attach.rs b/crates/minimal-client/src/attach.rs
index 68e4f78819..528d67fd47 100644
--- a/crates/minimal-client/src/attach.rs
+++ b/crates/minimal-client/src/attach.rs
@@ -111,6 +111,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.
@@ -143,6 +159,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",
@@ -1024,6 +1044,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 cd64c7bf5f..fd96560bb2 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
+ /// `[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
@@ -645,6 +647,22 @@ impl Client {
.await
.context("set task env drop list")?;
}
+ // 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 verdict")?;
+ }
channel
.exec(true, command)
.await
diff --git a/crates/minimal/src/cmd/boxes/attach.rs b/crates/minimal/src/cmd/boxes/attach.rs
index 32c01b5d37..ca3f9e5874 100644
--- a/crates/minimal/src/cmd/boxes/attach.rs
+++ b/crates/minimal/src/cmd/boxes/attach.rs
@@ -203,6 +203,19 @@ pub(crate) async fn box_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
+}
+
+/// [`box_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
@@ -213,8 +226,13 @@ pub(crate) async fn box_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/cmd/session.rs b/crates/minimal/src/cmd/session.rs
index 2a9eec0603..a599a10fda 100644
--- a/crates/minimal/src/cmd/session.rs
+++ b/crates/minimal/src/cmd/session.rs
@@ -133,7 +133,20 @@ pub async fn cmd_session_run(
"found session"
);
- box_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
@@ -149,6 +162,7 @@ pub async fn cmd_session_run(
),
None,
None,
+ &[(minimald_rpc::taskenv::TASK_PATCH_VERDICT, verdict.as_str())],
)
.await
}
diff --git a/crates/minimal/src/task.rs b/crates/minimal/src/task.rs
index aa914ae99b..62a20b1575 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,39 @@ 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. 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(boxes::core::expansion::literal_policy_pattern(path));
+ }
+ 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 +399,327 @@ 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 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(),
+ )
+}
+
+/// 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 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.
+///
+/// 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,
+ 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 {
+ use boxes::core::compose::{TaskPatchEntry, gate_task_patch_paths};
+
+ // 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, setting) in &task.patch.dir {
+ entries.push(TaskPatchEntry {
+ declared: key,
+ is_file: false,
+ read_only: matches!(setting, mfile::PatchSetting::ReadOnly),
+ source,
+ });
+ }
+ for (key, setting) in &task.patch.file {
+ entries.push(TaskPatchEntry {
+ declared: key,
+ is_file: true,
+ read_only: matches!(setting, mfile::PatchSetting::ReadOnly),
+ 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(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(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}'"));
+ }
+ };
+
+ // Verdicts pair with `entries` in order, each naming its raw declared
+ // 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(minimald_rpc::taskenv::AllowedPatch {
+ path: key,
+ is_file: entry.is_file,
+ read_only: entry.read_only,
+ })
+ }
+ boxes::core::compose::NameVerdict::Ignored => {
+ out.drop.insert(minimald_rpc::taskenv::DroppedPatch {
+ path: key,
+ is_file: entry.is_file,
+ })
+ }
+ };
+ }
+ 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"
+ )
+}
+
+/// 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 {
+ 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. {next}",
+ 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(
+ 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."
+ ),
+ TaskPatchWalkGap::NotADirectory => format!(
+ "task '{task_name}': patch directory {path} is a file, not a directory. \
+ Declare it under patch.file instead."
+ ),
+ }
+}
+
+/// 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"
+ }
+}
+
+/// 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,
+ no_input: bool,
+) -> Result {
+ let hooks = RefuseAndRecord::default();
+ let verdict = 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 {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" },
+ );
+ }
+ 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. 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 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() {
+ 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
/// whitespace is visible. Split out for unit tests.
fn untrimmed_task_message(task: &str) -> String {
@@ -609,21 +978,32 @@ 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);
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" },
);
}
- (task_env?, user_policy)
+ let mut task_env = task_env?;
+ 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());
let task_env = resolve_task_env(
@@ -635,6 +1015,22 @@ pub async fn cmd_task_run(global: &GlobalArgs, args: TaskRunArgs) -> Result<(),
&hooks,
|k| std::env::var(k),
);
+ // 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. 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 = Some(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();
@@ -644,7 +1040,7 @@ 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)
+ (gated?, after)
};
crate::ensure_daemon(global)?;
@@ -1166,6 +1562,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 +1574,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 +1608,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 +1638,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 +1980,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 +2026,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 +2061,475 @@ 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."
+ );
+ 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,
+ /// 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 path `/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",
+ );
+ }
+
+ /// 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(),
+ true,
+ )
+ .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}");
+ 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}");
+ }
+
+ /// 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 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]
+ 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
+ /// 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}");
+ }
+
+ /// 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]
+ 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 verdict = 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", 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");
+ }
+
+ /// 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_its_patches_like_any_task() {
+ 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 err = resolve_task_patches(
+ &task,
+ "t",
+ policy,
+ &policy_path_fixture(),
+ &project_source(),
+ &NeverAsked,
+ &minimald_rpc::taskenv::TaskEnv::default(),
+ )
+ .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,
+ minimald_rpc::taskenv::PatchVerdict::default(),
+ "nothing to send"
+ );
+ }
+
+ /// 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 verdict = 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!(verdict.drop.is_empty(), "an approved patch is not dropped");
+ assert!(
+ verdict.allows("/opt/tool/bin", true, true),
+ "an approved patch is named as allowed, with its kind and mode, or the daemon \
+ refuses it"
+ );
+ }
+
/// `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..09b58f7dda 100644
--- a/crates/minimald-rpc/src/taskenv.rs
+++ b/crates/minimald-rpc/src/taskenv.rs
@@ -41,6 +41,27 @@ 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 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 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_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]
pub fn wire_name(name: &str) -> String {
@@ -86,27 +107,115 @@ pub fn drops_from_channel_env(env_vars: &BTreeMap) -> BTreeSet,
+ /// Declarations 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,
+}
+
+/// 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
+///
+/// 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_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 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.
+/// 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,
+ /// 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.set.is_empty() && self.drop.is_empty() && self.patch.is_none()
}
}
@@ -280,6 +389,96 @@ 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_VERDICT.starts_with(TASK_ENV_PREFIX));
+ }
+
+ /// 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_verdict_round_trips() {
+ let verdict = PatchVerdict {
+ allow: [AllowedPatch {
+ path: "~/.claude".to_string(),
+ is_file: false,
+ read_only: true,
+ }]
+ .into_iter()
+ .collect(),
+ drop: [DroppedPatch {
+ path: "/etc/secrets".to_string(),
+ is_file: true,
+ }]
+ .into_iter()
+ .collect(),
+ };
+ let mut channel = BTreeMap::new();
+ channel.insert(
+ TASK_PATCH_VERDICT.to_string(),
+ encode_patch_verdict(&verdict).unwrap(),
+ );
+
+ 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.
+ assert!(drops_from_channel_env(&channel).is_empty());
+ }
+
+ /// 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_unparseable_or_oversized_patch_verdict_is_none() {
+ let mut absent = BTreeMap::new();
+ absent.insert("MINIMAL_SESSION_ID".to_string(), "an-id".to_string());
+ assert_eq!(patch_verdict_from_channel_env(&absent), None);
+
+ let mut junk = BTreeMap::new();
+ 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| AllowedPatch {
+ path: format!("/p/{i}"),
+ is_file: true,
+ read_only: true,
+ })
+ .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/env.rs b/crates/minimald/src/env.rs
index 9b05b77681..9350eed63d 100644
--- a/crates/minimald/src/env.rs
+++ b/crates/minimald/src/env.rs
@@ -1470,6 +1470,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) => {
@@ -2963,6 +2971,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();
@@ -2971,7 +2994,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()
@@ -3020,6 +3043,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 f736b93a44..f983157425 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,
+ /// 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.
+ ///
+ /// `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`
@@ -342,6 +352,383 @@ fn parse_task_args(
.map_err(|e| e.to_string())
}
+/// Apply the client's `[patches]` verdict to a task's declared patches:
+/// 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
+/// 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, or names as another kind or mode, since the client never
+/// checked that declaration. 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 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
+ // that is now read-write would be writable, and created if missing.
+ let declared = patch
+ .dir
+ .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 \
+ run. The task's declaration here differs from the minimal.toml \
+ `min` read; run the task again once they match"
+ ));
+ }
+ 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.
+///
+/// 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, 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,
+ 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 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 {
+ // 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"
+ ));
+ }
+ }
+ }
+ }
+ 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, 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}");
+ }
+ 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"]),
+ &home,
+ )
+ .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 {
+ p.dir
+ .insert((*d).to_string(), mfile::PatchSetting::default());
+ }
+ for f in files {
+ p.file
+ .insert((*f).to_string(), mfile::PatchSetting::default());
+ }
+ p
+ }
+
+ /// A verdict allowing each `(key, is_file)` read-only, the mode
+ /// [`patches`] declares.
+ fn verdict(allow: &[(&str, bool)], drop: &[(&str, bool)]) -> PatchVerdict {
+ PatchVerdict {
+ allow: allow
+ .iter()
+ .map(|(path, is_file)| AllowedPatch {
+ path: (*path).to_string(),
+ is_file: *is_file,
+ read_only: true,
+ })
+ .collect(),
+ drop: drop
+ .iter()
+ .map(|(path, is_file)| DroppedPatch {
+ path: (*path).to_string(),
+ is_file: *is_file,
+ })
+ .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 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", true)],
+ );
+ 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 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]
+ fn a_key_the_verdict_does_not_name_is_refused() {
+ let mut p = patches(&["/opt/cache"], &["/etc/shadow"]);
+ 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]
+ 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"
+ );
+ }
+ }
+}
+
/// 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
@@ -414,6 +801,11 @@ async fn task_producer(
for name in &exec.drop_env {
task.vars.remove(name);
}
+ // 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()));
@@ -435,6 +827,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(
@@ -492,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)))?;
@@ -1872,6 +2277,10 @@ pub(crate) async fn handle_exec(
trace_env.clone(),
);
let drop_env = minimald_rpc::taskenv::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(
@@ -1890,6 +2299,7 @@ pub(crate) async fn handle_exec(
task: task.clone(),
env: task_env,
drop_env,
+ patch,
cwd,
},
};
diff --git a/docs/reference/tasks.md b/docs/reference/tasks.md
index c795d9d948..d1eefe08f5 100644
--- a/docs/reference/tasks.md
+++ b/docs/reference/tasks.md
@@ -300,7 +300,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_
@@ -329,6 +329,16 @@ 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. 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`.
+
### `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..8ba898fcab 100644
--- a/docs/reference/user-policy.md
+++ b/docs/reference/user-policy.md
@@ -154,6 +154,56 @@ 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 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 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 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
+ 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
+ one file out.
+- 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.
+
+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