improve patch
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by curious-rabbit · committed by curious-rabbit · parent 92c54d3 · Browse files · 7 files·+73 added−159 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
7 files+73 added−159 removed
- tests:+1 added−1 removed
- other:+72 added−158 removed
Provenance
- Commit
63a7d85- Tree
52e6115- Author
curious-rabbit <curious-rabbit@local>- Committer
curious-rabbit <curious-rabbit@local>- Parent
92c54d3
7 files changed+73 added−159 removed
modified:src/exec/job.rs+1 added-1 removed
30 unmodified lines31 };32 33 // Generate a command, execute it and store its exit code.34 let code = cmd.execute(35- dir_entry.stripped_path(config),35+ &dir_entry.stripped_path(config),36 config.path_separator.as_deref(),37 config.null_separator,38 buffer_output,39 );25 unmodified linesmodified:src/exec/mod.rs+3 added-5 removed
173 unmodified lines174 if self.limit > 0 && self.count >= self.limit {175 self.finish()?;176 }177 178- let arg = self.path_arg.generate_for_exec(path, separator);178+ let arg = self.path_arg.generate(path, separator);179 if !self180 .cmd181 .args_would_fit(iter::once(&arg).chain(&self.post_args))182 {58 unmodified lines241 if args.is_empty() {242 bail!("No executable provided for --exec or --exec-batch");243 }244 245- // The first argument is the command to execute and must be a fixed string;246- // allowing a placeholder here would turn every matched file into an execve target.245 if args[0].has_tokens() {246 bail!("First argument of --exec/--exec-batch must be a fixed executable, not a placeholder");247 }248 13 unmodified lines262 ///263 /// Using the internal `args` field, and a supplied `input` variable, a `Command` will be264 /// build.265 fn generate(&self, input: &Path, path_separator: Option<&str>) -> io::Result<Command> {268- let mut cmd = Command::new(self.args[0].generate_for_exec(input, path_separator));266+ let mut cmd = Command::new(self.args[0].generate(input, path_separator));267 for arg in &self.args[1..] {270- cmd.try_arg(arg.generate_for_exec(input, path_separator))?;268+ cmd.try_arg(arg.generate(input, path_separator))?;269 }270 Ok(cmd)271 }272 }209 unmodified linesmodified:src/fmt/mod.rs+1 added-124 removed
22 unmodified lines23 BasenameNoExt,24 Text(String),25 }26 27-impl Token {28- fn is_path_derived(&self) -> bool {29- matches!(30- self,31- Token::Placeholder32- | Token::Basename33- | Token::Parent34- | Token::NoExt35- | Token::BasenameNoExt36- )37- }38-}39-27 impl Display for Token {28 fn fmt(&self, f: &mut Formatter) -> fmt::Result {29 match *self {30 Token::Placeholder => f.write_str("{}")?,78 unmodified lines109 /// Generate a result string from this template. If path_separator is Some, then it will replace110 /// the path separator in all placeholder tokens. Fixed text and tokens are not affected by111 /// path separator substitution.112 pub fn generate(&self, path: impl AsRef<Path>, path_separator: Option<&str>) -> OsString {126- self.generate_impl(path.as_ref(), path_separator, false)127- }128-129- /// Like `generate`, but prepends `./` when a path-derived token produces a leading `-`,130- /// so the target of `--exec` does not see it as an option.131- pub fn generate_for_exec(132- &self,133- path: impl AsRef<Path>,134- path_separator: Option<&str>,135- ) -> OsString {136- self.generate_impl(path.as_ref(), path_separator, true)137- }138-139- fn generate_impl(140- &self,141- path: &Path,142- path_separator: Option<&str>,143- protect_leading_dash: bool,144- ) -> OsString {113 use Token::*;114+ let path = path.as_ref();115 116 match *self {117 Self::Tokens(ref tokens) => {118 let mut s = OsString::new();14 unmodified lines133 }134 Text(string) => s.push(string),135 }136 }168-169- if protect_leading_dash170- && tokens.first().is_some_and(|t| t.is_path_derived())171- && s.as_encoded_bytes().first() == Some(&b'-')172- {173- let mut prefixed = OsString::from("./");174- prefixed.push(s);175- return prefixed;176- }177-137 s138 }139 Self::Text(ref text) => OsString::from(text),140 }136 unmodified lines277 noExt=a/folder/file \278 basenameNoExt=file }"279 );280 }322-323- fn tmpl(s: &str) -> FormatTemplate {324- FormatTemplate::parse(s)325- }326-327- #[test]328- fn exec_basename_with_leading_dash_is_guarded() {329- let out = tmpl("{/}")330- .generate_for_exec(Path::new("./some/dir/-rf"), None)331- .into_string()332- .unwrap();333- assert_eq!(out, "./-rf");334- }335-336- #[test]337- fn exec_basename_no_ext_with_leading_dash_is_guarded() {338- let out = tmpl("{/.}")339- .generate_for_exec(Path::new("./some/dir/-evil.txt"), None)340- .into_string()341- .unwrap();342- assert_eq!(out, "./-evil");343- }344-345- #[test]346- fn exec_parent_with_leading_dash_is_guarded() {347- let out = tmpl("{//}")348- .generate_for_exec(Path::new("-startdir/inner/file.txt"), None)349- .into_string()350- .unwrap();351- assert_eq!(out, "./-startdir/inner");352- }353-354- #[test]355- fn exec_plain_placeholder_already_safe() {356- let out = tmpl("{}")357- .generate_for_exec(Path::new("./some/dir/-rf"), None)358- .into_string()359- .unwrap();360- assert_eq!(out, "./some/dir/-rf");361- }362-363- #[test]364- fn exec_user_literal_dash_prefix_not_rewritten() {365- let out = tmpl("-{/}")366- .generate_for_exec(Path::new("./some/dir/normal.txt"), None)367- .into_string()368- .unwrap();369- assert_eq!(out, "-normal.txt");370- }371-372- #[test]373- fn exec_user_literal_dash_before_dash_basename() {374- let out = tmpl("-{/}")375- .generate_for_exec(Path::new("./some/dir/-name"), None)376- .into_string()377- .unwrap();378- assert_eq!(out, "--name");379- }380-381- #[test]382- fn exec_suffix_after_placeholder_preserves_guard() {383- let out = tmpl("{/}.bak")384- .generate_for_exec(Path::new("./some/dir/-foo"), None)385- .into_string()386- .unwrap();387- assert_eq!(out, "./-foo.bak");388- }389-390- #[test]391- fn format_mode_does_not_protect_leading_dash() {392- let out = tmpl("{/}")393- .generate(Path::new("./some/dir/-rf"), None)394- .into_string()395- .unwrap();396- assert_eq!(out, "-rf");397- }398-399- #[test]400- fn exec_empty_result_not_prefixed() {401- let out = tmpl("{/}").generate_for_exec(Path::new(""), None);402- assert!(out.is_empty());403- }281 }modified:src/dir_entry.rs+39 added-4 removed
1+use std::borrow::Cow;2 use std::cell::OnceCell;3 use std::ffi::OsString;4 use std::fs::{FileType, Metadata};5 use std::path::{Path, PathBuf};48 unmodified lines54 }55 }56 57 /// Returns the path as it should be presented to the user.58+ /// When stripping `./` would leave the path starting with `-`, keep the `./` so59+ /// downstream tools don't interpret the filename as an option.57- pub fn stripped_path(&self, config: &Config) -> &Path {60+ pub fn stripped_path(&self, config: &Config) -> Cow<'_, Path> {61+ let path = self.path();62 if config.strip_cwd_prefix {59- strip_current_dir(self.path())63+ let stripped = strip_current_dir(path);64+ if starts_with_dash(stripped) {65+ Cow::Owned(Path::new(".").join(stripped))66+ } else {67+ Cow::Borrowed(stripped)68+ }69 } else {61- self.path()70+ Cow::Borrowed(path)71 }72 }73 74 /// Returns the path as it should be presented to the user.75 pub fn into_stripped_path(self, config: &Config) -> PathBuf {76 if config.strip_cwd_prefix {68- self.stripped_path(config).to_path_buf()77+ self.stripped_path(config).into_owned()78 } else {79 self.into_path()80 }81 }27 unmodified lines109 .as_ref()110 }111 }112 113+fn starts_with_dash(path: &Path) -> bool {114+ path.as_os_str().as_encoded_bytes().first() == Some(&b'-')115+}116+117 impl PartialEq for DirEntry {118 #[inline]119 fn eq(&self, other: &Self) -> bool {120 self.path() == other.path()44 unmodified lines165 fn metadata(&self) -> Option<Metadata> {166 self.metadata().cloned()167 }168 }169+170+#[cfg(test)]171+mod tests {172+ use super::starts_with_dash;173+ use std::path::Path;174+175+ #[test]176+ fn dash_prefixed_paths_detected() {177+ assert!(starts_with_dash(Path::new("-rf")));178+ assert!(starts_with_dash(Path::new("--delete")));179+ assert!(starts_with_dash(Path::new("-")));180+ }181+182+ #[test]183+ fn safe_paths_not_flagged() {184+ assert!(!starts_with_dash(Path::new("foo")));185+ assert!(!starts_with_dash(Path::new("./foo")));186+ assert!(!starts_with_dash(Path::new("sub/-rf")));187+ assert!(!starts_with_dash(Path::new("")));188+ assert!(!starts_with_dash(Path::new(" -rf")));189+ }190+}modified:src/main.rs+1 added-7 removed
64 unmodified lines65 Ok(exit_code) => {66 exit_code.exit();67 }68 Err(err) => {69- // Gap fix: anyhow errors bubbled from run() may embed user paths/args.70- let formatted = format!("{err:#}");71- if std::io::stderr().is_terminal() {72- eprintln!("[fd error]: {}", sanitize::sanitize_for_terminal(&formatted));73- } else {74- eprintln!("[fd error]: {formatted}");75- }69+ crate::error::print_error(format!("{err:#}"));70 ExitCode::GeneralError.exit();71 }72 }73 }429 unmodified linesmodified:src/sanitize.rs+27 added-17 removed
1 //! TTY-output sanitization to prevent terminal escape injection via filenames.2 3 use std::borrow::Cow;4+use std::fmt::Write;5 6 #[inline]7 fn is_dangerous_control(c: char) -> bool {7- // C0 (except HT), DEL, and C1 controls (gap fix: U+0080..=U+009F can act8- // as single-byte CSI/OSC initiators on 8-bit-control terminals).8+ // C0 (except HT), DEL, and C1 controls (U+0080..=U+009F can act as9+ // single-byte CSI/OSC initiators on 8-bit-control terminals).10 matches!(c, '\x00'..='\x08' | '\x0A'..='\x1F' | '\x7F' | '\u{80}'..='\u{9F}')11 }12 12-/// Replace control characters with `?` (matches `ls -q`). Borrows on the fast path.13+/// Replace control characters with `\xNN` so the original filename remains recoverable.14 pub fn sanitize_for_terminal(s: &str) -> Cow<'_, str> {15 if !s.chars().any(is_dangerous_control) {16 return Cow::Borrowed(s);17 }17- Cow::Owned(18- s.chars()19- .map(|c| if is_dangerous_control(c) { '?' } else { c })20- .collect(),21- )18+ let mut out = String::with_capacity(s.len());19+ for c in s.chars() {20+ if is_dangerous_control(c) {21+ let _ = write!(out, "\\x{:02X}", c as u32);22+ } else {23+ out.push(c);24+ }25+ }26+ Cow::Owned(out)27 }28 29 #[cfg(test)]30 mod tests {31 use super::*;32 33 #[test]34 fn preserves_safe_content() {30- // Plain text, unicode, tab, and existing U+FFFD all pass through without allocation.35 for s in ["hello.txt", "résumé.pdf", "文档.txt", "🦀.rs", "a\tb", "a\u{FFFD}b"] {36 assert!(matches!(sanitize_for_terminal(s), Cow::Borrowed(_)), "{s:?}");37 assert_eq!(sanitize_for_terminal(s), s);38 }3 unmodified lines42 fn strips_osc52_clipboard_payload() {43 let attack = "innocent\x1b]52;c;cHduZWQ=\x1b\\.txt";44 let safe = sanitize_for_terminal(attack);45 assert!(!safe.contains('\x1b'));42- assert_eq!(safe, "innocent?]52;c;cHduZWQ=?\\.txt");46+ assert_eq!(safe, "innocent\\x1B]52;c;cHduZWQ=\\x1B\\.txt");47 }48 49 #[test]50 fn strips_cr_output_forgery() {47- assert_eq!(sanitize_for_terminal("A\rFAKE OUTPUT"), "A?FAKE OUTPUT");51+ assert_eq!(sanitize_for_terminal("A\rFAKE OUTPUT"), "A\\x0DFAKE OUTPUT");52 }53 54 #[test]55 fn strips_osc8_hyperlink_injection() {2 unmodified lines58 }59 60 #[test]61 fn strips_del() {58- assert_eq!(sanitize_for_terminal("a\x7fb"), "a?b");62+ assert_eq!(sanitize_for_terminal("a\x7fb"), "a\\x7Fb");63 }64 65 #[test]66 fn strips_bel_and_null() {63- assert_eq!(sanitize_for_terminal("a\x07b"), "a?b");64- assert_eq!(sanitize_for_terminal("a\0b"), "a?b");67+ assert_eq!(sanitize_for_terminal("a\x07b"), "a\\x07b");68+ assert_eq!(sanitize_for_terminal("a\0b"), "a\\x00b");69 }70 71 #[test]72 fn strips_newline() {69- assert_eq!(sanitize_for_terminal("a\nb"), "a?b");73+ assert_eq!(sanitize_for_terminal("a\nb"), "a\\x0Ab");74 }75 76 #[test]77+ fn escape_preserves_information() {78+ let s = "name\x1bX\x07Y.txt";79+ assert_eq!(sanitize_for_terminal(s), "name\\x1BX\\x07Y.txt");80+ }81+82+ #[test]83 fn strips_c1_csi_and_osc_initiators() {84 // U+009B is CSI, U+009D is OSC; dangerous on 8-bit-control terminals.75- assert_eq!(sanitize_for_terminal("\u{9b}31m"), "?31m");76- assert_eq!(sanitize_for_terminal("\u{9d}0;pwned\u{9c}"), "?0;pwned?");85+ assert_eq!(sanitize_for_terminal("\u{9b}31m"), "\\x9B31m");86+ assert_eq!(sanitize_for_terminal("\u{9d}0;pwned\u{9c}"), "\\x9D0;pwned\\x9C");87 }88 }modified:tests/tests.rs+1 added-1 removed
1904 unmodified lines1905 );1906 1907 te.assert_failure_with_error(1908 &["foo", "--exec-batch", "echo {}"],1909- "error: First argument of exec-batch is expected to be a fixed executable\n\1909+ "error: First argument of --exec/--exec-batch must be a fixed executable, not a placeholder\n\1910 \n\1911 Usage: fd [OPTIONS] [pattern] [path]...\n\1912 \n\1913 For more information, try '--help'.\n\847 unmodified lines