From 12f0eb5775c5c9bed1acdb98d3ff8a7e31134300 Mon Sep 17 00:00:00 2001 From: Mykhailo Chalyi Date: Thu, 19 Nov 2026 18:09:01 +0000 Subject: [PATCH 1/3] fix(realpath): resolve symlinks anywhere in the path realpath only cleaned . and .. lexically, so /l/c with /l -> /a/b printed /l/c. Share readlink -f's bounded symlink walk for operands and the --relative-to/--relative-base path; -s keeps lexical mode; loops report ELOOP; -e failures continue to the next operand like GNU. --- crates/bashkit/src/builtins/path.rs | 165 ++++++++++++++---- .../tests/spec_cases/bash/path.test.sh | 18 ++ 2 files changed, 153 insertions(+), 30 deletions(-) diff --git a/crates/bashkit/src/builtins/path.rs b/crates/bashkit/src/builtins/path.rs index 965226ebd..54b0f720a 100644 --- a/crates/bashkit/src/builtins/path.rs +++ b/crates/bashkit/src/builtins/path.rs @@ -218,6 +218,8 @@ impl Builtin for Realpath { let quiet = matches.get_flag("quiet"); let zero = matches.get_flag("zero"); let canonicalize_existing = matches.get_flag("canonicalize-existing"); + // -s: lexical `.`/`..` cleanup only, symlinks kept. + let strip = matches.get_flag("strip"); let relative_to = matches .get_one::("relative-to") .map(|s| s.to_string_lossy().into_owned()); @@ -230,54 +232,81 @@ impl Builtin for Realpath { .map(|vs| vs.map(|v| v.to_string_lossy().into_owned()).collect()) .unwrap_or_default(); + // Decision: realpath shares readlink -f's symlink walk, so a symlink + // anywhere in the path resolves (`/l/c` with /l -> /a/b gives + // /a/b/c). Existence: -e requires the final path; -E (upstream + // default) and -m require nothing here, same as before. + let fs = ctx.fs.as_ref(); + let canonical = |arg: &str| { + let resolved = super::resolve_path(ctx.cwd, arg); + async move { + if strip { + Some(resolved) + } else { + follow_readlink_symlinks(fs, resolved).await + } + } + }; + let separator = if zero { '\0' } else { '\n' }; let mut output = String::new(); - let mut had_error = false; + let mut errors = String::new(); + let mut failed = false; + + let base_path = match relative_to.as_ref().or(relative_base.as_ref()) { + Some(base) => match canonical(base).await { + Some(p) => Some(p), + None => { + return Ok(ExecResult::err( + format!("realpath: {base}: Too many levels of symbolic links\n"), + 1, + )); + } + }, + None => None, + }; for arg in &files { - let resolved = super::resolve_path(ctx.cwd, arg); + let Some(resolved) = canonical(arg).await else { + failed = true; + if !quiet { + errors.push_str(&format!( + "realpath: {arg}: Too many levels of symbolic links\n" + )); + } + continue; + }; - // -e: every component must exist. - // -m (default in bashkit): no existence requirement. - // -E (default upstream): only the parent must exist — - // without symlinks the distinction between -E and -m is - // purely existence-based, so we treat them identically. if canonicalize_existing && !ctx.fs.exists(&resolved).await.unwrap_or(false) { - had_error = true; + failed = true; if !quiet { - return Ok(ExecResult::err( - format!( - "realpath: {}: No such file or directory\n", - resolved.display() - ), - 1, - )); + errors.push_str(&format!("realpath: {arg}: No such file or directory\n")); } continue; } let mut printed = resolved.to_string_lossy().into_owned(); - if let Some(base) = relative_to.as_ref().or(relative_base.as_ref()) { - let base_path = super::resolve_path(ctx.cwd, base); - if let Ok(rel) = std::path::Path::new(&printed) + if let Some(base_path) = &base_path + && let Ok(rel) = std::path::Path::new(&printed) .strip_prefix(base_path.to_string_lossy().as_ref()) - { - let rel_str = rel.to_string_lossy(); - printed = if rel_str.is_empty() { - ".".to_string() - } else { - rel_str.into_owned() - }; - } + { + let rel_str = rel.to_string_lossy(); + printed = if rel_str.is_empty() { + ".".to_string() + } else { + rel_str.into_owned() + }; } output.push_str(&printed); output.push(separator); } - if had_error { - return Ok(ExecResult::err(output, 1)); - } - Ok(ExecResult::ok(output)) + Ok(ExecResult { + stdout: output.into(), + stderr: errors.into(), + exit_code: i32::from(failed), + ..Default::default() + }) } } @@ -829,6 +858,82 @@ mod tests { assert_eq!(result.stdout, "/real/file\n"); } + async fn run_realpath_with_fs(args: &[&str], fs: Arc) -> ExecResult { + let mut variables = HashMap::new(); + let env = HashMap::new(); + let mut cwd = PathBuf::from("/"); + + let args: Vec = args.iter().map(|s| s.to_string()).collect(); + let ctx = Context { + args: &args, + env: &env, + variables: &mut variables, + cwd: &mut cwd, + fs, + stdin: None, + #[cfg(feature = "http_client")] + http_client: None, + #[cfg(feature = "git")] + git_client: None, + #[cfg(feature = "ssh")] + ssh_client: None, + shell: None, + }; + + Realpath.execute(ctx).await.unwrap() + } + + async fn symlinked_dir_fs() -> Arc { + let fs = Arc::new(InMemoryFs::new()) as Arc; + fs.mkdir(Path::new("/a/b"), true).await.unwrap(); + fs.write_file(Path::new("/a/b/c"), b"x").await.unwrap(); + fs.symlink(Path::new("/a/b"), Path::new("/l")) + .await + .unwrap(); + fs + } + + #[tokio::test] + async fn test_realpath_follows_intermediate_symlink() { + let fs = symlinked_dir_fs().await; + let result = run_realpath_with_fs(&["/l/c", "/l", "/l/missing"], fs).await; + assert_eq!(result.exit_code, 0); + assert_eq!(result.stdout, "/a/b/c\n/a/b\n/a/b/missing\n"); + } + + #[tokio::test] + async fn test_realpath_e_follows_symlink_and_requires_target() { + let fs = symlinked_dir_fs().await; + let ok = run_realpath_with_fs(&["-e", "/l/c"], fs.clone()).await; + assert_eq!(ok.stdout, "/a/b/c\n"); + let missing = run_realpath_with_fs(&["-e", "/l/nope"], fs).await; + assert_eq!(missing.exit_code, 1); + } + + #[tokio::test] + async fn test_realpath_strip_keeps_symlinks() { + let fs = symlinked_dir_fs().await; + let result = run_realpath_with_fs(&["-s", "/l/./c"], fs).await; + assert_eq!(result.stdout, "/l/c\n"); + } + + #[tokio::test] + async fn test_realpath_relative_to_resolves_both_sides() { + let fs = symlinked_dir_fs().await; + let result = run_realpath_with_fs(&["--relative-to=/l", "/a/b/c"], fs).await; + assert_eq!(result.stdout, "c\n"); + } + + #[tokio::test] + async fn test_realpath_rejects_symlink_loop() { + let fs = Arc::new(InMemoryFs::new()) as Arc; + fs.symlink(Path::new("/y"), Path::new("/x")).await.unwrap(); + fs.symlink(Path::new("/x"), Path::new("/y")).await.unwrap(); + let result = run_realpath_with_fs(&["/x"], fs).await; + assert_eq!(result.exit_code, 1); + assert!(result.stderr.contains("Too many levels of symbolic links")); + } + #[tokio::test] async fn test_readlink_canonicalize_rejects_symlink_loop() { let fs = Arc::new(InMemoryFs::new()) as Arc; diff --git a/crates/bashkit/tests/spec_cases/bash/path.test.sh b/crates/bashkit/tests/spec_cases/bash/path.test.sh index 983f1b051..fe5c19adb 100644 --- a/crates/bashkit/tests/spec_cases/bash/path.test.sh +++ b/crates/bashkit/tests/spec_cases/bash/path.test.sh @@ -122,6 +122,24 @@ realpath /home/user/docs/../file.txt /home/user/file.txt ### end +### realpath_follows_intermediate_symlink +# realpath resolves a symlinked directory anywhere in the path +d=$(mktemp -d) +mkdir -p "$d/a/b"; touch "$d/a/b/c"; ln -s "$d/a/b" "$d/l" +realpath "$d/l/c" "$d/l" | sed "s|^$d|D|" +realpath -s "$d/l/./c" | sed "s|^$d|D|" +realpath -e "$d/l/nope" 2>/dev/null; echo "e=$?" +realpath --relative-to="$d/l" "$d/a/b/c" +cd "$d/l" && realpath c | sed "s|^$d|D|" +### expect +D/a/b/c +D/a/b +D/l/c +e=1 +c +D/a/b/c +### end + ### realpath_no_args ### bash_diff: clap-backed realpath returns exit 2 for parse errors; GNU realpath returns 1 # realpath with no args should error From c04e0964b7020529b1d5443f56acdda38f87dfcb Mon Sep 17 00:00:00 2001 From: Mykhailo Chalyi Date: Thu, 19 Nov 2026 18:09:01 +0000 Subject: [PATCH 2/3] chore(knowledge): log realpath symlink resolution --- knowledge/log.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/knowledge/log.md b/knowledge/log.md index 019349fe1..8e91c7c8d 100644 --- a/knowledge/log.md +++ b/knowledge/log.md @@ -1,5 +1,9 @@ # Bashkit Knowledge Update Log +## 2026-11-19 + +* **`realpath` resolves symlinks**: `realpath` only cleaned `.`/`..` lexically, so with `/l -> /a/b`, `realpath /l/c` printed `/l/c` where bash prints `/a/b/c`; it also could not see a symlink in `--relative-to`. It now shares `readlink -f`'s bounded symlink walk (40-hop cap, path limits), on operands and the relative base. `-s` keeps the old lexical behavior, a loop reports `Too many levels of symbolic links`, and `-e` failures continue to the next operand with the operand as given, like GNU. Spec case `realpath_follows_intermediate_symlink` matches real bash. Found while writing the #2933 separator tests. See [Virtual Filesystem](foundations/vfs.md). + ## 2026-11-18 * **Byte-exact `tee`, `split`, `cut`, `xxd -r`; `sort -o` in place refuses non-UTF-8**: a 60-command differential probe (bashkit vs bash on a Latin-1 + invalid-byte file, follow-up to issue #2935) found byte-oriented builtins decoding through text: `tee` rewrote both its output and the file to U+FFFD, `split -b`/`-l` wrote damaged pieces (and `-l` dropped `\r` from CRLF lines), `cut -b` was an alias of `-c`, and `xxd -r` returned lossy UTF-8. All four now work on bytes; `cut -b` selects bytes, `cut -c` counts a UTF-8 char or an invalid byte as one unit. `sort -o FILE FILE` would silently destroy a non-UTF-8 FILE, so it now refuses with exit 2, matching `sed -i` (L-SED-003). Pinned by differential tests in `byte_stream_tests`. See [Limitations](operations/limitations.md) L-STREAM-001. From 239f1a6a35e9392d7413cfce5cc2871ae05d44ae Mon Sep 17 00:00:00 2001 From: Mykhailo Chalyi Date: Thu, 19 Nov 2026 18:19:01 +0000 Subject: [PATCH 3/3] fix(realpath): GNU --relative-to/--relative-base semantics --relative-to prints ../-style relative paths; --relative-base prints paths under DIR relative and others absolute, and turns --relative-to off when DIR is outside it. -q silences a base loop error. Fix stale doc. --- crates/bashkit/src/builtins/path.rs | 128 ++++++++++++++++++++++------ knowledge/log.md | 2 +- 2 files changed, 102 insertions(+), 28 deletions(-) diff --git a/crates/bashkit/src/builtins/path.rs b/crates/bashkit/src/builtins/path.rs index 54b0f720a..9aae0baee 100644 --- a/crates/bashkit/src/builtins/path.rs +++ b/crates/bashkit/src/builtins/path.rs @@ -2,7 +2,7 @@ use super::clap_cache::cached_command; use async_trait::async_trait; -use std::path::Path; +use std::path::{Path, PathBuf}; use super::{Builtin, Context}; use crate::error::Result; @@ -178,10 +178,10 @@ impl Builtin for Dirname { /// `generated/realpath_args.rs`. Behaviour is implemented locally /// against the bashkit VFS. /// -/// Symlink resolution stays disabled per L-FS-001 in `knowledge/operations/limitations.md`'s -/// "Intentionally Unimplemented" entry: bashkit's VFS does not model -/// symlinks, so `-e`/`-m` only differ on existence checks, and -/// `-L`/`-P`/`--strip` collapse to the same lexical canonicalisation. +/// Symlinks are followed through the same bounded walk as `readlink -f`; +/// `-s` keeps lexical `.`/`..` cleanup only. `..` resolves lexically +/// (L-FS-001 in `knowledge/operations/limitations.md`), so `-L`/`-P` are +/// the same. `-E` and `-m` both skip the existence check; `-e` requires it. pub struct Realpath; // Cached `realpath` arg surface: pre-built once, cloned per invocation. @@ -253,18 +253,30 @@ impl Builtin for Realpath { let mut errors = String::new(); let mut failed = false; - let base_path = match relative_to.as_ref().or(relative_base.as_ref()) { - Some(base) => match canonical(base).await { - Some(p) => Some(p), - None => { - return Ok(ExecResult::err( - format!("realpath: {base}: Too many levels of symbolic links\n"), - 1, - )); + // GNU: --relative-base prints paths under DIR relative, others + // absolute; --relative-to prints `..`-style relative paths, unless a + // --relative-base is given and DIR is outside it. + let resolve_base = + async |base: &Option| -> std::result::Result, String> { + match base { + Some(b) => canonical(b).await.map(Some).ok_or_else(|| { + format!("realpath: {b}: Too many levels of symbolic links\n") + }), + None => Ok(None), } - }, - None => None, + }; + let (rel_to, rel_base) = match ( + resolve_base(&relative_to).await, + resolve_base(&relative_base).await, + ) { + (Ok(to), Ok(base)) => (to, base), + (Err(e), _) | (_, Err(e)) => { + return Ok(ExecResult::err(if quiet { String::new() } else { e }, 1)); + } }; + // --relative-to outside --relative-base: every path stays absolute. + let all_absolute = + matches!((&rel_to, &rel_base), (Some(to), Some(base)) if !to.starts_with(base)); for arg in &files { let Some(resolved) = canonical(arg).await else { @@ -285,18 +297,13 @@ impl Builtin for Realpath { continue; } - let mut printed = resolved.to_string_lossy().into_owned(); - if let Some(base_path) = &base_path - && let Ok(rel) = std::path::Path::new(&printed) - .strip_prefix(base_path.to_string_lossy().as_ref()) - { - let rel_str = rel.to_string_lossy(); - printed = if rel_str.is_empty() { - ".".to_string() - } else { - rel_str.into_owned() - }; - } + let printed = match (&rel_to, &rel_base) { + _ if all_absolute => resolved, + (_, Some(base)) if !resolved.starts_with(base) => resolved, + (Some(dir), _) | (None, Some(dir)) => relative_from(&resolved, dir), + (None, None) => resolved, + }; + let printed = printed.to_string_lossy(); output.push_str(&printed); output.push(separator); } @@ -310,6 +317,32 @@ impl Builtin for Realpath { } } +/// `path` relative to directory `dir`, both absolute and normalized: +/// shared prefix dropped, one `..` per remaining `dir` component. +fn relative_from(path: &Path, dir: &Path) -> PathBuf { + let p: Vec<_> = path.components().collect(); + let d: Vec<_> = dir.components().collect(); + let common = p.iter().zip(&d).take_while(|(a, b)| a == b).count(); + // OsString, not `Path::join`: keeps `/` on Windows and non-UTF-8 bytes. + let mut parts: Vec<&std::ffi::OsStr> = Vec::new(); + parts.extend(std::iter::repeat_n( + std::ffi::OsStr::new(".."), + d.len() - common, + )); + parts.extend(p[common..].iter().map(|c| c.as_os_str())); + if parts.is_empty() { + return PathBuf::from("."); + } + let mut out = std::ffi::OsString::new(); + for (i, part) in parts.iter().enumerate() { + if i > 0 { + out.push("/"); + } + out.push(part); + } + PathBuf::from(out) +} + /// The readlink builtin - print resolved symbolic links or canonical file names. /// /// Argument surface is generated from uutils/coreutils' `uu_app()` via the @@ -924,6 +957,47 @@ mod tests { assert_eq!(result.stdout, "c\n"); } + #[tokio::test] + async fn test_realpath_relative_to_and_base_match_gnu() { + // Expected values from GNU coreutils `realpath -m`. + let fs = Arc::new(InMemoryFs::new()) as Arc; + let cases: &[(&[&str], &str)] = &[ + (&["--relative-to=/a", "/b/c"], "../b/c\n"), + (&["--relative-to=/a/x", "/a/y/z"], "../y/z\n"), + (&["--relative-to=/", "/a"], "a\n"), + ( + &["--relative-base=/a", "/a/b", "/c/d", "/a"], + "b\n/c/d\n.\n", + ), + (&["--relative-base=/", "/a", "/"], "a\n.\n"), + ( + &["--relative-to=/a/b", "--relative-base=/a", "/a/c", "/x/y"], + "../c\n/x/y\n", + ), + ( + &["--relative-to=/x", "--relative-base=/a", "/a/c"], + "/a/c\n", + ), + ]; + for (args, expected) in cases { + let result = run_realpath_with_fs(args, fs.clone()).await; + assert_eq!(result.stdout, *expected, "{args:?}"); // debug-ok: test assertion + } + } + + #[tokio::test] + async fn test_realpath_quiet_silences_base_loop() { + let fs = Arc::new(InMemoryFs::new()) as Arc; + fs.symlink(Path::new("/y"), Path::new("/x")).await.unwrap(); + fs.symlink(Path::new("/x"), Path::new("/y")).await.unwrap(); + let loud = run_realpath_with_fs(&["--relative-to=/x", "/a"], fs.clone()).await; + assert_eq!(loud.exit_code, 1); + assert!(loud.stderr.contains("Too many levels")); + let quiet = run_realpath_with_fs(&["-q", "--relative-to=/x", "/a"], fs).await; + assert_eq!(quiet.exit_code, 1); + assert!(quiet.stderr.is_empty()); + } + #[tokio::test] async fn test_realpath_rejects_symlink_loop() { let fs = Arc::new(InMemoryFs::new()) as Arc; diff --git a/knowledge/log.md b/knowledge/log.md index 8e91c7c8d..7de24d56d 100644 --- a/knowledge/log.md +++ b/knowledge/log.md @@ -2,7 +2,7 @@ ## 2026-11-19 -* **`realpath` resolves symlinks**: `realpath` only cleaned `.`/`..` lexically, so with `/l -> /a/b`, `realpath /l/c` printed `/l/c` where bash prints `/a/b/c`; it also could not see a symlink in `--relative-to`. It now shares `readlink -f`'s bounded symlink walk (40-hop cap, path limits), on operands and the relative base. `-s` keeps the old lexical behavior, a loop reports `Too many levels of symbolic links`, and `-e` failures continue to the next operand with the operand as given, like GNU. Spec case `realpath_follows_intermediate_symlink` matches real bash. Found while writing the #2933 separator tests. See [Virtual Filesystem](foundations/vfs.md). +* **`realpath` resolves symlinks**: `realpath` only cleaned `.`/`..` lexically, so with `/l -> /a/b`, `realpath /l/c` printed `/l/c` where bash prints `/a/b/c`; it also could not see a symlink in `--relative-to`. It now shares `readlink -f`'s bounded symlink walk (40-hop cap, path limits), on operands and the relative base; `--relative-to` now prints `..`-style paths and `--relative-base` gates it, as GNU does (both were a bare prefix strip). `-s` keeps the old lexical behavior, a loop reports `Too many levels of symbolic links`, and `-e` failures continue to the next operand with the operand as given, like GNU. Spec case `realpath_follows_intermediate_symlink` matches real bash. Found while writing the #2933 separator tests. See [Virtual Filesystem](foundations/vfs.md). ## 2026-11-18