From 36f9c16761bb244427de2978754c815a424d40f5 Mon Sep 17 00:00:00 2001 From: ualtinok <94532+ualtinok@users.noreply.github.com> Date: Sun, 6 Dec 2026 17:28:07 +0100 Subject: [PATCH 1/7] mason: cover platform-specific bash permission matching Pin both deny-rule spellings, basename-only normalization, and launcher recognition with injected case behavior; the new macOS cases are red until the matching change. Co-authored-by: alfonso-aft <289616620+alfonso-aft@users.noreply.github.com> --- crates/aft-shell/src/bash_permissions/scan.rs | 44 ++++++++++++++++++- .../src/bash_permissions/synthetic_load.rs | 20 ++++++--- .../src/__tests__/bash-permissions.test.ts | 31 ++++++++++++- packages/aft-bridge/src/bash-permissions.ts | 17 ++++--- 4 files changed, 98 insertions(+), 14 deletions(-) diff --git a/crates/aft-shell/src/bash_permissions/scan.rs b/crates/aft-shell/src/bash_permissions/scan.rs index d77967fc98..6bc411f1df 100644 --- a/crates/aft-shell/src/bash_permissions/scan.rs +++ b/crates/aft-shell/src/bash_permissions/scan.rs @@ -87,7 +87,7 @@ pub fn scan_with_cwd_for_session( }; let registry = ctx.bash_background(); let owned_artifact = |path: &Path| registry.is_session_owned_artifact_path(session_id, path); - scan_with_read_exemption(command, &project_root, cwd, Some(&owned_artifact)) + scan_with_read_exemption(command, &project_root, cwd, Some(&owned_artifact), false) } pub fn scan_with_project_root( @@ -95,7 +95,7 @@ pub fn scan_with_project_root( project_root: &Path, cwd: &Path, ) -> Vec { - scan_with_read_exemption(command, project_root, cwd, None) + scan_with_read_exemption(command, project_root, cwd, None, false) } fn scan_with_read_exemption( @@ -103,6 +103,7 @@ fn scan_with_read_exemption( project_root: &Path, cwd: &Path, read_exemption: Option>, + _fold_executable_case: bool, ) -> Vec { let project_root = resolve_existing(&project_root); let cwd = resolve_existing(cwd); @@ -1902,6 +1903,45 @@ mod tests { .collect() } + #[test] + fn executable_case_checks_both_spellings_against_host_denies() { + let project = tempfile::tempdir().unwrap(); + let root = project.path(); + for fold in [true, false] { + let asks = scan_with_read_exemption("Git push --force", root, root, None, fold); + assert_eq!(asks.len(), 1); + let patterns = &asks[0].patterns; + let matches_prefix = |prefix| patterns.iter().any(|pattern| pattern.starts_with(prefix)); + assert_eq!(matches_prefix("git push"), fold, "deny `git push*`"); + assert!(matches_prefix("Git push"), "deny `Git push*`"); + assert_eq!(patterns[0], if fold { "git push --force" } else { "Git push --force" }); + assert_eq!(patterns.len(), if fold { 2 } else { 1 }); + } + } + + #[test] + fn executable_case_preserves_the_path_prefix_and_rest_of_the_line() { + let project = tempfile::tempdir().unwrap(); + let root = project.path(); + let command = "FLAG=UP ./Tools/Git show Git"; + let asks = scan_with_read_exemption(command, root, root, None, true); + assert_eq!(asks[0].patterns, ["FLAG=UP ./Tools/git show Git", command]); + } + + #[test] + fn executable_case_checks_the_xargs_target_on_case_insensitive_hosts() { + let project = tempfile::tempdir().unwrap(); + let root = project.path(); + let command = "XARGS Git push --force"; + let asks = scan_with_read_exemption(command, root, root, None, true); + assert_eq!(asks.len(), 2); + assert_eq!(asks[0].patterns, ["xargs Git push --force", command]); + assert_eq!(asks[1].patterns, ["git push --force", "Git push --force"]); + let asks = scan_with_read_exemption(command, root, root, None, false); + assert_eq!(asks.len(), 1); + assert_eq!(asks[0].patterns, [command]); + } + #[test] fn directory_targets_preserve_literal_absolute_paths() { let dir = tempfile::tempdir().unwrap(); diff --git a/crates/aft-shell/src/bash_permissions/synthetic_load.rs b/crates/aft-shell/src/bash_permissions/synthetic_load.rs index 47fb4b60df..c0302f2224 100644 --- a/crates/aft-shell/src/bash_permissions/synthetic_load.rs +++ b/crates/aft-shell/src/bash_permissions/synthetic_load.rs @@ -18,7 +18,7 @@ pub fn is_synthetic_load(source: &str) -> bool { collect_commands(tree.root_node(), &mut commands); commands.into_iter().any(|node| { let words = command_words(source, node); - let Some((words, indirect)) = executable_words(&words) else { + let Some((words, indirect)) = executable_words(&words, false) else { return false; }; match command_name(&words) { @@ -103,7 +103,7 @@ fn command_name(words: &Words) -> Option<&str> { /// Peel only known execution wrappers and launcher options. In particular, /// `command -v yes` is a lookup, and `xargs -Iyes echo yes` executes echo. -fn executable_words(words: &Words) -> Option<(Vec>, bool)> { +fn executable_words(words: &Words, _fold_executable_case: bool) -> Option<(Vec>, bool)> { let mut words = words.to_vec(); let mut indirect = false; 'wrappers: loop { @@ -378,7 +378,7 @@ fn pipes_to_device_reader(source: &str, node: Node<'_>) -> bool { return false; }; let words = command_words(source, next); - executable_words(&words) + executable_words(&words, false) .is_some_and(|(words, _)| matches!(command_name(&words), Some("cat" | "dd" | "pv"))) } @@ -445,7 +445,7 @@ fn small_head_pipeline(source: &str, node: Node<'_>) -> bool { return false; } let words = command_words(source, head); - let Some((words, indirect)) = executable_words(&words) else { + let Some((words, indirect)) = executable_words(&words, false) else { return false; }; if indirect || command_name(&words) != Some("head") { @@ -486,7 +486,17 @@ fn small_head_pipeline(source: &str, node: Node<'_>) -> bool { #[cfg(test)] mod tests { - use super::is_synthetic_load; + use super::{executable_words, is_synthetic_load}; + + #[test] + fn executable_case_peels_mixed_case_load_guard_launchers() { + let words = ["/Tools/Env", "MODE=UP", "XARGS", "printf", "UP"].map(|s| Some(s.to_string())); + assert_eq!( + executable_words(&words, true), + Some((words[3..].to_vec(), true)), + ); + assert_eq!(executable_words(&words, false), Some((words.to_vec(), false))); + } #[test] fn synthetic_load_refuses_obvious_load_forms() { diff --git a/packages/aft-bridge/src/__tests__/bash-permissions.test.ts b/packages/aft-bridge/src/__tests__/bash-permissions.test.ts index 4384f3ed59..d115c39b8a 100644 --- a/packages/aft-bridge/src/__tests__/bash-permissions.test.ts +++ b/packages/aft-bridge/src/__tests__/bash-permissions.test.ts @@ -245,7 +245,6 @@ test.each([ ["printf .+^${}()|[]$&", "printf .+^${}()|[]$&", true], ["echo axb", "echo a.b", false], ["git show HEAD extra", "git show HEAD", false], - ["Git show HEAD", "git *", process.platform === "win32"], ])("permission loop matches OpenCode wildcard %p against %p (%p)", async (part, pattern, matches) => { const parts = ["mkdir -p x", part]; const cause = Object.assign(new Error("Permission denied: shell"), { @@ -268,6 +267,36 @@ test.each([ ); }); +test.each([ + ["darwin", "Git push --force", "git push*", true], + ["linux", "Git push --force", "git push*", false], + ["win32", "Git push --force", "git push*", true], + ["darwin", "/Tools/Git push --force", "/tools/git push*", true], + ["linux", "/Tools/Git push --force", "/tools/git push*", false], + ["win32", "C:\\Tools\\Git push --force", "c:/tools/git push*", true], +] as const)("permission loop attributes denials on %s for %s against %s", async (platform, part, resource, matches) => { + const parts = ["mkdir -p x", part]; + const cause = Object.assign(new Error("Permission denied: shell"), { + _tag: "Permission.BlockedError", + permission: "shell", + resources: parts, + rules: [{ action: "shell", resource, effect: "deny" }], + }); + const error = await withBashPermissionLoop({ + platform, + request: async () => ({ ...required, asks: [{ kind: "bash", patterns: parts }] }), + approve: async () => { + throw cause; + }, + }).catch((error) => error); + expect(error.message).toBe( + (matches ? SHELL_REFUSAL_KNOWN : SHELL_REFUSAL_UNKNOWN).replace( + "git ls-tree HEAD src", + () => part, + ), + ); +}); + test("permission loop reports a later refusal with only the newly asked parts", async () => { const laterAsk = { kind: "bash", patterns: ["rm -rf x"] }; const cause = new Error("Permission denied: shell"); diff --git a/packages/aft-bridge/src/bash-permissions.ts b/packages/aft-bridge/src/bash-permissions.ts index 738d093d64..954e5e35b9 100644 --- a/packages/aft-bridge/src/bash-permissions.ts +++ b/packages/aft-bridge/src/bash-permissions.ts @@ -69,7 +69,7 @@ function permissionAskPath(ask: BashPermissionAsk): string { return permissionAskParts(ask).join(", "); } -function hostWildcardMatches(input: string, pattern: string): boolean { +function hostWildcardMatches(input: string, pattern: string, platform: NodeJS.Platform): boolean { // OpenCode @opencode/core 2.1.0, dist/util/wildcard.js:1-7 re-exports this // matcher from dist/chunks/shell-y1fvbwt7.js:11-16 (src/util/wildcard.ts). const normalized = input.replaceAll("\\", "/"); @@ -79,7 +79,7 @@ function hostWildcardMatches(input: string, pattern: string): boolean { .replace(/\*/g, ".*") .replace(/\?/g, "."); if (escaped.endsWith(" .*")) escaped = `${escaped.slice(0, -3)}( .*)?`; - return new RegExp(`^${escaped}$`, process.platform === "win32" ? "si" : "s").test(normalized); + return new RegExp(`^${escaped}$`, platform === "win32" ? "si" : "s").test(normalized); } interface HostPermissionRule { @@ -101,7 +101,11 @@ function isHostPermissionRule(rule: unknown): rule is HostPermissionRule { ); } -function hostDeniedParts(error: unknown, parts: readonly string[]): Set { +function hostDeniedParts( + error: unknown, + parts: readonly string[], + platform: NodeJS.Platform, +): Set { const denied = new Set(); if (typeof error !== "object" || error === null || !("_tag" in error)) return denied; const blocked = error._tag === "Tool.Error" && "error" in error ? error.error : error; @@ -128,8 +132,8 @@ function hostDeniedParts(error: unknown, parts: readonly string[]): Set const rule = blocked.rules[index]; if ( !rule || - !hostWildcardMatches(blocked.permission, rule.action) || - !hostWildcardMatches(part, rule.resource) + !hostWildcardMatches(blocked.permission, rule.action, platform) || + !hostWildcardMatches(part, rule.resource, platform) ) { continue; } @@ -145,6 +149,7 @@ export async function withBashPermissionLoop(options: { request: (granted: readonly string[]) => Promise>; approve: (asks: readonly BashPermissionAsk[]) => Promise; operation?: string; + platform?: NodeJS.Platform; }): Promise> { const granted = new Set(); const alreadyGranted = (ask: BashPermissionAsk) => { @@ -183,7 +188,7 @@ export async function withBashPermissionLoop(options: { await options.approve(pendingAsks); } catch (error) { const parts = pendingAsks.flatMap(permissionAskParts); - const denied = hostDeniedParts(error, parts); + const denied = hostDeniedParts(error, parts, options.platform ?? process.platform); const quotedParts = (parts: readonly string[]) => parts.map((part) => `\`${part}\``).join(", "); const notDenied = parts.filter((part) => !denied.has(part)); From 1bdbb7cf2c38764308b84faf0715cae0aca671fc Mon Sep 17 00:00:00 2001 From: ualtinok <94532+ualtinok@users.noreply.github.com> Date: Sun, 6 Dec 2026 17:33:38 +0100 Subject: [PATCH 2/7] mason: close mixed-case Bash permission gaps on macOS Offer the host the ASCII-folded executable basename and the original resource so both lowercase and exact-spelling denies still work. Apply the same case policy to recognized launchers and to bridge denial attribution without changing refusal wording or Linux matching. Co-authored-by: alfonso-aft <289616620+alfonso-aft@users.noreply.github.com> --- .../src/bash_permissions/executable_case.rs | 40 +++++++++++ crates/aft-shell/src/bash_permissions/mod.rs | 1 + crates/aft-shell/src/bash_permissions/scan.rs | 67 ++++++++++++++----- .../src/bash_permissions/synthetic_load.rs | 37 +++++++--- packages/aft-bridge/src/bash-permissions.ts | 5 +- 5 files changed, 121 insertions(+), 29 deletions(-) create mode 100644 crates/aft-shell/src/bash_permissions/executable_case.rs diff --git a/crates/aft-shell/src/bash_permissions/executable_case.rs b/crates/aft-shell/src/bash_permissions/executable_case.rs new file mode 100644 index 0000000000..02c4d32299 --- /dev/null +++ b/crates/aft-shell/src/bash_permissions/executable_case.rs @@ -0,0 +1,40 @@ +use std::borrow::Cow; +use std::ops::Range; + +// macOS volumes are case-insensitive by default, so a program runs under +// any letter-case spelling of its name. +pub(super) const FOLD_EXECUTABLE_CASE: bool = cfg!(any(target_os = "macos", windows)); + +pub(super) fn basename(word: &str) -> &str { + word.rsplit('/').next().unwrap_or(word) +} + +pub(super) fn fold_basename(word: &str, fold: bool) -> Cow<'_, str> { + let basename = basename(word); + if !fold || !basename.bytes().any(|byte| byte.is_ascii_uppercase()) { + return Cow::Borrowed(word); + } + let mut folded = word.to_owned(); + folded[word.len() - basename.len()..].make_ascii_lowercase(); + Cow::Owned(folded) +} + +pub(super) fn host_patterns(source: &str, head: Option>, fold: bool) -> Vec { + if let Some(head) = head.filter(|_| fold) { + let word = &source[head.clone()]; + if let Cow::Owned(folded) = fold_basename(word, fold) { + // Rewrite only literal executable words, not variable names or + // command substitutions used to compute an executable at runtime. + if crate::bash_parse::parse(word).is_some_and(|parsed| { + parsed.args.len() == 1 && parsed.appends_to.is_none() && parsed.heredoc.is_none() + }) { + let mut normalized = source.to_owned(); + normalized.replace_range(head, &folded); + // The host also checks the original spelling, so normalization + // can't discard a deny rule that matches only that spelling. + return vec![normalized.trim().to_owned(), source.trim().to_owned()]; + } + } + } + vec![source.trim().to_owned()] +} diff --git a/crates/aft-shell/src/bash_permissions/mod.rs b/crates/aft-shell/src/bash_permissions/mod.rs index 36e742302a..073ca3e71c 100644 --- a/crates/aft-shell/src/bash_permissions/mod.rs +++ b/crates/aft-shell/src/bash_permissions/mod.rs @@ -11,6 +11,7 @@ pub mod synthetic_load; #[cfg(unix)] pub(crate) mod writes; +mod executable_case; mod heredoc; mod host; pub use host::PermissionScanHost; diff --git a/crates/aft-shell/src/bash_permissions/scan.rs b/crates/aft-shell/src/bash_permissions/scan.rs index 6bc411f1df..54319c4b3b 100644 --- a/crates/aft-shell/src/bash_permissions/scan.rs +++ b/crates/aft-shell/src/bash_permissions/scan.rs @@ -3,6 +3,7 @@ use std::path::{Path, PathBuf}; use tree_sitter::{Node, Tree}; +use super::executable_case::{basename, host_patterns, FOLD_EXECUTABLE_CASE}; use super::PermissionScanHost; use super::{arity, PermissionAsk, PermissionKind}; @@ -87,7 +88,13 @@ pub fn scan_with_cwd_for_session( }; let registry = ctx.bash_background(); let owned_artifact = |path: &Path| registry.is_session_owned_artifact_path(session_id, path); - scan_with_read_exemption(command, &project_root, cwd, Some(&owned_artifact), false) + scan_with_read_exemption( + command, + &project_root, + cwd, + Some(&owned_artifact), + FOLD_EXECUTABLE_CASE, + ) } pub fn scan_with_project_root( @@ -95,7 +102,7 @@ pub fn scan_with_project_root( project_root: &Path, cwd: &Path, ) -> Vec { - scan_with_read_exemption(command, project_root, cwd, None, false) + scan_with_read_exemption(command, project_root, cwd, None, FOLD_EXECUTABLE_CASE) } fn scan_with_read_exemption( @@ -103,7 +110,7 @@ fn scan_with_read_exemption( project_root: &Path, cwd: &Path, read_exemption: Option>, - _fold_executable_case: bool, + fold_executable_case: bool, ) -> Vec { let project_root = resolve_existing(&project_root); let cwd = resolve_existing(cwd); @@ -246,14 +253,16 @@ fn scan_with_read_exemption( if !CWD_COMMANDS.contains(&head) { // A heredoc opener between words is not part of argv. Rules must // see the recovered command words, not the opener or body. - let pattern = if recovered.is_some() { - tokens.join(" ") + let patterns = if recovered.is_some() { + host_patterns(&tokens.join(" "), Some(0..head.len()), fold_executable_case) } else { - source(command, node) + command_patterns(command, node, fold_executable_case) }; - push_bash_ask(&mut asks, &mut seen, pattern, &tokens); - if head == "xargs" { - push_xargs_ask(&mut asks, &mut seen, &tokens); + push_bash_ask(&mut asks, &mut seen, patterns, &tokens); + if head == "xargs" + || (fold_executable_case && basename(head).eq_ignore_ascii_case("xargs")) + { + push_xargs_ask(&mut asks, &mut seen, &tokens, fold_executable_case); } } } @@ -1418,12 +1427,16 @@ fn command_parts(source: &str, node: Node<'_>) -> Vec { out } -fn source(command: &str, node: Node<'_>) -> String { - let node = node +fn command_patterns(command: &str, node: Node<'_>, fold_executable_case: bool) -> Vec { + let statement = node .parent() .filter(|parent| parent.kind() == "redirected_statement") .unwrap_or(node); - node_text(command, node).trim().to_string() + let offset = statement.start_byte(); + let head = node + .child_by_field_name("name") + .map(|head| head.start_byte() - offset..head.end_byte() - offset); + host_patterns(node_text(command, statement), head, fold_executable_case) } fn node_text<'source>(source: &'source str, node: Node<'_>) -> &'source str { @@ -1739,7 +1752,7 @@ fn display_path(path: &Path) -> String { fn push_bash_ask( asks: &mut Vec, seen: &mut HashSet, - pattern: String, + patterns: Vec, tokens: &[String], ) { let stable = arity::prefix(tokens).join(" "); @@ -1751,7 +1764,7 @@ fn push_bash_ask( seen, PermissionAsk { kind: PermissionKind::Bash, - patterns: vec![pattern], + patterns, always: vec![format!("{stable} *")], reason: None, unreadable: false, @@ -1760,7 +1773,12 @@ fn push_bash_ask( ); } -fn push_xargs_ask(asks: &mut Vec, seen: &mut HashSet, tokens: &[String]) { +fn push_xargs_ask( + asks: &mut Vec, + seen: &mut HashSet, + tokens: &[String], + fold_executable_case: bool, +) { let mut index = 1; while index < tokens.len() && tokens[index].starts_with('-') { index += 1; @@ -1768,7 +1786,12 @@ fn push_xargs_ask(asks: &mut Vec, seen: &mut HashSet, tok if index >= tokens.len() { return; } - push_bash_ask(asks, seen, tokens[index..].join(" "), &tokens[index..]); + let patterns = host_patterns( + &tokens[index..].join(" "), + Some(0..tokens[index].len()), + fold_executable_case, + ); + push_bash_ask(asks, seen, patterns, &tokens[index..]); } /// Match POSIX device-file paths on the RAW string the agent typed (not a @@ -1911,10 +1934,18 @@ mod tests { let asks = scan_with_read_exemption("Git push --force", root, root, None, fold); assert_eq!(asks.len(), 1); let patterns = &asks[0].patterns; - let matches_prefix = |prefix| patterns.iter().any(|pattern| pattern.starts_with(prefix)); + let matches_prefix = + |prefix| patterns.iter().any(|pattern| pattern.starts_with(prefix)); assert_eq!(matches_prefix("git push"), fold, "deny `git push*`"); assert!(matches_prefix("Git push"), "deny `Git push*`"); - assert_eq!(patterns[0], if fold { "git push --force" } else { "Git push --force" }); + assert_eq!( + patterns[0], + if fold { + "git push --force" + } else { + "Git push --force" + } + ); assert_eq!(patterns.len(), if fold { 2 } else { 1 }); } } diff --git a/crates/aft-shell/src/bash_permissions/synthetic_load.rs b/crates/aft-shell/src/bash_permissions/synthetic_load.rs index c0302f2224..310bd37780 100644 --- a/crates/aft-shell/src/bash_permissions/synthetic_load.rs +++ b/crates/aft-shell/src/bash_permissions/synthetic_load.rs @@ -1,7 +1,10 @@ //! Narrow, syntax-based detection of obvious synthetic CPU load. +use std::borrow::Cow; + use tree_sitter::Node; +use super::executable_case::{basename, fold_basename, FOLD_EXECUTABLE_CASE}; use super::scan::{collect_commands, parse_tree_best_effort}; type Words = [Option]; @@ -18,10 +21,10 @@ pub fn is_synthetic_load(source: &str) -> bool { collect_commands(tree.root_node(), &mut commands); commands.into_iter().any(|node| { let words = command_words(source, node); - let Some((words, indirect)) = executable_words(&words, false) else { + let Some((words, indirect)) = executable_words(&words, FOLD_EXECUTABLE_CASE) else { return false; }; - match command_name(&words) { + match command_name(&words, FOLD_EXECUTABLE_CASE).as_deref() { Some("stress" | "stress-ng") => true, // Only a directly connected, tiny head is an exception for yes. // One gigabyte is bounded too, but is still substantial CPU load. @@ -97,17 +100,22 @@ fn command_words(source: &str, node: Node<'_>) -> Vec> { words } -fn command_name(words: &Words) -> Option<&str> { - words.first()?.as_deref()?.rsplit('/').next() +fn command_name(words: &Words, fold_executable_case: bool) -> Option> { + let name = basename(words.first()?.as_deref()?); + Some(fold_basename(name, fold_executable_case)) } /// Peel only known execution wrappers and launcher options. In particular, /// `command -v yes` is a lookup, and `xargs -Iyes echo yes` executes echo. -fn executable_words(words: &Words, _fold_executable_case: bool) -> Option<(Vec>, bool)> { +fn executable_words( + words: &Words, + fold_executable_case: bool, +) -> Option<(Vec>, bool)> { let mut words = words.to_vec(); let mut indirect = false; 'wrappers: loop { - let name = command_name(&words)?; + let name = command_name(&words, fold_executable_case)?; + let name = name.as_ref(); let index = match name { "env" | "nice" | "timeout" | "command" | "xargs" | "parallel" | "exec" | "nohup" | "setsid" | "stdbuf" | "time" | "caffeinate" => { @@ -378,8 +386,12 @@ fn pipes_to_device_reader(source: &str, node: Node<'_>) -> bool { return false; }; let words = command_words(source, next); - executable_words(&words, false) - .is_some_and(|(words, _)| matches!(command_name(&words), Some("cat" | "dd" | "pv"))) + executable_words(&words, FOLD_EXECUTABLE_CASE).is_some_and(|(words, _)| { + matches!( + command_name(&words, FOLD_EXECUTABLE_CASE).as_deref(), + Some("cat" | "dd" | "pv") + ) + }) } /// Visit redirects on the command and enclosing groups, but not those on a @@ -445,10 +457,12 @@ fn small_head_pipeline(source: &str, node: Node<'_>) -> bool { return false; } let words = command_words(source, head); + // Keep the exception exact: an uppercase launcher or consumer could be + // a different executable on a case-sensitive volume. let Some((words, indirect)) = executable_words(&words, false) else { return false; }; - if indirect || command_name(&words) != Some("head") { + if indirect || command_name(&words, false).as_deref() != Some("head") { return false; } // Allow at most 100 lines or 64 KiB, with a literal positive decimal @@ -495,7 +509,10 @@ mod tests { executable_words(&words, true), Some((words[3..].to_vec(), true)), ); - assert_eq!(executable_words(&words, false), Some((words.to_vec(), false))); + assert_eq!( + executable_words(&words, false), + Some((words.to_vec(), false)) + ); } #[test] diff --git a/packages/aft-bridge/src/bash-permissions.ts b/packages/aft-bridge/src/bash-permissions.ts index 954e5e35b9..f5653b62c6 100644 --- a/packages/aft-bridge/src/bash-permissions.ts +++ b/packages/aft-bridge/src/bash-permissions.ts @@ -79,7 +79,10 @@ function hostWildcardMatches(input: string, pattern: string, platform: NodeJS.Pl .replace(/\*/g, ".*") .replace(/\?/g, "."); if (escaped.endsWith(" .*")) escaped = `${escaped.slice(0, -3)}( .*)?`; - return new RegExp(`^${escaped}$`, platform === "win32" ? "si" : "s").test(normalized); + // macOS volumes are case-insensitive by default, so a program runs under + // any letter-case spelling of its name. + const flags = platform === "win32" || platform === "darwin" ? "si" : "s"; + return new RegExp(`^${escaped}$`, flags).test(normalized); } interface HostPermissionRule { From 9d784a155b7073d39812227fc02bb39977d1f7c1 Mon Sep 17 00:00:00 2001 From: ualtinok <94532+ualtinok@users.noreply.github.com> Date: Sun, 6 Dec 2026 17:39:58 +0100 Subject: [PATCH 3/7] bash permissions: name Windows in the letter-case comment; add search slice descriptor Co-authored-by: alfonso-aft <289616620+alfonso-aft@users.noreply.github.com> --- .../slice-descriptors/fix-bash-case-fold-macos.json | 1 + crates/aft-shell/src/bash_permissions/executable_case.rs | 4 ++-- 2 files changed, 3 insertions(+), 2 deletions(-) create mode 100644 benchmarks/aft-search/slice-descriptors/fix-bash-case-fold-macos.json diff --git a/benchmarks/aft-search/slice-descriptors/fix-bash-case-fold-macos.json b/benchmarks/aft-search/slice-descriptors/fix-bash-case-fold-macos.json new file mode 100644 index 0000000000..73429935e4 --- /dev/null +++ b/benchmarks/aft-search/slice-descriptors/fix-bash-case-fold-macos.json @@ -0,0 +1 @@ +{"fixtures":["harness-goldens"],"kind":"harness","slice_class":"non_ranking","targeted_mechanism":"none"} diff --git a/crates/aft-shell/src/bash_permissions/executable_case.rs b/crates/aft-shell/src/bash_permissions/executable_case.rs index 02c4d32299..f25f533eda 100644 --- a/crates/aft-shell/src/bash_permissions/executable_case.rs +++ b/crates/aft-shell/src/bash_permissions/executable_case.rs @@ -1,8 +1,8 @@ use std::borrow::Cow; use std::ops::Range; -// macOS volumes are case-insensitive by default, so a program runs under -// any letter-case spelling of its name. +// macOS volumes and Windows file systems are case-insensitive by default, so a +// program runs under any letter-case spelling of its name. pub(super) const FOLD_EXECUTABLE_CASE: bool = cfg!(any(target_os = "macos", windows)); pub(super) fn basename(word: &str) -> &str { From 8d01041984aa0e0f00d3b6a195227559f31678c6 Mon Sep 17 00:00:00 2001 From: ualtinok <94532+ualtinok@users.noreply.github.com> Date: Sun, 6 Dec 2026 17:55:24 +0100 Subject: [PATCH 4/7] bash permissions: fold launcher options by name; keep refusal attribution as the host matches The synthetic-load guard read a mixed-case launcher's options under its original spelling, so `Caffeinate -i yes` slipped past. Options are now read under the folded name, with the exact word kept to tell Bash's `time` keyword from an external time. The bridge's refusal attribution mirrors the host again: case-insensitive only on Windows. The scanner already sends the lower-case program-name variant as its own part, so attribution needs no wider matching. Co-authored-by: alfonso-aft <289616620+alfonso-aft@users.noreply.github.com> --- .../src/bash_permissions/synthetic_load.rs | 34 +++++++++++++------ .../src/__tests__/bash-permissions.test.ts | 8 +++-- packages/aft-bridge/src/bash-permissions.ts | 7 ++-- 3 files changed, 33 insertions(+), 16 deletions(-) diff --git a/crates/aft-shell/src/bash_permissions/synthetic_load.rs b/crates/aft-shell/src/bash_permissions/synthetic_load.rs index 310bd37780..2071ebf0ce 100644 --- a/crates/aft-shell/src/bash_permissions/synthetic_load.rs +++ b/crates/aft-shell/src/bash_permissions/synthetic_load.rs @@ -168,7 +168,7 @@ fn executable_words( name, "exec" | "nohup" | "setsid" | "stdbuf" | "time" | "caffeinate" ) { - index = execution_wrapper_option_end(&words, index)?; + index = execution_wrapper_option_end(&words, index, name)?; continue; } index += 1; @@ -196,14 +196,17 @@ fn executable_words( /// Return the index after a known wrapper option and its value, if any. Return /// None for unknown options or non-literal values rather than guessing which /// later argument is the executable and falsely refusing an unrelated command. -fn execution_wrapper_option_end(words: &Words, index: usize) -> Option { - let wrapper = words.first()?.as_deref()?; +/// `wrapper` is the launcher's basename as matched, already folded to lower case +/// where program names are case-insensitive. +fn execution_wrapper_option_end(words: &Words, index: usize, wrapper: &str) -> Option { + // The exact word tells Bash's `time` keyword apart from an external time. + let word = words.first()?.as_deref()?; let option = words.get(index)?.as_deref()?; let (flag, attached) = if option.starts_with("--") { let (flag, value) = option .split_once('=') .map_or((option, None), |(flag, value)| (flag, Some(value))); - if !execution_wrapper_option_takes_value(wrapper, flag)? { + if !execution_wrapper_option_takes_value(wrapper, word, flag)? { return value.is_none().then_some(index + 1); } (flag, value) @@ -212,7 +215,7 @@ fn execution_wrapper_option_end(words: &Words, index: usize) -> Option { let mut value_flag = None; for (offset, _) in flags.char_indices() { let flag = flags.get(offset..offset + 1)?; - if execution_wrapper_option_takes_value(wrapper, flag)? { + if execution_wrapper_option_takes_value(wrapper, word, flag)? { value_flag = Some((flag, &flags[offset + 1..])); break; } @@ -226,7 +229,7 @@ fn execution_wrapper_option_end(words: &Words, index: usize) -> Option { Some(value) => (value, index + 1), None => (words.get(index + 1)?.as_deref()?, index + 2), }; - let valid = match wrapper.rsplit('/').next()? { + let valid = match wrapper { "stdbuf" => { let suffix = value.trim_start_matches(|ch: char| ch.is_ascii_digit()); value == "L" @@ -267,8 +270,8 @@ fn execution_wrapper_option_end(words: &Words, index: usize) -> Option { valid.then_some(next) } -fn execution_wrapper_option_takes_value(wrapper: &str, option: &str) -> Option { - match (wrapper.rsplit('/').next()?, option) { +fn execution_wrapper_option_takes_value(wrapper: &str, word: &str, option: &str) -> Option { + match (wrapper, option) { ("exec", "a") => Some(true), ("exec", "c" | "l") => Some(false), ("setsid", "f" | "w" | "c" | "--fork" | "--wait" | "--ctty") => Some(false), @@ -279,8 +282,8 @@ fn execution_wrapper_option_takes_value(wrapper: &str, option: &str) -> Option Some(false), - ("time", "f" | "o" | "--format" | "--output") if wrapper != "time" => Some(true), + ) if word != "time" => Some(false), + ("time", "f" | "o" | "--format" | "--output") if word != "time" => Some(true), ("caffeinate", "d" | "i" | "m" | "s" | "u") => Some(false), ("caffeinate", "t" | "w") => Some(true), _ => None, @@ -513,6 +516,17 @@ mod tests { executable_words(&words, false), Some((words.to_vec(), false)) ); + // A mixed-case launcher's own options are read under the folded name. + let words = ["Caffeinate", "-i", "yes"].map(|s| Some(s.to_string())); + assert_eq!( + executable_words(&words, true), + Some((words[2..].to_vec(), false)), + ); + let words = ["STDBUF", "-o", "L", "yes"].map(|s| Some(s.to_string())); + assert_eq!( + executable_words(&words, true), + Some((words[3..].to_vec(), false)), + ); } #[test] diff --git a/packages/aft-bridge/src/__tests__/bash-permissions.test.ts b/packages/aft-bridge/src/__tests__/bash-permissions.test.ts index d115c39b8a..3c38b365b9 100644 --- a/packages/aft-bridge/src/__tests__/bash-permissions.test.ts +++ b/packages/aft-bridge/src/__tests__/bash-permissions.test.ts @@ -268,10 +268,14 @@ test.each([ }); test.each([ - ["darwin", "Git push --force", "git push*", true], + // The host ignores case only on Windows; on macOS the scanner sends the + // lower-case program-name variant as its own part. + ["darwin", "Git push --force", "git push*", false], + ["darwin", "git push --force", "git push*", true], + ["darwin", "git show HEAD", "git show head", false], ["linux", "Git push --force", "git push*", false], ["win32", "Git push --force", "git push*", true], - ["darwin", "/Tools/Git push --force", "/tools/git push*", true], + ["darwin", "/Tools/Git push --force", "/tools/git push*", false], ["linux", "/Tools/Git push --force", "/tools/git push*", false], ["win32", "C:\\Tools\\Git push --force", "c:/tools/git push*", true], ] as const)("permission loop attributes denials on %s for %s against %s", async (platform, part, resource, matches) => { diff --git a/packages/aft-bridge/src/bash-permissions.ts b/packages/aft-bridge/src/bash-permissions.ts index f5653b62c6..bf6f1098fe 100644 --- a/packages/aft-bridge/src/bash-permissions.ts +++ b/packages/aft-bridge/src/bash-permissions.ts @@ -79,10 +79,9 @@ function hostWildcardMatches(input: string, pattern: string, platform: NodeJS.Pl .replace(/\*/g, ".*") .replace(/\?/g, "."); if (escaped.endsWith(" .*")) escaped = `${escaped.slice(0, -3)}( .*)?`; - // macOS volumes are case-insensitive by default, so a program runs under - // any letter-case spelling of its name. - const flags = platform === "win32" || platform === "darwin" ? "si" : "s"; - return new RegExp(`^${escaped}$`, flags).test(normalized); + // Mirror the host: it ignores case only on Windows. On macOS the scanner + // already sends a lower-case program-name variant of each part. + return new RegExp(`^${escaped}$`, platform === "win32" ? "si" : "s").test(normalized); } interface HostPermissionRule { From 423bcfcc81d5e62a453595549aa84be7d530aed5 Mon Sep 17 00:00:00 2001 From: ualtinok <94532+ualtinok@users.noreply.github.com> Date: Sun, 6 Dec 2026 18:33:35 +0100 Subject: [PATCH 5/7] bash permissions: non-ASCII program names are unreadable on macOS and Windows MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Both match file names with Unicode case folding, so `ſh -c ...` runs sh and a Kelvin-sign `maKe` runs make. The program such a name runs can't be told from its spelling, so the line is unreadable there. File commands (`Touch`, `RM`) also get their outside-the-project asks under any ASCII letter case. Found by an internal review of the bash permission scanner. Co-authored-by: alfonso-aft <289616620+alfonso-aft@users.noreply.github.com> --- crates/aft-shell/src/bash_permissions/scan.rs | 45 +++++++++++++++++-- 1 file changed, 42 insertions(+), 3 deletions(-) diff --git a/crates/aft-shell/src/bash_permissions/scan.rs b/crates/aft-shell/src/bash_permissions/scan.rs index 54319c4b3b..6ca0b47577 100644 --- a/crates/aft-shell/src/bash_permissions/scan.rs +++ b/crates/aft-shell/src/bash_permissions/scan.rs @@ -3,7 +3,7 @@ use std::path::{Path, PathBuf}; use tree_sitter::{Node, Tree}; -use super::executable_case::{basename, host_patterns, FOLD_EXECUTABLE_CASE}; +use super::executable_case::{basename, fold_basename, host_patterns, FOLD_EXECUTABLE_CASE}; use super::PermissionScanHost; use super::{arity, PermissionAsk, PermissionKind}; @@ -199,8 +199,16 @@ fn scan_with_read_exemption( } unknown_cwd |= scan_cwd.is_none(); - if FILE_COMMANDS.contains(&head) { - let exemption = if READ_ONLY_FILE_COMMANDS.contains(&head) { + if fold_executable_case && !basename(head).is_ascii() { + // macOS and Windows match names with Unicode case folding, so a + // non-ASCII name such as `ſh` can run `sh`. Which program it runs + // can't be told from the spelling, so the line is unreadable. + return vec![parse_failed_ask(true)]; + } + let file_head = fold_basename(head, fold_executable_case); + let file_head = file_head.as_ref(); + if FILE_COMMANDS.contains(&file_head) { + let exemption = if READ_ONLY_FILE_COMMANDS.contains(&file_head) { read_exemption } else { None @@ -1926,6 +1934,37 @@ mod tests { .collect() } + #[test] + fn executable_case_marks_non_ascii_heads_unreadable_on_case_insensitive_hosts() { + let project = tempfile::tempdir().unwrap(); + let root = project.path(); + for command in [ + "\u{17f}h -c 'git push'", + "ba\u{17f}h -c 'git push'", + "ma\u{212a}e --eval=x x", + ] { + let asks = scan_with_read_exemption(command, root, root, None, true); + assert_eq!(asks.len(), 1, "{command}"); + assert!(asks[0].unreadable, "{command}"); + let asks = scan_with_read_exemption(command, root, root, None, false); + assert!(asks.iter().all(|ask| !ask.unreadable), "{command}"); + } + } + + #[test] + fn executable_case_checks_file_command_targets_on_case_insensitive_hosts() { + let project = tempfile::tempdir().unwrap(); + // The system temp folder is exempt from these asks, so aim outside it. + let command = "Touch /etc/aft-case-fold-probe"; + let external = |fold| { + scan_with_read_exemption(command, project.path(), project.path(), None, fold) + .iter() + .any(|ask| ask.kind == PermissionKind::ExternalDirectory) + }; + assert!(external(true)); + assert!(!external(false)); + } + #[test] fn executable_case_checks_both_spellings_against_host_denies() { let project = tempfile::tempdir().unwrap(); From 27522721f5530061fb4f9aedec1314c489d74f93 Mon Sep 17 00:00:00 2001 From: ualtinok <94532+ualtinok@users.noreply.github.com> Date: Sun, 6 Dec 2026 18:39:13 +0100 Subject: [PATCH 6/7] bash permissions: a non-ASCII program name adds an unreadable ask, keeping the others MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Replacing every ask with one unreadable `*` ask hid the line's readable commands from deny rules: `git push --force; é` asked instead of being denied. Readable commands now keep their asks beside the unreadable one. Co-authored-by: alfonso-aft <289616620+alfonso-aft@users.noreply.github.com> --- crates/aft-shell/src/bash_permissions/scan.rs | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/crates/aft-shell/src/bash_permissions/scan.rs b/crates/aft-shell/src/bash_permissions/scan.rs index 6ca0b47577..369c73b7a7 100644 --- a/crates/aft-shell/src/bash_permissions/scan.rs +++ b/crates/aft-shell/src/bash_permissions/scan.rs @@ -152,6 +152,7 @@ fn scan_with_read_exemption( // own stack from before the command is unknown, so a `popd` past these // entries leaves the directory unknown. let mut directory_stack = Vec::new(); + let mut unreadable_head = false; for node in command_nodes { let recovered = heredoc_words.remove(&node); let parts = if let Some(words) = &recovered { @@ -202,8 +203,10 @@ fn scan_with_read_exemption( if fold_executable_case && !basename(head).is_ascii() { // macOS and Windows match names with Unicode case folding, so a // non-ASCII name such as `ſh` can run `sh`. Which program it runs - // can't be told from the spelling, so the line is unreadable. - return vec![parse_failed_ask(true)]; + // can't be told from the spelling, so the line is unreadable. The + // other commands keep their own asks so deny rules still match them. + unreadable_head = true; + continue; } let file_head = fold_basename(head, fold_executable_case); let file_head = file_head.as_ref(); @@ -275,6 +278,9 @@ fn scan_with_read_exemption( } } + if unreadable_head { + asks.push(parse_failed_ask(true)); + } if unknown_cwd { // A relative folder approval has no stable identity after a dynamic cd. // Add exact-command approval without replacing the individual command @@ -1949,6 +1955,14 @@ mod tests { let asks = scan_with_read_exemption(command, root, root, None, false); assert!(asks.iter().all(|ask| !ask.unreadable), "{command}"); } + // Readable commands on the same line keep their asks, so a deny rule + // such as `git push*` still applies to them. + let asks = scan_with_read_exemption("git push --force; \u{e9}", root, root, None, true); + assert!(asks.iter().any(|ask| ask.unreadable)); + assert!(asks.iter().any(|ask| ask + .patterns + .iter() + .any(|pattern| pattern == "git push --force"))); } #[test] From 1df9ffe1a9bef9040c1227036bb3ec831d73b20b Mon Sep 17 00:00:00 2001 From: ualtinok <94532+ualtinok@users.noreply.github.com> Date: Sun, 6 Dec 2026 19:06:38 +0100 Subject: [PATCH 7/7] test: Windows memory-cap test waits 30 s for capped processes to exit On a hosted Windows runner (run 47680427371, shard 8) the job-object kill had ended the task, but one descendant was still running 5 s later. Process teardown on a loaded runner can take that long, so the positive wait is now 30 s. A process that really escaped the job still fails, now with its job membership in the message, which tells the two apart. Co-authored-by: alfonso-aft <289616620+alfonso-aft@users.noreply.github.com> --- .../src/bash_background/memory_limit_tests.rs | 20 +++++++++++++------ 1 file changed, 14 insertions(+), 6 deletions(-) diff --git a/crates/aft-shell/src/bash_background/memory_limit_tests.rs b/crates/aft-shell/src/bash_background/memory_limit_tests.rs index 072028a68c..da056d3828 100644 --- a/crates/aft-shell/src/bash_background/memory_limit_tests.rs +++ b/crates/aft-shell/src/bash_background/memory_limit_tests.rs @@ -603,12 +603,20 @@ fn memory_limit_cmd_waiter_contains_and_kills_powershell_tree() { ); std::thread::sleep(Duration::from_millis(25)); } - for process in &handles.0[1..] { - assert_eq!( - unsafe { WaitForSingleObject(*process, 5000) }, - WAIT_OBJECT_0, - "{form}: a capped process survived" - ); + // A job-object kill ends the tree at once, but a loaded hosted runner can + // take seconds to tear processes down, so this positive wait is long. A + // process that really escaped the job still fails, with its membership. + for (pid, process) in pids.iter().zip(&handles.0[1..]) { + let wait = unsafe { WaitForSingleObject(*process, 30_000) }; + if wait != WAIT_OBJECT_0 { + let mut included = 0; + let queried = unsafe { IsProcessInJob(*process, job, &mut included) }; + panic!( + "{form}: a capped process survived: pid={pid} wait={wait} in_job={included} \ + query_ok={queried} {}", + windows_memory_job_diagnostic(&id) + ); + } } trace_step("descendants_exited", ""); }