Skip to content
Open
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"fixtures":["harness-goldens"],"kind":"harness","slice_class":"non_ranking","targeted_mechanism":"none"}
20 changes: 14 additions & 6 deletions crates/aft-shell/src/bash_background/memory_limit_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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", "");
}
Expand Down
40 changes: 40 additions & 0 deletions crates/aft-shell/src/bash_permissions/executable_case.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
use std::borrow::Cow;
use std::ops::Range;

// 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 {
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<Range<usize>>, fold: bool) -> Vec<String> {
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()]
}
1 change: 1 addition & 0 deletions crates/aft-shell/src/bash_permissions/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
158 changes: 141 additions & 17 deletions crates/aft-shell/src/bash_permissions/scan.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ use std::path::{Path, PathBuf};

use tree_sitter::{Node, Tree};

use super::executable_case::{basename, fold_basename, host_patterns, FOLD_EXECUTABLE_CASE};
use super::PermissionScanHost;

use super::{arity, PermissionAsk, PermissionKind};
Expand Down Expand Up @@ -87,22 +88,29 @@ 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),
FOLD_EXECUTABLE_CASE,
)
}

pub fn scan_with_project_root(
command: &str,
project_root: &Path,
cwd: &Path,
) -> Vec<PermissionAsk> {
scan_with_read_exemption(command, project_root, cwd, None)
scan_with_read_exemption(command, project_root, cwd, None, FOLD_EXECUTABLE_CASE)
}

fn scan_with_read_exemption(
command: &str,
project_root: &Path,
cwd: &Path,
read_exemption: Option<ReadExemption<'_>>,
fold_executable_case: bool,
) -> Vec<PermissionAsk> {
let project_root = resolve_existing(&project_root);
let cwd = resolve_existing(cwd);
Expand Down Expand Up @@ -144,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 {
Expand Down Expand Up @@ -191,8 +200,18 @@ 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. 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();
if FILE_COMMANDS.contains(&file_head) {
let exemption = if READ_ONLY_FILE_COMMANDS.contains(&file_head) {
read_exemption
} else {
None
Expand Down Expand Up @@ -245,18 +264,23 @@ 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);
}
}
}

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
Expand Down Expand Up @@ -1417,12 +1441,16 @@ fn command_parts(source: &str, node: Node<'_>) -> Vec<Part> {
out
}

fn source(command: &str, node: Node<'_>) -> String {
let node = node
fn command_patterns(command: &str, node: Node<'_>, fold_executable_case: bool) -> Vec<String> {
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 {
Expand Down Expand Up @@ -1738,7 +1766,7 @@ fn display_path(path: &Path) -> String {
fn push_bash_ask(
asks: &mut Vec<PermissionAsk>,
seen: &mut HashSet<String>,
pattern: String,
patterns: Vec<String>,
tokens: &[String],
) {
let stable = arity::prefix(tokens).join(" ");
Expand All @@ -1750,7 +1778,7 @@ fn push_bash_ask(
seen,
PermissionAsk {
kind: PermissionKind::Bash,
patterns: vec![pattern],
patterns,
always: vec![format!("{stable} *")],
reason: None,
unreadable: false,
Expand All @@ -1759,15 +1787,25 @@ fn push_bash_ask(
);
}

fn push_xargs_ask(asks: &mut Vec<PermissionAsk>, seen: &mut HashSet<String>, tokens: &[String]) {
fn push_xargs_ask(
asks: &mut Vec<PermissionAsk>,
seen: &mut HashSet<String>,
tokens: &[String],
fold_executable_case: bool,
) {
let mut index = 1;
while index < tokens.len() && tokens[index].starts_with('-') {
index += 1;
}
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
Expand Down Expand Up @@ -1902,6 +1940,92 @@ 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}");
}
// 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]
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();
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();
Expand Down
Loading
Loading